Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Fall back to effective URL for forge detection with url.insteadOf (#1771)
Santi Chaustrec3c16253642b
diff --git a/src/commands/list/ci_status/github.rs b/src/commands/list/ci_status/github.rsindex dd0e40016..94245e1f0 100644--- a/src/commands/list/ci_status/github.rs+++ b/src/commands/list/ci_status/github.rs@@ -14,15 +14,13 @@ use super::{////// Used for GitHub API calls that require `repos/{owner}/{repo}/...` paths./// Searches all remotes for a GitHub URL (API calls are repo-wide, not branch-specific).+///+/// Uses [`Repository::find_forge_remote`] with effective URLs to handle+/// `url.insteadOf` aliases.fn github_owner_repo(repo: &Repository) -> Option<(String, String)> {- for (_, url) in repo.all_remote_urls() {- if let Some(parsed) = GitRemoteUrl::parse(&url)- && parsed.is_github()- {- return Some((parsed.owner().to_string(), parsed.repo().to_string()));- }- }- None+ let (_, url) = repo.find_forge_remote(|parsed| parsed.is_github())?;+ let parsed = GitRemoteUrl::parse(&url)?;+ Some((parsed.owner().to_string(), parsed.repo().to_string()))}/// Detect GitHub PR CI status for a branch.@@ -52,10 +50,10 @@ pub(super) fn detect_github(// Get the owner of the branch's push remote for filtering PRs by source repository.// For local branches: uses @{push} which resolves through pushRemote → remote.pushDefault → tracking remote.- // For remote branches: use the remote's URL directly (the branch IS on that remote).+ // For remote branches: use the remote's effective URL (handles insteadOf aliases).let branch_owner = if let Some(remote_name) = &branch.remote {- // Remote branch - get owner from the remote's URL- repo.remote_url(remote_name)+ // Remote branch - get owner from the remote's effective URL+ repo.effective_remote_url(remote_name).and_then(|url| parse_remote_owner(&url))} else {// Local branch - use existing push remote resolutiondiff --git a/src/commands/list/ci_status/platform.rs b/src/commands/list/ci_status/platform.rsindex 74d8d6197..5dea0d5df 100644--- a/src/commands/list/ci_status/platform.rs+++ b/src/commands/list/ci_status/platform.rs@@ -140,9 +140,10 @@ pub fn platform_for_repo();}- // If we have a specific remote hint (e.g., from a remote branch), use that first+ // If we have a specific remote hint (e.g., from a remote branch), use that first.+ // Uses effective URL to handle url.insteadOf aliases.if let Some(remote_name) = remote_hint- && let Some(url) = repo.remote_url(remote_name)+ && let Some(url) = repo.effective_remote_url(remote_name)&& let Some(platform) = detect_platform_from_url(&url){log::debug!(@@ -153,16 +154,18 @@ pub fn platform_for_repo(return Some(platform);}- // Search all remotes for a supported platform- for (remote_name, url) in repo.all_remote_urls() {- if let Some(platform) = detect_platform_from_url(&url) {- log::debug!(- "Detected CI platform {} from remote '{}'",- platform,- remote_name- );- return Some(platform);- }+ // Search all remotes for a supported platform.+ // Uses find_forge_remote which checks effective URLs (with insteadOf applied).+ if let Some((remote_name, url)) =+ repo.find_forge_remote(|parsed| parsed.is_github() || parsed.is_gitlab())+ {+ let platform = detect_platform_from_url(&url)?;+ log::debug!(+ "Detected CI platform {} from remote '{}'",+ platform,+ remote_name+ );+ return Some(platform);}Nonediff --git a/src/git/remote_ref/github.rs b/src/git/remote_ref/github.rsindex 9776fb069..83e108313 100644--- a/src/git/remote_ref/github.rs+++ b/src/git/remote_ref/github.rs@@ -80,9 +80,13 @@ fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefIlet repo_root = repo.repo_path()?;// Best-effort hostname extraction for GitHub Enterprise support.+ // Uses effective URL (with url.insteadOf applied) to handle custom SSH+ // hostnames (e.g., github-work → github.com for multi-key SSH setups).// Falls back to gh's default (github.com) if the remote URL can't be parsed.let hostname = repo- .primary_remote_url()+ .primary_remote()+ .ok()+ .and_then(|remote| repo.effective_remote_url(&remote)).and_then(|url| git::GitRemoteUrl::parse(&url)).map(|parsed| parsed.host().to_string()).unwrap_or_else(|| "github.com".to_string());diff --git a/src/git/repository/branch.rs b/src/git/repository/branch.rsindex be9bd150b..02c331c46 100644--- a/src/git/repository/branch.rs+++ b/src/git/repository/branch.rs@@ -148,8 +148,9 @@ impl<'a> Branch<'a> {////// 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.- pub fn push_remote_url(&self) -> Option<String> {+ fn push_remote_url(&self) -> Option<String> {// %(push:remotename) returns either a remote name or URL directly// Unlike @{push}, this doesn't fail when pushremote is a URLlet push_remote = self@@ -167,15 +168,19 @@ impl<'a> Branch<'a> {if push_remote.contains("://") || push_remote.starts_with("git@") {Some(push_remote)} else {- // It's a remote name, look up its URL- self.repo.remote_url(&push_remote)+ // It's a remote name — use effective URL (handles insteadOf)+ self.repo.effective_remote_url(&push_remote)}}/// Get the GitHub URL for this branch's push remote, if it's a GitHub URL.////// Returns the push remote URL if configured and pointing to GitHub,- /// otherwise returns `None`.+ /// otherwise returns `None`. Handles `url.insteadOf` aliases via+ /// `effective_remote_url` (cached).+ ///+ /// Handles both remote-name and URL-based pushremotes (the latter is set by+ /// `gh pr checkout` for fork PRs).pub fn github_push_url(&self) -> Option<String> {let url = self.push_remote_url()?;let parsed = GitRemoteUrl::parse(&url)?;diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 8119194d5..256707599 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -127,6 +127,9 @@ pub(super) struct RepoCache {/// Batch ahead/behind cache: (base_ref, branch_name) -> (ahead, behind)/// Populated by batch_ahead_behind(), used by cached_ahead_behind()pub(super) ahead_behind: DashMap<(String, String), (usize, usize)>,+ /// Effective remote URLs: remote_name -> effective URL (with `url.insteadOf` applied).+ /// Cached because forge detection may query the same remote multiple times.+ pub(super) effective_remote_urls: DashMap<String, Option<String>>,// ========== Per-worktree values (keyed by path) ==========/// Worktree root paths: worktree_path -> canonicalized rootdiff --git a/src/git/repository/remotes.rs b/src/git/repository/remotes.rsindex 963deb4a3..13955f24b 100644--- a/src/git/repository/remotes.rs+++ b/src/git/repository/remotes.rs@@ -1,4 +1,29 @@//! Remote and URL operations for Repository.+//!+//! # Forge resolution and `url.insteadOf`+//!+//! Worktrunk needs to identify the forge (GitHub, GitLab) behind a remote URL+//! for PR status, API calls, and push-remote detection. This is straightforward+//! when the raw URL contains a recognized hostname (`github.com`, `gitlab.com`,+//! etc.), but breaks when users configure `url.insteadOf` for multi-key SSH+//! setups — the raw URL may contain a custom hostname like `github-work`.+//!+//! All forge-aware lookups use [`effective_remote_url`](Repository::effective_remote_url),+//! which runs `git remote get-url <name>` to get the URL with `url.insteadOf`+//! rewrites applied. This is a local operation (no network I/O). Results are+//! cached per-remote in [`RepoCache`](super::RepoCache), so repeated lookups+//! for the same remote cost nothing after the first call.+//!+//! When no `insteadOf` rules are configured, the effective URL equals the raw+//! config URL — there is no behavioral difference.+//!+//! ## URL methods+//!+//! - `remote_url` — raw config value, no rewriting (for non-forge uses like+//! template variables and project identifiers)+//! - `effective_remote_url` — `git remote get-url`, with `insteadOf` applied+//! (cached; use for all forge detection)+//! - `find_forge_remote(pred)` — search all remotes using effective URLsuse anyhow::Context;@@ -58,6 +83,10 @@ impl Repository {}/// Get the URL for a remote, if configured.+ ///+ /// Returns the raw value from `.git/config` without applying `url.insteadOf`+ /// rewrites. Use [`effective_remote_url`](Self::effective_remote_url) when you+ /// need forge detection to work with `insteadOf` aliases.pub fn remote_url(&self, remote: &str) -> Option<String> {self.run_command(&["config", &format!("remote.{}.url", remote)]).ok()@@ -65,10 +94,35 @@ impl Repository {.filter(|url| !url.is_empty())}+ /// Get the effective URL for a remote, with `url.insteadOf` rewrites applied.+ ///+ /// Uses `git remote get-url` which applies `url.insteadOf` rewrites. When no+ /// rewrite rules are configured, returns the same value as [`remote_url`](Self::remote_url).+ ///+ /// Results are cached per-remote in the shared repo cache.+ ///+ /// Returns `None` if the remote doesn't exist or has no URL.+ pub fn effective_remote_url(&self, remote: &str) -> Option<String> {+ self.cache+ .effective_remote_urls+ .entry(remote.to_string())+ .or_insert_with(|| {+ self.run_command(&["remote", "get-url", remote])+ .ok()+ .map(|url| url.trim().to_string())+ .filter(|url| !url.is_empty())+ })+ .clone()+ }+/// Find a remote that points to a specific owner/repo.////// Searches all configured remotes and returns the name of the first one- /// whose URL matches the given owner and repo (case-insensitive).+ /// whose URL matches the given owner and repo (case-insensitive). Checks+ /// both the raw config URL and the effective URL (with `url.insteadOf`+ /// rewrites applied), so matches work in both directions: when the raw URL+ /// contains a real forge hostname, and when `insteadOf` rewrites a custom+ /// hostname to a real forge.////// When `host` is `Some`, the remote must also match the host. This is/// important for multi-host setups (e.g., both github.com and@@ -81,23 +135,24 @@ impl Repository {owner: &str,repo: &str,) -> Option<String> {- // Get all remotes with URLs- let output = self- .run_command(&["config", "--get-regexp", r"remote\..+\.url"])- .ok()?;-- for line in output.lines() {- // Parse "remote.<name>.url <value>" format- if let Some(rest) = line.strip_prefix("remote.")- && let Some((name, url)) = rest.split_once(".url ")- && let Some(parsed) = GitRemoteUrl::parse(url)- // Case-insensitive comparison (GitHub owner/repo names are case-insensitive)- && parsed.owner().eq_ignore_ascii_case(owner)+ let matches = |url: &str| -> bool {+ let Some(parsed) = GitRemoteUrl::parse(url) else {+ return false;+ };+ parsed.owner().eq_ignore_ascii_case(owner)&& parsed.repo().eq_ignore_ascii_case(repo)- // If host is specified, it must also match (case-insensitive)&& host.is_none_or(|h| parsed.host().eq_ignore_ascii_case(h))+ };++ for (remote_name, raw_url) in self.all_remote_urls() {+ if matches(&raw_url) {+ return Some(remote_name);+ }+ if let Some(effective_url) = self.effective_remote_url(&remote_name)+ && effective_url != raw_url+ && matches(&effective_url){- return Some(name.to_string());+ return Some(remote_name);}}@@ -141,7 +196,7 @@ impl Repository {/// Get the URL for the primary remote, if configured.///- /// Result is cached in the repository's shared cache (same for all clones).+ /// Returns the raw config value. Result is cached in the shared repo cache.pub fn primary_remote_url(&self) -> Option<String> {self.cache.primary_remote_url@@ -153,6 +208,27 @@ impl Repository {.clone()}+ /// Search all remotes for a URL matching a predicate.+ ///+ /// Uses effective URLs (with `url.insteadOf` rewrites applied) so that+ /// custom SSH hostnames resolve to real forge hostnames.+ ///+ /// Returns the first matching `(remote_name, url)` pair, or `None`.+ pub fn find_forge_remote<F>(&self, predicate: F) -> Option<(String, String)>+ where+ F: Fn(&GitRemoteUrl) -> bool,+ {+ for (remote_name, _) in self.all_remote_urls() {+ if let Some(url) = self.effective_remote_url(&remote_name)+ && let Some(parsed) = GitRemoteUrl::parse(&url)+ && predicate(&parsed)+ {+ return Some((remote_name, url));+ }+ }+ None+ }+/// Get a project identifier for approval tracking.////// Uses the git remote URL if available (e.g., "github.com/user/repo"),diff --git a/tests/integration_tests/default_branch.rs b/tests/integration_tests/default_branch.rsindex da6789bb6..0c3fc9cb6 100644--- a/tests/integration_tests/default_branch.rs+++ b/tests/integration_tests/default_branch.rs@@ -1,6 +1,6 @@use crate::common::{TestRepo, repo, repo_with_remote};use rstest::rstest;-use worktrunk::git::Repository;+use worktrunk::git::{GitRemoteUrl, Repository};#[rstest]fn test_get_default_branch_with_origin_head(#[from(repo_with_remote)] repo: TestRepo) {@@ -305,3 +305,292 @@ fn test_resolve_caret_fails_when_default_branch_unavailable(repo: TestRepo) {err_msg);}++// --- Forge URL resolution helpers ---++/// Configure a remote with a custom hostname and an insteadOf rewrite to a real forge.+///+/// Simulates the multi-key SSH pattern: custom host in .git/config, real forge via insteadOf.+fn setup_insteadof(repo: &TestRepo, remote: &str, custom_url: &str, real_prefix: &str) {+ // Extract the org prefix from the custom URL for the insteadOf mapping+ let custom_prefix = custom_url+ .rsplit_once('/')+ .map(|(p, _)| p)+ .unwrap_or(custom_url);+ repo.run_git(&["config", &format!("remote.{remote}.url"), custom_url]);+ repo.run_git(&[+ "config",+ &format!("url.{real_prefix}.insteadOf"),+ custom_prefix,+ ]);+}++/// Set up push tracking so `branch.push_remote()` and `github_push_url()` work.+fn setup_push_tracking(repo: &TestRepo, branch: &str, remote: &str) {+ repo.run_git(&["config", &format!("branch.{branch}.remote"), remote]);+ repo.run_git(&[+ "config",+ &format!("branch.{branch}.merge"),+ &format!("refs/heads/{branch}"),+ ]);+ repo.run_git(&[+ "update-ref",+ &format!("refs/remotes/{remote}/{branch}"),+ branch,+ ]);+}++/// Test effective_remote_url: insteadOf resolves custom hostname to real forge.+#[rstest]+fn test_effective_remote_url_insteadof(repo: TestRepo) {+ setup_insteadof(+ &repo,+ "origin",+ "git@work-ssh:org/repo.git",+ "[email protected]:org",+ );++ let git_repo = Repository::at(repo.root_path()).unwrap();++ // Raw URL has the custom hostname+ assert_eq!(+ git_repo.remote_url("origin").unwrap(),+ "git@work-ssh:org/repo.git"+ );+ // Effective URL has the real forge hostname+ let effective = git_repo.effective_remote_url("origin").unwrap();+ assert_eq!(effective, "[email protected]:org/repo.git");++ let parsed = GitRemoteUrl::parse(&effective).unwrap();+ assert!(parsed.is_github());+ assert_eq!(parsed.host(), "github.com");+ assert_eq!(parsed.owner(), "org");+ assert_eq!(parsed.repo(), "repo");+}++/// Test effective_remote_url: matches raw URL when no insteadOf is configured.+#[rstest]+fn test_effective_remote_url_without_insteadof(repo: TestRepo) {+ let git_repo = Repository::at(repo.root_path()).unwrap();+ assert_eq!(+ git_repo.remote_url("origin").unwrap(),+ git_repo.effective_remote_url("origin").unwrap()+ );+}++/// Test effective_remote_url: returns None for nonexistent remote.+#[rstest]+fn test_effective_remote_url_nonexistent_remote(repo: TestRepo) {+ let git_repo = Repository::at(repo.root_path()).unwrap();+ assert!(git_repo.effective_remote_url("nonexistent").is_none());+}++/// Test effective_remote_url: result is cached (same value on repeated calls).+#[rstest]+fn test_effective_remote_url_is_cached(repo: TestRepo) {+ let git_repo = Repository::at(repo.root_path()).unwrap();+ let first = git_repo.effective_remote_url("origin");+ let second = git_repo.effective_remote_url("origin");+ assert_eq!(first, second);+}++/// Test find_forge_remote: finds forge via effective URL with insteadOf.+#[rstest]+fn test_find_forge_remote_insteadof(repo: TestRepo) {+ setup_insteadof(+ &repo,+ "origin",+ "git@work-ssh:org/repo.git",+ "[email protected]:org",+ );++ let git_repo = Repository::at(repo.root_path()).unwrap();++ let (remote_name, url) = git_repo+ .find_forge_remote(|parsed| parsed.is_github())+ .expect("Should find GitHub via insteadOf");+ assert_eq!(remote_name, "origin");+ assert_eq!(GitRemoteUrl::parse(&url).unwrap().host(), "github.com");++ assert!(+ git_repo+ .find_forge_remote(|parsed| parsed.is_gitlab())+ .is_none(),+ "Should not find GitLab"+ );+}++/// Test find_forge_remote: matches when URL already has known forge hostname.+#[rstest]+fn test_find_forge_remote_known_forge(repo: TestRepo) {+ repo.run_git(&["config", "remote.origin.url", "[email protected]:org/repo.git"]);++ let git_repo = Repository::at(repo.root_path()).unwrap();+ let (name, url) = git_repo+ .find_forge_remote(|parsed| parsed.is_github())+ .expect("Should find GitHub");+ assert_eq!(name, "origin");+ assert_eq!(url, "[email protected]:org/repo.git");+}++/// Test find_forge_remote: returns None when no remotes are configured.+#[rstest]+fn test_find_forge_remote_no_remotes(repo: TestRepo) {+ repo.run_git(&["remote", "remove", "origin"]);++ let git_repo = Repository::at(repo.root_path()).unwrap();+ assert!(git_repo.find_forge_remote(|p| p.is_github()).is_none());+}++/// Test find_remote_for_repo: resolves through insteadOf to match owner/repo.+#[rstest]+fn test_find_remote_for_repo_insteadof(repo: TestRepo) {+ setup_insteadof(+ &repo,+ "origin",+ "git@work-ssh:org/repo.git",+ "[email protected]:org",+ );++ let git_repo = Repository::at(repo.root_path()).unwrap();++ // Raw URL has custom hostname — find_remote_for_repo should match via the+ // effective URL (github.com), which reveals the real forge after insteadOf+ let found = git_repo.find_remote_for_repo(Some("github.com"), "org", "repo");+ assert_eq!(found.as_deref(), Some("origin"));+}++/// Test find_remote_for_repo: case-insensitive matching works with insteadOf.+#[rstest]+fn test_find_remote_for_repo_insteadof_case_insensitive(repo: TestRepo) {+ setup_insteadof(+ &repo,+ "origin",+ "git@work-ssh:MyOrg/MyRepo.git",+ "[email protected]:MyOrg",+ );++ let git_repo = Repository::at(repo.root_path()).unwrap();+ let found = git_repo.find_remote_for_repo(Some("github.com"), "myorg", "myrepo");+ assert_eq!(found.as_deref(), Some("origin"));+}++/// Test find_remote_for_repo: matches without host constraint via insteadOf.+#[rstest]+fn test_find_remote_for_repo_insteadof_no_host(repo: TestRepo) {+ setup_insteadof(+ &repo,+ "origin",+ "git@work-ssh:org/repo.git",+ "[email protected]:org",+ );++ let git_repo = Repository::at(repo.root_path()).unwrap();+ // host=None should match any forge host+ let found = git_repo.find_remote_for_repo(None, "org", "repo");+ assert_eq!(found.as_deref(), Some("origin"));+}++/// Test find_remote_for_repo: picks the correct remote among multiple with insteadOf.+#[rstest]+fn test_find_remote_for_repo_insteadof_multiple_remotes(repo: TestRepo) {+ // origin → github.com:org/repo via insteadOf+ setup_insteadof(+ &repo,+ "origin",+ "git@work-ssh:org/repo.git",+ "[email protected]:org",+ );+ // upstream → github.com:upstream-org/repo via insteadOf+ repo.run_git(&[+ "config",+ "remote.upstream.url",+ "git@work-ssh-2:upstream-org/repo.git",+ ]);+ repo.run_git(&[+ "config",+ "[email protected]:upstream-org.insteadOf",+ "git@work-ssh-2:upstream-org",+ ]);++ let git_repo = Repository::at(repo.root_path()).unwrap();+ assert_eq!(+ git_repo+ .find_remote_for_repo(Some("github.com"), "upstream-org", "repo")+ .as_deref(),+ Some("upstream")+ );+ assert_eq!(+ git_repo+ .find_remote_for_repo(Some("github.com"), "org", "repo")+ .as_deref(),+ Some("origin")+ );+}++/// Test find_remote_by_url: resolves through insteadOf.+#[rstest]+fn test_find_remote_by_url_insteadof(repo: TestRepo) {+ setup_insteadof(+ &repo,+ "origin",+ "git@work-ssh:org/repo.git",+ "[email protected]:org",+ );++ let git_repo = Repository::at(repo.root_path()).unwrap();++ // target_url uses the real forge hostname (as API responses would)+ let found = git_repo.find_remote_by_url("[email protected]:org/repo.git");+ assert_eq!(found.as_deref(), Some("origin"));++ // HTTPS variant should also match+ let found = git_repo.find_remote_by_url("https://github.com/org/repo.git");+ assert_eq!(found.as_deref(), Some("origin"));+}++/// Test github_push_url: resolves through insteadOf on push remote.+#[rstest]+fn test_github_push_url_insteadof_fallback(repo: TestRepo) {+ setup_insteadof(+ &repo,+ "origin",+ "git@work-ssh:org/repo.git",+ "[email protected]:org",+ );+ setup_push_tracking(&repo, "main", "origin");++ let git_repo = Repository::at(repo.root_path()).unwrap();+ let url = git_repo+ .branch("main")+ .github_push_url()+ .expect("github_push_url should resolve via insteadOf");+ let parsed = GitRemoteUrl::parse(&url).unwrap();+ assert!(parsed.is_github());+ assert_eq!(parsed.host(), "github.com");+}++/// Test github_push_url: returns None for non-GitHub forge (GitLab).+#[rstest]+fn test_github_push_url_non_github_forge_returns_none(repo: TestRepo) {+ repo.run_git(&["config", "remote.origin.url", "[email protected]:org/repo.git"]);+ setup_push_tracking(&repo, "main", "origin");++ let git_repo = Repository::at(repo.root_path()).unwrap();+ assert!(git_repo.branch("main").github_push_url().is_none());+}++/// Test github_push_url: returns None when insteadOf resolves to GitLab (not GitHub).+#[rstest]+fn test_github_push_url_unknown_host_non_github_insteadof(repo: TestRepo) {+ setup_insteadof(+ &repo,+ "origin",+ "git@work-ssh:org/repo.git",+ "[email protected]:org",+ );+ setup_push_tracking(&repo, "main", "origin");++ let git_repo = Repository::at(repo.root_path()).unwrap();+ assert!(git_repo.branch("main").github_push_url().is_none());+}