Skip to content

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

refactor(git): replace porcelain commands with plumbing alternatives (#1345)

Maximilian Roos01a5dfba6088
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index 38ad38913..45188a1a5 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -14,7 +14,7 @@
//!
//! Pre-skeleton runs a **fixed number of git commands** regardless of worktree count.
//! This is achieved through:
-//! - **Batching** — timestamp fetch passes all SHAs to one `git show` command
+//! - **Batching** — timestamp fetch passes all SHAs to one `git log --no-walk` command
//! - **Parallelization** — independent commands run concurrently via `join!` macro
//!
//! **Steady-state (6-8 commands):**
@@ -28,7 +28,7 @@
//! | `git config remote.*.url` (1-3 calls) | Project identifier (for config + path check) | ✓ |
//! | `git for-each-ref refs/heads` | Only with `--branches` flag | ✓ |
//! | `git for-each-ref refs/remotes` | Only with `--remotes` flag | ✓ |
-//! | `git show -s --format='%H %ct' SHA1 SHA2 ...` | **Batched** timestamps | Sequential (needs SHAs) |
+//! | `git log --no-walk --format='%H %ct' SHA1 SHA2 ...` | **Batched** timestamps | Sequential (needs SHAs) |
//!
//! **Non-git operations (negligible latency):**
//! - Path canonicalization — detect current worktree
@@ -430,7 +430,7 @@ pub fn collect(
// 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.
+ // `git log --no-walk` to fail for ALL shas in the batch.
let all_shas: Vec<&str> = worktrees
.iter()
.map(|wt| wt.head.as_str())
diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rs
index 863778a61..450bc3982 100644
--- a/src/git/repository/diff.rs
+++ b/src/git/repository/diff.rs
@@ -52,23 +52,17 @@ impl Repository {
Ok(files)
}
- /// Get commit timestamp in seconds since epoch.
- pub fn commit_timestamp(&self, commit: &str) -> anyhow::Result<i64> {
- let stdout = self.run_command(&["show", "-s", "--format=%ct", commit])?;
- stdout.trim().parse().context("Failed to parse timestamp")
- }
-
/// Get commit timestamps for multiple commits in a single git command.
///
- /// Returns a map from commit SHA to timestamp. More efficient than calling
- /// `commit_timestamp` multiple times when you have many commits.
+ /// Returns a map from commit SHA to timestamp.
pub fn commit_timestamps(&self, commits: &[&str]) -> anyhow::Result<HashMap<String, i64>> {
if commits.is_empty() {
return Ok(HashMap::new());
}
- // Build command: git show -s --format='%H %ct' sha1 sha2 sha3 ...
- let mut args = vec!["show", "-s", "--format=%H %ct"];
+ // Build command: git log --no-walk --format='%H %ct' sha1 sha2 sha3 ...
+ // --no-walk shows exactly the named commits without DAG walking
+ let mut args = vec!["log", "--no-walk", "--format=%H %ct"];
args.extend(commits);
let stdout = self.run_command(&args)?;
@@ -85,26 +79,17 @@ impl Repository {
Ok(result)
}
- /// Get commit message (subject line) for a commit.
- pub fn commit_message(&self, commit: &str) -> anyhow::Result<String> {
- let stdout = self.run_command(&["show", "-s", "--format=%s", commit])?;
- Ok(stdout.trim().to_owned())
- }
-
/// Get commit timestamp and message in a single git command.
- ///
- /// More efficient than calling `commit_timestamp` and `commit_message` separately.
pub fn commit_details(&self, commit: &str) -> anyhow::Result<(i64, String)> {
// Use space separator - timestamps don't contain spaces, and %s (subject)
// is the first line only (no embedded newlines). Split on first space.
- let stdout = self.run_command(&["show", "-s", "--format=%ct %s", commit])?;
+ let stdout = self.run_command(&["log", "-1", "--format=%ct %s", commit])?;
// Only strip trailing newline, not spaces (empty subject = "timestamp ")
let line = stdout.trim_end_matches('\n');
let (timestamp_str, message) = line
.split_once(' ')
.context("Failed to parse commit details")?;
let timestamp = timestamp_str.parse().context("Failed to parse timestamp")?;
- // Trim the message to match commit_message() behavior
Ok((timestamp, message.trim().to_owned()))
}
diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rs
index ecaffb67d..28086fd7b 100644
--- a/src/git/repository/working_tree.rs
+++ b/src/git/repository/working_tree.rs
@@ -124,16 +124,16 @@ impl<'a> WorkingTree<'a> {
return Ok(cached.clone());
}
- // Not cached - run git command and propagate errors
- let stdout = self
- .run_command(&["branch", "--show-current"])
- .context("Failed to determine current branch")?;
-
- let branch = stdout.trim();
- let result = if branch.is_empty() {
- None // Detached HEAD
- } else {
- Some(branch.to_string())
+ // Not cached - use plumbing command to get current branch.
+ // rev-parse --symbolic-full-name returns "refs/heads/<branch>" on a branch,
+ // or "HEAD" when detached. Fails on unborn branches (no commits yet),
+ // so fall back to symbolic-ref which works in all cases except detached HEAD.
+ let result = match self.run_command(&["rev-parse", "--symbolic-full-name", "HEAD"]) {
+ Ok(stdout) => stdout.trim().strip_prefix("refs/heads/").map(str::to_owned),
+ Err(_) => self
+ .run_command(&["symbolic-ref", "--short", "HEAD"])
+ .ok()
+ .map(|s| s.trim().to_owned()),
};
// Cache the successful result
@@ -320,9 +320,11 @@ impl<'a> WorkingTree<'a> {
}
// Get current branch name to use in the ref name
- let branch = self
- .run_command(&["rev-parse", "--abbrev-ref", "HEAD"])?
+ let stdout = self.run_command(&["rev-parse", "--symbolic-full-name", "HEAD"])?;
+ let branch = stdout
.trim()
+ .strip_prefix("refs/heads/")
+ .unwrap_or("HEAD")
.to_string();
// Sanitize branch name for use in ref path (replace / with -)
diff --git a/tests/integration_tests/repository.rs b/tests/integration_tests/repository.rs
index 3f890cd76..2298d8aa9 100644
--- a/tests/integration_tests/repository.rs
+++ b/tests/integration_tests/repository.rs
@@ -723,6 +723,25 @@ fn test_branch_returns_none_for_detached_head() {
);
}
+#[test]
+fn test_branch_returns_branch_for_unborn_repo() {
+ let repo = TestRepo::empty();
+ let root = repo.root_path().to_path_buf();
+ let repository = Repository::at(&root).unwrap();
+ let wt = repository.worktree_at(&root);
+
+ let result = wt.branch();
+ assert!(
+ result.is_ok(),
+ "branch() should succeed for unborn repo (no commits)"
+ );
+ assert_eq!(
+ result.unwrap(),
+ Some("main".to_string()),
+ "branch() should return the default branch name even without commits"
+ );
+}
+
#[test]
fn test_branch_returns_branch_name() {
let repo = TestRepo::new();