amont 1.4.1

Opinionated git hooks that judge what you are committing, not what is on disk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! The three Rust checks, driven through the real binary against real cargo.
//!
//! These compile a tiny crate, so they are the slowest tests here. They earn it:
//! everything interesting is in the seam between git's staged set and cargo's
//! notion of a workspace, and nothing about that seam is exercised by a unit
//! test on path strings.

mod common;
use common::{missing, Repo};
use std::io::Write;
use std::process::{Command, Stdio};

/// A minimal, dependency-free crate — no network, no registry.
fn crate_files(r: &Repo, body: &str) {
    r.stage(
        "Cargo.toml",
        "[package]\nname = \"t\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[dependencies]\n",
    );
    r.stage("src/main.rs", body);
}

fn pre_push(r: &Repo, from: &str, to: &str) -> i32 {
    let line = format!("refs/heads/feat/x {to} refs/heads/feat/x {from}\n");
    let mut child = Command::new(env!("CARGO_BIN_EXE_amont"))
        .arg("--hooks-dir")
        .arg(r.path(".git/hooks"))
        .arg("pre-push-cargo-test")
        .current_dir(&r.dir)
        .stdin(Stdio::piped())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .spawn()
        .expect("spawn");
    child
        .stdin
        .as_mut()
        .expect("stdin")
        .write_all(line.as_bytes())
        .expect("write");
    child.wait().expect("wait").code().unwrap_or(-1)
}

fn head(r: &Repo) -> String {
    String::from_utf8_lossy(&r.git(&["rev-parse", "HEAD"]).stdout)
        .trim()
        .to_string()
}

/// The scoping guarantee that matters most: a repo with no Rust must never
/// invoke cargo, however the checks are wired.
#[test]
fn a_non_rust_repo_runs_nothing() {
    let r = Repo::new();
    r.stage("a.py", "x = 1\n");
    r.stage("README.md", "hi\n");
    assert!(r.hook("pre-commit-cargo-fmt", &[]).passed());
    assert!(r.hook("pre-commit-clippy", &[]).passed());
}

/// A `.rs` file with no `Cargo.toml` above it is not a cargo project — a loose
/// script must not make the hook try to build a workspace that doesn't exist.
#[test]
fn a_rust_file_outside_any_crate_is_skipped() {
    let r = Repo::new();
    r.stage("scripts/loose.rs", "fn main() {}\n");
    let run = r.hook("pre-commit-cargo-fmt", &[]);
    assert!(run.passed(), "{}", run.stdout);
    assert!(
        !run.says("Rust formatting"),
        "should not have run cargo at all: {}",
        run.stdout
    );
}

#[test]
fn cargo_fmt_rejects_unformatted_rust_and_accepts_clean() {
    if missing("cargo") {
        return;
    }
    let r = Repo::new();
    crate_files(&r, "fn main(){let _x=1;}\n");
    assert!(
        !r.hook("pre-commit-cargo-fmt", &[]).passed(),
        "unformatted code must fail"
    );

    let r2 = Repo::new();
    crate_files(&r2, "fn main() {\n    let _x = 1;\n}\n");
    let run = r2.hook("pre-commit-cargo-fmt", &[]);
    assert!(run.passed(), "formatted code must pass: {}", run.stdout);
    assert!(run.says("Rust formatting is clean"));
}

/// The registry has always declared `Fix::Rewrite` for `pre-commit-cargo-fmt`,
/// and `amont list --json` reported `"fix":"rewrite"` — which `agents_md`
/// tells agents to trust — while no fixing code existed anywhere. Only
/// prettier and the manifest's externals ever called `restage`. So an agent
/// could set `amont.fix true` and wait forever for a repair.
#[test]
fn cargo_fmt_repairs_and_restages_when_asked() {
    if missing("cargo") {
        return;
    }
    let r = Repo::new();
    r.git(&["config", "amont.fix", "true"]);
    crate_files(&r, "fn main(){let _x=1;}\n");

    let run = r.hook("pre-commit-cargo-fmt", &[]);
    assert!(
        run.passed(),
        "the repair should let it through: {}",
        run.stdout
    );
    assert!(run.says("reformatted and re-staged"), "{}", run.stdout);

    let staged = r.git(&["show", ":src/main.rs"]);
    assert_eq!(
        String::from_utf8_lossy(&staged.stdout),
        "fn main() {\n    let _x = 1;\n}\n",
        "the repair reached the index, not just the disk"
    );
}

/// With fixing OFF the file must come back byte for byte as it was written.
#[test]
fn cargo_fmt_leaves_files_alone_when_fixing_is_off() {
    if missing("cargo") {
        return;
    }
    let r = Repo::new();
    crate_files(&r, "fn main(){let _x=1;}\n");

    assert!(!r.hook("pre-commit-cargo-fmt", &[]).passed());
    assert_eq!(
        std::fs::read_to_string(r.path("src/main.rs")).expect("read"),
        "fn main(){let _x=1;}\n",
        "it rewrote a file nobody asked it to rewrite"
    );
}

/// The guard that makes the repair safe: `cargo fmt --all` formats the WHOLE
/// workspace, but `restage` is handed only the staged `.rs` list. A second,
/// unformatted, UNSTAGED file in the same crate is reformatted on disk (cargo's
/// doing) and must NOT appear in the index.
#[test]
fn a_repair_does_not_stage_an_unrelated_unformatted_file() {
    if missing("cargo") {
        return;
    }
    let r = Repo::new();
    r.git(&["config", "amont.fix", "true"]);
    // A clean, committed baseline for both files.
    crate_files(&r, "mod other;\nfn main() {}\n");
    r.stage("src/other.rs", "pub fn q() {}\n");
    r.commit("chore: seed");

    // The change being committed: staged and unformatted.
    r.stage("src/main.rs", "mod other;\nfn main(){let _x=1;}\n");
    // A second unformatted file in the same crate, deliberately KEPT BACK.
    r.write("src/other.rs", "pub fn q(){let _y=2;}\n");

    let run = r.hook("pre-commit-cargo-fmt", &[]);
    assert!(run.passed(), "{}", run.stdout);

    let staged = r.git(&["diff", "--cached", "--name-only"]);
    let staged = String::from_utf8_lossy(&staged.stdout);
    assert!(staged.contains("src/main.rs"), "{staged}");
    assert!(
        !staged.contains("src/other.rs"),
        "the repair swept in work the author kept back: {staged}"
    );
}

/// `-D warnings` is the point: an ordinary rustc warning has to fail the
/// commit, not merely print.
#[test]
fn clippy_denies_warnings() {
    if missing("cargo") {
        return;
    }
    let r = Repo::new();
    crate_files(&r, "fn main() {\n    let unused = 1;\n}\n");
    assert!(
        !r.hook("pre-commit-clippy", &[]).passed(),
        "an unused variable must fail under -D warnings"
    );

    let r2 = Repo::new();
    crate_files(&r2, "fn main() {\n    println!(\"ok\");\n}\n");
    let run = r2.hook("pre-commit-clippy", &[]);
    assert!(run.passed(), "clean code must pass: {}", run.stdout);
    assert!(run.says("Clippy passed"));
}

/// A dependency bump changes what compiles without touching a single `.rs`,
/// which is exactly when clippy is worth running.
#[test]
fn a_manifest_only_change_still_runs_clippy() {
    if missing("cargo") {
        return;
    }
    let r = Repo::new();
    crate_files(&r, "fn main() {\n    println!(\"ok\");\n}\n");
    r.commit("feat: base");
    // Stage ONLY the manifest.
    r.stage(
        "Cargo.toml",
        "[package]\nname = \"t\"\nversion = \"0.2.0\"\nedition = \"2021\"\n\n[dependencies]\n",
    );
    let run = r.hook("pre-commit-clippy", &[]);
    assert!(run.passed(), "{}", run.stdout);
    assert!(
        run.says("Clippy passed"),
        "a manifest-only change should still have run clippy: {}",
        run.stdout
    );
}

#[test]
fn cargo_test_gates_the_push() {
    if missing("cargo") {
        return;
    }
    let r = Repo::new();
    crate_files(
        &r,
        "fn main() {}\n\n#[test]\nfn passes() {\n    assert_eq!(1, 1);\n}\n",
    );
    r.commit("feat: base");
    let base = head(&r);
    r.stage(
        "src/main.rs",
        "fn main() {}\n\n#[test]\nfn fails() {\n    assert_eq!(1, 2);\n}\n",
    );
    r.commit("feat: a failing test");
    assert_ne!(
        pre_push(&r, &base, &head(&r)),
        0,
        "a failing test must abort the push"
    );
}

/// A push that touches no Rust must not pay for a workspace test run.
#[test]
fn a_docs_only_push_runs_no_tests() {
    let r = Repo::new();
    crate_files(&r, "fn main() {}\n");
    r.commit("feat: base");
    let base = head(&r);
    r.stage("README.md", "docs\n");
    r.commit("docs: readme");
    assert_eq!(pre_push(&r, &base, &head(&r)), 0);
}

/// The gate runs a project's test suite, and git hands every hook a GIT_DIR
/// pointing at the REAL repository. Those variables beat `current_dir`, so a
/// suite that shells out to git operates on the wrong repo entirely.
///
/// This is not theoretical: running the gate on this very repo let a fixture's
/// `git commit` land a stray commit on a real branch, authored by the test
/// user. The suite must see no git environment at all.
#[test]
fn the_test_gate_does_not_leak_git_env_to_the_suite() {
    if missing("cargo") {
        return;
    }
    let r = Repo::new();
    // A test that fails IF it can see git's environment.
    crate_files(
        &r,
        "fn main() {}\n\n#[test]\nfn no_git_env() {\n    \
         for (k, _) in std::env::vars() {\n        \
         assert!(!k.starts_with(\"GIT_\"), \"leaked {k}\");\n    }\n}\n",
    );
    r.commit("feat: base");
    let base = head(&r);
    r.stage("src/main.rs", "fn main() {}\n\n#[test]\nfn no_git_env() {\n    for (k, _) in std::env::vars() {\n        assert!(!k.starts_with(\"GIT_\"), \"leaked {k}\");\n    }\n}\n// touch\n");
    r.commit("feat: touch");

    // Run the gate with git's variables set, as git itself would.
    let line = format!("refs/heads/feat/x {} refs/heads/feat/x {base}\n", head(&r));
    let mut child = Command::new(env!("CARGO_BIN_EXE_amont"))
        .arg("--hooks-dir")
        .arg(r.path(".git/hooks"))
        .arg("pre-push-cargo-test")
        .current_dir(&r.dir)
        .env("GIT_DIR", r.path(".git"))
        .env("GIT_INDEX_FILE", r.path(".git/index"))
        .stdin(Stdio::piped())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .spawn()
        .expect("spawn");
    child
        .stdin
        .as_mut()
        .expect("stdin")
        .write_all(line.as_bytes())
        .expect("write");
    let code = child.wait().expect("wait").code().unwrap_or(-1);
    assert_eq!(code, 0, "the suite saw git's environment");
}

/// A brand-new branch's changed-file set must cover EVERY new commit, not
/// just the tip. For a new ref (`remote_oid` all-zero), the range logic used
/// to diff only the tip commit against its parent — a branch that added
/// `Cargo.toml`/`src/main.rs` two commits back and then a docs-only commit on
/// top would report only the docs file as changed, so `cargo_roots` found no
/// Rust and `pre-push-cargo-test` silently passed without ever running the
/// (here, deliberately failing) suite.
#[test]
fn a_new_branch_with_rust_several_commits_back_still_runs_the_suite() {
    if missing("cargo") {
        return;
    }
    let r = Repo::new();
    r.stage("README.md", "start\n");
    r.commit("chore: base");

    // The Rust project, added on the SECOND commit — not the tip.
    crate_files(
        &r,
        "fn main() {}\n\n#[test]\nfn t() {\n    assert!(false);\n}\n",
    );
    r.commit("feat: add a failing crate");

    // The tip: a docs-only commit that touches no Rust file at all.
    r.stage("README.md", "start\nand more\n");
    r.commit("docs: expand readme");

    let zero = "0".repeat(40);
    let code = pre_push(&r, &zero, &head(&r));
    assert_ne!(
        code, 0,
        "a new branch's failing Rust suite, added before the tip commit, was silently skipped"
    );
}

/// Two refs pushed at once (`git push origin a b`) must each be tested
/// against their OWN tip. A single worktree shared across the whole push used
/// to be checked out at only the first ref's commit, so the second ref's
/// suite ran against the first ref's tree — a real failure unique to the
/// second branch was invisible because its own content was never checked out
/// anywhere.
#[test]
fn each_ref_in_a_multi_ref_push_is_tested_against_its_own_tip() {
    if missing("cargo") {
        return;
    }
    let r = Repo::new();
    r.git(&["config", "amont.testPushedTree", "true"]);
    r.stage("README.md", "start\n");
    r.commit("chore: base");
    let base = head(&r);

    // Branch "a": a crate at `crate/` whose test PASSES.
    r.git(&["checkout", "-q", "-b", "a"]);
    r.stage(
        "crate/Cargo.toml",
        "[package]\nname = \"t\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[dependencies]\n",
    );
    r.stage(
        "crate/src/main.rs",
        "fn main() {}\n\n#[test]\nfn t() {\n    assert!(true);\n}\n",
    );
    r.commit("feat(a): passing crate");
    let tip_a = head(&r);

    // Branch "b": the SAME crate path, from the SAME base, but its test
    // FAILS. If the worktree used for "b" is actually "a"'s, this never
    // shows up.
    r.git(&["checkout", "-q", &base]);
    r.git(&["checkout", "-q", "-b", "b"]);
    r.stage(
        "crate/Cargo.toml",
        "[package]\nname = \"t\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n[dependencies]\n",
    );
    r.stage(
        "crate/src/main.rs",
        "fn main() {}\n\n#[test]\nfn t() {\n    assert!(false);\n}\n",
    );
    r.commit("feat(b): failing crate");
    let tip_b = head(&r);

    let zero = "0".repeat(40);
    let lines = format!(
        "refs/heads/a {tip_a} refs/heads/a {zero}\n\
         refs/heads/b {tip_b} refs/heads/b {zero}\n"
    );
    let mut child = Command::new(env!("CARGO_BIN_EXE_amont"))
        .arg("--hooks-dir")
        .arg(r.path(".git/hooks"))
        .arg("pre-push-cargo-test")
        .current_dir(&r.dir)
        .stdin(Stdio::piped())
        .stdout(Stdio::inherit())
        .stderr(Stdio::inherit())
        .spawn()
        .expect("spawn");
    child
        .stdin
        .as_mut()
        .expect("stdin")
        .write_all(lines.as_bytes())
        .expect("write");
    let code = child.wait().expect("wait").code().unwrap_or(-1);
    assert_ne!(
        code, 0,
        "branch b's failing crate was tested against branch a's tree instead of its own"
    );
}