Skip to main content

amont_runtime/
install.rs

1//! `amont install` — put the binary somewhere stable and wire up the shims.
2//!
3//! This was a Makefile recipe. It moved here for one reason: the guard below
4//! decides whether a directory is safe to delete, it has been got wrong TWICE —
5//! both times overwriting tracked source files with machine-specific paths — and
6//! shell that runs on one platform cannot be tested on three.
7//!
8//! Everything here is `std`. The commit path's dependency posture
9//! (`scripts/check-no-deps.sh`) is unchanged: this adds code, not crates.
10//!
11//! ## Why it is a subcommand and not a script
12//!
13//! A `.ps1` for Windows plus a Makefile for Unix would be two implementations of
14//! that guard, in two languages, one of them untested — for a routine whose
15//! failure mode is deleting your work. And `make` is not the Unix-only detail it
16//! looks like: Git for Windows ships `bash`, `sh` and coreutils but NOT `make`,
17//! so the dependency was the problem rather than the shell.
18//!
19//! The shim text is embedded with `include_str!`, so an installed binary carries
20//! its own shims and can install from any directory.
21
22use std::path::{Path, PathBuf};
23use std::process::Command;
24
25use crate::hookfile::{self, HookFile, Refuse, Staged, SwapFailure};
26use crate::ui::{error_sign, highlight, valid_sign, warning_sign};
27
28/// The token every shim carries until it is baked.
29pub const PLACEHOLDER: &str = "__AMONT_BIN__";
30
31/// The one shim. All four git-invoked hooks are the same file — it passes its
32/// own filename through — and `shims_on_disk_match_the_embedded_one` keeps the
33/// repository's `templates/hooks/` honest against this copy.
34///
35/// The canonical text lives INSIDE this crate, and that is a packaging
36/// constraint rather than a preference. It used to be
37/// `include_str!("../../../templates/hooks/pre-commit")`, reaching up to the
38/// repository root — which works in a checkout and cannot work in a published
39/// crate, because `cargo package` tars up this directory and nothing above it.
40/// The tarball compiled nowhere: `couldn't read src/../../../templates/hooks/
41/// pre-commit`. crates.io is immutable, so that would have been a broken
42/// release that could only be yanked, never fixed in place.
43///
44/// The repository's `templates/hooks/` still holds the four installable copies
45/// — that directory IS the product for anyone pointing `init.templateDir` at a
46/// clone, and it has to be real files rather than symlinks because Git for
47/// Windows materialises those as text files containing a path.
48pub const SHIM: &str = include_str!("../templates/hooks/pre-commit");
49
50/// The ownership question, and every other "may we touch this file?" answer,
51/// now live in [`crate::hookfile`] — one implementation that fails closed,
52/// rather than the three `unwrap_or(false)` one-liners that used to answer it
53/// here, in `fleet::scan` and in `fleet::fix`.
54///
55/// Re-exported rather than moved outright because both fleet call sites and the
56/// dashboard's `shim` module name them through this path, and a rename would be
57/// churn in files this change has no business editing.
58pub use crate::hookfile::{is_our_shim, SHIM_MARKER};
59
60/// The hook names git actually invokes, and so the only files we install.
61pub const DISPATCHERS: [&str; 5] = [
62    "commit-msg",
63    "post-commit",
64    "pre-commit",
65    "pre-push",
66    "prepare-commit-msg",
67];
68
69/// What may be done with a candidate template directory.
70///
71/// `~/.config/git/git-templates` is commonly a SYMLINK to a checkout of this
72/// repository, in which case "installing" there means deleting and overwriting
73/// TRACKED files.
74///
75/// Comparing the path against the source tree is NOT enough, and that is the
76/// mistake that caused both incidents: run the install from a git worktree and
77/// the two resolve to different paths — a different checkout of the same repo —
78/// so a path comparison says "not the source" and clobbers the main checkout.
79/// Asking git is the reliable test whatever route the symlink took.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub enum TemplateDir {
82    /// The path does not exist and could not be created.
83    Unresolvable,
84    /// No git to ask. Refuse rather than guess.
85    NoGit,
86    /// It holds tracked files: it IS a checkout. Nothing to install — `git init`
87    /// already reads its templates from there, and the shims keep their
88    /// placeholder and resolve the binary at run time.
89    IsCheckout,
90    /// Inside a checkout but tracking nothing here. Still not ours to empty.
91    InsideCheckout,
92    /// An ordinary directory. Safe to populate.
93    Safe,
94}
95
96fn git_ok(dir: &Path, args: &[&str]) -> bool {
97    Command::new("git")
98        .arg("-C")
99        .arg(dir)
100        .args(args)
101        .stdout(std::process::Stdio::null())
102        .stderr(std::process::Stdio::null())
103        .status()
104        .map(|s| s.success())
105        .unwrap_or(false)
106}
107
108/// Decide what may be done with `dir`. Never mutates anything.
109pub fn classify_dir(dir: &Path) -> TemplateDir {
110    let Ok(real) = dir.canonicalize() else {
111        return TemplateDir::Unresolvable;
112    };
113    if Command::new("git").arg("--version").output().is_err() {
114        return TemplateDir::NoGit;
115    }
116    // `ls-files --error-unmatch .` is the question that matters: does git track
117    // anything HERE? A directory can be inside a checkout and still be
118    // untracked scratch space, which the next test separates.
119    if git_ok(&real, &["ls-files", "--error-unmatch", "."]) {
120        return TemplateDir::IsCheckout;
121    }
122    if git_ok(&real, &["rev-parse", "--git-dir"]) {
123        return TemplateDir::InsideCheckout;
124    }
125    TemplateDir::Safe
126}
127
128/// Write the absolute binary path into a shim.
129///
130/// A plain global replace, which is why the shim's own comment must not spell
131/// the token out — it did, and every baked shim carried an "explanation" whose
132/// text was a machine path. Idempotent: re-baking a baked shim is a no-op
133/// because the token is gone.
134pub fn bake(shim: &str, bin: &str) -> String {
135    shim.replace(PLACEHOLDER, bin)
136}
137
138/// Whether the shim will accept `bin` as its baked path.
139///
140/// The shim rejects anything relative before it ever touches the filesystem,
141/// and this is the same rule stated where the value is produced. Git runs a
142/// hook with the working tree as the current directory, so a relative baked
143/// path is a question asked of the REPOSITORY — and a clone that ships a file
144/// by that name gets to answer it. Baking one would install a hook that either
145/// cannot resolve its binary or resolves it to somebody else's, so refuse here
146/// too, where the message can say which path was wrong.
147///
148/// Absolute means POSIX `/…` or a Windows drive path (`C:\…`, `C:/…`).
149pub fn is_bakeable(bin: &str) -> bool {
150    if bin.is_empty() || bin == PLACEHOLDER {
151        return false;
152    }
153    let b = bin.as_bytes();
154    if b[0] == b'/' {
155        return true;
156    }
157    b.len() > 2 && b[0].is_ascii_alphabetic() && b[1] == b':' && (b[2] == b'/' || b[2] == b'\\')
158}
159
160/// An absolute form of `p`, for baking.
161///
162/// NOT `canonicalize`: that returns an extended-length path (`\\?\C:\…`) on
163/// Windows, which `sh` cannot test, and it fails outright on a path that does
164/// not exist yet. `$AMONT_BIN_DIR` may be relative, which is the route by
165/// which a relative path could reach a shim at all.
166fn absolute(p: &Path) -> PathBuf {
167    if p.is_absolute() {
168        return p.to_path_buf();
169    }
170    match std::env::current_dir() {
171        Ok(cwd) => cwd.join(p),
172        Err(_) => p.to_path_buf(),
173    }
174}
175
176/// The one directory an UNBAKED shim looks in, hardcoded in the shim itself.
177///
178/// Deliberately NOT `bin_dir()`, and the difference is the whole point of
179/// `warn_if_unbaked_cannot_resolve`. `bin_dir()` answers "where should install
180/// PUT the binary?" and honours `$AMONT_BIN_DIR`. This answers "where will a
181/// shim that never got a path baked into it LOOK?", which is a constant in a
182/// POSIX sh file and cannot be configured at all.
183///
184/// `$AMONT_BIN_DIR` is deliberately not wired into the shim to close that
185/// gap. It is an install-time question answered in the shell where `amont
186/// install` ran; the shim runs inside git's environment during a commit, where
187/// that variable is almost never set — so honouring it there would ship a knob
188/// that looks like it works and silently does not. The runtime override already
189/// exists and is `$GIT_HOOKS_BIN`; a second variable able to redirect which
190/// binary executes on every commit would double that surface for nothing.
191///
192/// Not "XDG", either: the XDG Base Directory spec defines no binary directory.
193/// `~/.local/bin` is simply the widely-observed convention.
194fn unbaked_lookup_dir() -> PathBuf {
195    home().join(".local").join("bin")
196}
197
198/// Say so when the binary went somewhere an unbaked shim will never look.
199///
200/// Two supported choices stop composing when made together. A template dir that
201/// IS the checkout keeps the placeholder on purpose — those shims resolve the
202/// binary at run time from [`unbaked_lookup_dir`]. Install to a custom
203/// `$AMONT_BIN_DIR` as well and nothing baked a path, while the one path the
204/// shim knows is not where the binary went.
205///
206/// Nothing is silently skipped — the shim prints what it looked at and exits 1,
207/// which fails the commit loudly. But it fails at somebody's next commit, in a
208/// repository they have not thought about since, and the cause is a decision
209/// made here. So it is said here.
210fn warn_if_unbaked_cannot_resolve(binary: &str) {
211    let looked = unbaked_lookup_dir();
212    let placed = Path::new(binary).parent();
213
214    // Compare RESOLVED paths, and require both to resolve. `a.ok() == b.ok()`
215    // would read `None == None` as "the same directory" — the shape of a bug
216    // this module has already had once, in `already_there`.
217    let reachable = placed.is_some_and(|p| {
218        matches!(
219            (p.canonicalize(), looked.canonicalize()),
220            (Ok(a), Ok(b)) if a == b
221        )
222    });
223    if reachable {
224        return;
225    }
226
227    println!();
228    println!(
229        "{} the binary is at {}, which an unbaked shim will not find.",
230        warning_sign(),
231        highlight(binary)
232    );
233    println!(
234        "    Shims here keep the placeholder, and they look only in {}.",
235        looked.display()
236    );
237    println!("    Either link it where they look:");
238    println!("      ln -s {} {}", binary, looked.join("amont").display());
239    println!("    or set GIT_HOOKS_BIN in the environment git runs hooks with:");
240    println!("      export GIT_HOOKS_BIN={binary}");
241}
242
243/// `~/.local/bin`, or `$AMONT_BIN_DIR`.
244pub fn bin_dir() -> PathBuf {
245    if let Some(d) = std::env::var_os("AMONT_BIN_DIR") {
246        return PathBuf::from(d);
247    }
248    home().join(".local").join("bin")
249}
250
251/// `$XDG_CONFIG_HOME/git/git-templates/templates/hooks`.
252pub fn template_hooks_dir() -> PathBuf {
253    let base = std::env::var_os("XDG_CONFIG_HOME")
254        .map(PathBuf::from)
255        .unwrap_or_else(|| home().join(".config"));
256    base.join("git")
257        .join("git-templates")
258        .join("templates")
259        .join("hooks")
260}
261
262fn home() -> PathBuf {
263    std::env::var_os("HOME")
264        .or_else(|| std::env::var_os("USERPROFILE"))
265        .map(PathBuf::from)
266        .unwrap_or_else(|| PathBuf::from("."))
267}
268
269/// The name to install under. Windows builds `amont.exe`, and a shim testing
270/// `[ -x .../amont ]` is false for it.
271fn installed_name() -> String {
272    match std::env::current_exe() {
273        Ok(p) => name_for(&p),
274        Err(_) => "amont".to_string(),
275    }
276}
277
278/// Split from `installed_name` so it can be tested on every platform rather
279/// than only the one that produces a `.exe`. A `cfg!(windows)` assertion is
280/// vacuous on the machine most of this is written on.
281fn name_for(exe: &Path) -> String {
282    match exe.extension().and_then(|e| e.to_str()) {
283        Some(e) if !e.is_empty() => format!("amont.{e}"),
284        _ => "amont".to_string(),
285    }
286}
287
288/// Hook files in `dir` that exist and are NOT ours, each with its reason.
289///
290/// `install` used to write all four unconditionally, which silently destroyed a
291/// `commit-msg` somebody had written themselves. That is the same failure as the
292/// two that overwrote tracked files, one directory along, and it had no guard at
293/// all — the fleet's `fix` planner has one and the per-repo installer never did.
294///
295/// It carries the [`HookFile`] rather than only the name because "commit-msg is
296/// not ours" sends somebody to diff a file against a shim they have never seen,
297/// while "commit-msg is not valid UTF-8 — a compiled hook, probably" ends the
298/// question. The old version could not have said either: it read the file as a
299/// string, and a file it could not read came back as NOT foreign.
300fn foreign_hooks(dir: &Path) -> Vec<(&'static str, HookFile)> {
301    DISPATCHERS
302        .into_iter()
303        .map(|name| (name, hookfile::classify(&dir.join(name))))
304        .filter(|(_, what)| !matches!(what, HookFile::Absent | HookFile::Ours))
305        .collect()
306}
307
308/// One dispatcher that landed, and what stood at that path before it.
309///
310/// `replaced` exists so `--force` can say what it took. It printed
311/// "baked 4 shims" and nothing else, which is a receipt for an act whose whole
312/// point is that it destroys something — the user typed `--force` precisely
313/// because there was a file there, and the one thing the output never said was
314/// which files or what they were.
315#[derive(Debug)]
316pub struct Written {
317    pub path: PathBuf,
318    pub replaced: HookFile,
319}
320
321/// Why a set of shims was not written.
322#[derive(Debug)]
323pub enum ShimWriteError {
324    /// One or more paths are not ours to write. Every refusal is carried, not
325    /// just the first: somebody about to run `--force` should see all four.
326    Refused(Vec<Refuse>),
327    /// A failure before any destination was touched — an unbakeable path, or a
328    /// staging write that could not happen (no space, no permission).
329    Preflight { at: PathBuf, error: std::io::Error },
330    /// Staging succeeded and a rename did not. The only failure mode that can
331    /// leave a directory partly written, which is why it carries the lists.
332    Swap(SwapFailure),
333}
334
335impl std::fmt::Display for ShimWriteError {
336    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
337        match self {
338            ShimWriteError::Refused(refusals) => {
339                writeln!(f, "refusing to write {} hooks:", refusals.len())?;
340                for (i, r) in refusals.iter().enumerate() {
341                    if i > 0 {
342                        writeln!(f)?;
343                    }
344                    write!(f, "    {}", r.explain())?;
345                }
346                Ok(())
347            }
348            ShimWriteError::Preflight { at, error } => {
349                write!(f, "cannot prepare {}: {error}", at.display())
350            }
351            ShimWriteError::Swap(s) => write!(f, "{s}"),
352        }
353    }
354}
355
356/// Write the four dispatchers into `dir`: guard ALL, stage ALL, then swap.
357///
358/// Three phases, in that order, because the posture `bake_repo_hooks` has
359/// claimed since it was written — "fail closed, and for the whole repository
360/// rather than per file: a partial install is how a repo ends up with two of
361/// four hooks and no way to tell" — was a comment over a loop that checked one
362/// file and then wrote it, four times. A refusal on the third hook came after
363/// two had already been overwritten.
364///
365/// Now: every path is guarded before any body is written, and every body is
366/// written before any destination is touched. A refusal anywhere means nothing
367/// at all was written; a staging failure likewise. Only the swap can leave a
368/// directory partly done, and that is reported as exactly which files landed
369/// and which did not (see [`SwapFailure`]) rather than as a count.
370///
371/// Returns what was written and what each write replaced, so `--force` can name
372/// what it took.
373fn write_shims(dir: &Path, bin: &str, force: bool) -> Result<Vec<Written>, ShimWriteError> {
374    // Fail closed rather than write four hooks that resolve to nothing — or, if
375    // the repository happens to hold a file by that name, to something.
376    if !is_bakeable(bin) {
377        return Err(ShimWriteError::Preflight {
378            at: dir.to_path_buf(),
379            error: std::io::Error::other(format!(
380                "refusing to bake {bin:?}: the shim takes an absolute path only"
381            )),
382        });
383    }
384    let baked = bake(SHIM, bin);
385
386    // Phase 1 — guard every path. Nothing has been written and nothing will be
387    // if a single one of these refuses.
388    let mut allowed: Vec<(PathBuf, HookFile)> = Vec::new();
389    let mut refusals: Vec<Refuse> = Vec::new();
390    for name in DISPATCHERS {
391        let path = dir.join(name);
392        match hookfile::guard_write(&path, force) {
393            Ok(what) => allowed.push((path, what)),
394            Err(r) => refusals.push(r),
395        }
396    }
397    if !refusals.is_empty() {
398        return Err(ShimWriteError::Refused(refusals));
399    }
400
401    // Phase 2 — stage every body. A `Staged` that never lands removes its own
402    // temporary on drop, so an error here leaves the directory as it was.
403    let mut staged: Vec<Staged> = Vec::new();
404    for (path, _) in &allowed {
405        match hookfile::stage(path, &baked, true) {
406            Ok(s) => staged.push(s),
407            Err(error) => {
408                return Err(ShimWriteError::Preflight {
409                    at: path.clone(),
410                    error,
411                });
412            }
413        }
414    }
415
416    // Phase 3 — swap. Renames, so a symlinked destination is REPLACED rather
417    // than written through.
418    hookfile::commit_all(staged).map_err(ShimWriteError::Swap)?;
419    Ok(allowed
420        .into_iter()
421        .map(|(path, replaced)| Written { path, replaced })
422        .collect())
423}
424
425/// For the installed BINARY only — shims get their mode from `hookfile::stage`,
426/// before they are anywhere a hook could be dispatched from.
427#[cfg(unix)]
428fn make_executable(p: &Path) -> std::io::Result<()> {
429    use std::os::unix::fs::PermissionsExt;
430    std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o755))
431}
432
433#[cfg(not(unix))]
434fn make_executable(_p: &Path) -> std::io::Result<()> {
435    Ok(()) // Windows has no execute bit; git runs the shim through sh regardless.
436}
437
438/// Install: copy this binary somewhere stable, populate the template directory
439/// if that is safe, and bake the current repository's hooks.
440///
441/// Three steps, three functions. This was one 88-line body whose own comments
442/// numbered its sections — which is the tell that the sections wanted to be
443/// functions.
444pub fn run(force: bool) -> Result<(), String> {
445    let binary = install_binary()?;
446    populate_template_dir(&binary, force)?;
447    bake_repo_hooks(&binary, force)?;
448    offer_trust();
449    offer_agents_md();
450    point_at_setup();
451    Ok(())
452}
453
454/// `amont init` — wire up THIS repository, and touch nothing else.
455///
456/// The verb a package manager can call. `"prepare": "amont init"` in a
457/// `package.json` means a teammate who clones and runs `npm install` gets the
458/// hooks, which is the ergonomic husky has and this project did not.
459///
460/// ## Why `install` could not be that verb
461///
462/// Every one of its three extra steps is wrong for something that runs on every
463/// teammate's install, and the third is a hang:
464///
465///   * `install_binary` copies into `~/.local/bin` — a machine-level write from
466///     `npm install`;
467///   * `populate_template_dir` writes `~/.config/git/git-templates`, so a
468///     package manager would be arranging for every FUTURE clone to get hooks;
469///   * `offer_trust` calls `trust::confirm`, which opens `/dev/tty`. In a
470///     terminal that succeeds and BLOCKS, so `npm install` would stop dead on a
471///     prompt about a manifest the user has not read.
472///
473/// So this does one thing: bake four shims into the repository's own hooks
474/// directory.
475///
476/// ## What it bakes, and why not the PATH hit
477///
478/// `current_exe()`, always — never [`install_binary`]'s "is it already on
479/// `PATH`?" branch. Under npm the answer to that question is
480/// `node_modules/.bin/amont`, which is the **JS wrapper**: baking it would put a
481/// node process in front of every single commit, on a tool whose start-up cost
482/// is a stated feature. `current_exe()` is the native binary inside the platform
483/// package, which is what should run.
484///
485/// ## Silence, and its limits
486///
487/// Outside a git repository this reports nothing and exits 0. `npm install`
488/// legitimately runs where there is no `.git` — from a tarball, inside a Docker
489/// build, in CI — and failing there would make the package uninstallable in all
490/// three. It stays LOUD about everything else: a redirect, an unwritable
491/// directory, a foreign hook, and a repository git REFUSES to answer about
492/// (dubious ownership in a container bind mount, an unreadable `.git/config`)
493/// all still fail, because those are repositories where somebody believes they
494/// have hooks and does not. The silence is git's verdict, never git's absence.
495pub fn init() -> Result<(), String> {
496    let hooks = match repo_hooks() {
497        RepoHooks::Own(dir) => dir,
498        RepoHooks::Redirected { to, own } if redirect_is_hostile(&to, &own) => {
499            return Err(redirected_message(&to, &own))
500        }
501        RepoHooks::Redirected { to, .. } => to,
502        // The one silent exit, and the only one: git itself said this is not a
503        // repository.
504        RepoHooks::Nowhere => return Ok(()),
505        RepoHooks::Unanswerable { why } => {
506            return Err(format!(
507                "{} git would not say where this repository's hooks live —\n    {}\n    \
508                 Hooks were NOT installed.",
509                error_sign(),
510                crate::ui::sanitize(&why)
511            ))
512        }
513    };
514
515    let me =
516        std::env::current_exe().map_err(|e| format!("cannot locate the running binary: {e}"))?;
517    // `absolute` rather than `canonicalize`: the shim needs an absolute path
518    // and nothing more, so there is no reason to touch the filesystem again.
519    //
520    // It does NOT keep us off pnpm's `.pnpm/<pkg>@<version>/…` store path, and
521    // an earlier version of this comment claimed it did. By the time this runs,
522    // the JS wrapper has already resolved the binary through `require.resolve`,
523    // which returns the REAL path — and `current_exe()` resolves symlinks
524    // besides. A pnpm install bakes the versioned store path, verified.
525    //
526    // Which is fine, and worth saying why rather than leaving the next reader
527    // to worry about it: `prepare` runs on every install, so a version bump
528    // re-bakes before anything can dispatch against the old path — and if one
529    // ever does go missing, the shim's resolution order falls through to
530    // `~/.local/bin` and then `PATH`, and fails LOUDLY rather than skipping a
531    // check, which is the property that actually matters.
532    let binary = absolute(&me);
533    let binary = binary.to_string_lossy().into_owned();
534    if !is_bakeable(&binary) {
535        return Err(format!(
536            "{} cannot bake {binary:?} — the shim takes an absolute path only",
537            error_sign()
538        ));
539    }
540
541    std::fs::create_dir_all(&hooks)
542        .map_err(|e| format!("cannot create {}: {e}", hooks.display()))?;
543
544    // `force: false`. A hook somebody else wrote is theirs, and `init` runs
545    // unattended — there is no one at the keyboard to have decided otherwise.
546    let written = write_shims(&hooks, &binary, false)
547        .map_err(|e| format!("cannot write shims to {}: {e}", hooks.display()))?;
548    println!(
549        "{} amont: {} hooks in {}",
550        valid_sign(),
551        written.len(),
552        hooks.display()
553    );
554    Ok(())
555}
556
557/// Name the commit-style settings, once, at the moment somebody acquires them.
558///
559/// A PRINT, never a prompt. `install` has to remain answerable by nobody: it
560/// runs under `amont-fleet install --root`, in provisioning scripts, and not
561/// at all for the `init.templateDir` users whose hooks arrive with a clone. A
562/// third question would break all three; a line of output breaks none of them,
563/// and it puts the dial in front of the one person guaranteed to be reading.
564fn point_at_setup() {
565    let s = crate::commit_style::Style::resolve();
566    println!(
567        "  commit style: gitmoji {}, subject ≤{}, description ≤{} — `amont setup` to change",
568        s.gitmoji.as_str(),
569        s.subject_max,
570        s.description_max
571    );
572}
573
574/// Ask about the manifest, once, at the moment somebody is already deciding
575/// about this repository.
576///
577/// `direnv` has to ask lazily on `cd` because it has no install step to hang
578/// the question from. We have one — so this is a single question, shown with
579/// the declarations in view, and declining still leaves the built-ins working.
580///
581/// Never blocks and never fails the install: a repository that declares nothing
582/// says nothing, and a non-interactive install simply reports the state.
583fn offer_trust() {
584    // No repository, no manifest to ask about. `repo_root()` answered "." and
585    // this went looking for `./amont.conf` in whatever directory the
586    // install was run from — a file it would then have offered to trust ON
587    // BEHALF of a repository that does not exist.
588    let Ok(root) = crate::hooks::common::repo_root_checked() else {
589        return;
590    };
591    let root = Path::new(&root);
592    let state = crate::trust::state(root);
593    if matches!(
594        state,
595        crate::trust::State::NoManifest | crate::trust::State::Trusted
596    ) {
597        return;
598    }
599
600    println!();
601    println!(
602        "{} {} declares checks that would run on your commits:",
603        warning_sign(),
604        crate::manifest::MANIFEST
605    );
606    // Read ONCE, then show and fingerprint that same buffer. `confirm()` blocks
607    // on a keypress, sometimes for several seconds, and a file rewritten in
608    // that window must not be trusted under the guise of the content that was
609    // displayed — `record_verified` re-checks this fingerprint once the answer
610    // is in. Reading separately to show and to hash would leave the same gap
611    // one step earlier: the listing approved need not be the one recorded.
612    let manifest = root.join(crate::manifest::MANIFEST);
613    let Ok(source) = std::fs::read(&manifest) else {
614        println!(
615            "{} could not read {}",
616            warning_sign(),
617            crate::manifest::MANIFEST
618        );
619        return;
620    };
621    print!(
622        "{}",
623        crate::trust::describe_source(&String::from_utf8_lossy(&source))
624    );
625    let Some(fp) = crate::trust::fingerprint_bytes(root, &source) else {
626        println!(
627            "{} could not hash {}",
628            warning_sign(),
629            crate::manifest::MANIFEST
630        );
631        return;
632    };
633    if crate::trust::confirm("    Trust them? (y/N) ") {
634        match crate::trust::record_verified(root, &fp) {
635            Ok(()) => println!("{} trusted ({fp})", valid_sign()),
636            Err(e) => println!("{} {e}", warning_sign()),
637        }
638    } else {
639        println!("    Left untrusted. The built-ins still run; these do not.");
640        println!("    Change your mind with `amont trust`.");
641    }
642}
643
644/// Ask about `AGENTS.md`, once, right where `offer_trust` asks about the
645/// manifest — same reasoning, same shape: a single question with an install
646/// step to hang it from, and declining changes nothing about how the hooks
647/// themselves run.
648///
649/// This is the first thing `install` would write to TRACKED repo content —
650/// everything else here lives in `.git/hooks` (never tracked) or a
651/// machine-local path (`~/.local/bin`, the XDG template dir). That is exactly
652/// why it is a confirm, not a silent write: `crate::agents_md::write` is
653/// marker-scoped and safe to re-run, but "safe to overwrite" is not the same
654/// promise as "yours to write unasked."
655///
656/// Never blocks and never fails the install: skips silently when there is
657/// nothing to offer, and a non-interactive install simply leaves the
658/// question unanswered — `trust::confirm` already treats no tty as "no".
659fn offer_agents_md() {
660    // Same reason as `offer_trust`: with `repo_root()`'s "." fallback, an
661    // install run outside a repository offered to write an AGENTS.md into the
662    // current directory — the one thing `install` writes to TRACKED content,
663    // aimed at a directory nobody said was a project.
664    let Ok(root) = crate::hooks::common::repo_root_checked() else {
665        return;
666    };
667    let path = Path::new(&root).join("AGENTS.md");
668    match crate::agents_md::check(&path) {
669        Ok(crate::agents_md::CheckResult::MatchesGenerated) => return,
670        Ok(_) => {}
671        // Malformed markers: nothing this prompt can safely offer to fix.
672        Err(_) => return,
673    }
674
675    println!();
676    println!(
677        "{} AGENTS.md can point coding agents at `amont list --json` \
678         instead of leaving them to discover these checks the hard way:",
679        warning_sign()
680    );
681    if crate::trust::confirm("    Add it? (y/N) ") {
682        match crate::agents_md::write(&path) {
683            Ok(()) => println!("{} wrote {}", valid_sign(), path.display()),
684            Err(e) => println!("{} {e}", warning_sign()),
685        }
686    } else {
687        println!("    Left as-is. Change your mind with `amont agents-md`.");
688    }
689}
690
691/// Where this binary can already be found on `PATH`, if it can.
692///
693/// Returns the path as `PATH` exposes it — deliberately NOT the resolved one.
694/// Homebrew's `/usr/local/bin/amont` is a symlink into
695/// `/usr/local/Cellar/amont/<version>/bin/`, and that Cellar path is
696/// version-specific and removed on upgrade. Baking it would pin every repo to a
697/// version that is about to be deleted, which is worse than the copy this
698/// function exists to avoid. The same is true of any versioned store — nix,
699/// asdf, mise.
700///
701/// So the comparison is canonical (to recognise ourselves through the symlink)
702/// while the value returned is the entry that led here. That also makes the
703/// answer correct whichever way `current_exe()` behaves: it resolves symlinks
704/// on some platforms and libcs and not others, and this never has to care.
705fn on_path_already(me: &Path) -> Option<PathBuf> {
706    let me_real = me.canonicalize().ok()?;
707    let name = installed_name();
708    let path = std::env::var_os("PATH")?;
709    std::env::split_paths(&path)
710        .map(|dir| dir.join(&name))
711        .filter(|cand| !in_a_build_dir(cand))
712        .find(|cand| cand.canonicalize().is_ok_and(|real| real == me_real))
713        .map(|cand| absolute(&cand))
714        .filter(|abs| is_bakeable(&abs.to_string_lossy()))
715}
716
717/// Whether `p` sits inside a cargo build directory.
718///
719/// "On PATH" alone is not the question — the question is whether the path will
720/// still be there tomorrow, and a build directory is precisely the one that
721/// will not. `cargo clean`, or any rebuild, and the shims baked against it
722/// resolve nothing.
723///
724/// This is not hypothetical and it is not only about `cargo run`: **cargo
725/// prepends the build directory to PATH when it runs tests on Windows**, so
726/// `target/debug` genuinely appears there. That took out four existing install
727/// tests on the Windows runner and nowhere else, which is a fair description of
728/// how the loose predicate would have failed a user, too.
729///
730/// `CACHEDIR.TAG` is cargo's own marker for the directory, written since 1.55
731/// and standardised for exactly this — "a program wrote this, do not treat it
732/// as durable". Asking for it beats matching on the name `target`, which is
733/// configurable and is also an ordinary word for a directory. Bounded to a few
734/// levels so a stray tag high up somebody's home directory cannot disqualify
735/// every path on the system.
736fn in_a_build_dir(p: &Path) -> bool {
737    p.ancestors()
738        .skip(1)
739        .take(4)
740        .any(|dir| dir.join("CACHEDIR.TAG").is_file())
741}
742
743/// Copy the running binary to a stable location, and return where it now lives.
744fn install_binary() -> Result<String, String> {
745    let me =
746        std::env::current_exe().map_err(|e| format!("cannot locate the running binary: {e}"))?;
747
748    // A binary a package manager already put on PATH is not ours to copy.
749    //
750    // The copy below exists for `./target/release/amont install`, where the
751    // binary sits in a directory `cargo clean` will delete — baking that path
752    // would install hooks that stop resolving the next time somebody builds.
753    // For `brew install`, `cargo install` or a distro package, the opposite is
754    // true: the binary is already somewhere stable, and copying it produces a
755    // SECOND, unmanaged copy that the package manager will never update again.
756    //
757    // That is not hypothetical. It is what this machine was in: `brew upgrade`
758    // would have refreshed /usr/local/bin while every repo stayed baked to a
759    // frozen copy in ~/.local/bin — the same staleness the copy is meant to
760    // prevent, arrived at from the other direction.
761    //
762    // `$AMONT_BIN_DIR` is checked first because setting it IS the request to
763    // put the binary somewhere specific, and honouring it costs nothing.
764    if std::env::var_os("AMONT_BIN_DIR").is_none() {
765        if let Some(stable) = on_path_already(&me) {
766            let shown = stable.to_string_lossy().into_owned();
767            println!("{} using {}", valid_sign(), highlight(&shown));
768            println!("    already on PATH, so nothing was copied — an upgrade there");
769            println!("    reaches every repository without reinstalling.");
770            return Ok(shown);
771        }
772    }
773
774    let dir = bin_dir();
775    std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
776
777    // Absolute from here on: this path is what gets baked into every shim, and
778    // `bin_dir()` honours `$AMONT_BIN_DIR`, which may be relative.
779    let target = absolute(&dir.join(installed_name()));
780    // Copying a running binary over ITSELF fails on some platforms and is
781    // pointless on all of them.
782    //
783    // `me.canonicalize().ok() == target.canonicalize().ok()` is the version
784    // this replaces, and it was wrong in the one case that matters: when the
785    // TARGET does not exist yet — a first install, the whole point of the
786    // step — `canonicalize` returns `Err`, both sides are `None`, `None ==
787    // None` is true, and the copy was skipped. The binary was never installed,
788    // and `install` printed "installed <path>" for a file that was not there.
789    // Every shim then baked that path and resolved nothing. Two `Ok`s that
790    // agree is the only thing that means "same file".
791    let already_there = matches!(
792        (me.canonicalize(), target.canonicalize()),
793        (Ok(a), Ok(b)) if a == b
794    );
795    if !already_there {
796        std::fs::copy(&me, &target)
797            .map_err(|e| format!("cannot install to {}: {e}", target.display()))?;
798        make_executable(&target).map_err(|e| format!("cannot chmod {}: {e}", target.display()))?;
799    }
800    let installed = target.to_string_lossy().into_owned();
801    println!("{} installed {}", valid_sign(), highlight(&installed));
802    Ok(installed)
803}
804
805/// Write the shims into the template directory — unless doing so would delete
806/// somebody's source.
807///
808/// REFUSING is not an error: on a machine where the template dir is the
809/// checkout, there is nothing to install and the install has succeeded. FAILING
810/// to write one it was allowed to write is, though — reporting success after a
811/// step did not happen is the thing this whole codebase is arranged against.
812fn populate_template_dir(binary: &str, force: bool) -> Result<(), String> {
813    let dir = template_hooks_dir();
814    let _ = std::fs::create_dir_all(&dir);
815    // Report the RESOLVED path. "It is the checkout" is only useful with the
816    // checkout named, and the configured path is usually the symlink that hides
817    // exactly that.
818    let shown = dir.canonicalize().unwrap_or_else(|_| dir.clone());
819    let shown = shown.display();
820
821    match classify_dir(&dir) {
822        TemplateDir::IsCheckout => {
823            println!(
824                "{} template dir IS the checkout ({shown}) — nothing to install.",
825                warning_sign()
826            );
827            println!("    Its shims keep the placeholder deliberately and resolve");
828            println!("    {binary} at run time. This is the intended setup.");
829            // …as long as run-time resolution can actually reach the binary,
830            // which the sentence above used to assert unconditionally.
831            warn_if_unbaked_cannot_resolve(binary);
832        }
833        TemplateDir::InsideCheckout => {
834            println!(
835                "{} {shown} is inside a git checkout — leaving it alone.",
836                warning_sign()
837            );
838            warn_if_unbaked_cannot_resolve(binary);
839        }
840        TemplateDir::NoGit => println!(
841            "{} git is not on PATH — refusing to delete anything.",
842            warning_sign()
843        ),
844        TemplateDir::Unresolvable => {
845            println!("{} cannot resolve {shown} — skipping.", warning_sign())
846        }
847        TemplateDir::Safe => {
848            let written = write_shims(&dir, binary, force)
849                .map_err(|e| format!("cannot write shims to {shown}: {e}"))?;
850            println!("{} wrote {} shims to {shown}", valid_sign(), written.len());
851            report_overwrites(&written);
852        }
853    }
854    Ok(())
855}
856
857/// Say what each write took, for the writes that took something.
858///
859/// `install --force` used to print `baked 4 shims` and stop. `--force` is
860/// typed precisely because a file is in the way, so the one fact the output
861/// omitted is the only fact the user needed: which files, and what they were.
862/// A hook replaced with no record of what it was is unrecoverable — `.git` is
863/// not tracked, so there is nothing to `git checkout` it back from.
864fn report_overwrites(written: &[Written]) {
865    for w in written {
866        if matches!(w.replaced, HookFile::Absent | HookFile::Ours) {
867            continue;
868        }
869        println!(
870            "{} overwrote {} — it was {}",
871            warning_sign(),
872            w.path.display(),
873            w.replaced.describe()
874        );
875    }
876}
877
878/// Where git dispatches hooks from, and whether that is this repository's OWN
879/// hooks directory or somewhere `core.hooksPath` sent it.
880///
881/// This replaces a bare `repo_hooks_dir()` that returned only the dispatch path.
882/// `--git-path hooks` is still the right question — never `--git-dir` plus
883/// `join("hooks")`, because hooks are explicitly SHARED across worktrees while a
884/// linked worktree's `--git-dir` is its own PRIVATE gitdir, so joining "hooks"
885/// onto it names a directory git never dispatches from. The addition is asking
886/// `--git-common-dir` alongside it, so the answer can be compared against the
887/// directory that would be ours.
888///
889/// The distinction did not exist and its absence was silent. `--git-path hooks`
890/// honours `core.hooksPath`, so in a repository running husky it answers
891/// `.husky/_` — inside the repo, plausible, and wrong. `install` wrote four
892/// shims there, husky's own `prepare` regenerated the directory on the next
893/// `npm install`, and the repository went back to having no checks with nothing
894/// to show for it. Every guarantee this tool makes was off in those repositories
895/// and the fleet reported them as merely "drifted".
896#[derive(Debug, Clone, PartialEq, Eq)]
897pub enum RepoHooks {
898    /// `<git-common-dir>/hooks`. Git dispatches from here and it is ours to write.
899    Own(PathBuf),
900    /// `core.hooksPath` points somewhere else. Another tool owns dispatch here,
901    /// and writing to `own` would install shims git never runs.
902    Redirected { to: PathBuf, own: PathBuf },
903    /// Not in a repository — git itself said "not a git repository".
904    Nowhere,
905    /// git failed for any OTHER reason: dubious ownership, an unreadable
906    /// `.git/config`, a corrupt gitfile. There is plausibly a repository here;
907    /// git would not talk about it. Split from [`RepoHooks::Nowhere`] because
908    /// the two demand opposite behaviour from `init` — outside a repository,
909    /// silence is correct; a repository git refuses to answer about is one
910    /// where somebody believes they are getting hooks and is not, which is the
911    /// failure this whole tool is arranged against.
912    Unanswerable { why: String },
913}
914
915/// Ask git both questions at once — what it dispatches from, and what this
916/// repository's own hooks directory is — then compare.
917///
918/// Lexical comparison via [`crate::hookfile::resolve_lexical`], not
919/// `canonicalize`: neither directory is guaranteed to exist yet (a fresh clone
920/// has no `.git/hooks` until something writes one), and `canonicalize` cannot be
921/// asked about a path that does not. Same reason `is_within` is lexical.
922pub fn repo_hooks() -> RepoHooks {
923    // `git::output`, not `git::stdout`: the latter collapses every non-zero
924    // exit to `None` with stderr discarded, which folded "not in a repository"
925    // (silence is right) and "git refused to answer" (silence hid a container
926    // checkout getting no hooks from `prepare`, with exit 0) into one arm.
927    let Some(out) = crate::git::output(&[
928        "rev-parse",
929        "--path-format=absolute",
930        "--git-path",
931        "hooks",
932        "--git-common-dir",
933    ]) else {
934        return RepoHooks::Unanswerable {
935            why: "could not run git".to_string(),
936        };
937    };
938    if out.code != 0 {
939        // git's own verdict draws the line — the same phrase
940        // `amont-fleet::scan::hooks_dir_for` keys on.
941        if out.stderr.contains("not a git repository") {
942            return RepoHooks::Nowhere;
943        }
944        let why = out
945            .stderr
946            .lines()
947            .find(|l| l.starts_with("fatal:"))
948            .or_else(|| out.stderr.lines().find(|l| !l.trim().is_empty()))
949            .unwrap_or("git gave no reason")
950            .to_string();
951        return RepoHooks::Unanswerable { why };
952    }
953    let mut lines = out.stdout.lines();
954    let (Some(dispatched), Some(common)) = (lines.next(), lines.next()) else {
955        return RepoHooks::Nowhere;
956    };
957    let dispatched = PathBuf::from(dispatched);
958    let own = PathBuf::from(common).join("hooks");
959    if crate::hookfile::resolve_lexical(&dispatched) == crate::hookfile::resolve_lexical(&own) {
960        RepoHooks::Own(own)
961    } else {
962        RepoHooks::Redirected {
963            to: dispatched,
964            own,
965        }
966    }
967}
968
969/// Name the tool behind a `core.hooksPath`, when the path gives it away.
970///
971/// A short list on purpose. It is half of [`redirect_is_hostile`]'s evidence,
972/// not a general classifier, and a name guessed wrong is worse than none.
973pub fn redirect_culprit(to: &Path) -> Option<&'static str> {
974    let s = to.to_string_lossy().replace('\\', "/");
975    if s.contains("/.husky") {
976        return Some("husky");
977    }
978    if s.contains("/.lefthook") || s.contains("lefthook") {
979        return Some("lefthook");
980    }
981    None
982}
983
984/// Whether any of our four shims sits in `dir`.
985///
986/// The runtime's own copy of the question `amont-fleet::scan::is_managed`
987/// answers, because the guard that needs it runs in the commit-path crate and
988/// cannot depend on the dashboard.
989pub fn holds_our_shims(dir: &Path) -> bool {
990    DISPATCHERS
991        .iter()
992        .any(|name| matches!(hookfile::classify(&dir.join(name)), HookFile::Ours))
993}
994
995/// Whether a redirect must be REFUSED rather than followed.
996///
997/// Not every `core.hooksPath` is a problem, and the first cut of this refused
998/// them all — which would have broken a repository that deliberately keeps its
999/// hooks in `tooling/hooks` under version control. That is a setup this project
1000/// has always honoured and `plan_finds_shims_at_a_redirected_hooks_path` pins.
1001///
1002/// So the refusal rests on evidence, not on the mere presence of the setting.
1003/// Either is enough:
1004///
1005///   * **the destination belongs to a hook manager we recognise** — husky and
1006///     lefthook both REGENERATE their directory on install, so anything we wrote
1007///     there is gone by the next `npm install` and the repository silently stops
1008///     being checked;
1009///   * **our shims sit in the repository's own hooks directory and NOT at the
1010///     destination** — amont was installed here and something later took
1011///     dispatch away. Whatever the destination is, this repository is not
1012///     running the checks it believes it is, and that is worth stopping for
1013///     whether or not we can name the culprit.
1014///
1015/// The second signal needs both halves. A repository whose shims sit at the
1016/// destination too moved its hooks there deliberately — amont IS running, from
1017/// the directory the repository chose — and whatever lingers in
1018/// `<git-common-dir>/hooks` is leftovers from before the move, not evidence of
1019/// a takeover. Refusing on the leftovers alone locked such a repository out of
1020/// `install` (and of `amont init` from npm's `prepare`, failing every
1021/// `npm install`) with a remedy that would have broken the deliberate setup.
1022///
1023/// A repository with neither signal keeps the old behaviour exactly.
1024pub fn redirect_is_hostile(to: &Path, own: &Path) -> bool {
1025    redirect_culprit(to).is_some() || (holds_our_shims(own) && !holds_our_shims(to))
1026}
1027
1028/// The refusal both `install` and `init` give when another tool owns dispatch.
1029///
1030/// One function, so the two cannot drift into saying different things about the
1031/// same situation — and so the remedy is spelled exactly once.
1032pub fn redirected_message(to: &Path, own: &Path) -> String {
1033    let mut msg = format!(
1034        "{} git dispatches hooks from {}, not {}",
1035        error_sign(),
1036        highlight(&to.display().to_string()),
1037        own.display()
1038    );
1039    match redirect_culprit(to) {
1040        Some(tool) => msg.push_str(&format!(
1041            "\n    `core.hooksPath` is set, so {tool} owns the hooks here. Shims\n    \
1042             written to either directory would be overwritten or never run."
1043        )),
1044        None => msg.push_str(
1045            "\n    `core.hooksPath` is set, so another tool owns the hooks here.\n    \
1046             Shims written to either directory would be overwritten or never run.",
1047        ),
1048    }
1049    msg.push_str(&format!(
1050        "\n    Hand dispatch back first: {}",
1051        highlight("git config --unset core.hooksPath")
1052    ));
1053    // Stranded shims are the evidence when no culprit is named — say how to
1054    // clear them, because "unset core.hooksPath" is the WRONG remedy for a
1055    // repository whose redirect is deliberate and merely predates a cleanup.
1056    if redirect_culprit(to).is_none() && holds_our_shims(own) {
1057        msg.push_str(&format!(
1058            "\n    Or, if the redirect is deliberate, clear our stale shims from {}\n    \
1059             first: {}",
1060            own.display(),
1061            highlight("amont uninstall")
1062        ));
1063    }
1064    msg
1065}
1066
1067/// Bake the shims into the repository we are standing in, if we are in one.
1068///
1069/// The tracked guard is inherited from `hookfile::guard_write` rather than
1070/// written here, and that inheritance closes a verified bug: with
1071/// `.git/hooks/pre-commit` a symlink to a TRACKED `devhooks/pre-commit`,
1072/// `install --force` rewrote the tracked source file. Every guard this function
1073/// had was about the LINK path — untracked, inside `.git`, unremarkable — while
1074/// `fs::write` followed the link and landed in the working tree. Both halves
1075/// are fixed at once: the symlink is refused by name, and `--force` replaces
1076/// the link by rename instead of writing through it.
1077fn bake_repo_hooks(binary: &str, force: bool) -> Result<(), String> {
1078    let hooks = match repo_hooks() {
1079        RepoHooks::Own(dir) => dir,
1080        // A hostile redirect is refused, and `--force` does not move it.
1081        // `--force` means "that file is mine to replace"; it has never meant
1082        // "write where git does not look". Writing `own` would leave four shims
1083        // git never dispatches, and writing `to` would hand our files to the
1084        // tool that regenerates that directory.
1085        //
1086        // A redirect that is merely a redirect is followed, as it always was —
1087        // see `redirect_is_hostile` for where the line is.
1088        RepoHooks::Redirected { to, own } if redirect_is_hostile(&to, &own) => {
1089            return Err(redirected_message(&to, &own))
1090        }
1091        RepoHooks::Redirected { to, .. } => to,
1092        RepoHooks::Nowhere => {
1093            println!(
1094                "{} not inside a git repository — no repo hooks written.",
1095                warning_sign()
1096            );
1097            return Ok(());
1098        }
1099        RepoHooks::Unanswerable { why } => {
1100            return Err(format!(
1101                "{} git would not say where this repository's hooks live —\n    {}",
1102                error_sign(),
1103                crate::ui::sanitize(&why)
1104            ))
1105        }
1106    };
1107    let _ = std::fs::create_dir_all(&hooks);
1108
1109    // Asked here, ahead of the guard, only so the message can offer `--force`.
1110    // The guard inside `write_shims` is the one that decides, and it refuses
1111    // things `--force` will not move (a tracked path, a path git cannot answer
1112    // for) which this pre-check deliberately says nothing about.
1113    let foreign = foreign_hooks(&hooks);
1114    if !foreign.is_empty() && !force {
1115        let mut msg = format!(
1116            "{} {} already has hooks that are not ours:",
1117            error_sign(),
1118            hooks.display()
1119        );
1120        for (name, what) in &foreign {
1121            msg.push_str(&format!("\n    {name} — {}", what.describe()));
1122        }
1123        msg.push_str("\n    Look at them first, then `amont install --force`.");
1124        return Err(msg);
1125    }
1126
1127    let written = write_shims(&hooks, binary, force)
1128        .map_err(|e| format!("cannot write shims to {}: {e}", hooks.display()))?;
1129    println!(
1130        "{} baked {} shims into {}",
1131        valid_sign(),
1132        written.len(),
1133        hooks.display()
1134    );
1135    report_overwrites(&written);
1136    Ok(())
1137}
1138
1139/// Take the shims out of the repository we are standing in.
1140///
1141/// Deliberately narrow. It removes files that are OURS and nothing else:
1142///
1143/// - a hook we did not write is left alone and named, because somebody wrote it
1144///   on purpose;
1145/// - `hook.skip` and `amont.severity` are never touched — those are the
1146///   user's statements about their own repository, not our artefacts, and a
1147///   reinstall should not silently forget that they disabled a check;
1148/// - the binary goes only when asked, because other repositories are using it.
1149pub fn uninstall(remove_binary: bool) -> Result<(), String> {
1150    // The template directory FIRST, and unconditionally, because it is the only
1151    // part of an install that keeps working when you are not standing in a
1152    // repository — and because `uninstall` returning early with "not inside a
1153    // git repository" is how the standing grant survived every attempt to
1154    // revoke it.
1155    uninstall_template_dir()?;
1156    uninstall_repo_hooks()?;
1157
1158    if remove_binary {
1159        let target = bin_dir().join(installed_name());
1160        match std::fs::remove_file(&target) {
1161            Ok(()) => println!(
1162                "{} removed {}",
1163                valid_sign(),
1164                highlight(&target.to_string_lossy())
1165            ),
1166            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
1167            Err(e) => return Err(format!("cannot remove {}: {e}", target.display())),
1168        }
1169    }
1170
1171    report_global_template_dir();
1172
1173    // Said out loud, because a user who uninstalls and reinstalls should not be
1174    // surprised that a check they disabled is still disabled.
1175    println!("    hook.skip and amont.severity were not touched.");
1176    Ok(())
1177}
1178
1179/// Remove our shims from the repository we are standing in, naming everything
1180/// we did not take and why.
1181///
1182/// Every non-removal is now NAMED. The loop this replaces matched
1183/// `Err(_) => {}` on `read_to_string`, so a hook that could not be read at all
1184/// — a compiled one, or one whose permissions we lack — was passed over in
1185/// total silence: not removed, not counted, not mentioned. The README's promise
1186/// that a foreign hook is "left alone and named" was true only for hooks that
1187/// happened to be valid UTF-8.
1188///
1189/// Not being in a repository is a warning rather than an error. It used to
1190/// return `Err`, which was defensible on its own but became wrong once
1191/// `uninstall_template_dir` existed: the early return meant that running
1192/// `amont uninstall` from a plain directory did nothing AND said nothing,
1193/// while `init.templateDir` quietly went on installing hooks into every future
1194/// clone. Refusing is not failing — the same rule `populate_template_dir`
1195/// already states.
1196fn uninstall_repo_hooks() -> Result<(), String> {
1197    // BOTH directories, where they differ. Uninstall is the one path that must
1198    // not inherit `install`'s new refusal: versions before it wrote shims into
1199    // whatever `core.hooksPath` named, so a repository can be carrying our files
1200    // in `.husky/_` right now — and refusing to look there would leave the only
1201    // command that removes them unable to find them. Removal is safe in a way
1202    // writing is not; `guard_remove` still decides file by file.
1203    let dirs: Vec<PathBuf> = match repo_hooks() {
1204        RepoHooks::Own(dir) => vec![dir],
1205        RepoHooks::Redirected { to, own } => vec![to, own],
1206        RepoHooks::Nowhere => {
1207            println!(
1208                "{} not inside a git repository — no repo hooks removed.",
1209                warning_sign()
1210            );
1211            return Ok(());
1212        }
1213        // Removal stays forgiving where writing does not: failing here would
1214        // leave `uninstall --binary` unable to finish its cleanup. Loud, and Ok.
1215        RepoHooks::Unanswerable { why } => {
1216            println!(
1217                "{} git would not answer here — no repo hooks removed ({})",
1218                warning_sign(),
1219                crate::ui::sanitize(&why)
1220            );
1221            return Ok(());
1222        }
1223    };
1224
1225    for hooks in &dirs {
1226        let mut removed = 0usize;
1227        let mut left: Vec<String> = Vec::new();
1228        for name in DISPATCHERS {
1229            let path = hooks.join(name);
1230            match hookfile::classify(&path) {
1231                HookFile::Absent => {}
1232                HookFile::Ours => match hookfile::guard_remove(&path, true) {
1233                    Ok(()) => {
1234                        hookfile::remove_regular(&path)
1235                            .map_err(|e| format!("cannot remove {}: {e}", path.display()))?;
1236                        removed += 1;
1237                    }
1238                    // Ours by marker, and still not ours to delete: a tracked
1239                    // path, or one git could not answer for.
1240                    Err(r) => left.push(r.explain()),
1241                },
1242                what => left.push(format!("{name} — {}", what.describe())),
1243            }
1244        }
1245        // The second directory is usually empty of ours and saying so every time
1246        // would be noise. Report it only when it held something.
1247        if removed > 0 || !left.is_empty() || dirs.len() == 1 {
1248            println!(
1249                "{} removed {removed} shims from {}",
1250                valid_sign(),
1251                hooks.display()
1252            );
1253        }
1254        for reason in &left {
1255            println!("{} left alone: {reason}", warning_sign());
1256        }
1257    }
1258    // The gate stamps, the bypass ledger and the seen-identity memo are OUR
1259    // bookkeeping — they only ever say "amont checked this" (or "didn't"),
1260    // which stops being true of anything the moment the hooks are gone.
1261    // `hook.skip` and `amont.severity` stay: those are the user's statements
1262    // about their repository, not ours.
1263    crate::gate_stamp::forget();
1264    crate::bypass::forget();
1265    // `--unset-all` exits 5 when the key is absent; not a failure here.
1266    let _ = crate::git::succeeds(&["config", "--unset-all", "amont.knownIdentity"]);
1267    Ok(())
1268}
1269
1270/// Take our shims back out of the template directory.
1271///
1272/// `install` writes there; `uninstall` did not, which meant uninstall did not
1273/// undo install. Combined with `init.templateDir`, that is the failure worth
1274/// spelling out: the user runs `amont uninstall`, sees "removed 4 shims",
1275/// believes they are done — and every `git clone` and `git init` from then on
1276/// copies the template directory into the new repository's `.git/hooks` and
1277/// installs the hooks again. They uninstalled a repository, not a machine.
1278///
1279/// The same classification `install` uses decides what may happen here, for the
1280/// same reason and with the sharper stake: `~/.config/git/git-templates` is
1281/// commonly a SYMLINK to a checkout of this repository, and "uninstalling"
1282/// there means `rm` on tracked source. That is not a hypothetical; it is the
1283/// two incidents this module exists because of, and a delete has no `--force`.
1284fn uninstall_template_dir() -> Result<(), String> {
1285    let dir = template_hooks_dir();
1286    // The RESOLVED path, because the configured one is usually the symlink that
1287    // hides exactly what we are about to explain.
1288    let shown = dir.canonicalize().unwrap_or_else(|_| dir.clone());
1289    let shown = shown.display();
1290
1291    match classify_dir(&dir) {
1292        TemplateDir::IsCheckout | TemplateDir::InsideCheckout => {
1293            println!(
1294                "{} template dir is a git checkout ({shown}) — deleting NOTHING there.",
1295                warning_sign()
1296            );
1297            println!("    Those shims are tracked files belonging to that checkout,");
1298            println!("    not something this install put there. Remove them with git,");
1299            println!("    or point init.templateDir somewhere else.");
1300        }
1301        TemplateDir::NoGit => println!(
1302            "{} git is not on PATH — cannot tell whether {shown} is a checkout, deleting nothing.",
1303            warning_sign()
1304        ),
1305        TemplateDir::Unresolvable => println!(
1306            "{} no template dir at {shown} — nothing to remove.",
1307            warning_sign()
1308        ),
1309        TemplateDir::Safe => {
1310            let mut removed = 0usize;
1311            let mut left: Vec<String> = Vec::new();
1312            for name in DISPATCHERS {
1313                let path = dir.join(name);
1314                match hookfile::classify(&path) {
1315                    HookFile::Absent => {}
1316                    HookFile::Ours => match hookfile::guard_remove(&path, true) {
1317                        Ok(()) => {
1318                            hookfile::remove_regular(&path)
1319                                .map_err(|e| format!("cannot remove {}: {e}", path.display()))?;
1320                            removed += 1;
1321                        }
1322                        Err(r) => left.push(r.explain()),
1323                    },
1324                    what => left.push(format!("{name} — {}", what.describe())),
1325                }
1326            }
1327            println!("{} removed {removed} shims from {shown}", valid_sign());
1328            for reason in &left {
1329                println!("{} left alone: {reason}", warning_sign());
1330            }
1331        }
1332    }
1333    Ok(())
1334}
1335
1336/// Say, every time, whether `init.templateDir` is still pointing at us.
1337///
1338/// UNCONDITIONAL, including when the template dir was a checkout we refused to
1339/// touch and when there was no template dir at all — because the config setting
1340/// is what actually installs hooks into new repositories, and it survives every
1341/// file this command removes. An uninstall that leaves it set has not
1342/// uninstalled anything durable: the next `git clone` re-installs.
1343///
1344/// Printed rather than unset. `git config --global` is the user's file, holding
1345/// their identity and their aliases, and reaching into it uninvited is a larger
1346/// claim than removing files this tool wrote. The command to run is given
1347/// verbatim so it is a copy rather than a lookup.
1348fn report_global_template_dir() {
1349    let Some(configured) = crate::git::stdout(&["config", "--global", "--get", "init.templateDir"])
1350        .filter(|s| !s.is_empty())
1351    else {
1352        return;
1353    };
1354    println!();
1355    println!(
1356        "{} init.templateDir is still set: {}",
1357        warning_sign(),
1358        highlight(&configured)
1359    );
1360    println!("    Every `git clone` and `git init` still copies hooks from there");
1361    println!("    into the new repository. Uninstalling this repo did not change that.");
1362    println!("    Undo it with:");
1363    println!(
1364        "        {}",
1365        highlight("git config --global --unset init.templateDir")
1366    );
1367}
1368
1369#[cfg(test)]
1370mod tests {
1371    use super::*;
1372
1373    fn tmp(name: &str) -> PathBuf {
1374        let d = std::env::temp_dir().join(format!("gh-install-{name}-{}", std::process::id()));
1375        let _ = std::fs::remove_dir_all(&d);
1376        std::fs::create_dir_all(&d).expect("mkdir");
1377        d
1378    }
1379
1380    fn git(dir: &Path, args: &[&str]) {
1381        Command::new("git")
1382            .arg("-C")
1383            .arg(dir)
1384            .args(args)
1385            .output()
1386            .expect("git");
1387    }
1388
1389    /// The embedded shim must be the shim that ships. `include_str!` takes one
1390    /// of the four; if they ever diverge, the installer would write a file
1391    /// nobody reviewed.
1392    #[test]
1393    fn shims_on_disk_match_the_embedded_one() {
1394        let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../templates/hooks");
1395        // Absent when this crate is built from its PUBLISHED tarball, which
1396        // contains this directory and nothing above it. There is no drift to
1397        // catch in that situation — the only shim present is the one compiled
1398        // in — so say so rather than fail a test about a file that is not
1399        // supposed to be there.
1400        if !Path::new(dir).is_dir() {
1401            println!(
1402                "! no repository checkout here — nothing to compare the embedded shim against"
1403            );
1404            return;
1405        }
1406        for name in DISPATCHERS {
1407            let disk = std::fs::read_to_string(Path::new(dir).join(name))
1408                .unwrap_or_else(|e| panic!("read {name}: {e}"));
1409            assert_eq!(disk, SHIM, "{name} differs from the embedded shim");
1410        }
1411    }
1412
1413    /// The whole point of the module. A directory holding tracked files is the
1414    /// source checkout reached through a symlink, and emptying it destroys work.
1415    #[test]
1416    fn a_directory_holding_tracked_files_is_never_safe() {
1417        let d = tmp("tracked");
1418        git(&d, &["init", "-q", "--template=", "."]);
1419        git(&d, &["config", "user.email", "t@t.test"]);
1420        git(&d, &["config", "user.name", "t"]);
1421        std::fs::write(d.join("kept.txt"), "precious\n").expect("write");
1422        git(&d, &["add", "-A"]);
1423        git(&d, &["commit", "-qm", "seed"]);
1424
1425        assert_eq!(classify_dir(&d), TemplateDir::IsCheckout);
1426        let _ = std::fs::remove_dir_all(&d);
1427    }
1428
1429    /// A path comparison against the source tree passes here and is WRONG: a
1430    /// worktree is a different path holding the same tracked files. This is the
1431    /// case that caused the second incident.
1432    #[test]
1433    fn a_worktree_is_recognised_even_though_its_path_differs() {
1434        let d = tmp("wt-main");
1435        git(&d, &["init", "-q", "--template=", "."]);
1436        git(&d, &["config", "user.email", "t@t.test"]);
1437        git(&d, &["config", "user.name", "t"]);
1438        std::fs::write(d.join("kept.txt"), "precious\n").expect("write");
1439        git(&d, &["add", "-A"]);
1440        git(&d, &["commit", "-qm", "seed"]);
1441
1442        let wt = d.with_extension("wt");
1443        let _ = std::fs::remove_dir_all(&wt);
1444        git(&d, &["worktree", "add", "-q", wt.to_str().unwrap()]);
1445        assert!(
1446            wt.join("kept.txt").is_file(),
1447            "worktree did not materialise"
1448        );
1449        assert_ne!(d.canonicalize().ok(), wt.canonicalize().ok());
1450        assert_eq!(
1451            classify_dir(&wt),
1452            TemplateDir::IsCheckout,
1453            "a worktree must be refused exactly like the main checkout"
1454        );
1455        let _ = std::fs::remove_dir_all(&wt);
1456        let _ = std::fs::remove_dir_all(&d);
1457    }
1458
1459    /// Inside a checkout but tracking nothing here — still not ours to empty.
1460    #[test]
1461    fn an_untracked_directory_inside_a_checkout_is_refused() {
1462        let d = tmp("inside");
1463        git(&d, &["init", "-q", "--template=", "."]);
1464        let sub = d.join("scratch");
1465        std::fs::create_dir_all(&sub).expect("mkdir");
1466        assert_eq!(classify_dir(&sub), TemplateDir::InsideCheckout);
1467        let _ = std::fs::remove_dir_all(&d);
1468    }
1469
1470    #[test]
1471    fn an_ordinary_directory_is_safe() {
1472        let d = tmp("plain");
1473        assert_eq!(classify_dir(&d), TemplateDir::Safe);
1474        let _ = std::fs::remove_dir_all(&d);
1475    }
1476
1477    #[test]
1478    fn a_missing_directory_is_unresolvable_not_safe() {
1479        assert_eq!(
1480            classify_dir(Path::new("/nonexistent-install-c8f2/hooks")),
1481            TemplateDir::Unresolvable
1482        );
1483    }
1484
1485    /// Baking replaces every occurrence and is idempotent.
1486    #[test]
1487    fn baking_is_total_and_idempotent() {
1488        let once = bake(SHIM, "/opt/amont");
1489        assert!(!once.contains(PLACEHOLDER), "a token survived baking");
1490        assert!(once.contains("/opt/amont"));
1491        assert_eq!(bake(&once, "/other"), once, "re-baking must be a no-op");
1492    }
1493
1494    /// The shim's comment must not spell the token out, or a global replace
1495    /// turns the explanation into a machine path — which it did, in every shim
1496    /// baked before this module existed.
1497    #[test]
1498    fn baking_does_not_rewrite_the_comment_explaining_it() {
1499        for line in bake(SHIM, "/opt/amont").lines() {
1500            if line.trim_start().starts_with('#') {
1501                assert!(
1502                    !line.contains("/opt/amont"),
1503                    "baking rewrote a comment: {line}"
1504                );
1505            }
1506        }
1507    }
1508
1509    /// Only an absolute path may be baked.
1510    ///
1511    /// A relative one is resolved by the shim against the WORKING TREE, so a
1512    /// repository shipping an executable by that name would be running it on
1513    /// the first commit after clone.
1514    #[test]
1515    fn only_an_absolute_path_is_bakeable() {
1516        for good in [
1517            "/opt/amont",
1518            "/home/u/.local/bin/amont",
1519            "C:/Users/u/amont.exe",
1520            "C:\\Users\\u\\amont.exe",
1521        ] {
1522            assert!(is_bakeable(good), "{good} should be bakeable");
1523        }
1524        for bad in [
1525            "",
1526            PLACEHOLDER,
1527            "amont",
1528            "./amont",
1529            "../amont",
1530            "target/debug/amont",
1531            "C:amont.exe",
1532        ] {
1533            assert!(!is_bakeable(bad), "{bad:?} must not be bakeable");
1534        }
1535    }
1536
1537    /// The shim must never hand the unsubstituted token to `[ -x ]`: that is a
1538    /// filesystem question asked in the repository's own directory.
1539    #[test]
1540    fn the_shim_never_tests_the_placeholder_as_a_path() {
1541        assert!(
1542            !SHIM.contains(&format!("[ -x \"{PLACEHOLDER}\" ]")),
1543            "the shim tests the raw token as a path"
1544        );
1545        assert!(
1546            SHIM.contains("case \"$BAKED\" in"),
1547            "the shim lost its absoluteness guard"
1548        );
1549    }
1550
1551    /// Refusing beats writing four hooks that cannot resolve their binary.
1552    #[test]
1553    fn write_shims_refuses_a_relative_binary_path() {
1554        let d = tmp("relative");
1555        let err = write_shims(&d, "target/debug/amont", false).expect_err("must refuse");
1556        assert!(err.to_string().contains("absolute"), "{err}");
1557        for name in DISPATCHERS {
1558            assert!(!d.join(name).exists(), "{name} was written anyway");
1559        }
1560        let _ = std::fs::remove_dir_all(&d);
1561    }
1562
1563    /// Every hook git invokes gets a file, and each is the baked shim.
1564    #[test]
1565    fn writing_shims_covers_every_dispatcher() {
1566        let d = tmp("write");
1567        let written = write_shims(&d, "/opt/amont", false).expect("write");
1568        assert_eq!(written.len(), DISPATCHERS.len());
1569        for name in DISPATCHERS {
1570            let got = std::fs::read_to_string(d.join(name)).expect("read");
1571            assert!(!got.contains(PLACEHOLDER), "{name} was written unbaked");
1572            assert!(got.contains("/opt/amont"), "{name} has no path");
1573        }
1574        let _ = std::fs::remove_dir_all(&d);
1575    }
1576
1577    /// The whole-repository posture, at the level of the function that owes it:
1578    /// ONE unwritable path and nothing at all is written. `bake_repo_hooks` has
1579    /// claimed this in a comment since it was written, over a loop that checked
1580    /// one file then wrote it, four times over — so a refusal on the third hook
1581    /// arrived after two were already gone.
1582    #[test]
1583    fn one_refusal_writes_nothing_at_all() {
1584        let d = tmp("all-or-nothing");
1585        // `prepare-commit-msg` sorts last among the dispatchers, so under the
1586        // old check-then-write loop the first three would already be on disk by
1587        // the time this one refused.
1588        let theirs = d.join("prepare-commit-msg");
1589        std::fs::write(&theirs, "#!/bin/sh\necho MINE\n").expect("write");
1590
1591        let err = write_shims(&d, "/opt/amont", false).expect_err("must refuse");
1592        assert!(
1593            matches!(err, ShimWriteError::Refused(ref rs) if rs.len() == 1),
1594            "{err}"
1595        );
1596        for name in ["commit-msg", "pre-commit", "pre-push"] {
1597            assert!(
1598                !d.join(name).exists(),
1599                "{name} was written despite a refusal elsewhere"
1600            );
1601        }
1602        assert_eq!(
1603            std::fs::read_to_string(&theirs).expect("read"),
1604            "#!/bin/sh\necho MINE\n"
1605        );
1606        let _ = std::fs::remove_dir_all(&d);
1607    }
1608
1609    /// A refusal has to say WHAT was in the way, not only that something was.
1610    /// The old predicate could not: it read the file as a string, so the one
1611    /// case worth naming — a compiled hook — came back as "not foreign" and was
1612    /// overwritten in silence.
1613    #[test]
1614    fn a_refusal_names_the_reason_for_each_hook() {
1615        let d = tmp("named");
1616        std::fs::write(d.join("commit-msg"), [0x7f, b'E', b'L', b'F', 0xff]).expect("write");
1617        std::fs::write(d.join("pre-commit"), "#!/bin/sh\necho mine\n").expect("write");
1618
1619        let err = write_shims(&d, "/opt/amont", false).expect_err("must refuse");
1620        let text = err.to_string();
1621        assert!(text.contains("not valid UTF-8"), "{text}");
1622        assert!(text.contains("commit-msg"), "{text}");
1623        assert!(text.contains("pre-commit"), "{text}");
1624
1625        // And `foreign_hooks` — which is what phrases the `--force` offer —
1626        // agrees about both.
1627        let foreign = foreign_hooks(&d);
1628        assert_eq!(foreign.len(), 2, "{foreign:?}");
1629        assert!(foreign
1630            .iter()
1631            .any(|(n, w)| *n == "commit-msg" && matches!(w, HookFile::Foreign(_))));
1632        let _ = std::fs::remove_dir_all(&d);
1633    }
1634
1635    /// `--force` says what it took, per file, with what it was. Without this
1636    /// the output was "baked 4 shims" — a receipt with the transaction left
1637    /// off, for the one operation whose purpose is to destroy something.
1638    #[test]
1639    fn force_reports_what_each_write_replaced() {
1640        let d = tmp("force-report");
1641        std::fs::write(d.join("commit-msg"), "#!/bin/sh\necho mine\n").expect("write");
1642        let written = write_shims(&d, "/opt/amont", true).expect("force must write");
1643        let replaced: Vec<_> = written
1644            .iter()
1645            .filter(|w| !matches!(w.replaced, HookFile::Absent))
1646            .collect();
1647        assert_eq!(replaced.len(), 1, "{written:?}");
1648        assert!(replaced[0].path.ends_with("commit-msg"));
1649        assert!(matches!(replaced[0].replaced, HookFile::Foreign(_)));
1650        let _ = std::fs::remove_dir_all(&d);
1651    }
1652
1653    /// Windows builds amont.exe, and a shim testing `[ -x .../amont ]` is
1654    /// false for it — so the installed name has to keep the suffix. Asserted
1655    /// against explicit paths, because a `cfg!(windows)` branch is vacuous on
1656    /// the platform this is usually run on.
1657    #[test]
1658    fn the_installed_name_keeps_the_platform_suffix() {
1659        assert_eq!(
1660            name_for(Path::new("/w/target/release/amont.exe")),
1661            "amont.exe"
1662        );
1663        assert_eq!(name_for(Path::new("/u/target/release/amont")), "amont");
1664        // A path that happens to contain a dot elsewhere is not an extension.
1665        assert_eq!(name_for(Path::new("/some.dir/amont")), "amont");
1666    }
1667}