env.ts 12.1 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6 7 8 9 10 11
/*---------------------------------------------------------------------------------------------
 *  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 crypto = require('crypto');
import fs = require('fs');
import path = require('path');
import os = require('os');
12
import {app} from 'electron';
E
Erich Gamma 已提交
13 14
import arrays = require('vs/base/common/arrays');
import strings = require('vs/base/common/strings');
15
import paths = require('vs/base/common/paths');
E
Erich Gamma 已提交
16 17 18
import platform = require('vs/base/common/platform');
import uri from 'vs/base/common/uri';
import types = require('vs/base/common/types');
J
Joao Moreno 已提交
19
import {ServiceIdentifier, createDecorator} from 'vs/platform/instantiation/common/instantiation';
J
Joao Moreno 已提交
20
import product, {IProductConfiguration} from './product';
J
Joao Moreno 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

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

export interface ICommandLineArguments {
	verboseLogging: boolean;
	debugExtensionHostPort: number;
	debugBrkExtensionHost: boolean;
	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 已提交
44 45
}

J
renames  
Joao Moreno 已提交
46
export const IEnvironmentService = createDecorator<IEnvironmentService>('environmentService');
J
Joao Moreno 已提交
47

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

J
renames  
Joao Moreno 已提交
69
export class EnvService implements IEnvironmentService {
J
Joao Moreno 已提交
70

J
renames  
Joao Moreno 已提交
71
	serviceId = IEnvironmentService;
J
Joao Moreno 已提交
72

J
Joao Moreno 已提交
73
	private _cliArgs: ICommandLineArguments;
J
Joao Moreno 已提交
74 75
	get cliArgs(): ICommandLineArguments { return this._cliArgs; }

J
Joao Moreno 已提交
76
	private _userExtensionsHome: string;
J
Joao Moreno 已提交
77 78
	get userExtensionsHome(): string { return this._userExtensionsHome; }

J
Joao Moreno 已提交
79
	private _isTestingFromCli: boolean;
J
Joao Moreno 已提交
80 81 82 83
	get isTestingFromCli(): boolean { return this._isTestingFromCli; }

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

J
Joao Moreno 已提交
84 85 86
	get product(): IProductConfiguration { return product; }
	get updateUrl(): string { return product.updateUrl; }
	get quality(): string { return product.quality; }
J
Joao Moreno 已提交
87 88 89 90

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

J
Joao Moreno 已提交
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
	private _appRoot: string;
	get appRoot(): string { return this._appRoot; }

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

	private _version: string;
	get version(): string { return this._version; }

	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 已提交
112 113 114 115 116
	private _mainIPCHandle: string;
	get mainIPCHandle(): string { return this._mainIPCHandle; }

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

J
Joao Moreno 已提交
118
	constructor() {
J
Joao Moreno 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132
		this._appRoot = path.dirname(uri.parse(require.toUrl('')).fsPath);
		this._currentWorkingDirectory = process.env['VSCODE_CWD'] || process.cwd();
		this._version = app.getVersion();
		this._appHome = app.getPath('userData');
		this._appSettingsHome = path.join(this._appHome, 'User');

		// TODO move out of here!
		if (!fs.existsSync(this._appSettingsHome)) {
			fs.mkdirSync(this._appSettingsHome);
		}

		this._appSettingsPath = path.join(this._appSettingsHome, 'settings.json');
		this._appKeybindingsPath = path.join(this._appSettingsHome, 'keybindings.json');

J
Joao Moreno 已提交
133 134 135
		// Remove the Electron executable
		let [, ...args] = process.argv;

J
Joao Moreno 已提交
136
		// If dev, remove the first argument: it's the app location
J
Joao Moreno 已提交
137
		if (!this.isBuilt) {
J
Joao Moreno 已提交
138 139 140 141
			[, ...args] = args;
		}

		// Finally, prepend any extra arguments from the 'argv' file
J
Joao Moreno 已提交
142 143
		if (fs.existsSync(path.join(this._appRoot, 'argv'))) {
			const extraargs: string[] = JSON.parse(fs.readFileSync(path.join(this._appRoot, 'argv'), 'utf8'));
J
Joao Moreno 已提交
144 145 146 147 148 149 150 151 152 153 154
			args = [...extraargs, ...args];
		}

		const debugBrkExtensionHostPort = parseNumber(args, '--debugBrkPluginHost', 5870);
		let debugExtensionHostPort: number;
		let debugBrkExtensionHost: boolean;

		if (debugBrkExtensionHostPort) {
			debugExtensionHostPort = debugBrkExtensionHostPort;
			debugBrkExtensionHost = true;
		} else {
J
Joao Moreno 已提交
155
			debugExtensionHostPort = parseNumber(args, '--debugPluginHost', 5870, this.isBuilt ? void 0 : 5870);
J
Joao Moreno 已提交
156 157
		}

J
Joao Moreno 已提交
158 159
		const opts = parseOpts(args);
		const gotoLineMode = !!opts['g'] || !!opts['goto'];
J
Joao Moreno 已提交
160
		const pathArguments = parsePathArguments(this._currentWorkingDirectory, args, gotoLineMode);
J
Joao Moreno 已提交
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181

		this._cliArgs = Object.freeze({
			pathArguments: pathArguments,
			programStart: parseNumber(args, '--timestamp', 0, 0),
			enablePerformance: !!opts['p'],
			verboseLogging: !!opts['verbose'],
			debugExtensionHostPort: debugExtensionHostPort,
			debugBrkExtensionHost: debugBrkExtensionHost,
			logExtensionHostCommunication: !!opts['logExtensionHostCommunication'],
			openNewWindow: !!opts['n'] || !!opts['new-window'],
			openInSameWindow: !!opts['r'] || !!opts['reuse-window'],
			gotoLineMode: gotoLineMode,
			diffMode: (!!opts['d'] || !!opts['diff']) && pathArguments.length === 2,
			extensionsHomePath: normalizePath(parseString(args, '--extensionHomePath')),
			extensionDevelopmentPath: normalizePath(parseString(args, '--extensionDevelopmentPath')),
			extensionTestsPath: normalizePath(parseString(args, '--extensionTestsPath')),
			disableExtensions: !!opts['disableExtensions'] || !!opts['disable-extensions'],
			locale: parseString(args, '--locale'),
			waitForWindowClose: !!opts['w'] || !!opts['wait']
		});

J
Joao Moreno 已提交
182 183
		this._isTestingFromCli = this.cliArgs.extensionTestsPath && !this.cliArgs.debugBrkExtensionHost;

J
Joao Moreno 已提交
184
		this._userHome = path.join(app.getPath('home'), product.dataFolderName);
J
Joao Moreno 已提交
185 186

		// TODO move out of here!
J
Joao Moreno 已提交
187 188
		if (!fs.existsSync(this._userHome)) {
			fs.mkdirSync(this._userHome);
J
Joao Moreno 已提交
189 190
		}

J
Joao Moreno 已提交
191 192 193 194 195 196 197 198 199
		this._userExtensionsHome = this.cliArgs.extensionsHomePath || path.join(this.userHome, 'extensions');

		// TODO move out of here!
		if (!fs.existsSync(this._userExtensionsHome)) {
			fs.mkdirSync(this._userExtensionsHome);
		}

		this._mainIPCHandle = this.getMainIPCHandle();
		this._sharedIPCHandle = this.getSharedIPCHandle();
J
Joao Moreno 已提交
200
	}
J
Joao Moreno 已提交
201

J
Joao Moreno 已提交
202 203
	private getMainIPCHandle(): string {
		return this.getIPCHandleName() + (process.platform === 'win32' ? '-sock' : '.sock');
J
Joao Moreno 已提交
204 205
	}

J
Joao Moreno 已提交
206 207
	private getSharedIPCHandle(): string {
		return this.getIPCHandleName() + '-shared' + (process.platform === 'win32' ? '-sock' : '.sock');
J
Joao Moreno 已提交
208 209
	}

J
Joao Moreno 已提交
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
	private getIPCHandleName(): string {
		let handleName = app.getName();

		if (!this.isBuilt) {
			handleName += '-dev';
		}

		// 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) {
			handleName += ('-' + userId);
		}

		if (process.platform === 'win32') {
			return '\\\\.\\pipe\\' + handleName;
		}

		return path.join(os.tmpdir(), handleName);
	}

	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 已提交
245 246
	}
}
E
Erich Gamma 已提交
247 248 249 250 251 252 253 254 255 256

type OptionBag = { [opt: string]: boolean; };

function parseOpts(argv: string[]): OptionBag {
	return argv
		.filter(a => /^-/.test(a))
		.map(a => a.replace(/^-*/, ''))
		.reduce((r, a) => { r[a] = true; return r; }, <OptionBag>{});
}

J
Joao Moreno 已提交
257
function parsePathArguments(cwd: string, argv: string[], gotoLineMode?: boolean): string[] {
258 259 260 261 262 263 264 265 266 267 268 269 270
	return arrays.coalesce(							// no invalid paths
		arrays.distinct(							// no duplicates
			argv.filter(a => !(/^-/.test(a))) 		// arguments without leading "-"
				.map((arg) => {
					let pathCandidate = arg;

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

					if (pathCandidate) {
J
Joao Moreno 已提交
271
						pathCandidate = preparePath(cwd, pathCandidate);
272 273 274 275 276 277 278 279
					}

					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
J
Joao Moreno 已提交
280
						realPath = path.normalize(path.isAbsolute(pathCandidate) ? pathCandidate : path.join(cwd, pathCandidate));
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
					}

					if (!paths.isValidBasename(path.basename(realPath))) {
						return null; // do not allow invalid file names
					}

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

					return realPath;
				}),
			(element) => {
				return element && (platform.isWindows || platform.isMacintosh) ? element.toLowerCase() : element; // only linux is case sensitive on the fs
			}
		)
	);
}
E
Erich Gamma 已提交
300

J
Joao Moreno 已提交
301
function preparePath(cwd: string, p: string): string {
B
polish  
Benjamin Pasero 已提交
302 303

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

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

311
	if (platform.isWindows) {
B
polish  
Benjamin Pasero 已提交
312 313

		// Resolve the path against cwd if it is relative
J
Joao Moreno 已提交
314
		p = path.resolve(cwd, p);
B
polish  
Benjamin Pasero 已提交
315 316 317

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

B
polish  
Benjamin Pasero 已提交
320
	return p;
E
Erich Gamma 已提交
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
}

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

function parseNumber(argv: string[], key: string, defaultValue?: number, fallbackValue?: number): number {
	let value: number;

	for (let i = 0; i < argv.length; i++) {
		let segments = argv[i].split('=');
		if (segments[0] === key) {
			value = Number(segments[1]) || defaultValue;
			break;
		}
	}

	return types.isNumber(value) ? value : fallbackValue;
}

function parseString(argv: string[], key: string, defaultValue?: string, fallbackValue?: string): string {
	let value: string;

	for (let i = 0; i < argv.length; i++) {
		let segments = argv[i].split('=');
		if (segments[0] === key) {
			value = String(segments[1]) || defaultValue;
			break;
		}
	}

	return types.isString(value) ? strings.trim(value, '"') : fallbackValue;
}

export function getPlatformIdentifier(): string {
	if (process.platform === 'linux') {
357
		return `linux-${process.arch}`;
E
Erich Gamma 已提交
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
	}

	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 已提交
391
	};
E
Erich Gamma 已提交
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
}

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(':');
}