Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: replace string parsing with structured error handling (#787)
Maximilian Rooscf6d16dd0f49
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex f4786383e..6eebdf2f6 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -3,7 +3,7 @@ use std::process;use std::time::{SystemTime, UNIX_EPOCH};use super::worktree::{BranchDeletionMode, RemoveResult, get_path_mismatch};-use anyhow::Context;+use anyhow::{Context, bail};use color_print::cformat;use worktrunk::config::UserConfig;use worktrunk::git::{@@ -280,16 +280,13 @@ impl RepositoryCliExt for Repository {format_path_for_display(wt_path))))?;- let stash_output =- wt.run_command(&["stash", "push", "--include-untracked", "-m", &stash_name])?;-- if stash_output.contains("No local changes to save") {- return Ok(None);- }+ // Stash all changes including untracked files.+ // Note: git stash push returns exit code 0 whether or not anything was stashed.+ wt.run_command(&["stash", "push", "--include-untracked", "-m", &stash_name])?;+ // Verify stash was created by checking the stash list for our entry.let list_output = wt.run_command(&["stash", "list", "--format=%gd%x00%gs%x00"])?;let mut parts = list_output.split('\0');- let mut stash_ref = None;while let Some(id) = parts.next() {if id.is_empty() {continue;@@ -297,19 +294,23 @@ impl RepositoryCliExt for Repository {if let Some(message) = parts.next()&& (message == stash_name || message.ends_with(&stash_name)){- stash_ref = Some(id.to_string());- break;+ return Ok(Some(TargetWorktreeStash::new(wt_path, id.to_string())));}}- let Some(stash_ref) = stash_ref else {- return Err(anyhow::anyhow!(- "Failed to locate autostash entry '{}'",+ // Stash entry not found. Verify the worktree is now clean — if it's still+ // dirty, stashing may have failed silently or our lookup missed the entry.+ if wt.is_dirty()? {+ bail!(+ "Failed to stash changes in {}; worktree still has uncommitted changes. \+ Expected stash entry: '{}'. Check 'git stash list'.",+ format_path_for_display(wt_path),stash_name- ));- };+ );+ }- Ok(Some(TargetWorktreeStash::new(wt_path, stash_ref)))+ // Worktree is clean and no stash entry — nothing needed to be stashed+ Ok(None)}fn is_rebased_onto(&self, target: &str) -> anyhow::Result<bool> {diff --git a/src/git/mr_ref.rs b/src/git/mr_ref.rsindex 8e57f1ab0..434863d01 100644--- a/src/git/mr_ref.rs+++ b/src/git/mr_ref.rs@@ -11,12 +11,12 @@//!//! ## API Fields//!-//! We use `glab mr view <number> --output json` which returns:+//! 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-//! - `source_project.ssh_url_to_repo`, `http_url_to_repo` — fork URLs-//! - `target_project.ssh_url_to_repo`, `http_url_to_repo` — target URLs//! - `web_url` — MR web URL+//!+//! For fork URLs, we make additional API calls to fetch project details.use std::io::ErrorKind;use std::path::Path;@@ -84,7 +84,7 @@ impl super::RefContext for MrInfo {}}-/// Raw JSON response from `glab mr view <number> --output json`.+/// Raw JSON response from `glab api projects/:id/merge_requests/<number>`.#[derive(Debug, Deserialize)]struct GlabMrResponse {title: String,@@ -96,14 +96,9 @@ struct GlabMrResponse {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>,}+/// Raw JSON response from `glab api projects/<id>`.#[derive(Debug, Deserialize)]struct GlabAuthor {username: String,@@ -115,6 +110,16 @@ struct GlabProject {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.@@ -125,8 +130,8 @@ pub fn parse_mr_ref(input: &str) -> Option<u32> {/// Fetch MR information from GitLab using the `glab` CLI.///-/// Uses `glab mr view` to get MR metadata including source and target-/// project information.+/// Uses `glab api` to get MR metadata. For fork MRs, makes additional+/// API calls to fetch source and target project URLs.////// # Errors///@@ -135,8 +140,10 @@ pub fn parse_mr_ref(input: &str) -> Option<u32> {/// - The MR doesn't exist/// - The JSON response is malformedpub 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(["mr", "view", &mr_number.to_string(), "--output", "json"])+ .args(["api", &api_path]).current_dir(repo_root).env("GLAB_NO_PROMPT", "1").run()@@ -149,43 +156,44 @@ pub fn fetch_mr_info(mr_number: u32, repo_root: &std::path::Path) -> anyhow::Res"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 mr view"));+ return Err(anyhow::Error::from(e).context("Failed to run glab api"));}};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");+ // 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);+ }}- // Unknown error - show full output in gutter for debugging- // (Rate limits, network errors, etc. fall through here with helpful stderr)+ // 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 mr view failed for MR !{}", mr_number),- stderr: stderr.trim().to_string(),+ message: format!("glab api failed for MR !{}", mr_number),+ stderr: details,}.into());}@@ -208,6 +216,32 @@ pub fn fetch_mr_info(mr_number: u32, repo_root: &std::path::Path) -> anyhow::Reslet 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,@@ -217,27 +251,36 @@ pub fn fetch_mr_info(mr_number: u32, repo_root: &std::path::Path) -> anyhow::Ressource_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()),+ 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 ensuresdiff --git a/src/git/pr_ref.rs b/src/git/pr_ref.rsindex 5f77bfce0..ebdc36584 100644--- a/src/git/pr_ref.rs+++ b/src/git/pr_ref.rs@@ -104,6 +104,17 @@ struct GhApiPrResponse {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,@@ -168,45 +179,36 @@ pub fn fetch_pr_info(pr_number: u32, repo_root: &std::path::Path) -> anyhow::Res};if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- let stderr_lower = stderr.to_lowercase();-- // PR not found (HTTP 404)- if stderr_lower.contains("not found") || stderr_lower.contains("404") {- bail!("PR #{} not found", pr_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")- {- bail!("GitHub CLI not authenticated; run gh auth login");- }-- // Rate limiting- if stderr_lower.contains("rate limit")- || stderr_lower.contains("api rate")- || stderr_lower.contains("403")- {- bail!("GitHub API rate limit exceeded; wait a few minutes and retry");- }-- // Network errors- if stderr_lower.contains("network")- || stderr_lower.contains("connection")- || stderr_lower.contains("timeout")- {- bail!("Network error connecting to GitHub; check your internet connection");+ // 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);+ }+ _ => {}+ }}- // Unknown error - show full output in gutter for debugging+ // 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: stderr.trim().to_string(),+ stderr: details,}.into());}diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rsindex 3612862eb..74af39325 100644--- a/src/git/repository/working_tree.rs+++ b/src/git/repository/working_tree.rs@@ -54,12 +54,7 @@ pub struct WorkingTree<'a> {impl<'a> WorkingTree<'a> {/// Run a git command in this worktree and return stdout.pub fn run_command(&self, args: &[&str]) -> anyhow::Result<String> {- let output = Cmd::new("git")- .args(args.iter().copied())- .current_dir(&self.path)- .context(path_to_logging_context(&self.path))- .run()- .with_context(|| format!("Failed to execute: git {}", args.join(" ")))?;+ let output = self.run_command_output(args)?;if !output.status.success() {let stderr = String::from_utf8_lossy(&output.stderr);@@ -77,6 +72,19 @@ impl<'a> WorkingTree<'a> {Ok(stdout)}+ /// Run a git command in this worktree and return the raw Output.+ ///+ /// Use this when you need to check exit codes directly (e.g., for commands+ /// where non-zero exit is not an error condition).+ pub fn run_command_output(&self, args: &[&str]) -> anyhow::Result<std::process::Output> {+ Cmd::new("git")+ .args(args.iter().copied())+ .current_dir(&self.path)+ .context(path_to_logging_context(&self.path))+ .run()+ .with_context(|| format!("Failed to execute: git {}", args.join(" ")))+ }+// =========================================================================// Worktree-specific methods// =========================================================================diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex ab1310ec0..d38f73073 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -1673,12 +1673,14 @@ fn test_switch_pr_not_found(#[from(repo_with_remote)] repo: TestRepo) {// Copy mock-stub binary as "gh"copy_mock_binary(&mock_bin, "gh");- // Configure gh api to return error for PR not found (errors go to stderr)+ // Configure gh api to return error for PR not found (JSON on stdout, human-readable on stderr)MockConfig::new("gh").version("gh version 2.0.0 (mock)").command("api",- MockResponse::stderr("gh api: Not Found (HTTP 404)").with_exit_code(1),+ MockResponse::output(r#"{"message":"Not Found","status":"404"}"#)+ .with_stderr("gh: Not Found (HTTP 404)")+ .with_exit_code(1),).command("_default", MockResponse::exit(1)).write(&mock_bin);@@ -2097,15 +2099,14 @@ fn test_switch_pr_not_authenticated(#[from(repo_with_remote)] repo: TestRepo) {copy_mock_binary(&mock_bin, "gh");- // Configure gh api to return auth error+ // Configure gh api to return auth error (JSON on stdout, human-readable on stderr)MockConfig::new("gh").version("gh version 2.0.0 (mock)").command("api",- MockResponse::stderr(- "To use GitHub CLI in a non-interactive context, please run gh auth login",- )- .with_exit_code(1),+ MockResponse::output(r#"{"message":"Requires authentication","status":"401"}"#)+ .with_stderr("gh: Requires authentication (HTTP 401)")+ .with_exit_code(1),).command("_default", MockResponse::exit(1)).write(&mock_bin);@@ -2126,13 +2127,16 @@ fn test_switch_pr_rate_limit(#[from(repo_with_remote)] repo: TestRepo) {copy_mock_binary(&mock_bin, "gh");- // Configure gh api to return rate limit error (HTTP 403)+ // Configure gh api to return rate limit error (JSON on stdout, human-readable on stderr)MockConfig::new("gh").version("gh version 2.0.0 (mock)").command("api",- MockResponse::stderr("gh api: API rate limit exceeded for user (HTTP 403)")- .with_exit_code(1),+ MockResponse::output(+ r#"{"message":"API rate limit exceeded for user","status":"403"}"#,+ )+ .with_stderr("gh: API rate limit exceeded (HTTP 403)")+ .with_exit_code(1),).command("_default", MockResponse::exit(1)).write(&mock_bin);@@ -2176,7 +2180,7 @@ fn test_switch_pr_network_error(#[from(repo_with_remote)] repo: TestRepo) {copy_mock_binary(&mock_bin, "gh");- // Configure gh api to return network error+ // Configure gh api to return network error (no JSON, just stderr for network failures)MockConfig::new("gh").version("gh version 2.0.0 (mock)").command(@@ -2266,7 +2270,7 @@ fn test_switch_pr_empty_branch(#[from(repo_with_remote)] repo: TestRepo) {/// 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:+/// The response should be in `glab api projects/:id/merge_requests/<number>` 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 {@@ -2282,7 +2286,7 @@ fn setup_mock_glab_for_mr(repo: &TestRepo, glab_response: Option<&str>) -> std::MockConfig::new("glab").version("glab version 1.40.0 (mock)")- .command("mr", MockResponse::file("mr_response.json"))+ .command("api", MockResponse::file("mr_response.json")).command("_default", MockResponse::exit(1)).write(&mock_bin);}@@ -2340,7 +2344,7 @@ fn test_switch_mr_same_repo(#[from(repo_with_remote)] mut repo: TestRepo) {// Create a feature branch and push itrepo.add_worktree("feature-auth");- // glab mr view <number> --output json format+ // glab api projects/:id/merge_requests/<number> formatlet glab_response = r#"{"title": "Fix authentication bug in login flow","author": {"username": "alice"},@@ -2371,15 +2375,12 @@ fn test_switch_mr_not_found(#[from(repo_with_remote)] repo: TestRepo) {// Copy mock-stub binary as "glab"copy_mock_binary(&mock_bin, "glab");- // Configure glab mr to return error for MR not found+ // Configure glab api to return 404 error (JSON on stdout like real GitLab API)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),+ "api",+ MockResponse::output(r#"{"message":"404 Not found"}"#).with_exit_code(1),).command("_default", MockResponse::exit(1)).write(&mock_bin);@@ -2400,15 +2401,12 @@ fn test_switch_mr_not_authenticated(#[from(repo_with_remote)] repo: TestRepo) {copy_mock_binary(&mock_bin, "glab");- // Configure glab mr to return auth error+ // Configure glab api to return 401 error (JSON on stdout like real GitLab API)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),+ "api",+ MockResponse::output(r#"{"message":"401 Unauthorized"}"#).with_exit_code(1),).command("_default", MockResponse::exit(1)).write(&mock_bin);@@ -2429,10 +2427,10 @@ fn test_switch_mr_invalid_json(#[from(repo_with_remote)] repo: TestRepo) {copy_mock_binary(&mock_bin, "glab");- // Configure glab mr to return invalid JSON+ // Configure glab api to return invalid JSONMockConfig::new("glab").version("glab version 1.40.0 (mock)")- .command("mr", MockResponse::output("not valid json {{{"))+ .command("api", MockResponse::output("not valid json {{{")).command("_default", MockResponse::exit(1)).write(&mock_bin);@@ -2452,7 +2450,7 @@ fn test_switch_mr_empty_branch(#[from(repo_with_remote)] repo: TestRepo) {copy_mock_binary(&mock_bin, "glab");- // Configure glab to return valid JSON but with empty branch name+ // Configure glab api to return valid JSON but with empty branch namelet glab_response = r#"{"title": "MR with empty branch","author": {"username": "contributor"},@@ -2466,7 +2464,7 @@ fn test_switch_mr_empty_branch(#[from(repo_with_remote)] repo: TestRepo) {MockConfig::new("glab").version("glab version 1.40.0 (mock)")- .command("mr", MockResponse::output(glab_response))+ .command("api", MockResponse::output(glab_response)).command("_default", MockResponse::exit(1)).write(&mock_bin);@@ -2539,9 +2537,15 @@ fn test_switch_mr_fork(#[from(repo_with_remote)] repo: TestRepo) {"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#"{+ // Set up mock glab with separate responses for MR API and project APIs.+ // The mock-stub supports compound keys like "api projects/456" to match+ // different API paths.+ let mock_bin = repo.root_path().join("mock-bin");+ fs::create_dir_all(&mock_bin).unwrap();+ copy_mock_binary(&mock_bin, "glab");++ // MR API response (no nested project data - that comes from separate calls)+ let mr_response = r#"{"title": "Add feature fix for edge case","author": {"username": "contributor"},"state": "opened",@@ -2549,18 +2553,40 @@ fn test_switch_mr_fork(#[from(repo_with_remote)] repo: TestRepo) {"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"- }+ "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/42"}"#;- let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));+ // Source project (fork) API response+ let source_project_response = r#"{+ "ssh_url_to_repo": "[email protected]:contributor/test-repo.git",+ "http_url_to_repo": "https://gitlab.com/contributor/test-repo.git"+ }"#;++ // Target project (upstream) API response+ let target_project_response = r#"{+ "ssh_url_to_repo": "[email protected]:owner/test-repo.git",+ "http_url_to_repo": "https://gitlab.com/owner/test-repo.git"+ }"#;++ MockConfig::new("glab")+ .version("glab version 1.40.0 (mock)")+ // Compound key: "api projects/:id/merge_requests/42"+ .command(+ "api projects/:id/merge_requests/42",+ MockResponse::output(mr_response),+ )+ // Compound key: "api projects/456" (source project)+ .command(+ "api projects/456",+ MockResponse::output(source_project_response),+ )+ // Compound key: "api projects/123" (target project)+ .command(+ "api projects/123",+ MockResponse::output(target_project_response),+ )+ .command("_default", MockResponse::exit(1))+ .write(&mock_bin);let settings = setup_snapshot_settings(&repo);settings.bind(|| {@@ -2630,7 +2656,7 @@ fn test_switch_mr_fork_existing_branch_tracks_mr(#[from(repo_with_remote)] repo:"https://gitlab.com/owner/test-repo.git",]);- // Fork MR response+ // Fork MR response (project URLs not needed since branch already exists)let glab_response = r#"{"title": "Add feature fix for edge case","author": {"username": "contributor"},@@ -2639,15 +2665,7 @@ fn test_switch_mr_fork_existing_branch_tracks_mr(#[from(repo_with_remote)] repo:"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"- }+ "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/42"}"#;let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));@@ -2688,7 +2706,7 @@ fn test_switch_mr_fork_existing_branch_tracks_different(#[from(repo_with_remote)"https://gitlab.com/owner/test-repo.git",]);- // Fork MR response for MR 42, but branch tracks MR 99+ // Fork MR response for MR 42, but branch tracks MR 99 (error case)let glab_response = r#"{"title": "Add feature fix for edge case","author": {"username": "contributor"},@@ -2697,15 +2715,7 @@ fn test_switch_mr_fork_existing_branch_tracks_different(#[from(repo_with_remote)"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"- }+ "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/42"}"#;let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));@@ -2733,7 +2743,7 @@ fn test_switch_mr_fork_existing_no_tracking(#[from(repo_with_remote)] repo: Test"https://gitlab.com/owner/test-repo.git",]);- // Fork MR response+ // Fork MR response (project URLs not needed since branch already exists)let glab_response = r#"{"title": "Add feature fix for edge case","author": {"username": "contributor"},@@ -2742,15 +2752,7 @@ fn test_switch_mr_fork_existing_no_tracking(#[from(repo_with_remote)] repo: Test"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"- }+ "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/42"}"#;let mock_bin = setup_mock_glab_for_mr(&repo, Some(glab_response));@@ -2771,11 +2773,11 @@ fn test_switch_mr_unknown_error(#[from(repo_with_remote)] repo: TestRepo) {copy_mock_binary(&mock_bin, "glab");- // Configure glab mr to return an unknown error+ // Configure glab api to return an unknown error (non-JSON stderr, like network errors)MockConfig::new("glab").version("glab version 1.40.0 (mock)").command(- "mr",+ "api",MockResponse::stderr("glab: unexpected internal error: something went wrong").with_exit_code(1),)diff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_unknown_error.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_unknown_error.snapindex f01aa4a81..b84f81bef 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_mr_unknown_error.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_unknown_error.snap@@ -36,5 +36,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mFetching MR !101...[39m-[31m✗[39m [31mglab mr view failed for MR !101[39m+[31m✗[39m [31mglab api failed for MR !101[39m[107m [0m glab: unexpected internal error: something went wrongdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_network_error.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_network_error.snapindex 204b168d4..efa601e73 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_pr_network_error.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_network_error.snap@@ -36,4 +36,5 @@ exit_code: 1----- stderr -----[36m◎[39m [36mFetching PR #101...[39m-[31m✗[39m [31mNetwork error connecting to GitHub; check your internet connection[39m+[31m✗[39m [31mgh api failed for PR #101[39m+[107m [0m connection refused: network is unreachable