Skip to content

Visual Studio Code, rebuilt in Rust

Rust
2.8 KB
Raw Blame
use std::path::{Path, PathBuf};
use std::process::Command;

use super::*;

fn temp_dir(name: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("code-gpui-shell-command-{name}-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    dir
}

fn app_with_script(dir: &Path) -> PathBuf {
    let app_root = dir.join("VSRustium.app/Contents/Resources/app");
    std::fs::create_dir_all(shell_script(&app_root).parent().unwrap()).unwrap();
    std::fs::write(shell_script(&app_root), "#!/usr/bin/env bash\n").unwrap();
    app_root
}

#[test]
fn the_link_needs_the_apps_script() {
    let dir = temp_dir("missing");
    let error = shell_command_link(&dir, &dir.join("bin")).unwrap_err();
    assert_eq!(error, format!("Unable to find shell script in '{}'", shell_script(&dir).display()));
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn install_links_the_command_to_the_apps_script() {
    let dir = temp_dir("install");
    let link = shell_command_link(&app_with_script(&dir), &dir.join("usr/local/bin")).unwrap();
    assert_eq!(link.source, dir.join("usr/local/bin").join(application_name()));
    assert!(!is_installed(&link).unwrap());

    // `ln -sf` replaces what is there.
    std::fs::create_dir_all(link.source.parent().unwrap()).unwrap();
    std::fs::write(&link.source, "an older command").unwrap();
    assert!(!is_installed(&link).unwrap());
    // The privileged script, run here as the user on a temp folder.
    assert!(Command::new("/bin/sh").arg("-c").arg(install_script(&link)).status().unwrap().success());
    assert!(is_installed(&link).unwrap());
    assert_eq!(std::fs::read_link(&link.source).unwrap(), link.target);
    std::fs::remove_dir_all(&dir).unwrap();
}

// osascript: the Linux install is the M23 Linux row of shell_command.rs.
#[cfg(target_os = "macos")]
#[test]
fn the_privileged_script_quotes_every_path() {
    let dir = temp_dir("quote");
    let odd = dir.join(r#"it's "a" $(touch pwned) \ `touch pwned`"#);
    let link = shell_command_link(&app_with_script(&odd), &odd.join("bin")).unwrap();
    let script = install_script(&link);

    let status = Command::new("/bin/sh").arg("-c").arg(&script).current_dir(&dir).status().unwrap();
    assert!(status.success(), "{script}");
    assert!(is_installed(&link).unwrap(), "{script}");
    assert!(!dir.join("pwned").exists());

    // The AppleScript literal hands osascript the script unchanged.
    let [_, statement] = administrator_arguments(&script);
    let literal = statement.strip_prefix("do shell script ").unwrap().strip_suffix(" with administrator privileges").unwrap();
    let output = Command::new("/usr/bin/osascript").arg("-e").arg(format!("return {literal}")).output().unwrap();
    assert_eq!(String::from_utf8(output.stdout).unwrap().trim_end_matches('\n'), script);
    std::fs::remove_dir_all(&dir).unwrap();
}