use assert_cmd::Command;
#[test]
fn help_flag_prints_usage_and_exits_zero() {
let out = Command::cargo_bin("croft").unwrap().arg("--help").assert();
let out = out.success();
let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
assert!(stdout.contains("Usage:"), "stdout was: {stdout}");
assert!(stdout.contains("setup-terminal"));
}
#[test]
fn version_flag_prints_version() {
let out = Command::cargo_bin("croft")
.unwrap()
.arg("--version")
.assert();
let out = out.success();
let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
assert!(stdout.contains("croft"));
}
#[test]
fn build_info_carries_provenance_and_version_does_not() {
let out = Command::cargo_bin("croft")
.unwrap()
.arg("--build-info")
.assert();
let out = out.success();
let build_info = String::from_utf8(out.get_output().stdout.clone()).unwrap();
assert!(
build_info.contains(env!("CARGO_PKG_VERSION")) && build_info.contains("built "),
"--build-info carries version and build time: {build_info}"
);
let out = Command::cargo_bin("croft")
.unwrap()
.arg("--version")
.assert();
let out = out.success();
let version = String::from_utf8(out.get_output().stdout.clone()).unwrap();
assert_eq!(
version.trim(),
format!("croft {}", env!("CARGO_PKG_VERSION")),
"--version stays bare"
);
}
#[test]
fn setup_terminal_help_works() {
Command::cargo_bin("croft")
.unwrap()
.args(["setup-terminal", "--help"])
.assert()
.success();
}
#[test]
fn probe_subcommands_answer_instantly_even_with_a_stripped_path() {
let dir = tempfile::tempdir().unwrap();
let slow_shell = dir.path().join("slow-shell");
std::fs::write(&slow_shell, "#!/bin/sh\nsleep 30\n").unwrap();
let mut perm = std::fs::metadata(&slow_shell).unwrap().permissions();
std::os::unix::fs::PermissionsExt::set_mode(&mut perm, 0o755);
std::fs::set_permissions(&slow_shell, perm).unwrap();
for sub in ["session-host", "collab-relay"] {
let start = std::time::Instant::now();
Command::cargo_bin("croft")
.unwrap()
.args([sub, "--probe"])
.env("PATH", "/usr/bin:/bin:/usr/sbin:/sbin")
.env("SHELL", &slow_shell)
.assert()
.success();
assert!(
start.elapsed() < std::time::Duration::from_secs(15),
"{sub} --probe took {:?} with a stripped PATH",
start.elapsed()
);
}
}
#[test]
fn nonexistent_path_fails_cleanly() {
Command::cargo_bin("croft")
.unwrap()
.arg("/nonexistent/path/that/does/not/exist/abc123")
.assert()
.failure();
}
#[test]
fn pr_without_a_usable_gh_says_how_to_fix_it_before_starting() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let bin = tmp.path().join("bin");
std::fs::create_dir(&bin).unwrap();
let pr = |expected: &str| {
let out = Command::cargo_bin("croft")
.unwrap()
.args(["pr", "42"])
.current_dir(tmp.path())
.env("PATH", &bin)
.env("HOME", tmp.path())
.env_remove("GH_TOKEN")
.env_remove("GITHUB_TOKEN")
.env_remove("GH_ENTERPRISE_TOKEN")
.env_remove("GITHUB_ENTERPRISE_TOKEN")
.timeout(std::time::Duration::from_secs(30))
.assert()
.failure()
.code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(stderr.starts_with("croft pr: "), "{stderr}");
assert!(stderr.contains(expected), "{stderr}");
assert_eq!(stderr.trim().lines().count(), 1, "{stderr}");
};
pr("install it from https://cli.github.com, then run gh auth login");
let gh = bin.join("gh");
std::fs::write(&gh, "#!/bin/sh\necho 'no oauth token found' >&2\nexit 1\n").unwrap();
std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap();
pr("not signed in; run gh auth login");
}
#[test]
fn pair_off_and_reactivation_keep_the_recorded_backend() {
let home = tempfile::Builder::new()
.prefix("h")
.tempdir_in("/tmp")
.unwrap();
let ws = tempfile::tempdir().unwrap();
let run = |args: &[&str]| {
Command::cargo_bin("croft")
.unwrap()
.args(args)
.arg("--workspace")
.arg(ws.path())
.env("HOME", home.path())
.assert()
.success();
};
run(&[
"pair",
"--provider",
"ollama",
"--model",
"qwen3-coder:30b",
"--base-url",
"http://localhost:9999",
]);
let record_path = || {
let dir = home.path().join(".cache/croft/sessions");
std::fs::read_dir(&dir)
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.path())
.find(|p| p.to_string_lossy().ends_with(".pair.json"))
.expect("a pair record exists")
};
let read = || std::fs::read_to_string(record_path()).unwrap();
assert!(read().contains("http://localhost:9999"));
run(&["pair", "--provider", "ollama", "--off"]);
let r = read();
assert!(r.contains("\"enabled\":false"), "{r}");
assert!(
r.contains("http://localhost:9999"),
"the default endpoint must not clobber the custom one: {r}"
);
run(&["pair"]);
let r = read();
assert!(r.contains("\"enabled\":true"), "{r}");
assert!(r.contains("\"provider\":\"ollama\""), "{r}");
assert!(r.contains("http://localhost:9999"), "{r}");
assert!(r.contains("qwen3-coder:30b"), "{r}");
run(&["pair", "--provider", "claude"]);
let r = read();
assert!(r.contains("\"provider\":\"claude\""), "{r}");
assert!(
!r.contains("http://localhost:9999"),
"the ollama endpoint must not survive a provider switch: {r}"
);
assert!(!r.contains("qwen3-coder:30b"), "{r}");
reap_pair_relays(home.path());
}
fn reap_pair_relays(home: &std::path::Path) {
let sessions = home.join(".cache/croft/sessions");
if let Ok(entries) = std::fs::read_dir(&sessions) {
for e in entries.filter_map(|e| e.ok()) {
let p = e.path();
if p.to_string_lossy().ends_with(".collab.sock") {
let _ = std::process::Command::new("pkill")
.args(["-f", &p.to_string_lossy()])
.status();
}
}
}
}
#[test]
fn pair_rerun_without_name_keeps_the_recorded_name() {
let home = tempfile::Builder::new()
.prefix("h")
.tempdir_in("/tmp")
.unwrap();
let ws = tempfile::tempdir().unwrap();
let run = |args: &[&str]| {
let out = Command::cargo_bin("croft")
.unwrap()
.args(args)
.arg("--workspace")
.arg(ws.path())
.env("HOME", home.path())
.assert()
.success();
String::from_utf8(out.get_output().stdout.clone()).unwrap()
};
let read = || {
let dir = home.path().join(".cache/croft/sessions");
let path = std::fs::read_dir(&dir)
.unwrap()
.filter_map(|e| e.ok())
.map(|e| e.path())
.find(|p| p.to_string_lossy().ends_with(".pair.json"))
.expect("a pair record exists");
std::fs::read_to_string(path).unwrap()
};
run(&[
"pair",
"--name",
"navigator",
"--model",
"claude-haiku-4-5-20251001",
]);
assert!(read().contains("\"name\":\"navigator\""));
run(&["pair", "--off"]);
let r = read();
assert!(r.contains("\"enabled\":false"), "{r}");
assert!(
r.contains("\"name\":\"navigator\""),
"--off keeps the name: {r}"
);
let out = run(&["pair"]);
let r = read();
assert!(r.contains("\"enabled\":true"), "{r}");
assert!(
r.contains("\"name\":\"navigator\""),
"re-activation keeps the name: {r}"
);
assert!(r.contains("claude-haiku-4-5-20251001"), "{r}");
assert!(out.contains("navigator 'navigator' active"), "{out}");
run(&["pair", "--name", "other"]);
assert!(read().contains("\"name\":\"other\""));
reap_pair_relays(home.path());
}
#[test]
fn view_outside_croft_exits_one_with_an_explanation() {
let out = Command::cargo_bin("croft")
.unwrap()
.env_remove("CROFT_VIEW_SOCK")
.args(["view", "Cargo.toml"])
.assert();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.contains("croft view needs a croft"),
"stderr must say why, was: {stderr}"
);
assert_eq!(
stderr.lines().filter(|l| !l.trim().is_empty()).count(),
1,
"one line, not a backtrace: {stderr}"
);
}
#[test]
fn view_treats_an_empty_socket_variable_as_no_croft_at_all() {
let out = Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", "")
.args(["view", "Cargo.toml"])
.assert();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.contains("croft view needs a croft"),
"stderr was: {stderr}"
);
}
#[test]
fn view_against_a_vanished_croft_says_the_croft_is_gone() {
let tmp = tempfile::tempdir().unwrap();
let out = Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", tmp.path().join("nobody.sock"))
.args(["view", "Cargo.toml"])
.assert();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.contains("is gone"),
"stderr must name the situation, was: {stderr}"
);
}
#[test]
fn view_sends_the_resolved_path_to_the_socket_and_exits_zero() {
use std::io::{BufRead, BufReader, Write};
let tmp = tempfile::tempdir().unwrap();
let sock = tmp.path().join("v.sock");
let target = tmp.path().join("report.txt");
std::fs::write(&target, b"hello").unwrap();
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut line = String::new();
BufReader::new(&stream).read_line(&mut line).unwrap();
stream.write_all(b"{\"status\":\"ok\"}\n").unwrap();
line
});
Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", &sock)
.current_dir(tmp.path())
.args(["view", "report.txt"])
.assert()
.success();
let request = server.join().unwrap();
let bytes: Vec<u8> = request
.trim()
.trim_start_matches("{\"path\":[")
.trim_end_matches("]}")
.split(',')
.map(|n| n.trim().parse::<u8>().expect("the wire is a byte array"))
.collect();
let received = std::path::PathBuf::from(String::from_utf8(bytes).unwrap());
assert_eq!(
received.canonicalize().unwrap_or(received),
target.canonicalize().unwrap_or(target.clone()),
"the server must receive the path resolved against the client's cwd"
);
}
#[test]
fn view_refuses_a_missing_file_without_bothering_the_socket() {
let tmp = tempfile::tempdir().unwrap();
let sock = tmp.path().join("v.sock");
let _listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let out = Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", &sock)
.current_dir(tmp.path())
.args(["view", "nope.pdf"])
.assert();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.contains("no such file") && stderr.contains("nope.pdf"),
"stderr must name the missing path, was: {stderr}"
);
}
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn view_transmits_a_non_utf8_filename_byte_for_byte() {
use std::ffi::OsStr;
use std::io::{BufRead, BufReader, Write};
use std::os::unix::ffi::OsStrExt;
let tmp = tempfile::tempdir().unwrap();
let sock = tmp.path().join("v.sock");
let name = OsStr::from_bytes(b"od\xffd.txt");
let target = tmp.path().join(name);
std::fs::write(&target, b"x").unwrap();
assert!(
target.to_str().is_none(),
"fixture must be invalid UTF-8, or this test proves nothing"
);
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut line = String::new();
BufReader::new(&stream).read_line(&mut line).unwrap();
stream.write_all(b"{\"status\":\"ok\"}\n").unwrap();
line
});
Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", &sock)
.current_dir(tmp.path())
.arg("view")
.arg(name)
.assert()
.success();
let request = server.join().unwrap();
let bytes: Vec<u8> = request
.trim()
.trim_start_matches("{\"path\":[")
.trim_end_matches("]}")
.split(',')
.map(|n| n.trim().parse::<u8>().expect("the wire is a byte array"))
.collect();
assert!(
bytes.contains(&0xff),
"the 0xff byte must reach the server intact, got {bytes:?}"
);
assert_eq!(std::path::PathBuf::from(OsStr::from_bytes(&bytes)), target);
}
#[test]
fn view_refuses_an_as_flag_that_cannot_be_a_file_extension() {
let tmp = tempfile::tempdir().unwrap();
let sock = tmp.path().join("v.sock");
let _listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let home = tmp.path().join("home");
std::fs::create_dir(&home).unwrap();
let out = Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", &sock)
.env("HOME", &home)
.current_dir(tmp.path())
.write_stdin("a,b\n1,2\n")
.args(["view", "-", "--as", "../x"])
.assert();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.contains("--as"),
"the message must name the flag, was: {stderr}"
);
assert!(
!home.join(".cache/croft/view-stdin").exists(),
"a refused --as must not create the staging directory"
);
}
#[test]
fn view_from_a_pipe_stages_an_owner_only_file_and_sends_its_path() {
use std::io::{BufRead, BufReader, Write};
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
std::fs::create_dir(&home).unwrap();
let sock = tmp.path().join("v.sock");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut line = String::new();
BufReader::new(&stream).read_line(&mut line).unwrap();
stream.write_all(b"{\"status\":\"ok\"}\n").unwrap();
line
});
Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", &sock)
.env("HOME", &home)
.current_dir(tmp.path())
.write_stdin("a,b\n1,2\n")
.args(["view", "-"])
.assert()
.success();
let request = server.join().unwrap();
let bytes: Vec<u8> = request
.trim()
.trim_start_matches("{\"path\":[")
.trim_end_matches("]}")
.split(',')
.map(|n| n.trim().parse::<u8>().expect("the wire is a byte array"))
.collect();
let staged = std::path::PathBuf::from(String::from_utf8(bytes).unwrap());
assert_eq!(
staged.extension().and_then(|e| e.to_str()),
Some("csv"),
"delimited text must be staged under the extension the sheet viewer \
routes on, or it arrives as plain text: {staged:?}"
);
assert!(
staged.starts_with(home.join(".cache").join("croft")),
"the staged file belongs under the cache dir, not beside the user's \
own files: {staged:?}"
);
let meta = std::fs::metadata(&staged)
.expect("the staged file must exist by the time the server is told about it");
assert_eq!(
meta.permissions().mode() & 0o777,
0o600,
"piped content is owner-only: `vault read ... | croft view -` is the \
case this command invites"
);
assert_eq!(
std::fs::read(&staged).unwrap(),
b"a,b\n1,2\n",
"and it is the bytes that came down the pipe, unaltered"
);
}
#[test]
fn view_refuses_an_as_flag_on_a_named_file_rather_than_ignoring_it() {
let tmp = tempfile::tempdir().unwrap();
let sock = tmp.path().join("v.sock");
let target = tmp.path().join("data.log");
std::fs::write(&target, b"a,b\n1,2\n").unwrap();
let _listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let out = Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", &sock)
.current_dir(tmp.path())
.args(["view", "data.log", "--as", "csv"])
.assert();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.contains("--as"),
"the message must name the flag that was refused, was: {stderr}"
);
assert!(
stderr.contains("piped"),
"and say what it applies to, or the user cannot tell what to do \
instead, was: {stderr}"
);
}
#[test]
fn view_from_an_empty_pipe_says_nothing_arrived() {
let tmp = tempfile::tempdir().unwrap();
let home = tmp.path().join("home");
std::fs::create_dir(&home).unwrap();
let sock = tmp.path().join("v.sock");
let _listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let out = Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", &sock)
.env("HOME", &home)
.current_dir(tmp.path())
.write_stdin("")
.args(["view", "-"])
.assert();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.contains("nothing arrived on stdin"),
"an empty pipe must say so rather than staging a zero-byte file and \
reporting success, was: {stderr}"
);
assert!(
!home.join(".cache/croft/view-stdin").exists(),
"and it must not create the staging directory either"
);
}
#[test]
fn edit_wait_creates_a_new_file_opens_it_and_returns_once_it_closes() {
use std::io::{BufRead, BufReader, Write};
let tmp = tempfile::tempdir().unwrap();
let sock = tmp.path().join("v.sock");
let target = tmp.path().join("TODO.md");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let server = std::thread::spawn(move || {
let replies: [&[u8]; 2] = [
b"{\"status\":\"ok\"}\n",
b"{\"status\":\"err\",\"message\":\"closed\"}\n",
];
let mut requests = Vec::new();
for reply in replies {
let (mut stream, _) = listener.accept().unwrap();
let mut line = String::new();
BufReader::new(&stream).read_line(&mut line).unwrap();
stream.write_all(reply).unwrap();
requests.push(line);
}
requests
});
Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", &sock)
.current_dir(tmp.path())
.args(["edit", "--wait", "TODO.md"])
.assert()
.success();
let requests = server.join().unwrap();
assert!(
!requests[0].contains("probe"),
"first the open: {requests:?}"
);
assert!(
requests[1].contains("\"probe\":true"),
"then the wait's probe: {requests:?}"
);
assert_eq!(
std::fs::read(&target).unwrap(),
b"",
"the new file was created, empty"
);
}
#[test]
fn edit_outside_croft_names_itself_and_creates_nothing() {
let tmp = tempfile::tempdir().unwrap();
let out = Command::cargo_bin("croft")
.unwrap()
.env_remove("CROFT_VIEW_SOCK")
.current_dir(tmp.path())
.args(["edit", "new.txt"])
.assert();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.contains("croft edit needs a croft") && !stderr.contains("croft view"),
"stderr must name the command the user typed, was: {stderr}"
);
assert!(!tmp.path().join("new.txt").exists());
}
#[test]
fn edit_refuses_a_missing_folder_without_bothering_the_socket() {
let tmp = tempfile::tempdir().unwrap();
let sock = tmp.path().join("v.sock");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
listener.set_nonblocking(true).unwrap();
let out = Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", &sock)
.current_dir(tmp.path())
.args(["edit", "no/such/TODO.md"])
.assert();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.starts_with("croft edit: ") && stderr.contains("no such directory"),
"stderr must name the command and the reason, was: {stderr}"
);
assert!(
matches!(listener.accept(), Err(e) if e.kind() == std::io::ErrorKind::WouldBlock),
"no croft was asked to open anything"
);
assert!(!tmp.path().join("no").exists(), "no folders were created");
}
#[test]
fn edit_against_a_vanished_croft_leaves_no_new_file_behind() {
let tmp = tempfile::tempdir().unwrap();
let out = Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", tmp.path().join("nobody.sock"))
.current_dir(tmp.path())
.args(["edit", "new.txt"])
.assert();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.contains("croft edit: the croft that opened this pane is gone"),
"stderr must name the command and the situation, was: {stderr}"
);
assert!(
!tmp.path().join("new.txt").exists(),
"the empty file this call created was left behind"
);
}
#[test]
fn edit_refused_by_the_croft_leaves_no_new_file_behind() {
use std::io::{BufRead, BufReader, Write};
let tmp = tempfile::tempdir().unwrap();
let sock = tmp.path().join("v.sock");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut line = String::new();
BufReader::new(&stream).read_line(&mut line).unwrap();
stream
.write_all(b"{\"status\":\"err\",\"message\":\"cannot open that here\"}\n")
.unwrap();
});
let out = Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", &sock)
.current_dir(tmp.path())
.args(["edit", "new.txt"])
.assert();
server.join().unwrap();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.contains("croft edit: cannot open that here"),
"stderr was: {stderr}"
);
assert!(
!tmp.path().join("new.txt").exists(),
"the empty file this call created was left behind"
);
}
#[test]
fn edit_against_a_vanished_croft_never_removes_an_existing_file() {
let tmp = tempfile::tempdir().unwrap();
for (name, body) in [("keep.txt", "keep me"), ("empty.txt", "")] {
let path = tmp.path().join(name);
std::fs::write(&path, body).unwrap();
Command::cargo_bin("croft")
.unwrap()
.env("CROFT_VIEW_SOCK", tmp.path().join("nobody.sock"))
.current_dir(tmp.path())
.args(["edit", name])
.assert()
.failure()
.code(1);
assert_eq!(
std::fs::read_to_string(&path).ok().as_deref(),
Some(body),
"{name} must survive a failed open untouched"
);
}
}
#[cfg(unix)]
#[test]
fn typing_with_images_on_does_not_stream_images_per_keystroke() {
use std::io::Read;
use std::os::fd::{FromRawFd, OwnedFd};
use std::os::unix::process::CommandExt;
use std::time::{Duration, Instant};
let home = tempfile::tempdir().unwrap();
let file = home.path().join("a.rs");
std::fs::write(&file, "fn main() {\n println!(\"hi\");\n}\n".repeat(300)).unwrap();
let (mut master, mut slave) = (0, 0);
let mut ws = libc::winsize {
ws_row: 50,
ws_col: 160,
ws_xpixel: 160 * 9,
ws_ypixel: 50 * 18,
};
assert_eq!(
unsafe {
libc::openpty(
&mut master,
&mut slave,
std::ptr::null_mut(),
std::ptr::null_mut(),
&raw mut ws,
)
},
0
);
for fd in [master, slave] {
assert_ne!(
unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) },
-1
);
}
let slave = unsafe { OwnedFd::from_raw_fd(slave) };
let bin = assert_cmd::cargo::cargo_bin("croft");
let mut cmd = std::process::Command::new(bin);
cmd.arg("a.rs")
.current_dir(home.path())
.env("HOME", home.path())
.env("TERM", "xterm-256color")
.env("TERM_PROGRAM", "iTerm.app")
.env("CROFT_FORCE_INLINE_IMAGES", "1")
.stdin(slave.try_clone().unwrap())
.stdout(slave.try_clone().unwrap())
.stderr(slave.try_clone().unwrap());
unsafe {
cmd.pre_exec(|| {
libc::setsid();
libc::ioctl(0, libc::TIOCSCTTY as _, 0);
Ok(())
});
}
let mut child = cmd.spawn().unwrap();
drop(slave);
unsafe {
let flags = libc::fcntl(master, libc::F_GETFL);
libc::fcntl(master, libc::F_SETFL, flags | libc::O_NONBLOCK);
}
let mut pty = unsafe { std::fs::File::from_raw_fd(master) };
let mut tty = pty.try_clone().unwrap();
let mut drain = |for_: Duration| {
let mut n = 0usize;
let mut buf = [0u8; 1 << 16];
let end = Instant::now() + for_;
while Instant::now() < end {
match pty.read(&mut buf) {
Ok(0) => break,
Ok(k) => n += k,
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
std::thread::sleep(Duration::from_millis(10))
}
Err(_) => break,
}
}
n
};
let started = drain(Duration::from_secs(8));
assert!(started > 1000, "croft drew nothing ({started} bytes)");
use std::io::Write;
tty.write_all(b"\x1b").unwrap();
drain(Duration::from_secs(2));
let mut typed = 0;
for _ in 0..20 {
tty.write_all(b"x").unwrap();
typed += drain(Duration::from_millis(80));
}
typed += drain(Duration::from_secs(1));
let _ = child.kill();
drop((pty, tty));
let _ = child.wait();
assert!(
typed < 30_000,
"20 keystrokes wrote {typed} bytes: images are being re-sent per frame"
);
}
#[cfg(unix)]
#[test]
fn unsaved_edits_survive_a_kill_and_come_back_on_the_next_launch() {
use std::io::{Read, Write};
use std::os::fd::{FromRawFd, OwnedFd};
use std::os::unix::process::CommandExt;
use std::time::{Duration, Instant};
fn spawn(dir: &std::path::Path, args: &[&str]) -> (std::process::Child, std::fs::File) {
let (mut master, mut slave) = (0, 0);
let mut ws = libc::winsize {
ws_row: 40,
ws_col: 140,
ws_xpixel: 0,
ws_ypixel: 0,
};
let opened = unsafe {
libc::openpty(
&mut master,
&mut slave,
std::ptr::null_mut(),
std::ptr::null_mut(),
&raw mut ws,
)
};
assert_eq!(opened, 0);
for fd in [master, slave] {
assert_ne!(
unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) },
-1
);
}
let slave = unsafe { OwnedFd::from_raw_fd(slave) };
let mut cmd = std::process::Command::new(assert_cmd::cargo::cargo_bin("croft"));
cmd.args(args)
.current_dir(dir)
.env("HOME", dir)
.env("TERM", "xterm-256color")
.env_remove("TERM_PROGRAM")
.env_remove("XDG_STATE_HOME")
.stdin(slave.try_clone().unwrap())
.stdout(slave.try_clone().unwrap())
.stderr(slave.try_clone().unwrap());
unsafe {
cmd.pre_exec(|| {
if libc::setsid() == -1 || libc::ioctl(0, libc::TIOCSCTTY as _, 0) == -1 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
let child = cmd.spawn().unwrap();
drop(slave);
unsafe {
let flags = libc::fcntl(master, libc::F_GETFL);
libc::fcntl(master, libc::F_SETFL, flags | libc::O_NONBLOCK);
}
(child, unsafe { std::fs::File::from_raw_fd(master) })
}
fn read_until(
pty: &mut std::fs::File,
limit: Duration,
mut done: impl FnMut(&str) -> bool,
) -> String {
let mut out = String::new();
let mut buf = [0u8; 1 << 16];
let end = Instant::now() + limit;
while !done(&out) && Instant::now() < end {
match pty.read(&mut buf) {
Ok(0) => break,
Ok(k) => out.push_str(&String::from_utf8_lossy(&buf[..k])),
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
std::thread::sleep(Duration::from_millis(10))
}
Err(e) if e.raw_os_error() == Some(libc::EIO) => break,
Err(e) => panic!("reading croft's terminal: {e}"),
}
}
out
}
fn a_backup_holds(dir: &std::path::Path, text: &str) -> bool {
let Ok(workspaces) = std::fs::read_dir(dir) else {
return false;
};
workspaces
.flatten()
.filter_map(|ws| std::fs::read_dir(ws.path()).ok())
.flat_map(|files| files.flatten())
.filter(|f| f.path().extension().is_some_and(|x| x == "json"))
.any(|f| std::fs::read_to_string(f.path()).is_ok_and(|t| t.contains(text)))
}
let limit = Duration::from_secs(20);
let home = tempfile::tempdir().unwrap();
let file = home.path().join("a.txt");
std::fs::write(&file, "alpha\n").unwrap();
let backups = home.path().join(".local/state/croft/hot-exit");
let (mut child, mut pty) = spawn(home.path(), &["a.txt"]);
let started = read_until(&mut pty, limit, |out| out.contains("alpha"));
assert!(
started.contains("alpha"),
"croft never drew a.txt: {started:?}"
);
pty.write_all(b"\x1b").unwrap();
read_until(&mut pty, Duration::from_millis(300), |_| false);
pty.write_all(b"HOTEXIT").unwrap();
let end = Instant::now() + limit;
while !a_backup_holds(&backups, "HOTEXIT") && Instant::now() < end {
read_until(&mut pty, Duration::from_millis(100), |_| false);
}
assert!(
a_backup_holds(&backups, "HOTEXIT"),
"a backup holds the edit"
);
child.kill().unwrap();
drop(pty);
child.wait().unwrap();
assert_eq!(
std::fs::read_to_string(&file).unwrap(),
"alpha\n",
"never saved"
);
let (mut child, mut pty) = spawn(home.path(), &[]);
let drawn = read_until(&mut pty, limit, |out| {
out.contains("HOTEXITalpha") && out.contains("restored 1 unsaved tab")
});
let _ = child.kill();
drop(pty);
let _ = child.wait();
assert!(
drawn.contains("HOTEXITalpha"),
"the unsaved edit is back on the next launch"
);
assert!(
drawn.contains("restored 1 unsaved tab"),
"and croft says so"
);
assert_eq!(std::fs::read_to_string(&file).unwrap(), "alpha\n");
}
#[test]
fn locale_template_accepts_a_full_locale() {
let out = Command::cargo_bin("croft")
.unwrap()
.args(["locale-template", "de_DE.UTF-8"])
.assert()
.success();
let stdout = String::from_utf8(out.get_output().stdout.clone()).unwrap();
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
let catalog: serde_json::Value = serde_json::from_str(&stdout).unwrap();
let filled = catalog
.as_object()
.unwrap()
.values()
.filter(|v| v.as_str().is_some_and(|s| !s.is_empty()))
.count();
assert!(filled > 0, "the built-in German entries seed it");
assert!(stderr.contains("locales/de.json"), "{stderr}");
}
fn unescape_rust_literal(body: &str) -> String {
let mut out = String::with_capacity(body.len());
let mut chars = body.chars();
while let Some(c) = chars.next() {
if c != '\\' {
out.push(c);
continue;
}
match chars.next() {
Some('n') => out.push('\n'),
Some('r') => out.push('\r'),
Some('t') => out.push('\t'),
Some('0') => out.push('\0'),
Some('x') => {
let hex: String = chars.by_ref().take(2).collect();
out.push(char::from(u8::from_str_radix(&hex, 16).unwrap()));
}
Some('u') => {
let hex: String = chars.by_ref().skip(1).take_while(|&c| c != '}').collect();
out.push(char::from_u32(u32::from_str_radix(&hex, 16).unwrap()).unwrap());
}
Some(other) => out.push(other),
None => out.push('\\'),
}
}
out
}
#[test]
fn unescape_rust_literal_reads_every_rust_escape() {
for (body, text) in [
(r"plain", "plain"),
(r#"a \"quoted\" word"#, "a \"quoted\" word"),
(r"back\\slash", "back\\slash"),
(r"line\nbreak", "line\nbreak"),
(r"tab\there", "tab\there"),
(r"cr\r", "cr\r"),
(r"nul\0", "nul\0"),
(r"it\'s", "it's"),
(r"hex\x41", "hexA"),
(r"\u{2026}\u{1F600}", "\u{2026}\u{1F600}"),
(
r"\\n stays a backslash and an n",
"\\n stays a backslash and an n",
),
] {
assert_eq!(unescape_rust_literal(body), text, "{body}");
}
}
fn strings_croft_translates() -> std::collections::BTreeMap<String, String> {
let lit = r#""((?:[^"\\]|\\.)*)""#;
let patterns: Vec<regex::Regex> = [
format!(r"\btr\(\s*{lit}\s*\)"),
format!(r"MenuEntry::(?:item|header)\(\s*{lit}"),
format!(r"MenuEntry::item\(\s*if [^{{]*\{{\s*{lit}\s*\}}\s*else\s*\{{\s*{lit}\s*\}}"),
format!(r"MenuEntry::Submenu\s*\{{\s*label:\s*(?:String::from\(\s*)?{lit}"),
format!(r"\(\s*String::from\(\s*{lit}\s*\)\s*,\s*MenuAction::"),
format!(r"\(\s*{lit}\s*\.(?:to_string|to_owned|into)\(\)\s*,\s*MenuAction::"),
]
.iter()
.map(|p| regex::Regex::new(p).unwrap())
.collect();
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut dirs = vec![root.clone()];
let mut found = std::collections::BTreeMap::new();
while let Some(dir) = dirs.pop() {
for entry in std::fs::read_dir(&dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
if !path.ends_with("app/tests") {
dirs.push(path);
}
continue;
}
if path.extension().is_none_or(|e| e != "rs") {
continue;
}
let text = std::fs::read_to_string(&path).unwrap();
let text = text
.find("#[cfg(test)]\nmod tests")
.map_or(text.as_str(), |i| &text[..i]);
let file = path.strip_prefix(&root).unwrap().display().to_string();
for re in &patterns {
for caps in re.captures_iter(text) {
for m in caps.iter().skip(1).flatten() {
found.insert(unescape_rust_literal(m.as_str()), file.clone());
}
}
}
}
}
found
}
#[test]
fn locale_template_lists_every_string_croft_translates() {
let found = strings_croft_translates();
for known in [
"Close to the Right",
"Panel Alignment",
"CodeQL",
"Pin",
"Unpin",
] {
assert!(
found.contains_key(known),
"the source scan still sees {known:?}; update it with the code"
);
}
let out = Command::cargo_bin("croft")
.unwrap()
.args(["locale-template", "xx"])
.assert()
.success();
let template: std::collections::HashMap<String, String> =
serde_json::from_slice(&out.get_output().stdout).unwrap();
let missing: Vec<String> = found
.iter()
.filter(|(s, _)| !template.contains_key(*s))
.map(|(s, file)| format!("{s:?} ({file})"))
.collect();
assert!(
missing.is_empty(),
"{} string(s) croft translates are missing from the template; add them to \
i18n::TRANSLATABLE:\n{}",
missing.len(),
missing.join("\n")
);
}
fn config_with_french_started() -> (tempfile::TempDir, std::path::PathBuf) {
let cfg = tempfile::tempdir().unwrap();
let file = cfg.path().join("croft/locales/fr.json");
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
std::fs::write(
&file,
"{\n \"File: Save\": \"Enregistrer\",\n \"View: Toggle Terminal\": \"Afficher le terminal\"\n}\n",
)
.unwrap();
(cfg, file)
}
fn json_object(text: &str) -> serde_json::Map<String, serde_json::Value> {
serde_json::from_str::<serde_json::Value>(text)
.unwrap()
.as_object()
.unwrap()
.clone()
}
#[test]
fn locale_template_write_keeps_the_translations_already_in_the_file() {
let (cfg, file) = config_with_french_started();
let out = Command::cargo_bin("croft")
.unwrap()
.env("XDG_CONFIG_HOME", cfg.path())
.args(["locale-template", "fr", "--write"])
.assert()
.success();
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
let map = json_object(&std::fs::read_to_string(&file).unwrap());
assert_eq!(map["File: Save"], "Enregistrer");
assert_eq!(map["View: Toggle Terminal"], "Afficher le terminal");
assert!(map.len() > 2, "the missing strings are added");
assert!(stderr.contains("locales/fr.json"), "{stderr}");
}
#[test]
fn locale_template_prints_the_users_own_translations() {
let (cfg, _file) = config_with_french_started();
let out = Command::cargo_bin("croft")
.unwrap()
.env("XDG_CONFIG_HOME", cfg.path())
.args(["locale-template", "fr"])
.assert()
.success();
let map = json_object(&String::from_utf8(out.get_output().stdout.clone()).unwrap());
assert_eq!(map["File: Save"], "Enregistrer");
}
#[test]
fn locale_template_write_starts_a_new_translation() {
let cfg = tempfile::tempdir().unwrap();
Command::cargo_bin("croft")
.unwrap()
.env("XDG_CONFIG_HOME", cfg.path())
.args(["locale-template", "fr", "--write"])
.assert()
.success();
let map =
json_object(&std::fs::read_to_string(cfg.path().join("croft/locales/fr.json")).unwrap());
assert_eq!(map["File: Save"], "");
}
#[test]
fn locale_template_write_leaves_an_unreadable_file_alone() {
let (cfg, file) = config_with_french_started();
let broken = "{\n \"File: Save\": \"Enregistrer\",\n";
std::fs::write(&file, broken).unwrap();
let out = Command::cargo_bin("croft")
.unwrap()
.env("XDG_CONFIG_HOME", cfg.path())
.args(["locale-template", "fr", "--write"])
.assert()
.failure()
.code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert_eq!(std::fs::read_to_string(&file).unwrap(), broken);
assert!(stderr.contains("fr.json"), "{stderr}");
}
#[test]
fn locale_template_write_for_english_writes_nothing() {
let cfg = tempfile::tempdir().unwrap();
Command::cargo_bin("croft")
.unwrap()
.env("XDG_CONFIG_HOME", cfg.path())
.args(["locale-template", "en", "--write"])
.assert()
.failure()
.code(1);
assert!(!cfg.path().join("croft/locales").exists());
}
#[cfg(unix)]
#[test]
fn import_vscode_writes_its_files_when_stdout_is_closed() {
use std::os::unix::process::ExitStatusExt;
let cfg = tempfile::tempdir().unwrap();
let from = tempfile::tempdir().unwrap();
std::fs::write(
from.path().join("settings.json"),
r#"{ "editor.formatOnSave": true }"#,
)
.unwrap();
std::fs::write(
from.path().join("keybindings.json"),
r#"[{ "key": "ctrl+s", "command": "workbench.action.files.save" }]"#,
)
.unwrap();
let mut child = std::process::Command::new(assert_cmd::cargo::cargo_bin("croft"))
.args(["import-vscode", "--from"])
.arg(from.path())
.env("XDG_CONFIG_HOME", cfg.path())
.current_dir(cfg.path())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
drop(child.stdout.take());
let out = child.wait_with_output().unwrap();
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
out.status.success() || out.status.signal() == Some(13),
"a closed pipe ends croft quietly, not with {:?}: {stderr}",
out.status
);
assert!(!stderr.contains("panicked"), "{stderr}");
let config = std::fs::read_to_string(cfg.path().join("croft/config.json")).unwrap();
assert!(config.contains("format_on_save"), "{config}");
assert!(cfg.path().join("croft/keybindings.json").is_file());
}
#[cfg(unix)]
#[test]
fn import_vscode_reports_a_failed_write_when_stdout_is_closed() {
let tmp = tempfile::tempdir().unwrap();
let from = tempfile::tempdir().unwrap();
std::fs::write(
from.path().join("settings.json"),
r#"{ "editor.formatOnSave": true }"#,
)
.unwrap();
let blocked = tmp.path().join("not-a-dir");
std::fs::write(&blocked, "").unwrap();
let mut child = std::process::Command::new(assert_cmd::cargo::cargo_bin("croft"))
.args(["import-vscode", "--from"])
.arg(from.path())
.env("XDG_CONFIG_HOME", &blocked)
.current_dir(tmp.path())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.unwrap();
drop(child.stdout.take());
let out = child.wait_with_output().unwrap();
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(!out.status.success(), "{:?}", out.status);
assert!(
stderr.contains("not-a-dir"),
"the failure is said: {stderr}"
);
}
#[cfg(unix)]
struct PtyCroft {
child: std::process::Child,
pty: std::mem::ManuallyDrop<std::fs::File>,
}
#[cfg(unix)]
impl PtyCroft {
fn spawn(dir: &std::path::Path, args: &[&str]) -> Self {
use std::os::fd::{FromRawFd, OwnedFd};
use std::os::unix::process::CommandExt;
let (mut master, mut slave) = (0, 0);
let mut ws = libc::winsize {
ws_row: 40,
ws_col: 140,
ws_xpixel: 0,
ws_ypixel: 0,
};
assert_eq!(
unsafe {
libc::openpty(
&mut master,
&mut slave,
std::ptr::null_mut(),
std::ptr::null_mut(),
&raw mut ws,
)
},
0
);
for fd in [master, slave] {
assert_ne!(
unsafe { libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC) },
-1
);
}
let slave = unsafe { OwnedFd::from_raw_fd(slave) };
let mut cmd = std::process::Command::new(assert_cmd::cargo::cargo_bin("croft"));
cmd.args(args)
.current_dir(dir)
.env("HOME", dir)
.env("TERM", "xterm-256color")
.env_remove("TERM_PROGRAM")
.env_remove("TMUX")
.stdin(slave.try_clone().unwrap())
.stdout(slave.try_clone().unwrap())
.stderr(slave.try_clone().unwrap());
unsafe {
cmd.pre_exec(|| {
if libc::setsid() == -1 || libc::ioctl(0, libc::TIOCSCTTY as _, 0) == -1 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
let child = cmd.spawn().unwrap();
drop(slave);
unsafe {
let flags = libc::fcntl(master, libc::F_GETFL);
libc::fcntl(master, libc::F_SETFL, flags | libc::O_NONBLOCK);
}
let pty = unsafe { std::fs::File::from_raw_fd(master) };
Self {
child,
pty: std::mem::ManuallyDrop::new(pty),
}
}
fn read_until(
&mut self,
limit: std::time::Duration,
mut done: impl FnMut(&str) -> bool,
) -> String {
use std::io::Read;
let mut out = String::new();
let mut buf = [0u8; 1 << 16];
let end = std::time::Instant::now() + limit;
while !done(&out) && std::time::Instant::now() < end {
match self.pty.read(&mut buf) {
Ok(0) => break,
Ok(k) => out.push_str(&String::from_utf8_lossy(&buf[..k])),
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
std::thread::sleep(std::time::Duration::from_millis(10))
}
Err(e) if e.raw_os_error() == Some(libc::EIO) => break,
Err(e) => panic!("reading croft's terminal: {e}"),
}
}
out
}
fn send(&mut self, bytes: &[u8]) {
use std::io::Write;
self.pty.write_all(bytes).unwrap();
}
}
#[cfg(unix)]
const PTY_LIMIT: std::time::Duration = std::time::Duration::from_secs(20);
#[cfg(unix)]
impl Drop for PtyCroft {
fn drop(&mut self) {
let _ = self.child.kill();
unsafe { std::mem::ManuallyDrop::drop(&mut self.pty) };
let _ = self.child.wait();
}
}
#[cfg(unix)]
#[test]
fn croft_keys_reads_tmux_ctrl_shift_s_with_the_shift_and_nothing_else_with_one() {
let home = tempfile::tempdir().unwrap();
let mut croft = PtyCroft::spawn(home.path(), &["keys"]);
let banner = croft.read_until(PTY_LIMIT, |out| out.contains("croft keys"));
assert!(banner.contains("croft keys"), "no banner: {banner:?}");
let cases: [(&str, &[u8]); 4] = [
("tmux CSI u Ctrl+Shift+S", b"\x1b[83;6u"),
("legacy Ctrl+S byte", b"\x13"),
("uppercase S, Ctrl, no Shift flag", b"\x1b[83;5u"),
("tmux 3.5 CSI 27 Ctrl+Shift+S", b"\x1b[27;6;83~"),
];
let mut reports = Vec::new();
for (i, (name, bytes)) in cases.iter().enumerate() {
let marker = format!("code=Char('{i}')");
croft.send(bytes);
croft.send(format!("{i}").as_bytes());
let seen = croft.read_until(PTY_LIMIT, |out| out.contains(&marker));
let lines: Vec<String> = seen
.lines()
.filter(|l| l.contains("code="))
.take_while(|l| !l.contains(&marker))
.map(|l| l.split(" code=").nth(1).unwrap_or(l).trim().to_string())
.collect();
assert!(seen.contains(&marker), "{name}: marker lost in {seen:?}");
reports.push((*name, lines));
}
let [csi_u, legacy, no_flag, csi_27] = reports.try_into().unwrap();
assert_eq!(
csi_u.1,
vec!["Char('S') modifiers=[CONTROL + SHIFT] kitty=true"],
"{}",
csi_u.0
);
assert_eq!(
legacy.1,
vec!["Char('s') modifiers=[CONTROL] kitty=true"],
"{}",
legacy.0
);
assert_eq!(
no_flag.1,
vec!["Char('S') modifiers=[CONTROL] kitty=true"],
"{}",
no_flag.0
);
assert!(
csi_27
.1
.iter()
.all(|l| !l.ends_with("modifiers=[CONTROL] kitty=true")),
"{}: {:?}",
csi_27.0,
csi_27.1
);
}
#[cfg(unix)]
#[test]
fn ctrl_shift_s_as_tmux_sends_it_does_not_save_while_ctrl_s_does() {
let home = tempfile::tempdir().unwrap();
let file = home.path().join("a.txt");
std::fs::write(&file, "alpha\n").unwrap();
let mut croft = PtyCroft::spawn(home.path(), &["a.txt"]);
let saved = |want: &str| std::fs::read_to_string(&file).unwrap() == want;
let started = croft.read_until(PTY_LIMIT, |out| out.contains("alpha"));
assert!(
started.contains("alpha"),
"croft never drew a.txt: {started:?}"
);
croft.send(b"\x1b");
croft.read_until(std::time::Duration::from_millis(300), |_| false);
croft.send(b"x");
croft.send(b"\x13");
croft.read_until(PTY_LIMIT, |_| saved("xalpha\n"));
assert_eq!(
std::fs::read_to_string(&file).unwrap(),
"xalpha\n",
"setup: the typed x lands in a.txt and Ctrl+S saves it"
);
croft.send(b"y");
croft.send(b"\x1b[83;6u");
let drawn = croft.read_until(PTY_LIMIT, |out| out.contains("SOURCE CONTROL"));
assert_eq!(
std::fs::read_to_string(&file).unwrap(),
"xalpha\n",
"Ctrl+Shift+S with the Shift reported must not save"
);
assert!(
drawn.contains("SOURCE CONTROL"),
"Ctrl+Shift+S opens Source Control"
);
}
fn sequence_editor_command(dir: &std::path::Path, editor: &str) -> Command {
let no_config = dir.join("empty.gitconfig");
std::fs::write(&no_config, "").unwrap();
let mut cmd = Command::cargo_bin("croft").unwrap();
cmd.env("GIT_EDITOR", editor)
.env("GIT_CONFIG_GLOBAL", &no_config)
.env("GIT_CONFIG_NOSYSTEM", "1")
.current_dir(dir);
cmd
}
#[test]
fn the_sequence_editor_falls_back_to_gits_editor_when_its_croft_is_gone() {
let tmp = tempfile::tempdir().unwrap();
let plan = tmp.path().join("git-rebase-todo");
std::fs::write(&plan, "pick 1234567 one\n").unwrap();
let out = sequence_editor_command(tmp.path(), "echo edited >>")
.env("CROFT_VIEW_SOCK", tmp.path().join("nobody.sock"))
.args(["edit", "--wait", "--sequence-editor", "git-rebase-todo"])
.assert();
let out = out.success();
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.contains("croft is not running; using echo edited >>"),
"says which editor it used, was: {stderr}"
);
assert_eq!(
std::fs::read_to_string(&plan).unwrap(),
"pick 1234567 one\nedited\n",
"git's editor ran on the plan"
);
}
#[test]
fn the_sequence_editor_falls_back_when_no_croft_socket_is_set() {
let tmp = tempfile::tempdir().unwrap();
let plan = tmp.path().join("git-rebase-todo");
std::fs::write(&plan, "pick 1234567 one\n").unwrap();
sequence_editor_command(tmp.path(), "echo edited >>")
.env_remove("CROFT_VIEW_SOCK")
.args(["edit", "--wait", "--sequence-editor", "git-rebase-todo"])
.assert()
.success();
assert!(
std::fs::read_to_string(&plan)
.unwrap()
.ends_with("edited\n")
);
}
#[test]
fn a_failing_fallback_editor_fails_the_sequence_editor() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("git-rebase-todo"), "pick 1234567 one\n").unwrap();
let out = sequence_editor_command(tmp.path(), "exit 3;")
.env("CROFT_VIEW_SOCK", tmp.path().join("nobody.sock"))
.args(["edit", "--wait", "--sequence-editor", "git-rebase-todo"])
.assert();
let out = out.failure().code(3);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(stderr.contains("using exit 3;"), "stderr was: {stderr}");
}
#[test]
fn a_plain_edit_against_a_gone_croft_still_fails() {
let tmp = tempfile::tempdir().unwrap();
let plan = tmp.path().join("notes.txt");
std::fs::write(&plan, "keep\n").unwrap();
let out = sequence_editor_command(tmp.path(), "echo edited >>")
.env("CROFT_VIEW_SOCK", tmp.path().join("nobody.sock"))
.args(["edit", "--wait", "notes.txt"])
.assert();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.contains("the croft that opened this pane is gone"),
"stderr was: {stderr}"
);
assert_eq!(std::fs::read_to_string(&plan).unwrap(), "keep\n");
}
#[test]
fn a_croft_that_refuses_the_plan_is_not_replaced_by_gits_editor() {
use std::io::{BufRead, BufReader, Write};
let tmp = tempfile::tempdir().unwrap();
let plan = tmp.path().join("git-rebase-todo");
std::fs::write(&plan, "pick 1234567 one\n").unwrap();
let sock = tmp.path().join("v.sock");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let server = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut line = String::new();
BufReader::new(&stream).read_line(&mut line).unwrap();
stream
.write_all(b"{\"status\":\"err\",\"message\":\"cannot open that here\"}\n")
.unwrap();
});
let out = sequence_editor_command(tmp.path(), "echo edited >>")
.env("CROFT_VIEW_SOCK", &sock)
.args(["edit", "--wait", "--sequence-editor", "git-rebase-todo"])
.assert();
server.join().unwrap();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(
stderr.contains("cannot open that here"),
"stderr was: {stderr}"
);
assert_eq!(
std::fs::read_to_string(&plan).unwrap(),
"pick 1234567 one\n"
);
}
#[test]
fn a_croft_that_closes_without_replying_is_not_replaced_by_gits_editor() {
use std::io::{BufRead, BufReader};
let tmp = tempfile::tempdir().unwrap();
let plan = tmp.path().join("git-rebase-todo");
std::fs::write(&plan, "pick 1234567 one\n").unwrap();
let sock = tmp.path().join("v.sock");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let server = std::thread::spawn(move || {
let (stream, _) = listener.accept().unwrap();
let mut line = String::new();
BufReader::new(&stream).read_line(&mut line).unwrap();
});
let out = sequence_editor_command(tmp.path(), "echo edited >>")
.env("CROFT_VIEW_SOCK", &sock)
.args(["edit", "--wait", "--sequence-editor", "git-rebase-todo"])
.assert();
server.join().unwrap();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(!stderr.contains("not running"), "stderr was: {stderr}");
assert_eq!(
std::fs::read_to_string(&plan).unwrap(),
"pick 1234567 one\n"
);
}
#[test]
fn the_sequence_editor_fails_when_git_names_no_editor() {
let tmp = tempfile::tempdir().unwrap();
let plan = tmp.path().join("git-rebase-todo");
std::fs::write(&plan, "pick 1234567 one\n").unwrap();
let out = sequence_editor_command(tmp.path(), "unused")
.env_remove("GIT_EDITOR")
.env_remove("VISUAL")
.env_remove("EDITOR")
.env("TERM", "dumb")
.env("CROFT_VIEW_SOCK", tmp.path().join("nobody.sock"))
.args(["edit", "--wait", "--sequence-editor", "git-rebase-todo"])
.assert();
let out = out.failure().code(1);
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(!stderr.contains("using"), "stderr was: {stderr}");
assert!(
stderr.contains("the croft that opened this pane is gone"),
"stderr was: {stderr}"
);
assert_eq!(
std::fs::read_to_string(&plan).unwrap(),
"pick 1234567 one\n"
);
}
#[test]
fn a_live_croft_still_gets_the_plan() {
use std::io::{BufRead, BufReader, Write};
let tmp = tempfile::tempdir().unwrap();
let plan = tmp.path().join("git-rebase-todo");
std::fs::write(&plan, "pick 1234567 one\n").unwrap();
let sock = tmp.path().join("v.sock");
let listener = std::os::unix::net::UnixListener::bind(&sock).unwrap();
let server = std::thread::spawn(move || {
let replies: [&[u8]; 2] = [
b"{\"status\":\"ok\"}\n",
b"{\"status\":\"err\",\"message\":\"closed\"}\n",
];
for reply in replies {
let (mut stream, _) = listener.accept().unwrap();
let mut line = String::new();
BufReader::new(&stream).read_line(&mut line).unwrap();
stream.write_all(reply).unwrap();
}
});
let out = sequence_editor_command(tmp.path(), "echo edited >>")
.env("CROFT_VIEW_SOCK", &sock)
.args(["edit", "--wait", "--sequence-editor", "git-rebase-todo"])
.assert();
server.join().unwrap();
let out = out.success();
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(!stderr.contains("not running"), "stderr was: {stderr}");
assert_eq!(
std::fs::read_to_string(&plan).unwrap(),
"pick 1234567 one\n"
);
}
#[cfg(not(target_os = "macos"))]
#[test]
fn setup_ghostty_refuses_off_macos_and_writes_nothing() {
let home = tempfile::tempdir().unwrap();
let config = home.path().join(".config/ghostty/config.ghostty");
std::fs::create_dir_all(config.parent().unwrap()).unwrap();
std::fs::write(&config, "font-size = 14\n").unwrap();
let out = Command::cargo_bin("croft")
.unwrap()
.args(["setup-ghostty", "-y"])
.env("HOME", home.path())
.env_remove("XDG_CONFIG_HOME")
.assert()
.failure();
let stderr = String::from_utf8(out.get_output().stderr.clone()).unwrap();
assert!(stderr.contains("macOS-only"), "stderr was: {stderr}");
assert!(!home.path().join("Library").exists());
assert_eq!(
std::fs::read_to_string(&config).unwrap(),
"font-size = 14\n"
);
}