Skip to content

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

feat(switch): add --path to create a worktree outside the worktree-path template (#4317)

Worktrunk Bot1a2015bfc562
diff --git a/docs/src/content/docs/switch.md b/docs/src/content/docs/switch.md
index f4d42dd85..4af8419dd 100644
--- a/docs/src/content/docs/switch.md
+++ b/docs/src/content/docs/switch.md
@@ -40,7 +40,7 @@ A new branch tracks the remote branch it starts from only when the two share a n
If the branch already has a worktree, `wt switch` changes directories to it. Otherwise, it creates one:
1. Runs [pre-switch hooks](/hook/#hook-types), blocking until complete
-2. Creates worktree at configured path
+2. Creates worktree at configured path (or at `--path`)
3. Switches to new directory
4. Runs [pre-start hooks](/hook/#hook-types), blocking until complete
5. Spawns [post-start](/hook/#hook-types) and [post-switch hooks](/hook/#hook-types) in the background
@@ -52,6 +52,20 @@ $ wt switch --create fix --base release # New branch from release
$ wt switch --create temp --no-hooks # Skip hooks
```
+### Custom path
+
+<span class="badge-experimental"></span>
+
+`--path` places one worktree outside the `worktree-path` template, keeping the branch name intact:
+
+```console
+$ wt switch --create feature/JIRA-1234 --path ../dark-mode
+$ wt switch ../dark-mode # Switch by path...
+$ wt switch feature/JIRA-1234 # ...or by branch
+```
+
+Worktrunk finds the worktree from git's own records, so only [`wt step relocate`](/step/#wt-step-relocate) treats it differently: it offers to move the worktree back to the template path.
+
## Naming a worktree
Worktrees are addressed by branch name, and every argument that takes one also accepts the path of the worktree itself — resolved after the branch, so a directory never shadows a branch sharing its name. A path names what a branch cannot: a detached worktree, or one of two checkouts of the same branch. Relative paths resolve against `-C` and a leading `~` against the home directory, so a path worktrunk printed can be pasted back.
@@ -195,6 +209,13 @@ Options:
Defaults to default branch. Supports the same shortcuts as the branch argument: ^, @, -,
pr:{N}, mr:{N}.
+ --path <PATH>
+ Worktree directory for a new worktree [experimental]
+
+ Overrides the worktree-path template for this worktree. Relative paths resolve from the
+ current directory, as with git worktree add. The branch keeps its own name; afterwards,
+ switch by branch or by path.
+
-x, --execute <EXECUTE>
Program to run after switch
diff --git a/plugins/worktrunk/skills/worktrunk/reference/switch.md b/plugins/worktrunk/skills/worktrunk/reference/switch.md
index 0ab06ad78..305193c78 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/switch.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/switch.md
@@ -26,7 +26,7 @@ A new branch tracks the remote branch it starts from only when the two share a n
If the branch already has a worktree, `wt switch` changes directories to it. Otherwise, it creates one:
1. Runs [pre-switch hooks](https://worktrunk.dev/hook/#hook-types), blocking until complete
-2. Creates worktree at configured path
+2. Creates worktree at configured path (or at `--path`)
3. Switches to new directory
4. Runs [pre-start hooks](https://worktrunk.dev/hook/#hook-types), blocking until complete
5. Spawns [post-start](https://worktrunk.dev/hook/#hook-types) and [post-switch hooks](https://worktrunk.dev/hook/#hook-types) in the background
@@ -38,6 +38,18 @@ $ wt switch --create fix --base release # New branch from release
$ wt switch --create temp --no-hooks # Skip hooks
```
+### Custom path [experimental]
+
+`--path` places one worktree outside the `worktree-path` template, keeping the branch name intact:
+
+```console
+$ wt switch --create feature/JIRA-1234 --path ../dark-mode
+$ wt switch ../dark-mode # Switch by path...
+$ wt switch feature/JIRA-1234 # ...or by branch
+```
+
+Worktrunk finds the worktree from git's own records, so only [`wt step relocate`](https://worktrunk.dev/step/#wt-step-relocate) treats it differently: it offers to move the worktree back to the template path.
+
## Naming a worktree
Worktrees are addressed by branch name, and every argument that takes one also accepts the path of the worktree itself — resolved after the branch, so a directory never shadows a branch sharing its name. A path names what a branch cannot: a detached worktree, or one of two checkouts of the same branch. Relative paths resolve against `-C` and a leading `~` against the home directory, so a path worktrunk printed can be pasted back.
@@ -167,6 +179,13 @@ Options:
Defaults to default branch. Supports the same shortcuts as the branch argument: ^, @, -,
pr:{N}, mr:{N}.
+ --path <PATH>
+ Worktree directory for a new worktree [experimental]
+
+ Overrides the worktree-path template for this worktree. Relative paths resolve from the
+ current directory, as with git worktree add. The branch keeps its own name; afterwards,
+ switch by branch or by path.
+
-x, --execute <EXECUTE>
Program to run after switch
diff --git a/skills/worktrunk/reference/switch.md b/skills/worktrunk/reference/switch.md
index 0ab06ad78..305193c78 100644
--- a/skills/worktrunk/reference/switch.md
+++ b/skills/worktrunk/reference/switch.md
@@ -26,7 +26,7 @@ A new branch tracks the remote branch it starts from only when the two share a n
If the branch already has a worktree, `wt switch` changes directories to it. Otherwise, it creates one:
1. Runs [pre-switch hooks](https://worktrunk.dev/hook/#hook-types), blocking until complete
-2. Creates worktree at configured path
+2. Creates worktree at configured path (or at `--path`)
3. Switches to new directory
4. Runs [pre-start hooks](https://worktrunk.dev/hook/#hook-types), blocking until complete
5. Spawns [post-start](https://worktrunk.dev/hook/#hook-types) and [post-switch hooks](https://worktrunk.dev/hook/#hook-types) in the background
@@ -38,6 +38,18 @@ $ wt switch --create fix --base release # New branch from release
$ wt switch --create temp --no-hooks # Skip hooks
```
+### Custom path [experimental]
+
+`--path` places one worktree outside the `worktree-path` template, keeping the branch name intact:
+
+```console
+$ wt switch --create feature/JIRA-1234 --path ../dark-mode
+$ wt switch ../dark-mode # Switch by path...
+$ wt switch feature/JIRA-1234 # ...or by branch
+```
+
+Worktrunk finds the worktree from git's own records, so only [`wt step relocate`](https://worktrunk.dev/step/#wt-step-relocate) treats it differently: it offers to move the worktree back to the template path.
+
## Naming a worktree
Worktrees are addressed by branch name, and every argument that takes one also accepts the path of the worktree itself — resolved after the branch, so a directory never shadows a branch sharing its name. A path names what a branch cannot: a detached worktree, or one of two checkouts of the same branch. Relative paths resolve against `-C` and a leading `~` against the home directory, so a path worktrunk printed can be pasted back.
@@ -167,6 +179,13 @@ Options:
Defaults to default branch. Supports the same shortcuts as the branch argument: ^, @, -,
pr:{N}, mr:{N}.
+ --path <PATH>
+ Worktree directory for a new worktree [experimental]
+
+ Overrides the worktree-path template for this worktree. Relative paths resolve from the
+ current directory, as with git worktree add. The branch keeps its own name; afterwards,
+ switch by branch or by path.
+
-x, --execute <EXECUTE>
Program to run after switch
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index dc0cff314..01d60e3dc 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -372,6 +372,15 @@ pub(crate) struct SwitchArgs {
#[arg(short = 'b', long, requires = "branch", add = crate::completion::branch_value_completer(), value_parser = crate::cli::non_empty_branch)]
pub(crate) base: Option<String>,
+ /// Worktree directory for a new worktree \[experimental\]
+ ///
+ /// Overrides the `worktree-path` template for this worktree. Relative
+ /// paths resolve from the current directory, as with `git worktree add`.
+ /// The branch keeps its own name; afterwards, switch by branch or by
+ /// path.
+ #[arg(long, requires = "branch", value_hint = clap::ValueHint::DirPath, conflicts_with_all = ["branches", "remotes", "prs"])]
+ pub(crate) path: Option<std::path::PathBuf>,
+
/// Program to run after switch
///
/// Runs one external program after switching, with full terminal control.
@@ -653,7 +662,7 @@ A new branch tracks the remote branch it starts from only when the two share a n
If the branch already has a worktree, `wt switch` changes directories to it. Otherwise, it creates one:
1. Runs [pre-switch hooks](/hook/#hook-types), blocking until complete
-2. Creates worktree at configured path
+2. Creates worktree at configured path (or at `--path`)
3. Switches to new directory
4. Runs [pre-start hooks](/hook/#hook-types), blocking until complete
5. Spawns [post-start](/hook/#hook-types) and [post-switch hooks](/hook/#hook-types) in the background
@@ -665,6 +674,18 @@ $ wt switch --create fix --base release # New branch from release
$ wt switch --create temp --no-hooks # Skip hooks
```
+### Custom path [experimental]
+
+`--path` places one worktree outside the `worktree-path` template, keeping the branch name intact:
+
+```console
+$ wt switch --create feature/JIRA-1234 --path ../dark-mode
+$ wt switch ../dark-mode # Switch by path...
+$ wt switch feature/JIRA-1234 # ...or by branch
+```
+
+Worktrunk finds the worktree from git's own records, so only [`wt step relocate`](/step/#wt-step-relocate) treats it differently: it offers to move the worktree back to the template path.
+
## Naming a worktree
Worktrees are addressed by branch name, and every argument that takes one also accepts the path of the worktree itself — resolved after the branch, so a directory never shadows a branch sharing its name. A path names what a branch cannot: a detached worktree, or one of two checkouts of the same branch. Relative paths resolve against `-C` and a leading `~` against the home directory, so a path worktrunk printed can be pasted back.
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index 1af0627c8..f9dfd8a49 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -2204,6 +2204,7 @@ pub fn handle_picker(
identifier: &identifier,
create: should_create,
base: None,
+ path: None,
clobber: false,
verify: true,
yes: false,
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index bf3c048e3..6342a1966 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -10,6 +10,7 @@ use crate::display::format_relative_time_short;
use anyhow::{Context, bail};
use color_print::cformat;
use dunce::canonicalize;
+use normalize_path::NormalizePath;
use serde::Serialize;
use worktrunk::HookType;
use worktrunk::config::{
@@ -19,8 +20,9 @@ use worktrunk::config::{
use worktrunk::git::remote_ref::{self, RemoteRefInfo, parse_ref_url};
use worktrunk::git::{
ForgeKind, GitError, GitRemoteUrl, RefType, Repository, ResolvedWorktree, Selector,
- SwitchSuggestionCtx, WorktreeId, branch_tracks_ref, current_or_recover,
+ SwitchSuggestionCtx, WorktreeId, branch_tracks_ref, current_or_recover, resolve_input_path,
};
+use worktrunk::path::format_path_for_display;
use worktrunk::shell_exec::{ShellEscapeMode, shell_cwd};
use worktrunk::styling::{
eprintln, format_with_gutter, hint_message, info_message, println, progress_message,
@@ -915,12 +917,14 @@ 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>,
create: bool,
base: Option<&str>,
+ path: Option<&Path>,
clobber: bool,
config: &UserConfig,
) -> anyhow::Result<SwitchPlan> {
@@ -931,6 +935,15 @@ fn plan_switch(
// pre-resolved from the caller, ahead of the pre-switch hooks)
let target = resolve_switch_target(repo, branch, ref_target, create, base)?;
+ // Resolve `--path` the way git resolves `git worktree add <path>`: from
+ // the directory wt was pointed at, normalized so the comparisons below and
+ // the path git records agree.
+ let requested_path = path
+ .map(|path| -> anyhow::Result<PathBuf> {
+ Ok(std::path::absolute(resolve_input_path(path))?.normalize())
+ })
+ .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
@@ -951,6 +964,19 @@ fn plan_switch(
)
.into());
}
+ // `--path` only places a new worktree. Naming a different
+ // directory for one that already exists would otherwise be
+ // silently ignored.
+ 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</>"
+ ));
+ }
return Ok(SwitchPlan::Existing {
path: operational_worktree_path(path),
branch,
@@ -968,8 +994,15 @@ fn plan_switch(
_ => {}
}
- // Phase 3: Compute expected path (only needed for create)
- let expected_path = compute_worktree_path(repo, target.selector.token(), config)?;
+ // Phase 3: Compute expected path (only needed for create). `--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)?,
+ };
// Phase 4: Validate we can create at this path
let needs_clobber_backup = validate_worktree_creation(
@@ -991,6 +1024,41 @@ fn plan_switch(
})
}
+/// Refuse a `--path` directory that holds a worktree or the repository, or
+/// that sits inside one.
+///
+/// Such a directory always exists, so `validate_worktree_creation` would
+/// otherwise offer `--clobber`, which moves it aside: `--path ..` would move
+/// the repository itself, and `--path src` a tracked directory of the current
+/// worktree. The template never produces these; a typed path easily does. A
+/// directory that does not exist yet is left alone — nesting a new worktree
+/// inside another is git's call, not a clobber.
+fn reject_path_overlapping_worktrees(repo: &Repository, requested: &Path) -> anyhow::Result<()> {
+ let Ok(requested) = canonicalize(requested) else {
+ return Ok(());
+ };
+ let registered = repo.list_worktrees()?.iter().map(|wt| wt.path.as_path());
+ for existing in registered.chain([repo.git_common_dir()]) {
+ let existing = canonicalize(existing).unwrap_or_else(|_| existing.to_path_buf());
+ if existing == requested {
+ continue;
+ }
+ let relation = if existing.starts_with(&requested) {
+ "contains"
+ } else if requested.starts_with(&existing) {
+ "is inside"
+ } else {
+ continue;
+ };
+ let requested = format_path_for_display(&requested);
+ let existing = format_path_for_display(&existing);
+ bail!(cformat!(
+ "<bold>--path {requested}</> {relation} <bold>{existing}</>; choose a directory outside the repository and its worktrees"
+ ));
+ }
+ Ok(())
+}
+
/// Preserve the filesystem spelling Git and downstream commands can operate
/// on. This is deliberately separate from [`WorktreeId`]'s comparison form:
/// on deep Windows paths, `dunce` keeps the `\\?\` prefix while the identity
@@ -1496,6 +1564,7 @@ struct SwitchOptions<'a> {
branch: &'a str,
create: bool,
base: Option<&'a str>,
+ path: Option<&'a Path>,
execute: Option<&'a str>,
execute_args: &'a [String],
yes: bool,
@@ -1746,6 +1815,9 @@ pub(crate) struct SwitchPipeline<'a> {
pub identifier: &'a str,
pub create: bool,
pub base: Option<&'a str>,
+ /// `--path`: where to create the worktree instead of the `worktree-path`
+ /// template.
+ pub path: Option<&'a Path>,
pub clobber: bool,
pub verify: bool,
/// `--yes`: skip approval prompts and force past clobber checks.
@@ -1780,6 +1852,7 @@ impl SwitchPipeline<'_> {
identifier,
create,
base,
+ path,
clobber,
verify,
yes,
@@ -1828,18 +1901,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, 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,
- })?;
+ 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(),
+ }
+ .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, skip
@@ -1998,6 +2073,7 @@ fn run_switch(
branch,
create,
base,
+ path,
execute,
execute_args,
yes,
@@ -2016,15 +2092,22 @@ fn run_switch(
config.resolved(project_id.as_deref()).switch.cd()
});
- // Build switch suggestion context for enriching error hints with --execute/trailing args.
+ // Build switch suggestion context for enriching error hints with --path/--execute/trailing args.
// Without this, errors like "branch already exists" would suggest `wt switch <branch>`
- // instead of the full `wt switch <branch> --execute=<cmd> -- <args>`.
- let suggestion_ctx = execute.map(|exec| {
+ // instead of the full `wt switch <branch> --path=<dir> --execute=<cmd> -- <args>`.
+ // Dropping `--path` would point `--clobber` at the template's path instead.
+ let mut extra_flags = Vec::new();
+ if let Some(path) = path {
+ let escaped = shell_escape::unix::escape(path.to_string_lossy());
+ extra_flags.push(format!("--path={escaped}"));
+ }
+ if let Some(exec) = execute {
let escaped = shell_escape::unix::escape(exec.into());
- SwitchSuggestionCtx {
- extra_flags: vec![format!("--execute={escaped}")],
- trailing_args: execute_args.to_vec(),
- }
+ extra_flags.push(format!("--execute={escaped}"));
+ }
+ let suggestion_ctx = (!extra_flags.is_empty()).then(|| SwitchSuggestionCtx {
+ extra_flags,
+ trailing_args: execute_args.to_vec(),
});
SwitchPipeline {
@@ -2033,6 +2116,7 @@ fn run_switch(
identifier: branch,
create,
base,
+ path,
clobber,
verify,
yes,
@@ -2083,6 +2167,7 @@ pub fn handle_switch_command(args: SwitchArgs, yes: bool) -> anyhow::Result<()>
branch: &branch,
create: args.create,
base: args.base.as_deref(),
+ path: args.path.as_deref(),
execute: args.execute.as_deref(),
execute_args: &args.execute_args,
yes,
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index d4b58093f..790e0d34f 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -627,7 +627,7 @@ fn base_path() -> &'static PathBuf {
/// prints its own paths in is a form wt also accepts.
///
/// This is the one resolution point for those paths, so they cannot drift
-/// apart: worktree path arguments (`wt switch ../repo.feature`), `--config`,
+/// apart: worktree path arguments (`wt switch ../repo.feature`), `wt switch --path`, `--config`,
/// `WORKTRUNK_CONFIG_PATH`, `WORKTRUNK_SYSTEM_CONFIG_PATH`, and the trace file
/// of `wt config state logs profile`. The rule is "the user named a file for wt
/// to open" — three neighbours look similar and are deliberately outside it:
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 6e72252d2..8bfd4aada 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -8470,3 +8470,107 @@ fn test_switch_create_names_branch_left_by_failed_worktree_add(repo: TestRepo) {
"expected a recovery suggestion for the leftover branch, got: {stderr}"
);
}
+
+// `--path` tests
+
+#[rstest]
+fn test_switch_create_with_path(repo: TestRepo) {
+ let custom = repo.root_path().parent().unwrap().join("dark-mode");
+
+ // Relative to the current directory (the repo root here), like `git worktree add`
+ snapshot_switch(
+ "switch_create_with_path",
+ &repo,
+ &["--create", "feature/dark-mode", "--path", "../dark-mode"],
+ );
+
+ assert!(custom.join(".git").exists());
+
+ // Once created, the worktree is found by branch or by path; `--path`
+ // naming the same directory is accepted too.
+ for args in [
+ &["feature/dark-mode"][..],
+ &["../dark-mode"],
+ &["feature/dark-mode", "--path", "../dark-mode"],
+ ] {
+ let output = repo.wt_command().arg("switch").args(args).output().unwrap();
+ assert!(output.status.success(), "{args:?}: {output:?}");
+ }
+}
+
+#[rstest]
+fn test_switch_path_existing_branch_without_worktree(repo: TestRepo) {
+ repo.run_git(&["branch", "existing"]);
+ let custom = repo.root_path().parent().unwrap().join("custom-dir");
+
+ // No `--create`: the branch exists and only its worktree is new
+ snapshot_switch(
+ "switch_path_existing_branch",
+ &repo,
+ &["existing", "--path", "../custom-dir"],
+ );
+
+ assert!(custom.join(".git").exists());
+}
+
+#[rstest]
+fn test_switch_path_rejects_existing_worktree_elsewhere(mut repo: TestRepo) {
+ repo.add_worktree("feature-z");
+
+ snapshot_switch(
+ "switch_path_existing_worktree_elsewhere",
+ &repo,
+ &["feature-z", "--path", "../somewhere-else"],
+ );
+
+ assert!(
+ !repo
+ .root_path()
+ .parent()
+ .unwrap()
+ .join("somewhere-else")
+ .exists()
+ );
+}
+
+#[rstest]
+fn test_switch_path_occupied_suggests_path_in_clobber_hint(repo: TestRepo) {
+ let custom = repo.root_path().parent().unwrap().join("occupied");
+ std::fs::create_dir_all(&custom).unwrap();
+
+ // The `--clobber` suggestion must keep `--path`, or following it would
+ // back up the template's path instead of this one.
+ snapshot_switch(
+ "switch_path_occupied",
+ &repo,
+ &["--create", "feature-y", "--path", "../occupied"],
+ );
+}
+
+#[rstest]
+fn test_switch_path_rejects_directory_overlapping_repo(repo: TestRepo) {
+ std::fs::create_dir_all(repo.root_path().join("src")).unwrap();
+
+ // `--path ..` holds the repository and `--path src` sits inside it; with
+ // `--clobber` either would be moved aside, so both are refused outright.
+ for (path, relation) in [("..", "contains"), ("src", "is inside")] {
+ let output = repo
+ .wt_command()
+ .args([
+ "switch",
+ "--create",
+ "feature-o",
+ "--clobber",
+ "--path",
+ path,
+ ])
+ .output()
+ .unwrap();
+ assert!(!output.status.success(), "{path}: {output:?}");
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(stderr.contains(relation), "{path}: {stderr}");
+ }
+
+ assert!(repo.root_path().join("src").is_dir());
+ assert!(repo.root_path().join(".git").exists());
+}
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 6f05f3dec..a20507c92 100644
--- a/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_switch_long.snap
@@ -66,6 +66,11 @@ Usage: wt switch [OPTIONS] [BRANCH] [--
Defaults to default branch. Supports the same shortcuts as the branch argument: ^, @, -, pr:{N}, mr:{N}.
+ --path <PATH>
+ Worktree directory for a new worktree [experimental]
+
+ Overrides the worktree-path template for this worktree. Relative paths resolve from the current directory, as with git worktree add. The branch keeps its own name; afterwards, switch by branch or by path.
+
-x, --execute <EXECUTE>
Program to run after switch
@@ -161,7 +166,7 @@ A new branch tracks the remote branch it starts from only when the two share a n
If the branch already has a worktree, wt switch changes directories to it. Otherwise, it creates one:
1. Runs pre-switch hooks, blocking until complete
-2. Creates worktree at configured path
+2. Creates worktree at configured path (or at --path)
3. Switches to new directory
4. Runs pre-start hooks, blocking until complete
5. Spawns post-start and post-switch hooks in the background
@@ -171,6 +176,16 @@ If the branch already has a worktree, wt switch changes directories to i
  wt switch --create fix --base release # New branch from release
  wt switch --create temp --no-hooks # Skip hooks
+Custom path [experimental]
+
+--path places one worktree outside the worktree-path template, keeping the branch name intact:
+
+  wt switch --create feature/JIRA-1234 --path ../dark-mode
+  wt switch ../dark-mode # Switch by path...
+  wt switch feature/JIRA-1234 # ...or by branch
+
+Worktrunk finds the worktree from git's own records, so only wt step relocate treats it differently: it offers to move the worktree back to the template path.
+
Naming a worktree
Worktrees are addressed by branch name, and every argument that takes one also accepts the path of the worktree itself — resolved after the branch, so a directory never shadows a branch sharing its name. A path names what a branch cannot: a detached worktree, or one of two checkouts of the same branch. Relative paths resolve against -C and a leading ~ against the home directory, so a path worktrunk printed can be pasted back.
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 89a903008..cdb56cdd1 100644
--- a/tests/snapshots/integration__integration_tests__help__help_switch_short.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_switch_short.snap
@@ -53,6 +53,7 @@ Usage: wt switch [OPTIONS] [BRANCH] [--
Options:
-c, --create Create a new branch
-b, --base <BASE> Base branch
+ --path <PATH> Worktree directory for a new worktree [experimental]
-x, --execute <EXECUTE> Program to run after switch
--clobber Remove stale paths at target
--no-cd Skip directory change after switching
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_create_with_path.snap b/tests/snapshots/integration__integration_tests__switch__switch_create_with_path.snap
new file mode 100644
index 000000000..c7ec828c4
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_create_with_path.snap
@@ -0,0 +1,68 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - feature/dark-mode
+ - "--path"
+ - "../dark-mode"
+ 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: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+✓ Created branch feature/dark-mode from main and worktree @ _PARENT_/dark-mode
+↳ To customize worktree locations, run wt config create
+▲ 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_path_existing_branch.snap b/tests/snapshots/integration__integration_tests__switch__switch_path_existing_branch.snap
new file mode 100644
index 000000000..7016f74bd
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_path_existing_branch.snap
@@ -0,0 +1,66 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - switch
+ - existing
+ - "--path"
+ - "../custom-dir"
+ 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: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+✓ Created worktree for existing @ _PARENT_/custom-dir
+▲ 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_path_existing_worktree_elsewhere.snap b/tests/snapshots/integration__integration_tests__switch__switch_path_existing_worktree_elsewhere.snap
new file mode 100644
index 000000000..8b8f76594
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_path_existing_worktree_elsewhere.snap
@@ -0,0 +1,64 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - switch
+ - feature-z
+ - "--path"
+ - "../somewhere-else"
+ 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 -----
+✗ feature-z already has a worktree @ _REPO_.feature-z, not _PARENT_/somewhere-else; to switch to it, run without --path
diff --git a/tests/snapshots/integration__integration_tests__switch__switch_path_occupied.snap b/tests/snapshots/integration__integration_tests__switch__switch_path_occupied.snap
new file mode 100644
index 000000000..ad248e810
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__switch__switch_path_occupied.snap
@@ -0,0 +1,66 @@
+---
+source: tests/integration_tests/switch.rs
+info:
+ program: wt
+ args:
+ - switch
+ - "--create"
+ - feature-y
+ - "--path"
+ - "../occupied"
+ 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 -----
+✗ Directory already exists: _PARENT_/occupied
+↳ To remove manually, run rm -rf _PARENT_/occupied; to overwrite (with backup), run wt switch --create --clobber feature-y --path=../occupied