Skip to content

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

feat: Implement `@` to reference current HEAD

Maximilian Roosc3b462b23566
diff --git a/README.md b/README.md
index aa230649f..96c2dd635 100644
--- a/README.md
+++ b/README.md
@@ -93,12 +93,19 @@ These trade manual control for automation. For fine-grained control, use `git wo
## All Commands
- `wt switch [branch]` - Switch to existing worktree
-- `wt switch --create [branch]` - Create and switch
-- `wt remove` - Remove current, return to main
+- `wt switch --create [branch]` - Create and switch (supports `--base=@` to branch from current HEAD)
+- `wt remove [branch]` - Remove worktree (use `@` for current)
- `wt merge [target]` - Merge, push, cleanup
- `wt list` - Show all worktrees
- `wt config` - Manage configuration
+**Shortcut:** Use `@` to refer to your current HEAD (following git's convention):
+```bash
+wt switch @ # Switch to current branch's worktree
+wt switch --create new-feature --base=@ # Branch from current HEAD
+wt remove @ # Remove current worktree
+```
+
See `wt --help` for details.
<details>
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 6a598aa42..4c4a9a5ac 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -155,33 +155,46 @@ pub fn handle_switch(
force: bool,
no_verify: bool,
config: &WorktrunkConfig,
-) -> Result<SwitchResult, GitError> {
+) -> Result<(SwitchResult, String), GitError> {
let repo = Repository::current();
+ // Resolve "@" to current branch
+ let resolved_branch = repo.resolve_worktree_name(branch)?;
+
+ // Resolve base if provided
+ let resolved_base = if let Some(base_str) = base {
+ Some(repo.resolve_worktree_name(base_str)?)
+ } else {
+ None
+ };
+
// Check for conflicting conditions
- if create && repo.local_branch_exists(branch)? {
+ if create && repo.local_branch_exists(&resolved_branch)? {
return Err(GitError::BranchAlreadyExists {
- branch: branch.to_string(),
+ branch: resolved_branch.clone(),
});
}
// Check if base flag was provided without create flag
- if base.is_some() && !create {
+ if resolved_base.is_some() && !create {
crate::output::progress(format!(
"{WARNING_EMOJI} {WARNING}--base flag is only used with --create, ignoring{WARNING:#}"
))?;
}
// Check if worktree already exists for this branch
- match repo.worktree_for_branch(branch)? {
+ match repo.worktree_for_branch(&resolved_branch)? {
Some(existing_path) if existing_path.exists() => {
// Canonicalize the path for cleaner display
let canonical_existing_path = existing_path.canonicalize().unwrap_or(existing_path);
- return Ok(SwitchResult::ExistingWorktree(canonical_existing_path));
+ return Ok((
+ SwitchResult::ExistingWorktree(canonical_existing_path),
+ resolved_branch,
+ ));
}
Some(_) => {
return Err(GitError::WorktreeMissing {
- branch: branch.to_string(),
+ branch: resolved_branch.clone(),
});
}
None => {}
@@ -196,7 +209,7 @@ pub fn handle_switch(
.to_str()
.ok_or_else(|| GitError::CommandFailed("Invalid UTF-8 in path".to_string()))?;
- let worktree_path = repo_root.join(config.format_path(repo_name, branch));
+ let worktree_path = repo_root.join(config.format_path(repo_name, &resolved_branch));
// Create the worktree
// Build git worktree add command
@@ -216,12 +229,12 @@ pub fn handle_switch(
// Build args based on whether we're creating or checking out
if create {
args.push("-b");
- args.push(branch);
+ args.push(&resolved_branch);
if let Some(ref base_branch) = resolved_base {
args.push(base_branch);
}
} else {
- args.push(branch);
+ args.push(&resolved_branch);
}
repo.run_command(&args)
@@ -235,7 +248,8 @@ pub fn handle_switch(
// Execute post-create commands (sequential, blocking)
// Note: If user declines, continue anyway - worktree already created
if !no_verify
- && let Err(e) = execute_post_create_commands(&worktree_path, &repo, config, branch, force)
+ && let Err(e) =
+ execute_post_create_commands(&worktree_path, &repo, config, &resolved_branch, force)
{
// Only treat CommandNotApproved as non-fatal (user declined)
// Other errors should still fail
@@ -247,27 +261,37 @@ pub fn handle_switch(
// Note: post-start commands are spawned AFTER success message is shown
// (see main.rs switch handler for temporal locality)
- Ok(SwitchResult::CreatedWorktree {
- path: worktree_path,
- created_branch: create,
- base_branch: resolved_base,
- })
+ Ok((
+ SwitchResult::CreatedWorktree {
+ path: worktree_path,
+ created_branch: create,
+ base_branch: resolved_base,
+ },
+ resolved_branch,
+ ))
}
pub fn handle_remove(worktree_name: Option<&str>) -> Result<RemoveResult, GitError> {
- // Show progress immediately, before slow validation
+ let repo = Repository::current();
+
+ // Resolve "@" to current branch early so progress message shows resolved name
+ let resolved_name = if let Some(name) = worktree_name {
+ Some(repo.resolve_worktree_name(name)?)
+ } else {
+ None
+ };
+
+ // Show progress with resolved name
let cyan_bold = CYAN.bold();
- let progress_msg = if let Some(b) = worktree_name {
+ let progress_msg = if let Some(ref b) = resolved_name {
format!("πŸ”„ {CYAN}Removing worktree for {cyan_bold}{b}{cyan_bold:#}...{CYAN:#}")
} else {
format!("πŸ”„ {CYAN}Removing worktree...{CYAN:#}")
};
crate::output::progress(progress_msg)?;
- let repo = Repository::current();
-
// Two modes: remove current worktree vs. remove by name
- match worktree_name {
+ match resolved_name.as_deref() {
None => remove_current_worktree(&repo),
Some(name) => remove_worktree_by_name(&repo, name),
}
@@ -311,7 +335,7 @@ fn remove_current_worktree(repo: &Repository) -> Result<RemoveResult, GitError>
}
}
-/// Remove a worktree by branch name
+/// Remove a worktree by branch name (branch_name should already be resolved)
fn remove_worktree_by_name(repo: &Repository, branch_name: &str) -> Result<RemoveResult, GitError> {
// Find the worktree for this branch
let worktree_path = repo.worktree_for_branch(branch_name)?;
diff --git a/src/git/repository.rs b/src/git/repository.rs
index 61b30bdeb..d79bf4c3f 100644
--- a/src/git/repository.rs
+++ b/src/git/repository.rs
@@ -143,6 +143,23 @@ impl Repository {
}
}
+ /// Resolve a worktree name, expanding "@" to the current branch.
+ ///
+ /// # Arguments
+ /// * `name` - The worktree name to resolve (or "@" for current HEAD)
+ ///
+ /// # Returns
+ /// - `Ok(name)` if not "@"
+ /// - `Ok(current_branch)` if "@" and on a branch
+ /// - `Err(DetachedHead)` if "@" and in detached HEAD state
+ pub fn resolve_worktree_name(&self, name: &str) -> Result<String, GitError> {
+ if name == "@" {
+ self.current_branch()?.ok_or(GitError::DetachedHead)
+ } else {
+ Ok(name.to_string())
+ }
+ }
+
/// Get the default branch name for the repository.
///
/// **Performance note:** This method may trigger a network call on first invocation
diff --git a/src/main.rs b/src/main.rs
index d27dd77be..0c949ed09 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -239,14 +239,14 @@ Create and run command:
Skip hooks during creation:
wt switch --create temp --no-verify")]
Switch {
- /// Branch name or worktree path
+ /// Branch name, worktree path, or '@' for current HEAD
branch: String,
/// Create a new branch
#[arg(short = 'c', long)]
create: bool,
- /// Base branch to create from (only with --create)
+ /// Base branch to create from (only with --create). Use '@' for current HEAD
#[arg(short = 'b', long)]
base: Option<String>,
@@ -307,7 +307,7 @@ Remove multiple worktrees:
Switch to default in primary:
wt remove # (when already in primary worktree)")]
Remove {
- /// Worktree names or branches to remove (defaults to current worktree if none specified)
+ /// Worktree names or branches to remove (use '@' for current, defaults to current if none specified)
worktrees: Vec<String>,
},
@@ -564,11 +564,11 @@ fn main() {
.git_context("Failed to load config")
.and_then(|config| {
// Execute switch operation (creates worktree, runs post-create hooks)
- let result =
+ let (result, resolved_branch) =
handle_switch(&branch, create, base.as_deref(), force, no_verify, &config)?;
// Show success message (temporal locality: immediately after worktree creation)
- handle_switch_output(&result, &branch, execute.is_some())?;
+ handle_switch_output(&result, &resolved_branch, execute.is_some())?;
// Now spawn post-start hooks (background processes, after success message)
// Only run post-start commands when creating a NEW worktree, not when switching to existing
@@ -576,7 +576,11 @@ fn main() {
if !no_verify && let SwitchResult::CreatedWorktree { path, .. } = &result {
let repo = Repository::current();
if let Err(e) = commands::worktree::spawn_post_start_commands(
- path, &repo, &config, &branch, force,
+ path,
+ &repo,
+ &config,
+ &resolved_branch,
+ force,
) {
// Only treat CommandNotApproved as non-fatal (user declined)
// Other errors should still fail
@@ -609,8 +613,11 @@ fn main() {
let mut current = None;
for worktree_name in worktrees.iter() {
+ // Resolve "@" to current branch (fail fast on errors like detached HEAD)
+ let resolved = repo.resolve_worktree_name(worktree_name)?;
+
// Check if this is the current worktree by comparing branch names
- if let Ok(Some(worktree_path)) = repo.worktree_for_branch(worktree_name) {
+ if let Ok(Some(worktree_path)) = repo.worktree_for_branch(&resolved) {
if Some(&worktree_path) == current_worktree.as_ref() {
current = Some(worktree_name);
} else {
diff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snap
index 23ca1ae24..5933fc856 100644
--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpitEqRx/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmprYnT86/test-config.toml
---
success: true
exit_code: 0
@@ -172,8 +172,8 @@ if type -q wt; or set -q WORKTRUNK_BIN
complete -c wt -n '__fish_seen_subcommand_from dev; and __fish_seen_subcommand_from squash' -f -a '(__wt_complete)' -d 'Target branch to squash against (defaults to default branch)'
complete -c wt -n '__fish_seen_subcommand_from dev; and __fish_seen_subcommand_from push' -f -a '(__wt_complete)' -d 'Target branch (defaults to default branch)'
complete -c wt -n '__fish_seen_subcommand_from dev; and __fish_seen_subcommand_from rebase' -f -a '(__wt_complete)' -d 'Target branch to rebase onto (defaults to default branch)'
- complete -c wt -n '__fish_seen_subcommand_from switch' -f -a '(__wt_complete)' -d 'Branch name or worktree path'
- complete -c wt -n '__fish_seen_subcommand_from remove' -f -a '(__wt_complete)' -d 'Worktree names or branches to remove (defaults to current worktree if none specified)'
+ complete -c wt -n '__fish_seen_subcommand_from switch' -f -a '(__wt_complete)' -d 'Branch name, worktree path, or '@' for current HEAD'
+ complete -c wt -n '__fish_seen_subcommand_from remove' -f -a '(__wt_complete)' -d 'Worktree names or branches to remove (use '@' for current, defaults to current if none specified)'
complete -c wt -n '__fish_seen_subcommand_from merge' -f -a '(__wt_complete)' -d 'Target branch to merge into (defaults to default branch)'
complete -c wt -n '__fish_seen_subcommand_from completion' -f -a '(__wt_complete)' -d 'Shell to generate completions for'
complete -c wt -n '__fish_seen_subcommand_from complete' -f -a '(__wt_complete)' -d 'Arguments to complete'
@@ -273,7 +273,7 @@ complete -c wt -n "__fish_wt_using_subcommand list" -l branches -d 'Include bran
complete -c wt -n "__fish_wt_using_subcommand list" -l full -d 'Show CI status, conflict detection, and complete diff statistics'
complete -c wt -n "__fish_wt_using_subcommand list" -s v -l verbose -d 'Enable verbose output (show git commands and debug info)'
complete -c wt -n "__fish_wt_using_subcommand list" -s h -l help -d 'Print help (see more with \'--help\')'
-complete -c wt -n "__fish_wt_using_subcommand switch" -s b -l base -d 'Base branch to create from (only with --create)' -r
+complete -c wt -n "__fish_wt_using_subcommand switch" -s b -l base -d 'Base branch to create from (only with --create). Use \'@\' for current HEAD' -r
complete -c wt -n "__fish_wt_using_subcommand switch" -s x -l execute -d 'Execute command after switching' -r
complete -c wt -n "__fish_wt_using_subcommand switch" -s c -l create -d 'Create a new branch'
complete -c wt -n "__fish_wt_using_subcommand switch" -s f -l force -d 'Skip confirmation prompt'
diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
index 1b802f2fd..cf3d1d834 100644
--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap
+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpxgY3i2/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpacy9En/test-config.toml
---
success: true
exit_code: 0
@@ -311,8 +311,8 @@ json\:"Machine-readable JSON with display fields (includes styled unicode for re
;;
(switch)
_arguments "${_arguments_options[@]}" : \
-'-b+[Base branch to create from (only with --create)]:BASE:_default' \
-'--base=[Base branch to create from (only with --create)]:BASE:_default' \
+'-b+[Base branch to create from (only with --create). Use '\''@'\'' for current HEAD]:BASE:_default' \
+'--base=[Base branch to create from (only with --create). Use '\''@'\'' for current HEAD]:BASE:_default' \
'-x+[Execute command after switching]:EXECUTE:_default' \
'--execute=[Execute command after switching]:EXECUTE:_default' \
'-c[Create a new branch]' \
@@ -324,7 +324,7 @@ _arguments "${_arguments_options[@]}" : \
'--verbose[Enable verbose output (show git commands and debug info)]' \
'-h[Print help]' \
'--help[Print help]' \
-':branch -- Branch name or worktree path:_default' \
+':branch -- Branch name, worktree path, or '\''@'\'' for current HEAD:_default' \
&& ret=0
;;
(remove)
@@ -333,7 +333,7 @@ _arguments "${_arguments_options[@]}" : \
'--verbose[Enable verbose output (show git commands and debug info)]' \
'-h[Print help]' \
'--help[Print help]' \
-'*::worktrees -- Worktree names or branches to remove (defaults to current worktree if none specified):_default' \
+'*::worktrees -- Worktree names or branches to remove (use '\''@'\'' for current, defaults to current if none specified):_default' \
&& ret=0
;;
(merge)