Skip to content

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

Use structured output instead of parsing error messages (#570)

Maximilian Roosdb4e0e5dddc6
diff --git a/CLAUDE.md b/CLAUDE.md
index 623fcb355..708f044da 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -153,6 +153,36 @@ for line in reader.lines() {
let lines: Vec<_> = reader.lines().collect();
```
+### Structured Output Over Error Message Parsing
+
+Prefer structured output (exit codes, `--porcelain`, `--json`) over parsing human-readable messages. Error messages break on locale changes, version updates, and minor rewording.
+
+```rust
+// GOOD - exit codes encode meaning
+// git merge-base: 0 = found, 1 = no common ancestor, 128 = invalid ref
+if output.status.success() {
+ Some(parse_sha(&output.stdout))
+} else if output.status.code() == Some(1) {
+ None
+} else {
+ bail!("git merge-base failed: {}", stderr)
+}
+
+// BAD - parsing error messages (breaks on wording changes)
+if msg.contains("no merge base") { return Ok(true); }
+```
+
+**Structured alternatives:**
+
+| Tool | Fragile | Structured |
+|------|---------|------------|
+| `git diff` | `--shortstat` (localized) | `--numstat` |
+| `git status` | default | `--porcelain=v2` |
+| `git merge-base` | error messages | exit codes |
+| `gh` / `glab` | default | `--json` |
+
+When no structured alternative exists, document the fragility inline.
+
## Background Operation Logs
All background logs are centralized in `.git/wt-logs/` (main worktree's git directory):
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 49f4c58f9..545874f29 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -297,7 +297,10 @@ impl RepositoryCliExt for Repository {
}
fn is_rebased_onto(&self, target: &str) -> anyhow::Result<bool> {
- let merge_base = self.merge_base("HEAD", target)?;
+ // Orphan branches have no common ancestor, so they can't be "rebased onto" target
+ 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();
if merge_base != target_sha {
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index 419a7ed1d..7419119cb 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -152,8 +152,10 @@ pub fn handle_squash(
.map_err(worktrunk::git::add_hook_skip_hint)?;
}
- // Get merge base with target branch
- let merge_base = repo.merge_base("HEAD", &target_branch)?;
+ // Get merge base with target branch (required for squash)
+ let merge_base = repo
+ .merge_base("HEAD", &target_branch)?
+ .context("Cannot squash: no common ancestor with target branch")?;
// Count commits since merge base
let commit_count = repo.count_commits(&merge_base, "HEAD")?;
@@ -302,8 +304,10 @@ pub fn step_show_squash_prompt(
.branch()?
.unwrap_or_else(|| "HEAD".to_string());
- // Get merge base with target branch
- let merge_base = repo.merge_base("HEAD", &target_branch)?;
+ // Get merge base with target branch (required for generating squash message)
+ let merge_base = repo
+ .merge_base("HEAD", &target_branch)?
+ .context("Cannot generate squash message: no common ancestor with target branch")?;
// Get commit subjects for the squash message
let range = format!("{}..HEAD", merge_base);
@@ -351,7 +355,9 @@ pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {
}
// Check if this is a fast-forward or true rebase
- let merge_base = repo.merge_base("HEAD", &target_branch)?;
+ let merge_base = repo
+ .merge_base("HEAD", &target_branch)?
+ .context("Cannot rebase: no common ancestor with target branch")?;
let head_sha = repo.run_command(&["rev-parse", "HEAD"])?.trim().to_string();
let is_fast_forward = merge_base == head_sha;
diff --git a/src/git/diff.rs b/src/git/diff.rs
index 5ed20406d..fb4a29f73 100644
--- a/src/git/diff.rs
+++ b/src/git/diff.rs
@@ -72,65 +72,45 @@ impl From<(usize, usize)> for LineDiff {
}
}
-/// Parse git diff --shortstat output
-#[derive(Debug)]
+/// Diff statistics (files changed, insertions, deletions).
+#[derive(Debug, Default)]
pub struct DiffStats {
- pub files: Option<usize>,
- pub insertions: Option<usize>,
- pub deletions: Option<usize>,
+ pub files: usize,
+ pub insertions: usize,
+ pub deletions: usize,
}
impl DiffStats {
- /// Construct stats from `git diff --shortstat` output.
- pub fn from_shortstat(output: &str) -> Self {
- let mut stats = DiffStats {
- files: None,
- insertions: None,
- deletions: None,
- };
-
- // Example: " 3 files changed, 45 insertions(+), 12 deletions(-)"
- let parts: Vec<&str> = output.split(',').collect();
-
- for part in parts {
- let part = part.trim();
-
- if part.contains("file") {
- if let Some(num_str) = part.split_whitespace().next() {
- stats.files = num_str.parse().ok();
- }
- } else if part.contains("insertion") {
- if let Some(num_str) = part.split_whitespace().next() {
- stats.insertions = num_str.parse().ok();
- }
- } else if part.contains("deletion")
- && let Some(num_str) = part.split_whitespace().next()
- {
- stats.deletions = num_str.parse().ok();
+ /// Construct stats from `git diff --numstat` output.
+ pub fn from_numstat(output: &str) -> Self {
+ let mut stats = Self::default();
+ for line in output.lines() {
+ if let Some((added, deleted)) = parse_numstat_line(line) {
+ stats.files += 1;
+ stats.insertions += added;
+ stats.deletions += deleted;
+ } else if !line.trim().is_empty() {
+ // Binary file (shows as "-\t-\tfilename") - count file but not lines
+ stats.files += 1;
}
}
-
stats
}
- /// Format stats as a summary string (e.g., "3 files, +45, -12")
+ /// Format stats as a summary string (e.g., "3 files, +45, -12").
+ /// Zero values are omitted.
pub fn format_summary(&self) -> Vec<String> {
let mut parts = Vec::new();
-
- if let Some(files) = self.files {
- parts.push(format!(
- "{} file{}",
- files,
- if files == 1 { "" } else { "s" }
- ));
+ if self.files > 0 {
+ let s = if self.files == 1 { "" } else { "s" };
+ parts.push(format!("{} file{}", self.files, s));
}
- if let Some(insertions) = self.insertions {
- parts.push(cformat!("<green>+{insertions}</>"));
+ if self.insertions > 0 {
+ parts.push(cformat!("<green>+{}</>", self.insertions));
}
- if let Some(deletions) = self.deletions {
- parts.push(cformat!("<red>-{deletions}</>"));
+ if self.deletions > 0 {
+ parts.push(cformat!("<red>-{}</>", self.deletions));
}
-
parts
}
}
@@ -326,120 +306,83 @@ mod tests {
// DiffStats Tests
// ============================================================================
- #[test]
- fn test_diff_stats_from_shortstat_empty() {
- let stats = DiffStats::from_shortstat("");
- assert!(stats.files.is_none());
- assert!(stats.insertions.is_none());
- assert!(stats.deletions.is_none());
- }
-
- #[test]
- fn test_diff_stats_from_shortstat_full() {
- let output = " 3 files changed, 45 insertions(+), 12 deletions(-)";
- let stats = DiffStats::from_shortstat(output);
- assert_eq!(stats.files, Some(3));
- assert_eq!(stats.insertions, Some(45));
- assert_eq!(stats.deletions, Some(12));
- }
-
- #[test]
- fn test_diff_stats_from_shortstat_single_file() {
- let output = " 1 file changed, 10 insertions(+)";
- let stats = DiffStats::from_shortstat(output);
- assert_eq!(stats.files, Some(1));
- assert_eq!(stats.insertions, Some(10));
- assert!(stats.deletions.is_none());
- }
-
- #[test]
- fn test_diff_stats_from_shortstat_only_deletions() {
- let output = " 2 files changed, 5 deletions(-)";
- let stats = DiffStats::from_shortstat(output);
- assert_eq!(stats.files, Some(2));
- assert!(stats.insertions.is_none());
- assert_eq!(stats.deletions, Some(5));
- }
-
- #[test]
- fn test_diff_stats_from_shortstat_no_changes() {
- // Output when comparing identical trees
- let output = "";
- let stats = DiffStats::from_shortstat(output);
- assert!(stats.files.is_none());
- }
-
#[test]
fn test_diff_stats_format_summary_empty() {
- let stats = DiffStats {
- files: None,
- insertions: None,
- deletions: None,
- };
- let summary = stats.format_summary();
- assert!(summary.is_empty());
+ let stats = DiffStats::default();
+ assert!(stats.format_summary().is_empty());
}
#[test]
fn test_diff_stats_format_summary_all_parts() {
let stats = DiffStats {
- files: Some(3),
- insertions: Some(45),
- deletions: Some(12),
+ files: 3,
+ insertions: 45,
+ deletions: 12,
};
let summary = stats.format_summary();
assert_eq!(summary.len(), 3);
assert_eq!(summary[0], "3 files");
- assert!(summary[1].contains("45")); // Has color codes
- assert!(summary[2].contains("12")); // Has color codes
+ assert!(summary[1].contains("45"));
+ assert!(summary[2].contains("12"));
}
#[test]
fn test_diff_stats_format_summary_single_file() {
let stats = DiffStats {
- files: Some(1),
- insertions: Some(10),
- deletions: None,
+ files: 1,
+ insertions: 10,
+ deletions: 0,
};
let summary = stats.format_summary();
assert_eq!(summary.len(), 2);
- assert_eq!(summary[0], "1 file"); // Singular
+ assert_eq!(summary[0], "1 file");
assert!(summary[1].contains("10"));
}
+ // ============================================================================
+ // DiffStats::from_numstat Tests
+ // ============================================================================
+
#[test]
- fn test_diff_stats_format_summary_only_files() {
- let stats = DiffStats {
- files: Some(5),
- insertions: None,
- deletions: None,
- };
- let summary = stats.format_summary();
- assert_eq!(summary.len(), 1);
- assert_eq!(summary[0], "5 files");
+ fn test_diff_stats_from_numstat_empty() {
+ let stats = DiffStats::from_numstat("");
+ assert_eq!(stats.files, 0);
+ assert_eq!(stats.insertions, 0);
+ assert_eq!(stats.deletions, 0);
}
#[test]
- fn test_diff_stats_format_summary_only_insertions() {
- let stats = DiffStats {
- files: None,
- insertions: Some(100),
- deletions: None,
- };
- let summary = stats.format_summary();
- assert_eq!(summary.len(), 1);
- assert!(summary[0].contains("100"));
+ fn test_diff_stats_from_numstat_single_file() {
+ let stats = DiffStats::from_numstat("45\t12\tpath/to/file.rs");
+ assert_eq!(stats.files, 1);
+ assert_eq!(stats.insertions, 45);
+ assert_eq!(stats.deletions, 12);
}
#[test]
- fn test_diff_stats_format_summary_only_deletions() {
- let stats = DiffStats {
- files: None,
- insertions: None,
- deletions: Some(50),
- };
- let summary = stats.format_summary();
- assert_eq!(summary.len(), 1);
- assert!(summary[0].contains("50"));
+ fn test_diff_stats_from_numstat_multiple_files() {
+ let output = "10\t5\tsrc/main.rs\n20\t3\tsrc/lib.rs\n15\t4\ttests/test.rs";
+ let stats = DiffStats::from_numstat(output);
+ assert_eq!(stats.files, 3);
+ assert_eq!(stats.insertions, 45);
+ assert_eq!(stats.deletions, 12);
+ }
+
+ #[test]
+ fn test_diff_stats_from_numstat_binary_file() {
+ // Binary files show as "-" for both counts - file counted, no line stats
+ let stats = DiffStats::from_numstat("-\t-\timage.png");
+ assert_eq!(stats.files, 1);
+ assert_eq!(stats.insertions, 0);
+ assert_eq!(stats.deletions, 0);
+ }
+
+ #[test]
+ fn test_diff_stats_from_numstat_mixed_binary_and_text() {
+ let output = "10\t5\tsrc/main.rs\n-\t-\tassets/logo.png\n20\t0\tsrc/lib.rs";
+ let stats = DiffStats::from_numstat(output);
+ assert_eq!(stats.files, 3);
+ assert_eq!(stats.insertions, 30);
+ assert_eq!(stats.deletions, 5);
}
}
diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rs
index aae6fa178..ac1c608bd 100644
--- a/src/git/repository/diff.rs
+++ b/src/git/repository/diff.rs
@@ -140,10 +140,15 @@ impl Repository {
/// Get the merge base between two commits.
///
+ /// Returns `Ok(Some(sha))` if a merge base exists, `Ok(None)` for orphan branches
+ /// with no common ancestor (git exit code 1), or `Err` for invalid refs.
+ ///
/// Results are cached in the shared repo cache to avoid redundant git commands
/// when multiple tasks need the same merge-base (e.g., parallel `wt list` tasks).
/// The cache key is normalized (sorted) since merge-base(A, B) == merge-base(B, A).
- pub fn merge_base(&self, commit1: &str, commit2: &str) -> anyhow::Result<String> {
+ pub fn merge_base(&self, commit1: &str, commit2: &str) -> anyhow::Result<Option<String>> {
+ use anyhow::bail;
+
// Normalize key order since merge-base is symmetric: merge-base(A, B) == merge-base(B, A)
let key = if commit1 <= commit2 {
(commit1.to_string(), commit2.to_string())
@@ -151,16 +156,28 @@ impl Repository {
(commit2.to_string(), commit1.to_string())
};
- Ok(self
- .cache
- .merge_base
- .entry(key)
- .or_insert_with(|| {
- self.run_command(&["merge-base", commit1, commit2])
- .map(|output| output.trim().to_owned())
- .unwrap_or_default()
- })
- .clone())
+ // Check cache first
+ if let Some(cached) = self.cache.merge_base.get(&key) {
+ return Ok(cached.clone());
+ }
+
+ // Exit codes: 0 = found, 1 = no common ancestor, 128+ = invalid ref
+ let output = self.run_command_output(&["merge-base", commit1, commit2])?;
+
+ let result = if output.status.success() {
+ Some(String::from_utf8_lossy(&output.stdout).trim().to_owned())
+ } else if output.status.code() == Some(1) {
+ None
+ } else {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ bail!(
+ "git merge-base failed for {commit1} {commit2}: {}",
+ stderr.trim()
+ );
+ };
+
+ self.cache.merge_base.insert(key, result.clone());
+ Ok(result)
}
/// Calculate commits ahead and behind between two refs.
@@ -168,12 +185,18 @@ impl Repository {
/// Returns (ahead, behind) where ahead is commits in head not in base,
/// and behind is commits in base not in head.
///
+ /// For orphan branches with no common ancestor, returns `(0, 0)`.
+ /// TODO: Consider distinct display for orphan branches (e.g., "–" or "∅")
+ ///
/// Uses `merge_base()` internally (which is cached) to compute the common
/// ancestor, then counts commits using two-dot syntax. This allows the
/// merge-base result to be reused across multiple operations.
pub fn ahead_behind(&self, base: &str, head: &str) -> anyhow::Result<(usize, usize)> {
// Get merge-base (cached in shared repo cache)
- let merge_base = self.merge_base(base, head)?;
+ let Some(merge_base) = self.merge_base(base, head)? else {
+ // Orphan branch - no common ancestor
+ return Ok((0, 0));
+ };
// Count commits using two-dot syntax (faster when merge-base is cached)
// ahead = commits in head but not in merge_base
@@ -262,12 +285,16 @@ impl Repository {
/// Uses merge-base (cached) to find common ancestor, then two-dot diff
/// to get the stats. This allows the merge-base result to be reused
/// across multiple operations.
+ ///
+ /// For orphan branches with no common ancestor, returns zeros.
pub fn branch_diff_stats(&self, base: &str, head: &str) -> anyhow::Result<LineDiff> {
// Limit concurrent diff operations to reduce mmap thrash on pack files
let _guard = super::super::HEAVY_OPS_SEMAPHORE.acquire();
// Get merge-base (cached in shared repo cache)
- let merge_base = self.merge_base(base, head)?;
+ let Some(merge_base) = self.merge_base(base, head)? else {
+ return Ok(LineDiff::default());
+ };
// Use two-dot syntax with the cached merge-base
let range = format!("{}..{}", merge_base, head);
@@ -280,11 +307,24 @@ impl Repository {
/// Returns a vector of formatted strings like ["3 files", "+45", "-12"].
/// Returns empty vector if diff command fails or produces no output.
///
- /// This method combines git diff --shortstat, parsing, and formatting into a single call.
+ /// Callers should pass `--shortstat` in args for compatibility; this method
+ /// internally replaces it with `--numstat` for locale-independent parsing.
pub fn diff_stats_summary(&self, args: &[&str]) -> Vec<String> {
- self.run_command(args)
+ // Replace --shortstat with --numstat for locale-independent parsing
+ let args: Vec<&str> = args
+ .iter()
+ .map(|&arg| {
+ if arg == "--shortstat" {
+ "--numstat"
+ } else {
+ arg
+ }
+ })
+ .collect();
+
+ self.run_command(&args)
.ok()
- .map(|output| DiffStats::from_shortstat(&output).format_summary())
+ .map(|output| DiffStats::from_numstat(&output).format_summary())
.unwrap_or_default()
}
diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rs
index b534f23c4..3242c3ceb 100644
--- a/src/git/repository/integration.rs
+++ b/src/git/repository/integration.rs
@@ -33,17 +33,10 @@ impl Repository {
/// For orphan branches (no common ancestor with target), returns true since all
/// their changes are unique.
pub fn has_added_changes(&self, branch: &str, target: &str) -> anyhow::Result<bool> {
- // Try to get merge-base (cached). Orphan branches will fail here.
- let merge_base = match self.merge_base(target, branch) {
- Ok(base) => base,
- Err(e) => {
- // Check if it's an orphan branch (no common ancestor)
- let msg = e.to_string();
- if msg.contains("no merge base") || msg.contains("Not a valid commit") {
- return Ok(true); // Orphan branches have unique changes
- }
- return Err(e);
- }
+ // Try to get merge-base (cached). Orphan branches return None.
+ let Some(merge_base) = self.merge_base(target, branch)? else {
+ // Orphan branches have no common ancestor, so all their changes are unique
+ return Ok(true);
};
// git diff --name-only merge_base..branch shows files changed from merge-base to branch
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 3ca722ed1..7fed3f371 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -80,8 +80,8 @@ pub(super) struct RepoCache {
pub(super) worktree_base: 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
- pub(super) merge_base: DashMap<(String, String), String>,
+ /// Merge-base cache: (commit1, commit2) -> merge_base_sha (None = no common ancestor)
+ pub(super) merge_base: DashMap<(String, String), Option<String>>,
/// Batch ahead/behind cache: (base_ref, branch_name) -> (ahead, behind)
/// Populated by batch_ahead_behind(), used by get_cached_ahead_behind()
pub(super) ahead_behind: DashMap<(String, String), (usize, usize)>,
@@ -507,16 +507,22 @@ impl Repository {
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn run_command_check(&self, args: &[&str]) -> anyhow::Result<bool> {
+ Ok(self.run_command_output(args)?.status.success())
+ }
+
+ /// Run a git command and return the raw Output (for inspecting exit codes).
+ ///
+ /// Use this when exit codes have semantic meaning beyond success/failure.
+ /// For most cases, prefer `run_command` (returns stdout) or `run_command_check` (returns bool).
+ pub(super) fn run_command_output(&self, args: &[&str]) -> anyhow::Result<std::process::Output> {
use crate::shell_exec::run;
let mut cmd = Command::new("git");
cmd.args(args);
cmd.current_dir(&self.discovery_path);
- let output = run(&mut cmd, Some(&self.logging_context()))
- .with_context(|| format!("Failed to execute: git {}", args.join(" ")))?;
-
- Ok(output.status.success())
+ run(&mut cmd, Some(&self.logging_context()))
+ .with_context(|| format!("Failed to execute: git {}", args.join(" ")))
}
}
diff --git a/tests/integration_tests/cache_sharing.rs b/tests/integration_tests/cache_sharing.rs
index 750e0889b..d1ed39df9 100644
--- a/tests/integration_tests/cache_sharing.rs
+++ b/tests/integration_tests/cache_sharing.rs
@@ -64,7 +64,7 @@ fn test_merge_base_cache_shared(mut repo: TestRepo) {
assert_eq!(base1, base2);
// The merge base should be main's HEAD since feature branched from there
- assert_eq!(base1, main_head);
+ assert_eq!(base1, Some(main_head));
}
/// Test that parallel tasks share the cache when cloning Repository.
diff --git a/tests/snapshots/integration__integration_tests__list__list_handles_orphan_branch.snap b/tests/snapshots/integration__integration_tests__list__list_handles_orphan_branch.snap
index f60fb139e..ae075aa88 100644
--- a/tests/snapshots/integration__integration_tests__list__list_handles_orphan_branch.snap
+++ b/tests/snapshots/integration__integration_tests__list__list_handles_orphan_branch.snap
@@ -32,8 +32,8 @@ exit_code: 0
----- stdout -----
Branch Status HEAD± main↕ Path Remote⇅ Commit Age Message
@ main ^ . a1e809f5 1d Initial commit
- assets /✗ ↑1 50209039 1d Add asset
+ assets /✗ 50209039 1d Add asset
-○ Showing 1 worktrees, 1 branches, 1 ahead
+○ Showing 1 worktrees, 1 branches
----- stderr -----
diff --git a/tests/snapshots/integration__integration_tests__list__list_shows_warning_on_git_error.snap b/tests/snapshots/integration__integration_tests__list__list_shows_warning_on_git_error.snap
index 99f21b1fc..6057c0608 100644
--- a/tests/snapshots/integration__integration_tests__list__list_shows_warning_on_git_error.snap
+++ b/tests/snapshots/integration__integration_tests__list__list_shows_warning_on_git_error.snap
@@ -38,8 +38,8 @@ exit_code: 0
----- stderr -----
▲ Some git operations failed:
  feature: commit-details (fatal: bad object 0000000000000000000000000000000000000000)
-  feature: ahead-behind (fatal: Invalid revision range ..0000000000000000000000000000000000000000)
+  feature: ahead-behind (git merge-base failed for main 0000000000000000000000000000000000000000: fatal: Not a valid commit name 0000000000000000000000000000000000000000)
  feature: committed-trees-match (fatal: ambiguous argument '0000000000000000000000000000000000000000^{tree}': unknown revision or path not in the working tree.)
-  feature: has-file-changes (fatal: Invalid revision range ..feature)
+  feature: has-file-changes (git merge-base failed for main feature: fatal: Not a valid commit name feature)
  feature: working-tree-diff (fatal: bad object HEAD)
↳ To create a diagnostic file, run with -vv