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

'use strict';

J
Joao Moreno 已提交
8
import * as crypto from 'crypto';
B
Benjamin Pasero 已提交
9
import * as fs from 'original-fs';
J
Joao Moreno 已提交
10
import * as path from 'path';
J
Joao Moreno 已提交
11
import * as os from 'os';
J
Joao Moreno 已提交
12 13 14 15 16 17 18
import { app } from 'electron';
import * as arrays from 'vs/base/common/arrays';
import * as strings from 'vs/base/common/strings';
import * as paths from 'vs/base/common/paths';
import * as platform from 'vs/base/common/platform';
import URI from 'vs/base/common/uri';
import * as types from 'vs/base/common/types';
19
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
J
Joao Moreno 已提交
20
import product, { IProductConfiguration } from 'vs/platform/product';
21
import { parseArgs } from 'vs/code/node/argv';
J
Joao Moreno 已提交
22
import pkg from 'vs/platform/package';
J
Joao Moreno 已提交
23 24 25 26 27 28 29 30 31

export interface IProcessEnvironment {
	[key: string]: string;
}

export interface ICommandLineArguments {
	verboseLogging: boolean;
	debugExtensionHostPort: number;
	debugBrkExtensionHost: boolean;
32
	debugBrkFileWatcherPort: number;
J
Joao Moreno 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46
	logExtensionHostCommunication: boolean;
	disableExtensions: boolean;
	extensionsHomePath: string;
	extensionDevelopmentPath: string;
	extensionTestsPath: string;
	programStart: number;
	pathArguments?: string[];
	enablePerformance?: boolean;
	openNewWindow?: boolean;
	openInSameWindow?: boolean;
	gotoLineMode?: boolean;
	diffMode?: boolean;
	locale?: string;
	waitForWindowClose?: boolean;
J
Joao Moreno 已提交
47 48
}

J
Joao Moreno 已提交
49
export const IEnvironmentService = createDecorator<IEnvironmentService>('mainEnvironmentService');
J
Joao Moreno 已提交
50

J
renames  
Joao Moreno 已提交
51
export interface IEnvironmentService {
52
	_serviceBrand: any;
J
Joao Moreno 已提交
53 54 55
	cliArgs: ICommandLineArguments;
	userExtensionsHome: string;
	isTestingFromCli: boolean;
J
Joao Moreno 已提交
56 57 58 59 60
	isBuilt: boolean;
	product: IProductConfiguration;
	updateUrl: string;
	quality: string;
	userHome: string;
J
Joao Moreno 已提交
61 62 63 64 65 66
	appRoot: string;
	currentWorkingDirectory: string;
	appHome: string;
	appSettingsHome: string;
	appSettingsPath: string;
	appKeybindingsPath: string;
J
Joao Moreno 已提交
67 68
	mainIPCHandle: string;
	sharedIPCHandle: string;
J
Joao Moreno 已提交
69 70
}

J
Joao Moreno 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84
function getNumericValue(value: string, defaultValue: number, fallback: number = void 0) {
	const numericValue = parseInt(value);

	if (types.isNumber(numericValue)) {
		return numericValue;
	}

	if (value) {
		return defaultValue;
	}

	return fallback;
}

J
renames  
Joao Moreno 已提交
85
export class EnvService implements IEnvironmentService {
J
Joao Moreno 已提交
86

87
	_serviceBrand: any;
J
Joao Moreno 已提交
88

J
Joao Moreno 已提交
89
	private _cliArgs: ICommandLineArguments;
J
Joao Moreno 已提交
90 91
	get cliArgs(): ICommandLineArguments { return this._cliArgs; }

J
Joao Moreno 已提交
92
	private _userExtensionsHome: string;
J
Joao Moreno 已提交
93 94
	get userExtensionsHome(): string { return this._userExtensionsHome; }

J
Joao Moreno 已提交
95
	private _isTestingFromCli: boolean;
J
Joao Moreno 已提交
96 97 98 99
	get isTestingFromCli(): boolean { return this._isTestingFromCli; }

	get isBuilt(): boolean { return !process.env['VSCODE_DEV']; }

J
Joao Moreno 已提交
100 101 102
	get product(): IProductConfiguration { return product; }
	get updateUrl(): string { return product.updateUrl; }
	get quality(): string { return product.quality; }
J
Joao Moreno 已提交
103 104 105 106

	private _userHome: string;
	get userHome(): string { return this._userHome; }

J
Joao Moreno 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
	private _appRoot: string;
	get appRoot(): string { return this._appRoot; }

	private _currentWorkingDirectory: string;
	get currentWorkingDirectory(): string { return this._currentWorkingDirectory; }

	private _appHome: string;
	get appHome(): string { return this._appHome; }

	private _appSettingsHome: string;
	get appSettingsHome(): string { return this._appSettingsHome; }

	private _appSettingsPath: string;
	get appSettingsPath(): string { return this._appSettingsPath; }

	private _appKeybindingsPath: string;
	get appKeybindingsPath(): string { return this._appKeybindingsPath; }

J
Joao Moreno 已提交
125 126 127 128 129
	private _mainIPCHandle: string;
	get mainIPCHandle(): string { return this._mainIPCHandle; }

	private _sharedIPCHandle: string;
	get sharedIPCHandle(): string { return this._sharedIPCHandle; }
J
Joao Moreno 已提交
130

J
Joao Moreno 已提交
131
	constructor() {
J
Joao Moreno 已提交
132
		this._appRoot = path.dirname(URI.parse(require.toUrl('')).fsPath);
J
Joao Moreno 已提交
133 134 135 136 137 138
		this._currentWorkingDirectory = process.env['VSCODE_CWD'] || process.cwd();
		this._appHome = app.getPath('userData');
		this._appSettingsHome = path.join(this._appHome, 'User');
		this._appSettingsPath = path.join(this._appSettingsHome, 'settings.json');
		this._appKeybindingsPath = path.join(this._appSettingsHome, 'keybindings.json');

J
Joao Moreno 已提交
139 140 141
		// Remove the Electron executable
		let [, ...args] = process.argv;

J
Joao Moreno 已提交
142
		// If dev, remove the first non-option argument: it's the app location
J
Joao Moreno 已提交
143
		if (!this.isBuilt) {
J
Joao Moreno 已提交
144 145 146 147 148
			const index = arrays.firstIndex(args, a => !/^-/.test(a));

			if (index > -1) {
				args.splice(index, 1);
			}
J
Joao Moreno 已提交
149 150 151
		}

		// Finally, prepend any extra arguments from the 'argv' file
J
Joao Moreno 已提交
152 153
		if (fs.existsSync(path.join(this._appRoot, 'argv'))) {
			const extraargs: string[] = JSON.parse(fs.readFileSync(path.join(this._appRoot, 'argv'), 'utf8'));
J
Joao Moreno 已提交
154 155 156
			args = [...extraargs, ...args];
		}

J
Joao Moreno 已提交
157
		const argv = parseArgs(args);
J
Joao Moreno 已提交
158

J
Joao Moreno 已提交
159 160
		const debugBrkExtensionHostPort = getNumericValue(argv.debugBrkPluginHost, 5870);
		const debugExtensionHostPort = getNumericValue(argv.debugPluginHost, 5870, this.isBuilt ? void 0 : 5870);
J
Joao Moreno 已提交
161
		const pathArguments = parsePathArguments(this._currentWorkingDirectory, argv._, argv.goto);
J
Joao Moreno 已提交
162
		const timestamp = parseInt(argv.timestamp);
163
		const debugBrkFileWatcherPort = getNumericValue(argv.debugBrkFileWatcherPort, void 0);
J
Joao Moreno 已提交
164 165 166

		this._cliArgs = Object.freeze({
			pathArguments: pathArguments,
J
Joao Moreno 已提交
167
			programStart: types.isNumber(timestamp) ? timestamp : 0,
J
Joao Moreno 已提交
168 169
			enablePerformance: argv.performance,
			verboseLogging: argv.verbose,
J
Joao Moreno 已提交
170 171
			debugExtensionHostPort: debugBrkExtensionHostPort || debugExtensionHostPort,
			debugBrkExtensionHost: !!debugBrkExtensionHostPort,
J
Joao Moreno 已提交
172
			logExtensionHostCommunication: argv.logExtensionHostCommunication,
173
			debugBrkFileWatcherPort: debugBrkFileWatcherPort,
J
Joao Moreno 已提交
174 175 176 177
			openNewWindow: argv['new-window'],
			openInSameWindow: argv['reuse-window'],
			gotoLineMode: argv.goto,
			diffMode: argv.diff && pathArguments.length === 2,
J
Joao Moreno 已提交
178 179 180
			extensionsHomePath: normalizePath(argv.extensionHomePath),
			extensionDevelopmentPath: normalizePath(argv.extensionDevelopmentPath),
			extensionTestsPath: normalizePath(argv.extensionTestsPath),
J
Joao Moreno 已提交
181
			disableExtensions: argv['disable-extensions'],
J
Joao Moreno 已提交
182
			locale: argv.locale,
J
Joao Moreno 已提交
183
			waitForWindowClose: argv.wait
J
Joao Moreno 已提交
184 185
		});

J
Joao Moreno 已提交
186
		this._isTestingFromCli = this.cliArgs.extensionTestsPath && !this.cliArgs.debugBrkExtensionHost;
J
Joao Moreno 已提交
187
		this._userHome = path.join(os.homedir(), product.dataFolderName);
J
Joao Moreno 已提交
188
		this._userExtensionsHome = this.cliArgs.extensionsHomePath || path.join(this._userHome, 'extensions');
J
Joao Moreno 已提交
189

J
Joao Moreno 已提交
190 191
		const prefix = this.getIPCHandleBaseName();
		const suffix = process.platform === 'win32' ? '-sock' : '.sock';
J
Joao Moreno 已提交
192

J
Joao Moreno 已提交
193 194
		this._mainIPCHandle = `${ prefix }-${ pkg.version }${ suffix }`;
		this._sharedIPCHandle = `${ prefix }-${ pkg.version }-shared${ suffix }`;
J
Joao Moreno 已提交
195 196
	}

J
Joao Moreno 已提交
197 198
	private getIPCHandleBaseName(): string {
		let name = pkg.name;
J
Joao Moreno 已提交
199 200 201 202 203

		// Support to run VS Code multiple times as different user
		// by making the socket unique over the logged in user
		let userId = EnvService.getUniqueUserId();
		if (userId) {
J
Joao Moreno 已提交
204
			name += `-${ userId }`;
J
Joao Moreno 已提交
205 206 207
		}

		if (process.platform === 'win32') {
J
Joao Moreno 已提交
208
			return `\\\\.\\pipe\\${ name }`;
J
Joao Moreno 已提交
209 210
		}

J
Joao Moreno 已提交
211
		return path.join(os.tmpdir(), name);
J
Joao Moreno 已提交
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
	}

	private static getUniqueUserId(): string {
		let username: string;
		if (platform.isWindows) {
			username = process.env.USERNAME;
		} else {
			username = process.env.USER;
		}

		if (!username) {
			return ''; // fail gracefully if there is no user name
		}

		// use sha256 to ensure the userid value can be used in filenames and are unique
		return crypto.createHash('sha256').update(username).digest('hex').substr(0, 6);
J
Joao Moreno 已提交
228 229
	}
}
E
Erich Gamma 已提交
230

J
Joao Moreno 已提交
231 232
function parsePathArguments(cwd: string, args: string[], gotoLineMode?: boolean): string[] {
	const result = args.map(arg => {
B
Benjamin Pasero 已提交
233 234 235 236
		if (typeof arg !== 'string') {
			return null; // TODO@Ben workaround for https://github.com/Microsoft/vscode/issues/7498
		}

J
Joao Moreno 已提交
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
		let pathCandidate = arg;

		let parsedPath: IParsedPath;
		if (gotoLineMode) {
			parsedPath = parseLineAndColumnAware(arg);
			pathCandidate = parsedPath.path;
		}

		if (pathCandidate) {
			pathCandidate = preparePath(cwd, pathCandidate);
		}

		let realPath: string;
		try {
			realPath = fs.realpathSync(pathCandidate);
		} catch (error) {
			// in case of an error, assume the user wants to create this file
			// if the path is relative, we join it to the cwd
			realPath = path.normalize(path.isAbsolute(pathCandidate) ? pathCandidate : path.join(cwd, pathCandidate));
		}

258 259
		const basename = path.basename(realPath);
		if (basename /* can be empty if code is opened on root */ && !paths.isValidBasename(basename)) {
J
Joao Moreno 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
			return null; // do not allow invalid file names
		}

		if (gotoLineMode) {
			parsedPath.path = realPath;
			return toLineAndColumnPath(parsedPath);
		}

		return realPath;
	});

	const caseInsensitive = platform.isWindows || platform.isMacintosh;
	const distinct = arrays.distinct(result, e => e && caseInsensitive ? e.toLowerCase() : e);

	return arrays.coalesce(distinct);
275
}
E
Erich Gamma 已提交
276

J
Joao Moreno 已提交
277
function preparePath(cwd: string, p: string): string {
B
polish  
Benjamin Pasero 已提交
278 279

	// Trim trailing quotes
280
	if (platform.isWindows) {
B
polish  
Benjamin Pasero 已提交
281
		p = strings.rtrim(p, '"'); // https://github.com/Microsoft/vscode/issues/1498
282
	}
283

284
	// Trim whitespaces
B
polish  
Benjamin Pasero 已提交
285
	p = strings.trim(strings.trim(p, ' '), '\t');
E
Erich Gamma 已提交
286

287
	if (platform.isWindows) {
B
polish  
Benjamin Pasero 已提交
288 289

		// Resolve the path against cwd if it is relative
J
Joao Moreno 已提交
290
		p = path.resolve(cwd, p);
B
polish  
Benjamin Pasero 已提交
291 292 293

		// Trim trailing '.' chars on Windows to prevent invalid file names
		p = strings.rtrim(p, '.');
294 295
	}

B
polish  
Benjamin Pasero 已提交
296
	return p;
E
Erich Gamma 已提交
297 298 299 300 301 302 303 304
}

function normalizePath(p?: string): string {
	return p ? path.normalize(p) : p;
}

export function getPlatformIdentifier(): string {
	if (process.platform === 'linux') {
305
		return `linux-${process.arch}`;
E
Erich Gamma 已提交
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
	}

	return process.platform;
}

export interface IParsedPath {
	path: string;
	line?: number;
	column?: number;
}

export function parseLineAndColumnAware(rawPath: string): IParsedPath {
	let segments = rawPath.split(':'); // C:\file.txt:<line>:<column>

	let path: string;
	let line: number = null;
	let column: number = null;

	segments.forEach(segment => {
		let segmentAsNumber = Number(segment);
		if (!types.isNumber(segmentAsNumber)) {
			path = !!path ? [path, segment].join(':') : segment; // a colon can well be part of a path (e.g. C:\...)
		} else if (line === null) {
			line = segmentAsNumber;
		} else if (column === null) {
			column = segmentAsNumber;
		}
	});

	return {
		path: path,
		line: line !== null ? line : void 0,
		column: column !== null ? column : line !== null ? 1 : void 0 // if we have a line, make sure column is also set
B
Benjamin Pasero 已提交
339
	};
E
Erich Gamma 已提交
340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
}

export function toLineAndColumnPath(parsedPath: IParsedPath): string {
	let segments = [parsedPath.path];

	if (types.isNumber(parsedPath.line)) {
		segments.push(String(parsedPath.line));
	}

	if (types.isNumber(parsedPath.column)) {
		segments.push(String(parsedPath.column));
	}

	return segments.join(':');
}