use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::time::Duration;
use serde_json::Value;
use tam_daemon::daemon::Daemon;
struct Env {
root: PathBuf,
}
impl Env {
fn tam(&self, dir: &Path, args: &[&str]) -> Command {
let mut cmd = Command::new(env!("CARGO_BIN_EXE_tam"));
cmd.args(args)
.env("XDG_RUNTIME_DIR", self.root.join("rt"))
.env("XDG_DATA_HOME", self.root.join("data"))
.env("XDG_CONFIG_HOME", self.root.join("config"))
.env("HOME", self.root.join("home"))
.env("SHELL", "/bin/sh")
.env_remove("TAM_AGENT_ID")
.env_remove("TAM_SOCKET")
.current_dir(dir)
.stdin(Stdio::null());
tam_worktree::git::without_local_env(&mut cmd);
cmd
}
async fn run(&self, dir: &Path, args: &[&str]) -> Output {
let mut cmd = self.tam(dir, args);
tokio::task::spawn_blocking(move || cmd.output().unwrap())
.await
.unwrap()
}
async fn json(&self, dir: &Path, args: &[&str]) -> (Option<i32>, Value) {
let out = self.run(dir, args).await;
let doc = serde_json::from_slice(&out.stdout)
.unwrap_or_else(|e| panic!("{args:?}: {e}: {} {}", stdout(&out), stderr(&out)));
(out.status.code(), doc)
}
async fn shells(&self) -> Vec<Value> {
let (code, doc) = self.json(&self.root, &["ps", "--json"]).await;
assert_eq!(code, Some(0), "{doc}");
doc["shells"].as_array().unwrap().clone()
}
fn config(&self, extra: &str) {
let dir = self.root.join("config").join("tam");
std::fs::create_dir_all(&dir).unwrap();
let text = format!(
"[worktree]\nroot = \"{}\"\n{extra}",
self.root.join("wt").display()
);
std::fs::write(dir.join("config.toml"), text).unwrap();
}
}
fn stdout(out: &Output) -> String {
String::from_utf8_lossy(&out.stdout).into_owned()
}
fn stderr(out: &Output) -> String {
String::from_utf8_lossy(&out.stderr).into_owned()
}
fn git(dir: &Path, args: &[&str]) {
let out = tam_worktree::git::command()
.args(["-c", "user.name=t", "-c", "user.email=t@t"])
.args(args)
.current_dir(dir)
.output()
.unwrap();
assert!(
out.status.success(),
"git {args:?}: {}",
String::from_utf8_lossy(&out.stderr)
);
}
fn opened(code: Option<i32>, doc: &Value) -> String {
assert_eq!(code, Some(0), "{doc}");
doc["shell"].as_str().unwrap().to_string()
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn shells_from_the_command_line() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path().canonicalize().unwrap();
std::env::set_var("HOME", root.join("home"));
std::env::set_var("XDG_CONFIG_HOME", root.join("config"));
std::env::set_var("XDG_DATA_HOME", root.join("data"));
let env = Env { root: root.clone() };
env.config("");
let sock = root.join("rt").join("tam").join("sock");
let daemon = Daemon::new(sock.clone(), root.join("ledger.jsonl"));
tokio::spawn(async move {
let _ = daemon.run().await;
});
while tokio::net::UnixStream::connect(&sock).await.is_err() {
tokio::time::sleep(Duration::from_millis(50)).await;
}
let src = root.join("home").join("src");
let api = src.join("api");
std::fs::create_dir_all(&api).unwrap();
git(&api, &["init", "-q", "-b", "main"]);
git(&api, &["commit", "-q", "--allow-empty", "-m", "init"]);
let out = env
.run(&src, &["new", "feat", "-r", "api", "--no-start"])
.await;
assert!(out.status.success(), "{}", stderr(&out));
let worktree = root.join("wt").join("api--feat");
assert!(worktree.join(".git").is_file());
let (code, doc) = env.json(&worktree, &["shell", "-d", "--json"]).await;
let first = opened(code, &doc);
assert!(first.starts_with("sh-"), "{doc}");
assert_eq!(doc["schema_version"], 1);
assert_eq!(doc["name"], "Shell #1");
assert_eq!(doc["number"], 1);
assert_eq!(doc["task"], "feat");
assert!(doc["member"].as_str().unwrap().starts_with("m-"), "{doc}");
assert_eq!(doc["repo"], "api");
assert_eq!(doc["dir"], worktree.display().to_string());
assert!(doc["pid"].as_u64().is_some(), "{doc}");
let (code, doc) = env.json(&root, &["shell", "feat", "-d", "--json"]).await;
let second = opened(code, &doc);
assert_eq!(doc["name"], "Shell #2");
assert_eq!(doc["dir"], worktree.display().to_string());
let home = root.join("home");
let (code, doc) = env
.json(&home, &["shell", "-r", "api", "-d", "--json"])
.await;
let on_checkout = opened(code, &doc);
assert_eq!(doc["name"], "Shell #1");
assert!(doc["task"].is_null() && doc["member"].is_null(), "{doc}");
assert_eq!(doc["dir"], api.display().to_string());
std::fs::create_dir_all(api.join("lib")).unwrap();
let out = env.run(&api.join("lib"), &["shell", "-d"]).await;
assert!(out.status.success(), "{}", stderr(&out));
let here = stdout(&out).trim_end().to_string();
assert!(here.starts_with("sh-") && !here.contains(' '), "{here}");
assert!(
stderr(&out).contains(&format!(
"Opened Shell #2 of api in ~/src/api. Attach with: tam attach {here}"
)),
"{}",
stderr(&out)
);
let loose = root.join("wt").join("api--loose");
git(
&api,
&[
"worktree",
"add",
"-q",
"-b",
"loose",
loose.to_str().unwrap(),
],
);
let out = env.run(&loose, &["shell", "-d"]).await;
assert_eq!(out.status.code(), Some(3), "{}", stderr(&out));
assert!(
stderr(&out).contains("tam adopt") && stderr(&out).contains("tam shell -r ."),
"{}",
stderr(&out)
);
let out = env.run(&root, &["shell", "-d"]).await;
assert_eq!(out.status.code(), Some(3), "{}", stderr(&out));
assert!(
stderr(&out).contains("no task or repository"),
"{}",
stderr(&out)
);
let (code, doc) = env.json(&root, &["shell", "nope", "-d", "--json"]).await;
assert_eq!(code, Some(3), "{doc}");
assert_eq!(doc["error"]["kind"], "not_found");
let out = env.run(&root, &["shell", "-r", "nope", "-d"]).await;
assert_eq!(out.status.code(), Some(1), "{}", stderr(&out));
assert_eq!(env.shells().await.len(), 4, "nothing more opened");
let out = env.run(&root, &["ps"]).await;
assert!(out.status.success(), "{}", stderr(&out));
let shown = stdout(&out);
let lines: Vec<&str> = shown.lines().collect();
assert!(
lines[0].starts_with("SHELL") && lines[0].contains("ID"),
"{shown}"
);
assert!(lines[1].starts_with("Shell #1") && lines[1].contains(&on_checkout));
assert!(lines[1].ends_with("~/src/api"), "{shown}");
assert!(lines[2].starts_with("Shell #2") && lines[2].contains(&here));
assert_eq!(lines[3], "", "{shown}");
assert!(lines[4].contains("TASK"), "{shown}");
assert!(lines[5].contains("feat"), "{shown}");
assert!(
lines[6].trim_start() == format!("├─ Shell #1 ({first})"),
"{shown}"
);
assert!(
lines[7].trim_start() == format!("└─ Shell #2 ({second})"),
"{shown}"
);
let shells = env.shells().await;
let ids: Vec<&str> = shells.iter().map(|s| s["id"].as_str().unwrap()).collect();
assert_eq!(ids, [&first, &second, &on_checkout, &here], "opening order");
assert_eq!(shells[0]["task"], "feat");
assert_eq!(shells[0]["viewers"], 0);
assert!(shells[2]["task"].is_null() && shells[2]["member"].is_null());
for args in [
&["run", &first, "-d"][..],
&["msg", &first, "hello"][..],
&["wait", &first, "-t", "1"][..],
&["result", &first][..],
&["history", &first][..],
&["drop", &first][..],
&["merge", "feat", &first][..],
&["close", &first, "-y"][..],
&["shell", &first, "-d"][..],
] {
let out = env.run(&root, args).await;
assert_eq!(out.status.code(), Some(3), "{args:?}: {}", stderr(&out));
assert!(
stderr(&out).contains(&format!("'{first}' is a shell (Shell #1)")),
"{args:?}: {}",
stderr(&out)
);
assert!(
stderr(&out).contains(&format!("tam stop {first} closes it")),
"{args:?}: {}",
stderr(&out)
);
}
for args in [
&["run", &first, "-d", "--json"][..],
&["wait", &first, "--json"][..],
&["result", &first, "--json"][..],
] {
let (code, doc) = env.json(&root, args).await;
assert_eq!(code, Some(3), "{args:?}: {doc}");
assert_eq!(doc["error"]["kind"], "not_found", "{args:?}: {doc}");
}
let out = env.run(&root, &["attach", &first]).await;
assert_eq!(out.status.code(), Some(1), "{}", stderr(&out));
assert!(
stderr(&out).contains("stdin is not a terminal"),
"{}",
stderr(&out)
);
let out = env.run(&root, &["stop", &first]).await;
assert!(out.status.success(), "{}", stderr(&out));
assert_eq!(stdout(&out), format!("Closed Shell #1 of feat ({first})\n"));
let out = env.run(&root, &["stop", &first]).await;
assert_eq!(out.status.code(), Some(3), "{}", stderr(&out));
assert!(
stderr(&out).contains(&format!("no open shell '{first}'")),
"{}",
stderr(&out)
);
let out = env.run(&root, &["attach", &first]).await;
assert_eq!(out.status.code(), Some(3), "{}", stderr(&out));
assert_eq!(env.shells().await.len(), 3);
let wrap = root.join("wrap");
let mark = root.join("wrapped");
std::fs::write(
&wrap,
format!("#!/bin/sh\npwd > '{}'\nexec \"$@\"\n", mark.display()),
)
.unwrap();
std::fs::set_permissions(&wrap, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
env.config(&format!("[spawn]\nwrapper = [\"{}\"]\n", wrap.display()));
let (code, doc) = env.json(&root, &["shell", "feat", "-d", "--json"]).await;
let third = opened(code, &doc);
env.config("");
assert_eq!(doc["name"], "Shell #3");
for _ in 0..500 {
if mark.exists() {
break;
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
assert_eq!(
std::fs::read_to_string(&mark).unwrap().trim_end(),
worktree.display().to_string()
);
let out = env.run(&root, &["drop", "feat"]).await;
assert!(out.status.success(), "{}", stderr(&out));
assert_eq!(
stdout(&out),
"Dropped task 'feat' and closed its 2 shells\n"
);
let ids: Vec<String> = env
.shells()
.await
.iter()
.map(|s| s["id"].as_str().unwrap().to_string())
.collect();
assert_eq!(ids, [on_checkout.clone(), here.clone()]);
assert!(!ids.contains(&second) && !ids.contains(&third));
for id in [on_checkout, here] {
let out = env.run(&root, &["stop", &id]).await;
assert!(out.status.success(), "{}", stderr(&out));
assert!(
stdout(&out).starts_with("Closed Shell #"),
"{}",
stdout(&out)
);
assert!(stdout(&out).contains(" of api "), "{}", stdout(&out));
}
assert!(env.shells().await.is_empty());
}