Path: blob/main/src/vs/platform/environment/node/argv.ts
3296 views
/*---------------------------------------------------------------------------------------------1* Copyright (c) Microsoft Corporation. All rights reserved.2* Licensed under the MIT License. See License.txt in the project root for license information.3*--------------------------------------------------------------------------------------------*/45import minimist from 'minimist';6import { isWindows } from '../../../base/common/platform.js';7import { localize } from '../../../nls.js';8import { NativeParsedArgs } from '../common/argv.js';910/**11* This code is also used by standalone cli's. Avoid adding any other dependencies.12*/13const helpCategories = {14o: localize('optionsUpperCase', "Options"),15e: localize('extensionsManagement', "Extensions Management"),16t: localize('troubleshooting', "Troubleshooting"),17m: localize('mcp', "Model Context Protocol")18};1920export interface Option<OptionType> {21type: OptionType;22alias?: string;23deprecates?: string[]; // old deprecated ids24args?: string | string[];25description?: string;26deprecationMessage?: string;27allowEmptyValue?: boolean;28cat?: keyof typeof helpCategories;29global?: boolean;30}3132export interface Subcommand<T> {33type: 'subcommand';34description?: string;35deprecationMessage?: string;36options: OptionDescriptions<Required<T>>;37}3839export type OptionDescriptions<T> = {40[P in keyof T]:41T[P] extends boolean | undefined ? Option<'boolean'> :42T[P] extends string | undefined ? Option<'string'> :43T[P] extends string[] | undefined ? Option<'string[]'> :44Subcommand<T[P]>45};4647export const NATIVE_CLI_COMMANDS = ['tunnel', 'serve-web'] as const;4849export const OPTIONS: OptionDescriptions<Required<NativeParsedArgs>> = {50'chat': {51type: 'subcommand',52description: 'Pass in a prompt to run in a chat session in the current working directory.',53options: {54'_': { type: 'string[]', description: localize('prompt', "The prompt to use as chat.") },55'mode': { type: 'string', cat: 'o', alias: 'm', args: 'mode', description: localize('chatMode', "The mode to use for the chat session. Available options: 'ask', 'edit', 'agent', or the identifier of a custom mode. Defaults to 'agent'.") },56'add-file': { type: 'string[]', cat: 'o', alias: 'a', args: 'path', description: localize('addFile', "Add files as context to the chat session.") },57'maximize': { type: 'boolean', cat: 'o', description: localize('chatMaximize', "Maximize the chat session view.") },58'reuse-window': { type: 'boolean', cat: 'o', alias: 'r', description: localize('reuseWindowForChat', "Force to use the last active window for the chat session.") },59'new-window': { type: 'boolean', cat: 'o', alias: 'n', description: localize('newWindowForChat', "Force to open an empty window for the chat session.") },60'profile': { type: 'string', 'cat': 'o', args: 'profileName', description: localize('profileName', "Opens the provided folder or workspace with the given profile and associates the profile with the workspace. If the profile does not exist, a new empty one is created.") },61'help': { type: 'boolean', alias: 'h', description: localize('help', "Print usage.") }62}63},64'serve-web': {65type: 'subcommand',66description: 'Run a server that displays the editor UI in browsers.',67options: {68'cli-data-dir': { type: 'string', args: 'dir', description: localize('cliDataDir', "Directory where CLI metadata should be stored.") },69'disable-telemetry': { type: 'boolean' },70'telemetry-level': { type: 'string' },71}72},73'tunnel': {74type: 'subcommand',75description: 'Make the current machine accessible from vscode.dev or other machines through a secure tunnel.',76options: {77'cli-data-dir': { type: 'string', args: 'dir', description: localize('cliDataDir', "Directory where CLI metadata should be stored.") },78'disable-telemetry': { type: 'boolean' },79'telemetry-level': { type: 'string' },80user: {81type: 'subcommand',82options: {83login: {84type: 'subcommand',85options: {86provider: { type: 'string' },87'access-token': { type: 'string' }88}89}90}91}92}93},94'diff': { type: 'boolean', cat: 'o', alias: 'd', args: ['file', 'file'], description: localize('diff', "Compare two files with each other.") },95'merge': { type: 'boolean', cat: 'o', alias: 'm', args: ['path1', 'path2', 'base', 'result'], description: localize('merge', "Perform a three-way merge by providing paths for two modified versions of a file, the common origin of both modified versions and the output file to save merge results.") },96'add': { type: 'boolean', cat: 'o', alias: 'a', args: 'folder', description: localize('add', "Add folder(s) to the last active window.") },97'remove': { type: 'boolean', cat: 'o', args: 'folder', description: localize('remove', "Remove folder(s) from the last active window.") },98'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.") },99'new-window': { type: 'boolean', cat: 'o', alias: 'n', description: localize('newWindow', "Force to open a new window.") },100'reuse-window': { type: 'boolean', cat: 'o', alias: 'r', description: localize('reuseWindow', "Force to open a file or folder in an already opened window.") },101'wait': { type: 'boolean', cat: 'o', alias: 'w', description: localize('wait', "Wait for the files to be closed before returning.") },102'waitMarkerFilePath': { type: 'string' },103'locale': { type: 'string', cat: 'o', args: 'locale', description: localize('locale', "The locale to use (e.g. en-US or zh-TW).") },104'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.") },105'profile': { type: 'string', 'cat': 'o', args: 'profileName', description: localize('profileName', "Opens the provided folder or workspace with the given profile and associates the profile with the workspace. If the profile does not exist, a new empty one is created.") },106'help': { type: 'boolean', cat: 'o', alias: 'h', description: localize('help', "Print usage.") },107108'extensions-dir': { type: 'string', deprecates: ['extensionHomePath'], cat: 'e', args: 'dir', description: localize('extensionHomePath', "Set the root path for extensions.") },109'extensions-download-dir': { type: 'string' },110'builtin-extensions-dir': { type: 'string' },111'list-extensions': { type: 'boolean', cat: 'e', description: localize('listExtensions', "List the installed extensions.") },112'show-versions': { type: 'boolean', cat: 'e', description: localize('showVersions', "Show versions of installed extensions, when using --list-extensions.") },113'category': { type: 'string', allowEmptyValue: true, cat: 'e', description: localize('category', "Filters installed extensions by provided category, when using --list-extensions."), args: 'category' },114'install-extension': { type: 'string[]', cat: 'e', args: 'ext-id | path', description: localize('installExtension', "Installs or updates an extension. The argument is either an extension id or a path to a VSIX. The identifier of an extension is '${publisher}.${name}'. Use '--force' argument to update to latest version. To install a specific version provide '@${version}'. For example: '[email protected]'.") },115'pre-release': { type: 'boolean', cat: 'e', description: localize('install prerelease', "Installs the pre-release version of the extension, when using --install-extension") },116'uninstall-extension': { type: 'string[]', cat: 'e', args: 'ext-id', description: localize('uninstallExtension', "Uninstalls an extension.") },117'update-extensions': { type: 'boolean', cat: 'e', description: localize('updateExtensions', "Update the installed extensions.") },118'enable-proposed-api': { type: 'string[]', allowEmptyValue: true, cat: 'e', args: 'ext-id', description: localize('experimentalApis', "Enables proposed API features for extensions. Can receive one or more extension IDs to enable individually.") },119120'add-mcp': { type: 'string[]', cat: 'm', args: 'json', description: localize('addMcp', "Adds a Model Context Protocol server definition to the user profile. Accepts JSON input in the form '{\"name\":\"server-name\",\"command\":...}'") },121122'version': { type: 'boolean', cat: 't', alias: 'v', description: localize('version', "Print version.") },123'verbose': { type: 'boolean', cat: 't', global: true, description: localize('verbose', "Print verbose output (implies --wait).") },124'log': { type: 'string[]', cat: 't', args: 'level', global: true, description: localize('log', "Log level to use. Default is 'info'. Allowed values are 'critical', 'error', 'warn', 'info', 'debug', 'trace', 'off'. You can also configure the log level of an extension by passing extension id and log level in the following format: '${publisher}.${name}:${logLevel}'. For example: 'vscode.csharp:trace'. Can receive one or more such entries.") },125'status': { type: 'boolean', alias: 's', cat: 't', description: localize('status', "Print process usage and diagnostics information.") },126'prof-startup': { type: 'boolean', cat: 't', description: localize('prof-startup', "Run CPU profiler during startup.") },127'prof-append-timers': { type: 'string' },128'prof-duration-markers': { type: 'string[]' },129'prof-duration-markers-file': { type: 'string' },130'no-cached-data': { type: 'boolean' },131'prof-startup-prefix': { type: 'string' },132'prof-v8-extensions': { type: 'boolean' },133'disable-extensions': { type: 'boolean', deprecates: ['disableExtensions'], cat: 't', description: localize('disableExtensions', "Disable all installed extensions. This option is not persisted and is effective only when the command opens a new window.") },134'disable-extension': { type: 'string[]', cat: 't', args: 'ext-id', description: localize('disableExtension', "Disable the provided extension. This option is not persisted and is effective only when the command opens a new window.") },135'sync': { type: 'string', cat: 't', description: localize('turn sync', "Turn sync on or off."), args: ['on | off'] },136137'inspect-extensions': { type: 'string', allowEmptyValue: true, deprecates: ['debugPluginHost'], args: 'port', cat: 't', description: localize('inspect-extensions', "Allow debugging and profiling of extensions. Check the developer tools for the connection URI.") },138'inspect-brk-extensions': { type: 'string', allowEmptyValue: true, 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.") },139'disable-lcd-text': { type: 'boolean', cat: 't', description: localize('disableLCDText', "Disable LCD font rendering.") },140'disable-gpu': { type: 'boolean', cat: 't', description: localize('disableGPU', "Disable GPU hardware acceleration.") },141'disable-chromium-sandbox': { type: 'boolean', cat: 't', description: localize('disableChromiumSandbox', "Use this option only when there is requirement to launch the application as sudo user on Linux or when running as an elevated user in an applocker environment on Windows.") },142'sandbox': { type: 'boolean' },143'locate-shell-integration-path': { type: 'string', cat: 't', args: ['shell'], description: localize('locateShellIntegrationPath', "Print the path to a terminal shell integration script. Allowed values are 'bash', 'pwsh', 'zsh' or 'fish'.") },144'telemetry': { type: 'boolean', cat: 't', description: localize('telemetry', "Shows all telemetry events which VS code collects.") },145146'remote': { type: 'string', allowEmptyValue: true },147'folder-uri': { type: 'string[]', cat: 'o', args: 'uri' },148'file-uri': { type: 'string[]', cat: 'o', args: 'uri' },149150'locate-extension': { type: 'string[]' },151'extensionDevelopmentPath': { type: 'string[]' },152'extensionDevelopmentKind': { type: 'string[]' },153'extensionTestsPath': { type: 'string' },154'extensionEnvironment': { type: 'string' },155'debugId': { type: 'string' },156'debugRenderer': { type: 'boolean' },157'inspect-ptyhost': { type: 'string', allowEmptyValue: true },158'inspect-brk-ptyhost': { type: 'string', allowEmptyValue: true },159'inspect-search': { type: 'string', deprecates: ['debugSearch'], allowEmptyValue: true },160'inspect-brk-search': { type: 'string', deprecates: ['debugBrkSearch'], allowEmptyValue: true },161'inspect-sharedprocess': { type: 'string', allowEmptyValue: true },162'inspect-brk-sharedprocess': { type: 'string', allowEmptyValue: true },163'export-default-configuration': { type: 'string' },164'install-source': { type: 'string' },165'enable-smoke-test-driver': { type: 'boolean' },166'logExtensionHostCommunication': { type: 'boolean' },167'skip-release-notes': { type: 'boolean' },168'skip-welcome': { type: 'boolean' },169'disable-telemetry': { type: 'boolean' },170'disable-updates': { type: 'boolean' },171'transient': { type: 'boolean', cat: 't', description: localize('transient', "Run with temporary data and extension directories, as if launched for the first time.") },172'use-inmemory-secretstorage': { type: 'boolean', deprecates: ['disable-keytar'] },173'password-store': { type: 'string' },174'disable-workspace-trust': { type: 'boolean' },175'disable-crash-reporter': { type: 'boolean' },176'crash-reporter-directory': { type: 'string' },177'crash-reporter-id': { type: 'string' },178'skip-add-to-recently-opened': { type: 'boolean' },179'open-url': { type: 'boolean' },180'file-write': { type: 'boolean' },181'file-chmod': { type: 'boolean' },182'install-builtin-extension': { type: 'string[]' },183'force': { type: 'boolean' },184'do-not-sync': { type: 'boolean' },185'do-not-include-pack-dependencies': { type: 'boolean' },186'trace': { type: 'boolean' },187'trace-memory-infra': { type: 'boolean' },188'trace-category-filter': { type: 'string' },189'trace-options': { type: 'string' },190'preserve-env': { type: 'boolean' },191'force-user-env': { type: 'boolean' },192'force-disable-user-env': { type: 'boolean' },193'open-devtools': { type: 'boolean' },194'disable-gpu-sandbox': { type: 'boolean' },195'logsPath': { type: 'string' },196'__enable-file-policy': { type: 'boolean' },197'editSessionId': { type: 'string' },198'continueOn': { type: 'string' },199'enable-coi': { type: 'boolean' },200'unresponsive-sample-interval': { type: 'string' },201'unresponsive-sample-period': { type: 'string' },202'enable-rdp-display-tracking': { type: 'boolean' },203'disable-layout-restore': { type: 'boolean' },204'disable-experiments': { type: 'boolean' },205206// chromium flags207'no-proxy-server': { type: 'boolean' },208// Minimist incorrectly parses keys that start with `--no`209// https://github.com/substack/minimist/blob/aeb3e27dae0412de5c0494e9563a5f10c82cc7a9/index.js#L118-L121210// If --no-sandbox is passed via cli wrapper it will be treated as --sandbox which is incorrect, we use211// the alias here to make sure --no-sandbox is always respected.212// For https://github.com/microsoft/vscode/issues/128279213'no-sandbox': { type: 'boolean', alias: 'sandbox' },214'proxy-server': { type: 'string' },215'proxy-bypass-list': { type: 'string' },216'proxy-pac-url': { type: 'string' },217'js-flags': { type: 'string' }, // chrome js flags218'inspect': { type: 'string', allowEmptyValue: true },219'inspect-brk': { type: 'string', allowEmptyValue: true },220'nolazy': { type: 'boolean' }, // node inspect221'force-device-scale-factor': { type: 'string' },222'force-renderer-accessibility': { type: 'boolean' },223'ignore-certificate-errors': { type: 'boolean' },224'allow-insecure-localhost': { type: 'boolean' },225'log-net-log': { type: 'string' },226'vmodule': { type: 'string' },227'_urls': { type: 'string[]' },228'disable-dev-shm-usage': { type: 'boolean' },229'profile-temp': { type: 'boolean' },230'ozone-platform': { type: 'string' },231'enable-tracing': { type: 'string' },232'trace-startup-format': { type: 'string' },233'trace-startup-file': { type: 'string' },234'trace-startup-duration': { type: 'string' },235'xdg-portal-required-version': { type: 'string' },236237_: { type: 'string[]' } // main arguments238};239240export interface ErrorReporter {241onUnknownOption(id: string): void;242onMultipleValues(id: string, usedValue: string): void;243onEmptyValue(id: string): void;244onDeprecatedOption(deprecatedId: string, message: string): void;245246getSubcommandReporter?(command: string): ErrorReporter;247}248249const ignoringReporter = {250onUnknownOption: () => { },251onMultipleValues: () => { },252onEmptyValue: () => { },253onDeprecatedOption: () => { }254};255256export function parseArgs<T>(args: string[], options: OptionDescriptions<T>, errorReporter: ErrorReporter = ignoringReporter): T {257// Find the first non-option arg, which also isn't the value for a previous `--flag`258const firstPossibleCommand = args.find((a, i) => a.length > 0 && a[0] !== '-' && options.hasOwnProperty(a) && options[a as T].type === 'subcommand');259260const alias: { [key: string]: string } = {};261const stringOptions: string[] = ['_'];262const booleanOptions: string[] = [];263const globalOptions: OptionDescriptions<any> = {};264let command: Subcommand<any> | undefined = undefined;265for (const optionId in options) {266const o = options[optionId];267if (o.type === 'subcommand') {268if (optionId === firstPossibleCommand) {269command = o;270}271} else {272if (o.alias) {273alias[optionId] = o.alias;274}275276if (o.type === 'string' || o.type === 'string[]') {277stringOptions.push(optionId);278if (o.deprecates) {279stringOptions.push(...o.deprecates);280}281} else if (o.type === 'boolean') {282booleanOptions.push(optionId);283if (o.deprecates) {284booleanOptions.push(...o.deprecates);285}286}287if (o.global) {288globalOptions[optionId] = o;289}290}291}292if (command && firstPossibleCommand) {293const options = globalOptions;294for (const optionId in command.options) {295options[optionId] = command.options[optionId];296}297const newArgs = args.filter(a => a !== firstPossibleCommand);298const reporter = errorReporter.getSubcommandReporter ? errorReporter.getSubcommandReporter(firstPossibleCommand) : undefined;299const subcommandOptions = parseArgs(newArgs, options, reporter);300// eslint-disable-next-line local/code-no-dangerous-type-assertions301return <T>{302[firstPossibleCommand]: subcommandOptions,303_: []304};305}306307308// remove aliases to avoid confusion309const parsedArgs = minimist(args, { string: stringOptions, boolean: booleanOptions, alias });310311const cleanedArgs: any = {};312const remainingArgs: any = parsedArgs;313314// https://github.com/microsoft/vscode/issues/58177, https://github.com/microsoft/vscode/issues/106617315cleanedArgs._ = parsedArgs._.map(arg => String(arg)).filter(arg => arg.length > 0);316317delete remainingArgs._;318319for (const optionId in options) {320const o = options[optionId];321if (o.type === 'subcommand') {322continue;323}324if (o.alias) {325delete remainingArgs[o.alias];326}327328let val = remainingArgs[optionId];329if (o.deprecates) {330for (const deprecatedId of o.deprecates) {331if (remainingArgs.hasOwnProperty(deprecatedId)) {332if (!val) {333val = remainingArgs[deprecatedId];334if (val) {335errorReporter.onDeprecatedOption(deprecatedId, o.deprecationMessage || localize('deprecated.useInstead', 'Use {0} instead.', optionId));336}337}338delete remainingArgs[deprecatedId];339}340}341}342343if (typeof val !== 'undefined') {344if (o.type === 'string[]') {345if (!Array.isArray(val)) {346val = [val];347}348if (!o.allowEmptyValue) {349const sanitized = val.filter((v: string) => v.length > 0);350if (sanitized.length !== val.length) {351errorReporter.onEmptyValue(optionId);352val = sanitized.length > 0 ? sanitized : undefined;353}354}355} else if (o.type === 'string') {356if (Array.isArray(val)) {357val = val.pop(); // take the last358errorReporter.onMultipleValues(optionId, val);359} else if (!val && !o.allowEmptyValue) {360errorReporter.onEmptyValue(optionId);361val = undefined;362}363}364cleanedArgs[optionId] = val;365366if (o.deprecationMessage) {367errorReporter.onDeprecatedOption(optionId, o.deprecationMessage);368}369}370delete remainingArgs[optionId];371}372373for (const key in remainingArgs) {374errorReporter.onUnknownOption(key);375}376377return cleanedArgs;378}379380function formatUsage(optionId: string, option: Option<any>) {381let args = '';382if (option.args) {383if (Array.isArray(option.args)) {384args = ` <${option.args.join('> <')}>`;385} else {386args = ` <${option.args}>`;387}388}389if (option.alias) {390return `-${option.alias} --${optionId}${args}`;391}392return `--${optionId}${args}`;393}394395// exported only for testing396export function formatOptions(options: OptionDescriptions<any>, columns: number): string[] {397const usageTexts: [string, string][] = [];398for (const optionId in options) {399const o = options[optionId];400const usageText = formatUsage(optionId, o);401usageTexts.push([usageText, o.description!]);402}403return formatUsageTexts(usageTexts, columns);404}405406function formatUsageTexts(usageTexts: [string, string][], columns: number) {407const maxLength = usageTexts.reduce((previous, e) => Math.max(previous, e[0].length), 12);408const argLength = maxLength + 2/*left padding*/ + 1/*right padding*/;409if (columns - argLength < 25) {410// Use a condensed version on narrow terminals411return usageTexts.reduce<string[]>((r, ut) => r.concat([` ${ut[0]}`, ` ${ut[1]}`]), []);412}413const descriptionColumns = columns - argLength - 1;414const result: string[] = [];415for (const ut of usageTexts) {416const usage = ut[0];417const wrappedDescription = wrapText(ut[1], descriptionColumns);418const keyPadding = indent(argLength - usage.length - 2/*left padding*/);419result.push(' ' + usage + keyPadding + wrappedDescription[0]);420for (let i = 1; i < wrappedDescription.length; i++) {421result.push(indent(argLength) + wrappedDescription[i]);422}423}424return result;425}426427function indent(count: number): string {428return ' '.repeat(count);429}430431function wrapText(text: string, columns: number): string[] {432const lines: string[] = [];433while (text.length) {434let index = text.length < columns ? text.length : text.lastIndexOf(' ', columns);435if (index === 0) {436index = columns;437}438const line = text.slice(0, index).trim();439text = text.slice(index).trimStart();440lines.push(line);441}442return lines;443}444445export function buildHelpMessage(productName: string, executableName: string, version: string, options: OptionDescriptions<any>, capabilities?: { noPipe?: boolean; noInputFiles?: boolean; isChat?: boolean }): string {446const columns = (process.stdout).isTTY && (process.stdout).columns || 80;447const inputFiles = capabilities?.noInputFiles ? '' : capabilities?.isChat ? ` [${localize('cliPrompt', 'prompt')}]` : ` [${localize('paths', 'paths')}...]`;448const subcommand = capabilities?.isChat ? ' chat' : '';449450const help = [`${productName} ${version}`];451help.push('');452help.push(`${localize('usage', "Usage")}: ${executableName}${subcommand} [${localize('options', "options")}]${inputFiles}`);453help.push('');454if (capabilities?.noPipe !== true) {455help.push(buildStdinMessage(executableName, capabilities?.isChat));456help.push('');457}458const optionsByCategory: { [P in keyof typeof helpCategories]?: OptionDescriptions<any> } = {};459const subcommands: { command: string; description: string }[] = [];460for (const optionId in options) {461const o = options[optionId];462if (o.type === 'subcommand') {463if (o.description) {464subcommands.push({ command: optionId, description: o.description });465}466} else if (o.description && o.cat) {467let optionsByCat = optionsByCategory[o.cat];468if (!optionsByCat) {469optionsByCategory[o.cat] = optionsByCat = {};470}471optionsByCat[optionId] = o;472}473}474475for (const helpCategoryKey in optionsByCategory) {476const key = <keyof typeof helpCategories>helpCategoryKey;477478const categoryOptions = optionsByCategory[key];479if (categoryOptions) {480help.push(helpCategories[key]);481help.push(...formatOptions(categoryOptions, columns));482help.push('');483}484}485486if (subcommands.length) {487help.push(localize('subcommands', "Subcommands"));488help.push(...formatUsageTexts(subcommands.map(s => [s.command, s.description]), columns));489help.push('');490}491492return help.join('\n');493}494495export function buildStdinMessage(executableName: string, isChat?: boolean): string {496let example: string;497if (isWindows) {498if (isChat) {499example = `echo Hello World | ${executableName} chat <prompt> -`;500} else {501example = `echo Hello World | ${executableName} -`;502}503} else {504if (isChat) {505example = `ps aux | grep code | ${executableName} chat <prompt> -`;506} else {507example = `ps aux | grep code | ${executableName} -`;508}509}510511return localize('stdinUsage', "To read from stdin, append '-' (e.g. '{0}')", example);512}513514export function buildVersionMessage(version: string | undefined, commit: string | undefined): string {515return `${version || localize('unknownVersion', "Unknown version")}\n${commit || localize('unknownCommit', "Unknown commit")}\n${process.arch}`;516}517518519