Skip to content

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

fix(git): harden user-ref git call sites against hyphen-prefixed refs (#2725)

Maximilian Roos16ceea946a59
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 5c8941d04..19daebfc8 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -292,7 +292,7 @@ pub fn build_hook_context(
let commit = match ctx.branch {
Some(branch) => ctx
.repo
- .run_command(&["rev-parse", branch])
+ .run_command(&["rev-parse", "--verify", "--end-of-options", branch])
.ok()
.map(|s| s.trim().to_owned()),
None => ctx
diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rs
index 5ad3e2934..3e7fbc710 100644
--- a/src/commands/list/collect/tasks.rs
+++ b/src/commands/list/collect/tasks.rs
@@ -126,7 +126,7 @@ impl TaskContext {
}
Ok(self
.repo
- .run_command(&["rev-parse", name])?
+ .run_command(&["rev-parse", "--verify", "--end-of-options", name])?
.trim()
.to_string())
}
diff --git a/src/commands/picker/items.rs b/src/commands/picker/items.rs
index 4be6369ad..1bfc23623 100644
--- a/src/commands/picker/items.rs
+++ b/src/commands/picker/items.rs
@@ -362,7 +362,9 @@ impl WorktreeSkimItem {
let reset = Reset;
let upstream_ref = format!("{branch}@{{u}}");
- let Ok(upstream_sha_raw) = repo.run_command(&["rev-parse", &upstream_ref]) else {
+ let Ok(upstream_sha_raw) =
+ repo.run_command(&["rev-parse", "--verify", "--end-of-options", &upstream_ref])
+ else {
return cformat!(
"{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no upstream tracking branch\n"
);
@@ -376,8 +378,13 @@ impl WorktreeSkimItem {
}
let probe_range = format!("{}...{upstream_sha}", item.head());
- let Ok(counts) = repo.run_command(&["rev-list", "--left-right", "--count", &probe_range])
- else {
+ let Ok(counts) = repo.run_command(&[
+ "rev-list",
+ "--left-right",
+ "--count",
+ "--end-of-options",
+ &probe_range,
+ ]) else {
return cformat!(
"{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no upstream tracking branch\n"
);
@@ -522,7 +529,9 @@ impl WorktreeSkimItem {
// pane. Silent fallbacks beat disruptive errors during navigation;
// the preview is supplementary, users can still select worktrees
// even if a probe fails.
- let Ok(merge_base_output) = repo.run_command(&["merge-base", &default_branch, head]) else {
+ let Ok(merge_base_output) =
+ repo.run_command(&["merge-base", "--end-of-options", &default_branch, head])
+ else {
return (
cformat!("{INFO_SYMBOL}{reset} <bold>{branch}</>{reset} has no commits\n"),
false,
diff --git a/src/commands/relocate.rs b/src/commands/relocate.rs
index 41aa213bb..1d64d1c88 100644
--- a/src/commands/relocate.rs
+++ b/src/commands/relocate.rs
@@ -553,6 +553,13 @@ impl<'a> RelocationExecutor<'a> {
}
/// Main worktree can't use `git worktree move`; must create new + switch.
+ ///
+ /// If `worktree add` fails after the initial checkout, the main worktree
+ /// is left on `default_branch` rather than the original branch — the user
+ /// can recover with `git switch -`. Restoring it here would be best-effort
+ /// (no error surface) and the failure modes for `worktree add` (invalid
+ /// path, branch already checked out elsewhere) are clear enough that the
+ /// user knows what to do.
fn move_main_worktree(&mut self, idx: usize, default_branch: &str) -> anyhow::Result<()> {
let candidate = &self.pending[idx];
let branch = candidate.branch();
@@ -560,28 +567,16 @@ impl<'a> RelocationExecutor<'a> {
let msg = cformat!("Switching main worktree to <bold>{default_branch}</>...");
eprintln!("{}", progress_message(msg));
- // Bind the main worktree up front so the rollback path can reuse it
- // without threading another `?` through a best-effort cleanup.
let main_wt = self.repo.worktree_at(self.repo.repo_path()?);
main_wt
- .run_command(&["checkout", default_branch])
+ .run_command(&["checkout", "--end-of-options", default_branch])
.with_context(|| format!("Failed to checkout default branch '{default_branch}'"))?;
- // Try to create worktree; if it fails, rollback to original branch.
let dest = candidate.expected_path.to_string_lossy();
- let add_result = main_wt.run_command(&["worktree", "add", &dest, branch]);
-
- if let Err(e) = add_result {
- // Rollback: checkout the original branch to restore user context
- let rollback_msg = cformat!("Worktree creation failed, restoring <bold>{branch}</>...");
- eprintln!("{}", warning_message(rollback_msg));
-
- // Best-effort rollback: log failures but don't mask the original error.
- let _ = main_wt.run_command(&["checkout", branch]);
-
- return Err(e).context("Failed to create worktree for main relocation");
- }
+ main_wt
+ .run_command(&["worktree", "add", &dest, branch])
+ .context("Failed to create worktree for main relocation")?;
Ok(())
}
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 2c4cad500..2fe61047a 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -451,7 +451,10 @@ impl RepositoryCliExt for Repository {
let Some(merge_base) = self.merge_base("HEAD", target)? else {
return Ok(false);
};
- let target_sha = self.run_command(&["rev-parse", target])?.trim().to_string();
+ let target_sha = self
+ .run_command(&["rev-parse", "--verify", "--end-of-options", target])?
+ .trim()
+ .to_string();
if merge_base != target_sha {
return Ok(false); // Target has advanced past merge-base
@@ -459,7 +462,12 @@ impl RepositoryCliExt for Repository {
// Check for merge commits — if present, history is not linear
let merge_commits = self
- .run_command(&["rev-list", "--merges", &format!("{}..HEAD", target)])?
+ .run_command(&[
+ "rev-list",
+ "--merges",
+ "--end-of-options",
+ &format!("{}..HEAD", target),
+ ])?
.trim()
.to_string();
diff --git a/src/commands/step/promote.rs b/src/commands/step/promote.rs
index 22b0bf428..4f306902d 100644
--- a/src/commands/step/promote.rs
+++ b/src/commands/step/promote.rs
@@ -231,9 +231,11 @@ fn print_promote_announcement(is_restoring: bool, default_branch: Option<&str>)
/// Exchange branches between two worktrees.
///
/// Steps: detach target → detach main → switch main → switch target.
-/// Both worktrees must be clean (verified by caller). On failure, attempts
-/// best-effort rollback — but failure here is near-impossible given the
-/// preconditions (`ensure_clean` passed, branches exist, detach released locks).
+/// Both worktrees must be clean (verified by caller). Failure here is
+/// near-impossible given the preconditions (`ensure_clean` passed, branches
+/// exist, detach released locks); if it does happen, the caller surfaces the
+/// error and the worktrees may be left in a detached state for the user to
+/// resolve manually.
fn exchange_branches(
main_wt: &worktrunk::git::WorkingTree<'_>,
main_branch: &str,
@@ -243,17 +245,21 @@ fn exchange_branches(
let steps: &[(&worktrunk::git::WorkingTree<'_>, &[&str], &str)] = &[
(target_wt, &["switch", "--detach"], "detach target"),
(main_wt, &["switch", "--detach"], "detach main"),
- (main_wt, &["switch", target_branch], "switch main"),
- (target_wt, &["switch", main_branch], "switch target"),
+ (
+ main_wt,
+ &["switch", "--end-of-options", target_branch],
+ "switch main",
+ ),
+ (
+ target_wt,
+ &["switch", "--end-of-options", main_branch],
+ "switch target",
+ ),
];
for (wt, args, label) in steps {
- if let Err(e) = wt.run_command(args) {
- // Best-effort rollback: try to re-attach both branches.
- let _ = main_wt.run_command(&["switch", main_branch]);
- let _ = target_wt.run_command(&["switch", target_branch]);
- return Err(e.context(format!("branch exchange failed at: {label}")));
- }
+ wt.run_command(args)
+ .with_context(|| format!("branch exchange failed at: {label}"))?;
}
Ok(())
diff --git a/src/commands/step/rebase.rs b/src/commands/step/rebase.rs
index 2a2d344e9..b15b8bde4 100644
--- a/src/commands/step/rebase.rs
+++ b/src/commands/step/rebase.rs
@@ -42,7 +42,7 @@ pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {
);
}
- let rebase_result = repo.run_command(&["rebase", &integration_target]);
+ let rebase_result = repo.run_command(&["rebase", "--end-of-options", &integration_target]);
// If rebase failed, check if it's due to conflicts
if let Err(e) = rebase_result {
diff --git a/src/git/mod.rs b/src/git/mod.rs
index efc7d850b..7aef773e7 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -305,7 +305,10 @@ fn resolve_via_snapshot(
if let Some(sha) = snapshot.resolve(name) {
return Ok(sha.to_string());
}
- Ok(repo.run_command(&["rev-parse", name])?.trim().to_string())
+ Ok(repo
+ .run_command(&["rev-parse", "--verify", "--end-of-options", name])?
+ .trim()
+ .to_string())
}
/// Category of branch for completion display
diff --git a/src/git/repository/branches.rs b/src/git/repository/branches.rs
index 077481e38..bd1d794e2 100644
--- a/src/git/repository/branches.rs
+++ b/src/git/repository/branches.rs
@@ -96,6 +96,7 @@ impl Repository {
.run_command(&[
"rev-parse",
"--verify",
+ "--end-of-options",
&format!("{}^{{commit}}", reference),
])
.is_ok())
diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rs
index 3846f48b8..e84b7c6ef 100644
--- a/src/git/repository/diff.rs
+++ b/src/git/repository/diff.rs
@@ -14,7 +14,7 @@ impl Repository {
let _guard = super::super::HEAVY_OPS_SEMAPHORE.acquire();
let range = format!("{}..{}", base, head);
- let stdout = self.run_command(&["rev-list", "--count", &range])?;
+ let stdout = self.run_command(&["rev-list", "--count", "--end-of-options", &range])?;
stdout
.trim()
@@ -29,7 +29,8 @@ impl Repository {
/// is renamed in one branch but has uncommitted changes under the old name).
pub fn changed_files(&self, base: &str, head: &str) -> anyhow::Result<Vec<String>> {
let range = format!("{}..{}", base, head);
- let stdout = self.run_command(&["diff", "--name-status", "-z", &range])?;
+ let stdout =
+ self.run_command(&["diff", "--name-status", "-z", "--end-of-options", &range])?;
// Format: STATUS\0PATH\0 or STATUS\0NEW_PATH\0OLD_PATH\0 for renames/copies
let mut files = Vec::new();
@@ -113,7 +114,13 @@ impl Repository {
/// Get commit subjects (first line of commit message) from a range.
pub fn commit_subjects(&self, range: &str) -> anyhow::Result<Vec<String>> {
- let output = self.run_command(&["log", "--no-show-signature", "--format=%s", range])?;
+ let output = self.run_command(&[
+ "log",
+ "--no-show-signature",
+ "--format=%s",
+ "--end-of-options",
+ range,
+ ])?;
Ok(output.lines().map(String::from).collect())
}
@@ -137,6 +144,7 @@ impl Repository {
"--no-merges",
];
if let Some(ref_name) = start_ref {
+ args.push("--end-of-options");
args.push(ref_name);
}
self.run_command(&args).ok().and_then(|output| {
diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rs
index 6b09c8aa7..11bc1cff3 100644
--- a/src/git/repository/integration.rs
+++ b/src/git/repository/integration.rs
@@ -575,14 +575,20 @@ impl Repository {
/// Uncached — tree resolution is cheap (~1 ms) and stale-prone if memoized
/// against a moving ref name.
pub(super) fn rev_parse_tree(&self, spec: &str) -> anyhow::Result<String> {
- Ok(self.run_command(&["rev-parse", spec])?.trim().to_string())
+ Ok(self
+ .run_command(&["rev-parse", "--verify", "--end-of-options", spec])?
+ .trim()
+ .to_string())
}
/// Resolve a ref to its commit SHA. Uncached — callers that want
/// SHA-stable lookups for an entire command should capture a
/// [`RefSnapshot`] up front and resolve through it.
pub(super) fn rev_parse_commit(&self, r: &str) -> anyhow::Result<String> {
- Ok(self.run_command(&["rev-parse", r])?.trim().to_string())
+ Ok(self
+ .run_command(&["rev-parse", "--verify", "--end-of-options", r])?
+ .trim()
+ .to_string())
}
/// Resolve a ref to its commit SHA, skipping git when the input already
@@ -717,7 +723,10 @@ fn snapshot_resolve(
if let Some(sha) = snapshot.resolve(name) {
return Ok(sha.to_string());
}
- Ok(repo.run_command(&["rev-parse", name])?.trim().to_string())
+ Ok(repo
+ .run_command(&["rev-parse", "--verify", "--end-of-options", name])?
+ .trim()
+ .to_string())
}
/// Returns true when `s` is a 40-character hex string — the canonical form
@@ -726,6 +735,33 @@ fn is_hex_commit_sha(s: &str) -> bool {
s.len() == 40 && s.bytes().all(|b| b.is_ascii_hexdigit())
}
+#[cfg(test)]
+mod snapshot_resolve_tests {
+ use super::*;
+ use crate::testing::TestRepo;
+
+ /// Exercises the `git rev-parse` fallback when the snapshot doesn't
+ /// carry the ref (e.g. `HEAD`, tags, raw SHAs). The protective
+ /// `--verify --end-of-options` is on this call site too — keep this
+ /// test honest about what shape rev-parse returns.
+ #[test]
+ fn falls_back_to_rev_parse_for_refs_not_in_snapshot() {
+ let test = TestRepo::with_initial_commit();
+ let repo = Repository::at(test.root_path()).unwrap();
+ let snapshot = repo.capture_refs().unwrap();
+
+ // `HEAD` isn't captured into the snapshot; the fallback resolves it
+ // through git, producing the same SHA HEAD points at.
+ let head_sha_via_fallback = snapshot_resolve(&repo, &snapshot, "HEAD").unwrap();
+ let head_sha_direct = repo.run_command(&["rev-parse", "HEAD"]).unwrap();
+ assert_eq!(head_sha_via_fallback, head_sha_direct.trim());
+
+ // Bogus ref → error (not a confusing "unknown option" — `--verify`
+ // surfaces a clean "Needed a single revision" / "bad revision").
+ assert!(snapshot_resolve(&repo, &snapshot, "no-such-ref").is_err());
+ }
+}
+
#[cfg(test)]
mod hex_sha_tests {
use super::is_hex_commit_sha;
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index c56c4019e..f255e7f75 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -1290,6 +1290,19 @@ impl Repository {
/// Executes the git command with this repository's discovery path as the working directory.
/// For repo-wide operations, any path within the repo works.
///
+ /// # Passing refs
+ ///
+ /// A ref that starts with `-` (e.g. a branch literally named `-foo`,
+ /// which `git update-ref refs/heads/-foo HEAD` will write) is parsed as a
+ /// flag. When the ref's value isn't provably safe — a SHA, a
+ /// `refs/heads/{}` wrap, a hardcoded `HEAD` — put `--end-of-options`
+ /// before it, *after* every other flag (everything following becomes
+ /// positional, so `git log` rejects later flags). For `git rev-parse`,
+ /// use `--verify --end-of-options`: plain `--end-of-options` makes
+ /// rev-parse echo the literal marker to stdout ahead of the SHA, and
+ /// `--verify` forces single-revision strict mode — so it can't cover the
+ /// two-ref `rev-parse <a> <b>` form, which stays unguarded.
+ ///
/// # Examples
/// ```no_run
/// use worktrunk::git::Repository;
diff --git a/src/summary.rs b/src/summary.rs
index 286306088..ded081539 100644
--- a/src/summary.rs
+++ b/src/summary.rs
@@ -236,10 +236,12 @@ pub(crate) fn compute_combined_diff(
let is_default_branch = branch == *default_branch;
if !is_default_branch {
let merge_base = format!("{}...{}", default_branch, head);
- if let Ok(branch_stat) = repo.run_command(&["diff", &merge_base, "--stat"]) {
+ if let Ok(branch_stat) =
+ repo.run_command(&["diff", "--stat", "--end-of-options", &merge_base])
+ {
stat.push_str(&branch_stat);
}
- if let Ok(branch_diff) = repo.run_command(&["diff", &merge_base]) {
+ if let Ok(branch_diff) = repo.run_command(&["diff", "--end-of-options", &merge_base]) {
diff.push_str(&branch_diff);
}
}