Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(switch): set upstream when --base pr:N pairs with --create (#2498)
Worktrunk Bot90d5cfcb5f40
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 1c1efa0d2..8aee0aa85 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -139,6 +139,7 @@ fn resolve_fork_ref(method: CreationMethod::Regular {create_branch: false,base_branch: None,+ base_pr_upstream: None,},});}@@ -165,6 +166,7 @@ fn resolve_fork_ref(method: CreationMethod::Regular {create_branch: false,base_branch: None,+ base_pr_upstream: None,},});}@@ -268,6 +270,7 @@ fn resolve_same_repo_ref(method: CreationMethod::Regular {create_branch: false,base_branch: None,+ base_pr_upstream: None,},})}@@ -292,13 +295,20 @@ fn fetch_same_repo_branch(repo: &Repository, info: &RemoteRefInfo) -> anyhow::Re/// Resolve a `--base` value, expanding `pr:`/`mr:` shortcuts. Non-shortcut/// inputs go through [`Repository::resolve_worktree_name`] (handles `@`/`-`/`^`).///+/// Returns the resolved ref plus, when the user picked a `pr:`/`mr:` shortcut+/// against a same-repo PR/MR, the `(remote, branch)` pair the new branch+/// should be configured to track — see [`CreationMethod::Regular`].+////// When the bare name doesn't exist locally but a single remote has it,/// returns the remote-qualified form so the validation in/// [`resolve_switch_target`] doesn't reject `wt switch -c new --base/// remote-only-branch`. Git's rev-parse doesn't auto-expand `foo` to/// `refs/remotes/origin/foo`. The new branch's upstream is unset downstream/// to keep `git push` from targeting the base.-fn resolve_base_ref(repo: &Repository, base: &str) -> anyhow::Result<String> {+fn resolve_base_ref(+ repo: &Repository,+ base: &str,+) -> anyhow::Result<(String, Option<(String, String)>)> {if let Some(suffix) = base.strip_prefix("pr:")&& let Ok(number) = suffix.parse::<u32>(){@@ -316,21 +326,22 @@ fn resolve_base_ref(repo: &Repository, base: &str) -> anyhow::Result<String> {if !repo.ref_exists(&resolved)? {let remotes = repo.branch(&resolved).remotes()?;if remotes.len() == 1 {- return Ok(format!("{}/{}", remotes[0], resolved));+ return Ok((format!("{}/{}", remotes[0], resolved), None));}}- Ok(resolved)+ Ok((resolved, None))}/// Resolve `pr:{N}` / `mr:{N}` for `--base`. Same-repo returns the source-/// branch name; fork returns the PR head SHA so we don't create a tracking-/// branch for a ref the user hasn't asked to check out.+/// branch name plus the (remote, branch) the new branch should track; fork+/// returns the PR head SHA so we don't create a tracking branch for a ref+/// the user hasn't asked to check out.fn resolve_remote_ref_as_base(repo: &Repository,provider: &dyn RemoteRefProvider,number: u32,-) -> anyhow::Result<String> {+) -> anyhow::Result<(String, Option<(String, String)>)> {let ref_type = provider.ref_type();let symbol = ref_type.symbol();@@ -347,18 +358,23 @@ fn resolve_remote_ref_as_base(if !info.is_cross_repo {fetch_same_repo_branch(repo, &info)?;- return Ok(info.source_branch.clone());+ let remote = remote_ref::find_remote(repo, &info)?;+ return Ok((+ info.source_branch.clone(),+ Some((remote, info.source_branch.clone())),+ ));}let remote = remote_ref::find_remote(repo, &info)?;let display = ref_type.display(number);repo.run_command(&["fetch", "--", &remote, &provider.tracking_ref(number)]).with_context(|| cformat!("Failed to fetch <bold>{display}</> from {remote}"))?;- Ok(repo+ let sha = repo.run_command(&["rev-parse", "FETCH_HEAD"]).context("Failed to resolve FETCH_HEAD to a commit SHA")?.trim()- .to_string())+ .to_string();+ Ok((sha, None))}/// Resolve the switch target, handling pr:/mr: syntax and --create/--base flags.@@ -397,25 +413,25 @@ fn resolve_switch_target(}// Resolve and validate base (only when --create is set)- let resolved_base = if let Some(base_str) = base {+ let (resolved_base, base_pr_upstream) = if let Some(base_str) = base {if !create {eprintln!("{}",warning_message("--base flag is only used with --create, ignoring"));- None+ (None, None)} else {- let resolved = resolve_base_ref(repo, base_str)?;+ let (resolved, upstream) = resolve_base_ref(repo, base_str)?;if !repo.ref_exists(&resolved)? {return Err(GitError::ReferenceNotFound {reference: resolved,}.into());}- Some(resolved)+ (Some(resolved), upstream)}} else {- None+ (None, None)};// Validate --create constraints@@ -470,6 +486,7 @@ fn resolve_switch_target(method: CreationMethod::Regular {create_branch: create,base_branch,+ base_pr_upstream,},})}@@ -765,6 +782,7 @@ pub fn execute_switch(CreationMethod::Regular {create_branch,base_branch,+ base_pr_upstream,} => {// Check if local branch exists BEFORE git worktree add (for DWIM detection)let branch_handle = repo.branch(&branch);@@ -835,6 +853,21 @@ pub fn execute_switch(branch_handle.unset_upstream()?;}+ // `--base pr:N` / `--base mr:N` against a same-repo PR/MR: the+ // user asked for a custom local name pointing at an existing+ // remote branch — wire up tracking so `git push` from the new+ // worktree pushes back to the PR/MR's source branch instead+ // of failing with "no upstream branch". See issue #2497.+ if *create_branch+ && let Some((upstream_remote, upstream_branch)) = base_pr_upstream+ {+ repo.set_config(&format!("branch.{branch}.remote"), upstream_remote)?;+ repo.set_config(+ &format!("branch.{branch}.merge"),+ &format!("refs/heads/{upstream_branch}"),+ )?;+ }+// Report tracking info when the branch was auto-created from a remotelet from_remote = if !create_branch && !local_branch_existed {branch_handle.upstream()?diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rsindex edcb0ac15..d522bbf5c 100644--- a/src/commands/worktree/types.rs+++ b/src/commands/worktree/types.rs@@ -69,6 +69,15 @@ pub enum CreationMethod {create_branch: bool,/// Base branch for creation (resolved, validated to exist)base_branch: Option<String>,+ /// When `--base pr:N` / `--base mr:N` (same-repo) is paired with `--create`,+ /// the user's intent is "create a new branch tracking the PR/MR's source+ /// branch on the remote", so `git push` from the new worktree pushes back+ /// to that PR/MR. `git worktree add -b new <bare-name>` doesn't set up+ /// tracking on its own (only `<remote>/<branch>` triggers DWIM, and even+ /// then we'd unset it via the issue-#713 safety check), so we capture the+ /// (remote, branch) pair here and configure tracking explicitly after+ /// `git worktree add` succeeds. `None` for any other base resolution.+ base_pr_upstream: Option<(String, String)>,},/// Fork PR/MR: fetch from refs/pull/N/head or refs/merge-requests/N/head,/// create branch, configure pushRemote.diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 94053a59a..944a28951 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -2470,6 +2470,99 @@ fn test_switch_base_pr_same_repo(#[from(repo_with_remote)] mut repo: TestRepo) {});}+/// Reproduction for #2497: `wt switch --create X --base pr:N` should set the+/// new local branch's upstream to the PR's source branch on the remote, so+/// `git push` from the new worktree pushes back to the PR rather than failing+/// with "no upstream branch".+#[rstest]+fn test_switch_base_pr_sets_upstream(#[from(repo_with_remote)] mut repo: TestRepo) {+ let pr_source_branch = "feature-this-is-a-very-long-pr-source-branch-name";+ repo.add_worktree(pr_source_branch);+ repo.run_git(&["push", "origin", pr_source_branch]);++ 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://github.com/owner/test-repo.git",+ ]);+ repo.run_git(&[+ "config",+ &format!("url.{}.insteadOf", bare_url),+ "https://github.com/owner/test-repo.git",+ ]);++ let gh_response = format!(+ r#"{{+ "title": "Some PR title",+ "user": {{"login": "alice"}},+ "state": "open",+ "draft": false,+ "head": {{+ "ref": "{pr_source_branch}",+ "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/2648"+ }}"#+ );++ let mock_bin = setup_mock_gh_for_pr(&repo, Some(&gh_response));++ let mut cmd = repo.wt_command();+ cmd.args([+ "switch", "--create", "swa-65", "--base", "pr:2648", "--no-cd",+ ]);+ configure_mock_gh_env(&mut cmd, &mock_bin);+ let status = cmd.status().expect("wt switch should run");+ assert!(status.success(), "wt switch failed: {:?}", status);++ let remote = String::from_utf8_lossy(+ &repo+ .git_command()+ .args(["config", "--get", "branch.swa-65.remote"])+ .run()+ .unwrap()+ .stdout,+ )+ .trim()+ .to_string();+ let merge = String::from_utf8_lossy(+ &repo+ .git_command()+ .args(["config", "--get", "branch.swa-65.merge"])+ .run()+ .unwrap()+ .stdout,+ )+ .trim()+ .to_string();++ assert_eq!(+ remote, "origin",+ "branch.swa-65.remote should be set so `git push` knows where to push"+ );+ assert_eq!(+ merge,+ format!("refs/heads/{pr_source_branch}"),+ "branch.swa-65.merge should target the PR's source branch on the remote"+ );+}+/// `wt switch --create X --base pr:N` resolves a fork PR to its head commit/// SHA via refs/pull/N/head without creating a tracking branch.#[rstest]