Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(errors): report a directory holding no worktree as a directory (#3773)
Maximilian Roosf3ea2fd598d8
diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex 93235f01b..8da88b4d1 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -792,8 +792,10 @@ pub fn handle_state_get((None, Some(sha)) => BranchRef::remote_branch(&branch_name, sha),(None, None) => {return Err(worktrunk::git::GitError::BranchNotFound {+ // Offering `--create` for a name git rejects sends the+ // user to a command that fails.+ show_create_hint: worktrunk::git::is_valid_branch_name(&branch_name),branch: branch_name,- show_create_hint: true,last_fetch_ago: None,pr_mr_platform: repo.detect_ref_type(),}diff --git a/src/commands/context.rs b/src/commands/context.rsindex fd3953ca0..b45252bd6 100644--- a/src/commands/context.rs+++ b/src/commands/context.rs@@ -113,6 +113,7 @@ impl CommandEnv {self.branch.as_deref().ok_or_else(|| {worktrunk::git::GitError::DetachedHead {action: Some(action.into()),+ worktree: None,}.into()})diff --git a/src/commands/remove.rs b/src/commands/remove.rsindex abdfc39c3..59a4e295e 100644--- a/src/commands/remove.rs+++ b/src/commands/remove.rs@@ -126,7 +126,19 @@ fn validate_remove_targets(// otherwise (see its shared-branch handling).RemoveTarget::WorktreePath(path_canonical)}- ResolvedWorktree::BranchOnly { branch } => RemoveTarget::BranchOnly(branch),+ // Resolution tried the argument as a branch and as a worktree path+ // and matched neither, so a directory sitting there is a leftover+ // skeleton rather than anything wt can remove. Reported here, where+ // the user's own token is still in hand — the picker and `wt step+ // prune` reach `prepare_worktree_removal` with a branch read off a+ // row, which is nobody's typed path.+ ResolvedWorktree::BranchOnly { branch } => match repo.path_selector_error(&branch) {+ Some(err) => {+ plans.record_error(err.into());+ continue;+ }+ None => RemoveTarget::BranchOnly(branch),+ },};match repo.prepare_worktree_removal(diff --git a/src/commands/step/promote.rs b/src/commands/step/promote.rsindex 1c63302b3..ffec9b1a7 100644--- a/src/commands/step/promote.rs+++ b/src/commands/step/promote.rs@@ -194,6 +194,7 @@ fn resolve_target_branch(branch: Option<&str>, repo: &Repository) -> anyhow::Rescurrent_wt.branch()?.ok_or_else(|| {GitError::DetachedHead {action: Some("promote".into()),+ worktree: None,}.into()})@@ -317,6 +318,7 @@ pub fn handle_promote(branch: Option<&str>) -> anyhow::Result<PromoteResult> {.clone().ok_or_else(|| GitError::DetachedHead {action: Some("promote".into()),+ worktree: Some(main_path.clone()),})?;// Resolve the branch to promote (default_branch computed lazily, only when needed)diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 1d6edec06..fe050836b 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -691,7 +691,10 @@ fn validate_worktree_creation({return Err(GitError::BranchNotFound {branch: branch.to_string(),- show_create_hint: true,+ // Offering `--create` for a name git rejects sends the user to a+ // command that fails; the argument was a path spelling, whether or+ // not a directory happens to sit at it.+ show_create_hint: worktrunk::git::is_valid_branch_name(branch),last_fetch_ago: format_last_fetch_ago(repo),pr_mr_platform: repo.detect_ref_type(),}@@ -851,16 +854,22 @@ fn plan_switch(// argument is the name of a branch that does not exist yet, and not when// Phase 1 rewrote the argument (a shortcut, `pr:`/`mr:`, a stripped remote// prefix), which is exactly when the literal token would be a nonsense path.- if !create- && target.branch == branch- && let Some((path, wt_branch)) = repo.worktree_at_input_path(branch)?- {- let canonical = canonicalize(&path).unwrap_or_else(|_| path.clone());- return Ok(SwitchPlan::Existing {- path: canonical,- branch: wt_branch,- new_previous,- });+ if !create && target.branch == branch {+ if let Some((path, wt_branch)) = repo.worktree_at_input_path(branch)? {+ let canonical = canonicalize(&path).unwrap_or_else(|_| path.clone());+ return Ok(SwitchPlan::Existing {+ path: canonical,+ branch: wt_branch,+ 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.+ if let Some(err) = repo.path_selector_error(branch) {+ return Err(err.into());+ }}// Phase 3: Compute expected path (only needed for create)diff --git a/src/git/error.rs b/src/git/error.rsindex 7a95e27f5..836662c1d 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -372,7 +372,7 @@ impl SwitchSuggestionCtx {////// // A typed error converts into a type-erased one (in real code, into `anyhow::Error`)./// let err: Box<dyn std::error::Error> =-/// GitError::DetachedHead { action: Some("merge".into()) }.into();+/// GitError::DetachedHead { action: Some("merge".into()), worktree: None }.into();////// // Recover the typed error to branch on the variant./// if let Some(GitError::BranchAlreadyExists { branch }) = err.downcast_ref::<GitError>() {@@ -382,8 +382,17 @@ impl SwitchSuggestionCtx {#[derive(Debug, Clone)]pub enum GitError {// Git state errors+ /// A worktree is not on a branch, so a command needing one refuses.+ ///+ /// `worktree` names the detached worktree when that isn't the one the+ /// command ran in, and changes only the hint. `git switch` acts on the tree+ /// it runs in, so an unqualified suggestion points at the tree the user is+ /// standing in — the wrong one when the detached worktree is a target they+ /// named (`wt merge ../other`). [`GitError::OperationInProgress`] carries+ /// `branch` for the same reason.DetachedHead {action: Option<String>,+ worktree: Option<PathBuf>,},/// A worktree is partway through a git operation, so a command that/// rewrites or moves commits (`wt merge`, `wt step rebase`,@@ -589,6 +598,18 @@ pub enum GitError {WorktreeSelectorNotFound {selector: String,},+ /// A directory that holds no worktree, named by a selector no branch could+ /// answer to.+ ///+ /// The third member of the family: [`GitError::WorktreeNotFound`] is a+ /// branch without a checkout, [`GitError::WorktreeSelectorNotFound`] a+ /// token that could have been either, and this one a directory `wt list`+ /// will never show and only the user can delete. Built solely by+ /// [`Repository::path_selector_error`](crate::git::Repository::path_selector_error),+ /// which owns every test that has to pass before this claim is safe.+ WorktreeNotFoundAtPath {+ path: PathBuf,+ },/// --create flag used with pr:/mr: syntax (conflict - branch already exists)RefCreateConflict {ref_type: RefType,@@ -658,7 +679,7 @@ impl GitError {match self {GitError::WithSwitchSuggestion { source, .. } => source.title(),- GitError::DetachedHead { action } => match action {+ GitError::DetachedHead { action, .. } => match action {Some(action) => cformat!("Cannot {action}: not on a branch (detached HEAD)"),None => "Not on a branch (detached HEAD)".to_string(),},@@ -850,6 +871,11 @@ impl GitError {cformat!("No branch or worktree named <bold>{selector}</>")}+ GitError::WorktreeNotFoundAtPath { path } => {+ let path_display = format_path_for_display(path);+ cformat!("No worktree @ <bold>{path_display}</>")+ }+GitError::RefCreateConflict {ref_type,number,@@ -907,14 +933,20 @@ impl GitError {source.write_render_with_ctx(f, Some(ctx))}- GitError::DetachedHead { .. } => {+ GitError::DetachedHead { worktree, .. } => {let title = self.title();+ let switch_cmd = match worktree {+ Some(path) => {+ format!("git -C {} switch <branch>", format_path_for_display(path))+ }+ None => "git switch <branch>".to_string(),+ };write!(f,"{}\n{}",error_message(&title),hint_message(cformat!(- "To switch to a branch, run <underline>git switch <<branch>></>"+ "To switch to a branch, run <underline>{switch_cmd}</>")))}@@ -1400,6 +1432,19 @@ impl GitError {)}+ GitError::WorktreeNotFoundAtPath { .. } => {+ let title = self.title();+ let list_cmd = suggest_command("list", &[], &[]);+ write!(+ f,+ "{}\n{}",+ error_message(&title),+ hint_message(cformat!(+ "The directory exists but is not a worktree; to list worktrees, run <underline>{list_cmd}</>"+ ))+ )+ }+GitError::RefCreateConflict {ref_type, number, ..} => {@@ -1920,7 +1965,11 @@ mod tests {Some(5));assert_eq!(- anyhow::Error::from(GitError::DetachedHead { action: None }).exit_code(),+ anyhow::Error::from(GitError::DetachedHead {+ action: None,+ worktree: None+ })+ .exit_code(),None);@@ -2048,7 +2097,11 @@ mod tests {.into();assert!(!render_anyhow(&add_hook_skip_hint(err)).contains("--no-hooks"));- let err: anyhow::Error = GitError::DetachedHead { action: None }.into();+ let err: anyhow::Error = GitError::DetachedHead {+ action: None,+ worktree: None,+ }+ .into();assert!(!render_anyhow(&add_hook_skip_hint(err)).contains("--no-hooks"));let err: anyhow::Error = GitError::Other {@@ -2085,11 +2138,11 @@ mod tests {@"Rebase onto main incomplete");assert_snapshot!(- GitError::DetachedHead { action: Some("merge".into()) }.to_string(),+ GitError::DetachedHead { action: Some("merge".into()), worktree: None }.to_string(),@"Cannot merge: not on a branch (detached HEAD)");assert_snapshot!(- GitError::DetachedHead { action: None }.to_string(),+ GitError::DetachedHead { action: None, worktree: None }.to_string(),@"Not on a branch (detached HEAD)");@@ -2594,6 +2647,7 @@ mod tests {// Non-switch-suggestion errors should be completely unaffected by the wrapperlet inner = GitError::DetachedHead {action: Some("merge".into()),+ worktree: None,};let wrapped = GitError::WithSwitchSuggestion {source: Box::new(inner.clone()),diff --git a/src/git/mod.rs b/src/git/mod.rsindex fed17e2ec..47659d9bf 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -81,7 +81,7 @@ pub use repository::sha_cache;pub use repository::{Branch, BranchDiffSpec, CommitMessageDetail, InProgressOperation, IntegrationTargets,RefSnapshot, Repository, ResolvedWorktree, TempIndex, WorkingTree, duplicated_branches,- resolve_input_path, select_comparison_base, set_base_path,+ is_valid_branch_name, resolve_input_path, select_comparison_base, set_base_path,};pub use url::parse_owner_repo;pub use url::{GitRemoteUrl, GitRepoInfo, GitRepoProvider};diff --git a/src/git/repository/branch.rs b/src/git/repository/branch.rsindex 831094b0f..d0b03b2f2 100644--- a/src/git/repository/branch.rs+++ b/src/git/repository/branch.rs@@ -2,6 +2,34 @@use super::Repository;+/// Whether `refs/heads/<name>` is a well-formed ref, which is what a branch is.+///+/// A worktree selector is tried as a branch first and as a path second (see+/// [`Repository::resolve_worktree`](super::Repository::resolve_worktree)), so+/// when neither matches, the error has to pick which of the two the user meant.+/// This answers it: a name git could never put under `refs/heads/` — an+/// absolute path, `~/…`, `./…`, a Windows drive letter — was only ever a path,+/// and reporting it as a missing branch sends the user to `wt list --branches`+/// for something that would never appear there.+///+/// The rules are git's own, as `git check-ref-format refs/heads/<name>` applies+/// them; `branch_name_matches_git_check_ref_format` pins each one against that+/// command. In-process because it runs wherever a selector fails to resolve,+/// where a subprocess would buy nothing.+pub fn is_valid_branch_name(name: &str) -> bool {+ if name.is_empty() || name.ends_with('.') || name.contains("..") || name.contains("@{") {+ return false;+ }+ if name.chars().any(|c| {+ c.is_ascii_control() || matches!(c, ' ' | '~' | '^' | ':' | '?' | '*' | '[' | '\\')+ }) {+ return false;+ }+ // An empty component covers a leading `/`, a trailing `/`, and `//`.+ name.split('/')+ .all(|part| !part.is_empty() && !part.starts_with('.') && !part.ends_with(".lock"))+}+/// A handle for running git commands on a specific branch.////// This type holds a reference to [`Repository`] and a branch name.diff --git a/src/git/repository/config.rs b/src/git/repository/config.rsindex d0b9f03a9..4eefeceda 100644--- a/src/git/repository/config.rs+++ b/src/git/repository/config.rs@@ -9,6 +9,7 @@ use color_print::cformat;use crate::config::ProjectConfig;use crate::git::CommandError;+use crate::path::format_path_for_display;use super::{DefaultBranchName, GitError, Repository};@@ -526,17 +527,21 @@ impl Repository {////// `resolved` is `target` after shortcut expansion; an expansion means the/// literal token was a symbol rather than a path.- fn target_branch_at_path(+ ///+ /// The worktree is returned whole rather than just its branch, so `None`+ /// means "nothing registered here" alone. A detached worktree — `Some` with+ /// no branch — is the case that makes the distinction load-bearing: it is+ /// reachable by path and by nothing else, so folding it into `None` would+ /// let a caller report a worktree `wt list` shows as absent.+ fn target_worktree_at_path(&self,target: Option<&str>,resolved: &str,- ) -> anyhow::Result<Option<String>> {+ ) -> anyhow::Result<Option<(PathBuf, Option<String>)>> {let Some(target) = target.filter(|t| *t == resolved) else {return Ok(None);};- Ok(self- .worktree_at_input_path(target)?- .and_then(|(_, branch)| branch))+ self.worktree_at_input_path(target)}/// Resolve and validate a target that must be a branch.@@ -552,8 +557,21 @@ impl Repository {pub fn require_target_branch(&self, target: Option<&str>) -> anyhow::Result<String> {let branch = self.resolve_target_branch(target)?;if !self.branch(&branch).exists()? {- if let Some(from_path) = self.target_branch_at_path(target, &branch)? {- return Ok(from_path);+ match self.target_worktree_at_path(target, &branch)? {+ Some((_, Some(from_path))) => return Ok(from_path),+ // A worktree is there, so the path resolved — it just has no+ // branch to be the target of a merge or a push.+ Some((path, None)) => {+ return Err(GitError::DetachedHead {+ action: Some(cformat!(+ "use <bold>{}</> as a target",+ format_path_for_display(&path)+ )),+ worktree: Some(path),+ }+ .into());+ }+ None => {}}if target.is_none() {if self.is_unborn_branch(&branch) {@@ -561,9 +579,17 @@ impl Repository {}return Err(GitError::StaleDefaultBranch { branch }.into());}+ // Nothing is registered at the path, which is what this error+ // asserts; the arms above consumed both worktree cases.+ if let Some(err) = self.path_selector_error(&branch) {+ return Err(err.into());+ }return Err(GitError::BranchNotFound {+ // Offering `--create` for a name git rejects sends the user to+ // a command that fails; the argument was a path spelling,+ // whether or not a directory happens to sit at it.+ show_create_hint: super::is_valid_branch_name(&branch),branch,- show_create_hint: true,last_fetch_ago: None,pr_mr_platform: self.detect_ref_type(),}@@ -584,9 +610,11 @@ impl Repository {pub fn require_target_ref(&self, target: Option<&str>) -> anyhow::Result<String> {let reference = self.resolve_target_branch(target)?;if !self.ref_exists(&reference)? {- if let Some(from_path) = self.target_branch_at_path(target, &reference)? {+ if let Some((_, Some(from_path))) = self.target_worktree_at_path(target, &reference)? {return Ok(from_path);}+ // No path claim here: a commit-ish is spelled in a wider vocabulary+ // than a worktree selector, and `ReferenceNotFound` names all of it.if target.is_none() {if self.is_unborn_branch(&reference) {return Err(GitError::UnbornDefaultBranch { branch: reference }.into());diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex e760d3ed5..dcbd12ac3 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -161,6 +161,7 @@ mod worktrees;// Re-export WorkingTree, Branch, IntegrationTargets, and RefSnapshotpub use branch::Branch;+pub use branch::is_valid_branch_name;pub use diff::CommitMessageDetail;pub use integration::{BranchDiffSpec, IntegrationTargets, select_comparison_base};pub use ref_snapshot::RefSnapshot;@@ -1274,6 +1275,7 @@ impl Repository {self.current_worktree().branch()?.ok_or_else(|| {GitError::DetachedHead {action: Some(action.into()),+ worktree: None,}.into()})diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rsindex 63e233e81..6a8b40d32 100644--- a/src/git/repository/tests.rs+++ b/src/git/repository/tests.rs@@ -1447,21 +1447,362 @@ fn resolve_worktree_falls_through_to_branch_only() {let test = TestRepo::with_initial_commit();- let resolved = test.repo.resolve_worktree("../nowhere").unwrap();+ let resolved = test.repo.resolve_worktree("nowhere").unwrap();let ResolvedWorktree::BranchOnly { branch } = resolved else {panic!("an unmatched selector should resolve to branch-only");};- assert_eq!(branch, "../nowhere");+ assert_eq!(branch, "nowhere");// A selector matching nothing names neither, so the error claims neither —- // suggesting `wt switch ../nowhere` to create a worktree would only fail.- let err = test.repo.require_worktree("../nowhere").unwrap_err();+ // suggesting `wt switch nowhere` to create a worktree would only fail.+ let err = test.repo.require_worktree("nowhere").unwrap_err();assert!(err.to_string().contains("No branch or worktree named"),"expected an unmatched-selector error, got: {err}");}+/// A directory holding no worktree is reported as the directory it is, rather+/// than as a missing branch — the `wt list --branches` the branch error suggests+/// would never list it.+///+/// Both halves of the test are exercised, since either alone over-claims: a+/// selector git could accept as a branch name keeps the branch error even with a+/// directory beside it, and a selector it could not keeps the branch error when+/// nothing is on disk.+#[test]+fn directory_holding_no_worktree_is_reported_as_a_directory() {+ use crate::git::{ErrorExt, ResolvedWorktree};+ use crate::testing::TestRepo;++ let test = TestRepo::with_initial_commit();+ let ghost = test.root_path().join("ghost");+ std::fs::create_dir(&ghost).unwrap();++ // Resolution still falls through to branch-only; the selector's shape is+ // read where the failure is reported, not where it is resolved.+ let selector = ghost.to_str().unwrap();+ let resolved = test.repo.resolve_worktree(selector).unwrap();+ assert!(matches!(resolved, ResolvedWorktree::BranchOnly { .. }));++ let rendered = test+ .repo+ .require_worktree(selector)+ .unwrap_err()+ .render_diagnostic()+ .unwrap();+ assert!(+ rendered.contains("No worktree @") && rendered.contains("is not a worktree"),+ "expected a directory-holds-no-worktree error, got: {rendered}"+ );++ // A branch is what a state key names, so a directory is refused rather than+ // silently stored as one.+ let err = test+ .repo+ .require_selected_branch(selector, "set marker")+ .unwrap_err();+ assert!(+ err.to_string().contains("No worktree @"),+ "expected a directory selector to be refused as a branch, got: {err}"+ );++ // Nothing on disk: wt cannot tell a mistyped path from a mistyped branch,+ // so the error claims neither.+ let err = test+ .repo+ .require_worktree(ghost.join("deeper").to_str().unwrap())+ .unwrap_err();+ assert!(+ err.to_string().contains("No branch or worktree named"),+ "expected an unmatched-selector error, got: {err}"+ );++ // A name git would accept as a branch is a branch, whatever sits beside it:+ // `wt remove docs` means the branch even when `docs/` is right there.+ std::fs::create_dir(test.root_path().join("docs")).unwrap();+ let err = test.repo.require_worktree("docs").unwrap_err();+ assert!(+ err.to_string().contains("No branch or worktree named"),+ "a directory must not shadow a branch name, got: {err}"+ );++ // Somebody's checkout, which `list_worktrees` cannot see because it belongs+ // to another repository. worktrunk gathers every repo and worktree into one+ // parent, so a sibling is one `../` from any command, and calling a live+ // one "not a worktree" reads as an invitation to delete it.+ let parent = test.root_path().parent().unwrap();+ let sibling = parent.join("sibling");+ std::fs::create_dir_all(sibling.join(".git")).unwrap();++ // And a bare repository, which is the git directory rather than holding+ // one — worktrunk's bare layout sits it among the worktrees it serves, so+ // it is as reachable as they are, and it holds every object.+ let bare = parent.join("project.bare");+ std::fs::create_dir_all(bare.join("objects")).unwrap();+ std::fs::create_dir_all(bare.join("refs")).unwrap();+ std::fs::write(bare.join("HEAD"), "ref: refs/heads/main\n").unwrap();++ for checkout in [&sibling, &bare] {+ assert!(+ test.repo+ .path_selector_error(checkout.to_str().unwrap())+ .is_none(),+ "a directory holding git data must not be called a leftover: {}",+ checkout.display()+ );+ }++ // A lone `HEAD` is not git data — the skeleton keeps its report.+ let decoy = test.root_path().join("decoy");+ std::fs::create_dir(&decoy).unwrap();+ std::fs::write(decoy.join("HEAD"), "").unwrap();+ assert!(+ test.repo+ .path_selector_error(decoy.to_str().unwrap())+ .is_some(),+ "a directory that merely contains a HEAD file is still a leftover"+ );+}++/// A `.git` nobody can follow still marks somebody's checkout.+///+/// `Path::exists` answers `false` for every error alike and resolves symlinks,+/// so both shapes here would read as "no git data" — and both are ways the+/// bystander of a repo-wide prune presents: a `.git` symlink is how a git+/// directory is put on another filesystem, which is the volume that gets+/// unmounted.+#[test]+fn an_unresolvable_git_entry_still_counts_as_git_data() {+ use crate::testing::TestRepo;++ let test = TestRepo::with_initial_commit();+ let parent = test.root_path().parent().unwrap();++ let dangling_file = parent.join("bystander-file");+ std::fs::create_dir_all(&dangling_file).unwrap();+ std::fs::write(dangling_file.join(".git"), "gitdir: /gone/worktrees/x\n").unwrap();++ let checkouts = [dangling_file];++ #[cfg(unix)]+ let checkouts = {+ let dangling_link = parent.join("bystander-link");+ std::fs::create_dir_all(&dangling_link).unwrap();+ std::os::unix::fs::symlink("/gone/worktrees/x", dangling_link.join(".git")).unwrap();+ [checkouts[0].clone(), dangling_link]+ };++ for checkout in checkouts {+ assert!(+ test.repo+ .path_selector_error(checkout.to_str().unwrap())+ .is_none(),+ "an unresolvable .git must still withhold the claim: {}",+ checkout.display()+ );+ }+}++/// A detached worktree is reachable by its path and by nothing else, so a merge+/// target naming one is reported as detached rather than as absent — the claim+/// `wt list` would contradict.+#[test]+fn detached_worktree_target_is_reported_as_detached() {+ use crate::git::ErrorExt;+ use crate::testing::TestRepo;++ let mut test = TestRepo::with_initial_commit();+ let worktree_path = test.add_worktree("feature");+ test.detach_head_in_worktree("feature");+ let selector = worktree_path.to_str().unwrap();++ let err = test.repo.require_target_branch(Some(selector)).unwrap_err();+ let rendered = err.to_string();+ assert!(+ rendered.contains("detached") && !rendered.contains("No worktree @"),+ "expected a detached-target error, got: {rendered}"+ );++ // The detached worktree is the one the argument named, so the hint has to+ // send the user there: `git switch` run where they are standing would+ // switch the wrong tree.+ let hint = err.render_diagnostic().expect("typed diagnostic");+ let quoted = crate::path::format_path_for_display(&worktree_path);+ assert!(+ hint.contains(&format!("git -C {quoted} switch")),+ "expected the hint to name the target worktree, got: {hint}"+ );++ // A commit-ish target is spelled in a wider vocabulary than a worktree+ // selector, so it claims nothing about paths either way.+ if let Err(err) = test.repo.require_target_ref(Some(selector)) {+ assert!(+ !err.to_string().contains("No worktree @"),+ "a registered worktree must never be reported as absent, got: {err}"+ );+ }+}++/// The directory claim checks for itself that nothing is registered at the path,+/// rather than trusting the caller to have looked.+///+/// A shortcut is the case that breaks the trust: `resolve_worktree` skips its+/// path lookup whenever one rewrote the argument, so `-` expanding to a+/// worktree's own path arrives having matched nothing at all.+#[test]+fn path_selector_error_checks_for_a_registered_worktree() {+ use crate::testing::TestRepo;++ let mut test = TestRepo::with_initial_commit();+ let worktree_path = test.add_worktree("feature");+ let selector = worktree_path.to_str().unwrap();++ assert!(+ test.repo.path_selector_error(selector).is_none(),+ "a registered worktree's own path must never be reported as holding none"+ );++ // Reached through the shortcut, which is the route with no prior lookup.+ test.repo.set_switch_previous(Some(selector)).unwrap();+ let err = test.repo.require_worktree("-").unwrap_err();+ assert!(+ !err.to_string().contains("No worktree @"),+ "an expanded shortcut naming a live worktree must not report it as absent, got: {err}"+ );+}++/// A merge target naming a directory that holds no worktree gets the same+/// answer as every other worktree argument, rather than an offer to create a+/// branch git would reject.+#[test]+fn directory_merge_target_is_reported_as_a_directory() {+ use crate::git::ErrorExt;+ use crate::testing::TestRepo;++ let test = TestRepo::with_initial_commit();+ let ghost = test.root_path().join("ghost");+ std::fs::create_dir(&ghost).unwrap();++ let rendered = test+ .repo+ .require_target_branch(Some(ghost.to_str().unwrap()))+ .unwrap_err()+ .render_diagnostic()+ .unwrap();+ assert!(+ rendered.contains("No worktree @") && !rendered.contains("--create"),+ "expected a directory-holds-no-worktree error, got: {rendered}"+ );++ // Revision syntax is no more a branch name than a path is, and naming no+ // directory is what keeps it out of the path claim.+ for revspec in ["HEAD@{1}", "main^", "v1.0..v2.0", "pr:5"] {+ let err = test+ .repo+ .require_target_branch(Some(revspec))+ .expect_err(revspec);+ assert!(+ !err.to_string().contains("No worktree @"),+ "{revspec} must not be reported as a path, got: {err}"+ );+ }+}++/// A mistyped path names no directory, so it keeps the branch error — but the+/// offer to create a branch goes, because git would reject the name whether or+/// not anything sits at the path.+#[test]+fn a_path_spelling_is_never_offered_as_a_branch_to_create() {+ use crate::git::ErrorExt;+ use crate::testing::TestRepo;++ let test = TestRepo::with_initial_commit();++ for selector in ["../repo.mistyped", "./nowhere", "/abs/nowhere"] {+ let rendered = test+ .repo+ .require_target_branch(Some(selector))+ .unwrap_err()+ .render_diagnostic()+ .unwrap();+ assert!(+ !rendered.contains("--create"),+ "{selector} must not be offered to --create, got: {rendered}"+ );+ }++ // A name git would take keeps the offer.+ let rendered = test+ .repo+ .require_target_branch(Some("new-branch"))+ .unwrap_err()+ .render_diagnostic()+ .unwrap();+ assert!(+ rendered.contains("--create"),+ "a usable branch name keeps the create hint, got: {rendered}"+ );+}++/// The branch-name rules are git's, so git decides them.+#[test]+fn branch_name_matches_git_check_ref_format() {+ use super::is_valid_branch_name;+ use crate::shell_exec::Cmd;++ let names = [+ // Ordinary branch names, including the ones that look like paths.+ "main",+ "feature/auth",+ "release/1.2/rc",+ "-x",+ "@",+ "nowhere",+ // The `.lock` rule is case-sensitive and non-ASCII is fine — both are+ // easy to over-reject when re-deriving the rules from prose.+ "a.LOCK",+ "café",+ // Path spellings.+ "/abs/path/ghost",+ "./ghost",+ "../ghost",+ "~/code/myproject",+ "ghost/",+ ".claude/worktrees/ghost",+ "C:\\code\\myproject",+ // The remaining ref-format rules, one name each.+ "",+ "a//b",+ "a..b",+ "a.lock",+ "a.lock/b",+ "a.",+ "a@{b",+ "a b",+ "a\tb",+ "a\u{7f}b",+ "a~b",+ "a^b",+ "a:b",+ "a?b",+ "a*b",+ "a[b",+ ];++ for name in names {+ let out = crate::testing::configure_git_env(Cmd::new("git"))+ .args(["check-ref-format", &format!("refs/heads/{name}")])+ .run()+ .unwrap();+ assert_eq!(+ is_valid_branch_name(name),+ out.status.success(),+ "disagreed with git check-ref-format on {name:?}"+ );+ }+}+/// A branch that exists without a checkout is the one case where offering to/// create a worktree is right, so it keeps the distinct message and hint.#[test]diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rsindex 4476c9339..49d7fdf8e 100644--- a/src/git/repository/worktrees.rs+++ b/src/git/repository/worktrees.rs@@ -8,7 +8,9 @@ use anyhow::Context as _;use color_print::cformat;use dunce::canonicalize;-use super::{GitError, Repository, ResolvedWorktree, WorktreeInfo, resolve_input_path};+use super::{+ GitError, Repository, ResolvedWorktree, WorktreeInfo, is_valid_branch_name, resolve_input_path,+};use crate::path::{format_path_for_display, paths_match};use crate::styling::{eprintln, format_with_gutter, hint_message, suggest_command, warning_message,@@ -269,6 +271,7 @@ impl Repository {"@" => self.current_worktree().branch()?.ok_or_else(|| {GitError::DetachedHead {action: Some("resolve @ to current branch".into()),+ worktree: None,}.into()}),@@ -313,6 +316,13 @@ impl Repository {/// relative to `-C` (see [`resolve_input_path`])/// 5. otherwise the branch alone, which may or may not exist///+ /// A path that named no worktree lands in `BranchOnly` too, since step 5+ /// asks nothing of the token — as does a shortcut whose expansion matched+ /// nothing, which never reached step 4 at all. What the selector could have+ /// meant is worked out where the failure is reported, by+ /// [`path_selector_error`](Self::path_selector_error); the callers that go+ /// on to succeed never need the answer.+ ////// # Returns/// - `Worktree { path, branch }` — `branch` is `None` for a detached worktree/// - `BranchOnly { branch }` when nothing is checked out under that name@@ -375,13 +385,19 @@ impl Repository {ResolvedWorktree::Worktree {branch: Some(branch),..- }- | ResolvedWorktree::BranchOnly { branch } => Ok(branch),+ } => Ok(branch),+ // A path selector reaches here only when it named no worktree, and+ // it can't be the branch the caller is about to key state by.+ ResolvedWorktree::BranchOnly { branch } => match self.path_selector_error(&branch) {+ Some(err) => Err(err.into()),+ None => Ok(branch),+ },ResolvedWorktree::Worktree { path, branch: None } => Err(GitError::DetachedHead {action: Some(cformat!("{action} — <bold>{}</> is detached",format_path_for_display(&path))),+ worktree: Some(path),}.into()),}@@ -404,8 +420,79 @@ impl Repository {}}+ /// The not-found error for a selector naming a directory that holds no+ /// worktree — the skeleton an interrupted create or remove leaves behind.+ ///+ /// Every argument naming a worktree is tried as a branch first and as a+ /// path second, so each place that reports "no such thing" has to say which+ /// of the two it was looking for. Answering that takes all four tests+ /// below, and no three of them are enough:+ ///+ /// - Git could never accept the selector as a branch name, so branch-first+ /// never had a candidate. Without this, revision syntax reports as a+ /// path: `~`, `^`, `:` and `@{` are ordinary vocabulary for naming a+ /// commit as well as characters no branch name may hold.+ /// - A directory is there to name, which is what makes "the user meant a+ /// path" more than a guess. Without this, a name shadows a branch:+ /// `wt remove docs` means the branch even when `docs/` sits beside it.+ /// - No worktree of this repository is registered there, which is half of+ /// what the error asserts. A detached worktree is reachable by its path+ /// and by nothing else, so without this the message contradicts the+ /// `wt list` its hint points at. The check is here rather than left to+ /// callers because a caller cannot be relied on to have made it:+ /// `resolve_worktree` skips the path lookup whenever a shortcut rewrote+ /// the argument, so `-` expanding to a worktree's path arrives having+ /// matched nothing.+ /// - Nothing there claims to be a git directory, which is the other half:+ /// `list_worktrees` covers only *this* repository, and worktrunk gathers+ /// every repo and every worktree into one parent, so a sibling's live+ /// checkout is one `../` away from any command. Calling one "not a+ /// worktree" reads as an invitation to delete it, and it may hold+ /// uncommitted work or the only copy of an object. A skeleton is what an+ /// interrupted create or remove leaves, which holds no git data at all+ /// (see `holds_git_data`).+ ///+ /// `None` when any test fails, leaving the caller's own error in place.+ ///+ /// The path is reported as the selector spells it, resolved against `-C`+ /// but not otherwise tidied. A trailing `/` is the reason: `docs/` and+ /// `docs` are the same directory but not the same selector — only the+ /// second finds the branch — and echoing back the spelling that works would+ /// hide the one character that did not. The cost is that a `-C` base and a+ /// `./`-prefixed selector join to a visible `/./`.+ ///+ /// Both hold on Unix only. Rendering runs through `format_path_for_display`+ /// and so through `path_slash`'s `to_slash_lossy`, which is+ /// `to_string_lossy` verbatim there but rebuilds the string from+ /// `Path::components()` on Windows: a trailing `/` is dropped (only a+ /// trailing `\`, the platform separator, survives) and an interior `/./`+ /// collapses. `wt switch docs/` reports `…/docs` there — true of the path,+ /// and missing the character that explains why the selector found no+ /// branch.+ pub fn path_selector_error(&self, selector: &str) -> Option<GitError> {+ if is_valid_branch_name(selector) {+ return None;+ }+ let path = resolve_input_path(selector);+ if !path.is_dir() {+ return None;+ }+ // A failed listing says nothing about what is registered, so it counts+ // against the claim exactly as a match does.+ if !matches!(self.worktree_at_path(&path), Ok(None)) {+ return None;+ }+ if holds_git_data(&path) {+ return None;+ }+ Some(GitError::WorktreeNotFoundAtPath { path })+ }+/// The error for a selector that resolved to a branch with no checkout.fn no_worktree_error(&self, branch: String) -> anyhow::Error {+ if let Some(err) = self.path_selector_error(&branch) {+ return err.into();+ }match self.branch(&branch).exists_locally() {Ok(true) => GitError::WorktreeNotFound { branch }.into(),// A ref lookup that fails says nothing about the branch, so fall@@ -444,6 +531,52 @@ impl Repository {}}+/// Whether `path` is a directory git would find data in — somebody's checkout+/// or repository, rather than a leftover skeleton.+///+/// Two shapes, because a repository is not always inside a working tree:+/// a worktree and a non-bare repo carry a `.git` (a file for the first, a+/// directory for the second), while a bare repo *is* the git directory and so+/// carries none. The second is the one worth spelling out — under worktrunk's+/// bare layout the repository sits among the worktrees it serves, one `../`+/// from any command, and it holds every object.+///+/// The bare test is git's own from `is_git_directory()`: `HEAD`, plus `objects`+/// and `refs` directories. It is deliberately shallow — this decides whether to+/// *withhold* a claim, so a false positive costs a vaguer message and a false+/// negative costs a wrong one.+///+/// Which is why absence has to be established rather than assumed. `Path::exists`+/// answers `false` for every error alike, so a `.git` that cannot be statted —+/// a clone the process may not traverse, a symlink whose target is gone —+/// would read as "no git data" and the message would tell someone their live+/// checkout is theirs to delete. Only a definite `NotFound` counts as nothing+/// being there; anything else keeps the claim withheld.+///+/// A `.git` whose pointer dangles counts too, and following it to check would+/// be the wrong refinement. Two very different directories carry a dangling+/// `.git`: a `git worktree add` that died after writing it, holding nothing+/// else; and a worktree a repo-wide prune unregistered while its volume was+/// unmounted, holding all its files and any uncommitted work (the bystander+/// case [`Repository::prune_worktree_entry`] documents). The pointer cannot+/// tell them apart, so resolving it would license "this is a leftover" over the+/// second.+fn holds_git_data(path: &Path) -> bool {+ // `symlink_metadata` reports on the entry itself, so a symlink counts even+ // when its target is gone, and it surfaces a traversal error instead of+ // swallowing it.+ let no_git_entry = matches!(+ std::fs::symlink_metadata(path.join(".git")),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound+ );+ if !no_git_entry {+ return true;+ }+ // Reached only when that probe succeeded in saying "nothing there", so the+ // directory is readable and the bare shape can be read plainly.+ path.join("HEAD").exists() && path.join("objects").is_dir() && path.join("refs").is_dir()+}+/// Paths of every worktree checked out on `branch`, in git's listing order.////// At most one under normal use; more than one only when the user randiff --git a/tests/integration_tests/git_error_display.rs b/tests/integration_tests/git_error_display.rsindex c908e97a0..49529cad5 100644--- a/tests/integration_tests/git_error_display.rs+++ b/tests/integration_tests/git_error_display.rs@@ -93,6 +93,13 @@ fn worktree_errors_render() {}.render(),),+ (+ "no worktree at a leftover directory",+ GitError::WorktreeNotFoundAtPath {+ path: PathBuf::from("/tmp/repo/.claude/worktrees/ghost"),+ }+ .render(),+ ),("branch not found",GitError::BranchNotFound {@@ -187,12 +194,27 @@ fn git_state_errors_render() {"detached HEAD while merging",GitError::DetachedHead {action: Some("merge".into()),+ worktree: None,}.render(),),("detached HEAD without action",- GitError::DetachedHead { action: None }.render(),+ GitError::DetachedHead {+ action: None,+ worktree: None,+ }+ .render(),+ ),+ (+ // The detached worktree is the target the user named, not the one+ // they are standing in, so the hint has to say where to switch.+ "detached HEAD in a named target worktree",+ GitError::DetachedHead {+ action: Some("use /tmp/repo.other as a target".into()),+ worktree: Some(PathBuf::from("/tmp/repo.other")),+ }+ .render(),),("rebase in progress",diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex f1720e9e2..4dd8eb598 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -418,6 +418,27 @@ fn test_remove_nonexistent_branch(repo: TestRepo) {assert_cmd_snapshot!(make_snapshot_cmd(&repo, "remove", &["nonexistent"], None));}+/// A directory holding no worktree — a skeleton left behind by an interrupted+/// create — is reported as the directory it is. Resolution falls through to a+/// branch name, and reporting that would send the user to a branch listing the+/// path could never appear in.+///+/// Spelled `../<sibling>`, which is both worktrunk's own layout and the shape+/// that resolves against the cwd rather than against `-C`; the absolute form is+/// covered at the unit boundary.+#[rstest]+fn test_remove_path_holding_no_worktree(repo: TestRepo) {+ let leftover = repo.root_path().parent().unwrap().join("repo.leftover");+ std::fs::create_dir_all(&leftover).unwrap();++ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "remove",+ &["../repo.leftover"],+ None+ ));+}+#[rstest]fn test_remove_partial_success(mut repo: TestRepo) {// Create one valid worktreediff --git a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__git_state_errors.snap b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__git_state_errors.snapindex fc78e2dea..e02f22218 100644--- a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__git_state_errors.snap+++ b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__git_state_errors.snap@@ -12,6 +12,11 @@ expression: render_cases(cases)[31m✗[39m [31mNot on a branch (detached HEAD)[39m[2m↳[22m [2mTo switch to a branch, run [4mgit switch <branch>[24m[22m+## detached HEAD in a named target worktree++[31m✗[39m [31mCannot use /tmp/repo.other as a target: not on a branch (detached HEAD)[39m+[2m↳[22m [2mTo switch to a branch, run [4mgit -C /tmp/repo.other switch <branch>[24m[22m+## rebase in progress[31m✗[39m [31mCannot rebase: a git operation is already in progress[39mdiff --git a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_errors.snap b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_errors.snapindex f1556608b..50ee1b283 100644--- a/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_errors.snap+++ b/tests/integration_tests/snapshots/integration__integration_tests__git_error_display__worktree_errors.snap@@ -46,6 +46,11 @@ expression: render_cases(cases)[31m✗[39m [31mWorktree directory missing for [1mstale-branch[22m[39m[2m↳[22m [2mTo clean up, run [4mgit worktree prune[24m[22m+## no worktree at a leftover directory++[31m✗[39m [31mNo worktree @ [1m/tmp/repo/.claude/worktrees/ghost[22m[39m+[2m↳[22m [2mThe directory exists but is not a worktree; to list worktrees, run [4mwt list[24m[22m+## branch not found[31m✗[39m [31mNo branch named [1mnonexistent[22m[39mdiff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 007837f7d..c15fbb7db 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -524,6 +524,21 @@ fn test_switch_create_with_invalid_base(repo: TestRepo) {);}+/// A path naming a directory that holds no worktree is reported as a directory,+/// not as a missing branch — and, unlike a name that could be one, carries no+/// `--create` suggestion, since git rejects a path spelling as a branch name.+#[rstest]+fn test_switch_path_holding_no_worktree(repo: TestRepo) {+ let leftover = repo.root_path().parent().unwrap().join("repo.leftover");+ fs::create_dir_all(&leftover).unwrap();++ snapshot_switch(+ "switch_path_holding_no_worktree",+ &repo,+ &["../repo.leftover"],+ );+}+#[rstest]fn test_switch_nonexistent_branch(repo: TestRepo) {// Switching to a nonexistent branch (without --create) should give a cleardiff --git a/tests/snapshots/integration__integration_tests__remove__remove_path_holding_no_worktree.snap b/tests/snapshots/integration__integration_tests__remove__remove_path_holding_no_worktree.snapnew file mode 100644index 000000000..14ef5b235--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__remove_path_holding_no_worktree.snap@@ -0,0 +1,62 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ - "../repo.leftover"+ 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_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 [31mNo worktree @ [1m../repo.leftover[22m[39m+[2m↳[22m [2mThe directory exists but is not a worktree; to list worktrees, run [4mwt list[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__security__error_message_with_directive_not_executed.snap b/tests/snapshots/integration__integration_tests__security__error_message_with_directive_not_executed.snapindex 56ad738f0..b9578a036 100644--- a/tests/snapshots/integration__integration_tests__security__error_message_with_directive_not_executed.snap+++ b/tests/snapshots/integration__integration_tests__security__error_message_with_directive_not_executed.snap@@ -7,12 +7,23 @@ info:- __WORKTRUNK_EXEC__echo PWNED > /tmp/hacked6env:APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"CLICOLOR_FORCE: "1"COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: fileGIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test UserGIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"- GIT_CONFIG_SYSTEM: /dev/null+ 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@@ -37,6 +48,7 @@ info: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_SKIP_URL_HEALTH_CHECK: "1"@@ -49,5 +61,5 @@ exit_code: 1----- stderr -----[31m✗[39m [31mNo branch named [1m__WORKTRUNK_EXEC__echo PWNED > /tmp/hacked6[22m[39m-[2m↳[22m [2mTo create a new branch, run [4mwt switch --create '__WORKTRUNK_EXEC__echo PWNED > /tmp/hacked6'[24m; to list branches, run [4mwt list --branches --remotes[24m[22m+[2m↳[22m [2mTo list branches, run [4mwt list --branches --remotes[24m[22m[0mdiff --git a/tests/snapshots/integration__integration_tests__step_promote__promote_detached_head_main.snap b/tests/snapshots/integration__integration_tests__step_promote__promote_detached_head_main.snapindex 4dceac18d..a8a5a8d03 100644--- a/tests/snapshots/integration__integration_tests__step_promote__promote_detached_head_main.snap+++ b/tests/snapshots/integration__integration_tests__step_promote__promote_detached_head_main.snap@@ -8,12 +8,23 @@ info:- featureenv:APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"CLICOLOR_FORCE: "1"COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: fileGIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test UserGIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"- GIT_CONFIG_SYSTEM: /dev/null+ 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@@ -36,6 +47,7 @@ info: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_SKIP_URL_HEALTH_CHECK: "1"@@ -48,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_ switch <branch>[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_path_holding_no_worktree.snap b/tests/snapshots/integration__integration_tests__switch__switch_path_holding_no_worktree.snapnew file mode 100644index 000000000..b211692cb--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_path_holding_no_worktree.snap@@ -0,0 +1,62 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - switch+ - "../repo.leftover"+ 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_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 [31mNo worktree @ [1m../repo.leftover[22m[39m+[2m↳[22m [2mThe directory exists but is not a worktree; to list worktrees, run [4mwt list[24m[22m