Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(list): handle empty repos (no commits) gracefully (#1058)
Maximilian Roosbb3efee9c14d
diff --git a/src/commands/list/collect/execution.rs b/src/commands/list/collect/execution.rsindex 681d93e3f..e7b176077 100644--- a/src/commands/list/collect/execution.rs+++ b/src/commands/list/collect/execution.rs@@ -32,6 +32,21 @@ const EXPENSIVE_TASKS: &[TaskKind] = &[TaskKind::MergeTreeConflicts, // git merge-tree simulation];+/// Tasks that require a valid commit SHA. Skipped for unborn branches (no commits yet).+/// Without this, these tasks would fail on the null OID and show as errors in the table.+const COMMIT_TASKS: &[TaskKind] = &[+ TaskKind::CommitDetails,+ TaskKind::AheadBehind,+ TaskKind::CommittedTreesMatch,+ TaskKind::HasFileChanges,+ TaskKind::IsAncestor,+ TaskKind::BranchDiff,+ TaskKind::MergeTreeConflicts,+ TaskKind::WouldMergeAdd,+ TaskKind::CiStatus,+ TaskKind::Upstream,+];+// ============================================================================// Work Item Dispatch (for flat parallelism)// ============================================================================@@ -185,6 +200,8 @@ pub fn work_items_for_worktree(.as_deref().is_some_and(|b| options.stale_branches.contains(b));+ let has_commits = wt.has_commits();+let mut items = Vec::with_capacity(15);// Helper to add a work item and register the expected result@@ -219,6 +236,10 @@ pub fn work_items_for_worktree(if is_stale && EXPENSIVE_TASKS.contains(&kind) {continue;}+ // Skip commit-dependent tasks for unborn branches (no commits yet)+ if !has_commits && COMMIT_TASKS.contains(&kind) {+ continue;+ }add_item(kind);}// URL status health check task (if we have a URL).diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rsindex 75c608e81..3774e1978 100644--- a/src/commands/list/collect/mod.rs+++ b/src/commands/list/collect/mod.rs@@ -331,6 +331,8 @@ pub fn collect(// (skeleton shows placeholder gutter, actual symbols appear when data loads)// Phase 3: Batch fetch timestamps (needs all SHAs from worktrees + branches)+ // Filter out null OIDs from unborn branches — a single null OID would cause+ // `git show` to fail for ALL shas in the batch.let all_shas: Vec<&str> = worktrees.iter().map(|wt| wt.head.as_str())@@ -340,6 +342,7 @@ pub fn collect(.map(|(_, sha)| sha.as_str()),).chain(remote_branches.iter().map(|(_, sha)| sha.as_str()))+ .filter(|sha| *sha != worktrunk::git::NULL_OID).collect();let timestamps = repo.commit_timestamps(&all_shas).unwrap_or_default();diff --git a/src/commands/list/json_output.rs b/src/commands/list/json_output.rsindex d4f068d91..64af63817 100644--- a/src/commands/list/json_output.rs+++ b/src/commands/list/json_output.rs@@ -229,12 +229,13 @@ impl JsonItem {let is_current = worktree_data.is_some_and(|d| d.is_current);let is_previous = worktree_data.is_some_and(|d| d.is_previous);- // Commit info- let sha = item.head.clone();- let short_sha = if sha.len() >= 7 {- sha[..7].to_string()+ // Commit info — empty strings for null OID (unborn branches)+ let (sha, short_sha) = if item.head == worktrunk::git::NULL_OID {+ (String::new(), String::new())} else {- sha.clone()+ let sha = item.head.clone();+ let short_sha = sha[..7.min(sha.len())].to_string();+ (sha, short_sha)};let commit = JsonCommit {sha,diff --git a/src/commands/list/render.rs b/src/commands/list/render.rsindex be85ec346..f1ee7023a 100644--- a/src/commands/list/render.rs+++ b/src/commands/list/render.rs@@ -287,10 +287,12 @@ impl LayoutConfig {cell.pad_to(col.width);}ColumnKind::Commit => {- // Show actual commit hash (always available)+ // Show actual commit hash (empty for unborn branches with null OID)let head = item.head();- let short_head = &head[..8.min(head.len())];- cell.push_styled(short_head, dim);+ if head != worktrunk::git::NULL_OID {+ let short_head = &head[..8.min(head.len())];+ cell.push_styled(short_head, dim);+ }}_ => {// Show spinner for data columns (placeholder_cell handles alignment)@@ -488,8 +490,12 @@ impl ColumnLayout {}ColumnKind::Commit => {let head = item.head();- let short_head = &head[..8.min(head.len())];- self.render_text_cell(short_head, Some(Style::new().dimmed()))+ if head == worktrunk::git::NULL_OID {+ self.render_text_cell("", None)+ } else {+ let short_head = &head[..8.min(head.len())];+ self.render_text_cell(short_head, Some(Style::new().dimmed()))+ }}ColumnKind::Message => {let Some(ref commit) = item.commit else {diff --git a/src/git/mod.rs b/src/git/mod.rsindex e5836ccc4..a78751587 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -29,6 +29,9 @@ use crate::sync::Semaphore;use std::sync::LazyLock;static HEAVY_OPS_SEMAPHORE: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(4));+/// The null OID returned by git when no commits exist (e.g., `git rev-parse HEAD` on an unborn branch).+pub const NULL_OID: &str = "0000000000000000000000000000000000000000";+// Re-exports from submodulespub(crate) use diff::DiffStats;pub use diff::{LineDiff, parse_numstat_line};@@ -451,6 +454,13 @@ impl WorktreeInfo {self.prunable.is_some()}+ /// Returns true if this worktree points to a real commit (not the null OID).+ ///+ /// Unborn branches (no commits yet) have the null OID as their HEAD.+ pub fn has_commits(&self) -> bool {+ self.head != NULL_OID+ }+/// Returns the worktree directory name.////// This is the filesystem directory name (e.g., "repo.feature" from "/path/to/repo.feature").diff --git a/src/git/repository/config.rs b/src/git/repository/config.rsindex 8b1557fee..9aee9115c 100644--- a/src/git/repository/config.rs+++ b/src/git/repository/config.rs@@ -156,6 +156,11 @@ impl Repository {let _ = self.cache.invalid_default_branch.set(None);return Some(branch.clone());}+ // Check if this is the unborn default branch (HEAD points to it but no commits yet)+ if self.is_unborn_head_branch(branch) {+ let _ = self.cache.invalid_default_branch.set(None);+ return Some(branch.clone());+ }// Configured branch doesn't exist - cache for warning, return Nonelet _ = self.cache.invalid_default_branch.set(Some(branch.clone()));log::debug!(@@ -322,6 +327,18 @@ impl Repository {// Private helpers for default_branch detection+ /// Check if a branch is the unborn default branch (HEAD points to it but no commits exist).+ ///+ /// This is the case in a freshly `git init`-ed repo: HEAD is `refs/heads/main` but the+ /// branch doesn't exist yet (no commits). We accept this as a valid default branch.+ fn is_unborn_head_branch(&self, branch: &str) -> bool {+ self.run_command(&["symbolic-ref", "HEAD"])+ .ok()+ .and_then(|s| s.trim().strip_prefix("refs/heads/").map(String::from))+ .is_some_and(|head_branch| head_branch == branch)+ && self.local_branches().is_ok_and(|b| b.is_empty())+ }+fn get_local_default_branch(&self, remote: &str) -> anyhow::Result<String> {let stdout =self.run_command(&["rev-parse", "--abbrev-ref", &format!("{}/HEAD", remote)])?;diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rsindex 92d056b50..d530ff1c8 100644--- a/tests/integration_tests/list.rs+++ b/tests/integration_tests/list.rs@@ -2928,3 +2928,41 @@ fn test_list_nested_worktree_json_is_current(mut repo: TestRepo) {"Parent worktree 'main' should NOT be marked as current");}++/// Tests that `wt list` handles a freshly `git init`-ed repo with no commits.+///+/// Empty repos have the null OID for HEAD and no branches. Without proper handling,+/// this causes task failures (git operations on null OID), garbage data (00000000, 56y),+/// and spurious "default branch does not exist locally" warnings.+#[test]+fn test_list_empty_repo() {+ let repo = TestRepo::empty();+ // Pre-set default branch cache so the `is_unborn_head_branch` validation path is exercised+ repo.run_git(&["config", "worktrunk.default-branch", "main"]);+ // Should show the branch with empty commit columns and no errors+ assert_cmd_snapshot!(list_snapshots::command(&repo, repo.root_path()));+}++/// Tests JSON output for an empty repo (no commits).+#[test]+fn test_list_empty_repo_json() {+ let repo = TestRepo::empty();+ let output = repo+ .wt_command()+ .args(["list", "--format=json"])+ .current_dir(repo.root_path())+ .output()+ .unwrap();++ assert!(+ output.status.success(),+ "wt list --format=json should succeed"+ );+ let json: Vec<serde_json::Value> = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(json.len(), 1, "Should have one worktree entry");++ let item = &json[0];+ assert_eq!(item["branch"], "main");+ assert_eq!(item["commit"]["sha"], "");+ assert_eq!(item["commit"]["short_sha"], "");+}diff --git a/tests/snapshots/integration__integration_tests__list__list_empty_repo.snap b/tests/snapshots/integration__integration_tests__list__list_empty_repo.snapnew file mode 100644index 000000000..91e2ad01f--- /dev/null+++ b/tests/snapshots/integration__integration_tests__list__list_empty_repo.snap@@ -0,0 +1,42 @@+---+source: tests/integration_tests/list.rs+info:+ program: wt+ args:+ - list+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----+ [1mBranch[0m [1mStatus[0m [1mHEAD±[0m [1mmain↕[0m [1mPath[0m [1mRemote⇅[0m [1mCommit[0m [1mAge[0m [1mMessage+@ main [2m^[22m . [2m⋯[0m [2m⋯++[2m○[22m [2mShowing 1 worktree++----- 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.snapindex e001b221b..cf47a8a7c 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@@ -28,6 +28,7 @@ info:WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"WORKTRUNK_TEST_POWERSHELL_ENV: "0"WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"@@ -37,18 +38,14 @@ exit_code: 0----- stdout -----[1mBranch[0m [1mStatus[0m [1mHEAD±[0m [1mmain↕[0m [1mPath[0m [1mRemote⇅[0m [1mCommit[0m [1mAge[0m [1mMessage@ main [2m^[22m[2m|[22m . [2m|[0m [2m05a4a45d[0m [2m16h[0m [2mInitial commit-+ feature [33m✗[39m [2m⋯[0m ../repo.feature [2m00000000[0m [2m55y[0m [2m+ feature-a [2m↑[22m [32m↑1[0m ../repo.feature-a [2m1b87d473[0m [2m16h[0m [2mAdd feature-a file+ feature-b [2m↑[22m [32m↑1[0m ../repo.feature-b [2mf62940fc[0m [2m16h[0m [2mAdd feature-b file+ feature-c [2m↑[22m [32m↑1[0m ../repo.feature-c [2m345c7c93[0m [2m16h[0m [2mAdd feature-c file++ feature [2m⋯[0m ../repo.feature [2m⋯[0m [2m⋯-[2m○[22m [2mShowing 5 worktrees, 3 ahead. 5 tasks failed+[2m○[22m [2mShowing 5 worktrees, 3 ahead. 1 task failed----- stderr -----[33m▲[39m [33mSome git operations failed:-[107m [0m [1mfeature[22m: commit-details (fatal: bad object 0000000000000000000000000000000000000000)-[107m [0m [1mfeature[22m: ahead-behind (git merge-base failed for main 0000000000000000000000000000000000000000: fatal: Not a valid commit name 0000000000000000000000000000000000000000)-[107m [0m [1mfeature[22m: committed-trees-match (fatal: ambiguous argument '0000000000000000000000000000000000000000^{tree}': unknown revision or path not in the working tree.)-[107m [0m [1mfeature[22m: has-file-changes (git merge-base failed for refs/heads/main refs/heads/feature: fatal: Not a valid commit name refs/heads/feature)[107m [0m [1mfeature[22m: working-tree-diff (fatal: bad object HEAD)[39m[2m↳[22m [2mTo create a diagnostic file, run with [90m-vv[39m[22m