Skip to content

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

fix(recover): find the bare repository when a deleted CWD has no .git ancestor (#4067)

Worktrunk Bot28399c2ae518
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 18ec95fc3..35574c246 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,8 @@
- **`wt merge` no longer deletes a worktree locked with `git worktree lock`**: its cleanup step removed the worktree anyway and reported success. The merge now completes and prints `Worktree preserved (locked)`, and every Worktrunk removal path refuses a lock even under `--force` — what `git worktree remove` does, minus git's `-f -f` override. Unlock with `git worktree unlock <path>` first. ([#4073](https://github.com/max-sixty/worktrunk/pull/4073), thanks @Duang777)
+- **`wt switch` recovers from a removed worktree in a bare repository**: recovery walks up from `$PWD` looking for a `.git` directory, and a bare repo has none — not at the bare directory and not at any ancestor — so the walk ran to the filesystem root and found nothing. Bare worktrees typically sit *inside* the bare directory, leaving it nowhere else to land, so `wt switch` and the picker surfaced git's raw "cannot resolve CWD" error instead of recovering and the removed-directory message dropped its `wt switch ^` suggestion. A directory that is itself a bare repository now counts as one to recover from; the deleted path still has to appear in that repository's worktree list before recovery accepts it. ([#4067](https://github.com/max-sixty/worktrunk/pull/4067))
+
- **`wt config update` migrates `[ci] platform` into a `[forge]` section that only sets `hostname`**: the migration stood down whenever a `[forge]` section existed at all, so the config a GitHub Enterprise or self-hosted GitLab user ends up with — `[ci] platform` from before the rename, `[forge] hostname` added later for an SSH host alias — kept the deprecated key with no warning and nothing `wt config update` would do about it. The platform still resolved, so nothing broke; the deprecation notice that precedes `[ci]`'s eventual removal simply never arrived. A `[forge]` that already sets `platform`, or a `forge` that isn't a section, still stands down.
- **`wt config shell install` migrates a fish wrapper at the deprecated `conf.d` path even when `~/.config/fish/functions` doesn't exist yet**: fish was skipped for want of a config location, so the bare command left the deprecated wrapper running and only `wt config shell install fish` migrated it. A worktrunk wrapper at the old path now counts as fish being configured, just at the old path. `wt config show` reports that wrapper too, where before it showed nothing at all for fish unless fish was on `PATH`.
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 98e817afd..9c815ce33 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -40,6 +40,24 @@ static HEAVY_OPS_SEMAPHORE: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::ne
/// The null OID returned by git when no commits exist (e.g., `git rev-parse HEAD` on an unborn branch).
pub const NULL_OID: &str = "0000000000000000000000000000000000000000";
+/// Whether `dir` is itself a git directory — a bare repository, or the `.git`
+/// directory of a non-bare one.
+///
+/// Git's own `is_git_directory()` shape: a `HEAD`, an `objects/`, and a
+/// `refs/`. Read from disk rather than by asking git, because both callers ask
+/// about an arbitrary directory and git's own discovery answers *upward* — it
+/// would report on some enclosing repository instead of saying "not one here".
+///
+/// Deliberately shallow: git additionally validates what `HEAD` contains, and
+/// a false positive costs each caller little — one withholds a claim, the
+/// other still has to find the deleted path in the candidate's own worktree
+/// list before it recovers. [`Repository::at`] is not that check: discovering
+/// upward, it succeeds for a false positive that sits inside a real
+/// repository.
+pub(crate) fn is_bare_repo_dir(dir: &Path) -> bool {
+ dir.join("HEAD").is_file() && dir.join("objects").is_dir() && dir.join("refs").is_dir()
+}
+
// Re-exports from submodules
pub use ci_platform::ForgeKind;
pub(crate) use diff::DiffStats;
diff --git a/src/git/recover.rs b/src/git/recover.rs
index 023657af0..75d4e68f3 100644
--- a/src/git/recover.rs
+++ b/src/git/recover.rs
@@ -12,7 +12,7 @@ use color_print::cformat;
use crate::path::canonicalize_with_parents;
use crate::styling::eprintln;
-use super::Repository;
+use super::{Repository, is_bare_repo_dir};
/// Try to get the current repository, recovering from a deleted CWD if possible.
///
@@ -135,8 +135,9 @@ fn recover_from_path(deleted_path: &Path) -> Option<Repository> {
/// Look for a git repository at `dir` or its immediate children that recognizes
/// `deleted_path` as a (former) worktree.
///
-/// Only checks for `.git` **directories** (main repos), not `.git` files
-/// (which are linked worktrees — we need the main repo to recover).
+/// Matches `.git` **directories** (main worktrees) and bare repositories, not
+/// `.git` files (which are linked worktrees — we need the repository that owns
+/// the worktree to recover).
fn find_validated_repo_near(dir: &Path, deleted_path: &Path) -> Option<Repository> {
// Check the directory itself first
if let Some(repo) = try_repo_at(dir)
@@ -145,7 +146,9 @@ fn find_validated_repo_near(dir: &Path, deleted_path: &Path) -> Option<Repositor
return Some(repo);
}
- // Check immediate children for .git directories.
+ // Check immediate children for either shape, which is where a sibling
+ // layout keeps the repository: `<root>/repo` beside the worktrees, or
+ // `<root>/.bare`.
// Uses is_some_and instead of ? so an unreadable entry (e.g., broken symlink)
// skips that entry rather than aborting the entire search.
let entries = std::fs::read_dir(dir).ok()?;
@@ -163,16 +166,16 @@ fn find_validated_repo_near(dir: &Path, deleted_path: &Path) -> Option<Repositor
/// Try to discover a repository at the given path.
///
-/// Returns `Some(repo)` if the path contains a `.git` directory (not a file)
-/// and `Repository::at()` succeeds.
+/// Returns `Some(repo)` if the path holds a `.git` directory (a main worktree)
+/// or is itself a bare repository, and `Repository::at()` succeeds. A `.git`
+/// *file* is a linked worktree — recovery needs the repository that owns it,
+/// which the ancestor walk reaches separately.
///
-/// Note: This only matches `.git` directories, so bare repos (which have no
-/// `.git` subdirectory) won't be discovered. `cwd_removed_hint()` handles
-/// this gracefully by falling back to progressively less specific hints.
+/// The bare arm is what a bare layout needs: a bare repo has no `.git` entry
+/// anywhere, and its worktrees typically sit *inside* the bare directory, so
+/// without it the ancestor walk has nowhere to land.
fn try_repo_at(dir: &Path) -> Option<Repository> {
- let git_path = dir.join(".git");
- // Only match .git directories (main repos), not .git files (linked worktrees)
- if git_path.is_dir() {
+ if dir.join(".git").is_dir() || is_bare_repo_dir(dir) {
Repository::at(dir).ok()
} else {
None
@@ -219,7 +222,7 @@ fn paths_match(worktree_path: &Path, deleted_path: &Path) -> bool {
#[cfg(test)]
mod tests {
use super::*;
- use crate::testing::{TestRepo, test_tempdir};
+ use crate::testing::{BareRepoTest, TestRepo, TestRepoBase, test_tempdir};
use ansi_str::AnsiStr;
#[test]
@@ -236,6 +239,18 @@ mod tests {
assert!(try_repo_at(test.path()).is_some());
}
+ #[test]
+ fn test_try_repo_at_accepts_bare_repo_dir() {
+ let test = TestRepo::bare();
+ assert!(try_repo_at(test.path()).is_some());
+ }
+
+ #[test]
+ fn test_try_repo_at_rejects_plain_directory() {
+ let tmp = test_tempdir();
+ assert!(try_repo_at(tmp.path()).is_none());
+ }
+
#[test]
fn test_recover_returns_none_when_cwd_exists() {
// current_dir() succeeds in test environment, so recovery should return None
@@ -417,6 +432,23 @@ mod tests {
assert!(recover_from_path(&wt_path).is_some());
}
+ /// A bare repo has no `.git` entry anywhere in the ancestor walk, so
+ /// before `is_bare_repo_dir` every bare layout fell through to "no
+ /// repository found" and `wt switch` reported the raw CWD error instead
+ /// of recovering.
+ #[test]
+ fn test_recover_from_path_bare_repo_worktree() {
+ let test = BareRepoTest::new();
+ let wt_path = test.create_worktree("feature", "feature");
+ test.commit_in(&wt_path, "init");
+
+ std::fs::remove_dir_all(&wt_path).unwrap();
+
+ let recovered =
+ recover_from_path(&wt_path).expect("recovery should find the bare repository");
+ assert_eq!(recovered.git_common_dir(), test.bare_repo_path());
+ }
+
#[test]
fn test_recover_from_path_deep_pwd() {
let tmp = test_tempdir();
diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rs
index 47cbde66a..827591b25 100644
--- a/src/git/repository/worktrees.rs
+++ b/src/git/repository/worktrees.rs
@@ -12,7 +12,7 @@ use super::{
GitError, Repository, ResolvedWorktree, Selector, WorktreeInfo, is_valid_branch_name,
normalize_selector, resolve_input_path,
};
-use crate::git::WorktreeId;
+use crate::git::{WorktreeId, is_bare_repo_dir};
use crate::path::{format_path_for_display, paths_match};
use crate::styling::{
eprintln, format_with_gutter, hint_message, suggest_command, warning_message,
@@ -658,10 +658,9 @@ impl Repository {
/// 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.
+/// The bare test is [`is_bare_repo_dir`], and its shallowness is what this
+/// caller wants: the answer 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 —
@@ -691,7 +690,7 @@ fn holds_git_data(path: &Path) -> bool {
}
// 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()
+ is_bare_repo_dir(path)
}
/// Paths of every worktree checked out on `branch`, in git's listing order.