Visual Studio Code, rebuilt in Rust
Rust
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::time::{Duration, Instant};
use ghostty_vt::{Column, Line, Point};
use super::pty::PtyEvent;
use super::*;
fn dark_colors() -> colors::TerminalColors {
let app_root = std::path::Path::new(env!("VSCODE_SRC")).to_path_buf();
let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
colors::TerminalColors::new(&crate::theme::load_theme(&[themes], "Dark Modern").unwrap())
}
/// `sh -c`, on Windows `cmd.exe /c` with the process's environment, which cmd.exe needs (`SystemRoot`).
fn shell(sh_script: &str, cmd_script: &str) -> ShellLaunchConfig {
let (executable, args, env) = if cfg!(windows) {
("cmd.exe", vec!["/c".into(), cmd_script.into()], std::env::vars().collect())
} else {
("/bin/sh", vec!["-c".into(), sh_script.into()], HashMap::from([("PATH".into(), "/usr/bin:/bin".into())]))
};
ShellLaunchConfig { executable: executable.into(), args, cwd: std::env::temp_dir(), env, ..Default::default() }
}
fn screen_line(instance: &TerminalInstance, line: i32) -> String {
let columns = instance.term.columns();
(0..columns).map(|column| instance.term.cell(Point::new(Line(line), Column(column))).c).collect::<String>().trim_end().to_owned()
}
#[test]
fn a_shell_runs_in_a_pty_and_its_output_reaches_the_screen() {
let launch = if cfg!(windows) {
let script = "Write-Output ('cols=' + $Host.UI.RawUI.WindowSize.Width); Write-Host -NoNewline ([char]27 + '[31mred' + [char]27 + '[0m'); exit 3";
ShellLaunchConfig { executable: "powershell.exe".into(), args: vec!["-NoProfile".into(), "-Command".into(), script.into()], cwd: std::env::temp_dir(), env: std::env::vars().collect(), ..Default::default() }
} else {
ShellLaunchConfig {
executable: "/bin/sh".into(),
args: vec!["-c".into(), "printf 'cols=%s\\n' \"$(tput cols)\"; printf '\\033[31mred\\033[0m'; exit 3".into()],
cwd: std::env::temp_dir(),
env: HashMap::from([("TERM".into(), "xterm-256color".into()), ("PATH".into(), "/usr/bin:/bin".into())]),
..Default::default()
}
};
let colors = dark_colors();
let (mut instance, receiver) = TerminalInstance::new(1, launch, 40, 5, Config { scrolling_history: 1000, ..Config::default() });
let mut receiver = receiver.expect("the shell spawned");
let deadline = Instant::now() + Duration::from_secs(10);
while instance.exit_code.is_none() && Instant::now() < deadline {
match receiver.try_recv() {
Ok(PtyEvent::Data(bytes)) => _ = instance.process(&bytes, &colors),
Ok(PtyEvent::Exit(code)) => instance.exited(code),
Err(_) => std::thread::sleep(Duration::from_millis(10)),
}
}
assert_eq!(instance.exit_code, Some(Some(3)));
assert_eq!(screen_line(&instance, 0), "cols=40");
assert_eq!(screen_line(&instance, 1), "red");
let red = &instance.term.cell(Point::new(Line(1), Column(0)));
assert_eq!(red.fg, ghostty_vt::Color::Indexed(1));
}
/// childProcessMonitor.ts `hasChildProcesses`: a background job of the shell counts, a shell alone does not.
#[test]
fn a_background_job_is_a_child_process_of_the_shell() {
let has_children_once_started = |sh_script: &str, cmd_script: &str| {
let launch = shell(sh_script, cmd_script);
let (instance, receiver) = TerminalInstance::new(1, launch, 40, 5, Config::default());
let mut receiver = receiver.expect("the shell spawned");
let deadline = Instant::now() + Duration::from_secs(10);
let mut output = Vec::new();
while !String::from_utf8_lossy(&output).contains("started") && Instant::now() < deadline {
match receiver.try_recv() {
Ok(PtyEvent::Data(bytes)) => output.extend(bytes),
_ => std::thread::sleep(Duration::from_millis(10)),
}
}
instance.has_child_processes()
};
assert!(has_children_once_started("sleep 5 & echo started; read line", "start /b ping -n 6 127.0.0.1 >nul & echo started & set /p line="));
assert!(!has_children_once_started("echo started; read line", "echo started & set /p line="));
}
fn run_to_exit(instance: &mut TerminalInstance, mut receiver: futures::channel::mpsc::UnboundedReceiver<PtyEvent>, colors: &colors::TerminalColors) {
let deadline = Instant::now() + Duration::from_secs(10);
while instance.exit_code.is_none() && Instant::now() < deadline {
match receiver.try_recv() {
Ok(PtyEvent::Data(bytes)) => _ = instance.process(&bytes, colors),
Ok(PtyEvent::Exit(code)) => instance.exited(code),
Err(_) => std::thread::sleep(Duration::from_millis(10)),
}
}
}
#[test]
fn a_reused_terminal_runs_the_next_process_below_the_last_one_and_keeps_its_name() {
let launch = |sh_script: &str, cmd_script: &str| ShellLaunchConfig { name: Some("first".into()), ..shell(sh_script, cmd_script) };
let colors = dark_colors();
let (mut instance, receiver) = TerminalInstance::new(1, launch("printf one", "<nul set /p =one"), 40, 5, Config::default());
run_to_exit(&mut instance, receiver.expect("the shell spawned"), &colors);
instance.waiting_on_exit = true;
let receiver = instance.reuse(ShellLaunchConfig { name: Some("second".into()), ..shell("printf two; exit 2", "<nul set /p =two & exit /b 2") }, "next\r\n", &colors);
assert!(!instance.waiting_on_exit && instance.exit_code.is_none());
run_to_exit(&mut instance, receiver.expect("the shell spawned again"), &colors);
assert_eq!(instance.exit_code, Some(Some(2)));
assert_eq!([0, 1, 2].map(|line| screen_line(&instance, line)), ["one", "next", "two"]);
assert_eq!(instance.title(), "first");
}
#[test]
fn the_environment_drops_vscode_variables_and_adds_terminal_keys() {
let base = [("PATH", "/bin"), ("VSCODE_PID", "1"), ("VSCODE_SHELL_LOGIN", "1"), ("ELECTRON_RUN_AS_NODE", "1"), ("VSCODE_NODE_OPTIONS", "--x"), ("HOME", "/h")];
let base = base.into_iter().map(|(key, value)| (key.to_owned(), value.to_owned()));
let overrides = [HashMap::from([("HOME".to_owned(), None), ("FOO".to_owned(), Some("bar".to_owned()))])];
let env = create_environment(base, &overrides, "1.147.0", "en", "auto");
let mut keys: Vec<_> = env.iter().map(|(key, value)| format!("{key}={value}")).collect();
keys.sort();
assert_eq!(
keys,
["COLORTERM=truecolor", "FOO=bar", "LANG=en_US.UTF-8", "NODE_OPTIONS=--x", "PATH=/bin", "TERM=xterm-256color", "TERM_PROGRAM=vscode", "TERM_PROGRAM_VERSION=1.147.0", "VSCODE_SHELL_LOGIN=1"]
);
assert_eq!(lang_variable("pt-br"), "pt_BR.UTF-8");
assert_eq!(lang_variable("xx"), "xx.UTF-8");
let kept = create_environment([("LANG".to_owned(), "pl_PL.UTF-8".to_owned())].into_iter(), &[], "1", "en", "auto");
assert_eq!(kept["LANG"], "pl_PL.UTF-8");
}
#[test]
fn paste_uses_carriage_returns_and_bracketed_paste_markers() {
assert_eq!(paste_data("a\r\nb\nc", false), "a\rb\rc");
assert_eq!(paste_data("a\n", true), "\x1b[200~a\r\x1b[201~");
assert_eq!(paste_data("a\x1b[201~rm -rf ~\n", true), "\x1b[200~a\u{241b}[201~rm -rf ~\r\x1b[201~");
assert_eq!(paste_data("\x1b", false), "\x1b");
let launch = ShellLaunchConfig { executable: "/bin/cat".into(), cwd: std::env::temp_dir(), ..Default::default() };
let colors = dark_colors();
let (mut instance, _receiver) = TerminalInstance::new(1, launch, 20, 3, Config { scrolling_history: 100, ..Config::default() });
instance.process(b"\x1b[?2004h", &colors);
assert!(instance.term.mode().contains(TermMode::BRACKETED_PASTE));
instance.process(b"abc\r\ndef", &colors);
instance.select_all();
assert_eq!(instance.selection_text().as_deref(), Some("abc\ndef\n"));
}
/// Record Terminal Session: output, typed input and sent text are separate events, a resize records the new size.
#[test]
fn a_recording_keeps_each_kind_of_event() {
let launch = ShellLaunchConfig { extension_pty: true, cwd: std::env::temp_dir(), ..Default::default() };
let (mut instance, _receiver) = TerminalInstance::new(1, launch, 20, 3, Config::default());
instance.process_input = Some(Box::new(|_: &str| {}));
instance.input("not recorded");
instance.recording = Some(Recording { events: Vec::new(), last_event: Instant::now() });
let colors = dark_colors();
instance.process(b"out", &colors);
instance.input("a");
instance.send_text("ls", true);
instance.resize(30, 4);
let events = instance.recording.unwrap().events;
assert_eq!(serde_json::Value::Array(events), json!([
{ "type": "output", "data": "out" },
{ "type": "input", "data": "a" },
{ "type": "sendText", "data": "ls\r" },
{ "type": "resize", "cols": 30, "rows": 4 },
]));
}
#[test]
fn osc_52_stores_and_reads_the_clipboard() {
let launch = ShellLaunchConfig { extension_pty: true, cwd: std::env::temp_dir(), ..Default::default() };
let (mut instance, _receiver) = TerminalInstance::new(1, launch, 20, 3, Config::default());
let written = Rc::new(RefCell::new(String::new()));
let sink = written.clone();
instance.process_input = Some(Box::new(move |data: &str| sink.borrow_mut().push_str(data)));
let colors = dark_colors();
instance.process(b"\x1b]52;c;aGk=\x07\x1b]52;c;?\x07", &colors);
assert_eq!(instance.clipboard_requests, ["hi"]);
instance.answer_clipboard_loads("hey");
assert_eq!(*written.borrow(), "\x1b]52;c;aGV5\x07");
assert!(instance.clipboard_loads.is_empty());
instance.process(b"\x1b]52;c\rrm -rf ~\r;?\x07", &colors);
instance.answer_clipboard_loads("");
assert_eq!(*written.borrow(), "\x1b]52;c;aGV5\x07\x1b]52;crm -rf ~;\x07", "the reply carries no control characters");
}
#[test]
fn clear_keeps_the_cursor_line_as_the_first_line() {
let launch = ShellLaunchConfig { executable: "/bin/cat".into(), cwd: std::env::temp_dir(), ..Default::default() };
let colors = dark_colors();
let (mut instance, _receiver) = TerminalInstance::new(1, launch, 20, 3, Config { scrolling_history: 100, ..Config::default() });
instance.process(b"1\r\n2\r\n3\r\n4\r\n$ ab", &colors);
assert!(instance.term.history_size() > 0);
instance.clear();
assert_eq!(instance.term.history_size(), 0);
assert_eq!(screen_line(&instance, 0), "$ ab");
assert_eq!(screen_line(&instance, 1), "");
assert_eq!(instance.term.cursor().point, Point::new(Line(0), Column(4)));
}
/// terminalInstance.ts `_onProcessExit`: after the launch, an exit alert shows with `showExitAlert` unless the last
/// input was Ctrl+D (xtermTerminal.ts `lastInputEvent`).
#[test]
fn a_ctrl_d_exit_shows_no_exit_alert() {
let launch = ShellLaunchConfig { executable: "/bin/cat".into(), cwd: std::env::temp_dir(), ..Default::default() };
let (mut instance, _receiver) = TerminalInstance::new(1, launch, 20, 3, Config { scrolling_history: 100, ..Config::default() });
instance.launched = std::time::Instant::now() - std::time::Duration::from_secs(1);
instance.input("a");
assert_eq!((instance.shows_exit_alert(true), instance.shows_exit_alert(false)), (true, false));
instance.input("\x04");
assert!(!instance.shows_exit_alert(true), "Ctrl+D ended the process");
instance.launched = std::time::Instant::now();
assert!(instance.shows_exit_alert(false), "a failed launch always alerts");
}
#[test]
fn exit_messages_follow_parse_exit_result() {
let launch = ShellLaunchConfig { executable: "/bin/zsh".into(), args: vec!["-l".into(), "-i".into()], cwd: std::env::temp_dir(), ..Default::default() };
let (mut instance, _receiver) = TerminalInstance::new(1, launch, 20, 3, Config { scrolling_history: 100, ..Config::default() });
// A loaded `cargo test` can take longer than ERROR_LAUNCH_THRESHOLD to spawn the login shell.
instance.launched = std::time::Instant::now();
assert_eq!(instance.exit_message(0), None);
assert_eq!(instance.exit_message(1).as_deref(), Some("The terminal process \"/bin/zsh '-l', '-i'\" failed to launch (exit code: 1)."));
instance.kill();
assert_eq!(instance.exit_message(2).as_deref(), Some("The terminal process \"/bin/zsh '-l', '-i'\" terminated with exit code: 2."));
}
/// terminalTaskSystem.ts: a task terminal's initial text echoes the command, `writeln` leaves a blank line before the
/// output, and the reuse message's D sequence ends the command the A..C sequences started, with its exit code.
#[test]
fn a_task_terminal_echoes_its_command_and_records_it_as_a_command() {
let launch = ShellLaunchConfig { extension_pty: true, cwd: std::env::temp_dir(), nonce: "n".into(), ..Default::default() };
let (mut instance, _receiver) = TerminalInstance::new(1, launch, 60, 6, Config::default());
let colors = dark_colors();
let command_line = format!("{};n", shell_integration::serialize_message("echo hi"));
instance.process(task_initial_text(std::path::Path::new("/w"), Some("Executing task: echo hi"), Some(&command_line)).as_bytes(), &colors);
instance.process(b"hi\r\n", &colors);
instance.process(format_message_for_terminal("\x1b]633;D;0\x07Terminal will be reused").as_bytes(), &colors);
let lines: Vec<String> = (0..4).map(|line| screen_line(&instance, line)).collect();
assert_eq!(lines, [" * Executing task: echo hi", "", "hi", " * Terminal will be reused"]);
let command = &instance.commands[0];
assert_eq!((command.command.as_str(), command.exit_code, command.prompt_line, command.is_trusted), ("echo hi", Some(0), Some(0), true));
}
/// terminalStatusList.ts `primary`: the most severe status, a later one winning a tie unless only the earlier has an icon.
#[test]
fn the_primary_status_is_the_most_severe() {
let launch = ShellLaunchConfig { extension_pty: true, cwd: std::env::temp_dir(), ..Default::default() };
let (mut instance, _receiver) = TerminalInstance::new(1, launch, 20, 3, Config::default());
let status = |id, severity, icon| TerminalStatus { id, severity, icon, tooltip: None };
instance.add_status(status("a", 1, Some("check")));
instance.add_status(status("b", 1, None));
assert_eq!(instance.primary_status().map(|status| status.id), Some("a"));
instance.add_status(status("c", 3, Some("error")));
assert_eq!(instance.primary_status().map(|status| status.id), Some("c"));
instance.add_status(status("a", 3, Some("warning")));
assert_eq!(instance.primary_status().map(|status| status.id), Some("a"));
instance.remove_status("a");
assert_eq!(instance.statuses.iter().map(|status| status.id).collect::<Vec<_>>(), ["b", "c"]);
}
/// terminalEnvironment.test.ts `escapeNonWindowsPath`: expanding characters are dropped and a quote in the name does
/// not end the quoting, so a file name cannot run a second command.
#[test]
fn paths_are_quoted_for_the_shell_that_reads_them() {
assert_eq!(escape_non_windows_path("/a/b c.py", Some("zsh")), "'/a/b c.py'");
assert_eq!(escape_non_windows_path("/a/x'; touch p; '.py", Some("zsh")), "'/a/x'\\'' touch p '\\''.py'");
assert_eq!(escape_non_windows_path("/a/it's \"q\"", Some("bash")), "$'/a/it\\'s \"q\"'");
assert_eq!(escape_non_windows_path("/a/$(id)`id`", None), "'/a/(id)id'");
assert_eq!(escape_non_windows_path("/a/it's", Some("fish")), "'/a/it\\'s'");
assert_eq!(escape_non_windows_path("/a/it's", Some("pwsh")), "'/a/it''s'");
assert_eq!(escape_non_windows_path("/a\\b", Some("zsh")), "'/a\\\\b'");
}
#[test]
fn a_power_shell_terminal_runs_a_path_with_its_call_operator() {
let launch = ShellLaunchConfig { executable: "/usr/local/bin/pwsh".into(), cwd: std::env::temp_dir(), extension_pty: true, ..Default::default() };
let (instance, _receiver) = TerminalInstance::new(1, launch, 20, 3, Config::default());
assert_eq!(instance.prepare_path_for_shell("/a/b c.ps1"), "& '/a/b c.ps1'");
assert_eq!(instance.prepare_path_for_shell("/a/b\u{7}.ps1"), "'/a/b.ps1'");
}