diff --git a/LESSONS.md b/LESSONS.md index cb0811b..bd91506 100644 --- a/LESSONS.md +++ b/LESSONS.md @@ -4,7 +4,8 @@ - `git clone --bare` sets no `remote.origin.fetch`; without it `fetch` never creates `refs/remotes/*`. Use `receive::ensure_fetch_refspec`. - `Git::run` trims stdout, which also eats the leading space of the first `status --porcelain` line (` M x` becomes `M x`). Don't assert on that format via `run`. - Fetch other machines' snapshots into `refs/sync-remote/*`, never into `refs/sync/*`, or a fetch can clobber this machine's own refs. -- Run tests that create many temp repos with unique dir names (pid + nanos); the shared `tests/common` helper does this. +- Run tests that create many temp repos with unique dir names (pid + nanos + counter) via the shared RAII `test-support/tmp.rs` (`TempDir`, included with `#[path]`); never call `std::env::temp_dir()` directly in a test. +- Tests must clean their temp dirs, also on failure: `/tmp` is tmpfs and ran out of inodes after a day of `cargo test` runs. Use `TempDir` (removed on drop) and kill spawned daemons by their own `Child` handle before the dir goes. - Bare-layout clones must set upstream tracking per branch, or `status` silently reports Synced for Behind/Diverged. Assert tracking in tests of any clone path. - Unix socket paths are limited to ~100 bytes: use a short `XDG_RUNTIME_DIR` (e.g. `/tmp/gd`) when running a daemon from deep scratch dirs. - Mock-server tests must parse the JSON request body; pretty-printed JSON breaks string asserts. diff --git a/crates/grove-core/src/busy.rs b/crates/grove-core/src/busy.rs index 58f399f..7539ea6 100644 --- a/crates/grove-core/src/busy.rs +++ b/crates/grove-core/src/busy.rs @@ -73,8 +73,8 @@ mod tests { #[test] fn marker_lifecycle() { - let d = std::env::temp_dir().join(format!("grove-busy-{}", std::process::id())); - let _ = fs::remove_dir_all(&d); + let tmp = crate::test_tmp::TempDir::new("busy"); + let d = tmp.path().join("d"); assert_eq!(busy_state(&d), BusyState::Free); let g = BusyGuard::acquire(&d).unwrap(); assert_eq!(busy_state(&d), BusyState::Active); diff --git a/crates/grove-core/src/lib.rs b/crates/grove-core/src/lib.rs index 59e8c8e..04797f0 100644 --- a/crates/grove-core/src/lib.rs +++ b/crates/grove-core/src/lib.rs @@ -1,5 +1,9 @@ //! Sync engine core: git plumbing wrapper, config, snapshots and state classification. +#[cfg(test)] +#[path = "../../../test-support/tmp.rs"] +mod test_tmp; + pub mod busy; pub mod config; pub mod git; diff --git a/crates/grove-core/src/registry.rs b/crates/grove-core/src/registry.rs index 7da8120..e0e5712 100644 --- a/crates/grove-core/src/registry.rs +++ b/crates/grove-core/src/registry.rs @@ -218,8 +218,8 @@ mod tests { #[test] fn rollback_that_cannot_remove_everything_leaves_a_stage_marker() { - let d = std::env::temp_dir().join(format!("grove-rb-{}", std::process::id())); - let _ = fs::remove_dir_all(&d); + let tmp = crate::test_tmp::TempDir::new("rb"); + let d = tmp.path().join("d"); let locked = d.join(".bare/locked"); fs::create_dir_all(&locked).unwrap(); fs::write(locked.join("f"), "x").unwrap(); diff --git a/crates/grove-core/tests/common/mod.rs b/crates/grove-core/tests/common/mod.rs index af7ccad..c8a8ccc 100644 --- a/crates/grove-core/tests/common/mod.rs +++ b/crates/grove-core/tests/common/mod.rs @@ -1,19 +1,14 @@ #![allow(dead_code)] use grove_core::git::Git; use std::fs; -use std::path::{Path, PathBuf}; +use std::path::Path; -pub fn tmpdir(tag: &str) -> PathBuf { - let p = std::env::temp_dir().join(format!( - "grove-test-{tag}-{}-{}", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - fs::create_dir_all(&p).unwrap(); - p +#[path = "../../../../test-support/tmp.rs"] +pub mod tmp; + +/// A unique temp dir that is removed (recursively) when dropped, also if the test fails. +pub fn tmpdir(tag: &str) -> tmp::TempDir { + tmp::TempDir::new(tag) } pub fn init(dir: &Path) -> Git { diff --git a/crates/grove-core/tests/inspect.rs b/crates/grove-core/tests/inspect.rs index 527ac16..5dbeaed 100644 --- a/crates/grove-core/tests/inspect.rs +++ b/crates/grove-core/tests/inspect.rs @@ -1,22 +1,11 @@ use grove_core::git::Git; use grove_core::inspect::{state, worktrees}; use grove_core::state::State; +mod common; +use common::tmpdir; use std::fs; use std::path::{Path, PathBuf}; -fn tmpdir(tag: &str) -> PathBuf { - let p = std::env::temp_dir().join(format!( - "grove-test-{tag}-{}-{}", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - fs::create_dir_all(&p).unwrap(); - p -} - fn commit(g: &Git, dir: &Path, file: &str, body: &str) { fs::write(dir.join(file), body).unwrap(); g.run(&["add", "."]).unwrap(); @@ -24,7 +13,7 @@ fn commit(g: &Git, dir: &Path, file: &str, body: &str) { } /// A bare "remote" plus two clones (two machines) tracking its `main`. -fn setup() -> (Git, PathBuf, Git, PathBuf) { +fn setup() -> (common::tmp::TempDir, Git, PathBuf, Git, PathBuf) { let base = tmpdir("inspect"); let remote = base.join("remote.git"); Git::new(&base) @@ -60,12 +49,12 @@ fn setup() -> (Git, PathBuf, Git, PathBuf) { g2.run(&["pull", "-q", "origin", "main"]).unwrap(); g2.run(&["branch", "-q", "--set-upstream-to=origin/main", "main"]) .unwrap(); - (g1, d1, g2, d2) + (base, g1, d1, g2, d2) } #[test] fn classifies_real_repos() { - let (g1, d1, g2, d2) = setup(); + let (_base, g1, d1, g2, d2) = setup(); assert_eq!(state(&d1), State::Synced); fs::write(d1.join("wip.txt"), "x").unwrap(); diff --git a/crates/grove-core/tests/receive.rs b/crates/grove-core/tests/receive.rs index 567614b..b86bd34 100644 --- a/crates/grove-core/tests/receive.rs +++ b/crates/grove-core/tests/receive.rs @@ -9,6 +9,7 @@ use std::fs; use std::path::PathBuf; struct World { + _tmp: common::tmp::TempDir, base: PathBuf, remote: PathBuf, g1: Git, @@ -19,7 +20,8 @@ struct World { /// Bare remote plus two plain clones (machines "m1" and "m2") sharing `main` with one commit. fn world() -> World { - let base = tmpdir("recv"); + let tmp = tmpdir("recv"); + let base = tmp.to_path_buf(); let remote = base.join("remote.git"); Git::new(&base) .run(&[ @@ -51,6 +53,7 @@ fn world() -> World { g2.run(&["config", "user.email", "t@t"]).unwrap(); g2.run(&["config", "user.name", "t"]).unwrap(); World { + _tmp: tmp, base, remote, g1, diff --git a/crates/grove-core/tests/resolve.rs b/crates/grove-core/tests/resolve.rs index 6d6e32e..a46017b 100644 --- a/crates/grove-core/tests/resolve.rs +++ b/crates/grove-core/tests/resolve.rs @@ -9,7 +9,7 @@ use std::fs; use std::path::PathBuf; /// Two machines on the bare layout, both committed on main: diverged on B. -fn diverged() -> (PathBuf, PathBuf, PathBuf) { +fn diverged() -> (common::tmp::TempDir, PathBuf, PathBuf) { let base = tmpdir("resolve"); let remote = base.join("r.git"); Git::new(&base) diff --git a/crates/grove-core/tests/snapshot.rs b/crates/grove-core/tests/snapshot.rs index 4c62007..f3447c9 100644 --- a/crates/grove-core/tests/snapshot.rs +++ b/crates/grove-core/tests/snapshot.rs @@ -1,20 +1,9 @@ use grove_core::git::Git; use grove_core::snapshot::{Outcome, take}; +mod common; +use common::tmpdir; use std::fs; -use std::path::{Path, PathBuf}; - -fn tmpdir(tag: &str) -> PathBuf { - let p = std::env::temp_dir().join(format!( - "grove-test-{tag}-{}-{}", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - fs::create_dir_all(&p).unwrap(); - p -} +use std::path::Path; fn repo(dir: &Path) -> Git { let g = Git::new(dir); diff --git a/crates/grove-daemon/src/discover.rs b/crates/grove-daemon/src/discover.rs index 94b33b3..c28f54d 100644 --- a/crates/grove-daemon/src/discover.rs +++ b/crates/grove-daemon/src/discover.rs @@ -91,7 +91,8 @@ mod tests { #[test] fn only_bare_layout_repos_in_configured_groups_are_managed() { - let base = std::env::temp_dir().join(format!("grove-disc-{}", std::process::id())); + let _tmp = crate::test_tmp::TempDir::new("grove-disc"); + let base = _tmp.path().to_path_buf(); let _ = std::fs::remove_dir_all(&base); for d in [ "grp/migrated/.bare", diff --git a/crates/grove-daemon/src/lib.rs b/crates/grove-daemon/src/lib.rs index 15ee4ea..0bed1d6 100644 --- a/crates/grove-daemon/src/lib.rs +++ b/crates/grove-daemon/src/lib.rs @@ -6,6 +6,9 @@ pub mod activity; pub mod daemon; pub mod discover; pub mod ipc; +#[cfg(test)] +#[path = "../../../test-support/tmp.rs"] +mod test_tmp; pub mod visibility; pub use activity::{Activity, Event}; diff --git a/crates/grove-daemon/src/visibility.rs b/crates/grove-daemon/src/visibility.rs index 7a4bd36..bd63c88 100644 --- a/crates/grove-daemon/src/visibility.rs +++ b/crates/grove-daemon/src/visibility.rs @@ -670,7 +670,8 @@ owners = { github = "gh-org" } #[test] fn cache_persists_in_the_state_dir_with_mode_0600() { use std::os::unix::fs::PermissionsExt; - let dir = std::env::temp_dir().join(format!("grove-vis-{}", std::process::id())); + let _tmp = crate::test_tmp::TempDir::new("grove-vis"); + let dir = _tmp.path().to_path_buf(); let _ = std::fs::remove_dir_all(&dir); let file = dir.join("visibility.json"); let c = cfg(); @@ -714,7 +715,8 @@ owners = { github = "gh-org" } #[test] fn gate_uses_group_policy_and_every_push_url() { let c = cfg(); - let base = std::env::temp_dir().join(format!("grove-gate-{}", std::process::id())); + let _tmp = crate::test_tmp::TempDir::new("grove-gate"); + let base = _tmp.path().to_path_buf(); let _ = std::fs::remove_dir_all(&base); let f = Fake::default() .with("o/r", Ok(Seen::Private)) @@ -752,7 +754,8 @@ owners = { github = "gh-org" } #[test] fn gate_checks_all_push_urls_and_push_instead_of() { let c = cfg(); - let base = std::env::temp_dir().join(format!("grove-gate2-{}", std::process::id())); + let _tmp = crate::test_tmp::TempDir::new("grove-gate2"); + let base = _tmp.path().to_path_buf(); let _ = std::fs::remove_dir_all(&base); let f = Fake::default() .with("o/r", Ok(Seen::Private)) @@ -781,7 +784,8 @@ owners = { github = "gh-org" } #[test] fn gate_requires_mirror_targets_to_be_private_or_absent() { let c = cfg(); - let base = std::env::temp_dir().join(format!("grove-gate3-{}", std::process::id())); + let _tmp = crate::test_tmp::TempDir::new("grove-gate3"); + let base = _tmp.path().to_path_buf(); let _ = std::fs::remove_dir_all(&base); let repo = mk(&base, "mir", &["https://git.example.com:3000/o/r.git"], &[]); let gate = |f: &Fake| { diff --git a/crates/grove-daemon/tests/daemon.rs b/crates/grove-daemon/tests/daemon.rs index 1500b7d..04cd008 100644 --- a/crates/grove-daemon/tests/daemon.rs +++ b/crates/grove-daemon/tests/daemon.rs @@ -1,6 +1,8 @@ use grove_core::config::Config; use grove_daemon::{Daemon, Settings, ipc}; use serde_json::json; +#[path = "../../../test-support/tmp.rs"] +mod tmp; use std::fs; use std::path::{Path, PathBuf}; use std::process::Command; @@ -39,18 +41,24 @@ fn wait_until(what: &str, secs: u64, mut f: impl FnMut() -> bool) { struct World { base: PathBuf, remote: PathBuf, + // Declared last so it is dropped (and the dir removed) after everything else in the world. + _tmp: tmp::TempDir, } -fn tmpdir(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("grove-dt-{tag}-{}", std::process::id())); - let _ = fs::remove_dir_all(&d); - fs::create_dir_all(&d).unwrap(); - d +/// Kills and reaps a spawned `groved` (by its own handle) when dropped, also on panic. +struct Spawned(std::process::Child); + +impl Drop for Spawned { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } } /// A bare remote plus one seeded clone per machine under `//repo`. fn world(tag: &str, machines: &[&str]) -> World { - let base = tmpdir(tag); + let tmp = tmp::TempDir::new(tag); + let base = tmp.path().to_path_buf(); let remote = base.join("remote.git"); fs::create_dir_all(&remote).unwrap(); git(&remote, &["init", "-q", "--bare", "-b", "main"]); @@ -70,7 +78,11 @@ fn world(tag: &str, machines: &[&str]) -> World { fs::create_dir_all(&dir).unwrap(); bare_layout(&dir.join("g/repo"), &remote); } - World { base, remote } + World { + base, + remote, + _tmp: tmp, + } } /// A bare + worktrees repo (`.bare`, worktree `main`) cloned from `remote`, as `grove add` leaves it. @@ -274,22 +286,24 @@ fn killing_the_daemon_loses_nothing_and_a_restart_recovers() { let runtime = w.base.join("run"); fs::create_dir_all(&runtime).unwrap(); let spawn = || { - Command::new(env!("CARGO_BIN_EXE_groved")) - .arg("--config") - .arg(&cfg_path) - .env("XDG_RUNTIME_DIR", &runtime) - .env("XDG_STATE_HOME", w.base.join("state")) - .env("GIT_AUTHOR_NAME", "t") - .spawn() - .unwrap() + Spawned( + Command::new(env!("CARGO_BIN_EXE_groved")) + .arg("--config") + .arg(&cfg_path) + .env("XDG_RUNTIME_DIR", &runtime) + .env("XDG_STATE_HOME", w.base.join("state")) + .env("GIT_AUTHOR_NAME", "t") + .spawn() + .unwrap(), + ) }; let mut child = spawn(); std::thread::sleep(Duration::from_millis(300)); fs::write(repo.join("wip.txt"), "precious\n").unwrap(); // Kill at an arbitrary moment: maybe before, during or after a pass. std::thread::sleep(Duration::from_millis(400)); - child.kill().unwrap(); - child.wait().unwrap(); + child.0.kill().unwrap(); + child.0.wait().unwrap(); assert_eq!( fs::read_to_string(repo.join("wip.txt")).unwrap(), @@ -310,8 +324,8 @@ fn killing_the_daemon_loses_nothing_and_a_restart_recovers() { fs::read_to_string(repo.join("wip.txt")).unwrap(), "precious\n" ); - child.kill().unwrap(); - child.wait().unwrap(); + child.0.kill().unwrap(); + child.0.wait().unwrap(); } #[test] @@ -356,24 +370,26 @@ fn paused_daemon_does_not_spin() { .unwrap(); let runtime = w.base.join("run"); fs::create_dir_all(&runtime).unwrap(); - let mut child = Command::new(env!("CARGO_BIN_EXE_groved")) - .arg("--config") - .arg(&cfg_path) - .env("XDG_RUNTIME_DIR", &runtime) - .env("XDG_STATE_HOME", w.base.join("state")) - .spawn() - .unwrap(); + let mut child = Spawned( + Command::new(env!("CARGO_BIN_EXE_groved")) + .arg("--config") + .arg(&cfg_path) + .env("XDG_RUNTIME_DIR", &runtime) + .env("XDG_STATE_HOME", w.base.join("state")) + .spawn() + .unwrap(), + ); let sock = runtime.join("grove/grove.sock"); wait_until("daemon up", 10, || { ipc::request(&sock, &json!({"v":1,"cmd":"ping"})).is_ok() }); ipc::request(&sock, &json!({"v":1,"cmd":"pause"})).unwrap(); std::thread::sleep(Duration::from_millis(1500)); // let any in-flight pass finish - let before = cpu_ticks(child.id()); + let before = cpu_ticks(child.0.id()); std::thread::sleep(Duration::from_secs(3)); // well past several fetch intervals - let used = cpu_ticks(child.id()) - before; - child.kill().unwrap(); - child.wait().unwrap(); + let used = cpu_ticks(child.0.id()) - before; + child.0.kill().unwrap(); + child.0.wait().unwrap(); assert!(used < 30, "paused daemon burned {used} ticks of CPU in 3 s"); } diff --git a/crates/grove-gui/src/autostart.rs b/crates/grove-gui/src/autostart.rs index 94082a4..5d2dcbd 100644 --- a/crates/grove-gui/src/autostart.rs +++ b/crates/grove-gui/src/autostart.rs @@ -41,7 +41,8 @@ mod tests { #[test] fn toggle_writes_and_removes_the_desktop_file() { - let d = std::env::temp_dir().join(format!("gg-auto-{}", std::process::id())); + let _tmp = crate::test_tmp::TempDir::new("gg-auto"); + let d = _tmp.path().to_path_buf(); assert!(!is_enabled(&d)); set(&d, true).unwrap(); assert!(is_enabled(&d)); diff --git a/crates/grove-gui/src/bridge.rs b/crates/grove-gui/src/bridge.rs index b41bddd..cb6897c 100644 --- a/crates/grove-gui/src/bridge.rs +++ b/crates/grove-gui/src/bridge.rs @@ -219,7 +219,8 @@ mod tests { #[test] fn migrate_path_must_be_a_clone_directly_under_a_group() { - let base = std::env::temp_dir().join(format!("grove-mig-{}", std::process::id())); + let _tmp = crate::test_tmp::TempDir::new("grove-mig"); + let base = _tmp.path().to_path_buf(); let _ = std::fs::remove_dir_all(&base); std::fs::create_dir_all(base.join("work/proj/sub")).unwrap(); std::fs::create_dir_all(base.join("other/proj")).unwrap(); @@ -248,7 +249,8 @@ mod tests { #[test] fn add_runs_only_for_valid_clone_paths() { use std::os::unix::fs::PermissionsExt; - let base = std::env::temp_dir().join(format!("grove-add-{}", std::process::id())); + let _tmp = crate::test_tmp::TempDir::new("grove-add"); + let base = _tmp.path().to_path_buf(); let _ = std::fs::remove_dir_all(&base); std::fs::create_dir_all(base.join("work/proj")).unwrap(); std::fs::create_dir_all(base.join("elsewhere")).unwrap(); diff --git a/crates/grove-gui/src/instance.rs b/crates/grove-gui/src/instance.rs index f699084..39f00ad 100644 --- a/crates/grove-gui/src/instance.rs +++ b/crates/grove-gui/src/instance.rs @@ -125,17 +125,16 @@ mod tests { use std::os::unix::fs::PermissionsExt; use std::sync::mpsc; - fn tmp_sock(tag: &str) -> PathBuf { - let d = std::env::temp_dir().join(format!("gg-{tag}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&d); // leftovers of an earlier run with the same pid - std::fs::create_dir_all(&d).unwrap(); - std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o700)).unwrap(); - d.join("gui.sock") + fn tmp_sock(tag: &str) -> (crate::test_tmp::TempDir, PathBuf) { + let t = crate::test_tmp::TempDir::new(&format!("gg-{tag}")); + std::fs::set_permissions(t.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); + let p = t.path().join("gui.sock"); + (t, p) } #[test] fn second_launch_asks_first_to_show() { - let p = tmp_sock("show"); + let (_t, p) = tmp_sock("show"); let Role::Primary(l) = acquire(&p, true).unwrap() else { panic!("first must be primary"); }; @@ -151,7 +150,7 @@ mod tests { #[test] fn unresponsive_instance_is_not_evicted() { - let p = tmp_sock("busy"); + let (_t, p) = tmp_sock("busy"); let l = UnixListener::bind(&p).unwrap(); // Accepts but never answers (a primary stuck in startup). let t = std::thread::spawn(move || { @@ -167,7 +166,8 @@ mod tests { #[test] fn private_dir_is_enforced() { - let base = std::env::temp_dir().join(format!("gg-priv-{}", std::process::id())); + let _tmp = crate::test_tmp::TempDir::new("gg-priv"); + let base = _tmp.path().to_path_buf(); let d = base.join("x"); ensure_private_dir(&d).unwrap(); assert_eq!(std::fs::metadata(&d).unwrap().mode() & 0o777, 0o700); @@ -179,7 +179,7 @@ mod tests { #[test] fn stale_socket_is_replaced() { - let p = tmp_sock("stale"); + let (_t, p) = tmp_sock("stale"); drop(UnixListener::bind(&p).unwrap()); // leaves the socket file behind assert!(p.exists()); assert!(matches!(acquire(&p, true).unwrap(), Role::Primary(_))); diff --git a/crates/grove-gui/src/main.rs b/crates/grove-gui/src/main.rs index 5012adc..3aede80 100644 --- a/crates/grove-gui/src/main.rs +++ b/crates/grove-gui/src/main.rs @@ -9,6 +9,9 @@ mod bridge; mod instance; mod log; mod model; +#[cfg(test)] +#[path = "../../../test-support/tmp.rs"] +mod test_tmp; mod tray; use anyhow::{Context, Result}; diff --git a/crates/grove-providers/tests/api.rs b/crates/grove-providers/tests/api.rs index 8ed6369..8df2a7f 100644 --- a/crates/grove-providers/tests/api.rs +++ b/crates/grove-providers/tests/api.rs @@ -1,3 +1,5 @@ +#[path = "../../../test-support/tmp.rs"] +mod tmp; use grove_core::config::ProviderKind; use grove_providers::{Error, GitHub, Gitea, MirrorSpec, NewRepo, Provider, PullMirrorSpec, token}; use std::io::{Read, Write}; @@ -273,15 +275,8 @@ fn github_cannot_pull_mirror() { fn falls_back_to_tea_and_gh_logins() { use grove_core::config::Provider as ProviderCfg; use std::os::unix::fs::PermissionsExt; - let dir = std::env::temp_dir().join(format!( - "grove-clitok-{}-{}", - std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap() - .as_nanos() - )); - std::fs::create_dir_all(&dir).unwrap(); + let tmp = tmp::TempDir::new("clitok"); + let dir = tmp.path().to_path_buf(); // tea's credential helper answers only for its host; gh echoes the host it was asked for. let scripts = [ ( @@ -320,7 +315,6 @@ fn falls_back_to_tea_and_gh_logins() { drop(off); let _off = EnvGuard::set("GROVE_NO_CLI_TOKENS", "1"); assert!(token::resolve(&id, &github).is_err()); - std::fs::remove_dir_all(&dir).unwrap(); } #[test] diff --git a/crates/grove/src/main.rs b/crates/grove/src/main.rs index b07c152..a9883bc 100644 --- a/crates/grove/src/main.rs +++ b/crates/grove/src/main.rs @@ -13,6 +13,9 @@ use std::path::{Path, PathBuf}; use std::time::{SystemTime, UNIX_EPOCH}; mod secrets; +#[cfg(test)] +#[path = "../../../test-support/tmp.rs"] +mod test_tmp; mod workflow; #[derive(Parser)] diff --git a/crates/grove/src/workflow.rs b/crates/grove/src/workflow.rs index c5a8259..5822007 100644 --- a/crates/grove/src/workflow.rs +++ b/crates/grove/src/workflow.rs @@ -763,7 +763,8 @@ mod tests { #[test] fn local_repos_match_by_name_or_origin_ignoring_case() { - let d = std::env::temp_dir().join(format!("grove-local-{}", std::process::id())); + let _tmp = crate::test_tmp::TempDir::new("grove-local"); + let d = _tmp.path().to_path_buf(); let _ = fs::remove_dir_all(&d); // `synapse` (lowercase dir) whose origin is Dasemu/Synapse; `other` with a renamed origin. for (dir, origin) in [ diff --git a/crates/grove/tests/cli.rs b/crates/grove/tests/cli.rs index 0598bd8..1f96063 100644 --- a/crates/grove/tests/cli.rs +++ b/crates/grove/tests/cli.rs @@ -1,12 +1,11 @@ +#[path = "../../../test-support/tmp.rs"] +mod tmp; use std::fs; -use std::path::{Path, PathBuf}; +use std::path::Path; use std::process::{Command, Output}; -fn tmp(tag: &str) -> PathBuf { - let p = std::env::temp_dir().join(format!("grove-cli-{tag}-{}", std::process::id())); - let _ = fs::remove_dir_all(&p); - fs::create_dir_all(&p).unwrap(); - p +fn tmp(tag: &str) -> tmp::TempDir { + tmp::TempDir::new(tag) } fn git(dir: &Path, args: &[&str]) -> String { diff --git a/test-support/tmp.rs b/test-support/tmp.rs new file mode 100644 index 0000000..25519c0 --- /dev/null +++ b/test-support/tmp.rs @@ -0,0 +1,87 @@ +//! Shared RAII temp-dir helper for tests; included with `#[path]` so no extra crate is needed. +//! +//! Creates a unique directory under `std::env::temp_dir()` and removes it recursively on drop, +//! also when the test panics. `/tmp` is tmpfs and has run out of inodes before, so tests must +//! never leave directories behind. +#![allow(dead_code)] + +use std::ops::Deref; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; + +static COUNTER: AtomicU64 = AtomicU64::new(0); + +pub struct TempDir { + path: PathBuf, +} + +impl TempDir { + /// `/grove-test----`, created (with parents). + pub fn new(tag: &str) -> TempDir { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0); + let n = COUNTER.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "grove-test-{tag}-{}-{nanos}-{n}", + std::process::id() + )); + std::fs::create_dir_all(&path).expect("create temp dir"); + TempDir { path } + } + + pub fn path(&self) -> &Path { + &self.path + } +} + +/// Remove `path` recursively, making read-only entries (git objects) writable first. +fn remove_all(path: &Path) { + if std::fs::remove_dir_all(path).is_ok() { + return; + } + fn chmod(p: &Path) { + use std::os::unix::fs::PermissionsExt; + let Ok(meta) = std::fs::symlink_metadata(p) else { + return; + }; + if meta.is_dir() { + let _ = std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o700)); + if let Ok(rd) = std::fs::read_dir(p) { + for e in rd.flatten() { + chmod(&e.path()); + } + } + } else if !meta.file_type().is_symlink() { + let _ = std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o600)); + } + } + chmod(path); + let _ = std::fs::remove_dir_all(path); +} + +impl Drop for TempDir { + fn drop(&mut self) { + remove_all(&self.path); + } +} + +impl Deref for TempDir { + type Target = Path; + fn deref(&self) -> &Path { + &self.path + } +} + +impl AsRef for TempDir { + fn as_ref(&self) -> &Path { + &self.path + } +} + +impl From<&TempDir> for PathBuf { + fn from(t: &TempDir) -> PathBuf { + t.path.clone() + } +}