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

E
Erich Gamma 已提交
6 7
'use strict';

8 9 10 11 12
import * as paths from 'path';
import * as fs from 'fs';
import * as os from 'os';
import * as crypto from 'crypto';
import * as assert from 'assert';
13 14
import { isParent, FileOperation, FileOperationEvent, IContent, IFileService, IResolveFileOptions, IResolveFileResult, IResolveContentOptions, IFileStat, IStreamContent, FileOperationError, FileOperationResult, IUpdateContentOptions, FileChangeType, FileChangesEvent, ICreateFileOptions, IContentData, ITextSnapshot, IFilesConfiguration, IFileSystemProviderRegistrationEvent, IFileSystemProvider } from 'vs/platform/files/common/files';
import { MAX_FILE_SIZE, MAX_HEAP_SIZE } from 'vs/platform/files/node/files';
15 16 17
import { isEqualOrParent } from 'vs/base/common/paths';
import { ResourceMap } from 'vs/base/common/map';
import * as arrays from 'vs/base/common/arrays';
J
Johannes Rieken 已提交
18
import { TPromise } from 'vs/base/common/winjs.base';
19 20
import * as objects from 'vs/base/common/objects';
import * as extfs from 'vs/base/node/extfs';
B
Benjamin Pasero 已提交
21
import { nfcall, ThrottledDelayer, toWinJsPromise } from 'vs/base/common/async';
E
Erich Gamma 已提交
22
import uri from 'vs/base/common/uri';
23 24
import * as nls from 'vs/nls';
import { isWindows, isLinux, isMacintosh } from 'vs/base/common/platform';
B
Benjamin Pasero 已提交
25
import { IDisposable, toDisposable, Disposable } from 'vs/base/common/lifecycle';
26 27 28 29 30 31 32
import { IWorkspaceContextService, WorkbenchState } from 'vs/platform/workspace/common/workspace';
import * as pfs from 'vs/base/node/pfs';
import * as encoding from 'vs/base/node/encoding';
import * as flow from 'vs/base/node/flow';
import { FileWatcher as UnixWatcherService } from 'vs/workbench/services/files/node/watcher/unix/watcherService';
import { FileWatcher as WindowsWatcherService } from 'vs/workbench/services/files/node/watcher/win32/watcherService';
import { toFileChangesEvent, normalize, IRawFileChange } from 'vs/workbench/services/files/node/watcher/common';
M
Matt Bierner 已提交
33
import { Event, Emitter } from 'vs/base/common/event';
34
import { FileWatcher as NsfwWatcherService } from 'vs/workbench/services/files/node/watcher/nsfw/watcherService';
35
import { ITextResourceConfigurationService } from 'vs/editor/common/services/resourceConfiguration';
36 37 38 39 40
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { ILifecycleService, LifecyclePhase } from 'vs/platform/lifecycle/common/lifecycle';
import { getBaseLabel } from 'vs/base/common/labels';
B
Benjamin Pasero 已提交
41
import { Schemas } from 'vs/base/common/network';
42 43 44 45
import { IStorageService, StorageScope } from 'vs/platform/storage/common/storage';
import { INotificationService, Severity } from 'vs/platform/notification/common/notification';
import { onUnexpectedError } from 'vs/base/common/errors';
import product from 'vs/platform/node/product';
46
import { IEncodingOverride, ResourceEncodings } from 'vs/workbench/services/files/electron-browser/encoding';
47
import { createReadableOfSnapshot } from 'vs/workbench/services/files/electron-browser/streams';
48

49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
class BufferPool {

	static _64K = new BufferPool(64 * 1024, 5);

	constructor(
		readonly bufferSize: number,
		private readonly _capacity: number,
		private readonly _free: Buffer[] = [],
	) { }

	acquire(): Buffer {
		if (this._free.length === 0) {
			return Buffer.allocUnsafe(this.bufferSize);
		} else {
			return this._free.shift();
		}
	}

	release(buf: Buffer): void {
		if (this._free.length <= this._capacity) {
			this._free.push(buf);
		}
	}
}

export interface IFileServiceTestOptions {
	disableWatcher?: boolean;
	encodingOverride?: IEncodingOverride[];
}

B
Benjamin Pasero 已提交
79
export class FileService extends Disposable implements IFileService {
E
Erich Gamma 已提交
80

B
Benjamin Pasero 已提交
81
	_serviceBrand: any;
82

83 84 85
	private static readonly FS_EVENT_DELAY = 50; // aggregate and only emit events when changes have stopped for this duration (in ms)
	private static readonly FS_REWATCH_DELAY = 300; // delay to rewatch a file that was renamed or deleted (in ms)

86 87
	private static readonly NET_VERSION_ERROR = 'System.MissingMethodException';
	private static readonly NET_VERSION_ERROR_IGNORE_KEY = 'ignoreNetVersionError';
88

B
Benjamin Pasero 已提交
89 90 91
	private static readonly ENOSPC_ERROR = 'ENOSPC';
	private static readonly ENOSPC_ERROR_IGNORE_KEY = 'ignoreEnospcError';

B
Benjamin Pasero 已提交
92 93
	protected readonly _onFileChanges: Emitter<FileChangesEvent> = this._register(new Emitter<FileChangesEvent>());
	get onFileChanges(): Event<FileChangesEvent> { return this._onFileChanges.event; }
94

B
Benjamin Pasero 已提交
95 96 97 98 99
	protected readonly _onAfterOperation: Emitter<FileOperationEvent> = this._register(new Emitter<FileOperationEvent>());
	get onAfterOperation(): Event<FileOperationEvent> { return this._onAfterOperation.event; }

	protected readonly _onDidChangeFileSystemProviderRegistrations = this._register(new Emitter<IFileSystemProviderRegistrationEvent>());
	get onDidChangeFileSystemProviderRegistrations(): Event<IFileSystemProviderRegistrationEvent> { return this._onDidChangeFileSystemProviderRegistrations.event; }
E
Erich Gamma 已提交
100

101
	private activeWorkspaceFileChangeWatcher: IDisposable;
B
Benjamin Pasero 已提交
102
	private activeFileChangesWatchers: ResourceMap<{ unwatch: Function, count: number }>;
103 104 105
	private fileChangesWatchDelayer: ThrottledDelayer<void>;
	private undeliveredRawFileChangesEvents: IRawFileChange[];

106
	private _encoding: ResourceEncodings;
107

E
Erich Gamma 已提交
108
	constructor(
109 110 111 112 113 114 115 116
		private contextService: IWorkspaceContextService,
		private environmentService: IEnvironmentService,
		private textResourceConfigurationService: ITextResourceConfigurationService,
		private configurationService: IConfigurationService,
		private lifecycleService: ILifecycleService,
		private storageService: IStorageService,
		private notificationService: INotificationService,
		private options: IFileServiceTestOptions = Object.create(null)
E
Erich Gamma 已提交
117
	) {
B
Benjamin Pasero 已提交
118
		super();
119

B
Benjamin Pasero 已提交
120
		this.activeFileChangesWatchers = new ResourceMap<{ unwatch: Function, count: number }>();
121 122
		this.fileChangesWatchDelayer = new ThrottledDelayer<void>(FileService.FS_EVENT_DELAY);
		this.undeliveredRawFileChangesEvents = [];
123

124
		this._encoding = new ResourceEncodings(textResourceConfigurationService, environmentService, contextService, this.options.encodingOverride);
E
Erich Gamma 已提交
125

126
		this.registerListeners();
E
Erich Gamma 已提交
127 128
	}

B
Benjamin Pasero 已提交
129
	get encoding(): ResourceEncodings {
130 131 132
		return this._encoding;
	}

133 134 135 136 137 138 139 140
	private registerListeners(): void {

		// Wait until we are fully running before starting file watchers
		this.lifecycleService.when(LifecyclePhase.Running).then(() => {
			this.setupFileWatching();
		});

		// Workbench State Change
B
Benjamin Pasero 已提交
141
		this._register(this.contextService.onDidChangeWorkbenchState(() => {
142 143 144 145 146 147 148
			if (this.lifecycleService.phase >= LifecyclePhase.Running) {
				this.setupFileWatching();
			}
		}));

		// Lifecycle
		this.lifecycleService.onShutdown(this.dispose, this);
149 150
	}

151
	private handleError(error: string | Error): void {
B
Benjamin Pasero 已提交
152 153 154 155
		const msg = error ? error.toString() : void 0;
		if (!msg) {
			return;
		}
156 157

		// Forward to unexpected error handler
158
		onUnexpectedError(msg);
159

B
Benjamin Pasero 已提交
160
		// Detect if we run < .NET Framework 4.5 (TODO@ben remove with new watcher impl)
B
Benjamin Pasero 已提交
161
		if (msg.indexOf(FileService.NET_VERSION_ERROR) >= 0 && !this.storageService.getBoolean(FileService.NET_VERSION_ERROR_IGNORE_KEY, StorageScope.WORKSPACE)) {
162 163 164 165 166 167 168 169 170 171 172 173 174
			this.notificationService.prompt(
				Severity.Warning,
				nls.localize('netVersionError', "The Microsoft .NET Framework 4.5 is required. Please follow the link to install it."),
				[{
					label: nls.localize('installNet', "Download .NET Framework 4.5"),
					run: () => window.open('https://go.microsoft.com/fwlink/?LinkId=786533')
				},
				{
					label: nls.localize('neverShowAgain', "Don't Show Again"),
					isSecondary: true,
					run: () => this.storageService.store(FileService.NET_VERSION_ERROR_IGNORE_KEY, true, StorageScope.WORKSPACE)
				}]
			);
175
		}
B
Benjamin Pasero 已提交
176

177
		// Detect if we run into ENOSPC issues
B
Benjamin Pasero 已提交
178
		if (msg.indexOf(FileService.ENOSPC_ERROR) >= 0 && !this.storageService.getBoolean(FileService.ENOSPC_ERROR_IGNORE_KEY, StorageScope.WORKSPACE)) {
179 180 181 182 183 184 185 186 187 188 189 190 191
			this.notificationService.prompt(
				Severity.Warning,
				nls.localize('enospcError', "{0} is unable to watch for file changes in this large workspace. Please follow the instructions link to resolve this issue.", product.nameLong),
				[{
					label: nls.localize('learnMore', "Instructions"),
					run: () => window.open('https://go.microsoft.com/fwlink/?linkid=867693')
				},
				{
					label: nls.localize('neverShowAgain', "Don't Show Again"),
					isSecondary: true,
					run: () => this.storageService.store(FileService.ENOSPC_ERROR_IGNORE_KEY, true, StorageScope.WORKSPACE)
				}]
			);
B
Benjamin Pasero 已提交
192
		}
193 194
	}

195
	private setupFileWatching(): void {
196

197 198 199 200
		// dispose old if any
		if (this.activeWorkspaceFileChangeWatcher) {
			this.activeWorkspaceFileChangeWatcher.dispose();
		}
201

202 203 204 205 206
		// Return if not aplicable
		const workbenchState = this.contextService.getWorkbenchState();
		if (workbenchState === WorkbenchState.EMPTY || this.options.disableWatcher) {
			return;
		}
207

208
		// new watcher: use it if setting tells us so or we run in multi-root environment
B
Benjamin Pasero 已提交
209 210
		const configuration = this.configurationService.getValue<IFilesConfiguration>();
		if ((configuration.files && configuration.files.useExperimentalFileWatcher) || workbenchState === WorkbenchState.WORKSPACE) {
211 212
			const multiRootWatcher = new NsfwWatcherService(this.contextService, this.configurationService, e => this._onFileChanges.fire(e), err => this.handleError(err), this.environmentService.verbose);
			this.activeWorkspaceFileChangeWatcher = toDisposable(multiRootWatcher.startWatching());
213
		}
B
Benjamin Pasero 已提交
214

215
		// legacy watcher
216
		else {
B
Benjamin Pasero 已提交
217 218 219 220 221
			let watcherIgnoredPatterns: string[] = [];
			if (configuration.files && configuration.files.watcherExclude) {
				watcherIgnoredPatterns = Object.keys(configuration.files.watcherExclude).filter(k => !!configuration.files.watcherExclude[k]);
			}

222
			if (isWindows) {
223 224
				const legacyWindowsWatcher = new WindowsWatcherService(this.contextService, watcherIgnoredPatterns, e => this._onFileChanges.fire(e), err => this.handleError(err), this.environmentService.verbose);
				this.activeWorkspaceFileChangeWatcher = toDisposable(legacyWindowsWatcher.startWatching());
225
			} else {
M
Martin Aeschlimann 已提交
226
				const legacyUnixWatcher = new UnixWatcherService(this.contextService, this.configurationService, e => this._onFileChanges.fire(e), err => this.handleError(err), this.environmentService.verbose);
227
				this.activeWorkspaceFileChangeWatcher = toDisposable(legacyUnixWatcher.startWatching());
228 229
			}
		}
B
Benjamin Pasero 已提交
230 231
	}

B
Benjamin Pasero 已提交
232
	registerProvider(scheme: string, provider: IFileSystemProvider): IDisposable {
233 234 235
		throw new Error('not implemented');
	}

B
Benjamin Pasero 已提交
236
	canHandleResource(resource: uri): boolean {
237 238 239
		return resource.scheme === Schemas.file;
	}

B
Benjamin Pasero 已提交
240
	resolveFile(resource: uri, options?: IResolveFileOptions): TPromise<IFileStat> {
241
		return this.resolve(resource, options);
E
Erich Gamma 已提交
242 243
	}

B
Benjamin Pasero 已提交
244
	resolveFiles(toResolve: { resource: uri, options?: IResolveFileOptions }[]): TPromise<IResolveFileResult[]> {
245 246
		return TPromise.join(toResolve.map(resourceAndOptions => this.resolve(resourceAndOptions.resource, resourceAndOptions.options)
			.then(stat => ({ stat, success: true }), error => ({ stat: void 0, success: false }))));
I
isidor 已提交
247 248
	}

B
Benjamin Pasero 已提交
249
	existsFile(resource: uri): TPromise<boolean> {
250
		return this.resolveFile(resource).then(() => true, () => false);
251 252
	}

B
Benjamin Pasero 已提交
253
	resolveContent(resource: uri, options?: IResolveContentOptions): TPromise<IContent> {
254 255 256 257 258 259 260 261 262
		return this.resolveStreamContent(resource, options).then(streamContent => {
			return new TPromise<IContent>((resolve, reject) => {

				const result: IContent = {
					resource: streamContent.resource,
					name: streamContent.name,
					mtime: streamContent.mtime,
					etag: streamContent.etag,
					encoding: streamContent.encoding,
I
isidor 已提交
263
					isReadonly: streamContent.isReadonly,
264 265 266 267 268 269 270 271 272 273
					value: ''
				};

				streamContent.value.on('data', chunk => result.value += chunk);
				streamContent.value.on('error', err => reject(err));
				streamContent.value.on('end', _ => resolve(result));

				return result;
			});
		});
E
Erich Gamma 已提交
274 275
	}

B
Benjamin Pasero 已提交
276
	resolveStreamContent(resource: uri, options?: IResolveContentOptions): TPromise<IStreamContent> {
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292

		// Guard early against attempts to resolve an invalid file path
		if (resource.scheme !== Schemas.file || !resource.fsPath) {
			return TPromise.wrapError<IStreamContent>(new FileOperationError(
				nls.localize('fileInvalidPath', "Invalid file resource ({0})", resource.toString(true)),
				FileOperationResult.FILE_INVALID_PATH,
				options
			));
		}

		const result: IStreamContent = {
			resource: void 0,
			name: void 0,
			mtime: void 0,
			etag: void 0,
			encoding: void 0,
I
isidor 已提交
293
			isReadonly: false,
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 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
			value: void 0
		};

		const contentResolverTokenSource = new CancellationTokenSource();

		const onStatError = (error: Error) => {

			// error: stop reading the file the stat and content resolve call
			// usually race, mostly likely the stat call will win and cancel
			// the content call
			contentResolverTokenSource.cancel();

			// forward error
			return TPromise.wrapError(error);
		};

		const statsPromise = this.resolveFile(resource).then(stat => {
			result.resource = stat.resource;
			result.name = stat.name;
			result.mtime = stat.mtime;
			result.etag = stat.etag;

			// Return early if resource is a directory
			if (stat.isDirectory) {
				return onStatError(new FileOperationError(
					nls.localize('fileIsDirectoryError', "File is directory"),
					FileOperationResult.FILE_IS_DIRECTORY,
					options
				));
			}

			// Return early if file not modified since
			if (options && options.etag && options.etag === stat.etag) {
				return onStatError(new FileOperationError(
					nls.localize('fileNotModifiedError', "File not modified since"),
					FileOperationResult.FILE_NOT_MODIFIED_SINCE,
					options
				));
			}

			// Return early if file is too large to load
			if (typeof stat.size === 'number') {
				if (stat.size > Math.max(this.environmentService.args['max-memory'] * 1024 * 1024 || 0, MAX_HEAP_SIZE)) {
					return onStatError(new FileOperationError(
						nls.localize('fileTooLargeForHeapError', "To open a file of this size, you need to restart VS Code and allow it to use more memory"),
						FileOperationResult.FILE_EXCEED_MEMORY_LIMIT
					));
				}

				if (stat.size > MAX_FILE_SIZE) {
					return onStatError(new FileOperationError(
						nls.localize('fileTooLargeError', "File too large to open"),
						FileOperationResult.FILE_TOO_LARGE
					));
				}
			}

			return void 0;
		}, err => {

			// Wrap file not found errors
			if (err.code === 'ENOENT') {
				return onStatError(new FileOperationError(
					nls.localize('fileNotFoundError', "File not found ({0})", resource.toString(true)),
					FileOperationResult.FILE_NOT_FOUND,
					options
				));
			}

			return onStatError(err);
		});

B
Benjamin Pasero 已提交
366
		let completePromise: TPromise<void>;
367 368 369 370 371 372 373 374 375 376 377 378

		// await the stat iff we already have an etag so that we compare the
		// etag from the stat before we actually read the file again.
		if (options && options.etag) {
			completePromise = statsPromise.then(() => {
				return this.fillInContents(result, resource, options, contentResolverTokenSource.token); // Waterfall -> only now resolve the contents
			});
		}

		// a fresh load without a previous etag which means we can resolve the file stat
		// and the content at the same time, avoiding the waterfall.
		else {
B
Benjamin Pasero 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
			completePromise = TPromise.join([statsPromise, this.fillInContents(result, resource, options, contentResolverTokenSource.token)]).then(() => void 0, error => {
				// Joining promises via TPromise will execute both and return errors
				// as array-like object for each. Since each can return a FileOperationError
				// we want to prefer that one if possible. Otherwise we just return with the
				// first error we get.
				const firstError = error[0];
				const secondError = error[1];

				if (FileOperationError.isFileOperationError(firstError)) {
					return TPromise.wrapError(firstError);
				}

				if (FileOperationError.isFileOperationError(secondError)) {
					return TPromise.wrapError(secondError);
				}

				return TPromise.wrapError(firstError || secondError);
			});
397 398
		}

B
Benjamin Pasero 已提交
399
		return completePromise.then(() => {
400 401 402
			contentResolverTokenSource.dispose();

			return result;
B
Benjamin Pasero 已提交
403 404 405 406
		}, error => {
			contentResolverTokenSource.dispose();

			return TPromise.wrapError(error);
407
		});
A
Alex Dima 已提交
408 409
	}

B
Benjamin Pasero 已提交
410
	private fillInContents(content: IStreamContent, resource: uri, options: IResolveContentOptions, token: CancellationToken): TPromise<void> {
411 412 413 414
		return this.resolveFileData(resource, options, token).then(data => {
			content.encoding = data.encoding;
			content.value = data.stream;
		});
E
Erich Gamma 已提交
415 416
	}

B
Benjamin Pasero 已提交
417
	private resolveFileData(resource: uri, options: IResolveContentOptions, token: CancellationToken): TPromise<IContentData> {
418 419 420 421 422 423 424 425

		const chunkBuffer = BufferPool._64K.acquire();

		const result: IContentData = {
			encoding: void 0,
			stream: void 0
		};

B
Benjamin Pasero 已提交
426
		return new TPromise<IContentData>((resolve, reject) => {
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
			fs.open(this.toAbsolutePath(resource), 'r', (err, fd) => {
				if (err) {
					if (err.code === 'ENOENT') {
						// Wrap file not found errors
						err = new FileOperationError(
							nls.localize('fileNotFoundError', "File not found ({0})", resource.toString(true)),
							FileOperationResult.FILE_NOT_FOUND,
							options
						);
					}

					return reject(err);
				}

				let decoder: NodeJS.ReadWriteStream;
				let totalBytesRead = 0;

				const finish = (err?: any) => {

					if (err) {
						if (err.code === 'EISDIR') {
							// Wrap EISDIR errors (fs.open on a directory works, but you cannot read from it)
							err = new FileOperationError(
								nls.localize('fileIsDirectoryError', "File is directory"),
								FileOperationResult.FILE_IS_DIRECTORY,
								options
							);
						}
						if (decoder) {
							// If the decoder already started, we have to emit the error through it as
							// event because the promise is already resolved!
							decoder.emit('error', err);
						} else {
							reject(err);
						}
					}
					if (decoder) {
						decoder.end();
					}

					// return the shared buffer
					BufferPool._64K.release(chunkBuffer);

					if (fd) {
						fs.close(fd, err => {
							if (err) {
								this.handleError(`resolveFileData#close(): ${err.toString()}`);
							}
						});
					}
				};

				const handleChunk = (bytesRead: number) => {
					if (token.isCancellationRequested) {
						// cancellation -> finish
						finish(new Error('cancelled'));
					} else if (bytesRead === 0) {
						// no more data -> finish
						finish();
					} else if (bytesRead < chunkBuffer.length) {
						// write the sub-part of data we received -> repeat
						decoder.write(chunkBuffer.slice(0, bytesRead), readChunk);
					} else {
						// write all data we received -> repeat
						decoder.write(chunkBuffer, readChunk);
					}
				};

				let currentPosition: number = (options && options.position) || null;

				const readChunk = () => {
					fs.read(fd, chunkBuffer, 0, chunkBuffer.length, currentPosition, (err, bytesRead) => {
						totalBytesRead += bytesRead;

						if (typeof currentPosition === 'number') {
							// if we received a position argument as option we need to ensure that
							// we advance the position by the number of bytesread
							currentPosition += bytesRead;
						}

						if (totalBytesRead > Math.max(this.environmentService.args['max-memory'] * 1024 * 1024 || 0, MAX_HEAP_SIZE)) {
							finish(new FileOperationError(
								nls.localize('fileTooLargeForHeapError', "To open a file of this size, you need to restart VS Code and allow it to use more memory"),
								FileOperationResult.FILE_EXCEED_MEMORY_LIMIT
							));
						}

						if (totalBytesRead > MAX_FILE_SIZE) {
							// stop when reading too much
							finish(new FileOperationError(
								nls.localize('fileTooLargeError', "File too large to open"),
								FileOperationResult.FILE_TOO_LARGE,
								options
							));
						} else if (err) {
							// some error happened
							finish(err);

						} else if (decoder) {
							// pass on to decoder
							handleChunk(bytesRead);

						} else {
							// when receiving the first chunk of data we need to create the
							// decoding stream which is then used to drive the string stream.
532
							const autoGuessEncoding = (options && options.autoGuessEncoding) || this.textResourceConfigurationService.getValue(resource, 'files.autoGuessEncoding');
533 534
							TPromise.as(encoding.detectEncodingFromBuffer(
								{ buffer: chunkBuffer, bytesRead },
535
								autoGuessEncoding
536 537 538 539 540 541 542 543 544 545 546
							)).then(detected => {

								if (options && options.acceptTextOnly && detected.seemsBinary) {
									// Return error early if client only accepts text and this is not text
									finish(new FileOperationError(
										nls.localize('fileBinaryError', "File seems to be binary and cannot be opened as text"),
										FileOperationResult.FILE_IS_BINARY,
										options
									));

								} else {
547
									result.encoding = this._encoding.getReadEncoding(resource, options, detected);
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
									result.stream = decoder = encoding.decodeStream(result.encoding);
									resolve(result);
									handleChunk(bytesRead);
								}

							}).then(void 0, err => {
								// failed to get encoding
								finish(err);
							});
						}
					});
				};

				// start reading
				readChunk();
			});
		});
E
Erich Gamma 已提交
565 566
	}

B
Benjamin Pasero 已提交
567
	updateContent(resource: uri, value: string | ITextSnapshot, options: IUpdateContentOptions = Object.create(null)): TPromise<IFileStat> {
568 569 570 571 572
		if (options.writeElevated) {
			return this.doUpdateContentElevated(resource, value, options);
		}

		return this.doUpdateContent(resource, value, options);
E
Erich Gamma 已提交
573 574
	}

575 576 577 578 579 580 581 582 583 584 585 586 587 588
	private doUpdateContent(resource: uri, value: string | ITextSnapshot, options: IUpdateContentOptions = Object.create(null)): TPromise<IFileStat> {
		const absolutePath = this.toAbsolutePath(resource);

		// 1.) check file for writing
		return this.checkFileBeforeWriting(absolutePath, options).then(exists => {
			let createParentsPromise: TPromise<boolean>;
			if (exists) {
				createParentsPromise = TPromise.as(null);
			} else {
				createParentsPromise = pfs.mkdirp(paths.dirname(absolutePath));
			}

			// 2.) create parents as needed
			return createParentsPromise.then(() => {
589
				const encodingToWrite = this._encoding.getWriteEncoding(resource, options.encoding);
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
				let addBomPromise: TPromise<boolean> = TPromise.as(false);

				// UTF_16 BE and LE as well as UTF_8 with BOM always have a BOM
				if (encodingToWrite === encoding.UTF16be || encodingToWrite === encoding.UTF16le || encodingToWrite === encoding.UTF8_with_bom) {
					addBomPromise = TPromise.as(true);
				}

				// Existing UTF-8 file: check for options regarding BOM
				else if (exists && encodingToWrite === encoding.UTF8) {
					if (options.overwriteEncoding) {
						addBomPromise = TPromise.as(false); // if we are to overwrite the encoding, we do not preserve it if found
					} else {
						addBomPromise = encoding.detectEncodingByBOM(absolutePath).then(enc => enc === encoding.UTF8); // otherwise preserve it if found
					}
				}

				// 3.) check to add UTF BOM
				return addBomPromise.then(addBom => {

					// 4.) set contents and resolve
610 611 612
					if (!exists || !isWindows) {
						return this.doSetContentsAndResolve(resource, absolutePath, value, addBom, encodingToWrite);
					}
613

614 615 616 617 618
					// On Windows and if the file exists, we use a different strategy of saving the file
					// by first truncating the file and then writing with r+ mode. This helps to save hidden files on Windows
					// (see https://github.com/Microsoft/vscode/issues/931) and prevent removing alternate data streams
					// (see https://github.com/Microsoft/vscode/issues/6363)
					else {
619

620
						// 4.) truncate
621 622
						return pfs.truncate(absolutePath, 0).then(() => {

623
							// 5.) set contents (with r+ mode) and resolve
624 625
							return this.doSetContentsAndResolve(resource, absolutePath, value, addBom, encodingToWrite, { flag: 'r+' });
						});
626
					}
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
				});
			});
		}).then(null, error => {
			if (error.code === 'EACCES' || error.code === 'EPERM') {
				return TPromise.wrapError(new FileOperationError(
					nls.localize('filePermission', "Permission denied writing to file ({0})", resource.toString(true)),
					FileOperationResult.FILE_PERMISSION_DENIED,
					options
				));
			}

			return TPromise.wrapError(error);
		});
	}

	private doSetContentsAndResolve(resource: uri, absolutePath: string, value: string | ITextSnapshot, addBOM: boolean, encodingToWrite: string, options?: { mode?: number; flag?: string; }): TPromise<IFileStat> {
		let writeFilePromise: TPromise<void>;

		// Configure encoding related options as needed
		const writeFileOptions: extfs.IWriteFileOptions = options ? options : Object.create(null);
		if (addBOM || encodingToWrite !== encoding.UTF8) {
			writeFileOptions.encoding = {
				charset: encodingToWrite,
				addBOM
			};
		}

		if (typeof value === 'string') {
			writeFilePromise = pfs.writeFile(absolutePath, value, writeFileOptions);
		} else {
657
			writeFilePromise = pfs.writeFile(absolutePath, createReadableOfSnapshot(value), writeFileOptions);
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
		}

		// set contents
		return writeFilePromise.then(() => {

			// resolve
			return this.resolve(resource);
		});
	}

	private doUpdateContentElevated(resource: uri, value: string | ITextSnapshot, options: IUpdateContentOptions = Object.create(null)): TPromise<IFileStat> {
		const absolutePath = this.toAbsolutePath(resource);

		// 1.) check file for writing
		return this.checkFileBeforeWriting(absolutePath, options, options.overwriteReadonly /* ignore readonly if we overwrite readonly, this is handled via sudo later */).then(exists => {
			const writeOptions: IUpdateContentOptions = objects.assign(Object.create(null), options);
			writeOptions.writeElevated = false;
675
			writeOptions.encoding = this._encoding.getWriteEncoding(resource, options.encoding);
676 677

			// 2.) write to a temporary file to be able to copy over later
B
Benjamin Pasero 已提交
678
			const tmpPath = paths.join(os.tmpdir(), `code-elevated-${Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 6)}`);
679 680 681
			return this.updateContent(uri.file(tmpPath), value, writeOptions).then(() => {

				// 3.) invoke our CLI as super user
B
Benjamin Pasero 已提交
682
				return toWinJsPromise(import('sudo-prompt')).then(sudoPrompt => {
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
					return new TPromise<void>((c, e) => {
						const promptOptions = {
							name: this.environmentService.appNameLong.replace('-', ''),
							icns: (isMacintosh && this.environmentService.isBuilt) ? paths.join(paths.dirname(this.environmentService.appRoot), `${product.nameShort}.icns`) : void 0
						};

						const sudoCommand: string[] = [`"${this.environmentService.cliPath}"`];
						if (options.overwriteReadonly) {
							sudoCommand.push('--file-chmod');
						}
						sudoCommand.push('--file-write', `"${tmpPath}"`, `"${absolutePath}"`);

						sudoPrompt.exec(sudoCommand.join(' '), promptOptions, (error: string, stdout: string, stderr: string) => {
							if (error || stderr) {
								e(error || stderr);
							} else {
								c(void 0);
							}
						});
					});
				}).then(() => {

					// 3.) delete temp file
B
Benjamin Pasero 已提交
706
					return pfs.del(tmpPath, os.tmpdir()).then(() => {
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729

						// 4.) resolve again
						return this.resolve(resource);
					});
				});
			});
		}).then(null, error => {
			if (this.environmentService.verbose) {
				this.handleError(`Unable to write to file '${resource.toString(true)}' as elevated user (${error})`);
			}

			if (!FileOperationError.isFileOperationError(error)) {
				error = new FileOperationError(
					nls.localize('filePermission', "Permission denied writing to file ({0})", resource.toString(true)),
					FileOperationResult.FILE_PERMISSION_DENIED,
					options
				);
			}

			return TPromise.wrapError(error);
		});
	}

B
Benjamin Pasero 已提交
730
	createFile(resource: uri, content: string = '', options: ICreateFileOptions = Object.create(null)): TPromise<IFileStat> {
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
		const absolutePath = this.toAbsolutePath(resource);

		let checkFilePromise: TPromise<boolean>;
		if (options.overwrite) {
			checkFilePromise = TPromise.as(false);
		} else {
			checkFilePromise = pfs.exists(absolutePath);
		}

		// Check file exists
		return checkFilePromise.then(exists => {
			if (exists && !options.overwrite) {
				return TPromise.wrapError<IFileStat>(new FileOperationError(
					nls.localize('fileExists', "File to create already exists ({0})", resource.toString(true)),
					FileOperationResult.FILE_MODIFIED_SINCE,
					options
				));
			}

			// Create file
			return this.updateContent(resource, content).then(result => {

				// Events
				this._onAfterOperation.fire(new FileOperationEvent(resource, FileOperation.CREATE, result));

				return result;
			});
		});
E
Erich Gamma 已提交
759 760
	}

B
Benjamin Pasero 已提交
761
	createFolder(resource: uri): TPromise<IFileStat> {
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837

		// 1.) Create folder
		const absolutePath = this.toAbsolutePath(resource);
		return pfs.mkdirp(absolutePath).then(() => {

			// 2.) Resolve
			return this.resolve(resource).then(result => {

				// Events
				this._onAfterOperation.fire(new FileOperationEvent(resource, FileOperation.CREATE, result));

				return result;
			});
		});
	}

	private checkFileBeforeWriting(absolutePath: string, options: IUpdateContentOptions = Object.create(null), ignoreReadonly?: boolean): TPromise<boolean /* exists */> {
		return pfs.exists(absolutePath).then(exists => {
			if (exists) {
				return pfs.stat(absolutePath).then(stat => {
					if (stat.isDirectory()) {
						return TPromise.wrapError<boolean>(new Error('Expected file is actually a directory'));
					}

					// Dirty write prevention: if the file on disk has been changed and does not match our expected
					// mtime and etag, we bail out to prevent dirty writing.
					//
					// First, we check for a mtime that is in the future before we do more checks. The assumption is
					// that only the mtime is an indicator for a file that has changd on disk.
					//
					// Second, if the mtime has advanced, we compare the size of the file on disk with our previous
					// one using the etag() function. Relying only on the mtime check has prooven to produce false
					// positives due to file system weirdness (especially around remote file systems). As such, the
					// check for size is a weaker check because it can return a false negative if the file has changed
					// but to the same length. This is a compromise we take to avoid having to produce checksums of
					// the file content for comparison which would be much slower to compute.
					if (typeof options.mtime === 'number' && typeof options.etag === 'string' && options.mtime < stat.mtime.getTime() && options.etag !== etag(stat.size, options.mtime)) {
						return TPromise.wrapError<boolean>(new FileOperationError(nls.localize('fileModifiedError', "File Modified Since"), FileOperationResult.FILE_MODIFIED_SINCE, options));
					}

					// Throw if file is readonly and we are not instructed to overwrite
					if (!ignoreReadonly && !(stat.mode & 128) /* readonly */) {
						if (!options.overwriteReadonly) {
							return this.readOnlyError<boolean>(options);
						}

						// Try to change mode to writeable
						let mode = stat.mode;
						mode = mode | 128;
						return pfs.chmod(absolutePath, mode).then(() => {

							// Make sure to check the mode again, it could have failed
							return pfs.stat(absolutePath).then(stat => {
								if (!(stat.mode & 128) /* readonly */) {
									return this.readOnlyError<boolean>(options);
								}

								return exists;
							});
						});
					}

					return TPromise.as<boolean>(exists);
				});
			}

			return TPromise.as<boolean>(exists);
		});
	}

	private readOnlyError<T>(options: IUpdateContentOptions): TPromise<T> {
		return TPromise.wrapError<T>(new FileOperationError(
			nls.localize('fileReadOnlyError', "File is Read Only"),
			FileOperationResult.FILE_READ_ONLY,
			options
		));
E
Erich Gamma 已提交
838 839
	}

B
Benjamin Pasero 已提交
840
	moveFile(source: uri, target: uri, overwrite?: boolean): TPromise<IFileStat> {
841 842 843
		return this.moveOrCopyFile(source, target, false, overwrite);
	}

B
Benjamin Pasero 已提交
844
	copyFile(source: uri, target: uri, overwrite?: boolean): TPromise<IFileStat> {
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
		return this.moveOrCopyFile(source, target, true, overwrite);
	}

	private moveOrCopyFile(source: uri, target: uri, keepCopy: boolean, overwrite: boolean): TPromise<IFileStat> {
		const sourcePath = this.toAbsolutePath(source);
		const targetPath = this.toAbsolutePath(target);

		// 1.) move / copy
		return this.doMoveOrCopyFile(sourcePath, targetPath, keepCopy, overwrite).then(() => {

			// 2.) resolve
			return this.resolve(target).then(result => {

				// Events
				this._onAfterOperation.fire(new FileOperationEvent(source, keepCopy ? FileOperation.COPY : FileOperation.MOVE, result));

				return result;
			});
		});
	}

	private doMoveOrCopyFile(sourcePath: string, targetPath: string, keepCopy: boolean, overwrite: boolean): TPromise<boolean /* exists */> {

		// 1.) validate operation
		if (isParent(targetPath, sourcePath, !isLinux)) {
			return TPromise.wrapError<boolean>(new Error('Unable to move/copy when source path is parent of target path'));
		}

		// 2.) check if target exists
		return pfs.exists(targetPath).then(exists => {
			const isCaseRename = sourcePath.toLowerCase() === targetPath.toLowerCase();
			const isSameFile = sourcePath === targetPath;

			// Return early with conflict if target exists and we are not told to overwrite
			if (exists && !isCaseRename && !overwrite) {
				return TPromise.wrapError<boolean>(new FileOperationError(nls.localize('fileMoveConflict', "Unable to move/copy. File already exists at destination."), FileOperationResult.FILE_MOVE_CONFLICT));
			}

			// 3.) make sure target is deleted before we move/copy unless this is a case rename of the same file
			let deleteTargetPromise = TPromise.wrap<void>(void 0);
			if (exists && !isCaseRename) {
				if (isEqualOrParent(sourcePath, targetPath, !isLinux /* ignorecase */)) {
					return TPromise.wrapError<boolean>(new Error(nls.localize('unableToMoveCopyError', "Unable to move/copy. File would replace folder it is contained in."))); // catch this corner case!
				}

890
				deleteTargetPromise = this.del(uri.file(targetPath), { recursive: true });
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
			}

			return deleteTargetPromise.then(() => {

				// 4.) make sure parents exists
				return pfs.mkdirp(paths.dirname(targetPath)).then(() => {

					// 4.) copy/move
					if (isSameFile) {
						return TPromise.wrap(null);
					} else if (keepCopy) {
						return nfcall(extfs.copy, sourcePath, targetPath);
					} else {
						return nfcall(extfs.mv, sourcePath, targetPath);
					}
				}).then(() => exists);
			});
		});
	}

B
Benjamin Pasero 已提交
911
	del(resource: uri, options?: { useTrash?: boolean, recursive?: boolean }): TPromise<void> {
912
		if (options && options.useTrash) {
B
Benjamin Pasero 已提交
913
			return this.doMoveItemToTrash(resource);
E
Erich Gamma 已提交
914 915
		}

916
		return this.doDelete(resource, options && options.recursive);
E
Erich Gamma 已提交
917 918
	}

B
Benjamin Pasero 已提交
919
	private doMoveItemToTrash(resource: uri): TPromise<void> {
B
Benjamin Pasero 已提交
920
		const absolutePath = resource.fsPath;
E
Erich Gamma 已提交
921

B
Benjamin Pasero 已提交
922
		const shell = (require('electron') as Electron.RendererInterface).shell; // workaround for being able to run tests out of VSCode debugger
923 924 925 926
		const result = shell.moveItemToTrash(absolutePath);
		if (!result) {
			return TPromise.wrapError(new Error(isWindows ? nls.localize('binFailed', "Failed to move '{0}' to the recycle bin", paths.basename(absolutePath)) : nls.localize('trashFailed', "Failed to move '{0}' to the trash", paths.basename(absolutePath))));
		}
927

928
		this._onAfterOperation.fire(new FileOperationEvent(resource, FileOperation.DELETE));
929

930
		return TPromise.as(void 0);
E
Erich Gamma 已提交
931 932
	}

933
	private doDelete(resource: uri, recursive: boolean): TPromise<void> {
934 935
		const absolutePath = this.toAbsolutePath(resource);

936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956
		let assertNonRecursiveDelete: TPromise<void>;
		if (!recursive) {
			assertNonRecursiveDelete = pfs.stat(absolutePath).then(stat => {
				if (!stat.isDirectory()) {
					return TPromise.as(void 0);
				}

				return pfs.readdir(absolutePath).then(children => {
					if (children.length === 0) {
						return TPromise.as(void 0);
					}

					return TPromise.wrapError(new Error(nls.localize('deleteFailed', "Failed to delete non-empty folder '{0}'.", paths.basename(absolutePath))));
				});
			}, error => TPromise.as(void 0) /* ignore errors */);
		} else {
			assertNonRecursiveDelete = TPromise.as(void 0);
		}

		return assertNonRecursiveDelete.then(() => {
			return pfs.del(absolutePath, os.tmpdir()).then(() => {
957

958 959 960
				// Events
				this._onAfterOperation.fire(new FileOperationEvent(resource, FileOperation.DELETE));
			});
E
Erich Gamma 已提交
961 962 963
		});
	}

964 965 966 967 968 969 970 971
	// Helpers

	private toAbsolutePath(arg1: uri | IFileStat): string {
		let resource: uri;
		if (arg1 instanceof uri) {
			resource = <uri>arg1;
		} else {
			resource = (<IFileStat>arg1).resource;
E
Erich Gamma 已提交
972 973
		}

974 975 976 977 978 979
		assert.ok(resource && resource.scheme === Schemas.file, `Invalid resource: ${resource}`);

		return paths.normalize(resource.fsPath);
	}

	private resolve(resource: uri, options: IResolveFileOptions = Object.create(null)): TPromise<IFileStat> {
980
		return this.toStatResolver(resource).then(model => model.resolve(options));
981 982 983 984 985 986 987 988 989 990
	}

	private toStatResolver(resource: uri): TPromise<StatResolver> {
		const absolutePath = this.toAbsolutePath(resource);

		return pfs.statLink(absolutePath).then(({ isSymbolicLink, stat }) => {
			return new StatResolver(resource, isSymbolicLink, stat.isDirectory(), stat.mtime.getTime(), stat.size, this.environmentService.verbose ? err => this.handleError(err) : void 0);
		});
	}

B
Benjamin Pasero 已提交
991
	watchFileChanges(resource: uri): void {
992 993
		assert.ok(resource && resource.scheme === Schemas.file, `Invalid resource for watching: ${resource}`);

B
Benjamin Pasero 已提交
994 995 996 997
		// Check for existing watcher first
		const entry = this.activeFileChangesWatchers.get(resource);
		if (entry) {
			entry.count += 1;
998

B
Benjamin Pasero 已提交
999 1000
			return;
		}
1001

B
Benjamin Pasero 已提交
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
		// Create or get watcher for provided path
		const fsPath = resource.fsPath;
		const fsName = paths.basename(resource.fsPath);

		const watcher = extfs.watch(fsPath, (eventType: string, filename: string) => {
			const renamedOrDeleted = ((filename && filename !== fsName) || eventType === 'rename');

			// The file was either deleted or renamed. Many tools apply changes to files in an
			// atomic way ("Atomic Save") by first renaming the file to a temporary name and then
			// renaming it back to the original name. Our watcher will detect this as a rename
			// and then stops to work on Mac and Linux because the watcher is applied to the
			// inode and not the name. The fix is to detect this case and trying to watch the file
			// again after a certain delay.
			// In addition, we send out a delete event if after a timeout we detect that the file
			// does indeed not exist anymore.
			if (renamedOrDeleted) {

				// Very important to dispose the watcher which now points to a stale inode
B
Benjamin Pasero 已提交
1020 1021
				watcher.close();
				this.activeFileChangesWatchers.delete(resource);
B
Benjamin Pasero 已提交
1022 1023 1024 1025 1026 1027 1028 1029 1030

				// Wait a bit and try to install watcher again, assuming that the file was renamed quickly ("Atomic Save")
				setTimeout(() => {
					this.existsFile(resource).done(exists => {

						// File still exists, so reapply the watcher
						if (exists) {
							this.watchFileChanges(resource);
						}
1031

B
Benjamin Pasero 已提交
1032 1033 1034 1035 1036 1037 1038 1039 1040
						// File seems to be really gone, so emit a deleted event
						else {
							this.onRawFileChange({
								type: FileChangeType.DELETED,
								path: fsPath
							});
						}
					});
				}, FileService.FS_REWATCH_DELAY);
1041
			}
B
Benjamin Pasero 已提交
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055

			// Handle raw file change
			this.onRawFileChange({
				type: FileChangeType.UPDATED,
				path: fsPath
			});
		}, (error: string) => this.handleError(error));

		// Remember in map
		if (watcher) {
			this.activeFileChangesWatchers.set(resource, {
				count: 1,
				unwatch: () => watcher.close()
			});
1056 1057 1058 1059 1060 1061 1062 1063 1064
		}
	}

	private onRawFileChange(event: IRawFileChange): void {

		// add to bucket of undelivered events
		this.undeliveredRawFileChangesEvents.push(event);

		if (this.environmentService.verbose) {
1065
			console.log('%c[File Watcher (node.js)]%c', 'color: blue', 'color: black', event.type === FileChangeType.ADDED ? '[ADDED]' : event.type === FileChangeType.DELETED ? '[DELETED]' : '[CHANGED]', event.path);
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078
		}

		// handle emit through delayer to accommodate for bulk changes
		this.fileChangesWatchDelayer.trigger(() => {
			const buffer = this.undeliveredRawFileChangesEvents;
			this.undeliveredRawFileChangesEvents = [];

			// Normalize
			const normalizedEvents = normalize(buffer);

			// Logging
			if (this.environmentService.verbose) {
				normalizedEvents.forEach(r => {
1079
					console.log('%c[File Watcher (node.js)]%c >> normalized', 'color: blue', 'color: black', r.type === FileChangeType.ADDED ? '[ADDED]' : r.type === FileChangeType.DELETED ? '[DELETED]' : '[CHANGED]', r.path);
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
				});
			}

			// Emit
			this._onFileChanges.fire(toFileChangesEvent(normalizedEvents));

			return TPromise.as(null);
		});
	}

B
Benjamin Pasero 已提交
1090
	unwatchFileChanges(resource: uri): void {
1091
		const watcher = this.activeFileChangesWatchers.get(resource);
B
Benjamin Pasero 已提交
1092 1093
		if (watcher && --watcher.count === 0) {
			watcher.unwatch();
1094 1095
			this.activeFileChangesWatchers.delete(resource);
		}
1096 1097
	}

B
Benjamin Pasero 已提交
1098 1099
	dispose(): void {
		super.dispose();
1100 1101 1102 1103 1104 1105

		if (this.activeWorkspaceFileChangeWatcher) {
			this.activeWorkspaceFileChangeWatcher.dispose();
			this.activeWorkspaceFileChangeWatcher = null;
		}

B
Benjamin Pasero 已提交
1106
		this.activeFileChangesWatchers.forEach(watcher => watcher.unwatch());
1107 1108 1109 1110
		this.activeFileChangesWatchers.clear();
	}
}

B
Benjamin Pasero 已提交
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
function etag(stat: fs.Stats): string;
function etag(size: number, mtime: number): string;
function etag(arg1: any, arg2?: any): string {
	let size: number;
	let mtime: number;
	if (typeof arg2 === 'number') {
		size = arg1;
		mtime = arg2;
	} else {
		size = (<fs.Stats>arg1).size;
		mtime = (<fs.Stats>arg1).mtime.getTime();
	}

	return `"${crypto.createHash('sha1').update(String(size) + String(mtime)).digest('hex')}"`;
}

1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
export class StatResolver {
	private name: string;
	private etag: string;

	constructor(
		private resource: uri,
		private isSymbolicLink: boolean,
		private isDirectory: boolean,
		private mtime: number,
		private size: number,
		private errorLogger?: (error: Error | string) => void
	) {
		assert.ok(resource && resource.scheme === Schemas.file, `Invalid resource: ${resource}`);

		this.name = getBaseLabel(resource);
		this.etag = etag(size, mtime);
	}

B
Benjamin Pasero 已提交
1145
	resolve(options: IResolveFileOptions): TPromise<IFileStat> {
1146 1147 1148 1149 1150 1151

		// General Data
		const fileStat: IFileStat = {
			resource: this.resource,
			isDirectory: this.isDirectory,
			isSymbolicLink: this.isSymbolicLink,
I
isidor 已提交
1152
			isReadonly: false,
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162
			name: this.name,
			etag: this.etag,
			size: this.size,
			mtime: this.mtime
		};

		// File Specific Data
		if (!this.isDirectory) {
			return TPromise.as(fileStat);
		}
E
Erich Gamma 已提交
1163

1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
		// Directory Specific Data
		else {

			// Convert the paths from options.resolveTo to absolute paths
			let absoluteTargetPaths: string[] = null;
			if (options && options.resolveTo) {
				absoluteTargetPaths = [];
				options.resolveTo.forEach(resource => {
					absoluteTargetPaths.push(resource.fsPath);
				});
			}

			return new TPromise<IFileStat>((c, e) => {

				// Load children
				this.resolveChildren(this.resource.fsPath, absoluteTargetPaths, options && options.resolveSingleChildDescendants, children => {
					children = arrays.coalesce(children); // we don't want those null children (could be permission denied when reading a child)
					fileStat.children = children || [];

					c(fileStat);
				});
			});
		}
	}

	private resolveChildren(absolutePath: string, absoluteTargetPaths: string[], resolveSingleChildDescendants: boolean, callback: (children: IFileStat[]) => void): void {
		extfs.readdir(absolutePath, (error: Error, files: string[]) => {
			if (error) {
				if (this.errorLogger) {
					this.errorLogger(error);
				}

				return callback(null); // return - we might not have permissions to read the folder
			}

			// for each file in the folder
			flow.parallel(files, (file: string, clb: (error: Error, children: IFileStat) => void) => {
				const fileResource = uri.file(paths.resolve(absolutePath, file));
				let fileStat: fs.Stats;
				let isSymbolicLink = false;
				const $this = this;

				flow.sequence(
					function onError(error: Error): void {
						if ($this.errorLogger) {
							$this.errorLogger(error);
						}

						clb(null, null); // return - we might not have permissions to read the folder or stat the file
					},

					function stat(this: any): void {
						extfs.statLink(fileResource.fsPath, this);
					},

					function countChildren(this: any, statAndLink: extfs.IStatAndLink): void {
						fileStat = statAndLink.stat;
						isSymbolicLink = statAndLink.isSymbolicLink;

						if (fileStat.isDirectory()) {
							extfs.readdir(fileResource.fsPath, (error, result) => {
								this(null, result ? result.length : 0);
							});
						} else {
							this(null, 0);
						}
					},

					function resolve(childCount: number): void {
						const childStat: IFileStat = {
							resource: fileResource,
							isDirectory: fileStat.isDirectory(),
							isSymbolicLink,
I
isidor 已提交
1237
							isReadonly: false,
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
							name: file,
							mtime: fileStat.mtime.getTime(),
							etag: etag(fileStat),
							size: fileStat.size
						};

						// Return early for files
						if (!fileStat.isDirectory()) {
							return clb(null, childStat);
						}

						// Handle Folder
						let resolveFolderChildren = false;
						if (files.length === 1 && resolveSingleChildDescendants) {
							resolveFolderChildren = true;
						} else if (childCount > 0 && absoluteTargetPaths && absoluteTargetPaths.some(targetPath => isEqualOrParent(targetPath, fileResource.fsPath, !isLinux /* ignorecase */))) {
							resolveFolderChildren = true;
						}

						// Continue resolving children based on condition
						if (resolveFolderChildren) {
							$this.resolveChildren(fileResource.fsPath, absoluteTargetPaths, resolveSingleChildDescendants, children => {
								children = arrays.coalesce(children);  // we don't want those null children
								childStat.children = children || [];

								clb(null, childStat);
							});
						}

						// Otherwise return result
						else {
							clb(null, childStat);
						}
					});
			}, (errors, result) => {
				callback(result);
			});
		});
E
Erich Gamma 已提交
1276
	}
1277
}