argv.ts 14.0 KB
Newer Older
J
Joao Moreno 已提交
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.
 *--------------------------------------------------------------------------------------------*/

D
Daniel Imms 已提交
6
import * as minimist from 'minimist';
J
Joao Moreno 已提交
7
import { localize } from 'vs/nls';
8
import { isWindows } from 'vs/base/common/platform';
9
import { NativeParsedArgs } from 'vs/platform/environment/common/argv';
J
Joao Moreno 已提交
10

J
Joao Moreno 已提交
11
/**
M
Martin Aeschlimann 已提交
12
 * This code is also used by standalone cli's. Avoid adding any other dependencies.
J
Joao Moreno 已提交
13
 */
14 15 16 17 18
const helpCategories = {
	o: localize('optionsUpperCase', "Options"),
	e: localize('extensionsManagement', "Extensions Management"),
	t: localize('troubleshooting', "Troubleshooting")
};
J
Joao Moreno 已提交
19

20 21
export interface Option<OptionType> {
	type: OptionType;
M
Martin Aeschlimann 已提交
22
	alias?: string;
23
	deprecates?: string; // old deprecated id
M
Martin Aeschlimann 已提交
24 25
	args?: string | string[];
	description?: string;
26
	cat?: keyof typeof helpCategories;
M
Martin Aeschlimann 已提交
27
}
28 29

export type OptionDescriptions<T> = {
M
Martin Aeschlimann 已提交
30
	[P in keyof T]: Option<OptionTypeName<T[P]>>;
31 32
};

M
Martin Aeschlimann 已提交
33
type OptionTypeName<T> =
34 35 36 37 38 39
	T extends boolean ? 'boolean' :
	T extends string ? 'string' :
	T extends string[] ? 'string[]' :
	T extends undefined ? 'undefined' :
	'unknown';

40
export const OPTIONS: OptionDescriptions<Required<NativeParsedArgs>> = {
41 42 43 44 45 46
	'diff': { type: 'boolean', cat: 'o', alias: 'd', args: ['file', 'file'], description: localize('diff', "Compare two files with each other.") },
	'add': { type: 'boolean', cat: 'o', alias: 'a', args: 'folder', description: localize('add', "Add folder(s) to the last active window.") },
	'goto': { type: 'boolean', cat: 'o', alias: 'g', args: 'file:line[:character]', description: localize('goto', "Open a file at the path on the specified line and character position.") },
	'new-window': { type: 'boolean', cat: 'o', alias: 'n', description: localize('newWindow', "Force to open a new window.") },
	'reuse-window': { type: 'boolean', cat: 'o', alias: 'r', description: localize('reuseWindow', "Force to open a file or folder in an already opened window.") },
	'wait': { type: 'boolean', cat: 'o', alias: 'w', description: localize('wait', "Wait for the files to be closed before returning.") },
M
Martin Aeschlimann 已提交
47
	'waitMarkerFilePath': { type: 'string' },
48 49
	'locale': { type: 'string', cat: 'o', args: 'locale', description: localize('locale', "The locale to use (e.g. en-US or zh-TW).") },
	'user-data-dir': { type: 'string', cat: 'o', args: 'dir', description: localize('userDataDir', "Specifies the directory that user data is kept in. Can be used to open multiple distinct instances of Code.") },
B
Benjamin Pasero 已提交
50
	'help': { type: 'boolean', cat: 'o', alias: 'h', description: localize('help', "Print usage.") },
51 52

	'extensions-dir': { type: 'string', deprecates: 'extensionHomePath', cat: 'e', args: 'dir', description: localize('extensionHomePath', "Set the root path for extensions.") },
53
	'extensions-download-dir': { type: 'string' },
M
Martin Aeschlimann 已提交
54
	'builtin-extensions-dir': { type: 'string' },
55
	'list-extensions': { type: 'boolean', cat: 'e', description: localize('listExtensions', "List the installed extensions.") },
56 57
	'show-versions': { type: 'boolean', cat: 'e', description: localize('showVersions', "Show versions of installed extensions, when using --list-extensions.") },
	'category': { type: 'string', cat: 'e', description: localize('category', "Filters installed extensions by provided category, when using --list-extensions.") },
S
Sandeep Somavarapu 已提交
58
	'install-extension': { type: 'string[]', cat: 'e', args: 'extension-id[@version] | path-to-vsix', description: localize('installExtension', "Installs or updates the extension. The identifier of an extension is always `${publisher}.${name}`. Use `--force` argument to update to latest version. To install a specific version provide `@${version}`. For example: 'vscode.csharp@1.2.3'.") },
59 60 61
	'uninstall-extension': { type: 'string[]', cat: 'e', args: 'extension-id', description: localize('uninstallExtension', "Uninstalls an extension.") },
	'enable-proposed-api': { type: 'string[]', cat: 'e', args: 'extension-id', description: localize('experimentalApis', "Enables proposed API features for extensions. Can receive one or more extension IDs to enable individually.") },

B
Benjamin Pasero 已提交
62
	'version': { type: 'boolean', cat: 't', alias: 'v', description: localize('version', "Print version.") },
63 64 65 66
	'verbose': { type: 'boolean', cat: 't', description: localize('verbose', "Print verbose output (implies --wait).") },
	'log': { type: 'string', cat: 't', args: 'level', description: localize('log', "Log level to use. Default is 'info'. Allowed values are 'critical', 'error', 'warn', 'info', 'debug', 'trace', 'off'.") },
	'status': { type: 'boolean', alias: 's', cat: 't', description: localize('status', "Print process usage and diagnostics information.") },
	'prof-startup': { type: 'boolean', cat: 't', description: localize('prof-startup', "Run CPU profiler during startup") },
67
	'prof-append-timers': { type: 'string' },
M
Martin Aeschlimann 已提交
68
	'prof-startup-prefix': { type: 'string' },
69
	'prof-v8-extensions': { type: 'boolean' },
70 71
	'disable-extensions': { type: 'boolean', deprecates: 'disableExtensions', cat: 't', description: localize('disableExtensions', "Disable all installed extensions.") },
	'disable-extension': { type: 'string[]', cat: 't', args: 'extension-id', description: localize('disableExtension', "Disable an extension.") },
72
	'sync': { type: 'string', cat: 't', description: localize('turn sync', "Turn sync on or off"), args: ['on', 'off'] },
73 74 75 76 77

	'inspect-extensions': { type: 'string', deprecates: 'debugPluginHost', args: 'port', cat: 't', description: localize('inspect-extensions', "Allow debugging and profiling of extensions. Check the developer tools for the connection URI.") },
	'inspect-brk-extensions': { type: 'string', deprecates: 'debugBrkPluginHost', args: 'port', cat: 't', description: localize('inspect-brk-extensions', "Allow debugging and profiling of extensions with the extension host being paused after start. Check the developer tools for the connection URI.") },
	'disable-gpu': { type: 'boolean', cat: 't', description: localize('disableGPU', "Disable GPU hardware acceleration.") },
	'max-memory': { type: 'string', cat: 't', description: localize('maxMemory', "Max memory size for a window (in Mbytes).") },
78
	'telemetry': { type: 'boolean', cat: 't', description: localize('telemetry', "Shows all telemetry events which VS code collects.") },
79 80

	'remote': { type: 'string' },
81 82 83
	'folder-uri': { type: 'string[]', cat: 'o', args: 'uri' },
	'file-uri': { type: 'string[]', cat: 'o', args: 'uri' },

84 85 86 87
	'locate-extension': { type: 'string[]' },
	'extensionDevelopmentPath': { type: 'string[]' },
	'extensionTestsPath': { type: 'string' },
	'debugId': { type: 'string' },
88
	'debugRenderer': { type: 'boolean' },
89 90 91 92 93 94
	'inspect-search': { type: 'string', deprecates: 'debugSearch' },
	'inspect-brk-search': { type: 'string', deprecates: 'debugBrkSearch' },
	'export-default-configuration': { type: 'string' },
	'install-source': { type: 'string' },
	'driver': { type: 'string' },
	'logExtensionHostCommunication': { type: 'boolean' },
95
	'skip-release-notes': { type: 'boolean' },
96 97 98
	'disable-telemetry': { type: 'boolean' },
	'disable-updates': { type: 'boolean' },
	'disable-crash-reporter': { type: 'boolean' },
99
	'crash-reporter-directory': { type: 'string' },
R
Robo 已提交
100
	'crash-reporter-id': { type: 'string' },
101 102 103 104 105 106
	'skip-add-to-recently-opened': { type: 'boolean' },
	'unity-launch': { type: 'boolean' },
	'open-url': { type: 'boolean' },
	'file-write': { type: 'boolean' },
	'file-chmod': { type: 'boolean' },
	'driver-verbose': { type: 'boolean' },
107
	'install-builtin-extension': { type: 'string[]' },
108
	'force': { type: 'boolean' },
109
	'do-not-sync': { type: 'boolean' },
M
Martin Aeschlimann 已提交
110
	'trace': { type: 'boolean' },
111 112
	'trace-category-filter': { type: 'string' },
	'trace-options': { type: 'string' },
J
João Moreno 已提交
113
	'force-user-env': { type: 'boolean' },
114
	'force-disable-user-env': { type: 'boolean' },
115
	'open-devtools': { type: 'boolean' },
116
	'__sandbox': { type: 'boolean' },
S
Sandeep Somavarapu 已提交
117
	'logsPath': { type: 'string' },
118

119 120 121 122 123
	// chromium flags
	'no-proxy-server': { type: 'boolean' },
	'proxy-server': { type: 'string' },
	'proxy-bypass-list': { type: 'string' },
	'proxy-pac-url': { type: 'string' },
124
	'js-flags': { type: 'string' }, // chrome js flags
125 126
	'inspect': { type: 'string' },
	'inspect-brk': { type: 'string' },
127
	'nolazy': { type: 'boolean' }, // node inspect
128
	'force-device-scale-factor': { type: 'string' },
129
	'force-renderer-accessibility': { type: 'boolean' },
C
Christof Marti 已提交
130
	'ignore-certificate-errors': { type: 'boolean' },
131
	'allow-insecure-localhost': { type: 'boolean' },
C
Christof Marti 已提交
132
	'log-net-log': { type: 'string' },
M
Martin Aeschlimann 已提交
133
	'_urls': { type: 'string[]' },
134 135 136

	_: { type: 'string[]' } // main arguments
};
M
Martin Aeschlimann 已提交
137

138 139 140 141 142 143 144 145 146 147
export interface ErrorReporter {
	onUnknownOption(id: string): void;
	onMultipleValues(id: string, usedValue: string): void;
}

const ignoringReporter: ErrorReporter = {
	onUnknownOption: () => { },
	onMultipleValues: () => { }
};

148
export function parseArgs<T>(args: string[], options: OptionDescriptions<T>, errorReporter: ErrorReporter = ignoringReporter): T {
M
Martin Aeschlimann 已提交
149 150 151
	const alias: { [key: string]: string } = {};
	const string: string[] = [];
	const boolean: string[] = [];
152
	for (let optionId in options) {
M
Martin Aeschlimann 已提交
153 154 155 156
		if (optionId[0] === '_') {
			continue;
		}

157 158 159
		const o = options[optionId];
		if (o.alias) {
			alias[optionId] = o.alias;
M
Martin Aeschlimann 已提交
160
		}
161

162
		if (o.type === 'string' || o.type === 'string[]') {
163
			string.push(optionId);
164 165 166
			if (o.deprecates) {
				string.push(o.deprecates);
			}
M
Martin Aeschlimann 已提交
167
		} else if (o.type === 'boolean') {
168
			boolean.push(optionId);
169 170 171
			if (o.deprecates) {
				boolean.push(o.deprecates);
			}
M
Martin Aeschlimann 已提交
172
		}
J
Joao Moreno 已提交
173
	}
174
	// remove aliases to avoid confusion
175
	const parsedArgs = minimist(args, { string, boolean, alias });
M
Martin Aeschlimann 已提交
176 177

	const cleanedArgs: any = {};
178
	const remainingArgs: any = parsedArgs;
M
Martin Aeschlimann 已提交
179

180 181
	// https://github.com/microsoft/vscode/issues/58177, https://github.com/microsoft/vscode/issues/106617
	cleanedArgs._ = parsedArgs._.map(arg => String(arg)).filter(arg => arg.length > 0);
182 183

	delete remainingArgs._;
184 185 186

	for (let optionId in options) {
		const o = options[optionId];
M
Martin Aeschlimann 已提交
187
		if (o.alias) {
188
			delete remainingArgs[o.alias];
M
Martin Aeschlimann 已提交
189
		}
M
Martin Aeschlimann 已提交
190

191 192
		let val = remainingArgs[optionId];
		if (o.deprecates && remainingArgs.hasOwnProperty(o.deprecates)) {
M
Martin Aeschlimann 已提交
193
			if (!val) {
194
				val = remainingArgs[o.deprecates];
M
Martin Aeschlimann 已提交
195
			}
196
			delete remainingArgs[o.deprecates];
197
		}
M
Martin Aeschlimann 已提交
198

A
Andrew Wong 已提交
199
		if (typeof val !== 'undefined') {
200 201 202 203 204 205 206 207
			if (o.type === 'string[]') {
				if (val && !Array.isArray(val)) {
					val = [val];
				}
			} else if (o.type === 'string') {
				if (Array.isArray(val)) {
					val = val.pop(); // take the last
					errorReporter.onMultipleValues(optionId, val);
M
Martin Aeschlimann 已提交
208
				}
209
			}
210
			cleanedArgs[optionId] = val;
211
		}
212
		delete remainingArgs[optionId];
M
Martin Aeschlimann 已提交
213
	}
J
Joao Moreno 已提交
214

215
	for (let key in remainingArgs) {
216
		errorReporter.onUnknownOption(key);
M
Martin Aeschlimann 已提交
217
	}
218

M
Martin Aeschlimann 已提交
219
	return cleanedArgs;
J
Joao Moreno 已提交
220 221
}

222
function formatUsage(optionId: string, option: Option<any>) {
M
Martin Aeschlimann 已提交
223 224 225 226 227 228 229 230 231
	let args = '';
	if (option.args) {
		if (Array.isArray(option.args)) {
			args = ` <${option.args.join('> <')}>`;
		} else {
			args = ` <${option.args}>`;
		}
	}
	if (option.alias) {
232
		return `-${option.alias} --${optionId}${args}`;
M
Martin Aeschlimann 已提交
233
	}
234
	return `--${optionId}${args}`;
J
Joao Moreno 已提交
235 236
}

M
Martin Aeschlimann 已提交
237
// exported only for testing
238 239 240 241 242 243 244 245 246 247
export function formatOptions(options: OptionDescriptions<any>, columns: number): string[] {
	let maxLength = 0;
	let usageTexts: [string, string][] = [];
	for (const optionId in options) {
		const o = options[optionId];
		const usageText = formatUsage(optionId, o);
		maxLength = Math.max(maxLength, usageText.length);
		usageTexts.push([usageText, o.description!]);
	}
	let argLength = maxLength + 2/*left padding*/ + 1/*right padding*/;
D
Daniel Imms 已提交
248 249
	if (columns - argLength < 25) {
		// Use a condensed version on narrow terminals
250
		return usageTexts.reduce<string[]>((r, ut) => r.concat([`  ${ut[0]}`, `      ${ut[1]}`]), []);
D
Daniel Imms 已提交
251 252
	}
	let descriptionColumns = columns - argLength - 1;
M
Martin Aeschlimann 已提交
253
	let result: string[] = [];
254 255 256
	for (const ut of usageTexts) {
		let usage = ut[0];
		let wrappedDescription = wrapText(ut[1], descriptionColumns);
M
Martin Aeschlimann 已提交
257 258
		let keyPadding = indent(argLength - usage.length - 2/*left padding*/);
		result.push('  ' + usage + keyPadding + wrappedDescription[0]);
259
		for (let i = 1; i < wrappedDescription.length; i++) {
M
Martin Aeschlimann 已提交
260
			result.push(indent(argLength) + wrappedDescription[i]);
D
Daniel Imms 已提交
261
		}
262
	}
D
Daniel Imms 已提交
263
	return result;
J
Joao Moreno 已提交
264 265
}

M
Martin Aeschlimann 已提交
266 267 268 269
function indent(count: number): string {
	return (<any>' ').repeat(count);
}

J
Johannes Rieken 已提交
270
function wrapText(text: string, columns: number): string[] {
M
Martin Aeschlimann 已提交
271
	let lines: string[] = [];
D
Daniel Imms 已提交
272 273
	while (text.length) {
		let index = text.length < columns ? text.length : text.lastIndexOf(' ', columns);
D
Daniel Imms 已提交
274
		let line = text.slice(0, index).trim();
D
Daniel Imms 已提交
275 276 277 278 279 280
		text = text.slice(index);
		lines.push(line);
	}
	return lines;
}

281
export function buildHelpMessage(productName: string, executableName: string, version: string, options: OptionDescriptions<any>, isPipeSupported = true): string {
M
Martin Aeschlimann 已提交
282
	const columns = (process.stdout).isTTY && (process.stdout).columns || 80;
J
Joao Moreno 已提交
283

M
Martin Aeschlimann 已提交
284 285 286 287
	let help = [`${productName} ${version}`];
	help.push('');
	help.push(`${localize('usage', "Usage")}: ${executableName} [${localize('options', "options")}][${localize('paths', 'paths')}...]`);
	help.push('');
288
	if (isPipeSupported) {
289
		if (isWindows) {
290 291 292 293 294
			help.push(localize('stdinWindows', "To read output from another program, append '-' (e.g. 'echo Hello World | {0} -')", executableName));
		} else {
			help.push(localize('stdinUnix', "To read from stdin, append '-' (e.g. 'ps aux | grep code | {0} -')", executableName));
		}
		help.push('');
M
Martin Aeschlimann 已提交
295
	}
M
Martin Aeschlimann 已提交
296
	const optionsByCategory: { [P in keyof typeof helpCategories]?: OptionDescriptions<any> } = {};
297 298 299
	for (const optionId in options) {
		const o = options[optionId];
		if (o.description && o.cat) {
M
Martin Aeschlimann 已提交
300 301 302 303 304
			let optionsByCat = optionsByCategory[o.cat];
			if (!optionsByCat) {
				optionsByCategory[o.cat] = optionsByCat = {};
			}
			optionsByCat[optionId] = o;
305 306 307 308
		}
	}

	for (let helpCategoryKey in optionsByCategory) {
309 310
		const key = <keyof typeof helpCategories>helpCategoryKey;

311
		let categoryOptions = optionsByCategory[key];
M
Martin Aeschlimann 已提交
312
		if (categoryOptions) {
313
			help.push(helpCategories[key]);
M
Martin Aeschlimann 已提交
314 315 316 317 318 319
			help.push(...formatOptions(categoryOptions, columns));
			help.push('');
		}
	}
	return help.join('\n');
}
B
Benjamin Pasero 已提交
320

M
Martin Aeschlimann 已提交
321 322
export function buildVersionMessage(version: string | undefined, commit: string | undefined): string {
	return `${version || localize('unknownVersion', "Unknown version")}\n${commit || localize('unknownCommit', "Unknown commit")}\n${process.arch}`;
323
}
M
Martin Aeschlimann 已提交
324