nativeTextFileService.ts 18.4 KB
Newer Older
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6
import { tmpdir } from 'os';
7
import { localize } from 'vs/nls';
8
import { AbstractTextFileService } from 'vs/workbench/services/textfile/browser/textFileService';
9
import { ITextFileService, ITextFileStreamContent, ITextFileContent, IResourceEncodings, IResourceEncoding, IReadTextFileOptions, IWriteTextFileOptions, stringToSnapshot, TextFileOperationResult, TextFileOperationError } from 'vs/workbench/services/textfile/common/textfiles';
10 11
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import { URI } from 'vs/base/common/uri';
12
import { IFileStatWithMetadata, ICreateFileOptions, FileOperationError, FileOperationResult, IFileStreamContent, IFileService } from 'vs/platform/files/common/files';
13
import { Schemas } from 'vs/base/common/network';
14
import { exists, stat, chmod, rimraf, MAX_FILE_SIZE, MAX_HEAP_SIZE } from 'vs/base/node/pfs';
15
import { join, dirname } from 'vs/base/common/path';
16
import { isMacintosh } from 'vs/base/common/platform';
17
import { IProductService } from 'vs/platform/product/common/productService';
S
rename  
Sandeep Somavarapu 已提交
18
import { ITextResourceConfigurationService } from 'vs/editor/common/services/textResourceConfigurationService';
19
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
B
Benjamin Pasero 已提交
20
import { UTF8, UTF8_with_bom, UTF16be, UTF16le, encodingExists, encodeStream, UTF8_BOM, toDecodeStream, IDecodeStreamResult, detectEncodingByBOMFromBuffer, isUTFEncoding } from 'vs/base/node/encoding';
21 22 23 24
import { WORKSPACE_EXTENSION } from 'vs/platform/workspaces/common/workspaces';
import { joinPath, extname, isEqualOrParent } from 'vs/base/common/resources';
import { Disposable } from 'vs/base/common/lifecycle';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
25
import { VSBufferReadable, bufferToStream } from 'vs/base/common/buffer';
26
import { Readable } from 'stream';
27
import { createTextBufferFactoryFromStream } from 'vs/editor/common/model/textModel';
28
import { ITextSnapshot } from 'vs/editor/common/model';
B
Benjamin Pasero 已提交
29
import { nodeReadableToString, streamToNodeReadable, nodeStreamToVSBufferReadable } from 'vs/base/node/stream';
30
import { IUntitledTextEditorService } from 'vs/workbench/services/untitled/common/untitledTextEditorService';
31 32 33 34 35
import { ILifecycleService } from 'vs/platform/lifecycle/common/lifecycle';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IModelService } from 'vs/editor/common/services/modelService';
import { IWorkbenchEnvironmentService } from 'vs/workbench/services/environment/common/environmentService';
import { IDialogService, IFileDialogService } from 'vs/platform/dialogs/common/dialogs';
36
import { assign } from 'vs/base/common/objects';
37
import { IFilesConfigurationService } from 'vs/workbench/services/filesConfiguration/common/filesConfigurationService';
38
import { ITextModelService } from 'vs/editor/common/services/resolverService';
39
import { ICodeEditorService } from 'vs/editor/browser/services/codeEditorService';
40
import { IRemotePathService } from 'vs/workbench/services/path/common/remotePathService';
41
import { IWorkingCopyFileService } from 'vs/workbench/services/workingCopy/common/workingCopyFileService';
42
import { INativeWorkbenchEnvironmentService } from 'vs/workbench/services/environment/electron-browser/environmentService';
43
import { ILogService } from 'vs/platform/log/common/log';
44

45
export class NativeTextFileService extends AbstractTextFileService {
46

47 48
	constructor(
		@IFileService fileService: IFileService,
49
		@IUntitledTextEditorService untitledTextEditorService: IUntitledTextEditorService,
50 51 52
		@ILifecycleService lifecycleService: ILifecycleService,
		@IInstantiationService instantiationService: IInstantiationService,
		@IModelService modelService: IModelService,
53
		@IWorkbenchEnvironmentService protected environmentService: INativeWorkbenchEnvironmentService,
54 55
		@IDialogService dialogService: IDialogService,
		@IFileDialogService fileDialogService: IFileDialogService,
S
rename  
Sandeep Somavarapu 已提交
56
		@ITextResourceConfigurationService textResourceConfigurationService: ITextResourceConfigurationService,
57
		@IProductService private readonly productService: IProductService,
58
		@IFilesConfigurationService filesConfigurationService: IFilesConfigurationService,
59
		@ITextModelService textModelService: ITextModelService,
60
		@ICodeEditorService codeEditorService: ICodeEditorService,
61
		@IRemotePathService remotePathService: IRemotePathService,
62 63
		@IWorkingCopyFileService workingCopyFileService: IWorkingCopyFileService,
		@ILogService private readonly logService: ILogService
64
	) {
65
		super(fileService, untitledTextEditorService, lifecycleService, instantiationService, modelService, environmentService, dialogService, fileDialogService, textResourceConfigurationService, filesConfigurationService, textModelService, codeEditorService, remotePathService, workingCopyFileService);
66 67
	}

68
	private _encoding: EncodingOracle | undefined;
69
	get encoding(): EncodingOracle {
70
		if (!this._encoding) {
B
Benjamin Pasero 已提交
71
			this._encoding = this._register(this.instantiationService.createInstance(EncodingOracle));
72 73 74 75 76
		}

		return this._encoding;
	}

77
	async read(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileContent> {
78 79 80 81 82 83 84 85 86 87
		const [bufferStream, decoder] = await this.doRead(resource,
			assign({
				// optimization: since we know that the caller does not
				// care about buffering, we indicate this to the reader.
				// this reduces all the overhead the buffered reading
				// has (open, read, close) if the provider supports
				// unbuffered reading.
				preferUnbuffered: true
			}, options || Object.create(null))
		);
88

89 90 91
		return {
			...bufferStream,
			encoding: decoder.detected.encoding || UTF8,
B
Benjamin Pasero 已提交
92
			value: await nodeReadableToString(decoder.stream)
93 94
		};
	}
95

96 97 98 99 100 101 102
	async readStream(resource: URI, options?: IReadTextFileOptions): Promise<ITextFileStreamContent> {
		const [bufferStream, decoder] = await this.doRead(resource, options);

		return {
			...bufferStream,
			encoding: decoder.detected.encoding || UTF8,
			value: await createTextBufferFactoryFromStream(decoder.stream)
103
		};
104 105
	}

106
	private async doRead(resource: URI, options?: IReadTextFileOptions & { preferUnbuffered?: boolean }): Promise<[IFileStreamContent, IDecodeStreamResult]> {
107

108 109
		// ensure limits
		options = this.ensureLimits(options);
110

111 112 113 114 115 116 117 118 119 120 121
		// read stream raw (either buffered or unbuffered)
		let bufferStream: IFileStreamContent;
		if (options.preferUnbuffered) {
			const content = await this.fileService.readFile(resource, options);
			bufferStream = {
				...content,
				value: bufferToStream(content.value)
			};
		} else {
			bufferStream = await this.fileService.readFileStream(resource, options);
		}
122 123

		// read through encoding library
B
Benjamin Pasero 已提交
124
		const decoder = await toDecodeStream(streamToNodeReadable(bufferStream.value), {
B
Benjamin Pasero 已提交
125
			guessEncoding: options?.autoGuessEncoding || this.textResourceConfigurationService.getValue(resource, 'files.autoGuessEncoding'),
126
			overwriteEncoding: detectedEncoding => this.encoding.getReadEncoding(resource, options, detectedEncoding)
127 128 129
		});

		// validate binary
B
Benjamin Pasero 已提交
130
		if (options?.acceptTextOnly && decoder.detected.seemsBinary) {
131
			throw new TextFileOperationError(localize('fileBinaryError', "File seems to be binary and cannot be opened as text"), TextFileOperationResult.FILE_IS_BINARY, options);
132 133
		}

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
		return [bufferStream, decoder];
	}

	private ensureLimits(options?: IReadTextFileOptions): IReadTextFileOptions {
		let ensuredOptions: IReadTextFileOptions;
		if (!options) {
			ensuredOptions = Object.create(null);
		} else {
			ensuredOptions = options;
		}

		let ensuredLimits: { size?: number; memory?: number; };
		if (!ensuredOptions.limits) {
			ensuredLimits = Object.create(null);
			ensuredOptions.limits = ensuredLimits;
		} else {
			ensuredLimits = ensuredOptions.limits;
		}

		if (typeof ensuredLimits.size !== 'number') {
			ensuredLimits.size = MAX_FILE_SIZE;
		}

		if (typeof ensuredLimits.memory !== 'number') {
			ensuredLimits.memory = Math.max(typeof this.environmentService.args['max-memory'] === 'string' ? parseInt(this.environmentService.args['max-memory']) * 1024 * 1024 || 0 : 0, MAX_HEAP_SIZE);
		}

		return ensuredOptions;
162 163
	}

164 165 166 167 168 169 170 171 172 173 174 175 176 177
	protected async doCreate(resource: URI, value?: string, options?: ICreateFileOptions): Promise<IFileStatWithMetadata> {

		// check for encoding
		const { encoding, addBOM } = await this.encoding.getWriteEncoding(resource);

		// return to parent when encoding is standard
		if (encoding === UTF8 && !addBOM) {
			return super.doCreate(resource, value, options);
		}

		// otherwise create with encoding
		return this.fileService.createFile(resource, this.getEncodedReadable(value || '', encoding, addBOM), options);
	}

178 179 180 181
	async write(resource: URI, value: string | ITextSnapshot, options?: IWriteTextFileOptions): Promise<IFileStatWithMetadata> {

		// check for overwriteReadonly property (only supported for local file://)
		try {
B
Benjamin Pasero 已提交
182
			if (options?.overwriteReadonly && resource.scheme === Schemas.file && await exists(resource.fsPath)) {
183 184 185 186 187 188 189 190 191
				const fileStat = await stat(resource.fsPath);

				// try to change mode to writeable
				await chmod(resource.fsPath, fileStat.mode | 128);
			}
		} catch (error) {
			// ignore and simply retry the operation
		}

192
		// check for writeElevated property (only supported for local file://)
B
Benjamin Pasero 已提交
193
		if (options?.writeElevated && resource.scheme === Schemas.file) {
194 195 196
			return this.writeElevated(resource, value, options);
		}

197
		try {
198

199 200 201 202 203 204 205 206 207 208 209 210 211
			// check for encoding
			const { encoding, addBOM } = await this.encoding.getWriteEncoding(resource, options);

			// return to parent when encoding is standard
			if (encoding === UTF8 && !addBOM) {
				return await super.write(resource, value, options);
			}

			// otherwise save with encoding
			else {
				return await this.fileService.writeFile(resource, this.getEncodedReadable(value, encoding, addBOM), options);
			}
		} catch (error) {
212

213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
			// In case of permission denied, we need to check for readonly
			if ((<FileOperationError>error).fileOperationResult === FileOperationResult.FILE_PERMISSION_DENIED) {
				let isReadonly = false;
				try {
					const fileStat = await stat(resource.fsPath);
					if (!(fileStat.mode & 128)) {
						isReadonly = true;
					}
				} catch (error) {
					// ignore - rethrow original error
				}

				if (isReadonly) {
					throw new FileOperationError(localize('fileReadOnlyError', "File is Read Only"), FileOperationResult.FILE_READ_ONLY, options);
				}
			}

			throw error;
		}
232 233
	}

B
Benjamin Pasero 已提交
234
	private getEncodedReadable(value: string | ITextSnapshot, encoding: string, addBOM: boolean): VSBufferReadable {
235
		const readable = this.snapshotToNodeReadable(typeof value === 'string' ? stringToSnapshot(value) : value);
B
Benjamin Pasero 已提交
236 237 238 239
		const encoder = encodeStream(encoding, { addBOM });

		const encodedReadable = readable.pipe(encoder);

B
Benjamin Pasero 已提交
240
		return nodeStreamToVSBufferReadable(encodedReadable, addBOM && isUTFEncoding(encoding) ? { encoding } : undefined);
B
Benjamin Pasero 已提交
241 242
	}

243
	private snapshotToNodeReadable(snapshot: ITextSnapshot): Readable {
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
		return new Readable({
			read: function () {
				try {
					let chunk: string | null = null;
					let canPush = true;

					// Push all chunks as long as we can push and as long as
					// the underlying snapshot returns strings to us
					while (canPush && typeof (chunk = snapshot.read()) === 'string') {
						canPush = this.push(chunk);
					}

					// Signal EOS by pushing NULL
					if (typeof chunk !== 'string') {
						this.push(null);
					}
				} catch (error) {
					this.emit('error', error);
				}
			},
			encoding: UTF8 // very important, so that strings are passed around and not buffers!
		});
	}

268 269 270 271
	private async writeElevated(resource: URI, value: string | ITextSnapshot, options?: IWriteTextFileOptions): Promise<IFileStatWithMetadata> {

		// write into a tmp file first
		const tmpPath = join(tmpdir(), `code-elevated-${Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 6)}`);
272 273
		const { encoding, addBOM } = await this.encoding.getWriteEncoding(resource, options);
		await this.write(URI.file(tmpPath), value, { encoding: encoding === UTF8 && addBOM ? UTF8_with_bom : encoding });
274 275 276 277 278 279 280 281 282 283 284 285 286

		// sudo prompt copy
		await this.sudoPromptCopy(tmpPath, resource.fsPath, options);

		// clean up
		await rimraf(tmpPath);

		return this.fileService.resolve(resource, { resolveMetadata: true });
	}

	private async sudoPromptCopy(source: string, target: string, options?: IWriteTextFileOptions): Promise<void> {

		// load sudo-prompt module lazy
B
Benjamin Pasero 已提交
287
		const sudoPrompt = await import('sudo-prompt');
288 289 290

		return new Promise<void>((resolve, reject) => {
			const promptOptions = {
291 292
				name: this.productService.nameLong.replace('-', ''),
				icns: (isMacintosh && this.environmentService.isBuilt) ? join(dirname(this.environmentService.appRoot), `${this.productService.nameShort}.icns`) : undefined
293 294 295
			};

			const sudoCommand: string[] = [`"${this.environmentService.cliPath}"`];
B
Benjamin Pasero 已提交
296
			if (options?.overwriteReadonly) {
297 298 299 300 301 302
				sudoCommand.push('--file-chmod');
			}

			sudoCommand.push('--file-write', `"${source}"`, `"${target}"`);

			sudoPrompt.exec(sudoCommand.join(' '), promptOptions, (error: string, stdout: string, stderr: string) => {
303 304 305 306 307 308 309 310 311 312
				if (stdout) {
					this.logService.trace(`[sudo-prompt] received stdout: ${stdout}`);
				}

				if (stderr) {
					this.logService.trace(`[sudo-prompt] received stderr: ${stderr}`);
				}

				if (error) {
					reject(error);
313 314 315 316 317 318
				} else {
					resolve(undefined);
				}
			});
		});
	}
319 320
}

321 322 323 324 325 326
export interface IEncodingOverride {
	parent?: URI;
	extension?: string;
	encoding: string;
}

327
export class EncodingOracle extends Disposable implements IResourceEncodings {
B
Benjamin Pasero 已提交
328
	protected encodingOverrides: IEncodingOverride[];
329 330

	constructor(
S
rename  
Sandeep Somavarapu 已提交
331
		@ITextResourceConfigurationService private textResourceConfigurationService: ITextResourceConfigurationService,
332
		@IEnvironmentService private environmentService: IEnvironmentService,
333 334
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
		@IFileService private fileService: IFileService
335 336 337
	) {
		super();

B
Benjamin Pasero 已提交
338
		this.encodingOverrides = this.getDefaultEncodingOverrides();
339 340 341 342 343 344 345 346 347 348 349 350 351 352

		this.registerListeners();
	}

	private registerListeners(): void {

		// Workspace Folder Change
		this._register(this.contextService.onDidChangeWorkspaceFolders(() => this.encodingOverrides = this.getDefaultEncodingOverrides()));
	}

	private getDefaultEncodingOverrides(): IEncodingOverride[] {
		const defaultEncodingOverrides: IEncodingOverride[] = [];

		// Global settings
353
		defaultEncodingOverrides.push({ parent: this.environmentService.userRoamingDataHome, encoding: UTF8 });
354

355
		// Workspace files (via extension and via untitled workspaces location)
356
		defaultEncodingOverrides.push({ extension: WORKSPACE_EXTENSION, encoding: UTF8 });
357
		defaultEncodingOverrides.push({ parent: this.environmentService.untitledWorkspacesHome, encoding: UTF8 });
358 359 360 361 362 363 364 365 366 367

		// Folder Settings
		this.contextService.getWorkspace().folders.forEach(folder => {
			defaultEncodingOverrides.push({ parent: joinPath(folder.uri, '.vscode'), encoding: UTF8 });
		});

		return defaultEncodingOverrides;
	}

	async getWriteEncoding(resource: URI, options?: IWriteTextFileOptions): Promise<{ encoding: string, addBOM: boolean }> {
368
		const { encoding, hasBOM } = this.getPreferredWriteEncoding(resource, options ? options.encoding : undefined);
369 370 371 372 373 374

		// Some encodings come with a BOM automatically
		if (hasBOM) {
			return { encoding, addBOM: true };
		}

375 376
		// Ensure that we preserve an existing BOM if found for UTF8
		// unless we are instructed to overwrite the encoding
B
Benjamin Pasero 已提交
377
		const overwriteEncoding = options?.overwriteEncoding;
378 379
		if (!overwriteEncoding && encoding === UTF8) {
			try {
B
Benjamin Pasero 已提交
380
				const buffer = (await this.fileService.readFile(resource, { length: UTF8_BOM.length })).value;
B
Benjamin Pasero 已提交
381
				if (detectEncodingByBOMFromBuffer(buffer, buffer.byteLength) === UTF8_with_bom) {
382 383 384 385 386
					return { encoding, addBOM: true };
				}
			} catch (error) {
				// ignore - file might not exist
			}
387 388 389 390 391
		}

		return { encoding, addBOM: false };
	}

392
	getPreferredWriteEncoding(resource: URI, preferredEncoding?: string): IResourceEncoding {
393 394 395 396 397 398 399 400
		const resourceEncoding = this.getEncodingForResource(resource, preferredEncoding);

		return {
			encoding: resourceEncoding,
			hasBOM: resourceEncoding === UTF16be || resourceEncoding === UTF16le || resourceEncoding === UTF8_with_bom // enforce BOM for certain encodings
		};
	}

401
	getReadEncoding(resource: URI, options: IReadTextFileOptions | undefined, detectedEncoding: string | null): string {
402 403 404
		let preferredEncoding: string | undefined;

		// Encoding passed in as option
B
Benjamin Pasero 已提交
405
		if (options?.encoding) {
B
Benjamin Pasero 已提交
406
			if (detectedEncoding === UTF8_with_bom && options.encoding === UTF8) {
407 408 409 410 411 412 413
				preferredEncoding = 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
			}
		}

		// Encoding detected
414
		else if (detectedEncoding) {
B
Benjamin Pasero 已提交
415
			preferredEncoding = detectedEncoding;
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
		}

		// Encoding configured
		else if (this.textResourceConfigurationService.getValue(resource, 'files.encoding') === UTF8_with_bom) {
			preferredEncoding = UTF8; // if we did not detect UTF 8 BOM before, this can only be UTF 8 then
		}

		return this.getEncodingForResource(resource, preferredEncoding);
	}

	private getEncodingForResource(resource: URI, preferredEncoding?: string): string {
		let fileEncoding: string;

		const override = this.getEncodingOverride(resource);
		if (override) {
			fileEncoding = override; // encoding override always wins
		} else if (preferredEncoding) {
			fileEncoding = preferredEncoding; // preferred encoding comes second
		} else {
			fileEncoding = this.textResourceConfigurationService.getValue(resource, 'files.encoding'); // and last we check for settings
		}

		if (!fileEncoding || !encodingExists(fileEncoding)) {
			fileEncoding = UTF8; // the default is UTF 8
		}

		return fileEncoding;
	}

	private getEncodingOverride(resource: URI): string | undefined {
		if (this.encodingOverrides && this.encodingOverrides.length) {
			for (const override of this.encodingOverrides) {

				// check if the resource is child of encoding override path
450
				if (override.parent && isEqualOrParent(resource, override.parent)) {
451 452 453 454 455 456 457 458 459 460 461 462 463 464
					return override.encoding;
				}

				// check if the resource extension is equal to encoding override
				if (override.extension && extname(resource) === `.${override.extension}`) {
					return override.encoding;
				}
			}
		}

		return undefined;
	}
}

465
registerSingleton(ITextFileService, NativeTextFileService);