Skip to content

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

fix(list): tolerate missing index in temp-index probe (#2884)

Maximilian Roosba518b4f568e
diff --git a/src/commands/step/commit.rs b/src/commands/step/commit.rs
index 8b6cf217c..2fd85a120 100644
--- a/src/commands/step/commit.rs
+++ b/src/commands/step/commit.rs
@@ -97,7 +97,7 @@ fn preview_commit(stage: Option<StageMode>, dry_run: bool, yes: bool) -> anyhow:
} else {
None
};
- let index_override = temp_index.as_ref().map(|t| t.path());
+ let index_override = temp_index.as_deref();
let ctx = env.context(yes);
let project_append = resolve_template_for_preview(&ctx, &commit_config, dry_run)?;
@@ -118,21 +118,27 @@ fn preview_commit(stage: Option<StageMode>, dry_run: bool, yes: bool) -> anyhow:
/// Copy the current worktree's index to a temp file and run `git <add_args>` against it.
///
-/// Returns the [`tempfile::NamedTempFile`] so the caller controls its lifetime — when
+/// Returns the [`tempfile::TempPath`] so the caller controls its lifetime — when
/// dropped, the temp file is removed without ever touching the user's real index.
-fn stage_to_temp_index(
- repo: &Repository,
- add_args: &[&str],
-) -> anyhow::Result<tempfile::NamedTempFile> {
+fn stage_to_temp_index(repo: &Repository, add_args: &[&str]) -> anyhow::Result<tempfile::TempPath> {
let wt = repo.current_worktree();
let real_index = wt.git_dir()?.join("index");
- let temp = tempfile::NamedTempFile::new().context("Failed to create temporary index")?;
- fs::copy(&real_index, temp.path()).context("Failed to copy index file")?;
+ // Close the freshly-created 0-byte tempfile's handle (Windows leaves
+ // the name delete-pending if it's still open) and clear the file; if a
+ // real index exists, copy it back, otherwise let `git add` create a
+ // fresh index at the reserved path. Mirrors `WorkingTree::temp_index`.
+ let temp = tempfile::NamedTempFile::new()
+ .context("Failed to create temporary index")?
+ .into_temp_path();
+ fs::remove_file(&temp).context("Failed to clear temporary index")?;
+ if real_index.exists() {
+ fs::copy(&real_index, &temp).context("Failed to copy index file")?;
+ }
let output = Cmd::new("git")
.args(add_args.iter().copied())
.current_dir(wt.root()?)
- .env("GIT_INDEX_FILE", temp.path())
+ .env("GIT_INDEX_FILE", &temp)
.run()
.context("Failed to stage changes into temp index")?;
if !output.status.success() {
diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rs
index bc631aaa0..8f648bd56 100644
--- a/src/git/repository/working_tree.rs
+++ b/src/git/repository/working_tree.rs
@@ -486,11 +486,22 @@ impl<'a> WorkingTree<'a> {
let real_index = git_dir.join("index");
let log_ctx = path_to_logging_context(self.path());
- let temp = tempfile::NamedTempFile::new().context("Failed to create temporary index")?;
- std::fs::copy(&real_index, temp.path()).context("Failed to copy index file")?;
+ // A missing `<gitdir>/index` is semantically an empty index (nothing
+ // staged), so mirror git's own behaviour. Close the
+ // freshly-created 0-byte tempfile's handle (Windows leaves the name
+ // delete-pending if it's still open) and remove the file; if a real
+ // index exists, copy it back, otherwise leave the path empty and
+ // let the first `git` call against `GIT_INDEX_FILE` create a fresh
+ // valid index there.
+ let temp = tempfile::NamedTempFile::new()
+ .context("Failed to create temporary index")?
+ .into_temp_path();
+ std::fs::remove_file(&temp).context("Failed to clear temporary index")?;
+ if real_index.exists() {
+ std::fs::copy(&real_index, &temp).context("Failed to copy index file")?;
+ }
// Validate UTF-8 once so `TempIndex::path` is infallible.
- temp.path()
- .to_str()
+ temp.to_str()
.context("Temporary index path is not valid UTF-8")?;
Ok(TempIndex {
@@ -602,7 +613,7 @@ impl<'a> WorkingTree<'a> {
/// merge-conflict probing), and `wt step diff` (diff vs target merge-base
/// with untracked).
pub struct TempIndex {
- temp: tempfile::NamedTempFile,
+ temp: tempfile::TempPath,
worktree_root: PathBuf,
log_ctx: String,
}
@@ -610,10 +621,7 @@ pub struct TempIndex {
impl TempIndex {
/// UTF-8 path to the temp index file. Validated at construction.
pub fn path(&self) -> &str {
- self.temp
- .path()
- .to_str()
- .expect("validated in temp_index()")
+ self.temp.to_str().expect("validated in temp_index()")
}
/// Build a `git` command pointed at this temp index.
@@ -638,6 +646,7 @@ impl TempIndex {
mod tests {
use super::has_initialized_submodules_from_status;
use crate::git::Repository;
+ use crate::shell_exec::Cmd;
use crate::testing::TestRepo;
#[test]
@@ -861,4 +870,52 @@ mod tests {
"real index must not be mutated by the temp-index path"
);
}
+
+ #[test]
+ fn temp_index_tolerates_missing_real_index() {
+ // A worktree whose `<gitdir>/index` file is absent must not error
+ // when callers ask for a temp index — git itself treats a missing
+ // index as empty, and the WorkingTreeConflictsTask used to surface
+ // this as a misleading `working-tree-conflicts (Failed to copy
+ // index file)` footer.
+ let test = TestRepo::with_initial_commit();
+ std::fs::write(test.root_path().join("tracked.txt"), "hello\n").unwrap();
+ std::fs::write(test.root_path().join("untracked.txt"), "world\n").unwrap();
+
+ let repo = Repository::at(test.root_path()).unwrap();
+ let wt = repo.worktree_at(test.root_path());
+ let real_index = wt.git_dir().unwrap().join("index");
+ std::fs::remove_file(&real_index).unwrap();
+ assert!(!real_index.exists(), "precondition: real index removed");
+
+ // (a) temp_index() succeeds without <gitdir>/index.
+ let idx = wt
+ .temp_index()
+ .expect("temp_index tolerates missing real index");
+
+ // (b) git add -A against the resulting temp index produces a tree
+ // containing the working-tree files.
+ idx.git(["add", "-A"]).run().unwrap();
+ let write_tree = idx.git(["write-tree"]).run().unwrap();
+ let tree_sha = String::from_utf8_lossy(&write_tree.stdout)
+ .trim()
+ .to_string();
+ let ls_tree = Cmd::new("git")
+ .args(["ls-tree", "-r", "--name-only", &tree_sha])
+ .current_dir(test.root_path())
+ .run()
+ .unwrap();
+ let mut names: Vec<&str> = std::str::from_utf8(&ls_tree.stdout)
+ .unwrap()
+ .lines()
+ .collect();
+ names.sort();
+ assert_eq!(names, vec!["file.txt", "tracked.txt", "untracked.txt"]);
+
+ // (c) the real index is still absent afterward.
+ assert!(
+ !real_index.exists(),
+ "temp_index must not resurrect the real index"
+ );
+ }
}
diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rs
index 8fd4f195a..269138f73 100644
--- a/tests/integration_tests/list.rs
+++ b/tests/integration_tests/list.rs
@@ -3523,3 +3523,61 @@ fn test_list_integrated_when_squash_merged_on_remote_with_local_diverged(
"main_state must be \"integrated\" — instead got entry: {feature}"
);
}
+
+/// Regression: `wt list` against a worktree whose `<gitdir>/index` file is
+/// absent must not surface `working-tree-conflicts (Failed to copy index
+/// file)`. A missing index is semantically empty (nothing staged), so the
+/// conflict probe should compute against the working tree as if the real
+/// index were empty.
+#[rstest]
+fn test_list_tolerates_missing_index(mut repo: TestRepo) {
+ std::fs::write(repo.root_path().join("shared.txt"), "original").unwrap();
+ repo.commit("Initial commit");
+
+ let feature = repo.add_worktree("feature");
+
+ // Dirty the worktree so WorkingTreeConflictsTask exercises the temp-index path.
+ std::fs::write(feature.join("shared.txt"), "feature changes").unwrap();
+ std::fs::write(feature.join("untracked.txt"), "extra\n").unwrap();
+
+ // Delete the worktree's index file — the state the dispatching session
+ // observed across 37 of 38 user worktrees. The linked worktree's gitdir
+ // is recorded in its `.git` pointer file (`gitdir: <abs path>`).
+ let dot_git = std::fs::read_to_string(feature.join(".git")).unwrap();
+ let feature_gitdir = std::path::PathBuf::from(
+ dot_git
+ .trim()
+ .strip_prefix("gitdir: ")
+ .expect("worktree .git points at a gitdir")
+ .trim(),
+ );
+ let feature_index = feature_gitdir.join("index");
+ std::fs::remove_file(&feature_index).unwrap();
+ assert!(
+ !feature_index.exists(),
+ "precondition: feature index removed"
+ );
+
+ let output = repo
+ .wt_command()
+ .args(["list", "--full"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ let combined = format!("{stdout}{stderr}");
+
+ assert!(
+ !combined.contains("Failed to copy index file"),
+ "missing index must not surface as a copy error.\nstdout:\n{stdout}\nstderr:\n{stderr}"
+ );
+ assert!(
+ !combined.contains("working-tree-conflicts ("),
+ "missing index must not produce a working-tree-conflicts task error.\nstdout:\n{stdout}\nstderr:\n{stderr}"
+ );
+ assert!(
+ !feature_index.exists(),
+ "wt list must not resurrect the real index"
+ );
+}
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index a4dd63b96..cbb9f4b38 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -2726,6 +2726,46 @@ fn test_step_commit_dry_run_propagates_git_add_failure(repo: TestRepo) {
);
}
+/// Regression: `--dry-run` must tolerate a missing `<gitdir>/index`. The
+/// temp-index copy used to error with ENOENT (`Failed to copy index file`)
+/// when the real index was absent; the fix mirrors git's own behaviour and
+/// treats a missing index as empty, letting `git add` populate a fresh
+/// temp index.
+#[rstest]
+fn test_step_commit_dry_run_tolerates_missing_index(repo: TestRepo) {
+ fs::write(repo.root_path().join("new.txt"), "x").expect("Failed to write file");
+
+ let index_path = repo.root_path().join(".git").join("index");
+ fs::remove_file(&index_path).expect("Failed to remove index");
+
+ let worktrunk_config = r#"
+[commit.generation]
+command = "cat >/dev/null && echo 'feat: missing-index'"
+"#;
+ fs::write(repo.test_config_path(), worktrunk_config).unwrap();
+
+ let output = make_snapshot_cmd(&repo, "step", &["commit", "--dry-run"], None)
+ .output()
+ .expect("wt step commit --dry-run failed to spawn");
+ assert!(
+ output.status.success(),
+ "missing index must not fail --dry-run; stdout:\n{}\nstderr:\n{}",
+ String::from_utf8_lossy(&output.stdout),
+ String::from_utf8_lossy(&output.stderr),
+ );
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ !stderr.contains("Failed to copy index file"),
+ "missing index must not surface as a copy error; got stderr:\n{stderr}"
+ );
+
+ // Real index must remain absent — dry-run must not resurrect it.
+ assert!(
+ !index_path.exists(),
+ "wt step commit --dry-run must not write the real index"
+ );
+}
+
/// `wt step squash --show-prompt` propagates template errors from
/// `build_squash_prompt`. A malformed jinja template must surface the failure
/// rather than producing an empty prompt.