Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: unify PR/MR reference resolution (#778)
Maximilian Roos575ba0f4cdf3
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex e42e35855..506686025 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -8,8 +8,9 @@ use anyhow::Context;use color_print::cformat;use dunce::canonicalize;use worktrunk::config::UserConfig;-use worktrunk::git::pr_ref::fork_remote_url;-use worktrunk::git::{GitError, Repository};+use worktrunk::git::mr_ref;+use worktrunk::git::pr_ref::{self, fork_remote_url};+use worktrunk::git::{GitError, RefType, Repository};use worktrunk::styling::{hint_message, info_message, progress_message, suggest_command, warning_message,};@@ -26,210 +27,240 @@ struct ResolvedTarget {method: CreationMethod,}-/// Resolve the switch target, handling pr:/mr: syntax and --create/--base flags.-///-/// This is the first phase of planning: determine what branch we're switching to-/// and how we'll create the worktree. May involve network calls for PR/MR resolution.-fn resolve_switch_target(+/// Resolve a PR reference (`pr:<number>` syntax).+fn resolve_pr_ref(repo: &Repository,- branch: &str,+ pr_number: u32,create: bool,base: Option<&str>,) -> anyhow::Result<ResolvedTarget> {- use worktrunk::git::mr_ref;- use worktrunk::git::pr_ref::{fetch_pr_info, local_branch_name};-- // Handle pr:<number> syntax- if let Some(pr_number) = worktrunk::git::pr_ref::parse_pr_ref(branch) {- // --create and --base are invalid with pr: syntax- if create {- return Err(GitError::RefCreateConflict {- ref_type: worktrunk::git::RefType::Pr,- number: pr_number,- }- .into());+ // --create and --base are invalid with pr: syntax+ if create {+ return Err(GitError::RefCreateConflict {+ ref_type: RefType::Pr,+ number: pr_number,}- if base.is_some() {- return Err(GitError::RefBaseConflict {- ref_type: worktrunk::git::RefType::Pr,- number: pr_number,- }- .into());+ .into());+ }+ if base.is_some() {+ return Err(GitError::RefBaseConflict {+ ref_type: RefType::Pr,+ number: pr_number,}+ .into());+ }- // Fetch PR info (network call via gh CLI)- crate::output::print(progress_message(cformat!("Fetching PR #{pr_number}...")))?;+ // Fetch PR info (network call via gh CLI)+ crate::output::print(progress_message(cformat!("Fetching PR #{pr_number}...")))?;- let repo_root = repo.repo_path();- let pr_info = fetch_pr_info(pr_number, repo_root)?;+ let repo_root = repo.repo_path();+ let pr_info = pr_ref::fetch_pr_info(pr_number, repo_root)?;- if pr_info.is_cross_repository {- // Fork PR: will need fetch + pushRemote config (see pr_ref module docs)- let local_branch = local_branch_name(&pr_info);+ if pr_info.is_cross_repository {+ // Fork PR: check if branch already exists and is tracking this PR+ let local_branch = pr_ref::local_branch_name(&pr_info);- // Check if branch already exists and is tracking this PR- // If so, we can reuse it without re-fetching or re-configuring- if let Some(tracks_this_pr) =- worktrunk::git::pr_ref::branch_tracks_pr(repo_root, &local_branch, pr_number)- {- if tracks_this_pr {- // Branch exists and tracks this PR - just create worktree- crate::output::print(info_message(cformat!(- "Branch <bold>{local_branch}</> already configured for PR #{pr_number}"- )))?;- return Ok(ResolvedTarget {- branch: local_branch,- method: CreationMethod::Regular {- create_branch: false,- base_branch: None,- },- });- } else {- // Branch exists but tracks something else- return Err(GitError::BranchTracksDifferentRef {- branch: local_branch,- ref_type: worktrunk::git::RefType::Pr,- number: pr_number,- }- .into());+ if let Some(tracks_this) = pr_ref::branch_tracks_pr(repo_root, &local_branch, pr_number) {+ if tracks_this {+ crate::output::print(info_message(cformat!(+ "Branch <bold>{local_branch}</> already configured for PR #{pr_number}"+ )))?;+ return Ok(ResolvedTarget {+ branch: local_branch,+ method: CreationMethod::Regular {+ create_branch: false,+ base_branch: None,+ },+ });+ } else {+ return Err(GitError::BranchTracksDifferentRef {+ branch: local_branch,+ ref_type: RefType::Pr,+ number: pr_number,}+ .into());}+ }- // Branch doesn't exist - need full fork PR setup- let fork_push_url =- fork_remote_url(&pr_info.host, &pr_info.head_owner, &pr_info.head_repo);-- return Ok(ResolvedTarget {- branch: local_branch,- method: CreationMethod::ForkPr {- pr_number,- fork_push_url,- pr_url: pr_info.url,- host: pr_info.host,- base_owner: pr_info.base_owner,- base_repo: pr_info.base_repo,- },- });- } else {- // Same-repo PR: fetch the branch to ensure remote refs are up-to-date.- // The branch exists on GitHub (per the API), but local refs may be stale.- // Use find_remote_for_repo (not primary_remote) because the PR's repo might- // be on a different remote (e.g., upstream vs origin in fork workflows).- let remote = repo- .find_remote_for_repo(&pr_info.base_owner, &pr_info.base_repo)- .ok_or_else(|| {- let suggested_url =- fork_remote_url(&pr_info.host, &pr_info.base_owner, &pr_info.base_repo);- GitError::NoRemoteForRepo {- owner: pr_info.base_owner.clone(),- repo: pr_info.base_repo.clone(),- suggested_url,- }- })?;- let branch = &pr_info.head_ref_name;-- let msg = cformat!("Fetching <bold>{branch}</> from {remote}...");- crate::output::print(progress_message(msg))?;+ // Branch doesn't exist - need fork setup+ // Resolve the remote now (during planning) to fail early if no matching remote exists+ let remote = repo+ .find_remote_for_repo(Some(&pr_info.host), &pr_info.base_owner, &pr_info.base_repo)+ .ok_or_else(|| {+ let suggested_url =+ fork_remote_url(&pr_info.host, &pr_info.base_owner, &pr_info.base_repo);+ GitError::NoRemoteForRepo {+ owner: pr_info.base_owner.clone(),+ repo: pr_info.base_repo.clone(),+ suggested_url,+ }+ })?;- repo.run_command(&["fetch", &remote, branch])- .with_context(|| format!("Failed to fetch branch '{}' from {}", branch, remote))?;+ let fork_push_url = fork_remote_url(&pr_info.host, &pr_info.head_owner, &pr_info.head_repo);- return Ok(ResolvedTarget {- branch: pr_info.head_ref_name,- method: CreationMethod::Regular {- create_branch: false,- base_branch: None,- },- });- }+ return Ok(ResolvedTarget {+ branch: local_branch,+ method: CreationMethod::ForkRef {+ ref_type: RefType::Pr,+ number: pr_number,+ fork_push_url,+ ref_url: pr_info.url,+ remote,+ },+ });}- // Handle mr:<number> syntax (GitLab MRs)- if let Some(mr_number) = mr_ref::parse_mr_ref(branch) {- // --create and --base are invalid with mr: syntax- if create {- return Err(GitError::RefCreateConflict {- ref_type: worktrunk::git::RefType::Mr,- number: mr_number,+ // Same-repo PR: fetch the branch to ensure remote refs are up-to-date.+ // Use host-aware matching for multi-host setups (e.g., github.com + github.enterprise.com).+ let remote = repo+ .find_remote_for_repo(Some(&pr_info.host), &pr_info.base_owner, &pr_info.base_repo)+ .ok_or_else(|| {+ let suggested_url =+ fork_remote_url(&pr_info.host, &pr_info.base_owner, &pr_info.base_repo);+ GitError::NoRemoteForRepo {+ owner: pr_info.base_owner.clone(),+ repo: pr_info.base_repo.clone(),+ suggested_url,}- .into());+ })?;+ let branch = &pr_info.head_ref_name;++ crate::output::print(progress_message(cformat!(+ "Fetching <bold>{branch}</> from {remote}..."+ )))?;+ repo.run_command(&["fetch", &remote, branch])+ .with_context(|| format!("Failed to fetch branch '{}' from {}", branch, remote))?;++ Ok(ResolvedTarget {+ branch: pr_info.head_ref_name,+ method: CreationMethod::Regular {+ create_branch: false,+ base_branch: None,+ },+ })+}++/// Resolve an MR reference (`mr:<number>` syntax).+fn resolve_mr_ref(+ repo: &Repository,+ mr_number: u32,+ create: bool,+ base: Option<&str>,+) -> anyhow::Result<ResolvedTarget> {+ // --create and --base are invalid with mr: syntax+ if create {+ return Err(GitError::RefCreateConflict {+ ref_type: RefType::Mr,+ number: mr_number,}- if base.is_some() {- return Err(GitError::RefBaseConflict {- ref_type: worktrunk::git::RefType::Mr,- number: mr_number,- }- .into());+ .into());+ }+ if base.is_some() {+ return Err(GitError::RefBaseConflict {+ ref_type: RefType::Mr,+ number: mr_number,}+ .into());+ }- // Fetch MR info (network call via glab CLI)- crate::output::print(progress_message(cformat!("Fetching MR !{mr_number}...")))?;+ // Fetch MR info (network call via glab CLI)+ crate::output::print(progress_message(cformat!("Fetching MR !{mr_number}...")))?;- let repo_root = repo.repo_path();- let mr_info = mr_ref::fetch_mr_info(mr_number, repo_root)?;+ let repo_root = repo.repo_path();+ let mr_info = mr_ref::fetch_mr_info(mr_number, repo_root)?;- if mr_info.is_cross_project {- // Fork MR: will need fetch + pushRemote config (see mr_ref module docs)- let local_branch = mr_ref::local_branch_name(&mr_info);+ if mr_info.is_cross_project {+ // Fork MR: check if branch already exists and is tracking this MR+ let local_branch = mr_ref::local_branch_name(&mr_info);- // Check if branch already exists and is tracking this MR- // If so, we can reuse it without re-fetching or re-configuring- if let Some(tracks_this_mr) =- mr_ref::branch_tracks_mr(repo_root, &local_branch, mr_number)- {- if tracks_this_mr {- // Branch exists and tracks this MR - just create worktree- crate::output::print(info_message(cformat!(- "Branch <bold>{local_branch}</> already configured for MR !{mr_number}"- )))?;- return Ok(ResolvedTarget {- branch: local_branch,- method: CreationMethod::Regular {- create_branch: false,- base_branch: None,- },- });- } else {- // Branch exists but tracks something else- return Err(GitError::BranchTracksDifferentRef {- branch: local_branch,- ref_type: worktrunk::git::RefType::Mr,- number: mr_number,- }- .into());+ if let Some(tracks_this) = mr_ref::branch_tracks_mr(repo_root, &local_branch, mr_number) {+ if tracks_this {+ crate::output::print(info_message(cformat!(+ "Branch <bold>{local_branch}</> already configured for MR !{mr_number}"+ )))?;+ return Ok(ResolvedTarget {+ branch: local_branch,+ method: CreationMethod::Regular {+ create_branch: false,+ base_branch: None,+ },+ });+ } else {+ return Err(GitError::BranchTracksDifferentRef {+ branch: local_branch,+ ref_type: RefType::Mr,+ number: mr_number,}+ .into());}+ }- // Branch doesn't exist - need full fork MR setup- // Use `glab config get git_protocol` to determine SSH vs HTTPS preference.- let fork_push_url = mr_ref::fork_remote_url(&mr_info).ok_or_else(|| {- anyhow::anyhow!(- "MR !{} is from a fork but glab didn't provide source project URL; \- upgrade glab or checkout the fork branch manually",- mr_number- )- })?;- let target_project_url = mr_ref::target_remote_url(&mr_info);+ // Branch doesn't exist - need fork setup+ let fork_push_url = mr_ref::fork_remote_url(&mr_info).ok_or_else(|| {+ anyhow::anyhow!(+ "MR !{} is from a fork but glab didn't provide source project URL; \+ upgrade glab or checkout the fork branch manually",+ mr_number+ )+ })?;+ let target_url = mr_ref::target_remote_url(&mr_info).ok_or_else(|| {+ anyhow::anyhow!(+ "MR !{} is from a fork but glab didn't provide target project URL; \+ upgrade glab or checkout the fork branch manually",+ mr_number+ )+ })?;++ // Resolve the remote now (during planning) to fail early if no matching remote exists+ let remote = repo.find_remote_by_url(&target_url).ok_or_else(|| {+ anyhow::anyhow!(+ "No remote found for target project; \+ add a remote pointing to {} (e.g., `git remote add upstream {}`)",+ target_url,+ target_url+ )+ })?;++ return Ok(ResolvedTarget {+ branch: local_branch,+ method: CreationMethod::ForkRef {+ ref_type: RefType::Mr,+ number: mr_number,+ fork_push_url,+ ref_url: mr_info.url,+ remote,+ },+ });+ }- return Ok(ResolvedTarget {- branch: local_branch,- method: CreationMethod::ForkMr {- mr_number,- fork_push_url,- mr_url: mr_info.url,- target_project_url,- },- });- } else {- // Same-repo MR: just use the branch name, regular switch- return Ok(ResolvedTarget {- branch: mr_info.source_branch,- method: CreationMethod::Regular {- create_branch: false,- base_branch: None,- },- });- }+ // Same-repo MR: just use the branch name+ Ok(ResolvedTarget {+ branch: mr_info.source_branch,+ method: CreationMethod::Regular {+ create_branch: false,+ base_branch: None,+ },+ })+}++/// Resolve the switch target, handling pr:/mr: syntax and --create/--base flags.+///+/// This is the first phase of planning: determine what branch we're switching to+/// and how we'll create the worktree. May involve network calls for PR/MR resolution.+fn resolve_switch_target(+ repo: &Repository,+ branch: &str,+ create: bool,+ base: Option<&str>,+) -> anyhow::Result<ResolvedTarget> {+ // Handle pr:<number> syntax+ if let Some(pr_number) = pr_ref::parse_pr_ref(branch) {+ return resolve_pr_ref(repo, pr_number, create, base);+ }++ // Handle mr:<number> syntax (GitLab MRs)+ if let Some(mr_number) = mr_ref::parse_mr_ref(branch) {+ return resolve_mr_ref(repo, mr_number, create, base);}// Regular branch switch@@ -637,114 +668,37 @@ pub fn execute_switch((*create_branch, base_branch.clone(), from_remote)}- CreationMethod::ForkPr {- pr_number,+ CreationMethod::ForkRef {+ ref_type,+ number,fork_push_url,- pr_url: _,- host,- base_owner,- base_repo,+ ref_url: _,+ remote,} => {- let pr_ref = format!("pull/{}/head", pr_number);-- // Find the remote that points to the base repo (where PR refs live)- let remote = repo- .find_remote_for_repo(base_owner, base_repo)- .ok_or_else(|| {- let suggested_url = fork_remote_url(host, base_owner, base_repo);- GitError::NoRemoteForRepo {- owner: base_owner.clone(),- repo: base_repo.clone(),- suggested_url,- }- })?;-- // Fetch the PR head (progress already shown during planning)- repo.run_command(&["fetch", &remote, &pr_ref])- .with_context(|| {- format!("Failed to fetch PR #{} from {}", pr_number, remote)- })?;-- // Execute branch creation and configuration with cleanup on failure.- // If any step after branch creation fails, we must delete the branch- // to avoid leaving orphaned state that blocks future attempts.- let setup_result = setup_fork_branch(- repo,- &branch,- &remote,- &pr_ref,- fork_push_url,- &worktree_path,- &format!("PR #{}", pr_number),- );-- if let Err(e) = setup_result {- // Cleanup: try to delete the branch if it was created- // (ignore errors - branch may not exist if creation failed)- // Use -- to prevent branch names starting with - from being interpreted as flags- let _ = repo.run_command(&["branch", "-D", "--", &branch]);- return Err(e);- }-- crate::output::print(info_message(cformat!(- "Push configured to fork: <bright-black>{fork_push_url}</>"- )))?;-- (false, None, Some(format!("PR #{}", pr_number)))- }-- CreationMethod::ForkMr {- mr_number,- fork_push_url,- mr_url: _,- target_project_url,- } => {- let mr_ref = format!("merge-requests/{}/head", mr_number);-- // Find the remote that points to the target project (where MR refs live).- // This handles contributor clones where origin=fork and upstream=target.- let remote = match &target_project_url {- Some(url) => repo.find_remote_by_url(url).ok_or_else(|| {- anyhow::anyhow!(- "No remote found for target project; \- add a remote pointing to {} (e.g., `git remote add upstream {}`)",- url,- url- )- })?,- None => {- // glab didn't provide target project URL (older version)- anyhow::bail!(- "MR !{} is from a fork but glab didn't provide target project URL; \- upgrade glab or checkout the fork branch manually",- mr_number- );- }+ // Compute the ref path based on type+ let remote_ref = match ref_type {+ RefType::Pr => format!("pull/{}/head", number),+ RefType::Mr => format!("merge-requests/{}/head", number),};+ let label = ref_type.display(*number);- // Fetch the MR head (progress already shown during planning)- repo.run_command(&["fetch", &remote, &mr_ref])- .with_context(|| {- format!("Failed to fetch MR !{} from {}", mr_number, remote)- })?;+ // Fetch the ref (remote was resolved during planning)+ repo.run_command(&["fetch", remote, &remote_ref])+ .with_context(|| format!("Failed to fetch {} from {}", label, remote))?;// Execute branch creation and configuration with cleanup on failure.- // If any step after branch creation fails, we must delete the branch- // to avoid leaving orphaned state that blocks future attempts.let setup_result = setup_fork_branch(repo,&branch,- &remote,- &mr_ref,+ remote,+ &remote_ref,fork_push_url,&worktree_path,- &format!("MR !{}", mr_number),+ &label,);if let Err(e) = setup_result {// Cleanup: try to delete the branch if it was created- // (ignore errors - branch may not exist if creation failed)- // Use -- to prevent branch names starting with - from being interpreted as flagslet _ = repo.run_command(&["branch", "-D", "--", &branch]);return Err(e);}@@ -753,7 +707,7 @@ pub fn execute_switch("Push configured to fork: <bright-black>{fork_push_url}</>")))?;- (false, None, Some(format!("MR !{}", mr_number)))+ (false, None, Some(label))}};@@ -780,20 +734,19 @@ pub fn execute_switch(.collect();ctx.execute_post_create_commands(&extra_vars)?;}- CreationMethod::ForkPr {- pr_number, pr_url, ..- } => {- let pr_num_str = pr_number.to_string();- let extra_vars: Vec<(&str, &str)> =- vec![("pr_number", &pr_num_str), ("pr_url", pr_url)];- ctx.execute_post_create_commands(&extra_vars)?;- }- CreationMethod::ForkMr {- mr_number, mr_url, ..+ CreationMethod::ForkRef {+ ref_type,+ number,+ ref_url,+ ..} => {- let mr_num_str = mr_number.to_string();+ let num_str = number.to_string();+ let (num_key, url_key) = match ref_type {+ RefType::Pr => ("pr_number", "pr_url"),+ RefType::Mr => ("mr_number", "mr_url"),+ };let extra_vars: Vec<(&str, &str)> =- vec![("mr_number", &mr_num_str), ("mr_url", mr_url)];+ vec![(num_key, &num_str), (url_key, ref_url)];ctx.execute_post_create_commands(&extra_vars)?;}}diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rsindex 6f81b908a..07448abd2 100644--- a/src/commands/worktree/types.rs+++ b/src/commands/worktree/types.rs@@ -4,6 +4,8 @@use std::path::{Path, PathBuf};+use worktrunk::git::RefType;+/// Flags indicating which merge operations occurred#[derive(Debug, Clone, Copy)]pub struct MergeOperations {@@ -63,25 +65,22 @@ pub enum CreationMethod {/// Base branch for creation (resolved, validated to exist)base_branch: Option<String>,},- /// Fork PR: fetch from refs/pull/N/head, create branch, configure pushRemote- ForkPr {- pr_number: u32,- fork_push_url: String,- pr_url: String,- /// GitHub host (e.g., "github.com", "github.enterprise.com")- host: String,- /// Owner of the base repository (where the PR was opened)- base_owner: String,- /// Name of the base repository- base_repo: String,- },- /// Fork MR: fetch from refs/merge-requests/N/head, create branch, configure pushRemote- ForkMr {- mr_number: u32,+ /// Fork PR/MR: fetch from refs/pull/N/head or refs/merge-requests/N/head,+ /// create branch, configure pushRemote.+ ///+ /// The remote is resolved during planning (before approval prompts) to ensure+ /// early failure if no matching remote exists.+ ForkRef {+ /// The reference type (PR or MR).+ ref_type: RefType,+ /// The PR/MR number.+ number: u32,+ /// URL to push to (the fork's URL).fork_push_url: String,- mr_url: String,- /// Target project URL (for finding the correct remote to fetch MR refs from)- target_project_url: Option<String>,+ /// Web URL for the PR/MR.+ ref_url: String,+ /// Resolved remote name where PR/MR refs live (e.g., "origin", "upstream").+ remote: String,},}diff --git a/src/git/error.rs b/src/git/error.rsindex 4eb4f6839..17b59f37f 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -67,6 +67,11 @@ impl RefType {Self::Mr => "mr:",}}++ /// Returns a display string like "PR #42" or "MR !42".+ pub fn display(self, number: u32) -> String {+ format!("{} {}{}", self.name(), self.symbol(), number)+ }}/// Domain errors for git and worktree operations.diff --git a/src/git/mod.rs b/src/git/mod.rsindex 8b8a05fa1..6ac82b81d 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -8,6 +8,7 @@ mod error;pub mod mr_ref;mod parse;pub mod pr_ref;+pub mod remote_ref;mod repository;mod url;diff --git a/src/git/mr_ref.rs b/src/git/mr_ref.rsindex 0983e9d32..71147b8f5 100644--- a/src/git/mr_ref.rs+++ b/src/git/mr_ref.rs@@ -1,164 +1,25 @@-//! MR reference resolution (`mr:<number>` syntax).+//! GitLab MR reference resolution (`mr:<number>` syntax).//!-//! This module resolves MR numbers to branches, enabling `wt switch mr:101` to-//! check out the branch associated with a merge request.+//! This module resolves MR numbers to branches for `wt switch mr:42`.+//! For shared documentation on PR/MR resolution, see the `remote_ref` module.//!-//! # Syntax-//!-//! The `mr:<number>` prefix is unambiguous because colons are invalid in git-//! branch names (git rejects them as "not a valid branch name").-//!-//! ```text-//! wt switch mr:101 # Switch to branch for MR !101-//! wt switch mr:101 --yes # Skip approval prompts-//! ```-//!-//! **Invalid usage:**-//!-//! ```text-//! wt switch --create mr:101 # Error: MR branch already exists-//! ```-//!-//! The `--create` flag is incompatible with `mr:` because the branch must-//! already exist (it's the MR's source branch).-//!-//! # Resolution Flow-//!-//! ```text-//! mr:101-//! │-//! ▼-//! ┌─────────────────────────────────────────────────────────┐-//! │ glab mr view 101 --output json │-//! │ → source_branch, source_project_id, target_project_id │-//! └─────────────────────────────────────────────────────────┘-//! │-//! ├─── source_project_id == target_project_id ───▶ Same-repo MR-//! │ │-//! │ └─▶ Branch exists in primary remote, use directly-//! │-//! └─── source_project_id != target_project_id ───▶ Fork MR-//! │-//! ├─▶ Find remote for target project (where MR refs live)-//! └─▶ Set up push to fork URL (from source project)-//! ```-//!-//! Push permissions are not checked upfront — if the user lacks permission-//! (doesn't own fork, maintainer edits disabled), push will fail with a clear-//! error. This avoids complex permission detection logic.-//!-//! # Same-Repo MRs-//!-//! When `source_project_id == target_project_id`, the MR's branch exists in-//! the primary remote:-//!-//! 1. Resolve `source_branch` (e.g., `"feature-auth"`)-//! 2. Check if worktree exists for that branch → switch to it-//! 3. Otherwise, create worktree for the branch (DWIM from remote)-//! 4. Pushing works normally: `git push`-//!-//! This is equivalent to `wt switch feature-auth` — the `mr:` syntax is just-//! a convenience for looking up the branch name.-//!-//! # Fork MRs-//!-//! When `source_project_id != target_project_id`, the branch exists in a fork,-//! not the target project.-//!-//! ## The Problem: MR Refs Are Read-Only-//!-//! GitLab's `refs/merge-requests/<N>/head` refs are **read-only** and cannot be-//! pushed to. Similar to GitHub, the only way to update a fork MR is to push-//! directly to the fork's branch.-//!-//! ## Push Strategy (No Remote Required)-//!-//! Git's `branch.<name>.pushRemote` config accepts a URL directly, not just a-//! named remote. This means we can set up push tracking without adding remotes:-//!-//! ```text-//! branch.contributor/feature.remote = origin-//! branch.contributor/feature.merge = refs/merge-requests/101/head-//! branch.contributor/feature.pushRemote = [email protected]:contributor/repo.git-//! ```-//!-//! This configuration gives us:-//! - `git pull` fetches from the target repo's MR ref (stays up to date with MR)-//! - `git push` pushes to the fork URL (updates the MR)-//! - No stray remotes cluttering `git remote -v`-//!-//! ## Checkout Flow (Fork MRs)-//!-//! ```text-//! 1. Get MR metadata from glab mr view-//! │-//! ▼-//! 2. Find remote for target project (where MR refs live)-//! e.g., origin → gitlab.com/group/project-//! │-//! ▼-//! 3. Fetch MR head from that remote-//! git fetch origin merge-requests/101/head-//! │-//! ▼-//! 4. Create local branch from FETCH_HEAD-//! git branch <local-branch> FETCH_HEAD-//! │-//! ▼-//! 5. Configure branch tracking-//! git config branch.<local-branch>.remote origin-//! git config branch.<local-branch>.merge refs/merge-requests/101/head-//! git config branch.<local-branch>.pushRemote <fork-url>-//! │-//! ▼-//! 6. Create worktree for the branch-//! ```-//!-//! ## Local Branch Naming-//!-//! **The local branch name must match the fork's branch name** for `git push`-//! to work. With `push.default = current` (the common default), git pushes to-//! a same-named branch on the pushRemote. If the names differ, push fails.-//!-//! # Error Handling-//!-//! ## MR Not Found-//!-//! ```text-//! ✗ MR !101 not found-//! ```-//!-//! ## glab Not Authenticated-//!-//! ```text-//! ✗ GitLab CLI not authenticated-//! ↳ Run glab auth login to authenticate-//! ```-//!-//! ## glab Not Installed-//!-//! ```text-//! ✗ GitLab CLI (glab) required for mr: syntax-//! ↳ Install from https://gitlab.com/gitlab-org/cli-//! ```-//!-//! ## --create Conflict-//!-//! ```text-//! ✗ Cannot use --create with mr: syntax-//! ↳ The MR's branch already exists; remove --create-//! ```-//!-//! # Platform Notes-//!-//! This feature is GitLab-specific. For GitHub PRs, use `pr:<number>` syntax-//! (see `pr_ref` module).+//! # GitLab-Specific Notes//!//! GitLab's permission model differs from GitHub's "maintainer edits" feature.//! GitLab uses the `allow_collaboration` flag to indicate if fork maintainers//! can push to the MR branch.+//!+//! ## API Fields+//!+//! We use `glab mr view <number> --output json` which returns:+//! - `source_branch` — MR branch name+//! - `source_project_id`, `target_project_id` — for fork detection+//! - `source_project.ssh_url_to_repo`, `http_url_to_repo` — fork URLs+//! - `target_project.ssh_url_to_repo`, `http_url_to_repo` — target URLs+//! - `web_url` — MR web URLuse std::io::ErrorKind;+use std::path::Path;use anyhow::{Context, bail};use serde::Deserialize;@@ -401,7 +262,7 @@ pub fn target_remote_url(mr: &MrInfo) -> Option<String> {/// Returns `Some(true)` if the branch is configured to track `refs/merge-requests/<mr_number>/head`./// Returns `Some(false)` if the branch exists but tracks something else./// Returns `None` if the branch doesn't exist.-pub fn branch_tracks_mr(repo_root: &std::path::Path, branch: &str, mr_number: u32) -> Option<bool> {+pub fn branch_tracks_mr(repo_root: &Path, branch: &str, mr_number: u32) -> Option<bool> {let expected_ref = format!("refs/merge-requests/{}/head", mr_number);super::branch_tracks_ref(repo_root, branch, &expected_ref)}diff --git a/src/git/pr_ref.rs b/src/git/pr_ref.rsindex 68ad9f84e..de3141b6e 100644--- a/src/git/pr_ref.rs+++ b/src/git/pr_ref.rs@@ -1,229 +1,9 @@-//! PR reference resolution (`pr:<number>` syntax).+//! GitHub PR reference resolution (`pr:<number>` syntax).//!-//! This module resolves PR numbers to branches, enabling `wt switch pr:101` to-//! check out the branch associated with a pull request.+//! This module resolves PR numbers to branches for `wt switch pr:101`.+//! For shared documentation on PR/MR resolution, see the `remote_ref` module.//!-//! # Syntax-//!-//! The `pr:<number>` prefix is unambiguous because colons are invalid in git-//! branch names (git rejects them as "not a valid branch name").-//!-//! ```text-//! wt switch pr:101 # Switch to branch for PR #101-//! wt switch pr:101 --yes # Skip approval prompts-//! ```-//!-//! **Invalid usage:**-//!-//! ```text-//! wt switch --create pr:101 # Error: PR branch already exists-//! ```-//!-//! The `--create` flag is incompatible with `pr:` because the branch must-//! already exist (it's the PR's head branch).-//!-//! # Resolution Flow-//!-//! ```text-//! pr:101-//! │-//! ▼-//! ┌─────────────────────────────────────────────────────────┐-//! │ gh api repos/{owner}/{repo}/pulls/101 │-//! │ → head.ref, head.repo, base.repo, html_url │-//! └─────────────────────────────────────────────────────────┘-//! │-//! ├─── base.repo == head.repo ───▶ Same-repo PR-//! │ │-//! │ └─▶ Branch exists in primary remote, use directly-//! │-//! └─── base.repo != head.repo ───▶ Fork PR-//! │-//! ├─▶ Find remote for base.repo (where PR refs live)-//! └─▶ Set up push to fork URL-//! ```-//!-//! Push permissions are not checked upfront — if the user lacks permission-//! (doesn't own fork, maintainer edits disabled), push will fail with a clear-//! error. This avoids complex permission detection logic.-//!-//! # Same-Repo PRs-//!-//! When `base.repo == head.repo`, the PR's branch exists in the primary remote:-//!-//! 1. Resolve `head.ref` (e.g., `"feature-auth"`)-//! 2. Check if worktree exists for that branch → switch to it-//! 3. Otherwise, create worktree for the branch (DWIM from remote)-//! 4. Pushing works normally: `git push`-//!-//! This is equivalent to `wt switch feature-auth` — the `pr:` syntax is just-//! a convenience for looking up the branch name.-//!-//! # Fork PRs-//!-//! When `base.repo != head.repo`, the branch exists in a fork, not the base repo.-//!-//! ## The Problem: PR Refs Are Read-Only-//!-//! GitHub's `refs/pull/<N>/head` refs are **read-only** and cannot be pushed to.-//! This is explicitly documented by GitHub — the `refs/pull/` namespace is a-//! "hidden ref" that GitHub manages automatically:-//!-//! ```text-//! $ git push origin HEAD:refs/pull/101/head-//! ! [remote rejected] HEAD -> refs/pull/101/head (deny updating a hidden ref)-//! ```-//!-//! There is no alternative writable ref on the base repo. The only way to update-//! a fork PR is to push directly to the fork's branch.-//!-//! The "Allow edits from maintainers" feature grants push access to the fork's-//! branch itself — it's a permission change on the fork, not a proxy through-//! the base repo's refs.-//!-//! ## Push Strategy (No Remote Required)-//!-//! Git's `branch.<name>.pushRemote` config accepts a URL directly, not just a-//! named remote. This means we can set up push tracking without adding remotes:-//!-//! ```text-//! branch.contributor/feature.remote = upstream-//! branch.contributor/feature.merge = refs/pull/101/head-//! branch.contributor/feature.pushRemote = [email protected]:contributor/repo.git-//! ```-//!-//! This configuration gives us:-//! - `git pull` fetches from the base repo's PR ref (stays up to date with PR)-//! - `git push` pushes to the fork URL (updates the PR)-//! - No stray remotes cluttering `git remote -v`-//!-//! ## Checkout Flow (Fork PRs)-//!-//! ```text-//! 1. Get PR metadata from gh api-//! │-//! ▼-//! 2. Find remote for base repo (where PR refs live)-//! e.g., upstream → github.com/owner/repo-//! │-//! ▼-//! 3. Fetch PR head from that remote-//! git fetch upstream pull/101/head-//! │-//! ▼-//! 4. Create local branch from FETCH_HEAD-//! git branch <local-branch> FETCH_HEAD-//! │-//! ▼-//! 5. Configure branch tracking-//! git config branch.<local-branch>.remote upstream-//! git config branch.<local-branch>.merge refs/pull/101/head-//! git config branch.<local-branch>.pushRemote <fork-url>-//! │-//! ▼-//! 6. Create worktree for the branch-//! ```-//!-//! ## Local Branch Naming-//!-//! **The local branch name must match the fork's branch name** for `git push`-//! to work. With `push.default = current` (the common default), git pushes to-//! a same-named branch on the pushRemote. If the names differ, push fails:-//!-//! ```text-//! # If local branch is "contributor/feature" but fork has "feature":-//! $ git push-//! error: src refspec contributor/feature does not match any-//! ```-//!-//! Git has no per-branch configuration for "push to a differently-named branch."-//! The only options are explicit refspecs (`git push HEAD:feature`) or matching-//! names. We choose matching names so `git push` "just works."-//!-//! - **Same-repo PR**: Use `headRefName` directly (e.g., `feature-auth`)-//! - **Fork PR**: Use `headRefName` directly (e.g., `feature-auth`)-//!-//! This means two fork PRs with the same branch name would conflict. The-//! `branch_tracks_pr()` check handles this by erroring if a branch exists-//! but tracks a different PR.-//!-//! ## Push Behavior-//!-//! After checkout, `git push` sends to the fork URL:-//!-//! ```text-//! $ git push-//! # Pushes to [email protected]:contributor/repo.git-//! # PR automatically updates on GitHub-//! ```-//!-//! No named remote is added — the URL is used directly via `pushRemote`.-//!-//! # Error Handling-//!-//! ## PR Not Found-//!-//! ```text-//! ✗ PR #101 not found-//! ↳ Run gh repo set-default --view to check which repo is being queried-//! ```-//!-//! This often happens when the primary remote points to a fork but `gh` hasn't-//! been configured to look at the upstream repo. Fix with `gh repo set-default`.-//!-//! ## gh Not Authenticated-//!-//! ```text-//! ✗ GitHub CLI not authenticated-//! ↳ Run gh auth login to authenticate-//! ```-//!-//! ## gh Not Installed-//!-//! ```text-//! ✗ GitHub CLI (gh) required for pr: syntax-//! ↳ Install from https://cli.github.com/-//! ```-//!-//! ## --create Conflict-//!-//! ```text-//! ✗ Cannot use --create with pr: syntax-//! ↳ The PR's branch already exists; remove --create-//! ```-//!-//! # Edge Cases-//!-//! ## Branch Name Collisions-//!-//! If user already has a local branch with the same name as the PR's branch:-//!-//! - Check if it tracks the same PR ref → reuse it-//! - Otherwise → error with suggestion to rename their branch first-//!-//! ## Worktree Already Exists-//!-//! If worktree already exists for the resolved branch:-//!-//! - Switch to it (normal `wt switch` behavior)-//! - Don't re-fetch or re-configure-//!-//! ## Draft PRs-//!-//! Draft PRs are checkable like regular PRs. The `isDraft` field could be-//! shown in output but doesn't affect behavior.-//!-//! ## Renamed Branches-//!-//! If the PR's head branch was renamed after PR creation, `headRefName`-//! reflects the current name. We always use the current name.-//!-//! # Platform Support-//!-//! This feature is GitHub-specific. For GitLab merge requests, use the-//! `mr:<number>` syntax (see `mr_ref` module).-//!-//! # Implementation Notes+//! # GitHub-Specific Notes//!//! ## Repository Resolution//!@@ -234,66 +14,20 @@//! The `gh` CLI handles this via `gh repo set-default`://!//! ```text-//! # Stores in git config: remote.origin.gh-resolved = base-//! gh repo set-default owner/upstream-repo-//!-//! # View current setting-//! gh repo set-default --view+//! gh repo set-default owner/upstream-repo # Stores: remote.origin.gh-resolved = base+//! gh repo set-default --view # View current setting//! ```//!-//! If `gh-resolved` is not set, `gh` may prompt interactively or use heuristics-//! (checking if the repo is a fork and using its parent).-//!-//! **Diagnostics:** `wt config show` should display the resolved repo so users-//! understand which repo PR lookups will query.+//! If `gh-resolved` is not set, `gh` may prompt interactively or use heuristics.//!-//! ## GitHub API Fields+//! ## API Fields//!//! We use `gh api repos/{owner}/{repo}/pulls/<number>` which returns://! - `head.ref`, `head.repo.owner.login`, `head.repo.name` — PR branch info//! - `base.repo.owner.login`, `base.repo.name` — target repo (where PR refs live)//! - `html_url` — PR web URL-//!-//! ## Remote URL Construction-//!-//! For SSH remotes:-//! ```text-//! [email protected]:<owner>/<repo>.git-//! ```-//!-//! For HTTPS remotes:-//! ```text-//! https://github.com/<owner>/<repo>.git-//! ```-//!-//! We match the protocol of the existing primary remote to be consistent-//! with the user's authentication setup.-//!-//! ## Caching-//!-//! PR metadata is not cached — we always fetch fresh to ensure we have-//! current state (PR might have been closed, branch might have been pushed).-//!-//! # Testing Strategy-//!-//! ## Unit Tests-//!-//! - PR number parsing from `pr:<number>` syntax-//! - Local branch name generation-//! - URL construction matching primary remote protocol-//!-//! ## Integration Tests (with mock gh)-//!-//! - Same-repo PR checkout-//! - Fork PR checkout-//! - Existing worktree reuse-//! - Error cases: PR not found, gh not authenticated-//!-//! ## Manual Testing-//!-//! - Fork PR push/pull cycle-//! - Interaction with `wt merge`-//! - Multiple fork PRs with same branch name++use std::path::Path;use anyhow::{Context, bail};use serde::Deserialize;@@ -549,7 +283,7 @@ fn fork_remote_url_https(host: &str, owner: &str, repo: &str) -> String {/// Returns `Some(true)` if the branch is configured to track `refs/pull/<pr_number>/head`./// Returns `Some(false)` if the branch exists but tracks something else./// Returns `None` if the branch doesn't exist.-pub fn branch_tracks_pr(repo_root: &std::path::Path, branch: &str, pr_number: u32) -> Option<bool> {+pub fn branch_tracks_pr(repo_root: &Path, branch: &str, pr_number: u32) -> Option<bool> {let expected_ref = format!("refs/pull/{}/head", pr_number);super::branch_tracks_ref(repo_root, branch, &expected_ref)}diff --git a/src/git/remote_ref.rs b/src/git/remote_ref.rsnew file mode 100644index 000000000..553cdfee1--- /dev/null+++ b/src/git/remote_ref.rs@@ -0,0 +1,115 @@+//! Unified PR/MR reference resolution (`pr:<number>` and `mr:<number>` syntax).+//!+//! This module provides shared infrastructure for resolving GitHub PRs and GitLab MRs.+//! Platform-specific implementations live in `pr_ref` and `mr_ref` modules.+//!+//! # Syntax+//!+//! The `pr:<number>` and `mr:<number>` prefixes are unambiguous because colons are+//! invalid in git branch names (git rejects them as "not a valid branch name").+//!+//! ```text+//! wt switch pr:101 # Switch to branch for GitHub PR #101+//! wt switch mr:42 # Switch to branch for GitLab MR !42+//! wt switch pr:101 --yes # Skip approval prompts+//! ```+//!+//! **Invalid usage:**+//!+//! ```text+//! wt switch --create pr:101 # Error: PR/MR branch already exists+//! wt switch --base main pr:101 # Error: base is predetermined+//! ```+//!+//! # Resolution Flow+//!+//! Both PR and MR resolution follow the same pattern:+//!+//! ```text+//! pr:101 / mr:42+//! │+//! ▼+//! ┌─────────────────────────────────────────────────────────┐+//! │ Fetch metadata via CLI (gh api / glab mr view) │+//! │ → branch name, source/target repos, URLs │+//! └─────────────────────────────────────────────────────────┘+//! │+//! ├─── Same-repo ───▶ Branch exists in primary remote+//! │ │+//! │ └─▶ Use directly, standard switch+//! │+//! └─── Fork/Cross-repo ───▶ Branch exists in fork+//! │+//! ├─▶ Find remote for base/target repo (where refs live)+//! └─▶ Set up push to fork URL+//! ```+//!+//! # Fork PR/MR Handling+//!+//! ## The Problem: PR/MR Refs Are Read-Only+//!+//! Both GitHub's `refs/pull/<N>/head` and GitLab's `refs/merge-requests/<N>/head`+//! are **read-only** and cannot be pushed to. These are managed by the platform:+//!+//! ```text+//! $ git push origin HEAD:refs/pull/101/head+//! ! [remote rejected] HEAD -> refs/pull/101/head (deny updating a hidden ref)+//! ```+//!+//! The only way to update a fork PR/MR is to push directly to the fork's branch.+//!+//! ## Push Strategy (No Remote Required)+//!+//! Git's `branch.<name>.pushRemote` config accepts a URL directly, not just a+//! named remote. This means we can set up push tracking without adding remotes:+//!+//! ```text+//! branch.feature.remote = upstream+//! branch.feature.merge = refs/pull/101/head # or refs/merge-requests/42/head+//! branch.feature.pushRemote = [email protected]:contributor/repo.git+//! ```+//!+//! This configuration gives us:+//! - `git pull` fetches from the base repo's PR/MR ref (stays up to date)+//! - `git push` pushes to the fork URL (updates the PR/MR)+//! - No stray remotes cluttering `git remote -v`+//!+//! ## Local Branch Naming+//!+//! **The local branch name must match the fork's branch name** for `git push`+//! to work. With `push.default = current` (the common default), git pushes to+//! a same-named branch on the pushRemote. If the names differ, push fails.+//!+//! This means two fork PRs/MRs with the same branch name would conflict. The+//! `branch_tracks_ref()` check handles this by erroring if a branch exists+//! but tracks a different PR/MR.+//!+//! # Error Handling+//!+//! ## Not Found+//!+//! ```text+//! ✗ PR #101 not found+//! ✗ MR !42 not found+//! ```+//!+//! ## CLI Not Authenticated+//!+//! ```text+//! ✗ GitHub CLI not authenticated; run gh auth login+//! ✗ GitLab CLI not authenticated; run glab auth login+//! ```+//!+//! ## CLI Not Installed+//!+//! ```text+//! ✗ GitHub CLI (gh) not installed; install from https://cli.github.com/+//! ✗ GitLab CLI (glab) not installed; install from https://gitlab.com/gitlab-org/cli+//! ```+//!+//! ## --create Conflict+//!+//! ```text+//! ✗ Cannot use --create with pr:101+//! ↳ PRs already have a branch; remove --create+//! ```diff --git a/src/git/repository/remotes.rs b/src/git/repository/remotes.rsindex 764c7d421..c1aeac9aa 100644--- a/src/git/repository/remotes.rs+++ b/src/git/repository/remotes.rs@@ -68,10 +68,19 @@ impl Repository {/// 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 for owner).+ /// whose URL matches the given owner and repo (case-insensitive).+ ///+ /// When `host` is `Some`, the remote must also match the host. This is+ /// important for multi-host setups (e.g., both github.com and+ /// github.enterprise.com).////// Returns `None` if no matching remote is found.- pub fn find_remote_for_repo(&self, owner: &str, repo: &str) -> Option<String> {+ pub fn find_remote_for_repo(+ &self,+ host: Option<&str>,+ owner: &str,+ repo: &str,+ ) -> Option<String> {// Get all remotes with URLslet output = self.run_command(&["config", "--get-regexp", r"remote\..+\.url"])@@ -85,6 +94,8 @@ impl Repository {// Case-insensitive comparison (GitHub owner/repo names are case-insensitive)&& 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)){return Some(name.to_string());}@@ -95,13 +106,16 @@ impl Repository {/// Find a remote that points to the same project as the given URL.///- /// Parses the URL to extract owner/repo, then searches configured remotes.+ /// Parses the URL to extract host/owner/repo, then searches configured remotes.+ /// Host matching ensures correct remote selection in multi-host setups+ /// (e.g., both gitlab.com and gitlab.enterprise.com).+ ////// Useful for GitLab MRs where glab provides URLs directly.////// Returns `None` if the URL can't be parsed or no matching remote is found.pub fn find_remote_by_url(&self, target_url: &str) -> Option<String> {let parsed = GitRemoteUrl::parse(target_url)?;- self.find_remote_for_repo(parsed.owner(), parsed.repo())+ self.find_remote_for_repo(Some(parsed.host()), parsed.owner(), parsed.repo())}/// Get all configured remote URLs.