fileService.ts 30.7 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13
/*---------------------------------------------------------------------------------------------
 *  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 paths = require('path');
import fs = require('fs');
import os = require('os');
import crypto = require('crypto');
import assert = require('assert');

J
Johannes Rieken 已提交
14
import { IContent, IFileService, IResolveFileOptions, IResolveContentOptions, IFileStat, IStreamContent, IFileOperationResult, FileOperationResult, IBaseStat, IUpdateContentOptions, FileChangeType, EventType, IImportResult, MAX_FILE_SIZE } from 'vs/platform/files/common/files';
E
Erich Gamma 已提交
15 16 17 18
import strings = require('vs/base/common/strings');
import arrays = require('vs/base/common/arrays');
import baseMime = require('vs/base/common/mime');
import basePaths = require('vs/base/common/paths');
J
Johannes Rieken 已提交
19
import { TPromise } from 'vs/base/common/winjs.base';
E
Erich Gamma 已提交
20 21 22
import types = require('vs/base/common/types');
import objects = require('vs/base/common/objects');
import extfs = require('vs/base/node/extfs');
J
Johannes Rieken 已提交
23
import { nfcall, Limiter, ThrottledDelayer } from 'vs/base/common/async';
E
Erich Gamma 已提交
24 25 26 27 28 29 30
import uri from 'vs/base/common/uri';
import nls = require('vs/nls');

import pfs = require('vs/base/node/pfs');
import encoding = require('vs/base/node/encoding');
import mime = require('vs/base/node/mime');
import flow = require('vs/base/node/flow');
31
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
J
Johannes Rieken 已提交
32 33 34 35
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';
import { IEventService } from 'vs/platform/event/common/event';
36 37 38 39 40
import { IBackupService } from 'vs/platform/backup/common/backup';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IFilesConfiguration } from 'vs/platform/files/common/files';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
E
Erich Gamma 已提交
41 42 43 44 45 46 47 48 49 50

export interface IEncodingOverride {
	resource: uri;
	encoding: string;
}

export interface IFileServiceOptions {
	tmpDir?: string;
	errorLogger?: (msg: string) => void;
	encoding?: string;
51
	bom?: string;
E
Erich Gamma 已提交
52 53 54 55 56 57
	encodingOverride?: IEncodingOverride[];
	watcherIgnoredPatterns?: string[];
	disableWatcher?: boolean;
	verboseLogging?: boolean;
}

58
function etag(stat: fs.Stats): string;
E
Erich Gamma 已提交
59 60 61 62 63 64 65 66
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 {
67 68
		size = (<fs.Stats>arg1).size;
		mtime = (<fs.Stats>arg1).mtime.getTime();
E
Erich Gamma 已提交
69 70 71 72 73
	}

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

B
Benjamin Pasero 已提交
74
export class FileService implements IFileService {
E
Erich Gamma 已提交
75

76
	public _serviceBrand: any;
E
Erich Gamma 已提交
77 78 79 80

	private static FS_EVENT_DELAY = 50; // aggregate and only emit events when changes have stopped for this duration (in ms)
	private static MAX_DEGREE_OF_PARALLEL_FS_OPS = 10; // degree of parallel fs calls that we accept at the same time

D
Daniel Imms 已提交
81
	private toUnbind: IDisposable[];
E
Erich Gamma 已提交
82 83 84 85 86 87 88
	private basePath: string;
	private tmpPath: string;
	private options: IFileServiceOptions;

	private workspaceWatcherToDispose: () => void;

	private activeFileChangesWatchers: { [resource: string]: fs.FSWatcher; };
J
Joao Moreno 已提交
89
	private fileChangesWatchDelayer: ThrottledDelayer<void>;
E
Erich Gamma 已提交
90 91
	private undeliveredRawFileChangesEvents: IRawFileChange[];

D
Daniel Imms 已提交
92 93
	private configuredHotExit: boolean;

94 95 96 97 98 99 100 101 102
	constructor(
		basePath: string,
		options: IFileServiceOptions,
		private eventEmitter: IEventService,
		private environmentService: IEnvironmentService,
		private configurationService: IConfigurationService,
		private backupService: IBackupService,
		private contextService: IWorkspaceContextService
	) {
E
Erich Gamma 已提交
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 132
		this.basePath = basePath ? paths.normalize(basePath) : void 0;

		if (this.basePath && this.basePath.indexOf('\\\\') === 0 && strings.endsWith(this.basePath, paths.sep)) {
			// for some weird reason, node adds a trailing slash to UNC paths
			// we never ever want trailing slashes as our base path unless
			// someone opens root ("/").
			// See also https://github.com/nodejs/io.js/issues/1765
			this.basePath = strings.rtrim(this.basePath, paths.sep);
		}

		if (this.basePath && !paths.isAbsolute(basePath)) {
			throw new Error('basePath has to be an absolute path');
		}

		this.options = options || Object.create(null);
		this.tmpPath = this.options.tmpDir || os.tmpdir();

		if (this.options && !this.options.errorLogger) {
			this.options.errorLogger = console.error;
		}

		if (this.basePath && !this.options.disableWatcher) {
			if (process.platform === 'win32') {
				this.setupWin32WorkspaceWatching();
			} else {
				this.setupUnixWorkspaceWatching();
			}
		}

		this.activeFileChangesWatchers = Object.create(null);
J
Joao Moreno 已提交
133
		this.fileChangesWatchDelayer = new ThrottledDelayer<void>(FileService.FS_EVENT_DELAY);
E
Erich Gamma 已提交
134
		this.undeliveredRawFileChangesEvents = [];
D
Daniel Imms 已提交
135 136 137

		// Configuration changes
		this.toUnbind = [];
D
Daniel Imms 已提交
138 139
		if (this.configurationService) {
			this.toUnbind.push(this.configurationService.onDidUpdateConfiguration(e => this.onConfigurationChange(e.config)));
D
Daniel Imms 已提交
140

D
Daniel Imms 已提交
141 142 143
			const configuration = this.configurationService.getConfiguration<IFilesConfiguration>();
			this.onConfigurationChange(configuration);
		}
D
Daniel Imms 已提交
144 145 146 147
	}

	private onConfigurationChange(configuration: IFilesConfiguration): void {
		this.configuredHotExit = configuration && configuration.files && configuration.files.hotExit;
E
Erich Gamma 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160
	}

	public updateOptions(options: IFileServiceOptions): void {
		if (options) {
			objects.mixin(this.options, options); // overwrite current options
		}
	}

	private setupWin32WorkspaceWatching(): void {
		this.workspaceWatcherToDispose = new WindowsWatcherService(this.basePath, this.options.watcherIgnoredPatterns, this.eventEmitter, this.options.errorLogger, this.options.verboseLogging).startWatching();
	}

	private setupUnixWorkspaceWatching(): void {
J
Joao Moreno 已提交
161
		this.workspaceWatcherToDispose = new UnixWatcherService(this.basePath, this.options.watcherIgnoredPatterns, this.eventEmitter, this.options.errorLogger, this.options.verboseLogging).startWatching();
E
Erich Gamma 已提交
162 163
	}

B
Benjamin Pasero 已提交
164
	public resolveFile(resource: uri, options?: IResolveFileOptions): TPromise<IFileStat> {
E
Erich Gamma 已提交
165 166 167
		return this.resolve(resource, options);
	}

168 169 170 171
	public existsFile(resource: uri): TPromise<boolean> {
		return this.resolveFile(resource).then(() => true, () => false);
	}

B
Benjamin Pasero 已提交
172 173
	public resolveContent(resource: uri, options?: IResolveContentOptions): TPromise<IContent> {
		return this.doResolveContent(resource, options, (resource, etag, enc) => this.resolveFileContent(resource, etag, enc));
A
Alex Dima 已提交
174 175
	}

B
Benjamin Pasero 已提交
176 177
	public resolveStreamContent(resource: uri, options?: IResolveContentOptions): TPromise<IStreamContent> {
		return this.doResolveContent(resource, options, (resource, etag, enc) => this.resolveFileStreamContent(resource, etag, enc));
A
Alex Dima 已提交
178 179
	}

B
Benjamin Pasero 已提交
180
	private doResolveContent<T extends IBaseStat>(resource: uri, options: IResolveContentOptions, contentResolver: (resource: uri, etag?: string, enc?: string) => TPromise<T>): TPromise<T> {
B
Benjamin Pasero 已提交
181
		const absolutePath = this.toAbsolutePath(resource);
E
Erich Gamma 已提交
182

183 184 185
		// Guard early against attempts to resolve an invalid file path
		if (resource.scheme !== 'file' || !resource.fsPath) {
			return TPromise.wrapError(<IFileOperationResult>{
B
Benjamin Pasero 已提交
186 187
				message: nls.localize('fileInvalidPath', "Invalid file resource ({0})", resource.toString()),
				fileOperationResult: FileOperationResult.FILE_INVALID_PATH
188 189 190
			});
		}

E
Erich Gamma 已提交
191
		// 1.) detect mimes
B
Benjamin Pasero 已提交
192
		return nfcall(mime.detectMimesFromFile, absolutePath).then((detected: mime.IMimeAndEncoding): TPromise<T> => {
B
Benjamin Pasero 已提交
193
			const isText = detected.mimes.indexOf(baseMime.MIME_BINARY) === -1;
E
Erich Gamma 已提交
194 195 196

			// Return error early if client only accepts text and this is not text
			if (options && options.acceptTextOnly && !isText) {
B
Benjamin Pasero 已提交
197
				return TPromise.wrapError(<IFileOperationResult>{
E
Erich Gamma 已提交
198
					message: nls.localize('fileBinaryError', "File seems to be binary and cannot be opened as text"),
B
Benjamin Pasero 已提交
199
					fileOperationResult: FileOperationResult.FILE_IS_BINARY
E
Erich Gamma 已提交
200 201 202
				});
			}

B
Benjamin Pasero 已提交
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
			let preferredEncoding: string;
			if (options && options.encoding) {
				if (detected.encoding === encoding.UTF8 && options.encoding === encoding.UTF8) {
					preferredEncoding = encoding.UTF8_with_bom; // indicate the file has BOM if we are to resolve with UTF 8
				} else {
					preferredEncoding = options.encoding; // give passed in encoding highest priority
				}
			} else if (detected.encoding) {
				if (detected.encoding === encoding.UTF8) {
					preferredEncoding = encoding.UTF8_with_bom; // if we detected UTF-8, it can only be because of a BOM
				} else {
					preferredEncoding = detected.encoding;
				}
			} else if (this.options.encoding === encoding.UTF8_with_bom) {
				preferredEncoding = encoding.UTF8; // if we did not detect UTF 8 BOM before, this can only be UTF 8 then
B
wip  
Benjamin Pasero 已提交
218 219
			}

E
Erich Gamma 已提交
220
			// 2.) get content
221
			return contentResolver(resource, options && options.etag, preferredEncoding);
E
Erich Gamma 已提交
222 223 224
		}, (error) => {

			// bubble up existing file operation results
B
Benjamin Pasero 已提交
225
			if (!types.isUndefinedOrNull((<IFileOperationResult>error).fileOperationResult)) {
226
				return TPromise.wrapError(error);
E
Erich Gamma 已提交
227 228 229
			}

			// on error check if the file does not exist or is a folder and return with proper error result
230
			return pfs.exists(absolutePath).then(exists => {
E
Erich Gamma 已提交
231 232 233

				// Return if file not found
				if (!exists) {
B
Benjamin Pasero 已提交
234
					return TPromise.wrapError(<IFileOperationResult>{
E
Erich Gamma 已提交
235
						message: nls.localize('fileNotFoundError', "File not found ({0})", absolutePath),
B
Benjamin Pasero 已提交
236
						fileOperationResult: FileOperationResult.FILE_NOT_FOUND
E
Erich Gamma 已提交
237 238 239 240
					});
				}

				// Otherwise check for file being a folder?
241
				return pfs.stat(absolutePath).then(stat => {
E
Erich Gamma 已提交
242
					if (stat.isDirectory()) {
B
Benjamin Pasero 已提交
243
						return TPromise.wrapError(<IFileOperationResult>{
E
Erich Gamma 已提交
244
							message: nls.localize('fileIsDirectoryError', "File is directory ({0})", absolutePath),
B
Benjamin Pasero 已提交
245
							fileOperationResult: FileOperationResult.FILE_IS_DIRECTORY
E
Erich Gamma 已提交
246 247 248 249
						});
					}

					// otherwise just give up
250
					return TPromise.wrapError(error);
E
Erich Gamma 已提交
251 252 253 254 255
				});
			});
		});
	}

B
Benjamin Pasero 已提交
256
	public resolveContents(resources: uri[]): TPromise<IContent[]> {
B
Benjamin Pasero 已提交
257
		const limiter = new Limiter(FileService.MAX_DEGREE_OF_PARALLEL_FS_OPS);
E
Erich Gamma 已提交
258

B
Benjamin Pasero 已提交
259
		const contentPromises = <TPromise<IContent>[]>[];
260 261
		resources.forEach(resource => {
			contentPromises.push(limiter.queue(() => this.resolveFileContent(resource).then(content => content, error => TPromise.as(null /* ignore errors gracefully */))));
E
Erich Gamma 已提交
262 263
		});

264
		return TPromise.join(contentPromises).then(contents => {
E
Erich Gamma 已提交
265 266 267 268
			return arrays.coalesce(contents);
		});
	}

B
Benjamin Pasero 已提交
269
	public updateContent(resource: uri, value: string, options: IUpdateContentOptions = Object.create(null)): TPromise<IFileStat> {
B
Benjamin Pasero 已提交
270
		const absolutePath = this.toAbsolutePath(resource);
E
Erich Gamma 已提交
271 272

		// 1.) check file
273
		return this.checkFile(absolutePath, options).then(exists => {
274
			let createParentsPromise: TPromise<boolean>;
E
Erich Gamma 已提交
275
			if (exists) {
A
Alex Dima 已提交
276
				createParentsPromise = TPromise.as(null);
E
Erich Gamma 已提交
277 278 279 280 281 282
			} else {
				createParentsPromise = pfs.mkdirp(paths.dirname(absolutePath));
			}

			// 2.) create parents as needed
			return createParentsPromise.then(() => {
B
Benjamin Pasero 已提交
283
				const encodingToWrite = this.getEncoding(resource, options.encoding);
E
Erich Gamma 已提交
284
				let addBomPromise: TPromise<boolean> = TPromise.as(false);
B
wip  
Benjamin Pasero 已提交
285 286 287

				// 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) {
E
Erich Gamma 已提交
288 289 290
					addBomPromise = TPromise.as(true);
				}

B
wip  
Benjamin Pasero 已提交
291 292 293 294 295
				// 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 {
296
						addBomPromise = nfcall(encoding.detectEncodingByBOM, absolutePath).then(enc => enc === encoding.UTF8); // otherwise preserve it if found
297
					}
E
Erich Gamma 已提交
298 299 300
				}

				// 3.) check to add UTF BOM
301
				return addBomPromise.then(addBom => {
302
					let writeFilePromise: TPromise<void>;
E
Erich Gamma 已提交
303 304 305

					// Write fast if we do UTF 8 without BOM
					if (!addBom && encodingToWrite === encoding.UTF8) {
306
						writeFilePromise = pfs.writeFileAndFlush(absolutePath, value, encoding.UTF8);
E
Erich Gamma 已提交
307 308
					}

B
wip  
Benjamin Pasero 已提交
309
					// Otherwise use encoding lib
E
Erich Gamma 已提交
310
					else {
B
Benjamin Pasero 已提交
311
						const encoded = encoding.encode(value, encodingToWrite, { addBOM: addBom });
312
						writeFilePromise = pfs.writeFileAndFlush(absolutePath, encoded);
E
Erich Gamma 已提交
313 314 315 316 317 318 319 320 321 322 323 324 325
					}

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

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

B
Benjamin Pasero 已提交
326
	public createFile(resource: uri, content: string = ''): TPromise<IFileStat> {
E
Erich Gamma 已提交
327 328 329
		return this.updateContent(resource, content);
	}

B
Benjamin Pasero 已提交
330
	public createFolder(resource: uri): TPromise<IFileStat> {
E
Erich Gamma 已提交
331 332

		// 1.) create folder
B
Benjamin Pasero 已提交
333
		const absolutePath = this.toAbsolutePath(resource);
E
Erich Gamma 已提交
334 335 336 337 338 339 340
		return pfs.mkdirp(absolutePath).then(() => {

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

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
	public touchFile(resource: uri): TPromise<IFileStat> {
		const absolutePath = this.toAbsolutePath(resource);

		// 1.) check file
		return this.checkFile(absolutePath).then(exists => {
			let createPromise: TPromise<IFileStat>;
			if (exists) {
				createPromise = TPromise.as(null);
			} else {
				createPromise = this.createFile(resource);
			}

			// 2.) create file as needed
			return createPromise.then(() => {

				// 3.) update atime and mtime
				return pfs.utimes(absolutePath, new Date(), new Date()).then(() => {

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

B
Benjamin Pasero 已提交
366
	public rename(resource: uri, newName: string): TPromise<IFileStat> {
B
Benjamin Pasero 已提交
367
		const newPath = paths.join(paths.dirname(resource.fsPath), newName);
E
Erich Gamma 已提交
368 369 370 371

		return this.moveFile(resource, uri.file(newPath));
	}

B
Benjamin Pasero 已提交
372
	public moveFile(source: uri, target: uri, overwrite?: boolean): TPromise<IFileStat> {
E
Erich Gamma 已提交
373 374 375
		return this.moveOrCopyFile(source, target, false, overwrite);
	}

B
Benjamin Pasero 已提交
376
	public copyFile(source: uri, target: uri, overwrite?: boolean): TPromise<IFileStat> {
E
Erich Gamma 已提交
377 378 379
		return this.moveOrCopyFile(source, target, true, overwrite);
	}

B
Benjamin Pasero 已提交
380
	private moveOrCopyFile(source: uri, target: uri, keepCopy: boolean, overwrite: boolean): TPromise<IFileStat> {
B
Benjamin Pasero 已提交
381 382
		const sourcePath = this.toAbsolutePath(source);
		const targetPath = this.toAbsolutePath(target);
E
Erich Gamma 已提交
383 384 385 386 387 388 389 390 391 392 393 394

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

			// 2.) resolve
			return this.resolve(target);
		});
	}

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

		// 1.) check if target exists
395
		return pfs.exists(targetPath).then(exists => {
B
Benjamin Pasero 已提交
396 397
			const isCaseRename = sourcePath.toLowerCase() === targetPath.toLowerCase();
			const isSameFile = sourcePath === targetPath;
E
Erich Gamma 已提交
398 399 400

			// Return early with conflict if target exists and we are not told to overwrite
			if (exists && !isCaseRename && !overwrite) {
B
Benjamin Pasero 已提交
401 402
				return TPromise.wrapError(<IFileOperationResult>{
					fileOperationResult: FileOperationResult.FILE_MOVE_CONFLICT
E
Erich Gamma 已提交
403 404 405 406
				});
			}

			// 2.) make sure target is deleted before we move/copy unless this is a case rename of the same file
A
Alex Dima 已提交
407
			let deleteTargetPromise = TPromise.as(null);
E
Erich Gamma 已提交
408 409
			if (exists && !isCaseRename) {
				if (basePaths.isEqualOrParent(sourcePath, targetPath)) {
410
					return TPromise.wrapError(nls.localize('unableToMoveCopyError', "Unable to move/copy. File would replace folder it is contained in.")); // catch this corner case!
E
Erich Gamma 已提交
411 412 413 414 415 416 417 418 419
				}

				deleteTargetPromise = this.del(uri.file(targetPath));
			}

			return deleteTargetPromise.then(() => {

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

E
Erich Gamma 已提交
421
					// 4.) copy/move
422 423 424
					if (isSameFile) {
						return TPromise.as(null);
					} else if (keepCopy) {
E
Erich Gamma 已提交
425 426 427 428 429 430 431 432 433
						return nfcall(extfs.copy, sourcePath, targetPath);
					} else {
						return nfcall(extfs.mv, sourcePath, targetPath);
					}
				}).then(() => exists);
			});
		});
	}

B
Benjamin Pasero 已提交
434
	public importFile(source: uri, targetFolder: uri): TPromise<IImportResult> {
B
Benjamin Pasero 已提交
435 436 437
		const sourcePath = this.toAbsolutePath(source);
		const targetResource = uri.file(paths.join(targetFolder.fsPath, paths.basename(source.fsPath)));
		const targetPath = this.toAbsolutePath(targetResource);
E
Erich Gamma 已提交
438 439

		// 1.) resolve
440
		return pfs.stat(sourcePath).then(stat => {
E
Erich Gamma 已提交
441
			if (stat.isDirectory()) {
442
				return TPromise.wrapError(nls.localize('foldersCopyError', "Folders cannot be copied into the workspace. Please select individual files to copy them.")); // for now we do not allow to import a folder into a workspace
E
Erich Gamma 已提交
443 444 445
			}

			// 2.) copy
446
			return this.doMoveOrCopyFile(sourcePath, targetPath, true, true).then(exists => {
E
Erich Gamma 已提交
447 448

				// 3.) resolve
449
				return this.resolve(targetResource).then(stat => <IImportResult>{ isNew: !exists, stat: stat });
E
Erich Gamma 已提交
450 451 452 453
			});
		});
	}

454
	public del(resource: uri): TPromise<void> {
B
Benjamin Pasero 已提交
455
		const absolutePath = this.toAbsolutePath(resource);
E
Erich Gamma 已提交
456 457 458 459

		return nfcall(extfs.del, absolutePath, this.tmpPath);
	}

D
Daniel Imms 已提交
460
	public backupFile(resource: uri, content: string): TPromise<IFileStat> {
461
		// TODO: This should not backup unless necessary. Currently this is called for each file on close to ensure the files are backed up.
462
		let registerResourcePromise: TPromise<void>;
463
		if (resource.scheme === 'file') {
464 465 466
			registerResourcePromise = this.backupService.registerResourceForBackup(resource);
		} else {
			registerResourcePromise = TPromise.as(void 0);
467
		}
468 469
		return registerResourcePromise.then(() => {
			const backupResource = this.getBackupPath(resource);
470

471 472 473 474
			// Hot exit is disabled for empty workspaces
			if (!backupResource) {
				return TPromise.as(null);
			}
475

476 477
			return this.updateContent(backupResource, content);
		});
478 479
	}

480
	public discardBackup(resource: uri): TPromise<void> {
481 482
		return this.backupService.deregisterResourceForBackup(resource).then(() => {
			const backupResource = this.getBackupPath(resource);
483

484 485 486 487
			// Hot exit is disabled for empty workspaces
			if (!backupResource) {
				return TPromise.as(null);
			}
488

489 490
			return this.del(backupResource);
		});
491 492
	}

D
Daniel Imms 已提交
493
	public discardBackups(): TPromise<void> {
494 495 496 497 498 499 500
		// Hot exit is disabled for empty workspaces
		const backupRootPath = this.getBackupRootPath();
		if (!backupRootPath) {
			return TPromise.as(void 0);
		}

		return this.del(uri.file(backupRootPath));
D
Daniel Imms 已提交
501 502
	}

D
Daniel Imms 已提交
503 504 505 506
	public isHotExitEnabled(): boolean {
		return this.configuredHotExit;
	}

E
Erich Gamma 已提交
507 508
	// Helpers

509
	private getBackupPath(resource: uri): uri {
510 511 512 513 514 515
		// Hot exit is disabled for empty workspaces
		const backupRootPath = this.getBackupRootPath();
		if (!backupRootPath) {
			return null;
		}

516
		const backupName = crypto.createHash('md5').update(resource.fsPath).digest('hex');
517
		const backupPath = paths.join(backupRootPath, resource.scheme, backupName);
518 519 520
		return uri.file(backupPath);
	}

521 522 523 524 525 526 527 528
	private getBackupRootPath(): string {
		// Hot exit is disabled for empty workspaces
		const workspace = this.contextService.getWorkspace();
		if (!workspace) {
			return null;
		}

		const workspaceHash = crypto.createHash('md5').update(workspace.resource.fsPath).digest('hex');
529
		return paths.join(this.environmentService.userDataPath, 'Backups', workspaceHash);
530 531
	}

B
Benjamin Pasero 已提交
532
	private toAbsolutePath(arg1: uri | IFileStat): string {
E
Erich Gamma 已提交
533
		let resource: uri;
534
		if (arg1 instanceof uri) {
E
Erich Gamma 已提交
535 536
			resource = <uri>arg1;
		} else {
B
Benjamin Pasero 已提交
537
			resource = (<IFileStat>arg1).resource;
E
Erich Gamma 已提交
538 539 540 541 542 543 544
		}

		assert.ok(resource && resource.scheme === 'file', 'Invalid resource: ' + resource);

		return paths.normalize(resource.fsPath);
	}

B
Benjamin Pasero 已提交
545
	private resolve(resource: uri, options: IResolveFileOptions = Object.create(null)): TPromise<IFileStat> {
E
Erich Gamma 已提交
546 547 548 549 550
		return this.toStatResolver(resource)
			.then(model => model.resolve(options));
	}

	private toStatResolver(resource: uri): TPromise<StatResolver> {
B
Benjamin Pasero 已提交
551
		const absolutePath = this.toAbsolutePath(resource);
E
Erich Gamma 已提交
552

553
		return pfs.stat(absolutePath).then(stat => {
554
			return new StatResolver(resource, stat.isDirectory(), stat.mtime.getTime(), stat.size, this.options.verboseLogging);
E
Erich Gamma 已提交
555 556 557
		});
	}

B
Benjamin Pasero 已提交
558
	private resolveFileStreamContent(resource: uri, etag?: string, enc?: string): TPromise<IStreamContent> {
B
Benjamin Pasero 已提交
559
		const absolutePath = this.toAbsolutePath(resource);
E
Erich Gamma 已提交
560

B
Benjamin Pasero 已提交
561
		return this.resolve(resource).then((model): TPromise<IStreamContent> => {
E
Erich Gamma 已提交
562 563 564

			// Return early if file not modified since
			if (etag && etag === model.etag) {
B
Benjamin Pasero 已提交
565 566
				return TPromise.wrapError(<IFileOperationResult>{
					fileOperationResult: FileOperationResult.FILE_NOT_MODIFIED_SINCE
E
Erich Gamma 已提交
567 568 569 570
				});
			}

			// Return early if file is too large to load
B
Benjamin Pasero 已提交
571 572 573
			if (types.isNumber(model.size) && model.size > MAX_FILE_SIZE) {
				return TPromise.wrapError(<IFileOperationResult>{
					fileOperationResult: FileOperationResult.FILE_TOO_LARGE
E
Erich Gamma 已提交
574 575 576
				});
			}

B
Benjamin Pasero 已提交
577
			const fileEncoding = this.getEncoding(model.resource, enc);
A
Alex Dima 已提交
578 579 580

			const reader = fs.createReadStream(absolutePath).pipe(encoding.decodeStream(fileEncoding)); // decode takes care of stripping any BOMs from the file content

B
Benjamin Pasero 已提交
581
			const content: IStreamContent = <any>model;
A
Alex Dima 已提交
582 583
			content.value = reader;
			content.encoding = fileEncoding; // make sure to store the encoding in the model to restore it later when writing
B
Benjamin Pasero 已提交
584

A
Alex Dima 已提交
585 586 587 588
			return TPromise.as(content);
		});
	}

B
Benjamin Pasero 已提交
589
	private resolveFileContent(resource: uri, etag?: string, enc?: string): TPromise<IContent> {
A
Alex Dima 已提交
590
		return this.resolveFileStreamContent(resource, etag, enc).then((streamContent) => {
B
Benjamin Pasero 已提交
591
			return new TPromise<IContent>((c, e) => {
592
				let done = false;
B
Benjamin Pasero 已提交
593
				const chunks: string[] = [];
E
Erich Gamma 已提交
594

595
				streamContent.value.on('data', buf => {
596 597 598
					chunks.push(buf);
				});

599
				streamContent.value.on('error', error => {
600 601 602 603 604 605
					if (!done) {
						done = true;
						e(error);
					}
				});

A
Alex Dima 已提交
606
				streamContent.value.on('end', () => {
B
Benjamin Pasero 已提交
607
					const content: IContent = <any>streamContent;
608 609 610 611 612 613
					content.value = chunks.join('');

					if (!done) {
						done = true;
						c(content);
					}
B
Benjamin Pasero 已提交
614
				});
E
Erich Gamma 已提交
615 616 617 618
			});
		});
	}

B
Benjamin Pasero 已提交
619
	private getEncoding(resource: uri, preferredEncoding?: string): string {
E
Erich Gamma 已提交
620 621
		let fileEncoding: string;

B
Benjamin Pasero 已提交
622
		const override = this.getEncodingOverride(resource);
E
Erich Gamma 已提交
623 624
		if (override) {
			fileEncoding = override;
B
Benjamin Pasero 已提交
625 626
		} else if (preferredEncoding) {
			fileEncoding = preferredEncoding;
627
		} else {
B
Benjamin Pasero 已提交
628
			fileEncoding = this.options.encoding;
E
Erich Gamma 已提交
629 630
		}

B
wip  
Benjamin Pasero 已提交
631
		if (!fileEncoding || !encoding.encodingExists(fileEncoding)) {
E
Erich Gamma 已提交
632 633 634 635 636 637 638 639 640
			fileEncoding = encoding.UTF8; // the default is UTF 8
		}

		return fileEncoding;
	}

	private getEncodingOverride(resource: uri): string {
		if (resource && this.options.encodingOverride && this.options.encodingOverride.length) {
			for (let i = 0; i < this.options.encodingOverride.length; i++) {
B
Benjamin Pasero 已提交
641
				const override = this.options.encodingOverride[i];
E
Erich Gamma 已提交
642 643 644 645 646 647 648 649 650 651 652 653

				// check if the resource is a child of the resource with override and use
				// the provided encoding in that case
				if (resource.toString().indexOf(override.resource.toString() + '/') === 0) {
					return override.encoding;
				}
			}
		}

		return null;
	}

654
	private checkFile(absolutePath: string, options: IUpdateContentOptions = Object.create(null)): TPromise<boolean /* exists */> {
655
		return pfs.exists(absolutePath).then(exists => {
E
Erich Gamma 已提交
656
			if (exists) {
657
				return pfs.stat(absolutePath).then(stat => {
E
Erich Gamma 已提交
658
					if (stat.isDirectory()) {
659
						return TPromise.wrapError(new Error('Expected file is actually a directory'));
E
Erich Gamma 已提交
660 661 662 663 664 665 666
					}

					// Dirty write prevention
					if (typeof options.mtime === 'number' && typeof options.etag === 'string' && options.mtime < stat.mtime.getTime()) {

						// Find out if content length has changed
						if (options.etag !== etag(stat.size, options.mtime)) {
B
Benjamin Pasero 已提交
667
							return TPromise.wrapError(<IFileOperationResult>{
E
Erich Gamma 已提交
668
								message: 'File Modified Since',
B
Benjamin Pasero 已提交
669
								fileOperationResult: FileOperationResult.FILE_MODIFIED_SINCE
E
Erich Gamma 已提交
670 671 672 673 674
							});
						}
					}

					let mode = stat.mode;
B
Benjamin Pasero 已提交
675
					const readonly = !(mode & 128);
E
Erich Gamma 已提交
676 677 678

					// Throw if file is readonly and we are not instructed to overwrite
					if (readonly && !options.overwriteReadonly) {
B
Benjamin Pasero 已提交
679
						return TPromise.wrapError(<IFileOperationResult>{
E
Erich Gamma 已提交
680
							message: nls.localize('fileReadOnlyError', "File is Read Only"),
B
Benjamin Pasero 已提交
681
							fileOperationResult: FileOperationResult.FILE_READ_ONLY
E
Erich Gamma 已提交
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
						});
					}

					if (readonly) {
						mode = mode | 128;
						return pfs.chmod(absolutePath, mode).then(() => exists);
					}

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

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

	public watchFileChanges(resource: uri): void {
		assert.ok(resource && resource.scheme === 'file', 'Invalid resource for watching: ' + resource);

B
Benjamin Pasero 已提交
701
		const fsPath = resource.fsPath;
E
Erich Gamma 已提交
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722

		// Create or get watcher for provided path
		let watcher = this.activeFileChangesWatchers[resource.toString()];
		if (!watcher) {
			try {
				watcher = fs.watch(fsPath); // will be persistent but not recursive
			} catch (error) {
				// the path might not exist anymore, ignore this error and return
				return;
			}

			this.activeFileChangesWatchers[resource.toString()] = watcher;

			// eventType is either 'rename' or 'change'
			watcher.on('change', (eventType: string) => {
				if (eventType !== 'change') {
					return; // only care about changes for now ('rename' is not reliable and can be send even if the file is still there with some tools)
				}

				// add to bucket of undelivered events
				this.undeliveredRawFileChangesEvents.push({
B
Benjamin Pasero 已提交
723
					type: FileChangeType.UPDATED,
E
Erich Gamma 已提交
724 725 726
					path: fsPath
				});

727
				// handle emit through delayer to accommodate for bulk changes
E
Erich Gamma 已提交
728
				this.fileChangesWatchDelayer.trigger(() => {
B
Benjamin Pasero 已提交
729
					const buffer = this.undeliveredRawFileChangesEvents;
E
Erich Gamma 已提交
730 731 732
					this.undeliveredRawFileChangesEvents = [];

					// Normalize
B
Benjamin Pasero 已提交
733
					const normalizedEvents = normalize(buffer);
E
Erich Gamma 已提交
734 735

					// Emit
B
Benjamin Pasero 已提交
736
					this.eventEmitter.emit(EventType.FILE_CHANGES, toFileChangesEvent(normalizedEvents));
E
Erich Gamma 已提交
737

A
Alex Dima 已提交
738
					return TPromise.as(null);
E
Erich Gamma 已提交
739 740 741 742 743 744 745 746
				});
			});
		}
	}

	public unwatchFileChanges(resource: uri): void;
	public unwatchFileChanges(path: string): void;
	public unwatchFileChanges(arg1: any): void {
B
Benjamin Pasero 已提交
747
		const resource = (typeof arg1 === 'string') ? uri.parse(arg1) : arg1;
E
Erich Gamma 已提交
748

B
Benjamin Pasero 已提交
749
		const watcher = this.activeFileChangesWatchers[resource.toString()];
E
Erich Gamma 已提交
750 751 752 753 754 755 756 757 758 759 760 761 762
		if (watcher) {
			watcher.close();
			delete this.activeFileChangesWatchers[resource.toString()];
		}
	}

	public dispose(): void {
		if (this.workspaceWatcherToDispose) {
			this.workspaceWatcherToDispose();
			this.workspaceWatcherToDispose = null;
		}

		for (let key in this.activeFileChangesWatchers) {
B
Benjamin Pasero 已提交
763
			const watcher = this.activeFileChangesWatchers[key];
E
Erich Gamma 已提交
764 765 766
			watcher.close();
		}
		this.activeFileChangesWatchers = Object.create(null);
D
Daniel Imms 已提交
767 768

		this.toUnbind = dispose(this.toUnbind);
E
Erich Gamma 已提交
769 770 771 772 773 774 775 776 777 778
	}
}

export class StatResolver {
	private resource: uri;
	private isDirectory: boolean;
	private mtime: number;
	private name: string;
	private etag: string;
	private size: number;
779
	private verboseLogging: boolean;
E
Erich Gamma 已提交
780

781
	constructor(resource: uri, isDirectory: boolean, mtime: number, size: number, verboseLogging: boolean) {
E
Erich Gamma 已提交
782 783 784 785 786 787 788 789
		assert.ok(resource && resource.scheme === 'file', 'Invalid resource: ' + resource);

		this.resource = resource;
		this.isDirectory = isDirectory;
		this.mtime = mtime;
		this.name = paths.basename(resource.fsPath);
		this.etag = etag(size, mtime);
		this.size = size;
790 791

		this.verboseLogging = verboseLogging;
E
Erich Gamma 已提交
792 793
	}

B
Benjamin Pasero 已提交
794
	public resolve(options: IResolveFileOptions): TPromise<IFileStat> {
E
Erich Gamma 已提交
795 796

		// General Data
B
Benjamin Pasero 已提交
797
		const fileStat: IFileStat = {
E
Erich Gamma 已提交
798 799 800 801 802 803
			resource: this.resource,
			isDirectory: this.isDirectory,
			hasChildren: undefined,
			name: this.name,
			etag: this.etag,
			size: this.size,
804
			mtime: this.mtime
E
Erich Gamma 已提交
805 806 807 808 809 810 811 812 813 814 815 816 817 818
		};

		// File Specific Data
		if (!this.isDirectory) {
			return TPromise.as(fileStat);
		}

		// Directory Specific Data
		else {

			// Convert the paths from options.resolveTo to absolute paths
			let absoluteTargetPaths: string[] = null;
			if (options && options.resolveTo) {
				absoluteTargetPaths = [];
819
				options.resolveTo.forEach(resource => {
E
Erich Gamma 已提交
820 821 822 823 824
					absoluteTargetPaths.push(resource.fsPath);
				});
			}

			return new TPromise((c, e) => {
825

E
Erich Gamma 已提交
826 827
				// Load children
				this.resolveChildren(this.resource.fsPath, absoluteTargetPaths, options && options.resolveSingleChildDescendants, (children) => {
828
					children = arrays.coalesce(children); // we don't want those null children (could be permission denied when reading a child)
E
Erich Gamma 已提交
829 830 831 832 833 834 835 836 837
					fileStat.hasChildren = children && children.length > 0;
					fileStat.children = children || [];

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

B
Benjamin Pasero 已提交
838
	private resolveChildren(absolutePath: string, absoluteTargetPaths: string[], resolveSingleChildDescendants: boolean, callback: (children: IFileStat[]) => void): void {
E
Erich Gamma 已提交
839 840
		extfs.readdir(absolutePath, (error: Error, files: string[]) => {
			if (error) {
841 842 843
				if (this.verboseLogging) {
					console.error(error);
				}
E
Erich Gamma 已提交
844 845 846 847 848

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

			// for each file in the folder
B
Benjamin Pasero 已提交
849
			flow.parallel(files, (file: string, clb: (error: Error, children: IFileStat) => void) => {
B
Benjamin Pasero 已提交
850
				const fileResource = uri.file(paths.resolve(absolutePath, file));
851
				let fileStat: fs.Stats;
B
Benjamin Pasero 已提交
852
				const $this = this;
E
Erich Gamma 已提交
853 854 855

				flow.sequence(
					function onError(error: Error): void {
856
						if ($this.verboseLogging) {
857 858
							console.error(error);
						}
E
Erich Gamma 已提交
859 860 861 862 863

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

					function stat(): void {
864
						fs.stat(fileResource.fsPath, this);
E
Erich Gamma 已提交
865 866
					},

867
					function countChildren(fsstat: fs.Stats): void {
E
Erich Gamma 已提交
868 869 870
						fileStat = fsstat;

						if (fileStat.isDirectory()) {
871
							extfs.readdir(fileResource.fsPath, (error, result) => {
E
Erich Gamma 已提交
872 873 874 875 876 877 878 879
								this(null, result ? result.length : 0);
							});
						} else {
							this(null, 0);
						}
					},

					function resolve(childCount: number): void {
B
Benjamin Pasero 已提交
880
						const childStat: IFileStat = {
E
Erich Gamma 已提交
881 882 883 884 885 886
							resource: fileResource,
							isDirectory: fileStat.isDirectory(),
							hasChildren: childCount > 0,
							name: file,
							mtime: fileStat.mtime.getTime(),
							etag: etag(fileStat),
887
							size: fileStat.size
E
Erich Gamma 已提交
888 889 890 891 892 893 894 895 896 897 898
						};

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

						// Handle Folder
						let resolveFolderChildren = false;
						if (files.length === 1 && resolveSingleChildDescendants) {
							resolveFolderChildren = true;
899
						} else if (childCount > 0 && absoluteTargetPaths && absoluteTargetPaths.some(targetPath => basePaths.isEqualOrParent(targetPath, fileResource.fsPath))) {
E
Erich Gamma 已提交
900 901 902 903 904
							resolveFolderChildren = true;
						}

						// Continue resolving children based on condition
						if (resolveFolderChildren) {
905
							$this.resolveChildren(fileResource.fsPath, absoluteTargetPaths, resolveSingleChildDescendants, children => {
906
								children = arrays.coalesce(children);  // we don't want those null children
E
Erich Gamma 已提交
907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
								childStat.hasChildren = children && children.length > 0;
								childStat.children = children || [];

								clb(null, childStat);
							});
						}

						// Otherwise return result
						else {
							clb(null, childStat);
						}
					});
			}, (errors, result) => {
				callback(result);
			});
		});
	}
}