Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: add `TestRepo::at(path)` and consolidate test repo creation (#2005)
Maximilian Roosc3b0913a7d64
diff --git a/src/commands/picker/summary.rs b/src/commands/picker/summary.rsindex 3f005d180..32815d95b 100644--- a/src/commands/picker/summary.rs+++ b/src/commands/picker/summary.rs@@ -58,7 +58,7 @@ mod tests {use super::*;use crate::commands::list::model::{ItemKind, WorktreeData};use std::fs;- use worktrunk::testing::{TestRepo, set_test_identity};+ use worktrunk::testing::TestRepo;/// Create a minimal temp git repo (for cache-only tests that don't need branches).fn temp_repo() -> (TestRepo, Repository) {@@ -377,36 +377,24 @@ mod tests {// infer_default_branch_locally() won't detect (it checks "main",// "master", "develop", "trunk"). This ensures default_branch() returns// None, exercising the code path where branch diff is skipped.- let dir = tempfile::tempdir().unwrap();- worktrunk::shell_exec::Cmd::new("git")- .args(["init", "--initial-branch=init-branch"])- .current_dir(dir.path())- .run()- .unwrap();- let setup_repo = Repository::at(dir.path()).unwrap();- set_test_identity(&setup_repo);- fs::write(dir.path().join("README.md"), "# Project\n").unwrap();- setup_repo.run_command(&["add", "README.md"]).unwrap();- setup_repo- .run_command(&["commit", "-m", "initial commit"])- .unwrap();- setup_repo- .run_command(&["checkout", "-b", "feature"])- .unwrap();- setup_repo- .run_command(&["commit", "--allow-empty", "-m", "feature commit"])- .unwrap();+ let t = TestRepo::new();+ t.commit("initial commit");+ // Rename to exotic branch name so infer_default_branch_locally() returns None+ t.run_git(&["branch", "-m", "main", "init-branch"]);+ t.run_git(&["checkout", "-b", "feature"]);+ t.run_git(&["commit", "--allow-empty", "-m", "feature commit"]);// Add uncommitted changes- fs::write(dir.path().join("wip.txt"), "work in progress\n").unwrap();- setup_repo.run_command(&["add", "wip.txt"]).unwrap();+ fs::write(t.path().join("wip.txt"), "work in progress\n").unwrap();+ t.repo.run_command(&["add", "wip.txt"]).unwrap();- let head = setup_repo+ let head = t+ .repo.run_command(&["rev-parse", "HEAD"]).unwrap().trim().to_string();- let repo = Repository::at(dir.path()).unwrap();+ let repo = Repository::at(t.path()).unwrap();// Verify default_branch() actually returns None with these branch namesassert!(@@ -414,7 +402,7 @@ mod tests {"expected no default branch with exotic branch names");- let result = compute_combined_diff("feature", &head, Some(dir.path()), &repo);+ let result = compute_combined_diff("feature", &head, Some(t.path()), &repo);assert!(result.is_some(),"should include working tree diff even without default branch"diff --git a/src/git/recover.rs b/src/git/recover.rsindex 7ad4e4793..f8bf0667b 100644--- a/src/git/recover.rs+++ b/src/git/recover.rs@@ -208,17 +208,9 @@ fn paths_match(worktree_path: &Path, deleted_path: &Path) -> bool {mod tests {use super::*;use crate::shell_exec::Cmd;- use crate::testing::{TestRepo, set_test_identity};+ use crate::testing::TestRepo;use ansi_str::AnsiStr;- fn git_init(path: &Path) {- Cmd::new("git")- .args(["init", "--quiet", "-b", "main"])- .current_dir(path)- .run()- .unwrap();- }-#[test]fn test_try_repo_at_rejects_git_file() {let tmp = tempfile::tempdir().unwrap();@@ -229,9 +221,8 @@ mod tests {#[test]fn test_try_repo_at_accepts_git_dir() {- let tmp = tempfile::tempdir().unwrap();- git_init(tmp.path());- assert!(try_repo_at(tmp.path()).is_some());+ let test = TestRepo::new();+ assert!(try_repo_at(test.path()).is_some());}#[test]@@ -277,24 +268,18 @@ mod tests {#[test]fn test_was_worktree_of_finds_existing_worktree() {let tmp = tempfile::tempdir().unwrap();- // Canonicalize to handle symlinks (e.g., /tmp -> /private/tmp on macOS)let base = dunce::canonicalize(tmp.path()).unwrap();- let repo_dir = base.join("repo");- std::fs::create_dir(&repo_dir).unwrap();- git_init(&repo_dir);- let repo = Repository::at(&repo_dir).unwrap();- set_test_identity(&repo);- // Create an initial commit so worktree add works- repo.run_command(&["commit", "--allow-empty", "-m", "init"])- .unwrap();+ let test = TestRepo::at(&base.join("repo"));+ test.commit("init");// Add a linked worktreelet wt_path = base.join("feature-wt");let wt_str = wt_path.to_string_lossy();- repo.run_command(&["worktree", "add", &wt_str, "-b", "feature"])+ test.repo+ .run_command(&["worktree", "add", &wt_str, "-b", "feature"]).unwrap();- assert!(was_worktree_of(&repo, &wt_path));+ assert!(was_worktree_of(&test.repo, &wt_path));}#[test]@@ -318,18 +303,14 @@ mod tests {fn test_recover_from_path_finds_deleted_worktree() {let tmp = tempfile::tempdir().unwrap();let base = dunce::canonicalize(tmp.path()).unwrap();- let repo_dir = base.join("repo");- std::fs::create_dir(&repo_dir).unwrap();- git_init(&repo_dir);- let repo = Repository::at(&repo_dir).unwrap();- set_test_identity(&repo);- repo.run_command(&["commit", "--allow-empty", "-m", "init"])- .unwrap();+ let test = TestRepo::at(&base.join("repo"));+ test.commit("init");// Add a linked worktreelet wt_path = base.join("feature-wt");let wt_str = wt_path.to_string_lossy();- repo.run_command(&["worktree", "add", &wt_str, "-b", "feature"])+ test.repo+ .run_command(&["worktree", "add", &wt_str, "-b", "feature"]).unwrap();// Delete the worktree directory (simulating external removal)@@ -343,13 +324,8 @@ mod tests {fn test_recover_from_path_returns_none_for_unrelated_path() {let tmp = tempfile::tempdir().unwrap();let base = dunce::canonicalize(tmp.path()).unwrap();- let repo_dir = base.join("repo");- std::fs::create_dir(&repo_dir).unwrap();- git_init(&repo_dir);- let repo = Repository::at(&repo_dir).unwrap();- set_test_identity(&repo);- repo.run_command(&["commit", "--allow-empty", "-m", "init"])- .unwrap();+ let test = TestRepo::at(&base.join("repo"));+ test.commit("init");// Try to recover from a path that was never a worktreelet unrelated = base.join("not-a-worktree");@@ -362,29 +338,21 @@ mod tests {let base = dunce::canonicalize(tmp.path()).unwrap();// Create two sibling repos- let repo_a = base.join("alpha");- let repo_b = base.join("beta");- std::fs::create_dir(&repo_a).unwrap();- std::fs::create_dir(&repo_b).unwrap();- git_init(&repo_a);- git_init(&repo_b);- let repo_a_handle = Repository::at(&repo_a).unwrap();- let repo_b_handle = Repository::at(&repo_b).unwrap();- for repo in [&repo_a_handle, &repo_b_handle] {- set_test_identity(repo);- repo.run_command(&["commit", "--allow-empty", "-m", "init"])- .unwrap();- }+ let alpha = TestRepo::at(&base.join("alpha"));+ let beta = TestRepo::at(&base.join("beta"));+ alpha.commit("init");+ beta.commit("init");// Add worktrees for both repos as siblingslet wt_a = base.join("alpha.feature");let wt_b = base.join("beta.feature");let wt_a_str = wt_a.to_string_lossy();let wt_b_str = wt_b.to_string_lossy();- repo_a_handle+ alpha+ .repo.run_command(&["worktree", "add", &wt_a_str, "-b", "feature"]).unwrap();- repo_b_handle+ beta.repo.run_command(&["worktree", "add", &wt_b_str, "-b", "feature"]).unwrap();@@ -395,7 +363,7 @@ mod tests {let recovered = recover_from_path(&wt_b).unwrap();assert_eq!(dunce::canonicalize(recovered.repo_path().unwrap()).unwrap(),- repo_b+ base.join("beta"));}@@ -404,19 +372,15 @@ mod tests {let tmp = tempfile::tempdir().unwrap();let base = dunce::canonicalize(tmp.path()).unwrap();- let repo_dir = base.join("myrepo");- std::fs::create_dir(&repo_dir).unwrap();- git_init(&repo_dir);- let repo = Repository::at(&repo_dir).unwrap();- set_test_identity(&repo);- repo.run_command(&["commit", "--allow-empty", "-m", "init"])- .unwrap();+ let test = TestRepo::at(&base.join("myrepo"));+ test.commit("init");// Add a worktree nested under the repo- let wt_path = repo_dir.join(".worktrees").join("feature");+ let wt_path = test.path().join(".worktrees").join("feature");std::fs::create_dir_all(wt_path.parent().unwrap()).unwrap();let wt_str = wt_path.to_string_lossy();- repo.run_command(&["worktree", "add", &wt_str, "-b", "feature"])+ test.repo+ .run_command(&["worktree", "add", &wt_str, "-b", "feature"]).unwrap();// Delete the worktree@@ -430,17 +394,13 @@ mod tests {fn test_recover_from_path_deep_pwd() {let tmp = tempfile::tempdir().unwrap();let base = dunce::canonicalize(tmp.path()).unwrap();- let repo_dir = base.join("repo");- std::fs::create_dir(&repo_dir).unwrap();- git_init(&repo_dir);- let repo = Repository::at(&repo_dir).unwrap();- set_test_identity(&repo);- repo.run_command(&["commit", "--allow-empty", "-m", "init"])- .unwrap();+ let test = TestRepo::at(&base.join("repo"));+ test.commit("init");let wt_path = base.join("feature-wt");let wt_str = wt_path.to_string_lossy();- repo.run_command(&["worktree", "add", &wt_str, "-b", "feature"])+ test.repo+ .run_command(&["worktree", "add", &wt_str, "-b", "feature"]).unwrap();// Delete the worktreediff --git a/src/testing/mod.rs b/src/testing/mod.rsindex 38409b67f..58ece6e55 100644--- a/src/testing/mod.rs+++ b/src/testing/mod.rs@@ -14,6 +14,8 @@//!//! - [`TestRepo::new()`] — lightweight: `git init` + identity. For unit tests.//! - [`TestRepo::with_initial_commit()`] — lightweight + one commit.+//! - [`TestRepo::at(path)`](TestRepo::at) — repo at a caller-specified path.+//! For tests needing multiple repos in a shared directory.//! - [`TestRepo::standard()`] — copies pre-built fixture with remote + worktrees.//! For integration tests (used by the `repo()` rstest fixture).//! - [`TestRepo::empty()`] — `git init` with no commits, no branches.@@ -565,16 +567,6 @@ pub fn set_xdg_config_path(cmd: &mut Command, home: &Path) {);}-/// Set git user identity on a repository.-///-/// Use this for tests that manage their own repo creation (not via-/// [`TestRepo`]) and need identity configured for commits.-pub fn set_test_identity(repo: &Repository) {- repo.run_command(&["config", "user.name", "Test"]).unwrap();- repo.run_command(&["config", "user.email", "[email protected]"])- .unwrap();-}-/// Check that a git command succeeded, panicking with diagnostics if not.////// Use this after `git_command().run()` to ensure the command succeeded.@@ -708,6 +700,51 @@ impl TestRepo {repo}+ /// Create a repo at a caller-specified path with identity configured.+ ///+ /// Unlike [`new()`](Self::new), this does not own the repo's parent+ /// directory — the caller manages its lifetime (e.g., via their own+ /// `TempDir`). A separate internal tempdir holds config files.+ ///+ /// Use for tests that need multiple repos in a shared directory+ /// (e.g., sibling worktrees, multi-repo recovery tests).+ pub fn at(path: &Path) -> Self {+ std::fs::create_dir_all(path).unwrap();++ let config_dir = TempDir::new().unwrap();+ let test_config_path = config_dir.path().join("test-config.toml");+ let test_approvals_path = config_dir.path().join("test-approvals.toml");+ let git_config_path = config_dir.path().join("test-gitconfig");+ write_test_gitconfig(&git_config_path);++ configure_git_env(Cmd::new("git"), &git_config_path)+ .args(["init", "-b", "main", "--quiet"])+ .current_dir(path)+ .run()+ .unwrap();++ let root = canonicalize(path).unwrap();+ let repo = Repository::at(&root).unwrap();+ repo.run_command(&["config", "user.name", "Test User"])+ .unwrap();+ repo.run_command(&["config", "user.email", "[email protected]"])+ .unwrap();++ Self {+ temp_dir: config_dir,+ root: root.clone(),+ repo,+ worktrees: HashMap::new(),+ remote: None,+ test_config_path,+ test_approvals_path,+ git_config_path,+ mock_bin_path: None,+ claude_installed: false,+ opencode_installed: false,+ }+ }+/// Create an empty test repository (no commits, no branches).////// Use this for tests that specifically need to test behavior in andiff --git a/tests/integration_tests/repository.rs b/tests/integration_tests/repository.rsindex 501ce45f1..8e074bc68 100644--- a/tests/integration_tests/repository.rs+++ b/tests/integration_tests/repository.rs@@ -3,7 +3,6 @@use std::fs;use worktrunk::git::Repository;-use worktrunk::shell_exec::Cmd;use crate::common::TestRepo;@@ -664,86 +663,33 @@ fn test_merge_integration_probe_already_integrated() {/// falling back to parent of git_common_dir for normal repos.#[test]fn test_repo_path_in_submodule() {- use tempfile::TempDir;-- // Create parent repository- let parent_temp = TempDir::new().unwrap();- let parent_path = parent_temp.path().join("parent");- fs::create_dir(&parent_path).unwrap();-- // Initialize parent repo with git config- Cmd::new("git")- .args(["init", "-q"])- .current_dir(&parent_path)- .env("GIT_CONFIG_SYSTEM", "/dev/null")- .env("GIT_CONFIG_GLOBAL", "/dev/null")- .run()- .unwrap();+ // Create parent and submodule-origin repos+ let parent = TestRepo::new();+ fs::write(parent.path().join("README.md"), "# Parent").unwrap();+ parent.run_git(&["add", "."]);+ parent.run_git(&["commit", "-m", "Initial commit"]);- // Configure git user for commits- let parent_repo = Repository::at(&parent_path).unwrap();- parent_repo- .run_command(&["config", "user.email", "[email protected]"])- .unwrap();- parent_repo- .run_command(&["config", "user.name", "Test User"])- .unwrap();-- // Create initial commit in parent- fs::write(parent_path.join("README.md"), "# Parent").unwrap();- parent_repo.run_command(&["add", "."]).unwrap();- parent_repo- .run_command(&["commit", "-m", "Initial commit"])- .unwrap();-- // Create submodule repository (as a separate repo first)- let sub_temp = TempDir::new().unwrap();- let sub_origin_path = sub_temp.path().join("submodule-origin");- fs::create_dir(&sub_origin_path).unwrap();-- Cmd::new("git")- .args(["init", "-q"])- .current_dir(&sub_origin_path)- .env("GIT_CONFIG_SYSTEM", "/dev/null")- .env("GIT_CONFIG_GLOBAL", "/dev/null")- .run()- .unwrap();-- // Configure git user for submodule- let sub_repo = Repository::at(&sub_origin_path).unwrap();- sub_repo- .run_command(&["config", "user.email", "[email protected]"])- .unwrap();- sub_repo- .run_command(&["config", "user.name", "Test User"])- .unwrap();-- // Create initial commit in submodule origin- fs::write(sub_origin_path.join("README.md"), "# Submodule").unwrap();- sub_repo.run_command(&["add", "."]).unwrap();- sub_repo- .run_command(&["commit", "-m", "Submodule initial commit"])- .unwrap();+ let sub_origin = TestRepo::new();+ fs::write(sub_origin.path().join("README.md"), "# Submodule").unwrap();+ sub_origin.run_git(&["add", "."]);+ sub_origin.run_git(&["commit", "-m", "Submodule initial commit"]);// Add submodule to parent (using local path directly, with file transport allowed)- parent_repo+ parent+ .repo.run_command(&["-c","protocol.file.allow=always","submodule","add",- sub_origin_path.to_str().unwrap(),+ sub_origin.path().to_str().unwrap(),"sub",]).unwrap();-- // Commit the submodule addition- parent_repo- .run_command(&["commit", "-m", "Add submodule"])- .unwrap();+ parent.run_git(&["commit", "-m", "Add submodule"]);// Now test: create Repository from inside the submodule- let submodule_path = parent_path.join("sub");+ let submodule_path = parent.path().join("sub");assert!(submodule_path.exists(),"Submodule path should exist: {:?}",