Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Consolidate remote-ref forge dispatch (#3963)
Maximilian Roosf483ae5735f0
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex c5837895c..aff2ee25c 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -16,13 +16,10 @@ use worktrunk::config::{UserConfig, ValidationScope, VarScope, referenced_vars_for_templates, template_references_var,validate_template,};-use worktrunk::git::remote_ref::{- self, AzureDevOpsProvider, GitHubProvider, GitLabProvider, GiteaProvider, RemoteRefInfo,- RemoteRefProvider, parse_ref_url,-};+use worktrunk::git::remote_ref::{self, RemoteRefInfo, parse_ref_url};use worktrunk::git::{ForgeKind, GitError, GitRemoteUrl, RefType, Repository, ResolvedWorktree, Selector,- SwitchSuggestionCtx, WorktreeId, current_or_recover,+ SwitchSuggestionCtx, WorktreeId, branch_tracks_ref, current_or_recover,};use worktrunk::shell_exec::{ShellEscapeMode, directive_shell_escape_mode, shell_cwd, shell_escape_for,@@ -83,10 +80,6 @@ impl ResolvedTarget {}}-static GITHUB_PROVIDER: GitHubProvider = GitHubProvider;-static GITEA_PROVIDER: GiteaProvider = GiteaProvider;-static AZURE_DEVOPS_PROVIDER: AzureDevOpsProvider = AzureDevOpsProvider;-/// Format PR/MR context for gutter display after fetching.////// Returns two lines for gutter formatting:@@ -111,7 +104,7 @@ fn format_ref_context(info: &RemoteRefInfo) -> String {)}-/// Choose which provider should handle `pr:<number>` resolution.+/// Choose which forge should handle `pr:<number>` resolution.////// Priority:/// 1. The configured `forge.platform` (`github` / `gitea` / `azure-devops`) —@@ -125,17 +118,14 @@ fn format_ref_context(info: &RemoteRefInfo) -> String {////// The default-to-GitHub fall-through means a self-hosted Gitea on a branded/// host (e.g. `git.example.com`) without `tea login add` will see a single-/// GitHub error (with hint to set `forge.platform = "gitea"`), instead of a-/// wrapped two-provider error.-fn choose_pr_provider(repo: &Repository) -> anyhow::Result<&'static dyn RemoteRefProvider> {+/// GitHub error with a hint to set `forge.platform = "gitea"`.+fn choose_pr_forge(repo: &Repository) -> anyhow::Result<ForgeKind> {if let Some(platform_raw) = repo.configured_forge_platform() {match platform_raw.to_ascii_lowercase().parse::<ForgeKind>() {- Ok(ForgeKind::GitHub) => return Ok(&GITHUB_PROVIDER),- Ok(ForgeKind::Gitea) => return Ok(&GITEA_PROVIDER),- Ok(ForgeKind::AzureDevOps) => return Ok(&AZURE_DEVOPS_PROVIDER),Ok(ForgeKind::GitLab) => {bail!("forge.platform is set to gitlab; use mr:<number> instead of pr:<number>")}+ Ok(platform) => return Ok(platform),Err(_) => bail!("Invalid forge.platform value `{platform_raw}` (from `[forge]` in project \config or a `[projects]` entry in user config); \@@ -155,13 +145,13 @@ fn choose_pr_provider(repo: &Repository) -> anyhow::Result<&'static dyn RemoteRelet has_forge = |forge| all_parsed.iter().any(|url| url.forge_kind() == Some(forge));if has_forge(ForgeKind::GitHub) {- return Ok(&GITHUB_PROVIDER);+ return Ok(ForgeKind::GitHub);}if has_forge(ForgeKind::Gitea) {- return Ok(&GITEA_PROVIDER);+ return Ok(ForgeKind::Gitea);}if has_forge(ForgeKind::AzureDevOps) {- return Ok(&AZURE_DEVOPS_PROVIDER);+ return Ok(ForgeKind::AzureDevOps);}if has_forge(ForgeKind::GitLab) {bail!("Detected GitLab remote; use mr:<number> instead of pr:<number>")@@ -179,52 +169,52 @@ fn choose_pr_provider(repo: &Repository) -> anyhow::Result<&'static dyn RemoteRe.and_then(|url| GitRemoteUrl::parse(&url)).map(|u| u.host().to_string())else {- return Ok(&GITHUB_PROVIDER);+ return Ok(ForgeKind::GitHub);};if remote_ref::gitea::is_authed_for(&host) && !remote_ref::github::is_authed_for(&host) {- Ok(&GITEA_PROVIDER)+ Ok(ForgeKind::Gitea)} else {- Ok(&GITHUB_PROVIDER)+ Ok(ForgeKind::GitHub)}}/// Fetch PR/MR info while showing a "still waiting" status.///-/// The host lookup (`gh`/`glab` API) captures its output and can stall on a slow-/// network, so without feedback the command looks frozen. The watchdog clears+/// The forge CLI captures its output and can stall on a slow network, so+/// without feedback the command looks frozen. The watchdog clears/// before the caller prints the resolved ref context. No command gutter — the/// host CLI invocation isn't readily available here, and the status line alone/// is the signal.fn fetch_ref_info(- provider: &dyn RemoteRefProvider,+ forge: ForgeKind,number: u32,repo: &Repository,) -> anyhow::Result<RemoteRefInfo> {let _watchdog = worktrunk::progress::Watchdog::start(- &format!("the {} lookup", provider.ref_type().name()),+ &format!("the {} lookup", forge.ref_type().name()),None,);- provider.fetch_info(number, repo)+ remote_ref::fetch_info(forge, number, repo)}-/// Resolve a remote ref (PR or MR) using the unified provider interface.+/// Resolve a remote ref (PR or MR) through the selected forge.fn resolve_remote_ref(repo: &Repository,- provider: &dyn RemoteRefProvider,+ forge: ForgeKind,number: u32,create: bool,) -> anyhow::Result<ResolvedTarget> {- let ref_type = provider.ref_type();+ let ref_type = forge.ref_type();let symbol = ref_type.symbol();- // Fetch ref info (network call via gh/glab CLI)+ // Fetch ref info through the forge CLI.eprintln!("{}",progress_message(cformat!("Fetching {} {symbol}{number}...", ref_type.name())));- let info = fetch_ref_info(provider, number, repo)?;+ let info = fetch_ref_info(forge, number, repo)?;// Display context with URL (as gutter under fetch progress)eprintln!("{}", format_with_gutter(&format_ref_context(&info), None));@@ -240,7 +230,7 @@ fn resolve_remote_ref(}let target = if info.is_cross_repo {- resolve_fork_ref(repo, provider, number, &info)?+ resolve_fork_ref(repo, forge, number, &info)?} else {// Same-repo ref: fetch the branch to ensure remote tracking refs existfetch_same_repo_branch(repo, &info)?;@@ -265,13 +255,14 @@ fn resolve_remote_ref(/// Resolve a fork (cross-repo) PR/MR.fn resolve_fork_ref(repo: &Repository,- provider: &dyn RemoteRefProvider,+ forge: ForgeKind,number: u32,info: &RemoteRefInfo,) -> anyhow::Result<ResolvedTarget> {- let ref_type = provider.ref_type();+ let ref_type = forge.ref_type();let repo_root = repo.repo_path()?;let local_branch = info.source_branch.clone();+ let tracking_ref = remote_ref::tracking_ref(forge, number);let expected_remote = match remote_ref::find_remote(repo, info) {Ok(remote) => Some(remote),Err(e) => {@@ -281,11 +272,10 @@ fn resolve_fork_ref(};// Check if branch already exists and is tracking this ref- if let Some(tracks_this) = remote_ref::branch_tracks_ref(+ if let Some(tracks_this) = branch_tracks_ref(repo_root,&local_branch,- provider,- number,+ &tracking_ref,expected_remote.as_deref(),) {if tracks_this {@@ -308,11 +298,10 @@ fn resolve_fork_ref(// Branch exists but doesn't track this ref - try prefixed name (GitHub/Gitea)if let Some(prefixed) = info.prefixed_local_branch_name() {- if let Some(prefixed_tracks) = remote_ref::branch_tracks_ref(+ if let Some(prefixed_tracks) = branch_tracks_ref(repo_root,&prefixed,- provider,- number,+ &tracking_ref,expected_remote.as_deref(),) {if prefixed_tracks {@@ -341,22 +330,22 @@ fn resolve_fork_ref(.into());}- // Use prefixed branch name; push won't work (None for fork_push_url)- // This is GitHub-only (GitLab doesn't support prefixed names)+ // GitHub and Gitea support prefixed branch names. This path has no+ // fork push URL, so the branch remains fetch-only.let remote = remote_ref::find_remote(repo, info)?;return Ok(ResolvedTarget::new(Selector::rewritten_to(prefixed),CreationMethod::ForkRef {ref_type,number,- ref_path: provider.ref_path(number),+ ref_path: remote_ref::ref_path(forge, number),fork_push_url: None,remote,},));}- // GitLab doesn't support prefixed branch names - error+ // GitLab and Azure DevOps don't support prefixed branch names.return Err(GitError::BranchTracksDifferentRef {branch: local_branch,ref_type,@@ -369,7 +358,7 @@ fn resolve_fork_ref(// Resolve remote and URLs based on platform.let (fork_push_url, remote) = match ref_type {RefType::Pr => {- // GitHub: URLs already in info, just find remote.+ // PR backends include fork URLs in the initial response.let remote = remote_ref::find_remote(repo, info)?;(info.fork_push_url.clone(), remote)}@@ -410,7 +399,7 @@ fn resolve_fork_ref(CreationMethod::ForkRef {ref_type,number,- ref_path: provider.ref_path(number),+ ref_path: remote_ref::ref_path(forge, number),fork_push_url,remote,},@@ -478,11 +467,11 @@ fn resolve_base_ref(base: &str,) -> anyhow::Result<(String, Option<(String, String)>)> {if let Some((ref_type, number)) = parse_ref_shortcut(base) {- let provider: &dyn RemoteRefProvider = match ref_type {- RefType::Pr => choose_pr_provider(repo)?,- RefType::Mr => &GitLabProvider,+ let forge = match ref_type {+ RefType::Pr => choose_pr_forge(repo)?,+ RefType::Mr => ForgeKind::GitLab,};- return resolve_remote_ref_as_base(repo, provider, number);+ return resolve_remote_ref_as_base(repo, forge, number);}let selector = repo.expand_selector(base)?;@@ -512,10 +501,10 @@ fn resolve_base_ref(/// user hasn't asked to check out.fn resolve_remote_ref_as_base(repo: &Repository,- provider: &dyn RemoteRefProvider,+ forge: ForgeKind,number: u32,) -> anyhow::Result<(String, Option<(String, String)>)> {- let ref_type = provider.ref_type();+ let ref_type = forge.ref_type();let symbol = ref_type.symbol();eprintln!(@@ -526,7 +515,7 @@ fn resolve_remote_ref_as_base()));- let info = fetch_ref_info(provider, number, repo)?;+ let info = fetch_ref_info(forge, number, repo)?;eprintln!("{}", format_with_gutter(&format_ref_context(&info), None));if !info.is_cross_repo {@@ -549,8 +538,13 @@ fn resolve_remote_ref_as_base(let remote = remote_ref::find_remote(repo, &info)?;let display = ref_type.display(number);- repo.run_command(&["fetch", "--", &remote, &provider.tracking_ref(number)])- .with_context(|| cformat!("Failed to fetch <bold>{display}</> from {remote}"))?;+ repo.run_command(&[+ "fetch",+ "--",+ &remote,+ &remote_ref::tracking_ref(forge, number),+ ])+ .with_context(|| cformat!("Failed to fetch <bold>{display}</> from {remote}"))?;let sha = repo.run_command(&["rev-parse", "FETCH_HEAD"]).context("Failed to resolve FETCH_HEAD to a commit SHA")?@@ -584,22 +578,22 @@ fn resolve_ref_shortcut_target(let Some((ref_type, number)) = parse_ref_shortcut(branch) else {return Ok(None);};- // Fail closed on a malformed project config before any provider is chosen:+ // Fail closed on a malformed project config before choosing a forge:// `forge.platform` lives there, and `configured_forge_platform` reports a// config that won't parse as "unset", which would route an intended// override to the wrong CLI. The hook-approval gate used to be what// surfaced this, but that no longer runs first.repo.project_config()?;- // --base is invalid with pr:/mr: syntax (check before provider selection,+ // --base is invalid with pr:/mr: syntax (check before forge selection,// which may invoke a forge CLI to inspect authentication).if base.is_some() {return Err(GitError::RefBaseConflict { ref_type, number }.into());}- let provider: &dyn RemoteRefProvider = match ref_type {- RefType::Pr => choose_pr_provider(repo)?,- RefType::Mr => &GitLabProvider,+ let forge = match ref_type {+ RefType::Pr => choose_pr_forge(repo)?,+ RefType::Mr => ForgeKind::GitLab,};- resolve_remote_ref(repo, provider, number, create).map(Some)+ resolve_remote_ref(repo, forge, number, create).map(Some)}/// Resolve the switch target, handling --create/--base flags.@@ -2327,7 +2321,7 @@ mod tests {}#[test]- fn choose_pr_provider_prefers_github_over_azure() {+ fn choose_pr_forge_prefers_github_over_azure() {// Mixed-remote setup: a repo with both a GitHub remote and an Azure// DevOps remote falls through to GitHub. Operators with an explicit// preference set `forge.platform`.@@ -2340,15 +2334,12 @@ mod tests {"https://dev.azure.com/myorg/proj/_git/myrepo",]);- assert_eq!(- choose_pr_provider(&test.repo).unwrap().forge_kind(),- ForgeKind::GitHub- );+ assert_eq!(choose_pr_forge(&test.repo).unwrap(), ForgeKind::GitHub);}#[test]- fn choose_pr_provider_azure_only() {- // Azure-only repo (no GitHub remote) gets the Azure provider.+ fn choose_pr_forge_azure_only() {+ // Azure-only repo (no GitHub remote) uses Azure DevOps.let test = TestRepo::with_initial_commit();test.run_git(&["remote",@@ -2357,25 +2348,19 @@ mod tests {"https://dev.azure.com/myorg/proj/_git/myrepo",]);- assert_eq!(- choose_pr_provider(&test.repo).unwrap().forge_kind(),- ForgeKind::AzureDevOps- );+ assert_eq!(choose_pr_forge(&test.repo).unwrap(), ForgeKind::AzureDevOps);}#[test]- fn choose_pr_provider_no_recognised_remote() {+ fn choose_pr_forge_no_recognised_remote() {// Falls back to GitHub when no recognisable forge remote exists,// preserving the existing error message from `gh`.let test = TestRepo::with_initial_commit();- assert_eq!(- choose_pr_provider(&test.repo).unwrap().forge_kind(),- ForgeKind::GitHub- );+ assert_eq!(choose_pr_forge(&test.repo).unwrap(), ForgeKind::GitHub);}#[test]- fn choose_pr_provider_forge_platform_override_wins() {+ fn choose_pr_forge_platform_override_wins() {// The bug worth covering: a mixed-remote repo where the user explicitly// pinned `forge.platform = "azure-devops"`. Without the override, the// GitHub remote would win — and the user has no way to redirect `pr:N`.@@ -2391,14 +2376,11 @@ mod tests {]);test.write_project_config("[forge]\nplatform = \"azure-devops\"\n");- assert_eq!(- choose_pr_provider(&test.repo).unwrap().forge_kind(),- ForgeKind::AzureDevOps- );+ assert_eq!(choose_pr_forge(&test.repo).unwrap(), ForgeKind::AzureDevOps);}#[test]- fn choose_pr_provider_forge_platform_github_in_azure_only_repo() {+ fn choose_pr_forge_platform_github_in_azure_only_repo() {// Inverse override: Azure-only remotes but `forge.platform = "github"`.// Verifies the config arm flips the inferred-from-remotes default.let test = TestRepo::with_initial_commit();@@ -2410,9 +2392,6 @@ mod tests {]);test.write_project_config("[forge]\nplatform = \"github\"\n");- assert_eq!(- choose_pr_provider(&test.repo).unwrap().forge_kind(),- ForgeKind::GitHub- );+ assert_eq!(choose_pr_forge(&test.repo).unwrap(), ForgeKind::GitHub);}}diff --git a/src/git/ci_platform.rs b/src/git/ci_platform.rsindex 55931084b..7bd1ebe80 100644--- a/src/git/ci_platform.rs+++ b/src/git/ci_platform.rs@@ -11,7 +11,7 @@ use crate::git::{GitRemoteUrl, RefType, Repository};/// A known forge.////// This is the canonical identity shared by configuration, remote-host-/// classification, remote-ref providers, and CI dispatch. Unknown hosts stay+/// classification, remote-ref dispatch, and CI dispatch. Unknown hosts stay/// outside the enum as `None`; callers that expose an explicit `unknown` value/// add it only at that output boundary.#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display, strum::EnumString)]diff --git a/src/git/remote_ref/azure.rs b/src/git/remote_ref/azure.rsindex 33abe4966..cee7dade8 100644--- a/src/git/remote_ref/azure.rs+++ b/src/git/remote_ref/azure.rs@@ -1,36 +1,16 @@-//! Azure DevOps PR provider.-//!-//! Implements `RemoteRefProvider` for Azure DevOps Pull Requests using the `az` CLI.-//! Requires the `azure-devops` extension (`az extension add --name azure-devops`).+//! Azure DevOps PR backend using the `az` CLI. Requires the `azure-devops`+//! extension (`az extension add --name azure-devops`).use anyhow::{Context, bail};use serde::Deserialize;-use super::{CliApiRequest, PlatformData, RemoteRefInfo, RemoteRefProvider, cli_api_error};+use super::{CliApiRequest, PlatformData, RemoteRefInfo, cli_api_error};use crate::git::canonical_url_path_segment;use crate::git::ci_platform::host_is_within;use crate::git::url::{GitRemoteUrl, authority_host};use crate::git::{ForgeKind, Repository};use crate::shell_exec::Cmd;-/// Azure DevOps Pull Request provider.-#[derive(Debug, Clone, Copy)]-pub struct AzureDevOpsProvider;--impl RemoteRefProvider for AzureDevOpsProvider {- fn forge_kind(&self) -> ForgeKind {- ForgeKind::AzureDevOps- }-- fn fetch_info(&self, number: u32, repo: &Repository) -> anyhow::Result<RemoteRefInfo> {- fetch_pr_info(number, repo)- }-- fn ref_path(&self, number: u32) -> String {- format!("pull/{}/head", number)- }-}-/// Construct an Azure DevOps remote URL for a repo.////// Emits `https://{host}/{org}/{project}/_git/{repo}` for `dev.azure.com` and@@ -230,7 +210,7 @@ pub fn azure_devops_extension_installed(repo_root: &std::path::Path) -> bool {.is_none_or(|extensions| extensions.iter().any(|e| e.name == "azure-devops"))}-fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefInfo> {+pub(super) fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefInfo> {let repo_root = repo.repo_path()?;let pr_id = pr_number.to_string();@@ -297,8 +277,8 @@ fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefI.unwrap_or(&response.source_ref_name).to_string();- // Validate at the provider boundary — same as the GitHub/GitLab/Gitea- // providers — so an empty or `refs/heads/`-only sourceRefName produces a+ // Validate at the forge backend boundary — same as the GitHub/GitLab/Gitea+ // backends — so an empty or `refs/heads/`-only sourceRefName produces a// clear diagnostic rather than confusing downstream git/path errors.if source_branch.is_empty() {bail!(@@ -358,19 +338,6 @@ fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefImod tests {use super::*;- #[test]- fn test_ref_path() {- let provider = AzureDevOpsProvider;- assert_eq!(provider.ref_path(550), "pull/550/head");- assert_eq!(provider.tracking_ref(550), "refs/pull/550/head");- }-- #[test]- fn test_ref_type() {- let provider = AzureDevOpsProvider;- assert_eq!(provider.ref_type(), crate::git::RefType::Pr);- }-#[test]fn test_parse_web_url_dev_azure() {let parsed = parse_web_url(Some("https://dev.azure.com/myorg/myproject/_git/myrepo"));diff --git a/src/git/remote_ref/gitea.rs b/src/git/remote_ref/gitea.rsindex 9cded62ae..2c025c18b 100644--- a/src/git/remote_ref/gitea.rs+++ b/src/git/remote_ref/gitea.rs@@ -1,7 +1,5 @@-//! Gitea PR provider.-//!-//! Implements `RemoteRefProvider` for Gitea Pull Requests using the `tea` CLI,-//! and hosts the `tea`-facing helpers other modules share: [`api_status`] (how+//! Gitea PR backend using the `tea` CLI. It also hosts the `tea`-facing helpers+//! other modules share: [`api_status`] (how//! every caller separates a failed request from a resource, and decides whether//! a retry could help), [`is_authed_for`], and [`has_any_login`] — read by the//! switch dispatcher and the CI-status backend, so a change to one of them is@@ -37,29 +35,11 @@ use anyhow::{Context, bail};use serde::Deserialize;use super::{- CliApiRequest, PlatformData, RemoteRefInfo, RemoteRefProvider, cli_api_error,- extract_host_from_html_url, run_cli_api,+ CliApiRequest, PlatformData, RemoteRefInfo, cli_api_error, extract_host_from_html_url,+ run_cli_api,};use crate::git::{ForgeKind, Repository};-/// Gitea Pull Request provider.-#[derive(Debug, Clone, Copy)]-pub struct GiteaProvider;--impl RemoteRefProvider for GiteaProvider {- fn forge_kind(&self) -> ForgeKind {- ForgeKind::Gitea- }-- fn fetch_info(&self, number: u32, repo: &Repository) -> anyhow::Result<RemoteRefInfo> {- fetch_pr_info(number, repo)- }-- fn ref_path(&self, number: u32) -> String {- format!("pull/{}/head", number)- }-}-/// Raw JSON response from `tea api repos/{owner}/{repo}/pulls/{number}`.#[derive(Debug, Deserialize)]struct TeaApiPrResponse {@@ -150,7 +130,7 @@ struct TeaOwner {}/// Fetch PR information from Gitea using the `tea` CLI.-fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefInfo> {+pub(super) fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefInfo> {let repo_root = repo.repo_path()?;// Resolve owner/repo from the Gitea remote — which may be non-primary in@@ -334,7 +314,7 @@ pub fn fork_remote_url(host: &str, owner: &str, repo: &str) -> String {/// Whether `tea` has a login configured for `host`.///-/// Used by the switch dispatcher to decide which provider to try when the+/// Used by the switch dispatcher to decide which forge CLI to try when the/// remote URL doesn't unambiguously identify the forge. Reads tea's config/// file directly — `$XDG_CONFIG_HOME/tea/config.yml` (default/// `~/.config/tea/config.yml`) with legacy fallback `~/.tea/tea.yml` — and@@ -416,19 +396,6 @@ fn read_tea_config() -> Option<String> {mod tests {use super::*;- #[test]- fn test_ref_path() {- let provider = GiteaProvider;- assert_eq!(provider.ref_path(7), "pull/7/head");- assert_eq!(provider.tracking_ref(7), "refs/pull/7/head");- }-- #[test]- fn test_ref_type() {- let provider = GiteaProvider;- assert_eq!(provider.ref_type(), crate::git::RefType::Pr);- }-/// The status line is the discriminator, and it is the second token of the/// first `HTTP/` line — reachable past whatever `tea` wrote before it, and/// past a status with no reason phrase.diff --git a/src/git/remote_ref/github.rs b/src/git/remote_ref/github.rsindex 88526a6f6..2feab8760 100644--- a/src/git/remote_ref/github.rs+++ b/src/git/remote_ref/github.rs@@ -1,6 +1,4 @@-//! GitHub PR provider.-//!-//! Implements `RemoteRefProvider` for GitHub Pull Requests using the `gh` CLI.+//! GitHub PR backend using the `gh` CLI.use std::path::Path;@@ -8,30 +6,12 @@ use anyhow::{Context, bail};use serde::Deserialize;use super::{- CliApiRequest, PlatformData, RemoteRefInfo, RemoteRefProvider, cli_api_error, cli_config_value,+ CliApiRequest, PlatformData, RemoteRefInfo, cli_api_error, cli_config_value,extract_host_from_html_url, run_cli_api,};use crate::git::{ForgeKind, Repository};use crate::shell_exec::Cmd;-/// GitHub Pull Request provider.-#[derive(Debug, Clone, Copy)]-pub struct GitHubProvider;--impl RemoteRefProvider for GitHubProvider {- fn forge_kind(&self) -> ForgeKind {- ForgeKind::GitHub- }-- fn fetch_info(&self, number: u32, repo: &Repository) -> anyhow::Result<RemoteRefInfo> {- fetch_pr_info(number, repo)- }-- fn ref_path(&self, number: u32) -> String {- format!("pull/{}/head", number)- }-}-/// Raw JSON response from `gh api repos/{owner}/{repo}/pulls/{number}`.#[derive(Debug, Deserialize)]struct GhApiPrResponse {@@ -100,7 +80,7 @@ fn gh_default_repo(repo_root: &Path) -> Option<(String, String)> {}/// Fetch PR information from GitHub using the `gh` CLI.-fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefInfo> {+pub(super) fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefInfo> {let repo_root = repo.repo_path()?;// Determine which owner/repo to query. Prefer gh's default repo@@ -239,7 +219,7 @@ fn use_ssh_protocol() -> bool {/// Whether `gh` has an authentication token configured for `host`.///-/// Used by the switch dispatcher to decide which provider to try when the+/// Used by the switch dispatcher to decide which forge CLI to try when the/// remote URL doesn't unambiguously identify the forge (e.g. self-hosted on/// `git.example.com`). `gh auth token --hostname <host>` reads from/// `~/.config/gh/hosts.yml` and the OS keyring — no network. Returns `false`@@ -266,19 +246,6 @@ pub fn fork_remote_url(host: &str, owner: &str, repo: &str) -> String {mod tests {use super::*;- #[test]- fn test_ref_path() {- let provider = GitHubProvider;- assert_eq!(provider.ref_path(123), "pull/123/head");- assert_eq!(provider.tracking_ref(123), "refs/pull/123/head");- }-- #[test]- fn test_ref_type() {- let provider = GitHubProvider;- assert_eq!(provider.ref_type(), crate::git::RefType::Pr);- }-#[test]fn test_fork_remote_url_formats() {// Protocol depends on `gh config get git_protocol`, so just check formatdiff --git a/src/git/remote_ref/gitlab.rs b/src/git/remote_ref/gitlab.rsindex 236641f04..0581bf7b4 100644--- a/src/git/remote_ref/gitlab.rs+++ b/src/git/remote_ref/gitlab.rs@@ -1,6 +1,4 @@-//! GitLab MR provider.-//!-//! Implements `RemoteRefProvider` for GitLab Merge Requests using the `glab` CLI.+//! GitLab MR backend using the `glab` CLI.//!//! # API Differences from GitHub//!@@ -27,30 +25,10 @@ use anyhow::{Context, bail};use serde::Deserialize;use super::{- CliApiRequest, PlatformData, RemoteRefInfo, RemoteRefProvider, cli_api_error, cli_config_value,- run_cli_api,+ CliApiRequest, PlatformData, RemoteRefInfo, cli_api_error, cli_config_value, run_cli_api,};use crate::git::{ForgeKind, Repository};-/// GitLab Merge Request provider.-#[derive(Debug, Clone, Copy)]-pub struct GitLabProvider;--impl RemoteRefProvider for GitLabProvider {- fn forge_kind(&self) -> ForgeKind {- ForgeKind::GitLab- }-- fn fetch_info(&self, number: u32, repo: &Repository) -> anyhow::Result<RemoteRefInfo> {- let repo_root = repo.repo_path()?;- fetch_mr_info(number, repo_root)- }-- fn ref_path(&self, number: u32) -> String {- format!("merge-requests/{}/head", number)- }-}-/// Raw JSON response from `glab api projects/:id/merge_requests/<number>`.#[derive(Debug, Deserialize)]struct GlabMrResponse {@@ -77,7 +55,8 @@ struct GlabProject {}/// Fetch MR information from GitLab using the `glab` CLI.-fn fetch_mr_info(mr_number: u32, repo_root: &Path) -> anyhow::Result<RemoteRefInfo> {+pub(super) fn fetch_mr_info(mr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefInfo> {+ let repo_root = repo.repo_path()?;let api_path = format!("projects/:id/merge_requests/{}", mr_number);let args = ["api", api_path.as_str()];let output = run_cli_api(CliApiRequest {@@ -284,19 +263,6 @@ mod tests {use super::*;use crate::git::remote_ref::RemoteRefInfo;- #[test]- fn test_ref_path() {- let provider = GitLabProvider;- assert_eq!(provider.ref_path(42), "merge-requests/42/head");- assert_eq!(provider.tracking_ref(42), "refs/merge-requests/42/head");- }-- #[test]- fn test_ref_type() {- let provider = GitLabProvider;- assert_eq!(provider.ref_type(), crate::git::RefType::Mr);- }-#[test]fn test_fork_remote_url_formats() {// Protocol depends on `glab config get git_protocol`, so just check formatdiff --git a/src/git/remote_ref/mod.rs b/src/git/remote_ref/mod.rsindex 65a48175f..c37f00091 100644--- a/src/git/remote_ref/mod.rs+++ b/src/git/remote_ref/mod.rs@@ -1,7 +1,8 @@//! Unified PR/MR reference resolution.//!-//! This module provides a trait-based architecture for resolving GitHub PRs, Gitea PRs,-//! GitLab MRs, and Azure DevOps PRs to local branches. All platforms follow the same workflow:+//! This module resolves GitHub PRs, Gitea PRs, GitLab MRs, and Azure DevOps PRs+//! to local branches. [`ForgeKind`] is the forge identity throughout; all+//! platforms follow the same workflow://!//! 1. Parse `pr:<number>` or `mr:<number>` syntax//! 2. Fetch metadata from the platform API@@ -12,11 +13,10 @@//!//! ```no_run//! use worktrunk::git::Repository;-//! use worktrunk::git::remote_ref::{GitHubProvider, RemoteRefProvider};+//! use worktrunk::git::{ForgeKind, remote_ref};//! # fn example() -> Result<(), Box<dyn std::error::Error>> {//! let repo = Repository::at(".")?;-//! let provider = GitHubProvider;-//! let info = provider.fetch_info(123, &repo)?;+//! let info = remote_ref::fetch_info(ForgeKind::GitHub, 123, &repo)?;//! println!("PR #{}: {}", info.number, info.title);//! # Ok(())//! # }@@ -32,7 +32,7 @@//! way that line stays accurate across locale, CLI version, and API rewording in//! a way our paraphrase of it would not.//!-//! A provider writes a message of its own only where the CLI structurally cannot+//! A backend writes a message of its own only where the CLI structurally cannot//! report the condition://!//! - **GitHub's 404** answers about an owner/repo that is *our* choice — from@@ -48,10 +48,10 @@//! with the status dropped, and cost a `starts_with("401")` test against prose//! to select it.//!-//! Where a provider still classifies, it keys on structure and falls through to+//! Where a backend still classifies, it keys on structure and falls through to//! forwarding when the structure isn't there: `gh` puts a `status` field in its//! error body, while `glab` puts the status only inside the message text, so-//! there is nothing there to key on. Gitea is the one provider whose response+//! there is nothing there to key on. Gitea is the one backend whose response//! *shape* is the error channel at all, because `tea api` copies the body to//! stdout and exits 0 whatever the status — see [`gitea`].//!@@ -71,7 +71,7 @@//!//! Uses `tea api repos/{owner}/{repo}/pulls/<number>`. Unlike `gh`, `tea`'s//! `{owner}`/`{repo}` template expansion depends on local repo context, so the-//! provider resolves owner/repo from a matching Gitea remote and passes a+//! backend resolves owner/repo from a matching Gitea remote and passes a//! pre-expanded path.//!//! ## Azure DevOps@@ -86,10 +86,6 @@ pub mod github;pub mod gitlab;mod info;-pub use azure::AzureDevOpsProvider;-pub use gitea::GiteaProvider;-pub use github::GitHubProvider;-pub use gitlab::GitLabProvider;pub use info::{PlatformData, RemoteRefInfo};use std::io::ErrorKind;@@ -104,38 +100,35 @@ use crate::git::url::authority_host;use crate::git::{ForgeKind, GitRepoInfo, GitRepoProvider, RefType, Repository};use crate::shell_exec::Cmd;-/// Provider trait for platform-specific PR/MR operations.-///-/// Each platform (GitHub, Gitea, GitLab, Azure DevOps) implements this trait to-/// provide unified access to PR/MR metadata and ref paths.-pub trait RemoteRefProvider {- /// The forge whose API and ref namespace this provider implements.- fn forge_kind(&self) -> ForgeKind;-- /// The reference type this provider handles.- fn ref_type(&self) -> RefType {- self.forge_kind().ref_type()+/// Fetch PR/MR metadata through the forge's CLI.+pub fn fetch_info(+ forge: ForgeKind,+ number: u32,+ repo: &Repository,+) -> anyhow::Result<RemoteRefInfo> {+ match forge {+ ForgeKind::GitHub => github::fetch_pr_info(number, repo),+ ForgeKind::GitLab => gitlab::fetch_mr_info(number, repo),+ ForgeKind::Gitea => gitea::fetch_pr_info(number, repo),+ ForgeKind::AzureDevOps => azure::fetch_pr_info(number, repo),}+}- /// Fetch ref information from the platform API.- ///- /// # Errors- ///- /// Returns an error if:- /// - The CLI tool is not installed or not authenticated- /// - The ref doesn't exist- /// - The JSON response is malformed- fn fetch_info(&self, number: u32, repo: &Repository) -> anyhow::Result<RemoteRefInfo>;-- /// Get the git ref path for this ref (e.g., "pull/123/head" or "merge-requests/42/head").- fn ref_path(&self, number: u32) -> String;-- /// Get the full tracking ref (e.g., "refs/pull/123/head").- fn tracking_ref(&self, number: u32) -> String {- format!("refs/{}", self.ref_path(number))+/// Get the fetch ref path for a forge PR/MR.+pub fn ref_path(forge: ForgeKind, number: u32) -> String {+ match forge {+ ForgeKind::GitLab => format!("merge-requests/{number}/head"),+ ForgeKind::GitHub | ForgeKind::Gitea | ForgeKind::AzureDevOps => {+ format!("pull/{number}/head")+ }}}+/// Get the full tracking ref for a forge PR/MR.+pub fn tracking_ref(forge: ForgeKind, number: u32) -> String {+ format!("refs/{}", ref_path(forge, number))+}+pub(super) struct CliApiRequest<'a> {pub tool: &'a str,pub args: &'a [&'a str],@@ -179,9 +172,9 @@ pub(super) fn cli_api_error_details(output: &Output) -> String {/// Wrap a failed forge-CLI invocation, rendering `message` above the CLI's own/// output in a gutter.///-/// Every provider's failure path ends here, and forwarding is the default:+/// Every backend's failure path ends here, and forwarding is the default:/// `message` names the request we made ("gh api failed for PR #123") and the-/// gutter carries the CLI's verdict on it. A provider with something of its own+/// gutter carries the CLI's verdict on it. A backend with something of its own/// to say — the cases in the module docs — passes it as `message` rather than/// bailing, so its words are added to the CLI's rather than substituted for/// them.@@ -293,22 +286,6 @@ pub fn find_remote(repo: &Repository, info: &RemoteRefInfo) -> Result<String, Gi})}-/// Check if a local branch is tracking a specific remote ref.-///-/// Returns `Some(true)` if the branch is configured to track the given ref.-/// Returns `Some(false)` if the branch exists but tracks something else (or nothing).-/// Returns `None` if the branch doesn't exist.-pub fn branch_tracks_ref(- repo_root: &Path,- branch: &str,- provider: &dyn RemoteRefProvider,- number: u32,- expected_remote: Option<&str>,-) -> Option<bool> {- let expected_ref = provider.tracking_ref(number);- crate::git::branch_tracks_ref(repo_root, branch, &expected_ref, expected_remote)-}-/// A forge PR/MR web URL decomposed into its parts.////// Detection is shape-based, not host-based: the URL must use `http(s)://`@@ -554,18 +531,17 @@ mod tests {}#[test]- fn test_ref_paths() {- let gh = GitHubProvider;- assert_eq!(gh.ref_path(123), "pull/123/head");- assert_eq!(gh.tracking_ref(123), "refs/pull/123/head");-- let ge = GiteaProvider;- assert_eq!(ge.ref_path(7), "pull/7/head");- assert_eq!(ge.tracking_ref(7), "refs/pull/7/head");-- let gl = GitLabProvider;- assert_eq!(gl.ref_path(42), "merge-requests/42/head");- assert_eq!(gl.tracking_ref(42), "refs/merge-requests/42/head");+ fn tracking_refs_follow_forge_namespaces() {+ assert_eq!(tracking_ref(ForgeKind::GitHub, 123), "refs/pull/123/head");+ assert_eq!(tracking_ref(ForgeKind::Gitea, 7), "refs/pull/7/head");+ assert_eq!(+ tracking_ref(ForgeKind::AzureDevOps, 550),+ "refs/pull/550/head"+ );+ assert_eq!(+ tracking_ref(ForgeKind::GitLab, 42),+ "refs/merge-requests/42/head"+ );}#[test]diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 0db53dc87..b52767920 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -5352,8 +5352,8 @@ fn test_switch_pr_empty_branch(#[from(repo_with_remote)] repo: TestRepo) {// ============================================================================// PR Syntax Tests on Gitea remotes//-// These exercise `pr:<N>` against a Gitea remote (host detection picks the-// `tea` provider; provider selection is in choose_pr_provider). The remote+// These exercise `pr:<N>` against a Gitea remote (`choose_pr_forge` selects+// Gitea, whose backend calls `tea`). The remote// URLs use `gitea.example.com` so `GitRemoteUrl::is_gitea()` matches and the// ambiguous fallback is skipped — the runtime calls only the mock `tea`,// not real `gh`.@@ -5363,7 +5363,7 @@ fn test_switch_pr_empty_branch(#[from(repo_with_remote)] repo: TestRepo) {/// stderr and `body` on stdout — the two streams a real `tea` writes for one/// HTTP response.///-/// The status is what the Gitea provider classifies on, so every test states+/// The status is what the Gitea backend classifies on, so every test states/// the one it stands for rather than leaving it implied. Returns the mock bin/// directory; pass it to `configure_mock_cli_env`.fn setup_mock_tea(repo: &TestRepo, status: &str, body: &str) -> std::path::PathBuf {@@ -5618,8 +5618,8 @@ fn test_switch_pr_gitea_tea_not_installed(#[from(repo_with_remote)] repo: TestRe});}-/// `forge.platform = "gitea"` selects the Gitea provider directly, even when-/// the remote URL doesn't look like Gitea (no ambiguous two-provider fallback).+/// `forge.platform = "gitea"` selects Gitea directly, even when the remote URL+/// doesn't look like Gitea.#[rstest]fn test_switch_pr_gitea_forge_platform(#[from(repo_with_remote)] repo: TestRepo) {// Non-Gitea-looking URL — without `forge.platform` set we'd hit the ambiguous path.@@ -5699,11 +5699,11 @@ fn test_switch_pr_forge_platform_invalid_bails(#[from(repo_with_remote)] repo: T});}-/// Malformed project config must fail closed before `pr:` provider fallback.+/// Malformed project config must fail closed before `pr:` forge fallback./// Otherwise an intended `forge.platform` override on an opaque/self-hosted/// remote can be ignored and route to the wrong CLI.#[rstest]-fn test_switch_pr_malformed_project_config_bails_before_provider_selection(+fn test_switch_pr_malformed_project_config_bails_before_forge_selection(#[from(repo_with_remote)] repo: TestRepo,) {repo.run_git(&[@@ -5727,7 +5727,7 @@ fn test_switch_pr_malformed_project_config_bails_before_provider_selection().command("api",- MockResponse::stderr("GH provider fallback was invoked\n").with_exit_code(42),+ MockResponse::stderr("GH fallback was invoked\n").with_exit_code(42),).command("_default", MockResponse::exit(42)).write(&mock_bin);@@ -5753,14 +5753,13 @@ fn test_switch_pr_malformed_project_config_bails_before_provider_selection("expected TOML parse diagnostic, got:\n{stderr}");assert!(- !stderr.contains("GH provider fallback was invoked"),- "provider fallback should not run after malformed project config:\n{stderr}"+ !stderr.contains("GH fallback was invoked"),+ "forge fallback should not run after malformed project config:\n{stderr}");}/// With no parseable remote URL, dispatch defaults to GitHub. Without `gh`-/// installed the GitHub provider bails with the install hint — a single,-/// readable error rather than a wrapped two-provider message.+/// installed, the GitHub backend returns its install hint.#[rstest]fn test_switch_pr_no_remote_defaults_to_github(repo: TestRepo) {let Some(minimal_bin) = setup_minimal_bin_without_cli(&repo) else {@@ -6190,8 +6189,8 @@ fn test_switch_pr_gitea_proxy_error_page(#[from(repo_with_remote)] repo: TestRep// ============================================================================// PR Syntax Tests on Azure DevOps remotes//-// These exercise `pr:<N>` against an Azure DevOps remote. Host detection picks-// the `az` provider (provider selection is in choose_pr_provider). The remote+// These exercise `pr:<N>` against an Azure DevOps remote. `choose_pr_forge`+// selects Azure DevOps, whose backend calls `az`. The remote// URLs use `dev.azure.com` / `*.visualstudio.com` so `GitRemoteUrl::is_azure_devops()`// matches and the ambiguous fallback is skipped — the runtime calls only the// mock `az`, not real `gh`.@@ -6361,7 +6360,7 @@ fn test_switch_pr_azure_project_name_with_spaces(#[from(repo_with_remote)] mut r/// A full Azure DevOps PR web URL passed to `wt switch` resolves the same as the/// `pr:N` shortcut: the URL normalises to `pr:101` (shape-based `parse_ref_url`),-/// dispatch selects `AzureDevOpsProvider`, and the worktree is created. The+/// dispatch selects Azure DevOps, and the worktree is created. The/// snapshot should match `switch_pr_azure_same_repo`, since both forms converge/// on the same shortcut.#[rstest]@@ -6404,7 +6403,7 @@ fn test_switch_pr_azure_web_url(#[from(repo_with_remote)] mut repo: TestRepo) {}/// Regression: an Azure PR whose `sourceRefName` is just `refs/heads/`-/// (empty branch after stripping) must fail at the provider boundary with a+/// (empty branch after stripping) must fail at the forge boundary with a/// clear message — matching GitHub/GitLab/Gitea — not produce a confusing/// downstream git/path error.#[rstest]@@ -6583,7 +6582,7 @@ fn test_switch_pr_azure_not_found(#[from(repo_with_remote)] repo: TestRepo) {}/// `az` not installed: with an Azure remote, dispatch routes to the Azure-/// provider, which bails with the install hint when `az` isn't on PATH.+/// backend, which returns the install hint when `az` isn't on PATH.#[rstest]fn test_switch_pr_azure_az_not_installed(#[from(repo_with_remote)] repo: TestRepo) {repo.run_git(&[@@ -6606,7 +6605,7 @@ fn test_switch_pr_azure_az_not_installed(#[from(repo_with_remote)] repo: TestRep});}-/// `forge.platform = "azure-devops"` selects the Azure provider directly, even+/// `forge.platform = "azure-devops"` selects Azure DevOps directly, even/// when the remote URL doesn't look like Azure DevOps.#[rstest]fn test_switch_pr_azure_forge_platform(#[from(repo_with_remote)] repo: TestRepo) {