Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(git): consolidate PR/MR resolution into unified remote_ref module (#893)
Maximilian Roos44b61be8fc4b
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 5ab8f3fbf..34f835fca 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::mr_ref;-use worktrunk::git::pr_ref::{self, fork_remote_url, prefixed_local_branch_name};+use worktrunk::git::remote_ref::{+ self, GitHubProvider, GitLabProvider, RemoteRefInfo, RemoteRefProvider,+};use worktrunk::git::{GitError, RefContext, RefType, Repository};use worktrunk::styling::{eprintln, format_with_gutter, hint_message, info_message, progress_message, suggest_command,@@ -52,281 +53,262 @@ fn format_ref_context(ctx: &impl RefContext) -> String {)}-/// Resolve a PR reference (`pr:<number>` syntax).-fn resolve_pr_ref(+/// Resolve a remote ref (PR or MR) using the unified provider interface.+fn resolve_remote_ref(repo: &Repository,- pr_number: u32,+ provider: &dyn RemoteRefProvider,+ number: u32,create: bool,base: Option<&str>,) -> anyhow::Result<ResolvedTarget> {- // --base is invalid with pr: syntax (check early, no network needed)+ let ref_type = provider.ref_type();+ let symbol = ref_type.symbol();++ // --base is invalid with pr:/mr: syntax (check early, no network needed)if base.is_some() {- return Err(GitError::RefBaseConflict {- ref_type: RefType::Pr,- number: pr_number,- }- .into());+ return Err(GitError::RefBaseConflict { ref_type, number }.into());}- // Fetch PR info (network call via gh CLI)+ // Fetch ref info (network call via gh/glab CLI)eprintln!("{}",- progress_message(cformat!("Fetching PR #{pr_number}..."))+ progress_message(cformat!("Fetching {} {symbol}{number}...", ref_type.name())));let repo_root = repo.repo_path();- let pr_info = pr_ref::fetch_pr_info(pr_number, repo_root)?;+ let info = provider.fetch_info(number, repo_root)?;- // Display PR context with URL (as gutter under fetch progress)- eprintln!(- "{}",- format_with_gutter(&format_ref_context(&pr_info), None)- );+ // Display context with URL (as gutter under fetch progress)+ eprintln!("{}", format_with_gutter(&format_ref_context(&info), None));- // --create is invalid with pr: syntax (check after fetch to show branch name)+ // --create is invalid with pr:/mr: syntax (check after fetch to show branch name)if create {return Err(GitError::RefCreateConflict {- ref_type: RefType::Pr,- number: pr_number,- branch: pr_info.head_ref_name.clone(),+ ref_type,+ number,+ branch: info.source_branch.clone(),}.into());}- 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);+ if info.is_cross_repo {+ return resolve_fork_ref(repo, provider, number, &info);+ }- // Determine if we need to use a prefixed branch name due to conflicts- let (final_branch, fork_push_url) = if let Some(tracks_this) =- pr_ref::branch_tracks_pr(repo_root, &local_branch, pr_number)- {- if tracks_this {- eprintln!(- "{}",- 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 doesn't track this PR - use prefixed name- let prefixed = prefixed_local_branch_name(&pr_info);-- // Check if the prefixed branch also exists and tracks this PR- if let Some(prefixed_tracks) =- pr_ref::branch_tracks_pr(repo_root, &prefixed, pr_number)- {- if prefixed_tracks {- eprintln!(- "{}",- info_message(cformat!(- "Branch <bold>{prefixed}</> already configured for PR #{pr_number}"- ))- );- return Ok(ResolvedTarget {- branch: prefixed,- method: CreationMethod::Regular {- create_branch: false,- base_branch: None,- },- });- }- // Prefixed branch exists but tracks something else - error- return Err(GitError::BranchTracksDifferentRef {+ // Same-repo ref: for PRs, fetch the branch; for MRs, just use the branch name+ resolve_same_repo_ref(repo, &info)+}++/// Resolve a fork (cross-repo) PR/MR.+fn resolve_fork_ref(+ repo: &Repository,+ provider: &dyn RemoteRefProvider,+ number: u32,+ info: &RemoteRefInfo,+) -> anyhow::Result<ResolvedTarget> {+ let ref_type = provider.ref_type();+ let repo_root = repo.repo_path();+ let local_branch = remote_ref::local_branch_name(info);++ // Check if branch already exists and is tracking this ref+ if let Some(tracks_this) =+ remote_ref::branch_tracks_ref(repo_root, &local_branch, provider, number)+ {+ if tracks_this {+ eprintln!(+ "{}",+ info_message(cformat!(+ "Branch <bold>{local_branch}</> already configured for {}",+ ref_type.display(number)+ ))+ );+ return Ok(ResolvedTarget {+ branch: local_branch,+ method: CreationMethod::Regular {+ create_branch: false,+ base_branch: None,+ },+ });+ }++ // Branch exists but doesn't track this ref - try prefixed name (GitHub only)+ if let Some(prefixed) = info.prefixed_local_branch_name() {+ if let Some(prefixed_tracks) =+ remote_ref::branch_tracks_ref(repo_root, &prefixed, provider, number)+ {+ if prefixed_tracks {+ eprintln!(+ "{}",+ info_message(cformat!(+ "Branch <bold>{prefixed}</> already configured for {}",+ ref_type.display(number)+ ))+ );+ return Ok(ResolvedTarget {branch: prefixed,- ref_type: RefType::Pr,- number: pr_number,- }- .into());+ method: CreationMethod::Regular {+ create_branch: false,+ base_branch: None,+ },+ });}-- // Use prefixed branch name; push won't work (None for fork_push_url)- (prefixed, None)+ // Prefixed branch exists but tracks something else - error+ return Err(GitError::BranchTracksDifferentRef {+ branch: prefixed,+ ref_type,+ number,+ }+ .into());}- } else {- // Branch doesn't exist - use unprefixed name with push support- let fork_push_url =- fork_remote_url(&pr_info.host, &pr_info.head_owner, &pr_info.head_repo);- (local_branch, Some(fork_push_url))- };- // 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,- }- })?;+ // Use prefixed branch name; push won't work (None for fork_push_url)+ // This is GitHub-only (GitLab doesn't support prefixed names)+ let remote = find_github_remote(repo, info)?;+ return Ok(ResolvedTarget {+ branch: prefixed,+ method: CreationMethod::ForkRef {+ ref_type,+ number,+ ref_path: provider.ref_path(number),+ fork_push_url: None,+ ref_url: info.url.clone(),+ remote,+ },+ });+ }- return Ok(ResolvedTarget {- branch: final_branch,- method: CreationMethod::ForkRef {- ref_type: RefType::Pr,- number: pr_number,- fork_push_url,- ref_url: pr_info.url,- remote,- },- });+ // GitLab doesn't support prefixed branch names - error+ return Err(GitError::BranchTracksDifferentRef {+ branch: local_branch,+ ref_type,+ number,+ }+ .into());}- // 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,+ // Branch doesn't exist - need to create it with push support.+ // 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+ let remote = find_github_remote(repo, info)?;+ (info.fork_push_url.clone(), remote)+ }+ RefType::Mr => {+ // GitLab: fetch project URLs now (deferred from fetch_mr_info for perf)+ let urls =+ worktrunk::git::remote_ref::gitlab::fetch_gitlab_project_urls(info, repo_root)?;+ let target_url = urls.target_url.ok_or_else(|| {+ anyhow::anyhow!(+ "{} is from a fork but glab didn't provide target project URL; \+ upgrade glab or checkout the fork branch manually",+ ref_type.display(number)+ )+ })?;+ // TODO(gitlab-protocol): We only try the URL based on glab's git_protocol setting.+ // If the user's remote uses the other protocol (ssh vs https), we'll fail to find it.+ // Consider trying both ssh and https URLs before erroring.+ 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+ )+ })?;+ if urls.fork_push_url.is_none() {+ anyhow::bail!(+ "{} is from a fork but glab didn't provide source project URL; \+ upgrade glab or checkout the fork branch manually",+ ref_type.display(number)+ );}- })?;- let branch = &pr_info.head_ref_name;-- eprintln!(- "{}",- progress_message(cformat!("Fetching <bold>{branch}</> from {remote}..."))- );- repo.run_command(&["fetch", &remote, branch])- .with_context(|| format!("Failed to fetch branch '{}' from {}", branch, remote))?;+ (urls.fork_push_url, remote)+ }+ };Ok(ResolvedTarget {- branch: pr_info.head_ref_name,- method: CreationMethod::Regular {- create_branch: false,- base_branch: None,+ branch: local_branch,+ method: CreationMethod::ForkRef {+ ref_type,+ number,+ ref_path: provider.ref_path(number),+ fork_push_url,+ ref_url: info.url.clone(),+ remote,},})}-/// Resolve an MR reference (`mr:<number>` syntax).-fn resolve_mr_ref(- repo: &Repository,- mr_number: u32,- create: bool,- base: Option<&str>,-) -> anyhow::Result<ResolvedTarget> {- // --base is invalid with mr: syntax (check early, no network needed)- if base.is_some() {- return Err(GitError::RefBaseConflict {- ref_type: RefType::Mr,- number: mr_number,- }- .into());- }-- // Fetch MR info (network call via glab CLI)- eprintln!(- "{}",- 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)?;+/// Find the remote for a GitHub PR (where PR refs live).+fn find_github_remote(repo: &Repository, info: &RemoteRefInfo) -> anyhow::Result<String> {+ use worktrunk::git::remote_ref::PlatformData;- // Display MR context with URL (as gutter under fetch progress)- eprintln!(- "{}",- format_with_gutter(&format_ref_context(&mr_info), None)- );+ let PlatformData::GitHub {+ host,+ base_owner,+ base_repo,+ ..+ } = &info.platform_data+ else {+ anyhow::bail!("find_github_remote called on non-GitHub ref");+ };- // --create is invalid with mr: syntax (check after fetch to show branch name)- if create {- return Err(GitError::RefCreateConflict {- ref_type: RefType::Mr,- number: mr_number,- branch: mr_info.source_branch.clone(),- }- .into());- }+ repo.find_remote_for_repo(Some(host), base_owner, base_repo)+ .ok_or_else(|| {+ let suggested_url =+ worktrunk::git::remote_ref::github::fork_remote_url(host, base_owner, base_repo);+ GitError::NoRemoteForRepo {+ owner: base_owner.clone(),+ repo: base_repo.clone(),+ suggested_url,+ }+ .into()+ })+}- 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);+/// Resolve a same-repo (non-fork) PR/MR.+fn resolve_same_repo_ref(+ repo: &Repository,+ info: &RemoteRefInfo,+) -> anyhow::Result<ResolvedTarget> {+ use worktrunk::git::remote_ref::PlatformData;- if let Some(tracks_this) = mr_ref::branch_tracks_mr(repo_root, &local_branch, mr_number) {- if tracks_this {- eprintln!(- "{}",- info_message(cformat!(- "Branch <bold>{local_branch}</> already configured for MR !{mr_number}"- ))+ // For GitHub PRs, fetch the branch to ensure remote refs are up-to-date+ if let PlatformData::GitHub {+ host,+ base_owner,+ base_repo,+ ..+ } = &info.platform_data+ {+ let remote = repo+ .find_remote_for_repo(Some(host), base_owner, base_repo)+ .ok_or_else(|| {+ let suggested_url = worktrunk::git::remote_ref::github::fork_remote_url(+ host, base_owner, base_repo,);- return Ok(ResolvedTarget {- branch: local_branch,- method: CreationMethod::Regular {- create_branch: false,- base_branch: None,- },- });- } else {- // TODO: Consider adding prefixed branch support for MRs like we do for PRs.- // For now, MRs with conflicting branch names return an error.- // See https://github.com/max-sixty/worktrunk/issues/714 for PR support.- return Err(GitError::BranchTracksDifferentRef {- branch: local_branch,- ref_type: RefType::Mr,- number: mr_number,+ GitError::NoRemoteForRepo {+ owner: base_owner.clone(),+ repo: base_repo.clone(),+ suggested_url,}- .into());- }- }-- // 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: Some(fork_push_url),- ref_url: mr_info.url,- remote,- },- });+ })?;+ let branch = &info.source_branch;++ eprintln!(+ "{}",+ progress_message(cformat!("Fetching <bold>{branch}</> from {remote}..."))+ );+ // Use -- to prevent branch names starting with - from being interpreted as flags+ repo.run_command(&["fetch", "--", &remote, branch])+ .with_context(|| format!("Failed to fetch branch '{}' from {}", branch, remote))?;}- // Same-repo MR: just use the branch name+ // For GitLab same-repo MRs, we just use the branch name directly+Ok(ResolvedTarget {- branch: mr_info.source_branch,+ branch: info.source_branch.clone(),method: CreationMethod::Regular {create_branch: false,base_branch: None,@@ -345,13 +327,17 @@ fn resolve_switch_target(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);+ if let Some(suffix) = branch.strip_prefix("pr:")+ && let Ok(number) = suffix.parse::<u32>()+ {+ return resolve_remote_ref(repo, &GitHubProvider, 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);+ if let Some(suffix) = branch.strip_prefix("mr:")+ && let Ok(number) = suffix.parse::<u32>()+ {+ return resolve_remote_ref(repo, &GitLabProvider, number, create, base);}// Regular branch switch@@ -573,9 +559,10 @@ fn setup_fork_branch(}// Create worktree (delayed streaming: silent if fast, shows progress if slow)+ // Use -- to prevent branch names starting with - from being interpreted as flagslet worktree_path_str = worktree_path.to_string_lossy();repo.run_command_delayed_stream(- &["worktree", "add", worktree_path_str.as_ref(), branch],+ &["worktree", "add", "--", worktree_path_str.as_ref(), branch],Repository::SLOW_OPERATION_DELAY_MS,Some(progress_message(cformat!("Creating worktree for <bold>{}</>...", branch)).to_string(),@@ -783,19 +770,16 @@ pub fn execute_switch(CreationMethod::ForkRef {ref_type,number,+ ref_path,fork_push_url,ref_url: _,remote,} => {- // 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 ref (remote was resolved during planning)- repo.run_command(&["fetch", remote, &remote_ref])+ // Use -- to prevent refs starting with - from being interpreted as flags+ repo.run_command(&["fetch", "--", remote, ref_path]).with_context(|| format!("Failed to fetch {} from {}", label, remote))?;// Execute branch creation and configuration with cleanup on failure.@@ -803,7 +787,7 @@ pub fn execute_switch(repo,&branch,remote,- &remote_ref,+ ref_path,fork_push_url.as_deref(),&worktree_path,&label,diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rsindex be9f7ef72..f68178754 100644--- a/src/commands/worktree/types.rs+++ b/src/commands/worktree/types.rs@@ -75,6 +75,8 @@ pub enum CreationMethod {ref_type: RefType,/// The PR/MR number.number: u32,+ /// The ref path (e.g., "pull/123/head" or "merge-requests/42/head").+ ref_path: String,/// URL to push to (the fork's URL). `None` when using a prefixed branch/// name (e.g., `contributor/main`) because push won't work.fork_push_url: Option<String>,diff --git a/src/git/mod.rs b/src/git/mod.rsindex 786368a36..086036ad4 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -5,9 +5,7 @@ use std::path::PathBuf;// Submodulesmod diff;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.rsdeleted file mode 100644index 7021576e5..000000000--- a/src/git/mr_ref.rs+++ /dev/null@@ -1,715 +0,0 @@-//! GitLab MR reference resolution (`mr:<number>` syntax).-//!-//! This module resolves MR numbers to branches for `wt switch mr:42`.-//! For shared documentation on PR/MR resolution, see the `remote_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 api projects/:id/merge_requests/<number>` which returns:-//! - `source_branch` — MR branch name-//! - `source_project_id`, `target_project_id` — for fork detection-//! - `web_url` — MR web URL-//!-//! For fork URLs, we make additional API calls to fetch project details.--use std::io::ErrorKind;-use std::path::Path;--use anyhow::{Context, bail};-use serde::Deserialize;--use super::error::GitError;-use crate::shell_exec::Cmd;--/// Information about an MR retrieved from GitLab.-#[derive(Debug, Clone)]-pub struct MrInfo {- /// The MR number (iid in GitLab terms).- pub number: u32,- /// The MR title.- pub title: String,- /// The MR author's username.- pub author: String,- /// The MR state ("opened", "closed", "merged").- pub state: String,- /// Whether this is a draft/WIP MR.- pub draft: bool,- /// The branch name in the source project.- pub source_branch: String,- /// The source project ID.- pub source_project_id: u64,- /// The target project ID.- pub target_project_id: u64,- /// The source project's SSH URL (for fork push).- pub source_project_ssh_url: Option<String>,- /// The source project's HTTP URL (for fork push).- pub source_project_http_url: Option<String>,- /// The target project's SSH URL (for finding the correct remote).- pub target_project_ssh_url: Option<String>,- /// The target project's HTTP URL (for finding the correct remote).- pub target_project_http_url: Option<String>,- /// Whether this is a cross-project (fork) MR.- pub is_cross_project: bool,- /// The MR's web URL.- pub url: String,-}--impl super::RefContext for MrInfo {- fn ref_type(&self) -> super::RefType {- super::RefType::Mr- }- fn number(&self) -> u32 {- self.number- }- fn title(&self) -> &str {- &self.title- }- fn author(&self) -> &str {- &self.author- }- fn state(&self) -> &str {- &self.state- }- fn draft(&self) -> bool {- self.draft- }- fn url(&self) -> &str {- &self.url- }- fn source_ref(&self) -> String {- if self.is_cross_project {- // Try to extract owner from source project URL- let owner = self- .source_project_http_url- .as_ref()- .or(self.source_project_ssh_url.as_ref())- .and_then(|url| extract_owner_from_url(url));- match owner {- Some(owner) => format!("{}:{}", owner, self.source_branch),- None => self.source_branch.clone(),- }- } else {- self.source_branch.clone()- }- }-}--/// Extract owner from a git URL.-///-/// Handles both SSH (`[email protected]:owner/repo.git`) and HTTPS-/// (`https://gitlab.com/owner/repo.git`) formats.-fn extract_owner_from_url(url: &str) -> Option<String> {- // SSH format: [email protected]:owner/repo.git- if let Some(path) = url.strip_prefix("git@").and_then(|s| s.split(':').nth(1)) {- return path.split('/').next().map(|s| s.to_string());- }- // HTTPS format: https://gitlab.com/owner/repo.git- // After stripping prefix: "gitlab.com/owner/repo.git"- // nth(1) skips the host and returns the owner- if let Some(path) = url- .strip_prefix("https://")- .or_else(|| url.strip_prefix("http://"))- {- return path.split('/').nth(1).map(|s| s.to_string());- }- None-}--/// Raw JSON response from `glab api projects/:id/merge_requests/<number>`.-#[derive(Debug, Deserialize)]-struct GlabMrResponse {- title: String,- author: GlabAuthor,- state: String,- #[serde(default)]- draft: bool,- source_branch: String,- source_project_id: u64,- target_project_id: u64,- web_url: String,-}--/// Raw JSON response from `glab api projects/<id>`.-#[derive(Debug, Deserialize)]-struct GlabAuthor {- username: String,-}--#[derive(Debug, Deserialize)]-struct GlabProject {- ssh_url_to_repo: Option<String>,- http_url_to_repo: Option<String>,-}--/// Error response from GitLab API (stdout on failure).-/// Example: `{"message":"404 Not found","error":"404 Not found"}`-#[derive(Debug, Deserialize)]-struct GlabApiErrorResponse {- #[serde(default)]- message: String,- #[serde(default)]- error: String,-}--/// Parse a `mr:<number>` reference, returning the MR number if valid.-///-/// Returns `None` if the input doesn't match the `mr:<number>` pattern.-pub fn parse_mr_ref(input: &str) -> Option<u32> {- let suffix = input.strip_prefix("mr:")?;- suffix.parse().ok()-}--/// Fetch MR information from GitLab using the `glab` CLI.-///-/// Uses `glab api` to get MR metadata. For fork MRs, makes additional-/// API calls to fetch source and target project URLs.-///-/// # Errors-///-/// Returns an error if:-/// - `glab` is not installed or not authenticated-/// - The MR doesn't exist-/// - The JSON response is malformed-pub fn fetch_mr_info(mr_number: u32, repo_root: &std::path::Path) -> anyhow::Result<MrInfo> {- let api_path = format!("projects/:id/merge_requests/{}", mr_number);-- let output = match Cmd::new("glab")- .args(["api", &api_path])- .current_dir(repo_root)- .env("GLAB_NO_PROMPT", "1")- .run()- {- Ok(output) => output,- Err(e) => {- // Check if glab is not installed (OS error for command not found)- if e.kind() == ErrorKind::NotFound {- bail!(- "GitLab CLI (glab) not installed; install from https://gitlab.com/gitlab-org/cli#installation"- );- }- return Err(anyhow::Error::from(e).context("Failed to run glab api"));- }- };-- if !output.status.success() {- // Parse the JSON error response from stdout for structured error handling.- // GitLab API returns JSON with "message" or "error" field containing the error.- if let Ok(error_response) = serde_json::from_slice::<GlabApiErrorResponse>(&output.stdout) {- let error_text = if !error_response.message.is_empty() {- &error_response.message- } else {- &error_response.error- };-- // GitLab includes status code in error message: "404 Not found", "401 Unauthorized"- if error_text.starts_with("404") {- bail!("MR !{} not found", mr_number);- }- if error_text.starts_with("401") {- bail!("GitLab CLI not authenticated; run glab auth login");- }- if error_text.starts_with("403") {- bail!("GitLab API access forbidden for MR !{}", mr_number);- }- }-- // Fallback for non-JSON errors (network issues, glab not configured, etc.)- // Include stdout if stderr is empty, as some errors are reported there.- let stderr = String::from_utf8_lossy(&output.stderr);- let details = if stderr.trim().is_empty() {- String::from_utf8_lossy(&output.stdout).trim().to_string()- } else {- stderr.trim().to_string()- };- return Err(GitError::CliApiError {- ref_type: super::RefType::Mr,- message: format!("glab api failed for MR !{}", mr_number),- stderr: details,- }- .into());- }-- let response: GlabMrResponse = serde_json::from_slice(&output.stdout).with_context(|| {- format!(- "Failed to parse GitLab API response for MR !{}. \- This may indicate a GitLab API change.",- mr_number- )- })?;-- // Validate required fields are not empty- if response.source_branch.is_empty() {- bail!(- "MR !{} has empty branch name; the MR may be in an invalid state",- mr_number- );- }-- let is_cross_project = response.source_project_id != response.target_project_id;-- // Fetch project URLs for cross-project (fork) MRs.- // The GitLab MR API only returns project IDs, so we need separate API calls.- // TODO(perf): Defer URL fetching until after branch_tracks_mr check in switch.rs- // to avoid unnecessary API calls when branch already exists and tracks this MR.- let (source_project_ssh_url, source_project_http_url) = if is_cross_project {- fetch_project_urls(response.source_project_id, repo_root).with_context(|| {- format!(- "Failed to fetch source project {} for MR !{}",- response.source_project_id, mr_number- )- })?- } else {- (None, None)- };-- let (target_project_ssh_url, target_project_http_url) = if is_cross_project {- fetch_project_urls(response.target_project_id, repo_root).with_context(|| {- format!(- "Failed to fetch target project {} for MR !{}",- response.target_project_id, mr_number- )- })?- } else {- (None, None)- };-- Ok(MrInfo {- number: mr_number,- title: response.title,- author: response.author.username,- state: response.state,- draft: response.draft,- source_branch: response.source_branch,- source_project_id: response.source_project_id,- target_project_id: response.target_project_id,- source_project_ssh_url,- source_project_http_url,- target_project_ssh_url,- target_project_http_url,- is_cross_project,- url: response.web_url,- })-}--/// Fetch project URLs from GitLab API.-fn fetch_project_urls(- project_id: u64,- repo_root: &Path,-) -> anyhow::Result<(Option<String>, Option<String>)> {- let api_path = format!("projects/{}", project_id);-- let output = Cmd::new("glab")- .args(["api", &api_path])- .current_dir(repo_root)- .env("GLAB_NO_PROMPT", "1")- .run()?;-- if !output.status.success() {- bail!("Failed to fetch project {}", project_id);- }-- let response: GlabProject = serde_json::from_slice(&output.stdout)?;- Ok((response.ssh_url_to_repo, response.http_url_to_repo))-}--/// Generate the local branch name for an MR.-///-/// Uses `source_branch` directly for both same-repo and fork MRs. This ensures-/// the local branch name matches the remote branch name, which is required for-/// `git push` to work correctly with `push.default = current`.-pub fn local_branch_name(mr: &MrInfo) -> String {- mr.source_branch.clone()-}--/// Get the git protocol configured in `glab` (GitLab CLI).-///-/// Returns "https" or "ssh" based on `glab config get git_protocol`.-/// Defaults to "https" if the command fails or returns unexpected output.-pub fn get_git_protocol() -> String {- Cmd::new("glab")- .args(["config", "get", "git_protocol"])- .run()- .ok()- .filter(|output| output.status.success())- .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string())- .filter(|p| p == "ssh" || p == "https")- .unwrap_or_else(|| "https".to_string())-}--/// Get the fork remote URL for pushing.-///-/// For fork MRs, we need the source project's URL. GitLab provides both SSH and-/// HTTP URLs; we choose based on `glab config get git_protocol`.-///-/// Falls back to the other protocol if the preferred one is not available.-/// Returns `None` if neither URL is available (shouldn't happen for valid MRs).-pub fn fork_remote_url(mr: &MrInfo) -> Option<String> {- let use_ssh = get_git_protocol() == "ssh";-- if use_ssh {- mr.source_project_ssh_url- .clone()- .or_else(|| mr.source_project_http_url.clone())- } else {- mr.source_project_http_url- .clone()- .or_else(|| mr.source_project_ssh_url.clone())- }-}--/// Get the target project URL (where MR refs live).-///-/// For fork MRs, we need to fetch from the target project's MR refs. GitLab-/// provides both SSH and HTTP URLs; we choose based on `glab config get git_protocol`.-///-/// Returns `None` if glab didn't provide target project URLs (older versions).-pub fn target_remote_url(mr: &MrInfo) -> Option<String> {- let use_ssh = get_git_protocol() == "ssh";-- if use_ssh {- mr.target_project_ssh_url- .clone()- .or_else(|| mr.target_project_http_url.clone())- } else {- mr.target_project_http_url- .clone()- .or_else(|| mr.target_project_ssh_url.clone())- }-}--/// Check if a branch is tracking a specific MR.-///-/// 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: &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)-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn test_parse_mr_ref() {- assert_eq!(parse_mr_ref("mr:101"), Some(101));- assert_eq!(parse_mr_ref("mr:1"), Some(1));- assert_eq!(parse_mr_ref("mr:99999"), Some(99999));-- // Invalid cases- assert_eq!(parse_mr_ref("mr:"), None);- assert_eq!(parse_mr_ref("mr:abc"), None);- assert_eq!(parse_mr_ref("mr:-1"), None);- assert_eq!(parse_mr_ref("MR:101"), None); // case-sensitive- assert_eq!(parse_mr_ref("feature-branch"), None);- assert_eq!(parse_mr_ref("101"), None);- assert_eq!(parse_mr_ref("pr:101"), None); // wrong prefix- }-- #[test]- fn test_local_branch_name() {- let mr = MrInfo {- number: 101,- title: "Fix authentication bug".to_string(),- author: "alice".to_string(),- state: "opened".to_string(),- draft: false,- source_branch: "feature-auth".to_string(),- source_project_id: 123,- target_project_id: 123,- source_project_ssh_url: None,- source_project_http_url: None,- target_project_ssh_url: None,- target_project_http_url: None,- is_cross_project: false,- url: "https://gitlab.com/owner/repo/-/merge_requests/101".to_string(),- };- assert_eq!(local_branch_name(&mr), "feature-auth");- }-- #[test]- fn test_local_branch_name_fork() {- // Fork MRs also use source_branch directly (not owner/branch) because- // the local branch name must match the fork's branch for git push to work- let mr = MrInfo {- number: 101,- title: "Fix authentication bug".to_string(),- author: "contributor".to_string(),- state: "opened".to_string(),- draft: false,- source_branch: "feature-auth".to_string(),- source_project_id: 456,- target_project_id: 123,- source_project_ssh_url: Some("[email protected]:contributor/repo.git".to_string()),- source_project_http_url: Some("https://gitlab.com/contributor/repo.git".to_string()),- target_project_ssh_url: Some("[email protected]:owner/repo.git".to_string()),- target_project_http_url: Some("https://gitlab.com/owner/repo.git".to_string()),- is_cross_project: true,- url: "https://gitlab.com/owner/repo/-/merge_requests/101".to_string(),- };- assert_eq!(local_branch_name(&mr), "feature-auth");- }-- #[test]- fn test_fork_remote_url_with_both_urls() {- let mr = MrInfo {- number: 101,- title: "Feature".to_string(),- author: "contributor".to_string(),- state: "opened".to_string(),- draft: false,- source_branch: "feature".to_string(),- source_project_id: 456,- target_project_id: 123,- source_project_ssh_url: Some("[email protected]:contributor/repo.git".to_string()),- source_project_http_url: Some("https://gitlab.com/contributor/repo.git".to_string()),- target_project_ssh_url: Some("[email protected]:owner/repo.git".to_string()),- target_project_http_url: Some("https://gitlab.com/owner/repo.git".to_string()),- is_cross_project: true,- url: "https://gitlab.com/owner/repo/-/merge_requests/101".to_string(),- };-- // When both URLs are available, returns one based on glab config- let url = fork_remote_url(&mr);- assert!(url.is_some());- let url = url.unwrap();- let valid_urls = [- "[email protected]:contributor/repo.git",- "https://gitlab.com/contributor/repo.git",- ];- assert!(valid_urls.contains(&url.as_str()), "unexpected URL: {url}");- }-- #[test]- fn test_fork_remote_url_ssh_only() {- let mr = MrInfo {- number: 101,- title: "Feature".to_string(),- author: "contributor".to_string(),- state: "opened".to_string(),- draft: false,- source_branch: "feature".to_string(),- source_project_id: 456,- target_project_id: 123,- source_project_ssh_url: Some("[email protected]:contributor/repo.git".to_string()),- source_project_http_url: None,- target_project_ssh_url: Some("[email protected]:owner/repo.git".to_string()),- target_project_http_url: None,- is_cross_project: true,- url: "https://gitlab.com/owner/repo/-/merge_requests/101".to_string(),- };-- // When only SSH is available, returns SSH regardless of config- let url = fork_remote_url(&mr);- assert_eq!(url, Some("[email protected]:contributor/repo.git".to_string()));- }-- #[test]- fn test_fork_remote_url_https_only() {- let mr = MrInfo {- number: 101,- title: "Feature".to_string(),- author: "contributor".to_string(),- state: "opened".to_string(),- draft: false,- source_branch: "feature".to_string(),- source_project_id: 456,- target_project_id: 123,- source_project_ssh_url: None,- source_project_http_url: Some("https://gitlab.com/contributor/repo.git".to_string()),- target_project_ssh_url: None,- target_project_http_url: Some("https://gitlab.com/owner/repo.git".to_string()),- is_cross_project: true,- url: "https://gitlab.com/owner/repo/-/merge_requests/101".to_string(),- };-- // When only HTTPS is available, returns HTTPS regardless of config- let url = fork_remote_url(&mr);- assert_eq!(- url,- Some("https://gitlab.com/contributor/repo.git".to_string())- );- }-- #[test]- fn test_fork_remote_url_none() {- let mr = MrInfo {- number: 101,- title: "Feature".to_string(),- author: "contributor".to_string(),- state: "opened".to_string(),- draft: false,- source_branch: "feature".to_string(),- source_project_id: 456,- target_project_id: 123,- source_project_ssh_url: None,- source_project_http_url: None,- target_project_ssh_url: None,- target_project_http_url: None,- is_cross_project: true,- url: "https://gitlab.com/owner/repo/-/merge_requests/101".to_string(),- };-- // When no source URLs are available, returns None- let url = fork_remote_url(&mr);- assert_eq!(url, None);- }-- #[test]- fn test_target_remote_url_with_both_urls() {- let mr = MrInfo {- number: 101,- title: "Feature".to_string(),- author: "contributor".to_string(),- state: "opened".to_string(),- draft: false,- source_branch: "feature".to_string(),- source_project_id: 456,- target_project_id: 123,- source_project_ssh_url: Some("[email protected]:contributor/repo.git".to_string()),- source_project_http_url: Some("https://gitlab.com/contributor/repo.git".to_string()),- target_project_ssh_url: Some("[email protected]:owner/repo.git".to_string()),- target_project_http_url: Some("https://gitlab.com/owner/repo.git".to_string()),- is_cross_project: true,- url: "https://gitlab.com/owner/repo/-/merge_requests/101".to_string(),- };-- // When both URLs are available, returns one based on glab config- let url = target_remote_url(&mr);- assert!(url.is_some());- let url = url.unwrap();- let valid_urls = [- "[email protected]:owner/repo.git",- "https://gitlab.com/owner/repo.git",- ];- assert!(valid_urls.contains(&url.as_str()), "unexpected URL: {url}");- }-- #[test]- fn test_target_remote_url_none() {- let mr = MrInfo {- number: 101,- title: "Feature".to_string(),- author: "contributor".to_string(),- state: "opened".to_string(),- draft: false,- source_branch: "feature".to_string(),- source_project_id: 456,- target_project_id: 123,- source_project_ssh_url: Some("[email protected]:contributor/repo.git".to_string()),- source_project_http_url: Some("https://gitlab.com/contributor/repo.git".to_string()),- target_project_ssh_url: None,- target_project_http_url: None,- is_cross_project: true,- url: "https://gitlab.com/owner/repo/-/merge_requests/101".to_string(),- };-- // When no target URLs are available, returns None- let url = target_remote_url(&mr);- assert_eq!(url, None);- }-- #[test]- fn test_extract_owner_from_url_ssh() {- assert_eq!(- extract_owner_from_url("[email protected]:owner/repo.git"),- Some("owner".to_string())- );- assert_eq!(- extract_owner_from_url("[email protected]:org/repo.git"),- Some("org".to_string())- );- }-- #[test]- fn test_extract_owner_from_url_https() {- assert_eq!(- extract_owner_from_url("https://gitlab.com/owner/repo.git"),- Some("owner".to_string())- );- assert_eq!(- extract_owner_from_url("http://gitlab.com/owner/repo.git"),- Some("owner".to_string())- );- }-- #[test]- fn test_extract_owner_from_url_invalid() {- assert_eq!(extract_owner_from_url("invalid-url"), None);- assert_eq!(extract_owner_from_url(""), None);- }-- #[test]- fn test_source_ref_same_project() {- let mr = MrInfo {- number: 101,- title: "Fix bug".to_string(),- author: "alice".to_string(),- state: "opened".to_string(),- draft: false,- source_branch: "feature-auth".to_string(),- source_project_id: 123,- target_project_id: 123,- source_project_ssh_url: None,- source_project_http_url: None,- target_project_ssh_url: None,- target_project_http_url: None,- is_cross_project: false,- url: "https://gitlab.com/owner/repo/-/merge_requests/101".to_string(),- };- use crate::git::RefContext;- assert_eq!(mr.source_ref(), "feature-auth");- }-- #[test]- fn test_source_ref_cross_project() {- let mr = MrInfo {- number: 101,- title: "Fix bug".to_string(),- author: "contributor".to_string(),- state: "opened".to_string(),- draft: false,- source_branch: "feature-fix".to_string(),- source_project_id: 456,- target_project_id: 123,- source_project_ssh_url: Some("[email protected]:contributor/repo.git".to_string()),- source_project_http_url: Some("https://gitlab.com/contributor/repo.git".to_string()),- target_project_ssh_url: None,- target_project_http_url: None,- is_cross_project: true,- url: "https://gitlab.com/owner/repo/-/merge_requests/101".to_string(),- };- use crate::git::RefContext;- assert_eq!(mr.source_ref(), "contributor:feature-fix");- }-- #[test]- fn test_source_ref_cross_project_no_url() {- // When URL parsing fails, falls back to just the branch name- let mr = MrInfo {- number: 101,- title: "Fix bug".to_string(),- author: "contributor".to_string(),- state: "opened".to_string(),- draft: false,- source_branch: "feature-fix".to_string(),- source_project_id: 456,- target_project_id: 123,- source_project_ssh_url: None,- source_project_http_url: None,- target_project_ssh_url: None,- target_project_http_url: None,- is_cross_project: true,- url: "https://gitlab.com/owner/repo/-/merge_requests/101".to_string(),- };- use crate::git::RefContext;- assert_eq!(mr.source_ref(), "feature-fix");- }-}diff --git a/src/git/pr_ref.rs b/src/git/pr_ref.rsdeleted file mode 100644index 6d1dfaf33..000000000--- a/src/git/pr_ref.rs+++ /dev/null@@ -1,519 +0,0 @@-//! GitHub PR reference resolution (`pr:<number>` syntax).-//!-//! This module resolves PR numbers to branches for `wt switch pr:101`.-//! For shared documentation on PR/MR resolution, see the `remote_ref` module.-//!-//! # GitHub-Specific Notes-//!-//! ## Repository Resolution-//!-//! `gh api` needs to know which GitHub repo to query. For fork workflows-//! where the primary remote points to a fork, `gh` needs to know to look at-//! the parent repo for PRs.-//!-//! The `gh` CLI handles this via `gh repo set-default`:-//!-//! ```text-//! 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.-//!-//! ## 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--use std::io::ErrorKind;-use std::path::Path;--use anyhow::{Context, bail};-use serde::Deserialize;--use super::error::GitError;-use crate::shell_exec::Cmd;--/// Information about a PR retrieved from GitHub.-#[derive(Debug, Clone)]-pub struct PrInfo {- /// The PR number.- pub number: u32,- /// The PR title.- pub title: String,- /// The PR author's username.- pub author: String,- /// The PR state ("open", "closed").- pub state: String,- /// Whether this is a draft PR.- pub draft: bool,- /// The branch name in the head repository.- pub head_ref_name: String,- /// The owner of the head repository (fork owner for cross-repo PRs).- pub head_owner: String,- /// The name of the head repository.- pub head_repo: String,- /// The owner of the base repository (where the PR was opened).- pub base_owner: String,- /// The name of the base repository.- pub base_repo: String,- /// Whether this is a cross-repository (fork) PR.- pub is_cross_repository: bool,- /// The GitHub host extracted from `html_url` (e.g., "github.com", "github.enterprise.com").- pub host: String,- /// The PR's web URL.- pub url: String,-}--impl super::RefContext for PrInfo {- fn ref_type(&self) -> super::RefType {- super::RefType::Pr- }- fn number(&self) -> u32 {- self.number- }- fn title(&self) -> &str {- &self.title- }- fn author(&self) -> &str {- &self.author- }- fn state(&self) -> &str {- &self.state- }- fn draft(&self) -> bool {- self.draft- }- fn url(&self) -> &str {- &self.url- }- fn source_ref(&self) -> String {- if self.is_cross_repository {- format!("{}:{}", self.head_owner, self.head_ref_name)- } else {- self.head_ref_name.clone()- }- }-}--/// Raw JSON response from `gh api repos/{owner}/{repo}/pulls/{number}`.-#[derive(Debug, Deserialize)]-struct GhApiPrResponse {- title: String,- user: GhUser,- state: String,- #[serde(default)]- draft: bool,- head: GhPrRef,- base: GhPrRef,- html_url: String,-}--/// Error response from GitHub API (stdout on failure).-/// Example: `{"message":"Not Found","documentation_url":"...","status":"404"}`-#[derive(Debug, Deserialize)]-struct GhApiErrorResponse {- #[serde(default)]- message: String,- /// HTTP status code as a string (e.g., "404", "401", "403")- #[serde(default)]- status: String,-}--#[derive(Debug, Deserialize)]-struct GhUser {- login: String,-}--#[derive(Debug, Deserialize)]-struct GhPrRef {- #[serde(rename = "ref")]- ref_name: String,- /// The repository for this ref. Can be `null` if the fork was deleted.- repo: Option<GhPrRepo>,-}--#[derive(Debug, Deserialize)]-struct GhPrRepo {- name: String,- owner: GhOwner,-}--#[derive(Debug, Deserialize)]-struct GhOwner {- login: String,-}--/// Parse a `pr:<number>` reference, returning the PR number if valid.-///-/// Returns `None` if the input doesn't match the `pr:<number>` pattern.-pub fn parse_pr_ref(input: &str) -> Option<u32> {- let suffix = input.strip_prefix("pr:")?;- suffix.parse().ok()-}--/// Fetch PR information from GitHub using the `gh` CLI.-///-/// Uses `gh api` to query the GitHub API directly, which provides-/// both head and base repository information.-///-/// # Errors-///-/// Returns an error if:-/// - `gh` is not installed or not authenticated-/// - The PR doesn't exist-/// - The JSON response is malformed-pub fn fetch_pr_info(pr_number: u32, repo_root: &std::path::Path) -> anyhow::Result<PrInfo> {- // Use gh api with {owner}/{repo} placeholders - gh resolves these from repo context- let api_path = format!("repos/{{owner}}/{{repo}}/pulls/{}", pr_number);-- let output = match Cmd::new("gh")- .args(["api", &api_path])- .current_dir(repo_root)- .env("GH_PROMPT_DISABLED", "1")- .run()- {- Ok(output) => output,- Err(e) => {- // Check if gh is not installed (OS error for command not found)- if e.kind() == ErrorKind::NotFound {- bail!("GitHub CLI (gh) not installed; install from https://cli.github.com/");- }- return Err(anyhow::Error::from(e).context("Failed to run gh api"));- }- };-- if !output.status.success() {- // Parse the JSON error response from stdout for structured error handling.- // GitHub API returns JSON with "status" field containing the HTTP status code.- if let Ok(error_response) = serde_json::from_slice::<GhApiErrorResponse>(&output.stdout) {- match error_response.status.as_str() {- "404" => bail!("PR #{} not found", pr_number),- "401" => bail!("GitHub CLI not authenticated; run gh auth login"),- "403" => {- // 403 can be rate limiting or permission denied- let message_lower = error_response.message.to_lowercase();- if message_lower.contains("rate limit") {- bail!("GitHub API rate limit exceeded; wait a few minutes and retry");- }- bail!("GitHub API access forbidden: {}", error_response.message);- }- _ => {}- }- }-- // Fallback for non-JSON errors (network issues, gh not configured, etc.)- // Include stdout if stderr is empty, as some errors are reported there.- let stderr = String::from_utf8_lossy(&output.stderr);- let details = if stderr.trim().is_empty() {- String::from_utf8_lossy(&output.stdout).trim().to_string()- } else {- stderr.trim().to_string()- };- return Err(GitError::CliApiError {- ref_type: super::RefType::Pr,- message: format!("gh api failed for PR #{}", pr_number),- stderr: details,- }- .into());- }-- let response: GhApiPrResponse = serde_json::from_slice(&output.stdout).with_context(|| {- format!(- "Failed to parse GitHub API response for PR #{}. \- This may indicate a GitHub API change.",- pr_number- )- })?;-- // Validate required fields are not empty- if response.head.ref_name.is_empty() {- bail!(- "PR #{} has empty branch name; the PR may be in an invalid state",- pr_number- );- }-- // Extract base repo (should always be present - the PR is opened against an existing repo)- let base_repo = response.base.repo.context(- "PR base repository is null; this is unexpected and may indicate a GitHub API issue",- )?;-- // Extract head repo (can be null if the fork was deleted)- let head_repo = response.head.repo.ok_or_else(|| {- anyhow::anyhow!(- "PR #{} source repository was deleted. \- The fork that this PR was opened from no longer exists, \- so the branch cannot be checked out.",- pr_number- )- })?;-- // Compute is_cross_repository by comparing base and head repos (case-insensitive)- let is_cross_repository = !base_repo- .owner- .login- .eq_ignore_ascii_case(&head_repo.owner.login)- || !base_repo.name.eq_ignore_ascii_case(&head_repo.name);-- // Extract host from html_url (e.g., "https://github.com/owner/repo/pull/123" → "github.com")- let host = response- .html_url- .strip_prefix("https://")- .or_else(|| response.html_url.strip_prefix("http://"))- .and_then(|s| s.split('/').next())- .filter(|h| !h.is_empty())- .with_context(|| format!("Failed to parse host from PR URL: {}", response.html_url))?- .to_string();-- Ok(PrInfo {- number: pr_number,- title: response.title,- author: response.user.login,- state: response.state,- draft: response.draft,- head_ref_name: response.head.ref_name,- head_owner: head_repo.owner.login,- head_repo: head_repo.name,- base_owner: base_repo.owner.login,- base_repo: base_repo.name,- is_cross_repository,- host,- url: response.html_url,- })-}--/// Generate the local branch name for a PR.-///-/// Uses `headRefName` directly for both same-repo and fork PRs. This ensures-/// the local branch name matches the remote branch name, which is required for-/// `git push` to work correctly with `push.default = current`.-///-/// See module docs for why we can't use a prefixed name like `<owner>/<branch>`.-pub fn local_branch_name(pr: &PrInfo) -> String {- pr.head_ref_name.clone()-}--/// Generate a prefixed local branch name for a fork PR when the unprefixed name conflicts.-///-/// Returns `<head_owner>/<head_ref_name>` (e.g., `contributor/main`).-///-/// This is used when the PR's branch name conflicts with an existing local branch.-/// Note: `git push` won't work with this naming because the local and remote-/// branch names don't match. Users must push manually with explicit refspecs.-pub fn prefixed_local_branch_name(pr: &PrInfo) -> String {- format!("{}/{}", pr.head_owner, pr.head_ref_name)-}--/// Get the git protocol preference from `gh` (GitHub CLI).-///-/// Returns `true` for SSH if `gh config get git_protocol` returns "ssh".-fn use_ssh_protocol() -> bool {- Cmd::new("gh")- .args(["config", "get", "git_protocol"])- .run()- .ok()- .filter(|output| output.status.success())- .map(|output| String::from_utf8_lossy(&output.stdout).trim() == "ssh")- .unwrap_or(false)-}--/// Construct the remote URL for a fork repository.-///-/// Uses `gh config get git_protocol` to determine SSH vs HTTPS preference.-pub fn fork_remote_url(host: &str, owner: &str, repo: &str) -> String {- if use_ssh_protocol() {- fork_remote_url_ssh(host, owner, repo)- } else {- fork_remote_url_https(host, owner, repo)- }-}--/// Construct an SSH-format remote URL.-fn fork_remote_url_ssh(host: &str, owner: &str, repo: &str) -> String {- format!("git@{}:{}/{}.git", host, owner, repo)-}--/// Construct an HTTPS-format remote URL.-fn fork_remote_url_https(host: &str, owner: &str, repo: &str) -> String {- format!("https://{}/{}/{}.git", host, owner, repo)-}--/// Check if a branch is tracking a specific PR.-///-/// 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: &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)-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn test_parse_pr_ref() {- assert_eq!(parse_pr_ref("pr:101"), Some(101));- assert_eq!(parse_pr_ref("pr:1"), Some(1));- assert_eq!(parse_pr_ref("pr:99999"), Some(99999));-- // Invalid cases- assert_eq!(parse_pr_ref("pr:"), None);- assert_eq!(parse_pr_ref("pr:abc"), None);- assert_eq!(parse_pr_ref("pr:-1"), None);- assert_eq!(parse_pr_ref("PR:101"), None); // case-sensitive- assert_eq!(parse_pr_ref("feature-branch"), None);- assert_eq!(parse_pr_ref("101"), None);- }-- #[test]- fn test_local_branch_name_same_repo() {- let pr = PrInfo {- number: 101,- title: "Fix authentication bug".to_string(),- author: "alice".to_string(),- state: "open".to_string(),- draft: false,- head_ref_name: "feature-auth".to_string(),- head_owner: "owner".to_string(),- head_repo: "repo".to_string(),- base_owner: "owner".to_string(),- base_repo: "repo".to_string(),- is_cross_repository: false,- host: "github.com".to_string(),- url: "https://github.com/owner/repo/pull/101".to_string(),- };- assert_eq!(local_branch_name(&pr), "feature-auth");- }-- #[test]- fn test_local_branch_name_fork() {- // Fork PRs also use headRefName directly (not owner/branch) because- // the local branch name must match the fork's branch for git push to work- let pr = PrInfo {- number: 101,- title: "Fix authentication bug".to_string(),- author: "contributor".to_string(),- state: "open".to_string(),- draft: false,- head_ref_name: "feature-auth".to_string(),- head_owner: "contributor".to_string(),- head_repo: "repo".to_string(),- base_owner: "owner".to_string(),- base_repo: "repo".to_string(),- is_cross_repository: true,- host: "github.com".to_string(),- url: "https://github.com/owner/repo/pull/101".to_string(),- };- assert_eq!(local_branch_name(&pr), "feature-auth");- }-- #[test]- fn test_prefixed_local_branch_name() {- // When the fork's branch name conflicts with a local branch,- // we use owner/branch format as a fallback (push won't work)- let pr = PrInfo {- number: 101,- head_ref_name: "main".to_string(),- head_owner: "contributor".to_string(),- head_repo: "repo".to_string(),- base_owner: "owner".to_string(),- base_repo: "repo".to_string(),- is_cross_repository: true,- host: "github.com".to_string(),- url: "https://github.com/owner/repo/pull/101".to_string(),- title: "Test PR".to_string(),- author: "contributor".to_string(),- state: "open".to_string(),- draft: false,- };- assert_eq!(prefixed_local_branch_name(&pr), "contributor/main");- }-- #[test]- fn test_fork_remote_url() {- // Protocol depends on `gh config get git_protocol`- let url = fork_remote_url("github.com", "contributor", "repo");- let valid_urls = [- "[email protected]:contributor/repo.git",- "https://github.com/contributor/repo.git",- ];- assert!(valid_urls.contains(&url.as_str()), "unexpected URL: {url}");-- let url = fork_remote_url("github.example.com", "contributor", "repo");- let valid_urls = [- "[email protected]:contributor/repo.git",- "https://github.example.com/contributor/repo.git",- ];- assert!(valid_urls.contains(&url.as_str()), "unexpected URL: {url}");- }-- #[test]- fn test_fork_remote_url_formats() {- // Test SSH format explicitly- assert_eq!(- fork_remote_url_ssh("github.com", "contributor", "repo"),- "[email protected]:contributor/repo.git"- );- assert_eq!(- fork_remote_url_ssh("github.example.com", "org", "project"),- "[email protected]:org/project.git"- );-- // Test HTTPS format explicitly- assert_eq!(- fork_remote_url_https("github.com", "contributor", "repo"),- "https://github.com/contributor/repo.git"- );- assert_eq!(- fork_remote_url_https("github.example.com", "org", "project"),- "https://github.example.com/org/project.git"- );- }-- #[test]- fn test_source_ref_same_repo() {- let pr = PrInfo {- number: 101,- title: "Fix bug".to_string(),- author: "alice".to_string(),- state: "open".to_string(),- draft: false,- head_ref_name: "feature-auth".to_string(),- head_owner: "owner".to_string(),- head_repo: "repo".to_string(),- base_owner: "owner".to_string(),- base_repo: "repo".to_string(),- is_cross_repository: false,- host: "github.com".to_string(),- url: "https://github.com/owner/repo/pull/101".to_string(),- };- use crate::git::RefContext;- assert_eq!(pr.source_ref(), "feature-auth");- }-- #[test]- fn test_source_ref_fork() {- let pr = PrInfo {- number: 42,- title: "Add feature".to_string(),- author: "contributor".to_string(),- state: "open".to_string(),- draft: false,- head_ref_name: "feature-fix".to_string(),- head_owner: "contributor".to_string(),- head_repo: "repo".to_string(),- base_owner: "owner".to_string(),- base_repo: "repo".to_string(),- is_cross_repository: true,- host: "github.com".to_string(),- url: "https://github.com/owner/repo/pull/42".to_string(),- };- use crate::git::RefContext;- assert_eq!(pr.source_ref(), "contributor:feature-fix");- }-}diff --git a/src/git/remote_ref.rs b/src/git/remote_ref.rsdeleted file mode 100644index e679d7296..000000000--- a/src/git/remote_ref.rs+++ /dev/null@@ -1,115 +0,0 @@-//! 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 create branch for pr:101 — PR already has branch feature-auth-//! ↳ To switch to it: wt switch pr:101-//! ```diff --git a/src/git/remote_ref/github.rs b/src/git/remote_ref/github.rsnew file mode 100644index 000000000..f610b1ae7--- /dev/null+++ b/src/git/remote_ref/github.rs@@ -0,0 +1,257 @@+//! GitHub PR provider.+//!+//! Implements `RemoteRefProvider` for GitHub Pull Requests using the `gh` CLI.++use std::io::ErrorKind;+use std::path::Path;++use anyhow::{Context, bail};+use serde::Deserialize;++use super::{PlatformData, RemoteRefInfo, RemoteRefProvider};+use crate::git::RefType;+use crate::git::error::GitError;+use crate::shell_exec::Cmd;++/// GitHub Pull Request provider.+#[derive(Debug, Clone, Copy)]+pub struct GitHubProvider;++impl RemoteRefProvider for GitHubProvider {+ fn ref_type(&self) -> RefType {+ RefType::Pr+ }++ fn fetch_info(&self, number: u32, repo_root: &Path) -> anyhow::Result<RemoteRefInfo> {+ fetch_pr_info(number, repo_root)+ }++ 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 {+ title: String,+ user: GhUser,+ state: String,+ #[serde(default)]+ draft: bool,+ head: GhPrRef,+ base: GhPrRef,+ html_url: String,+}++/// Error response from GitHub API.+#[derive(Debug, Deserialize)]+struct GhApiErrorResponse {+ #[serde(default)]+ message: String,+ #[serde(default)]+ status: String,+}++#[derive(Debug, Deserialize)]+struct GhUser {+ login: String,+}++#[derive(Debug, Deserialize)]+struct GhPrRef {+ #[serde(rename = "ref")]+ ref_name: String,+ repo: Option<GhPrRepo>,+}++#[derive(Debug, Deserialize)]+struct GhPrRepo {+ name: String,+ owner: GhOwner,+}++#[derive(Debug, Deserialize)]+struct GhOwner {+ login: String,+}++/// Fetch PR information from GitHub using the `gh` CLI.+fn fetch_pr_info(pr_number: u32, repo_root: &Path) -> anyhow::Result<RemoteRefInfo> {+ let api_path = format!("repos/{{owner}}/{{repo}}/pulls/{}", pr_number);++ let output = match Cmd::new("gh")+ .args(["api", &api_path])+ .current_dir(repo_root)+ .env("GH_PROMPT_DISABLED", "1")+ .run()+ {+ Ok(output) => output,+ Err(e) => {+ if e.kind() == ErrorKind::NotFound {+ bail!("GitHub CLI (gh) not installed; install from https://cli.github.com/");+ }+ return Err(anyhow::Error::from(e).context("Failed to run gh api"));+ }+ };++ if !output.status.success() {+ if let Ok(error_response) = serde_json::from_slice::<GhApiErrorResponse>(&output.stdout) {+ match error_response.status.as_str() {+ "404" => bail!("PR #{} not found", pr_number),+ "401" => bail!("GitHub CLI not authenticated; run gh auth login"),+ "403" => {+ let message_lower = error_response.message.to_lowercase();+ if message_lower.contains("rate limit") {+ bail!("GitHub API rate limit exceeded; wait a few minutes and retry");+ }+ bail!("GitHub API access forbidden: {}", error_response.message);+ }+ _ => {}+ }+ }++ let stderr = String::from_utf8_lossy(&output.stderr);+ let details = if stderr.trim().is_empty() {+ String::from_utf8_lossy(&output.stdout).trim().to_string()+ } else {+ stderr.trim().to_string()+ };+ return Err(GitError::CliApiError {+ ref_type: RefType::Pr,+ message: format!("gh api failed for PR #{}", pr_number),+ stderr: details,+ }+ .into());+ }++ let response: GhApiPrResponse = serde_json::from_slice(&output.stdout).with_context(|| {+ format!(+ "Failed to parse GitHub API response for PR #{}. \+ This may indicate a GitHub API change.",+ pr_number+ )+ })?;++ if response.head.ref_name.is_empty() {+ bail!(+ "PR #{} has empty branch name; the PR may be in an invalid state",+ pr_number+ );+ }++ let base_repo = response.base.repo.context(+ "PR base repository is null; this is unexpected and may indicate a GitHub API issue",+ )?;++ let head_repo = response.head.repo.ok_or_else(|| {+ anyhow::anyhow!(+ "PR #{} source repository was deleted. \+ The fork that this PR was opened from no longer exists, \+ so the branch cannot be checked out.",+ pr_number+ )+ })?;++ let is_cross_repo = !base_repo+ .owner+ .login+ .eq_ignore_ascii_case(&head_repo.owner.login)+ || !base_repo.name.eq_ignore_ascii_case(&head_repo.name);++ let host = response+ .html_url+ .strip_prefix("https://")+ .or_else(|| response.html_url.strip_prefix("http://"))+ .and_then(|s| s.split('/').next())+ .filter(|h| !h.is_empty())+ .with_context(|| format!("Failed to parse host from PR URL: {}", response.html_url))?+ .to_string();++ // Compute fork push URL only for cross-repo PRs+ let fork_push_url = if is_cross_repo {+ Some(fork_remote_url(+ &host,+ &head_repo.owner.login,+ &head_repo.name,+ ))+ } else {+ None+ };++ Ok(RemoteRefInfo {+ ref_type: RefType::Pr,+ number: pr_number,+ title: response.title,+ author: response.user.login,+ state: response.state,+ draft: response.draft,+ source_branch: response.head.ref_name,+ is_cross_repo,+ url: response.html_url,+ fork_push_url,+ platform_data: PlatformData::GitHub {+ host,+ head_owner: head_repo.owner.login,+ head_repo: head_repo.name,+ base_owner: base_repo.owner.login,+ base_repo: base_repo.name,+ },+ })+}++/// Get the git protocol preference from `gh` (GitHub CLI).+fn use_ssh_protocol() -> bool {+ Cmd::new("gh")+ .args(["config", "get", "git_protocol"])+ .run()+ .ok()+ .filter(|output| output.status.success())+ .map(|output| String::from_utf8_lossy(&output.stdout).trim() == "ssh")+ .unwrap_or(false)+}++/// Construct the remote URL for a fork repository.+pub fn fork_remote_url(host: &str, owner: &str, repo: &str) -> String {+ if use_ssh_protocol() {+ format!("git@{}:{}/{}.git", host, owner, repo)+ } else {+ format!("https://{}/{}/{}.git", host, owner, repo)+ }+}++#[cfg(test)]+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(), RefType::Pr);+ }++ #[test]+ fn test_fork_remote_url_formats() {+ // Protocol depends on `gh config get git_protocol`, so just check format+ let url = fork_remote_url("github.com", "contributor", "repo");+ let valid_urls = [+ "[email protected]:contributor/repo.git",+ "https://github.com/contributor/repo.git",+ ];+ assert!(valid_urls.contains(&url.as_str()), "unexpected URL: {url}");++ let url = fork_remote_url("github.example.com", "org", "project");+ let valid_urls = [+ "[email protected]:org/project.git",+ "https://github.example.com/org/project.git",+ ];+ assert!(valid_urls.contains(&url.as_str()), "unexpected URL: {url}");+ }+}diff --git a/src/git/remote_ref/gitlab.rs b/src/git/remote_ref/gitlab.rsnew file mode 100644index 000000000..155423573--- /dev/null+++ b/src/git/remote_ref/gitlab.rs@@ -0,0 +1,323 @@+//! GitLab MR provider.+//!+//! Implements `RemoteRefProvider` for GitLab Merge Requests using the `glab` CLI.+//!+//! # API Differences from GitHub+//!+//! GitLab's MR API (`projects/:id/merge_requests/:iid`) only returns project IDs,+//! not full project objects. To get clone URLs for fork MRs, we must make separate+//! calls to the Projects API (`projects/:id`).+//!+//! In contrast, GitHub's PR API returns complete `head.repo` and `base.repo` objects+//! with `clone_url` and `ssh_url` — everything in one call.+//!+//! # Deferred URL Fetching+//!+//! To avoid the ~1 second overhead of 2 extra API calls, we defer URL fetching:+//!+//! 1. `fetch_mr_info()` returns `RemoteRefInfo` with `fork_push_url: None`+//! 2. Caller checks if branch already tracks the MR via `branch_tracks_ref()`+//! 3. Only if a new branch is needed, call `fetch_gitlab_project_urls()`+//!+//! This saves ~1 second for the common case (switching to an existing MR branch).++use std::io::ErrorKind;+use std::path::Path;++use anyhow::{Context, bail};+use serde::Deserialize;++use super::{PlatformData, RemoteRefInfo, RemoteRefProvider};+use crate::git::RefType;+use crate::git::error::GitError;+use crate::shell_exec::Cmd;++/// GitLab Merge Request provider.+#[derive(Debug, Clone, Copy)]+pub struct GitLabProvider;++impl RemoteRefProvider for GitLabProvider {+ fn ref_type(&self) -> RefType {+ RefType::Mr+ }++ fn fetch_info(&self, number: u32, repo_root: &Path) -> anyhow::Result<RemoteRefInfo> {+ 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 {+ title: String,+ author: GlabAuthor,+ state: String,+ #[serde(default)]+ draft: bool,+ source_branch: String,+ source_project_id: u64,+ target_project_id: u64,+ web_url: String,+}++#[derive(Debug, Deserialize)]+struct GlabAuthor {+ username: String,+}++#[derive(Debug, Deserialize)]+struct GlabProject {+ ssh_url_to_repo: Option<String>,+ http_url_to_repo: Option<String>,+}++/// Error response from GitLab API.+#[derive(Debug, Deserialize)]+struct GlabApiErrorResponse {+ #[serde(default)]+ message: String,+ #[serde(default)]+ error: String,+}++/// Fetch MR information from GitLab using the `glab` CLI.+fn fetch_mr_info(mr_number: u32, repo_root: &Path) -> anyhow::Result<RemoteRefInfo> {+ let api_path = format!("projects/:id/merge_requests/{}", mr_number);++ let output = match Cmd::new("glab")+ .args(["api", &api_path])+ .current_dir(repo_root)+ .env("GLAB_NO_PROMPT", "1")+ .run()+ {+ Ok(output) => output,+ Err(e) => {+ if e.kind() == ErrorKind::NotFound {+ bail!(+ "GitLab CLI (glab) not installed; install from https://gitlab.com/gitlab-org/cli#installation"+ );+ }+ return Err(anyhow::Error::from(e).context("Failed to run glab api"));+ }+ };++ if !output.status.success() {+ if let Ok(error_response) = serde_json::from_slice::<GlabApiErrorResponse>(&output.stdout) {+ let error_text = if !error_response.message.is_empty() {+ &error_response.message+ } else {+ &error_response.error+ };++ if error_text.starts_with("404") {+ bail!("MR !{} not found", mr_number);+ }+ if error_text.starts_with("401") {+ bail!("GitLab CLI not authenticated; run glab auth login");+ }+ if error_text.starts_with("403") {+ bail!("GitLab API access forbidden for MR !{}", mr_number);+ }+ }++ let stderr = String::from_utf8_lossy(&output.stderr);+ let details = if stderr.trim().is_empty() {+ String::from_utf8_lossy(&output.stdout).trim().to_string()+ } else {+ stderr.trim().to_string()+ };+ return Err(GitError::CliApiError {+ ref_type: RefType::Mr,+ message: format!("glab api failed for MR !{}", mr_number),+ stderr: details,+ }+ .into());+ }++ let response: GlabMrResponse = serde_json::from_slice(&output.stdout).with_context(|| {+ format!(+ "Failed to parse GitLab API response for MR !{}. \+ This may indicate a GitLab API change.",+ mr_number+ )+ })?;++ if response.source_branch.is_empty() {+ bail!(+ "MR !{} has empty branch name; the MR may be in an invalid state",+ mr_number+ );+ }++ let is_cross_repo = response.source_project_id != response.target_project_id;++ // Don't fetch project URLs here - defer until after branch_tracks_ref check+ // in switch.rs, which often short-circuits (branch already configured).+ // Use fetch_gitlab_project_urls() when URLs are actually needed.++ Ok(RemoteRefInfo {+ ref_type: RefType::Mr,+ number: mr_number,+ title: response.title,+ author: response.author.username,+ state: response.state,+ draft: response.draft,+ source_branch: response.source_branch,+ is_cross_repo,+ url: response.web_url,+ fork_push_url: None, // Populated later by fetch_gitlab_project_urls if needed+ platform_data: PlatformData::GitLab {+ source_project_id: response.source_project_id,+ target_project_id: response.target_project_id,+ },+ })+}++/// URLs for a GitLab fork MR.+#[derive(Debug)]+pub struct GitLabForkUrls {+ /// URL to push to the fork (source project).+ pub fork_push_url: Option<String>,+ /// Target project URL (where MR refs live) - SSH or HTTPS based on config.+ pub target_url: Option<String>,+}++/// Fetch project URLs for a GitLab fork MR.+///+/// This is deferred from `fetch_mr_info` because GitLab's MR API doesn't include+/// project URLs (unlike GitHub's PR API which returns full repo objects). The 2+/// extra API calls (~500ms each) are only needed when creating a new branch.+///+/// See module-level docs for the full explanation of this optimization.+pub fn fetch_gitlab_project_urls(+ info: &RemoteRefInfo,+ repo_root: &Path,+) -> anyhow::Result<GitLabForkUrls> {+ let PlatformData::GitLab {+ source_project_id,+ target_project_id,+ ..+ } = &info.platform_data+ else {+ bail!("fetch_gitlab_project_urls called on non-GitLab ref");+ };++ // Fetch source project URLs (for fork push)+ let (source_ssh, source_http) = fetch_project_urls(*source_project_id, repo_root)+ .with_context(|| {+ format!(+ "Failed to fetch source project {} for MR !{}",+ source_project_id, info.number+ )+ })?;++ // Fetch target project URLs (where MR refs live)+ let (target_ssh, target_http) = fetch_project_urls(*target_project_id, repo_root)+ .with_context(|| {+ format!(+ "Failed to fetch target project {} for MR !{}",+ target_project_id, info.number+ )+ })?;++ // Compute URLs based on protocol preference+ let use_ssh = get_git_protocol() == "ssh";+ let fork_push_url = if use_ssh {+ source_ssh.or(source_http)+ } else {+ source_http.or(source_ssh)+ };+ let target_url = if use_ssh {+ target_ssh.or(target_http)+ } else {+ target_http.or(target_ssh)+ };++ Ok(GitLabForkUrls {+ fork_push_url,+ target_url,+ })+}++/// Fetch project URLs from GitLab API.+fn fetch_project_urls(+ project_id: u64,+ repo_root: &Path,+) -> anyhow::Result<(Option<String>, Option<String>)> {+ let api_path = format!("projects/{}", project_id);++ let output = Cmd::new("glab")+ .args(["api", &api_path])+ .current_dir(repo_root)+ .env("GLAB_NO_PROMPT", "1")+ .run()?;++ if !output.status.success() {+ bail!("Failed to fetch project {}", project_id);+ }++ let response: GlabProject = serde_json::from_slice(&output.stdout)?;+ Ok((response.ssh_url_to_repo, response.http_url_to_repo))+}++/// Get the git protocol configured in `glab` (GitLab CLI).+pub fn get_git_protocol() -> String {+ Cmd::new("glab")+ .args(["config", "get", "git_protocol"])+ .run()+ .ok()+ .filter(|output| output.status.success())+ .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string())+ .filter(|p| p == "ssh" || p == "https")+ .unwrap_or_else(|| "https".to_string())+}++#[cfg(test)]+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(), RefType::Mr);+ }++ #[test]+ fn test_fetch_gitlab_project_urls_rejects_github_ref() {+ let github_info = RemoteRefInfo {+ ref_type: RefType::Pr,+ number: 123,+ title: "Test PR".to_string(),+ author: "user".to_string(),+ state: "open".to_string(),+ draft: false,+ source_branch: "feature".to_string(),+ is_cross_repo: false,+ url: "https://github.com/owner/repo/pull/123".to_string(),+ fork_push_url: None,+ platform_data: PlatformData::GitHub {+ host: "github.com".to_string(),+ head_owner: "user".to_string(),+ head_repo: "repo".to_string(),+ base_owner: "owner".to_string(),+ base_repo: "repo".to_string(),+ },+ };++ let result = fetch_gitlab_project_urls(&github_info, std::path::Path::new("."));+ assert!(result.is_err());+ assert!(result.unwrap_err().to_string().contains("non-GitLab ref"));+ }+}diff --git a/src/git/remote_ref/info.rs b/src/git/remote_ref/info.rsnew file mode 100644index 000000000..ae38c11e3--- /dev/null+++ b/src/git/remote_ref/info.rs@@ -0,0 +1,337 @@+//! Remote ref info types.+//!+//! Provides unified types for PR/MR metadata across platforms.++use crate::git::{RefContext, RefType};++/// Platform-specific data for a remote ref.+///+/// Contains fields that differ between GitHub and GitLab.+#[derive(Debug, Clone)]+pub enum PlatformData {+ /// GitHub-specific data.+ GitHub {+ /// GitHub host (e.g., "github.com", "github.enterprise.com").+ host: String,+ /// Owner of the head (source) repository.+ head_owner: String,+ /// Name of the head (source) repository.+ head_repo: String,+ /// Owner of the base (target) repository.+ base_owner: String,+ /// Name of the base (target) repository.+ base_repo: String,+ },+ /// GitLab-specific data.+ GitLab {+ /// Source project ID (used for deferred URL fetching).+ source_project_id: u64,+ /// Target project ID (used for deferred URL fetching).+ target_project_id: u64,+ },+}++/// Unified information about a PR or MR.+///+/// This struct contains all the data needed to create a local branch+/// for a PR/MR, regardless of platform.+#[derive(Debug, Clone)]+pub struct RemoteRefInfo {+ /// The reference type (PR or MR).+ pub ref_type: RefType,+ /// The PR/MR number.+ pub number: u32,+ /// The PR/MR title.+ pub title: String,+ /// The PR/MR author's username.+ pub author: String,+ /// The PR/MR state ("open", "closed", "merged", etc.).+ pub state: String,+ /// Whether this is a draft PR/MR.+ pub draft: bool,+ /// The branch name in the source repository.+ pub source_branch: String,+ /// Whether this is a cross-repository (fork) PR/MR.+ pub is_cross_repo: bool,+ /// The PR/MR web URL.+ pub url: String,+ /// URL to push to for fork PRs/MRs, or `None` if push isn't supported.+ pub fork_push_url: Option<String>,+ /// Platform-specific data.+ pub platform_data: PlatformData,+}++impl RefContext for RemoteRefInfo {+ fn ref_type(&self) -> RefType {+ self.ref_type+ }++ fn number(&self) -> u32 {+ self.number+ }++ fn title(&self) -> &str {+ &self.title+ }++ fn author(&self) -> &str {+ &self.author+ }++ fn state(&self) -> &str {+ &self.state+ }++ fn draft(&self) -> bool {+ self.draft+ }++ fn url(&self) -> &str {+ &self.url+ }++ fn source_ref(&self) -> String {+ if self.is_cross_repo {+ // Try to extract owner for display+ match &self.platform_data {+ PlatformData::GitHub { head_owner, .. } => {+ format!("{}:{}", head_owner, self.source_branch)+ }+ PlatformData::GitLab { .. } => {+ // For GitLab, try to extract namespace from fork_push_url+ if let Some(url) = &self.fork_push_url+ && let Some(namespace) = extract_namespace_from_url(url)+ {+ return format!("{}:{}", namespace, self.source_branch);+ }+ self.source_branch.clone()+ }+ }+ } else {+ self.source_branch.clone()+ }+ }+}++impl RemoteRefInfo {+ /// Generate a prefixed local branch name for when the unprefixed name conflicts.+ ///+ /// Returns `<owner>/<branch>` (e.g., `contributor/main`).+ /// Only meaningful for GitHub fork PRs; GitLab doesn't support this pattern.+ pub fn prefixed_local_branch_name(&self) -> Option<String> {+ match &self.platform_data {+ PlatformData::GitHub { head_owner, .. } => {+ Some(format!("{}/{}", head_owner, self.source_branch))+ }+ PlatformData::GitLab { .. } => None,+ }+ }+}++/// Extract namespace (owner or group/subgroup) from a git URL.+///+/// Handles both SSH (`git@host:namespace/repo.git`) and HTTPS+/// (`https://host/namespace/repo.git`) formats. Supports GitLab nested+/// namespaces like `group/subgroup/repo.git` → `group/subgroup`.+fn extract_namespace_from_url(url: &str) -> Option<String> {+ // SSH format: git@host:namespace/repo.git+ if let Some(path) = url.strip_prefix("git@").and_then(|s| s.split(':').nth(1)) {+ return extract_namespace_from_path(path);+ }+ // HTTPS format: https://host/namespace/repo.git+ if let Some(rest) = url+ .strip_prefix("https://")+ .or_else(|| url.strip_prefix("http://"))+ {+ // Skip the host segment+ let path = rest.split('/').skip(1).collect::<Vec<_>>().join("/");+ return extract_namespace_from_path(&path);+ }+ None+}++/// Extract namespace from a path like `group/subgroup/repo.git`.+///+/// Returns everything except the last segment (repo name).+fn extract_namespace_from_path(path: &str) -> Option<String> {+ let path = path.strip_suffix(".git").unwrap_or(path);+ let segments: Vec<_> = path.split('/').collect();+ if segments.len() < 2 {+ return None;+ }+ // All segments except the last (which is the repo name)+ Some(segments[..segments.len() - 1].join("/"))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_source_ref_same_repo() {+ let info = RemoteRefInfo {+ ref_type: RefType::Pr,+ number: 101,+ title: "Fix bug".to_string(),+ author: "alice".to_string(),+ state: "open".to_string(),+ draft: false,+ source_branch: "feature-auth".to_string(),+ is_cross_repo: false,+ url: "https://github.com/owner/repo/pull/101".to_string(),+ fork_push_url: None,+ platform_data: PlatformData::GitHub {+ host: "github.com".to_string(),+ head_owner: "owner".to_string(),+ head_repo: "repo".to_string(),+ base_owner: "owner".to_string(),+ base_repo: "repo".to_string(),+ },+ };+ assert_eq!(info.source_ref(), "feature-auth");+ }++ #[test]+ fn test_source_ref_fork_github() {+ let info = RemoteRefInfo {+ ref_type: RefType::Pr,+ number: 42,+ title: "Add feature".to_string(),+ author: "contributor".to_string(),+ state: "open".to_string(),+ draft: false,+ source_branch: "feature-fix".to_string(),+ is_cross_repo: true,+ url: "https://github.com/owner/repo/pull/42".to_string(),+ fork_push_url: Some("[email protected]:contributor/repo.git".to_string()),+ platform_data: PlatformData::GitHub {+ host: "github.com".to_string(),+ head_owner: "contributor".to_string(),+ head_repo: "repo".to_string(),+ base_owner: "owner".to_string(),+ base_repo: "repo".to_string(),+ },+ };+ assert_eq!(info.source_ref(), "contributor:feature-fix");+ }++ #[test]+ fn test_source_ref_fork_gitlab() {+ let info = RemoteRefInfo {+ ref_type: RefType::Mr,+ number: 101,+ title: "Fix bug".to_string(),+ author: "contributor".to_string(),+ state: "opened".to_string(),+ draft: false,+ source_branch: "feature-fix".to_string(),+ is_cross_repo: true,+ url: "https://gitlab.com/owner/repo/-/merge_requests/101".to_string(),+ fork_push_url: Some("[email protected]:contributor/repo.git".to_string()),+ platform_data: PlatformData::GitLab {+ source_project_id: 456,+ target_project_id: 123,+ },+ };+ assert_eq!(info.source_ref(), "contributor:feature-fix");+ }++ #[test]+ fn test_prefixed_local_branch_name_github() {+ let info = RemoteRefInfo {+ ref_type: RefType::Pr,+ number: 101,+ title: "Test".to_string(),+ author: "contributor".to_string(),+ state: "open".to_string(),+ draft: false,+ source_branch: "main".to_string(),+ is_cross_repo: true,+ url: "https://github.com/owner/repo/pull/101".to_string(),+ fork_push_url: Some("[email protected]:contributor/repo.git".to_string()),+ platform_data: PlatformData::GitHub {+ host: "github.com".to_string(),+ head_owner: "contributor".to_string(),+ head_repo: "repo".to_string(),+ base_owner: "owner".to_string(),+ base_repo: "repo".to_string(),+ },+ };+ assert_eq!(+ info.prefixed_local_branch_name(),+ Some("contributor/main".to_string())+ );+ }++ #[test]+ fn test_prefixed_local_branch_name_gitlab() {+ let info = RemoteRefInfo {+ ref_type: RefType::Mr,+ number: 101,+ title: "Test".to_string(),+ author: "contributor".to_string(),+ state: "opened".to_string(),+ draft: false,+ source_branch: "main".to_string(),+ is_cross_repo: true,+ url: "https://gitlab.com/owner/repo/-/merge_requests/101".to_string(),+ fork_push_url: Some("[email protected]:contributor/repo.git".to_string()),+ platform_data: PlatformData::GitLab {+ source_project_id: 456,+ target_project_id: 123,+ },+ };+ // GitLab doesn't support prefixed branch names+ assert_eq!(info.prefixed_local_branch_name(), None);+ }++ #[test]+ fn test_extract_namespace_from_url_ssh() {+ assert_eq!(+ extract_namespace_from_url("[email protected]:owner/repo.git"),+ Some("owner".to_string())+ );+ assert_eq!(+ extract_namespace_from_url("[email protected]:contributor/repo.git"),+ Some("contributor".to_string())+ );+ }++ #[test]+ fn test_extract_namespace_from_url_https() {+ assert_eq!(+ extract_namespace_from_url("https://gitlab.com/owner/repo.git"),+ Some("owner".to_string())+ );+ assert_eq!(+ extract_namespace_from_url("http://github.com/owner/repo.git"),+ Some("owner".to_string())+ );+ }++ #[test]+ fn test_extract_namespace_from_url_nested() {+ // GitLab nested namespaces+ assert_eq!(+ extract_namespace_from_url("[email protected]:group/subgroup/repo.git"),+ Some("group/subgroup".to_string())+ );+ assert_eq!(+ extract_namespace_from_url("https://gitlab.com/group/subgroup/repo.git"),+ Some("group/subgroup".to_string())+ );+ // Even deeper nesting+ assert_eq!(+ extract_namespace_from_url("[email protected]:org/team/project/repo.git"),+ Some("org/team/project".to_string())+ );+ }++ #[test]+ fn test_extract_namespace_from_url_invalid() {+ assert_eq!(extract_namespace_from_url("invalid-url"), None);+ assert_eq!(extract_namespace_from_url(""), None);+ // Just a repo name, no namespace+ assert_eq!(extract_namespace_from_url("[email protected]:repo.git"), None);+ }+}diff --git a/src/git/remote_ref/mod.rs b/src/git/remote_ref/mod.rsnew file mode 100644index 000000000..bfb4c0603--- /dev/null+++ b/src/git/remote_ref/mod.rs@@ -0,0 +1,110 @@+//! Unified PR/MR reference resolution.+//!+//! This module provides a trait-based architecture for resolving GitHub PRs and GitLab MRs+//! to local branches. Both platforms follow the same workflow:+//!+//! 1. Parse `pr:<number>` or `mr:<number>` syntax+//! 2. Fetch metadata from the platform API+//! 3. Check if a local branch already tracks this ref+//! 4. Create/configure the branch if needed+//!+//! # Usage+//!+//! ```ignore+//! use worktrunk::git::remote_ref::{GitHubProvider, RemoteRefProvider};+//!+//! let provider = GitHubProvider;+//! let info = provider.fetch_info(123, repo_root)?;+//! println!("PR #{}: {}", info.number, info.title);+//! ```+//!+//! # Platform-Specific Notes+//!+//! ## GitHub+//!+//! Uses `gh api repos/{owner}/{repo}/pulls/<number>` which returns head/base repo info.+//! For fork workflows, `gh repo set-default` controls which repo is queried.+//!+//! ## GitLab+//!+//! Uses `glab api projects/:id/merge_requests/<number>`. Fork MRs require additional+//! API calls to fetch source/target project URLs.++pub mod github;+pub mod gitlab;+mod info;++pub use github::GitHubProvider;+pub use gitlab::GitLabProvider;+pub use info::{PlatformData, RemoteRefInfo};++use std::path::Path;++use crate::git::RefType;++/// Provider trait for platform-specific PR/MR operations.+///+/// Each platform (GitHub, GitLab) implements this trait to provide+/// unified access to PR/MR metadata and ref paths.+pub trait RemoteRefProvider {+ /// The reference type this provider handles.+ fn ref_type(&self) -> RefType;++ /// 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_root: &Path) -> 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))+ }+}++/// 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,+) -> Option<bool> {+ let expected_ref = provider.tracking_ref(number);+ crate::git::branch_tracks_ref(repo_root, branch, &expected_ref)+}++/// Generate the local branch name for a remote ref.+///+/// Uses the source branch name directly. This ensures the local branch name+/// matches the remote branch name, which is required for `git push` to work+/// correctly with `push.default = current`.+pub fn local_branch_name(info: &RemoteRefInfo) -> String {+ info.source_branch.clone()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[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 gl = GitLabProvider;+ assert_eq!(gl.ref_path(42), "merge-requests/42/head");+ assert_eq!(gl.tracking_ref(42), "refs/merge-requests/42/head");+ }+}diff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_fork.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_fork.snapindex 49531193c..8de3652d6 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_mr_fork.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_fork.snap@@ -25,6 +25,7 @@ info:TERM: alacrittyUSERPROFILE: "[TEST_HOME]"WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"WT_TEST_DELAYED_STREAM_MS: "-1"WT_TEST_EPOCH: "1735776000"@@ -37,7 +38,7 @@ exit_code: 0----- stderr -----[36m◎[39m [36mFetching MR !42...[39m[107m [0m [1mAdd feature fix for edge case[22m (!42)-[107m [0m by @contributor · opened · contributor:feature-fix · [90mhttps://gitlab.com/owner/test-repo/-/merge_requests/42[39m+[107m [0m by @contributor · opened · feature-fix · [90mhttps://gitlab.com/owner/test-repo/-/merge_requests/42[39m[2m○[22m Push configured to fork: [90mhttps://gitlab.com/contributor/test-repo.git[39m[32m✓[39m [32mCreated branch [1mfeature-fix[22m (tracking [1mMR !42[22m) and worktree @ [1m_REPO_.feature-fix[22m[39m[33m▲[39m [33mCannot change directory — shell integration not installed[39m