Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: resolve worktree arguments once and pass the resolved worktree through (#4496)
Maximilian Roos0c75655c6c19
diff --git a/src/commands/context.rs b/src/commands/context.rsindex 7702e5701..201361107 100644--- a/src/commands/context.rs+++ b/src/commands/context.rs@@ -59,13 +59,7 @@ impl CommandEnv {/// named by path expands `{{ branch }}` to the branch checked out there.pub fn for_selector(config: UserConfig, selector: &str) -> anyhow::Result<Self> {let repo = Repository::current()?;- let worktree_path = repo.require_worktree(selector)?;- // Re-read the branch off the resolved worktree rather than the- // selector, which may have been the path. The lookup is against the- // cached worktree list `require_worktree` just walked.- let branch = repo- .worktree_at_path(&worktree_path)?- .and_then(|(_, branch)| branch);+ let (worktree_path, branch) = repo.require_worktree(selector)?;Ok(Self {repo: Repository::at(&worktree_path)?,diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 2d91c67db..6645b21ab 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -52,7 +52,8 @@ fn run_post_hook(extra_vars,name_filters,FailureStrategy::Warn,- );+ )+ .map(drop);}// Filter path merges user + project matches into one pipeline (the user@@ -342,6 +343,7 @@ pub fn run_hook(name_filters,FailureStrategy::FailFast,)+ .map(drop)} else {run_post_hook(&ctx,diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex d0d70a043..df51fe3a2 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -695,6 +695,8 @@ pub(crate) fn sourced_steps_to_foreground(/// The announcement shows the worktree path when commands run somewhere other/// than the user's cwd ([`crate::output::pre_hook_display_path`] — pre-hooks/// and manual `wt hook` invocations both run with the user still at cwd).+///+/// Returns whether any hook ran.pub(crate) fn run_hooks_foreground(ctx: &CommandContext,user_config: Option<&CommandConfig>,@@ -703,7 +705,7 @@ pub(crate) fn run_hooks_foreground(extra_vars: &[(&str, &str)],name_filters: &[String],failure_strategy: FailureStrategy,-) -> anyhow::Result<()> {+) -> anyhow::Result<bool> {let sourced_steps = prepare_and_check(ctx,user_config,@@ -714,7 +716,7 @@ pub(crate) fn run_hooks_foreground()?;if sourced_steps.is_empty() {- return Ok(());+ return Ok(false);}let kind = PipelineKind::Hook {@@ -729,7 +731,8 @@ pub(crate) fn run_hooks_foreground(ctx.repo,ctx.worktree_path,failure_strategy,- )+ )?;+ Ok(true)}/// Run a single hook type in the foreground for an operation (merge, switch,@@ -744,12 +747,14 @@ pub(crate) fn run_hooks_foreground(/// Project config comes from `ctx.repo.load_project_config()` — see the/// module-level "Which `.config/wt.toml` a hook reads" docs for which worktree/// `ctx.repo` is rooted at per hook type.+///+/// Returns whether any hook ran.pub(crate) fn execute_hook(ctx: &CommandContext,hook_type: HookType,extra_vars: &[(&str, &str)],failure_strategy: FailureStrategy,-) -> anyhow::Result<()> {+) -> anyhow::Result<bool> {let project_config = ctx.repo.load_project_config()?;let user_hooks = ctx.config.hooks(ctx.project_id().as_deref());run_hooks_foreground(diff --git a/src/commands/relocate.rs b/src/commands/relocate.rsindex 5c1dfb699..130dd28b5 100644--- a/src/commands/relocate.rs+++ b/src/commands/relocate.rs@@ -170,7 +170,7 @@ pub fn gather_candidates(} else {let mut selected: Vec<WorktreeInfo> = Vec::new();for arg in filter_branches {- let path = repo.require_worktree(arg)?;+ let (path, _) = repo.require_worktree(arg)?;let Some(wt) = worktrees.iter().find(|wt| paths_match(&path, &wt.path)) else {// Resolved, but pruned out above: its directory or `.git` is// gone, so there is nothing to move.diff --git a/src/commands/step/copy_ignored.rs b/src/commands/step/copy_ignored.rsindex d099813bc..7d1e49737 100644--- a/src/commands/step/copy_ignored.rs+++ b/src/commands/step/copy_ignored.rs@@ -7,7 +7,7 @@ use std::time::SystemTime;use anyhow::Context;use color_print::cformat;use worktrunk::copy::{copy_dir_recursive, copy_leaf};-use worktrunk::git::Repository;+use worktrunk::git::{Repository, path_dir_name};use worktrunk::path::format_path_for_display;use worktrunk::progress::{Progress, format_bytes, format_reflink_paren};use worktrunk::styling::{@@ -67,7 +67,11 @@ pub fn step_copy_ignored(// Resolve source and destination worktree pathslet (source_path, source_context) = match from {- Some(branch) => (repo.require_worktree(branch)?, branch.to_string()),+ Some(selector) => {+ let (path, branch) = repo.require_worktree(selector)?;+ let context = branch.unwrap_or_else(|| path_dir_name(&path).to_string());+ (path, context)+ }None => {// Default source is the primary worktree (main worktree for normal repos,// default branch worktree for bare repos).@@ -76,16 +80,13 @@ pub fn step_copy_ignored("No primary worktree found (bare repo with no default branch worktree)")})?;- let context = path- .file_name()- .map(|n| n.to_string_lossy().into_owned())- .unwrap_or_default();+ let context = path_dir_name(&path).to_string();(path, context)}};let dest_path = match to {- Some(branch) => repo.require_worktree(branch)?,+ Some(selector) => repo.require_worktree(selector)?.0,None => repo.current_worktree().root()?,};diff --git a/src/commands/step/diff.rs b/src/commands/step/diff.rsindex b45001e9f..fe8ede1fb 100644--- a/src/commands/step/diff.rs+++ b/src/commands/step/diff.rs@@ -27,7 +27,7 @@ pub fn step_diff(extra_args: &[String],) -> anyhow::Result<()> {let repo = match branch {- Some(b) => Repository::at(&Repository::current()?.require_worktree(b)?)?,+ Some(b) => Repository::at(Repository::current()?.require_worktree(b)?.0)?,None => Repository::current()?,};let wt = repo.current_worktree();diff --git a/src/commands/step/promote.rs b/src/commands/step/promote.rsindex 3a96c8976..4a98a38b6 100644--- a/src/commands/step/promote.rs+++ b/src/commands/step/promote.rs@@ -8,7 +8,7 @@ use anyhow::{Context, bail};use color_print::cformat;use path_slash::PathExt as _;use worktrunk::copy::{copy_dir_recursive, copy_leaf};-use worktrunk::git::Repository;+use worktrunk::git::{Repository, duplicated_branches};use worktrunk::path::format_path_for_display;use worktrunk::progress::Progress;use worktrunk::styling::{eprintln, hint_message, info_message, success_message, warning_message};@@ -184,36 +184,28 @@ pub enum PromoteResult {AlreadyInMain(String),}-/// Resolve the branch to promote.+/// Resolve the worktree to promote, and its branch.///-/// An explicit argument goes through the worktree selector, so the branch can be-/// named by its worktree's path as well as by name. With no argument: from the-/// main worktree, restore the default branch; from a linked worktree, promote-/// the current branch.-fn resolve_target_branch(branch: Option<&str>, repo: &Repository) -> anyhow::Result<String> {+/// An explicit argument goes through the worktree selector, so it can name the+/// branch or its worktree's path. With no argument: from the main worktree,+/// restore the default branch (`^`); from a linked worktree, promote the+/// current one (`@`).+fn resolve_target(branch: Option<&str>, repo: &Repository) -> anyhow::Result<(PathBuf, String)> {use worktrunk::git::GitError;- if let Some(b) = branch {- // Promoting swaps two branches between worktrees, so a detached- // worktree has nothing to swap in.- return repo.require_selected_branch(b, "promote");- }-- let current_wt = repo.current_worktree();- if !current_wt.is_linked()? {- // From main worktree with no args: restore default branch- repo.default_branch()- .ok_or_else(|| anyhow::anyhow!("Could not determine default branch"))- } else {- // From other worktree with no args: promote current branch- current_wt.branch()?.ok_or_else(|| {- GitError::DetachedHead {- action: Some("promote".into()),- worktree: None,- }- .into()- })- }+ let selector = match branch {+ Some(b) => b,+ None if repo.current_worktree().is_linked()? => "@",+ None => "^",+ };+ let (path, branch) = repo.require_worktree(selector)?;+ // Promoting swaps two branches between worktrees, so a detached worktree+ // has nothing to swap in.+ let branch = branch.ok_or_else(|| GitError::DetachedHead {+ action: Some("promote".into()),+ worktree: Some(path.clone()),+ })?;+ Ok((path, branch))}/// Bail if a leftover staging dir exists from a previous interrupted promote —@@ -336,24 +328,31 @@ pub fn handle_promote(branch: Option<&str>) -> anyhow::Result<PromoteResult> {worktree: Some(main_path.clone()),})?;- // Resolve the branch to promote (default_branch computed lazily, only when needed)- let target_branch = resolve_target_branch(branch, &repo)?;+ let (target_path, target_branch) = resolve_target(branch, &repo)?;// Check if target is already in main worktreeif target_branch == main_branch {return Ok(PromoteResult::AlreadyInMain(target_branch));}- // Find the worktree with the target branch- let target_wt = worktrees- .iter()- .skip(1) // Skip main worktree- .find(|wt| wt.branch.as_deref() == Some(&target_branch))- .ok_or_else(|| GitError::WorktreeNotFound {- branch: target_branch.clone(),- })?;-- let target_path = &target_wt.path;+ // The exchange checks each branch out in the other worktree, which git+ // refuses while a third worktree holds it — and by then both worktrees are+ // detached. Worktrunk never creates such a duplicate, but `git worktree+ // add --force` can.+ let duplicated = duplicated_branches(worktrees);+ for branch in [&main_branch, &target_branch] {+ if duplicated.contains(branch.as_str()) {+ let paths: Vec<_> = worktrees+ .iter()+ .filter(|wt| wt.branch.as_ref() == Some(branch))+ .map(|wt| format_path_for_display(&wt.path).to_string())+ .collect();+ return Err(anyhow::anyhow!(paths.join("\n")).context(cformat!(+ "Cannot promote: <bold>{branch}</> is checked out in {} worktrees",+ paths.len()+ )));+ }+ }// Bail early if a leftover staging dir exists from a previous interrupted promote —// checked before `ensure_clean` so users see the recovery path first.@@ -362,7 +361,7 @@ pub fn handle_promote(branch: Option<&str>) -> anyhow::Result<PromoteResult> {// Ensure both worktrees are cleanlet main_working_tree = repo.worktree_at(main_path);- let target_working_tree = repo.worktree_at(target_path);+ let target_working_tree = repo.worktree_at(&target_path);main_working_tree.ensure_clean("promote", Some(&main_branch), false)?;target_working_tree.ensure_clean("promote", Some(&target_branch), false)?;@@ -379,8 +378,12 @@ pub fn handle_promote(branch: Option<&str>) -> anyhow::Result<PromoteResult> {let no_excludes: &[String] = &[];let main_entries =list_and_filter_ignored_entries(main_path, &main_branch, &worktree_paths, no_excludes)?;- let target_entries =- list_and_filter_ignored_entries(target_path, &target_branch, &worktree_paths, no_excludes)?;+ let target_entries = list_and_filter_ignored_entries(+ &target_path,+ &target_branch,+ &worktree_paths,+ no_excludes,+ )?;// Move gitignored files to staging BEFORE branch exchange.// `git switch` silently overwrites ignored files that collide with tracked@@ -390,7 +393,7 @@ pub fn handle_promote(branch: Option<&str>) -> anyhow::Result<PromoteResult> {&repo,main_path,&main_entries,- target_path,+ &target_path,&target_entries,).context(format!(@@ -418,7 +421,7 @@ pub fn handle_promote(branch: Option<&str>) -> anyhow::Result<PromoteResult> {staging_dir,main_path,&main_entries,- target_path,+ &target_path,&target_entries,).context(format!(@@ -436,7 +439,7 @@ pub fn handle_promote(branch: Option<&str>) -> anyhow::Result<PromoteResult> {"{}",success_message(cformat!("Promoted: main worktree now has <bold>{target_branch}</>; {} now has <bold>{main_branch}</>",- worktrunk::path::format_path_for_display(target_path)+ worktrunk::path::format_path_for_display(&target_path))));if swapped > 0 {diff --git a/src/commands/worktree/resolve.rs b/src/commands/worktree/resolve.rsindex 87a923def..9b5bd9e53 100644--- a/src/commands/worktree/resolve.rs+++ b/src/commands/worktree/resolve.rs@@ -131,6 +131,7 @@ fn template_references_repo_name(template: &str) -> bool {/// When a bare repo lives at a hidden path like `.git` or `.bare`, the `{{ repo }}`/// template variable resolves to that directory name, producing broken worktree paths./// This function detects the situation and offers to set a project-level override.+/// `branch` is the branch the switch resolved to, which the example paths show.////// Returns `true` if config was modified (caller should use the updated config).pub fn offer_bare_repo_worktree_path_fix(@@ -142,13 +143,6 @@ pub fn offer_bare_repo_worktree_path_fix(return Ok(false);}- // Symbolic identifiers (-, @, ^, pr:N, mr:N) haven't been resolved to a real- // branch name yet, so the example paths would be misleading. Skip the prompt;- // it will surface on the next switch with a concrete branch name.- if branch == "-" || branch == "@" || branch == "^" || branch.contains(':') {- return Ok(false);- }-let repo_path = repo.repo_path()?;let repo_name = repo_path.file_name().and_then(|n| n.to_str()).unwrap_or("");if !repo_name.starts_with('.') {diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 9a2a4727a..124e3811b 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -45,39 +45,137 @@ use crate::output::{prompt_shell_integration,};-/// Result of resolving the switch target.+/// A `pr:N` / `mr:N` argument resolved through the forge.struct ResolvedTarget {- /// The branch to switch to, carrying whether the token may still be tried- /// as a path. Two things take that off: a rewrite, since `pr:`/`mr:`- /// dispatch and the remote-prefix strip leave the user's literal argument- /// naming nothing; and `--create`, where the argument names a branch that- /// does not exist yet.+ /// The PR/MR's branch, under the local name it is or will be checked out as.selector: Selector,/// How to create the worktreemethod: CreationMethod,- /// Set when the argument was `pr:N` / `mr:N`, for the `pr_number` /- /// `pr_url` hook variables. Independent of `method`: a same-repo PR- /// resolves to `CreationMethod::Regular` and still has an identity.- ref_identity: Option<RefIdentity>,+ /// The PR/MR itself, for the `pr_number` / `pr_url` hook variables.+ /// Independent of `method`: a same-repo PR resolves to+ /// `CreationMethod::Regular` and still has an identity.+ ref_identity: RefIdentity,}-impl ResolvedTarget {- /// A target with no PR/MR identity — every form but `pr:N` / `mr:N`.- fn new(selector: Selector, method: CreationMethod) -> Self {- Self {- selector,- method,- ref_identity: None,+/// The switch argument resolved to its destination.+///+/// [`SwitchPipeline::run`] resolves it before the `pre-switch` hooks, so their+/// variables describe the destination, and hands the same value to+/// [`plan_switch`]. A hook is arbitrary code, though, and may fetch or create+/// the branch the argument names, so when one ran the pipeline locates the+/// argument again through the same [`SwitchTarget::locate`], on a fresh+/// [`Repository`]. The forge is asked about `pr:N` / `mr:N` only the first+/// time. How to create a new worktree — `--base` and the `--create` checks —+/// is left to `plan_switch` for the same reason.+struct SwitchTarget {+ destination: SwitchDestination,+ /// The forge's answer for `pr:N` / `mr:N`.+ remote_ref: Option<ResolvedTarget>,+}++enum SwitchDestination {+ /// A worktree the argument names; `branch` is `None` when it is detached,+ /// which only a path can name.+ Existing {+ path: PathBuf,+ branch: Option<String>,+ },+ /// A branch with no worktree, or one `--create` is about to make.+ New { branch: String },+}++impl SwitchTarget {+ /// Resolve `identifier`, reaching the forge for `pr:N` / `mr:N`.+ fn resolve(+ repo: &Repository,+ identifier: &str,+ create: bool,+ base: Option<&str>,+ ) -> anyhow::Result<Self> {+ let remote_ref = resolve_ref_shortcut_target(repo, identifier, create, base)?;+ Self::locate(repo, identifier, create, remote_ref)+ }++ /// Find what `identifier` names in `repo` as it is now, given the forge's+ /// answer when the argument was `pr:N` / `mr:N`.+ fn locate(+ repo: &Repository,+ identifier: &str,+ create: bool,+ remote_ref: Option<ResolvedTarget>,+ ) -> anyhow::Result<Self> {+ let resolved = match &remote_ref {+ Some(target) => repo.resolve_selector(&target.selector)?,+ // Under `--create` the argument names a branch that does not exist+ // yet: not a worktree, a path, or a remote-tracking name.+ None if create => {+ let branch = repo+ .expand_selector(identifier)+ .context("Failed to resolve branch name")?+ .token()+ .to_string();+ return Ok(Self {+ destination: SwitchDestination::New { branch },+ remote_ref,+ });+ }+ None => resolve_switch_argument(repo, identifier)?,+ };+ let destination = match resolved {+ ResolvedWorktree::Worktree { path, branch, .. } => {+ SwitchDestination::Existing { path, branch }+ }+ ResolvedWorktree::BranchOnly { branch, .. } => SwitchDestination::New { branch },+ // Nothing is registered there, and a path is all the argument+ // could have been, so there is no destination to switch to,+ // create, or describe to the hooks.+ ResolvedWorktree::NoWorktreeAtPath { path } => {+ return Err(GitError::WorktreeNotFoundAtPath { path }.into());+ }+ };+ Ok(Self {+ destination,+ remote_ref,+ })+ }++ /// The branch the switch lands on. `None` for a detached worktree.+ fn branch(&self) -> Option<&str> {+ match &self.destination {+ SwitchDestination::Existing { branch, .. } => branch.as_deref(),+ SwitchDestination::New { branch } => Some(branch),}}- /// Attach the PR/MR the argument named. Called on the single return path- /// of [`resolve_remote_ref`], so a fork resolution can't reach the plan- /// without an identity the way it could when each arm set the field.- fn with_ref_identity(mut self, identity: RefIdentity) -> Self {- self.ref_identity = Some(identity);- self+ fn ref_identity(&self) -> Option<&RefIdentity> {+ self.remote_ref.as_ref().map(|target| &target.ref_identity)+ }+}++/// Resolve a `wt switch` argument other than `pr:N` / `mr:N` or a `--create`+/// name.+///+/// [`Repository::resolve_worktree`] — the ladder every worktree argument goes+/// through, `@` resolving by path — plus one rewrite: a remote-tracking name+/// such as `origin/feature`, which the picker passes for a remote branch,+/// names the local branch `feature` unless a local branch is literally called+/// `origin/feature`.+fn resolve_switch_argument(+ repo: &Repository,+ identifier: &str,+) -> anyhow::Result<ResolvedWorktree> {+ let resolved = repo+ .resolve_worktree(identifier)+ .context("Failed to resolve branch name")?;+ if let ResolvedWorktree::BranchOnly { branch, .. } = &resolved+ && !repo.branch(branch).exists_locally()?+ && let Some(local_name) = repo.strip_remote_prefix(branch)+ {+ // A rewrite like any other: `origin/foo` may have been a path the user+ // typed, but `foo` is one nobody did.+ return repo.resolve_selector(&Selector::rewritten_to(local_name));}+ Ok(resolved)}/// Format PR/MR context for gutter display after fetching.@@ -229,12 +327,12 @@ fn resolve_remote_ref(.into());}- let target = if info.is_cross_repo {+ let (selector, method) = if info.is_cross_repo {resolve_fork_ref(repo, forge, number, &info)?} else {// Same-repo ref: fetch the branch to ensure remote tracking refs existfetch_same_repo_branch(repo, &info)?;- ResolvedTarget::new(+ (Selector::rewritten_to(info.source_branch),CreationMethod::Regular {create_branch: false,@@ -244,12 +342,14 @@ fn resolve_remote_ref()};- // Every path out of here resolved the same PR/MR, so the identity is set- // once here rather than repeated on each arm of `resolve_fork_ref`.- Ok(target.with_ref_identity(RefIdentity {- number,- url: info.url,- }))+ Ok(ResolvedTarget {+ selector,+ method,+ ref_identity: RefIdentity {+ number,+ url: info.url,+ },+ })}/// Resolve a fork (cross-repo) PR/MR.@@ -258,7 +358,7 @@ fn resolve_fork_ref(forge: ForgeKind,number: u32,info: &RemoteRefInfo,-) -> anyhow::Result<ResolvedTarget> {+) -> anyhow::Result<(Selector, CreationMethod)> {let ref_type = forge.ref_type();let repo_root = repo.repo_path()?;let local_branch = info.source_branch.clone();@@ -286,7 +386,7 @@ fn resolve_fork_ref(ref_type.display(number))));- return Ok(ResolvedTarget::new(+ return Ok((Selector::rewritten_to(local_branch),CreationMethod::Regular {create_branch: false,@@ -312,7 +412,7 @@ fn resolve_fork_ref(ref_type.display(number))));- return Ok(ResolvedTarget::new(+ return Ok((Selector::rewritten_to(prefixed),CreationMethod::Regular {create_branch: false,@@ -333,7 +433,7 @@ fn resolve_fork_ref(// GitHub and Gitea support prefixed branch names. This path has no// fork push URL, so the branch remains fetch-only.let remote = remote_ref::find_remote(repo, info)?;- return Ok(ResolvedTarget::new(+ return Ok((Selector::rewritten_to(prefixed),CreationMethod::ForkRef {ref_type,@@ -394,7 +494,7 @@ fn resolve_fork_ref(}};- Ok(ResolvedTarget::new(+ Ok((Selector::rewritten_to(local_branch),CreationMethod::ForkRef {ref_type,@@ -455,7 +555,7 @@ fn parse_ref_shortcut(input: &str) -> Option<(RefType, u32)> {////// 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+/// [`creation_method`] 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`. `git worktree add` does DWIM the bare form, but/// destructively: given `-b <name>` it drops the `-b` and creates the remote@@ -526,7 +626,7 @@ fn resolve_remote_ref_as_base(// source branch nobody has checked out locally resolves only under its// remote: git's rev-parse never expands a bare name to a// remote-tracking ref, and the bare name would fail the base- // validation in `resolve_switch_target`. Same rule, same spelling as+ // validation in `creation_method`. Same rule, same spelling as// the remote-only base above.let base = if repo.ref_exists(branch)? {branch.clone()@@ -553,20 +653,12 @@ fn resolve_remote_ref_as_base(Ok((sha, None))}-/// Resolve a `pr:N` / `mr:N` argument through the forge, ahead of the rest of-/// planning.+/// Resolve a `pr:N` / `mr:N` argument through the forge.////// Returns `None` for any other argument — this is the one form whose branch-/// name can't be derived locally.-///-/// Split out of [`resolve_switch_target`] so [`SwitchPipeline::run`] can-/// resolve it *before* `pre-switch` hooks: a hook that receives the raw-/// `pr:3933` token sees a `branch` / `target` naming nothing, and no-/// `target_worktree_path` even when the PR's branch is already checked out-/// (#3934). Symbolic arguments (`-`, `@`, `^`) already resolve ahead of the-/// hook for the same reason (#2310); this extends the rule to the one-/// resolution that costs a forge round-trip. The result is threaded back into-/// [`plan_switch`], so the forge is still queried exactly once.+/// name can't be derived locally, and the one resolution that costs a forge+/// round-trip. Like every other argument it resolves ahead of the+/// `pre-switch` hooks (#3934), and the forge is queried exactly once.fn resolve_ref_shortcut_target(repo: &Repository,branch: &str,@@ -596,60 +688,20 @@ fn resolve_ref_shortcut_target(resolve_remote_ref(repo, forge, number, create).map(Some)}-/// Resolve the switch target, handling --create/--base flags.+/// Decide how a new worktree for `branch` gets created, validating+/// `--create` and `--base`.///-/// This is the first phase of planning: determine what branch we're switching to-/// and how we'll create the worktree. `pr:`/`mr:` arguments arrive already-/// resolved in `ref_target` — [`resolve_ref_shortcut_target`] runs them before-/// `pre-switch` hooks, and its result is passed straight through here.-fn resolve_switch_target(+/// Runs after the `pre-switch` hooks, which may fetch the ref `--base` names+/// or the remote branch `--create` warns about shadowing.+fn creation_method(repo: &Repository,branch: &str,- ref_target: Option<ResolvedTarget>,create: bool,base: Option<&str>,-) -> anyhow::Result<ResolvedTarget> {- if let Some(target) = ref_target {- return Ok(target);- }- // Everything below treats `branch` as a branch name, so a `pr:N` token- // arriving unresolved would go looking for a literal branch called- // `pr:101`. One caller today, and it always resolves first — this is what- // fails the tests if a second one forgets to.- debug_assert!(- parse_ref_shortcut(branch).is_none(),- "`pr:`/`mr:` must reach plan_switch pre-resolved (resolve_ref_shortcut_target)"- );-- // Regular branch switch. `expand_selector` normalizes the token and- // expands `@` / `-` / `^`, reporting whether it rewrote anything.- let mut selector = repo- .expand_selector(branch)- .context("Failed to resolve branch name")?;-- // Handle remote-tracking ref names (e.g., "origin/username/feature-1" from the picker).- // Strip the remote prefix only when there is no exact local branch/worktree,- // so a local branch literally named `origin/foo` is not retargeted to `foo`.- if !create- && repo.worktree_for_branch(selector.token())?.is_none()- && !repo.branch(selector.token()).exists_locally()?- && let Some(local_name) = repo.strip_remote_prefix(selector.token())- {- // A rewrite like any other: `origin/foo` may have been a path the user- // typed, but `foo` is one nobody did.- selector = Selector::rewritten_to(local_name);- }- let resolved_branch = selector.token().to_string();-- // Resolve and validate base (only when --create is set)- 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)- } else {+) -> anyhow::Result<CreationMethod> {+ // Resolve and validate base (only used with --create)+ let (resolved_base, base_pr_upstream) = match base {+ Some(base_str) if create => {let (resolved, upstream) = resolve_base_ref(repo, base_str)?;if !repo.ref_exists(&resolved)? {return Err(GitError::ReferenceNotFound {@@ -660,17 +712,16 @@ fn resolve_switch_target(}(Some(resolved), upstream)}- } else {- (None, None)+ _ => (None, None),};// Validate --create constraintsif create {- let branch_handle = repo.branch(&resolved_branch);+ let branch_handle = repo.branch(branch);branch_handle.require_valid_name()?;if branch_handle.exists_locally()? {return Err(GitError::BranchAlreadyExists {- branch: resolved_branch,+ branch: branch.to_string(),}.into());}@@ -678,18 +729,18 @@ fn resolve_switch_target(// Warn if --create would shadow a remote branchlet remotes = branch_handle.remotes()?;if !remotes.is_empty() {- let remote_ref = format!("{}/{}", remotes[0], resolved_branch);+ let remote_ref = format!("{}/{}", remotes[0], branch);eprintln!("{}",warning_message(cformat!(- "Branch <bold>{resolved_branch}</> exists on remote ({remote_ref}); creating new branch from base instead"+ "Branch <bold>{branch}</> exists on remote ({remote_ref}); creating new branch from base instead")));// `--foreground` is required: background removal leaves a placeholder// directory at the original path (to keep shell PWD valid), which// would block the subsequent `wt switch` with "Directory already exists".- let remove_cmd = suggest_command("remove", &[&resolved_branch], &["--foreground"]);- let switch_cmd = suggest_command("switch", &[&resolved_branch], &[]);+ let remove_cmd = suggest_command("remove", &[branch], &["--foreground"]);+ let switch_cmd = suggest_command("switch", &[branch], &[]);eprintln!("{}",hint_message(cformat!(@@ -714,21 +765,11 @@ fn resolve_switch_target(None};- Ok(ResolvedTarget::new(- // Under `--create` the argument names a branch that does not exist- // yet, so it is not a path to look up — stated here, where `create`- // lives, rather than re-tested at each arm that consults it.- if create {- selector.branch_only()- } else {- selector- },- CreationMethod::Regular {- create_branch: create,- base_branch,- base_pr_upstream,- },- ))+ Ok(CreationMethod::Regular {+ create_branch: create,+ base_branch,+ base_pr_upstream,+ })}/// Validate that we can create a worktree at the given path.@@ -738,7 +779,7 @@ fn resolve_switch_target(/// - For regular switches (not --create), branch must exist/// - Handles --clobber for stale directories///-/// Note: Fork PR/MR branch existence is checked earlier in resolve_switch_target()+/// Note: Fork PR/MR branch existence is checked earlier in resolve_fork_ref()/// where we can also check if it's tracking the correct PR/MR.fn validate_worktree_creation(repo: &Repository,@@ -912,11 +953,9 @@ fn setup_fork_branch(////// Warnings (remote branch shadow, --base without --create, invalid default branch)/// are printed during planning since they're informational, not blocking.-#[allow(clippy::too_many_arguments)]fn plan_switch(repo: &Repository,- branch: &str,- ref_target: Option<ResolvedTarget>,+ target: SwitchTarget,create: bool,base: Option<&str>,path: Option<&Path>,@@ -926,9 +965,12 @@ fn plan_switch(// Record current branch for `wt switch -` supportlet new_previous = repo.current_worktree().branch().ok().flatten();- // Phase 1: Resolve target (validates --create/--base; `pr:`/`mr:` arrived- // pre-resolved from the caller, ahead of the pre-switch hooks)- let target = resolve_switch_target(repo, branch, ref_target, create, base)?;+ if base.is_some() && !create {+ eprintln!(+ "{}",+ warning_message("--base flag is only used with --create, ignoring")+ );+ }// Resolve `--path` the way git resolves `git worktree add <path>`: from// the directory wt was pointed at, normalized so the comparisons below and@@ -939,25 +981,22 @@ fn plan_switch(}).transpose()?;- // Phase 2: the shared worktree ladder — the branch, then the argument as a- // worktree's own path (the way to name a detached one, which has no- // branch), then a verdict on what a selector matching neither was reaching- // for. `target.selector` carries whether Phase 1 rewrote the token, so the- // path arm switches itself off after a shortcut, `pr:`/`mr:`, or a stripped- // remote prefix.- //- // Resolving before the path template is also the fast path: an existing- // worktree answers without the ~7 git commands `compute_worktree_path` runs.- match repo.resolve_selector(&target.selector)? {- ResolvedWorktree::Worktree { path, branch, .. } => {+ let SwitchTarget {+ destination,+ remote_ref,+ } = target;++ // Phase 1: an existing worktree answers without the ~7 git commands+ // `compute_worktree_path` runs.+ let branch = match destination {+ SwitchDestination::Existing { path, branch } => {+ let name = branch+ .clone()+ .unwrap_or_else(|| worktrunk::git::path_dir_name(&path).to_string());// A registration whose directory is gone or broken has nothing to// switch into; `wt remove` is the one command that still wants it.if repo.worktree_is_unusable(&path)? {- return Err(GitError::worktree_missing(- branch.unwrap_or_else(|| worktrunk::git::path_dir_name(&path).to_string()),- &path,- )- .into());+ return Err(GitError::worktree_missing(name, &path).into());}// `--path` only places a new worktree. Naming a different// directory for one that already exists would otherwise be@@ -965,11 +1004,10 @@ fn plan_switch(if let Some(requested) = requested_path.as_deref()&& !same_worktree_path(requested, &path){- let token = target.selector.token();let existing = format_path_for_display(&path);let requested = format_path_for_display(requested);bail!(cformat!(- "<bold>{token}</> already has a worktree @ <bold>{existing}</>, not <bold>{requested}</>; to switch to it, run without <bold>--path</>"+ "<bold>{name}</> already has a worktree @ <bold>{existing}</>, not <bold>{requested}</>; to switch to it, run without <bold>--path</>"));}return Ok(SwitchPlan::Existing {@@ -978,42 +1016,35 @@ fn plan_switch(new_previous,});}- // Nothing is registered there, and a path is all the argument could- // have been — so stop here rather than carrying it to Phase 4, which- // would report a missing branch and offer to create one under a name- // git rejects. `--create` never reaches this arm: its selector says- // the token is not a path, so `resolve_selector` returns `BranchOnly`.- ResolvedWorktree::NoWorktreeAtPath { path } => {- return Err(GitError::WorktreeNotFoundAtPath { path }.into());- }- _ => {}- }+ SwitchDestination::New { branch } => branch,+ };++ // Phase 2: how to create it (validates --create/--base; `pr:`/`mr:`+ // arrived with the forge's answer)+ let (method, ref_identity) = match remote_ref {+ Some(target) => (target.method, Some(target.ref_identity)),+ None => (creation_method(repo, &branch, create, base)?, None),+ };- // Phase 3: Compute expected path (only needed for create). `--path`- // replaces the template outright.+ // Phase 3: Compute expected path. `--path` replaces the template outright.let expected_path = match requested_path {Some(path) => {reject_path_overlapping_worktrees(repo, &path)?;path}- None => compute_worktree_path(repo, target.selector.token(), config)?,+ None => compute_worktree_path(repo, &branch, config)?,};// Phase 4: Validate we can create at this path- let needs_clobber_backup = validate_worktree_creation(- repo,- target.selector.token(),- &expected_path,- clobber,- &target.method,- )?;+ let needs_clobber_backup =+ validate_worktree_creation(repo, &branch, &expected_path, clobber, &method)?;// Phase 5: Return the planOk(SwitchPlan::Create {- branch: target.selector.token().to_string(),+ branch,worktree_path: expected_path,- method: target.method,- ref_identity: target.ref_identity,+ method,+ ref_identity,needs_clobber_backup,new_previous,})@@ -1569,15 +1600,12 @@ struct SwitchOptions<'a> {format: crate::cli::SwitchFormat,}-/// Run pre-switch hooks before worktree creation.+/// Run pre-switch hooks before worktree creation, returning whether any ran.///-/// Symbolic arguments (`-`, `@`, `^`) are resolved to concrete branch names-/// before building the hook context so `{{ target }}`, `{{ target_worktree_path }}`,-/// and the Active overrides point at the real destination. When resolution-/// fails (e.g., no previous branch for `-`), the raw argument is used — the-/// same error surfaces later from `plan_switch` with the canonical message.-/// `pr:N` / `mr:N` cannot resolve locally at all, so the caller resolves them-/// through the forge first and passes the result in `ref_target`.+/// `target` is the destination as resolved before the hooks, so+/// `{{ branch }}`, `{{ target }}`, and `{{ target_worktree_path }}` describe+/// where the switch lands however the argument named it: a shortcut, `pr:N`,+/// a remote-tracking name, or a worktree's path.////// Directional vars:/// - `base` / `base_worktree_path`: current (source) branch and worktree@@ -1586,84 +1614,59 @@ struct SwitchOptions<'a> {fn run_pre_switch_hooks(repo: &Repository,config: &UserConfig,- target_branch: &str,- ref_target: Option<&ResolvedTarget>,- create: bool,+ target: &SwitchTarget,yes: bool,-) -> anyhow::Result<()> {+) -> anyhow::Result<bool> {let current_wt = repo.current_worktree();let current_path = current_wt.path().to_path_buf();- // `expand_selector`, not the bare shortcut expander: the `target` var a- // pre-switch hook receives has to name the same branch the switch goes on- // to resolve, normalization included. A `pr:`/`mr:` argument is already- // past that point — the forge answered with the branch name itself.- let selector = match ref_target {- Some(target) => Some(target.selector.clone()),- // `--create` names a branch that doesn't exist yet, never a path —- // the same reading `resolve_switch_target` gives it.- None => repo- .expand_selector(target_branch)- .ok()- .map(|s| if create { s.branch_only() } else { s }),- };- // The same worktree ladder `plan_switch` runs, so a worktree named by its- // path — which is how the picker names one — describes the destination- // just as its branch name would (issue #4492). A detached destination has- // no branch, which leaves `branch` and `target` unset.- let (dest_branch, dest_path) = match selector.as_ref().map(|s| repo.resolve_selector(s)) {- Some(Ok(ResolvedWorktree::Worktree { path, branch, .. })) => (branch, Some(path)),- _ => (- Some(- selector- .as_ref()- .map_or(target_branch, |s| s.token())- .to_string(),- ),- None,- ),+ // A detached destination has no branch, which leaves `branch` and+ // `target` unset (issue #4009).+ let dest_branch = target.branch();+ let dest_path = match &target.destination {+ SwitchDestination::Existing { path, .. } => Some(path.as_path()),+ SwitchDestination::New { .. } => None,};- let pre_ctx = CommandContext::new(repo, config, dest_branch.as_deref(), ¤t_path, yes);-- let pre_switch_approved = approve_hooks(&pre_ctx, &[HookType::PreSwitch])?;- if pre_switch_approved {- // Base vars: source (where the user currently is). Target vars and- // Active overrides come from the destination worktree if it exists —- // for creates the planned path is computed later during plan_switch,- // so worktree_path stays at its default (the source = cwd).- // A detached source worktree leaves `base` unset rather than empty,- // matching `branch` and what `wt hook pre-switch` already renders- // there (issue #4009).- let base_branch = current_wt.branch().ok().flatten();-- let ref_identity = ref_target.and_then(|t| t.ref_identity.as_ref());- let mut vars = TemplateVars::new()- .with_base(base_branch.as_deref(), ¤t_path)- .with_target_opt(dest_branch.as_deref())- .with_pr(- ref_identity.map(|id| id.number),- ref_identity.map(|id| id.url.as_str()),- );- if let Some(p) = dest_path.as_deref() {- vars = vars.with_target_worktree_path(p).with_active_worktree(p);- // Without a branch, `commit` would otherwise read HEAD where the- // hook runs — the source worktree.- if dest_branch.is_none()- && let Ok(Some(commit)) = repo.worktree_at(p).head_sha()- && let Ok(short) = repo.short_sha(&commit)- {- vars = vars.with_active_commit(&commit, &short);- }- }- let extra_vars = vars.as_extra_vars();+ let pre_ctx = CommandContext::new(repo, config, dest_branch, ¤t_path, yes);- execute_hook(- &pre_ctx,- HookType::PreSwitch,- &extra_vars,- FailureStrategy::FailFast,- )?;+ if !approve_hooks(&pre_ctx, &[HookType::PreSwitch])? {+ return Ok(false);}- Ok(())+ // Base vars: source (where the user currently is). Target vars and+ // Active overrides come from the destination worktree if it exists —+ // for creates the planned path is computed later during plan_switch,+ // so worktree_path stays at its default (the source = cwd).+ // A detached source worktree leaves `base` unset rather than empty,+ // matching `branch` and what `wt hook pre-switch` already renders+ // there (issue #4009).+ let base_branch = current_wt.branch().ok().flatten();++ let ref_identity = target.ref_identity();+ let mut vars = TemplateVars::new()+ .with_base(base_branch.as_deref(), ¤t_path)+ .with_target_opt(dest_branch)+ .with_pr(+ ref_identity.map(|id| id.number),+ ref_identity.map(|id| id.url.as_str()),+ );+ if let Some(p) = dest_path {+ vars = vars.with_target_worktree_path(p).with_active_worktree(p);+ // Without a branch, `commit` would otherwise read HEAD where the+ // hook runs — the source worktree.+ if dest_branch.is_none()+ && let Ok(Some(commit)) = repo.worktree_at(p).head_sha()+ && let Ok(short) = repo.short_sha(&commit)+ {+ vars = vars.with_active_commit(&commit, &short);+ }+ }+ let extra_vars = vars.as_extra_vars();++ execute_hook(+ &pre_ctx,+ HookType::PreSwitch,+ &extra_vars,+ FailureStrategy::FailFast,+ )}/// Hook types that apply after a switch operation.@@ -1805,9 +1808,9 @@ fn capture_switch_source(repo: &Repository, is_recovered: bool) -> (String, Stri/// The full switch sequence shared by the argument path ([`run_switch`]) and/// the interactive picker.///-/// Each caller only resolves a branch identifier and loads config; everything-/// else runs in [`SwitchPipeline::run`] — the bare-repo path-fix offer,-/// pre-switch hooks, source-identity capture, `plan_switch` →+/// Each caller only supplies the identifier and loads config; everything+/// else runs in [`SwitchPipeline::run`] — target resolution, the bare-repo+/// path-fix offer, pre-switch hooks, source-identity capture, `plan_switch` →/// `approve_switch_hooks` → `validate_switch_templates` → `execute_switch` →/// output → background hooks → `--execute`. One sequence, so the two entry/// points cannot drift. In particular the single `verify` / `yes` pair gates@@ -1831,7 +1834,8 @@ pub(crate) struct SwitchPipeline<'a> {/// it shared.pub config: &'a mut UserConfig,/// Branch identifier — a CLI argument or the picker's selection. Symbolic- /// forms (`-`, `@`, `pr:`/`mr:`) are resolved downstream by `plan_switch`.+ /// forms (`-`, `@`, `pr:`/`mr:`) and worktree paths are resolved by+ /// [`SwitchTarget::resolve`].pub identifier: &'a str,pub create: bool,pub base: Option<&'a str>,@@ -1885,34 +1889,42 @@ impl SwitchPipeline<'_> {shell_integration_binary,} = self;- // Offer to fix worktree-path for bare repos with hidden directory names- // (.git, .bare) before anything reads worktree-path config.- offer_bare_repo_worktree_path_fix(repo, config, identifier)?;-- // Resolve a `pr:N` / `mr:N` argument before the hooks below, so their- // `{{ branch }}` / `{{ target }}` name the PR's branch rather than the- // raw token. This is the one resolution that reaches the forge, and it- // is bounded to the argument form that asked for it; the resolved- // target is handed to `plan_switch`, which queries nothing further.- let ref_target = resolve_ref_shortcut_target(repo, identifier, create, base)?;+ // Resolve the argument ahead of everything that describes the+ // destination: the bare-repo offer's example paths, the `pre-switch`+ // hooks' variables, and the plan itself. A `pr:N` argument reaches+ // the forge here.+ let target = SwitchTarget::resolve(repo, identifier, create, base)?;// Kept past the move into `plan_switch`: a `pr:N` switch onto a branch// that already has a worktree produces `SwitchResult::Existing`, which// carries no PR identity of its own, and the hooks on that path should// still see the same `pr_number` / `pr_url` as the creating run.- let ref_identity = ref_target- .as_ref()- .and_then(|target| target.ref_identity.clone());-- // Run pre-switch hooks before worktree creation. run_pre_switch_hooks- // resolves symbolic args (`-`, `@`, `^`) first, so {{ branch }} and- // {{ target }} carry the concrete destination, not the raw token. Skip- // when recovered — the source worktree is gone, nothing to run hooks- // against. `yes` is the single switch-wide flag, so the picker (no- // `--yes`) and the argument path gate `pre-switch` hooks identically.- if verify && !is_recovered {- run_pre_switch_hooks(repo, config, identifier, ref_target.as_ref(), create, yes)?;+ let ref_identity = target.ref_identity().cloned();++ // Offer to fix worktree-path for bare repos with hidden directory names+ // (.git, .bare) before anything reads worktree-path config.+ if let Some(branch) = target.branch() {+ offer_bare_repo_worktree_path_fix(repo, config, branch)?;}+ // Run pre-switch hooks before worktree creation. Skip when recovered —+ // the source worktree is gone, nothing to run hooks against. `yes` is+ // the single switch-wide flag, so the picker (no `--yes`) and the+ // argument path gate `pre-switch` hooks identically.+ let hooks_ran =+ verify && !is_recovered && run_pre_switch_hooks(repo, config, &target, yes)?;++ // A hook may have fetched or created what the argument names, and+ // `repo` cached the refs and worktrees it read before the hook ran. So+ // plan against a fresh repository, locating the argument again there.+ let refreshed;+ let (repo, target) = if hooks_ran {+ refreshed = Repository::at(repo.discovery_path())?;+ let target = SwitchTarget::locate(&refreshed, identifier, create, target.remote_ref)?;+ (&refreshed, target)+ } else {+ (repo, target)+ };+// Capture source (base) worktree identity BEFORE the switch, for// post-switch {{ base }} / {{ base_worktree_path }}. Done here — after// pre-switch hooks, before plan / approve / validate, none of which move@@ -1921,20 +1933,20 @@ impl SwitchPipeline<'_> {let (source_branch, source_path) = capture_switch_source(repo, is_recovered);// Validate and resolve the target branch.- let plan = plan_switch(- repo, identifier, ref_target, create, base, path, clobber, config,- )- .map_err(|err| match suggestion_ctx {- Some(ref ctx) => match err.downcast::<GitError>() {- Ok(git_err) => GitError::WithSwitchSuggestion {- source: Box::new(git_err),- ctx: ctx.clone(),+ let plan =+ plan_switch(repo, target, create, base, path, clobber, config).map_err(|err| {+ match suggestion_ctx {+ Some(ref ctx) => match err.downcast::<GitError>() {+ Ok(git_err) => GitError::WithSwitchSuggestion {+ source: Box::new(git_err),+ ctx: ctx.clone(),+ }+ .into(),+ Err(err) => err,+ },+ None => err,}- .into(),- Err(err) => err,- },- None => err,- })?;+ })?;// "Approve at the Gate": collect and approve hooks upfront. Approval// happens once at the command entry point. If the user declines, skipdiff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rsindex e0a9e5ca3..fbfabbca7 100644--- a/src/commands/worktree/types.rs+++ b/src/commands/worktree/types.rs@@ -96,7 +96,7 @@ pub enum CreationMethod {/// Identity of the PR/MR a `pr:N` / `mr:N` argument resolved to.////// Resolved once, before `pre-switch` hooks run, then held by whoever needs it:-/// the `ResolvedTarget` `pre-switch` reads, the plan `pre-start` reads, and the+/// the `SwitchTarget` `pre-switch` reads, the plan `pre-start` reads, and the/// pipeline's own clone behind the post-* hooks — an `Existing` switch builds no/// `SwitchPlan::Create` at all. So `pr_number` / `pr_url` reach every switch/// hook whether the PR came from this repo or a fork. Reading it back offdiff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 348b987eb..05f1563ee 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -437,11 +437,7 @@ impl ResolvedWorktree {/// So the producers state it. A token nobody touched may name a path/// ([`Selector::literal`]). One an earlier step produced may not/// ([`Selector::rewritten_to`]) — a shortcut expansion, a `pr:`/`mr:` lookup, a-/// stripped remote prefix, a default branch read from cache. Neither does one-/// that names a branch by construction ([`Selector::branch_only`]), which is-/// `wt switch --create <name>`: nothing rewrote the argument, but it names a-/// branch that does not exist yet, so a directory sitting at that spelling is-/// not what the user meant.+/// stripped remote prefix, a default branch read from cache.#[derive(Debug, Clone)]pub struct Selector {token: String,@@ -466,14 +462,6 @@ impl Selector {}}- /// Take the path arm off a token that names a branch by construction.- pub fn branch_only(self) -> Self {- Self {- may_name_path: false,- ..self- }- }-/// The name to look up.pub fn token(&self) -> &str {&self.tokendiff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rsindex 162063c60..dbbeb31a8 100644--- a/src/git/repository/worktrees.rs+++ b/src/git/repository/worktrees.rs@@ -530,10 +530,10 @@ impl Repository {/// what the selector could have meant.////// Split from [`resolve_worktree`](Self::resolve_worktree) for the callers- /// that do their own expanding before they get here — `wt switch`, whose- /// `pr:`/`mr:` dispatch and remote-prefix strip run first and report their- /// rewriting through the [`Selector`]. They used to re-implement these- /// three steps rather than expand into a shared one.+ /// whose selector comes from somewhere other than the user's token — `wt+ /// switch`, for a `pr:`/`mr:` branch or a stripped remote prefix — and+ /// report that rewriting through the [`Selector`]. They used to+ /// re-implement these three steps rather than expand into a shared one.pub fn resolve_selector(&self, selector: &Selector) -> anyhow::Result<ResolvedWorktree> {let token = selector.token();@@ -542,11 +542,9 @@ impl Repository {}// Both remaining steps are about the token as a path, so- // `names_a_path` gates them together — a caller that turns it off gets- // neither a worktree matched by path nor a verdict about a directory,- // which is what `wt switch --create` needs: the argument names a branch- // to create, and a directory sitting at that spelling is the clobber- // check's business.+ // `names_a_path` gates them together: a rewritten token gets neither a+ // worktree matched by path nor a verdict about a directory, since the+ // user never typed it as a path.if !selector.names_a_path() {return Ok(ResolvedWorktree::branch_only(token.to_string()));}@@ -568,10 +566,10 @@ impl Repository {/// worktree.////// [`resolve_worktree`](Self::resolve_worktree) for the arguments that want- /// a branch rather than a worktree — `wt step promote`, and the `--branch`- /// of the `wt config state` commands, which key state by branch name. A- /// branch with no worktree is a fine answer to those; a worktree named by- /// path that has no branch is not.+ /// a branch rather than a worktree — the `--branch` of the `wt config+ /// state` commands, which key state by branch name. A branch with no+ /// worktree is a fine answer to those; a worktree named by path that has no+ /// branch is not.pub fn require_selected_branch(&self, name: &str, action: &str) -> anyhow::Result<String> {match self.resolve_worktree(name)? {ResolvedWorktree::Worktree {@@ -597,19 +595,22 @@ impl Repository {}}- /// The path of the worktree a selector names, erroring when it names none.+ /// The worktree a selector names — its path, and its branch (`None` when+ /// detached) — erroring when it names none.////// [`resolve_worktree`](Self::resolve_worktree) for the commands that need a- /// worktree to operate in rather than a branch to reason about — `wt step- /// diff --branch`, `copy-ignored --from`/`--to`, `promote`. A branch with no- /// checkout and a name matching nothing at all are the same answer to them.+ /// worktree to operate in rather than a branch to reason about. A branch+ /// with no checkout and a name matching nothing at all are the same answer+ /// to them. The branch comes back with the path so a caller that needs+ /// both uses the pair resolution found, rather than looking one up from+ /// the other: a branch checked out twice maps back to the wrong path./// A selector matching nothing at all is reported as such, rather than as a/// branch without a worktree: `wt switch <the selector>` creates a worktree/// only when the branch exists, so offering it for a mistyped path would/// just fail again.- pub fn require_worktree(&self, name: &str) -> anyhow::Result<PathBuf> {+ pub fn require_worktree(&self, name: &str) -> anyhow::Result<(PathBuf, Option<String>)> {match self.resolve_worktree(name)? {- ResolvedWorktree::Worktree { path, .. } => Ok(path),+ ResolvedWorktree::Worktree { path, branch, .. } => Ok((path, branch)),ResolvedWorktree::BranchOnly { branch, .. } => Err(self.no_worktree_error(branch)),ResolvedWorktree::NoWorktreeAtPath { path } => {Err(GitError::WorktreeNotFoundAtPath { path }.into())diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex a36b57592..334bba546 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -197,6 +197,18 @@ pub fn canonical_temp_home(temp_home: &TempDir) -> std::path::PathBuf {dunce::canonicalize(temp_home.path()).unwrap()}+/// Check out `branch` a second time at `<repo>.<suffix>`, the state only+/// `--force` can produce.+pub fn add_force_duplicate(repo: &TestRepo, branch: &str, suffix: &str) -> std::path::PathBuf {+ let dup = repo+ .root_path()+ .parent()+ .unwrap()+ .join(format!("repo.{suffix}"));+ repo.run_git(&["worktree", "add", "--force", dup.to_str().unwrap(), branch]);+ dup+}+/// Repo with remote tracking set up.////// Builds on the `repo` fixture, adding a "remote" for the default branch.diff --git a/tests/integration_tests/bare_repository.rs b/tests/integration_tests/bare_repository.rsindex 9182ad454..7876bbbdf 100644--- a/tests/integration_tests/bare_repository.rs+++ b/tests/integration_tests/bare_repository.rs@@ -2061,16 +2061,14 @@ fn test_bare_repo_worktree_path_warning_uses_configured_template() {);}-/// Symbolic identifiers (-, @, pr:N) are passed before branch resolution, so-/// the example paths in the prompt would show the raw symbol. The function-/// must return early without prompting.+/// A shortcut resolves before the bare-repo warning, so its example path names+/// the branch the shortcut stands for rather than the raw symbol.#[test]-fn test_bare_repo_worktree_path_prompt_skipped_for_symbolic_identifier() {+fn test_bare_repo_worktree_path_warning_names_resolved_shortcut() {let test = setup_unconfigured_nested_bare_repo();let main_worktree = test.project_path().join("main");- // `@` means HEAD — resolves to `main`, which already exists. The prompt- // must not appear because `@` is a symbolic form.+ // `@` is the current worktree, on `main`.let mut cmd = wt_command();test.configure_wt_cmd(&mut cmd);cmd.args(["switch", "@"]).current_dir(&main_worktree);@@ -2078,12 +2076,12 @@ fn test_bare_repo_worktree_path_prompt_skipped_for_symbolic_identifier() {let stderr = String::from_utf8_lossy(&output.stderr);assert!(- !stderr.contains("Configure worktree-path"),- "Prompt should not appear for symbolic identifier '@', got: {stderr}"+ stderr.contains("worktrees will be at") && stderr.contains(".git.main"),+ "Warning should name the resolved branch `main`, got: {stderr}");assert!(- !stderr.contains("Bare repo at"),- "Warning should not appear for symbolic identifier '@', got: {stderr}"+ !stderr.contains(".git.@"),+ "Warning should not name the raw `@`, got: {stderr}");}diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex b33ffa45f..d10747682 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -1,9 +1,9 @@#[cfg(unix)]use crate::common::temp_home;use crate::common::{- BareRepoTest, SLEEP_FOR_ABSENCE_CHECK, TestRepo, TestRepoBase, configure_directive_file,- directive_file, make_snapshot_cmd, repo, repo_with_remote, setup_snapshot_settings,- setup_temp_snapshot_settings, wt_command,+ BareRepoTest, SLEEP_FOR_ABSENCE_CHECK, TestRepo, TestRepoBase, add_force_duplicate,+ configure_directive_file, directive_file, make_snapshot_cmd, repo, repo_with_remote,+ setup_snapshot_settings, setup_temp_snapshot_settings, wt_command,};use ansi_str::AnsiStr;use insta::assert_snapshot;@@ -5601,18 +5601,6 @@ fn test_remove_merged_locally_when_upstream_diverged(#[from(repo_with_remote)] r// test here asserts on the survivor's `HEAD`, not just on the branch.// ============================================================================-/// Check out `branch` a second time at `<repo>.<suffix>`, the state only-/// `--force` can produce.-fn add_force_duplicate(repo: &TestRepo, branch: &str, suffix: &str) -> std::path::PathBuf {- let dup = repo- .root_path()- .parent()- .unwrap()- .join(format!("repo.{suffix}"));- repo.run_git(&["worktree", "add", "--force", dup.to_str().unwrap(), branch]);- dup-}-/// Assert `worktree` still resolves `HEAD` to a commit — the corruption a/// deleted-but-checked-out branch leaves behind.#[track_caller]diff --git a/tests/integration_tests/step_promote.rs b/tests/integration_tests/step_promote.rsindex 854f7ca11..ef7763ad4 100644--- a/tests/integration_tests/step_promote.rs+++ b/tests/integration_tests/step_promote.rs@@ -1,8 +1,10 @@//! Integration tests for `wt step promote`use crate::common::{- TestRepo, configure_git_env, make_snapshot_cmd, repo, setup_snapshot_settings, wt_command,+ TestRepo, add_force_duplicate, configure_git_env, make_snapshot_cmd, repo,+ setup_snapshot_settings, wt_command,};+use ansi_str::AnsiStr;use insta_cmd::assert_cmd_snapshot;use rstest::rstest;use std::fs;@@ -78,6 +80,62 @@ fn test_promote_with_branch_argument(mut repo: TestRepo) {);}+/// A branch checked out in two worktrees (`git worktree add --force`) can't+/// be exchanged: git won't check it out in the main worktree while the other+/// copy holds it. Promote refuses before touching anything, here with the+/// second copy named by its path, which used to promote the first.+#[rstest]+fn test_promote_refuses_duplicate_checkout_by_path(mut repo: TestRepo) {+ let _settings_guard = setup_snapshot_settings(&repo).bind_to_scope();+ let first = repo.add_worktree("feature");+ let second = add_force_duplicate(&repo, "feature", "feature-copy");++ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "step",+ &["promote", second.to_str().unwrap()],+ Some(repo.root_path()),+ ));++ assert_eq!(branch_name(&repo, repo.root_path()), "main");+ assert_eq!(branch_name(&repo, &first), "feature");+ assert_eq!(branch_name(&repo, &second), "feature");+}++/// The other two routes to a duplicated branch: run with no argument from the+/// second copy of the target, and a default branch checked out twice.+#[rstest]+#[case::target_from_second_copy("feature")]+#[case::main_branch("main")]+fn test_promote_refuses_duplicate_checkout(mut repo: TestRepo, #[case] duplicated: &str) {+ let feature = repo.add_worktree("feature");+ let copy = add_force_duplicate(&repo, duplicated, "copy");+ let run_from = if duplicated == "feature" {+ ©+ } else {+ &feature+ };++ let output = repo+ .wt_command()+ .args(["step", "promote"])+ .current_dir(run_from)+ .output()+ .unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr)+ .ansi_strip()+ .to_string();+ assert!(!output.status.success(), "stderr: {stderr}");+ assert!(+ stderr.contains(&format!("{duplicated} is checked out in 2 worktrees")),+ "stderr: {stderr}"+ );++ assert_eq!(branch_name(&repo, repo.root_path()), "main");+ assert_eq!(branch_name(&repo, &feature), "feature");+ assert_eq!(branch_name(&repo, ©), duplicated);+}+/// Test restoring canonical state#[rstest]fn test_promote_restore(mut repo: TestRepo) {diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 435106b2e..67346219b 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -1,8 +1,8 @@use crate::common::{- SLEEP_FOR_ABSENCE_CHECK, TestRepo, configure_directive_file, directive_file, make_snapshot_cmd,- make_snapshot_cmd_with_global_flags, repo, repo_with_remote, set_temp_home_env,- setup_home_snapshot_settings, setup_snapshot_settings, temp_home, wait_for_file_content,- wt_command,+ SLEEP_FOR_ABSENCE_CHECK, TestRepo, add_force_duplicate, configure_directive_file,+ directive_file, make_snapshot_cmd, make_snapshot_cmd_with_global_flags, repo, repo_with_remote,+ set_temp_home_env, setup_home_snapshot_settings, setup_snapshot_settings, temp_home,+ wait_for_file_content, wt_command,};use ansi_str::AnsiStr;use insta_cmd::assert_cmd_snapshot;@@ -8584,6 +8584,39 @@ fn test_switch_with_relative_worktree_paths(repo: TestRepo) {snapshot_switch("switch_to_relative_paths", &repo, &["relative-test"]);}+/// `@` names the worktree the command runs in, by path, so it reaches the+/// checkouts its branch name can't: the second copy of a branch checked out+/// twice, and a detached worktree.+#[rstest]+#[case::second_checkout(false)]+#[case::detached(true)]+fn test_switch_at_names_the_current_worktree(mut repo: TestRepo, #[case] detached: bool) {+ repo.add_worktree("feature");+ let current = if detached {+ repo.detach_head_in_worktree("feature");+ repo.worktrees["feature"].clone()+ } else {+ add_force_duplicate(&repo, "feature", "feature-copy")+ };++ let output = repo+ .wt_command()+ .args(["switch", "@", "--no-cd", "--yes", "--format=json"])+ .current_dir(¤t)+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(json["action"], "already_at");+ let path = std::path::Path::new(json["path"].as_str().unwrap());+ assert_eq!(path.file_name(), current.file_name());+}+// -- JSON format tests --#[rstest]diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex fa11162b4..f68deb9a3 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -8,8 +8,8 @@use crate::common::{SLEEP_FOR_ABSENCE_CHECK, TestRepo, make_snapshot_cmd, make_snapshot_cmd_with_global_flags,- repo, resolve_git_common_dir, setup_snapshot_settings, wait_for_file, wait_for_file_content,- wait_for_file_count,+ repo, repo_with_remote, resolve_git_common_dir, setup_snapshot_settings, wait_for_file,+ wait_for_file_content, wait_for_file_count,};use insta::assert_snapshot;use insta_cmd::assert_cmd_snapshot;@@ -4085,6 +4085,90 @@ capture = "echo 'branch={% if branch is defined %}{{ branch }}{% else %}unset{%);}+/// A remote-tracking name (`origin/feature`, which the picker passes for a+/// remote branch) switches to the local branch, so the pre-switch vars name+/// that branch — with its worktree when it has one, and without when the+/// switch creates it.+#[rstest]+#[case::existing_worktree("feature", "set")]+#[case::remote_only("remote-feature", "unset")]+fn test_pre_switch_vars_with_remote_prefixed_argument(+ #[from(repo_with_remote)] mut repo: TestRepo,+ #[case] branch: &str,+ #[case] target_wt: &str,+) {+ if branch == "feature" {+ repo.add_worktree("feature");+ repo.run_git(&["push", "origin", "feature"]);+ } else {+ repo.run_git(&["branch", branch]);+ repo.run_git(&["push", "origin", branch]);+ repo.run_git(&["branch", "-D", branch]);+ }++ repo.write_test_config(+ r#"[pre-switch]+capture = "echo 'branch={{ branch }} target={{ target }} target_wt={% if target_worktree_path %}set{% else %}unset{% endif %}' > pre_switch_remote.txt"+"#,+ );++ let output = repo+ .wt_command()+ .args(["switch", &format!("origin/{branch}"), "--yes"])+ .current_dir(repo.root_path())+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );++ let content = fs::read_to_string(repo.root_path().join("pre_switch_remote.txt")).unwrap();+ assert_eq!(+ content.trim(),+ format!("branch={branch} target={branch} target_wt={target_wt}"),+ );+}++/// A pre-switch hook that fetches makes a branch it fetched switchable in the+/// same run — the fetch-if-stale use the hook exists for — whether the+/// argument names the branch or its remote-tracking ref.+#[rstest]+#[case::branch("late")]+#[case::remote_tracking("origin/late")]+fn test_pre_switch_fetch_makes_branch_switchable(+ #[from(repo_with_remote)] repo: TestRepo,+ #[case] argument: &str,+) {+ // `late` exists on the remote, but nothing local knows about it yet.+ repo.run_git(&["branch", "late"]);+ repo.run_git(&["push", "origin", "late"]);+ repo.run_git(&["branch", "-D", "late"]);+ repo.run_git(&["update-ref", "-d", "refs/remotes/origin/late"]);++ repo.write_test_config(+ r#"[pre-switch]+fetch = "git fetch -q origin"+"#,+ );++ let output = repo+ .wt_command()+ .args(["switch", argument, "--no-cd", "--yes", "--format=json"])+ .current_dir(repo.root_path())+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "stderr: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(json["action"], "created");+ assert_eq!(json["branch"], "late");+}+/// Post-remove: target/target_worktree_path point to where user ends up.#[rstest]fn test_post_remove_has_target_vars(mut repo: TestRepo) {diff --git a/tests/snapshots/integration__integration_tests__step_promote__promote_detached_head_linked.snap b/tests/snapshots/integration__integration_tests__step_promote__promote_detached_head_linked.snapindex a4267bb7b..1ea70f26f 100644--- a/tests/snapshots/integration__integration_tests__step_promote__promote_detached_head_linked.snap+++ b/tests/snapshots/integration__integration_tests__step_promote__promote_detached_head_linked.snap@@ -60,4 +60,4 @@ exit_code: 1----- stderr -----[31m✗[39m [31mCannot promote: not on a branch (detached HEAD)[39m-[2m↳[22m [2mTo switch to a branch, run [4mgit switch <branch>[24m[22m+[2m↳[22m [2mTo switch to a branch, run [4mgit -C _REPO_.feature switch <branch>[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__step_promote__promote_refuses_duplicate_checkout_by_path.snap b/tests/snapshots/integration__integration_tests__step_promote__promote_refuses_duplicate_checkout_by_path.snapnew file mode 100644index 000000000..8e1dc84e4--- /dev/null+++ b/tests/snapshots/integration__integration_tests__step_promote__promote_refuses_duplicate_checkout_by_path.snap@@ -0,0 +1,65 @@+---+source: tests/integration_tests/step_promote.rs+info:+ program: wt+ args:+ - step+ - promote+ - _REPO_.feature-copy+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: file+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test User+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[31m✗[39m [31mCannot promote: [1mfeature[22m is checked out in 2 worktrees[39m+[107m [0m _REPO_.feature+[107m [0m _REPO_.feature-copy