Skip to content

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

feat(switch): add pr:<number> syntax for switching to GitHub PRs (#673)

Maximilian Roos043ed4671cb4
diff --git a/.claude-plugin/skills/worktrunk/reference/switch.md b/.claude-plugin/skills/worktrunk/reference/switch.md
index fd3129081..81ec593c2 100644
--- a/.claude-plugin/skills/worktrunk/reference/switch.md
+++ b/.claude-plugin/skills/worktrunk/reference/switch.md
@@ -11,6 +11,7 @@ wt switch feature-auth # Switch to worktree
wt switch - # Previous worktree (like cd -)
wt switch --create new-feature # Create new branch and worktree
wt switch --create hotfix --base production
+wt switch pr:123 # Switch to PR #123's branch
```
## Creating a branch
@@ -42,13 +43,27 @@ wt switch --create temp --no-verify # Skip hooks
| `^` | Default branch (`main`/`master`) |
| `@` | Current branch/worktree |
| `-` | Previous worktree (like `cd -`) |
+| `pr:{N}` | GitHub PR #N's branch |
```bash
wt switch - # Back to previous
wt switch ^ # Default branch worktree
wt switch --create fix --base=@ # Branch from current HEAD
+wt switch pr:123 # PR #123's branch
```
+## GitHub pull requests (experimental)
+
+The `pr:<number>` syntax resolves the branch for a GitHub pull request. For same-repo PRs, it switches to the branch directly. For fork PRs, it fetches `refs/pull/N/head` and configures `pushRemote` to the fork URL.
+
+```bash
+wt switch pr:101 # Checkout PR #101
+```
+
+Requires `gh` CLI to be installed and authenticated. The `--create` flag cannot be used with `pr:` syntax since the branch already exists.
+
+**Fork PRs:** To push changes, use `git push HEAD:<branch-name>` where `<branch-name>` is the PR's head branch (e.g., `feature-fix`). The local branch is named `<owner>/<branch>` to avoid collisions, so plain `git push` won't work with default settings.
+
## When wt switch fails
- **Branch doesn't exist** — Use `--create`, or check `wt list --branches`
@@ -67,9 +82,10 @@ Usage: <b><span class=c>wt switch</span></b> <span class=c>[OPTIONS]</span> <spa
<b><span class=g>Arguments:</span></b>
<span class=c>&lt;BRANCH&gt;</span>
- Branch name
+ Branch name or shortcut
- Shortcuts: &#39;^&#39; (default branch), &#39;-&#39; (previous), &#39;@&#39; (current)
+ Shortcuts: &#39;^&#39; (default branch), &#39;-&#39; (previous), &#39;@&#39; (current),
+ &#39;pr:{N}&#39; (GitHub PR, experimental)
<span class=c>[EXECUTE_ARGS]...</span>
Additional arguments for --execute command (after --)
diff --git a/docs/content/switch.md b/docs/content/switch.md
index 743acd411..3fd20abbb 100644
--- a/docs/content/switch.md
+++ b/docs/content/switch.md
@@ -25,6 +25,7 @@ wt switch feature-auth # Switch to worktree
wt switch - # Previous worktree (like cd -)
wt switch --create new-feature # Create new branch and worktree
wt switch --create hotfix --base production
+wt switch pr:123 # Switch to PR #123's branch
```
## Creating a branch
@@ -56,13 +57,27 @@ wt switch --create temp --no-verify # Skip hooks
| `^` | Default branch (`main`/`master`) |
| `@` | Current branch/worktree |
| `-` | Previous worktree (like `cd -`) |
+| `pr:{N}` | GitHub PR #N's branch |
```bash
wt switch - # Back to previous
wt switch ^ # Default branch worktree
wt switch --create fix --base=@ # Branch from current HEAD
+wt switch pr:123 # PR #123's branch
```
+## GitHub pull requests (experimental)
+
+The `pr:<number>` syntax resolves the branch for a GitHub pull request. For same-repo PRs, it switches to the branch directly. For fork PRs, it fetches `refs/pull/N/head` and configures `pushRemote` to the fork URL.
+
+```bash
+wt switch pr:101 # Checkout PR #101
+```
+
+Requires `gh` CLI to be installed and authenticated. The `--create` flag cannot be used with `pr:` syntax since the branch already exists.
+
+**Fork PRs:** To push changes, use `git push HEAD:<branch-name>` where `<branch-name>` is the PR's head branch (e.g., `feature-fix`). The local branch is named `<owner>/<branch>` to avoid collisions, so plain `git push` won't work with default settings.
+
## When wt switch fails
- **Branch doesn't exist** — Use `--create`, or check `wt list --branches`
@@ -89,9 +104,10 @@ Usage: <b><span class=c>wt switch</span></b> <span class=c>[OPTIONS]</span> <spa
<b><span class=g>Arguments:</span></b>
<span class=c>&lt;BRANCH&gt;</span>
- Branch name
+ Branch name or shortcut
- Shortcuts: &#39;^&#39; (default branch), &#39;-&#39; (previous), &#39;@&#39; (current)
+ Shortcuts: &#39;^&#39; (default branch), &#39;-&#39; (previous), &#39;@&#39; (current),
+ &#39;pr:{N}&#39; (GitHub PR, experimental)
<span class=c>[EXECUTE_ARGS]...</span>
Additional arguments for --execute command (after --)
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 8f584d9b4..852148aa4 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -256,6 +256,7 @@ wt switch feature-auth # Switch to worktree
wt switch - # Previous worktree (like cd -)
wt switch --create new-feature # Create new branch and worktree
wt switch --create hotfix --base production
+wt switch pr:123 # Switch to PR #123's branch
```
## Creating a branch
@@ -287,13 +288,27 @@ wt switch --create temp --no-verify # Skip hooks
| `^` | Default branch (`main`/`master`) |
| `@` | Current branch/worktree |
| `-` | Previous worktree (like `cd -`) |
+| `pr:{N}` | GitHub PR #N's branch |
```console
wt switch - # Back to previous
wt switch ^ # Default branch worktree
wt switch --create fix --base=@ # Branch from current HEAD
+wt switch pr:123 # PR #123's branch
```
+## GitHub pull requests (experimental)
+
+The `pr:<number>` syntax resolves the branch for a GitHub pull request. For same-repo PRs, it switches to the branch directly. For fork PRs, it fetches `refs/pull/N/head` and configures `pushRemote` to the fork URL.
+
+```console
+wt switch pr:101 # Checkout PR #101
+```
+
+Requires `gh` CLI to be installed and authenticated. The `--create` flag cannot be used with `pr:` syntax since the branch already exists.
+
+**Fork PRs:** To push changes, use `git push HEAD:<branch-name>` where `<branch-name>` is the PR's head branch (e.g., `feature-fix`). The local branch is named `<owner>/<branch>` to avoid collisions, so plain `git push` won't work with default settings.
+
## When wt switch fails
- **Branch doesn't exist** — Use `--create`, or check `wt list --branches`
@@ -311,9 +326,9 @@ To change which branch a worktree is on, use `git switch` inside that worktree.
"#
)]
Switch {
- /// Branch name
+ /// Branch name or shortcut
///
- /// Shortcuts: '^' (default branch), '-' (previous), '@' (current)
+ /// Shortcuts: '^' (default branch), '-' (previous), '@' (current), 'pr:{N}' (GitHub PR, experimental)
#[arg(add = crate::completion::worktree_branch_completer())]
branch: String,
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index fc40b04f9..ffba03e55 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -120,6 +120,45 @@ fn generate_backup_path(path: &std::path::Path, suffix: &str) -> anyhow::Result<
}
}
+/// Compute the backup path for clobber operations.
+///
+/// Returns `Ok(None)` if path doesn't exist.
+/// Returns `Ok(Some(backup_path))` if clobber is true and path exists.
+/// Returns `Err(GitError::WorktreePathExists)` if clobber is false and path exists.
+fn compute_clobber_backup(
+ path: &Path,
+ branch: &str,
+ clobber: bool,
+ create: bool,
+) -> anyhow::Result<Option<PathBuf>> {
+ if !path.exists() {
+ return Ok(None);
+ }
+
+ if clobber {
+ let timestamp = worktrunk::utils::get_now() as i64;
+ let datetime =
+ chrono::DateTime::from_timestamp(timestamp, 0).unwrap_or_else(chrono::Utc::now);
+ let suffix = datetime.format("%Y%m%d-%H%M%S").to_string();
+ let backup_path = generate_backup_path(path, &suffix)?;
+
+ if backup_path.exists() {
+ anyhow::bail!(
+ "Backup path already exists: {}",
+ worktrunk::path::format_path_for_display(&backup_path)
+ );
+ }
+ Ok(Some(backup_path))
+ } else {
+ Err(GitError::WorktreePathExists {
+ branch: branch.to_string(),
+ path: path.to_path_buf(),
+ create,
+ }
+ .into())
+ }
+}
+
/// Context for worktree resolution - determines which checks are performed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ResolutionContext {
@@ -348,6 +387,24 @@ pub struct SwitchBranchInfo {
pub expected_path: Option<PathBuf>,
}
+/// How the worktree will be created.
+#[derive(Debug)]
+pub enum CreationMethod {
+ /// Use `git worktree add` - handles existing branch, DWIM from remote, or -b for new
+ Regular {
+ /// True if using `-b` to create a new branch (--create flag)
+ create_branch: bool,
+ /// Base branch for creation (resolved, validated to exist)
+ base_branch: Option<String>,
+ },
+ /// Fork PR: fetch from refs/pull/N/head, create branch, configure pushRemote
+ ForkPr {
+ pr_number: u32,
+ fork_push_url: String,
+ pr_url: String,
+ },
+}
+
/// Validated plan for a switch operation.
///
/// Created by `plan_switch()`, consumed by `execute_switch()`.
@@ -368,10 +425,8 @@ pub enum SwitchPlan {
Create {
branch: String,
worktree_path: PathBuf,
- /// True if using `-b` to create a new branch (--create flag)
- create_branch: bool,
- /// Base branch for creation (resolved, validated to exist)
- base_branch: Option<String>,
+ /// How to create the worktree
+ method: CreationMethod,
/// If path exists and --clobber, this is the backup path to move it to
clobber_backup: Option<PathBuf>,
/// Branch to record as "previous" for `wt switch -`
@@ -391,8 +446,7 @@ impl SwitchPlan {
/// Get the branch name for this plan.
pub fn branch(&self) -> &str {
match self {
- SwitchPlan::Existing { branch, .. } => branch,
- SwitchPlan::Create { branch, .. } => branch,
+ SwitchPlan::Existing { branch, .. } | SwitchPlan::Create { branch, .. } => branch,
}
}
@@ -470,48 +524,136 @@ pub enum RemoveResult {
},
}
-/// Validate and plan a switch operation.
-///
-/// This performs all validation upfront, returning a `SwitchPlan` that can be
-/// executed later. Call this BEFORE approval prompts to ensure users aren't
-/// asked to approve hooks for operations that will fail.
+/// Result of resolving the switch target.
+struct ResolvedTarget {
+ /// The resolved branch name
+ branch: String,
+ /// How to create the worktree
+ method: CreationMethod,
+}
+
+/// Resolve the switch target, handling pr: syntax and --create/--base flags.
///
-/// Warnings (remote branch shadow, --base without --create, invalid default branch)
-/// are printed during planning since they're informational, not blocking.
-pub fn plan_switch(
+/// This is the first phase of planning: determine what branch we're switching to
+/// and how we'll create the worktree. May involve network calls for PR resolution.
+fn resolve_switch_target(
repo: &Repository,
branch: &str,
create: bool,
base: Option<&str>,
- clobber: bool,
- config: &WorktrunkConfig,
-) -> anyhow::Result<SwitchPlan> {
- // Get the actual current branch BEFORE switching.
- // This is what we'll record as "previous" in history for `wt switch -` support.
- let new_previous = repo.current_worktree().branch().ok().flatten();
+) -> anyhow::Result<ResolvedTarget> {
+ use worktrunk::git::pr_ref::{fetch_pr_info, fork_remote_url, local_branch_name};
+
+ // Handle pr:<number> syntax
+ if let Some(pr_number) = worktrunk::git::pr_ref::parse_pr_ref(branch) {
+ // --create and --base are invalid with pr: syntax
+ if create {
+ return Err(GitError::PrCreateConflict { pr_number }.into());
+ }
+ if base.is_some() {
+ return Err(GitError::PrBaseConflict { pr_number }.into());
+ }
+
+ // Fetch PR info (network call)
+ let remote = repo.primary_remote()?;
+ crate::output::print(progress_message(cformat!(
+ "Fetching PR #{pr_number} from <bold>{remote}</>..."
+ )))?;
- // Resolve special branch names ("@" for current, "-" for previous)
+ let repo_root = repo.repo_path()?;
+ let pr_info = fetch_pr_info(pr_number, &repo_root)?;
+
+ if pr_info.is_cross_repository {
+ // Fork PR: use owner/branch naming, will need fetch + config
+ let local_branch = local_branch_name(&pr_info);
+
+ // Check if branch already exists and is tracking this PR
+ // If so, we can reuse it without re-fetching or re-configuring
+ if let Some(tracks_this_pr) =
+ worktrunk::git::pr_ref::branch_tracks_pr(&repo_root, &local_branch, pr_number)
+ {
+ if tracks_this_pr {
+ // Branch exists and tracks this PR - just create worktree
+ crate::output::print(info_message(cformat!(
+ "Branch <bold>{local_branch}</> already configured for PR #{pr_number}"
+ )))?;
+ return Ok(ResolvedTarget {
+ branch: local_branch,
+ method: CreationMethod::Regular {
+ create_branch: false,
+ base_branch: None,
+ },
+ });
+ } else {
+ // Branch exists but tracks something else
+ return Err(GitError::BranchTracksDifferentPr {
+ branch: local_branch,
+ pr_number,
+ }
+ .into());
+ }
+ }
+
+ // Branch doesn't exist - need full fork PR setup
+ let remote_url = repo.primary_remote_url().unwrap_or_default();
+ let fork_push_url =
+ fork_remote_url(&pr_info.head_owner, &pr_info.head_repo, &remote_url);
+
+ return Ok(ResolvedTarget {
+ branch: local_branch,
+ method: CreationMethod::ForkPr {
+ pr_number,
+ fork_push_url,
+ pr_url: pr_info.url,
+ },
+ });
+ } else {
+ // Same-repo PR: just use the branch name, regular switch
+ return Ok(ResolvedTarget {
+ branch: pr_info.head_ref_name,
+ method: CreationMethod::Regular {
+ create_branch: false,
+ base_branch: None,
+ },
+ });
+ }
+ }
+
+ // Regular branch switch
let resolved_branch = repo
.resolve_worktree_name(branch)
.context("Failed to resolve branch name")?;
- // Resolve base if provided
+ // Resolve and validate base
let resolved_base = if let Some(base_str) = base {
- Some(repo.resolve_worktree_name(base_str)?)
+ let resolved = repo.resolve_worktree_name(base_str)?;
+ if !create {
+ crate::output::print(warning_message(
+ "--base flag is only used with --create, ignoring",
+ ))?;
+ None
+ } else if !repo.ref_exists(&resolved)? {
+ return Err(GitError::InvalidReference {
+ reference: resolved,
+ }
+ .into());
+ } else {
+ Some(resolved)
+ }
} else {
None
};
- // Check for conflicting conditions
- if create && repo.local_branch_exists(&resolved_branch)? {
- return Err(GitError::BranchAlreadyExists {
- branch: resolved_branch.clone(),
+ // Validate --create constraints
+ if create {
+ if repo.local_branch_exists(&resolved_branch)? {
+ return Err(GitError::BranchAlreadyExists {
+ branch: resolved_branch,
+ }
+ .into());
}
- .into());
- }
- // Warn if --create would shadow a remote branch
- if create {
+ // Warn if --create would shadow a remote branch
let remotes = repo.remotes_with_branch(&resolved_branch)?;
if !remotes.is_empty() {
let remote_ref = format!("{}/{}", remotes[0], resolved_branch);
@@ -526,124 +668,211 @@ pub fn plan_switch(
}
}
- // Check if base flag was provided without create flag
- if resolved_base.is_some() && !create {
- crate::output::print(warning_message(
- "--base flag is only used with --create, ignoring",
- ))?;
- }
+ // Compute base branch for creation
+ let base_branch = if create {
+ resolved_base.or_else(|| {
+ // Check for invalid configured default branch
+ if let Some(configured) = repo.invalid_default_branch_config() {
+ let _ = crate::output::print(warning_message(cformat!(
+ "Configured default branch <bold>{configured}</> does not exist locally"
+ )));
+ let _ = crate::output::print(hint_message(cformat!(
+ "To reset, run <bright-black>wt config state default-branch clear</>"
+ )));
+ }
+ repo.resolve_target_branch(None)
+ .ok()
+ .filter(|b| repo.local_branch_exists(b).unwrap_or(false))
+ })
+ } else {
+ None
+ };
- // Compute expected worktree path for this branch
- let expected_path = compute_worktree_path(repo, &resolved_branch, config)?;
+ Ok(ResolvedTarget {
+ branch: resolved_branch,
+ method: CreationMethod::Regular {
+ create_branch: create,
+ base_branch,
+ },
+ })
+}
- // Branch-first lookup: check if branch has a worktree anywhere
- match repo.worktree_for_branch(&resolved_branch)? {
- Some(existing_path) if existing_path.exists() => {
- return Ok(SwitchPlan::Existing {
- path: canonicalize(&existing_path).unwrap_or(existing_path),
- branch: resolved_branch,
- expected_path,
- new_previous,
- });
- }
- Some(_) => {
- return Err(GitError::WorktreeMissing {
- branch: resolved_branch.clone(),
- }
- .into());
+/// Check if branch already has a worktree.
+///
+/// Returns `Some(Existing)` if worktree exists and is valid.
+/// Returns error if worktree record exists but directory is missing.
+/// Returns `None` if no worktree exists for this branch.
+fn check_existing_worktree(
+ repo: &Repository,
+ branch: &str,
+ expected_path: &Path,
+ new_previous: Option<String>,
+) -> anyhow::Result<Option<SwitchPlan>> {
+ match repo.worktree_for_branch(branch)? {
+ Some(existing_path) if existing_path.exists() => Ok(Some(SwitchPlan::Existing {
+ path: canonicalize(&existing_path).unwrap_or(existing_path),
+ branch: branch.to_string(),
+ expected_path: expected_path.to_path_buf(),
+ new_previous,
+ })),
+ Some(_) => Err(GitError::WorktreeMissing {
+ branch: branch.to_string(),
}
- None => {}
+ .into()),
+ None => Ok(None),
}
+}
- // No worktree for branch - validate branch exists before proceeding
- if !create && !repo.branch_exists(&resolved_branch)? {
+/// Validate that we can create a worktree at the given path.
+///
+/// Checks:
+/// - Path not occupied by another worktree
+/// - For regular switches (not --create), branch must exist
+/// - Handles --clobber for stale directories
+///
+/// Note: Fork PR branch existence is checked earlier in resolve_switch_target()
+/// where we can also check if it's tracking the correct PR.
+fn validate_worktree_creation(
+ repo: &Repository,
+ branch: &str,
+ path: &Path,
+ clobber: bool,
+ method: &CreationMethod,
+) -> anyhow::Result<Option<PathBuf>> {
+ // For regular switches without --create, validate branch exists
+ if let CreationMethod::Regular {
+ create_branch: false,
+ ..
+ } = method
+ && !repo.branch_exists(branch)?
+ {
return Err(GitError::InvalidReference {
- reference: resolved_branch.clone(),
+ reference: branch.to_string(),
}
.into());
}
- // Check if expected path is occupied by a different branch's worktree
- if let Some((existing_path, path_branch)) = repo.worktree_at_path(&expected_path)? {
+ // Check if path is occupied by another worktree
+ if let Some((existing_path, occupant)) = repo.worktree_at_path(path)? {
if !existing_path.exists() {
- let branch = path_branch.unwrap_or_else(|| resolved_branch.clone());
- return Err(GitError::WorktreeMissing { branch }.into());
+ let occupant_branch = occupant.unwrap_or_else(|| branch.to_string());
+ return Err(GitError::WorktreeMissing {
+ branch: occupant_branch,
+ }
+ .into());
}
return Err(GitError::WorktreePathOccupied {
- branch: resolved_branch.clone(),
- path: expected_path,
- occupant: path_branch,
+ branch: branch.to_string(),
+ path: path.to_path_buf(),
+ occupant,
}
.into());
}
- // Determine clobber backup path if needed
- let clobber_backup = if expected_path.exists() {
- if clobber {
- let timestamp = worktrunk::utils::get_now() as i64;
- let datetime =
- chrono::DateTime::from_timestamp(timestamp, 0).unwrap_or_else(chrono::Utc::now);
- let suffix = datetime.format("%Y%m%d-%H%M%S").to_string();
- let backup_path = generate_backup_path(&expected_path, &suffix)?;
-
- if backup_path.exists() {
- anyhow::bail!(
- "Backup path already exists: {}",
- worktrunk::path::format_path_for_display(&backup_path)
- );
- }
- Some(backup_path)
- } else {
- return Err(GitError::WorktreePathExists {
- branch: resolved_branch.clone(),
- path: expected_path,
- create,
- }
- .into());
+ // Handle clobber for stale directories
+ let is_create = matches!(
+ method,
+ CreationMethod::Regular {
+ create_branch: true,
+ ..
}
- } else {
- None
- };
+ );
+ compute_clobber_backup(path, branch, clobber, is_create)
+}
+
+/// Set up a local branch for a fork PR.
+///
+/// Creates the branch, configures tracking, and creates the worktree.
+/// Returns an error if any step fails - caller is responsible for cleanup.
+fn setup_fork_pr_branch(
+ repo: &Repository,
+ branch: &str,
+ remote: &str,
+ pr_ref: &str,
+ fork_push_url: &str,
+ worktree_path: &Path,
+ pr_number: u32,
+) -> anyhow::Result<()> {
+ // Create local branch from FETCH_HEAD
+ repo.run_command(&["branch", branch, "FETCH_HEAD"])
+ .with_context(|| {
+ format!(
+ "Failed to create local branch '{}' from PR #{}",
+ branch, pr_number
+ )
+ })?;
+
+ // Configure branch tracking for pull and push
+ let branch_remote_key = format!("branch.{}.remote", branch);
+ let branch_merge_key = format!("branch.{}.merge", branch);
+ let branch_push_remote_key = format!("branch.{}.pushRemote", branch);
+ let merge_ref = format!("refs/{}", pr_ref);
+
+ repo.run_command(&["config", &branch_remote_key, remote])
+ .with_context(|| format!("Failed to configure branch.{}.remote", branch))?;
+ repo.run_command(&["config", &branch_merge_key, &merge_ref])
+ .with_context(|| format!("Failed to configure branch.{}.merge", branch))?;
+ repo.run_command(&["config", &branch_push_remote_key, fork_push_url])
+ .with_context(|| format!("Failed to configure branch.{}.pushRemote", branch))?;
+
+ // Create worktree
+ let worktree_path_str = worktree_path.to_string_lossy();
+ repo.run_command(&["worktree", "add", worktree_path_str.as_ref(), branch])
+ .map_err(|e| GitError::WorktreeCreationFailed {
+ branch: branch.to_string(),
+ base_branch: None,
+ error: e.to_string(),
+ })?;
+
+ Ok(())
+}
- // Check for invalid configured default branch when creating without explicit --base
- if create
- && resolved_base.is_none()
- && let Some(configured) = repo.invalid_default_branch_config()
+/// Validate and plan a switch operation.
+///
+/// This performs all validation upfront, returning a `SwitchPlan` that can be
+/// executed later. Call this BEFORE approval prompts to ensure users aren't
+/// asked to approve hooks for operations that will fail.
+///
+/// Warnings (remote branch shadow, --base without --create, invalid default branch)
+/// are printed during planning since they're informational, not blocking.
+pub fn plan_switch(
+ repo: &Repository,
+ branch: &str,
+ create: bool,
+ base: Option<&str>,
+ clobber: bool,
+ config: &WorktrunkConfig,
+) -> anyhow::Result<SwitchPlan> {
+ // Record current branch for `wt switch -` support
+ let new_previous = repo.current_worktree().branch().ok().flatten();
+
+ // Phase 1: Resolve target (handles pr:, validates --create/--base, may do network)
+ let target = resolve_switch_target(repo, branch, create, base)?;
+
+ // Phase 2: Compute expected path
+ let expected_path = compute_worktree_path(repo, &target.branch, config)?;
+
+ // Phase 3: Check if worktree already exists for this branch
+ if let Some(existing) =
+ check_existing_worktree(repo, &target.branch, &expected_path, new_previous.clone())?
{
- crate::output::print(warning_message(cformat!(
- "Configured default branch <bold>{configured}</> does not exist locally"
- )))?;
- crate::output::print(hint_message(cformat!(
- "To reset, run <bright-black>wt config state default-branch clear</>"
- )))?;
+ return Ok(existing);
}
- // Resolve base ref for creation (accepts any commit-ish: branch, tag, SHA, HEAD)
- let base_branch = if create {
- match resolved_base {
- Some(ref b) => {
- if !repo.ref_exists(b)? {
- return Err(GitError::InvalidReference {
- reference: b.clone(),
- }
- .into());
- }
- Some(b.clone())
- }
- None => repo
- .resolve_target_branch(None)
- .ok()
- .filter(|b| repo.local_branch_exists(b).unwrap_or(false)),
- }
- } else {
- None
- };
+ // Phase 4: Validate we can create at this path
+ let clobber_backup = validate_worktree_creation(
+ repo,
+ &target.branch,
+ &expected_path,
+ clobber,
+ &target.method,
+ )?;
+ // Phase 5: Return the plan
Ok(SwitchPlan::Create {
- branch: resolved_branch,
+ branch: target.branch,
worktree_path: expected_path,
- create_branch: create,
- base_branch,
+ method: target.method,
clobber_backup,
new_previous,
})
@@ -702,58 +931,106 @@ pub fn execute_switch(
SwitchPlan::Create {
branch,
worktree_path,
- create_branch,
- base_branch,
+ method,
clobber_backup,
new_previous,
} => {
- // Handle --clobber backup if needed
- if let Some(backup_path) = clobber_backup {
+ // Handle --clobber backup if needed (shared for all creation methods)
+ if let Some(backup_path) = &clobber_backup {
let path_display = worktrunk::path::format_path_for_display(&worktree_path);
- let backup_display = worktrunk::path::format_path_for_display(&backup_path);
+ let backup_display = worktrunk::path::format_path_for_display(backup_path);
crate::output::print(warning_message(cformat!(
"Moving <bold>{path_display}</> to <bold>{backup_display}</> (--clobber)"
)))?;
- std::fs::rename(&worktree_path, &backup_path).with_context(|| {
+ std::fs::rename(&worktree_path, backup_path).with_context(|| {
format!("Failed to move {path_display} to {backup_display}")
})?;
}
- // Check if local branch exists BEFORE git worktree add (for DWIM detection).
- // Only relevant when not using --create (which explicitly creates the branch).
- let local_branch_existed =
- !create_branch && repo.local_branch_exists(&branch).unwrap_or(false);
+ // Execute based on creation method
+ let (created_branch, base_branch, from_remote) = match &method {
+ CreationMethod::Regular {
+ create_branch,
+ base_branch,
+ } => {
+ // Check if local branch exists BEFORE git worktree add (for DWIM detection)
+ let local_branch_existed =
+ !create_branch && repo.local_branch_exists(&branch).unwrap_or(false);
+
+ // Build git worktree add command
+ let worktree_path_str = worktree_path.to_string_lossy();
+ let mut args = vec!["worktree", "add", worktree_path_str.as_ref()];
+
+ if *create_branch {
+ args.push("-b");
+ args.push(&branch);
+ if let Some(base) = base_branch {
+ args.push(base);
+ }
+ } else {
+ args.push(&branch);
+ }
- // Build git worktree add command
- let worktree_path_str = worktree_path.to_string_lossy();
- let mut args = vec!["worktree", "add", worktree_path_str.as_ref()];
+ if let Err(e) = repo.run_command(&args) {
+ return Err(GitError::WorktreeCreationFailed {
+ branch: branch.clone(),
+ base_branch: base_branch.clone(),
+ error: e.to_string(),
+ }
+ .into());
+ }
- if create_branch {
- args.push("-b");
- args.push(&branch);
- if let Some(ref base) = base_branch {
- args.push(base);
- }
- } else {
- args.push(&branch);
- }
+ // Report tracking info only if git's DWIM created the branch from a remote
+ let from_remote = if !create_branch && !local_branch_existed {
+ repo.upstream_branch(&branch)?
+ } else {
+ None
+ };
- // Create worktree
- if let Err(e) = repo.run_command(&args) {
- return Err(GitError::WorktreeCreationFailed {
- branch: branch.clone(),
- base_branch: base_branch.clone(),
- error: e.to_string(),
+ (*create_branch, base_branch.clone(), from_remote)
}
- .into());
- }
- // Report tracking info only if git's DWIM created the branch from a remote
- let from_remote = if !create_branch && !local_branch_existed {
- repo.upstream_branch(&branch)?
- } else {
- None
+ CreationMethod::ForkPr {
+ pr_number,
+ fork_push_url,
+ pr_url: _,
+ } => {
+ let pr_ref = format!("pull/{}/head", pr_number);
+ let remote = repo.primary_remote()?;
+
+ // Fetch the PR head (progress already shown during planning)
+ repo.run_command(&["fetch", &remote, &pr_ref])
+ .with_context(|| {
+ format!("Failed to fetch PR #{} from {}", pr_number, remote)
+ })?;
+
+ // Execute branch creation and configuration with cleanup on failure.
+ // If any step after branch creation fails, we must delete the branch
+ // to avoid leaving orphaned state that blocks future attempts.
+ let setup_result = setup_fork_pr_branch(
+ repo,
+ &branch,
+ &remote,
+ &pr_ref,
+ fork_push_url,
+ &worktree_path,
+ *pr_number,
+ );
+
+ if let Err(e) = setup_result {
+ // Cleanup: try to delete the branch if it was created
+ // (ignore errors - branch may not exist if creation failed)
+ let _ = repo.run_command(&["branch", "-D", &branch]);
+ return Err(e);
+ }
+
+ crate::output::print(info_message(cformat!(
+ "Push configured to fork: <bright-black>{fork_push_url}</>"
+ )))?;
+
+ (false, None, Some(format!("PR #{}", pr_number)))
+ }
};
// Compute base worktree path for hooks and result
@@ -774,17 +1051,28 @@ pub fn execute_switch(
force,
);
- let extra_vars: Vec<(&str, &str)> = [
- base_branch.as_ref().map(|b| ("base", b.as_str())),
- base_worktree_path
- .as_ref()
- .map(|p| ("base_worktree_path", p.as_str())),
- ]
- .into_iter()
- .flatten()
- .collect();
-
- ctx.execute_post_create_commands(&extra_vars)?;
+ match &method {
+ CreationMethod::Regular { base_branch, .. } => {
+ let extra_vars: Vec<(&str, &str)> = [
+ base_branch.as_ref().map(|b| ("base", b.as_str())),
+ base_worktree_path
+ .as_ref()
+ .map(|p| ("base_worktree_path", p.as_str())),
+ ]
+ .into_iter()
+ .flatten()
+ .collect();
+ ctx.execute_post_create_commands(&extra_vars)?;
+ }
+ CreationMethod::ForkPr {
+ pr_number, pr_url, ..
+ } => {
+ let pr_num_str = pr_number.to_string();
+ let extra_vars: Vec<(&str, &str)> =
+ vec![("pr_number", &pr_num_str), ("pr_url", pr_url)];
+ ctx.execute_post_create_commands(&extra_vars)?;
+ }
+ }
}
// Record successful switch in history
@@ -793,7 +1081,7 @@ pub fn execute_switch(
Ok((
SwitchResult::Created {
path: worktree_path,
- created_branch: create_branch,
+ created_branch,
base_branch,
base_worktree_path,
from_remote,
diff --git a/src/git/error.rs b/src/git/error.rs
index 70f63a08b..bb5547d56 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -148,6 +148,19 @@ pub enum GitError {
WorktreeNotFound {
branch: String,
},
+ /// --create flag used with pr: syntax (conflict - PR branch already exists)
+ PrCreateConflict {
+ pr_number: u32,
+ },
+ /// --base flag used with pr: syntax (conflict - PR base is predetermined)
+ PrBaseConflict {
+ pr_number: u32,
+ },
+ /// Branch exists but is tracking a different PR
+ BranchTracksDifferentPr {
+ branch: String,
+ pr_number: u32,
+ },
Other {
message: String,
},
@@ -575,6 +588,41 @@ impl std::fmt::Display for GitError {
)
}
+ GitError::PrCreateConflict { pr_number } => {
+ write!(
+ f,
+ "{}\n{}",
+ error_message(cformat!(
+ "Cannot use <bold>--create</> with <bold>pr:{pr_number}</>"
+ )),
+ hint_message("PRs already have a branch; remove --create")
+ )
+ }
+
+ GitError::PrBaseConflict { pr_number } => {
+ write!(
+ f,
+ "{}\n{}",
+ error_message(cformat!(
+ "Cannot use <bold>--base</> with <bold>pr:{pr_number}</>"
+ )),
+ hint_message("PRs already have a base; remove --base")
+ )
+ }
+
+ GitError::BranchTracksDifferentPr { branch, pr_number } => {
+ write!(
+ f,
+ "{}\n{}",
+ error_message(cformat!(
+ "Branch <bold>{branch}</> exists but is not tracking PR #{pr_number}"
+ )),
+ hint_message(cformat!(
+ "Delete the branch first: <bright-black>git branch -D {branch}</>"
+ ))
+ )
+ }
+
GitError::Other { message } => {
write!(f, "{}", error_message(message))
}
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 8f361ba66..a1298327d 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -6,6 +6,7 @@ use std::path::PathBuf;
mod diff;
mod error;
mod parse;
+pub mod pr_ref;
mod repository;
mod url;
diff --git a/src/git/pr_ref.rs b/src/git/pr_ref.rs
new file mode 100644
index 000000000..5f3ef965a
--- /dev/null
+++ b/src/git/pr_ref.rs
@@ -0,0 +1,547 @@
+//! PR reference resolution (`pr:<number>` syntax).
+//!
+//! This module resolves PR numbers to branches, enabling `wt switch pr:101` to
+//! check out the branch associated with a pull request.
+//!
+//! # Syntax
+//!
+//! The `pr:<number>` prefix is unambiguous because colons are invalid in git
+//! branch names (git rejects them as "not a valid branch name").
+//!
+//! ```text
+//! wt switch pr:101 # Switch to branch for PR #101
+//! wt switch pr:101 --yes # Skip approval prompts
+//! ```
+//!
+//! **Invalid usage:**
+//!
+//! ```text
+//! wt switch --create pr:101 # Error: PR branch already exists
+//! ```
+//!
+//! The `--create` flag is incompatible with `pr:` because the branch must
+//! already exist (it's the PR's head branch).
+//!
+//! # Resolution Flow
+//!
+//! ```text
+//! pr:101
+//! │
+//! ▼
+//! ┌─────────────────────────────────────────────────────────┐
+//! │ gh pr view 101 --json headRefName,headRepository, │
+//! │ headRepositoryOwner,isCrossRepository,url │
+//! └─────────────────────────────────────────────────────────┘
+//! │
+//! ├─── isCrossRepository == false ───▶ Same-repo PR
+//! │ │
+//! │ └─▶ Branch exists in origin, use directly
+//! │
+//! └─── isCrossRepository == true ───▶ Fork PR
+//! │
+//! └─▶ Set up push to fork URL
+//! ```
+//!
+//! Push permissions are not checked upfront — if the user lacks permission
+//! (doesn't own fork, maintainer edits disabled), push will fail with a clear
+//! error. This avoids complex permission detection logic.
+//!
+//! # Same-Repo PRs
+//!
+//! When `isCrossRepository` is `false`, the PR's branch exists in `origin`:
+//!
+//! 1. Resolve `headRefName` (e.g., `"feature-auth"`)
+//! 2. Check if worktree exists for that branch → switch to it
+//! 3. Otherwise, create worktree for the branch (DWIM from remote)
+//! 4. Pushing works normally: `git push origin feature-auth`
+//!
+//! This is equivalent to `wt switch feature-auth` — the `pr:` syntax is just
+//! a convenience for looking up the branch name.
+//!
+//! # Fork PRs
+//!
+//! When `isCrossRepository` is `true`, the branch exists in a fork, not `origin`.
+//!
+//! ## The Problem
+//!
+//! GitHub's `refs/pull/<N>/head` refs are **read-only**. You cannot push to them:
+//!
+//! ```text
+//! $ git push origin HEAD:refs/pull/101/head
+//! error: cannot lock ref 'refs/pull/101/head': unable to resolve reference
+//! ```
+//!
+//! To update a fork PR, you must push to the **fork's branch**, not the PR ref.
+//!
+//! ## Push Strategy (No Remote Required)
+//!
+//! Git's `branch.<name>.pushRemote` config accepts a URL directly, not just a
+//! named remote. This means we can set up push tracking without adding remotes:
+//!
+//! ```text
+//! branch.contributor/feature.remote = origin
+//! branch.contributor/feature.merge = refs/pull/101/head
+//! branch.contributor/feature.pushRemote = [email protected]:contributor/repo.git
+//! ```
+//!
+//! This configuration gives us:
+//! - `git pull` fetches from origin's PR ref (stays up to date with PR)
+//! - `git push` pushes to the fork URL (updates the PR)
+//! - No stray remotes cluttering `git remote -v`
+//!
+//! ## Checkout Flow (Fork PRs)
+//!
+//! ```text
+//! 1. Get PR metadata from gh
+//! │
+//! ▼
+//! 2. Fetch PR head from origin
+//! git fetch origin pull/101/head
+//! │
+//! ▼
+//! 3. Create local branch from FETCH_HEAD
+//! git branch <local-branch> FETCH_HEAD
+//! │
+//! ▼
+//! 4. Configure branch tracking
+//! git config branch.<local-branch>.remote origin
+//! git config branch.<local-branch>.merge refs/pull/101/head
+//! git config branch.<local-branch>.pushRemote <fork-url>
+//! │
+//! ▼
+//! 5. Create worktree for the branch
+//! ```
+//!
+//! ## Local Branch Naming
+//!
+//! To avoid collisions when multiple PRs have the same branch name (common with
+//! branches like `fix`, `update`, etc.), we use a naming scheme:
+//!
+//! - **Same-repo PR**: Use `headRefName` directly (e.g., `feature-auth`)
+//! - **Fork PR**: Use `<owner>/<headRefName>` (e.g., `contributor/feature-auth`)
+//!
+//! The `<owner>/` prefix ensures uniqueness and makes it clear which fork the
+//! branch comes from.
+//!
+//! ## Push Behavior
+//!
+//! After checkout, `git push` sends to the fork URL:
+//!
+//! ```text
+//! $ git push
+//! # Pushes to [email protected]:contributor/repo.git
+//! # PR automatically updates on GitHub
+//! ```
+//!
+//! No named remote is added — the URL is used directly via `pushRemote`.
+//!
+//! # Error Handling
+//!
+//! ## PR Not Found
+//!
+//! ```text
+//! ✗ PR #101 not found
+//! ↳ Run gh repo set-default --view to check which repo is being queried
+//! ```
+//!
+//! This often happens when `origin` points to a fork but `gh` hasn't been
+//! configured to look at the upstream repo. Fix with `gh repo set-default`.
+//!
+//! ## gh Not Authenticated
+//!
+//! ```text
+//! ✗ GitHub CLI not authenticated
+//! ↳ Run gh auth login to authenticate
+//! ```
+//!
+//! ## gh Not Installed
+//!
+//! ```text
+//! ✗ GitHub CLI (gh) required for pr: syntax
+//! ↳ Install from https://cli.github.com/
+//! ```
+//!
+//! ## --create Conflict
+//!
+//! ```text
+//! ✗ Cannot use --create with pr: syntax
+//! ↳ The PR's branch already exists; remove --create
+//! ```
+//!
+//! # Edge Cases
+//!
+//! ## Branch Name Collisions
+//!
+//! If user already has a local branch named `contributor/feature`:
+//!
+//! - Check if it tracks the same PR ref → reuse it
+//! - Otherwise → error with suggestion to delete the branch or use a different name
+//!
+//! ## Worktree Already Exists
+//!
+//! If worktree already exists for the resolved branch:
+//!
+//! - Switch to it (normal `wt switch` behavior)
+//! - Don't re-fetch or re-configure
+//!
+//! ## Draft PRs
+//!
+//! Draft PRs are checkable like regular PRs. The `isDraft` field could be
+//! shown in output but doesn't affect behavior.
+//!
+//! ## Renamed Branches
+//!
+//! If the PR's head branch was renamed after PR creation, `headRefName`
+//! reflects the current name. We always use the current name.
+//!
+//! # Platform Support
+//!
+//! This feature is GitHub-specific. GitLab has similar concepts:
+//!
+//! - `glab mr view <number>` with `source_branch` field
+//! - Different permission model (no exact "maintainer edits" equivalent)
+//!
+//! Future work could add `mr:<number>` syntax for GitLab, following the same
+//! patterns but using `glab` CLI.
+//!
+//! # Implementation Notes
+//!
+//! ## Repository Resolution
+//!
+//! `gh pr view` needs to know which GitHub repo to query. For fork workflows
+//! where `origin` points to a fork, `gh` needs to know to look at the parent
+//! repo for PRs.
+//!
+//! The `gh` CLI handles this via `gh repo set-default`:
+//!
+//! ```text
+//! # Stores in git config: remote.origin.gh-resolved = base
+//! gh repo set-default owner/upstream-repo
+//!
+//! # View current setting
+//! gh repo set-default --view
+//! ```
+//!
+//! If `gh-resolved` is not set, `gh` may prompt interactively or use heuristics
+//! (checking if the repo is a fork and using its parent).
+//!
+//! **Diagnostics:** `wt config show` should display the resolved repo so users
+//! understand which repo PR lookups will query.
+//!
+//! ## Required gh Fields
+//!
+//! ```bash
+//! gh pr view <number> --json \
+//! headRefName,headRepository,headRepositoryOwner,isCrossRepository,url
+//! ```
+//!
+//! ## Remote URL Construction
+//!
+//! For SSH remotes:
+//! ```text
+//! [email protected]:<owner>/<repo>.git
+//! ```
+//!
+//! For HTTPS remotes:
+//! ```text
+//! https://github.com/<owner>/<repo>.git
+//! ```
+//!
+//! We match the protocol of the existing `origin` remote to be consistent
+//! with the user's authentication setup.
+//!
+//! ## Caching
+//!
+//! PR metadata is not cached — we always fetch fresh to ensure we have
+//! current state (PR might have been closed, branch might have been pushed).
+//!
+//! # Testing Strategy
+//!
+//! ## Unit Tests
+//!
+//! - PR number parsing from `pr:<number>` syntax
+//! - Local branch name generation
+//! - URL construction matching origin protocol
+//!
+//! ## Integration Tests (with mock gh)
+//!
+//! - Same-repo PR checkout
+//! - Fork PR checkout
+//! - Existing worktree reuse
+//! - Error cases: PR not found, gh not authenticated
+//!
+//! ## Manual Testing
+//!
+//! - Fork PR push/pull cycle
+//! - Interaction with `wt merge`
+//! - Multiple fork PRs with same branch name
+
+use anyhow::{Context, bail};
+use serde::Deserialize;
+
+use crate::shell_exec::Cmd;
+
+/// Information about a PR retrieved from GitHub.
+#[derive(Debug, Clone)]
+pub struct PrInfo {
+ /// The PR number.
+ pub number: u32,
+ /// The branch name in the head repository.
+ pub head_ref_name: String,
+ /// The owner of the head repository (fork owner for cross-repo PRs).
+ pub head_owner: String,
+ /// The name of the head repository.
+ pub head_repo: String,
+ /// Whether this is a cross-repository (fork) PR.
+ pub is_cross_repository: bool,
+ /// The PR's web URL.
+ pub url: String,
+}
+
+/// Raw JSON response from `gh pr view`.
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct GhPrResponse {
+ head_ref_name: String,
+ head_repository: GhRepository,
+ head_repository_owner: GhOwner,
+ is_cross_repository: bool,
+ url: String,
+}
+
+#[derive(Debug, Deserialize)]
+struct GhRepository {
+ name: String,
+}
+
+#[derive(Debug, Deserialize)]
+struct GhOwner {
+ login: String,
+}
+
+/// Parse a `pr:<number>` reference, returning the PR number if valid.
+///
+/// Returns `None` if the input doesn't match the `pr:<number>` pattern.
+pub fn parse_pr_ref(input: &str) -> Option<u32> {
+ let suffix = input.strip_prefix("pr:")?;
+ suffix.parse().ok()
+}
+
+/// Fetch PR information from GitHub using the `gh` CLI.
+///
+/// # Errors
+///
+/// Returns an error if:
+/// - `gh` is not installed or not authenticated
+/// - The PR doesn't exist
+/// - The JSON response is malformed
+pub fn fetch_pr_info(pr_number: u32, repo_root: &std::path::Path) -> anyhow::Result<PrInfo> {
+ let output = match Cmd::new("gh")
+ .args([
+ "pr",
+ "view",
+ &pr_number.to_string(),
+ "--json",
+ "headRefName,headRepository,headRepositoryOwner,isCrossRepository,url",
+ ])
+ .current_dir(repo_root)
+ .env("GH_PROMPT_DISABLED", "1")
+ .run()
+ {
+ Ok(output) => output,
+ Err(e) => {
+ // Check if gh is not installed (OS error for command not found)
+ let error_str = e.to_string();
+ if error_str.contains("No such file")
+ || error_str.contains("not found")
+ || error_str.contains("cannot find")
+ {
+ bail!("GitHub CLI (gh) not installed; install from https://cli.github.com/");
+ }
+ return Err(anyhow::Error::from(e).context("Failed to run gh pr view"));
+ }
+ };
+
+ if !output.status.success() {
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ let stderr_lower = stderr.to_lowercase();
+
+ // PR not found (various phrasings across gh versions)
+ if stderr_lower.contains("could not resolve")
+ || stderr_lower.contains("not found")
+ || stderr_lower.contains("no pull request")
+ {
+ 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")
+ {
+ bail!("GitHub CLI not authenticated; run gh auth login");
+ }
+
+ // Rate limiting
+ if stderr_lower.contains("rate limit") || stderr_lower.contains("api rate") {
+ 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");
+ }
+
+ bail!("gh pr view failed: {}", stderr.trim());
+ }
+
+ let response: GhPrResponse = serde_json::from_slice(&output.stdout).with_context(|| {
+ format!(
+ "Failed to parse gh pr view JSON for PR #{}. \
+ This may indicate a gh version incompatibility or GitHub API change.",
+ pr_number
+ )
+ })?;
+
+ // Validate required fields are not empty
+ if response.head_ref_name.is_empty() {
+ bail!(
+ "PR #{} has empty branch name; the PR may be in an invalid state",
+ pr_number
+ );
+ }
+
+ Ok(PrInfo {
+ number: pr_number,
+ head_ref_name: response.head_ref_name,
+ head_owner: response.head_repository_owner.login,
+ head_repo: response.head_repository.name,
+ is_cross_repository: response.is_cross_repository,
+ url: response.url,
+ })
+}
+
+/// Generate the local branch name for a PR.
+///
+/// - Same-repo PRs: use `headRefName` directly
+/// - Fork PRs: use `<owner>/<headRefName>` to avoid collisions
+pub fn local_branch_name(pr: &PrInfo) -> String {
+ if pr.is_cross_repository {
+ format!("{}/{}", pr.head_owner, pr.head_ref_name)
+ } else {
+ pr.head_ref_name.clone()
+ }
+}
+
+/// Construct the remote URL for a fork, matching the protocol of the primary remote.
+///
+/// If remote uses SSH (`[email protected]:`), returns SSH URL.
+/// If remote uses HTTPS (`https://github.com/`), returns HTTPS URL.
+pub fn fork_remote_url(owner: &str, repo: &str, remote_url: &str) -> String {
+ if remote_url.starts_with("git@") || remote_url.contains("ssh://") {
+ format!("[email protected]:{}/{}.git", owner, repo)
+ } else {
+ format!("https://github.com/{}/{}.git", owner, repo)
+ }
+}
+
+/// Check if a branch is tracking a specific PR.
+///
+/// Returns `Some(true)` if the branch is configured to track `refs/pull/<pr_number>/head`.
+/// Returns `Some(false)` if the branch exists but tracks something else.
+/// Returns `None` if the branch doesn't exist.
+pub fn branch_tracks_pr(repo_root: &std::path::Path, branch: &str, pr_number: u32) -> Option<bool> {
+ use crate::shell_exec::Cmd;
+
+ let config_key = format!("branch.{}.merge", branch);
+ let output = Cmd::new("git")
+ .args(["config", "--get", &config_key])
+ .current_dir(repo_root)
+ .run()
+ .ok()?;
+
+ if !output.status.success() {
+ // Config key doesn't exist - branch might not track anything
+ // Check if branch exists at all
+ let branch_exists = Cmd::new("git")
+ .args([
+ "show-ref",
+ "--verify",
+ "--quiet",
+ &format!("refs/heads/{}", branch),
+ ])
+ .current_dir(repo_root)
+ .run()
+ .map(|o| o.status.success())
+ .unwrap_or(false);
+
+ return if branch_exists { Some(false) } else { None };
+ }
+
+ let merge_ref = String::from_utf8_lossy(&output.stdout).trim().to_string();
+ let expected_ref = format!("refs/pull/{}/head", pr_number);
+
+ Some(merge_ref == expected_ref)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_parse_pr_ref() {
+ assert_eq!(parse_pr_ref("pr:101"), Some(101));
+ assert_eq!(parse_pr_ref("pr:1"), Some(1));
+ assert_eq!(parse_pr_ref("pr:99999"), Some(99999));
+
+ // Invalid cases
+ assert_eq!(parse_pr_ref("pr:"), None);
+ assert_eq!(parse_pr_ref("pr:abc"), None);
+ assert_eq!(parse_pr_ref("pr:-1"), None);
+ assert_eq!(parse_pr_ref("PR:101"), None); // case-sensitive
+ assert_eq!(parse_pr_ref("feature-branch"), None);
+ assert_eq!(parse_pr_ref("101"), None);
+ }
+
+ #[test]
+ fn test_local_branch_name_same_repo() {
+ let pr = PrInfo {
+ number: 101,
+ head_ref_name: "feature-auth".to_string(),
+ head_owner: "owner".to_string(),
+ head_repo: "repo".to_string(),
+ is_cross_repository: false,
+ url: "https://github.com/owner/repo/pull/101".to_string(),
+ };
+ assert_eq!(local_branch_name(&pr), "feature-auth");
+ }
+
+ #[test]
+ fn test_local_branch_name_fork() {
+ let pr = PrInfo {
+ number: 101,
+ head_ref_name: "feature-auth".to_string(),
+ head_owner: "contributor".to_string(),
+ head_repo: "repo".to_string(),
+ is_cross_repository: true,
+ url: "https://github.com/owner/repo/pull/101".to_string(),
+ };
+ assert_eq!(local_branch_name(&pr), "contributor/feature-auth");
+ }
+
+ #[test]
+ fn test_fork_remote_url_ssh() {
+ let url = fork_remote_url("contributor", "repo", "[email protected]:owner/repo.git");
+ assert_eq!(url, "[email protected]:contributor/repo.git");
+ }
+
+ #[test]
+ fn test_fork_remote_url_https() {
+ let url = fork_remote_url("contributor", "repo", "https://github.com/owner/repo.git");
+ assert_eq!(url, "https://github.com/contributor/repo.git");
+ }
+}
diff --git a/tests/common/mock_commands.rs b/tests/common/mock_commands.rs
index b8a51baee..aacaa8125 100644
--- a/tests/common/mock_commands.rs
+++ b/tests/common/mock_commands.rs
@@ -53,6 +53,7 @@ pub struct MockConfig {
pub struct MockResponse {
file: Option<String>,
output: Option<String>,
+ stderr: Option<String>,
exit_code: i32,
}
@@ -62,15 +63,27 @@ impl MockResponse {
Self {
file: Some(path.to_string()),
output: None,
+ stderr: None,
exit_code: 0,
}
}
- /// Respond with literal output.
+ /// Respond with literal output (stdout).
pub fn output(text: &str) -> Self {
Self {
file: None,
output: Some(text.to_string()),
+ stderr: None,
+ exit_code: 0,
+ }
+ }
+
+ /// Respond with stderr output.
+ pub fn stderr(text: &str) -> Self {
+ Self {
+ file: None,
+ output: None,
+ stderr: Some(text.to_string()),
exit_code: 0,
}
}
@@ -80,6 +93,7 @@ impl MockResponse {
Self {
file: None,
output: None,
+ stderr: None,
exit_code: code,
}
}
@@ -90,6 +104,12 @@ impl MockResponse {
self
}
+ /// Add stderr output (chainable).
+ pub fn with_stderr(mut self, text: &str) -> Self {
+ self.stderr = Some(text.to_string());
+ self
+ }
+
fn to_json(&self) -> serde_json::Value {
let mut obj = serde_json::Map::new();
if let Some(f) = &self.file {
@@ -98,7 +118,12 @@ impl MockResponse {
if let Some(o) = &self.output {
obj.insert("output".to_string(), json!(o));
}
- if self.exit_code != 0 || (self.file.is_none() && self.output.is_none()) {
+ if let Some(e) = &self.stderr {
+ obj.insert("stderr".to_string(), json!(e));
+ }
+ if self.exit_code != 0
+ || (self.file.is_none() && self.output.is_none() && self.stderr.is_none())
+ {
obj.insert("exit_code".to_string(), json!(self.exit_code));
}
serde_json::Value::Object(obj)
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index e61bacddb..600ae0d7b 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -1255,6 +1255,11 @@ impl TestRepo {
&self.root
}
+ /// Get the path to the bare remote repository, if created.
+ pub fn remote_path(&self) -> Option<&Path> {
+ self.remote.as_deref()
+ }
+
/// Get the project identifier for test configs.
///
/// Returns the repository directory name. This works because the standard
diff --git a/tests/helpers/mock-stub/src/main.rs b/tests/helpers/mock-stub/src/main.rs
index 4a63265d8..eb6e034dc 100644
--- a/tests/helpers/mock-stub/src/main.rs
+++ b/tests/helpers/mock-stub/src/main.rs
@@ -46,6 +46,7 @@ struct Config {
struct CommandResponse {
file: Option<String>,
output: Option<String>,
+ stderr: Option<String>,
#[serde(default)]
exit_code: i32,
}
@@ -93,6 +94,7 @@ fn main() {
let default_response = CommandResponse {
file: None,
output: None,
+ stderr: None,
exit_code: 1,
};
let response = args
@@ -118,5 +120,10 @@ fn main() {
io::stdout().flush().unwrap();
}
+ if let Some(stderr_output) = &response.stderr {
+ eprint!("{}", stderr_output);
+ io::stderr().flush().unwrap();
+ }
+
exit(response.exit_code);
}
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index b67175392..a7144a34c 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -5,6 +5,7 @@ use crate::common::{
};
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
+use std::fs;
use std::path::Path;
use tempfile::TempDir;
@@ -272,6 +273,28 @@ fn test_switch_error_missing_worktree_directory(mut repo: TestRepo) {
snapshot_switch("switch_error_missing_directory", &repo, &["missing-wt"]);
}
+/// Test error when target path is registered to a worktree whose directory is missing.
+///
+/// Scenario: branch "feature/collision" has a worktree at "repo.feature-collision",
+/// but the directory was deleted. Trying to create "feature-collision" (which maps
+/// to the same path) should error about the missing worktree, not try to overwrite.
+#[rstest]
+fn test_switch_error_path_occupied_by_missing_worktree(mut repo: TestRepo) {
+ // Create a worktree for "feature/collision" -> path "repo.feature-collision"
+ let wt_path = repo.add_worktree("feature/collision");
+
+ // Delete the worktree directory (but leave it registered in git)
+ std::fs::remove_dir_all(&wt_path).unwrap();
+
+ // Try to create "feature-collision" which maps to the same path
+ // Should fail because the path is registered to a missing worktree
+ snapshot_switch(
+ "switch_error_path_occupied_missing",
+ &repo,
+ &["--create", "feature-collision"],
+ );
+}
+
#[rstest]
fn test_switch_error_path_occupied(repo: TestRepo) {
// Calculate where the worktree would be created
@@ -1235,3 +1258,428 @@ fn test_switch_create_no_hint_with_custom_worktree_path(repo: TestRepo) {
"Hint should be suppressed when user has custom worktree-path config"
);
}
+
+// ============================================================================
+// PR Syntax Tests (pr:<number>)
+// ============================================================================
+
+use crate::common::mock_commands::{MockConfig, MockResponse, copy_mock_binary};
+
+/// Helper to set up mock gh for PR tests with custom PR response.
+fn setup_mock_gh_for_pr(repo: &TestRepo, gh_response: Option<&str>) -> std::path::PathBuf {
+ let mock_bin = repo.root_path().join("mock-bin");
+ fs::create_dir_all(&mock_bin).unwrap();
+
+ // Copy mock-stub binary as "gh"
+ copy_mock_binary(&mock_bin, "gh");
+
+ // Write PR response file if provided
+ if let Some(response) = gh_response {
+ fs::write(mock_bin.join("pr_response.json"), response).unwrap();
+
+ MockConfig::new("gh")
+ .version("gh version 2.0.0 (mock)")
+ .command("pr", MockResponse::file("pr_response.json"))
+ .command("_default", MockResponse::exit(1))
+ .write(&mock_bin);
+ }
+
+ mock_bin
+}
+
+/// Configure command environment for mock gh.
+fn configure_mock_gh_env(cmd: &mut std::process::Command, mock_bin: &Path) {
+ // Tell mock-stub where to find config files
+ cmd.env("MOCK_CONFIG_DIR", mock_bin);
+
+ // Build PATH with mock binary first
+ let (path_var_name, current_path) = std::env::vars_os()
+ .find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
+ .map(|(k, v)| (k.to_string_lossy().into_owned(), Some(v)))
+ .unwrap_or(("PATH".to_string(), None));
+
+ let mut paths: Vec<std::path::PathBuf> = current_path
+ .as_deref()
+ .map(|p| std::env::split_paths(p).collect())
+ .unwrap_or_default();
+ paths.insert(0, mock_bin.to_path_buf());
+ let new_path = std::env::join_paths(&paths)
+ .unwrap()
+ .to_string_lossy()
+ .into_owned();
+
+ cmd.env(path_var_name, new_path);
+}
+
+/// Test that --create flag conflicts with pr: syntax
+#[rstest]
+fn test_switch_pr_create_conflict(repo: TestRepo) {
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["--create", "pr:101"], None);
+ assert_cmd_snapshot!("switch_pr_create_conflict", cmd);
+ });
+}
+
+/// Test same-repo PR checkout (isCrossRepository: false)
+#[rstest]
+fn test_switch_pr_same_repo(#[from(repo_with_remote)] mut repo: TestRepo) {
+ // Create a feature branch and push it
+ repo.add_worktree("feature-auth");
+
+ let gh_response = r#"{
+ "headRefName": "feature-auth",
+ "headRepository": {"name": "test-repo"},
+ "headRepositoryOwner": {"login": "owner"},
+ "isCrossRepository": false,
+ "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", cmd);
+ });
+}
+
+/// Test fork PR checkout (isCrossRepository: true)
+#[rstest]
+fn test_switch_pr_fork(#[from(repo_with_remote)] repo: TestRepo) {
+ // Create a PR ref on the remote that can be fetched
+ // First, create a commit that represents the PR head
+ 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"]);
+
+ // Get the commit SHA and push to remote as refs/pull/42/head
+ let commit_sha = repo
+ .git_command()
+ .args(["rev-parse", "HEAD"])
+ .output()
+ .unwrap();
+ let sha = String::from_utf8_lossy(&commit_sha.stdout)
+ .trim()
+ .to_string();
+
+ // Push the ref to the bare remote
+ repo.run_git(&["push", "origin", &format!("{}:refs/pull/42/head", sha)]);
+
+ // Go back to main
+ repo.run_git(&["checkout", "main"]);
+
+ let gh_response = r#"{
+ "headRefName": "feature-fix",
+ "headRepository": {"name": "test-repo"},
+ "headRepositoryOwner": {"login": "contributor"},
+ "isCrossRepository": true,
+ "url": "https://github.com/owner/test-repo/pull/42"
+ }"#;
+
+ 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:42"], None);
+ configure_mock_gh_env(&mut cmd, &mock_bin);
+ assert_cmd_snapshot!("switch_pr_fork", cmd);
+ });
+}
+
+/// Test error when PR is not found
+#[rstest]
+fn test_switch_pr_not_found(#[from(repo_with_remote)] repo: TestRepo) {
+ let mock_bin = repo.root_path().join("mock-bin");
+ fs::create_dir_all(&mock_bin).unwrap();
+
+ // Copy mock-stub binary as "gh"
+ copy_mock_binary(&mock_bin, "gh");
+
+ // Configure gh to return error for PR not found (errors go to stderr)
+ MockConfig::new("gh")
+ .version("gh version 2.0.0 (mock)")
+ .command(
+ "pr",
+ MockResponse::stderr("Could not resolve to a PullRequest with the number 9999")
+ .with_exit_code(1),
+ )
+ .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:9999"], None);
+ configure_mock_gh_env(&mut cmd, &mock_bin);
+ assert_cmd_snapshot!("switch_pr_not_found", cmd);
+ });
+}
+
+/// Test that --base flag conflicts with pr: syntax
+#[rstest]
+fn test_switch_pr_base_conflict(repo: TestRepo) {
+ let settings = setup_snapshot_settings(&repo);
+ settings.bind(|| {
+ let mut cmd = make_snapshot_cmd(&repo, "switch", &["--base", "main", "pr:101"], None);
+ assert_cmd_snapshot!("switch_pr_base_conflict", cmd);
+ });
+}
+
+/// Test fork PR where branch already exists and tracks same PR (should reuse)
+#[rstest]
+fn test_switch_pr_fork_existing_same_pr(#[from(repo_with_remote)] repo: TestRepo) {
+ // First, manually create the branch with correct tracking config
+ let branch_name = "contributor/feature-fix";
+ repo.run_git(&["branch", branch_name, "main"]);
+ repo.run_git(&[
+ "config",
+ &format!("branch.{}.remote", branch_name),
+ "origin",
+ ]);
+ repo.run_git(&[
+ "config",
+ &format!("branch.{}.merge", branch_name),
+ "refs/pull/42/head",
+ ]);
+
+ let gh_response = r#"{
+ "headRefName": "feature-fix",
+ "headRepository": {"name": "test-repo"},
+ "headRepositoryOwner": {"login": "contributor"},
+ "isCrossRepository": true,
+ "url": "https://github.com/owner/test-repo/pull/42"
+ }"#;
+
+ 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:42"], None);
+ configure_mock_gh_env(&mut cmd, &mock_bin);
+ assert_cmd_snapshot!("switch_pr_fork_existing_same_pr", cmd);
+ });
+}
+
+/// Test fork PR where branch already exists but tracks different PR (should error)
+#[rstest]
+fn test_switch_pr_fork_existing_different_pr(#[from(repo_with_remote)] repo: TestRepo) {
+ // Create the branch with tracking config for a DIFFERENT PR
+ let branch_name = "contributor/feature-fix";
+ repo.run_git(&["branch", branch_name, "main"]);
+ repo.run_git(&[
+ "config",
+ &format!("branch.{}.remote", branch_name),
+ "origin",
+ ]);
+ repo.run_git(&[
+ "config",
+ &format!("branch.{}.merge", branch_name),
+ "refs/pull/99/head", // Different PR!
+ ]);
+
+ let gh_response = r#"{
+ "headRefName": "feature-fix",
+ "headRepository": {"name": "test-repo"},
+ "headRepositoryOwner": {"login": "contributor"},
+ "isCrossRepository": true,
+ "url": "https://github.com/owner/test-repo/pull/42"
+ }"#;
+
+ 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:42"], None);
+ configure_mock_gh_env(&mut cmd, &mock_bin);
+ assert_cmd_snapshot!("switch_pr_fork_existing_different_pr", cmd);
+ });
+}
+
+/// Test fork PR where branch exists but has no tracking config
+#[rstest]
+fn test_switch_pr_fork_existing_no_tracking(#[from(repo_with_remote)] repo: TestRepo) {
+ // Create the branch without any tracking config
+ let branch_name = "contributor/feature-fix";
+ repo.run_git(&["branch", branch_name, "main"]);
+ // No config set - branch exists but doesn't track anything
+
+ let gh_response = r#"{
+ "headRefName": "feature-fix",
+ "headRepository": {"name": "test-repo"},
+ "headRepositoryOwner": {"login": "contributor"},
+ "isCrossRepository": true,
+ "url": "https://github.com/owner/test-repo/pull/42"
+ }"#;
+
+ 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:42"], None);
+ configure_mock_gh_env(&mut cmd, &mock_bin);
+ assert_cmd_snapshot!("switch_pr_fork_existing_no_tracking", cmd);
+ });
+}
+
+/// Test pr: when gh is not authenticated
+#[rstest]
+fn test_switch_pr_not_authenticated(#[from(repo_with_remote)] repo: TestRepo) {
+ let mock_bin = repo.root_path().join("mock-bin");
+ fs::create_dir_all(&mock_bin).unwrap();
+
+ copy_mock_binary(&mock_bin, "gh");
+
+ // Configure gh to return auth error
+ MockConfig::new("gh")
+ .version("gh version 2.0.0 (mock)")
+ .command(
+ "pr",
+ MockResponse::stderr(
+ "To use GitHub CLI in a non-interactive context, please run gh auth login",
+ )
+ .with_exit_code(1),
+ )
+ .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:101"], None);
+ configure_mock_gh_env(&mut cmd, &mock_bin);
+ assert_cmd_snapshot!("switch_pr_not_authenticated", cmd);
+ });
+}
+
+/// Test pr: when hitting GitHub rate limit
+#[rstest]
+fn test_switch_pr_rate_limit(#[from(repo_with_remote)] repo: TestRepo) {
+ let mock_bin = repo.root_path().join("mock-bin");
+ fs::create_dir_all(&mock_bin).unwrap();
+
+ copy_mock_binary(&mock_bin, "gh");
+
+ // Configure gh to return rate limit error
+ MockConfig::new("gh")
+ .version("gh version 2.0.0 (mock)")
+ .command(
+ "pr",
+ MockResponse::stderr("API rate limit exceeded for user").with_exit_code(1),
+ )
+ .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:101"], None);
+ configure_mock_gh_env(&mut cmd, &mock_bin);
+ assert_cmd_snapshot!("switch_pr_rate_limit", cmd);
+ });
+}
+
+/// Test pr: when gh returns invalid JSON
+#[rstest]
+fn test_switch_pr_invalid_json(#[from(repo_with_remote)] repo: TestRepo) {
+ let mock_bin = repo.root_path().join("mock-bin");
+ fs::create_dir_all(&mock_bin).unwrap();
+
+ copy_mock_binary(&mock_bin, "gh");
+
+ // Configure gh to return invalid JSON
+ MockConfig::new("gh")
+ .version("gh version 2.0.0 (mock)")
+ .command("pr", 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", &["pr:101"], None);
+ configure_mock_gh_env(&mut cmd, &mock_bin);
+ assert_cmd_snapshot!("switch_pr_invalid_json", cmd);
+ });
+}
+
+/// Test pr: when network error occurs
+#[rstest]
+fn test_switch_pr_network_error(#[from(repo_with_remote)] repo: TestRepo) {
+ let mock_bin = repo.root_path().join("mock-bin");
+ fs::create_dir_all(&mock_bin).unwrap();
+
+ copy_mock_binary(&mock_bin, "gh");
+
+ // Configure gh to return network error
+ MockConfig::new("gh")
+ .version("gh version 2.0.0 (mock)")
+ .command(
+ "pr",
+ MockResponse::stderr("connection refused: network is unreachable").with_exit_code(1),
+ )
+ .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:101"], None);
+ configure_mock_gh_env(&mut cmd, &mock_bin);
+ assert_cmd_snapshot!("switch_pr_network_error", cmd);
+ });
+}
+
+/// Test pr: when gh returns unknown error
+#[rstest]
+fn test_switch_pr_unknown_error(#[from(repo_with_remote)] repo: TestRepo) {
+ let mock_bin = repo.root_path().join("mock-bin");
+ fs::create_dir_all(&mock_bin).unwrap();
+
+ copy_mock_binary(&mock_bin, "gh");
+
+ // Configure gh to return an unrecognized error
+ MockConfig::new("gh")
+ .version("gh version 2.0.0 (mock)")
+ .command(
+ "pr",
+ MockResponse::stderr("something completely unexpected happened").with_exit_code(1),
+ )
+ .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:101"], None);
+ configure_mock_gh_env(&mut cmd, &mock_bin);
+ assert_cmd_snapshot!("switch_pr_unknown_error", cmd);
+ });
+}
+
+/// Test pr: when PR has empty branch name
+#[rstest]
+fn test_switch_pr_empty_branch(#[from(repo_with_remote)] repo: TestRepo) {
+ let mock_bin = repo.root_path().join("mock-bin");
+ fs::create_dir_all(&mock_bin).unwrap();
+
+ copy_mock_binary(&mock_bin, "gh");
+
+ // Configure gh to return valid JSON but with empty branch name
+ let gh_response = r#"{
+ "headRefName": "",
+ "headRepository": {"name": "test-repo"},
+ "headRepositoryOwner": {"login": "contributor"},
+ "isCrossRepository": false,
+ "url": "https://github.com/owner/test-repo/pull/101"
+ }"#;
+
+ MockConfig::new("gh")
+ .version("gh version 2.0.0 (mock)")
+ .command("pr", MockResponse::output(gh_response))
+ .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:101"], None);
+ configure_mock_gh_env(&mut cmd, &mock_bin);
+ assert_cmd_snapshot!("switch_pr_empty_branch", cmd);
+ });
+}
diff --git a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
index a8a96844e..c303e2b1b 100644
--- a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
@@ -28,9 +28,9 @@ Usage: wt switch [OPTIONS] <BRANCH> [--
Arguments:
<BRANCH>
- Branch name
+ Branch name or shortcut
- Shortcuts: '^' (default branch), '-' (previous), '@' (current)
+ Shortcuts: '^' (default branch), '-' (previous), '@' (current), 'pr:{N}' (GitHub PR, experimental)
[EXECUTE_ARGS]...
Additional arguments for --execute command (after --)
@@ -92,6 +92,7 @@ Worktrees are addressed by branch name; paths are computed from a configurable t
wt switch - # Previous worktree (like cd -)
wt switch --create new-feature # Create new branch and worktree
wt switch --create hotfix --base production
+ wt switch pr:123 # Switch to PR #123's branch
Creating a branch
@@ -120,10 +121,22 @@ When creating a worktree, worktrunk:
^ Default branch (main/master)
@ Current branch/worktree
- Previous worktree (like cd -)
+ pr:{N} GitHub PR #N's branch
wt switch - # Back to previous
wt switch ^ # Default branch worktree
wt switch --create fix --base=@ # Branch from current HEAD
+ wt switch pr:123 # PR #123's branch
+
+GitHub pull requests (experimental)
+
+The pr:<number> syntax resolves the branch for a GitHub pull request. For same-repo PRs, it switches to the branch directly. For fork PRs, it fetches refs/pull/N/head and configures pushRemote to the fork URL.
+
+ wt switch pr:101 # Checkout PR #101
+
+Requires gh CLI to be installed and authenticated. The --create flag cannot be used with pr: syntax since the branch already exists.
+
+Fork PRs: To push changes, use git push HEAD:<branch-name> where <branch-name> is the PR's head branch (e.g., feature-fix). The local branch is named <owner>/<branch> to avoid collisions, so plain git push won't work with default settings.
When wt switch fails
diff --git a/tests/snapshots/integration__integration_tests__help__help_switch_short.snap b/tests/snapshots/integration__integration_tests__help__help_switch_short.snap
index 56611ed94..1c0f88604 100644
--- a/tests/snapshots/integration__integration_tests__help__help_switch_short.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_switch_short.snap
@@ -7,7 +7,7 @@ info:
- "-h"
env:
CLICOLOR_FORCE: "1"
- COLUMNS: "150"
+ COLUMNS: "500"
GIT_EDITOR: ""
RUST_LOG: warn
SOURCE_DATE_EPOCH: "1735776000"
@@ -25,7 +25,7 @@ wt switch - Switch to a worktree
Usage: wt switch [OPTIONS] <BRANCH> [-- <EXECUTE_ARGS>...]
Arguments:
- <BRANCH> Branch name
+ <BRANCH> Branch name or shortcut
[EXECUTE_ARGS]... Additional arguments for --execute command (after --)
Options:
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_missing.snap b/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_missing.snap
new file mode 100644
index 000000000..e6619e1a0
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_error_path_occupied_missing.snap
@@ -0,0 +1,38 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - feature-collision
+ 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: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpons9bk/mock-bin
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+✗ Worktree directory missing for feature/collision
+↳ To clean up, run git worktree prune
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_base_conflict.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_base_conflict.snap
new file mode 100644
index 000000000..41cb56503
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_base_conflict.snap
@@ -0,0 +1,39 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--base"
+ - main
+ - "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: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpUkPMaC/mock-bin
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+✗ Cannot use --base with pr:101
+↳ PRs already have a base; remove --base
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_create_conflict.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_create_conflict.snap
new file mode 100644
index 000000000..a3667f3ce
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_create_conflict.snap
@@ -0,0 +1,38 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - "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: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp4ZpO8c/mock-bin
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+✗ Cannot use --create with pr:101
+↳ PRs already have a branch; remove --create
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_empty_branch.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_empty_branch.snap
new file mode 100644
index 000000000..da81e9365
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_empty_branch.snap
@@ -0,0 +1,37 @@
+---
+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: /private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpaZU3Am/repo/mock-bin
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+◎ Fetching PR #101 from origin...
+✗ PR #101 has empty branch name; the PR may be in an invalid state
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_fork.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_fork.snap
new file mode 100644
index 000000000..79f9c4c28
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_fork.snap
@@ -0,0 +1,40 @@
+---
+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: /private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp21Mo4b/repo/mock-bin
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Fetching PR #42 from origin...
+○ Push configured to fork: https://github.com/contributor/test-repo.git
+✓ Created branch contributor/feature-fix (tracking PR #42) and worktree @ _REPO_.contributor-feature-fix
+▲ Cannot change directory — shell integration not installed
+↳ To enable automatic cd, run wt config shell install
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_fork_existing_different_pr.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_fork_existing_different_pr.snap
new file mode 100644
index 000000000..91c8e1997
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_fork_existing_different_pr.snap
@@ -0,0 +1,38 @@
+---
+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: /private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp3ZvcLv/repo/mock-bin
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+◎ Fetching PR #42 from origin...
+✗ Branch contributor/feature-fix exists but is not tracking PR #42
+↳ Delete the branch first: git branch -D contributor/feature-fix
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_fork_existing_no_tracking.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_fork_existing_no_tracking.snap
new file mode 100644
index 000000000..9cf5d137c
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_fork_existing_no_tracking.snap
@@ -0,0 +1,38 @@
+---
+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: /private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpmUEy2n/repo/mock-bin
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+◎ Fetching PR #42 from origin...
+✗ Branch contributor/feature-fix exists but is not tracking PR #42
+↳ Delete the branch first: git branch -D contributor/feature-fix
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_fork_existing_same_pr.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_fork_existing_same_pr.snap
new file mode 100644
index 000000000..e06b31926
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_fork_existing_same_pr.snap
@@ -0,0 +1,40 @@
+---
+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: /private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpTYfCXg/repo/mock-bin
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Fetching PR #42 from origin...
+○ Branch contributor/feature-fix already configured for PR #42
+✓ Created worktree for contributor/feature-fix @ _REPO_.contributor-feature-fix
+▲ Cannot change directory — shell integration not installed
+↳ To enable automatic cd, run wt config shell install
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_invalid_json.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_invalid_json.snap
new file mode 100644
index 000000000..63bd0a1c3
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_invalid_json.snap
@@ -0,0 +1,38 @@
+---
+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: /private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpRh8Dpz/repo/mock-bin
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+◎ Fetching PR #101 from origin...
+✗ Failed to parse gh pr view JSON for PR #101. This may indicate a gh version incompatibility or GitHub API change.
+  expected ident at line 1 column 2
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_network_error.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_network_error.snap
new file mode 100644
index 000000000..4d7ad5c85
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_network_error.snap
@@ -0,0 +1,37 @@
+---
+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: /private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpt5UXqw/repo/mock-bin
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+◎ Fetching PR #101 from origin...
+✗ Network error connecting to GitHub; check your internet connection
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_not_authenticated.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_not_authenticated.snap
new file mode 100644
index 000000000..3f365086b
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_not_authenticated.snap
@@ -0,0 +1,37 @@
+---
+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: /private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpqAg3i9/repo/mock-bin
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+◎ Fetching PR #101 from origin...
+✗ GitHub CLI not authenticated; run gh auth login
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_not_found.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_not_found.snap
new file mode 100644
index 000000000..87f102d40
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_not_found.snap
@@ -0,0 +1,37 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "pr:9999"
+ 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: /private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpUbK6oP/repo/mock-bin
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+◎ Fetching PR #9999 from origin...
+✗ PR #9999 not found
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_rate_limit.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_rate_limit.snap
new file mode 100644
index 000000000..657980377
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_rate_limit.snap
@@ -0,0 +1,37 @@
+---
+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: /private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpUBbBov/repo/mock-bin
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+◎ Fetching PR #101 from origin...
+✗ GitHub API rate limit exceeded; wait a few minutes and retry
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.snap
new file mode 100644
index 000000000..d41a93377
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_same_repo.snap
@@ -0,0 +1,38 @@
+---
+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: /private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpWBoesk/repo/mock-bin
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Fetching PR #101 from origin...
+▲ Worktree for feature-auth @ _REPO_.feature-auth, but cannot change directory — shell integration not installed
+↳ To enable automatic cd, run wt config shell install
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_pr_unknown_error.snap b/tests/snapshots/integration__integration_tests__switch__switch_pr_unknown_error.snap
new file mode 100644
index 000000000..feaacebbe
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_pr_unknown_error.snap
@@ -0,0 +1,37 @@
+---
+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: /private/var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpN24ynF/repo/mock-bin
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+◎ Fetching PR #101 from origin...
+✗ gh pr view failed: something completely unexpected happened