Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(gitlab): forward glab's verdict when the project lookup fails (#3799)
Worktrunk Bot1636b78ddf47
diff --git a/src/git/remote_ref/gitlab.rs b/src/git/remote_ref/gitlab.rsindex ae67a890a..236641f04 100644--- a/src/git/remote_ref/gitlab.rs+++ b/src/git/remote_ref/gitlab.rs@@ -182,7 +182,7 @@ pub fn fetch_gitlab_project_urls(};// Fetch source project URLs (for fork push)- let (source_ssh, source_http) = fetch_project_urls(*source_project_id, repo_root)+ let (source_ssh, source_http) = fetch_project_urls(*source_project_id, "source", repo_root).with_context(|| {format!("Failed to fetch source project {} for MR !{}",@@ -191,7 +191,7 @@ pub fn fetch_gitlab_project_urls(})?;// Fetch target project URLs (where MR refs live)- let (target_ssh, target_http) = fetch_project_urls(*target_project_id, repo_root)+ let (target_ssh, target_http) = fetch_project_urls(*target_project_id, "target", repo_root).with_context(|| {format!("Failed to fetch target project {} for MR !{}",@@ -219,8 +219,16 @@ pub fn fetch_gitlab_project_urls(}/// Fetch project URLs from GitLab API.+///+/// `role` is the caller's word for which of the two projects this is ("source"+/// or "target"). It belongs in the CLI-failure message rather than in the+/// caller's `with_context`, because that context is inert there: `cli_api_error`+/// returns a `GitError`, and `format_command_error` renders only the first+/// `Diagnostic` in the chain. A numeric project ID alone can't tell a user which+/// of the two repos they're locked out of.fn fetch_project_urls(project_id: u64,+ role: &str,repo_root: &Path,) -> anyhow::Result<(Option<String>, Option<String>)> {let api_path = format!("projects/{}", project_id);@@ -235,10 +243,23 @@ fn fetch_project_urls(})?;if !output.status.success() {- bail!("Failed to fetch project {}", project_id);+ // Forward glab's own verdict, same as `fetch_mr_info` above — a bare+ // "Failed to fetch project 456" hides whether the call was a 401, a+ // 404, or a network failure.+ return Err(cli_api_error(+ ForgeKind::GitLab.ref_type(),+ format!("glab api failed for {} project {}", role, project_id),+ &output,+ ));}- let response: GlabProject = serde_json::from_slice(&output.stdout)?;+ let response: GlabProject = serde_json::from_slice(&output.stdout).with_context(|| {+ format!(+ "Failed to parse GitLab API response for project {}. \+ This may indicate a GitLab API change.",+ project_id+ )+ })?;Ok((response.ssh_url_to_repo, response.http_url_to_repo))}diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 3cd32fcb7..43c69e3e7 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -6736,6 +6736,212 @@ fn test_switch_mr_fork(#[from(repo_with_remote)] repo: TestRepo) {});}+/// A failing `glab api projects/<id>` surfaces glab's own verdict.+///+/// The MR call already forwards it (`fetch_mr_info`); the deferred project+/// call is the other half of the same fork path, and a bare "Failed to fetch+/// project 456" leaves the reader unable to tell a 401 from a 404.+#[rstest]+fn test_switch_mr_fork_project_fetch_error(#[from(repo_with_remote)] repo: TestRepo) {+ let bare_url = String::from_utf8_lossy(+ &repo+ .git_command()+ .args(["config", "remote.origin.url"])+ .run()+ .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",+ ]);++ let mr_response = r#"{+ "title": "Add feature fix for edge case",+ "author": {"username": "contributor"},+ "state": "opened",+ "draft": false,+ "source_branch": "feature-fix",+ "source_project_id": 456,+ "target_project_id": 123,+ "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/42"+ }"#;++ let mock_bin = repo.root_path().join("mock-bin");+ fs::create_dir_all(&mock_bin).unwrap();++ MockConfig::new("glab")+ .version("glab version 1.40.0 (mock)")+ .command(+ "api projects/:id/merge_requests/42",+ MockResponse::output(mr_response),+ )+ // The source (fork) project lookup is denied.+ .command(+ "api projects/456",+ MockResponse::exit(1).with_stderr("glab: 404 Project Not Found (HTTP 404)"),+ )+ .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:42"], None);+ configure_mock_cli_env(&mut cmd, &mock_bin);+ assert_cmd_snapshot!("switch_mr_fork_project_fetch_error", cmd);+ });+}++/// The other half of the role label: when the source lookup succeeds and the+/// *target* one is denied, the message names "target project 123".+///+/// Without this, changing the target call's `role` literal to `"source"` in+/// `fetch_gitlab_project_urls` leaves the suite green while telling the user+/// they're locked out of the fork when it's actually the upstream. (Swapping+/// *both* literals is already caught by the sibling above, whose snapshot+/// pins "source project 456".)+#[rstest]+fn test_switch_mr_fork_target_project_fetch_error(#[from(repo_with_remote)] repo: TestRepo) {+ let bare_url = String::from_utf8_lossy(+ &repo+ .git_command()+ .args(["config", "remote.origin.url"])+ .run()+ .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",+ ]);++ let mr_response = r#"{+ "title": "Add feature fix for edge case",+ "author": {"username": "contributor"},+ "state": "opened",+ "draft": false,+ "source_branch": "feature-fix",+ "source_project_id": 456,+ "target_project_id": 123,+ "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/42"+ }"#;++ 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"+ }"#;++ let mock_bin = repo.root_path().join("mock-bin");+ fs::create_dir_all(&mock_bin).unwrap();++ MockConfig::new("glab")+ .version("glab version 1.40.0 (mock)")+ .command(+ "api projects/:id/merge_requests/42",+ MockResponse::output(mr_response),+ )+ // The source (fork) project lookup succeeds ...+ .command(+ "api projects/456",+ MockResponse::output(source_project_response),+ )+ // ... and the target (upstream) one is denied.+ .command(+ "api projects/123",+ MockResponse::exit(1).with_stderr("glab: 403 Forbidden (HTTP 403)"),+ )+ .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:42"], None);+ configure_mock_cli_env(&mut cmd, &mock_bin);+ assert_cmd_snapshot!("switch_mr_fork_target_project_fetch_error", cmd);+ });+}++/// A `glab api projects/<id>` response that isn't the expected shape names the+/// project it came from, the same as the MR parse arm above it.+#[rstest]+fn test_switch_mr_fork_project_invalid_json(#[from(repo_with_remote)] repo: TestRepo) {+ let bare_url = String::from_utf8_lossy(+ &repo+ .git_command()+ .args(["config", "remote.origin.url"])+ .run()+ .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",+ ]);++ let mr_response = r#"{+ "title": "Add feature fix for edge case",+ "author": {"username": "contributor"},+ "state": "opened",+ "draft": false,+ "source_branch": "feature-fix",+ "source_project_id": 456,+ "target_project_id": 123,+ "web_url": "https://gitlab.com/owner/test-repo/-/merge_requests/42"+ }"#;++ let mock_bin = repo.root_path().join("mock-bin");+ fs::create_dir_all(&mock_bin).unwrap();++ MockConfig::new("glab")+ .version("glab version 1.40.0 (mock)")+ .command(+ "api projects/:id/merge_requests/42",+ MockResponse::output(mr_response),+ )+ // The source (fork) project lookup succeeds but answers with something+ // that isn't a project object.+ .command(+ "api projects/456",+ 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:42"], None);+ configure_mock_cli_env(&mut cmd, &mock_bin);+ assert_cmd_snapshot!("switch_mr_fork_project_invalid_json", 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) {diff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_fork_project_fetch_error.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_fork_project_fetch_error.snapnew file mode 100644index 000000000..f80b0f4f5--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_fork_project_fetch_error.snap@@ -0,0 +1,66 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "mr:42"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: file+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test User+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[36m◎[39m [36mFetching MR !42...[39m+[107m [0m [1mAdd feature fix for edge case[22m (!42)+[107m [0m by @contributor · opened · feature-fix · [90mhttps://gitlab.com/owner/test-repo/-/merge_requests/42[39m+[31m✗[39m [31mglab api failed for source project 456[39m+[107m [0m glab: 404 Project Not Found (HTTP 404)diff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_fork_project_invalid_json.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_fork_project_invalid_json.snapnew file mode 100644index 000000000..a228c82f7--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_fork_project_invalid_json.snap@@ -0,0 +1,67 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "mr:42"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: file+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test User+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[36m◎[39m [36mFetching MR !42...[39m+[107m [0m [1mAdd feature fix for edge case[22m (!42)+[107m [0m by @contributor · opened · feature-fix · [90mhttps://gitlab.com/owner/test-repo/-/merge_requests/42[39m+[31m✗[39m [31mFailed to fetch source project 456 for MR !42[39m+[107m [0m Failed to parse GitLab API response for project 456. This may indicate a GitLab API change.+[107m [0m expected ident at line 1 column 2diff --git a/tests/snapshots/integration__integration_tests__switch__switch_mr_fork_target_project_fetch_error.snap b/tests/snapshots/integration__integration_tests__switch__switch_mr_fork_target_project_fetch_error.snapnew file mode 100644index 000000000..3a61f385d--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_mr_fork_target_project_fetch_error.snap@@ -0,0 +1,66 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "mr:42"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: file+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test User+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[36m◎[39m [36mFetching MR !42...[39m+[107m [0m [1mAdd feature fix for edge case[22m (!42)+[107m [0m by @contributor · opened · feature-fix · [90mhttps://gitlab.com/owner/test-repo/-/merge_requests/42[39m+[31m✗[39m [31mglab api failed for target project 123[39m+[107m [0m glab: 403 Forbidden (HTTP 403)