Skip to content

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

fix(squash): commit on a detached HEAD so a failed squash keeps the branch (#4206)

Maximilian Roosd65b1a07fea5
diff --git a/docs/src/content/docs/step.md b/docs/src/content/docs/step.md
index 629fbda6b..5e6a820a3 100644
--- a/docs/src/content/docs/step.md
+++ b/docs/src/content/docs/step.md
@@ -201,6 +201,8 @@ See [LLM-generated commit messages](/llm-commits/) for configuration and prompt
`pre-commit` hooks run before the squash commit and abort it on failure; `post-commit` hooks run after it, in the background with their output logged. `--no-hooks` skips both. See [`wt hook`](/hook/).
+The squash commit is made on a detached HEAD, as `git rebase` does, so git's own commit hooks run and see no current branch. The branch moves to the squash commit once it exists — a commit that fails leaves the branch and its history untouched.
+
### Options
#### Staging
@@ -227,13 +229,13 @@ stage = "tracked"
#### Dry run
-Render the prompt, print the LLM command, generate the squash message, and exit without resetting, running hooks, or committing:
+Render the prompt, print the LLM command, generate the squash message, and exit without staging, running hooks, or squashing:
```console
$ wt step squash --dry-run
```
-Three sections are printed: the rendered prompt, the shell command that would invoke the LLM, and the message returned. The LLM call still happens — only the squash and commit are skipped.
+Three sections are printed: the rendered prompt, the shell command that would invoke the LLM, and the message returned. The LLM call still happens — only the squash is skipped.
### Command reference
diff --git a/plugins/worktrunk/skills/worktrunk/reference/step.md b/plugins/worktrunk/skills/worktrunk/reference/step.md
index fb359164c..5571ae05d 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/step.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/step.md
@@ -189,6 +189,8 @@ See [LLM-generated commit messages](https://worktrunk.dev/llm-commits/) for conf
`pre-commit` hooks run before the squash commit and abort it on failure; `post-commit` hooks run after it, in the background with their output logged. `--no-hooks` skips both. See [`wt hook`](https://worktrunk.dev/hook/).
+The squash commit is made on a detached HEAD, as `git rebase` does, so git's own commit hooks run and see no current branch. The branch moves to the squash commit once it exists — a commit that fails leaves the branch and its history untouched.
+
### Options
#### Staging
@@ -215,13 +217,13 @@ stage = "tracked"
#### Dry run
-Render the prompt, print the LLM command, generate the squash message, and exit without resetting, running hooks, or committing:
+Render the prompt, print the LLM command, generate the squash message, and exit without staging, running hooks, or squashing:
```console
$ wt step squash --dry-run
```
-Three sections are printed: the rendered prompt, the shell command that would invoke the LLM, and the message returned. The LLM call still happens — only the squash and commit are skipped.
+Three sections are printed: the rendered prompt, the shell command that would invoke the LLM, and the message returned. The LLM call still happens — only the squash is skipped.
### Command reference
diff --git a/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.md
index fb359164c..5571ae05d 100644
--- a/skills/worktrunk/reference/step.md
+++ b/skills/worktrunk/reference/step.md
@@ -189,6 +189,8 @@ See [LLM-generated commit messages](https://worktrunk.dev/llm-commits/) for conf
`pre-commit` hooks run before the squash commit and abort it on failure; `post-commit` hooks run after it, in the background with their output logged. `--no-hooks` skips both. See [`wt hook`](https://worktrunk.dev/hook/).
+The squash commit is made on a detached HEAD, as `git rebase` does, so git's own commit hooks run and see no current branch. The branch moves to the squash commit once it exists — a commit that fails leaves the branch and its history untouched.
+
### Options
#### Staging
@@ -215,13 +217,13 @@ stage = "tracked"
#### Dry run
-Render the prompt, print the LLM command, generate the squash message, and exit without resetting, running hooks, or committing:
+Render the prompt, print the LLM command, generate the squash message, and exit without staging, running hooks, or squashing:
```console
$ wt step squash --dry-run
```
-Three sections are printed: the rendered prompt, the shell command that would invoke the LLM, and the message returned. The LLM call still happens — only the squash and commit are skipped.
+Three sections are printed: the rendered prompt, the shell command that would invoke the LLM, and the message returned. The LLM call still happens — only the squash is skipped.
### Command reference
diff --git a/src/cli/step.rs b/src/cli/step.rs
index 590830203..85d627476 100644
--- a/src/cli/step.rs
+++ b/src/cli/step.rs
@@ -132,6 +132,8 @@ Three sections are printed: the rendered prompt, the shell command that would in
`pre-commit` hooks run before the squash commit and abort it on failure; `post-commit` hooks run after it, in the background with their output logged. `--no-hooks` skips both. See [`wt hook`](/hook/).
+The squash commit is made on a detached HEAD, as `git rebase` does, so git's own commit hooks run and see no current branch. The branch moves to the squash commit once it exists — a commit that fails leaves the branch and its history untouched.
+
## Options
### Staging
@@ -158,13 +160,13 @@ stage = "tracked"
### Dry run
-Render the prompt, print the LLM command, generate the squash message, and exit without resetting, running hooks, or committing:
+Render the prompt, print the LLM command, generate the squash message, and exit without staging, running hooks, or squashing:
```console
$ wt step squash --dry-run
```
-Three sections are printed: the rendered prompt, the shell command that would invoke the LLM, and the message returned. The LLM call still happens — only the squash and commit are skipped.
+Three sections are printed: the rendered prompt, the shell command that would invoke the LLM, and the message returned. The LLM call still happens — only the squash is skipped.
"#
)]
Squash(SquashArgs),
diff --git a/src/commands/step/squash.rs b/src/commands/step/squash.rs
index bd9b81b31..55203a274 100644
--- a/src/commands/step/squash.rs
+++ b/src/commands/step/squash.rs
@@ -4,7 +4,7 @@ use anyhow::Context;
use color_print::cformat;
use worktrunk::HookType;
use worktrunk::config::UserConfig;
-use worktrunk::git::Repository;
+use worktrunk::git::{Repository, WorkingTree};
use worktrunk::styling::{
eprintln, format_with_gutter, hint_message, info_message, println, progress_message,
success_message,
@@ -174,13 +174,17 @@ pub fn handle_squash(
)?;
}
+ // Resolve HEAD once, so the span, the message's commit list, and the
+ // compare-and-swap that finally moves the branch all describe one tip.
+ let head_sha = wt.run_command(&["rev-parse", "HEAD"])?.trim().to_string();
+
// Get merge base with target branch (required for squash)
let merge_base = repo
- .merge_base("HEAD", &span_target)?
+ .merge_base(&head_sha, &span_target)?
.context("Cannot squash: no common ancestor with target branch")?;
// Count commits since merge base
- let commit_count = repo.count_commits(&merge_base, "HEAD")?;
+ let commit_count = repo.count_commits(&merge_base, &head_sha)?;
// Check if there are staged changes in addition to commits
let has_staged = wt.has_staged_changes()?;
@@ -216,7 +220,7 @@ pub fn handle_squash(
// Either multiple commits OR single commit with staged changes - squash them
// Get diff stats early for display in progress message
- let range = format!("{}..HEAD", merge_base);
+ let range = format!("{merge_base}..{head_sha}");
let commit_text = if commit_count == 1 {
"commit"
@@ -228,7 +232,8 @@ pub fn handle_squash(
let total_stats = if has_staged {
wt.prepare_staged_diff(&merge_base).stats_summary()
} else {
- wt.prepare_commit_diff(&merge_base, "HEAD").stats_summary()
+ wt.prepare_commit_diff(&merge_base, &head_sha)
+ .stats_summary()
};
let with_changes = if has_staged {
@@ -255,7 +260,7 @@ pub fn handle_squash(
};
eprintln!("{}", progress_message(squash_progress));
- // Create safety backup before potentially destructive reset if there are working tree changes
+ // Back up working-tree changes before the squash commit absorbs them
if has_staged {
let backup_message = format!("{} → {} (squash)", current_branch, span_target);
let sha = wt.create_safety_backup(&backup_message)?;
@@ -297,18 +302,45 @@ pub fn handle_squash(
let formatted_message = generator.format_message_for_display(&commit_message);
eprintln!("{}", format_with_gutter(&formatted_message, None));
- // Reset to merge base (soft reset stages all changes, including any already-staged uncommitted changes)
- //
- // TOCTOU note: Between this reset and the commit below, an external process could
- // modify the staging area. This is extremely unlikely (requires precise timing) and
- // the consequence is minor (unexpected content in squash commit). The commit message
- // generated above accurately reflects the original commits being squashed, so any
- // discrepancy would be visible in the diff. Considered acceptable risk.
- repo.run_command(&["reset", "--soft", &merge_base])
- .context("Failed to reset to merge base")?;
-
- // Check if there are actually any changes to commit
- if !wt.has_staged_changes()? {
+ // Squash the way `git rebase` rewrites history: detach HEAD onto the merge
+ // base, commit there, and move the branch to the result. The branch keeps
+ // its commits until the commit exists, so a commit that fails — a
+ // `pre-commit` hook rejecting it, a broken signing setup — leaves the
+ // branch and its history where they were. Committing through `git commit`
+ // rather than plumbing is what keeps git's own hooks, `commit.cleanup`,
+ // signing, and identity resolution behaving as they do for any other
+ // commit; those hooks see a detached HEAD, as they do under `git rebase`.
+ let tree = wt.run_command(&["write-tree"])?.trim().to_string();
+ let base_tree = repo
+ .run_command(&["rev-parse", &format!("{merge_base}^{{tree}}")])?
+ .trim()
+ .to_string();
+
+ // One compare-and-swap moves the branch, refusing if it moved since
+ // `head_sha` was read; ORIG_HEAD then keeps the pre-squash tip, as `git
+ // reset` and `git rebase` leave it. That write is best-effort, exactly as
+ // `git reset` makes it: the branch has already moved by then, so failing
+ // over ORIG_HEAD would report a squash that landed as an error.
+ let branch_ref = format!("refs/heads/{current_branch}");
+ let move_branch = |new_sha: &str, reflog_message: &str| -> anyhow::Result<()> {
+ wt.run_command(&[
+ "update-ref",
+ "-m",
+ reflog_message,
+ &branch_ref,
+ new_sha,
+ &head_sha,
+ ])
+ .with_context(|| cformat!("Failed to update <bold>{current_branch}</>"))?;
+ let _ = wt.run_command(&["update-ref", "ORIG_HEAD", &head_sha]);
+ Ok(())
+ };
+
+ if tree == base_tree {
+ // The commits cancel out, so the squash produces no commit and the
+ // branch moves to the merge base, where `wt merge` finds nothing left
+ // to integrate.
+ move_branch(&merge_base, "wt squash: no net changes")?;
eprintln!(
"{}",
info_message(format!(
@@ -318,12 +350,42 @@ pub fn handle_squash(
return Ok(SquashResult::NoNetChanges);
}
- // Commit with the generated message
- repo.run_command(&["commit", "-m", &commit_message])
- .context("Failed to create squash commit")?;
+ // `--no-deref` moves HEAD itself, leaving the branch, the index and the
+ // working tree untouched; the compare-and-swap refuses if the branch moved
+ // while the message was being generated.
+ //
+ // TOCTOU note: `write-tree` above snapshots the index, and the commit below
+ // re-reads it, so an external process staging into this worktree in between
+ // lands in the squash commit. Precise timing, and the consequence is minor
+ // — unexpected content in a commit whose diff the user is about to see, and
+ // whose message still describes the commits being folded in.
+ wt.run_command(&[
+ "update-ref",
+ "--no-deref",
+ "-m",
+ "wt squash: detach to build the squash commit",
+ "HEAD",
+ &merge_base,
+ &head_sha,
+ ])
+ .context("Failed to detach HEAD onto the merge base")?;
+
+ let commit_sha = match wt
+ .run_command(&["commit", "-m", &commit_message])
+ .context("Failed to create squash commit")
+ .and_then(|_| wt.run_command(&["rev-parse", "HEAD"]))
+ {
+ Ok(sha) => sha.trim().to_string(),
+ Err(err) => return Err(reattach_after_failure(&wt, &branch_ref, err)),
+ };
+
+ let subject = commit_message.lines().next().unwrap_or_default();
+ if let Err(err) = move_branch(&commit_sha, &format!("wt squash: {subject}")) {
+ return Err(reattach_after_failure(&wt, &branch_ref, err));
+ }
+ reattach_head(&wt, &branch_ref)?;
// Full SHA for the JSON payload, abbreviated form for the success line.
- let commit_sha = repo.run_command(&["rev-parse", "HEAD"])?.trim().to_string();
let commit_hash = repo.short_sha(&commit_sha)?;
// Show success immediately after completing the squash
@@ -345,6 +407,33 @@ pub fn handle_squash(
})
}
+/// Put HEAD back on the branch it was detached from for the squash commit.
+fn reattach_head(wt: &WorkingTree<'_>, branch_ref: &str) -> anyhow::Result<()> {
+ wt.run_command(&["symbolic-ref", "HEAD", branch_ref])
+ .with_context(|| {
+ cformat!(
+ "HEAD is left detached; to put it back, run <bold>git symbolic-ref HEAD {branch_ref}</>"
+ )
+ })?;
+ Ok(())
+}
+
+/// Reattach HEAD after a failure that struck while it was detached, and return
+/// the failure that got us here.
+///
+/// The branch never moved, so a successful reattach restores the worktree
+/// exactly as it was and leaves nothing to report beyond `err`.
+fn reattach_after_failure(
+ wt: &WorkingTree<'_>,
+ branch_ref: &str,
+ err: anyhow::Error,
+) -> anyhow::Error {
+ match reattach_head(wt, branch_ref) {
+ Ok(()) => err,
+ Err(reattach_err) => err.context(format!("{reattach_err:#}")),
+ }
+}
+
/// Handle `wt step squash --show-prompt`
///
/// Builds and outputs the squash prompt without running the LLM or squashing.
@@ -360,7 +449,7 @@ pub fn step_show_squash_prompt(
/// Handle `wt step squash --dry-run`
///
/// Renders the squash prompt, prints the LLM command, generates the message, and prints
-/// it without resetting, running hooks, or committing.
+/// it without staging, running hooks, or squashing.
pub fn step_dry_run_squash(
target: Option<&str>,
stage: Option<StageMode>,
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 16a74d6bd..74804393e 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -1735,8 +1735,19 @@ impl Repository {
///
/// `git commit` and `git merge` honor it; `git commit-tree` ignores it, so
/// a commit meant to match what porcelain would record passes `-S` itself.
+ /// Asked of git from this worktree rather than read from the cached config
+ /// map, which is read from the common dir and so misses worktree-scoped
+ /// config, and whose boolean parsing is not git's (a valueless key is true
+ /// to git).
pub fn signs_commits(&self) -> anyhow::Result<bool> {
- self.config_bool("commit.gpgSign")
+ let args = ["config", "--type=bool", "--get", "commit.gpgSign"];
+ let output = self.run_command_output(&args)?;
+ match output.status.code() {
+ Some(0) => Ok(String::from_utf8_lossy(&output.stdout).trim() == "true"),
+ // Exit 1: the key is unset.
+ Some(1) => Ok(false),
+ _ => Err(super::error::CommandError::from_failed_output("git", &args, &output).into()),
+ }
}
/// Get the sparse checkout paths for this repository.
diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rs
index a78590f15..a9dfe3c1b 100644
--- a/src/git/repository/tests.rs
+++ b/src/git/repository/tests.rs
@@ -976,6 +976,46 @@ fn worktree_at_path_resolves_symlinked_path() {
assert_eq!(branch.as_deref(), Some("feature"));
}
+/// `signs_commits` answers as `git commit` would in the worktree it runs from:
+/// a valueless `gpgsign` is true to git, and a `--worktree` setting applies to
+/// its own worktree only.
+#[test]
+fn signs_commits_follows_gits_reading_per_worktree() {
+ use crate::git::Repository;
+ use crate::testing::TestRepo;
+
+ let mut test = TestRepo::with_initial_commit();
+ let feature_path = test.add_worktree("feature");
+ let signs = |path: &std::path::Path| Repository::at(path).unwrap().signs_commits().unwrap();
+
+ assert!(!signs(test.root_path()), "unset means unsigned");
+
+ let config_path = test.root_path().join(".git/config");
+ let mut config = std::fs::read_to_string(&config_path).unwrap();
+ config.push_str("[commit]\n\tgpgsign\n");
+ std::fs::write(&config_path, config).unwrap();
+ assert!(signs(test.root_path()), "a valueless key is true");
+
+ test.run_git(&["config", "extensions.worktreeConfig", "true"]);
+ test.run_git_in(
+ &feature_path,
+ &["config", "--worktree", "commit.gpgSign", "false"],
+ );
+ assert!(!signs(&feature_path), "the feature worktree opted out");
+ assert!(signs(test.root_path()), "the opt-out stays in its worktree");
+
+ // A value git can't read as a boolean is an error, not "unsigned" —
+ // `git commit` would refuse the same way.
+ test.run_git(&["config", "commit.gpgSign", "maybe"]);
+ assert!(
+ Repository::at(test.root_path())
+ .unwrap()
+ .signs_commits()
+ .is_err(),
+ "a value that isn't a boolean must surface as an error"
+ );
+}
+
#[test]
fn current_worktree_anchors_to_repository_discovery_path() {
// `Repository::at(p).current_worktree()` must resolve relative to `p`,
diff --git a/src/llm.rs b/src/llm.rs
index 52fb1cf57..75a6418d4 100644
--- a/src/llm.rs
+++ b/src/llm.rs
@@ -904,9 +904,9 @@ impl SquashInputs<'_> {
// Diff `merge_base` against the index, because the index is what the
// squash commits: `handle_squash` stages the working tree before
- // generating this message and soft-resets to `merge_base` afterwards, so
- // the index already holds everything the one resulting commit will
- // record. `merge_base..HEAD` would name only the pre-existing commits
+ // generating this message and writes the squash commit's tree from the
+ // index afterwards, so the index already holds everything the one
+ // resulting commit will record. `merge_base..HEAD` would name only the pre-existing commits
// and omit the working-tree changes folded into the same commit — and
// for `wt merge` on a dirty worktree those changes are the whole reason
// it ran, so the message came out describing the branch's older commits
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index 4c88c24c6..4d324c0ee 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -4433,6 +4433,196 @@ fn test_step_squash_no_net_changes_json(mut repo: TestRepo) {
);
let parsed: serde_json::Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
assert_eq!(parsed["outcome"], "no_net_changes");
+ assert_eq!(
+ repo.git_output(&["rev-parse", "feature"]),
+ repo.git_output(&["rev-parse", "main"]),
+ "commits that cancel out squash to nothing, leaving the branch at the merge base"
+ );
+}
+
+/// The squash commit is made on a detached HEAD, so the branch keeps its
+/// commits until that commit exists: git's own `pre-commit` hook still gates
+/// the squash, and rejecting it leaves the branch, HEAD and the history
+/// exactly as they were. Without the hook the same squash lands on the branch.
+#[rstest]
+fn test_step_squash_failed_commit_leaves_branch_intact(repo_with_multi_commit_feature: TestRepo) {
+ let repo = &repo_with_multi_commit_feature;
+ let feature_wt = &repo.worktrees["feature"];
+ let feature_dir = feature_wt.to_str().unwrap();
+
+ let hook = repo.root_path().join(".git/hooks/pre-commit");
+ fs::create_dir_all(hook.parent().unwrap()).unwrap();
+ fs::write(&hook, "#!/bin/sh\necho REJECTED-BY-GIT-HOOK >&2\nexit 1\n").unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ fs::set_permissions(&hook, fs::Permissions::from_mode(0o755)).unwrap();
+ }
+
+ let squash = || {
+ repo.wt_command()
+ .args(["step", "squash", "--no-hooks"])
+ .current_dir(feature_wt)
+ .env(
+ "WORKTRUNK_COMMIT__GENERATION__COMMAND",
+ "cat >/dev/null && echo 'squash: combined'",
+ )
+ .output()
+ .unwrap()
+ };
+ let original_tip = repo.git_output(&["rev-parse", "feature"]);
+
+ let output = squash();
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ !output.status.success() && stderr.contains("REJECTED-BY-GIT-HOOK"),
+ "git's pre-commit hook must gate the squash commit: {stderr}"
+ );
+ assert_eq!(
+ repo.git_output(&["rev-parse", "feature"]),
+ original_tip,
+ "a rejected squash commit must leave the branch at its original tip"
+ );
+ assert_eq!(
+ repo.git_output(&["-C", feature_dir, "symbolic-ref", "HEAD"]),
+ "refs/heads/feature",
+ "HEAD must be back on the branch"
+ );
+
+ fs::remove_file(&hook).unwrap();
+ let output = squash();
+ assert!(
+ output.status.success(),
+ "squash failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert_eq!(
+ repo.git_output(&["rev-parse", "feature^"]),
+ repo.git_output(&["rev-parse", "main"]),
+ "the squash commit sits directly on the merge base"
+ );
+ assert_eq!(
+ repo.git_output(&["log", "-1", "--format=%s", "feature"]),
+ "squash: combined"
+ );
+ assert_eq!(
+ repo.git_output(&["-C", feature_dir, "symbolic-ref", "HEAD"]),
+ "refs/heads/feature"
+ );
+ assert_eq!(
+ repo.git_output(&["-C", feature_dir, "rev-parse", "ORIG_HEAD"]),
+ original_tip
+ );
+}
+
+/// A writer that moves the branch while the squash commit is being built loses
+/// nothing: the compare-and-swap that moves the branch refuses rather than
+/// clobbering the other write, and HEAD goes back on the branch.
+#[rstest]
+fn test_step_squash_refuses_when_the_branch_moves_mid_squash(
+ repo_with_multi_commit_feature: TestRepo,
+) {
+ let repo = &repo_with_multi_commit_feature;
+ let feature_wt = &repo.worktrees["feature"];
+ let feature_dir = feature_wt.to_str().unwrap();
+
+ // `pre-commit` runs inside the squash's `git commit`, which is exactly the
+ // window a concurrent writer would move the branch in.
+ let hook = repo.root_path().join(".git/hooks/pre-commit");
+ fs::create_dir_all(hook.parent().unwrap()).unwrap();
+ fs::write(
+ &hook,
+ "#!/bin/sh\ngit update-ref refs/heads/feature \"$(git rev-parse main)\"\n",
+ )
+ .unwrap();
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ fs::set_permissions(&hook, fs::Permissions::from_mode(0o755)).unwrap();
+ }
+
+ let output = repo
+ .wt_command()
+ .args(["step", "squash", "--no-hooks"])
+ .current_dir(feature_wt)
+ .env(
+ "WORKTRUNK_COMMIT__GENERATION__COMMAND",
+ "cat >/dev/null && echo 'squash: combined'",
+ )
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ !output.status.success() && stderr.contains("Failed to update"),
+ "a branch that moved mid-squash must refuse the update: {stderr}"
+ );
+ assert_eq!(
+ repo.git_output(&["rev-parse", "feature"]),
+ repo.git_output(&["rev-parse", "main"]),
+ "the other writer's value stands"
+ );
+ assert_eq!(
+ repo.git_output(&["-C", feature_dir, "symbolic-ref", "HEAD"]),
+ "refs/heads/feature",
+ "HEAD must be back on the branch"
+ );
+}
+
+/// When HEAD can't be put back on the branch after a failed squash commit, the
+/// error says how to do it by hand — the worktree is left detached otherwise.
+#[cfg(unix)]
+#[rstest]
+fn test_step_squash_reports_how_to_reattach_head(repo_with_multi_commit_feature: TestRepo) {
+ use std::os::unix::fs::PermissionsExt;
+
+ let repo = &repo_with_multi_commit_feature;
+ let feature_wt = &repo.worktrees["feature"];
+ let feature_dir = feature_wt.to_str().unwrap();
+
+ // The hook seals the worktree's git directory before rejecting the commit,
+ // so the reattach that follows can't write HEAD either.
+ let hook = repo.root_path().join(".git/hooks/pre-commit");
+ fs::create_dir_all(hook.parent().unwrap()).unwrap();
+ fs::write(
+ &hook,
+ "#!/bin/sh\nchmod a-w \"$(git rev-parse --absolute-git-dir)\"\nexit 1\n",
+ )
+ .unwrap();
+ fs::set_permissions(&hook, fs::Permissions::from_mode(0o755)).unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["step", "squash", "--no-hooks"])
+ .current_dir(feature_wt)
+ .env(
+ "WORKTRUNK_COMMIT__GENERATION__COMMAND",
+ "cat >/dev/null && echo 'squash: combined'",
+ )
+ .output()
+ .unwrap();
+
+ let git_dir =
+ PathBuf::from(repo.git_output(&["-C", feature_dir, "rev-parse", "--absolute-git-dir"]));
+ let sealed = fs::write(git_dir.join("write-probe"), "x").is_err();
+ fs::set_permissions(&git_dir, fs::Permissions::from_mode(0o755)).unwrap();
+ repo.run_git(&[
+ "-C",
+ feature_dir,
+ "symbolic-ref",
+ "HEAD",
+ "refs/heads/feature",
+ ]);
+ if !sealed {
+ // Running with privileges that ignore the read-only directory, so the
+ // reattach succeeded and there is no message to assert.
+ return;
+ }
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ !output.status.success() && stderr.contains("git symbolic-ref HEAD refs/heads/feature"),
+ "a failed reattach must say how to put HEAD back: {stderr}"
+ );
}
/// `step rebase --format=json` reports `rebased` (not `fast_forwarded`) when