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