From 137d2adf1a472bc0f6f29ece29e15d7162f9e91f Mon Sep 17 00:00:00 2001 From: Christian Lauinger Date: Fri, 13 Nov 2026 08:35:19 +0100 Subject: [PATCH 1/2] fix(discard): discard staged changes under one index lock Take .git/index.lock before touching any file, run the per-file restore against a private copy of the index and write it once. A file that fails stays as it was and is reported through DiscardBatch. Paths are matched literally, so a name like [ab].txt no longer resets a.txt, and either name of a staged rename restores the original. No journal, no recovery on open. --- CHANGELOG.md | 5 + CLAUDE.md | 24 +- apps/desktop/src-tauri/src/core/post_hooks.rs | 17 +- apps/desktop/src-tauri/src/core/stage.rs | 259 +++++++++++++----- apps/desktop/src-tauri/tests/git_engine.rs | 118 ++++++++ 5 files changed, 348 insertions(+), 75 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 394cc454..e511ed58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,6 +45,11 @@ All notable changes to AngKorGit are documented here. The format follows `git merge` does, so `git diff ORIG_HEAD HEAD` shows what a pull brought in. ### Fixed +- **Discarding staged changes writes the index once and leaves other files alone.** + A file whose name contains `[`, `]`, `*` or `?` no longer resets files the name + happens to match. The whole batch waits for Git's index lock and changes nothing + while another Git process holds it. Picking either name of a staged rename + restores the original file. - **New worktrees stay protected while their post-checkout hook runs.** The target folder is reserved before creation, including access through a symlink alias, so another operation gets an info toast until the hook finishes. diff --git a/CLAUDE.md b/CLAUDE.md index 7f4912c2..20d73c8c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -478,10 +478,24 @@ core/ │ new-file start equals the old-file start (see G45), discard_file/all → report leftovers │ (UNSTAGED side: checkout_index, index untouched); │ discard_staged_file/all (owner request 2026-09-07: discard must not -│ be an unstaged-only affordance) → discard_to_head: checkout_tree of -│ HEAD with a path filter (index + worktree), or index.remove_path + -│ delete for a file HEAD does not have; renames discard both names; -│ returns clean/leftovers like the unstaged variants +│ be an unstaged-only affordance) → discard_staged (PR #91, the +│ maintainer's smaller shape after a 3,700-line journal/recovery version +│ was declined): IndexLock takes /index.lock with create_new +│ BEFORE any file moves (held by another process → nothing changes, +│ the error names the lock), copies the index into it and opens it as a +│ private git2::Index — never repo.index(): checkout_tree re-reads the +│ repo-owned index and would drop in-memory edits; per file a +│ checkout_tree of HEAD with update_index(false) + +│ disable_pathspec_match (a pathspec turned `[ab].txt` into a pattern +│ that also reset a.txt) then remove_path + add of the HEAD entry (zero +│ stat, so git and libgit2 re-hash on the next status), or delete + +│ remove_path for a path HEAD lacks; removals run before restores so a +│ file that replaced a folder is gone before the folder comes back; a +│ failing file stays as it was and lands in DiscardBatch.failed; the +│ index is written ONCE (index.write() into index.lock.lock → renamed +│ to index.lock, then index.lock → index); selecting either name of a +│ staged rename (renames_head_to_index) discards both; no journal, no +│ recovery on open ├── commit.rs ← commit + amend run the pre-commit and commit-msg hooks first (hooks.rs, │ G55; no_verify skips them) and return CommitOutcome {oid, hookWarning}; │ commit (merge-aware parents; refuses "Nothing staged to commit" when the @@ -4564,7 +4578,7 @@ update CLAUDE.md or docs/ — never the code. | Suite | Location | Coverage | | --- | --- | --- | -| Rust integration (191 macOS + 1 clone; platform cases in CI) | `apps/desktop/src-tauri/tests/git_engine.rs`, `tests/clone_hooks.rs` (own binary, sets HOME) | stage/commit/history, amend, branch/merge(ff+normal+conflict+message), branch-over-tag ref resolution (merge/rebase/history filter), ff-merge preserving uncommitted changes, drag-merge sequence (checkout target → merge source), no-ff merge commit when ff possible, can-fast-forward only when strictly behind, merge message available only during conflicted merge, interactive rebase (reorder/drop + range listing, squash/reword, conflict aborts untouched, invalid-plan rejection), a rebase aborted during post-checkout returns without replaying commits or running post-rewrite, a rebase step stopped by an untracked file names that file and commit, Continue re-applies the stopped commit so every commit survives (issue #88, same history as `git rebase --continue`), a Continue while the file is still in the way stops again with the history untouched and can be retried, and a re-applied step that conflicts pauses with markers and a conflict entry, then completes after resolution, file history lists only touching commits + paginates with skip, conflict resolve, stash (whole tree + selected paths incl. an untracked-only pick, a staged pick that leaves other staged files alone and pops with a dirty index, a staged-new pick removed and restored, git CLI agreeing on stash list/show; stash_files lists tracked + untracked entries with source_oid; stash_restore_files restores chosen files incl. an untracked one and a deletion, keeps the stash, rejects unknown paths), remote-branch checkout (stale local fast-forwarded with an untracked file preserved + upstream set, diverged local kept), tags, cherry-pick (plain keeps the message verbatim; record-origin output byte-equal to `git cherry-pick -x` for plain and trailer-block messages; many: in-order with per-commit origin lines, first conflict stops the run with progress counts), revert, reset (+ unknown-mode error), history pagination with and without filters, history position lookup by full + short hash, history search positions (case-insensitive text, hash prefix, none, blank, author alone, text + author, unknown author), stashes listed in the default walk as single-parent commits with a stash decoration while their index/untracked helper commits stay hidden and a branch-filtered walk omits them, broken-symlink staging (unix), diff hunks + whole-file context, unstage_all/discard_all, discard_staged_file/all (HEAD restored for index + worktree, staged-new file deleted, other staged files untouched), line+hunk ops on files without trailing newline, git-CLI interop, commit signing (SSH sign verified via `git verify-commit`, unsigned without config, amend re-signs, merge commit signed, failure blocks the commit and leaves HEAD/index untouched), PR checkout (fork-style refs/pull fetch creates + updates the local branch and re-runs cleanly, diverged local branch refused with HEAD untouched, same-repo tracking checkout sets the upstream), ref fingerprint (tracks refs/HEAD, ignores plain file edits), commit file lists (per-file counts without hunks), single-file commit diff scoped by pathspec, comparing two commits lists the net change exactly like `git diff --name-status A B` (a file changed and changed back is absent, a rename keeps its old path, counts and hunk lines are the net ones, swapping the commits flips additions into deletions) and works across two branches, worktrees (add lists + checks out the branch and reports is_worktree/main_path from inside the linked folder, new branch from a base commit + duplicate refused, branch held elsewhere refused, checkout of a held branch refused with HEAD untouched, dirty remove refused unless forced, prune of a deleted folder, ref fingerprint changes on add, `git worktree list --porcelain` reports the engine-created worktree and `git status` runs clean inside it), discover refuses a missing path instead of walking to the parent repo, push reports up_to_date without contacting the remote when the tip equals the tracking ref while `git push` prints Everything up-to-date, and pushes again after a new commit, push with tags lands a local tag on a bare remote through named refspecs, pull with mode rebase / configured pull.rebase keeps history linear while mode merge creates a merge commit, blame attributes lines to their commits and marks an uncommitted edit, blames at a revision and at `^`, an uncommitted edit inside a committed block keeps the author on both split halves (the G44 crash), untracked/staged-new files and paths missing from a commit get explicit errors, staging and unstaging a later hunk of a multi-hunk file leaves the other hunk alone, remote_add registers a remote that list and fetch then use while a duplicate or blank name is refused, reword of HEAD changes only the message (tree + author lines byte-equal, dirty worktree and staged file untouched), reword of an earlier commit rewrites the commits above it and returns the reworded commit's new oid while a dirty tree is refused, unpushed lists only commits missing from every refs/remotes ref, tree_files lists every path at a commit while commit_files still lists the two changed ones, index_files lists tracked and staged-new paths but no untracked file, file_contents reads a file at a commit and on disk as context lines with status unchanged, errors for a path missing from the commit and flags a NUL-byte file binary, the folder scan finds repos at any depth and repos inside repos while skipping node_modules, hidden folders, an empty `.git` folder and anything past the runaway depth guard, returns the discover-shaped path, a root that is itself a repo plus its nested repo, and an error for a missing folder, stage_files/unstage_files apply many paths in one index write, commit refuses an index that matches HEAD (HEAD and worktree untouched) and an empty first commit while a merge resolved to HEAD's tree still commits with two parents, submodules (a synced pull checks an in-sync submodule out at the bumped commit — fetching it — and leaves `git status --porcelain` empty, a synced checkout takes it back with the branch, the group Pull all does the same, a submodule with a local commit or an edited file stays where it is, an unsynced pull reports the drift as FileStatus.submodule recorded/checkedOut and discard_file, discard_all and submodule_update by path all check out the recorded commit, a submodule with only edited files reports no drift), pull_preview is empty when up to date or simply behind, lists the uncommitted files a pull would overwrite (and the real pull then fails), predicts the merge conflict a real pull then reports while leaving HEAD, status and the state files untouched, follows pull.rebase and stops at the first conflicting commit, catches a rebase conflict a merge would not have, reports none for edits that merge cleanly in both modes, and is None without an upstream or on a detached HEAD, commit hooks (a passing pre-commit commits and sees GIT_INDEX_FILE, a failing one blocks with its exit code and output as hook_failed detail and HEAD unchanged, a pre-commit that re-stages a formatted file commits the new content, commit-msg edits reach the commit while an untouched message stays byte-for-byte, a failing or emptying commit-msg blocks, no_verify skips failing hooks on commit and amend, amend runs both hooks with and without a new message, core.hooksPath wins over .git/hooks while `*.sample` and non-executable files never count, config-defined hooks are detected, commit-msg in a linked worktree writes that worktree's COMMIT_EDITMSG, both hooks see GIT_AUTHOR_NAME/EMAIL/DATE of the new commit and amend exports the original author after the identity changed, a pre-commit or commit-msg hook that checks out another branch at the same tip makes commit and amend refuse with both branch tips unchanged; pre-push gets the remote name and URL and a zero remote sha for a new branch, a failing one leaves the bare remote without the new commit and returns its output, a push with tags lists the branch update plus a lightweight and an annotated tag (tag object sha) and an up-to-date repeat sends empty stdin, push_tag runs it, a delete reads `(delete) `, a rejected non-fast-forward is left out while a force push carries the remote's current sha, it runs with empty stdin when nothing needs pushing and can fail that push, no_verify pushes past a failing hook on push and push_tag, core.hooksPath wins, a hook that outlasts an HTTP server's keep-alive timeout still lands the push and runs once, whether the server closes the idle connection or only half-closes it; post-* hooks: a branch switch, a new checked-out branch and a detached checkout run post-checkout with both heads and flag 1 while a branch made without checkout runs nothing, discarding a tracked file, all changes, staged changes and applying a stash file run post-checkout HEAD HEAD 0 once while discarding only untracked files runs nothing, post-merge 0 follows a fast-forward and a merge commit but not up to date or conflicts, amend and reword of HEAD run post-rewrite amend with old and new on stdin while a plain commit runs none, a rebase runs post-checkout orig onto 1 then post-rewrite rebase with one line per commit, a rebase onto HEAD itself or onto an upstream the branch already sits on linearly reports up_to_date, keeps the commits and runs nothing, the rebase's post-checkout sees HEAD at onto and the file without conflict markers although the rebase then stops on that conflict, Pull without hooks that stops on a rebase conflict, or on an untracked file after one commit was replayed, runs no post-rewrite when Continue (no_verify false) completes it, an up-to-date rebase still refuses unstaged or staged changes and a rebase in progress, repo_hooks reports a .husky hooksPath as inside the worktree (and ../shared-hooks or the default as not) and a pulled-in .husky/post-merge runs after a plain pull but not after a pull without hooks, (unix) a dangling `.git/hooks/post-merge` symlink into the worktree, a dangling `.git/hooks` folder symlink and a hook linked through an outside hop to a worktree file count as inside while a symlink to /usr/bin/true does not, a tracked `.husky` link to an empty folder outside counts as inside and the pull that replaces it with a folder holding post-merge runs that hook only without the skip, a hook linked to `proxy/../.husky/post-merge` with proxy linked to a worktree folder counts as inside, a core.hooksPath spelled in other letter case counts as inside exactly when the disk ignores case, an include.path to a tracked project.gitconfig holding only a comment counts as inside and the pull that adds core.hooksPath=.husky plus .husky/post-merge to it runs that hook only without the skip, a rebase goes through with only untracked files in a submodule but not with an edited one, an interactive rebase and the reword of an older commit go through with an edited submodule under `ignore = dirty` while the ordinary rebase still refuses it, and both interactive rebase and reword refuse a staged gitlink change under `ignore = all`, a quoted include through a .git symlink with a trailing space still offers the skip, a config scan that hits its 64-file limit with a tracked include still queued reports the hooks as inside the worktree, discarding three unstaged or two staged files in one call runs post-checkout once after all of them (and none for an untracked-only discard), (unix) a bulk discard records the untracked file it could not delete as failed, still restores the files before and after it and runs post-checkout once, (unix) Discard all staged changes does the same for a staged new file in a read-only folder (the files around it restored, one post-checkout seeing them), Pull all returns while a post-merge background job is running and lets it finish, while Cancel waits for a background job through a Linux pidfd or Windows job and immediately warns for a live macOS group; an exit-0 hook has no cancellation warning, and a setsid child can still write after Cancel without being seen, a fast-forward fails and leaves ORIG_HEAD and HEAD alone while ORIG_HEAD.lock is held and sets ORIG_HEAD once it is gone, and the script the pull brings runs only without the skip, a failing post-checkout's warning comes back next to the error of a replay that then fails, a fast-forward merge sets ORIG_HEAD so the post-merge hook's `git diff --name-only ORIG_HEAD HEAD` lists the new file, Pull all sets ORIG_HEAD to the old tip, a rebase paused on a conflict runs post-checkout and its continue runs post-rewrite once with the pairs from before the pause, an interactive pick + squash + drop runs post-checkout orig result 1, maps both picked commits to the squashed one and leaves the dropped one out, pull with rebase fast-forwards with post-merge when only behind and runs post-checkout + post-rewrite (no post-merge) when diverged while pull with merge runs post-merge and an up-to-date pull nothing, a failing post-checkout or post-merge comes back as a warning with exit code and output while HEAD moved, no_verify suppresses every post hook, Pull all runs post-merge in a repo that fast-forwarded but not in one already up to date, puts a failing hook on that repo's result while it still fast-forwards, and a run started skipping hooks runs none, group pull and the toolbar pull both run post-merge 0 and no post-checkout with core.hooksPath set, worktree add runs post-checkout 000… HEAD 1 inside the new worktree, and (clone_hooks.rs) a clone runs post-checkout 000… HEAD 1 from a global core.hooksPath while a no_verify clone and a clone of an empty repo run none) — skipped with a note when git ≥ 2.36 is not on PATH | +| Rust integration (195 macOS + 1 clone; platform cases in CI) | `apps/desktop/src-tauri/tests/git_engine.rs`, `tests/clone_hooks.rs` (own binary, sets HOME) | stage/commit/history, amend, branch/merge(ff+normal+conflict+message), branch-over-tag ref resolution (merge/rebase/history filter), ff-merge preserving uncommitted changes, drag-merge sequence (checkout target → merge source), no-ff merge commit when ff possible, can-fast-forward only when strictly behind, merge message available only during conflicted merge, interactive rebase (reorder/drop + range listing, squash/reword, conflict aborts untouched, invalid-plan rejection), a rebase aborted during post-checkout returns without replaying commits or running post-rewrite, a rebase step stopped by an untracked file names that file and commit, Continue re-applies the stopped commit so every commit survives (issue #88, same history as `git rebase --continue`), a Continue while the file is still in the way stops again with the history untouched and can be retried, and a re-applied step that conflicts pauses with markers and a conflict entry, then completes after resolution, file history lists only touching commits + paginates with skip, conflict resolve, stash (whole tree + selected paths incl. an untracked-only pick, a staged pick that leaves other staged files alone and pops with a dirty index, a staged-new pick removed and restored, git CLI agreeing on stash list/show; stash_files lists tracked + untracked entries with source_oid; stash_restore_files restores chosen files incl. an untracked one and a deletion, keeps the stash, rejects unknown paths), remote-branch checkout (stale local fast-forwarded with an untracked file preserved + upstream set, diverged local kept), tags, cherry-pick (plain keeps the message verbatim; record-origin output byte-equal to `git cherry-pick -x` for plain and trailer-block messages; many: in-order with per-commit origin lines, first conflict stops the run with progress counts), revert, reset (+ unknown-mode error), history pagination with and without filters, history position lookup by full + short hash, history search positions (case-insensitive text, hash prefix, none, blank, author alone, text + author, unknown author), stashes listed in the default walk as single-parent commits with a stash decoration while their index/untracked helper commits stay hidden and a branch-filtered walk omits them, broken-symlink staging (unix), diff hunks + whole-file context, unstage_all/discard_all, discard_staged_file/all (HEAD restored for index + worktree, staged-new file deleted, other staged files untouched; a name with glob characters leaves the files it would match staged; a held index.lock changes nothing and the retry after it is gone discards and leaves no lock; either name of a staged rename restores the original; a file that replaced a folder gives the folder back), line+hunk ops on files without trailing newline, git-CLI interop, commit signing (SSH sign verified via `git verify-commit`, unsigned without config, amend re-signs, merge commit signed, failure blocks the commit and leaves HEAD/index untouched), PR checkout (fork-style refs/pull fetch creates + updates the local branch and re-runs cleanly, diverged local branch refused with HEAD untouched, same-repo tracking checkout sets the upstream), ref fingerprint (tracks refs/HEAD, ignores plain file edits), commit file lists (per-file counts without hunks), single-file commit diff scoped by pathspec, comparing two commits lists the net change exactly like `git diff --name-status A B` (a file changed and changed back is absent, a rename keeps its old path, counts and hunk lines are the net ones, swapping the commits flips additions into deletions) and works across two branches, worktrees (add lists + checks out the branch and reports is_worktree/main_path from inside the linked folder, new branch from a base commit + duplicate refused, branch held elsewhere refused, checkout of a held branch refused with HEAD untouched, dirty remove refused unless forced, prune of a deleted folder, ref fingerprint changes on add, `git worktree list --porcelain` reports the engine-created worktree and `git status` runs clean inside it), discover refuses a missing path instead of walking to the parent repo, push reports up_to_date without contacting the remote when the tip equals the tracking ref while `git push` prints Everything up-to-date, and pushes again after a new commit, push with tags lands a local tag on a bare remote through named refspecs, pull with mode rebase / configured pull.rebase keeps history linear while mode merge creates a merge commit, blame attributes lines to their commits and marks an uncommitted edit, blames at a revision and at `^`, an uncommitted edit inside a committed block keeps the author on both split halves (the G44 crash), untracked/staged-new files and paths missing from a commit get explicit errors, staging and unstaging a later hunk of a multi-hunk file leaves the other hunk alone, remote_add registers a remote that list and fetch then use while a duplicate or blank name is refused, reword of HEAD changes only the message (tree + author lines byte-equal, dirty worktree and staged file untouched), reword of an earlier commit rewrites the commits above it and returns the reworded commit's new oid while a dirty tree is refused, unpushed lists only commits missing from every refs/remotes ref, tree_files lists every path at a commit while commit_files still lists the two changed ones, index_files lists tracked and staged-new paths but no untracked file, file_contents reads a file at a commit and on disk as context lines with status unchanged, errors for a path missing from the commit and flags a NUL-byte file binary, the folder scan finds repos at any depth and repos inside repos while skipping node_modules, hidden folders, an empty `.git` folder and anything past the runaway depth guard, returns the discover-shaped path, a root that is itself a repo plus its nested repo, and an error for a missing folder, stage_files/unstage_files apply many paths in one index write, commit refuses an index that matches HEAD (HEAD and worktree untouched) and an empty first commit while a merge resolved to HEAD's tree still commits with two parents, submodules (a synced pull checks an in-sync submodule out at the bumped commit — fetching it — and leaves `git status --porcelain` empty, a synced checkout takes it back with the branch, the group Pull all does the same, a submodule with a local commit or an edited file stays where it is, an unsynced pull reports the drift as FileStatus.submodule recorded/checkedOut and discard_file, discard_all and submodule_update by path all check out the recorded commit, a submodule with only edited files reports no drift), pull_preview is empty when up to date or simply behind, lists the uncommitted files a pull would overwrite (and the real pull then fails), predicts the merge conflict a real pull then reports while leaving HEAD, status and the state files untouched, follows pull.rebase and stops at the first conflicting commit, catches a rebase conflict a merge would not have, reports none for edits that merge cleanly in both modes, and is None without an upstream or on a detached HEAD, commit hooks (a passing pre-commit commits and sees GIT_INDEX_FILE, a failing one blocks with its exit code and output as hook_failed detail and HEAD unchanged, a pre-commit that re-stages a formatted file commits the new content, commit-msg edits reach the commit while an untouched message stays byte-for-byte, a failing or emptying commit-msg blocks, no_verify skips failing hooks on commit and amend, amend runs both hooks with and without a new message, core.hooksPath wins over .git/hooks while `*.sample` and non-executable files never count, config-defined hooks are detected, commit-msg in a linked worktree writes that worktree's COMMIT_EDITMSG, both hooks see GIT_AUTHOR_NAME/EMAIL/DATE of the new commit and amend exports the original author after the identity changed, a pre-commit or commit-msg hook that checks out another branch at the same tip makes commit and amend refuse with both branch tips unchanged; pre-push gets the remote name and URL and a zero remote sha for a new branch, a failing one leaves the bare remote without the new commit and returns its output, a push with tags lists the branch update plus a lightweight and an annotated tag (tag object sha) and an up-to-date repeat sends empty stdin, push_tag runs it, a delete reads `(delete) `, a rejected non-fast-forward is left out while a force push carries the remote's current sha, it runs with empty stdin when nothing needs pushing and can fail that push, no_verify pushes past a failing hook on push and push_tag, core.hooksPath wins, a hook that outlasts an HTTP server's keep-alive timeout still lands the push and runs once, whether the server closes the idle connection or only half-closes it; post-* hooks: a branch switch, a new checked-out branch and a detached checkout run post-checkout with both heads and flag 1 while a branch made without checkout runs nothing, discarding a tracked file, all changes, staged changes and applying a stash file run post-checkout HEAD HEAD 0 once while discarding only untracked files runs nothing, post-merge 0 follows a fast-forward and a merge commit but not up to date or conflicts, amend and reword of HEAD run post-rewrite amend with old and new on stdin while a plain commit runs none, a rebase runs post-checkout orig onto 1 then post-rewrite rebase with one line per commit, a rebase onto HEAD itself or onto an upstream the branch already sits on linearly reports up_to_date, keeps the commits and runs nothing, the rebase's post-checkout sees HEAD at onto and the file without conflict markers although the rebase then stops on that conflict, Pull without hooks that stops on a rebase conflict, or on an untracked file after one commit was replayed, runs no post-rewrite when Continue (no_verify false) completes it, an up-to-date rebase still refuses unstaged or staged changes and a rebase in progress, repo_hooks reports a .husky hooksPath as inside the worktree (and ../shared-hooks or the default as not) and a pulled-in .husky/post-merge runs after a plain pull but not after a pull without hooks, (unix) a dangling `.git/hooks/post-merge` symlink into the worktree, a dangling `.git/hooks` folder symlink and a hook linked through an outside hop to a worktree file count as inside while a symlink to /usr/bin/true does not, a tracked `.husky` link to an empty folder outside counts as inside and the pull that replaces it with a folder holding post-merge runs that hook only without the skip, a hook linked to `proxy/../.husky/post-merge` with proxy linked to a worktree folder counts as inside, a core.hooksPath spelled in other letter case counts as inside exactly when the disk ignores case, an include.path to a tracked project.gitconfig holding only a comment counts as inside and the pull that adds core.hooksPath=.husky plus .husky/post-merge to it runs that hook only without the skip, a rebase goes through with only untracked files in a submodule but not with an edited one, an interactive rebase and the reword of an older commit go through with an edited submodule under `ignore = dirty` while the ordinary rebase still refuses it, and both interactive rebase and reword refuse a staged gitlink change under `ignore = all`, a quoted include through a .git symlink with a trailing space still offers the skip, a config scan that hits its 64-file limit with a tracked include still queued reports the hooks as inside the worktree, discarding three unstaged or two staged files in one call runs post-checkout once after all of them (and none for an untracked-only discard), (unix) a bulk discard records the untracked file it could not delete as failed, still restores the files before and after it and runs post-checkout once, (unix) Discard all staged changes does the same for a staged new file in a read-only folder (the files around it restored, one post-checkout seeing them), Pull all returns while a post-merge background job is running and lets it finish, while Cancel waits for a background job through a Linux pidfd or Windows job and immediately warns for a live macOS group; an exit-0 hook has no cancellation warning, and a setsid child can still write after Cancel without being seen, a fast-forward fails and leaves ORIG_HEAD and HEAD alone while ORIG_HEAD.lock is held and sets ORIG_HEAD once it is gone, and the script the pull brings runs only without the skip, a failing post-checkout's warning comes back next to the error of a replay that then fails, a fast-forward merge sets ORIG_HEAD so the post-merge hook's `git diff --name-only ORIG_HEAD HEAD` lists the new file, Pull all sets ORIG_HEAD to the old tip, a rebase paused on a conflict runs post-checkout and its continue runs post-rewrite once with the pairs from before the pause, an interactive pick + squash + drop runs post-checkout orig result 1, maps both picked commits to the squashed one and leaves the dropped one out, pull with rebase fast-forwards with post-merge when only behind and runs post-checkout + post-rewrite (no post-merge) when diverged while pull with merge runs post-merge and an up-to-date pull nothing, a failing post-checkout or post-merge comes back as a warning with exit code and output while HEAD moved, no_verify suppresses every post hook, Pull all runs post-merge in a repo that fast-forwarded but not in one already up to date, puts a failing hook on that repo's result while it still fast-forwards, and a run started skipping hooks runs none, group pull and the toolbar pull both run post-merge 0 and no post-checkout with core.hooksPath set, worktree add runs post-checkout 000… HEAD 1 inside the new worktree, and (clone_hooks.rs) a clone runs post-checkout 000… HEAD 1 from a global core.hooksPath while a no_verify clone and a clone of an empty repo run none) — skipped with a note when git ≥ 2.36 is not on PATH | | Rust module (110 macOS; platform cases in CI) | `src/commands.rs` (2), `apps/desktop/src-tauri/src/cli.rs` (7), `src/state.rs` (1), `src/editors.rs` (5), `src/fonts.rs` (1), `src/ai_cli.rs` (18 macOS + Linux/Windows cases), `src/error.rs` (10), `src/core/hooks.rs` (12 macOS + Linux/Windows cases), `src/core/remote.rs` (20), `src/core/group_update.rs` (2), `src/terminal.rs` (3), `src/core/accounts.rs` (7), `src/core/sign.rs` (7), `src/forge.rs` (7), `src/proc.rs` (1), `src/watcher.rs` (7) | AI-CLI runner: program allowlist (incl. Cursor's `agent` and `cursor-agent` names), stdout capture via fake agent script, {OUTPUT_FILE} substitution, kill-on-timeout, a timed-out tree capture also killing the grandchild the shell started, a background process holding the pipes after exit not holding up the capture, cancellation waiting for a background job and stopping it at the deadline when a Linux pidfd or Windows job can signal it, macOS tracking a live group but reporting uncertainty immediately, and retain_for_cancel dropping an exit-0 tree, Cursor version-folder keys and the .cmd launcher → newest node.exe/index.js resolution (none for other agents or a missing versions dir) · error mapping: HTTP status extraction from libgit2 messages, 401/402/403 explanations, unmapped codes kept verbatim, io NotFound → not_found while other io errors stay io, hook failures serialize code hook_failed with the output as detail while other errors carry none · hooks: git version parsing incl. Apple and Windows suffixes, author dates in git's raw `@ <±hhmm>` form, runner choice (git for no input or ≥ 2.40, the hook file on unix for 2.36–2.39, a warning otherwise), the pre-push line format (new, up to date left out, delete, unknown remote commit kept), the direct runner handing a hook its args and stdin (unix), a hook without a shebang still getting its args, stdin, env and cwd through sh, only ENOEXEC triggering that retry, git-style whitespace cleanup of an edited message, output tail on a char boundary, post-checkout/post-merge/post-rewrite args and stdin in git's format with identical rebase pairs dropped, post-merge only after ok or fast_forward · forge proxy: api-subdomain host allowlist (dot-anchored), per-provider auth headers, bitbucket email requirement, unknown provider rejected, missing-token vs no-account message · SSH key resolution: `~` expansion, configured key ordered ahead of defaults, dedupe when the configured key IS a default, blank config ignored, generation never targeting an existing key · push refspec shapes (plain/force/tags never forced) · a retried push skips the pre-push hook only for update lines it already approved · rejection message quotes the server lines after the ref list (sideband lines trimmed, de-duplicated, "remote:" and rule lines dropped, capped at 12) · repo account-binding parse (valid/malformed) · accounts: upsert keeps both same-host accounts + default flags, one default per host, preferred-before-default candidate order, port-loose host match, ssh URLs ignored · signing config: off by default, ssh setup read from git config, empty-string values read as unset, ssh-without-key and x509 are clear errors, openpgp falls back to the committer identity, literal-key detection, ~ expansion · proc: no bare `Command::new` anywhere outside proc.rs (G31) · recents: new paths go on top in order, an existing path moves instead of duplicating, the list caps at RECENT_LIMIT · watcher: metadata filter unchanged for main repos, `worktrees/*/HEAD|gitdir|locked` relevant while `worktrees/*/index` is noise, a linked worktree watches its own gitdir + the shared commondir, main repos need no extra roots, a slow watch for the previous repo never replaces the current one, a late stop for the previous repo keeps the current watch, a stop while a watch is in flight drops it | | Unit (341) | `tests/unit/*.test.ts` | actionError (busy responses use info without a failure prefix, other errors keep default or custom formatting), themeContrast (every palette keeps body ≥ 7:1, muted ≥ 5.5:1, faint ≥ 4.5:1 against background and surface, in that order, and defines its own code comment colour), settingsFilter (AND terms, section labels, catalog coverage of every JSX card title), GraphLayout (incl. pagination stability, lane reuse), wordDiff (round-trip), conflict parse/serialize (diff3 labels, CRLF, bare markers, 8+-char content lines, close-without-separator — all lossless), cliAgents (per-agent argv/stdin shape incl. Cursor print mode with the prompt last, ANSI/OSC cleaning, output-file preference, error surfacing), aiProviders (empty/whitespace/missing content rejected for openai-compatible + ollama, HTTP status+body surfaced, real content passes; OpenAI itself gets max_completion_tokens while other compatible hosts and LM Studio keep max_tokens, a rejected temperature is dropped and remembered, a rejected max_tokens or max_completion_tokens swaps once and never loops, an unrelated 400 is not retried, a reasoning model that spent its budget thinking gets one retry at REASONING_MIN_TOKENS that sticks, a budget that ran out without reasoning explains itself), aiCapabilities (review conventions: absent by default, general-only, general+project order with precedence note, whitespace = absent, clipping), aiTextSegments (token parse: adjacent tokens, unclosed/inner-asterisk/multi-line markers stay literal, ** inside backticks is code), reviewSignature (staged-only, order-insensitive, unstaged-edit + set changes alter it, newline filenames don't collide, hashText determinism), commitStyle (prefix rule matching/tokens/ticket-fallthrough, `$`-sequence literalness, preset instructions, post-generation prefix enforcement), pullRequestUrl (https/scp/ssh remotes, non-standard ports kept, http preserved, ssh port dropped, Bitbucket Server /scm/ shape, .git-behind-slash strip, unknown forge → null), aiModels (per-provider list endpoints/headers incl. Groq-style base URLs, generateContent filtering for Gemini, dedupe/sort, invalid-JSON + HTTP-status errors, cli → empty without a request), forge (parseForgeRemote for all three forges + rejects, provider creation gating, github/gitlab/bitbucket adapters: request URLs, field mapping incl. fork + draft detection, create payloads, error-message surfacing incl. github field-level validation entries without a message, checkoutSpec shapes incl. bitbucket fork → null, pickForgeRemote upstream-first ordering, github 403 create refusals explained (fine-grained token into another owner's repo, missing pull request permission, rate limit left verbatim), gitlab self-hosted https→http transport fallback — GET-only (a retried POST could file a duplicate MR), never for gitlab.com or api-level errors, working scheme remembered per host and safe under concurrent fallbacks, reviewer candidates per forge + reviewer ids embedded/requested on create incl. github follow-up failure tolerance, authorAvatar per forge: github commit author, gitlab avatar-by-email URL encoding, bitbucket commit author user), worktree (folder-name slug from repo + branch, sibling-path suggestion incl. Windows separators, parentDirectory), highlight (block-comment continuation: JSDoc carried and closed, line comments and glob strings not treated as open, mid-line close resumes code, xml opener, no-block-comment languages ignore the flag; embedded languages: astro on the xml grammar, svelte/toml mappings, whole-file frontmatter + script/style blocks incl. lang="ts"/"scss" and a single-line script tag, hunk walk from line 1 and mid-file back to the first fence or closer, template-only hunk marks nothing, non-markup → null; shebangs: direct and env forms incl. -S and VAR=val, version suffixes, unknown interpreter and non-shebang → null, name and extension win over the shebang, diffFirstLine prefers the new side and falls back to a deleted file's old side), commitMessage (split/join round-trip, CRLF, second line without blank line is body, newline never enters the summary), fileFilter (empty/whitespace query passes all, case-insensitive substring, every term required), webUrl (https/scp/ssh:// remotes → repository page, ssh port dropped, http + web port kept, Bitbucket Server browse page, Bitbucket Cloud untouched, trailing slash, local path → null), blameable (hasCommittedHistory true for every tracked change kind, false for untracked and staged-new), imageMime (one media type per engine image extension, null otherwise), renderCap (lines at or under 5,000 chars stay whole, longer ones clip and count the hidden tail, custom cap), fork → upstream pull requests (github head `owner:branch`, gitlab GET target id then POST on the source project with target_project_id, bitbucket source.repository, forgeTargets dedupes same-host remotes and defaultForgeTarget prefers `upstream`), allFiles (tree paths marked with their change, deleted files kept, no duplicate paths, foldersWithChanges lists every ancestor of a changed file and nothing otherwise), fetchRemotes (continues after a failure and reports failures), patchText (headers + hunk headers + prefixed lines, rename old path, multi-file join, hasReviewableText rejects null/binary/image/empty), single-file review + explain prompts (file/where/sibling context lines, sibling cap at 30, section labels, conventions order, patch at the end, 4096-token budget), aiReport (labelled sections, bullet severities, continuation lines, verdict tones, unstructured fallback, bold inside a sentence is not a label), locateDiffLine (exact match prefers additions, deletion/context fallback, whitespace-insensitive whole-line hit, tiny/absent snippets null), commit review + explain prompts (commit line, file list capped at 30, conventions, patch at the end), terminalKeys (Alt+Up/Down map to ESC[1;3A/B on keydown only, every other modifier/key/phase left to xterm), chord (key from event.code so ⌥A stays A, unsupported keys null, id round-trip, exact modifier match, per-platform labels, no-modifier/reserved problems per platform, repoForChord lookup), repoGroups (empty/duplicate names ignoring case and the renamed group, least-used colour with wrap, recents bucketed in order with the rest ungrouped, a deleted group's paths fall back to ungrouped while empty groups stay listed, worktree inherits its main's group unless mapped itself, tabClusters/orderRepoTabs cluster open tabs by group with ungrouped last and leave a group-less strip alone, moveRepoGroup places a group before or after another and ignores self or unknown targets), tabLabels (unique names get no hint, nearest distinguishing parent folder, walks further up when parents collide, case-insensitive names and Windows separators), linePairs + pairHunk (the issue #62 hunk, single replacement always one row, comment block before a rewritten line, dissimilar deletion unpaired, pure runs unchanged, positional fallback past the cap, identical lines anchor, the demo load hunk; lineSimilarity ignores punctuation and repeats and compares symbol-only lines by text), remotes (pickRemote upstream → origin → first, pushSetsUpstream only for no upstream or the same remote), diffLocation (new line number for additions and context, old number and old path for a deletion, the clicked split pane wins, column only when given, none without a number on that side; columnAt counts characters from one, an emoji as one, nothing past the text or inside the clipped tail of a line over 5,000 characters) | | E2E (153) | `tests/e2e/smoke.spec.ts` | the AI button in the commit message editor keeps the summary focused after the click and Escape closes the editor while the stubbed Ollama /api/chat answer is held (the late answer is discarded), then fills summary + description from the commit's own diff and saves, folder rows in the working-copy tree stage and unstage everything inside them (one engine call each, chevron still folds, indeterminate in All files), stepping with n / the header chevron / p marks the active change rows and counts "k of n changes" in inline, split and wrapped views, View options stays open across two toggles, Settings filter (autofocus, SSH-only, first catalog hit across sections, locate flash, section-label match, no results, Escape clears then closes, close resets, AI section preset), splash→welcome, the AI chip names Ollama on the demo defaults, reads Set up AI when the CLI provider has no agent, Claude Code once picked, turns ok after Test connection, stale when the provider changes back to Ollama, and survives a reload, Blame is disabled in the file menu and the diff header for the untracked demo file while a tracked file keeps it enabled, the remote row menu's Open in browser opens the demo remote's GitHub page in a popup and the palette lists Open repository in browser, the sidebar and graph branch menus carry a fast-forward entry next to merge that is disabled while the current branch is ahead, settings installs the command line tool, settings lists the demo editors and picking Zed relabels the toolbar button and its menu, the Pull options menu offers merge and rebase, the status bar reports Fetched just now after the auto fetch, retries every remote after a partial auto fetch failure, keeps the timestamp and faint failed remote hint through partial and offline fetches, updates the timestamp on Pull, and explains the disabled Fetch button when no remotes exist, the diff header's Blame button opens file history in the blame pane with the Working copy row selected, per-hunk author buttons and an uncommitted hunk that disappears when a commit row is picked, a Blame at this commit menu, the Diff view toggle brings the diff controls back and Escape returns to the graph, the palette's Blame… picks a file and opens its blame pane, open repo, graph, inspector, palette, search, conflict resolver line picks, single-conflict nav + per-conflict take-all, per-block conflict hand edit, interactive rebase dialog + multi-select squash, cherry-pick dialog with the source-reference checkbox on by default, multi-select cherry-pick listing both commits and confirming, diff auto-jump lands at the first change with no scroll animation (frame-traced scrollTop), long path stays inside the discard confirm dialog, commit action buttons stay inside a narrow working copy panel (the row wraps), sidebar branch names align with and without the HEAD tick (measured left offsets), hovering a working-copy file reveals its full path, opening a diff folds the sidebar away and the toggle brings back the graph, avatars stay visible after a diff open/close round-trip (stubbed Gravatar), diff text selection survives the right-click copy menu and Esc closes only the menu, sidebar lists the demo pull requests and the create dialog opens, reconnecting an account opens the prefilled token form with focus in the token field, a file history row's Open commit button closes the panel and selects that commit in the graph, the author box finds commits with the graph lanes intact and combines with the text search, commit search finds matches in the full graph (n of m pill, Enter/Previous step, query survives selecting another commit, Escape clears), a search result that lands after a click keeps the clicked commit selected while clicking a match moves the pill to 2 of n and Enter steps to 3, searching a commit hash jumps to it in the full graph, a short hash prefix jumps too while an unknown hex word says No matches, a missing hash keeps the graph with No matches, mod+f focuses the commit search, sidebar lists the demo worktrees (incl. a missing-folder row) and the new-worktree dialog re-suggests the folder as the branch name is typed, the inner line of a JSDoc block in the demo CommitGraph.tsx diff renders as one hljs-comment span (guards the DiffViewer → prepareCommentStates wiring, which the unit tests cannot see), collapse-all folds every section and branch folder and a reopened section comes back with its folders closed, the inspector keeps its width (±1px) when a diff folds the sidebar away and both widths return on Escape (measured via data-panel-id after dragging the sidebar handle), the commit box renders the summary larger and bolder than the description with Enter/Backspace moving between them and commit disabled on an empty summary, dragging the commit box's top edge grows the description and double-click resets it, the Changes header's fold button collapses that list's folders (nested file hidden) and flips to expand-all, and no fold button exists in flat mode, the top graph row shows a whole `main` chip with no HEAD chip and no clipped chip text plus a 7-char hash copy button, the graph display menu hides the hash column and brings it back, the sidebar accordion pins collapsed headers at the bottom under an open Branches section and moves the Tags header up when Tags opens, the welcome page flags the demo's missing folder and opens a repository via ↓ + ⏎ from the autofocused search, the conflict resolver renders positive integer line numbers in A, B and Result with each starting at 1, the checked-out branch chip is opaque while another local branch's chip stays translucent, double-clicking the separated `origin/main` chip opens the reset prompt naming the 2 commits that would be lost and Cancel dismisses it (the demo repo puts origin/main 2 commits behind main so the split is real), the diff header's History button opens that same file's history panel and closes the diff, a working-copy row's "Stash this file…" opens the dialog naming that file and the toolbar pop button restores the latest demo stash, shift-click selects three working-copy rows and the bulk menu offers Stage 3 / Stash 3 files, the working-copy filter hides non-matching rows with "1 of 2" counts and the clear button restores them, the commit file filter narrows five demo files to one and Escape resets it, selecting the demo stash shows the stash hint and the hover restore button on a file toasts the restore, right-clicking a plain commit's file offers File history / Show in Finder / Copy path and no stash Apply entry, staged rows offer discard from the row, the menu and the header trash icon, the sidebar is visible again after a reload that happened with a diff open, the demo stash renders as a graph row with an Archive node and a dashed chip whose menu pops it, ↓ then → opens the second commit's first file with the file list focused, ↓/↑ walk files, twelve → presses stay on the same file and one ← returns to the graph on the same commit, the Graph display menu's "Lane color band" removes and restores the tail rects, the inspector stops at its minimum width when dragged and folds/returns for file history, dragging the sidebar shut and back open in one gesture shows its content again, conflict picks land in file order with a mixed-state side checkbox, the resolver picks with A/B/↑/↓ and ⌘⏎ opens the next conflicted file, leaving with picks asks first while Escape closes a clean resolver, right-clicking the main tip row offers Push main ↑2 while an inner commit's menu has no push, hovering the feature/diff-viewer chip stacks both its refs in a panel whose first chip sits on the row chip (≤2px) with the folded `release/0.4` under it, and right-clicking that one opens its Checkout menu (no reset entry for a plain local), the top row shows `main` as its visible chip although `hotfix/lane-colors` comes first in the refs and only `main` carries the check inside the stacked panel, right-clicking the separated `origin/main` chip offers "Reset main to this…" and opens the same reset dialog, clicking a working-copy file then ↓/↓/↑ moves the diff through ipc.ts → palette-seed.sql → Architecture.md and back — the Remotes header's Add remote button opens the add dialog with the button disabled until name and URL are filled, right-clicking the terminal shows Copy (disabled without a selection)/Paste/Select all/Clear terminal, Settings → Git → Clone destination remembers a chosen folder and the clone dialog's destination starts there, a four-row drag selection in the palette-seed diff stays a Range and still copies all four lines via ⌘C after its rows scroll out of the virtualizer in either direction, and reads the same text once scrolled back, the pushed demo commit opens the editor and Save asks "Rewrite a pushed commit?" (Cancel keeps the draft) while the top commit opens the inline editor on double-click (Esc cancels, Save rewrites the heading, body and graph row), the GitHub account form keeps the classic token link and adds the fine-grained page inline while the Token label still focuses the input, the Fonts card's Interface picker lists proportional fonts first and Code lists monospace first, picking Helvetica Neue/Fira Code changes --font-sans/--font-mono and the terminal follows Code until Menlo + 16 px is picked for it, all of it survives a reload and Reset fonts clears it, sidebar section headers and bodies carry no fill and no top border while each header shows a filled gold icon tile and a filled count badge, the commit Files header's A token narrows five files to one with All pressed off and back, the All files view lists Roadmap.md at the commit with 5 changed, keeps a change-free folder collapsed until clicked, opens the unchanged file with an unchanged badge and no @@ header while Folder tree hides it again, the working copy's All files view shows README.md beside the stage/unstage checkboxes of the changed files and opens it without a Stage file button, dragging a selection below the diff grows it past six lines from the start row and ⌘C copies the same text before and after scrolling away, the diff header's AI actions menu reviews the open file (busy strip → demo response under the header, Copy, fold to one line and back, full-view dialog, button disabled meanwhile, closing and reopening the diff dismisses the result) then explains it and Dismiss removes the panel, the inspector's Review with AI reviews the selected commit (Stop reviewing while busy, AI review card → demo response, Dismiss), file history's diff pane shows no change arrows on a commit that did not touch palette-seed.sql and, on the Working copy row, `n` jumps the scroller to the one change, `p` from the top wraps to it and the header's Next change button lands on the same offset, a second repo opened from the palette becomes a tab that ⌘1 / ⌘⇧] switch between (wrapping), the tab menu's Keyboard shortcut… capture box flags a bare `t` as no_modifier and ⌘K as reserved without opening the palette, saving ⌃⇧T shows the chip on the tab and the chord switches to it, and Settings → Shortcuts lists and removes it, Force push from the Push menu opens a "Force push?" confirm naming origin/main that Cancel dismisses without pushing, and repositories can be grouped on the welcome page: Add to group → New group… creates Frontend with a picked colour (Create disabled on an empty name, a duplicate name shows the taken hint), dragging a row onto the header moves it (counts 2 and 2), Enter in the name field creates Backend, the header menu's Move up puts Backend first (Move down disabled at the bottom) and Move down restores it, the header button collapses and re-expands it, searching flattens the list to the two matching rows, Open all in tabs opens both Frontend repos as tabs whose titles end in · Frontend, the tab menu's Move to group re-homes one to Backend and the strip splits into two clusters with chips, clicking the Backend chip hides its tab and shows Backend1, collapsing Frontend keeps the active tab visible, ⌘2 switches to the hidden temple-ui and reveals it, both chips expand again, the Backend chip's menu counts 1 under Close its tabs and Collapse other groups folds Frontend to Frontend1 while ⌘1 still reaches its hidden tab, Expand all groups brings both back, dragging the Backend chip onto the first cluster's left edge puts Backend first so ⌘1 reaches temple-ui and dragging it back restores Frontend, narrowing the window to 300px shows the overflow list whose temple-ui entry switches tabs and widening hides it again, no separators or overflow button exist with two tabs, the switcher lists repos under data-switcher-group labels, the palette's Close all in Backend closes its one open tab while Open all in Backend says 2 repositories, and Ungroup… confirms and leaves the repos in the list, the long-line diff scrollbar stays at the viewport bottom, pans both split panes together, accepts arrow keys and Shift+wheel, and disappears when wrapping is enabled, the code diff opened from a selected commit also scrolls horizontally in inline and split views, and a trackpad pan of one wheel event per frame moves the long-line diff by the whole gesture with no backward step, dragging the drawn thumb moves the layers by exactly the engine's scrollLeft and a click on the track pages back to 0, and a text selection dragged past the pane's right edge pans the long lines, grows the selection and stops panning when the pointer comes back, scanning ~/projects from the welcome page lists four repos with two marked In recents and disabled, unticking one adds the other to the recents list, a seeded tab whose folder is missing closes with a toast while two same-named angkorgit tabs show forks / projects hints and a unique one shows none, ⌘P on the welcome page filters four recents to temple-ui and Enter opens it as the only tab, ⌘P marks it Current and opens angkorgit as a second tab, a third ⌘P marks temple-ui Open tab and switches back without a new tab, ⌘K still opens the command palette, and ⌘T opens a picked folder as a third tab, the all files layout stacks the five demo commit files with GraphRow.tsx scrolled to the top and "2 of 5", clicking Architecture.md in the inspector scrolls it to the top ("4 of 5"), side by side applies inside the cards, a user wheel at the top moves the inspector highlight to CommitGraph.tsx, one file and then all files collapse and expand, Show one file returns to DiffPanel and the choice survives a reload, clicking a file in the inspector still jumps to it after scrolling reached it once and ← inside the page returns to the graph, a stash file never offers the all files layout even with 'all' remembered while a plain commit still gets it, a click into a file diff followed by ← closes it and returns to the graph, ⌘⏎ with nothing staged toasts "Stage some changes first" and commits nothing, and a file filter that hides every staged file leaves Commit enabled with the full count, and eleven tabs shrink to fit an 820px window with the inactive close buttons gone and no overflow button, scroll past their 48px floor at 480px and come back to their natural widths at 1440px, and What's new opens from the welcome footer and the status bar bell with its unread dot cleared once seen and after a reload, and a drifted demo submodule row has no Discard button, its menu offers Update submodule to efec64c without Discard changes…, and its hover Update button toasts the checkout and clears the row, and the Pull button carries a conflict warning whose tooltip names the files, opens "This pull will conflict" (Cancel closes, Pull and resolve pulls), switches to "Your changes are in the way" whose Stash 2 files… opens the stash dialog with those files, and shows no warning without a predicted problem, and a failing demo pre-commit hook opens the hook dialog with ANSI-free lint output (Close keeps the message and commits nothing, Commit without hooks commits) while a ticked Skip hooks commits directly and clears itself, and a repo without hooks shows no Skip hooks box, and a hook that fails after switching to another tab only toasts "Nothing was committed in angkorgit" there (no dialog, no commit, the other tab never shows Running hooks…) while the first tab keeps its draft and shows the waiting failure when the user returns, a commit hook keeps Commit busy as Running hooks… across selecting a graph commit and coming back and its failure dialog appears while the graph commit is shown, and Commit without hooks never reads Running hooks… while text typed during the run survives the commit, and a failing demo pre-push hook makes the toolbar Push open "A hook stopped the push" with ANSI-free test output while the Push menu offers Push without hooks (absent in a repo without hooks) and the dialog's Push without hooks pushes main, and after a Push without hooks that the remote rejects as non-fast-forward the dialog's Force push keeps skipping the hook and pushes main forced, and when develop was checked out while the hook ran the rejected dialog still names origin/main with Pull with rebase disabled ("Check out main first…") and Cancel focused, nothing pulls, and once main is checked out again the same dialog enables and focuses Pull with rebase, which pulls, and a graph chip takes its lane colour while every lane line is a rail (no cubic curves) and the WIP banner is opaque, a 14-lane demo history scrolls the graph sideways by exactly each wheel step, by the drawn thumb and back to 0 on a track click while vertical scrolling stays put, and dragging the Graph header edge narrows the column and its scrollbar, survives a reload and double-click resets it, and a running demo post-checkout shows a loading toast and responds to a second checkout with an info toast naming post-checkout and the repository, with no red failure toast, and a failing demo post-checkout hook shows a warning toast after "Checkout develop done" whose Show output opens the warning dialog with ANSI-free output and only Copy output and Close, the Pull menu's Pull without hooks pulls without the post-merge warning a plain Pull then shows (and is absent without hooks), and Pull all puts a post-merge warning with a collapsed Hook output on every updated row ("2 hook warnings") while Pull all without hooks from the group menu shows none, and a hook folder inside the worktree offers Pull without hooks and Pull all without hooks before any hook exists (but no Push without hooks), and the Pull menu shows Pull without hooks after the hook setup changed between two opens, Pull without hooks with a predicted conflict opens "This pull will conflict" first and Pull and resolve then pulls without the post-merge warning, and discarding three selected files shows one post-checkout warning, while a bulk discard that fails for one file names it with the reason and shows no success toast, and so does the Staged header's Discard all staged changes, and the Only matches toggle narrows a "merge" search to the matching commits with "n matching commits", steps them with Enter and brings the full graph back on the same commit, also when the search box is cleared — all on demo mode, and a squeezed same-name tab hint stays at least 18px wide in a 480px window, and graph nodes whose lanes leave the column stay inside it, pinned to an edge, at rest and after scrolling right, and right-clicking the 7th character of a diff line offers Copy path and line with `path:line:7` (copied, toast) while a right-click past the end of the text drops the column, and two cmd-selected commits offer Compare these commits, which puts a From/To header over the newer commit's file list (no message editor or AI buttons), opens a file diff and the all files layout labelled `older..newer`, swaps the direction from the header and leaves compare mode on a plain click, while three selected commits get no Compare entry, and switching to light and back recolours every element on the repo page in the same frame while hover fades keep their duration | diff --git a/apps/desktop/src-tauri/src/core/post_hooks.rs b/apps/desktop/src-tauri/src/core/post_hooks.rs index 21fc21c6..987a0dce 100644 --- a/apps/desktop/src-tauri/src/core/post_hooks.rs +++ b/apps/desktop/src-tauri/src/core/post_hooks.rs @@ -239,17 +239,20 @@ pub fn discard_files( staged: bool, no_verify: bool, ) -> AppResult> { + if staged { + let (batch, restored_any) = stage::discard_staged_files_reporting(path, files)?; + return Ok(if restored_any { + restored(path, batch, no_verify) + } else { + Hooked::plain(batch) + }); + } let repo = super::repo::open(path)?; let mut batch = DiscardBatch::default(); let mut restored_any = false; for file in files { - let restores = staged || restores_from_index(&repo, file).unwrap_or(false); - let result = if staged { - stage::discard_staged_file(path, file) - } else { - stage::discard_file(path, file) - }; - match result { + let restores = restores_from_index(&repo, file).unwrap_or(false); + match stage::discard_file(path, file) { Ok(clean) => { restored_any |= restores; if !clean { diff --git a/apps/desktop/src-tauri/src/core/stage.rs b/apps/desktop/src-tauri/src/core/stage.rs index 7ee8b31b..45c297ca 100644 --- a/apps/desktop/src-tauri/src/core/stage.rs +++ b/apps/desktop/src-tauri/src/core/stage.rs @@ -1,6 +1,6 @@ -use std::path::Path; +use std::path::{Path, PathBuf}; -use git2::{ApplyLocation, DiffFormat, DiffOptions, Repository}; +use git2::{ApplyLocation, DiffFormat, DiffOptions, Index, IndexEntry, IndexTime, Repository}; use super::types::{DiscardBatch, DiscardFailure}; use crate::error::{AppError, AppResult}; @@ -152,9 +152,11 @@ pub fn discard_all(path: &str) -> AppResult> { } pub fn discard_staged_file(path: &str, file: &str) -> AppResult { - let repo = super::repo::open(path)?; - discard_to_head(&repo, file)?; - Ok(!touched_paths(&repo)?.iter().any(|p| p == file)) + let (batch, _) = discard_staged(path, Some(&[file.to_string()]))?; + if let Some(failure) = batch.failed.into_iter().next() { + return Err(AppError::other(failure.message)); + } + Ok(batch.leftovers.is_empty()) } pub fn discard_staged_all(path: &str) -> AppResult> { @@ -166,83 +168,214 @@ pub fn discard_staged_all(path: &str) -> AppResult> { } pub(crate) fn discard_staged_all_reporting(path: &str) -> AppResult<(DiscardBatch, bool)> { + discard_staged(path, None) +} + +pub(crate) fn discard_staged_files_reporting( + path: &str, + files: &[String], +) -> AppResult<(DiscardBatch, bool)> { + discard_staged(path, Some(files)) +} + +fn discard_staged(path: &str, selected: Option<&[String]>) -> AppResult<(DiscardBatch, bool)> { let repo = super::repo::open(path)?; - let mut opts = git2::StatusOptions::new(); - opts.include_untracked(false); - let statuses = repo.statuses(Some(&mut opts))?; - let staged: Vec = statuses - .iter() - .filter(|e| { - e.status().intersects( - git2::Status::INDEX_NEW - | git2::Status::INDEX_MODIFIED - | git2::Status::INDEX_DELETED - | git2::Status::INDEX_RENAMED - | git2::Status::INDEX_TYPECHANGE, - ) - }) - .filter_map(|e| { - e.head_to_index() - .and_then(|d| d.old_file().path().map(|p| p.to_string_lossy().to_string())) - .or_else(|| e.path().map(String::from)) - }) - .collect(); - let renamed_targets: Vec = statuses - .iter() - .filter(|e| e.status().contains(git2::Status::INDEX_RENAMED)) - .filter_map(|e| { - e.head_to_index() - .and_then(|d| d.new_file().path().map(|p| p.to_string_lossy().to_string())) - }) - .collect(); - drop(statuses); + let workdir = repo + .workdir() + .ok_or_else(|| AppError::other("bare repository"))? + .to_path_buf(); + let lock = IndexLock::acquire(&repo)?; + let files = staged_targets(&repo, selected)?; let mut batch = DiscardBatch::default(); let mut restored_any = false; - for file in staged.iter().chain(renamed_targets.iter()) { - match discard_to_head(&repo, file) { - Ok(()) => restored_any = true, + if files.is_empty() { + return Ok((batch, restored_any)); + } + let head_tree = repo.head().ok().and_then(|h| h.peel_to_tree().ok()); + let (removals, restores): (Vec<_>, Vec<_>) = files + .into_iter() + .map(|file| { + let entry = head_tree + .as_ref() + .and_then(|tree| tree.get_path(Path::new(&file)).ok()) + .filter(|entry| entry.kind() != Some(git2::ObjectType::Tree)); + (file, entry) + }) + .partition(|(_, entry)| entry.is_none()); + let mut index = lock.index()?; + let mut processed = Vec::new(); + for (file, entry) in removals.into_iter().chain(restores) { + let result = match (&head_tree, &entry) { + (Some(tree), Some(entry)) => restore_from_head(&repo, tree, &mut index, &file, entry), + _ => remove_staged_addition(&workdir, &mut index, &file), + }; + match result { + Ok(()) => { + restored_any = true; + processed.push(file); + } Err(error) => batch.failed.push(DiscardFailure { - path: file.clone(), + path: file, message: error.to_string(), }), } } + if restored_any { + lock.publish(index)?; + } let remaining = touched_paths(&repo)?; - batch.leftovers = staged + batch.leftovers = processed .into_iter() - .chain(renamed_targets) - .filter(|p| remaining.contains(p) && !batch.failed.iter().any(|failure| &failure.path == p)) + .filter(|p| remaining.contains(p)) .collect(); Ok((batch, restored_any)) } -fn discard_to_head(repo: &git2::Repository, file: &str) -> AppResult<()> { - let workdir = repo - .workdir() - .ok_or_else(|| AppError::other("bare repository"))? - .to_path_buf(); - let head_tree = repo.head().ok().and_then(|h| h.peel_to_tree().ok()); - let in_head = head_tree - .as_ref() - .map(|t| t.get_path(Path::new(file)).is_ok()) - .unwrap_or(false); - if in_head { - let tree = head_tree.as_ref().expect("checked above"); - let mut builder = git2::build::CheckoutBuilder::new(); - builder.path(file).force(); - repo.checkout_tree(tree.as_object(), Some(&mut builder))?; - } else { - let mut index = repo.index()?; - let _ = index.remove_path(Path::new(file)); - index.write()?; - let full = workdir.join(file); - if full.is_file() || full.is_symlink() { - std::fs::remove_file(full)?; +fn staged_targets(repo: &Repository, selected: Option<&[String]>) -> AppResult> { + let mut opts = git2::StatusOptions::new(); + opts.include_untracked(false).renames_head_to_index(true); + let statuses = repo.statuses(Some(&mut opts))?; + let staged = git2::Status::INDEX_NEW + | git2::Status::INDEX_MODIFIED + | git2::Status::INDEX_DELETED + | git2::Status::INDEX_RENAMED + | git2::Status::INDEX_TYPECHANGE; + let groups: Vec> = statuses + .iter() + .filter(|e| e.status().intersects(staged)) + .map(|e| { + let delta = e.head_to_index(); + let old = delta + .as_ref() + .and_then(|d| d.old_file().path().map(path_string)); + let new = delta.and_then(|d| d.new_file().path().map(path_string)); + let mut paths: Vec = old.into_iter().chain(new).collect(); + paths.dedup(); + if paths.is_empty() { + paths.extend(e.path().map(String::from)); + } + paths + }) + .collect(); + let mut seen = std::collections::HashSet::new(); + let mut targets = Vec::new(); + let mut take = |paths: &[String]| { + for path in paths { + if seen.insert(path.clone()) { + targets.push(path.clone()); + } } + }; + match selected { + None => groups.iter().for_each(|group| take(group)), + Some(files) => { + for file in files { + match groups.iter().find(|group| group.contains(file)) { + Some(group) => take(group), + None => take(std::slice::from_ref(file)), + } + } + } + } + Ok(targets) +} + +fn path_string(path: &Path) -> String { + path.to_string_lossy().to_string() +} + +fn restore_from_head( + repo: &Repository, + tree: &git2::Tree, + index: &mut Index, + file: &str, + entry: &git2::TreeEntry, +) -> AppResult<()> { + let mut builder = git2::build::CheckoutBuilder::new(); + builder + .path(file) + .disable_pathspec_match(true) + .force() + .update_index(false); + repo.checkout_tree(tree.as_object(), Some(&mut builder))?; + index.remove_path(Path::new(file))?; + index.add(&IndexEntry { + ctime: IndexTime::new(0, 0), + mtime: IndexTime::new(0, 0), + dev: 0, + ino: 0, + mode: entry.filemode() as u32, + uid: 0, + gid: 0, + file_size: 0, + id: entry.id(), + flags: 0, + flags_extended: 0, + path: file.as_bytes().to_vec(), + })?; + Ok(()) +} + +fn remove_staged_addition(workdir: &Path, index: &mut Index, file: &str) -> AppResult<()> { + let full = workdir.join(file); + if full.is_file() || full.is_symlink() { + std::fs::remove_file(full)?; } + index.remove_path(Path::new(file))?; Ok(()) } +struct IndexLock { + lock: PathBuf, + index: PathBuf, + held: bool, +} + +impl IndexLock { + fn acquire(repo: &Repository) -> AppResult { + let lock = repo.path().join("index.lock"); + match std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&lock) + { + Ok(_) => Ok(Self { + lock, + index: repo.path().join("index"), + held: true, + }), + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => { + Err(AppError::other(format!( + "Another Git process is using this repository ({} exists), so nothing was discarded. If no Git process is running, delete that file and try again.", + lock.display() + ))) + } + Err(error) => Err(error.into()), + } + } + + fn index(&self) -> AppResult { + std::fs::copy(&self.index, &self.lock)?; + Ok(Index::open(&self.lock)?) + } + + fn publish(mut self, mut index: Index) -> AppResult<()> { + index.write()?; + drop(index); + std::fs::rename(&self.lock, &self.index)?; + self.held = false; + Ok(()) + } +} + +impl Drop for IndexLock { + fn drop(&mut self) { + if self.held { + let _ = std::fs::remove_file(&self.lock); + } + } +} + fn touched_paths(repo: &git2::Repository) -> AppResult> { let mut opts = git2::StatusOptions::new(); opts.include_untracked(true).recurse_untracked_dirs(true); diff --git a/apps/desktop/src-tauri/tests/git_engine.rs b/apps/desktop/src-tauri/tests/git_engine.rs index 7688e269..03c2bf43 100644 --- a/apps/desktop/src-tauri/tests/git_engine.rs +++ b/apps/desktop/src-tauri/tests/git_engine.rs @@ -490,6 +490,124 @@ fn discard_staged_file_restores_head_for_index_and_worktree() { assert_eq!(core::status(repo.path()).unwrap().files.len(), 0); } +fn staged_paths(repo: &TempRepo) -> Vec { + let mut paths: Vec = core::status(repo.path()) + .unwrap() + .files + .into_iter() + .filter(|f| f.staged.is_some()) + .map(|f| f.path) + .collect(); + paths.sort(); + paths +} + +#[test] +fn discarding_a_staged_file_with_glob_characters_leaves_the_files_it_matches() { + let repo = TempRepo::new(); + repo.write("[ab].txt", "pattern\n"); + repo.write("a.txt", "a\n"); + commit_all(&repo, "base"); + repo.write("[ab].txt", "pattern staged\n"); + repo.write("a.txt", "a staged\n"); + core::stage_all(repo.path()).unwrap(); + + assert!(core::discard_staged_file(repo.path(), "[ab].txt").unwrap()); + assert_eq!(repo.read("[ab].txt"), "pattern\n"); + assert_eq!(repo.read("a.txt"), "a staged\n"); + assert_eq!(staged_paths(&repo), vec!["a.txt"]); + + repo.write("[ab].txt", "pattern staged again\n"); + core::stage_all(repo.path()).unwrap(); + let batch = core::post_hooks::discard_files(repo.path(), &["[ab].txt".to_string()], true, true) + .unwrap(); + assert!(batch.value.failed.is_empty()); + assert_eq!(repo.read("[ab].txt"), "pattern\n"); + assert_eq!(repo.read("a.txt"), "a staged\n"); + assert_eq!(staged_paths(&repo), vec!["a.txt"]); +} + +#[test] +fn a_staged_discard_changes_nothing_while_another_process_holds_the_index_lock() { + let repo = TempRepo::new(); + repo.write("a.txt", "a\n"); + commit_all(&repo, "base"); + repo.write("a.txt", "staged\n"); + repo.write("fresh.txt", "new\n"); + core::stage_all(repo.path()).unwrap(); + let lock = repo.dir.join(".git/index.lock"); + std::fs::write(&lock, "held by someone else").unwrap(); + + let error = core::discard_staged_all(repo.path()).unwrap_err(); + assert!(error.to_string().contains("index.lock")); + assert!( + core::post_hooks::discard_files(repo.path(), &["a.txt".to_string()], true, true).is_err() + ); + assert_eq!(repo.read("a.txt"), "staged\n"); + assert_eq!(repo.read("fresh.txt"), "new\n"); + assert_eq!( + std::fs::read_to_string(&lock).unwrap(), + "held by someone else" + ); + + std::fs::remove_file(&lock).unwrap(); + assert_eq!(staged_paths(&repo), vec!["a.txt", "fresh.txt"]); + assert!(core::discard_staged_all(repo.path()).unwrap().is_empty()); + assert_eq!(repo.read("a.txt"), "a\n"); + assert!(!repo.dir.join("fresh.txt").exists()); + assert!(!lock.exists()); + assert!(core::status(repo.path()).unwrap().files.is_empty()); +} + +#[test] +fn discarding_either_path_of_a_staged_rename_restores_the_original() { + let repo = TempRepo::new(); + repo.write("old.txt", "same content for rename detection\n"); + commit_all(&repo, "base"); + for selected in ["new.txt", "old.txt"] { + std::fs::rename(repo.dir.join("old.txt"), repo.dir.join("new.txt")).unwrap(); + core::stage_all(repo.path()).unwrap(); + let status = core::status(repo.path()).unwrap(); + assert!(status + .files + .iter() + .any(|f| f.path == "new.txt" && f.orig_path.as_deref() == Some("old.txt"))); + + let batch = + core::post_hooks::discard_files(repo.path(), &[selected.to_string()], true, true) + .unwrap(); + assert!(batch.value.failed.is_empty()); + assert!(batch.value.leftovers.is_empty()); + assert_eq!(repo.read("old.txt"), "same content for rename detection\n"); + assert!(!repo.dir.join("new.txt").exists()); + assert!(core::status(repo.path()).unwrap().files.is_empty()); + assert!(!repo.dir.join(".git/index.lock").exists()); + } +} + +#[test] +fn discarding_a_folder_replaced_by_a_staged_file_restores_the_folder() { + let repo = TempRepo::new(); + repo.write("dir/inner.txt", "inner\n"); + repo.write("keep.txt", "keep\n"); + commit_all(&repo, "base"); + std::fs::remove_dir_all(repo.dir.join("dir")).unwrap(); + repo.write("dir", "now a file\n"); + repo.write("keep.txt", "keep staged\n"); + core::stage_all(repo.path()).unwrap(); + + let batch = core::post_hooks::discard_files( + repo.path(), + &["dir".to_string(), "dir/inner.txt".to_string()], + true, + true, + ) + .unwrap(); + assert!(batch.value.failed.is_empty(), "{:?}", batch.value.failed); + assert_eq!(repo.read("dir/inner.txt"), "inner\n"); + assert_eq!(staged_paths(&repo), vec!["keep.txt"]); +} + #[test] fn history_shows_stashes_as_single_parent_commits_and_hides_their_helpers() { let repo = TempRepo::new(); From 23b23022bb657f5347af7a4ce1490522bbe409e2 Mon Sep 17 00:00:00 2001 From: cheat2001 Date: Fri, 13 Nov 2026 16:17:39 +0700 Subject: [PATCH 2/2] docs(changelog): the staged discard stops on a held index lock --- CHANGELOG.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e511ed58..1c043d8e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,9 +47,9 @@ All notable changes to AngKorGit are documented here. The format follows ### Fixed - **Discarding staged changes writes the index once and leaves other files alone.** A file whose name contains `[`, `]`, `*` or `?` no longer resets files the name - happens to match. The whole batch waits for Git's index lock and changes nothing - while another Git process holds it. Picking either name of a staged rename - restores the original file. + happens to match. The whole batch takes Git's index lock and stops without + changing anything when another Git process holds it. Picking either name of a + staged rename restores the original file. - **New worktrees stay protected while their post-checkout hook runs.** The target folder is reserved before creation, including access through a symlink alias, so another operation gets an info toast until the hook finishes.