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

'use strict';

import uuid = require('vs/base/common/uuid');
import strings = require('vs/base/common/strings');
import platform = require('vs/base/common/platform');

import flow = require('vs/base/node/flow');

import fs = require('fs');
import paths = require('path');

B
Benjamin Pasero 已提交
17
const loop = flow.loop;
E
Erich Gamma 已提交
18

19 20
const ASAR_EXT = '.asar';

B
Benjamin Pasero 已提交
21 22 23 24
export interface IRawStat {
	size: number;
	mtime: Date;
	atime: Date;
25
	mode: number;
B
Benjamin Pasero 已提交
26 27 28 29 30 31
	isDirectory(): boolean;
	isSymbolicLink(): boolean;
	isFile(): boolean;
}

class FakeAsarStat implements IRawStat {
32
	size = 1024;
B
Benjamin Pasero 已提交
33 34 35
	mode = 0;
	mtime = new Date(0);
	atime = new Date(0);
36 37 38

	isDirectory(): boolean { return false; }
	isSymbolicLink(): boolean { return false; }
B
Benjamin Pasero 已提交
39
	isFile(): boolean { return true; }
40 41
}

B
Benjamin Pasero 已提交
42
export function stat(path: string, callback: (error: Error, stat: IRawStat) => void): void {
43
	if (path && paths.extname(path) === ASAR_EXT) {
B
Benjamin Pasero 已提交
44
		return callback(null, new FakeAsarStat()); // https://github.com/Microsoft/vscode/issues/646
45 46 47 48 49
	}

	return fs.stat(path, callback);
}

B
Benjamin Pasero 已提交
50 51 52 53 54 55 56 57 58
export function statSync(path: string): IRawStat {
	if (path && paths.extname(path) === ASAR_EXT) {
		return new FakeAsarStat(); // https://github.com/Microsoft/vscode/issues/646
	}

	return fs.statSync(path);
}

export function lstat(path: string, callback: (error: Error, stat: IRawStat) => void): void {
59
	if (path && paths.extname(path) === ASAR_EXT) {
B
Benjamin Pasero 已提交
60
		return callback(null, new FakeAsarStat()); // https://github.com/Microsoft/vscode/issues/646
61 62 63 64 65
	}

	return fs.lstat(path, callback);
}

E
Erich Gamma 已提交
66
export function readdir(path: string, callback: (error: Error, files: string[]) => void): void {
67 68 69
	if (path && paths.extname(path) === ASAR_EXT) {
		return callback(null, []); // https://github.com/Microsoft/vscode/issues/646
	}
E
Erich Gamma 已提交
70 71 72 73

	// Mac: uses NFD unicode form on disk, but we want NFC
	// See also https://github.com/nodejs/node/issues/2165
	if (platform.isMacintosh) {
74
		return readdirNormalize(path, (error, children) => {
E
Erich Gamma 已提交
75 76 77 78
			if (error) {
				return callback(error, null);
			}

79
			return callback(null, children.map(c => strings.normalizeNFC(c)));
E
Erich Gamma 已提交
80 81 82
		});
	}

83
	return readdirNormalize(path, callback);
B
Benjamin Pasero 已提交
84
}
E
Erich Gamma 已提交
85

86 87 88 89 90 91
function readdirNormalize(path: string, callback: (error: Error, files: string[]) => void): void {
	fs.readdir(path, (error, children) => {
		if (error) {
			return callback(error, null);
		}

92
		// Bug in node: In some environments we get "." and ".." as entries from the call to readdir().
93 94 95
		// For example Sharepoint via WebDav on Windows includes them. We never want those
		// entries in the result set though because they are not valid children of the folder
		// for our concerns.
96
		// See https://github.com/nodejs/node/issues/4002
B
polish  
Benjamin Pasero 已提交
97
		return callback(null, children.filter(c => c !== '.' && c !== '..'));
B
Benjamin Pasero 已提交
98
	});
99 100
}

E
Erich Gamma 已提交
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
export function mkdirp(path: string, mode: number, callback: (error: Error) => void): void {
	fs.exists(path, (exists) => {
		if (exists) {
			return isDirectory(path, (err: Error, itIs?: boolean) => {
				if (err) {
					return callback(err);
				}

				if (!itIs) {
					return callback(new Error('"' + path + '" is not a directory.'));
				}

				callback(null);
			});
		}

		mkdirp(paths.dirname(path), mode, (err: Error) => {
			if (err) { callback(err); return; }

			if (mode) {
121 122 123 124 125 126 127
				fs.mkdir(path, mode, (error) => {
					if (error) {
						return callback(error);
					}

					fs.chmod(path, mode, callback); // we need to explicitly chmod because of https://github.com/nodejs/node/issues/1104
				});
E
Erich Gamma 已提交
128 129 130 131 132 133 134 135
			} else {
				fs.mkdir(path, null, callback);
			}
		});
	});
}

function isDirectory(path: string, callback: (error: Error, isDirectory?: boolean) => void): void {
B
Benjamin Pasero 已提交
136
	stat(path, (error: Error, stat: IRawStat) => {
E
Erich Gamma 已提交
137 138 139 140 141 142 143 144 145 146 147
		if (error) { return callback(error); }

		callback(null, stat.isDirectory());
	});
}

export function copy(source: string, target: string, callback: (error: Error) => void, copiedSources?: { [path: string]: boolean }): void {
	if (!copiedSources) {
		copiedSources = Object.create(null);
	}

148
	stat(source, (error, stat) => {
E
Erich Gamma 已提交
149
		if (error) { return callback(error); }
150
		if (!stat.isDirectory()) { return pipeFs(source, target, stat.mode & 511, callback); }
E
Erich Gamma 已提交
151 152 153 154 155 156 157 158

		if (copiedSources[source]) {
			return callback(null); // escape when there are cycles (can happen with symlinks)
		} else {
			copiedSources[source] = true; // remember as copied
		}

		mkdirp(target, stat.mode & 511, (err) => {
159
			readdir(source, (err, files) => {
E
Erich Gamma 已提交
160 161 162 163 164 165 166 167
				loop(files, (file: string, clb: (error: Error) => void) => {
					copy(paths.join(source, file), paths.join(target, file), clb, copiedSources);
				}, callback);
			});
		});
	});
}

168
function pipeFs(source: string, target: string, mode: number, callback: (error: Error) => void): void {
B
Benjamin Pasero 已提交
169
	let callbackHandled = false;
E
Erich Gamma 已提交
170

B
Benjamin Pasero 已提交
171 172
	let readStream = fs.createReadStream(source);
	let writeStream = fs.createWriteStream(target, { mode: mode });
E
Erich Gamma 已提交
173

B
Benjamin Pasero 已提交
174
	let onError = (error: Error) => {
E
Erich Gamma 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187
		if (!callbackHandled) {
			callbackHandled = true;
			callback(error);
		}
	};

	readStream.on('error', onError);
	writeStream.on('error', onError);

	readStream.on('end', () => {
		(<any>writeStream).end(() => { // In this case the write stream is known to have an end signature with callback
			if (!callbackHandled) {
				callbackHandled = true;
188 189

				fs.chmod(target, mode, callback); // we need to explicitly chmod because of https://github.com/nodejs/node/issues/1104
E
Erich Gamma 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
			}
		});
	});

	// In node 0.8 there is no easy way to find out when the pipe operation has finished. As such, we use the end property = false
	// so that we are in charge of calling end() on the write stream and we will be notified when the write stream is really done.
	// We can do this because file streams have an end() method that allows to pass in a callback.
	// In node 0.10 there is an event 'finish' emitted from the write stream that can be used. See
	// https://groups.google.com/forum/?fromgroups=#!topic/nodejs/YWQ1sRoXOdI
	readStream.pipe(writeStream, { end: false });
}

// 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
206
export function del(path: string, tmpFolder: string, callback: (error: Error) => void, done?: (error: Error) => void): void {
E
Erich Gamma 已提交
207 208 209 210 211
	fs.exists(path, (exists) => {
		if (!exists) {
			return callback(null);
		}

212
		stat(path, (err, stat) => {
E
Erich Gamma 已提交
213 214 215 216 217 218 219 220 221 222
			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);
			}

B
Benjamin Pasero 已提交
223
			let pathInTemp = paths.join(tmpFolder, uuid.generateUuid());
E
Erich Gamma 已提交
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
			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
				rmRecursive(pathInTemp, (error) => {
					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!'));
	}

	fs.exists(path, (exists) => {
		if (!exists) {
			callback(null);
		} else {
256
			lstat(path, (err, stat) => {
E
Erich Gamma 已提交
257 258 259
				if (err || !stat) {
					callback(err);
				} else if (!stat.isDirectory() || stat.isSymbolicLink() /* !!! never recurse into links when deleting !!! */) {
B
Benjamin Pasero 已提交
260
					let mode = stat.mode;
E
Erich Gamma 已提交
261 262 263 264 265 266 267 268 269 270 271 272
					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 {
273
					readdir(path, (err, children) => {
E
Erich Gamma 已提交
274 275 276 277 278
						if (err || !children) {
							callback(err);
						} else if (children.length === 0) {
							fs.rmdir(path, callback);
						} else {
B
Benjamin Pasero 已提交
279 280
							let firstError: Error = null;
							let childrenLeft = children.length;
E
Erich Gamma 已提交
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
							children.forEach((child) => {
								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);
										}
									}
								});
							});
						}
					});
				}
			});
		}
	});
}

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);
		}

B
Benjamin Pasero 已提交
315
		stat(target, (error: Error, stat: IRawStat) => {
E
Erich Gamma 已提交
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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
			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);
	});
}