Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix: `wt step copy-ignored` fails in bare repository setups (#606)

Maximilian Roosbf13fd502c8c
diff --git a/.claude/rules/caching-strategy.md b/.claude/rules/caching-strategy.md
index 3986f1c82..b34125451 100644
--- a/.claude/rules/caching-strategy.md
+++ b/.claude/rules/caching-strategy.md
@@ -25,7 +25,7 @@ shares the cache — all clones see the same cached values.
- `git_common_dir` — computed at construction, stored on struct
- `worktree_root()` — per-worktree, keyed by path
-- `worktree_base()` — derived from git_common_dir and is_bare
+- `repo_path()` — derived from git_common_dir and is_bare
- `is_bare()` — git config, doesn't change
- `current_branch()` — per-worktree, keyed by path
- `project_identifier()` — derived from remote URL
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index faf80ea9b..f3d700182 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -87,12 +87,12 @@ pub fn build_hook_context(
map.insert("repo_root".into(), repo_path);
map.insert("worktree".into(), worktree);
- // Default branch and main worktree path
+ // Default branch and its worktree path
if let Some(default_branch) = ctx.repo.default_branch() {
- map.insert("default_branch".into(), default_branch.clone());
+ map.insert("default_branch".into(), default_branch);
- // main_worktree_path: path to the worktree on the default branch
- if let Ok(Some(path)) = ctx.repo.worktree_for_branch(&default_branch) {
+ // main_worktree_path: path to the worktree with the default branch checked out
+ if let Ok(Some(path)) = ctx.repo.default_branch_worktree() {
map.insert(
"main_worktree_path".into(),
to_posix_path(&path.to_string_lossy()),
diff --git a/src/commands/context.rs b/src/commands/context.rs
index 10a2c4559..75b22f6a4 100644
--- a/src/commands/context.rs
+++ b/src/commands/context.rs
@@ -35,7 +35,7 @@ impl CommandEnv {
let branch = repo.require_current_branch(action)?;
let config = WorktrunkConfig::load().context("Failed to load config")?;
let repo_root = repo
- .worktree_base()
+ .repo_path()
.context("Failed to determine repository root")?;
Ok(Self {
@@ -61,7 +61,7 @@ impl CommandEnv {
.context("Failed to determine current branch")?;
let config = WorktrunkConfig::load().context("Failed to load config")?;
let repo_root = repo
- .worktree_base()
+ .repo_path()
.context("Failed to determine repository root")?;
Ok(Self {
diff --git a/src/commands/for_each.rs b/src/commands/for_each.rs
index d978ae6ac..2a0cc1523 100644
--- a/src/commands/for_each.rs
+++ b/src/commands/for_each.rs
@@ -61,7 +61,7 @@ pub fn step_for_each(args: Vec<String>) -> anyhow::Result<()> {
let command_template = args.join(" ");
// Get repo root for context
- let repo_root = repo.worktree_base()?;
+ let repo_root = repo.repo_path()?;
for wt in &worktrees {
let display_name = worktree_display_name(wt, &repo, &config);
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rs
index 5aa13309f..33cae8377 100644
--- a/src/commands/list/collect.rs
+++ b/src/commands/list/collect.rs
@@ -746,7 +746,7 @@ pub fn collect(
let _ = default_branch_cell.set(repo.default_branch());
});
s.spawn(|_| {
- // Populate is_bare cache (value used later via worktree_base)
+ // Populate is_bare cache (value used later via repo_path)
let _ = repo.is_bare();
});
s.spawn(|_| {
diff --git a/src/commands/select.rs b/src/commands/select.rs
index 437534fad..fea6c90e0 100644
--- a/src/commands/select.rs
+++ b/src/commands/select.rs
@@ -718,7 +718,7 @@ fn batch_fetch_stats(repo: &Repository, hashes: &[String]) -> HashMap<String, (u
let stdin_data = hashes.iter().map(|h| format!("{h}\n")).collect::<String>();
let Ok(output) = Cmd::new("git")
.args(["diff-tree", "--numstat", "-r", "--root", "--stdin"])
- .current_dir(repo.worktree_base().unwrap_or_else(|_| ".".into()))
+ .current_dir(repo.repo_path().unwrap_or_else(|_| ".".into()))
.stdin_bytes(stdin_data)
.run()
else {
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index 103d13c37..32f133946 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -442,18 +442,18 @@ pub fn step_copy_ignored(
(path, branch.to_string())
}
None => {
- // Default source is the default branch's worktree.
- // For bare repos, worktree_base() returns the bare directory (which has no
- // working tree for git ls-files). We need the actual worktree path.
- let default_branch = repo
- .default_branch()
- .ok_or_else(|| anyhow::anyhow!("Cannot determine default branch"))?;
- let path = repo.worktree_for_branch(&default_branch)?.ok_or_else(|| {
- worktrunk::git::GitError::WorktreeNotFound {
- branch: default_branch.clone(),
- }
+ // Default source is the primary worktree (main worktree for normal repos,
+ // default branch worktree for bare repos).
+ let path = repo.primary_worktree()?.ok_or_else(|| {
+ anyhow::anyhow!(
+ "No primary worktree found (bare repo with no default branch worktree)"
+ )
})?;
- (path, default_branch)
+ let context = path
+ .file_name()
+ .map(|n| n.to_string_lossy().into_owned())
+ .unwrap_or_default();
+ (path, context)
}
};
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index d0029e429..24e3b1d6f 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -198,7 +198,7 @@ pub fn compute_worktree_path(
branch: &str,
config: &WorktrunkConfig,
) -> anyhow::Result<PathBuf> {
- let repo_root = repo.worktree_base()?;
+ let repo_root = repo.repo_path()?;
let default_branch = repo.default_branch().unwrap_or_default();
let is_bare = repo.is_bare()?;
@@ -759,7 +759,7 @@ pub fn execute_switch(
// Execute post-create commands
if !no_verify {
- let repo_root = repo.worktree_base()?;
+ let repo_root = repo.repo_path()?;
let ctx = CommandContext::new(
repo,
config,
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index b122ceecd..667df8980 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -76,8 +76,8 @@ pub(super) struct RepoCache {
pub(super) primary_remote_url: OnceCell<Option<String>>,
/// Project identifier derived from remote URL
pub(super) project_identifier: OnceCell<String>,
- /// Base path for worktrees (repo root for normal repos, bare repo path for bare)
- pub(super) worktree_base: OnceCell<PathBuf>,
+ /// Repository root path (main worktree for normal repos, bare directory for bare repos)
+ pub(super) repo_path: OnceCell<PathBuf>,
/// Project config (loaded from .config/wt.toml in main worktree)
pub(super) project_config: OnceCell<Option<ProjectConfig>>,
/// Merge-base cache: (commit1, commit2) -> merge_base_sha (None = no common ancestor)
@@ -299,16 +299,19 @@ impl Repository {
self.git_common_dir().join("wt-logs")
}
- /// Get the base directory where worktrees are created relative to.
+ /// The repository root path.
///
- /// For normal repositories: the parent of .git (the repo root).
+ /// For normal repositories: the main worktree directory (parent of .git).
/// For bare repositories: the bare repository directory itself.
///
- /// This is the path that should be used when constructing worktree paths.
+ /// This is the base for template expansion (`{{ repo }}`, `{{ repo_path }}`).
+ /// NOT necessarily where the default branch is checked out — use
+ /// `default_branch_worktree()` for that.
+ ///
/// Result is cached in the repository's shared cache (same for all clones).
- pub fn worktree_base(&self) -> anyhow::Result<PathBuf> {
+ pub fn repo_path(&self) -> anyhow::Result<PathBuf> {
self.cache
- .worktree_base
+ .repo_path
.get_or_try_init(|| {
let git_common_dir =
canonicalize(self.git_common_dir()).context("Failed to canonicalize path")?;
diff --git a/src/git/repository/remotes.rs b/src/git/repository/remotes.rs
index 337bbaac8..918b018df 100644
--- a/src/git/repository/remotes.rs
+++ b/src/git/repository/remotes.rs
@@ -110,7 +110,7 @@ impl Repository {
}
// Fall back to repository name (use worktree base for consistency across all worktrees)
- let repo_root = self.worktree_base()?;
+ let repo_root = self.repo_path()?;
let repo_name = repo_root
.file_name()
.and_then(|name| name.to_str())
diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rs
index 064b3ecd8..a6c4dd52a 100644
--- a/src/git/repository/worktrees.rs
+++ b/src/git/repository/worktrees.rs
@@ -47,6 +47,40 @@ impl Repository {
.map(|wt| wt.path.clone()))
}
+ /// The worktree with the default branch checked out, if one exists.
+ ///
+ /// Returns `None` if no worktree has the default branch (e.g., user
+ /// switched all worktrees to feature branches, or the default branch
+ /// cannot be determined).
+ ///
+ /// This is distinct from `repo_path()` which returns the repository root.
+ /// For normal repos where the main worktree has the default branch,
+ /// these are the same. They differ when:
+ /// - The main worktree is switched to a different branch
+ /// - The repo is bare (no main worktree exists)
+ ///
+ /// For template var `{{ main_worktree_path }}`.
+ pub fn default_branch_worktree(&self) -> anyhow::Result<Option<PathBuf>> {
+ let Some(branch) = self.default_branch() else {
+ return Ok(None);
+ };
+ self.worktree_for_branch(&branch)
+ }
+
+ /// The primary worktree — where established files (ignored files, configs) typically live.
+ ///
+ /// - Normal repos: the main worktree (repo root) — this is where you cloned and set things up
+ /// - Bare repos: the default branch's worktree — no main worktree exists
+ ///
+ /// Returns `None` for bare repos when no worktree has the default branch.
+ pub fn primary_worktree(&self) -> anyhow::Result<Option<PathBuf>> {
+ if self.is_bare()? {
+ self.default_branch_worktree()
+ } else {
+ Ok(Some(self.repo_path()?))
+ }
+ }
+
/// Find the worktree at a given path, returning its branch if known.
///
/// Returns `Some((path, branch))` if a worktree exists at the path,
@@ -198,6 +232,6 @@ impl Repository {
}
// No worktrees - fall back to repo base (bare repo case)
- self.worktree_base()
+ self.repo_path()
}
}
diff --git a/src/main.rs b/src/main.rs
index 4bc681e33..f133d3480 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1345,7 +1345,7 @@ fn main() {
// This ensures approval happens once at the command entry point
// If user declines, skip hooks but continue with worktree operation
let approved = if verify {
- let repo_root = repo.worktree_base().context("Failed to switch worktree")?;
+ let repo_root = repo.repo_path().context("Failed to switch worktree")?;
let ctx = CommandContext::new(
&repo,
&config,
@@ -1428,7 +1428,7 @@ fn main() {
// - post-start: runs only when creating a NEW worktree
if !skip_hooks {
let repo = Repository::current()?;
- let repo_root = repo.worktree_base().context("Failed to switch worktree")?;
+ let repo_root = repo.repo_path().context("Failed to switch worktree")?;
let ctx = CommandContext::new(
&repo,
&config,
@@ -1452,7 +1452,7 @@ fn main() {
if let Some(cmd) = execute {
// Build template context for expansion (includes base vars when creating)
let repo = Repository::current()?;
- let repo_root = repo.worktree_base().context("Failed to get repo root")?;
+ let repo_root = repo.repo_path().context("Failed to get repo root")?;
let ctx = CommandContext::new(
&repo,
&config,
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 8cee7633e..cc8ff7841 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -548,7 +548,7 @@ fn spawn_post_switch_after_remove(
// is removed (cwd may no longer exist).
let repo = Repository::at(main_path)?;
let dest_branch = repo.worktree_at(main_path).branch()?;
- let repo_root = repo.worktree_base()?;
+ let repo_root = repo.repo_path()?;
let ctx = CommandContext::new(
&repo,
&config,
diff --git a/tests/integration_tests/bare_repository.rs b/tests/integration_tests/bare_repository.rs
index 040ec8b15..44190528e 100644
--- a/tests/integration_tests/bare_repository.rs
+++ b/tests/integration_tests/bare_repository.rs
@@ -195,7 +195,7 @@ fn test_bare_repo_identifies_primary_correctly() {
}
#[test]
-fn test_bare_repo_worktree_base_used_for_paths() {
+fn test_bare_repo_path_used_for_worktree_paths() {
let test = BareRepoTest::new();
// Create initial worktree
@@ -213,12 +213,12 @@ fn test_bare_repo_worktree_base_used_for_paths() {
cmd.output().unwrap();
- // Verify path is created inside bare repo (using worktree_base)
+ // Verify path is created inside bare repo (using repo_path as base)
// Template: {{ branch }} -> repo/dev
let expected = test.bare_repo_path().join("dev");
assert!(
expected.exists(),
- "Worktree should be created using worktree_base: {:?}",
+ "Worktree should be created using repo_path: {:?}",
expected
);
diff --git a/tests/integration_tests/step_copy_ignored.rs b/tests/integration_tests/step_copy_ignored.rs
index 59949c2f0..d851cdd88 100644
--- a/tests/integration_tests/step_copy_ignored.rs
+++ b/tests/integration_tests/step_copy_ignored.rs
@@ -528,21 +528,32 @@ fn test_copy_ignored_to_nonexistent_worktree(repo: TestRepo) {
/// Test copy-ignored when default branch has no worktree
///
-/// When the default branch (main) has no worktree, copy-ignored should error clearly
-/// rather than failing cryptically with git ls-files errors.
+/// When the default branch (main) has no worktree, copy-ignored falls back to
+/// the main worktree (the original clone directory) for non-bare repos.
#[rstest]
fn test_copy_ignored_no_default_branch_worktree(mut repo: TestRepo) {
// Create a feature worktree and switch main worktree to a different branch
let feature_path = repo.add_worktree("feature");
repo.switch_primary_to("develop"); // main worktree is now on 'develop', not 'main'
- // Now 'main' has no worktree. Try to copy from default (main).
+ // Set up ignored file in the main worktree (which is now on 'develop')
+ fs::write(repo.root_path().join(".env"), "SECRET=value").unwrap();
+ fs::write(repo.root_path().join(".gitignore"), ".env\n").unwrap();
+ fs::write(repo.root_path().join(".worktreeinclude"), ".env\n").unwrap();
+
+ // Copy from feature - should use main worktree as source (primary_worktree fallback)
assert_cmd_snapshot!(make_snapshot_cmd(
&repo,
"step",
&["copy-ignored"],
Some(&feature_path),
));
+
+ // Verify file was copied from main worktree
+ assert!(
+ feature_path.join(".env").exists(),
+ ".env should be copied from main worktree"
+ );
}
/// Test copy-ignored in a bare repository setup
diff --git a/tests/snapshots/integration__integration_tests__step_copy_ignored__copy_ignored_no_default_branch_worktree.snap b/tests/snapshots/integration__integration_tests__step_copy_ignored__copy_ignored_no_default_branch_worktree.snap
index 8a2bcbae6..291bd2cd6 100644
--- a/tests/snapshots/integration__integration_tests__step_copy_ignored__copy_ignored_no_default_branch_worktree.snap
+++ b/tests/snapshots/integration__integration_tests__step_copy_ignored__copy_ignored_no_default_branch_worktree.snap
@@ -27,9 +27,9 @@ info:
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
---
-success: false
-exit_code: 1
+success: true
+exit_code: 0
----- stdout -----
----- stderr -----
-✗ No worktree found for branch main
+✓ Copied 1 entry