diff --git a/CHANGELOG.md b/CHANGELOG.md index 403f58b3..394cc454 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,62 @@ All notable changes to AngKorGit are documented here. The format follows ## [Unreleased] +### Added +- **Checkouts, merges and rewrites run your `post-*` hooks.** `post-checkout`, + `post-merge` and `post-rewrite` now run after the operations that run them in `git`, + with the same arguments and input: + - `post-checkout` after a checkout, a new branch you check out, a detached checkout, + a pull request checkout, a clone, a new worktree, and after discarding or applying + files from a stash (`git restore` runs it too, with flag `0`). + - `post-merge` after a merge or a pull that merged or fast-forwarded. + - `post-rewrite` after amend, reword, rebase, interactive rebase and a pull with + rebase, once with every rewritten commit, also when a paused rebase is continued. + As in `git`, a failing hook never undoes the operation: AngKorGit shows a warning + with **Show output** instead of an error. AngKorGit attempts to stop a foreground + hook at its 10-minute limit and reports a timeout with any captured output. The + warning says when exit could not be confirmed. **Skip hooks** in the commit box + also skips `post-rewrite` when amending, and the Pull menu has **Pull without hooks** when the + repository has one of these hooks, or keeps its hooks in a folder inside the repository + (like `.husky`), links a hook to a file there, or includes a Git config file from the + repository, where a pull can bring a new one. A rebase you started without hooks + stays without hooks when you continue it after a conflict. (#82) +- **Pull all runs `post-merge` in each repository it fast-forwarded.** One at a time, + never for a repository that was already up to date; a failing hook shows as a warning + with its output on that repository's row and the rest of the group still updates. + **Pull all without hooks** in the group menu skips it. **Cancel** waits for the + checkout and foreground hook already in progress. During that wait, it monitors + tracked background hooks and requests termination at each hook's original deadline. + On macOS and on Linux without usable process-group pidfd support, Cancel can finish + while background hook processes are still running. The affected repository's row + warns that exit could not be confirmed. Those processes may keep writing to the + repository past the hook's original deadline. (#69, #82) + +### Changed +- **Rebasing a branch that already sits on top of its target does nothing**, like + `git rebase`: it reports "Already up to date" instead of re-creating the branch's + commits with new commit dates. Uncommitted changes or an unfinished operation still + stop it first. +- **Fast-forward merges and pulls set `ORIG_HEAD`** to the commit you were on, like + `git merge` does, so `git diff ORIG_HEAD HEAD` shows what a pull brought in. + +### Fixed +- **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. +- **Aborting a rebase while post-checkout runs no longer reports a missing rebase + state file.** Once the hook returns, the rebase reports that it was aborted and + leaves the restored branch untouched, without replaying commits or post-rewrite. +- **A running hook gets an info toast when you try another operation.** It names + the hook and repository, such as "post-checkout is still running in angkorgit", + while the progress toast stays visible. +- **Cancel no longer warns about hooks that already finished.** Pull all treats an + empty hook process group as finished on macOS and Linux, including an `exit 0` hook. + A live group without a safe signalling handle still warns immediately. Children + that leave the group with `setsid` or daemonize are not tracked, as with Git. +- **Discarding several files, or all staged changes, no longer stops at a file it + cannot discard.** The other files are still restored, and AngKorGit names the files + it could not discard instead of reporting every change as discarded. + ## [0.27.0] — 2026-11-09 The review release. Text is easier to read in every theme, diffs are calmer to review, diff --git a/CLAUDE.md b/CLAUDE.md index 58e5aa52..7f4912c2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -36,7 +36,7 @@ craftsmanship from Cambodia 🇰🇭. | Router | react-router-dom 6 (MemoryRouter: `/welcome`, `/repo`) | | | Icons / fonts | lucide-react · Inter Variable + JetBrains Mono (self-hosted @fontsource) | | | Key libs | @tanstack/react-virtual, react-resizable-panels, cmdk, sonner, @xterm/xterm, highlight.js (lib/core + 26 langs) | | -| Rust deps | tauri-plugin-dialog/opener, portable-pty, keyring 3, notify-debouncer-mini, reqwest (rustls), which 7, base64, thiserror | | +| Rust deps | tauri-plugin-dialog/opener, portable-pty, keyring 3, notify-debouncer-mini, reqwest (rustls), which 7, base64, thiserror, same-file (hook paths by file identity); tempfile for tests only | | ## 3. Monorepo layout (pnpm workspaces) @@ -279,7 +279,12 @@ main.rs / lib.rs ← builder: plugins(dialog, opener), setup sets accounts: compact_wayland_titlebar (Linux only, best-effort, see G48) commands.rs ← THIN Tauri command layer; every git op via blocking() → spawn_blocking (incl. paths_exist(paths) → Vec is_dir, used by the welcome page - to flag recents whose folder is gone) + to flag recents whose folder is gone). HOOKED_OPERATIONS maps the + operation's canonical path to its running hook; the observer updates + that lock key even when clone/worktree hooks run in another folder. + worktree_add also reserves its future canonical target and keeps that + guard through post-checkout; both lock keys receive hook progress. + A blocked command returns Busy (operation_running, hook + folder name). error.rs ← AppError → serialized {code, message}; codes: conflict/auth/not_found/…; NotFastForward keeps code non_fast_forward and message() returns a next-step sentence (Pull with rebase / force push) instead of @@ -403,13 +408,21 @@ ai_cli.rs ← installed AI-CLI transport: detect (which_in over augm binaries only, stdin prompt, {OUTPUT_FILE} placeholder → temp file, neutral cwd, NO_COLOR/TERM=dumb env, kill-on-timeout); capture = spawn_piped + capture_child (kills the child only); hooks use - spawn_tree (own process group on unix) + capture_tree_child (kills - the whole group, or `taskkill /F /T` on Windows). OUTPUT IS DRAINED, NOT + spawn_tree(command, track_descendants) + run_tree(tree, stdin, timeout, retain) + → TreeRun {captured, timed_out, exit_unconfirmed}. A timeout + signals the process tree and returns the output so far. For group pull, + the runner keeps a handle for background processes it can identify. + Cancel monitors tracked processes while the current pull finishes + and reports when exit cannot be confirmed. Empty Unix groups finish + quietly (pidfd signal 0, else killpg signal 0); live groups without + a pidfd warn immediately. Detached children are outside this tracking. + See G55 (8). OUTPUT IS DRAINED, NOT JOINED (PR #85 reviews): the readers stream into shared buffers and, once the process has exited, get at most OUTPUT_DRAIN 1 s before collect() returns what was read — a background process that inherited stdout/stderr (a hook's `cmd &`) kept the old read_to_end joins blocked, - so Push never finished; 8 module tests. + so Push never finished (see §9 for tests). After capture, readers + keep draining inherited pipes without saving further output. WINDOWS BATCH LAUNCHERS (issue #43 follow-up, 2026-09-30): Cursor installs `cursor-agent.cmd` (→ .ps1 → versions\\node.exe index.js) and is the ONE agent whose prompt is a positional ARG @@ -502,13 +515,13 @@ core/ │ get_path, relative → worktree root, else commondir/hooks), │ present(repo, name) (exact name, exec bit on unix, existence + .exe on │ Windows, or a config-defined hook..event = name), run(repo, runner, -│ name, args, env, input) — the GENERIC runner the post-hooks will reuse: +│ name, args, env, input) — the GENERIC runner the post-hooks reuse: │ Runner::Git = `git hook run --ignore-missing [--to-stdin=] │ -- args`, Runner::Direct = the hook file itself with input on │ stdin (only for input on Git 2.36–2.39, unix only — pick_runner; an │ ENOEXEC spawn, a hook without a shebang, is retried as `/bin/sh │ ` with the same env/cwd/stdin, git's run-command fallback), both -│ through proc::hidden + ai_cli::spawn_tree/capture_tree_child +│ through proc::hidden + ai_cli::spawn_tree/run_tree │ (HOOK_TIMEOUT 600 s; the hook runs in its own process group on unix and │ a timeout kills the whole group with killpg, `taskkill /F /T` on │ Windows — killing only git left lint-staged writing the index after @@ -520,8 +533,39 @@ core/ │ GIT_AUTHOR_NAME/EMAIL/DATE (git_date: `@ <±hhmm>`) like git │ commit; PrePush::prepare(repo, remote, no_verify)/run(repo, refs) is │ the push flow (args = remote name + pushurl-or-url, stdin = -│ pre_push_input); repo_hooks(path) lists pre-commit/commit-msg/pre-push -│ for the UI; 9 module tests +│ pre_push_input); PR 3 (post-*): PostHook {Checkout{previous, new, +│ branch}, Merge, Rewrite{Amend|Rebase, pairs}} carries git's args and +│ stdin (PostHook::merged(outcome) for ok/fast_forward, ::rebased(pairs) +│ drops old == new and is None when nothing is left) and run_post(repo, +│ hooks, no_verify) → Vec runs each present one through the +│ same runner (post-rewrite takes the stdin path, so 2.40+ or Direct), +│ a non-zero exit, a launch error or a missing git is a WARNING, never an +│ Err; PostHooks is the collector the engine's *_with_hooks functions +│ take: run_now (a hook git runs mid-operation, e.g. post-checkout right +│ after a rebase checks out onto), later (after the operation and +│ submodule::synced), skip/skipped (a user's Skip hooks, remembered by a +│ paused rebase), off() for the plain engine functions, which run none; +│ repo_hooks(path) lists pre-commit/commit-msg/pre-push and the three +│ post hooks for the UI; 11 module tests +├── post_hooks.rs ← THE LIST OF OPERATIONS THAT RUN A POST-* HOOK (issue #82 PR 3), see G55 +│ (8): one wrapper per command — checkout_branch/checkout_detached/ +│ branch_create(checkout)/checkout_remote_ref snapshot HEAD around +│ submodule::synced(op) (so the hook sees the final state, submodules +│ included) → post-checkout 1; merge runs post-merge from the +│ outcome; pull/pull_branch/rebase/rebase_continue/rebase_interactive/ +│ amend/reword hand a PostHooks collector to the engine's *_with_hooks +│ functions and finish it after synced (pull and pull_branch decide +│ merge vs rebase vs ref-only move inside the engine); discard_file (tracked, not a drifted submodule)/discard_all +│ (only with tracked unstaged changes)/discard_staged_file/ +│ discard_staged_all (only with staged entries)/stash_restore_files → +│ post-checkout HEAD HEAD 0 like `git restore`; clone and worktree_add → +│ post-checkout 000… 1 in the new repo (none while HEAD is +│ unborn). Each returns Hooked {value, warnings}; commands.rs +│ report() emits one `hook-warning` event per warning (HookWarningEvent +│ {repoPath, hook, status, message, output}) and returns the value, so +│ no command changed its return type. The plain engine functions +│ (branch::rebase, remote::pull, commit::amend…) keep their signatures +│ and run no post-hook — the engine tests call them hundreds of times ├── branch.rs ← list(+ahead/behind), create/delete/rename, checkout (remote→local: │ a missing local is created tracking the remote; an EXISTING local │ that is strictly behind the remote is fast-forwarded to it with a @@ -3173,6 +3217,15 @@ drifted `vendor/libfoo` submodule row, cleared by the demo ipc.submoduleUpdate; `angkorgit-demo-hooks` = pass | fail makes ipc.repoHooks report pre-commit and pre-push, and `fail` makes ipc.commit/amend throw a pre-commit hook_failed error with lint output and ipc.push/pushTag a pre-push one with test output, unless noVerify; +`angkorgit-demo-post-hooks` = pass | fail adds post-checkout and post-merge to +ipc.repoHooks, makes the demo ipc.pull fast-forward and ipc.groupUpdate(pull) return a +fast-forward, and with `fail` emits a post-checkout (ipc.checkout) or post-merge +(ipc.pull without noVerify) `hook-warning` through a demo event bus that ipc.listen +subscribes to outside Tauri, and puts a post-merge warning on each group row unless the +run was started with noVerify; `angkorgit-demo-hooks-in-worktree` = 1 makes ipc.repoHooks +report inWorktree (a .husky-style hook folder) so the without-hooks pulls show with no hook; +`angkorgit-demo-discard-fails` = makes the demo ipc.discardFiles report that path as +failed ("Permission denied (os error 13)"); `angkorgit-demo-busy-graph` = 1 builds a 14-lane history so the graph overflows its column and scrolls sideways; `angkorgit-demo-hooks-delay` = ms stretches every demo commit, with or without hooks, and a demo push that runs its hook, so an e2e can switch tabs or select a graph commit mid-hook; @@ -4108,7 +4161,7 @@ update CLAUDE.md or docs/ — never the code. --no-verify again. (2) The RUNNER is `git hook run --ignore-missing -- args` (Git ≥ 2.36, version parsed from `git --version` incl. the Apple and `.windows.N` forms), git located with which_in over ai_cli::search_path (G16) and cached once found, spawned - through proc::hidden (G31) and ai_cli::spawn_tree + capture_tree_child (both runners) with + through proc::hidden (G31) and ai_cli::spawn_tree + run_tree (both runners) with HOOK_TIMEOUT 600 s (git has no timeout; without one a stuck hook kept Commit busy until a restart). The hook runs in its own process group and a timeout kills the GROUP (killpg; `taskkill /F /T` on Windows): @@ -4185,10 +4238,269 @@ update CLAUDE.md or docs/ — never the code. a small HTTP/1.1 server in tests/git_engine.rs that drops connections idle for 1 s (IdleDrop::Close) or shuts down its write side and keeps draining (IdleDrop::HalfClose), and give the hook a 3 s sleep; Close failed with the broken pipe before the retry, - HalfClose with "unexpected EOF" (class 34) before Http joined the list. NOT covered yet, by scope: prepare-commit-msg, post-commit, - post-checkout/merge/rewrite, hooks for commits made by reword, pull/merge, revert, - cherry-pick and rebase, live output and cancel. `group_pull_matches_toolbar_pull_with_ - active_hooks` still asserts that no post-hook runs (#69 decision open). + HalfClose with "unexpected EOF" (class 34) before Http joined the list. (8) POST-CHECKOUT, + POST-MERGE, POST-REWRITE (PR 3, 2026-11-06). Every rule was probed against git 2.56 with + logging hooks, not read from the docs, because the docs are incomplete: `git restore + ` runs post-checkout `HEAD HEAD 0` exactly like `git checkout -- ` (both end + in checkout.c's checkout_paths; the -p forms return before the hook), so DISCARD runs it; + deleting an untracked file is `git clean` and runs nothing. Clone and `worktree add` run + post-checkout `000… 1` (the worktree one in the new worktree), `--no-checkout` and + an empty repo run nothing. post-merge `0` follows a merge commit or a fast-forward, never + up to date or conflicts (`1` is only `--squash`, which the app has no form of). + `git pull --rebase` that can fast-forward MERGES (`--ff-only`) and runs post-merge; + diverged it runs post-checkout ` 1` then post-rewrite `rebase` and no + post-merge — remote::pull already took the same branch (rebase only when ahead AND + behind). A rebase runs post-checkout RIGHT AFTER it detaches onto, before replaying + anything (PR #87 review: it ran after the replay, so the hook saw a later HEAD or + conflict markers; branch::rebase_with_hooks calls hooks.run_now after repo.rebase(), + which checks onto out), also when it then stops on a conflict, and post-rewrite once when + it completes, with every pair; `--continue` runs only post-rewrite; abort runs nothing. UP + TO DATE: when onto is HEAD or an ancestor of HEAD with linear history in between + (builtin/rebase.c can_fast_forward + is_linear_history), git prints "Current branch is up + to date" and does nothing, so rebase_with_hooks returns status up_to_date before libgit2 + starts — libgit2 used to re-create those commits with new committer dates (a silent + --force-rebase) and the app then ran post-checkout and post-rewrite for them (PR #87 + review). The up-to-date shortcut runs AFTER ensure_rebase_can_start (no rebase, merge, + cherry-pick or revert in progress — repo.state() Clean — and ensure_tracked_clean, the + interactive rebase's precondition): the first shortcut answered "Already up to date" on + a dirty tree or mid-rebase, states libgit2's own rebase_init and git reject (PR #87 + review, second round). Both clean checks run ensure_clean: the status without submodules + plus a comparison of each submodule's HEAD and index gitlinks. An added, deleted or + changed staged pointer blocks a rebase even under `ignore = all`. + For worktree changes, repo.submodule_status checks WD_ADDED/DELETED/MODIFIED, + WD_INDEX_MODIFIED, WD_WD_MODIFIED and WD_UNTRACKED. The ordinary rebase asks with + SubmoduleIgnore::Untracked, the rule libgit2's own rebase_init check uses, so a submodule + holding only untracked files passes (round six). The interactive rebase and the reword of + an older commit (ensure_tracked_clean) ask with SubmoduleIgnore::Unspecified, i.e. each + submodule's configured `ignore` rule, so `ignore = dirty` in .gitmodules lets an edited + submodule through (round seven). TRAP: libgit2's repo.statuses() does NOT apply a + submodule's `ignore = dirty` — it reports WT_MODIFIED where `git status` is clean — so + the original statuses()-only check never honoured it either; only submodule_status does. FOUND WHILE TESTING THAT, + NOT FIXED: libgit2's rebase.commit() fails with GIT_EUNMERGED "unstaged changes exist in + workdir" when onto moves a submodule's recorded commit, because the replay never updates + the submodule folder; `git rebase` ignores submodules there. So a Pull with rebase whose + upstream bumped a submodule fails in the app — pre-existing on main. SKIP HOOKS SURVIVES A PAUSE: a rebase started with hooks skipped + (Pull without hooks with pull.rebase) writes `/rebase-merge/angkorgit-skip-hooks` + RIGHT AFTER repo.rebase() initializes, before any replay (aborting the rebase if the write + fails); rebase_continue_with_hooks reads it before anything else and skips its + post-rewrite — the toolbar's Continue rebase cannot know the original choice (PR #87 + review, P1). The first fix wrote it only on an index conflict, but replay can also stop + with an error (an untracked file in the way of a replayed commit) and leave a resumable + rebase with commits already rewritten (second round). libgit2 and git ignore the extra + file and delete it with the folder. Seen while testing that, NOT fixed here: after such an + error, libgit2's next() never wrote the index, so rebase_continue's commit() reports + Applied and the stopped commit is silently skipped, where `git rebase --continue` re-picks + it. The fix from main (#88, G58) is retained: stopped_step marks the failed step and + reapply_stopped_step re-picks it on Continue, after restoring the hook skip choice. + WARNINGS SURVIVE A FAILED REPLAY: + post_hooks::rebase and post_hooks::pull return Hooked> (not + AppResult> like the other wrappers) because their post-checkout runs before the + replay; finished_or_failed keeps the warnings PostHooks already collected when the + operation then fails (PostHooks::abandon drops only the not-yet-run hooks), and the two + commands emit them before returning the error. Hooked::into_result() turns it back into + AppResult> for the engine tests (PR #87 review, third round). + ORIG_HEAD: git merge writes ORIG_HEAD = HEAD before every merge (builtin/merge.c, even + when up to date); libgit2 does it in git_merge and git_rebase_init but the app's + hand-made fast-forwards skipped it, so a post-merge hook running `git diff --name-only + ORIG_HEAD HEAD` failed in a fresh clone (PR #87 review). branch::set_orig_head writes + ORIG_HEAD through repo.reference("ORIG_HEAD", …), so libgit2's refdb takes + `ORIG_HEAD.lock` and fails while another git process holds it instead of overwriting the + pointer (round six; a plain file write did); branch::merge calls it first and group pull + calls it inside its locked section before the checkout (not for an up-to-date repo: that + check runs outside the lock). + The pairs come from libgit2's `/rebase-merge/rewritten` ("old new" lines, + appended per commit, kept across a pause), read BEFORE `finish()` deletes the folder; + git2 0.20 has no onto_id(), onto is the upstream commit. post-rewrite `amend` lists the + pair even when old == new (git does); `rebase` drops identical pairs and runs only with + pairs left. Interactive rebase: post-checkout ` 1` and one post-rewrite + rebase, squash/fixup sources mapped to the combined commit, dropped commits left out. + git passes ` ` because it checks out onto before replaying; the app builds + the chain in memory and moves the worktree ONCE, from orig straight to the result, so + $2 names the commit the worktree was actually checked out to (the same rule as git's + args: $2 == HEAD when the hook runs) — reporting onto would hand the hook a commit that + was never checked out (PR #87 review applied the same reasoning to the plain rebase); + git's sequencer ALSO fires post-rewrite `amend` for each squash/fixup/reword step (an + in-process `commit --amend`) — deliberately NOT reproduced: the app builds the chain in + memory and a reword has no intermediate commit to report. Reword is an amend (HEAD) or an + interactive rebase (earlier commit) and runs those hooks; reword still runs no pre-hook. + Stash push/apply/pop, reset, cherry-pick, revert, merge/rebase abort and `git fetch b:b` + (pull_branch on a non-HEAD branch) run nothing. ORDER/STATE: the hooks run after + submodule::synced, so a hook sees submodules already followed. SKIP HOOKS DIFFERS FROM + GIT ON PURPOSE: `--no-verify` never skips a post-* hook in git (`commit --amend + --no-verify` still runs post-rewrite), but the issue's spec and the maintainer want the + app's Skip hooks to mean "no hooks": the commit box's Skip hooks also skips post-rewrite + on amend (it now shows when amend is ticked and post-rewrite exists, and drops "like + --no-verify" from its hint then), the Pull menu has Pull without hooks (shown when + post-merge, post-rewrite or post-checkout exists), the group menu has Pull all without + hooks (shown when any repo of the group has post-merge, checked on menu open). Both pull + items also show when the hooks LIVE IN THE WORKTREE (repo_hooks returns RepoHooks {found, + inWorktree}; hooks_live_in_worktree): for every hook candidate path (hooks_dir + name), + visits_worktree walks the path COMPONENT BY COMPONENT LIKE THE OS (a symlinked component + is replaced by its target plus the rest of the path, `..` pops the PHYSICAL directory + reached so far — removing `proxy/..` lexically first checked the wrong folder when proxy + is a link — up to SYMLINK_HOPS 40) and answers yes as soon as ANY visited path lies + strictly below the workdir and not in the gitdir or commondir. "Below" is decided by FILE + IDENTITY, not text: `within` opens each existing ancestor with same_file::Handle (a direct + dependency since PR #87; it was already in Cargo.lock through walkdir) and compares it to + the workdir's handle, so letter case on case-insensitive disks (C:\Work\Repo vs + c:/work/repo/.husky), macOS /var vs /private/var and Windows \\?\ prefixes cannot hide a + match; a symlink is never "the gitdir itself", only its ancestors count for it. A pull can + only change files in the worktree, so a hook is at risk exactly when locating it passes + through the worktree: core.hooksPath=.husky (even when `.husky` + is a tracked link to an empty folder outside — the pull can replace the link with a + folder holding post-merge), `.git/hooks` linked to `../githooks`, a hook linked to + `../../scripts/post-merge`, or a chain hook → /tmp/hop → worktree file, dangling or not. + The backend runs such a hook right after the fast-forward, so the opt-out must show + before any hook is present (PR #87 review, rounds two to five: canonicalizing the final + target missed the link-to-outside and the chained cases, lexical `..` missed a link + followed by `..`, and text prefixes missed a differently-cased path). CONFIG IN THE + WORKTREE counts too (round six): config_lives_in_worktree starts from commondir/config, + gitdir/config.worktree and libgit2's global, XDG and system files, opens each with + git2::Config::open, takes its OWN include.path / includeIf.*.path entries + (include_depth 0; git2 does not expose libgit2's origin_path, so the walk opens every + included file itself, relative paths against the including file's folder, `~/` via + remote::expand_home) and runs visits_worktree on every file. Home expansion + preserves whitespace in the parsed value, so `.git/project ` and `.git/project` + can lead to different files. It also resolves `~//src` under the home directory + because joining the suffix `/src` directly would drop the home prefix. + On Windows, the include scanner checks `HOME`, then the directory formed by + concatenating `HOMEDRIVE` and `HOMEPATH`, then `USERPROFILE`. The Windows test + compares the scanner with Git and libgit2 in a child process with separate + drive-and-path and profile directories. + An include such as `[include] path = + ../project.gitconfig` holding only a comment today can gain core.hooksPath=.husky and a + .husky/post-merge in one fast-forward. When the walk reaches CONFIG_FILE_LIMIT 64 files + with more still queued it answers YES (round seven: the stack order visited 64 outside + includes first and hid the tracked one listed before them) — an unfinished scan must + keep the opt-out, never hide it. ROUND EIGHT: (a) the bulk "Discard changes in n files…" + calls ONE command, discard_files(path, files, staged) — one `git restore a b c` runs one + post-checkout after all files are back; the per-file loop ran the hook n times against a + half-restored tree. It returns DiscardBatch {leftovers, failed: [{path, message}]}: every + file is attempted, a file that errors (an untracked file in a folder it may not delete + from) is recorded instead of aborting the batch, post-checkout runs once if any restore + happened, and the panel shows "k of n files could not be discarded" with the first + message and no success toast (round nine; the first version stopped at the first error + and the UI still said every change was discarded). The header's "Discard all staged + changes" (discard_staged_all) follows the same rule since round ten: it returned at the + first file it could not delete, after earlier files were already restored, and so never + ran post-checkout; it now returns DiscardBatch too, runs the hook once when any file came + back and the panel names the failed files ("k of n staged files could not be discarded") + without a success toast. + stage::discard_staged_all keeps its old Vec signature for + the engine tests (the first failure becomes its error). E2E TRAP met here: + `expect(locator).toHaveCount(0)` RETRIES until it holds, so it passes once a wrongly shown + toast expires (sonner's 4 s) — check absence with a one-shot `locator.count()` after a + wait, as the hook e2e tests do now. (b) "Pull without hooks" goes through PullCheckDialog like the main + Pull button when the preview predicts conflicts or blocking edits (pullCheck state + {noVerify}); the other Pull menu items still never ask. (c) GROUP PULL CONTAINS + POST-MERGE'S BACKGROUND PROCESSES: the runner waits for the foreground hook and + hands surviving processes to the group control before draining output, so + Cancel can enforce the original deadline while a child still holds a pipe open. + The runner publishes the captured output after the drain and Cancel attaches + it when building the receipt. An empty process group counts as finished on every + Unix platform. Linux probes through the group's pidfd when available, otherwise + Unix uses killpg(pgid, 0): ESRCH means empty, EPERM means still running, and other + errors mean unknown. Signal 0 never kills anything; a reused pgid only warns. + Children that leave the group (setsid or daemonizing) are not seen by Cancel, + matching Git and toolbar Pull. The engine test documents that they can still write. + Normal Pull all + completion lets background jobs such as `(npm install &)` continue, matching toolbar + Pull and Git. On Windows the runner starts Git suspended, assigns it to a job object + and resumes it. Assigning the job after Git started let fast hooks escape tracking. + The job handle can close while processes still run. A job setup or resume failure + reports a hook launch warning on the group row and terminates Git if it was spawned. + The empty-job regression test drops the reaped child handle, then polls with a + deadline. Windows job accounting can still report active processes while a + reference to the exited process remains open; waiting on the child alone does + not close its handle. See Microsoft's [ActiveProcesses documentation](https://learn.microsoft.com/windows/win32/api/winnt/ns-winnt-jobobject_basic_accounting_information). + Cancel stops new local writes and polls tracked background hooks while active + writes and foreground hooks finish. It polls each hook's deadline and termination + grace period independently, then adds the collected warnings to the final receipt + once the active operation has recorded its result. After the + foreground child has been reaped, a numeric process group ID can be reused. + Linux opens a pidfd for the group leader before reaping it and uses + `PIDFD_SIGNAL_PROCESS_GROUP` (Linux 6.9+) for polling and signalling. At each + hook's original deadline Cancel terminates the Windows job or signals the + group through its pidfd, then gives it one second to exit. If Unix cannot + acquire a usable group descriptor, Cancel reports uncertainty immediately for + that hook. On macOS and Linux without usable process-group pidfd support, the + app can clear the busy state while that hook's background processes still + write to the repository, even past the original deadline. The foreground timeout + can still signal its direct child's group while the child is unreaped. Unix + reports unconfirmed termination after either timeout because a child may have + left the group. A timed-out foreground child still waiting to exit on Unix is + reaped in the background. The Cancel receipt carries a warning for background + processes that reached the deadline. Empty groups, including ones that finish + before their deadline, cause no cancellation warning. A completed run + displays its ordinary hook results without these cancellation warnings. + To reproduce group ID reuse, run the ignored + `ai_cli::tests::cancellation_does_not_signal_a_reused_process_group` in the + Rust lib test binary with `unshare --user --map-root-user --pid --fork + --mount-proc --exact --ignored`. + The dialog waits for this receipt before + finishing, then applies its results to rows that already returned. + (d) TIMEOUTS ARE NOT "DID NOT + RUN": run_watched returns AppError::HookTimeout {hook, seconds, exit_unconfirmed, output} (code + hook_timeout, detail = output so far); a post-hook timeout becomes a HookWarning with + status null, timedOut true and the output, shown as "The hook timed out" + with the backend message so unconfirmed termination stays visible. The toast + offers Show output or Show details when there is no output. Status null + without timedOut still means it never started. An ordinary hook timeout requests + process-tree termination and waits for Git, then reports that descendant exit + could not be confirmed. Pre-hook + timeouts now carry the same message but still have no "without hooks" retry (the item + the maintainer marked "later" in #85). The toolbar's + Pull menu asks again on every open (useRepoHooks returns refresh(), called from the + menu's onOpenChange): the watcher ignores .git/config, so a core.hooksPath changed in a + terminal left the cached answer stale; the group menu already checks on open. Demo: + `angkorgit-demo-hooks-in-worktree` = 1. + Checkout, merge, rebase, discard, clone and worktree have no skip UI (git has no switch + either); the engine wrappers all take no_verify for the tests. Tauri's + blocking_post_hooks admits one hook-capable command at a time per worktree path + but rebase_abort can interrupt a rebase's post-checkout hook. After the hook + returns, rebase_with_hooks checks that rebase-merge still exists before replaying + a commit; an already aborted rebase returns "Rebase aborted" without replay or + post-rewrite. The integration test holds the hook while another thread aborts it. + blocking_post_hooks also installs a scoped observer on its blocking thread. The observer emits + hook progress for both the initiating worktree and a reserved target worktree. + worktree_add reserves the canonical future target before creating it (resolve + the nearest existing ancestor first), retains that guard through post-checkout, + and releases it on success or failure. A checkout opened through the new folder + or a symlink alias returns operation_running until the hook finishes. The unit + test holds the real hook while checking that canonical target lock and its release. + The observer emits + `post-hook-progress` when a post-hook runs and when it finishes. + HookWarningHost shows and dismisses the loading toast for that hook and worktree. + A second operation returns operation_running with the hook name and repository + folder; components/actionError.ts toastActionError displays it as toast.info, + leaving the progress toast visible. Other failures keep their existing error + messages, including the toolbar's separate headline and multiline details. + The demo emits the same typed response. The e2e checks the info toast and uses a + one-shot count for the absent red error, before it could expire. + It also listens for `hook-warning` + and shows toast.warning(message, "Nothing was undone in .", action Show output → + HookWarningDialog, the HookFailedDialog layout without a retry button, data-hook-warning= + ) 600 ms later (AFTER_OPERATION_TOAST_MS): the event arrives before the command's + response, and without the delay the caller's "Checkout x done" toast stacked on top of it; + a missing/old git reads "The hook did not run". GROUP PULL (#69, approved by the + maintainer in #82 on 2026-11-01): post-merge runs in group_update_inner INSIDE the same + with_active_result section as the fast-forward, after follow_recorded, and its warnings + ride on GroupUpdateResult.hookWarnings (serialized only when non-empty), so the receipt + Cancel returns includes them; the fast-forward and its hook are one unit — Cancel before + it means neither. Cancel during the hook waits for it like any active local write + while monitoring earlier background hooks. The skip choice is per run: + repository_group_start(runId, noVerify) → GroupUpdateControl::skipping_hooks. The dialog + shows the warning and a collapsed "Hook output" on the row (data-group-hook-warning), "n + hook warnings" in the counts line, and "Pull all without hooks" in the title. The clone + test lives in its own binary (tests/clone_hooks.rs): a fresh clone only has hooks from a + GLOBAL core.hooksPath, because libgit2's clone ignores init.templateDir (git clone copies + template hooks — a known gap), and HOME/GIT_CONFIG_GLOBAL must be set before libgit2 + initializes, which would leak into the parallel tests of git_engine.rs. NOT covered yet, + by scope: prepare-commit-msg, post-commit (trivial for commit/amend now that warnings have + a path; git also runs it for merge, cherry-pick, revert and rebase commits), pre-merge- + commit, pre-rebase, the submodules' own post-checkout (`git submodule update` runs it, + the app's follow and Update submodule do not), template hooks on clone, hooks for commits + made by pull/merge, revert, cherry-pick and rebase, live output and cancel. - **G56 — a theme switch must not run the hover fades**: inputs, buttons, menu items, checkboxes and tabs carry `transition-colors` (150 ms) for hover, and that transition @@ -4252,10 +4564,10 @@ update CLAUDE.md or docs/ — never the code. | Suite | Location | Coverage | | --- | --- | --- | -| Rust integration (155) | `apps/desktop/src-tauri/tests/git_engine.rs` | 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 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) — skipped with a note when git ≥ 2.36 is not on PATH | -| Rust module (96) | `apps/desktop/src-tauri/src/cli.rs` (7), `src/state.rs` (1), `src/editors.rs` (5), `src/fonts.rs` (1), `src/ai_cli.rs` (12), `src/error.rs` (8), `src/core/hooks.rs` (9), `src/core/remote.rs` (19), `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, 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 · 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 (338) | `tests/unit/*.test.ts` | 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 (141) | `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 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, 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 — all on demo mode | +| 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 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 | ## 9.5 Open-source & community files diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock index 801fc298..b0cacc82 100644 --- a/apps/desktop/src-tauri/Cargo.lock +++ b/apps/desktop/src-tauri/Cargo.lock @@ -66,6 +66,7 @@ dependencies = [ "notify-debouncer-mini", "portable-pty", "reqwest 0.12.28", + "same-file", "serde", "serde_json", "tauri", @@ -75,8 +76,10 @@ dependencies = [ "tauri-plugin-process", "tauri-plugin-single-instance", "tauri-plugin-updater", + "tempfile", "thiserror 2.0.19", "which", + "windows-sys 0.61.2", ] [[package]] diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index d4fb6980..314b3288 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -33,6 +33,7 @@ keyring = { version = "3", features = ["apple-native", "windows-native", "sync-s notify-debouncer-mini = "0.4" reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json"] } which = "7" +same-file = "1" fontdb = { version = "0.24", default-features = false, features = ["std", "fs", "memmap", "fontconfig"] } [target.'cfg(unix)'.dependencies] @@ -48,6 +49,10 @@ gtk = "0.18" # through OpenSSL on Windows instead; this compiles OpenSSL from source and # needs Perl available at build time. libssh2-sys = { version = "0.3", features = ["openssl-on-win32", "vendored-openssl"] } +windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Threading"] } + +[dev-dependencies] +tempfile = "3" [profile.release] codegen-units = 1 diff --git a/apps/desktop/src-tauri/src/ai_cli.rs b/apps/desktop/src-tauri/src/ai_cli.rs index 33d2a594..20371f82 100644 --- a/apps/desktop/src-tauri/src/ai_cli.rs +++ b/apps/desktop/src-tauri/src/ai_cli.rs @@ -20,6 +20,8 @@ const AGENTS: &[(&str, &str, &[&str])] = &[ const OUTPUT_FILE_PLACEHOLDER: &str = "{OUTPUT_FILE}"; const VERSION_TIMEOUT: Duration = Duration::from_secs(15); const OUTPUT_DRAIN: Duration = Duration::from_secs(1); +const PROCESS_EXIT_GRACE: Duration = Duration::from_secs(1); +pub(crate) const PROCESS_POLL_INTERVAL: Duration = Duration::from_millis(25); const CURSOR_LAUNCHERS: &[&str] = &["cursor-agent", "agent"]; #[derive(Serialize, Clone)] @@ -205,21 +207,75 @@ pub(crate) fn spawn_piped(mut command: Command) -> std::io::Result { command.spawn() } -pub(crate) fn spawn_tree(mut command: Command) -> std::io::Result { +pub(crate) struct TreeChild { + child: Child, + leftovers: Option, +} + +pub(crate) fn spawn_tree( + mut command: Command, + track_descendants: bool, +) -> std::io::Result { + #[cfg(not(any(unix, windows)))] + let _ = track_descendants; + #[cfg(windows)] + if track_descendants { + let job = job::Job::new()?; + let child = job::spawn_assigned(command, |child| job.assign(child))?; + return Ok(TreeChild { + child, + leftovers: Some(Leftovers { job }), + }); + } own_process_group(&mut command); - spawn_piped(command) + let child = spawn_piped(command)?; + #[cfg(unix)] + let leftovers = if track_descendants { + Some(Leftovers { + pgid: child.id(), + #[cfg(target_os = "linux")] + group: ProcessGroup::open(&child), + }) + } else { + None + }; + #[cfg(not(unix))] + let leftovers = None; + Ok(TreeChild { child, leftovers }) +} + +#[cfg(unix)] +pub fn background_process_signals_available() -> std::io::Result { + let mut command = crate::proc::hidden("/bin/sh"); + command.args(["-c", "exec sleep 30"]); + let mut tree = spawn_tree(command, true)?; + let can_stop = tree.leftovers.as_ref().is_some_and(Leftovers::can_stop); + kill_tree(&mut tree.child); + tree.child.wait()?; + Ok(can_stop) } pub(crate) fn capture_child(child: Child, stdin: &str, timeout: Duration) -> AppResult { collect(child, stdin, timeout, false) } -pub(crate) fn capture_tree_child( - child: Child, +pub(crate) struct TreeRun { + pub(crate) captured: Captured, + pub(crate) timed_out: bool, + pub(crate) exit_unconfirmed: bool, +} + +pub(crate) fn run_tree( + tree: TreeChild, stdin: &str, timeout: Duration, -) -> AppResult { - collect(child, stdin, timeout, true) + retain: impl FnOnce(BackgroundProcesses), +) -> TreeRun { + gather(tree.child, stdin, timeout, true, tree.leftovers, retain) +} + +fn timed_out(timeout: Duration) -> AppError { + AppError::other(format!("timed out after {}s", timeout.as_secs())) } #[cfg(unix)] @@ -232,12 +288,17 @@ fn own_process_group(command: &mut Command) { fn own_process_group(_command: &mut Command) {} #[cfg(unix)] -fn kill_tree(child: &mut Child) { - if let Ok(group) = libc::pid_t::try_from(child.id()) { +fn kill_group(id: u32) { + if let Ok(group) = libc::pid_t::try_from(id) { unsafe { libc::killpg(group, libc::SIGKILL); } } +} + +#[cfg(unix)] +fn kill_tree(child: &mut Child) { + kill_group(child.id()); let _ = child.kill(); } @@ -257,12 +318,422 @@ fn kill_tree(child: &mut Child) { let _ = child.kill(); } -fn collect( +#[cfg(target_os = "linux")] +struct ProcessGroup(std::os::fd::OwnedFd); + +#[cfg(target_os = "linux")] +impl ProcessGroup { + fn open(child: &Child) -> Option { + use std::os::fd::{FromRawFd, OwnedFd, RawFd}; + + let pid = libc::pid_t::try_from(child.id()).ok()?; + let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0u32) }; + if fd < 0 { + return None; + } + let group = Self(unsafe { OwnedFd::from_raw_fd(fd as RawFd) }); + group.signal(0).then_some(group) + } + + fn signal(&self, signal: libc::c_int) -> bool { + use std::os::fd::AsRawFd; + + unsafe { + libc::syscall( + libc::SYS_pidfd_send_signal, + self.0.as_raw_fd(), + signal, + std::ptr::null::(), + libc::PIDFD_SIGNAL_PROCESS_GROUP, + ) == 0 + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum ProcessState { + Running, + Empty, + Unknown, +} + +struct Leftovers { + #[cfg(unix)] + pgid: u32, + #[cfg(target_os = "linux")] + group: Option, + #[cfg(windows)] + job: job::Job, +} + +pub(crate) struct BackgroundProcesses { + leftovers: Option, + deadline: Instant, + stop_deadline: Option, +} + +#[derive(Debug, PartialEq, Eq)] +pub(crate) enum CancelOutcome { + Unconfirmed, + TimedOut { confirmed: bool }, +} + +pub(crate) enum CancelPoll { + Waiting(Instant), + Finished(Option), +} + +impl BackgroundProcesses { + #[cfg(test)] + pub(crate) fn is_tracking(&self) -> bool { + self.leftovers.is_some() + } + + #[cfg(test)] + pub(crate) fn can_stop(&self) -> bool { + self.leftovers.as_ref().is_some_and(Leftovers::can_stop) + } + + pub(crate) fn retain_for_cancel(&mut self) -> bool { + match self + .leftovers + .as_ref() + .map_or(ProcessState::Unknown, Leftovers::probe) + { + ProcessState::Empty => { + self.leftovers = None; + false + } + ProcessState::Running => true, + ProcessState::Unknown => { + self.leftovers = None; + true + } + } + } + + pub(crate) fn poll_on_cancel(&mut self) -> CancelPoll { + let Some(leftovers) = &self.leftovers else { + return CancelPoll::Finished(Some(CancelOutcome::Unconfirmed)); + }; + let state = leftovers.probe(); + let now = Instant::now(); + if let Some(deadline) = self.stop_deadline { + if state == ProcessState::Running && now < deadline { + return CancelPoll::Waiting(deadline); + } + return CancelPoll::Finished(Some(CancelOutcome::TimedOut { + confirmed: cfg!(windows) && state == ProcessState::Empty, + })); + } + if state == ProcessState::Empty { + return CancelPoll::Finished(None); + } + if state == ProcessState::Unknown || !leftovers.can_stop() { + return CancelPoll::Finished(Some(CancelOutcome::Unconfirmed)); + } + if now < self.deadline { + return CancelPoll::Waiting(self.deadline); + } + let grace = if leftovers.request_stop() { + PROCESS_EXIT_GRACE + } else { + Duration::ZERO + }; + let deadline = Instant::now() + grace; + self.stop_deadline = Some(deadline); + CancelPoll::Waiting(deadline) + } + + #[cfg(test)] + fn wait_on_cancel(mut self) -> Option { + loop { + match self.poll_on_cancel() { + CancelPoll::Waiting(deadline) => std::thread::sleep( + deadline + .saturating_duration_since(Instant::now()) + .min(PROCESS_POLL_INTERVAL), + ), + CancelPoll::Finished(outcome) => return outcome, + } + } + } +} + +impl Leftovers { + fn probe(&self) -> ProcessState { + #[cfg(target_os = "linux")] + if let Some(group) = &self.group { + return if group.signal(0) { + ProcessState::Running + } else if std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH) { + ProcessState::Empty + } else { + ProcessState::Unknown + }; + } + #[cfg(unix)] + { + let Ok(pgid) = libc::pid_t::try_from(self.pgid) else { + return ProcessState::Unknown; + }; + if unsafe { libc::killpg(pgid, 0) } == 0 { + return ProcessState::Running; + } + match std::io::Error::last_os_error().raw_os_error() { + Some(libc::ESRCH) => ProcessState::Empty, + Some(libc::EPERM) => ProcessState::Running, + _ => ProcessState::Unknown, + } + } + #[cfg(windows)] + { + if self.job.running() { + ProcessState::Running + } else { + ProcessState::Empty + } + } + #[cfg(not(any(unix, windows)))] + { + ProcessState::Unknown + } + } + + fn can_stop(&self) -> bool { + #[cfg(target_os = "linux")] + { + self.group.is_some() + } + #[cfg(windows)] + { + true + } + #[cfg(not(any(target_os = "linux", windows)))] + { + false + } + } + + fn stop(self, child: &mut Child) -> bool { + #[cfg(unix)] + { + kill_tree(child); + let _ = wait_for_process_exit(PROCESS_EXIT_GRACE, || { + Some(child.try_wait().ok()?.is_some() && self.probe() != ProcessState::Running) + }); + false + } + #[cfg(not(unix))] + let _ = child; + #[cfg(windows)] + { + self.job.stop() + } + #[cfg(not(any(unix, windows)))] + { + true + } + } + + fn request_stop(&self) -> bool { + #[cfg(target_os = "linux")] + { + self.group + .as_ref() + .is_some_and(|group| group.signal(libc::SIGKILL)) + } + #[cfg(not(any(target_os = "linux", windows)))] + { + false + } + #[cfg(windows)] + { + self.job.terminate() + } + } +} + +#[cfg(any(unix, windows, test))] +fn wait_for_process_exit(timeout: Duration, mut exited: impl FnMut() -> Option) -> bool { + let deadline = Instant::now() + timeout; + loop { + match exited() { + Some(true) => return true, + None => return false, + Some(false) => {} + } + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + return false; + } + std::thread::sleep(remaining.min(PROCESS_POLL_INTERVAL)); + } +} + +#[cfg(windows)] +mod job { + use std::io; + use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle}; + use std::os::windows::process::CommandExt; + use std::process::{Child, Command}; + + use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + use windows_sys::Win32::System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, Thread32First, Thread32Next, TH32CS_SNAPTHREAD, THREADENTRY32, + }; + use windows_sys::Win32::System::JobObjects::{ + AssignProcessToJobObject, CreateJobObjectW, JobObjectBasicAccountingInformation, + QueryInformationJobObject, TerminateJobObject, JOBOBJECT_BASIC_ACCOUNTING_INFORMATION, + }; + use windows_sys::Win32::System::Threading::{ + OpenThread, ResumeThread, CREATE_SUSPENDED, THREAD_SUSPEND_RESUME, + }; + + pub(super) struct Job(OwnedHandle); + + impl Job { + pub(super) fn new() -> io::Result { + let handle = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) }; + if handle.is_null() { + return Err(windows_error("could not create the hook job")); + } + Ok(Job(unsafe { OwnedHandle::from_raw_handle(handle) })) + } + + pub(super) fn assign(&self, child: &Child) -> io::Result<()> { + if unsafe { AssignProcessToJobObject(self.0.as_raw_handle(), child.as_raw_handle()) } + == 0 + { + return Err(windows_error( + "could not assign the suspended process to the hook job", + )); + } + Ok(()) + } + + pub(super) fn running(&self) -> bool { + self.active_processes() != Some(0) + } + + fn active_processes(&self) -> Option { + let mut info = JOBOBJECT_BASIC_ACCOUNTING_INFORMATION::default(); + let queried = unsafe { + QueryInformationJobObject( + self.0.as_raw_handle(), + JobObjectBasicAccountingInformation, + std::ptr::addr_of_mut!(info).cast(), + std::mem::size_of::() as u32, + std::ptr::null_mut(), + ) + }; + (queried != 0).then_some(info.ActiveProcesses) + } + + pub(super) fn terminate(&self) -> bool { + unsafe { TerminateJobObject(self.0.as_raw_handle(), 1) != 0 } + } + + pub(super) fn stop(self) -> bool { + if !self.terminate() { + return self.active_processes() == Some(0); + } + super::wait_for_process_exit(super::PROCESS_EXIT_GRACE, || { + self.active_processes().map(|count| count == 0) + }) + } + } + + pub(super) fn spawn_assigned( + mut command: Command, + assign: impl FnOnce(&Child) -> io::Result<()>, + ) -> io::Result { + command.creation_flags(crate::proc::CREATE_NO_WINDOW | CREATE_SUSPENDED); + let mut child = super::spawn_piped(command)?; + if let Err(error) = assign(&child).and_then(|()| resume_primary_thread(child.id())) { + let _ = child.kill(); + let _ = child.wait(); + return Err(error); + } + Ok(child) + } + + fn resume_primary_thread(process_id: u32) -> io::Result<()> { + let thread = primary_thread(process_id)?; + match unsafe { ResumeThread(thread.as_raw_handle()) } { + 1 => Ok(()), + u32::MAX => Err(windows_error("could not resume the hook thread")), + _ => Err(io::Error::other("unexpected hook thread suspend count")), + } + } + + fn primary_thread(process_id: u32) -> io::Result { + let snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) }; + if snapshot == INVALID_HANDLE_VALUE { + return Err(windows_error("could not find the suspended hook thread")); + } + let snapshot = unsafe { OwnedHandle::from_raw_handle(snapshot) }; + let mut entry = THREADENTRY32 { + dwSize: std::mem::size_of::() as u32, + ..Default::default() + }; + let mut found = unsafe { Thread32First(snapshot.as_raw_handle(), &mut entry) }; + while found != 0 { + if entry.th32OwnerProcessID == process_id { + let thread = unsafe { OpenThread(THREAD_SUSPEND_RESUME, 0, entry.th32ThreadID) }; + if thread.is_null() { + return Err(windows_error("could not open the suspended hook thread")); + } + return Ok(unsafe { OwnedHandle::from_raw_handle(thread) }); + } + found = unsafe { Thread32Next(snapshot.as_raw_handle(), &mut entry) }; + } + Err(windows_error("could not find the suspended hook thread")) + } + + fn windows_error(action: &str) -> io::Error { + io::Error::other(format!("{action}: {}", io::Error::last_os_error())) + } + + #[cfg(test)] + mod tests { + use super::*; + use windows_sys::Win32::System::Threading::SuspendThread; + + #[test] + fn hook_is_still_suspended_if_assignment_fails() { + let mut command = crate::proc::hidden("cmd"); + command.args(["/C", "pause"]); + let mut previous_suspend_count = 0; + let error = spawn_assigned(command, |child| { + let thread = primary_thread(child.id())?; + previous_suspend_count = unsafe { SuspendThread(thread.as_raw_handle()) }; + Err(io::Error::other("assignment refused")) + }) + .unwrap_err(); + assert_eq!(error.to_string(), "assignment refused"); + assert_eq!(previous_suspend_count, 1); + } + } +} + +fn collect(child: Child, stdin: &str, timeout: Duration, whole_tree: bool) -> AppResult { + let run = gather(child, stdin, timeout, whole_tree, None, |_| {}); + if run.timed_out { + return Err(timed_out(timeout)); + } + Ok(run.captured) +} + +fn gather( mut child: Child, stdin: &str, timeout: Duration, whole_tree: bool, -) -> AppResult { + mut leftovers: Option, + retain: impl FnOnce(BackgroundProcesses), +) -> TreeRun { + let deadline = Instant::now() + timeout; let stdin_data = stdin.as_bytes().to_vec(); let mut stdin_pipe = child.stdin.take(); let stdin_thread = std::thread::spawn(move || { @@ -273,24 +744,36 @@ fn collect( let (stdout, stdout_thread) = read_pipe(child.stdout.take()); let (stderr, stderr_thread) = read_pipe(child.stderr.take()); + let mut expired = false; + let mut exit_unconfirmed = false; let status = match wait_with_timeout(&mut child, timeout) { Some(status) => status, None => { - if whole_tree { - kill_tree(&mut child); + expired = true; + if let Some(leftovers) = leftovers.take() { + exit_unconfirmed = !leftovers.stop(&mut child); } else { - let _ = child.kill(); + if whole_tree { + kill_tree(&mut child); + exit_unconfirmed = true; + } else { + let _ = child.kill(); + } + let _ = child.wait(); } - let _ = child.wait(); - drop(stdin_thread); - drop(stdout_thread); - drop(stderr_thread); - return Err(AppError::other(format!( - "timed out after {}s", - timeout.as_secs() - ))); + -1 } }; + if let Some(leftovers) = leftovers { + let mut background = BackgroundProcesses { + leftovers: Some(leftovers), + deadline, + stop_deadline: None, + }; + if background.retain_for_cancel() { + retain(background); + } + } let drain_until = Instant::now() + OUTPUT_DRAIN; while !(stdout_thread.is_finished() && stderr_thread.is_finished()) && Instant::now() < drain_until @@ -298,19 +781,30 @@ fn collect( std::thread::sleep(Duration::from_millis(10)); } drop(stdin_thread); - Ok(Captured { + #[cfg(unix)] + if exit_unconfirmed && !matches!(child.try_wait(), Ok(Some(_))) { + let _ = std::thread::Builder::new().spawn(move || { + let _ = child.wait(); + }); + } + let captured = Captured { status, stdout: take_output(&stdout), stderr: take_output(&stderr), - }) + }; + TreeRun { + captured, + timed_out: expired, + exit_unconfirmed, + } } -type SharedOutput = std::sync::Arc>>; +type SharedOutput = std::sync::Arc>>>; fn read_pipe( pipe: Option, ) -> (SharedOutput, std::thread::JoinHandle<()>) { - let output = SharedOutput::default(); + let output = SharedOutput::new(std::sync::Mutex::new(Some(Vec::new()))); let sink = std::sync::Arc::clone(&output); let handle = std::thread::spawn(move || { let Some(mut pipe) = pipe else { @@ -321,8 +815,10 @@ fn read_pipe( match pipe.read(&mut chunk) { Ok(0) => break, Ok(read) => { - if let Ok(mut buffer) = sink.lock() { - buffer.extend_from_slice(&chunk[..read]); + if let Ok(mut output) = sink.lock() { + if let Some(buffer) = output.as_mut() { + buffer.extend_from_slice(&chunk[..read]); + } } } Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {} @@ -336,7 +832,8 @@ fn read_pipe( fn take_output(output: &SharedOutput) -> String { let bytes = output .lock() - .map(|mut buffer| std::mem::take(&mut *buffer)) + .ok() + .and_then(|mut buffer| buffer.take()) .unwrap_or_default(); String::from_utf8_lossy(&bytes).into_owned() } @@ -519,6 +1016,12 @@ pub fn run(request: CliRunRequest) -> AppResult { mod tests { use super::*; + fn run_test_tree(tree: TreeChild, timeout: Duration) -> (TreeRun, Option) { + let mut background = None; + let run = run_tree(tree, "", timeout, |processes| background = Some(processes)); + (run, background) + } + #[test] fn cursor_version_keys_follow_the_date_and_ignore_other_folders() { assert_eq!(cursor_version_key("2026.09.26-abcdef01"), Some(20_260_926)); @@ -699,11 +1202,9 @@ mod tests { pid_file.display() )); let started = Instant::now(); - let child = spawn_tree(command).unwrap(); - let Err(err) = capture_tree_child(child, "", Duration::from_secs(1)) else { - panic!("the sleeping shell must time out"); - }; - assert!(err.to_string().contains("timed out"), "{err}"); + let child = spawn_tree(command, false).unwrap(); + let (run, _) = run_test_tree(child, Duration::from_secs(1)); + assert!(run.timed_out, "the sleeping shell must time out"); assert!(started.elapsed() < Duration::from_secs(10)); let grandchild: libc::pid_t = std::fs::read_to_string(&pid_file) .unwrap() @@ -727,14 +1228,276 @@ mod tests { assert!(!alive, "the grandchild outlived the timeout"); } + #[cfg(windows)] + #[test] + fn cancellation_waits_for_a_windows_background_child() { + let mut command = crate::proc::hidden("cmd"); + command.args(["/C", "start", "", "/B", "ping", "-n", "3", "127.0.0.1"]); + let started = Instant::now(); + let child = spawn_tree(command, true).unwrap(); + let (run, background) = run_test_tree(child, Duration::from_secs(30)); + assert!(!run.timed_out); + assert_eq!(background.unwrap().wait_on_cancel(), None); + assert!( + started.elapsed() >= Duration::from_millis(1500), + "returned after {:?}, before the background ping finished", + started.elapsed() + ); + } + + #[test] + fn process_cleanup_stops_polling_at_the_deadline_without_confirming_exit() { + let mut states = [Some(false), Some(false), Some(true)].into_iter(); + let poll = || states.next().flatten(); + assert!(!wait_for_process_exit(Duration::from_millis(5), poll)); + assert!(wait_for_process_exit(Duration::ZERO, || Some(true))); + assert!(!wait_for_process_exit(Duration::ZERO, || None)); + } + + #[cfg(windows)] + #[test] + fn cancellation_stops_a_windows_background_child_at_the_deadline() { + let mut command = crate::proc::hidden("cmd"); + command.args(["/C", "start", "", "/B", "ping", "-n", "30", "127.0.0.1"]); + let started = Instant::now(); + let child = spawn_tree(command, true).unwrap(); + let (run, background) = run_test_tree(child, Duration::from_secs(2)); + assert!(!run.timed_out); + assert_eq!( + background.unwrap().wait_on_cancel(), + Some(CancelOutcome::TimedOut { confirmed: true }) + ); + assert!(started.elapsed() < Duration::from_secs(15)); + } + + #[cfg(unix)] + #[test] + fn a_timed_out_group_hook_cannot_confirm_descendant_exit_after_reaping_its_direct_child() { + let mut command = crate::proc::hidden("/bin/sh"); + command.arg("-c").arg("echo started; exec sleep 30"); + let child = spawn_tree(command, true).unwrap(); + let (run, _) = run_test_tree(child, Duration::from_secs(1)); + assert!(run.timed_out); + assert!(run.exit_unconfirmed); + assert_eq!(run.captured.stdout.trim(), "started"); + } + + #[cfg(unix)] + #[test] + fn a_timed_out_tree_run_keeps_the_output_it_printed_before() { + let mut command = crate::proc::hidden("/bin/sh"); + command + .arg("-c") + .arg("echo started; echo warming up >&2; sleep 30"); + let child = spawn_tree(command, false).unwrap(); + let (run, _) = run_test_tree(child, Duration::from_secs(1)); + assert!(run.timed_out); + assert!(run.exit_unconfirmed); + assert_eq!(run.captured.stdout.trim(), "started"); + assert_eq!(run.captured.stderr.trim(), "warming up"); + } + + #[cfg(target_os = "linux")] + #[test] + fn hook_timeouts_cannot_confirm_a_detached_child_exited() { + for track_descendants in [false, true] { + assert_detached_child_exit_unconfirmed(track_descendants); + } + } + + #[cfg(target_os = "linux")] + fn assert_detached_child_exit_unconfirmed(track_descendants: bool) { + let dir = tempfile::tempdir().unwrap(); + let pid_file = dir.path().join("child-pid"); + let mut command = crate::proc::hidden("/bin/sh"); + command + .arg("-c") + .arg("setsid sleep 30 > /dev/null 2>&1 & echo $! > \"$1\"; wait") + .arg("hook") + .arg(&pid_file); + let child = spawn_tree(command, track_descendants).unwrap(); + let (run, _) = run_test_tree(child, Duration::from_secs(3)); + let detached: libc::pid_t = std::fs::read_to_string(pid_file) + .unwrap() + .trim() + .parse() + .unwrap(); + let alive = unsafe { libc::kill(detached, 0) == 0 }; + if alive { + unsafe { libc::kill(detached, libc::SIGKILL) }; + } + assert!( + alive, + "the fixture child should outlive its original process group" + ); + assert!(run.timed_out); + assert!(run.exit_unconfirmed); + } + + #[cfg(any(unix, windows))] + #[test] + fn retain_for_cancel_drops_an_exit_zero_tree() { + #[cfg(unix)] + let mut command = crate::proc::hidden("/bin/sh"); + #[cfg(unix)] + command.args(["-c", "exit 0"]); + #[cfg(windows)] + let mut command = crate::proc::hidden("cmd"); + #[cfg(windows)] + command.args(["/C", "exit 0"]); + let mut tree = spawn_tree(command, true).unwrap(); + assert!(tree.child.wait().unwrap().success()); + drop(tree.child); + let mut background = BackgroundProcesses { + leftovers: tree.leftovers, + deadline: Instant::now() + Duration::from_secs(20), + stop_deadline: None, + }; + assert!(background.is_tracking()); + assert!(wait_for_process_exit(PROCESS_EXIT_GRACE, || { + Some(!background.retain_for_cancel()) + })); + assert!(!background.is_tracking()); + } + + #[cfg(unix)] + #[test] + fn cancellation_waits_for_background_work_to_finish() { + let dir = std::env::temp_dir().join(format!( + "angkorgit-leftovers-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or_default() + )); + std::fs::create_dir_all(&dir).unwrap(); + let marker = dir.join("late"); + let mut command = crate::proc::hidden("/bin/sh"); + command.arg("-c").arg(format!( + "(sleep 1; echo late > '{}') > /dev/null 2>&1 & echo done", + marker.display() + )); + let child = spawn_tree(command, true).unwrap(); + let (run, background) = run_test_tree(child, Duration::from_secs(20)); + assert!(!marker.exists()); + let background = background.unwrap(); + assert!(background.is_tracking()); + let can_stop = background.can_stop(); + assert_eq!( + background.wait_on_cancel(), + if can_stop { + None + } else { + Some(CancelOutcome::Unconfirmed) + } + ); + let written = marker.exists(); + let deadline = Instant::now() + Duration::from_secs(3); + while !marker.exists() && Instant::now() < deadline { + std::thread::sleep(PROCESS_POLL_INTERVAL); + } + std::fs::remove_dir_all(&dir).ok(); + assert!(!run.timed_out); + assert_eq!(run.captured.stdout.trim(), "done"); + assert!( + !can_stop || written, + "the run returned before its background work finished" + ); + } + + #[cfg(unix)] + #[test] + fn cancellation_stops_verified_background_work_at_the_deadline() { + let mut command = crate::proc::hidden("/bin/sh"); + command.arg("-c").arg("sleep 30 > /dev/null 2>&1 & echo $!"); + let started = Instant::now(); + let child = spawn_tree(command, true).unwrap(); + let (run, processes) = run_test_tree(child, Duration::from_secs(1)); + assert!(!run.timed_out); + let background: libc::pid_t = run.captured.stdout.trim().parse().unwrap(); + let processes = processes.unwrap(); + assert!(processes.is_tracking()); + let can_stop = processes.can_stop(); + let outcome = processes.wait_on_cancel(); + if !can_stop { + unsafe { libc::kill(background, libc::SIGKILL) }; + assert_eq!(outcome, Some(CancelOutcome::Unconfirmed)); + return; + } + assert_eq!(outcome, Some(CancelOutcome::TimedOut { confirmed: false })); + assert!(started.elapsed() < Duration::from_secs(10)); + let deadline = Instant::now() + Duration::from_secs(5); + let mut alive = true; + while alive && Instant::now() < deadline { + alive = unsafe { libc::kill(background, 0) } == 0; + if alive { + std::thread::sleep(Duration::from_millis(50)); + } + } + if alive { + unsafe { + libc::kill(background, libc::SIGKILL); + } + } + assert!(!alive, "the leftover process outlived the deadline"); + } + + #[cfg(target_os = "linux")] + #[test] + #[ignore = "run the test binary in a private PID namespace as PID 1"] + fn cancellation_does_not_signal_a_reused_process_group() { + assert_eq!(std::process::id(), 1); + assert_eq!(std::fs::read_link("/proc/self").unwrap(), Path::new("1")); + + let mut command = crate::proc::hidden("/bin/sh"); + command.arg("-c").arg("sleep 30 > /dev/null 2>&1 & echo $!"); + let original = spawn_tree(command, true).unwrap(); + let group = original.child.id(); + let (run, background) = run_test_tree(original, Duration::from_secs(1)); + assert!(!run.timed_out); + let orphan: libc::pid_t = run.captured.stdout.trim().parse().unwrap(); + assert_eq!(unsafe { libc::kill(orphan, libc::SIGKILL) }, 0); + assert_eq!( + unsafe { libc::waitpid(orphan, std::ptr::null_mut(), 0) }, + orphan + ); + + std::fs::write("/proc/sys/kernel/ns_last_pid", (group - 1).to_string()).unwrap(); + let mut command = crate::proc::hidden("/bin/sh"); + command.arg("-c").arg("exec sleep 30"); + let mut unrelated = spawn_tree(command, false).unwrap(); + assert_eq!(unrelated.child.id(), group); + let background = background.unwrap(); + let can_stop = background.can_stop(); + let outcome = background.wait_on_cancel(); + let survived = unrelated.child.try_wait().unwrap().is_none(); + if survived { + unrelated.child.kill().unwrap(); + } + unrelated.child.wait().unwrap(); + + assert!(survived, "Cancel killed the unrelated process group"); + assert_eq!( + outcome, + if can_stop { + None + } else { + Some(CancelOutcome::Unconfirmed) + } + ); + } + #[cfg(unix)] #[test] fn a_background_process_holding_the_pipes_does_not_hold_up_the_capture() { let mut command = crate::proc::hidden("/bin/sh"); command.arg("-c").arg("sleep 30 & echo $!; echo done"); let started = Instant::now(); - let child = spawn_tree(command).unwrap(); - let captured = capture_tree_child(child, "", Duration::from_secs(60)).unwrap(); + let child = spawn_tree(command, false).unwrap(); + let (run, _) = run_test_tree(child, Duration::from_secs(60)); + assert!(!run.timed_out); + let captured = run.captured; let elapsed = started.elapsed(); let mut lines = captured.stdout.lines(); let background: libc::pid_t = lines.next().unwrap().trim().parse().unwrap(); diff --git a/apps/desktop/src-tauri/src/commands.rs b/apps/desktop/src-tauri/src/commands.rs index bea5d57c..89dc5883 100644 --- a/apps/desktop/src-tauri/src/commands.rs +++ b/apps/desktop/src-tauri/src/commands.rs @@ -1,13 +1,31 @@ +use std::collections::HashMap; +use std::path::PathBuf; +use std::sync::{Mutex, OnceLock}; + use tauri::{AppHandle, Emitter, State}; +use crate::core::post_hooks::{self, Hooked}; use crate::core::types::*; use crate::core::{ branch, commit, conflict, diff, files, history, hooks, misc, pull_preview, remote, repo, scan, stage, submodule, worktree, }; -use crate::error::AppResult; +use crate::error::{AppError, AppResult}; use crate::terminal::TerminalState; +fn report(app: &AppHandle, repo_path: &str, hooked: Hooked) -> T { + for warning in hooked.warnings { + let _ = app.emit( + "hook-warning", + HookWarningEvent { + repo_path: repo_path.to_string(), + warning, + }, + ); + } + hooked.value +} + async fn blocking( f: impl FnOnce() -> AppResult + Send + 'static, ) -> AppResult { @@ -16,6 +34,126 @@ async fn blocking( .map_err(|e| crate::error::AppError::other(e.to_string()))? } +static HOOKED_OPERATIONS: OnceLock>>> = OnceLock::new(); + +struct HookedOperation(PathBuf); + +fn operation_path(path: PathBuf) -> AppResult { + let absolute = if path.is_absolute() { + path + } else { + std::env::current_dir()?.join(path) + }; + let mut parent = absolute.as_path(); + let mut missing = Vec::new(); + loop { + match parent.canonicalize() { + Ok(mut root) => { + for part in missing.into_iter().rev() { + root.push(part); + } + return Ok(root); + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => { + missing.push(parent.file_name().ok_or(error)?); + parent = parent + .parent() + .ok_or_else(|| AppError::other("invalid operation path"))?; + } + Err(error) => return Err(error.into()), + } + } +} + +impl HookedOperation { + fn start(path: PathBuf) -> AppResult { + let path = operation_path(path)?; + let mut active = HOOKED_OPERATIONS + .get_or_init(Mutex::default) + .lock() + .unwrap_or_else(|error| error.into_inner()); + if let Some(hook) = active.get(&path) { + return Err(AppError::Busy { + hook: hook.clone(), + repo: path + .file_name() + .unwrap_or(path.as_os_str()) + .to_string_lossy() + .into_owned(), + }); + } + active.insert(path.clone(), None); + Ok(Self(path)) + } +} + +impl Drop for HookedOperation { + fn drop(&mut self) { + HOOKED_OPERATIONS + .get_or_init(Mutex::default) + .lock() + .unwrap_or_else(|error| error.into_inner()) + .remove(&self.0); + } +} + +#[derive(Clone, serde::Serialize)] +#[serde(rename_all = "camelCase")] +struct PostHookProgress<'a> { + repo_path: &'a str, + hook: &'a str, + running: bool, +} + +async fn blocking_post_hooks( + app: &AppHandle, + path: String, + action: impl FnOnce(&str) -> AppResult + Send + 'static, +) -> AppResult { + let app = app.clone(); + blocking(move || { + let operation = HookedOperation::start(PathBuf::from(&path))?; + let operation_path = operation.0.clone(); + hooks::observe_post_hooks( + move |workdir, hook, running| { + let mut active = HOOKED_OPERATIONS + .get_or_init(Mutex::default) + .lock() + .unwrap_or_else(|error| error.into_inner()); + if let Some(active_hook) = active.get_mut(&operation_path) { + *active_hook = running.then(|| hook.to_string()); + } + if let Ok(hook_path) = workdir.canonicalize() { + if let Some(active_hook) = active.get_mut(&hook_path) { + *active_hook = running.then(|| hook.to_string()); + } + } + drop(active); + let workdir = workdir.to_string_lossy(); + let _ = app.emit( + "post-hook-progress", + PostHookProgress { + repo_path: workdir.trim_end_matches(['/', '\\']), + hook, + running, + }, + ); + }, + || action(&path), + ) + }) + .await +} + +async fn run_hooked( + app: AppHandle, + path: String, + action: impl FnOnce(&str) -> AppResult> + Send + 'static, +) -> AppResult { + let hooked = blocking_post_hooks(&app, path.clone(), action).await?; + Ok(report(&app, &path, hooked)) +} + #[tauri::command] pub async fn repo_open(app: AppHandle, path: String) -> AppResult { let info = blocking(move || { @@ -62,12 +200,20 @@ pub async fn repo_clone( branch: Option, ) -> AppResult { let emitter = app.clone(); - let root = blocking(move || { - remote::clone(&url, &into, branch.as_deref(), move |pct| { - let _ = emitter.emit("clone-progress", pct); - }) + let cloned = blocking_post_hooks(&app, into, move |into| { + post_hooks::clone( + &url, + into, + branch.as_deref(), + move |pct| { + let _ = emitter.emit("clone-progress", pct); + }, + false, + ) }) .await?; + let root = cloned.value.clone(); + report(&app, &root, cloned); crate::state::recent_add(&app, &root)?; Ok(root) } @@ -138,23 +284,45 @@ pub async fn unstage_all(path: String) -> AppResult<()> { } #[tauri::command] -pub async fn discard_file(path: String, file: String) -> AppResult { - blocking(move || stage::discard_file(&path, &file)).await +pub async fn discard_file(app: AppHandle, path: String, file: String) -> AppResult { + run_hooked(app, path, move |path| { + post_hooks::discard_file(path, &file, false) + }) + .await +} + +#[tauri::command] +pub async fn discard_files( + app: AppHandle, + path: String, + files: Vec, + staged: bool, +) -> AppResult { + run_hooked(app, path, move |path| { + post_hooks::discard_files(path, &files, staged, false) + }) + .await } #[tauri::command] -pub async fn discard_all(path: String) -> AppResult> { - blocking(move || stage::discard_all(&path)).await +pub async fn discard_all(app: AppHandle, path: String) -> AppResult> { + run_hooked(app, path, move |path| post_hooks::discard_all(path, false)).await } #[tauri::command] -pub async fn discard_staged_file(path: String, file: String) -> AppResult { - blocking(move || stage::discard_staged_file(&path, &file)).await +pub async fn discard_staged_file(app: AppHandle, path: String, file: String) -> AppResult { + run_hooked(app, path, move |path| { + post_hooks::discard_staged_file(path, &file, false) + }) + .await } #[tauri::command] -pub async fn discard_staged_all(path: String) -> AppResult> { - blocking(move || stage::discard_staged_all(&path)).await +pub async fn discard_staged_all(app: AppHandle, path: String) -> AppResult { + run_hooked(app, path, move |path| { + post_hooks::discard_staged_all(path, false) + }) + .await } #[tauri::command] @@ -305,21 +473,33 @@ pub async fn commit_create( #[tauri::command] pub async fn commit_amend( + app: AppHandle, path: String, message: Option, noVerify: Option, ) -> AppResult { - blocking(move || commit::amend(&path, message.as_deref(), noVerify.unwrap_or(false))).await + run_hooked(app, path, move |path| { + post_hooks::amend(path, message.as_deref(), noVerify.unwrap_or(false)) + }) + .await } #[tauri::command] -pub async fn repo_hooks(path: String) -> AppResult> { +pub async fn repo_hooks(path: String) -> AppResult { blocking(move || hooks::repo_hooks(&path)).await } #[tauri::command] -pub async fn commit_reword(path: String, oid: String, message: String) -> AppResult { - blocking(move || commit::reword(&path, &oid, &message)).await +pub async fn commit_reword( + app: AppHandle, + path: String, + oid: String, + message: String, +) -> AppResult { + run_hooked(app, path, move |path| { + post_hooks::reword(path, &oid, &message, false) + }) + .await } #[tauri::command] @@ -390,15 +570,14 @@ pub async fn branch_list(path: String) -> AppResult> { #[tauri::command] pub async fn branch_create( + app: AppHandle, path: String, name: String, fromOid: Option, checkout: bool, ) -> AppResult<()> { - blocking(move || { - submodule::synced(&path, || { - branch::create(&path, &name, fromOid.as_deref(), checkout) - }) + run_hooked(app, path, move |path| { + post_hooks::branch_create(path, &name, fromOid.as_deref(), checkout, false) }) .await } @@ -414,19 +593,30 @@ pub async fn branch_rename(path: String, oldName: String, newName: String) -> Ap } #[tauri::command] -pub async fn branch_checkout(path: String, name: String) -> AppResult<()> { - blocking(move || submodule::synced(&path, || branch::checkout_branch(&path, &name))).await +pub async fn branch_checkout(app: AppHandle, path: String, name: String) -> AppResult<()> { + run_hooked(app, path, move |path| { + post_hooks::checkout_branch(path, &name, false) + }) + .await } #[tauri::command] -pub async fn checkout_detached(path: String, rev: String) -> AppResult<()> { - blocking(move || submodule::synced(&path, || branch::checkout_detached(&path, &rev))).await +pub async fn checkout_detached(app: AppHandle, path: String, rev: String) -> AppResult<()> { + run_hooked(app, path, move |path| { + post_hooks::checkout_detached(path, &rev, false) + }) + .await } #[tauri::command] -pub async fn branch_merge(path: String, name: String, noFf: Option) -> AppResult { - blocking(move || { - submodule::synced(&path, || branch::merge(&path, &name, noFf.unwrap_or(false))) +pub async fn branch_merge( + app: AppHandle, + path: String, + name: String, + noFf: Option, +) -> AppResult { + run_hooked(app, path, move |path| { + post_hooks::merge(path, &name, noFf.unwrap_or(false), false) }) .await } @@ -437,13 +627,19 @@ pub async fn merge_abort(path: String) -> AppResult<()> { } #[tauri::command] -pub async fn branch_rebase(path: String, upstream: String) -> AppResult { - blocking(move || submodule::synced(&path, || branch::rebase(&path, &upstream))).await +pub async fn branch_rebase(app: AppHandle, path: String, upstream: String) -> AppResult { + run_hooked(app, path, move |path| { + Ok(post_hooks::rebase(path, &upstream, false)) + }) + .await? } #[tauri::command] -pub async fn rebase_continue(path: String) -> AppResult { - blocking(move || submodule::synced(&path, || branch::rebase_continue(&path))).await +pub async fn rebase_continue(app: AppHandle, path: String) -> AppResult { + run_hooked(app, path, move |path| { + post_hooks::rebase_continue(path, false) + }) + .await } #[tauri::command] @@ -458,12 +654,13 @@ pub async fn rebase_commits(path: String, baseOid: String) -> AppResult, ) -> AppResult { - blocking(move || { - submodule::synced(&path, || branch::rebase_interactive(&path, &baseOid, &todo)) + run_hooked(app, path, move |path| { + post_hooks::rebase_interactive(path, &baseOid, &todo, false) }) .await } @@ -537,17 +734,24 @@ pub async fn remote_fetch( #[tauri::command] pub async fn repository_group_update( + app: AppHandle, path: String, pull: bool, runId: String, ) -> AppResult { let control = crate::core::group_update::control(&runId)?; - blocking(move || remote::group_update_controlled(&path, pull, &control)).await + if !pull { + return blocking(move || remote::group_update_controlled(&path, false, &control)).await; + } + blocking_post_hooks(&app, path, move |path| { + remote::group_update_controlled(path, true, &control) + }) + .await } #[tauri::command] -pub fn repository_group_start(runId: String) -> AppResult<()> { - crate::core::group_update::start(&runId) +pub fn repository_group_start(runId: String, noVerify: Option) -> AppResult<()> { + crate::core::group_update::start(&runId, noVerify.unwrap_or(false)) } #[tauri::command] @@ -562,12 +766,21 @@ pub async fn repository_group_finish(runId: String) -> AppResult<()> { #[tauri::command] pub async fn remote_pull( + app: AppHandle, path: String, remote: String, mode: Option, + noVerify: Option, ) -> AppResult { - blocking(move || submodule::synced(&path, || remote::pull(&path, &remote, mode.as_deref()))) - .await + run_hooked(app, path, move |path| { + Ok(post_hooks::pull( + path, + &remote, + mode.as_deref(), + noVerify.unwrap_or(false), + )) + }) + .await? } #[tauri::command] @@ -600,8 +813,15 @@ pub async fn pull_preview(path: String, remote: String) -> AppResult AppResult { - blocking(move || remote::pull_branch(&path, &branch)).await +pub async fn remote_pull_branch( + app: AppHandle, + path: String, + branch: String, +) -> AppResult { + run_hooked(app, path, move |path| { + post_hooks::pull_branch(path, &branch, false) + }) + .await } #[tauri::command] @@ -659,11 +879,15 @@ pub async fn stash_files(path: String, index: usize) -> AppResult, ) -> AppResult> { - blocking(move || misc::stash_restore_files(&path, index, &paths)).await + run_hooked(app, path, move |path| { + post_hooks::stash_restore_files(path, index, &paths, false) + }) + .await } #[tauri::command] @@ -702,8 +926,20 @@ pub async fn worktree_list(path: String) -> AppResult> { } #[tauri::command] -pub async fn worktree_add(path: String, request: WorktreeAddRequest) -> AppResult { - blocking(move || worktree::add(&path, &request)).await +pub async fn worktree_add( + app: AppHandle, + path: String, + request: WorktreeAddRequest, +) -> AppResult { + let added = + blocking_post_hooks(&app, path, move |path| guarded_worktree_add(path, &request)).await?; + let created = added.value.clone(); + Ok(report(&app, &created, added)) +} + +fn guarded_worktree_add(path: &str, request: &WorktreeAddRequest) -> AppResult> { + let _target = HookedOperation::start(PathBuf::from(request.directory.trim()))?; + post_hooks::worktree_add(path, request, false) } #[tauri::command] @@ -968,16 +1204,15 @@ pub async fn forge_request( #[tauri::command] pub async fn pr_checkout( + app: AppHandle, path: String, remote: String, sourceRef: String, branch: String, track: bool, ) -> AppResult<()> { - blocking(move || { - submodule::synced(&path, || { - remote::checkout_remote_ref(&path, &remote, &sourceRef, &branch, track) - }) + run_hooked(app, path, move |path| { + post_hooks::checkout_remote_ref(path, &remote, &sourceRef, &branch, track, false) }) .await } @@ -1047,3 +1282,107 @@ pub async fn index_files(path: String) -> AppResult> { pub async fn file_contents(path: String, file: String, oid: Option) -> AppResult { blocking(move || files::file_contents(&path, &file, oid.as_deref())).await } + +#[cfg(test)] +mod tests { + use super::*; + use std::time::{Duration, Instant}; + + #[test] + fn a_new_worktree_is_locked_through_its_canonical_path_until_its_hook_finishes() { + if !hooks::runner_available() { + return; + } + let root = tempfile::tempdir().unwrap(); + let main = root.path().join("main"); + let repo = git2::Repository::init(&main).unwrap(); + let signature = git2::Signature::now("Test", "test@example.com").unwrap(); + let tree = repo.index().unwrap().write_tree().unwrap(); + let oid = repo + .commit( + Some("HEAD"), + &signature, + &signature, + "base", + &repo.find_tree(tree).unwrap(), + &[], + ) + .unwrap(); + repo.branch("topic", &repo.find_commit(oid).unwrap(), false) + .unwrap(); + let hooks_dir = repo.path().join("hooks"); + std::fs::create_dir_all(&hooks_dir).unwrap(); + repo.config() + .unwrap() + .set_str("core.hooksPath", hooks_dir.to_str().unwrap()) + .unwrap(); + let started = root.path().join("started"); + let release = root.path().join("release"); + let hook = hooks_dir.join("post-checkout"); + let shell_path = |path: &std::path::Path| path.to_string_lossy().replace('\\', "/"); + std::fs::write(&hook, format!("#!/bin/sh\necho started > '{}'\nattempts=0\nwhile [ ! -f '{}' ] && [ \"$attempts\" -lt 200 ]; do sleep 0.05; attempts=$((attempts + 1)); done\n", shell_path(&started), shell_path(&release))).unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + let target = root.path().join("real/new/target"); + std::fs::create_dir(root.path().join("real")).unwrap(); + #[cfg(unix)] + let requested = { + std::os::unix::fs::symlink(root.path().join("real"), root.path().join("alias")) + .unwrap(); + root.path().join("alias/new/target") + }; + #[cfg(not(unix))] + let requested = target.clone(); + let request = WorktreeAddRequest { + directory: requested.to_string_lossy().into_owned(), + branch: "topic".into(), + create_branch: false, + base: None, + }; + let (saw_hook, blocked, outcome) = std::thread::scope(|scope| { + let running = scope.spawn(|| guarded_worktree_add(main.to_str().unwrap(), &request)); + let deadline = Instant::now() + Duration::from_secs(5); + while !started.exists() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + let saw_hook = started.exists(); + let blocked = HookedOperation::start(target.join(".")); + std::fs::write(&release, "").unwrap(); + (saw_hook, blocked, running.join().unwrap()) + }); + assert!(saw_hook); + assert!(matches!(blocked, Err(AppError::Busy { .. }))); + let outcome = outcome.unwrap(); + assert!(outcome.warnings.is_empty(), "{:?}", outcome.warnings); + assert_eq!( + git2::Repository::open(&target) + .unwrap() + .head() + .unwrap() + .target(), + Some(oid) + ); + let _released = HookedOperation::start(target).unwrap(); + } + + #[test] + fn a_target_lock_conflict_does_not_create_a_worktree_or_branch() { + let root = tempfile::tempdir().unwrap(); + let target = root.path().join("missing/target"); + let guard = HookedOperation::start(target.clone()).unwrap(); + let request = WorktreeAddRequest { + directory: target.to_string_lossy().into_owned(), + branch: "topic".into(), + create_branch: true, + base: None, + }; + let result = guarded_worktree_add(root.path().to_str().unwrap(), &request); + assert!(matches!(result, Err(AppError::Busy { .. }))); + assert!(!target.exists()); + drop(guard); + let _released = HookedOperation::start(target).unwrap(); + } +} diff --git a/apps/desktop/src-tauri/src/core/branch.rs b/apps/desktop/src-tauri/src/core/branch.rs index 0f936e3d..711521cb 100644 --- a/apps/desktop/src-tauri/src/core/branch.rs +++ b/apps/desktop/src-tauri/src/core/branch.rs @@ -2,6 +2,7 @@ use git2::{build::CheckoutBuilder, BranchType, Repository, ResetType}; use crate::error::{AppError, AppResult}; +use super::hooks::{PostHook, PostHooks}; use super::types::{BranchInfo, CommitInfo, OpOutcome, RebaseTodoEntry}; pub fn list(path: &str) -> AppResult> { @@ -196,11 +197,19 @@ pub fn checkout_detached(path: &str, rev: &str) -> AppResult<()> { Ok(()) } +pub(crate) fn set_orig_head(repo: &Repository, oid: git2::Oid) -> AppResult<()> { + repo.reference("ORIG_HEAD", oid, true, "updating ORIG_HEAD")?; + Ok(()) +} + pub fn merge(path: &str, branch: &str, no_ff: bool) -> AppResult { let repo = super::repo::open(path)?; let reference = resolve_branch_ref(&repo, branch)?; let annotated = repo.reference_to_annotated_commit(&reference)?; let (analysis, _pref) = repo.merge_analysis(&[&annotated])?; + if let Some(head) = repo.head().ok().and_then(|head| head.target()) { + set_orig_head(&repo, head)?; + } if analysis.is_up_to_date() { return Ok(OpOutcome { @@ -264,13 +273,88 @@ pub fn abort_merge(path: &str) -> AppResult<()> { } pub fn rebase(path: &str, upstream: &str) -> AppResult { + rebase_with_hooks(path, upstream, &mut PostHooks::off()) +} + +const SKIP_HOOKS_MARK: &str = "angkorgit-skip-hooks"; + +fn rebase_state_dir(repo: &Repository) -> std::path::PathBuf { + repo.path().join("rebase-merge") +} + +fn paused_rebase() -> OpOutcome { + OpOutcome { + status: "conflicts".into(), + message: "Rebase paused on conflicts. Resolve them, then continue.".into(), + } +} + +fn ensure_rebase_can_start(repo: &Repository) -> AppResult<()> { + if repo.state() != git2::RepositoryState::Clean { + return Err(AppError::other( + "another operation is still in progress (a rebase, merge, cherry-pick or revert) — \ + finish or abort it first", + )); + } + ensure_clean_for_libgit2_rebase(repo) +} + +fn linear_since(repo: &Repository, head: git2::Oid, base: git2::Oid) -> AppResult { + let mut walk = repo.revwalk()?; + walk.push(head)?; + walk.hide(base)?; + for oid in walk { + if repo.find_commit(oid?)?.parent_count() > 1 { + return Ok(false); + } + } + Ok(true) +} + +pub(crate) fn rebase_with_hooks( + path: &str, + upstream: &str, + hooks: &mut PostHooks, +) -> AppResult { let repo = super::repo::open(path)?; let reference = resolve_branch_ref(&repo, upstream)?; let upstream_annotated = repo.reference_to_annotated_commit(&reference)?; let sig = repo.signature()?; + let previous = repo.head()?.peel_to_commit()?.id(); + let onto = upstream_annotated.id(); + ensure_rebase_can_start(&repo)?; + if previous == onto + || (repo.graph_descendant_of(previous, onto)? && linear_since(&repo, previous, onto)?) + { + return Ok(OpOutcome { + status: "up_to_date".into(), + message: format!("Already up to date with {upstream}"), + }); + } let mut opts = git2::RebaseOptions::new(); let mut rebase = repo.rebase(None, Some(&upstream_annotated), None, Some(&mut opts))?; + if hooks.skipped() { + if let Err(error) = std::fs::write(rebase_state_dir(&repo).join(SKIP_HOOKS_MARK), "") { + let _ = rebase.abort(); + return Err(error.into()); + } + } + hooks.run_now( + &repo, + PostHook::Checkout { + previous, + new: onto, + branch: true, + }, + ); + + if !rebase_state_dir(&repo).is_dir() { + return Ok(OpOutcome { + status: "ok".into(), + message: "Rebase aborted".into(), + }); + } while let Some(op) = rebase.next() { if let Err(error) = op { @@ -278,10 +362,7 @@ pub fn rebase(path: &str, upstream: &str) -> AppResult { } let index = repo.index()?; if index.has_conflicts() { - return Ok(OpOutcome { - status: "conflicts".into(), - message: "Rebase paused on conflicts. Resolve them, then continue.".into(), - }); + return Ok(paused_rebase()); } match rebase.commit(None, &sig, None) { Ok(_) => {} @@ -289,22 +370,48 @@ pub fn rebase(path: &str, upstream: &str) -> AppResult { Err(e) => return Err(e.into()), } } + let rewritten = rewritten_pairs(&repo); rebase.finish(Some(&sig))?; + if let Some(hook) = PostHook::rebased(rewritten) { + hooks.later(hook); + } Ok(OpOutcome { status: "ok".into(), message: format!("Rebased onto {upstream}"), }) } +fn rewritten_pairs(repo: &Repository) -> Vec<(git2::Oid, git2::Oid)> { + let file = rebase_state_dir(repo).join("rewritten"); + let Ok(text) = std::fs::read_to_string(file) else { + return Vec::new(); + }; + text.lines() + .filter_map(|line| { + let mut ids = line.split_whitespace(); + let old = git2::Oid::from_str(ids.next()?).ok()?; + let new = git2::Oid::from_str(ids.next()?).ok()?; + Some((old, new)) + }) + .collect() +} + pub fn rebase_continue(path: &str) -> AppResult { + rebase_continue_with_hooks(path, &mut PostHooks::off()) +} + +pub(crate) fn rebase_continue_with_hooks( + path: &str, + hooks: &mut PostHooks, +) -> AppResult { let repo = super::repo::open(path)?; let sig = repo.signature()?; let mut rebase = repo.open_rebase(None)?; + if rebase_state_dir(&repo).join(SKIP_HOOKS_MARK).exists() { + hooks.skip(); + } if reapply_stopped_step(&repo, &mut rebase)? { - return Ok(OpOutcome { - status: "conflicts".into(), - message: "Rebase paused on conflicts. Resolve them, then continue.".into(), - }); + return Ok(paused_rebase()); } { @@ -328,10 +435,7 @@ pub fn rebase_continue(path: &str) -> AppResult { } let index = repo.index()?; if index.has_conflicts() { - return Ok(OpOutcome { - status: "conflicts".into(), - message: "Rebase paused on conflicts. Resolve them, then continue.".into(), - }); + return Ok(paused_rebase()); } match rebase.commit(None, &sig, None) { Ok(_) => {} @@ -339,7 +443,11 @@ pub fn rebase_continue(path: &str) -> AppResult { Err(e) => return Err(e.into()), } } + let rewritten = rewritten_pairs(&repo); rebase.finish(Some(&sig))?; + if let Some(hook) = PostHook::rebased(rewritten) { + hooks.later(hook); + } Ok(OpOutcome { status: "ok".into(), message: "Rebase complete".into(), @@ -496,22 +604,65 @@ pub fn rebase_commits(path: &str, base: &str) -> AppResult> { Ok(commits) } +fn uncommitted_changes() -> AppError { + AppError::other("working tree has uncommitted changes — commit or stash them first") +} + fn ensure_tracked_clean(repo: &Repository) -> AppResult<()> { + ensure_clean(repo, git2::SubmoduleIgnore::Unspecified) +} + +fn ensure_clean_for_libgit2_rebase(repo: &Repository) -> AppResult<()> { + ensure_clean(repo, git2::SubmoduleIgnore::Untracked) +} + +fn ensure_clean(repo: &Repository, submodules: git2::SubmoduleIgnore) -> AppResult<()> { let mut opts = git2::StatusOptions::new(); - opts.include_untracked(false).include_ignored(false); - let statuses = repo.statuses(Some(&mut opts))?; - if !statuses.is_empty() { - return Err(AppError::other( - "working tree has uncommitted changes — commit or stash them first", - )); + opts.include_untracked(false) + .include_ignored(false) + .exclude_submodules(true); + if !repo.statuses(Some(&mut opts))?.is_empty() || submodule_changed(repo, submodules)? { + return Err(uncommitted_changes()); } Ok(()) } +fn submodule_changed(repo: &Repository, ignore: git2::SubmoduleIgnore) -> AppResult { + let worktree_changed = git2::SubmoduleStatus::WD_ADDED + | git2::SubmoduleStatus::WD_DELETED + | git2::SubmoduleStatus::WD_MODIFIED + | git2::SubmoduleStatus::WD_INDEX_MODIFIED + | git2::SubmoduleStatus::WD_WD_MODIFIED + | git2::SubmoduleStatus::WD_UNTRACKED; + for submodule in repo.submodules()? { + if submodule.head_id() != submodule.index_id() { + return Ok(true); + } + let Some(name) = submodule.name() else { + continue; + }; + let status = repo.submodule_status(name, ignore)?; + if status.intersects(worktree_changed) { + return Ok(true); + } + } + Ok(false) +} + pub fn rebase_interactive(path: &str, base: &str, todo: &[RebaseTodoEntry]) -> AppResult { + rebase_interactive_with_hooks(path, base, todo, &mut PostHooks::off()) +} + +pub(crate) fn rebase_interactive_with_hooks( + path: &str, + base: &str, + todo: &[RebaseTodoEntry], + hooks: &mut PostHooks, +) -> AppResult { let repo = super::repo::open(path)?; let sig = super::commit::default_signature(&repo)?; ensure_tracked_clean(&repo)?; + let previous = repo.head()?.peel_to_commit()?.id(); let range = rebase_commits(path, base)?; let allowed: std::collections::HashSet<&str> = range.iter().map(|c| c.oid.as_str()).collect(); @@ -539,6 +690,8 @@ pub fn rebase_interactive(path: &str, base: &str, todo: &[RebaseTodoEntry]) -> A let base_commit = repo.find_commit(git2::Oid::from_str(base)?)?; let mut parent = base_commit; let mut built_any = false; + let mut rewritten: Vec<(git2::Oid, git2::Oid)> = Vec::new(); + let mut chain: Vec = Vec::new(); for entry in todo { if entry.action == "drop" { continue; @@ -575,7 +728,9 @@ pub fn rebase_interactive(path: &str, base: &str, todo: &[RebaseTodoEntry]) -> A let parent_refs: Vec<&git2::Commit> = grandparents.iter().collect(); let oid = repo.commit(None, &parent.author(), &sig, &message, &tree, &parent_refs)?; parent = repo.find_commit(oid)?; + chain.push(commit.id()); } else { + rewritten.extend(chain.drain(..).map(|old| (old, parent.id()))); let message = match entry.message.as_deref().map(str::trim) { Some(m) if entry.action == "reword" && !m.is_empty() => m.to_string(), _ => commit.message().unwrap_or("").to_string(), @@ -583,10 +738,20 @@ pub fn rebase_interactive(path: &str, base: &str, todo: &[RebaseTodoEntry]) -> A let oid = repo.commit(None, &commit.author(), &sig, &message, &tree, &[&parent])?; parent = repo.find_commit(oid)?; built_any = true; + chain.push(commit.id()); } } + rewritten.extend(chain.drain(..).map(|old| (old, parent.id()))); repo.reset(parent.as_object(), ResetType::Hard, None)?; + hooks.later(PostHook::Checkout { + previous, + new: parent.id(), + branch: true, + }); + if let Some(hook) = PostHook::rebased(rewritten) { + hooks.later(hook); + } Ok(parent.id().to_string()) } diff --git a/apps/desktop/src-tauri/src/core/commit.rs b/apps/desktop/src-tauri/src/core/commit.rs index e9da39f0..ff48f4e7 100644 --- a/apps/desktop/src-tauri/src/core/commit.rs +++ b/apps/desktop/src-tauri/src/core/commit.rs @@ -2,7 +2,7 @@ use git2::Repository; use crate::error::{AppError, AppResult}; -use super::hooks::CommitHooks; +use super::hooks::{CommitHooks, PostHook, PostHooks, Rewrite}; use super::types::{CommitOutcome, OpOutcome, RebaseTodoEntry}; pub(crate) fn default_signature(repo: &Repository) -> AppResult> { @@ -174,6 +174,22 @@ pub fn revert(path: &str, oid: &str) -> AppResult { } pub fn amend(path: &str, message: Option<&str>, no_verify: bool) -> AppResult { + amend_with_hooks(path, message, no_verify, &mut PostHooks::off()) +} + +fn amended(old: git2::Oid, new: git2::Oid) -> PostHook { + PostHook::Rewrite { + command: Rewrite::Amend, + pairs: vec![(old, new)], + } +} + +pub(crate) fn amend_with_hooks( + path: &str, + message: Option<&str>, + no_verify: bool, + post_hooks: &mut PostHooks, +) -> AppResult { let repo = super::repo::open(path)?; let head = repo .head() @@ -204,6 +220,7 @@ pub fn amend(path: &str, message: Option<&str>, no_verify: bool) -> AppResult, no_verify: bool) -> AppResult, no_verify: bool) -> AppResult AppResult { + reword_with_hooks(path, oid, message, &mut PostHooks::off()) +} + +pub(crate) fn reword_with_hooks( + path: &str, + oid: &str, + message: &str, + hooks: &mut PostHooks, +) -> AppResult { let message = message.trim_end(); if message.trim().is_empty() { return Err(AppError::other("the commit message cannot be empty")); @@ -242,7 +269,9 @@ pub fn reword(path: &str, oid: &str, message: &str) -> AppResult { .map_err(|_| AppError::other("nothing to reword: repository has no commits"))? .peel_to_commit()?; if target.id() == head.id() { - return reword_head(&repo, &head, message); + let new = reword_head(&repo, &head, message)?; + hooks.later(amended(head.id(), new)); + return Ok(new.to_string()); } let parent = target.parent(0).map_err(|_| { AppError::other("the root commit can only be reworded while it is the latest commit") @@ -267,7 +296,7 @@ pub fn reword(path: &str, oid: &str, message: &str) -> AppResult { } }) .collect(); - let new_head = super::branch::rebase_interactive(path, &parent_oid, &todo)?; + let new_head = super::branch::rebase_interactive_with_hooks(path, &parent_oid, &todo, hooks)?; let mut commit = repo.find_commit(git2::Oid::from_str(&new_head)?)?; for _ in 0..index { commit = commit.parent(0)?; @@ -275,15 +304,14 @@ pub fn reword(path: &str, oid: &str, message: &str) -> AppResult { Ok(commit.id().to_string()) } -fn reword_head(repo: &Repository, head: &git2::Commit, message: &str) -> AppResult { +fn reword_head(repo: &Repository, head: &git2::Commit, message: &str) -> AppResult { if super::sign::signing_config(repo)?.is_none() { - let oid = head.amend(Some("HEAD"), None, None, None, Some(message), None)?; - return Ok(oid.to_string()); + return Ok(head.amend(Some("HEAD"), None, None, None, Some(message), None)?); } let tree = head.tree()?; let parents: Vec = head.parents().collect(); let parent_refs: Vec<&git2::Commit> = parents.iter().collect(); - let oid = super::sign::create_commit( + super::sign::create_commit( repo, Some("HEAD"), &head.author(), @@ -291,6 +319,5 @@ fn reword_head(repo: &Repository, head: &git2::Commit, message: &str) -> AppResu message, &tree, &parent_refs, - )?; - Ok(oid.to_string()) + ) } diff --git a/apps/desktop/src-tauri/src/core/group_update.rs b/apps/desktop/src-tauri/src/core/group_update.rs index 421afa46..d1df6fdd 100644 --- a/apps/desktop/src-tauri/src/core/group_update.rs +++ b/apps/desktop/src-tauri/src/core/group_update.rs @@ -1,14 +1,22 @@ use std::collections::HashMap; -use std::sync::{Arc, Mutex, MutexGuard, OnceLock}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock, TryLockError}; use std::time::{Duration, Instant}; +use super::hooks::PendingHook; use super::types::{GroupUpdateReceipt, GroupUpdateResult}; +use crate::ai_cli::{CancelPoll, PROCESS_POLL_INTERVAL}; use crate::error::{AppError, AppResult}; #[derive(Default)] pub struct GroupUpdateControl { - cancelled: Mutex, + cancelled: AtomicBool, + active: Mutex<()>, completed: Mutex>, + background_hooks: Mutex>, + background_changed: Condvar, + cancel_receipt: Mutex<()>, + no_verify: bool, } #[derive(Clone)] @@ -26,21 +34,81 @@ pub(super) struct FetchProgress { } impl GroupUpdateControl { + pub fn skipping_hooks(no_verify: bool) -> Self { + GroupUpdateControl { + no_verify, + ..Default::default() + } + } + + pub fn skips_hooks(&self) -> bool { + self.no_verify + } + pub fn cancel(&self) -> AppResult<()> { - *self - .cancelled - .lock() - .map_err(|_| AppError::other("Group update lock poisoned"))? = true; + self.cancelled.store(true, Ordering::Release); + drop( + self.active + .lock() + .map_err(|_| AppError::other("Group update lock poisoned"))?, + ); Ok(()) } pub fn cancel_results(&self) -> AppResult> { - self.cancel()?; - let completed = self - .completed + self.cancelled.store(true, Ordering::Release); + let _receipt = self + .cancel_receipt .lock() - .map_err(|_| AppError::other("Group results lock poisoned"))? - .clone(); + .map_err(|_| AppError::other("Group cancellation lock poisoned"))?; + let mut warnings = Vec::new(); + loop { + let active_done = match self.active.try_lock() { + Ok(_) => true, + Err(TryLockError::WouldBlock) => false, + Err(TryLockError::Poisoned(_)) => { + return Err(AppError::other("Group update lock poisoned")); + } + }; + let mut next_poll = Instant::now() + PROCESS_POLL_INTERVAL; + let mut hooks = self + .background_hooks + .lock() + .map_err(|_| AppError::other("Group hook lock poisoned"))?; + hooks.retain_mut(|(path, hook)| match hook.poll_on_cancel() { + CancelPoll::Waiting(deadline) => { + next_poll = next_poll.min(deadline); + true + } + CancelPoll::Finished(warning) => { + if let Some(warning) = warning { + warnings.push((std::mem::take(path), warning)); + } + false + } + }); + if active_done && hooks.is_empty() { + break; + } + let wait = next_poll.saturating_duration_since(Instant::now()); + drop( + self.background_changed + .wait_timeout(hooks, wait) + .map_err(|_| AppError::other("Group hook lock poisoned"))?, + ); + } + let completed = { + let mut completed = self + .completed + .lock() + .map_err(|_| AppError::other("Group results lock poisoned"))?; + for (path, warning) in warnings { + if let Some(Completed::Result(result)) = completed.get_mut(&path) { + result.hook_warnings.push(warning.into_warning()); + } + } + completed.clone() + }; Ok(completed .into_iter() .map(|(path, completed)| { @@ -73,6 +141,18 @@ impl GroupUpdateControl { .collect()) } + pub(super) fn record_background_hook(&self, path: &str, hook: PendingHook) { + let mut hooks = self + .background_hooks + .lock() + .unwrap_or_else(|error| error.into_inner()); + if !self.is_cancelled() { + hooks.retain_mut(|(_, hook)| hook.retain_for_cancel()); + } + hooks.push((path.into(), hook)); + self.background_changed.notify_one(); + } + pub(super) fn record_fetch(&self, path: &str, progress: FetchProgress) -> AppResult<()> { self.completed .lock() @@ -104,6 +184,7 @@ impl GroupUpdateControl { status: "failed".into(), message: error.to_string(), changes: Vec::new(), + ..Default::default() }, }; self.completed @@ -122,21 +203,18 @@ impl GroupUpdateControl { } pub fn is_cancelled(&self) -> bool { - self.cancelled - .lock() - .map(|cancelled| *cancelled) - .unwrap_or(true) + self.cancelled.load(Ordering::Acquire) } - fn active_guard(&self) -> AppResult> { - let cancelled = self - .cancelled + fn active_guard(&self) -> AppResult> { + let guard = self + .active .lock() .map_err(|_| AppError::other("Group update lock poisoned"))?; - if *cancelled { + if self.is_cancelled() { return Err(AppError::other("Group update cancelled")); } - Ok(cancelled) + Ok(guard) } pub fn ensure_active(&self) -> AppResult<()> { @@ -168,18 +246,18 @@ fn prune_expired(runs: &mut Runs, now: Instant) { if now.saturating_duration_since(run.last_used) < RUN_TTL { return true; } - match run.control.cancelled.try_lock() { - Ok(mut cancelled) => { - *cancelled = true; + match run.control.active.try_lock() { + Ok(_guard) => { + run.control.cancelled.store(true, Ordering::Release); false } - Err(std::sync::TryLockError::WouldBlock) => true, - Err(std::sync::TryLockError::Poisoned(_)) => false, + Err(TryLockError::WouldBlock) => true, + Err(TryLockError::Poisoned(_)) => false, } }); } -pub fn start(id: &str) -> AppResult<()> { +pub fn start(id: &str, no_verify: bool) -> AppResult<()> { let mut runs = runs() .lock() .map_err(|_| AppError::other("Group update registry poisoned"))?; @@ -191,7 +269,7 @@ pub fn start(id: &str) -> AppResult<()> { runs.insert( id.into(), Run { - control: Arc::new(GroupUpdateControl::default()), + control: Arc::new(GroupUpdateControl::skipping_hooks(no_verify)), last_used: now, }, ); @@ -275,10 +353,10 @@ mod tests { last_used: now - RUN_TTL, }, )]); - let guard = control.cancelled.lock().unwrap(); + let guard = control.active.lock().unwrap(); prune_expired(&mut runs, now); assert_eq!(runs.len(), 1); - assert!(!*guard); + assert!(!control.is_cancelled()); drop(guard); prune_expired(&mut runs, now); assert!(runs.is_empty()); diff --git a/apps/desktop/src-tauri/src/core/hooks.rs b/apps/desktop/src-tauri/src/core/hooks.rs index 02796e03..e341f3ca 100644 --- a/apps/desktop/src-tauri/src/core/hooks.rs +++ b/apps/desktop/src-tauri/src/core/hooks.rs @@ -1,17 +1,32 @@ +use std::cell::RefCell; use std::ffi::{OsStr, OsString}; -use std::path::{Path, PathBuf}; -use std::sync::Mutex; +use std::path::{Component, Path, PathBuf}; +use std::sync::{Arc, Mutex, OnceLock}; use std::time::Duration; use git2::{Oid, Repository}; +use same_file::Handle; -use crate::ai_cli::{capture, capture_tree_child, search_path, spawn_tree}; +use super::types::{HookWarning, RepoHooks}; +use crate::ai_cli::{ + capture, run_tree, search_path, spawn_tree, BackgroundProcesses, CancelOutcome, CancelPoll, +}; use crate::error::{AppError, AppResult}; pub const PRE_COMMIT: &str = "pre-commit"; pub const COMMIT_MSG: &str = "commit-msg"; pub const PRE_PUSH: &str = "pre-push"; -const REPO_HOOKS: &[&str] = &[PRE_COMMIT, COMMIT_MSG, PRE_PUSH]; +pub const POST_CHECKOUT: &str = "post-checkout"; +pub const POST_MERGE: &str = "post-merge"; +pub const POST_REWRITE: &str = "post-rewrite"; +const REPO_HOOKS: &[&str] = &[ + PRE_COMMIT, + COMMIT_MSG, + PRE_PUSH, + POST_CHECKOUT, + POST_MERGE, + POST_REWRITE, +]; const MIN_GIT_VERSION: (u32, u32) = (2, 36); const TO_STDIN_VERSION: (u32, u32) = (2, 40); @@ -109,18 +124,151 @@ fn configured_for(repo: &Repository, name: &str) -> AppResult { Ok(false) } -pub fn repo_hooks(path: &str) -> AppResult> { +pub fn repo_hooks(path: &str) -> AppResult { let repo = super::repo::open(path)?; - if repo.workdir().is_none() { - return Ok(Vec::new()); - } + let Some(workdir) = repo.workdir() else { + return Ok(RepoHooks::default()); + }; let mut found = Vec::new(); for name in REPO_HOOKS { if present(&repo, name)? { found.push(name.to_string()); } } - Ok(found) + let in_worktree = hooks_live_in_worktree(&repo, workdir)?; + Ok(RepoHooks { found, in_worktree }) +} + +const SYMLINK_HOPS: usize = 40; + +fn hooks_live_in_worktree(repo: &Repository, workdir: &Path) -> AppResult { + let Ok(workdir) = Handle::from_path(workdir) else { + return Ok(false); + }; + let gitdirs: Vec = [repo.path(), repo.commondir()] + .into_iter() + .filter_map(|dir| Handle::from_path(dir).ok()) + .collect(); + let dir = hooks_dir(repo)?; + let hook_paths = REPO_HOOKS + .iter() + .flat_map(|name| hook_candidates(&dir, name)) + .any(|hook| visits_worktree(&hook, &workdir, &gitdirs)); + Ok(hook_paths || config_lives_in_worktree(repo, &workdir, &gitdirs)) +} + +const CONFIG_FILE_LIMIT: usize = 64; + +#[cfg(windows)] +fn config_include_home() -> Option { + std::env::var_os("HOME") + .map(PathBuf::from) + .filter(|path| path.is_dir()) + .or_else(|| { + let mut drive = std::env::var_os("HOMEDRIVE")?; + drive.push(std::env::var_os("HOMEPATH")?); + let path = PathBuf::from(drive); + path.is_dir().then_some(path) + }) + .or_else(|| std::env::var_os("USERPROFILE").map(PathBuf::from)) +} + +#[cfg(not(windows))] +fn config_include_home() -> Option { + super::remote::home_dir() +} + +fn config_lives_in_worktree(repo: &Repository, workdir: &Handle, gitdirs: &[Handle]) -> bool { + let mut pending = vec![ + repo.commondir().join("config"), + repo.path().join("config.worktree"), + ]; + pending.extend(git2::Config::find_global().ok()); + pending.extend(git2::Config::find_xdg().ok()); + pending.extend(git2::Config::find_system().ok()); + let home = config_include_home(); + let mut seen = std::collections::HashSet::new(); + while let Some(file) = pending.pop() { + if seen.contains(&file) { + continue; + } + if seen.len() >= CONFIG_FILE_LIMIT { + return true; + } + seen.insert(file.clone()); + if visits_worktree(&file, workdir, gitdirs) { + return true; + } + pending.extend(include_targets(&file, home.as_deref())); + } + false +} + +fn include_targets(file: &Path, home: Option<&Path>) -> Vec { + let Ok(config) = git2::Config::open(file) else { + return Vec::new(); + }; + let Ok(mut entries) = config.entries(Some(r"^include(if\..+)?\.path$")) else { + return Vec::new(); + }; + let base = file.parent().unwrap_or(Path::new("")); + let mut targets = Vec::new(); + while let Some(Ok(entry)) = entries.next() { + if entry.include_depth() > 0 { + continue; + } + let Some(value) = entry.value() else { + continue; + }; + targets.push(base.join(super::remote::expand_home(value, home))); + } + targets +} + +fn visits_worktree(path: &Path, workdir: &Handle, gitdirs: &[Handle]) -> bool { + let mut current = PathBuf::new(); + let mut rest = path.to_path_buf(); + let mut hops = 0; + loop { + let mut parts = rest.components(); + let Some(part) = parts.next() else { + return false; + }; + let remaining = parts.as_path().to_path_buf(); + match part { + Component::Prefix(_) | Component::RootDir => current.push(part), + Component::CurDir => {} + Component::ParentDir => { + current.pop(); + } + Component::Normal(name) => { + let next = current.join(name); + let link = std::fs::read_link(&next).ok(); + let in_git = gitdirs + .iter() + .any(|gitdir| within(&next, gitdir, link.is_some())); + if within(&next, workdir, true) && !in_git { + return true; + } + if let Some(target) = link { + hops += 1; + if hops > SYMLINK_HOPS { + return false; + } + rest = target.join(remaining); + continue; + } + current = next; + } + } + rest = remaining; + } +} + +fn within(path: &Path, root: &Handle, strictly: bool) -> bool { + path.ancestors() + .skip(usize::from(strictly)) + .any(|dir| Handle::from_path(dir).is_ok_and(|handle| &handle == root)) } pub fn runner_available() -> bool { @@ -207,9 +355,14 @@ fn pick_runner( return Ok(Runner::Direct(file)); } let (major, minor) = git.version; + let input = if name == PRE_PUSH { + "the refs being pushed" + } else { + "the rewritten commits" + }; Err(format!( - "The {name} hook did not run because git {major}.{minor} cannot hand it the refs being \ - pushed. Git 2.40 or newer is needed to run it." + "The {name} hook did not run because git {major}.{minor} cannot hand it {input}. Git \ + 2.40 or newer is needed to run it." )) } @@ -238,6 +391,82 @@ impl Drop for InputFile { } } +pub(crate) struct PendingHook { + name: String, + timeout: Duration, + output: Arc>, + processes: BackgroundProcesses, +} + +pub(crate) struct PendingHookWarning { + warning: HookWarning, + output: Arc>, +} + +impl PendingHookWarning { + pub(crate) fn into_warning(mut self) -> HookWarning { + self.warning.output = self.output.get().cloned().unwrap_or_default(); + self.warning + } +} + +impl PendingHook { + pub(crate) fn retain_for_cancel(&mut self) -> bool { + self.processes.retain_for_cancel() + } + + pub(crate) fn poll_on_cancel(&mut self) -> CancelPoll { + let outcome = match self.processes.poll_on_cancel() { + CancelPoll::Waiting(deadline) => return CancelPoll::Waiting(deadline), + CancelPoll::Finished(outcome) => outcome, + }; + CancelPoll::Finished(outcome.map(|outcome| self.cancel_warning(outcome))) + } + + fn cancel_warning(&self, outcome: CancelOutcome) -> PendingHookWarning { + let (timed_out, message) = match outcome { + CancelOutcome::Unconfirmed => (false, format!( + "After the {} hook, Cancel could not confirm that all processes exited. Hook processes may still be running.", + self.name, + )), + CancelOutcome::TimedOut { confirmed } => (true, format!( + "Background processes from the {} hook exceeded its {} second limit during cancellation. {}", + self.name, + self.timeout.as_secs(), + if confirmed { + "They were stopped." + } else { + "Could not confirm that all processes stopped." + } + )), + }; + PendingHookWarning { + warning: post_warning(&self.name, None, timed_out, message, String::new()), + output: self.output.clone(), + } + } +} + +#[derive(Clone, Copy)] +pub(crate) struct Watch<'a> { + timeout: Duration, + retain: Option<&'a dyn Fn(PendingHook)>, +} + +impl<'a> Watch<'a> { + const PLAIN: Self = Self { + timeout: HOOK_TIMEOUT, + retain: None, + }; + + pub(crate) fn track_background(retain: &'a dyn Fn(PendingHook)) -> Self { + Self { + retain: Some(retain), + ..Self::PLAIN + } + } +} + pub(crate) fn run( repo: &Repository, runner: &Runner, @@ -245,6 +474,18 @@ pub(crate) fn run( args: &[&OsStr], env: &[(&str, &OsStr)], input: Option<&str>, +) -> AppResult<()> { + run_watched(repo, runner, name, args, env, input, Watch::PLAIN) +} + +fn run_watched( + repo: &Repository, + runner: &Runner, + name: &str, + args: &[&OsStr], + env: &[(&str, &OsStr)], + input: Option<&str>, + watch: Watch<'_>, ) -> AppResult<()> { let cwd = repo.workdir().unwrap_or_else(|| repo.path()); let input_file = match (runner, input) { @@ -274,18 +515,18 @@ pub(crate) fn run( command.arg("--").args(args); } configure(&mut command); - spawn_tree(command) + spawn_tree(command, watch.retain.is_some()) } Runner::Direct(hook) => { let mut command = crate::proc::hidden(hook); command.args(args); configure(&mut command); - match spawn_tree(command) { + match spawn_tree(command, watch.retain.is_some()) { Err(error) if is_exec_format_error(&error) => { let mut command = crate::proc::hidden(SHELL_PATH); command.arg(hook).args(args); configure(&mut command); - spawn_tree(command) + spawn_tree(command, watch.retain.is_some()) } spawned => spawned, } @@ -300,9 +541,21 @@ pub(crate) fn run( Runner::Direct(_) => input.unwrap_or(""), Runner::Git(_) => "", }; - let captured = capture_tree_child(child, piped, HOOK_TIMEOUT) - .map_err(|e| AppError::other(format!("The {name} hook could not run: {e}")))?; - if captured.status == 0 { + let mut background_output = None; + let run = run_tree(child, piped, watch.timeout, |processes| { + if let Some(retain) = watch.retain { + let output = Arc::new(OnceLock::new()); + background_output = Some(output.clone()); + retain(PendingHook { + name: name.to_string(), + timeout: watch.timeout, + output, + processes, + }); + } + }); + let captured = run.captured; + if captured.status == 0 && !run.timed_out && background_output.is_none() { return Ok(()); } let output = [captured.stdout.trim_end(), captured.stderr.trim_end()] @@ -310,10 +563,25 @@ pub(crate) fn run( .filter(|part| !part.is_empty()) .collect::>() .join("\n"); + let output = output_tail(&output, OUTPUT_CAP); + if let Some(background_output) = background_output { + let _ = background_output.set(output.clone()); + } + if captured.status == 0 && !run.timed_out { + return Ok(()); + } + if run.timed_out { + return Err(AppError::HookTimeout { + hook: name.to_string(), + seconds: watch.timeout.as_secs(), + exit_unconfirmed: run.exit_unconfirmed, + output, + }); + } Err(AppError::Hook { hook: name.to_string(), status: captured.status, - output: output_tail(&output, OUTPUT_CAP), + output, }) } @@ -522,6 +790,268 @@ fn rejected_as_non_fast_forward(repo: &Repository, r: &PushedRef) -> bool { } } +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum Rewrite { + Amend, + Rebase, +} + +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum PostHook { + Checkout { + previous: Oid, + new: Oid, + branch: bool, + }, + Merge, + Rewrite { + command: Rewrite, + pairs: Vec<(Oid, Oid)>, + }, +} + +impl PostHook { + pub(crate) fn merged(outcome: &super::types::OpOutcome) -> Option { + matches!(outcome.status.as_str(), "ok" | "fast_forward").then_some(PostHook::Merge) + } + + pub(crate) fn rebased(pairs: Vec<(Oid, Oid)>) -> Option { + let pairs: Vec<(Oid, Oid)> = pairs.into_iter().filter(|(old, new)| old != new).collect(); + (!pairs.is_empty()).then_some(PostHook::Rewrite { + command: Rewrite::Rebase, + pairs, + }) + } + + fn name(&self) -> &'static str { + match self { + PostHook::Checkout { .. } => POST_CHECKOUT, + PostHook::Merge => POST_MERGE, + PostHook::Rewrite { .. } => POST_REWRITE, + } + } + + fn args(&self) -> Vec { + match self { + PostHook::Checkout { + previous, + new, + branch, + } => vec![ + previous.to_string(), + new.to_string(), + if *branch { "1" } else { "0" }.to_string(), + ], + PostHook::Merge => vec!["0".to_string()], + PostHook::Rewrite { command, .. } => vec![match command { + Rewrite::Amend => "amend".to_string(), + Rewrite::Rebase => "rebase".to_string(), + }], + } + } + + fn input(&self) -> Option { + match self { + PostHook::Rewrite { pairs, .. } => Some( + pairs + .iter() + .map(|(old, new)| format!("{old} {new}\n")) + .collect(), + ), + _ => None, + } + } +} + +pub(crate) struct PostHooks { + run: bool, + skipped: bool, + pending: Vec, + warnings: Vec, +} + +impl PostHooks { + pub(crate) fn new(no_verify: bool) -> Self { + PostHooks { + run: !no_verify, + skipped: no_verify, + pending: Vec::new(), + warnings: Vec::new(), + } + } + + pub(crate) fn off() -> Self { + PostHooks { + run: false, + skipped: false, + pending: Vec::new(), + warnings: Vec::new(), + } + } + + pub(crate) fn skipped(&self) -> bool { + self.skipped + } + + pub(crate) fn skip(&mut self) { + self.run = false; + self.skipped = true; + self.pending.clear(); + } + + pub(crate) fn run_now(&mut self, repo: &Repository, hook: PostHook) { + if self.run { + let warnings = run_post(repo, &[hook], false); + self.warnings.extend(warnings); + } + } + + pub(crate) fn later(&mut self, hook: PostHook) { + if self.run { + self.pending.push(hook); + } + } + + pub(crate) fn abandon(self) -> Vec { + self.warnings + } + + pub(crate) fn finish(mut self, repo: Option<&Repository>) -> Vec { + if let Some(repo) = repo.filter(|_| !self.pending.is_empty()) { + let warnings = run_post(repo, &self.pending, false); + self.warnings.extend(warnings); + } + self.warnings + } +} + +pub(crate) fn run_post(repo: &Repository, hooks: &[PostHook], no_verify: bool) -> Vec { + run_post_watched(repo, hooks, no_verify, Watch::PLAIN) +} + +type PostHookObserver = Box; + +thread_local! { + static POST_HOOK_OBSERVER: RefCell> = const { RefCell::new(None) }; +} + +struct ObserverScope(Option); + +impl Drop for ObserverScope { + fn drop(&mut self) { + POST_HOOK_OBSERVER.with(|slot| slot.replace(self.0.take())); + } +} + +pub(crate) fn observe_post_hooks( + observer: impl Fn(&Path, &str, bool) + 'static, + action: impl FnOnce() -> T, +) -> T { + let _scope = + ObserverScope(POST_HOOK_OBSERVER.with(|slot| slot.replace(Some(Box::new(observer))))); + action() +} + +struct PostHookActivity<'a> { + workdir: &'a Path, + name: &'a str, +} + +impl PostHookActivity<'_> { + fn notify(&self, running: bool) { + POST_HOOK_OBSERVER.with(|slot| { + if let Some(observer) = slot.borrow().as_ref() { + observer(self.workdir, self.name, running); + } + }); + } +} + +impl Drop for PostHookActivity<'_> { + fn drop(&mut self) { + self.notify(false); + } +} + +pub(crate) fn run_post_watched( + repo: &Repository, + hooks: &[PostHook], + no_verify: bool, + watch: Watch<'_>, +) -> Vec { + let mut warnings: Vec = Vec::new(); + let Some(workdir) = repo.workdir() else { + return warnings; + }; + if no_verify { + return warnings; + } + for hook in hooks { + let name = hook.name(); + let found = match present(repo, name) { + Ok(found) => found, + Err(error) => { + warnings.push(post_warning( + name, + None, + false, + error.to_string(), + String::new(), + )); + continue; + } + }; + if !found { + continue; + } + let input = hook.input(); + let runner = match runner(repo, workdir, name, input.is_some()) { + Ok(runner) => runner, + Err(reason) => { + if !warnings.iter().any(|w| w.message == reason) { + warnings.push(post_warning(name, None, false, reason, String::new())); + } + continue; + } + }; + let args = hook.args(); + let args: Vec<&OsStr> = args.iter().map(OsStr::new).collect(); + let activity = PostHookActivity { workdir, name }; + activity.notify(true); + if let Err(error) = run_watched(repo, &runner, name, &args, &[], input.as_deref(), watch) { + let (status, timed_out, output) = match &error { + AppError::Hook { status, output, .. } => (Some(*status), false, output.clone()), + AppError::HookTimeout { output, .. } => (None, true, output.clone()), + _ => (None, false, String::new()), + }; + warnings.push(post_warning( + name, + status, + timed_out, + error.to_string(), + output, + )); + } + } + warnings +} + +fn post_warning( + hook: &str, + status: Option, + timed_out: bool, + message: String, + output: String, +) -> HookWarning { + HookWarning { + hook: hook.to_string(), + status, + timed_out, + message, + output, + } +} + fn commit_env(repo: &Repository, author: &git2::Signature<'_>) -> Vec<(&'static str, OsString)> { vec![ ("GIT_INDEX_FILE", repo.path().join("index").into_os_string()), @@ -591,6 +1121,246 @@ mod tests { assert_eq!(git_date(git2::Time::new(0, 0)), "@0 +0000"); } + #[cfg(unix)] + #[test] + fn a_post_hook_that_runs_past_its_time_is_a_timeout_warning_with_its_output() { + use std::os::unix::fs::PermissionsExt; + if !runner_available() { + return; + } + let (dir, repo) = temp_repo("timeout"); + let hook = dir.join(".git").join("hooks").join("post-merge"); + std::fs::create_dir_all(hook.parent().unwrap()).unwrap(); + std::fs::write(&hook, "#!/bin/sh\necho installing\nsleep 30\n").unwrap(); + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + let watch = Watch { + timeout: Duration::from_secs(3), + ..Watch::PLAIN + }; + let warnings = run_post_watched(&repo, &[PostHook::Merge], false, watch); + let _ = std::fs::remove_dir_all(dir); + assert_eq!(warnings.len(), 1); + let warning = &warnings[0]; + assert!(warning.timed_out); + assert_eq!(warning.status, None); + assert_eq!(warning.output, "installing"); + assert_eq!( + warning.message, + "The post-merge hook did not finish within 3 seconds. AngKorGit could not confirm that all hook processes exited." + ); + } + + #[cfg(any(target_os = "linux", windows))] + #[test] + fn group_cancel_enforces_an_earlier_hooks_deadline_while_a_later_pull_is_active() { + use super::super::group_update::GroupUpdateControl; + use super::super::types::GroupUpdateResult; + use std::cell::Cell; + use std::sync::mpsc; + use std::time::Instant; + + if !runner_available() { + return; + } + let dir = tempfile::tempdir().unwrap(); + let repo = Repository::init(dir.path()).unwrap(); + let hooks = repo.path().join("hooks"); + std::fs::create_dir_all(&hooks).unwrap(); + let hook = hooks.join(POST_MERGE); + let marker = repo.path().join("late-write"); + std::fs::write( + &hook, + "#!/bin/sh\necho installing\n(sleep 4; echo late > .git/late-write) >/dev/null 2>&1 &\n", + ) + .unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + + let control = &GroupUpdateControl::default(); + let can_stop = Cell::new(None); + let retain = |hook: PendingHook| { + can_stop.set(Some(hook.processes.can_stop())); + control.record_background_hook("earlier", hook); + }; + let watch = Watch { + timeout: Duration::from_secs(2), + retain: Some(&retain), + }; + control + .with_active_result("earlier", || { + let warnings = run_post_watched(&repo, &[PostHook::Merge], false, watch); + assert!(warnings.is_empty(), "{warnings:?}"); + Ok(GroupUpdateResult::default()) + }) + .unwrap(); + if cfg!(target_os = "linux") && can_stop.get() == Some(false) { + eprintln!("skipping: process-group signals are unavailable"); + return; + } + assert_eq!(can_stop.get(), Some(true)); + + let receipts = std::thread::scope(|scope| { + let (active, entered) = mpsc::channel(); + let (release, held) = mpsc::channel(); + let later = scope.spawn(move || { + control.with_active_result("later", || { + active.send(()).unwrap(); + held.recv_timeout(Duration::from_secs(8)).unwrap(); + Ok(GroupUpdateResult::default()) + }) + }); + entered.recv_timeout(Duration::from_secs(3)).unwrap(); + let cancel = scope.spawn(|| control.cancel_results()); + let until = Instant::now() + Duration::from_secs(5); + while !marker.exists() && Instant::now() < until { + std::thread::sleep(Duration::from_millis(25)); + } + release.send(()).unwrap(); + later.join().unwrap().unwrap(); + cancel.join().unwrap().unwrap() + }); + + assert!(!marker.exists(), "the earlier hook wrote past its deadline"); + let earlier = receipts + .iter() + .find(|receipt| receipt.path == "earlier") + .unwrap(); + assert_eq!(earlier.result.hook_warnings.len(), 1); + let warning = &earlier.result.hook_warnings[0]; + assert!(warning.timed_out); + assert_eq!(warning.output, "installing"); + assert!(receipts.iter().any(|receipt| receipt.path == "later")); + } + + #[cfg(any(target_os = "linux", windows))] + #[test] + fn group_cancel_enforces_the_hook_deadline_during_output_drain() { + use super::super::group_update::GroupUpdateControl; + use super::super::types::GroupUpdateResult; + use std::time::Instant; + + if !runner_available() { + return; + } + #[cfg(target_os = "linux")] + { + let mut command = crate::proc::hidden("/bin/sh"); + command.args(["-c", "sleep 1 >/dev/null 2>&1 &"]); + let child = spawn_tree(command, true).unwrap(); + let mut can_stop = false; + let run = run_tree(child, "", Duration::from_secs(2), |processes| { + can_stop = processes.can_stop(); + }); + assert!(!run.timed_out); + if !can_stop { + eprintln!("skipping: process-group signals are unavailable"); + return; + } + } + let dir = tempfile::tempdir().unwrap(); + let repo = Repository::init(dir.path()).unwrap(); + let hooks = repo.path().join("hooks"); + std::fs::create_dir_all(&hooks).unwrap(); + let hook = hooks.join(POST_MERGE); + let started = repo.path().join("foreground-started"); + let late_write = repo.path().join("late-write"); + std::fs::write(&hook, "#!/bin/sh\necho foreground\n: > .git/foreground-started\nsleep 2.4\n(sleep 0.15; echo draining; sleep 0.65; echo late > .git/late-write) &\n").unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + + let control = &GroupUpdateControl::default(); + let receipts = std::thread::scope(|scope| { + let active = scope.spawn(move || { + let retain = |hook| control.record_background_hook("repo", hook); + let watch = Watch { + timeout: Duration::from_secs(3), + retain: Some(&retain), + }; + control.with_active_result("repo", || { + let warnings = run_post_watched(&repo, &[PostHook::Merge], false, watch); + assert!(warnings.is_empty(), "{warnings:?}"); + Ok(GroupUpdateResult::default()) + }) + }); + let until = Instant::now() + Duration::from_secs(5); + while !started.exists() && Instant::now() < until { + std::thread::sleep(Duration::from_millis(10)); + } + assert!(started.exists()); + let receipts = control.cancel_results().unwrap(); + active.join().unwrap().unwrap(); + receipts + }); + assert!( + !late_write.exists(), + "background work wrote past the deadline during output drain" + ); + assert_eq!(receipts.len(), 1); + let warnings = &receipts[0].result.hook_warnings; + assert_eq!(warnings.len(), 1); + assert!(warnings[0].timed_out); + assert_eq!( + warnings[0].output.lines().collect::>(), + ["foreground", "draining"] + ); + } + + #[test] + fn post_hooks_get_the_args_and_stdin_git_passes() { + let a = Oid::from_str("1111111111111111111111111111111111111111").unwrap(); + let b = Oid::from_str("2222222222222222222222222222222222222222").unwrap(); + let switched = PostHook::Checkout { + previous: a, + new: b, + branch: true, + }; + assert_eq!( + switched.args(), + vec![a.to_string(), b.to_string(), "1".into()] + ); + assert_eq!(switched.input(), None); + let restored = PostHook::Checkout { + previous: a, + new: a, + branch: false, + }; + assert_eq!(restored.args()[2], "0"); + assert_eq!(PostHook::Merge.args(), vec!["0".to_string()]); + let amended = PostHook::Rewrite { + command: Rewrite::Amend, + pairs: vec![(a, a)], + }; + assert_eq!(amended.args(), vec!["amend".to_string()]); + assert_eq!(amended.input(), Some(format!("{a} {a}\n"))); + let Some(rebased) = PostHook::rebased(vec![(a, b), (b, b), (b, a)]) else { + panic!("a rebase that rewrote commits must run post-rewrite"); + }; + assert_eq!(rebased.args(), vec!["rebase".to_string()]); + assert_eq!(rebased.input(), Some(format!("{a} {b}\n{b} {a}\n"))); + assert_eq!(PostHook::rebased(vec![(a, a)]), None); + } + + #[test] + fn post_merge_follows_only_a_merge_that_moved_head() { + let outcome = |status: &str| super::super::types::OpOutcome { + status: status.into(), + message: String::new(), + }; + assert_eq!(PostHook::merged(&outcome("ok")), Some(PostHook::Merge)); + assert_eq!( + PostHook::merged(&outcome("fast_forward")), + Some(PostHook::Merge) + ); + assert_eq!(PostHook::merged(&outcome("up_to_date")), None); + assert_eq!(PostHook::merged(&outcome("conflicts")), None); + } + #[test] fn edited_messages_get_git_whitespace_cleanup() { assert_eq!( diff --git a/apps/desktop/src-tauri/src/core/mod.rs b/apps/desktop/src-tauri/src/core/mod.rs index 9a6b4522..11143996 100644 --- a/apps/desktop/src-tauri/src/core/mod.rs +++ b/apps/desktop/src-tauri/src/core/mod.rs @@ -10,6 +10,7 @@ pub mod group_update; pub mod history; pub mod hooks; pub mod misc; +pub mod post_hooks; pub mod pull_preview; pub mod remote; pub mod repo; diff --git a/apps/desktop/src-tauri/src/core/post_hooks.rs b/apps/desktop/src-tauri/src/core/post_hooks.rs new file mode 100644 index 00000000..21fc21c6 --- /dev/null +++ b/apps/desktop/src-tauri/src/core/post_hooks.rs @@ -0,0 +1,347 @@ +use std::path::Path; + +use git2::Oid; + +use super::hooks::{run_post, PostHook, PostHooks}; +use super::types::{ + CommitOutcome, DiscardBatch, DiscardFailure, HookWarning, OpOutcome, RebaseTodoEntry, + WorktreeAddRequest, +}; +use super::{branch, commit, misc, remote, stage, submodule, worktree}; +use crate::error::AppResult; + +pub struct Hooked { + pub value: T, + pub warnings: Vec, +} + +impl Hooked { + fn plain(value: T) -> Self { + Hooked { + value, + warnings: Vec::new(), + } + } +} + +impl Hooked> { + pub fn into_result(self) -> AppResult> { + let warnings = self.warnings; + self.value.map(|value| Hooked { value, warnings }) + } +} + +fn ran(path: &str, value: T, hooks: &[PostHook], no_verify: bool) -> Hooked { + let warnings = match super::repo::open(path) { + Ok(repo) if !hooks.is_empty() => run_post(&repo, hooks, no_verify), + _ => Vec::new(), + }; + Hooked { value, warnings } +} + +fn finished(path: &str, value: T, hooks: PostHooks) -> Hooked { + let repo = super::repo::open(path).ok(); + Hooked { + value, + warnings: hooks.finish(repo.as_ref()), + } +} + +fn finished_or_failed( + path: &str, + result: AppResult, + hooks: PostHooks, +) -> Hooked> { + match result { + Ok(value) => { + let done = finished(path, value, hooks); + Hooked { + value: Ok(done.value), + warnings: done.warnings, + } + } + Err(error) => Hooked { + value: Err(error), + warnings: hooks.abandon(), + }, + } +} + +fn head_oid(path: &str) -> Oid { + super::repo::open(path) + .ok() + .and_then(|repo| repo.head().ok().and_then(|head| head.target())) + .unwrap_or_else(Oid::zero) +} + +fn switched( + path: &str, + no_verify: bool, + op: impl FnOnce() -> AppResult, +) -> AppResult> { + let previous = head_oid(path); + let value = submodule::synced(path, op)?; + let checkout = PostHook::Checkout { + previous, + new: head_oid(path), + branch: true, + }; + Ok(ran(path, value, &[checkout], no_verify)) +} + +fn restored(path: &str, value: T, no_verify: bool) -> Hooked { + let head = head_oid(path); + let checkout = PostHook::Checkout { + previous: head, + new: head, + branch: false, + }; + ran(path, value, &[checkout], no_verify) +} + +fn checked_out(path: &str, value: T, no_verify: bool) -> Hooked { + let head = head_oid(path); + if head.is_zero() { + return Hooked::plain(value); + } + let checkout = PostHook::Checkout { + previous: Oid::zero(), + new: head, + branch: true, + }; + ran(path, value, &[checkout], no_verify) +} + +pub fn checkout_branch(path: &str, name: &str, no_verify: bool) -> AppResult> { + switched(path, no_verify, || branch::checkout_branch(path, name)) +} + +pub fn checkout_detached(path: &str, rev: &str, no_verify: bool) -> AppResult> { + switched(path, no_verify, || branch::checkout_detached(path, rev)) +} + +pub fn branch_create( + path: &str, + name: &str, + from_oid: Option<&str>, + checkout: bool, + no_verify: bool, +) -> AppResult> { + let create = || branch::create(path, name, from_oid, checkout); + if checkout { + switched(path, no_verify, create) + } else { + submodule::synced(path, create).map(Hooked::plain) + } +} + +pub fn checkout_remote_ref( + path: &str, + remote_name: &str, + source_ref: &str, + local_branch: &str, + track: bool, + no_verify: bool, +) -> AppResult> { + switched(path, no_verify, || { + remote::checkout_remote_ref(path, remote_name, source_ref, local_branch, track) + }) +} + +pub fn merge(path: &str, name: &str, no_ff: bool, no_verify: bool) -> AppResult> { + let outcome = submodule::synced(path, || branch::merge(path, name, no_ff))?; + let hooks: Vec = PostHook::merged(&outcome).into_iter().collect(); + Ok(ran(path, outcome, &hooks, no_verify)) +} + +pub fn pull( + path: &str, + remote_name: &str, + mode: Option<&str>, + no_verify: bool, +) -> Hooked> { + let mut hooks = PostHooks::new(no_verify); + let outcome = submodule::synced(path, || { + remote::pull_with_hooks(path, remote_name, mode, &mut hooks) + }); + finished_or_failed(path, outcome, hooks) +} + +pub fn pull_branch(path: &str, branch_name: &str, no_verify: bool) -> AppResult> { + let mut hooks = PostHooks::new(no_verify); + let outcome = remote::pull_branch_with_hooks(path, branch_name, &mut hooks)?; + Ok(finished(path, outcome, hooks)) +} + +pub fn rebase(path: &str, upstream: &str, no_verify: bool) -> Hooked> { + let mut hooks = PostHooks::new(no_verify); + let outcome = submodule::synced(path, || { + branch::rebase_with_hooks(path, upstream, &mut hooks) + }); + finished_or_failed(path, outcome, hooks) +} + +pub fn rebase_continue(path: &str, no_verify: bool) -> AppResult> { + let mut hooks = PostHooks::new(no_verify); + let outcome = submodule::synced(path, || { + branch::rebase_continue_with_hooks(path, &mut hooks) + })?; + Ok(finished(path, outcome, hooks)) +} + +pub fn rebase_interactive( + path: &str, + base: &str, + todo: &[RebaseTodoEntry], + no_verify: bool, +) -> AppResult> { + let mut hooks = PostHooks::new(no_verify); + let head = submodule::synced(path, || { + branch::rebase_interactive_with_hooks(path, base, todo, &mut hooks) + })?; + Ok(finished(path, head, hooks)) +} + +pub fn amend( + path: &str, + message: Option<&str>, + no_verify: bool, +) -> AppResult> { + let mut hooks = PostHooks::new(no_verify); + let outcome = commit::amend_with_hooks(path, message, no_verify, &mut hooks)?; + Ok(finished(path, outcome, hooks)) +} + +pub fn reword(path: &str, oid: &str, message: &str, no_verify: bool) -> AppResult> { + let mut hooks = PostHooks::new(no_verify); + let reworded = commit::reword_with_hooks(path, oid, message, &mut hooks)?; + Ok(finished(path, reworded, hooks)) +} + +fn restores_from_index(repo: &git2::Repository, file: &str) -> AppResult { + let tracked = repo.index()?.get_path(Path::new(file), 0).is_some(); + Ok(tracked && submodule::drifted(repo, file).is_none()) +} + +pub fn discard_file(path: &str, file: &str, no_verify: bool) -> AppResult> { + let restores = restores_from_index(&super::repo::open(path)?, file)?; + let clean = stage::discard_file(path, file)?; + Ok(if restores { + restored(path, clean, no_verify) + } else { + Hooked::plain(clean) + }) +} + +pub fn discard_files( + path: &str, + files: &[String], + staged: bool, + no_verify: bool, +) -> AppResult> { + 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 { + Ok(clean) => { + restored_any |= restores; + if !clean { + batch.leftovers.push(file.clone()); + } + } + Err(error) => batch.failed.push(DiscardFailure { + path: file.clone(), + message: error.to_string(), + }), + } + } + Ok(if restored_any { + restored(path, batch, no_verify) + } else { + Hooked::plain(batch) + }) +} + +pub fn discard_all(path: &str, no_verify: bool) -> AppResult>> { + let restores = has_status( + path, + git2::Status::WT_MODIFIED + | git2::Status::WT_DELETED + | git2::Status::WT_TYPECHANGE + | git2::Status::WT_RENAMED, + )?; + let leftovers = stage::discard_all(path)?; + Ok(if restores { + restored(path, leftovers, no_verify) + } else { + Hooked::plain(leftovers) + }) +} + +pub fn discard_staged_file(path: &str, file: &str, no_verify: bool) -> AppResult> { + let clean = stage::discard_staged_file(path, file)?; + Ok(restored(path, clean, no_verify)) +} + +pub fn discard_staged_all(path: &str, no_verify: bool) -> AppResult> { + let (batch, restored_any) = stage::discard_staged_all_reporting(path)?; + Ok(if restored_any { + restored(path, batch, no_verify) + } else { + Hooked::plain(batch) + }) +} + +fn has_status(path: &str, wanted: git2::Status) -> AppResult { + let repo = super::repo::open(path)?; + let mut opts = git2::StatusOptions::new(); + opts.include_untracked(false); + let statuses = repo.statuses(Some(&mut opts))?; + let found = statuses + .iter() + .any(|entry| entry.status().intersects(wanted)); + Ok(found) +} + +pub fn stash_restore_files( + path: &str, + index: usize, + paths: &[String], + no_verify: bool, +) -> AppResult>> { + let restored_paths = misc::stash_restore_files(path, index, paths)?; + Ok(if restored_paths.is_empty() { + Hooked::plain(restored_paths) + } else { + restored(path, restored_paths, no_verify) + }) +} + +pub fn clone( + url: &str, + into: &str, + branch: Option<&str>, + on_progress: impl Fn(u32) + Send, + no_verify: bool, +) -> AppResult> { + let root = remote::clone(url, into, branch, on_progress)?; + let path = root.clone(); + Ok(checked_out(&path, root, no_verify)) +} + +pub fn worktree_add( + path: &str, + request: &WorktreeAddRequest, + no_verify: bool, +) -> AppResult> { + let created = worktree::add(path, request)?; + let worktree_path = created.clone(); + Ok(checked_out(&worktree_path, created, no_verify)) +} diff --git a/apps/desktop/src-tauri/src/core/remote.rs b/apps/desktop/src-tauri/src/core/remote.rs index 8e0b1064..155cfebc 100644 --- a/apps/desktop/src-tauri/src/core/remote.rs +++ b/apps/desktop/src-tauri/src/core/remote.rs @@ -12,7 +12,7 @@ use git2::{ use crate::error::{AppError, AppResult}; use super::group_update::{FetchProgress, GroupUpdateControl}; -use super::hooks::{pre_push_input, PrePush, PushedRef}; +use super::hooks::{pre_push_input, PostHook, PostHooks, PrePush, PushedRef}; use super::types::{GeneratedKey, GroupUpdateResult, OpOutcome, RefMovement, RemoteInfo}; static CREDENTIAL_PREFS: OnceLock> = OnceLock::new(); @@ -64,20 +64,19 @@ fn prefs_snapshot() -> CredentialPrefs { .unwrap_or_default() } -fn home_dir() -> Option { +pub(crate) fn home_dir() -> Option { std::env::var_os("HOME") .or_else(|| std::env::var_os("USERPROFILE")) .map(PathBuf::from) } pub(crate) fn expand_home(path: &str, home: Option<&Path>) -> PathBuf { - let trimmed = path.trim(); - if let Some(rest) = trimmed.strip_prefix("~/") { + if let Some(rest) = path.strip_prefix("~/") { if let Some(home) = home { - return home.join(rest); + return home.join(rest.trim_start_matches('/')); } } - PathBuf::from(trimmed) + PathBuf::from(path) } const MAX_SSH_KEYS: usize = 5; @@ -126,7 +125,7 @@ fn discover_ssh_keys(home: Option<&Path>) -> Vec { } fn resolved_key_path(path: &str) -> AppResult { - let resolved = expand_home(path, home_dir().as_deref()); + let resolved = expand_home(path.trim(), home_dir().as_deref()); if resolved.as_os_str().is_empty() { return Err(AppError::other("choose a path for the key")); } @@ -479,6 +478,7 @@ pub fn group_update_controlled( status: "cancelled".into(), message: "Cancelled before completing the repository update".into(), changes: Vec::new(), + ..Default::default() }), Err(error) => Err(error), } @@ -495,6 +495,7 @@ fn group_update_inner( status: "skipped".into(), message: "Repository folder no longer exists".into(), changes: Vec::new(), + ..Default::default() }); } let repo = super::repo::open(path)?; @@ -502,6 +503,7 @@ fn group_update_inner( status: status.into(), message, changes: Vec::new(), + ..Default::default() }; if !pull { let names: Vec = repo.remotes()?.iter().flatten().map(String::from).collect(); @@ -687,6 +689,7 @@ fn group_update_inner( )); } let checkout = control.with_active_result(path, || { + super::branch::set_orig_head(&repo, old)?; let mut checkout = CheckoutBuilder::new(); checkout.safe(); if let Err(error) = repo.checkout_tree(target.as_object(), Some(&mut checkout)) { @@ -710,6 +713,14 @@ fn group_update_inner( )) })?; super::submodule::follow_recorded(path, &submodules, false); + let hook_warnings = super::hooks::run_post_watched( + &repo, + &[PostHook::Merge], + control.skips_hooks(), + super::hooks::Watch::track_background(&|hook| { + control.record_background_hook(path, hook); + }), + ); Ok(GroupUpdateResult { status: "ok".into(), message: format!("Fast-forwarded {branch_name} by {behind} commit(s)"), @@ -719,6 +730,7 @@ fn group_update_inner( new_oid: Some(new.to_string()), commits: Some(behind), }], + hook_warnings, }) }); checkout @@ -877,6 +889,7 @@ pub(super) fn fetch_progress_summary( status: status.into(), message, changes, + ..Default::default() } } @@ -924,6 +937,15 @@ fn fetched_refs(repo: &Repository) -> AppResult> { } pub fn pull(path: &str, remote_name: &str, mode: Option<&str>) -> AppResult { + pull_with_hooks(path, remote_name, mode, &mut PostHooks::off()) +} + +pub(crate) fn pull_with_hooks( + path: &str, + remote_name: &str, + mode: Option<&str>, + hooks: &mut PostHooks, +) -> AppResult { fetch(path, remote_name, false, false)?; let repo = super::repo::open(path)?; @@ -955,9 +977,13 @@ pub fn pull(path: &str, remote_name: &str, mode: Option<&str>) -> AppResult 0 && behind > 0 { - return super::branch::rebase(path, &upstream_name); + return super::branch::rebase_with_hooks(path, &upstream_name, hooks); } - super::branch::merge(path, &upstream_name, false) + let outcome = super::branch::merge(path, &upstream_name, false)?; + if let Some(hook) = PostHook::merged(&outcome) { + hooks.later(hook); + } + Ok(outcome) } pub(super) fn pull_source( @@ -1311,7 +1337,11 @@ fn tracking_ref_matches(repo: &Repository, remote_name: &str, branch_name: &str) local.is_some() && local == tip(format!("refs/remotes/{remote_name}/{branch_name}")) } -pub fn pull_branch(path: &str, branch_name: &str) -> AppResult { +pub(crate) fn pull_branch_with_hooks( + path: &str, + branch_name: &str, + hooks: &mut PostHooks, +) -> AppResult { let (upstream_name, remote_name) = { let repo = super::repo::open(path)?; let branch = repo.find_branch(branch_name, git2::BranchType::Local)?; @@ -1340,7 +1370,11 @@ pub fn pull_branch(path: &str, branch_name: &str) -> AppResult { .as_deref() == Some(branch_name); if is_head { - return super::branch::merge(path, &upstream_name, false); + let outcome = super::branch::merge(path, &upstream_name, false)?; + if let Some(hook) = PostHook::merged(&outcome) { + hooks.later(hook); + } + return Ok(outcome); } let branch = repo.find_branch(branch_name, git2::BranchType::Local)?; @@ -1628,6 +1662,14 @@ mod tests { ); } + #[test] + fn expands_a_leading_tilde_with_repeated_slashes() { + assert_eq!( + expand_home("~//src/repo/project.gitconfig", Some(&home())), + home().join("src/repo/project.gitconfig") + ); + } + #[test] fn leaves_absolute_paths_alone() { assert_eq!( diff --git a/apps/desktop/src-tauri/src/core/stage.rs b/apps/desktop/src-tauri/src/core/stage.rs index 519caf0f..7ee8b31b 100644 --- a/apps/desktop/src-tauri/src/core/stage.rs +++ b/apps/desktop/src-tauri/src/core/stage.rs @@ -2,6 +2,7 @@ use std::path::Path; use git2::{ApplyLocation, DiffFormat, DiffOptions, Repository}; +use super::types::{DiscardBatch, DiscardFailure}; use crate::error::{AppError, AppResult}; pub fn stage_file(path: &str, file: &str) -> AppResult<()> { @@ -157,6 +158,14 @@ pub fn discard_staged_file(path: &str, file: &str) -> AppResult { } pub fn discard_staged_all(path: &str) -> AppResult> { + let (batch, _) = discard_staged_all_reporting(path)?; + if let Some(failure) = batch.failed.first() { + return Err(AppError::other(failure.message.clone())); + } + Ok(batch.leftovers) +} + +pub(crate) fn discard_staged_all_reporting(path: &str) -> AppResult<(DiscardBatch, bool)> { let repo = super::repo::open(path)?; let mut opts = git2::StatusOptions::new(); opts.include_untracked(false); @@ -187,14 +196,24 @@ pub fn discard_staged_all(path: &str) -> AppResult> { }) .collect(); drop(statuses); + let mut batch = DiscardBatch::default(); + let mut restored_any = false; for file in staged.iter().chain(renamed_targets.iter()) { - discard_to_head(&repo, file)?; + match discard_to_head(&repo, file) { + Ok(()) => restored_any = true, + Err(error) => batch.failed.push(DiscardFailure { + path: file.clone(), + message: error.to_string(), + }), + } } let remaining = touched_paths(&repo)?; - Ok(staged + batch.leftovers = staged .into_iter() - .filter(|p| remaining.contains(p)) - .collect()) + .chain(renamed_targets) + .filter(|p| remaining.contains(p) && !batch.failed.iter().any(|failure| &failure.path == p)) + .collect(); + Ok((batch, restored_any)) } fn discard_to_head(repo: &git2::Repository, file: &str) -> AppResult<()> { diff --git a/apps/desktop/src-tauri/src/core/types.rs b/apps/desktop/src-tauri/src/core/types.rs index 9ffcddb1..12c89857 100644 --- a/apps/desktop/src-tauri/src/core/types.rs +++ b/apps/desktop/src-tauri/src/core/types.rs @@ -307,12 +307,53 @@ pub struct GeneratedKey { pub public_key: String, } -#[derive(Serialize, Debug, Clone)] +#[derive(Serialize, Debug, Clone, Default)] #[serde(rename_all = "camelCase")] pub struct GroupUpdateResult { pub status: String, pub message: String, pub changes: Vec, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub hook_warnings: Vec, +} + +#[derive(Serialize, Debug, Default)] +#[serde(rename_all = "camelCase")] +pub struct DiscardBatch { + pub leftovers: Vec, + pub failed: Vec, +} + +#[derive(Serialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct DiscardFailure { + pub path: String, + pub message: String, +} + +#[derive(Serialize, Debug, Default, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct RepoHooks { + pub found: Vec, + pub in_worktree: bool, +} + +#[derive(Serialize, Debug, Clone, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct HookWarning { + pub hook: String, + pub status: Option, + pub timed_out: bool, + pub message: String, + pub output: String, +} + +#[derive(Serialize, Clone)] +#[serde(rename_all = "camelCase")] +pub struct HookWarningEvent { + pub repo_path: String, + #[serde(flatten)] + pub warning: HookWarning, } #[derive(Serialize, Debug, Clone)] diff --git a/apps/desktop/src-tauri/src/error.rs b/apps/desktop/src-tauri/src/error.rs index 5373c286..4d75eadc 100644 --- a/apps/desktop/src-tauri/src/error.rs +++ b/apps/desktop/src-tauri/src/error.rs @@ -10,6 +10,8 @@ pub enum AppError { Other(String), #[error("no repository is open")] NoRepository, + #[error("{} is still running in {repo}", hook.as_deref().unwrap_or("Another operation"))] + Busy { hook: Option, repo: String }, #[error("operation would conflict: {0}")] Conflict(String), #[error("The {hook} hook failed (exit code {status}).")] @@ -18,6 +20,20 @@ pub enum AppError { status: i32, output: String, }, + #[error( + "The {hook} hook did not finish within {seconds} seconds{}", + if *.exit_unconfirmed { + ". AngKorGit could not confirm that all hook processes exited." + } else { + " and was stopped." + } + )] + HookTimeout { + hook: String, + seconds: u64, + exit_unconfirmed: bool, + output: String, + }, } const HTTP_STATUS_MARKER: &str = "unexpected http status code: "; @@ -94,14 +110,20 @@ impl AppError { }, AppError::Other(_) => "other", AppError::NoRepository => "no_repository", + AppError::Busy { .. } => "operation_running", AppError::Conflict(_) => "conflict", AppError::Hook { .. } => "hook_failed", + AppError::HookTimeout { .. } => "hook_timeout", } } fn detail(&self) -> Option { match self { - AppError::Hook { output, .. } if !output.is_empty() => Some(output.clone()), + AppError::Hook { output, .. } | AppError::HookTimeout { output, .. } + if !output.is_empty() => + { + Some(output.clone()) + } _ => None, } } @@ -193,6 +215,26 @@ mod tests { assert_eq!(denied.code(), "io"); } + #[test] + fn busy_operations_name_the_running_hook_and_repository() { + for (hook, message) in [ + ( + Some("post-checkout".to_string()), + "post-checkout is still running in angkorgit", + ), + (None, "Another operation is still running in angkorgit"), + ] { + let error = AppError::Busy { + hook, + repo: "angkorgit".into(), + }; + let payload = serde_json::to_value(error).unwrap(); + assert_eq!(payload["code"], "operation_running"); + assert_eq!(payload["message"], message); + assert!(payload.get("detail").is_none()); + } + } + #[test] fn hook_failures_carry_the_hook_output_as_detail() { let error = AppError::Hook { @@ -211,6 +253,23 @@ mod tests { assert!(plain.get("detail").is_none()); } + #[test] + fn a_hook_timeout_reports_an_unconfirmed_exit_and_keeps_its_output() { + let error = AppError::HookTimeout { + hook: "post-merge".into(), + seconds: 600, + exit_unconfirmed: true, + output: "installing".into(), + }; + let payload = serde_json::to_value(&error).unwrap(); + assert_eq!(payload["code"], "hook_timeout"); + assert_eq!( + payload["message"], + "The post-merge hook did not finish within 600 seconds. AngKorGit could not confirm that all hook processes exited." + ); + assert_eq!(payload["detail"], "installing"); + } + #[test] fn unauthorized_errors_hint_at_token_expiry() { let error = git_error("unexpected http status code: 401"); diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs index a2f9e9d9..39f310b9 100644 --- a/apps/desktop/src-tauri/src/lib.rs +++ b/apps/desktop/src-tauri/src/lib.rs @@ -16,11 +16,13 @@ mod terminal; mod watcher; pub mod test_api { + #[cfg(unix)] + pub use crate::ai_cli::background_process_signals_available; pub use crate::core::blame::blame_file; pub use crate::core::branch::{ can_fast_forward, checkout_branch, checkout_detached, cherry_pick, cherry_pick_many, - create as branch_create, list as branches, merge, rebase, rebase_commits, rebase_continue, - rebase_interactive, reset, + create as branch_create, list as branches, merge, rebase, rebase_abort, rebase_commits, + rebase_continue, rebase_interactive, reset, }; pub use crate::core::commit::{amend, commit, merge_message, revert, reword}; pub use crate::core::conflict::{ @@ -44,6 +46,7 @@ pub mod test_api { stash_create, stash_files, stash_list, stash_pop, stash_restore_files, tag_create, tag_delete, tag_list, }; + pub use crate::core::post_hooks; pub use crate::core::pull_preview::pull_preview; pub use crate::core::remote::{ add as remote_add, checkout_remote_ref, fetch, group_update, group_update_controlled, @@ -147,6 +150,7 @@ pub fn run() { commands::stage_all, commands::unstage_all, commands::discard_file, + commands::discard_files, commands::discard_all, commands::discard_staged_file, commands::discard_staged_all, diff --git a/apps/desktop/src-tauri/src/proc.rs b/apps/desktop/src-tauri/src/proc.rs index b010ac15..abe91b1f 100644 --- a/apps/desktop/src-tauri/src/proc.rs +++ b/apps/desktop/src-tauri/src/proc.rs @@ -2,7 +2,7 @@ use std::ffi::OsStr; use std::process::Command; #[cfg(windows)] -const CREATE_NO_WINDOW: u32 = 0x0800_0000; +pub(crate) const CREATE_NO_WINDOW: u32 = 0x0800_0000; #[cfg(windows)] pub fn hidden>(program: S) -> Command { diff --git a/apps/desktop/src-tauri/tests/clone_hooks.rs b/apps/desktop/src-tauri/tests/clone_hooks.rs new file mode 100644 index 00000000..ad7fe315 --- /dev/null +++ b/apps/desktop/src-tauri/tests/clone_hooks.rs @@ -0,0 +1,115 @@ +use std::path::Path; + +use angkorgit_lib::test_api as core; + +fn shell_path(path: &Path) -> String { + path.to_string_lossy().replace('\\', "/") +} + +fn head_of(path: &Path) -> String { + git2::Repository::open(path) + .unwrap() + .head() + .unwrap() + .target() + .unwrap() + .to_string() +} + +#[test] +fn post_checkout_runs_after_clone_with_a_zero_previous_head() { + let root = std::env::temp_dir().join(format!( + "angkorgit-clone-hooks-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + let home = root.join("home"); + let hooks = root.join("hooks"); + let log = root.join("post-checkout.log"); + std::fs::create_dir_all(&home).unwrap(); + let global = home.join(".gitconfig"); + std::fs::write( + &global, + format!( + "[core]\n\thooksPath = {}\n\tautocrlf = false\n[user]\n\tname = Test User\n\temail = \ + test@angkorgit.dev\n[commit]\n\tgpgsign = false\n", + shell_path(&hooks) + ), + ) + .unwrap(); + std::env::set_var("HOME", &home); + std::env::set_var("GIT_CONFIG_GLOBAL", &global); + std::env::set_var("XDG_CONFIG_HOME", home.join(".config")); + if !core::hook_runner_available() { + eprintln!("skipping: git 2.36 or newer is not on PATH"); + let _ = std::fs::remove_dir_all(&root); + return; + } + std::fs::create_dir_all(&hooks).unwrap(); + let hook = hooks.join("post-checkout"); + std::fs::write( + &hook, + format!( + "#!/bin/sh\necho \"post-checkout $*\" >> '{}'\n", + shell_path(&log) + ), + ) + .unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + + let source = root.join("source"); + core::init(source.to_str().unwrap()).unwrap(); + std::fs::write(source.join("a.txt"), "one\n").unwrap(); + core::stage_all(source.to_str().unwrap()).unwrap(); + let head = core::commit(source.to_str().unwrap(), "one", false) + .unwrap() + .oid; + + let into = root.join("clone"); + let cloned = core::post_hooks::clone( + source.to_str().unwrap(), + into.to_str().unwrap(), + None, + |_| {}, + false, + ) + .unwrap(); + assert!(cloned.warnings.is_empty()); + assert_eq!(head_of(&into), head); + assert_eq!( + std::fs::read_to_string(&log).unwrap(), + format!("post-checkout {} {head} 1\n", "0".repeat(40)) + ); + + std::fs::remove_file(&log).unwrap(); + core::post_hooks::clone( + source.to_str().unwrap(), + root.join("clone-without-hooks").to_str().unwrap(), + None, + |_| {}, + true, + ) + .unwrap(); + assert!(!log.exists()); + + let empty = root.join("empty"); + core::init(empty.to_str().unwrap()).unwrap(); + core::post_hooks::clone( + empty.to_str().unwrap(), + root.join("clone-of-empty").to_str().unwrap(), + None, + |_| {}, + false, + ) + .unwrap(); + assert!(!log.exists()); + + let _ = std::fs::remove_dir_all(&root); +} diff --git a/apps/desktop/src-tauri/tests/git_engine.rs b/apps/desktop/src-tauri/tests/git_engine.rs index 80eb04ed..7688e269 100644 --- a/apps/desktop/src-tauri/tests/git_engine.rs +++ b/apps/desktop/src-tauri/tests/git_engine.rs @@ -3505,6 +3505,9 @@ fn group_pull_matches_toolbar_pull_with_submodule_metadata_and_lfs_attributes() #[test] fn group_pull_matches_toolbar_pull_with_active_hooks() { + if !hooks_runnable() { + return; + } let local = TempRepo::new(); local.write("a.txt", "base\n"); commit_all(&local, "base"); @@ -3514,28 +3517,25 @@ fn group_pull_matches_toolbar_pull_with_active_hooks() { let toolbar = clone_of(&origin, &local, "toolbar-hooks"); let repo = git2::Repository::open(other.path()).unwrap(); let hooks = repo.path().join("custom-hooks"); - std::fs::create_dir_all(&hooks).unwrap(); for path in [other.path(), toolbar.path()] { core::set_config(Some(path), "core.hooksPath", hooks.to_str().unwrap(), false).unwrap(); } for name in ["post-checkout", "post-merge"] { - let hook = hooks.join(name); - std::fs::write(&hook, "#!/bin/sh\nprintf invoked > hook-ran\n").unwrap(); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap(); - } + write_hook(&hooks, name, &format!("printf '%s' \"$*\" > {name}-ran")); } local.write("a.txt", "updated\n"); let new = commit_all(&local, "updated"); core::push(local.path(), "origin", None, false, false, true, false).unwrap(); assert_eq!(core::group_update(other.path(), true).unwrap().status, "ok"); - core::pull(toolbar.path(), "origin", Some("merge")).unwrap(); + core::post_hooks::pull(toolbar.path(), "origin", Some("merge"), false) + .into_result() + .unwrap(); assert_eq!(other.read("a.txt"), toolbar.read("a.txt")); assert_eq!(repo.head().unwrap().target().unwrap().to_string(), new); - assert!(!other.dir.join("hook-ran").exists()); - assert!(!toolbar.dir.join("hook-ran").exists()); + for pulled in [&other, &toolbar] { + assert_eq!(pulled.read("post-merge-ran"), "0"); + assert!(!pulled.dir.join("post-checkout-ran").exists()); + } std::fs::remove_dir_all(origin).unwrap(); } @@ -3612,8 +3612,8 @@ fn group_cancel_acknowledges_a_stalled_remote_without_waiting_for_the_socket() { fn group_run_registry_keeps_cancellation_on_in_flight_handles_after_finish() { let local = TempRepo::new(); let id = local.path(); - core::group_update_start(id).unwrap(); - assert!(core::group_update_start(id).is_err()); + core::group_update_start(id, false).unwrap(); + assert!(core::group_update_start(id, false).is_err()); let control = core::group_update_control(id).unwrap(); assert!(!control.is_cancelled()); core::group_update_cancel(id).unwrap(); @@ -4765,7 +4765,7 @@ fn commit_hooks_follow_core_hooks_path_and_ignore_samples_and_plain_files() { write_hook(&default, "pre-commit.sample", "exit 1"); #[cfg(unix)] std::fs::write(default.join("commit-msg"), "#!/bin/sh\nexit 1\n").unwrap(); - assert!(core::repo_hooks(repo.path()).unwrap().is_empty()); + assert!(core::repo_hooks(repo.path()).unwrap().found.is_empty()); repo.write("a.txt", "one\n"); let base = commit_all(&repo, "base"); @@ -4776,7 +4776,10 @@ fn commit_hooks_follow_core_hooks_path_and_ignore_samples_and_plain_files() { "pre-commit", "echo 'from .githooks'\nexit 2", ); - assert_eq!(core::repo_hooks(repo.path()).unwrap(), vec!["pre-commit"]); + assert_eq!( + core::repo_hooks(repo.path()).unwrap().found, + vec!["pre-commit"] + ); if !hooks_runnable() { return; } @@ -4793,9 +4796,12 @@ fn commit_hooks_follow_core_hooks_path_and_ignore_samples_and_plain_files() { #[test] fn commit_hooks_include_hooks_defined_in_config() { let repo = TempRepo::new(); - assert!(core::repo_hooks(repo.path()).unwrap().is_empty()); + assert!(core::repo_hooks(repo.path()).unwrap().found.is_empty()); core::set_config(Some(repo.path()), "hook.lint.event", "pre-commit", false).unwrap(); - assert_eq!(core::repo_hooks(repo.path()).unwrap(), vec!["pre-commit"]); + assert_eq!( + core::repo_hooks(repo.path()).unwrap().found, + vec!["pre-commit"] + ); } #[test] @@ -5170,7 +5176,10 @@ fn pre_push_follows_core_hooks_path() { "pre-push", "echo 'from .githooks'\nexit 2", ); - assert_eq!(core::repo_hooks(local.path()).unwrap(), vec!["pre-push"]); + assert_eq!( + core::repo_hooks(local.path()).unwrap().found, + vec!["pre-push"] + ); if !hooks_runnable() { std::fs::remove_dir_all(origin).unwrap(); return; @@ -5439,3 +5448,1563 @@ fn an_amend_hook_that_switches_branch_leaves_both_branches_alone() { assert_eq!(branch_tip(&repo, "master"), base); assert_eq!(branch_tip(&repo, "other"), base); } + +const POST_HOOK_LOG: &str = ".git/post-hooks.log"; + +fn record_post_hooks(dir: &std::path::Path, log: &str) { + for name in ["post-checkout", "post-merge"] { + write_hook(dir, name, &format!("echo \"{name} $*\" >> '{log}'")); + } + write_hook( + dir, + "post-rewrite", + &format!("{{ echo \"post-rewrite $*\"; cat; }} >> '{log}'"), + ); +} + +fn post_hook_runs(repo: &TempRepo) -> Vec { + let file = repo.dir.join(POST_HOOK_LOG); + let text = std::fs::read_to_string(&file).unwrap_or_default(); + let _ = std::fs::remove_file(&file); + text.lines().map(str::to_string).collect() +} + +fn rev(repo: &TempRepo, spec: &str) -> String { + git2::Repository::open(repo.path()) + .unwrap() + .revparse_single(spec) + .unwrap() + .peel_to_commit() + .unwrap() + .id() + .to_string() +} + +fn shell_path(path: &std::path::Path) -> String { + path.to_string_lossy().replace('\\', "/") +} + +#[test] +fn post_checkout_runs_for_branch_switches_with_both_heads_and_flag_1() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "one\n"); + let first = commit_all(&repo, "one"); + core::branch_create(repo.path(), "other", None, false).unwrap(); + repo.write("a.txt", "two\n"); + let second = commit_all(&repo, "two"); + record_post_hooks(&default_hooks(&repo), POST_HOOK_LOG); + + let switched = core::post_hooks::checkout_branch(repo.path(), "other", false).unwrap(); + assert!(switched.warnings.is_empty()); + assert_eq!(repo.read("a.txt"), "one\n"); + assert_eq!( + post_hook_runs(&repo), + vec![format!("post-checkout {second} {first} 1")] + ); + + core::post_hooks::branch_create(repo.path(), "topic", None, true, false).unwrap(); + assert_eq!( + post_hook_runs(&repo), + vec![format!("post-checkout {first} {first} 1")] + ); + + core::post_hooks::branch_create(repo.path(), "quiet", None, false, false).unwrap(); + assert!(post_hook_runs(&repo).is_empty()); + + core::post_hooks::checkout_detached(repo.path(), &second, false).unwrap(); + assert_eq!( + post_hook_runs(&repo), + vec![format!("post-checkout {first} {second} 1")] + ); +} + +#[test] +fn discarding_changes_runs_post_checkout_with_flag_0_like_git_restore() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "one\n"); + repo.write("b.txt", "b\n"); + let head = commit_all(&repo, "one"); + record_post_hooks(&default_hooks(&repo), POST_HOOK_LOG); + let restored = vec![format!("post-checkout {head} {head} 0")]; + + repo.write("a.txt", "changed\n"); + core::post_hooks::discard_file(repo.path(), "a.txt", false).unwrap(); + assert_eq!(repo.read("a.txt"), "one\n"); + assert_eq!(post_hook_runs(&repo), restored); + + repo.write("new.txt", "untracked\n"); + core::post_hooks::discard_file(repo.path(), "new.txt", false).unwrap(); + assert!(!repo.dir.join("new.txt").exists()); + assert!(post_hook_runs(&repo).is_empty()); + + repo.write("new.txt", "untracked\n"); + core::post_hooks::discard_all(repo.path(), false).unwrap(); + assert!(post_hook_runs(&repo).is_empty()); + + repo.write("a.txt", "changed\n"); + repo.write("b.txt", "changed\n"); + core::post_hooks::discard_all(repo.path(), false).unwrap(); + assert_eq!(post_hook_runs(&repo), restored); + + repo.write("a.txt", "staged\n"); + core::stage_file(repo.path(), "a.txt").unwrap(); + core::post_hooks::discard_staged_file(repo.path(), "a.txt", false).unwrap(); + assert_eq!(post_hook_runs(&repo), restored); + + repo.write("b.txt", "staged\n"); + core::stage_file(repo.path(), "b.txt").unwrap(); + core::post_hooks::discard_staged_all(repo.path(), false).unwrap(); + assert_eq!(repo.read("b.txt"), "b\n"); + assert_eq!(post_hook_runs(&repo), restored); + + repo.write("a.txt", "stashed\n"); + core::stash_create(repo.path(), None, false, &[]).unwrap(); + core::post_hooks::stash_restore_files(repo.path(), 0, &["a.txt".to_string()], false).unwrap(); + assert_eq!(repo.read("a.txt"), "stashed\n"); + assert_eq!(post_hook_runs(&repo), restored); +} + +#[test] +fn discarding_several_files_runs_post_checkout_once_after_all_of_them() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "a\n"); + repo.write("b.txt", "b\n"); + repo.write("c.txt", "c\n"); + let head = commit_all(&repo, "three files"); + write_hook( + &default_hooks(&repo), + "post-checkout", + &format!("echo \"post-checkout $* $(cat a.txt b.txt c.txt | tr '\\n' ' ')\" >> '{POST_HOOK_LOG}'"), + ); + + for file in ["a.txt", "b.txt", "c.txt"] { + repo.write(file, "changed\n"); + } + let files: Vec = ["a.txt", "b.txt", "c.txt"].map(String::from).to_vec(); + let unstaged = core::post_hooks::discard_files(repo.path(), &files, false, false).unwrap(); + assert!(unstaged.value.leftovers.is_empty()); + assert!(unstaged.value.failed.is_empty()); + assert_eq!( + post_hook_runs(&repo), + vec![format!("post-checkout {head} {head} 0 a b c ")] + ); + + for file in ["a.txt", "b.txt"] { + repo.write(file, "staged\n"); + core::stage_file(repo.path(), file).unwrap(); + } + let staged: Vec = ["a.txt", "b.txt"].map(String::from).to_vec(); + core::post_hooks::discard_files(repo.path(), &staged, true, false).unwrap(); + assert_eq!( + post_hook_runs(&repo), + vec![format!("post-checkout {head} {head} 0 a b c ")] + ); + + repo.write("new.txt", "untracked\n"); + core::post_hooks::discard_files(repo.path(), &["new.txt".to_string()], false, false).unwrap(); + assert!(post_hook_runs(&repo).is_empty()); +} + +#[cfg(unix)] +#[test] +fn a_bulk_discard_reports_the_file_it_could_not_discard_and_keeps_the_others() { + use std::os::unix::fs::PermissionsExt; + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "a\n"); + repo.write("b.txt", "b\n"); + let head = commit_all(&repo, "two files"); + write_hook( + &default_hooks(&repo), + "post-checkout", + &format!("echo \"post-checkout $*\" >> '{POST_HOOK_LOG}'"), + ); + repo.write("a.txt", "changed\n"); + repo.write("locked/new.txt", "untracked\n"); + repo.write("b.txt", "changed\n"); + let locked = repo.dir.join("locked"); + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o555)).unwrap(); + if std::fs::write(locked.join("probe"), "").is_ok() { + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap(); + eprintln!("skipping: the folder stayed writable, permissions are not enforced here"); + return; + } + + let files: Vec = ["a.txt", "locked/new.txt", "b.txt"] + .map(String::from) + .to_vec(); + let result = core::post_hooks::discard_files(repo.path(), &files, false, false).unwrap(); + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert!(result.value.leftovers.is_empty()); + assert_eq!(result.value.failed.len(), 1); + assert_eq!(result.value.failed[0].path, "locked/new.txt"); + assert!(!result.value.failed[0].message.is_empty()); + assert_eq!(repo.read("a.txt"), "a\n"); + assert_eq!(repo.read("b.txt"), "b\n"); + assert!(repo.dir.join("locked/new.txt").exists()); + assert_eq!( + post_hook_runs(&repo), + vec![format!("post-checkout {head} {head} 0")] + ); +} + +#[cfg(unix)] +#[test] +fn discarding_all_staged_changes_keeps_going_past_a_file_it_cannot_delete() { + use std::os::unix::fs::PermissionsExt; + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "a\n"); + repo.write("z.txt", "z\n"); + let head = commit_all(&repo, "two files"); + write_hook( + &default_hooks(&repo), + "post-checkout", + &format!( + "echo \"post-checkout $* $(cat a.txt z.txt | tr '\\n' ' ')\" >> '{POST_HOOK_LOG}'" + ), + ); + for file in ["a.txt", "locked/new.txt", "z.txt"] { + repo.write(file, "staged\n"); + core::stage_file(repo.path(), file).unwrap(); + } + let locked = repo.dir.join("locked"); + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o555)).unwrap(); + if std::fs::write(locked.join("probe"), "").is_ok() { + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap(); + eprintln!("skipping: the folder stayed writable, permissions are not enforced here"); + return; + } + + let result = core::post_hooks::discard_staged_all(repo.path(), false); + std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap(); + let result = result.unwrap(); + assert!(result.value.leftovers.is_empty()); + assert_eq!(result.value.failed.len(), 1); + assert_eq!(result.value.failed[0].path, "locked/new.txt"); + assert!(!result.value.failed[0].message.is_empty()); + assert_eq!(repo.read("a.txt"), "a\n"); + assert_eq!(repo.read("z.txt"), "z\n"); + assert_eq!( + post_hook_runs(&repo), + vec![format!("post-checkout {head} {head} 0 a z ")] + ); +} + +#[test] +fn post_merge_runs_after_a_merge_commit_and_a_fast_forward_only() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "base\n"); + commit_all(&repo, "base"); + core::branch_create(repo.path(), "feature", None, true).unwrap(); + repo.write("f.txt", "feature\n"); + commit_all(&repo, "feature"); + core::checkout_branch(repo.path(), "master").unwrap(); + record_post_hooks(&default_hooks(&repo), POST_HOOK_LOG); + + let before = rev(&repo, "HEAD"); + write_hook( + &default_hooks(&repo), + "post-merge", + &format!( + "echo \"post-merge $*\" >> '{POST_HOOK_LOG}'\ngit diff --name-only ORIG_HEAD HEAD >> '{POST_HOOK_LOG}'" + ), + ); + let ff = core::post_hooks::merge(repo.path(), "feature", false, false).unwrap(); + assert_eq!(ff.value.status, "fast_forward"); + assert_eq!(rev(&repo, "ORIG_HEAD"), before); + assert_eq!(post_hook_runs(&repo), vec!["post-merge 0", "f.txt"]); + record_post_hooks(&default_hooks(&repo), POST_HOOK_LOG); + + let again = core::post_hooks::merge(repo.path(), "feature", false, false).unwrap(); + assert_eq!(again.value.status, "up_to_date"); + assert!(post_hook_runs(&repo).is_empty()); + + core::branch_create(repo.path(), "side", None, true).unwrap(); + repo.write("s.txt", "side\n"); + commit_all(&repo, "side"); + core::checkout_branch(repo.path(), "master").unwrap(); + repo.write("m.txt", "master\n"); + commit_all(&repo, "master"); + let merged = core::post_hooks::merge(repo.path(), "side", false, false).unwrap(); + assert_eq!(merged.value.status, "ok"); + assert_eq!(head_commit(&repo).1, 2); + assert_eq!(post_hook_runs(&repo), vec!["post-merge 0"]); + + core::branch_create(repo.path(), "clash", None, true).unwrap(); + repo.write("a.txt", "clash\n"); + commit_all(&repo, "clash"); + core::checkout_branch(repo.path(), "master").unwrap(); + repo.write("a.txt", "master edit\n"); + commit_all(&repo, "master edit"); + let conflicted = core::post_hooks::merge(repo.path(), "clash", true, false).unwrap(); + assert_eq!(conflicted.value.status, "conflicts"); + assert!(post_hook_runs(&repo).is_empty()); +} + +#[test] +fn post_rewrite_after_amend_and_reword_gets_the_old_and_new_commit() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "one\n"); + let first = commit_all(&repo, "one"); + record_post_hooks(&default_hooks(&repo), POST_HOOK_LOG); + + repo.write("a.txt", "two\n"); + core::stage_all(repo.path()).unwrap(); + let amended = core::post_hooks::amend(repo.path(), Some("one, amended"), false).unwrap(); + let new = amended.value.oid; + assert_ne!(new, first); + assert_eq!( + post_hook_runs(&repo), + vec!["post-rewrite amend".to_string(), format!("{first} {new}")] + ); + + let reworded = core::post_hooks::reword(repo.path(), &new, "one, reworded", false).unwrap(); + assert_eq!( + post_hook_runs(&repo), + vec![ + "post-rewrite amend".to_string(), + format!("{new} {}", reworded.value) + ] + ); + + repo.write("b.txt", "b\n"); + commit_all(&repo, "plain commit"); + assert!(post_hook_runs(&repo).is_empty()); +} + +#[test] +fn post_rewrite_after_rebase_lists_every_commit_once() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "base\n"); + commit_all(&repo, "base"); + core::branch_create(repo.path(), "topic", None, true).unwrap(); + repo.write("t1.txt", "t1\n"); + let t1 = commit_all(&repo, "t1"); + repo.write("t2.txt", "t2\n"); + let t2 = commit_all(&repo, "t2"); + core::checkout_branch(repo.path(), "master").unwrap(); + repo.write("m.txt", "m\n"); + let onto = commit_all(&repo, "m"); + core::checkout_branch(repo.path(), "topic").unwrap(); + record_post_hooks(&default_hooks(&repo), POST_HOOK_LOG); + + let rebased = core::post_hooks::rebase(repo.path(), "master", false) + .into_result() + .unwrap(); + assert_eq!(rebased.value.status, "ok"); + assert_eq!(rev(&repo, "HEAD~2"), onto); + assert_eq!( + post_hook_runs(&repo), + vec![ + format!("post-checkout {t2} {onto} 1"), + "post-rewrite rebase".to_string(), + format!("{t1} {}", rev(&repo, "HEAD~1")), + format!("{t2} {}", rev(&repo, "HEAD")), + ] + ); + + let again = core::post_hooks::rebase(repo.path(), "topic", false) + .into_result() + .unwrap(); + assert_eq!(again.value.status, "up_to_date"); + assert!(post_hook_runs(&repo).is_empty()); +} + +#[test] +fn rebasing_a_branch_already_on_top_of_its_upstream_is_up_to_date_and_runs_no_hook() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "base\n"); + commit_all(&repo, "base"); + core::branch_create(repo.path(), "topic", None, true).unwrap(); + repo.write("t1.txt", "t1\n"); + commit_all(&repo, "t1"); + repo.write("t2.txt", "t2\n"); + let tip = commit_all(&repo, "t2"); + record_post_hooks(&default_hooks(&repo), POST_HOOK_LOG); + + let rebased = core::post_hooks::rebase(repo.path(), "master", false) + .into_result() + .unwrap(); + assert_eq!( + rebased.value.status, "up_to_date", + "{}", + rebased.value.message + ); + assert_eq!(rev(&repo, "HEAD"), tip); + assert!(post_hook_runs(&repo).is_empty()); +} + +#[test] +fn a_rebase_aborted_during_post_checkout_does_not_replay_any_commits() { + use std::time::{Duration, Instant}; + + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("base.txt", "base\n"); + commit_all(&repo, "base"); + core::branch_create(repo.path(), "topic", None, true).unwrap(); + repo.write("topic.txt", "topic\n"); + let topic = commit_all(&repo, "topic"); + core::checkout_branch(repo.path(), "master").unwrap(); + repo.write("master.txt", "master\n"); + commit_all(&repo, "master"); + core::checkout_branch(repo.path(), "topic").unwrap(); + write_hook(&default_hooks(&repo), "post-checkout", "echo started > .git/hook-started\nattempts=0\nwhile [ ! -f .git/hook-release ] && [ \"$attempts\" -lt 200 ]; do\n sleep 0.05\n attempts=$((attempts + 1))\ndone\n"); + write_hook( + &default_hooks(&repo), + "post-rewrite", + &format!("echo rewritten >> '{POST_HOOK_LOG}'"), + ); + + let (started, aborted, outcome) = std::thread::scope(|scope| { + let running = scope.spawn(|| core::post_hooks::rebase(repo.path(), "master", false)); + let deadline = Instant::now() + Duration::from_secs(5); + while !repo.dir.join(".git/hook-started").exists() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(10)); + } + let started = repo.dir.join(".git/hook-started").exists(); + let aborted = core::rebase_abort(repo.path()); + std::fs::write(repo.dir.join(".git/hook-release"), "").unwrap(); + (started, aborted, running.join().unwrap()) + }); + assert!(started); + aborted.unwrap(); + let result = outcome.into_result().unwrap(); + assert_eq!(result.value.status, "ok"); + assert_eq!(result.value.message, "Rebase aborted"); + assert_eq!(rev(&repo, "HEAD"), topic); + assert_eq!(rev(&repo, "topic"), topic); + assert!(!repo.dir.join("master.txt").exists()); + assert!(!repo.dir.join(".git/rebase-merge").exists()); + assert!(core::status(repo.path()).unwrap().files.is_empty()); + assert!(post_hook_runs(&repo).is_empty()); +} + +#[test] +fn rebase_runs_post_checkout_on_onto_before_replaying_the_commits() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "base\n"); + commit_all(&repo, "base"); + core::branch_create(repo.path(), "topic", None, true).unwrap(); + repo.write("a.txt", "topic\n"); + let topic = commit_all(&repo, "topic"); + core::checkout_branch(repo.path(), "master").unwrap(); + repo.write("a.txt", "master\n"); + let onto = commit_all(&repo, "m"); + core::checkout_branch(repo.path(), "topic").unwrap(); + write_hook( + &default_hooks(&repo), + "post-checkout", + &format!("echo \"$2 $(git rev-parse HEAD) $(cat a.txt)\" >> '{POST_HOOK_LOG}'"), + ); + + let paused = core::post_hooks::rebase(repo.path(), "master", false) + .into_result() + .unwrap(); + assert_eq!(paused.value.status, "conflicts"); + assert!(repo.read("a.txt").contains("<<<<<<<")); + assert_eq!(post_hook_runs(&repo), vec![format!("{onto} {onto} master")]); + assert_ne!(topic, onto); +} + +#[test] +fn post_rewrite_runs_once_when_a_paused_rebase_completes() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "base\n"); + commit_all(&repo, "base"); + core::branch_create(repo.path(), "topic", None, true).unwrap(); + repo.write("t1.txt", "t1\n"); + let t1 = commit_all(&repo, "t1"); + repo.write("a.txt", "topic\n"); + let t2 = commit_all(&repo, "t2"); + core::checkout_branch(repo.path(), "master").unwrap(); + repo.write("a.txt", "master\n"); + let onto = commit_all(&repo, "m"); + core::checkout_branch(repo.path(), "topic").unwrap(); + record_post_hooks(&default_hooks(&repo), POST_HOOK_LOG); + + let paused = core::post_hooks::rebase(repo.path(), "master", false) + .into_result() + .unwrap(); + assert_eq!(paused.value.status, "conflicts"); + assert_eq!( + post_hook_runs(&repo), + vec![format!("post-checkout {t2} {onto} 1")] + ); + + core::conflict_resolve(repo.path(), "a.txt", "resolved\n").unwrap(); + let done = core::post_hooks::rebase_continue(repo.path(), false).unwrap(); + assert_eq!(done.value.status, "ok", "{}", done.value.message); + assert_eq!( + post_hook_runs(&repo), + vec![ + "post-rewrite rebase".to_string(), + format!("{t1} {}", rev(&repo, "HEAD~1")), + format!("{t2} {}", rev(&repo, "HEAD")), + ] + ); +} + +#[test] +fn interactive_rebase_maps_squashed_commits_and_leaves_out_dropped_ones() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "base\n"); + let base = commit_all(&repo, "base"); + repo.write("c1.txt", "c1\n"); + let c1 = commit_all(&repo, "c1"); + repo.write("c2.txt", "c2\n"); + let c2 = commit_all(&repo, "c2"); + repo.write("c3.txt", "c3\n"); + let c3 = commit_all(&repo, "c3"); + record_post_hooks(&default_hooks(&repo), POST_HOOK_LOG); + + let todo = vec![ + todo_entry(&c1, "pick", None), + todo_entry(&c2, "squash", Some("c1 and c2")), + todo_entry(&c3, "drop", None), + ]; + let rebased = core::post_hooks::rebase_interactive(repo.path(), &base, &todo, false).unwrap(); + let squashed = rebased.value; + assert_eq!(rev(&repo, "HEAD~1"), base); + assert_eq!( + post_hook_runs(&repo), + vec![ + format!("post-checkout {c3} {squashed} 1"), + "post-rewrite rebase".to_string(), + format!("{c1} {squashed}"), + format!("{c2} {squashed}"), + ] + ); +} + +#[test] +fn pull_with_rebase_runs_post_rewrite_and_never_post_merge() { + if !hooks_runnable() { + return; + } + let local = TempRepo::new(); + local.write("a.txt", "base\n"); + commit_all(&local, "base"); + let origin = bare_origin(&local); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + let other = clone_of(&origin, &local, "pull-hooks"); + record_post_hooks(&default_hooks(&other), POST_HOOK_LOG); + + local.write("b.txt", "b\n"); + commit_all(&local, "b"); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + let behind = core::post_hooks::pull(other.path(), "origin", Some("rebase"), false) + .into_result() + .unwrap(); + assert_eq!(behind.value.status, "fast_forward"); + assert_eq!(post_hook_runs(&other), vec!["post-merge 0"]); + + local.write("c.txt", "c\n"); + commit_all(&local, "c"); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + other.write("o.txt", "o\n"); + let mine = commit_all(&other, "o"); + let diverged = core::post_hooks::pull(other.path(), "origin", Some("rebase"), false) + .into_result() + .unwrap(); + assert_eq!(diverged.value.status, "ok", "{}", diverged.value.message); + assert_eq!(head_commit(&other).1, 1); + assert_eq!( + post_hook_runs(&other), + vec![ + format!("post-checkout {mine} {} 1", rev(&other, "origin/master")), + "post-rewrite rebase".to_string(), + format!("{mine} {}", rev(&other, "HEAD")), + ] + ); + + local.write("d.txt", "d\n"); + commit_all(&local, "d"); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + other.write("p.txt", "p\n"); + commit_all(&other, "p"); + let merged = core::post_hooks::pull(other.path(), "origin", Some("merge"), false) + .into_result() + .unwrap(); + assert_eq!(merged.value.status, "ok"); + assert_eq!(post_hook_runs(&other), vec!["post-merge 0"]); + + let current = core::post_hooks::pull(other.path(), "origin", Some("merge"), false) + .into_result() + .unwrap(); + assert_eq!(current.value.status, "up_to_date"); + assert!(post_hook_runs(&other).is_empty()); + std::fs::remove_dir_all(origin).unwrap(); +} + +#[test] +fn pull_without_hooks_stays_without_hooks_when_its_paused_rebase_is_continued() { + if !hooks_runnable() { + return; + } + let local = TempRepo::new(); + local.write("a.txt", "base\n"); + commit_all(&local, "base"); + let origin = bare_origin(&local); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + let other = clone_of(&origin, &local, "pull-skip-continue"); + record_post_hooks(&default_hooks(&other), POST_HOOK_LOG); + local.write("a.txt", "theirs\n"); + commit_all(&local, "theirs"); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + other.write("a.txt", "mine\n"); + commit_all(&other, "mine"); + + let paused = core::post_hooks::pull(other.path(), "origin", Some("rebase"), true) + .into_result() + .unwrap(); + assert_eq!(paused.value.status, "conflicts"); + core::conflict_resolve(other.path(), "a.txt", "both\n").unwrap(); + let done = core::post_hooks::rebase_continue(other.path(), false).unwrap(); + assert_eq!(done.value.status, "ok", "{}", done.value.message); + assert!(done.warnings.is_empty()); + assert!(post_hook_runs(&other).is_empty()); + std::fs::remove_dir_all(origin).unwrap(); +} + +#[test] +fn pull_without_hooks_stays_without_hooks_when_replay_stops_on_an_untracked_file() { + if !hooks_runnable() { + return; + } + let local = TempRepo::new(); + local.write("a.txt", "base\n"); + commit_all(&local, "base"); + let origin = bare_origin(&local); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + let other = clone_of(&origin, &local, "pull-skip-untracked"); + record_post_hooks(&default_hooks(&other), POST_HOOK_LOG); + local.write("theirs.txt", "theirs\n"); + commit_all(&local, "theirs"); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + other.write("first.txt", "replays cleanly\n"); + commit_all(&other, "first"); + other.write("later.txt", "added\n"); + commit_all(&other, "add later"); + std::fs::remove_file(other.dir.join("later.txt")).unwrap(); + commit_all(&other, "remove later"); + other.write("later.txt", "untracked and in the way\n"); + + let stopped = + core::post_hooks::pull(other.path(), "origin", Some("rebase"), true).into_result(); + assert!(stopped.is_err()); + let repo = git2::Repository::open(other.path()).unwrap(); + assert_eq!(repo.state(), git2::RepositoryState::RebaseMerge); + drop(repo); + std::fs::remove_file(other.dir.join("later.txt")).unwrap(); + let done = core::post_hooks::rebase_continue(other.path(), false).unwrap(); + assert_eq!(done.value.status, "ok", "{}", done.value.message); + assert!(post_hook_runs(&other).is_empty()); + std::fs::remove_dir_all(origin).unwrap(); +} + +#[test] +fn rebase_refuses_a_dirty_tree_or_a_rebase_in_progress_even_when_up_to_date() { + let repo = TempRepo::new(); + repo.write("a.txt", "base\n"); + commit_all(&repo, "base"); + core::branch_create(repo.path(), "topic", None, true).unwrap(); + repo.write("t.txt", "t\n"); + let tip = commit_all(&repo, "t"); + + repo.write("a.txt", "unstaged\n"); + let unstaged = core::post_hooks::rebase(repo.path(), "master", false).into_result(); + assert!(unstaged.is_err()); + core::stage_file(repo.path(), "a.txt").unwrap(); + let staged = core::post_hooks::rebase(repo.path(), "master", false).into_result(); + assert!(staged.is_err()); + assert_eq!(rev(&repo, "HEAD"), tip); + core::discard_staged_file(repo.path(), "a.txt").unwrap(); + + core::checkout_branch(repo.path(), "master").unwrap(); + repo.write("a.txt", "master\n"); + commit_all(&repo, "master edit"); + core::branch_create(repo.path(), "clash", Some(&tip), true).unwrap(); + repo.write("a.txt", "clash\n"); + commit_all(&repo, "clash edit"); + let paused = core::post_hooks::rebase(repo.path(), "master", false) + .into_result() + .unwrap(); + assert_eq!(paused.value.status, "conflicts"); + let again = core::post_hooks::rebase(repo.path(), "HEAD", false).into_result(); + assert!(again.is_err()); + let message = again.err().unwrap().to_string(); + assert!(message.contains("in progress"), "{message}"); +} + +#[test] +fn a_hook_folder_inside_the_worktree_is_reported_so_a_pull_can_skip_an_arriving_hook() { + if !hooks_runnable() { + return; + } + let local = TempRepo::new(); + local.write("a.txt", "base\n"); + commit_all(&local, "base"); + assert!(!core::repo_hooks(local.path()).unwrap().in_worktree); + core::set_config( + Some(local.path()), + "core.hooksPath", + "../shared-hooks", + false, + ) + .unwrap(); + assert!(!core::repo_hooks(local.path()).unwrap().in_worktree); + let origin = bare_origin(&local); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + let skipping = clone_of(&origin, &local, "husky-skip"); + let running = clone_of(&origin, &local, "husky-run"); + for repo in [&skipping, &running] { + core::set_config(Some(repo.path()), "core.hooksPath", ".husky", false).unwrap(); + let hooks = core::repo_hooks(repo.path()).unwrap(); + assert!(hooks.found.is_empty()); + assert!(hooks.in_worktree); + } + write_hook( + &local.dir.join(".husky"), + "post-merge", + &format!("echo \"post-merge $*\" >> '{POST_HOOK_LOG}'"), + ); + commit_all(&local, "add a post-merge hook"); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + + core::post_hooks::pull(skipping.path(), "origin", Some("merge"), true) + .into_result() + .unwrap(); + assert!(skipping.dir.join(".husky").join("post-merge").exists()); + assert!(post_hook_runs(&skipping).is_empty()); + core::post_hooks::pull(running.path(), "origin", Some("merge"), false) + .into_result() + .unwrap(); + assert_eq!(post_hook_runs(&running), vec!["post-merge 0"]); + std::fs::remove_dir_all(origin).unwrap(); +} + +#[cfg(unix)] +#[test] +fn a_hook_symlink_into_the_worktree_counts_as_a_hook_a_pull_can_bring() { + if !hooks_runnable() { + return; + } + let local = TempRepo::new(); + local.write("a.txt", "base\n"); + commit_all(&local, "base"); + let origin = bare_origin(&local); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + let skipping = clone_of(&origin, &local, "symlink-skip"); + let running = clone_of(&origin, &local, "symlink-run"); + for repo in [&skipping, &running] { + let link = default_hooks(repo).join("post-merge"); + std::os::unix::fs::symlink("../../scripts/post-merge", &link).unwrap(); + let hooks = core::repo_hooks(repo.path()).unwrap(); + assert!(!hooks.found.contains(&"post-merge".to_string())); + assert!(hooks.in_worktree); + } + let outside = TempRepo::new(); + std::os::unix::fs::symlink("/usr/bin/true", default_hooks(&outside).join("post-merge")) + .unwrap(); + assert!(!core::repo_hooks(outside.path()).unwrap().in_worktree); + let linked_folder = TempRepo::new(); + std::fs::remove_dir_all(default_hooks(&linked_folder)).ok(); + std::os::unix::fs::symlink("../githooks", default_hooks(&linked_folder)).unwrap(); + assert!(core::repo_hooks(linked_folder.path()).unwrap().in_worktree); + let chained = TempRepo::new(); + let hop = chained.dir.with_extension("hop"); + std::os::unix::fs::symlink(chained.dir.join("scripts").join("post-merge"), &hop).unwrap(); + std::os::unix::fs::symlink(&hop, default_hooks(&chained).join("post-merge")).unwrap(); + assert!(core::repo_hooks(chained.path()).unwrap().in_worktree); + std::fs::remove_file(hop).unwrap(); + + write_hook( + &local.dir.join("scripts"), + "post-merge", + &format!("echo \"post-merge $*\" >> '{POST_HOOK_LOG}'"), + ); + commit_all(&local, "add the post-merge script"); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + + core::post_hooks::pull(skipping.path(), "origin", Some("merge"), true) + .into_result() + .unwrap(); + assert!(post_hook_runs(&skipping).is_empty()); + core::post_hooks::pull(running.path(), "origin", Some("merge"), false) + .into_result() + .unwrap(); + assert_eq!(post_hook_runs(&running), vec!["post-merge 0"]); + std::fs::remove_dir_all(origin).unwrap(); +} + +#[cfg(unix)] +#[test] +fn a_hook_link_that_climbs_out_of_a_linked_folder_is_followed_like_the_filesystem_does() { + let repo = TempRepo::new(); + std::fs::create_dir_all(repo.dir.join("sub").join("dir")).unwrap(); + let hooks = default_hooks(&repo); + std::fs::create_dir_all(&hooks).unwrap(); + std::os::unix::fs::symlink(repo.dir.join("sub").join("dir"), hooks.join("proxy")).unwrap(); + std::os::unix::fs::symlink("proxy/../.husky/post-merge", hooks.join("post-merge")).unwrap(); + let found = core::repo_hooks(repo.path()).unwrap(); + assert!(!found.found.contains(&"post-merge".to_string())); + assert!(found.in_worktree); +} + +#[test] +fn a_hooks_path_spelled_with_other_letter_case_is_the_same_folder_where_the_disk_ignores_case() { + let repo = TempRepo::new(); + let name = repo + .dir + .file_name() + .unwrap() + .to_string_lossy() + .to_uppercase(); + let respelled = repo.dir.with_file_name(&name); + let ignores_case = std::fs::metadata(&respelled).is_ok(); + let configured = respelled.join(".husky"); + core::set_config( + Some(repo.path()), + "core.hooksPath", + configured.to_str().unwrap(), + false, + ) + .unwrap(); + assert_eq!( + core::repo_hooks(repo.path()).unwrap().in_worktree, + ignores_case + ); +} + +#[cfg(unix)] +#[test] +fn a_tracked_hooks_link_that_a_pull_replaces_with_a_folder_still_offers_the_skip() { + if !hooks_runnable() { + return; + } + let local = TempRepo::new(); + local.write("a.txt", "base\n"); + let empty = local.dir.with_extension("empty-hooks"); + std::fs::create_dir_all(&empty).unwrap(); + std::os::unix::fs::symlink(&empty, local.dir.join(".husky")).unwrap(); + commit_all(&local, "point .husky elsewhere"); + let origin = bare_origin(&local); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + let skipping = clone_of(&origin, &local, "husky-link-skip"); + let running = clone_of(&origin, &local, "husky-link-run"); + for repo in [&skipping, &running] { + core::set_config(Some(repo.path()), "core.hooksPath", ".husky", false).unwrap(); + let hooks = core::repo_hooks(repo.path()).unwrap(); + assert!(hooks.found.is_empty()); + assert!(hooks.in_worktree); + } + std::fs::remove_file(local.dir.join(".husky")).unwrap(); + write_hook( + &local.dir.join(".husky"), + "post-merge", + &format!("echo \"post-merge $*\" >> '{POST_HOOK_LOG}'"), + ); + commit_all(&local, "real .husky folder"); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + + core::post_hooks::pull(skipping.path(), "origin", Some("merge"), true) + .into_result() + .unwrap(); + assert!(skipping.dir.join(".husky").join("post-merge").is_file()); + assert!(post_hook_runs(&skipping).is_empty()); + core::post_hooks::pull(running.path(), "origin", Some("merge"), false) + .into_result() + .unwrap(); + assert_eq!(post_hook_runs(&running), vec!["post-merge 0"]); + std::fs::remove_dir_all(origin).unwrap(); + std::fs::remove_dir_all(empty).unwrap(); +} + +#[test] +fn a_post_checkout_warning_survives_a_replay_that_fails_afterwards() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "base\n"); + commit_all(&repo, "base"); + core::branch_create(repo.path(), "topic", None, false).unwrap(); + repo.write("theirs.txt", "theirs\n"); + commit_all(&repo, "theirs"); + core::checkout_branch(repo.path(), "topic").unwrap(); + repo.write("later.txt", "added\n"); + commit_all(&repo, "add later"); + std::fs::remove_file(repo.dir.join("later.txt")).unwrap(); + commit_all(&repo, "remove later"); + repo.write("later.txt", "untracked and in the way\n"); + write_hook( + &default_hooks(&repo), + "post-checkout", + "echo install failed >&2\nexit 3", + ); + + let stopped = core::post_hooks::rebase(repo.path(), "master", false); + assert!(stopped.value.is_err()); + assert_eq!(stopped.warnings.len(), 1); + assert_eq!(stopped.warnings[0].hook, "post-checkout"); + assert_eq!(stopped.warnings[0].status, Some(3)); + assert_eq!(stopped.warnings[0].output, "install failed"); +} + +#[test] +fn a_tracked_config_include_offers_the_skip_before_it_sets_a_hooks_path() { + if !hooks_runnable() { + return; + } + let local = TempRepo::new(); + local.write("project.gitconfig", "# project settings come later\n"); + commit_all(&local, "project config"); + let origin = bare_origin(&local); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + let skipping = clone_of(&origin, &local, "include-skip"); + let running = clone_of(&origin, &local, "include-run"); + for repo in [&skipping, &running] { + assert!(!core::repo_hooks(repo.path()).unwrap().in_worktree); + core::set_config( + Some(repo.path()), + "include.path", + "../project.gitconfig", + false, + ) + .unwrap(); + let hooks = core::repo_hooks(repo.path()).unwrap(); + assert!(hooks.found.is_empty()); + assert!(hooks.in_worktree); + } + local.write("project.gitconfig", "[core]\n\thooksPath = .husky\n"); + write_hook( + &local.dir.join(".husky"), + "post-merge", + &format!("echo \"post-merge $*\" >> '{POST_HOOK_LOG}'"), + ); + commit_all(&local, "hooks from the project config"); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + + core::post_hooks::pull(skipping.path(), "origin", Some("merge"), true) + .into_result() + .unwrap(); + assert!(post_hook_runs(&skipping).is_empty()); + core::post_hooks::pull(running.path(), "origin", Some("merge"), false) + .into_result() + .unwrap(); + assert_eq!(post_hook_runs(&running), vec!["post-merge 0"]); + std::fs::remove_dir_all(origin).unwrap(); +} + +#[cfg(unix)] +#[test] +fn a_quoted_config_include_preserves_trailing_whitespace() { + let repo = TempRepo::new(); + repo.write("project.gitconfig", "# project settings come later\n"); + commit_all(&repo, "project config"); + assert!(!core::repo_hooks(repo.path()).unwrap().in_worktree); + + std::os::unix::fs::symlink("../project.gitconfig", repo.dir.join(".git/project ")).unwrap(); + let config = repo.read(".git/config"); + repo.write( + ".git/config", + &format!("{config}\n[include]\n\tpath = \"project \"\n"), + ); + + let hooks = core::repo_hooks(repo.path()).unwrap(); + assert!(hooks.found.is_empty()); + assert!(hooks.in_worktree); +} + +#[cfg(windows)] +#[test] +fn a_config_include_uses_the_windows_home_drive_and_path() { + use std::path::{Component, Path}; + + const REPO: &str = "ANGKORGIT_TEST_WINDOWS_INCLUDE_REPO"; + if let Some(path) = std::env::var_os(REPO) { + let path = Path::new(&path); + assert_eq!( + git_in(path, &["config", "--get", "angkorgit-test.marker"]), + "included" + ); + let repo = git2::Repository::open(path).unwrap(); + assert_eq!( + repo.config() + .unwrap() + .get_string("angkorgit-test.marker") + .unwrap(), + "included" + ); + let hooks = core::repo_hooks(path.to_str().unwrap()).unwrap(); + assert!(hooks.found.is_empty()); + assert!(hooks.in_worktree); + return; + } + + let repo = TempRepo::new(); + repo.write( + "project.gitconfig", + "[angkorgit-test]\n\tmarker = included\n", + ); + commit_all(&repo, "track included config"); + let config = repo.read(".git/config"); + repo.write( + ".git/config", + &format!("{config}\n[include]\n\tpath = ~/project.gitconfig\n"), + ); + let profile = tempfile::tempdir().unwrap(); + let mut home = repo.dir.components(); + let Some(Component::Prefix(drive)) = home.next() else { + panic!("test repository needs a drive prefix"); + }; + let output = Command::new(std::env::current_exe().unwrap()) + .args([ + "--exact", + "a_config_include_uses_the_windows_home_drive_and_path", + "--nocapture", + ]) + .env(REPO, &repo.dir) + .env_remove("HOME") + .env("HOMEDRIVE", drive.as_os_str()) + .env("HOMEPATH", home.as_path()) + .env("USERPROFILE", profile.path()) + .output() + .unwrap(); + assert!( + output.status.success(), + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} + +#[test] +fn a_config_scan_that_hits_its_file_limit_still_offers_the_skip() { + let repo = TempRepo::new(); + repo.write("project.gitconfig", "# project settings come later\n"); + commit_all(&repo, "project config"); + let outside = repo.dir.with_extension("many-configs"); + std::fs::create_dir_all(&outside).unwrap(); + let mut includes = String::from("[include]\n\tpath = ../project.gitconfig\n"); + for n in 0..64 { + let file = outside.join(format!("c{n}.gitconfig")); + std::fs::write(&file, "# outside\n").unwrap(); + includes.push_str(&format!("\tpath = {}\n", shell_path(&file))); + } + let config = repo.dir.join(".git").join("config"); + let mut text = std::fs::read_to_string(&config).unwrap(); + text.push_str(&includes); + std::fs::write(&config, text).unwrap(); + + assert!(core::repo_hooks(repo.path()).unwrap().in_worktree); + std::fs::remove_dir_all(outside).unwrap(); +} + +#[test] +fn interactive_rebase_keeps_honouring_a_submodule_ignore_dirty_setting() { + let fixture = SubmoduleFixture::new(); + let local = &fixture.local; + let gitmodules = local.read(".gitmodules"); + local.write(".gitmodules", &format!("{gitmodules}\tignore = dirty\n")); + let configured = commit_all(local, "ignore dirty submodule content"); + local.write("one.txt", "one\n"); + let first = commit_all(local, "one"); + local.write("two.txt", "two\n"); + let second = commit_all(local, "two"); + local.write("deps/lib/lib.txt", "edited inside the submodule\n"); + + let todo = vec![ + todo_entry(&first, "pick", None), + todo_entry(&second, "reword", Some("two, reworded")), + ]; + core::post_hooks::rebase_interactive(local.path(), &configured, &todo, false).unwrap(); + assert_eq!(head_message(local).trim(), "two, reworded"); + let older = rev(local, "HEAD~1"); + core::post_hooks::reword(local.path(), &older, "one, reworded", false).unwrap(); + assert_eq!( + std::fs::read_to_string(local.dir.join("deps/lib/lib.txt")).unwrap(), + "edited inside the submodule\n" + ); + + core::branch_create(local.path(), "topic", Some(&configured), true).unwrap(); + local.write("topic.txt", "topic\n"); + commit_all(local, "topic"); + let ordinary = core::post_hooks::rebase(local.path(), "master", false).into_result(); + assert!(ordinary.is_err()); +} + +#[test] +fn interactive_rebase_and_reword_refuse_a_staged_pointer_for_an_ignored_submodule() { + let fixture = SubmoduleFixture::new(); + let local = &fixture.local; + let gitmodules = local.read(".gitmodules"); + local.write(".gitmodules", &format!("{gitmodules}\tignore = all\n")); + let configured = commit_all(local, "ignore the submodule worktree"); + local.write("one.txt", "one\n"); + let first = commit_all(local, "one"); + local.write("two.txt", "two\n"); + let head = commit_all(local, "two"); + git_in( + &local.dir, + &[ + "update-index", + "--cacheinfo", + &format!("160000,{},deps/lib", fixture.second), + ], + ); + + let todo = [ + todo_entry(&first, "pick", None), + todo_entry(&head, "reword", Some("two, reworded")), + ]; + let rebase = core::post_hooks::rebase_interactive(local.path(), &configured, &todo, true) + .err() + .expect("interactive rebase must refuse the staged gitlink"); + let reword = core::post_hooks::reword(local.path(), &first, "one, reworded", true) + .err() + .expect("reword must refuse the staged gitlink"); + for refused in [rebase.to_string(), reword.to_string()] { + assert!(refused.contains("uncommitted changes")); + } + assert_eq!(rev(local, "HEAD"), head); + assert_eq!( + git_in(&local.dir, &["rev-parse", ":deps/lib"]), + fixture.second + ); + assert_eq!(fixture.checked_out(), fixture.first); +} + +#[test] +fn rebase_allows_a_submodule_with_only_untracked_files_but_not_edited_ones() { + let fixture = SubmoduleFixture::new(); + let local = &fixture.local; + core::branch_create(local.path(), "topic", Some(&fixture.added), false).unwrap(); + local.write("README.md", "parent, edited on master\n"); + let onto = commit_all(local, "master edit"); + core::checkout_branch(local.path(), "topic").unwrap(); + local.write("notes.txt", "topic\n"); + commit_all(local, "topic note"); + local.write("deps/lib/scratch.txt", "untracked inside the submodule\n"); + + let rebased = core::post_hooks::rebase(local.path(), "master", false) + .into_result() + .unwrap(); + assert_eq!(rebased.value.status, "ok", "{}", rebased.value.message); + assert_eq!(rev(local, "HEAD~1"), onto); + assert!(local.dir.join("deps/lib/scratch.txt").exists()); + + core::branch_create(local.path(), "again", Some(&fixture.added), true).unwrap(); + local.write("again.txt", "again\n"); + commit_all(local, "again"); + local.write("deps/lib/lib.txt", "edited inside the submodule\n"); + let refused = core::post_hooks::rebase(local.path(), "master", false).into_result(); + assert!(refused.is_err()); +} + +#[test] +fn a_fast_forward_leaves_orig_head_alone_while_another_process_holds_its_lock() { + let repo = TempRepo::new(); + repo.write("a.txt", "base\n"); + let base = commit_all(&repo, "base"); + core::branch_create(repo.path(), "feature", None, true).unwrap(); + repo.write("f.txt", "feature\n"); + commit_all(&repo, "feature"); + core::checkout_branch(repo.path(), "master").unwrap(); + let gitdir = repo.dir.join(".git"); + std::fs::write(gitdir.join("ORIG_HEAD"), format!("{base}\n")).unwrap(); + std::fs::write(gitdir.join("ORIG_HEAD.lock"), "held by another git\n").unwrap(); + + let blocked = core::post_hooks::merge(repo.path(), "feature", false, false); + assert!(blocked.is_err()); + assert_eq!(rev(&repo, "HEAD"), base); + assert_eq!( + std::fs::read_to_string(gitdir.join("ORIG_HEAD")).unwrap(), + format!("{base}\n") + ); + + std::fs::remove_file(gitdir.join("ORIG_HEAD.lock")).unwrap(); + let merged = core::post_hooks::merge(repo.path(), "feature", false, false).unwrap(); + assert_eq!(merged.value.status, "fast_forward"); + assert_eq!(rev(&repo, "ORIG_HEAD"), base); +} + +#[test] +fn a_failing_post_hook_is_a_warning_and_the_operation_stands() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "one\n"); + let first = commit_all(&repo, "one"); + core::branch_create(repo.path(), "other", None, false).unwrap(); + repo.write("a.txt", "two\n"); + commit_all(&repo, "two"); + write_hook( + &default_hooks(&repo), + "post-checkout", + "echo checked out >&2\nexit 3", + ); + write_hook(&default_hooks(&repo), "post-merge", "echo merged\nexit 1"); + + let switched = core::post_hooks::checkout_branch(repo.path(), "other", false).unwrap(); + assert_eq!(rev(&repo, "HEAD"), first); + assert_eq!(switched.warnings.len(), 1); + let warning = &switched.warnings[0]; + assert_eq!(warning.hook, "post-checkout"); + assert_eq!(warning.status, Some(3)); + assert_eq!( + warning.message, + "The post-checkout hook failed (exit code 3)." + ); + assert_eq!(warning.output, "checked out"); + + let merged = core::post_hooks::merge(repo.path(), "master", false, false).unwrap(); + assert_eq!(merged.value.status, "fast_forward"); + assert_eq!(rev(&repo, "HEAD"), branch_tip(&repo, "master")); + assert_eq!(merged.warnings.len(), 1); + assert_eq!(merged.warnings[0].hook, "post-merge"); + assert_eq!(merged.warnings[0].status, Some(1)); + assert_eq!(merged.warnings[0].output, "merged"); +} + +#[test] +fn skipping_hooks_suppresses_every_post_hook() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "base\n"); + commit_all(&repo, "base"); + core::branch_create(repo.path(), "topic", None, false).unwrap(); + repo.write("m.txt", "m\n"); + commit_all(&repo, "m"); + record_post_hooks(&default_hooks(&repo), POST_HOOK_LOG); + + core::post_hooks::checkout_branch(repo.path(), "topic", true).unwrap(); + repo.write("t.txt", "t\n"); + commit_all(&repo, "t"); + core::post_hooks::rebase(repo.path(), "master", true) + .into_result() + .unwrap(); + repo.write("t.txt", "amended\n"); + core::stage_all(repo.path()).unwrap(); + core::post_hooks::amend(repo.path(), None, true).unwrap(); + repo.write("t.txt", "dirty\n"); + core::post_hooks::discard_file(repo.path(), "t.txt", true).unwrap(); + core::post_hooks::checkout_branch(repo.path(), "master", true).unwrap(); + let merged = core::post_hooks::merge(repo.path(), "topic", false, true).unwrap(); + assert_eq!(merged.value.status, "fast_forward"); + assert!(merged.warnings.is_empty()); + assert!(post_hook_runs(&repo).is_empty()); +} + +#[test] +fn group_pull_runs_post_merge_only_where_it_fast_forwarded() { + if !hooks_runnable() { + return; + } + let local = TempRepo::new(); + local.write("a.txt", "base\n"); + commit_all(&local, "base"); + let origin = bare_origin(&local); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + let behind = clone_of(&origin, &local, "group-behind"); + let current = clone_of(&origin, &local, "group-current"); + let failing = clone_of(&origin, &local, "group-failing"); + local.write("a.txt", "next\n"); + let next = commit_all(&local, "next"); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + core::pull(current.path(), "origin", None).unwrap(); + for repo in [&behind, ¤t] { + record_post_hooks(&default_hooks(repo), POST_HOOK_LOG); + } + write_hook( + &default_hooks(&failing), + "post-merge", + "echo install failed >&2\nexit 2", + ); + + let control = core::GroupUpdateControl::default(); + let base = rev(&behind, "HEAD"); + let pulled = core::group_update_controlled(behind.path(), true, &control).unwrap(); + assert_eq!(pulled.status, "ok"); + assert!(pulled.hook_warnings.is_empty()); + assert_eq!(rev(&behind, "ORIG_HEAD"), base); + assert_eq!(post_hook_runs(&behind), vec!["post-merge 0"]); + + let unchanged = core::group_update_controlled(current.path(), true, &control).unwrap(); + assert_eq!(unchanged.status, "up_to_date"); + assert!(post_hook_runs(¤t).is_empty()); + + let warned = core::group_update_controlled(failing.path(), true, &control).unwrap(); + assert_eq!(warned.status, "ok"); + assert_eq!(rev(&failing, "HEAD"), next); + assert_eq!(warned.hook_warnings.len(), 1); + assert_eq!(warned.hook_warnings[0].hook, "post-merge"); + assert_eq!(warned.hook_warnings[0].status, Some(2)); + assert_eq!(warned.hook_warnings[0].output, "install failed"); + + local.write("a.txt", "last\n"); + let last = commit_all(&local, "last"); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + let skipping = core::GroupUpdateControl::skipping_hooks(true); + for repo in [&behind, &failing] { + let result = core::group_update_controlled(repo.path(), true, &skipping).unwrap(); + assert_eq!(result.status, "ok"); + assert!(result.hook_warnings.is_empty()); + assert_eq!(rev(repo, "HEAD"), last); + } + assert!(post_hook_runs(&behind).is_empty()); + std::fs::remove_dir_all(origin).unwrap(); +} + +#[test] +fn group_cancel_does_not_warn_after_an_exit_zero_post_merge_hook() { + if !hooks_runnable() { + return; + } + let scene = PullScene::new(); + write_hook(&default_hooks(&scene.other), "post-merge", "exit 0"); + scene.upstream_commit("a.txt", "next\n", "next"); + let control = core::GroupUpdateControl::default(); + let pulled = core::group_update_controlled(scene.other.path(), true, &control).unwrap(); + assert_eq!(pulled.status, "ok"); + assert!(pulled.hook_warnings.is_empty()); + let receipts = control.cancel_results().unwrap(); + assert_eq!(receipts.len(), 1); + assert_eq!(receipts[0].result.status, "ok"); + assert!( + receipts[0].result.hook_warnings.is_empty(), + "{:?}", + receipts[0].result.hook_warnings + ); +} + +#[test] +fn group_pull_leaves_background_hooks_running_and_reports_their_state_on_cancel() { + use std::time::{Duration, Instant}; + + if !hooks_runnable() { + return; + } + #[cfg(unix)] + let can_stop = core::background_process_signals_available().unwrap(); + #[cfg(not(unix))] + let can_stop = cfg!(windows); + let local = TempRepo::new(); + local.write("a.txt", "base\n"); + commit_all(&local, "base"); + let origin = bare_origin(&local); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + let behind = clone_of(&origin, &local, "group-leftovers"); + let also_behind = clone_of(&origin, &local, "group-leftovers-cancel"); + for repo in [&behind, &also_behind] { + write_hook( + &default_hooks(repo), + "post-merge", + "(sleep 2; echo finished > .git/background-done) > /dev/null 2>&1 &", + ); + } + local.write("a.txt", "next\n"); + commit_all(&local, "next"); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + + let pulled = core::group_update(behind.path(), true).unwrap(); + assert_eq!(pulled.status, "ok"); + assert!(pulled.hook_warnings.is_empty()); + let marker = behind.dir.join(".git/background-done"); + assert!( + !marker.exists(), + "normal completion waited for background work" + ); + + let control = core::GroupUpdateControl::default(); + let pulled = core::group_update_controlled(also_behind.path(), true, &control).unwrap(); + assert_eq!(pulled.status, "ok"); + let cancel_marker = also_behind.dir.join(".git/background-done"); + assert!(!cancel_marker.exists()); + let receipts = control.cancel_results().unwrap(); + if can_stop { + assert!( + cancel_marker.exists(), + "Cancel returned before background work finished" + ); + } + assert_eq!(receipts.len(), 1); + assert_eq!(receipts[0].result.status, "ok"); + let warnings = &receipts[0].result.hook_warnings; + if !can_stop { + assert_eq!(warnings.len(), 1); + assert!(!warnings[0].timed_out); + assert!(warnings[0] + .message + .contains("could not confirm that all processes exited")); + } else { + assert!(warnings.is_empty()); + } + + let deadline = Instant::now() + Duration::from_secs(5); + while (!marker.exists() || !cancel_marker.exists()) && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(25)); + } + assert!( + marker.exists(), + "normal completion stopped the background job" + ); + assert!( + cancel_marker.exists(), + "Cancel stopped background work before the deadline" + ); + std::fs::remove_dir_all(origin).unwrap(); +} + +#[cfg(target_os = "linux")] +#[test] +fn group_cancel_does_not_see_a_hook_child_that_left_its_process_group() { + use std::time::{Duration, Instant}; + + if !hooks_runnable() { + return; + } + let local = TempRepo::new(); + local.write("a.txt", "base\n"); + commit_all(&local, "base"); + let origin = bare_origin(&local); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + let detached = clone_of(&origin, &local, "group-detached-hook"); + let other = clone_of(&origin, &local, "group-next-hook"); + write_hook( + &default_hooks(&detached), + "post-merge", + r#"setsid sh -c ' + echo ready > .git/detached-ready + attempts=0 + while [ "$attempts" -lt 200 ]; do + if [ -f .git/detached-release ]; then + echo finished > .git/detached-done + exit 0 + fi + sleep 0.05 + attempts=$((attempts + 1)) + done + ' /dev/null 2>&1 & + attempts=0 + while [ ! -f .git/detached-ready ] && [ "$attempts" -lt 100 ]; do + sleep 0.05 + attempts=$((attempts + 1)) + done + test -f .git/detached-ready"#, + ); + write_hook(&default_hooks(&other), "post-merge", "exit 0"); + local.write("a.txt", "next\n"); + commit_all(&local, "next"); + core::push(local.path(), "origin", None, false, false, true, false).unwrap(); + + let control = core::GroupUpdateControl::default(); + for repo in [&detached, &other] { + let pulled = core::group_update_controlled(repo.path(), true, &control).unwrap(); + assert_eq!(pulled.status, "ok"); + assert!( + pulled.hook_warnings.is_empty(), + "{:?}", + pulled.hook_warnings + ); + } + let receipts = control.cancel_results().unwrap(); + let marker = detached.dir.join(".git/detached-done"); + assert!(!marker.exists()); + detached.write(".git/detached-release", "release\n"); + let deadline = Instant::now() + Duration::from_secs(3); + while !marker.exists() && Instant::now() < deadline { + std::thread::sleep(Duration::from_millis(25)); + } + assert!( + marker.exists(), + "the detached child could still write after Cancel" + ); + + assert_eq!(receipts.len(), 2); + for receipt in receipts { + assert_eq!(receipt.result.status, "ok"); + assert!(receipt.result.hook_warnings.is_empty()); + } + std::fs::remove_dir_all(origin).unwrap(); +} + +#[test] +fn worktree_add_runs_post_checkout_inside_the_new_worktree() { + if !hooks_runnable() { + return; + } + let repo = TempRepo::new(); + repo.write("a.txt", "one\n"); + let head = commit_all(&repo, "one"); + let log = repo.dir.join(POST_HOOK_LOG); + write_hook( + &default_hooks(&repo), + "post-checkout", + &format!( + "echo \"post-checkout $*\" >> '{}'\ntouch post-checkout-ran-here", + shell_path(&log) + ), + ); + let (dir, _cleanup) = worktree_target(&repo, "post-checkout"); + + let added = core::post_hooks::worktree_add( + repo.path(), + &core::WorktreeAddRequest { + directory: dir.to_string_lossy().to_string(), + branch: "wt".to_string(), + create_branch: true, + base: None, + }, + false, + ) + .unwrap(); + assert!(added.warnings.is_empty()); + assert_eq!( + post_hook_runs(&repo), + vec![format!("post-checkout {ZERO_OID} {head} 1")] + ); + assert!(dir.join("post-checkout-ran-here").exists()); + assert!(!repo.dir.join("post-checkout-ran-here").exists()); +} diff --git a/apps/desktop/src/app/App.tsx b/apps/desktop/src/app/App.tsx index fd0951d1..fa7456d3 100644 --- a/apps/desktop/src/app/App.tsx +++ b/apps/desktop/src/app/App.tsx @@ -6,6 +6,7 @@ import { Spinner, TooltipProvider } from '@angkorgit/design-system'; import { SplashScreen } from './SplashScreen'; import { ConfirmHost } from '@/components/confirm'; import { HookFailureHost } from '@/components/hookFailure'; +import { HookWarningHost } from '@/components/hookWarnings'; import { ProfilePromptHost } from '@/components/profilePrompt'; import { ErrorBoundary } from '@/components/ErrorBoundary'; import { WelcomePage } from '@/features/repository/WelcomePage'; @@ -192,6 +193,7 @@ export function App() { + Promise } reportHookFailure({ repoPath: path, operation: 'push', error, retry: retryWithoutHooks }); return; } - toast.error(`${label} failed: ${(error as { message?: string }).message ?? error}`); + toastActionError(`${label} failed`, error); } })(); }; @@ -207,7 +208,7 @@ export function CommandPalette({ onRefresh }: { onRefresh: () => Promise } const outcome = await ipc.rebaseContinue(path); toastOutcome(outcome, 'Rebase continued'); } catch (error) { - toast.error(`Continue failed: ${(error as { message?: string }).message ?? error}`); + toastActionError('Continue failed', error); } await onRefresh(); })(); @@ -331,7 +332,7 @@ export function CommandPalette({ onRefresh }: { onRefresh: () => Promise } label="Push" onSelect={() => runPush('Push', (noVerify) => ipc.push(path, remote, false, false, true, headBranch, noVerify))} /> - {repoHooks.includes('pre-push') && ( + {repoHooks.found.includes('pre-push') && ( } label="Push without hooks" @@ -512,7 +513,7 @@ export function CommandPalette({ onRefresh }: { onRefresh: () => Promise } onSelect={() => { close(); void open(w.path).catch((error) => - toast.error(`Could not open worktree: ${(error as { message?: string }).message ?? error}`), + toastActionError('Could not open worktree', error), ); }} /> diff --git a/apps/desktop/src/components/HookFailedDialog.tsx b/apps/desktop/src/components/HookFailedDialog.tsx index 67c485c8..b52b7518 100644 --- a/apps/desktop/src/components/HookFailedDialog.tsx +++ b/apps/desktop/src/components/HookFailedDialog.tsx @@ -20,6 +20,14 @@ export interface HookFailureView { output: string; } +export interface HookWarningView { + hook: string; + timedOut: boolean; + message: string; + output: string; + repoName: string; +} + const COPY: Record = { commit: { outcome: 'Nothing was committed. Your message is still in the commit box.', @@ -35,6 +43,33 @@ const COPY: Record = { }, }; +function HookOutput({ output }: { output: string }) { + return output ? ( +
+      {output}
+    
+ ) : ( +

The hook printed nothing.

+ ); +} + +function CopyOutputButton({ output }: { output: string }) { + const copy = () => { + void navigator.clipboard.writeText(output).then( + () => toast.success('Copied the hook output'), + () => toast.error('Could not copy the hook output'), + ); + }; + return ( + + ); +} + export function HookFailedDialog({ failure, onRetry, @@ -45,12 +80,6 @@ export function HookFailedDialog({ onClose: () => void; }) { const output = useMemo(() => cleanCliOutput(failure?.output ?? ''), [failure?.output]); - const copy = () => { - void navigator.clipboard.writeText(output).then( - () => toast.success('Copied the hook output'), - () => toast.error('Could not copy the hook output'), - ); - }; const text = COPY[failure?.operation ?? 'commit']; return ( !next && onClose()}> @@ -61,20 +90,9 @@ export function HookFailedDialog({ {failure?.message} {text.outcome} - {output ? ( -
-            {output}
-          
- ) : ( -

The hook printed nothing.

- )} + - +
); } + +export function HookWarningDialog({ warning, onClose }: { warning: HookWarningView | null; onClose: () => void }) { + const output = useMemo(() => cleanCliOutput(warning?.output ?? ''), [warning?.output]); + return ( + !next && onClose()}> + + + + The {warning?.hook ?? 'post-checkout'} hook {warning?.timedOut ? 'timed out' : 'failed'} + + + {warning?.message} Nothing was undone in {warning?.repoName} + {warning?.timedOut ? '.' : ': git ignores the exit code of this hook.'} + + + + + + + + + + ); +} diff --git a/apps/desktop/src/components/Toolbar.tsx b/apps/desktop/src/components/Toolbar.tsx index 20807aab..652a9787 100644 --- a/apps/desktop/src/components/Toolbar.tsx +++ b/apps/desktop/src/components/Toolbar.tsx @@ -1,3 +1,4 @@ +import { toastActionError } from './actionError'; import { useEffect, useMemo, useState } from 'react'; import { chordLabels, groupRepos, parseChordId, pickRemote, pushSetsUpstream, type RecentRepository } from '@angkorgit/core'; import { useNavigate } from 'react-router-dom'; @@ -227,6 +228,8 @@ function RepoSwitcher() { ); } +const PULL_HOOKS = ['post-merge', 'post-rewrite', 'post-checkout']; + const STATE_LABELS: Record = { rebase: 'Rebase in progress', merge: 'Merge in progress', @@ -249,7 +252,7 @@ function StateActions({ onRefresh }: { onRefresh: () => Promise }) { const outcome = await ipc.rebaseContinue(path); toastOutcome(outcome, 'Rebase continued'); } catch (error) { - toast.error(`Continue failed: ${(error as { message?: string }).message ?? error}`); + toastActionError('Continue failed', error); } finish(); })(); @@ -457,7 +460,7 @@ export function Toolbar({ onRefresh }: { onRefresh: () => Promise }) { const editor = preferredEditor(editors, editorId); const [pushRejected, setPushRejected] = useState(null); - const [pullCheck, setPullCheck] = useState(false); + const [pullCheck, setPullCheck] = useState<{ noVerify: boolean } | null>(null); const pullWarning = pullWarningOf(pullPreview); const pullWarningLine = pullPreview ? pullWarningText(pullPreview) : null; @@ -487,11 +490,12 @@ export function Toolbar({ onRefresh }: { onRefresh: () => Promise }) { onNonFastForward(); return; } - const text = String((error as { message?: string }).message ?? error); - const [headline, ...rest] = text.split('\n'); - toast.error(`${label} failed: ${headline}`, { - description: rest.length > 0 ? {rest.join('\n')} : undefined, - duration: rest.length > 0 ? 12_000 : undefined, + toastActionError(`${label} failed`, error, (text) => { + const [headline, ...rest] = text.split('\n'); + toast.error(`${label} failed: ${headline}`, { + description: rest.length > 0 ? {rest.join('\n')} : undefined, + duration: rest.length > 0 ? 12_000 : undefined, + }); }); } finally { setBusy(null); @@ -591,15 +595,16 @@ export function Toolbar({ onRefresh }: { onRefresh: () => Promise }) { /> setPullCheck(false)} + onClose={() => setPullCheck(null)} onPull={() => { - setPullCheck(false); - void run('Pull', () => ipc.pull(repo.path, remote)); + const noVerify = pullCheck?.noVerify ?? false; + setPullCheck(null); + void run(noVerify ? 'Pull without hooks' : 'Pull', () => ipc.pull(repo.path, remote, undefined, noVerify)); }} onStash={(paths) => { - setPullCheck(false); + setPullCheck(null); openDialog('createStash', { paths }); }} /> @@ -644,7 +649,7 @@ export function Toolbar({ onRefresh }: { onRefresh: () => Promise }) { size="sm" className="rounded-r-none" disabled={!!busy} - onClick={() => (pullWarning ? setPullCheck(true) : void run('Pull', () => ipc.pull(repo.path, remote)))} + onClick={() => (pullWarning ? setPullCheck({ noVerify: false }) : void run('Pull', () => ipc.pull(repo.path, remote)))} > Pull @@ -657,7 +662,7 @@ export function Toolbar({ onRefresh }: { onRefresh: () => Promise }) { )} - + open && repoHooks.refresh()}>