Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
perf(list): skip the PR/MR lookup for branches never pushed (#4289)
Maximilian Roos7294e7964bf8
diff --git a/docs/src/content/docs/list.md b/docs/src/content/docs/list.mdindex 4c12707df..598826526 100644--- a/docs/src/content/docs/list.md+++ b/docs/src/content/docs/list.md@@ -122,7 +122,7 @@ The CI column shows the branch's open PR/MR — `#3035` on GitHub, Gitea, and Az| <span style='color:#a60'>⚠</span> yellow | `"error"` | CI status could not be fetched (rate limit, network, etc.) || <span style='color:#a0a'>#</span> magenta | `"changes_requested"` | A reviewer requested changes || <span style='color:#0aa'>#</span> cyan | `"pending"` | A review is required (e.g. branch protection) but not yet given |-| (blank) | `pr` and `checks` absent | No upstream, or no PR/MR and no branch workflow |+| (blank) | `pr` and `checks` absent | Branch never pushed, or no PR/MR and no branch workflow |The two remaining review states have no indicator of their own: `"draft"` only dims the cell and `"approved"` leaves the color unchanged.diff --git a/plugins/worktrunk/skills/worktrunk/reference/list.md b/plugins/worktrunk/skills/worktrunk/reference/list.mdindex f5a8a2f85..db12f3713 100644--- a/plugins/worktrunk/skills/worktrunk/reference/list.md+++ b/plugins/worktrunk/skills/worktrunk/reference/list.md@@ -108,7 +108,7 @@ The CI column shows the branch's open PR/MR — `#3035` on GitHub, Gitea, and Az| `⚠` yellow | `"error"` | CI status could not be fetched (rate limit, network, etc.) || `#` magenta | `"changes_requested"` | A reviewer requested changes || `#` cyan | `"pending"` | A review is required (e.g. branch protection) but not yet given |-| (blank) | `pr` and `checks` absent | No upstream, or no PR/MR and no branch workflow |+| (blank) | `pr` and `checks` absent | Branch never pushed, or no PR/MR and no branch workflow |The two remaining review states have no indicator of their own: `"draft"` only dims the cell and `"approved"` leaves the color unchanged.diff --git a/skills/worktrunk/reference/list.md b/skills/worktrunk/reference/list.mdindex f5a8a2f85..db12f3713 100644--- a/skills/worktrunk/reference/list.md+++ b/skills/worktrunk/reference/list.md@@ -108,7 +108,7 @@ The CI column shows the branch's open PR/MR — `#3035` on GitHub, Gitea, and Az| `⚠` yellow | `"error"` | CI status could not be fetched (rate limit, network, etc.) || `#` magenta | `"changes_requested"` | A reviewer requested changes || `#` cyan | `"pending"` | A review is required (e.g. branch protection) but not yet given |-| (blank) | `pr` and `checks` absent | No upstream, or no PR/MR and no branch workflow |+| (blank) | `pr` and `checks` absent | Branch never pushed, or no PR/MR and no branch workflow |The two remaining review states have no indicator of their own: `"draft"` only dims the cell and `"approved"` leaves the color unchanged.diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex b5922c74c..7aca1d6ad 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -887,7 +887,7 @@ The CI column shows the branch's open PR/MR — `#3035` on GitHub, Gitea, and Az| `⚠` yellow | `"error"` | CI status could not be fetched (rate limit, network, etc.) || `#` magenta | `"changes_requested"` | A reviewer requested changes || `#` cyan | `"pending"` | A review is required (e.g. branch protection) but not yet given |-| (blank) | `pr` and `checks` absent | No upstream, or no PR/MR and no branch workflow |+| (blank) | `pr` and `checks` absent | Branch never pushed, or no PR/MR and no branch workflow |The two remaining review states have no indicator of their own: `"draft"` only dims the cell and `"approved"` leaves the color unchanged.diff --git a/src/commands/list/ci_status/platform.rs b/src/commands/list/ci_status/platform.rsindex 17829c997..6c72e5b1d 100644--- a/src/commands/list/ci_status/platform.rs+++ b/src/commands/list/ci_status/platform.rs@@ -58,6 +58,35 @@ fn detect_pr_mr(}}+/// Whether a PR/MR could have this branch as its head.+///+/// Every forge opens a PR/MR from a branch it hosts, so a local branch that was+/// never pushed can't head one, and the forge call is skipped. Each skip saves+/// a ~450ms round trip and ~65ms of CPU, which adds up in a repo that keeps+/// many local-only branches. A remote row is on its remote by definition.+///+/// A local branch counts as never pushed when no remote has it under its name+/// and its push remote would have recorded it there: git updates+/// `refs/remotes/` on push only where the remote's fetch refspecs map the+/// branch. A `--single-branch` or `--depth` clone maps only the branch it+/// cloned, and a URL push remote (a fork's PR checked out with+/// `gh pr checkout`) maps nothing, so for those only the forge can answer.+///+/// A PR opened from a branch pushed by another clone shows once this clone+/// fetches it.+fn may_head_pr(repo: &Repository, branch: &CiBranchName) -> bool {+ if branch.is_remote() {+ return true;+ }+ let handle = repo.branch(&branch.name);+ if handle.remotes().map_or(true, |r| !r.is_empty()) {+ return true;+ }+ // Where `git push` sends it, as `branch_remote_url` resolves it.+ let push_remote = handle.push_remote().or_else(|| repo.primary_remote().ok());+ !push_remote.is_some_and(|remote| repo.fetch_tracks_branch(&remote, &branch.name))+}+/// Detect CI status from a branch workflow/pipeline (fallback when no PR/MR).fn detect_branch(platform: ForgeKind,@@ -76,7 +105,8 @@ fn detect_branch(}}-/// Detect CI status: PR/MR first, then branch workflow/pipeline if `has_upstream`.+/// Detect CI status: PR/MR first when the branch [may head one](may_head_pr),+/// then branch workflow/pipeline if `has_upstream`.////// Returns `None` if the CLI tool isn't installed or no CI status is found.pub(super) fn detect_ci(@@ -89,7 +119,9 @@ pub(super) fn detect_ci(if !is_tool_available(platform) {return None;}- if let Some(status) = detect_pr_mr(platform, repo, branch, local_head) {+ if may_head_pr(repo, branch)+ && let Some(status) = detect_pr_mr(platform, repo, branch, local_head)+ {return Some(status);}if has_upstream {diff --git a/src/git/mod.rs b/src/git/mod.rsindex 36734b190..774173253 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -379,6 +379,10 @@ pub struct LocalBranch {/// `None` when no upstream is set, or when the configured upstream is gone/// (git reports `[gone]` via `%(upstream:track)`).pub upstream_short: Option<String>,+ /// Where this branch pushes, from `%(push:remotename)`: a remote name, or a+ /// URL when `branch.<name>.pushRemote` is one (`gh pr checkout` sets that+ /// for a fork's PR). `None` when no push remote is configured.+ pub push_remote: Option<String>,}/// A single remote-tracking branch entry from the branch inventory.diff --git a/src/git/repository/branch.rs b/src/git/repository/branch.rsindex bc9900e8e..3b23564eb 100644--- a/src/git/repository/branch.rs+++ b/src/git/repository/branch.rs@@ -126,43 +126,43 @@ impl<'a> Branch<'a> {.and_then(|b| b.upstream_short.clone()))}- /// Get the URL of the remote where this branch would be pushed.+ /// Where this branch pushes: a remote name, or a URL when+ /// `branch.<name>.pushRemote` is one (`gh pr checkout` sets that for a+ /// fork's PR). Resolves `pushRemote` → `remote.pushDefault` → the tracking+ /// remote, as `git push` does.///- /// Uses `%(push:remotename)` which returns either a remote name or URL directly- /// (`gh pr checkout` sets pushremote to a URL rather than a remote name).- /// For remote names, uses `effective_remote_url` to apply `url.insteadOf` rewrites.- /// Returns `None` if no push remote is configured or the remote has no URL.+ /// Reads `%(push:remotename)` from the local-branch inventory (see+ /// [`Repository::local_branches`]), so it forks nothing after the first+ /// scan. Unlike `@{push}`, that field doesn't fail when the push remote is+ /// a URL. Returns `None` when no push remote is configured or no local+ /// branch has this name.///- /// Result is cached on `RepoCache.push_remote_urls`. The CI-status detector- /// calls this from both the PR-based path and the branch fallback, so- /// without the cache the `for-each-ref` runs twice for the same branch- /// on the no-PR path.- pub fn push_remote_url(&self) -> Option<String> {+ /// [`Repository::local_branches`]: super::Repository::local_branches+ pub fn push_remote(&self) -> Option<String> {self.repo- .cache- .push_remote_urls- .entry(self.name.clone())- .or_insert_with(|| {- // %(push:remotename) returns either a remote name or URL- // directly. Unlike @{push}, this doesn't fail when pushremote- // is a URL.- let push_remote = self- .repo- .run_command(&[- "for-each-ref",- "--format=%(push:remotename)",- &format!("refs/heads/{}", self.name),- ])- .ok()- .map(|s| s.trim().to_string())- .filter(|s| !s.is_empty())?;+ .local_branch(&self.name)+ .ok()+ .flatten()+ .and_then(|b| b.push_remote.clone())+ }- if push_remote.contains("://") || push_remote.starts_with("git@") {- Some(push_remote)- } else {- self.repo.effective_remote_url(&push_remote)- }- })- .clone()+ /// Get the URL of the remote where this branch would be pushed.+ ///+ /// A remote name goes through `effective_remote_url` to apply+ /// `url.insteadOf` rewrites; a URL push remote is returned as is.+ /// Returns `None` if no push remote is configured or the remote has no URL.+ pub fn push_remote_url(&self) -> Option<String> {+ let push_remote = self.push_remote()?;+ if is_url(&push_remote) {+ Some(push_remote)+ } else {+ self.repo.effective_remote_url(&push_remote)+ }}}++/// Whether a push remote from `%(push:remotename)` is a URL rather than a+/// remote name.+fn is_url(push_remote: &str) -> bool {+ push_remote.contains("://") || push_remote.starts_with("git@")+}diff --git a/src/git/repository/branches.rs b/src/git/repository/branches.rsindex d744fb6d2..643489c27 100644--- a/src/git/repository/branches.rs+++ b/src/git/repository/branches.rs@@ -74,8 +74,9 @@ const FIELD_SEP: char = '\0';////// Fields, in order: short name, object SHA, committer Unix timestamp,/// upstream short name (empty if none), upstream track (`[gone]` if the-/// configured upstream no longer exists on the remote).-const LOCAL_BRANCH_FORMAT: &str = "--format=%(refname:lstrip=2)%00%(objectname)%00%(committerdate:unix)%00%(upstream:short)%00%(upstream:track)";+/// configured upstream no longer exists on the remote), push remote (a remote+/// name or URL; empty if none).+const LOCAL_BRANCH_FORMAT: &str = "--format=%(refname:lstrip=2)%00%(objectname)%00%(committerdate:unix)%00%(upstream:short)%00%(upstream:track)%00%(push:remotename)";/// Format string for the remote-branch scan.///@@ -389,11 +390,15 @@ fn parse_local_branch_line(line: &str) -> Option<LocalBranch> {} else {Some(upstream_short_raw.to_string())};+ let push_remote = Some(parts.next()?)+ .filter(|s| !s.is_empty())+ .map(str::to_string);Some(LocalBranch {name,commit_sha,committer_ts,upstream_short,+ push_remote,})}diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex b750f5af4..eca8505a3 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -307,14 +307,6 @@ pub(super) struct RepoCache {/// Separate from `all_config` because `git remote get-url` applies/// `url.insteadOf` rewrites that aren't visible in raw config.pub(super) effective_remote_urls: DashMap<String, Option<String>>,- /// Per-branch effective push URL: branch_name -> push URL (or None if- /// no push remote is configured). One `for-each-ref %(push:remotename)`- /// per branch, then `effective_remote_url` for the resolved remote name.- /// `wt list`'s CI-status detection calls `push_remote_url` from both the- /// PR-based path and the branch fallback (via `branch_remote_url`), so- /// the same branch is queried twice on the no-PR path — this cache- /// collapses that to one subprocess.- pub(super) push_remote_urls: DashMap<String, Option<String>>,/// Local branch inventory: one `git for-each-ref refs/heads/` scan, cached/// for the lifetime of the repository. Entries are sorted by most recentdiff --git a/src/git/repository/remotes.rs b/src/git/repository/remotes.rsindex acde0ed0e..f78fe3f7d 100644--- a/src/git/repository/remotes.rs+++ b/src/git/repository/remotes.rs@@ -103,6 +103,26 @@ impl Repository {first_remote.ok_or_else(|| anyhow::anyhow!("No remotes configured"))}+ /// Whether `remote`'s fetch refspecs record `branch` under `refs/remotes/`.+ ///+ /// A push updates the remote-tracking ref only where these refspecs map+ /// one, so this decides whether a missing `refs/remotes/<remote>/<branch>`+ /// means the branch isn't on `remote`. A normal clone maps every branch;+ /// one made with `--single-branch` or `--depth` maps only the branch it+ /// cloned. A URL, or a remote with no fetch refspecs, maps nothing.+ ///+ /// Resolved from the bulk config map — O(1) once populated.+ pub fn fetch_tracks_branch(&self, remote: &str, branch: &str) -> bool {+ let key = super::canonical_config_key(&format!("remote.{remote}.fetch"));+ let Ok(config) = self.all_config() else {+ return false;+ };+ let guard = config.read().unwrap();+ guard+ .get(&key)+ .is_some_and(|refspecs| refspecs_track_ref(refspecs, &format!("refs/heads/{branch}")))+ }+/// Get the URL for a remote, if configured.////// Returns the raw value from `.git/config` without applying `url.insteadOf`@@ -443,10 +463,70 @@ impl Repository {}}+/// Whether fetch `refspecs` map `refname` to a remote-tracking ref: some+/// positive refspec's source matches it and its destination is under+/// `refs/remotes/`, and no negative (`^`) refspec matches it.+fn refspecs_track_ref(refspecs: &[String], refname: &str) -> bool {+ let mut tracked = false;+ for spec in refspecs {+ if let Some(excluded) = spec.strip_prefix('^') {+ if refspec_side_matches(excluded, refname) {+ return false;+ }+ continue;+ }+ let spec = spec.strip_prefix('+').unwrap_or(spec);+ if let Some((src, dst)) = spec.split_once(':')+ && dst.starts_with("refs/remotes/")+ && refspec_side_matches(src, refname)+ {+ tracked = true;+ }+ }+ tracked+}++/// Match `refname` against one side of a refspec, where a single `*` matches+/// any run of characters, `/` included.+fn refspec_side_matches(pattern: &str, refname: &str) -> bool {+ match pattern.split_once('*') {+ Some((prefix, suffix)) => {+ refname.len() >= prefix.len() + suffix.len()+ && refname.starts_with(prefix)+ && refname.ends_with(suffix)+ }+ None => pattern == refname,+ }+}+#[cfg(test)]mod tests {use crate::testing::TestRepo;+ #[test]+ fn refspecs_track_ref_follows_the_fetch_mapping() {+ let track = |specs: &[&str], refname: &str| {+ let specs: Vec<String> = specs.iter().map(|s| s.to_string()).collect();+ super::refspecs_track_ref(&specs, refname)+ };+ let full = "+refs/heads/*:refs/remotes/origin/*";+ assert!(track(&[full], "refs/heads/feature"));+ assert!(track(&[full], "refs/heads/nested/feature"));+ // `--single-branch` / `--depth` clone: only the cloned branch.+ let single = "+refs/heads/main:refs/remotes/origin/main";+ assert!(track(&[single], "refs/heads/main"));+ assert!(!track(&[single], "refs/heads/feature"));+ // A mapping outside `refs/remotes/` records no remote-tracking ref.+ assert!(!track(+ &["+refs/heads/*:refs/heads/*"],+ "refs/heads/feature"+ ));+ // A negative refspec excludes what a positive one would map.+ assert!(!track(&[full, "^refs/heads/wip/*"], "refs/heads/wip/x"));+ assert!(track(&[full, "^refs/heads/wip/*"], "refs/heads/feature"));+ assert!(!track(&[], "refs/heads/feature"));+ }+#[test]fn test_find_remote_for_azure_dev_azure() {let t = TestRepo::new();diff --git a/tests/integration_tests/ci_status.rs b/tests/integration_tests/ci_status.rsindex 142dc3184..da97bfb69 100644--- a/tests/integration_tests/ci_status.rs+++ b/tests/integration_tests/ci_status.rs@@ -700,6 +700,72 @@ fn test_gitlab_project_id_resolved_once_per_command(mut repo: TestRepo) {);}+/// A PR's head is a branch on the forge, so a never-pushed local branch can't+/// head one and costs no `gh pr list`. A missing `refs/remotes/` copy shows a+/// branch was never pushed only where a push would have recorded one: a URL+/// push remote (a fork's PR checked out with `gh pr checkout`) records nothing,+/// and a single-branch clone's remote records only the branch it cloned, so+/// branches pushing to either are still asked about. Assert the spawns, not+/// the rendering: an unpushed branch shows no CI either way.+#[rstest]+fn test_pr_lookup_skips_branches_on_no_remote(mut repo: TestRepo) {+ setup_github_repo_with_feature(&mut repo);+ repo.add_worktree("local-only");+ repo.add_worktree("fork-pr");+ repo.run_git(&[+ "config",+ "branch.fork-pr.pushremote",+ "https://github.com/fork-owner/test-repo.git",+ ]);+ // A remote fetched the way `git clone --single-branch` sets it up.+ repo.add_worktree("narrow-pushed");+ repo.run_git(&[+ "remote",+ "add",+ "-t",+ "main",+ "narrow",+ "https://github.com/test-owner/test-repo.git",+ ]);+ repo.run_git(&["config", "branch.narrow-pushed.pushremote", "narrow"]);+ repo.setup_mock_gh_with_ci_data("[]");++ let call_log = tempfile::tempdir().unwrap();+ let mut cmd = repo.wt_command();+ cmd.args(["list", "--full"]);+ repo.configure_mock_commands(&mut cmd);+ cmd.env("WORKTRUNK_TEST_MOCK_CALL_LOG_DIR", call_log.path());+ let output = cmd.output().unwrap();+ assert!(+ output.status.success(),+ "wt list --full should succeed: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ let calls = mock_calls(call_log.path(), "gh");+ let asked = |branch: &str| {+ calls+ .iter()+ .any(|call| call.starts_with(&format!("pr list --head {branch} ")))+ };+ assert!(+ asked("feature"),+ "a pushed branch is asked about. calls: {calls:#?}"+ );+ assert!(+ asked("fork-pr"),+ "a URL push remote is asked about. calls: {calls:#?}"+ );+ assert!(+ asked("narrow-pushed"),+ "a push remote that records no refs for the branch is asked about. calls: {calls:#?}"+ );+ assert!(+ !asked("local-only"),+ "a never-pushed branch is skipped. calls: {calls:#?}"+ );+}+// =============================================================================// GitLab project ID edge cases (PR #846 panic prevention)// =============================================================================diff --git a/tests/snapshots/integration__integration_tests__help__help_list_long.snap b/tests/snapshots/integration__integration_tests__help__help_list_long.snapindex 4f803f490..a04be9900 100644--- a/tests/snapshots/integration__integration_tests__help__help_list_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_list_long.snap@@ -188,7 +188,7 @@ The CI column shows the branch's open PR/MR — [2m#3035[0m on GitHub, Gitea,[33m⚠[0m yellow [2m"error"[0m CI status could not be fetched (rate limit, network, etc.)[35m#[0m magenta [2m"changes_requested"[0m A reviewer requested changes[36m#[0m cyan [2m"pending"[0m A review is required (e.g. branch protection) but not yet given- (blank) [2mpr[0m and [2mchecks[0m absent No upstream, or no PR/MR and no branch workflow+ (blank) [2mpr[0m and [2mchecks[0m absent Branch never pushed, or no PR/MR and no branch workflowThe two remaining review states have no indicator of their own: [2m"draft"[0m only dims the cell and [2m"approved"[0m leaves the color unchanged.diff --git a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snapindex 57c6edb89..cc45cc79b 100644--- a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap+++ b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap@@ -214,7 +214,8 @@ checks object and review states give the JSON form of each value:[35m#[0m magenta [2m"changes_requested"[0m A reviewer requested changes[36m#[0m cyan [2m"pending"[0m A review is required (e.g. branch protection)but not yet given- (blank) [2mpr[0m and [2mchecks[0m absent No upstream, or no PR/MR and no branch workflow+ (blank) [2mpr[0m and [2mchecks[0m absent Branch never pushed, or no PR/MR and no branch+ workflowThe two remaining review states have no indicator of their own: [2m"draft"[0m onlydims the cell and [2m"approved"[0m leaves the color unchanged.