Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: fetch branch for same-repo PRs to ensure refs are up-to-date (#742)
Maximilian Roos7966f095f9ae
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex e95fdb001..a3302e3b3 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -111,7 +111,30 @@ fn resolve_switch_target(},});} else {- // Same-repo PR: just use the branch name, regular switch+ // Same-repo PR: fetch the branch to ensure remote refs are up-to-date.+ // The branch exists on GitHub (per the API), but local refs may be stale.+ // Use find_remote_for_repo (not primary_remote) because the PR's repo might+ // be on a different remote (e.g., upstream vs origin in fork workflows).+ let remote = repo+ .find_remote_for_repo(&pr_info.base_owner, &pr_info.base_repo)+ .ok_or_else(|| {+ // Use PR's URL as reference - it has the correct host (github.com or enterprise)+ let suggested_url =+ fork_remote_url(&pr_info.base_owner, &pr_info.base_repo, &pr_info.url);+ GitError::NoRemoteForRepo {+ owner: pr_info.base_owner.clone(),+ repo: pr_info.base_repo.clone(),+ suggested_url,+ }+ })?;+ let branch = &pr_info.head_ref_name;++ let msg = cformat!("Fetching <bold>{branch}</> from {remote}...");+ crate::output::print(progress_message(msg))?;++ repo.run_command(&["fetch", &remote, branch])+ .with_context(|| format!("Failed to fetch branch '{}' from {}", branch, remote))?;+return Ok(ResolvedTarget {branch: pr_info.head_ref_name,method: CreationMethod::Regular {diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex b5981c6c8..540d148c1 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -1427,8 +1427,39 @@ fn test_switch_pr_create_conflict(repo: TestRepo) {/// Test same-repo PR checkout (base.repo == head.repo)#[rstest]fn test_switch_pr_same_repo(#[from(repo_with_remote)] mut repo: TestRepo) {- // Create a feature branch and push it+ // Create a feature branch and push it to the remoterepo.add_worktree("feature-auth");+ repo.run_git(&["push", "origin", "feature-auth"]);++ // 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 GitHub-style so find_remote_for_repo() can match owner/test-repo+ repo.run_git(&[+ "remote",+ "set-url",+ "origin",+ "https://github.com/owner/test-repo.git",+ ]);++ // Configure git to redirect github.com URLs to the local bare remote.+ // This is necessary because:+ // 1. origin must have a GitHub URL for find_remote_for_repo() to match owner/repo+ // 2. But we need git fetch to actually succeed using the local bare remote+ repo.run_git(&[+ "config",+ &format!("url.{}.insteadOf", bare_url),+ "https://github.com/owner/test-repo.git",+ ]);// gh api repos/{owner}/{repo}/pulls/{number} formatlet gh_response = r#"{@@ -1453,6 +1484,47 @@ fn test_switch_pr_same_repo(#[from(repo_with_remote)] mut repo: TestRepo) {});}+/// Test same-repo PR when origin points to a different repo (no remote for PR's repo)+///+/// User scenario:+/// 1. User has origin pointing to their fork (contributor/test-repo)+/// 2. PR #101 is a same-repo PR on the upstream (owner/test-repo)+/// 3. No remote exists for owner/test-repo -> error with hint to add upstream+#[rstest]+fn test_switch_pr_same_repo_no_remote(#[from(repo_with_remote)] repo: TestRepo) {+ // Set origin to point to a DIFFERENT repo than where the PR is+ repo.run_git(&[+ "remote",+ "set-url",+ "origin",+ "https://github.com/contributor/test-repo.git",+ ]);++ // gh api response says base.repo and head.repo are both owner/test-repo (same-repo PR)+ // but origin points to contributor/test-repo (different repo)+ // So find_remote_for_repo("owner", "test-repo") will fail+ let gh_response = r#"{+ "head": {+ "ref": "feature-auth",+ "repo": {"name": "test-repo", "owner": {"login": "owner"}}+ },+ "base": {+ "ref": "main",+ "repo": {"name": "test-repo", "owner": {"login": "owner"}}+ },+ "html_url": "https://github.com/owner/test-repo/pull/101"+ }"#;++ let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));++ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["pr:101"], None);+ configure_mock_gh_env(&mut cmd, &mock_bin);+ assert_cmd_snapshot!("switch_pr_same_repo_no_remote", cmd);+ });+}+/// Test fork PR checkout (base.repo != head.repo)#[rstest]fn test_switch_pr_fork(#[from(repo_with_remote)] repo: TestRepo) {diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_same_repo.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_same_repo.snapindex e46c89326..ec1d25675 100644--- a/tests/snapshots/integration__integration_tests__switch__switch_pr_same_repo.snap+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_same_repo.snap@@ -13,6 +13,7 @@ info: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@@ -26,6 +27,7 @@ info: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@@ -34,5 +36,6 @@ exit_code: 0----- stderr -----[36m◎[39m [36mFetching PR #101...[39m+[36m◎[39m [36mFetching [1mfeature-auth[22m from origin...[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_pr_same_repo_no_remote.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_same_repo_no_remote.snapnew file mode 100644index 000000000..834f8f183--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_same_repo_no_remote.snap@@ -0,0 +1,40 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "pr: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 PR #101...[39m+[31m✗[39m [31mNo remote found for [1mowner/test-repo[22m[39m+[2m↳[22m [2mAdd the remote: [90mgit remote add upstream https://github.com/owner/test-repo.git[39m[22m