Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Add nested bare repo documentation and test helpers (#320)
Maximilian Roosf21388acc033
diff --git a/docs/content/config.md b/docs/content/config.mdindex 6f74852a2..eb7190ceb 100644--- a/docs/content/config.md+++ b/docs/content/config.md@@ -70,6 +70,10 @@ worktree-path = ".worktrees/{{ branch | sanitize }}"# Namespaced (useful when multiple repos share a parent directory)# Creates: ~/code/worktrees/myproject/feature-loginworktree-path = "../worktrees/{{ main_worktree }}/{{ branch | sanitize }}"++# Nested bare repo (git clone --bare <url> project/.git)+# Creates: ~/code/project/feature-login (sibling to .git)+worktree-path = "../{{ branch | sanitize }}"```### Command settingsdiff --git a/src/cli.rs b/src/cli.rsindex a5c39f00e..cb992fbd0 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -1217,6 +1217,10 @@ worktree-path = ".worktrees/{{ branch | sanitize }}"# Namespaced (useful when multiple repos share a parent directory)# Creates: ~/code/worktrees/myproject/feature-loginworktree-path = "../worktrees/{{ main_worktree }}/{{ branch | sanitize }}"++# Nested bare repo (git clone --bare <url> project/.git)+# Creates: ~/code/project/feature-login (sibling to .git)+worktree-path = "../{{ branch | sanitize }}"```### Command settingsdiff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex c6b6297b4..d8f3ec8ff 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -204,31 +204,9 @@ pub fn compute_worktree_path(branch: &str,config: &WorktrunkConfig,) -> anyhow::Result<PathBuf> {- let repo_root = repo.worktree_base()?;-- // Default branch lives at repo root (main worktree), not a templated path.- // Exception: bare repos have no main worktree, so all branches use templated paths.- if !repo.is_bare()? && repo.default_branch().is_ok_and(|default| branch == default) {- return Ok(repo_root);- }-- let repo_name = repo_root- .file_name()- .ok_or_else(|| anyhow::anyhow!("Repository path has no filename: {}", repo_root.display()))?- .to_str()- .ok_or_else(|| {- anyhow::anyhow!(- "Repository path contains invalid UTF-8: {}",- repo_root.display()- )- })?;-- let relative_path = config- .format_path(repo_name, branch)- .map_err(|e| anyhow::anyhow!("Failed to format worktree path: {e}"))?;-- // Normalize to resolve ".." from relative paths like "../repo.branch"- Ok(repo_root.join(relative_path).normalize())+ let default_branch = repo.default_branch().unwrap_or_default();+ let is_bare = repo.is_bare()?;+ compute_worktree_path_with(repo, branch, config, &default_branch, is_bare)}/// Check if a worktree is at its expected path based on config template.@@ -246,7 +224,7 @@ fn is_worktree_at_expected_path(config: &WorktrunkConfig,) -> bool {// Compute default_branch and is_bare once, then delegate to the optimized variant- let default_branch = repo.default_branch().unwrap_or_else(|_| String::new());+ let default_branch = repo.default_branch().unwrap_or_default();let is_bare = repo.is_bare().unwrap_or(false);is_worktree_at_expected_path_with(wt, repo, config, &default_branch, is_bare)}diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex 55690c991..da0c4fa60 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -618,6 +618,28 @@ pub fn configure_cli_command(cmd: &mut Command) {}}+/// Configure a git command with isolated environment for testing.+///+/// Sets environment variables for:+/// - Isolated git config (using provided path or /dev/null)+/// - Deterministic commit timestamps+/// - Consistent locale settings+/// - No terminal prompts+///+/// # Arguments+/// * `cmd` - The git Command to configure+/// * `git_config_path` - Path to git config file (use `/dev/null` or `NULL_DEVICE` for none)+pub fn configure_git_cmd(cmd: &mut Command, git_config_path: &Path) {+ cmd.env("GIT_CONFIG_GLOBAL", git_config_path);+ cmd.env("GIT_CONFIG_SYSTEM", NULL_DEVICE);+ cmd.env("GIT_AUTHOR_DATE", "2025-01-01T00:00:00Z");+ cmd.env("GIT_COMMITTER_DATE", "2025-01-01T00:00:00Z");+ cmd.env("LC_ALL", "C");+ cmd.env("LANG", "C");+ cmd.env("SOURCE_DATE_EPOCH", TEST_EPOCH.to_string());+ cmd.env("GIT_TERMINAL_PROMPT", "0");+}+/// Create a temporary file for directive output.////// The shell wrapper sets WORKTRUNK_DIRECTIVE_FILE to a temp file before running wt.@@ -863,16 +885,7 @@ impl TestRepo {/// This sets environment variables only for the specific command,/// ensuring thread-safety and test isolation.pub fn configure_git_cmd(&self, cmd: &mut Command) {- // Use test git config file with advice settings disabled- cmd.env("GIT_CONFIG_GLOBAL", &self.git_config_path);- cmd.env("GIT_CONFIG_SYSTEM", NULL_DEVICE);- cmd.env("GIT_AUTHOR_DATE", "2025-01-01T00:00:00Z");- cmd.env("GIT_COMMITTER_DATE", "2025-01-01T00:00:00Z");- cmd.env("LC_ALL", "C");- cmd.env("LANG", "C");- cmd.env("SOURCE_DATE_EPOCH", TEST_EPOCH.to_string());- // Prevent git from prompting for credentials when running under a TTY- cmd.env("GIT_TERMINAL_PROMPT", "0");+ configure_git_cmd(cmd, &self.git_config_path);}/// Get standard test environment variables as a vectordiff --git a/tests/integration_tests/bare_repository.rs b/tests/integration_tests/bare_repository.rsindex c8f014a51..bfd13fdbf 100644--- a/tests/integration_tests/bare_repository.rs+++ b/tests/integration_tests/bare_repository.rs@@ -1,11 +1,11 @@use crate::common::{- TestRepo, canonicalize, configure_directive_file, directive_file, repo,+ TestRepo, canonicalize, configure_directive_file, configure_git_cmd, directive_file, repo,setup_temp_snapshot_settings, wait_for_file, wt_command,};use insta_cmd::assert_cmd_snapshot;use rstest::rstest;use std::fs;-use std::path::PathBuf;+use std::path::{Path, PathBuf};use std::process::Command;use std::time::Duration;@@ -663,6 +663,258 @@ fn test_bare_repo_slashed_branch_with_sanitize() {);}+/// Helper to create a nested bare repository test setup (project/.git pattern)+///+/// This tests the pattern from GitHub issue #313 where users clone with:+/// `git clone --bare <url> project/.git`+struct NestedBareRepoTest {+ temp_dir: tempfile::TempDir,+ /// Path to the parent directory (project/)+ project_path: PathBuf,+ /// Path to the bare repo (project/.git/)+ bare_repo_path: PathBuf,+ test_config_path: PathBuf,+ git_config_path: PathBuf,+}++impl NestedBareRepoTest {+ fn new() -> Self {+ let temp_dir = tempfile::TempDir::new().unwrap();+ // Create project directory+ let project_path = temp_dir.path().join("project");+ fs::create_dir(&project_path).unwrap();++ // Bare repo inside project directory as .git+ let bare_repo_path = project_path.join(".git");+ let test_config_path = temp_dir.path().join("test-config.toml");+ let git_config_path = temp_dir.path().join("test-gitconfig");++ // Write git config with user settings (like TestRepo)+ fs::write(+ &git_config_path,+ "[user]\n\tname = Test User\n\temail = [email protected]\n\+ [advice]\n\tmergeConflict = false\n\tresolveConflict = false\n\+ [init]\n\tdefaultBranch = main\n",+ )+ .unwrap();++ let mut test = Self {+ temp_dir,+ project_path,+ bare_repo_path,+ test_config_path,+ git_config_path,+ };++ // Create bare repository at project/.git+ let mut cmd = Command::new("git");+ cmd.args(["init", "--bare", "--initial-branch", "main"])+ .arg(&test.bare_repo_path);+ configure_git_cmd(&mut cmd, &test.git_config_path);+ let output = cmd.output().unwrap();++ if !output.status.success() {+ panic!(+ "Failed to init nested bare repo:\nstdout: {}\nstderr: {}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ }++ // Canonicalize paths+ test.project_path = canonicalize(&test.project_path).unwrap();+ test.bare_repo_path = canonicalize(&test.bare_repo_path).unwrap();++ // Write config with template for worktrees as siblings to .git+ // For nested bare repos (project/.git), we use "../{{ branch }}" to create+ // worktrees at project/main, project/feature (siblings to .git)+ fs::write(+ &test.test_config_path,+ "worktree-path = \"../{{ branch }}\"\n",+ )+ .unwrap();++ test+ }++ fn project_path(&self) -> &PathBuf {+ &self.project_path+ }++ fn bare_repo_path(&self) -> &PathBuf {+ &self.bare_repo_path+ }++ fn temp_path(&self) -> &std::path::Path {+ self.temp_dir.path()+ }++ /// Configure a wt command with test environment+ fn configure_wt_cmd(&self, cmd: &mut Command) {+ configure_git_cmd(cmd, &self.git_config_path);+ cmd.env("WORKTRUNK_CONFIG_PATH", &self.test_config_path)+ .env_remove("NO_COLOR")+ .env_remove("CLICOLOR_FORCE");+ }++ /// Get a git command configured for this test environment+ fn git_command(&self, dir: &Path) -> Command {+ let mut cmd = Command::new("git");+ cmd.current_dir(dir);+ configure_git_cmd(&mut cmd, &self.git_config_path);+ cmd+ }++ /// Create a commit in a worktree+ fn commit(&self, worktree: &Path, message: &str) {+ fs::write(worktree.join("file.txt"), message).unwrap();+ self.git_command(worktree)+ .args(["add", "."])+ .output()+ .unwrap();+ self.git_command(worktree)+ .args(["commit", "-m", message])+ .output()+ .unwrap();+ }+}++/// Test that nested bare repos (project/.git pattern) create worktrees in project/+/// instead of project/.git/ (GitHub issue #313)+#[test]+fn test_nested_bare_repo_worktree_path() {+ let test = NestedBareRepoTest::new();++ // Create first worktree using wt switch --create+ let (directive_path, _guard) = directive_file();+ let mut cmd = wt_command();+ test.configure_wt_cmd(&mut cmd);+ configure_directive_file(&mut cmd, &directive_path);+ cmd.args(["switch", "--create", "main"])+ .current_dir(test.bare_repo_path());++ let output = cmd.output().unwrap();++ if !output.status.success() {+ panic!(+ "wt switch --create main failed:\nstdout: {}\nstderr: {}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ }++ // CRITICAL: Worktree should be at project/main, NOT project/.git/main+ let expected_path = test.project_path().join("main");+ let wrong_path = test.bare_repo_path().join("main");++ assert!(+ expected_path.exists(),+ "Expected worktree at {:?} (sibling to .git)",+ expected_path+ );+ assert!(+ !wrong_path.exists(),+ "Worktree should NOT be inside .git directory at {:?}",+ wrong_path+ );+}++/// Test that nested bare repos work with the full workflow (create, list, remove)+#[test]+fn test_nested_bare_repo_full_workflow() {+ let test = NestedBareRepoTest::new();++ // Create main worktree+ let (directive_path, _guard) = directive_file();+ let mut cmd = wt_command();+ test.configure_wt_cmd(&mut cmd);+ configure_directive_file(&mut cmd, &directive_path);+ cmd.args(["switch", "--create", "main"])+ .current_dir(test.bare_repo_path());+ cmd.output().unwrap();++ let main_worktree = test.project_path().join("main");+ assert!(main_worktree.exists(), "Main worktree should exist");+ test.commit(&main_worktree, "Initial");++ // Create feature worktree+ let (directive_path, _guard) = directive_file();+ let mut cmd = wt_command();+ test.configure_wt_cmd(&mut cmd);+ configure_directive_file(&mut cmd, &directive_path);+ cmd.args(["switch", "--create", "feature"])+ .current_dir(&main_worktree);+ cmd.output().unwrap();++ // Feature worktree should be at project/feature+ let feature_worktree = test.project_path().join("feature");+ assert!(+ feature_worktree.exists(),+ "Feature worktree should be at project/feature"+ );++ // List should show both worktrees+ let mut cmd = wt_command();+ test.configure_wt_cmd(&mut cmd);+ cmd.arg("list").current_dir(&main_worktree);+ let output = cmd.output().unwrap();+ let stdout = String::from_utf8_lossy(&output.stdout);++ assert!(stdout.contains("main"), "Should list main worktree");+ assert!(stdout.contains("feature"), "Should list feature worktree");++ // Remove feature worktree+ let (directive_path, _guard) = directive_file();+ let mut cmd = wt_command();+ test.configure_wt_cmd(&mut cmd);+ configure_directive_file(&mut cmd, &directive_path);+ cmd.args(["remove", "feature", "--no-background"])+ .current_dir(&main_worktree);+ cmd.output().unwrap();++ assert!(+ !feature_worktree.exists(),+ "Feature worktree should be removed"+ );+ assert!(main_worktree.exists(), "Main worktree should still exist");+}++/// Test snapshot for nested bare repo list output+#[test]+fn test_nested_bare_repo_list_snapshot() {+ let test = NestedBareRepoTest::new();++ // Create main worktree+ let (directive_path, _guard) = directive_file();+ let mut cmd = wt_command();+ test.configure_wt_cmd(&mut cmd);+ configure_directive_file(&mut cmd, &directive_path);+ cmd.args(["switch", "--create", "main"])+ .current_dir(test.bare_repo_path());+ cmd.output().unwrap();++ let main_worktree = test.project_path().join("main");+ test.commit(&main_worktree, "Initial");++ // Create feature worktree+ let (directive_path, _guard) = directive_file();+ let mut cmd = wt_command();+ test.configure_wt_cmd(&mut cmd);+ configure_directive_file(&mut cmd, &directive_path);+ cmd.args(["switch", "--create", "feature"])+ .current_dir(&main_worktree);+ cmd.output().unwrap();++ // Take snapshot of list output+ let settings = setup_temp_snapshot_settings(test.temp_path());+ settings.bind(|| {+ let mut cmd = wt_command();+ test.configure_wt_cmd(&mut cmd);+ cmd.arg("list").current_dir(&main_worktree);+ assert_cmd_snapshot!(cmd);+ });+}+#[test]fn test_bare_repo_bootstrap_first_worktree() {// Test that we can create the first worktree in a bare repo using wt switch --creatediff --git a/tests/snapshots/integration__integration_tests__bare_repository__nested_bare_repo_list_snapshot.snap b/tests/snapshots/integration__integration_tests__bare_repository__nested_bare_repo_list_snapshot.snapnew file mode 100644index 000000000..3787955a5--- /dev/null+++ b/tests/snapshots/integration__integration_tests__bare_repository__nested_bare_repo_list_snapshot.snap@@ -0,0 +1,32 @@+---+source: tests/integration_tests/bare_repository.rs+info:+ program: wt+ args:+ - list+ env:+ CLICOLOR_FORCE: ""+ COLUMNS: "150"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ LANG: C+ LC_ALL: C+ NO_COLOR: ""+ RUST_LOG: warn+ SOURCE_DATE_EPOCH: "1735776000"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+---+success: true+exit_code: 0+----- stdout -----+ [1mBranch[0m [1mStatus[0m [1mHEAD±[0m [1mmain↕[0m [1mPath[0m [1mRemote⇅[0m [1mCommit[0m [1mAge[0m [1mMessage[0m+@ main [2m^[22m . [2ma6c13b13[0m [2m1d[0m [2mInitial[0m++ [2mfeature[0m [2m_[22m [2m../feature[0m [2ma6c13b13[0m [2m1d[0m [2mInitial[0m++[2m○[22m [2mShowing 2 worktrees[0m++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snapindex 8aacd7f7c..eef9c303e 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap@@ -95,6 +95,10 @@ Controls where new worktrees are created. The template is relative to the reposi[2m# Namespaced (useful when multiple repos share a parent directory)[2m# Creates: ~/code/worktrees/myproject/feature-login[2mworktree-path = "../worktrees/{{ main_worktree }}/{{ branch | sanitize }}"+ [2m+ [2m# Nested bare repo (git clone --bare <url> project/.git)+ [2m# Creates: ~/code/project/feature-login (sibling to .git)+ [2mworktree-path = "../{{ branch | sanitize }}"[1mCommand settings