Skip to content

Visual Studio Code, rebuilt in Rust

Rust
37.1 KB
Raw Blame
//! argv.ts `OPTIONS` and `parseArgs` (over minimist 1.2.8), argvHelper.ts `parseAndValidate` and `addArg`, the help,
//! version and stdin messages, and extpath.ts `parseLineAndColumnAware` for `--goto`.

use std::collections::BTreeMap;

#[derive(Clone, Copy)]
pub enum Kind {
    Boolean,
    String,
    StringArray,
    Subcommand(&'static [Opt]),
}

/// An `Option` or `Subcommand` of argv.ts.
pub struct Opt {
    pub id: &'static str,
    pub kind: Kind,
    alias: Option<&'static str>,
    deprecates: &'static [&'static str],
    args: &'static [&'static str],
    description: Option<&'static str>,
    allow_empty_value: bool,
    cat: Option<char>,
    global: bool,
}

const fn opt(id: &'static str, kind: Kind) -> Opt {
    Opt { id, kind, alias: None, deprecates: &[], args: &[], description: None, allow_empty_value: false, cat: None, global: false }
}
const fn boolean(id: &'static str) -> Opt {
    opt(id, Kind::Boolean)
}
const fn string(id: &'static str) -> Opt {
    opt(id, Kind::String)
}
const fn strings(id: &'static str) -> Opt {
    opt(id, Kind::StringArray)
}
const fn subcommand(id: &'static str, description: &'static str, options: &'static [Opt]) -> Opt {
    opt(id, Kind::Subcommand(options)).desc(description)
}

impl Opt {
    const fn alias(self, alias: &'static str) -> Opt {
        Opt { alias: Some(alias), ..self }
    }
    const fn deprecates(self, deprecates: &'static [&'static str]) -> Opt {
        Opt { deprecates, ..self }
    }
    const fn args(self, args: &'static [&'static str]) -> Opt {
        Opt { args, ..self }
    }
    const fn desc(self, description: &'static str) -> Opt {
        Opt { description: Some(description), ..self }
    }
    const fn allow_empty(self) -> Opt {
        Opt { allow_empty_value: true, ..self }
    }
    const fn cat(self, cat: char) -> Opt {
        Opt { cat: Some(cat), ..self }
    }
    const fn global(self) -> Opt {
        Opt { global: true, ..self }
    }
}

pub const NATIVE_CLI_COMMANDS: [&str; 3] = ["tunnel", "serve-web", "agent"];

const HELP_CATEGORIES: [(char, &str); 4] = [('o', "Options"), ('e', "Extensions Management"), ('t', "Troubleshooting"), ('m', "Model Context Protocol")];

const CLI_DATA_DIR: &str = "Directory where CLI metadata should be stored.";
const PROFILE: &str = "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.";

pub const CHAT_OPTIONS: &[Opt] = &[
    strings("_").desc("The prompt to use as chat."),
    string("mode").cat('o').alias("m").args(&["mode"]).desc("The mode to use for the chat session. Available options: 'ask', 'edit', 'agent', or the identifier of a custom mode. Defaults to 'agent'."),
    strings("add-file").cat('o').alias("a").args(&["path"]).desc("Add files as context to the chat session."),
    boolean("maximize").cat('o').desc("Maximize the chat session view."),
    boolean("reuse-window").cat('o').alias("r").desc("Force to use the last active window for the chat session."),
    boolean("new-window").cat('o').alias("n").desc("Force to open an empty window for the chat session."),
    string("profile").cat('o').args(&["profileName"]).desc(PROFILE),
    boolean("help").alias("h").desc("Print usage."),
];

const SERVER_OPTIONS: &[Opt] = &[string("cli-data-dir").args(&["dir"]).desc(CLI_DATA_DIR), boolean("disable-telemetry"), string("telemetry-level")];

const TUNNEL_USER_LOGIN: &[Opt] = &[string("provider"), string("access-token")];
const TUNNEL_USER: &[Opt] = &[opt("login", Kind::Subcommand(TUNNEL_USER_LOGIN))];
const TUNNEL_OPTIONS: &[Opt] = &[
    string("cli-data-dir").args(&["dir"]).desc(CLI_DATA_DIR),
    boolean("disable-telemetry"),
    string("telemetry-level"),
    opt("user", Kind::Subcommand(TUNNEL_USER)),
];

pub const OPTIONS: &[Opt] = &[
    subcommand("chat", "Pass in a prompt to run in a chat session in the current working directory.", CHAT_OPTIONS),
    subcommand("serve-web", "Run a server that displays the editor UI in browsers.", SERVER_OPTIONS),
    subcommand("agent", "Start and interact with AI agent hosts.", SERVER_OPTIONS),
    subcommand("tunnel", "Make the current machine accessible from vscode.dev or other machines through a secure tunnel.", TUNNEL_OPTIONS),
    boolean("diff").cat('o').alias("d").args(&["file", "file"]).desc("Compare two files with each other."),
    boolean("merge").cat('o').alias("m").args(&["path1", "path2", "base", "result"]).desc("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."),
    boolean("add").cat('o').alias("a").args(&["folder"]).desc("Add folder(s) to the last active window."),
    boolean("remove").cat('o').args(&["folder"]).desc("Remove folder(s) from the last active window."),
    boolean("goto").cat('o').alias("g").args(&["file:line[:character]"]).desc("Open a file at the path on the specified line and character position."),
    boolean("new-window").cat('o').alias("n").desc("Force to open a new window."),
    boolean("reuse-window").cat('o').alias("r").desc("Force to open a file or folder in an already opened window."),
    boolean("agents").cat('o').deprecates(&["sessions"]).desc("Opens the agents window. If a folder is provided, opens a new session with that folder selected."),
    string("session-title-base64"),
    boolean("wait").cat('o').alias("w").desc("Wait for the files to be closed before returning."),
    string("waitMarkerFilePath"),
    string("locale").cat('o').args(&["locale"]).desc("The locale to use (e.g. en-US or zh-TW)."),
    string("user-data-dir").cat('o').args(&["dir"]).desc("Specifies the directory that user data is kept in. Can be used to open multiple distinct instances of Code."),
    string("profile").cat('o').args(&["profileName"]).desc(PROFILE),
    boolean("help").cat('o').alias("h").desc("Print usage."),
    string("extensions-dir").deprecates(&["extensionHomePath"]).cat('e').args(&["dir"]).desc("Set the root path for extensions."),
    string("extensions-download-dir"),
    string("builtin-extensions-dir"),
    string("shared-data-dir"),
    boolean("list-extensions").cat('e').desc("List the installed extensions."),
    string("agent-plugins-dir"),
    string("agents-user-data-dir"),
    string("agents-extensions-dir"),
    boolean("show-versions").cat('e').desc("Show versions of installed extensions, when using --list-extensions."),
    string("category").allow_empty().cat('e').desc("Filters installed extensions by provided category, when using --list-extensions.").args(&["category"]),
    strings("install-extension").cat('e').args(&["ext-id | path"]).desc("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]'."),
    boolean("pre-release").cat('e').desc("Installs the pre-release version of the extension, when using --install-extension"),
    strings("uninstall-extension").cat('e').args(&["ext-id"]).desc("Uninstalls an extension."),
    boolean("update-extensions").cat('e').desc("Update the installed extensions."),
    strings("enable-proposed-api").allow_empty().cat('e').args(&["ext-id"]).desc("Enables proposed API features for extensions. Can receive one or more extension IDs to enable individually."),
    strings("add-mcp").cat('m').args(&["json"]).desc("Adds a Model Context Protocol server definition to the user profile. Accepts JSON input in the form '{\"name\":\"server-name\",\"command\":...}'"),
    boolean("version").cat('t').alias("v").desc("Print version."),
    boolean("verbose").cat('t').global().desc("Print verbose output (implies --wait)."),
    strings("log").cat('t').args(&["level"]).global().desc("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."),
    boolean("status").alias("s").cat('t').desc("Print process usage and diagnostics information."),
    boolean("prof-startup").cat('t').desc("Run CPU profiler during startup."),
    string("prof-append-timers"),
    strings("prof-duration-markers"),
    string("prof-duration-markers-file"),
    boolean("no-cached-data"),
    string("prof-startup-prefix"),
    boolean("prof-v8-extensions"),
    boolean("disable-extensions").deprecates(&["disableExtensions"]).cat('t').desc("Disable all installed extensions. This option is not persisted and is effective only when the command opens a new window."),
    strings("disable-extension").cat('t').args(&["ext-id"]).desc("Disable the provided extension. This option is not persisted and is effective only when the command opens a new window."),
    string("sync").cat('t').desc("Turn sync on or off.").args(&["on | off"]),
    string("inspect-extensions").allow_empty().deprecates(&["debugPluginHost"]).args(&["port"]).cat('t').desc("Allow debugging and profiling of extensions. Check the developer tools for the connection URI."),
    string("inspect-brk-extensions").allow_empty().deprecates(&["debugBrkPluginHost"]).args(&["port"]).cat('t').desc("Allow debugging and profiling of extensions with the extension host being paused after start. Check the developer tools for the connection URI."),
    boolean("disable-lcd-text").cat('t').desc("Disable LCD font rendering."),
    boolean("disable-gpu").cat('t').desc("Disable GPU hardware acceleration."),
    boolean("disable-chromium-sandbox").cat('t').desc("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."),
    boolean("sandbox"),
    string("locate-shell-integration-path").cat('t').args(&["shell"]).desc("Print the path to a terminal shell integration script. Allowed values are 'bash', 'pwsh', 'zsh' or 'fish'."),
    boolean("telemetry").cat('t').desc("Shows all telemetry events which VS code collects."),
    string("remote").allow_empty(),
    strings("folder-uri").cat('o').args(&["uri"]),
    strings("file-uri").cat('o').args(&["uri"]),
    strings("locate-extension"),
    strings("extensionDevelopmentPath"),
    strings("extensionDevelopmentKind"),
    string("extensionTestsPath"),
    boolean("hidden-window"),
    string("extensionEnvironment"),
    string("debugId"),
    boolean("debugRenderer"),
    string("inspect-ptyhost").allow_empty(),
    string("inspect-brk-ptyhost").allow_empty(),
    string("inspect-agenthost").allow_empty(),
    string("inspect-brk-agenthost").allow_empty(),
    string("inspect-sharedprocess").allow_empty(),
    string("inspect-brk-sharedprocess").allow_empty(),
    string("export-default-configuration"),
    string("export-policy-data").allow_empty(),
    string("export-default-keybindings").allow_empty(),
    string("install-source"),
    boolean("enable-smoke-test-driver"),
    boolean("skip-sessions-welcome"),
    boolean("logExtensionHostCommunication"),
    boolean("skip-release-notes"),
    boolean("skip-welcome"),
    boolean("disable-telemetry"),
    string("telemetry-level"),
    boolean("disable-updates"),
    boolean("share-secrets-with-agents-app"),
    boolean("transient").cat('t').desc("Run with temporary data and extension directories, as if launched for the first time."),
    boolean("use-inmemory-secretstorage").deprecates(&["disable-keytar"]),
    string("password-store"),
    boolean("disable-workspace-trust"),
    boolean("disable-crash-reporter"),
    string("crash-reporter-directory"),
    string("crash-reporter-id"),
    boolean("skip-add-to-recently-opened"),
    // The port's `--open-url <url>` hands an unbundled build the url (main.rs); upstream's is a boolean.
    string("open-url"),
    boolean("file-write"),
    boolean("file-chmod"),
    strings("install-builtin-extension"),
    boolean("force"),
    boolean("do-not-sync"),
    boolean("do-not-include-pack-dependencies"),
    boolean("trace"),
    boolean("trace-memory-infra"),
    string("trace-category-filter"),
    string("trace-options"),
    boolean("preserve-env"),
    boolean("force-user-env"),
    boolean("force-disable-user-env"),
    boolean("open-devtools"),
    boolean("disable-gpu-sandbox"),
    string("logsPath"),
    boolean("__enable-file-policy"),
    string("editSessionId"),
    string("continueOn"),
    boolean("enable-coi"),
    string("unresponsive-sample-interval"),
    string("unresponsive-sample-period"),
    boolean("enable-rdp-display-tracking"),
    boolean("disable-layout-restore"),
    boolean("disable-experiments"),
    boolean("no-proxy-server"),
    // argv.ts: the alias keeps minimist from reading `--no-sandbox` as `--sandbox=false` (vscode#128279).
    boolean("no-sandbox").alias("sandbox"),
    string("proxy-server"),
    string("proxy-bypass-list"),
    string("proxy-pac-url"),
    string("js-flags"),
    string("inspect").allow_empty(),
    string("inspect-brk").allow_empty(),
    boolean("nolazy"),
    string("force-device-scale-factor"),
    boolean("force-renderer-accessibility"),
    boolean("ignore-certificate-errors"),
    boolean("allow-insecure-localhost"),
    string("log-net-log"),
    string("vmodule"),
    strings("_urls"),
    boolean("disable-dev-shm-usage"),
    boolean("profile-temp"),
    string("ozone-platform"),
    string("enable-tracing"),
    string("trace-startup-format"),
    string("trace-startup-file"),
    string("trace-startup-duration"),
    string("xdg-portal-required-version"),
    // The port's own flags (main.rs): declared so minimist neither takes `--node`'s next argument as its value nor
    // reports them as unknown.
    boolean("node"),
    string("theme"),
    string("screenshot"),
    string("screenshot-keys"),
    string("screenshot-input"),
    strings("_"),
];

/// A parsed option's value: argv.ts's `boolean`, `string` and `string[]`.
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
    Bool(bool),
    Str(String),
    List(Vec<String>),
}

/// `NativeParsedArgs`: the options by id, `_`, and the subcommand with its own options.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ParsedArgs {
    pub values: BTreeMap<String, Value>,
    pub positional: Vec<String>,
    pub subcommand: Option<(String, Box<ParsedArgs>)>,
}

impl ParsedArgs {
    /// The option as JS tests it for truthiness (`args.wait`).
    pub fn flag(&self, id: &str) -> bool {
        match self.values.get(id) {
            Some(Value::Bool(value)) => *value,
            Some(Value::Str(value)) => !value.is_empty(),
            Some(Value::List(_)) => true,
            None => false,
        }
    }

    pub fn string(&self, id: &str) -> Option<&str> {
        match self.values.get(id) {
            Some(Value::Str(value)) => Some(value),
            _ => None,
        }
    }
}

/// `ErrorReporter` as argvHelper.ts words it, collected for the caller to print with `console.warn`.
struct Reporter {
    warnings: Vec<String>,
    /// The subcommand whose options are parsed: unknown ones of the native CLI commands are not reported.
    command: Option<String>,
}

impl Reporter {
    fn unknown_option(&mut self, id: &str) {
        match &self.command {
            None => self.warnings.push(format!("Warning: '{id}' is not in the list of known options, but still passed to Electron/Chromium.")),
            Some(command) if !NATIVE_CLI_COMMANDS.contains(&command.as_str()) => {
                self.warnings.push(format!("Warning: '{id}' is not in the list of known options for subcommand '{command}'"))
            }
            Some(_) => {}
        }
    }
}

/// argvHelper.ts `parseAndValidate`: the parsed arguments and the warnings to print, or the `--goto` validation error.
pub fn parse_and_validate(args: &[String]) -> Result<(ParsedArgs, Vec<String>), String> {
    let mut reporter = Reporter { warnings: Vec::new(), command: None };
    let parsed = parse_args(args, &OPTIONS.iter().collect::<Vec<_>>(), &mut reporter);
    if parsed.flag("goto") && !parsed.positional.iter().all(|arg| is_goto_argument(arg)) {
        return Err("Arguments in `--goto` mode should be in the format of `FILE(:LINE(:CHARACTER))`.".into());
    }
    Ok((parsed, reporter.warnings))
}

/// `/^(\w:)?[^:]+(:\d*){0,2}:?$/`
fn is_goto_argument(arg: &str) -> bool {
    let bytes = arg.as_bytes();
    let drive = bytes.len() >= 2 && (bytes[0].is_ascii_alphanumeric() || bytes[0] == b'_') && bytes[1] == b':';
    // The optional drive is tried first; the regex backtracks to no drive when the rest does not match.
    (drive && matches_after_drive(&arg[2..])) || matches_after_drive(arg)
}

fn matches_after_drive(rest: &str) -> bool {
    let mut parts = rest.split(':');
    let path = parts.next().unwrap_or_default();
    if path.is_empty() {
        return false;
    }
    let numbers: Vec<&str> = parts.collect();
    if !numbers.iter().all(|part| part.bytes().all(|byte| byte.is_ascii_digit())) {
        return false;
    }
    // `(:\d*){0,2}:?`: two groups and a trailing colon at most, so three segments when the last one is empty.
    numbers.len() <= 2 || (numbers.len() == 3 && numbers[2].is_empty())
}

fn parse_args(args: &[String], options: &[&Opt], reporter: &mut Reporter) -> ParsedArgs {
    let subcommand = |arg: &String| options.iter().find_map(|option| match option.kind {
        Kind::Subcommand(command_options) if option.id == arg.as_str() => Some(command_options),
        _ => None,
    });
    let first_possible_command = args.iter().find_map(|arg| subcommand(arg).filter(|_| !arg.starts_with('-')).map(|command_options| (arg, command_options)));
    if let Some((command, command_options)) = first_possible_command {
        let mut merged: Vec<&Opt> = options.iter().copied().filter(|option| option.global).collect();
        for option in command_options {
            match merged.iter().position(|existing| existing.id == option.id) {
                Some(index) => merged[index] = option,
                None => merged.push(option),
            }
        }
        let new_args: Vec<String> = args.iter().filter(|arg| *arg != command).cloned().collect();
        let mut command_reporter = Reporter { warnings: Vec::new(), command: Some(command.clone()) };
        let parsed = parse_args(&new_args, &merged, &mut command_reporter);
        reporter.warnings.extend(command_reporter.warnings);
        return ParsedArgs { subcommand: Some((command.clone(), Box::new(parsed))), ..ParsedArgs::default() };
    }
    parse_options(args, options, reporter)
}

fn parse_options(args: &[String], options: &[&Opt], reporter: &mut Reporter) -> ParsedArgs {
    let mut minimist = Minimist::default();
    minimist.strings.push("_".into());
    for option in options {
        match option.kind {
            Kind::Subcommand(_) => continue,
            Kind::String | Kind::StringArray => minimist.strings.extend(std::iter::once(option.id).chain(option.deprecates.iter().copied()).map(str::to_owned)),
            Kind::Boolean => minimist.bools.extend(std::iter::once(option.id).chain(option.deprecates.iter().copied()).map(str::to_owned)),
        }
        if let Some(alias) = option.alias {
            minimist.add_alias(option.id, alias);
        }
    }
    // argv.ts: `--no-KEY` of a declared `no-KEY` boolean is that boolean, not minimist's `KEY=false`.
    let mut extracted_no_booleans = Vec::new();
    let filtered: Vec<String> = args
        .iter()
        .filter(|arg| match arg.strip_prefix("--").filter(|key| key.starts_with("no-") && minimist.bools.iter().any(|bool| bool == key)) {
            Some(key) => {
                extracted_no_booleans.push(key.to_owned());
                false
            }
            None => true,
        })
        .cloned()
        .collect();
    let (mut remaining, positional) = minimist.parse(&filtered);
    for key in extracted_no_booleans {
        set_entry(&mut remaining, &key, Raw::Bool(true));
    }

    let mut parsed = ParsedArgs { positional: positional.into_iter().filter(|arg| !arg.is_empty()).collect(), ..ParsedArgs::default() };
    for option in options {
        if matches!(option.kind, Kind::Subcommand(_)) || option.id == "_" {
            continue;
        }
        if let Some(alias) = option.alias {
            take_entry(&mut remaining, alias);
        }
        let mut value = take_entry(&mut remaining, option.id);
        for deprecated in option.deprecates {
            if let Some(old) = take_entry(&mut remaining, deprecated)
                && !value.as_ref().is_some_and(Raw::truthy)
                && old.truthy()
            {
                reporter.warnings.push(format!("Option '{deprecated}' is deprecated: Use {} instead.", option.id));
                value = Some(old);
            }
        }
        let Some(value) = value else { continue };
        let value = match option.kind {
            Kind::StringArray => {
                let list = value.into_strings();
                match option.allow_empty_value || list.iter().all(|item| !item.is_empty()) {
                    true => Some(Value::List(list)),
                    false => {
                        reporter.warnings.push(format!("Option '{}' requires a non empty value. Ignoring the option.", option.id));
                        let sanitized: Vec<String> = list.into_iter().filter(|item| !item.is_empty()).collect();
                        (!sanitized.is_empty()).then_some(Value::List(sanitized))
                    }
                }
            }
            Kind::String => match value {
                Raw::List(items) => {
                    let last = items.last().map(Raw::to_text).unwrap_or_default();
                    reporter.warnings.push(format!("Option '{}' is defined more than once. Using value '{last}'.", option.id));
                    Some(Value::Str(last))
                }
                value if !value.truthy() && !option.allow_empty_value => {
                    reporter.warnings.push(format!("Option '{}' requires a non empty value. Ignoring the option.", option.id));
                    None
                }
                value => Some(value.into_value()),
            },
            _ => Some(value.into_value()),
        };
        if let Some(value) = value {
            parsed.values.insert(option.id.to_owned(), value);
        }
    }
    for (key, _) in remaining {
        reporter.unknown_option(&key);
    }
    parsed
}

/// A minimist value; numbers stay text, the port reads none of them as numbers.
#[derive(Clone, Debug)]
enum Raw {
    Bool(bool),
    Str(String),
    List(Vec<Raw>),
}

impl Raw {
    fn truthy(&self) -> bool {
        match self {
            Raw::Bool(value) => *value,
            Raw::Str(value) => !value.is_empty(),
            Raw::List(_) => true,
        }
    }

    fn to_text(&self) -> String {
        match self {
            Raw::Bool(value) => value.to_string(),
            Raw::Str(value) => value.clone(),
            Raw::List(items) => items.iter().map(Raw::to_text).collect::<Vec<_>>().join(","),
        }
    }

    fn into_strings(self) -> Vec<String> {
        match self {
            Raw::List(items) => items.iter().map(Raw::to_text).collect(),
            value => vec![value.to_text()],
        }
    }

    fn into_value(self) -> Value {
        match self {
            Raw::Bool(value) => Value::Bool(value),
            Raw::Str(value) => Value::Str(value),
            Raw::List(items) => Value::List(items.iter().map(Raw::to_text).collect()),
        }
    }
}

/// minimist's `argv` without `_`, in insertion order: argv.ts reports unknown options in that order.
type Entries = Vec<(String, Raw)>;

fn set_entry(entries: &mut Entries, key: &str, value: Raw) {
    match entries.iter_mut().find(|(existing, _)| existing == key) {
        Some((_, existing)) => *existing = value,
        None => entries.push((key.to_owned(), value)),
    }
}

fn take_entry(entries: &mut Entries, key: &str) -> Option<Raw> {
    let index = entries.iter().position(|(existing, _)| existing == key)?;
    Some(entries.remove(index).1)
}

/// minimist 1.2.8 with `string`, `boolean` and `alias` options, the ones argv.ts passes.
#[derive(Default)]
struct Minimist {
    bools: Vec<String>,
    strings: Vec<String>,
    aliases: BTreeMap<String, Vec<String>>,
    argv: Entries,
}

impl Minimist {
    fn add_alias(&mut self, key: &str, alias: &str) {
        self.aliases.insert(key.to_owned(), vec![alias.to_owned()]);
        self.aliases.insert(alias.to_owned(), vec![key.to_owned()]);
    }

    fn is_bool(&self, key: &str) -> bool {
        self.bools.iter().any(|bool| bool == key)
    }

    fn is_string(&self, key: &str) -> bool {
        self.strings.iter().any(|string| string == key) || self.aliases.get(key).is_some_and(|aliases| aliases.iter().any(|alias| self.strings.contains(alias)))
    }

    fn alias_is_boolean(&self, key: &str) -> bool {
        self.aliases[key].iter().any(|alias| self.is_bool(alias))
    }

    /// Whether the argument after `key` can be its value: `!flags.bools[key] && (aliases[key] ? !aliasIsBoolean(key) : true)`.
    fn takes_value(&self, key: &str) -> bool {
        !self.is_bool(key) && (!self.aliases.contains_key(key) || !self.alias_is_boolean(key))
    }

    fn set_key(&mut self, key: &str, value: Raw) {
        let replace = match self.argv.iter().find(|(existing, _)| existing == key) {
            None => true,
            Some((_, Raw::Bool(_))) => true,
            Some(_) => self.is_bool(key),
        };
        if replace {
            return set_entry(&mut self.argv, key, value);
        }
        let (_, existing) = self.argv.iter_mut().find(|(existing, _)| existing == key).expect("found above");
        match existing {
            Raw::List(items) => items.push(value),
            single => *single = Raw::List(vec![single.clone(), value]),
        }
    }

    fn set_arg(&mut self, key: &str, value: Raw) {
        self.set_key(key, value.clone());
        for alias in self.aliases.get(key).cloned().unwrap_or_default() {
            self.set_key(&alias, value.clone());
        }
    }

    fn empty_or_true(&self, key: &str) -> Raw {
        match self.is_string(key) {
            true => Raw::Str(String::new()),
            false => Raw::Bool(true),
        }
    }

    /// `/^(-|--)[^-]/`
    fn looks_like_flag(arg: &str) -> bool {
        let starts_without_dash = |rest: &str| rest.chars().next().is_some_and(|first| first != '-');
        arg.strip_prefix('-').is_some_and(|rest| starts_without_dash(rest) || rest.strip_prefix('-').is_some_and(starts_without_dash))
    }

    fn parse(mut self, args: &[String]) -> (Entries, Vec<String>) {
        for key in self.bools.clone() {
            self.set_arg(&key, Raw::Bool(false));
        }
        let (args, not_flags) = match args.iter().position(|arg| arg == "--") {
            Some(index) => (&args[..index], &args[index + 1..]),
            None => (args, &[][..]),
        };
        let mut positional = Vec::new();
        let mut i = 0;
        while i < args.len() {
            let arg = &args[i];
            let next = args.get(i + 1);
            if let Some((key, value)) = arg.strip_prefix("--").and_then(|rest| rest.split_once('=')).filter(|(key, _)| !key.is_empty()) {
                let value = match self.is_bool(key) {
                    true => Raw::Bool(value != "false"),
                    false => Raw::Str(value.to_owned()),
                };
                self.set_arg(key, value);
            } else if let Some(key) = arg.strip_prefix("--no-").filter(|key| !key.is_empty()) {
                self.set_arg(key, Raw::Bool(false));
            } else if let Some(key) = arg.strip_prefix("--").filter(|key| !key.is_empty()) {
                match next {
                    Some(next) if !Self::looks_like_flag(next) && self.takes_value(key) => {
                        self.set_arg(key, Raw::Str(next.clone()));
                        i += 1;
                    }
                    Some(next) if next == "true" || next == "false" => {
                        self.set_arg(key, Raw::Bool(next == "true"));
                        i += 1;
                    }
                    _ => self.set_arg(key, self.empty_or_true(key)),
                }
            } else if arg.len() > 1 && arg.starts_with('-') && !arg[1..].starts_with('-') {
                self.parse_short(arg, next.map(String::as_str), &mut i);
            } else {
                positional.push(arg.clone());
            }
            i += 1;
        }
        positional.extend(not_flags.iter().cloned());
        (self.argv, positional)
    }

    /// A `-abc` group: each letter a flag, the last one takes the next argument as minimist does.
    fn parse_short(&mut self, arg: &str, next_arg: Option<&str>, i: &mut usize) {
        let letters: Vec<char> = arg[1..].chars().collect();
        let mut broken = false;
        let byte_after = |j: usize| arg.char_indices().nth(j + 2).map_or(arg.len(), |(index, _)| index);
        for j in 0..letters.len() - 1 {
            let letter = letters[j].to_string();
            let next = &arg[byte_after(j)..];
            if next == "-" {
                self.set_arg(&letter, Raw::Str(next.to_owned()));
                continue;
            }
            if letters[j].is_ascii_alphabetic() && next.starts_with('=') {
                self.set_arg(&letter, Raw::Str(next[1..].to_owned()));
                broken = true;
                break;
            }
            if letters[j].is_ascii_alphabetic() && ends_with_number(next) {
                self.set_arg(&letter, Raw::Str(next.to_owned()));
                broken = true;
                break;
            }
            // minimist's `letters` stop before the last character, so the last pair is not tested.
            if j + 1 < letters.len() - 1 && !(letters[j + 1].is_ascii_alphanumeric() || letters[j + 1] == '_') {
                self.set_arg(&letter, Raw::Str(next.to_owned()));
                broken = true;
                break;
            }
            self.set_arg(&letter, self.empty_or_true(&letter));
        }
        let key = letters[letters.len() - 1].to_string();
        if broken || key == "-" {
            return;
        }
        match next_arg {
            Some(next) if !next.is_empty() && !Self::looks_like_flag(next) && self.takes_value(&key) => {
                self.set_arg(&key, Raw::Str(next.to_owned()));
                *i += 1;
            }
            Some(next) if next == "true" || next == "false" => {
                self.set_arg(&key, Raw::Bool(next == "true"));
                *i += 1;
            }
            _ => self.set_arg(&key, self.empty_or_true(&key)),
        }
    }
}

/// `/-?\d+(\.\d*)?(e-?\d+)?$/`: the text ends in a number.
fn ends_with_number(text: &str) -> bool {
    let mut rest = text;
    if let Some((mantissa, exponent)) = rest.rsplit_once('e') {
        let digits = exponent.strip_prefix('-').unwrap_or(exponent);
        if !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit()) {
            rest = mantissa;
        }
    }
    if let Some((integer, fraction)) = rest.rsplit_once('.')
        && fraction.bytes().all(|byte| byte.is_ascii_digit())
        && integer.bytes().last().is_some_and(|byte| byte.is_ascii_digit())
    {
        rest = integer;
    }
    rest.bytes().last().is_some_and(|byte| byte.is_ascii_digit())
}

/// argvHelper.ts `addArg`: before a `--` end of arguments marker, else at the end.
pub fn add_arg(argv: &mut Vec<String>, args: &[&str]) {
    let at = argv.iter().position(|arg| arg == "--").unwrap_or(argv.len());
    argv.splice(at..at, args.iter().map(|arg| arg.to_string()));
}

fn format_usage(option: &Opt) -> String {
    let args = match option.args {
        [] => String::new(),
        args => format!(" <{}>", args.join("> <")),
    };
    match option.alias {
        Some(alias) => format!("-{alias} --{}{args}", option.id),
        None => format!("--{}{args}", option.id),
    }
}

pub fn format_options(options: &[&Opt], columns: usize) -> Vec<String> {
    let usage_texts: Vec<(String, String)> = options.iter().map(|option| (format_usage(option), option.description.unwrap_or_default().to_owned())).collect();
    format_usage_texts(&usage_texts, columns)
}

fn format_usage_texts(usage_texts: &[(String, String)], columns: usize) -> Vec<String> {
    let max_length = usage_texts.iter().map(|(usage, _)| usage.chars().count()).fold(12, usize::max);
    let arg_length = max_length + 2 + 1;
    if columns < arg_length + 25 {
        return usage_texts.iter().flat_map(|(usage, description)| [format!("  {usage}"), format!("      {description}")]).collect();
    }
    let description_columns = columns - arg_length - 1;
    let mut result = Vec::new();
    for (usage, description) in usage_texts {
        let wrapped = wrap_text(description, description_columns);
        let key_padding = " ".repeat(arg_length - usage.chars().count() - 2);
        result.push(format!("  {usage}{key_padding}{}", wrapped.first().map(String::as_str).unwrap_or_default()));
        for line in wrapped.iter().skip(1) {
            result.push(format!("{}{line}", " ".repeat(arg_length)));
        }
    }
    result
}

fn wrap_text(text: &str, columns: usize) -> Vec<String> {
    let mut lines = Vec::new();
    let mut text: Vec<char> = text.chars().collect();
    while !text.is_empty() {
        // `text.lastIndexOf(' ', columns)`, -1 without a space; `slice(0, -1)` then drops the last character.
        let index = match text.len() < columns {
            true => text.len(),
            false => match text[..=columns.min(text.len() - 1)].iter().rposition(|char| *char == ' ') {
                Some(0) => columns.min(text.len()),
                Some(index) => index,
                None => text.len() - 1,
            },
        };
        lines.push(text[..index].iter().collect::<String>().trim().to_owned());
        text = text[index..].iter().collect::<String>().trim_start().chars().collect();
    }
    lines
}

/// `buildHelpMessage` of the main options (`is_chat` false) or of `chat`'s.
pub fn build_help_message(product_name: &str, executable_name: &str, version: &str, options: &[Opt], is_chat: bool, columns: usize) -> String {
    let input_files = if is_chat { " [prompt]" } else { " [paths...]" };
    let subcommand = if is_chat { " chat" } else { "" };
    let mut help = vec![format!("{product_name} {version}"), String::new(), format!("Usage: {executable_name}{subcommand} [options]{input_files}"), String::new()];
    help.push(build_stdin_message(executable_name, is_chat));
    help.push(String::new());
    let mut categories: Vec<(char, Vec<&Opt>)> = Vec::new();
    let mut subcommands = Vec::new();
    for option in options {
        match (option.kind, option.description, option.cat) {
            (Kind::Subcommand(_), Some(description), _) => subcommands.push((option.id.to_owned(), description.to_owned())),
            (Kind::Subcommand(_), None, _) => {}
            (_, Some(_), Some(cat)) => match categories.iter_mut().find(|(existing, _)| *existing == cat) {
                Some((_, members)) => members.push(option),
                None => categories.push((cat, vec![option])),
            },
            _ => {}
        }
    }
    for (cat, members) in categories {
        let title = HELP_CATEGORIES.iter().find(|(key, _)| *key == cat).expect("a help category").1;
        help.push(title.to_owned());
        help.extend(format_options(&members, columns));
        help.push(String::new());
    }
    if !subcommands.is_empty() {
        help.push("Subcommands".into());
        help.extend(format_usage_texts(&subcommands, columns));
        help.push(String::new());
    }
    help.join("\n")
}

pub fn build_stdin_message(executable_name: &str, is_chat: bool) -> String {
    let example = match is_chat {
        true => format!("ps aux | grep code | {executable_name} chat <prompt> -"),
        false => format!("ps aux | grep code | {executable_name} -"),
    };
    format!("To read from stdin, append '-' (e.g. '{example}')")
}

/// `buildVersionMessage`: version, commit and `process.arch`.
pub fn build_version_message(version: Option<&str>, commit: Option<&str>) -> String {
    let arch = if cfg!(target_arch = "aarch64") { "arm64" } else { "x64" };
    format!("{}\n{}\n{arch}", version.unwrap_or("Unknown version"), commit.unwrap_or("Unknown commit"))
}

/// extpath.ts `parseLineAndColumnAware`: `FILE:LINE(:COLUMN)`, the column 1 when only the line is given.
pub fn parse_line_and_column_aware(raw_path: &str) -> Result<(String, Option<u32>, Option<u32>), String> {
    let mut path: Option<String> = None;
    let (mut line, mut column) = (None, None);
    for segment in raw_path.split(':') {
        match js_number(segment) {
            None => path = Some(path.map_or_else(|| segment.to_owned(), |path| format!("{path}:{segment}"))),
            Some(number) if line.is_none() => line = Some(number),
            Some(number) if column.is_none() => column = Some(number),
            Some(_) => {}
        }
    }
    let path = path.filter(|path| !path.is_empty()).ok_or("Format for `--goto` should be: `FILE:LINE(:COLUMN)`")?;
    Ok((path, line, column.or(line.map(|_| 1))))
}

/// `Number(segment)` when it is not NaN, for the digits `--goto` passes validation with; `Number('')` is 0.
fn js_number(segment: &str) -> Option<u32> {
    let trimmed = segment.trim();
    if trimmed.is_empty() {
        return Some(0);
    }
    trimmed.parse().ok()
}

#[cfg(test)]
mod tests;