Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix: use `gh repo set-default` for PR lookup on forks (#2004)

Worktrunk Bot656a790528b5
diff --git a/src/git/remote_ref/github.rs b/src/git/remote_ref/github.rs
index 22efc0922..2f176d4f4 100644
--- a/src/git/remote_ref/github.rs
+++ b/src/git/remote_ref/github.rs
@@ -2,6 +2,8 @@
//!
//! Implements `RemoteRefProvider` for GitHub Pull Requests using the `gh` CLI.
+use std::path::Path;
+
use anyhow::{Context, bail};
use serde::Deserialize;
@@ -10,6 +12,7 @@ use super::{
run_cli_api,
};
use crate::git::{self, RefType, Repository};
+use crate::shell_exec::Cmd;
/// GitHub Pull Request provider.
#[derive(Debug, Clone, Copy)]
@@ -74,26 +77,51 @@ struct GhOwner {
login: String,
}
+/// Query the default repo configured via `gh repo set-default`.
+///
+/// Returns `Some((owner, repo))` if a default is configured and parseable.
+/// Returns `None` if `gh` is not installed, not configured, or no default is set.
+fn gh_default_repo(repo_root: &Path) -> Option<(String, String)> {
+ let output = Cmd::new("gh")
+ .args(["repo", "set-default", "--view"])
+ .current_dir(repo_root)
+ .env("GH_PROMPT_DISABLED", "1")
+ .run()
+ .ok()
+ .filter(|o| o.status.success())?;
+
+ let slug = String::from_utf8_lossy(&output.stdout).trim().to_string();
+ let (owner, repo) = slug.split_once('/')?;
+ Some((owner.to_string(), repo.to_string()))
+}
+
/// Fetch PR information from GitHub using the `gh` CLI.
fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefInfo> {
let repo_root = repo.repo_path()?;
- // Extract owner/repo from primary remote URL. Uses raw URL (not
- // effective) because insteadOf may rewrite to a non-parseable path.
- // SSH aliases only affect the host, not the path — owner/repo is always real.
- let remote = repo.primary_remote()?;
- let url = repo
- .remote_url(&remote)
- .ok_or_else(|| anyhow::anyhow!("Remote '{}' has no URL", remote))?;
- let parsed = git::GitRemoteUrl::parse(&url)
- .ok_or_else(|| anyhow::anyhow!("Cannot parse remote URL: {}", url))?;
-
- let api_path = format!(
- "repos/{}/{}/pulls/{}",
- parsed.owner(),
- parsed.repo(),
- pr_number
- );
+ // Determine which owner/repo to query. Prefer gh's default repo
+ // (set via `gh repo set-default`) so fork workflows can target the
+ // parent repo without reconfiguring git remotes.
+ let (owner, repo_name, source) = if let Some((owner, name)) = gh_default_repo(repo_root) {
+ (owner, name, "gh default".to_string())
+ } else {
+ // Extract owner/repo from primary remote URL. Uses raw URL (not
+ // effective) because insteadOf may rewrite to a non-parseable path.
+ // SSH aliases only affect the host, not the path — owner/repo is always real.
+ let remote = repo.primary_remote()?;
+ let url = repo
+ .remote_url(&remote)
+ .ok_or_else(|| anyhow::anyhow!("Remote '{}' has no URL", remote))?;
+ let parsed = git::GitRemoteUrl::parse(&url)
+ .ok_or_else(|| anyhow::anyhow!("Cannot parse remote URL: {}", url))?;
+ (
+ parsed.owner().to_string(),
+ parsed.repo().to_string(),
+ remote,
+ )
+ };
+
+ let api_path = format!("repos/{}/{}/pulls/{}", owner, repo_name, pr_number);
// Only pass --hostname when explicitly configured (for GHE / self-hosted).
let hostname = repo
@@ -119,13 +147,16 @@ fn fetch_pr_info(pr_number: u32, repo: &Repository) -> anyhow::Result<RemoteRefI
if let Ok(error_response) = serde_json::from_slice::<GhApiErrorResponse>(&output.stdout) {
match error_response.status.as_str() {
"404" => {
- bail!(
- "PR #{pr_number} not found on {}/{} ({remote}). \
- If the PR is on a different repository, \
+ let hint = if source == "gh default" {
+ "Check that `gh repo set-default` points to the correct repository."
+ } else {
+ "If the PR is on a different repository, \
run `gh repo set-default` to set the default \
- or configure a different primary remote.",
- parsed.owner(),
- parsed.repo(),
+ or configure a different primary remote."
+ };
+ bail!(
+ "PR #{pr_number} not found on {owner}/{repo_name} ({source}). \
+ {hint}",
);
}
"401" => bail!("GitHub CLI not authenticated; run gh auth login"),
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index c9be8d2fb..87366c230 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -2057,6 +2057,115 @@ fn test_switch_pr_fork_no_upstream_remote(#[from(repo_with_remote)] repo: TestRe
});
}
+/// Test fork PR when origin points to fork but `gh repo set-default` is configured
+///
+/// User scenario:
+/// 1. User forked owner/test-repo to contributor/test-repo
+/// 2. User cloned their fork, so origin = contributor/test-repo
+/// 3. User added upstream remote pointing to owner/test-repo
+/// 4. User ran `gh repo set-default owner/test-repo`
+/// 5. User runs `wt switch pr:42` where the PR is on owner/test-repo
+/// 6. Worktrunk queries the gh default repo instead of origin → success
+#[rstest]
+fn test_switch_pr_fork_gh_default_repo(#[from(repo_with_remote)] repo: TestRepo) {
+ // Create a PR ref on the remote
+ repo.run_git(&["checkout", "-b", "pr-source"]);
+ fs::write(repo.root_path().join("pr-file.txt"), "PR content").unwrap();
+ repo.run_git(&["add", "pr-file.txt"]);
+ repo.run_git(&["commit", "-m", "PR commit"]);
+
+ let commit_sha = repo
+ .git_command()
+ .args(["rev-parse", "HEAD"])
+ .run()
+ .unwrap();
+ let sha = String::from_utf8_lossy(&commit_sha.stdout)
+ .trim()
+ .to_string();
+
+ repo.run_git(&["push", "origin", &format!("{}:refs/pull/42/head", sha)]);
+ repo.run_git(&["checkout", "main"]);
+
+ // Get the bare remote's actual URL before modifying remotes
+ let bare_url = String::from_utf8_lossy(
+ &repo
+ .git_command()
+ .args(["config", "remote.origin.url"])
+ .run()
+ .unwrap()
+ .stdout,
+ )
+ .trim()
+ .to_string();
+
+ // Set origin to the FORK (contributor's repo) — this is the bug scenario
+ repo.run_git(&[
+ "remote",
+ "set-url",
+ "origin",
+ "https://github.com/contributor/test-repo.git",
+ ]);
+
+ // Add upstream remote pointing to the parent repo
+ repo.run_git(&[
+ "remote",
+ "add",
+ "upstream",
+ "https://github.com/owner/test-repo.git",
+ ]);
+
+ // Redirect both GitHub URLs to the local bare remote for git operations
+ repo.run_git(&[
+ "config",
+ &format!("url.{}.insteadOf", bare_url),
+ "https://github.com/contributor/test-repo.git",
+ ]);
+ repo.run_git(&[
+ "config",
+ "--add",
+ &format!("url.{}.insteadOf", bare_url),
+ "https://github.com/owner/test-repo.git",
+ ]);
+
+ // Cross-repo PR: head is contributor's fork, base is owner's repo
+ let gh_response = r#"{
+ "title": "Add feature fix for edge case",
+ "user": {"login": "contributor"},
+ "state": "open",
+ "draft": false,
+ "head": {
+ "ref": "feature-fix",
+ "repo": {"name": "test-repo", "owner": {"login": "contributor"}}
+ },
+ "base": {
+ "ref": "main",
+ "repo": {"name": "test-repo", "owner": {"login": "owner"}}
+ },
+ "html_url": "https://github.com/owner/test-repo/pull/42"
+ }"#;
+
+ let mock_bin = repo.root_path().join("mock-bin");
+ fs::create_dir_all(&mock_bin).unwrap();
+ fs::write(mock_bin.join("pr_response.json"), gh_response).unwrap();
+
+ MockConfig::new("gh")
+ .version("gh version 2.0.0 (mock)")
+ .command(
+ "repo set-default --view",
+ MockResponse::output("owner/test-repo\n"),
+ )
+ .command("api", MockResponse::file("pr_response.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", &["pr:42"], None);
+ configure_mock_gh_env(&mut cmd, &mock_bin);
+ assert_cmd_snapshot!("switch_pr_fork_gh_default", cmd);
+ });
+}
+
/// Test error when PR is not found
#[rstest]
fn test_switch_pr_not_found(#[from(repo_with_remote)] repo: TestRepo) {
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_fork_gh_default.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_fork_gh_default.snap
new file mode 100644
index 000000000..27ff4c1f1
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_fork_gh_default.snap
@@ -0,0 +1,53 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "pr: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]"
+ NO_COLOR: ""
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Fetching PR #42...
+  Add feature fix for edge case (#42)
+  by @contributor · open · contributor:feature-fix · https://github.com/owner/test-repo/pull/42
+○ Push configured to fork: https://github.com/contributor/test-repo.git
+✓ Created branch feature-fix (tracking PR #42) and worktree @ _REPO_.feature-fix
+▲ Cannot change directory — shell integration not installed
+↳ To enable automatic cd, run wt config shell install