extfs.ts 19.6 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

'use strict';

8 9
import * as fs from 'fs';
import * as paths from 'path';
10
import { nfcall } from 'vs/base/common/async';
11 12 13 14 15
import { normalizeNFC } from 'vs/base/common/normalization';
import * as platform from 'vs/base/common/platform';
import * as strings from 'vs/base/common/strings';
import * as uuid from 'vs/base/common/uuid';
import { TPromise } from 'vs/base/common/winjs.base';
16
import { encode, encodeStream } from 'vs/base/node/encoding';
17
import * as flow from 'vs/base/node/flow';
E
Erich Gamma 已提交
18

B
Benjamin Pasero 已提交
19
const loop = flow.loop;
E
Erich Gamma 已提交
20

B
Benjamin Pasero 已提交
21 22 23 24
export function readdirSync(path: string): string[] {
	// Mac: uses NFD unicode form on disk, but we want NFC
	// See also https://github.com/nodejs/node/issues/2165
	if (platform.isMacintosh) {
25
		return fs.readdirSync(path).map(c => normalizeNFC(c));
B
Benjamin Pasero 已提交
26 27 28 29 30
	}

	return fs.readdirSync(path);
}

E
Erich Gamma 已提交
31 32 33 34
export function readdir(path: string, callback: (error: Error, files: string[]) => void): void {
	// Mac: uses NFD unicode form on disk, but we want NFC
	// See also https://github.com/nodejs/node/issues/2165
	if (platform.isMacintosh) {
B
Benjamin Pasero 已提交
35
		return fs.readdir(path, (error, children) => {
E
Erich Gamma 已提交
36 37 38 39
			if (error) {
				return callback(error, null);
			}

40
			return callback(null, children.map(c => normalizeNFC(c)));
E
Erich Gamma 已提交
41 42 43
		});
	}

B
Benjamin Pasero 已提交
44
	return fs.readdir(path, callback);
45 46
}

B
Benjamin Pasero 已提交
47 48 49 50 51 52
export interface IStatAndLink {
	stat: fs.Stats;
	isSymbolicLink: boolean;
}

export function statLink(path: string, callback: (error: Error, statAndIsLink: IStatAndLink) => void): void {
I
isidor 已提交
53 54
	fs.lstat(path, (error, lstat) => {
		if (error || lstat.isSymbolicLink()) {
I
isidor 已提交
55 56 57 58 59
			fs.stat(path, (error, stat) => {
				if (error) {
					return callback(error, null);
				}

I
isidor 已提交
60
				callback(null, { stat, isSymbolicLink: lstat && lstat.isSymbolicLink() });
I
isidor 已提交
61 62
			});
		} else {
I
isidor 已提交
63
			callback(null, { stat: lstat, isSymbolicLink: false });
I
isidor 已提交
64 65 66 67
		}
	});
}

E
Erich Gamma 已提交
68 69 70 71 72
export function copy(source: string, target: string, callback: (error: Error) => void, copiedSources?: { [path: string]: boolean }): void {
	if (!copiedSources) {
		copiedSources = Object.create(null);
	}

73
	fs.stat(source, (error, stat) => {
74 75 76 77 78
		if (error) {
			return callback(error);
		}

		if (!stat.isDirectory()) {
79
			return doCopyFile(source, target, stat.mode & 511, callback);
80
		}
E
Erich Gamma 已提交
81 82 83 84 85

		if (copiedSources[source]) {
			return callback(null); // escape when there are cycles (can happen with symlinks)
		}

86 87 88
		copiedSources[source] = true; // remember as copied

		const proceed = function () {
89
			readdir(source, (err, files) => {
90 91
				loop(files, (file: string, clb: (error: Error, result: string[]) => void) => {
					copy(paths.join(source, file), paths.join(target, file), (error: Error) => clb(error, void 0), copiedSources);
E
Erich Gamma 已提交
92 93
				}, callback);
			});
94 95 96 97 98 99
		};

		mkdirp(target, stat.mode & 511).done(proceed, proceed);
	});
}

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
function doCopyFile(source: string, target: string, mode: number, callback: (error: Error) => void): void {
	const reader = fs.createReadStream(source);
	const writer = fs.createWriteStream(target, { mode });

	let finished = false;
	const finish = (error?: Error) => {
		if (!finished) {
			finished = true;

			// in error cases, pass to callback
			if (error) {
				callback(error);
			}

			// we need to explicitly chmod because of https://github.com/nodejs/node/issues/1104
			else {
				fs.chmod(target, mode, callback);
			}
		}
	};

	// handle errors properly
	reader.once('error', error => finish(error));
	writer.once('error', error => finish(error));

	// we are done (underlying fd has been closed)
	writer.once('close', () => finish());

	// start piping
	reader.pipe(writer);
}

132 133 134 135 136 137 138 139 140 141 142
export function mkdirp(path: string, mode?: number): TPromise<boolean> {
	const mkdir = () => nfcall(fs.mkdir, path, mode)
		.then(null, (err: NodeJS.ErrnoException) => {
			if (err.code === 'EEXIST') {
				return nfcall(fs.stat, path)
					.then((stat: fs.Stats) => stat.isDirectory
						? null
						: TPromise.wrapError(new Error(`'${path}' exists and is not a directory.`)));
			}

			return TPromise.wrapError<boolean>(err);
E
Erich Gamma 已提交
143
		});
144

145
	// stop at root
146 147 148 149
	if (path === paths.dirname(path)) {
		return TPromise.as(true);
	}

150
	// recursively mkdir
151 152 153 154 155 156
	return mkdir().then(null, (err: NodeJS.ErrnoException) => {
		if (err.code === 'ENOENT') {
			return mkdirp(paths.dirname(path), mode).then(mkdir);
		}

		return TPromise.wrapError<boolean>(err);
E
Erich Gamma 已提交
157 158 159 160 161 162 163
	});
}

// Deletes the given path by first moving it out of the workspace. This has two benefits. For one, the operation can return fast because
// after the rename, the contents are out of the workspace although not yet deleted. The greater benefit however is that this operation
// will fail in case any file is used by another process. fs.unlink() in node will not bail if a file unlinked is used by another process.
// However, the consequences are bad as outlined in all the related bugs from https://github.com/joyent/node/issues/7164
164
export function del(path: string, tmpFolder: string, callback: (error: Error) => void, done?: (error: Error) => void): void {
165
	fs.exists(path, exists => {
E
Erich Gamma 已提交
166 167 168 169
		if (!exists) {
			return callback(null);
		}

170
		fs.stat(path, (err, stat) => {
E
Erich Gamma 已提交
171 172 173 174 175 176 177 178 179 180
			if (err || !stat) {
				return callback(err);
			}

			// Special windows workaround: A file or folder that ends with a "." cannot be moved to another place
			// because it is not a valid file name. In this case, we really have to do the deletion without prior move.
			if (path[path.length - 1] === '.' || strings.endsWith(path, './') || strings.endsWith(path, '.\\')) {
				return rmRecursive(path, callback);
			}

181
			const pathInTemp = paths.join(tmpFolder, uuid.generateUuid());
E
Erich Gamma 已提交
182 183 184 185 186 187 188 189 190
			fs.rename(path, pathInTemp, (error: Error) => {
				if (error) {
					return rmRecursive(path, callback); // if rename fails, delete without tmp dir
				}

				// Return early since the move succeeded
				callback(null);

				// do the heavy deletion outside the callers callback
191
				rmRecursive(pathInTemp, error => {
E
Erich Gamma 已提交
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
					if (error) {
						console.error(error);
					}

					if (done) {
						done(error);
					}
				});
			});
		});
	});
}

function rmRecursive(path: string, callback: (error: Error) => void): void {
	if (path === '\\' || path === '/') {
		return callback(new Error('Will not delete root!'));
	}

210
	fs.exists(path, exists => {
E
Erich Gamma 已提交
211 212 213
		if (!exists) {
			callback(null);
		} else {
214
			fs.lstat(path, (err, stat) => {
E
Erich Gamma 已提交
215 216 217
				if (err || !stat) {
					callback(err);
				} else if (!stat.isDirectory() || stat.isSymbolicLink() /* !!! never recurse into links when deleting !!! */) {
218
					const mode = stat.mode;
E
Erich Gamma 已提交
219 220 221 222 223 224 225 226 227 228 229 230
					if (!(mode & 128)) { // 128 === 0200
						fs.chmod(path, mode | 128, (err: Error) => { // 128 === 0200
							if (err) {
								callback(err);
							} else {
								fs.unlink(path, callback);
							}
						});
					} else {
						fs.unlink(path, callback);
					}
				} else {
231
					readdir(path, (err, children) => {
E
Erich Gamma 已提交
232 233 234 235 236
						if (err || !children) {
							callback(err);
						} else if (children.length === 0) {
							fs.rmdir(path, callback);
						} else {
B
Benjamin Pasero 已提交
237 238
							let firstError: Error = null;
							let childrenLeft = children.length;
239
							children.forEach(child => {
E
Erich Gamma 已提交
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
								rmRecursive(paths.join(path, child), (err: Error) => {
									childrenLeft--;
									if (err) {
										firstError = firstError || err;
									}

									if (childrenLeft === 0) {
										if (firstError) {
											callback(firstError);
										} else {
											fs.rmdir(path, callback);
										}
									}
								});
							});
						}
					});
				}
			});
		}
	});
}

B
Benjamin Pasero 已提交
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
export function delSync(path: string): void {
	try {
		const stat = fs.lstatSync(path);
		if (stat.isDirectory() && !stat.isSymbolicLink()) {
			readdirSync(path).forEach(child => delSync(paths.join(path, child)));
			fs.rmdirSync(path);
		} else {
			fs.unlinkSync(path);
		}
	} catch (err) {
		if (err.code === 'ENOENT') {
			return; // not found
		}

		throw err;
	}
}

E
Erich Gamma 已提交
281 282 283 284 285 286 287 288 289 290
export function mv(source: string, target: string, callback: (error: Error) => void): void {
	if (source === target) {
		return callback(null);
	}

	function updateMtime(err: Error): void {
		if (err) {
			return callback(err);
		}

291
		fs.stat(target, (error, stat) => {
E
Erich Gamma 已提交
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
			if (error) {
				return callback(error);
			}

			if (stat.isDirectory()) {
				return callback(null);
			}

			fs.open(target, 'a', null, (err: Error, fd: number) => {
				if (err) {
					return callback(err);
				}

				fs.futimes(fd, stat.atime, new Date(), (err: Error) => {
					if (err) {
						return callback(err);
					}

					fs.close(fd, callback);
				});
			});
		});
	}

	// Try native rename()
	fs.rename(source, target, (err: Error) => {
		if (!err) {
			return updateMtime(null);
		}

		// In two cases we fallback to classic copy and delete:
		//
		// 1.) The EXDEV error indicates that source and target are on different devices
		// In this case, fallback to using a copy() operation as there is no way to
		// rename() between different devices.
		//
		// 2.) The user tries to rename a file/folder that ends with a dot. This is not
		// really possible to move then, at least on UNC devices.
		if (err && source.toLowerCase() !== target.toLowerCase() && ((<any>err).code === 'EXDEV') || strings.endsWith(source, '.')) {
			return copy(source, target, (err: Error) => {
				if (err) {
					return callback(err);
				}

				rmRecursive(source, updateMtime);
			});
		}

		return callback(err);
	});
342 343
}

344 345 346 347 348 349 350 351 352
export interface IWriteFileOptions {
	mode?: number;
	flag?: string;
	encoding?: {
		charset: string;
		addBOM: boolean;
	};
}

353
let canFlush = true;
354
export function writeFileAndFlush(path: string, data: string | NodeBuffer | NodeJS.ReadableStream, options: IWriteFileOptions, callback: (error?: Error) => void): void {
355 356
	options = ensureOptions(options);

357
	if (typeof data === 'string' || Buffer.isBuffer(data)) {
358
		doWriteFileAndFlush(path, data, options, callback);
359 360
	} else {
		doWriteFileStreamAndFlush(path, data, options, callback);
361 362 363
	}
}

364
function doWriteFileStreamAndFlush(path: string, reader: NodeJS.ReadableStream, options: IWriteFileOptions, callback: (error?: Error) => void): void {
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389

	// finish only once
	let finished = false;
	const finish = (error?: Error) => {
		if (!finished) {
			finished = true;

			// in error cases we need to manually close streams
			// if the write stream was successfully opened
			if (error) {
				if (isOpen) {
					writer.once('close', () => callback(error));
					writer.close();
				} else {
					callback(error);
				}
			}

			// otherwise just return without error
			else {
				callback();
			}
		}
	};

B
Benjamin Pasero 已提交
390 391 392
	// create writer to target. we set autoClose: false because we want to use the streams
	// file descriptor to call fs.fdatasync to ensure the data is flushed to disk
	const writer = fs.createWriteStream(path, { mode: options.mode, flags: options.flag, autoClose: false });
393

B
Benjamin Pasero 已提交
394
	// Event: 'open'
B
Benjamin Pasero 已提交
395
	// Purpose: save the fd for later use and start piping
B
Benjamin Pasero 已提交
396
	// Notes: will not be called when there is an error opening the file descriptor!
397 398 399 400 401
	let fd: number;
	let isOpen: boolean;
	writer.once('open', descriptor => {
		fd = descriptor;
		isOpen = true;
B
Benjamin Pasero 已提交
402

403 404 405 406 407 408
		// if an encoding is provided, we need to pipe the stream through
		// an encoder stream and forward the encoding related options
		if (options.encoding) {
			reader = reader.pipe(encodeStream(options.encoding.charset, { addBOM: options.encoding.addBOM }));
		}

B
Benjamin Pasero 已提交
409 410 411 412
		// start data piping only when we got a successful open. this ensures that we do
		// not consume the stream when an error happens and helps to fix this issue:
		// https://github.com/Microsoft/vscode/issues/42542
		reader.pipe(writer);
413 414
	});

B
Benjamin Pasero 已提交
415 416 417 418
	// Event: 'error'
	// Purpose: to return the error to the outside and to close the write stream (does not happen automatically)
	reader.once('error', error => finish(error));
	writer.once('error', error => finish(error));
419

B
Benjamin Pasero 已提交
420 421 422 423 424
	// Event: 'finish'
	// Purpose: use fs.fdatasync to flush the contents to disk
	// Notes: event is called when the writer has finished writing to the underlying resource. we must call writer.close()
	// because we have created the WriteStream with autoClose: false
	writer.once('finish', () => {
425 426 427 428 429 430 431 432 433 434 435 436

		// flush to disk
		if (canFlush && isOpen) {
			fs.fdatasync(fd, (syncError: Error) => {

				// In some exotic setups it is well possible that node fails to sync
				// In that case we disable flushing and warn to the console
				if (syncError) {
					console.warn('[node.js fs] fdatasync is now disabled for this session because it failed: ', syncError);
					canFlush = false;
				}

B
Benjamin Pasero 已提交
437
				writer.close();
438
			});
B
Benjamin Pasero 已提交
439 440
		} else {
			writer.close();
441 442 443
		}
	});

B
Benjamin Pasero 已提交
444 445 446 447
	// Event: 'close'
	// Purpose: signal we are done to the outside
	// Notes: event is called when the writer's filedescriptor is closed
	writer.once('close', () => finish());
448 449
}

450 451 452 453 454
// Calls fs.writeFile() followed by a fs.sync() call to flush the changes to disk
// We do this in cases where we want to make sure the data is really on disk and
// not in some cache.
//
// See https://github.com/nodejs/node/blob/v5.10.0/lib/fs.js#L1194
455 456 457 458 459
function doWriteFileAndFlush(path: string, data: string | NodeBuffer, options: IWriteFileOptions, callback: (error?: Error) => void): void {
	if (options.encoding) {
		data = encode(data, options.encoding.charset, { addBOM: options.encoding.addBOM });
	}

460
	if (!canFlush) {
461
		return fs.writeFile(path, data, { mode: options.mode, flag: options.flag }, callback);
462 463
	}

464 465 466 467 468 469 470
	// Open the file with same flags and mode as fs.writeFile()
	fs.open(path, options.flag, options.mode, (openError, fd) => {
		if (openError) {
			return callback(openError);
		}

		// It is valid to pass a fd handle to fs.writeFile() and this will keep the handle open!
471
		fs.writeFile(fd, data, writeError => {
472 473 474 475 476
			if (writeError) {
				return fs.close(fd, () => callback(writeError)); // still need to close the handle on error!
			}

			// Flush contents (not metadata) of the file to disk
477
			fs.fdatasync(fd, (syncError: Error) => {
478 479 480 481 482 483 484 485

				// In some exotic setups it is well possible that node fails to sync
				// In that case we disable flushing and warn to the console
				if (syncError) {
					console.warn('[node.js fs] fdatasync is now disabled for this session because it failed: ', syncError);
					canFlush = false;
				}

486
				return fs.close(fd, closeError => callback(closeError));
487 488 489
			});
		});
	});
490 491
}

492
export function writeFileAndFlushSync(path: string, data: string | NodeBuffer, options?: IWriteFileOptions): void {
493 494
	options = ensureOptions(options);

495 496 497 498
	if (options.encoding) {
		data = encode(data, options.encoding.charset, { addBOM: options.encoding.addBOM });
	}

499
	if (!canFlush) {
500
		return fs.writeFileSync(path, data, { mode: options.mode, flag: options.flag });
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
	}

	// Open the file with same flags and mode as fs.writeFile()
	const fd = fs.openSync(path, options.flag, options.mode);

	try {

		// It is valid to pass a fd handle to fs.writeFile() and this will keep the handle open!
		fs.writeFileSync(fd, data);

		// Flush contents (not metadata) of the file to disk
		try {
			fs.fdatasyncSync(fd);
		} catch (syncError) {
			console.warn('[node.js fs] fdatasyncSync is now disabled for this session because it failed: ', syncError);
			canFlush = false;
		}
	} finally {
		fs.closeSync(fd);
	}
}

523
function ensureOptions(options?: IWriteFileOptions): IWriteFileOptions {
524 525 526 527
	if (!options) {
		return { mode: 0o666, flag: 'w' };
	}

528
	const ensuredOptions: IWriteFileOptions = { mode: options.mode, flag: options.flag, encoding: options.encoding };
529 530 531 532 533 534 535 536 537 538 539 540

	if (typeof ensuredOptions.mode !== 'number') {
		ensuredOptions.mode = 0o666;
	}

	if (typeof ensuredOptions.flag !== 'string') {
		ensuredOptions.flag = 'w';
	}

	return ensuredOptions;
}

541 542 543
/**
 * Copied from: https://github.com/Microsoft/vscode-node-debug/blob/master/src/node/pathUtilities.ts#L83
 *
544
 * Given an absolute, normalized, and existing file path 'realcase' returns the exact path that the file has on disk.
545 546 547
 * On a case insensitive file system, the returned path might differ from the original path by character casing.
 * On a case sensitive file system, the returned path will always be identical to the original path.
 * In case of errors, null is returned. But you cannot use this function to verify that a path exists.
548
 * realcaseSync does not handle '..' or '.' path segments and it does not take the locale into account.
549
 */
550
export function realcaseSync(path: string): string {
551 552 553 554 555
	const dir = paths.dirname(path);
	if (path === dir) {	// end recursion
		return path;
	}

B
Benjamin Pasero 已提交
556
	const name = (paths.basename(path) /* can be '' for windows drive letters */ || path).toLowerCase();
557 558 559 560 561
	try {
		const entries = readdirSync(dir);
		const found = entries.filter(e => e.toLowerCase() === name);	// use a case insensitive search
		if (found.length === 1) {
			// on a case sensitive filesystem we cannot determine here, whether the file exists or not, hence we need the 'file exists' precondition
562
			const prefix = realcaseSync(dir);   // recurse
563 564 565 566 567 568 569
			if (prefix) {
				return paths.join(prefix, found[0]);
			}
		} else if (found.length > 1) {
			// must be a case sensitive $filesystem
			const ix = found.indexOf(name);
			if (ix >= 0) {	// case sensitive
570
				const prefix = realcaseSync(dir);   // recurse
571 572 573 574 575 576 577 578 579 580
				if (prefix) {
					return paths.join(prefix, found[ix]);
				}
			}
		}
	} catch (error) {
		// silently ignore error
	}

	return null;
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
}

export function realpathSync(path: string): string {
	try {
		return fs.realpathSync(path);
	} catch (error) {

		// We hit an error calling fs.realpathSync(). Since fs.realpathSync() is doing some path normalization
		// we now do a similar normalization and then try again if we can access the path with read
		// permissions at least. If that succeeds, we return that path.
		// fs.realpath() is resolving symlinks and that can fail in certain cases. The workaround is
		// to not resolve links but to simply see if the path is read accessible or not.
		const normalizedPath = normalizePath(path);
		fs.accessSync(normalizedPath, fs.constants.R_OK); // throws in case of an error

		return normalizedPath;
	}
}

export function realpath(path: string, callback: (error: Error, realpath: string) => void): void {
	return fs.realpath(path, (error, realpath) => {
		if (!error) {
			return callback(null, realpath);
		}

		// We hit an error calling fs.realpath(). Since fs.realpath() is doing some path normalization
		// we now do a similar normalization and then try again if we can access the path with read
		// permissions at least. If that succeeds, we return that path.
		// fs.realpath() is resolving symlinks and that can fail in certain cases. The workaround is
		// to not resolve links but to simply see if the path is read accessible or not.
		const normalizedPath = normalizePath(path);

		return fs.access(normalizedPath, fs.constants.R_OK, error => {
			return callback(error, normalizedPath);
		});
	});
}

function normalizePath(path: string): string {
	return strings.rtrim(paths.normalize(path), paths.sep);
621
}
622

B
Benjamin Pasero 已提交
623
export function watch(path: string, onChange: (type: string, path?: string) => void, onError: (error: string) => void): fs.FSWatcher {
624 625 626 627 628 629 630 631 632 633
	try {
		const watcher = fs.watch(path);

		watcher.on('change', (type, raw) => {
			let file: string = null;
			if (raw) { // https://github.com/Microsoft/vscode/issues/38191
				file = raw.toString();
				if (platform.isMacintosh) {
					// Mac: uses NFD unicode form on disk, but we want NFC
					// See also https://github.com/nodejs/node/issues/2165
634
					file = normalizeNFC(file);
635
				}
636
			}
637

638 639
			onChange(type, file);
		});
640

641 642 643 644 645 646 647 648 649 650
		watcher.on('error', (code: number, signal: string) => onError(`Failed to watch ${path} for changes (${code}, ${signal})`));

		return watcher;
	} catch (error) {
		fs.exists(path, exists => {
			if (exists) {
				onError(`Failed to watch ${path} for changes (${error.toString()})`);
			}
		});
	}
651

652
	return void 0;
I
isidor 已提交
653
}