use std::path::Path;
use anyhow::Result;
use super::{Env, TabToOpen, TerminalAdapter};
use crate::engine::rules::TerminalShape;
use crate::procs::ProcInfo;
pub struct ExampleTerminal;
impl TerminalAdapter for ExampleTerminal {
fn id(&self) -> &'static str {
"example-terminal"
}
fn name(&self) -> &'static str {
"Example Terminal"
}
fn shape(&self) -> TerminalShape {
TerminalShape::Tabs
}
fn find(&self, _env: &Env, lineage: &[ProcInfo]) -> Option<ProcInfo> {
lineage
.iter()
.skip(1) .find(|p| p.name.eq_ignore_ascii_case("example-terminal"))
.cloned()
}
fn tab_id(&self, env: &Env) -> Option<String> {
env.get("EXAMPLE_TERMINAL_TAB").cloned()
}
fn reopen(&self, exe: Option<&Path>, tabs: &[TabToOpen]) -> Result<()> {
let program = exe.unwrap_or(Path::new("example-terminal"));
for tab in tabs {
std::process::Command::new(program)
.args(new_tab_args(tab))
.spawn()?;
}
Ok(())
}
}
fn new_tab_args(tab: &TabToOpen) -> Vec<String> {
let mut args: Vec<String> = vec![
"--new-tab".into(),
"--title".into(),
tab.title.clone(),
"--cwd".into(),
tab.cwd.clone(),
];
if let Some(shell) = &tab.shell {
args.extend(["--shell".into(), shell.clone()]);
}
if !tab.run.is_empty() {
args.push("--".into());
args.extend(tab.run.iter().cloned());
}
args
}
#[cfg(test)]
mod tests {
use super::*;
use crate::procs::{fake::FakeTable, lineage};
const ID: &str = "00000000-0000-4000-8000-000000000001";
fn tab(cwd: &str, run: &[&str]) -> TabToOpen {
TabToOpen {
title: "mobile-app".into(),
cwd: cwd.into(),
profile: None,
shell: Some("bash".into()),
run: run.iter().map(|arg| arg.to_string()).collect(),
}
}
#[test]
fn finds_its_process_above_the_shell() {
let table = FakeTable::new(&[
(30, Some(20), "bash", Some(300)),
(20, Some(10), "example-terminal", Some(200)),
(10, Some(1), "launcher", Some(100)),
]);
let found = ExampleTerminal.find(&Env::new(), &lineage(&table, 30));
assert_eq!(found.map(|p| p.pid), Some(20));
}
#[test]
fn a_shell_in_another_terminal_is_not_found() {
let table = FakeTable::new(&[
(30, Some(10), "bash", Some(300)),
(10, None, "other-terminal", Some(100)),
]);
assert!(
ExampleTerminal
.find(&Env::new(), &lineage(&table, 30))
.is_none()
);
}
#[test]
fn the_tab_id_comes_from_the_environment() {
let env = Env::from([("EXAMPLE_TERMINAL_TAB".to_string(), "tab-7".to_string())]);
assert_eq!(ExampleTerminal.tab_id(&env).as_deref(), Some("tab-7"));
assert_eq!(ExampleTerminal.tab_id(&Env::new()), None);
}
#[test]
fn a_folder_with_spaces_and_non_ascii_stays_one_argument() {
let args = new_tab_args(&tab(
"/home/demo/my code/프로젝트",
&["claude", "--resume", ID],
));
assert_eq!(
args,
[
"--new-tab",
"--title",
"mobile-app",
"--cwd",
"/home/demo/my code/프로젝트",
"--shell",
"bash",
"--",
"claude",
"--resume",
ID
]
);
}
#[test]
fn a_plain_tab_runs_nothing() {
let args = new_tab_args(&tab("/home/demo", &[]));
assert!(!args.iter().any(|arg| arg == "--"));
}
}