Skip to content

Visual Studio Code, rebuilt in Rust

Rust
7.8 KB
Raw Blame
//! installActions.ts and nativeHostMainService.ts's macOS Shell Command: `/usr/local/bin/<applicationName>` links to
//! the app's bin/code, which port/tools/package-app writes from code.sh; on Linux `~/.local/bin/<applicationName>`.

use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::process::Command;

use gpui::{AsyncWindowContext, PromptLevel};

use super::Workbench;
use crate::commands::Outcome;
use crate::dialog::{self, InTests};
use crate::product;

impl Workbench {
    pub(super) fn register_shell_command_commands(&mut self) {
        self.commands.register("workbench.action.installCommandLine", |workbench, _, window, cx| {
            let link = shell_command_link(&workbench.app_root, &command_folder());
            cx.spawn_in(window, async move |_, cx| {
                let installed = match link {
                    Ok(link) => install_shell_command(&link, cx).await,
                    Err(error) => Err(error),
                };
                report(installed, "successfully installed in PATH", cx);
            })
            .detach();
            Outcome::done()
        });
        self.commands.register("workbench.action.uninstallCommandLine", |workbench, _, window, cx| {
            let link = shell_command_link(&workbench.app_root, &command_folder());
            cx.spawn_in(window, async move |_, cx| {
                let uninstalled = match link {
                    Ok(link) => uninstall_shell_command(&link, cx).await,
                    Err(error) => Err(error),
                };
                report(uninstalled, "successfully uninstalled from PATH", cx);
            })
            .detach();
            Outcome::done()
        });
    }
}

/// `getShellCommandLink`: `source` is the command in PATH, `target` the app's script.
#[derive(Debug)]
struct ShellCommandLink {
    source: PathBuf,
    target: PathBuf,
}

fn application_name() -> &'static str {
    product::get("applicationName").as_str().expect("product.json has applicationName")
}

fn shell_command_link(app_root: &Path, bin: &Path) -> Result<ShellCommandLink, String> {
    let target = shell_script(app_root);
    if !target.exists() {
        return Err(format!("Unable to find shell script in '{}'", target.display()));
    }
    Ok(ShellCommandLink { source: bin.join(application_name()), target })
}

/// The app's command line script: package-app writes `<bundle>/Contents/Resources/app/bin/code`.
#[cfg(target_os = "macos")]
fn shell_script(app_root: &Path) -> PathBuf {
    app_root.join("bin/code")
}

/// package-linux writes `bin/<applicationName>` beside `resources/app`, as VS Code's Linux archive.
#[cfg(target_os = "linux")]
fn shell_script(app_root: &Path) -> PathBuf {
    app_root.ancestors().nth(2).unwrap_or(app_root).join("bin").join(application_name())
}

/// The folder in PATH the command goes to: on Linux the user's own, which needs no privileges and which the
/// desktop file's `Exec=<applicationName>` finds.
fn command_folder() -> PathBuf {
    match cfg!(target_os = "linux") {
        true => PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(".local/bin"),
        false => PathBuf::from("/usr/local/bin"),
    }
}

/// `installShellCommand`: unless the link is there already, always through `osascript` with administrator
/// privileges; `Ok(false)` when the user cancelled the privileges prompt. Linux, where upstream has no Shell
/// Command, links into the user's own `~/.local/bin` without a prompt.
async fn install_shell_command(link: &ShellCommandLink, cx: &mut AsyncWindowContext) -> Result<bool, String> {
    if is_installed(link).map_err(|error| error.to_string())? {
        return Ok(true);
    }
    if cfg!(target_os = "linux") {
        let installed = Command::new("/bin/sh").arg("-c").arg(install_script(link)).status().is_ok_and(|status| status.success());
        return installed.then_some(true).ok_or_else(|| format!("Unable to install the shell command '{}'.", link.source.display()));
    }
    let message = format!("{} will now prompt with 'osascript' for Administrator privileges to install the shell command.", product::name_short());
    if !confirm_escalation(&message, cx).await {
        return Ok(false);
    }
    let script = install_script(link);
    run_with_administrator_privileges(&script, cx).await.map_err(|_| format!("Unable to install the shell command '{}'.", link.source.display()))?;
    Ok(true)
}

/// `uninstallShellCommand`; `Ok(false)` when the user cancelled the privileges prompt.
async fn uninstall_shell_command(link: &ShellCommandLink, cx: &mut AsyncWindowContext) -> Result<bool, String> {
    match std::fs::remove_file(&link.source) {
        Ok(()) => Ok(true),
        Err(error) if error.kind() == ErrorKind::NotFound => Ok(true),
        Err(error) if cfg!(target_os = "macos") && error.kind() == ErrorKind::PermissionDenied => {
            let message = format!("{} will now prompt with 'osascript' for Administrator privileges to uninstall the shell command.", product::name_short());
            if !confirm_escalation(&message, cx).await {
                return Ok(false);
            }
            let script = format!("rm {}", shell_quote(&link.source));
            run_with_administrator_privileges(&script, cx).await.map_err(|_| format!("Unable to uninstall the shell command '{}'.", link.source.display()))?;
            Ok(true)
        }
        Err(error) => Err(error.to_string()),
    }
}

/// `source` is a symbolic link resolving to `target`.
fn is_installed(link: &ShellCommandLink) -> std::io::Result<bool> {
    match std::fs::symlink_metadata(&link.source) {
        Ok(metadata) => Ok(metadata.is_symlink() && std::fs::canonicalize(&link.source).ok() == std::fs::canonicalize(&link.target).ok()),
        Err(error) if error.kind() == ErrorKind::NotFound => Ok(false),
        Err(error) => Err(error),
    }
}

fn install_script(link: &ShellCommandLink) -> String {
    let bin = link.source.parent().expect("the command is in a folder");
    format!("mkdir -p {} && ln -sf {} {}", shell_quote(bin), shell_quote(&link.target), shell_quote(&link.source))
}

/// The `osascript` arguments: the shell script as an AppleScript string literal, run without a shell in between.
fn administrator_arguments(script: &str) -> [String; 2] {
    ["-e".into(), format!("do shell script {} with administrator privileges", applescript_string(script))]
}

async fn run_with_administrator_privileges(script: &str, cx: &mut AsyncWindowContext) -> Result<(), ()> {
    let arguments = administrator_arguments(script);
    let output = cx.background_executor().spawn(async move { Command::new("/usr/bin/osascript").args(arguments).output() }).await;
    match output {
        Ok(output) if output.status.success() => Ok(()),
        _ => Err(()),
    }
}

/// The privileges prompt's OK and Cancel, a main process message box.
async fn confirm_escalation(message: &str, cx: &mut AsyncWindowContext) -> bool {
    let Ok(answer) = cx.update(|window, cx| dialog::show_message_box(window, InTests::Show, PromptLevel::Info, message, None, &["OK", "Cancel"], None, cx)) else {
        return false;
    };
    matches!(answer.await, Ok((0, _)))
}

/// installActions.ts: `dialogService.info` on success, `dialogService.error` on failure, nothing on cancel.
fn report(result: Result<bool, String>, done: &str, cx: &mut AsyncWindowContext) {
    let (level, message) = match result {
        Ok(false) => return,
        Ok(true) => (PromptLevel::Info, format!("Shell command '{}' {done}.", application_name())),
        Err(error) => (PromptLevel::Critical, error),
    };
    let _ = cx.update(|window, cx| drop(dialog::show_message_box(window, InTests::Refuse, level, &message, None, &["OK"], None, cx)));
}

fn shell_quote(path: &Path) -> String {
    format!("'{}'", path.to_string_lossy().replace('\'', r"'\''"))
}

fn applescript_string(text: &str) -> String {
    format!("\"{}\"", text.replace('\\', r"\\").replace('"', r#"\""#))
}

#[cfg(test)]
mod tests;