diff --git a/.changeset/prunable-worktree-entry.md b/.changeset/prunable-worktree-entry.md new file mode 100644 index 00000000..9b9732d3 --- /dev/null +++ b/.changeset/prunable-worktree-entry.md @@ -0,0 +1,5 @@ +--- +"@northguild/worktree": patch +--- + +`remove`, `list` and `cleanup` no longer fail when a worktree directory has lost its `.git` file. Git's record of it is pruned on removal, and the directory is left on disk for you to check. diff --git a/docs/src/chat/docs-routes.generated.ts b/docs/src/chat/docs-routes.generated.ts index 19e6d3b4..03c488e0 100644 --- a/docs/src/chat/docs-routes.generated.ts +++ b/docs/src/chat/docs-routes.generated.ts @@ -36,5 +36,5 @@ export const VALID_DOC_ROUTES: ReadonlySet = new Set([ /** What the Worker indexes: the hub's status line reads it. */ export const CORPUS_COUNTS: { pages: number; chunks: number } = { pages: 29, - chunks: 222, + chunks: 223, }; diff --git a/docs/src/content/docs/commands/cleanup.mdx b/docs/src/content/docs/commands/cleanup.mdx index de086142..5261c50d 100644 --- a/docs/src/content/docs/commands/cleanup.mdx +++ b/docs/src/content/docs/commands/cleanup.mdx @@ -65,11 +65,15 @@ Found 5 worktree branches that are marked safe to remove. - feature/eng-123-dark-mode (Linear issue ENG-123 canceled, no unpushed commits) ``` -Those five are the whole vocabulary. `merged into ` is the one that names a count rather +Those five are the whole vocabulary, with one more below for a directory that has lost its `.git` file. `merged into ` is the one that names a count rather than denying one: that worktree *is* ahead of `origin/main`, and every commit in it is already applied there. `Path does not exist` answers none of the checks above: a worktree whose directory is already gone is removed before its commits are considered, because there is no -directory to count them in. +directory to count them in. `Not a git checkout (.git missing), directory kept` is a directory that is still on disk but +has lost its `.git` file, as an interrupted removal can leave it. Unlike a directory that is gone, +its branch is still counted, from the repository, and it is removed only when the checks above +clear it. `cleanup` then drops git's record of it and its branch, and leaves the directory for you +to check for uncommitted work before you delete it by hand. `cleanup` also reports what it held back, under four headings: diff --git a/docs/src/content/docs/commands/list.mdx b/docs/src/content/docs/commands/list.mdx index 9250b2bd..649168fe 100644 --- a/docs/src/content/docs/commands/list.mdx +++ b/docs/src/content/docs/commands/list.mdx @@ -95,7 +95,7 @@ edits are not part of it; they are counted separately as `N uncommitted changes` - **It sits beside `Ahead:` and is shown only where `Ahead:` is.** A worktree with nothing ahead, and one whose branch is already merged, show no `Churn:` detail. The [JSON](#json-output) still carries what was taken for a merged branch. -- **It is left out where it could not be taken** — no comparison base resolved, the directory is gone, or +- **It is left out where it could not be taken** — no comparison base resolved, the directory is gone or has lost its `.git` file, or the diff failed, did not answer within 10 seconds or printed something unrecognised — rather than printed as `+0 -0`. - **It costs one more git call per worktree**, which is why it is opt-in. Without `--churn`, `list` runs exactly what it ran before, and [`remove`](/worktree/commands/remove/) and [`cleanup`](/worktree/commands/cleanup/) @@ -135,7 +135,8 @@ unchanged. [`remove`](/worktree/commands/remove/) never reads them. `Ahead:` counts commits this worktree carries that its comparison base does not. **The count is taken for every worktree whose directory is present, including one on a branch you have never pushed** — that is the case worth seeing, because -those commits exist in exactly one place. +those commits exist in exactly one place. A directory that has lost its `.git` file is +counted too, from the repository, against the branch git still holds for it. The base depends on whether the branch tracks a remote: @@ -190,18 +191,18 @@ and any warning go to stderr. It implies a [non-interactive run](/worktree/comma | --- | --- | | `branch`, `path` | the worktree's branch and absolute path | | `current` | whether it is the worktree you are in | -| `pathExists` | whether its directory is still on disk | +| `pathExists` | whether its directory is still on disk as a git checkout. `false` also when the directory is there but has lost its `.git` file; `list` then shows it as `Not a git checkout (.git missing), directory kept` | | `remote`, `remoteExists` | the upstream the branch tracks, `null` when it tracks none, and whether that remote branch still exists | | `ahead`, `behind` | the [counts above](#ahead-and-behind-counts) as numbers | | `mergedInto` | the base whose commits already contain all of this branch's changes; `null` when not known to be merged | -| `uncommittedChanges` | the number of uncommitted changes; `null` when the directory is gone, as there is nothing to count | +| `uncommittedChanges` | the number of uncommitted changes; `null` when `pathExists` is `false`, as there is nothing to count | | `safeToRemove` | the verdict [`cleanup`](/worktree/commands/cleanup/) acts on, from the data this run gathered. `cleanup` weighs agent sessions and canceled Linear issues; `list` does so only with `--agents` and `--issues`, so without them it can report `false` for a worktree `cleanup` would remove through a canceled issue, and `true` for one it would hold back for a live session. With both flags it is `cleanup`'s verdict, except for the worktree you are in (`current: true`), which `cleanup` never considers | | `churn` | only with `--churn`: `{files, insertions, deletions}` for the committed work, [as above](#showing-churn), or `null` when it could not be taken. All zeros means the diff was taken and was empty | | `issue` | only with `--issues`: `null` when the branch has no recorded Linear issue, otherwise `{provider, key, state}`: `provider` is `"linear"`, `key` the identifier such as `ENG-123`, and `state` the issue's state type (`canceled`, `started`, ...) or `null` when it could not be read. Only the type is read, never the state's name | | `agent` | only with `--agents`: `null` when no session lives in the worktree, otherwise `{name, sessionId, herdrAgent, live, interactive, waiting}`. `waiting` is `true` for a live session that is idle between turns or blocked on a question, whether or not it is interactive. `herdrAgent` is the name Herdr gives the agent, as `branch --json` reports it in `herdr.agent`, or the agent's pane id when Herdr reports no name | -**A count or flag that could not be taken is `null`, never `0` and never left out.** `ahead` and `uncommittedChanges` are -`null` when the directory is gone (and `ahead` also when no comparison base resolved), `behind` is `null` for a branch with no upstream, `churn` is `null` when no figure was taken for the worktree, `issue.state` is `null` when the type could not be read (a warning goes to stderr, and stdout is still one document), and +**A count or flag that could not be taken is `null`, never `0` and never left out.** `uncommittedChanges` is +`null` when `pathExists` is `false`, `ahead` is `null` when the directory is gone (but not when it has only lost its `.git` file, which is counted from the repository) and when no comparison base resolved, `behind` is `null` for a branch with no upstream, `churn` is `null` when no figure was taken for the worktree, `issue.state` is `null` when the type could not be read (a warning goes to stderr, and stdout is still one document), and inside `agent` any of `sessionId`, `herdrAgent`, `live`, `interactive` and `waiting` is `null` when the source did not say. A `0` always means the count was taken and is zero. diff --git a/docs/src/content/docs/commands/remove.mdx b/docs/src/content/docs/commands/remove.mdx index be92efed..13f1307d 100644 --- a/docs/src/content/docs/commands/remove.mdx +++ b/docs/src/content/docs/commands/remove.mdx @@ -51,6 +51,14 @@ counted as ahead, because a squash merge and a rebase both give the same work ne identities, but there is nothing in it to lose. Warning about those commits would teach you that this prompt does not mean anything, which is how the one that does gets waved through. +## A directory that has lost its `.git` file + +An interrupted removal, such as a stopped `rm -rf`, can leave a worktree's directory on disk without +the `.git` file that made it a checkout. Git still lists it, as `prunable`. Its unpushed commits are +still counted, from the repository against the branch git holds for it, so the prompt warns about +them as it would for any worktree. `remove` then drops git's record and deletes the branch. **The directory itself is kept**: without `.git` its contents can no longer be checked for +uncommitted work, so look through it before you delete it by hand. + ## When an agent is working in the worktree If an agent session is working in the worktree you name, the prompt opens with that fact and then diff --git a/src/commands/cleanup.ts b/src/commands/cleanup.ts index ac2027fc..c634ffbd 100644 --- a/src/commands/cleanup.ts +++ b/src/commands/cleanup.ts @@ -10,7 +10,11 @@ import { import { createSpinner } from "../lib/progress.js"; import { askConfirm } from "../lib/prompt.js"; import type { WorktreeListEntry } from "../lib/types.js"; -import { formatCount, worktreeListEntryToListName } from "../lib/utils.js"; +import { + formatCount, + missingPathDetail, + worktreeListEntryToListName, +} from "../lib/utils.js"; // A worktree cleanup would have swept but for the work sitting in it. Asking the // predicate about a zeroed copy keeps the safety rule in one place rather than @@ -88,7 +92,7 @@ function removalReason(wt: WorktreeListEntry): string { if (!wt.pathExists) { // Returned before any count is consulted, so this says nothing about // commits — deliberately. See §9 Q5. - return "Path does not exist"; + return missingPathDetail(wt); } if (wt.remoteExists && wt.issue?.state === "canceled") { // A worktree on a live remote qualifies only through D4's last clause, and diff --git a/src/lib/git.test.ts b/src/lib/git.test.ts index 8711dc5e..c9c4421d 100644 --- a/src/lib/git.test.ts +++ b/src/lib/git.test.ts @@ -767,6 +767,26 @@ describe("gitNukeWorktreeCmd", () => { ]); }); + // #368: an interrupted removal can leave the directory with no `.git` file. + // `git worktree remove` refuses it, and the record has to go by a prune. + it("prunes instead of removing when the directory has lost its .git file", async () => { + vi.spyOn(fs, "existsSync").mockImplementation( + (path) => path === worktreePath, + ); + const runSpy = vi.spyOn(cli, "run").mockResolvedValue(""); + + await gitNukeWorktreeCmd(target); + + // Nothing after the branch delete: the directory is left on disk. + expect(runSpy).toHaveBeenCalledTimes(2); + expect(runSpy).toHaveBeenNthCalledWith(1, "git", ["worktree", "prune"]); + expect(runSpy).toHaveBeenNthCalledWith(2, "git", [ + "branch", + "-D", + branchName, + ]); + }); + it("appends --force to the remove when forced", async () => { const runSpy = vi.spyOn(cli, "run").mockResolvedValue(""); @@ -1450,6 +1470,151 @@ describe("gitGetWorktreeList agent join", () => { // those with an upstream. A branch nobody ever pushed is precisely the case // the old `remoteExists` guard skipped, and skipping it is what let such a // worktree read as empty. +// #368: a record git marks `prunable` has a directory that is no checkout, and +// every probe run in it would climb into the parents and fail the whole gather. +// Its branch is still in the repository, so its commits are counted from there. +describe("gitGetWorktreeList with a prunable record", () => { + const rootPath = "/repo/project"; + const brokenPath = `${rootPath}.worktrees/broken`; + const prunableLine = "prunable gitdir file points to non-existent location"; + + beforeEach(() => { + vi.clearAllMocks(); + vi.spyOn(fs, "existsSync").mockReturnValue(true); + }); + + function mockPreamble(record: string) { + expectCommands( + "git fetch --prune", + "git --no-pager branch -r", + 'git for-each-ref "--format=%(refname:short) %(upstream:short)" refs/heads', + "git branch --show-current", + "git rev-parse --show-toplevel", + "git worktree list --porcelain", + "git symbolic-ref --short refs/remotes/origin/HEAD", + ); + mockRun + .mockResolvedValueOnce("") + .mockResolvedValueOnce("") + .mockResolvedValueOnce("") + .mockResolvedValueOnce("main") + .mockResolvedValueOnce(rootPath) + .mockResolvedValueOnce(record) + .mockResolvedValueOnce("origin/main"); + } + + it("counts its branch from the repository and runs nothing in the directory", async () => { + mockPreamble(`${porcelainRecord(brokenPath, "broken")}${prunableLine}\n`); + expectCommands("git rev-list --count origin/main..refs/heads/broken"); + mockRun.mockResolvedValueOnce("0"); + + const [worktree] = await gitGetWorktreeList(); + + expect(worktree?.branchName).toBe("broken"); + expect(worktree?.pathExists).toBe(false); + expect(worktree?.ahead).toBe(0); + expect(worktree?.safeToRemove).toBe(true); + expect(mockRun).toHaveBeenCalledWith( + "git", + ["rev-list", "--count", "origin/main..refs/heads/broken"], + undefined, + ); + for (const [, , options] of mockRun.mock.calls) { + expect(options?.cwd).not.toBe(brokenPath); + } + }); + + // The review of #372: before this, the missing-path clause let such a branch + // through, and `cleanup` ran `branch -D` on commits that exist nowhere else. + it("holds back a prunable branch that carries unmerged commits", async () => { + mockPreamble(`${porcelainRecord(brokenPath, "broken")}${prunableLine}\n`); + expectCommands( + "git rev-list --count origin/main..refs/heads/broken", + "git merge-base origin/main refs/heads/broken", + `git commit-tree refs/heads/broken^{tree} -p ${MERGE_BASE_SHA} -m "merged probe"`, + `git cherry origin/main ${PROBE_COMMIT_SHA}`, + ); + mockRun + .mockResolvedValueOnce("2") + .mockResolvedValueOnce(MERGE_BASE_SHA) + .mockResolvedValueOnce(PROBE_COMMIT_SHA) + .mockResolvedValueOnce(`+ ${PROBE_COMMIT_SHA}`); + + const [worktree] = await gitGetWorktreeList(); + + expect(worktree?.ahead).toBe(2); + expect(worktree?.mergedInto).toBeUndefined(); + expect(worktree?.safeToRemove).toBe(false); + }); + + // #372 review: git calls a record whose whole directory is gone prunable too. + // That one keeps the missing-path verdict it always had, uncounted. + it("leaves a prunable record whose directory is gone uncounted and safe", async () => { + vi.spyOn(fs, "existsSync").mockReturnValue(false); + mockPreamble(`${porcelainRecord(brokenPath, "broken")}${prunableLine}\n`); + + const [worktree] = await gitGetWorktreeList(); + + expect(worktree?.prunable).toBeUndefined(); + expect(worktree?.ahead).toBeUndefined(); + expect(worktree?.safeToRemove).toBe(true); + expect(mockRun).not.toHaveBeenCalledWith( + "git", + ["rev-list", "--count", "origin/main..refs/heads/broken"], + undefined, + ); + }); + + it("counts a prunable branch with a live upstream against that upstream", async () => { + expectCommands( + "git fetch --prune", + "git --no-pager branch -r", + 'git for-each-ref "--format=%(refname:short) %(upstream:short)" refs/heads', + "git branch --show-current", + "git rev-parse --show-toplevel", + "git worktree list --porcelain", + "git symbolic-ref --short refs/remotes/origin/HEAD", + "git rev-list --count broken@{u}..refs/heads/broken", + ); + mockRun + .mockResolvedValueOnce("") + .mockResolvedValueOnce("origin/broken") + .mockResolvedValueOnce("broken origin/broken") + .mockResolvedValueOnce("main") + .mockResolvedValueOnce(rootPath) + .mockResolvedValueOnce( + `${porcelainRecord(brokenPath, "broken")}${prunableLine}\n`, + ) + .mockResolvedValueOnce("origin/main") + .mockResolvedValueOnce("1"); + + const [worktree] = await gitGetWorktreeList(); + + expect(worktree?.remoteExists).toBe(true); + expect(worktree?.ahead).toBe(1); + expect(worktree?.safeToRemove).toBe(false); + }); + + it("counts a prunable detached record from the commit git recorded for it", async () => { + const sha = "abc1234abc1234abc1234abc1234abc1234abc1234"; + mockPreamble( + `worktree ${brokenPath}\nHEAD ${sha}\ndetached\n${prunableLine}\n`, + ); + expectCommands(`git rev-list --count origin/main..${sha}`); + mockRun.mockResolvedValueOnce("0"); + + const [worktree] = await gitGetWorktreeList(); + + expect(worktree?.branchName).toBe("(detached HEAD)"); + expect(worktree?.ahead).toBe(0); + expect(mockRun).toHaveBeenCalledWith( + "git", + ["rev-list", "--count", `origin/main..${sha}`], + undefined, + ); + }); +}); + describe("gitGetWorktreeList ahead counting", () => { const rootPath = "/repo/project"; const onePath = `${rootPath}.worktrees/feature/one`; @@ -2675,6 +2840,27 @@ describe("what the removal helpers report", () => { expect(progressMocks.start.mock.calls[0][0]).toBe(41); }); + // #372 review: a directory that lost its `.git` is pruned, not deleted, + // so walking it would draw a bar that nothing ever moves. + it("weighs a kept directory with no .git as one entry", async () => { + vi.spyOn(fs, "existsSync").mockImplementation( + (candidate) => candidate !== `${twoPath}/.git`, + ); + removalProgressMocks.measureTree.mockResolvedValueOnce({ + total: 40, + checkpoints: [], + coveredFraction: 0, + }); + + await gitRemoveWorktreesWithProgress([entry(), two]); + + expect(removalProgressMocks.measureTree).toHaveBeenCalledTimes(1); + expect(removalProgressMocks.measureTree).not.toHaveBeenCalledWith( + twoPath, + ); + expect(progressMocks.start.mock.calls[0][0]).toBe(41); + }); + it("falls back to a spinner line per worktree when the count throws, and still removes", async () => { removalProgressMocks.measureTree.mockRejectedValue( new Error("EACCES: permission denied"), @@ -2997,11 +3183,38 @@ describe("gitGetWorktrees", () => { ); vi.spyOn(fs, "existsSync").mockReturnValue(false); + // The directory is gone, which git also calls prunable. It keeps the + // missing-path verdict it always had, so it is not marked (#372 review). + expect(await gitGetWorktrees()).toEqual([ + { + path: `${treesPath}/prun`, + branchName: "prun", + pathExists: false, + isCurrent: false, + }, + ]); + }); + + it("marks a prunable worktree whose directory is still on disk", async () => { + mockList( + porcelain( + mainRecord, + linked( + `${treesPath}/prun`, + "prun", + "prunable gitdir file points to non-existent location", + ), + ), + ); + vi.spyOn(fs, "existsSync").mockReturnValue(true); + expect(await gitGetWorktrees()).toEqual([ { path: `${treesPath}/prun`, branchName: "prun", pathExists: false, + prunable: true, + head: hash, isCurrent: false, }, ]); diff --git a/src/lib/git.ts b/src/lib/git.ts index 858cbb66..e3a95061 100644 --- a/src/lib/git.ts +++ b/src/lib/git.ts @@ -223,8 +223,9 @@ export async function gitGetTopLevelPath() { // gitGetWorktreeList can pass gitGetComparisonBase()'s answer for a worktree // that has no upstream — `@{u}` does not resolve there and run() rejects. export async function gitGetCommitsAheadCount( - branchPath: string, + branchPath: string | undefined, base = "@{u}", + rev = "HEAD", ) { // An empty base is gitGetComparisonBase() saying nothing resolved, and git // does not refuse it: `rev-list --count ..HEAD` exits 0 and prints 0. That @@ -234,9 +235,11 @@ export async function gitGetCommitsAheadCount( if (!base) { return undefined; } - const countStr = await run("git", ["rev-list", "--count", `${base}..HEAD`], { - cwd: branchPath, - }); + const countStr = await run( + "git", + ["rev-list", "--count", `${base}..${rev}`], + branchPath === undefined ? undefined : { cwd: branchPath }, + ); if (countStr) { return strToNum(countStr); } @@ -298,28 +301,44 @@ export const DETACHED_LABEL = "(detached HEAD)"; // "Porcelain Format"): one `label value` line per attribute, a blank line after // each record. A path is everything after the first space of its line, so lines // are never trimmed. A record on neither a branch nor a detached HEAD, such as -// the `bare` one, has no branch to report and is dropped. -function parseWorktreeRecords( - porcelain: string, -): Array<{ path: string; branchName: string }> { - const entries: Array<{ path: string; branchName: string }> = []; +// the `bare` one, has no branch to report and is dropped. `prunable` marks a +// record git can no longer use, such as a directory that lost its `.git` file +// (#368); the directory may still be on disk. +function parseWorktreeRecords(porcelain: string): Array<{ + path: string; + branchName: string; + prunable: boolean; + head?: string; +}> { + const entries: Array<{ + path: string; + branchName: string; + prunable: boolean; + head?: string; + }> = []; for (const record of porcelain.split("\n\n")) { let path: string | undefined; let branchName: string | undefined; + let prunable = false; + let head: string | undefined; for (const line of record.split("\n")) { if (line.startsWith("worktree ")) { path = line.slice("worktree ".length); + } else if (line.startsWith("HEAD ")) { + head = line.slice("HEAD ".length); } else if (line.startsWith("branch ")) { branchName = line.slice("branch ".length).replace(/^refs\/heads\//, ""); } else if (line === "detached") { branchName = DETACHED_LABEL; + } else if (line === "prunable" || line.startsWith("prunable ")) { + prunable = true; } } if (path !== undefined && branchName !== undefined) { - entries.push({ path, branchName }); + entries.push({ path, branchName, prunable, head }); } } @@ -339,14 +358,27 @@ export async function gitGetWorktrees({ return ( parseWorktreeRecords(result) - .map(({ path, branchName }) => ({ - path, - branchName, - pathExists: fs.existsSync(path), - isCurrent: currentBranch - ? branchName === currentBranch - : path === currentPath, - })) + .map(({ path, branchName, prunable, head }) => { + const onDisk = fs.existsSync(path); + // Git marks a record `prunable` both when its directory is gone and + // when the directory is still there without its `.git` file. Only the + // second is new here (#368): it has no usable checkout, because git + // searches the parents of a directory with no `.git` and runs every + // probe in the wrong repository, or none. No probe runs in it; its + // commits are counted from the repository instead, and `remove` and + // `cleanup` prune it, leaving the directory as is. A directory that is + // gone keeps the verdict it always had, so it is not marked. + const kept = prunable && onDisk; + return { + path, + branchName, + ...(kept ? { prunable: true, head } : {}), + pathExists: !prunable && onDisk, + isCurrent: currentBranch + ? branchName === currentBranch + : path === currentPath, + }; + }) // Filter out any branches that are not worktree branches, and also skip the current branch. // The trailing separator keeps a sibling such as `.worktrees-old` out. .filter( @@ -430,10 +462,14 @@ function carriesNoKnownWork(wt: WorktreeListEntry): boolean { } export function isSafeToRemove(wt: WorktreeListEntry): boolean { - if (!wt.pathExists) { + if (!wt.pathExists && !wt.prunable) { // Worktree is defined but doesn't exist in the filesystem. Tested first, and // before the agent clause too: a directory that is already gone holds // nothing to lose, whoever the session listing still believes is in it. + // A prunable record whose directory is still on disk is not let through + // here (#368): its branch can carry commits that exist nowhere else, and + // `branch -D` would drop them, so it answers the clauses below on the count + // taken from the repository. A gone directory is not marked `prunable`. return true; } if (hasLiveAgent(wt)) { @@ -530,21 +566,51 @@ interface AheadCount { base?: string; } +// Where a worktree's commits are counted from. A checkout is asked from inside +// it, about its HEAD. A directory that lost its `.git` (marked `prunable`) has +// no checkout to ask from (#368), but git still holds its branch and its HEAD +// commit, so it is asked from the repository about those. A directory that is +// gone gets no probe, as it never did. +interface CommitProbe { + cwd: string | undefined; + rev: string; + upstream: string; +} + +function commitProbe(wt: WorktreeListBaseEntry): CommitProbe | undefined { + if (wt.pathExists) { + return { cwd: wt.path, rev: "HEAD", upstream: "@{u}" }; + } + if (!wt.prunable) { + return undefined; + } + if (wt.branchName !== DETACHED_LABEL) { + return { + cwd: undefined, + rev: `refs/heads/${wt.branchName}`, + upstream: `${wt.branchName}@{u}`, + }; + } + return wt.head + ? { cwd: undefined, rev: wt.head, upstream: wt.head } + : undefined; +} + // The one count that can legitimately fail to take, so every exit says which // happened: a number, or a reason it is missing. Never a zero standing in for a // count that was never taken — that substitution is the whole defect this // feature exists to remove. See UNPUSHED-COMMIT-GUARD-PLAN §3 D1, issue #63. async function countAhead( - worktreePath: string, - pathExists: boolean | undefined, + probe: CommitProbe | undefined, remoteExists: boolean, comparisonBase: string, ): Promise { - if (!pathExists) { - // No directory to run in. `pathExists` already carries this and the - // listing already prints "Path does not exist", so a second detail saying - // the same thing would only be noise. What such a worktree's verdict - // should be is §9 Q5, left open by this plan and by CLEANUP-DATA-LOSS. + if (!probe) { + // No directory to run in and no prunable record to count from (see + // `commitProbe`). `pathExists` already carries this and the listing + // already prints "Path does not exist", so a second detail saying the same + // thing would only be noise. What such a worktree's verdict should be is + // §9 Q5, left open by this plan and by CLEANUP-DATA-LOSS. return {}; } @@ -552,7 +618,7 @@ async function countAhead( // count `list` has always shown, and it is the more precise question. The // run's comparison base is for the branch nobody ever pushed, which is // exactly the worktree this feature exists to stop losing. - const base = remoteExists ? "@{u}" : comparisonBase; + const base = remoteExists ? probe.upstream : comparisonBase; if (!base) { return { aheadUnknownReason: @@ -561,7 +627,10 @@ async function countAhead( } try { - return { ahead: await gitGetCommitsAheadCount(worktreePath, base), base }; + return { + ahead: await gitGetCommitsAheadCount(probe.cwd, base, probe.rev), + base, + }; } catch { // D5: failing closed loses nothing, but failing closed *silently* makes a // cleanup that cannot classify anything look like a cleanup with nothing @@ -596,13 +665,12 @@ async function countAhead( const MERGED_PROBE_TIMEOUT_MS = 10_000; async function findMergedBase( - worktreePath: string, + probe: CommitProbe, base: string, ): Promise { + const at = probe.cwd === undefined ? {} : { cwd: probe.cwd }; try { - const mergeBase = await run("git", ["merge-base", base, "HEAD"], { - cwd: worktreePath, - }); + const mergeBase = await run("git", ["merge-base", base, probe.rev], at); // The probe commit is a real object in the repository — one per worktree // per run, unreachable from any ref, collected by `git gc` like any other // loose object. There is no way to ask git this question without one: a @@ -610,8 +678,15 @@ async function findMergedBase( // are individually the wrong patches. const probeCommit = await run( "git", - ["commit-tree", "HEAD^{tree}", "-p", mergeBase, "-m", "merged probe"], - { cwd: worktreePath }, + [ + "commit-tree", + `${probe.rev}^{tree}`, + "-p", + mergeBase, + "-m", + "merged probe", + ], + at, ); // The only unbounded call in the gather: `cherry` computes a patch-id for // every commit the base has gained since the merge base, so a worktree @@ -620,7 +695,7 @@ async function findMergedBase( // verdict, and the timeout bounds the pathological case to a held-back // worktree rather than a `list` that appears to hang. const cherry = await run("git", ["cherry", base, probeCommit], { - cwd: worktreePath, + ...at, timeout: MERGED_PROBE_TIMEOUT_MS, }); // One probe commit in, so one line out: `-` when the base already has an @@ -713,7 +788,9 @@ export async function gitGetWorktreeList({ const worktreeList: WorktreeListEntry[] = []; - for (const { path, branchName, pathExists, isCurrent } of result) { + for (const entry of result) { + const { path, branchName, pathExists, isCurrent } = entry; + const probe = commitProbe(entry); const remote = tracking.find((t) => t.local === branchName)?.remote ?? ""; const remoteExists = !!remote && remoteBranches.includes(remote); // `ahead` is now counted for every worktree whose directory is there, not @@ -722,8 +799,7 @@ export async function gitGetWorktreeList({ // rejects — and leaving the count untaken is what let a branch carrying // unpushed commits read as empty. const { ahead, aheadUnknownReason, base } = await countAhead( - path, - pathExists, + probe, remoteExists, comparisonBase, ); @@ -737,8 +813,8 @@ export async function gitGetWorktreeList({ // `comparisonBase` safe to hand over here: `countAhead` reaches the count // only through a base that is not empty. const mergedInto = - pathExists && !remoteExists && ahead - ? await findMergedBase(path, comparisonBase) + probe && !remoteExists && ahead + ? await findMergedBase(probe, comparisonBase) : undefined; // `behind` keeps that guard, deliberately. Against the default branch it // would mean "commits on main this branch does not have", non-zero for @@ -770,6 +846,7 @@ export async function gitGetWorktreeList({ aheadUnknownReason, mergedInto, pathExists, + ...(entry.prunable ? { prunable: true } : {}), uncommittedChanges, isCurrent, churn, @@ -870,7 +947,9 @@ export async function gitNukeWorktreeCmd( { branchName, path }: WorktreeTarget, { force = false }: GitNukeWorktreeCmdOptions = {}, ) { - if (fs.existsSync(path)) { + // A directory without its `.git` file is not a working tree git can remove, + // so it is pruned like a missing one. The directory is left where it is. + if (fs.existsSync(path) && fs.existsSync(`${path}/.git`)) { await run("git", [ "worktree", "remove", @@ -1373,7 +1452,9 @@ async function measureWorktrees( const measurements: TreeMeasurement[] = []; for (const wt of worktrees) { measurements.push( - fs.existsSync(wt.path) + // A kept directory weighs one entry too: a prunable one is pruned, not + // deleted, so walking it would draw a bar nothing ever moves (#368). + fs.existsSync(wt.path) && fs.existsSync(`${wt.path}/.git`) ? await measureTree(wt.path) : measureAbsentTree(), ); diff --git a/src/lib/types.ts b/src/lib/types.ts index 53b49844..da357084 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -72,6 +72,14 @@ export interface WorktreeListBaseEntry { path: string; branchName: string; pathExists?: boolean; + // The directory is still on disk, but git lists the record as `prunable` + // because it has lost its `.git` file, so it is no usable checkout (#368). + // Such an entry reports `pathExists: false`, and `head` is the commit git's + // own record holds for it, which is what its commits are counted from. A + // record whose directory is gone is never marked, though git calls it + // prunable too: it keeps the missing-path verdict it always had. + prunable?: boolean; + head?: string; isCurrent?: boolean; } diff --git a/src/lib/utils.test.ts b/src/lib/utils.test.ts index 0dc00763..a39a0a34 100644 --- a/src/lib/utils.test.ts +++ b/src/lib/utils.test.ts @@ -1,3 +1,4 @@ +import fs from "node:fs"; import type { WorktreeAgent, WorktreeListEntry } from "./types.js"; import { conjoin, @@ -58,6 +59,25 @@ describe("worktreeListEntryToListName", () => { expect(result).toContain("Path does not exist"); }); + // #368: the directory is still on disk but has lost its `.git` file, so it is + // no checkout, and removal keeps the directory. The label must not say gone. + it("names a directory still on disk as no git checkout, kept", () => { + const existsSpy = vi.spyOn(fs, "existsSync").mockReturnValue(true); + + const result = worktreeListEntryToListName({ + path: "/path/to/worktree", + branchName: "feature/test", + remote: "origin/feature/test", + pathExists: false, + }); + + expect(result).toContain( + "Not a git checkout (.git missing), directory kept", + ); + expect(result).not.toContain("Path does not exist"); + existsSpy.mockRestore(); + }); + it("should show remote branch does not exist when remote exists but is not found", () => { const result = worktreeListEntryToListName({ path: "/path/to/worktree", diff --git a/src/lib/utils.ts b/src/lib/utils.ts index 307f68dd..ad7e526b 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -1,7 +1,20 @@ +import fs from "node:fs"; import type { ColorName } from "chalk"; import chalk from "./color.js"; import type { WorktreeAgent, WorktreeListEntry } from "./types.js"; +/** + * What a worktree with no usable checkout is called. Its directory may still be + * on disk without the `.git` file that made it a checkout (#368); then `remove` + * and `cleanup` drop only git's record and the branch, and the directory is + * kept, so the label says so rather than claiming the path is gone. + */ +export function missingPathDetail(wt: Pick): string { + return fs.existsSync(wt.path) + ? "Not a git checkout (.git missing), directory kept" + : "Path does not exist"; +} + export function conjoin( arr: readonly (string | number)[], conjunction: "and" | "or" = "and", @@ -73,7 +86,7 @@ export function worktreeListEntryToListName( ): string { const details = []; if (!wt.pathExists) { - details.push("Path does not exist"); + details.push(missingPathDetail(wt)); } if (wt.remote && !wt.remoteExists) { details.push(`Remote removed`);