Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: add GitLab MR checkout with `mr:<number>` syntax (#734)
Maximilian Roos9d1a8cddacda
diff --git a/.claude-plugin/skills/worktrunk/reference/switch.md b/.claude-plugin/skills/worktrunk/reference/switch.mdindex e2dc30538..0e299bf79 100644--- a/.claude-plugin/skills/worktrunk/reference/switch.md+++ b/.claude-plugin/skills/worktrunk/reference/switch.md@@ -48,12 +48,14 @@ wt switch --create temp --no-verify # Skip hooks| `@` | Current branch/worktree || `-` | Previous worktree (like `cd -`) || `pr:{N}` | GitHub PR #N's branch |+| `mr:{N}` | GitLab MR !N's branch |```bashwt switch - # Back to previouswt switch ^ # Default branch worktreewt switch --create fix --base=@ # Branch from current HEADwt switch pr:123 # PR #123's branch+wt switch mr:101 # MR !101's branch```## GitHub pull requests (experimental)@@ -68,6 +70,18 @@ Requires `gh` CLI to be installed and authenticated. The `--create` flag cannot**Fork PRs:** The local branch uses the PR's branch name directly (e.g., `feature-fix`), so `git push` works normally. If a local branch with that name already exists tracking something else, rename it first.+## GitLab merge requests (experimental)++The `mr:<number>` syntax resolves the branch for a GitLab merge request. For same-project MRs, it switches to the branch directly. For fork MRs, it fetches `refs/merge-requests/N/head` and configures `pushRemote` to the fork URL.++```bash+wt switch mr:101 # Checkout MR !101+```++Requires `glab` CLI to be installed and authenticated. The `--create` flag cannot be used with `mr:` syntax since the branch already exists.++**Fork MRs:** The local branch uses the MR's branch name directly, so `git push` works normally. If a local branch with that name already exists tracking something else, rename it first.+## When wt switch fails- **Branch doesn't exist** — Use `--create`, or check `wt list --branches`@@ -89,7 +103,7 @@ Usage: <b><span class=c>wt switch</span></b> <span class=c>[OPTIONS]</span> <spaBranch name or shortcutShortcuts: '^' (default branch), '-' (previous), '@' (current),- 'pr:{N}' (GitHub PR, experimental)+ 'pr:{N}' (GitHub PR), 'mr:{N}' (GitLab MR)<span class=c>[EXECUTE_ARGS]...</span>Additional arguments for --execute command (after --)diff --git a/docs/content/switch.md b/docs/content/switch.mdindex e8dfc4d90..b3e6de3e3 100644--- a/docs/content/switch.md+++ b/docs/content/switch.md@@ -62,12 +62,14 @@ wt switch --create temp --no-verify # Skip hooks| `@` | Current branch/worktree || `-` | Previous worktree (like `cd -`) || `pr:{N}` | GitHub PR #N's branch |+| `mr:{N}` | GitLab MR !N's branch |```bashwt switch - # Back to previouswt switch ^ # Default branch worktreewt switch --create fix --base=@ # Branch from current HEADwt switch pr:123 # PR #123's branch+wt switch mr:101 # MR !101's branch```## GitHub pull requests (experimental)@@ -82,6 +84,18 @@ Requires `gh` CLI to be installed and authenticated. The `--create` flag cannot**Fork PRs:** The local branch uses the PR's branch name directly (e.g., `feature-fix`), so `git push` works normally. If a local branch with that name already exists tracking something else, rename it first.+## GitLab merge requests (experimental)++The `mr:<number>` syntax resolves the branch for a GitLab merge request. For same-project MRs, it switches to the branch directly. For fork MRs, it fetches `refs/merge-requests/N/head` and configures `pushRemote` to the fork URL.++```bash+wt switch mr:101 # Checkout MR !101+```++Requires `glab` CLI to be installed and authenticated. The `--create` flag cannot be used with `mr:` syntax since the branch already exists.++**Fork MRs:** The local branch uses the MR's branch name directly, so `git push` works normally. If a local branch with that name already exists tracking something else, rename it first.+## When wt switch fails- **Branch doesn't exist** — Use `--create`, or check `wt list --branches`@@ -111,7 +125,7 @@ Usage: <b><span class=c>wt switch</span></b> <span class=c>[OPTIONS]</span> <spaBranch name or shortcutShortcuts: '^' (default branch), '-' (previous), '@' (current),- 'pr:{N}' (GitHub PR, experimental)+ 'pr:{N}' (GitHub PR), 'mr:{N}' (GitLab MR)<span class=c>[EXECUTE_ARGS]...</span>Additional arguments for --execute command (after --)diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex e1b868626..caf690034 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -293,12 +293,14 @@ wt switch --create temp --no-verify # Skip hooks| `@` | Current branch/worktree || `-` | Previous worktree (like `cd -`) || `pr:{N}` | GitHub PR #N's branch |+| `mr:{N}` | GitLab MR !N's branch |```consolewt switch - # Back to previouswt switch ^ # Default branch worktreewt switch --create fix --base=@ # Branch from current HEADwt switch pr:123 # PR #123's branch+wt switch mr:101 # MR !101's branch```## GitHub pull requests (experimental)@@ -313,6 +315,18 @@ Requires `gh` CLI to be installed and authenticated. The `--create` flag cannot**Fork PRs:** The local branch uses the PR's branch name directly (e.g., `feature-fix`), so `git push` works normally. If a local branch with that name already exists tracking something else, rename it first.+## GitLab merge requests (experimental)++The `mr:<number>` syntax resolves the branch for a GitLab merge request. For same-project MRs, it switches to the branch directly. For fork MRs, it fetches `refs/merge-requests/N/head` and configures `pushRemote` to the fork URL.++```console+wt switch mr:101 # Checkout MR !101+```++Requires `glab` CLI to be installed and authenticated. The `--create` flag cannot be used with `mr:` syntax since the branch already exists.++**Fork MRs:** The local branch uses the MR's branch name directly, so `git push` works normally. If a local branch with that name already exists tracking something else, rename it first.+## When wt switch fails- **Branch doesn't exist** — Use `--create`, or check `wt list --branches`@@ -332,7 +346,7 @@ To change which branch a worktree is on, use `git switch` inside that worktree.Switch {/// Branch name or shortcut///- /// Shortcuts: '^' (default branch), '-' (previous), '@' (current), 'pr:{N}' (GitHub PR, experimental)+ /// Shortcuts: '^' (default branch), '-' (previous), '@' (current), 'pr:{N}' (GitHub PR), 'mr:{N}' (GitLab MR)#[arg(add = crate::completion::worktree_branch_completer())]branch: String,diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 19e521004..e95fdb001 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -26,26 +26,35 @@ struct ResolvedTarget {method: CreationMethod,}-/// Resolve the switch target, handling pr: syntax and --create/--base flags.+/// 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 resolution.+/// 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> {+ use worktrunk::git::mr_ref;use worktrunk::git::pr_ref::{fetch_pr_info, local_branch_name};// Handle pr:<number> syntaxif let Some(pr_number) = worktrunk::git::pr_ref::parse_pr_ref(branch) {// --create and --base are invalid with pr: syntaxif create {- return Err(GitError::PrCreateConflict { pr_number }.into());+ return Err(GitError::RefCreateConflict {+ ref_type: worktrunk::git::RefType::Pr,+ number: pr_number,+ }+ .into());}if base.is_some() {- return Err(GitError::PrBaseConflict { pr_number }.into());+ return Err(GitError::RefBaseConflict {+ ref_type: worktrunk::git::RefType::Pr,+ number: pr_number,+ }+ .into());}// Fetch PR info (network call via gh CLI)@@ -77,9 +86,10 @@ fn resolve_switch_target(});} else {// Branch exists but tracks something else- return Err(GitError::BranchTracksDifferentPr {+ return Err(GitError::BranchTracksDifferentRef {branch: local_branch,- pr_number,+ ref_type: worktrunk::git::RefType::Pr,+ number: pr_number,}.into());}@@ -112,6 +122,95 @@ fn resolve_switch_target(}}+ // 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,+ }+ .into());+ }+ if base.is_some() {+ return Err(GitError::RefBaseConflict {+ ref_type: worktrunk::git::RefType::Mr,+ number: mr_number,+ }+ .into());+ }++ // 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)?;++ 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);++ // 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());+ }+ }++ // Branch doesn't exist - need full fork MR setup+ let remote_url = repo.primary_remote_url().unwrap_or_default();+ let fork_push_url =+ mr_ref::fork_remote_url(&mr_info, &remote_url).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, &remote_url);++ 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,+ },+ });+ }+ }+// Regular branch switchlet resolved_branch = repo.resolve_worktree_name(branch)@@ -224,8 +323,8 @@ fn check_existing_worktree(/// - For regular switches (not --create), branch must exist/// - Handles --clobber for stale directories///-/// Note: Fork PR branch existence is checked earlier in resolve_switch_target()-/// where we can also check if it's tracking the correct PR.+/// Note: Fork PR/MR branch existence is checked earlier in resolve_switch_target()+/// where we can also check if it's tracking the correct PR/MR.fn validate_worktree_creation(repo: &Repository,branch: &str,@@ -274,33 +373,35 @@ fn validate_worktree_creation(compute_clobber_backup(path, branch, clobber, is_create)}-/// Set up a local branch for a fork PR.+/// Set up a local branch for a fork PR or MR.///-/// Creates the branch, configures tracking, and creates the worktree.-/// Returns an error if any step fails - caller is responsible for cleanup.-fn setup_fork_pr_branch(+/// Creates the branch from FETCH_HEAD, configures tracking (remote, merge ref,+/// pushRemote), and creates the worktree. Returns an error if any step fails -+/// caller is responsible for cleanup.+///+/// # Arguments+///+/// * `remote_ref` - The ref to track (e.g., "pull/123/head" or "merge-requests/101/head")+/// * `label` - Human-readable label for error messages (e.g., "PR #123" or "MR !101")+fn setup_fork_branch(repo: &Repository,branch: &str,remote: &str,- pr_ref: &str,+ remote_ref: &str,fork_push_url: &str,worktree_path: &Path,- pr_number: u32,+ label: &str,) -> anyhow::Result<()> {// Create local branch from FETCH_HEAD- repo.run_command(&["branch", branch, "FETCH_HEAD"])- .with_context(|| {- format!(- "Failed to create local branch '{}' from PR #{}",- branch, pr_number- )- })?;+ // Use -- to prevent branch names starting with - from being interpreted as flags+ repo.run_command(&["branch", "--", branch, "FETCH_HEAD"])+ .with_context(|| format!("Failed to create local branch '{}' from {}", branch, label))?;// Configure branch tracking for pull and pushlet branch_remote_key = format!("branch.{}.remote", branch);let branch_merge_key = format!("branch.{}.merge", branch);let branch_push_remote_key = format!("branch.{}.pushRemote", branch);- let merge_ref = format!("refs/{}", pr_ref);+ let merge_ref = format!("refs/{}", remote_ref);repo.run_command(&["config", &branch_remote_key, remote]).with_context(|| format!("Failed to configure branch.{}.remote", branch))?;@@ -547,20 +648,21 @@ pub fn execute_switch(// 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_pr_branch(+ let setup_result = setup_fork_branch(repo,&branch,&remote,&pr_ref,fork_push_url,&worktree_path,- *pr_number,+ &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)- let _ = repo.run_command(&["branch", "-D", &branch]);+ // Use -- to prevent branch names starting with - from being interpreted as flags+ let _ = repo.run_command(&["branch", "-D", "--", &branch]);return Err(e);}@@ -570,6 +672,62 @@ pub fn execute_switch((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.+ //+ // TODO: The fallback to primary_remote/origin is silent and can pick the+ // wrong remote (e.g., fork instead of target), causing fetch to fail with+ // a confusing "ref not found" error. Consider erroring with a targeted hint+ // like "add upstream remote for target project" when target_project_url is+ // missing or can't be matched to any remote.+ let remote = target_project_url+ .as_ref()+ .and_then(|url| repo.find_remote_by_url(url))+ .or_else(|| repo.primary_remote().ok())+ .unwrap_or_else(|| "origin".to_string());++ // 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)+ })?;++ // 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,+ fork_push_url,+ &worktree_path,+ &format!("MR !{}", mr_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!("MR !{}", mr_number)))+ }};// Compute base worktree path for hooks and result@@ -611,6 +769,14 @@ pub fn execute_switch(vec![("pr_number", &pr_num_str), ("pr_url", pr_url)];ctx.execute_post_create_commands(&extra_vars)?;}+ CreationMethod::ForkMr {+ mr_number, mr_url, ..+ } => {+ let mr_num_str = mr_number.to_string();+ let extra_vars: Vec<(&str, &str)> =+ vec![("mr_number", &mr_num_str), ("mr_url", mr_url)];+ ctx.execute_post_create_commands(&extra_vars)?;+ }}}diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rsindex 9b16b1d08..4a49eeda5 100644--- a/src/commands/worktree/types.rs+++ b/src/commands/worktree/types.rs@@ -73,6 +73,14 @@ pub enum CreationMethod {/// Name of the base repositorybase_repo: String,},+ /// Fork MR: fetch from refs/merge-requests/N/head, create branch, configure pushRemote+ ForkMr {+ mr_number: u32,+ 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>,+ },}/// Validated plan for a switch operation.diff --git a/src/git/error.rs b/src/git/error.rsindex 3a6ab2b71..a15cad417 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -22,6 +22,53 @@ use crate::styling::{suggest_command,};+/// Platform-specific reference type (PR vs MR).+///+/// Used to unify error handling for GitHub PRs and GitLab MRs.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum RefType {+ /// GitHub Pull Request+ Pr,+ /// GitLab Merge Request+ Mr,+}++impl RefType {+ /// Returns the number prefix symbol for this reference type.+ /// - PR: "#" (e.g., "PR #42")+ /// - MR: "!" (e.g., "MR !42")+ pub fn symbol(self) -> &'static str {+ match self {+ Self::Pr => "#",+ Self::Mr => "!",+ }+ }++ /// Returns the short name for this reference type.+ pub fn name(self) -> &'static str {+ match self {+ Self::Pr => "PR",+ Self::Mr => "MR",+ }+ }++ /// Returns the plural form of the short name.+ pub fn name_plural(self) -> &'static str {+ match self {+ Self::Pr => "PRs",+ Self::Mr => "MRs",+ }+ }++ /// Returns the CLI syntax prefix (e.g., "pr:" or "mr:").+ pub fn syntax(self) -> &'static str {+ match self {+ Self::Pr => "pr:",+ Self::Mr => "mr:",+ }+ }+}+/// Domain errors for git and worktree operations.////// This enum provides structured error data that can be pattern-matched and tested.@@ -148,18 +195,21 @@ pub enum GitError {WorktreeNotFound {branch: String,},- /// --create flag used with pr: syntax (conflict - PR branch already exists)- PrCreateConflict {- pr_number: u32,+ /// --create flag used with pr:/mr: syntax (conflict - branch already exists)+ RefCreateConflict {+ ref_type: RefType,+ number: u32,},- /// --base flag used with pr: syntax (conflict - PR base is predetermined)- PrBaseConflict {- pr_number: u32,+ /// --base flag used with pr:/mr: syntax (conflict - base is predetermined)+ RefBaseConflict {+ ref_type: RefType,+ number: u32,},- /// Branch exists but is tracking a different PR- BranchTracksDifferentPr {+ /// Branch exists but is tracking a different PR/MR+ BranchTracksDifferentRef {branch: String,- pr_number: u32,+ ref_type: RefType,+ number: u32,},/// No remote found for the repository where the PR livesNoRemoteForRepo {@@ -168,8 +218,9 @@ pub enum GitError {/// Suggested URL to add as a remote (derived from primary remote's protocol/host)suggested_url: String,},- /// GitHub CLI API command failed with unrecognized error- GhApiError {+ /// CLI API command failed with unrecognized error (gh or glab)+ CliApiError {+ ref_type: RefType,/// Short description of what failedmessage: String,/// Full stderr output for debugging@@ -602,40 +653,55 @@ impl std::fmt::Display for GitError {)}- GitError::PrCreateConflict { pr_number } => {+ GitError::RefCreateConflict { ref_type, number } => {+ let syntax = ref_type.syntax();+ let name_plural = ref_type.name_plural();write!(f,"{}\n{}",error_message(cformat!(- "Cannot use <bold>--create</> with <bold>pr:{pr_number}</>"+ "Cannot use <bold>--create</> with <bold>{syntax}{number}</>")),- hint_message("PRs already have a branch; remove --create")+ hint_message(format!(+ "{name_plural} already have a branch; remove --create"+ )))}- GitError::PrBaseConflict { pr_number } => {+ GitError::RefBaseConflict { ref_type, number } => {+ let syntax = ref_type.syntax();+ let name_plural = ref_type.name_plural();write!(f,"{}\n{}",error_message(cformat!(- "Cannot use <bold>--base</> with <bold>pr:{pr_number}</>"+ "Cannot use <bold>--base</> with <bold>{syntax}{number}</>")),- hint_message("PRs already have a base; remove --base")+ hint_message(format!("{name_plural} already have a base; remove --base")))}- GitError::BranchTracksDifferentPr { branch, pr_number } => {- // The PR's branch name conflicts with an existing local branch.+ GitError::BranchTracksDifferentRef {+ branch,+ ref_type,+ number,+ } => {+ // The ref's branch name conflicts with an existing local branch.// We can't use a different local name because git push requires// the local and remote branch names to match (with push.default=current).+ let escaped = escape(Cow::Borrowed(branch.as_str()));+ let old_name = format!("{branch}-old");+ let escaped_old = escape(Cow::Borrowed(&old_name));+ let name = ref_type.name();+ let symbol = ref_type.symbol();write!(f,"{}\n{}",error_message(cformat!(- "Branch <bold>{branch}</> exists but doesn't track PR #{pr_number}"+ "Branch <bold>{branch}</> exists but doesn't track {name} {symbol}{number}")),hint_message(cformat!(- "To free the name, run <bright-black>git branch -m {branch} {branch}-old</>"+ "To free the name, run <bright-black>git branch -m -- {escaped} {escaped_old}</>")))}@@ -655,7 +721,9 @@ impl std::fmt::Display for GitError {)}- GitError::GhApiError { message, stderr } => {+ GitError::CliApiError {+ message, stderr, ..+ } => {write!(f, "{}", format_error_block(error_message(message), stderr))}@@ -1230,8 +1298,9 @@ mod tests {}#[test]- fn test_git_error_gh_api_error() {- let err = GitError::GhApiError {+ fn test_git_error_cli_api_error() {+ let err = GitError::CliApiError {+ ref_type: RefType::Pr,message: "gh api failed for PR #42".into(),stderr: "error: unexpected response\ncode: 500".into(),};diff --git a/src/git/mod.rs b/src/git/mod.rsindex 0f8e53b7c..effad94e2 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -5,6 +5,7 @@ use std::path::PathBuf;// Submodulesmod diff;mod error;+pub mod mr_ref;mod parse;pub mod pr_ref;mod repository;@@ -37,6 +38,8 @@ pub use error::{GitError,// Special-handling error enum (Display produces styled output)HookErrorWithHint,+ // Platform-specific reference type (PR vs MR)+ RefType,WorktrunkError,// Error inspection functionsadd_hook_skip_hint,@@ -247,6 +250,58 @@ pub struct CompletionBranch {// Re-export parsing helpers for internal usepub(crate) use parse::DefaultBranchName;+use crate::shell_exec::Cmd;++/// 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.+///+/// Used by PR/MR checkout to detect when a branch name collision exists.+///+/// TODO: This only checks `branch.<name>.merge`, not `branch.<name>.remote`. A branch+/// could track the right ref but have the wrong remote configured, which matters for+/// fork PRs/MRs where refs live on the target repo. Consider checking both values.+///+/// # Arguments+/// * `repo_root` - Path to run git commands from+/// * `branch` - Local branch name to check+/// * `expected_ref` - Full ref path (e.g., `refs/pull/101/head` or `refs/merge-requests/42/head`)+pub fn branch_tracks_ref(+ repo_root: &std::path::Path,+ branch: &str,+ expected_ref: &str,+) -> Option<bool> {+ let config_key = format!("branch.{}.merge", branch);+ let output = Cmd::new("git")+ .args(["config", "--get", &config_key])+ .current_dir(repo_root)+ .run()+ .ok()?;++ if !output.status.success() {+ // Config key doesn't exist - branch might not track anything+ // Check if branch exists at all+ let branch_exists = Cmd::new("git")+ .args([+ "show-ref",+ "--verify",+ "--quiet",+ &format!("refs/heads/{}", branch),+ ])+ .current_dir(repo_root)+ .run()+ .map(|o| o.status.success())+ .unwrap_or(false);++ return if branch_exists { Some(false) } else { None };+ }++ let merge_ref = String::from_utf8_lossy(&output.stdout).trim().to_string();+ Some(merge_ref == expected_ref)+}+// Note: HookType and WorktreeInfo are defined in this module and are already public.// They're accessible as git::HookType and git::WorktreeInfo without needing re-export.diff --git a/src/git/mr_ref.rs b/src/git/mr_ref.rsnew file mode 100644index 000000000..d853a859d--- /dev/null+++ b/src/git/mr_ref.rs@@ -0,0 +1,554 @@+//! 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.+//!+//! # 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'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.++use std::io::ErrorKind;++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 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,+}++/// Raw JSON response from `glab mr view <number> --output json`.+#[derive(Debug, Deserialize)]+struct GlabMrResponse {+ source_branch: String,+ source_project_id: u64,+ target_project_id: u64,+ web_url: String,+ /// Source project info (for getting fork URL)+ #[serde(default)]+ source_project: Option<GlabProject>,+ /// Target project info (for finding the correct remote)+ #[serde(default)]+ target_project: Option<GlabProject>,+}++#[derive(Debug, Deserialize)]+struct GlabProject {+ ssh_url_to_repo: Option<String>,+ http_url_to_repo: Option<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 mr view` to get MR metadata including source and target+/// project information.+///+/// # 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 output = match Cmd::new("glab")+ .args(["mr", "view", &mr_number.to_string(), "--output", "json"])+ .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"+ );+ }+ return Err(anyhow::Error::from(e).context("Failed to run glab mr view"));+ }+ };++ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ let stderr_lower = stderr.to_lowercase();++ // TODO: Classifying errors by substring matching is brittle across glab versions+ // and locales. Consider using `glab api` with HTTP status codes for more reliable+ // error detection, or at minimum test against multiple glab versions.++ // MR not found+ if stderr_lower.contains("not found")+ || stderr_lower.contains("404")+ || stderr_lower.contains("could not find")+ {+ bail!("MR !{} not found", mr_number);+ }++ // Authentication errors+ if stderr_lower.contains("authentication")+ || stderr_lower.contains("logged in")+ || stderr_lower.contains("auth login")+ || stderr_lower.contains("not logged")+ || stderr_lower.contains("401")+ || stderr_lower.contains("unauthorized")+ {+ bail!("GitLab CLI not authenticated; run glab auth login");+ }++ // Unknown error - show full output in gutter for debugging+ // (Rate limits, network errors, etc. fall through here with helpful stderr)+ return Err(GitError::CliApiError {+ ref_type: super::RefType::Mr,+ message: format!("glab mr view failed for MR !{}", mr_number),+ stderr: stderr.trim().to_string(),+ }+ .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;++ Ok(MrInfo {+ number: mr_number,+ source_branch: response.source_branch,+ source_project_id: response.source_project_id,+ target_project_id: response.target_project_id,+ source_project_ssh_url: response+ .source_project+ .as_ref()+ .and_then(|p| p.ssh_url_to_repo.clone()),+ source_project_http_url: response+ .source_project+ .as_ref()+ .and_then(|p| p.http_url_to_repo.clone()),+ target_project_ssh_url: response+ .target_project+ .as_ref()+ .and_then(|p| p.ssh_url_to_repo.clone()),+ target_project_http_url: response+ .target_project+ .as_ref()+ .and_then(|p| p.http_url_to_repo.clone()),+ is_cross_project,+ url: response.web_url,+ })+}++/// 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 fork remote URL for pushing, matching the protocol of the reference URL.+///+/// For fork MRs, we need the source project's URL. GitLab provides both SSH and+/// HTTP URLs; we choose based on the primary remote's protocol.+///+/// Falls back to HTTP URL if SSH is not available, or returns `None` if neither+/// is available (shouldn't happen for valid MRs).+pub fn fork_remote_url(mr: &MrInfo, reference_url: &str) -> Option<String> {+ let use_ssh = reference_url.starts_with("git@") || reference_url.contains("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 return whichever is available (preferring+/// the one matching the reference URL protocol).+///+/// Returns `None` if glab didn't provide target project URLs (older versions).+pub fn target_remote_url(mr: &MrInfo, reference_url: &str) -> Option<String> {+ let use_ssh = reference_url.starts_with("git@") || reference_url.contains("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: &std::path::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,+ 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,+ 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_ssh() {+ let mr = MrInfo {+ number: 101,+ 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(),+ };++ // SSH reference → SSH fork URL+ let url = fork_remote_url(&mr, "[email protected]:owner/repo.git");+ assert_eq!(url, Some("[email protected]:contributor/repo.git".to_string()));+ }++ #[test]+ fn test_fork_remote_url_https() {+ let mr = MrInfo {+ number: 101,+ 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(),+ };++ // HTTPS reference → HTTPS fork URL+ let url = fork_remote_url(&mr, "https://gitlab.com/owner/repo.git");+ assert_eq!(+ url,+ Some("https://gitlab.com/contributor/repo.git".to_string())+ );+ }++ #[test]+ fn test_fork_remote_url_fallback() {+ // Only SSH URL available+ let mr = MrInfo {+ number: 101,+ 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(),+ };++ // HTTPS reference but only SSH available → falls back to SSH+ let url = fork_remote_url(&mr, "https://gitlab.com/owner/repo.git");+ assert_eq!(url, Some("[email protected]:contributor/repo.git".to_string()));+ }++ #[test]+ fn test_target_remote_url_ssh() {+ let mr = MrInfo {+ number: 101,+ 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(),+ };++ // SSH reference → SSH target URL+ let url = target_remote_url(&mr, "[email protected]:owner/repo.git");+ assert_eq!(url, Some("[email protected]:owner/repo.git".to_string()));+ }++ #[test]+ fn test_target_remote_url_https() {+ let mr = MrInfo {+ number: 101,+ 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(),+ };++ // HTTPS reference → HTTPS target URL+ let url = target_remote_url(&mr, "https://gitlab.com/owner/repo.git");+ assert_eq!(url, Some("https://gitlab.com/owner/repo.git".to_string()));+ }+}diff --git a/src/git/pr_ref.rs b/src/git/pr_ref.rsindex 3586f641f..b59893278 100644--- a/src/git/pr_ref.rs+++ b/src/git/pr_ref.rs@@ -220,13 +220,8 @@//!//! # Platform Support//!-//! This feature is GitHub-specific. GitLab has similar concepts:-//!-//! - `glab mr view <number>` with `source_branch` field-//! - Different permission model (no exact "maintainer edits" equivalent)-//!-//! Future work could add `mr:<number>` syntax for GitLab, following the same-//! patterns but using `glab` CLI.+//! This feature is GitHub-specific. For GitLab merge requests, use the+//! `mr:<number>` syntax (see `mr_ref` module).//!//! # Implementation Notes//!@@ -434,7 +429,8 @@ pub fn fetch_pr_info(pr_number: u32, repo_root: &std::path::Path) -> anyhow::Res}// Unknown error - show full output in gutter for debugging- return Err(GitError::GhApiError {+ return Err(GitError::CliApiError {+ ref_type: super::RefType::Pr,message: format!("gh api failed for PR #{}", pr_number),stderr: stderr.trim().to_string(),}@@ -525,35 +521,8 @@ pub fn fork_remote_url(owner: &str, repo: &str, reference_url: &str) -> String {/// 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> {- let config_key = format!("branch.{}.merge", branch);- let output = Cmd::new("git")- .args(["config", "--get", &config_key])- .current_dir(repo_root)- .run()- .ok()?;-- if !output.status.success() {- // Config key doesn't exist - branch might not track anything- // Check if branch exists at all- let branch_exists = Cmd::new("git")- .args([- "show-ref",- "--verify",- "--quiet",- &format!("refs/heads/{}", branch),- ])- .current_dir(repo_root)- .run()- .map(|o| o.status.success())- .unwrap_or(false);-- return if branch_exists { Some(false) } else { None };- }-- let merge_ref = String::from_utf8_lossy(&output.stdout).trim().to_string();let expected_ref = format!("refs/pull/{}/head", pr_number);-- Some(merge_ref == expected_ref)+ super::branch_tracks_ref(repo_root, branch, &expected_ref)}#[cfg(test)]diff --git a/src/git/repository/remotes.rs b/src/git/repository/remotes.rsindex 9d9e54699..258f84e86 100644--- a/src/git/repository/remotes.rs+++ b/src/git/repository/remotes.rs@@ -93,6 +93,17 @@ impl Repository {None}+ /// Find a remote that points to the same project as the given URL.+ ///+ /// Parses the URL to extract owner/repo, then searches configured remotes.+ /// 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())+ }+/// Get the URL for the primary remote, if configured.////// Result is cached in the repository's shared cache (same for all clones).diff --git a/src/git/url.rs b/src/git/url.rsindex 0017a9375..f1a18e129 100644--- a/src/git/url.rs+++ b/src/git/url.rs@@ -23,6 +23,11 @@ impl GitRemoteUrl {/// Parse a git remote URL into structured components.////// Returns `None` for malformed URLs or unsupported formats.+ ///+ /// TODO: This assumes exactly `/<owner>/<repo>` structure, which doesn't handle+ /// GitLab's nested group URLs like `gitlab.com/group/subgroup/repo`. For those,+ /// we should treat everything before the last path segment as the namespace.+ /// This can cause `find_remote_by_url` to fail on nested GitLab groups.pub fn parse(url: &str) -> Option<Self> {let url = url.trim();diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 76d9ecf35..b5981c6c8 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -1920,3 +1920,509 @@ fn test_switch_pr_empty_branch(#[from(repo_with_remote)] repo: TestRepo) {assert_cmd_snapshot!("switch_pr_empty_branch", cmd);});}++// ============================================================================+// MR Syntax Tests (mr:<number>) - GitLab+// ============================================================================++/// Helper to set up mock glab for MR tests with custom MR response.+///+/// The response should be in `glab mr view <number> --output json` format:+/// - `source_branch`, `source_project_id`, `target_project_id`+/// - `web_url`+fn setup_mock_glab_for_mr(repo: &TestRepo, glab_response: Option<&str>) -> std::path::PathBuf {+ let mock_bin = repo.root_path().join("mock-bin");+ fs::create_dir_all(&mock_bin).unwrap();++ // Copy mock-stub binary as "glab"+ copy_mock_binary(&mock_bin, "glab");++ // Write MR response file if provided+ if let Some(response) = glab_response {+ fs::write(mock_bin.join("mr_response.json"), response).unwrap();++ MockConfig::new("glab")+ .version("glab version 1.40.0 (mock)")+ .command("mr", MockResponse::file("mr_response.json"))+ .command("_default", MockResponse::exit(1))+ .write(&mock_bin);+ }++ mock_bin+}++/// Configure command environment for mock glab.+fn configure_mock_glab_env(cmd: &mut std::process::Command, mock_bin: &Path) {+ // Tell mock-stub where to find config files+ cmd.env("MOCK_CONFIG_DIR", mock_bin);++ // Build PATH with mock binary first+ let (path_var_name, current_path) = std::env::vars_os()+ .find(|(k, _)| k.eq_ignore_ascii_case("PATH"))+ .map(|(k, v)| (k.to_string_lossy().into_owned(), Some(v)))+ .unwrap_or(("PATH".to_string(), None));++ let mut paths: Vec<std::path::PathBuf> = current_path+ .as_deref()+ .map(|p| std::env::split_paths(p).collect())+ .unwrap_or_default();+ paths.insert(0, mock_bin.to_path_buf());+ let new_path = std::env::join_paths(&paths)+ .unwrap()+ .to_string_lossy()+ .into_owned();++ cmd.env(path_var_name, new_path);+}++/// Test that --create flag conflicts with mr: syntax+#[rstest]+fn test_switch_mr_create_conflict(repo: TestRepo) {+ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["--create", "mr:101"], None);+ assert_cmd_snapshot!("switch_mr_create_conflict", cmd);+ });+}++/// Test that --base flag conflicts with mr: syntax+#[rstest]+fn test_switch_mr_base_conflict(repo: TestRepo) {+ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["--base", "main", "mr:101"], None);+ assert_cmd_snapshot!("switch_mr_base_conflict", cmd);+ });+}++/// Test same-repo MR checkout (source_project_id == target_project_id)+#[rstest]+fn test_switch_mr_same_repo(#[from(repo_with_remote)] mut repo: TestRepo) {+ // Create a feature branch and push it+ repo.add_worktree("feature-auth");++ // glab mr view <number> --output json format+ let glab_response = r#"{+ "source_branch": "feature-auth",+ "source_project_id": 123,+ "target_project_id": 123,+ "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/101"+ }"#;++ let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:101"], None);+ configure_mock_glab_env(&mut cmd, &mock_bin);+ assert_cmd_snapshot!("switch_mr_same_repo", cmd);+ });+}++/// Test error when MR is not found+#[rstest]+fn test_switch_mr_not_found(#[from(repo_with_remote)] repo: TestRepo) {+ let mock_bin = repo.root_path().join("mock-bin");+ fs::create_dir_all(&mock_bin).unwrap();++ // Copy mock-stub binary as "glab"+ copy_mock_binary(&mock_bin, "glab");++ // Configure glab mr to return error for MR not found+ MockConfig::new("glab")+ .version("glab version 1.40.0 (mock)")+ .command(+ "mr",+ MockResponse::stderr(+ "GET https://gitlab.com/api/v4/projects/123/merge_requests/9999: 404 Not Found",+ )+ .with_exit_code(1),+ )+ .command("_default", MockResponse::exit(1))+ .write(&mock_bin);++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:9999"], None);+ configure_mock_glab_env(&mut cmd, &mock_bin);+ assert_cmd_snapshot!("switch_mr_not_found", cmd);+ });+}++/// Test mr: when glab is not authenticated+#[rstest]+fn test_switch_mr_not_authenticated(#[from(repo_with_remote)] repo: TestRepo) {+ let mock_bin = repo.root_path().join("mock-bin");+ fs::create_dir_all(&mock_bin).unwrap();++ copy_mock_binary(&mock_bin, "glab");++ // Configure glab mr to return auth error+ MockConfig::new("glab")+ .version("glab version 1.40.0 (mock)")+ .command(+ "mr",+ MockResponse::stderr(+ "glab: To use GitLab CLI in a non-interactive context, please run `glab auth login`",+ )+ .with_exit_code(1),+ )+ .command("_default", MockResponse::exit(1))+ .write(&mock_bin);++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:101"], None);+ configure_mock_glab_env(&mut cmd, &mock_bin);+ assert_cmd_snapshot!("switch_mr_not_authenticated", cmd);+ });+}++/// Test mr: when glab returns invalid JSON+#[rstest]+fn test_switch_mr_invalid_json(#[from(repo_with_remote)] repo: TestRepo) {+ let mock_bin = repo.root_path().join("mock-bin");+ fs::create_dir_all(&mock_bin).unwrap();++ copy_mock_binary(&mock_bin, "glab");++ // Configure glab mr to return invalid JSON+ MockConfig::new("glab")+ .version("glab version 1.40.0 (mock)")+ .command("mr", MockResponse::output("not valid json {{{"))+ .command("_default", MockResponse::exit(1))+ .write(&mock_bin);++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:101"], None);+ configure_mock_glab_env(&mut cmd, &mock_bin);+ assert_cmd_snapshot!("switch_mr_invalid_json", cmd);+ });+}++/// Test mr: when MR has empty branch name+#[rstest]+fn test_switch_mr_empty_branch(#[from(repo_with_remote)] repo: TestRepo) {+ let mock_bin = repo.root_path().join("mock-bin");+ fs::create_dir_all(&mock_bin).unwrap();++ copy_mock_binary(&mock_bin, "glab");++ // Configure glab to return valid JSON but with empty branch name+ let glab_response = r#"{+ "source_branch": "",+ "source_project_id": 456,+ "target_project_id": 123,+ "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/101"+ }"#;++ MockConfig::new("glab")+ .version("glab version 1.40.0 (mock)")+ .command("mr", MockResponse::output(glab_response))+ .command("_default", MockResponse::exit(1))+ .write(&mock_bin);++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:101"], None);+ configure_mock_glab_env(&mut cmd, &mock_bin);+ assert_cmd_snapshot!("switch_mr_empty_branch", cmd);+ });+}++/// Test fork MR checkout (source_project_id != target_project_id)+#[rstest]+fn test_switch_mr_fork(#[from(repo_with_remote)] repo: TestRepo) {+ // Create a MR ref on the remote that can be fetched+ // First, create a commit that represents the MR head+ repo.run_git(&["checkout", "-b", "mr-source"]);+ fs::write(repo.root_path().join("mr-file.txt"), "MR content").unwrap();+ repo.run_git(&["add", "mr-file.txt"]);+ repo.run_git(&["commit", "-m", "MR commit"]);++ // Get the commit SHA and push to remote as refs/merge-requests/42/head+ let commit_sha = repo+ .git_command()+ .args(["rev-parse", "HEAD"])+ .output()+ .unwrap();+ let sha = String::from_utf8_lossy(&commit_sha.stdout)+ .trim()+ .to_string();++ // Push the ref to the bare remote+ repo.run_git(&[+ "push",+ "origin",+ &format!("{}:refs/merge-requests/42/head", sha),+ ]);++ // Go back to main+ repo.run_git(&["checkout", "main"]);++ // Get the bare remote's actual URL before we modify origin+ let bare_url = String::from_utf8_lossy(+ &repo+ .git_command()+ .args(["config", "remote.origin.url"])+ .output()+ .unwrap()+ .stdout,+ )+ .trim()+ .to_string();++ // Set origin URL to GitLab-style so find_remote_by_url() can match+ repo.run_git(&[+ "remote",+ "set-url",+ "origin",+ "https://gitlab.com/owner/test-repo.git",+ ]);++ // Configure git to redirect gitlab.com URLs to the local bare remote.+ // This is necessary because:+ // 1. origin must have a GitLab URL for find_remote_by_url() to match target project+ // 2. But we need git fetch to actually succeed using the local bare remote+ // Git's url.<base>.insteadOf transparently rewrites the fetch URL.+ repo.run_git(&[+ "config",+ &format!("url.{}.insteadOf", bare_url),+ "https://gitlab.com/owner/test-repo.git",+ ]);++ // glab mr view <number> --output json format+ // source_project is the fork (contributor/test-repo), target_project is the upstream (owner/test-repo)+ let glab_response = r#"{+ "source_branch": "feature-fix",+ "source_project_id": 456,+ "target_project_id": 123,+ "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/42",+ "source_project": {+ "ssh_url_to_repo": "[email protected]:contributor/test-repo.git",+ "http_url_to_repo": "https://gitlab.com/contributor/test-repo.git"+ },+ "target_project": {+ "ssh_url_to_repo": "[email protected]:owner/test-repo.git",+ "http_url_to_repo": "https://gitlab.com/owner/test-repo.git"+ }+ }"#;++ let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:42"], None);+ configure_mock_glab_env(&mut cmd, &mock_bin);+ assert_cmd_snapshot!("switch_mr_fork", cmd);+ });+}++/// Test fork MR checkout when branch already exists and tracks the MR+#[rstest]+fn test_switch_mr_fork_existing_branch_tracks_mr(#[from(repo_with_remote)] repo: TestRepo) {+ // Create the branch that will track the MR+ repo.run_git(&["checkout", "-b", "feature-fix"]);+ fs::write(repo.root_path().join("mr-file.txt"), "MR content").unwrap();+ repo.run_git(&["add", "mr-file.txt"]);+ repo.run_git(&["commit", "-m", "MR commit"]);++ // Get the commit SHA and push to remote as refs/merge-requests/42/head+ let commit_sha = repo+ .git_command()+ .args(["rev-parse", "HEAD"])+ .output()+ .unwrap();+ let sha = String::from_utf8_lossy(&commit_sha.stdout)+ .trim()+ .to_string();++ repo.run_git(&[+ "push",+ "origin",+ &format!("{}:refs/merge-requests/42/head", sha),+ ]);++ // Configure branch to track the MR ref (as our code would set it up)+ repo.run_git(&["config", "branch.feature-fix.remote", "origin"]);+ repo.run_git(&[+ "config",+ "branch.feature-fix.merge",+ "refs/merge-requests/42/head",+ ]);++ // Go back to main+ repo.run_git(&["checkout", "main"]);++ // Set origin URL to GitLab-style+ let bare_url = String::from_utf8_lossy(+ &repo+ .git_command()+ .args(["config", "remote.origin.url"])+ .output()+ .unwrap()+ .stdout,+ )+ .trim()+ .to_string();++ repo.run_git(&[+ "remote",+ "set-url",+ "origin",+ "https://gitlab.com/owner/test-repo.git",+ ]);+ repo.run_git(&[+ "config",+ &format!("url.{}.insteadOf", bare_url),+ "https://gitlab.com/owner/test-repo.git",+ ]);++ // Fork MR response+ let glab_response = r#"{+ "source_branch": "feature-fix",+ "source_project_id": 456,+ "target_project_id": 123,+ "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/42",+ "source_project": {+ "ssh_url_to_repo": "[email protected]:contributor/test-repo.git",+ "http_url_to_repo": "https://gitlab.com/contributor/test-repo.git"+ },+ "target_project": {+ "ssh_url_to_repo": "[email protected]:owner/test-repo.git",+ "http_url_to_repo": "https://gitlab.com/owner/test-repo.git"+ }+ }"#;++ let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:42"], None);+ configure_mock_glab_env(&mut cmd, &mock_bin);+ assert_cmd_snapshot!("switch_mr_fork_existing_branch_tracks_mr", cmd);+ });+}++/// Test fork MR checkout when branch exists but tracks something else+#[rstest]+fn test_switch_mr_fork_existing_branch_tracks_different(#[from(repo_with_remote)] repo: TestRepo) {+ // Create the branch that tracks a different ref+ repo.run_git(&["checkout", "-b", "feature-fix"]);+ fs::write(repo.root_path().join("mr-file.txt"), "MR content").unwrap();+ repo.run_git(&["add", "mr-file.txt"]);+ repo.run_git(&["commit", "-m", "MR commit"]);++ // Configure branch to track a different MR+ repo.run_git(&["config", "branch.feature-fix.remote", "origin"]);+ repo.run_git(&[+ "config",+ "branch.feature-fix.merge",+ "refs/merge-requests/99/head", // Different MR number+ ]);++ // Go back to main+ repo.run_git(&["checkout", "main"]);++ // Set origin URL to GitLab-style+ repo.run_git(&[+ "remote",+ "set-url",+ "origin",+ "https://gitlab.com/owner/test-repo.git",+ ]);++ // Fork MR response for MR 42, but branch tracks MR 99+ let glab_response = r#"{+ "source_branch": "feature-fix",+ "source_project_id": 456,+ "target_project_id": 123,+ "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/42",+ "source_project": {+ "ssh_url_to_repo": "[email protected]:contributor/test-repo.git",+ "http_url_to_repo": "https://gitlab.com/contributor/test-repo.git"+ },+ "target_project": {+ "ssh_url_to_repo": "[email protected]:owner/test-repo.git",+ "http_url_to_repo": "https://gitlab.com/owner/test-repo.git"+ }+ }"#;++ let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:42"], None);+ configure_mock_glab_env(&mut cmd, &mock_bin);+ assert_cmd_snapshot!("switch_mr_fork_existing_branch_tracks_different", cmd);+ });+}++/// Test fork MR checkout when branch exists but has no tracking config+#[rstest]+fn test_switch_mr_fork_existing_no_tracking(#[from(repo_with_remote)] repo: TestRepo) {+ // Create the branch without any tracking config+ repo.run_git(&["branch", "feature-fix", "main"]);+ // No config set - branch exists but doesn't track anything++ // Set origin URL to GitLab-style+ repo.run_git(&[+ "remote",+ "set-url",+ "origin",+ "https://gitlab.com/owner/test-repo.git",+ ]);++ // Fork MR response+ let glab_response = r#"{+ "source_branch": "feature-fix",+ "source_project_id": 456,+ "target_project_id": 123,+ "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/42",+ "source_project": {+ "ssh_url_to_repo": "[email protected]:contributor/test-repo.git",+ "http_url_to_repo": "https://gitlab.com/contributor/test-repo.git"+ },+ "target_project": {+ "ssh_url_to_repo": "[email protected]:owner/test-repo.git",+ "http_url_to_repo": "https://gitlab.com/owner/test-repo.git"+ }+ }"#;++ let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:42"], None);+ configure_mock_glab_env(&mut cmd, &mock_bin);+ assert_cmd_snapshot!("switch_mr_fork_existing_no_tracking", cmd);+ });+}++/// Test mr: with unknown glab error (falls through to general error handler)+#[rstest]+fn test_switch_mr_unknown_error(#[from(repo_with_remote)] repo: TestRepo) {+ let mock_bin = repo.root_path().join("mock-bin");+ fs::create_dir_all(&mock_bin).unwrap();++ copy_mock_binary(&mock_bin, "glab");++ // Configure glab mr to return an unknown error+ MockConfig::new("glab")+ .version("glab version 1.40.0 (mock)")+ .command(+ "mr",+ MockResponse::stderr("glab: unexpected internal error: something went wrong")+ .with_exit_code(1),+ )+ .command("_default", MockResponse::exit(1))+ .write(&mock_bin);++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["mr:101"], None);+ configure_mock_glab_env(&mut cmd, &mock_bin);+ assert_cmd_snapshot!("switch_mr_unknown_error", cmd);+ });+}diff --git a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap b/tests/snapshots/integration__integration_tests__help__help_switch_long.snapindex c18b38940..8e0294777 100644--- a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap@@ -31,7 +31,7 @@ Usage: [1m[36mwt switch[0m [36m[OPTIONS][0m [36m<BRANCH>[0m [1m[36m[--[36m<BRANCH>Branch name or shortcut- Shortcuts: '^' (default branch), '-' (previous), '@' (current), 'pr:{N}' (GitHub PR, experimental)+ Shortcuts: '^' (default branch), '-' (previous), '@' (current), 'pr:{N}' (GitHub PR), 'mr:{N}' (GitLab MR)[36m[EXECUTE_ARGS]...Additional arguments for --execute command (after --)@@ -127,11 +127,13 @@ When creating a worktree, worktrunk:@ Current branch/worktree- Previous worktree (like cd -)pr:{N} GitHub PR #N's branch+ mr:{N} GitLab MR !N's branch[2mwt switch - # Back to previous[2mwt switch ^ # Default branch worktree[2mwt switch --create fix --base=@ # Branch from current HEAD[2mwt switch pr:123 # PR #123's branch+ [2mwt switch mr:101 # MR !101's branch[1m[32mGitHub pull requests (experimental)@@ -143,6 +145,16 @@ Requires [2mgh[0m CLI to be installed and authenticated. The [2m--create[0m[1mFork PRs:[0m The local branch uses the PR's branch name directly (e.g., [2mfeature-fix[0m), so [2mgit push[0m works normally. If a local branch with that name already exists tracking something else, rename it first.+[1m[32mGitLab merge requests (experimental)++The [2mmr:<number>[0m syntax resolves the branch for a GitLab merge request. For same-project MRs, it switches to the branch directly. For fork MRs, it fetches [2mrefs/merge-requests/N/head[0m and configures [2mpushRemote[0m to the fork URL.++ [2mwt switch mr:101 # Checkout MR !101++Requires [2mglab[0m CLI to be installed and authenticated. The [2m--create[0m flag cannot be used with [2mmr:[0m syntax since the branch already exists.++[1mFork MRs:[0m The local branch uses the MR's branch name directly, so [2mgit push[0m works normally. If a local branch with that name already exists tracking something else, rename it first.+[1m[32mWhen wt switch fails- [1mBranch doesn't exist[0m — Use [2m--create[0m, or check [2mwt list --branchesdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_base_conflict.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_base_conflict.snapnew file mode 100644index 000000000..ad831950c--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_base_conflict.snap@@ -0,0 +1,40 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "--base"+ - main+ - "mr:101"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ RUST_LOG: warn+ SHELL: ""+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[31m✗[39m [31mCannot use [1m--base[22m with [1mmr:101[22m[39m+[2m↳[22m [2mMRs already have a base; remove --base[22mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_create_conflict.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_create_conflict.snapnew file mode 100644index 000000000..5ea5d0cf7--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_create_conflict.snap@@ -0,0 +1,39 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "--create"+ - "mr:101"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ RUST_LOG: warn+ SHELL: ""+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[31m✗[39m [31mCannot use [1m--create[22m with [1mmr:101[22m[39m+[2m↳[22m [2mMRs already have a branch; remove --create[22mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_empty_branch.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_empty_branch.snapnew file mode 100644index 000000000..25f5dfc3a--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_empty_branch.snap@@ -0,0 +1,38 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "mr:101"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ RUST_LOG: warn+ SHELL: ""+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[36m◎[39m [36mFetching MR !101...[39m+[31m✗[39m [31mMR !101 has empty branch name; the MR may be in an invalid state[39mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_fork.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_fork.snapnew file mode 100644index 000000000..25753aa2b--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_fork.snap@@ -0,0 +1,41 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "mr:42"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ RUST_LOG: warn+ SHELL: ""+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[36m◎[39m [36mFetching MR !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+[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_fork_existing_branch_tracks_different.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_fork_existing_branch_tracks_different.snapnew file mode 100644index 000000000..2775ccbb0--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_fork_existing_branch_tracks_different.snap@@ -0,0 +1,40 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "mr:42"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ RUST_LOG: warn+ SHELL: ""+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WT_TEST_DELAYED_STREAM_MS: "999999"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[36m◎[39m [36mFetching MR !42...[39m+[31m✗[39m [31mBranch [1mfeature-fix[22m exists but doesn't track MR !42[39m+[2m↳[22m [2mTo free the name, run [90mgit branch -m -- feature-fix feature-fix-old[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_fork_existing_branch_tracks_mr.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_fork_existing_branch_tracks_mr.snapnew file mode 100644index 000000000..cf97949b5--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_fork_existing_branch_tracks_mr.snap@@ -0,0 +1,42 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "mr:42"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ RUST_LOG: warn+ SHELL: ""+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WT_TEST_DELAYED_STREAM_MS: "999999"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[36m◎[39m [36mFetching MR !42...[39m+[2m○[22m Branch [1mfeature-fix[22m already configured for MR !42+[32m✓[39m [32mCreated worktree for [1mfeature-fix[22m @ [1m_REPO_.feature-fix[22m[39m+[33m▲[39m [33mCannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_fork_existing_no_tracking.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_fork_existing_no_tracking.snapnew file mode 100644index 000000000..2775ccbb0--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_fork_existing_no_tracking.snap@@ -0,0 +1,40 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "mr:42"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ RUST_LOG: warn+ SHELL: ""+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WT_TEST_DELAYED_STREAM_MS: "999999"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[36m◎[39m [36mFetching MR !42...[39m+[31m✗[39m [31mBranch [1mfeature-fix[22m exists but doesn't track MR !42[39m+[2m↳[22m [2mTo free the name, run [90mgit branch -m -- feature-fix feature-fix-old[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_invalid_json.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_invalid_json.snapnew file mode 100644index 000000000..69084d33c--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_invalid_json.snap@@ -0,0 +1,39 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "mr:101"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ RUST_LOG: warn+ SHELL: ""+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[36m◎[39m [36mFetching MR !101...[39m+[31m✗[39m [31mFailed to parse GitLab API response for MR !101. This may indicate a GitLab API change.[39m+[107m [0m expected ident at line 1 column 2diff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_not_authenticated.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_not_authenticated.snapnew file mode 100644index 000000000..33297e829--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_not_authenticated.snap@@ -0,0 +1,38 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "mr:101"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ RUST_LOG: warn+ SHELL: ""+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[36m◎[39m [36mFetching MR !101...[39m+[31m✗[39m [31mGitLab CLI not authenticated; run glab auth login[39mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_not_found.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_not_found.snapnew file mode 100644index 000000000..ea609fafd--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_not_found.snap@@ -0,0 +1,38 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "mr:9999"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ RUST_LOG: warn+ SHELL: ""+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[36m◎[39m [36mFetching MR !9999...[39m+[31m✗[39m [31mMR !9999 not found[39mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_same_repo.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_same_repo.snapnew file mode 100644index 000000000..2e084c374--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_same_repo.snap@@ -0,0 +1,39 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "mr:101"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ RUST_LOG: warn+ SHELL: ""+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[36m◎[39m [36mFetching MR !101...[39m+[33m▲[39m [33mWorktree for [1mfeature-auth[22m @ [1m_REPO_.feature-auth[22m, but cannot change directory — shell integration not installed[39m+[2m↳[22m [2mTo enable automatic cd, run [90mwt config shell install[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_unknown_error.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_unknown_error.snapnew file mode 100644index 000000000..1e1f1b3f0--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_unknown_error.snap@@ -0,0 +1,40 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "mr:101"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ RUST_LOG: warn+ SHELL: ""+ SOURCE_DATE_EPOCH: "1735776000"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WT_TEST_DELAYED_STREAM_MS: "999999"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[36m◎[39m [36mFetching MR !101...[39m+[31m✗[39m [31mglab mr view failed for MR !101[39m+[107m [0m glab: unexpected internal error: something went wrongdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_fork_existing_different_pr.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_fork_existing_different_pr.snapindex a620bbe85..56996dda1 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_pr_fork_existing_different_pr.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_fork_existing_different_pr.snap@@ -36,4 +36,4 @@ exit_code: 1----- stderr -----[36m◎[39m [36mFetching PR #42...[39m[31m✗[39m [31mBranch [1mfeature-fix[22m exists but doesn't track PR #42[39m-[2m↳[22m [2mTo free the name, run [90mgit branch -m feature-fix feature-fix-old[39m[22m+[2m↳[22m [2mTo free the name, run [90mgit branch -m -- feature-fix feature-fix-old[39m[22mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_fork_existing_no_tracking.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_fork_existing_no_tracking.snapindex a620bbe85..56996dda1 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_pr_fork_existing_no_tracking.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_fork_existing_no_tracking.snap@@ -36,4 +36,4 @@ exit_code: 1----- stderr -----[36m◎[39m [36mFetching PR #42...[39m[31m✗[39m [31mBranch [1mfeature-fix[22m exists but doesn't track PR #42[39m-[2m↳[22m [2mTo free the name, run [90mgit branch -m feature-fix feature-fix-old[39m[22m+[2m↳[22m [2mTo free the name, run [90mgit branch -m -- feature-fix feature-fix-old[39m[22m