Skip to content

Visual Studio Code, rebuilt in Rust

Rust
18.6 KB
Raw Blame
//! code/node/cli.ts, run when `bin/<applicationName>` starts the app binary with `ELECTRON_RUN_AS_NODE=1` (the port of
//! resources/darwin/bin/code.sh): help and version, `-` reads stdin into a file, `--wait` waits for a marker file
//! the app deletes once the editors close, the extension commands run in this process (cli_process.rs), and every
//! other command line goes to the app.

use std::io::{IsTerminal, Read, Write};
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
#[cfg(unix)]
use std::os::unix::process::CommandExt;
#[cfg(windows)]
use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::Duration;

use crate::argv::{self, OPTIONS};
use crate::product;

/// `main(argv)`: the process exit code. As cli.js the arguments start after the binary and code.sh's `$CLI`.
/// `--version` of the app and its CLI: the display version, commit and arch.
pub fn version_message() -> String {
    argv::build_version_message(Some(&product::display_version()), product::get("commit").as_str())
}

pub fn main(process_args: Vec<String>, user_data: &Path, working_dir: &Path, app_root: &Path) -> i32 {
    let args = process_args.get(2..).unwrap_or_default();
    let (parsed, warnings) = match argv::parse_and_validate(args) {
        Ok(parsed) => parsed,
        // cli.ts prints the error and returns: the exit code stays 0.
        Err(error) => {
            eprintln!("{error}");
            return 0;
        }
    };
    for warning in warnings {
        eprintln!("{warning}");
    }
    let product = |key: &str| product::get(key).as_str();
    let executable = product("applicationName").expect("product.json has applicationName");
    if let Some((command, _)) = &parsed.subcommand {
        eprintln!("The '{command}' subcommand is not supported by {}.", product::name_long());
        return 1;
    }
    if parsed.flag("help") {
        println!("{}", argv::build_help_message(product::name_long(), executable, &product::display_version(), OPTIONS, false, terminal_columns()));
        return 0;
    }
    if parsed.flag("version") {
        println!("{}", version_message());
        return 0;
    }
    if crate::cli_process::handles(&parsed) {
        let run = crate::scan_system_extensions(app_root).and_then(|system| crate::cli_process::run(&parsed, user_data, working_dir, &system, &mut std::io::stdout()));
        return match run {
            Ok(()) => 0,
            Err(error) => {
                eprintln!("{error:#}");
                1
            }
        };
    }
    let mut argv = args.to_vec();
    let reads_stdin = parsed.positional.iter().any(|arg| arg == "-");
    argv.retain(|arg| arg != "-");
    let mut stdin_file = None;
    let mut stdin_reader = None;
    let piped_stdin = !std::io::stdin().is_terminal();
    if piped_stdin && reads_stdin {
        let path = random_path("code-stdin", 3);
        match create_user_only_file(&path) {
            Ok(file) => {
                let encoding = stdin_encoding(parsed.flag("verbose"));
                stdin_reader = Some(std::thread::spawn(move || copy_stdin(std::io::stdin().lock(), file, &encoding)));
                argv::add_arg(&mut argv, &[&path.to_string_lossy()]);
                argv::add_arg(&mut argv, &["--skip-add-to-recently-opened"]);
                println!("Reading from stdin via: {}", path.display());
                stdin_file = Some(path);
            }
            Err(error) => println!("Failed to create file to read via stdin: {error}"),
        }
    }
    let mut wait_marker = None;
    if parsed.flag("wait") {
        let path = random_path("", 8);
        match create_user_only_file(&path) {
            Ok(_) => {
                if parsed.flag("verbose") {
                    println!("Marker file for --wait created: {}", path.display());
                }
                argv::add_arg(&mut argv, &["--waitMarkerFilePath", &path.to_string_lossy()]);
                wait_marker = Some(path);
            }
            Err(error) if parsed.flag("verbose") => eprintln!("Failed to create marker file for --wait: {error}"),
            Err(_) => {}
        }
    }
    let shows_output = parsed.flag("verbose") || parsed.flag("status");
    let mut child = match spawn_app(&argv, shows_output) {
        Ok(child) => child,
        Err(error) => {
            eprintln!("{error}");
            return 1;
        }
    };
    // The user piped data but forgot the `-` argument.
    if piped_stdin && !reads_stdin && stdin_has_data_within(Duration::from_secs(1)) {
        println!("{}", argv::build_stdin_message(executable, false));
    }
    if parsed.flag("wait") {
        wait_until_deleted(wait_marker.as_deref(), &mut child);
        if let Some(path) = &stdin_file {
            let _ = std::fs::remove_file(path);
        }
    } else if let Some(reader) = stdin_reader {
        // Without `--wait` the CLI lives until stdin closed, so the file gets all of it.
        let _ = reader.join();
    }
    if shows_output {
        let _ = child.wait();
    }
    0
}

/// `ELECTRON_RUN_AS_NODE` dropped and `VSCODE_CLI` set (cli.ts, `isLaunchedFromCli`); on macOS through `open -n -g`
/// as upstream when the binary is in an app bundle, so the app starts as from the Dock (issue 102975). `--verbose`
/// and `--status` print the app's output: upstream redirects `open`'s to temp files, the port runs the binary.
fn spawn_app(argv: &[String], shows_output: bool) -> std::io::Result<std::process::Child> {
    let exe = std::env::current_exe()?;
    let mut env: Vec<(String, String)> = std::env::vars().filter(|(key, _)| key != "ELECTRON_RUN_AS_NODE" && key != "_").collect();
    env.push(("VSCODE_CLI".into(), "1".into()));
    // bootstrap-node.ts `setupCurrentWorkingDirectory`.
    if !env.iter().any(|(key, _)| key == "VSCODE_CWD") {
        env.push(("VSCODE_CWD".into(), std::env::current_dir()?.to_string_lossy().into_owned()));
    }
    env.push(("ELECTRON_NO_ATTACH_CONSOLE".into(), "1".into()));
    let bundled = exe.parent().and_then(Path::parent).is_some_and(|contents| contents.join("Info.plist").is_file());
    let mut command = match bundled && !shows_output {
        true => {
            let mut command = Command::new("/usr/bin/open");
            command.args(["-n", "-g", "-a"]).arg(&exe);
            for (key, value) in &env {
                command.arg("--env").arg(format!("{key}={value}"));
            }
            command.arg("--args").args(argv).env_clear().envs(env);
            command
        }
        false => {
            let mut command = Command::new(&exe);
            command.args(argv).env_clear().envs(env);
            #[cfg(unix)]
            command.process_group(0);
            // Node's `detached: true` on Windows: DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP.
            #[cfg(windows)]
            command.creation_flags(0x8 | 0x200);
            command
        }
    };
    if !shows_output {
        command.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
    }
    command.spawn()
}

/// cli.ts `--wait`: until the marker is deleted (pfs.ts `whenDeleted`, checked each second) or the launch failed.
fn wait_until_deleted(marker: Option<&Path>, child: &mut std::process::Child) {
    loop {
        if let Ok(Some(status)) = child.try_wait()
            && !status.success()
        {
            return;
        }
        if marker.is_none_or(|marker| !marker.exists()) {
            return;
        }
        std::thread::sleep(Duration::from_secs(1));
    }
}

/// extpath.ts `randomPath(tmpdir(), prefix, length)`.
fn random_path(prefix: &str, length: usize) -> PathBuf {
    let name = crate::local_history::random_name(length);
    std::env::temp_dir().join(if prefix.is_empty() { name } else { format!("{prefix}-{name}") })
}

/// stdin.ts `createStdInFile` and wait.ts `createWaitMarkerFileSync`: mode 0600 (vscode-remote-release 9048), and a
/// new file only, so a planted symlink in the temp folder is not followed.
#[cfg(unix)]
fn create_user_only_file(path: &Path) -> std::io::Result<std::fs::File> {
    std::fs::OpenOptions::new().write(true).create_new(true).mode(0o600).open(path)
}

/// Node ignores the mode on Windows; the temp folder is the user's own.
#[cfg(windows)]
fn create_user_only_file(path: &Path) -> std::io::Result<std::fs::File> {
    std::fs::OpenOptions::new().write(true).create_new(true).open(path)
}

/// stdin.ts `readFromStdin`: each chunk decoded from the terminal encoding and appended as it arrives, so watchers
/// see the file grow.
fn copy_stdin(mut stdin: impl Read, mut file: std::fs::File, encoding: &str) {
    let mut decoder = files::encoding::StreamDecoder::new(encoding);
    let mut buffer = [0; 64 * 1024];
    while let Ok(read) = stdin.read(&mut buffer) {
        let text = decoder.decode(&buffer[..read], read == 0);
        if file.write_all(text.as_bytes()).is_err() || read == 0 {
            return;
        }
    }
}

/// stdin.ts `readFromStdin`: `resolveTerminalEncoding`, UTF-8 when iconv-lite does not know it.
fn stdin_encoding(verbose: bool) -> String {
    let encoding = terminal_encoding(verbose);
    if files::encoding::exists(&encoding) {
        return encoding;
    }
    println!("Unsupported terminal encoding: {encoding}, falling back to UTF-8.");
    files::encoding::UTF8.to_string()
}

/// terminalEncoding.ts `resolveTerminalEncoding`: `VSCODE_CLI_ENCODING`, else `locale charmap`.
fn terminal_encoding(verbose: bool) -> String {
    let raw = match std::env::var("VSCODE_CLI_ENCODING").ok().filter(|encoding| !encoding.is_empty()) {
        Some(encoding) => {
            if verbose {
                println!("Found VSCODE_CLI_ENCODING variable: {encoding}");
            }
            encoding
        }
        #[cfg(windows)]
        None => {
            if verbose {
                println!("Running \"chcp\" to detect terminal encoding...");
            }
            // Node's `exec` runs it through cmd.exe, which finds chcp.com; Command only adds `.exe`.
            let stdout = Command::new("chcp.com").output().map(|output| String::from_utf8_lossy(&output.stdout).into_owned()).unwrap_or_default();
            if verbose && !stdout.is_empty() {
                println!("Output from \"chcp\" command is: {stdout}");
            }
            windows_terminal_encoding(&stdout).unwrap_or_default().to_owned()
        }
        #[cfg(unix)]
        None => {
            if verbose {
                println!("Running \"locale charmap\" to detect terminal encoding...");
            }
            let output = Command::new("/bin/sh").args(["-c", "locale charmap"]).output();
            output.map(|output| String::from_utf8_lossy(&output.stdout).into_owned()).unwrap_or_default()
        }
    };
    if verbose {
        println!("Detected raw terminal encoding: {raw}");
    }
    to_iconv_lite_encoding(&raw)
}

/// terminalEncoding.ts `windowsTerminalEncodings`: the first code page, in key order, that `chcp`'s output contains.
#[cfg(any(windows, test))]
fn windows_terminal_encoding(chcp: &str) -> Option<&'static str> {
    const ENCODINGS: [(&str, &str); 13] = [
        ("437", "cp437"),
        ("850", "cp850"),
        ("852", "cp852"),
        ("855", "cp855"),
        ("857", "cp857"),
        ("860", "cp860"),
        ("861", "cp861"),
        ("863", "cp863"),
        ("865", "cp865"),
        ("866", "cp866"),
        ("869", "cp869"),
        ("936", "cp936"),
        ("1252", "cp1252"),
    ];
    ENCODINGS.iter().find(|(page, _)| chcp.contains(page)).map(|(_, encoding)| *encoding)
}

/// `resolveTerminalEncoding`'s mapping of the raw name: empty and UTF-8 are `utf8`; others lose every character but
/// letters and digits (`toIconvLiteEncoding`).
fn to_iconv_lite_encoding(raw: &str) -> String {
    if raw.is_empty() || raw.eq_ignore_ascii_case("utf-8") || raw.eq_ignore_ascii_case(files::encoding::UTF8) {
        return files::encoding::UTF8.to_string();
    }
    let normalized = raw.chars().filter(char::is_ascii_alphanumeric).collect::<String>().to_ascii_lowercase();
    match normalized.as_str() {
        "ibm866" => "cp866".into(),
        "big5" => "cp950".into(),
        _ => normalized,
    }
}

/// stdin.ts `stdinDataListener`: whether a `data` event comes within `timeout`; an end of input is none.
#[cfg(windows)]
fn stdin_has_data_within(timeout: Duration) -> bool {
    let (sender, receiver) = std::sync::mpsc::channel();
    // A pipe without data blocks the read; the thread ends with the process.
    std::thread::spawn(move || sender.send(std::io::stdin().read(&mut [0]).is_ok_and(|read| read > 0)));
    receiver.recv_timeout(timeout).unwrap_or(false)
}

/// stdin.ts `stdinDataListener`: whether a `data` event comes within `timeout`; an end of input is none.
#[cfg(unix)]
fn stdin_has_data_within(timeout: Duration) -> bool {
    let mut poll = libc::pollfd { fd: libc::STDIN_FILENO, events: libc::POLLIN, revents: 0 };
    // SAFETY: one valid pollfd for the length passed.
    let ready = unsafe { libc::poll(&mut poll, 1, timeout.as_millis() as i32) };
    ready > 0 && std::io::stdin().read(&mut [0]).is_ok_and(|read| read > 0)
}

/// Chromium's `base::RouteStdioToConsole(false)`: output not redirected goes to the console of the process that
/// started this GUI binary, when it has one.
#[cfg(windows)]
pub fn route_stdio_to_console() {
    use windows_sys::Win32::Foundation::{GENERIC_READ, GENERIC_WRITE, INVALID_HANDLE_VALUE};
    use windows_sys::Win32::Storage::FileSystem::{CreateFileW, FILE_SHARE_READ, FILE_SHARE_WRITE, OPEN_EXISTING};
    use windows_sys::Win32::System::Console::{ATTACH_PARENT_PROCESS, AttachConsole, GetStdHandle, STD_ERROR_HANDLE, STD_HANDLE, STD_OUTPUT_HANDLE, SetStdHandle};
    let redirected = |id: STD_HANDLE| {
        // SAFETY: GetStdHandle takes a handle id and returns a handle or null; no pointers pass.
        let handle = unsafe { GetStdHandle(id) };
        !handle.is_null() && handle != INVALID_HANDLE_VALUE
    };
    if redirected(STD_OUTPUT_HANDLE) || redirected(STD_ERROR_HANDLE) {
        return;
    }
    // SAFETY: AttachConsole takes a process id constant; no pointers pass.
    if unsafe { AttachConsole(ATTACH_PARENT_PROCESS) } == 0 {
        return;
    }
    let name: Vec<u16> = "CONOUT$".encode_utf16().chain([0]).collect();
    // SAFETY: `name` is NUL-terminated UTF-16, alive for the call; the security and template arguments may be null.
    let console = unsafe { CreateFileW(name.as_ptr(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, std::ptr::null(), OPEN_EXISTING, 0, std::ptr::null_mut()) };
    if console == INVALID_HANDLE_VALUE {
        return;
    }
    // SAFETY: a console handle that lives until the process ends.
    unsafe {
        SetStdHandle(STD_OUTPUT_HANDLE, console);
        SetStdHandle(STD_ERROR_HANDLE, console);
    }
}

/// `process.stdout.columns` on a console (libuv's visible window width), else 80 (argv.ts `buildHelpMessage`).
#[cfg(windows)]
fn terminal_columns() -> usize {
    use windows_sys::Win32::System::Console::{CONSOLE_SCREEN_BUFFER_INFO, GetConsoleScreenBufferInfo, GetStdHandle, STD_OUTPUT_HANDLE};
    // SAFETY: CONSOLE_SCREEN_BUFFER_INFO is plain integers, valid when zeroed.
    let mut info: CONSOLE_SCREEN_BUFFER_INFO = unsafe { std::mem::zeroed() };
    // SAFETY: the standard output handle and one info struct for the call to fill.
    let ok = unsafe { GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &mut info) } != 0;
    let columns = i32::from(info.srWindow.Right) - i32::from(info.srWindow.Left) + 1;
    if ok && columns > 0 && std::io::stdout().is_terminal() { columns as usize } else { 80 }
}

/// `process.stdout.columns` on a terminal, else 80 (argv.ts `buildHelpMessage`).
#[cfg(unix)]
fn terminal_columns() -> usize {
    let mut size = libc::winsize { ws_row: 0, ws_col: 0, ws_xpixel: 0, ws_ypixel: 0 };
    // SAFETY: TIOCGWINSZ writes one winsize to the pointer.
    let ok = unsafe { libc::ioctl(libc::STDOUT_FILENO, libc::TIOCGWINSZ, &mut size) } == 0;
    if ok && size.ws_col > 0 && std::io::stdout().is_terminal() { usize::from(size.ws_col) } else { 80 }
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    #[test]
    fn version_message_names_the_release() {
        crate::product::load(Path::new(env!("VSCODE_SRC")), false);
        let release = crate::product::get("release").as_u64().unwrap();
        assert!(super::version_message().starts_with(&format!("1.148.0.{release}\n")));
    }

    #[test]
    fn chcp_output_maps_to_the_windows_terminal_encoding() {
        assert_eq!(super::windows_terminal_encoding("Active code page: 852\r\n"), Some("cp852"));
        assert_eq!(super::windows_terminal_encoding("Aktywna strona kodowa: 1252"), Some("cp1252"));
        assert_eq!(super::windows_terminal_encoding("Active code page: 65001"), None);
        assert_eq!(super::windows_terminal_encoding(""), None);
    }

    #[test]
    fn terminal_encodings_map_to_iconv_lite_names() {
        assert_eq!(super::to_iconv_lite_encoding(""), "utf8");
        assert_eq!(super::to_iconv_lite_encoding("UTF-8\n"), "utf8");
        assert_eq!(super::to_iconv_lite_encoding("ISO-8859-1\n"), "iso88591");
        assert_eq!(super::to_iconv_lite_encoding("IBM866"), "cp866");
        assert_eq!(super::to_iconv_lite_encoding("BIG5"), "cp950");
    }

    #[test]
    fn piped_input_is_written_as_text_of_the_terminal_encoding() {
        let path = std::env::temp_dir().join(format!("vsrustium-cli-stdin-{}", std::process::id()));
        let file = std::fs::File::create(&path).unwrap();
        super::copy_stdin(&[b'G', 0xFC, b'n'][..], file, "iso88591");
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "Gün");
        std::fs::remove_file(path).unwrap();
    }

    #[test]
    fn uninstall_extension_runs_in_the_cli_without_the_app() {
        let root = std::env::temp_dir().join(format!("vsrustium-cli-uninstall-{}", std::process::id()));
        let extensions = root.join("extensions");
        std::fs::create_dir_all(extensions.join("port.sample-1.0.0")).unwrap();
        let manifest = serde_json::json!({ "name": "sample", "publisher": "port", "version": "1.0.0", "engines": { "vscode": "^1.80.0" } });
        std::fs::write(extensions.join("port.sample-1.0.0/package.json"), manifest.to_string()).unwrap();
        let entries = serde_json::json!([{ "identifier": { "id": "port.sample" }, "version": "1.0.0", "relativeLocation": "port.sample-1.0.0" }]);
        std::fs::write(extensions.join("extensions.json"), entries.to_string()).unwrap();

        let args = ["vsrustium", "cli.js", "--uninstall-extension", "port.sample"].map(String::from).to_vec();
        assert_eq!(super::main(args, &root, &root, Path::new(env!("VSCODE_SRC"))), 0);

        let profile = std::fs::read_to_string(extensions.join("extensions.json")).unwrap();
        std::fs::remove_dir_all(&root).unwrap();
        assert_eq!(profile, "[]", "the extension is uninstalled before the CLI exits");
    }
}