1use std::ops::Range;
15use std::path::Path;
16
17pub const START: &str = "<!-- amont:start -->";
18pub const END: &str = "<!-- amont:end -->";
19
20pub fn generate_block(settings: &crate::config::Settings) -> String {
27 let clocks = |secs: u64| match secs {
28 0 => "no limit".to_string(),
29 s => crate::hooks::common::human_secs(s),
30 };
31 let idle = clocks(crate::hooks::common::idle_timeout(settings));
32 let ceiling = clocks(crate::hooks::common::check_timeout(settings));
33 let prefixes = crate::vocabulary::BRANCH_PREFIXES
34 .iter()
35 .map(|p| p.name)
36 .collect::<Vec<_>>()
37 .join(", ");
38 format!(
39 "{START}\n\
40\n\
41## Git hooks (amont)\n\
42\n\
43This repository enforces pre-commit / pre-push checks. Ask the registry\n\
44rather than guessing before assuming a change is safe:\n\
45\n\
46```sh\n\
47amont list --json\n\
48amont list --json --stage pre-push --pushed # exactly what pushing next gates\n\
49```\n\
50\n\
51Each check reports its _effective_ severity (`block`/`warn`, including any\n\
52`amont.severity.*` override) and whether it fires here. The same output\n\
53carries `commit_style`: the subject and description limits `commit-msg`\n\
54enforces, and where the type's gitmoji is placed. It also carries\n\
55`branch_style`: name a branch `<prefix>/<name>` BEFORE creating it —\n\
56prefixes are {prefixes} — because `pre-push` refuses a\n\
57new branch that breaks the pattern, at the end of the work instead of the\n\
58start.\n\
59\n\
60`git commit` and `git push` both run their checks first, and neither is\n\
61instant: pre-commit can invoke formatters, linters or clippy (a workspace\n\
62build), and pre-push gates include the test suite. Push with `amont land`:\n\
63it runs every push gate the push owes on a snapshot of the exact commit,\n\
64with no connection open, then pushes, and the push itself skips them (git\n\
65connects before pre-push runs, and a remote may drop the idle session while a\n\
66suite runs). A bare `git push` whose push gates have not run on its tree is\n\
67refused at once (`amont.pushGates refuse`, the default): run `amont land`, or\n\
68`amont rehearse --wait` (or `amont run --stamp`) first and push again. Push a\n\
69release tag with `amont land --tag <name>`: it runs the release audits on the\n\
70tagged commit first, which a branch rehearsal never does. Where\n\
71`amont.rehearseOnCommit` is on, every commit already starts that rehearsal in\n\
72the background and `--wait` only follows it. Give these commands the\n\
73longest timeout your tooling allows, never its default: here a check is\n\
74killed only after {idle} of silence or {ceiling} in total\n\
75(`amont.idleTimeout` / `amont.timeout`) — and on Linux and macOS a silent\n\
76check whose processes are busy on CPU is not \"silent\": it can run to the\n\
77{ceiling} ceiling. A check waiting on a cargo or uv lock answers to\n\
78`amont.lockWait` instead, the silence budget stretches with the machine's\n\
79load (`amont.idleLoadScale`), and a heavy check (clippy, a test suite) may\n\
80first queue for a host slot (`amont.hostSlots`) while other worktrees run\n\
81theirs. A test suite may legitimately run for most of that. If your tooling caps a foreground command below it,\n\
82run the command in the background and read its result when it exits —\n\
83while it runs, a line a minute on stderr says which check is alive and\n\
84when it last printed. A push killed mid-suite pushed nothing; a commit\n\
85killed mid-check committed nothing, and your unstaged work stays parked\n\
86until the next run says how to recover it. Neither is the checks failing —\n\
87it is the timeout. Run both bare and check the effect (`git log --oneline\n\
88-1`, `git ls-remote origin <branch>`): trimming their output with `| tail`\n\
89reports the pipe's exit status, so a killed or rejected run reads as\n\
90success.\n\
91\n\
92Never bypass with `--no-verify`. To change enforcement, downgrade it\n\
93intentionally instead:\n\
94\n\
95```sh\n\
96git config amont.severity.<check-id> warn\n\
97```\n\
98\n\
99`commit-msg` takes neither `hook.skip` nor a severity override. Write the\n\
100message it asks for, or change what it asks for — `amont setup`, or\n\
101`amont.commit.*` directly.\n\
102\n\
103{END}\n"
104 )
105}
106
107pub fn generate_pointer() -> String {
116 format!(
117 "{START}\n\
118\n\
119## Git hooks (amont)\n\
120\n\
121This repository enforces pre-commit / pre-push checks that can REJECT a\n\
122commit or a push. What runs, the branch-name rule, and why `git commit`\n\
123and `git push` both need a long timeout — or a background run — are in\n\
124[AGENTS.md](AGENTS.md) — read it before committing. Both files are\n\
125generated: run `amont agents-md` after changing either.\n\
126\n\
127{END}\n"
128 )
129}
130
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub enum MarkerState {
133 Malformed,
136}
137
138fn marker_range(text: &str) -> Result<Option<Range<usize>>, MarkerState> {
147 let start = text.find(START);
148 let end = text.find(END);
149
150 match (start, end) {
151 (None, None) => Ok(None),
152 (Some(s), Some(e)) if e >= s + START.len() => {
153 let mut range_end = e + END.len();
154 if text[range_end..].starts_with('\n') {
155 range_end += 1; }
157 Ok(Some(s..range_end))
158 }
159 _ => Err(MarkerState::Malformed),
161 }
162}
163
164pub fn desired_file_content(
172 settings: &crate::config::Settings,
173 existing: &str,
174) -> Result<String, MarkerState> {
175 desired_with(existing, &generate_block(settings))
176}
177
178pub fn desired_pointer_content(existing: &str) -> Result<String, MarkerState> {
180 desired_with(existing, &generate_pointer())
181}
182
183fn desired_with(existing: &str, block: &str) -> Result<String, MarkerState> {
188 match marker_range(existing)? {
189 Some(range) => Ok(format!(
190 "{}{}{}",
191 &existing[..range.start],
192 block,
193 &existing[range.end..]
194 )),
195 None if existing.is_empty() => Ok(block.to_string()),
196 None => {
197 let sep = if existing.ends_with("\n\n") {
198 ""
199 } else if existing.ends_with('\n') {
200 "\n"
201 } else {
202 "\n\n"
203 };
204 Ok(format!("{existing}{sep}{block}"))
205 }
206 }
207}
208
209pub fn write(settings: &crate::config::Settings, path: &Path) -> Result<(), String> {
210 write_with(path, &generate_block(settings))
211}
212
213pub fn write_pointer(path: &Path) -> Result<(), String> {
215 write_with(path, &generate_pointer())
216}
217
218fn write_with(path: &Path, block: &str) -> Result<(), String> {
219 let existing = std::fs::read_to_string(path).unwrap_or_default();
220 let content = desired_with(&existing, block).map_err(|_| {
221 format!(
222 "{}: has an unpaired amont marker — fix or remove it by hand, \
223 then re-run `amont agents-md`",
224 path.display()
225 )
226 })?;
227 if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
228 std::fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
229 }
230 std::fs::write(path, content).map_err(|e| format!("{}: {e}", path.display()))
231}
232
233#[derive(Debug, Clone, Copy, PartialEq, Eq)]
234pub enum CheckResult {
235 NotPresent,
238 MatchesGenerated,
239 Drifted,
240}
241
242pub fn check(settings: &crate::config::Settings, path: &Path) -> Result<CheckResult, String> {
243 check_with(path, &generate_block(settings))
244}
245
246pub fn check_pointer(path: &Path) -> Result<CheckResult, String> {
248 check_with(path, &generate_pointer())
249}
250
251fn check_with(path: &Path, block: &str) -> Result<CheckResult, String> {
252 let existing = std::fs::read_to_string(path).unwrap_or_default();
253 match marker_range(&existing) {
254 Err(_) => Err(format!(
255 "{}: has an unpaired amont marker — fix or remove it by hand",
256 path.display()
257 )),
258 Ok(None) => Ok(CheckResult::NotPresent),
259 Ok(Some(range)) => {
260 if &existing[range] == block {
261 Ok(CheckResult::MatchesGenerated)
262 } else {
263 Ok(CheckResult::Drifted)
264 }
265 }
266 }
267}
268
269#[cfg(test)]
270mod tests {
271 use super::*;
272
273 fn test_settings() -> crate::config::Settings {
276 crate::config::Settings::default()
277 }
278
279 #[test]
280 fn no_file_produces_just_the_block() {
281 assert_eq!(
282 desired_file_content(&test_settings(), "").unwrap(),
283 generate_block(&test_settings())
284 );
285 }
286
287 #[test]
296 fn the_generated_markdown_satisfies_prettier() {
297 for (what, text) in [
298 ("block", generate_block(&test_settings())),
299 ("pointer", generate_pointer()),
300 ] {
301 assert!(
302 text.starts_with(&format!("{START}\n\n")),
303 "{what}: prettier wants a blank line after the opening comment"
304 );
305 assert!(
306 text.ends_with(&format!("\n\n{END}\n")),
307 "{what}: prettier wants a blank line before the closing comment"
308 );
309 let opener = text
314 .as_bytes()
315 .windows(2)
316 .any(|w| w[0] == b'*' && w[1].is_ascii_alphanumeric());
317 assert!(
318 !opener,
319 "{what}: prettier rewrites *emphasis* into _emphasis_, and a \
320 formatted file then reads as drift — emit underscores"
321 );
322 }
323 }
324
325 #[test]
329 fn the_pointer_is_generated_and_therefore_checkable() {
330 let p = generate_pointer();
331 assert!(p.starts_with(START) && p.ends_with(&format!("{END}\n")));
332 assert!(p.contains("AGENTS.md"), "it has to name where to look");
333 assert_ne!(
334 p,
335 generate_block(&test_settings()),
336 "a signpost, not a second copy"
337 );
338 assert!(
339 !p.contains("amont list --json"),
340 "the registry command lives in ONE place; duplicating it here is \
341 the drift this design avoids"
342 );
343 let existing = "# Notes\n\nsomething the repo wrote\n";
346 let once = desired_pointer_content(existing).unwrap();
347 assert!(once.starts_with(existing), "never touches what was there");
348 assert!(once.ends_with(&p));
349 assert_eq!(
350 desired_pointer_content(&once).unwrap(),
351 once,
352 "re-running is a no-op, so `--check` can be trusted"
353 );
354 }
355
356 #[test]
357 fn no_markers_appends_with_one_blank_line() {
358 let got = desired_file_content(&test_settings(), "# My Project\n\nSome docs.\n").unwrap();
359 assert!(got.starts_with("# My Project\n\nSome docs.\n\n"));
360 assert!(got.ends_with(&generate_block(&test_settings())));
361 }
362
363 #[test]
364 fn no_markers_and_no_trailing_newline_still_gets_a_blank_line() {
365 let got = desired_file_content(&test_settings(), "# My Project").unwrap();
366 assert!(got.starts_with("# My Project\n\n"));
367 }
368
369 #[test]
370 fn existing_markers_are_replaced_and_everything_else_survives() {
371 let before = format!("before\n\n{START}\nstale\n{END}\n\nafter\n");
372 let got = desired_file_content(&test_settings(), &before).unwrap();
373 assert!(got.starts_with("before\n\n"));
374 assert!(got.ends_with("\n\nafter\n"));
375 assert!(got.contains(&generate_block(&test_settings())));
376 assert!(!got.contains("stale"));
377 }
378
379 #[test]
380 fn applying_twice_is_idempotent() {
381 let once = desired_file_content(&test_settings(), "preamble\n").unwrap();
382 let twice = desired_file_content(&test_settings(), &once).unwrap();
383 assert_eq!(once, twice);
384 }
385
386 #[test]
387 fn an_unpaired_marker_is_refused_not_guessed_at() {
388 assert_eq!(
389 desired_file_content(&test_settings(), &format!("{START}\nno end here\n")),
390 Err(MarkerState::Malformed)
391 );
392 assert_eq!(
393 desired_file_content(&test_settings(), &format!("no start\n{END}\n")),
394 Err(MarkerState::Malformed)
395 );
396 }
397
398 #[test]
403 fn end_appearing_before_start_is_malformed_not_reordered() {
404 assert_eq!(
405 desired_file_content(&test_settings(), &format!("{END}\n...\n{START}\n...\n")),
406 Err(MarkerState::Malformed)
407 );
408 }
409
410 #[test]
411 fn check_reports_not_present_for_a_missing_file() {
412 let tmp = std::env::temp_dir().join("amont-agents-md-test-nonexistent-xyz");
413 let _ = std::fs::remove_file(&tmp);
414 assert_eq!(
415 check(&test_settings(), &tmp).unwrap(),
416 CheckResult::NotPresent
417 );
418 }
419
420 #[test]
421 fn check_reports_matches_generated_after_a_write() {
422 let tmp =
423 std::env::temp_dir().join(format!("amont-agents-md-test-{}-match", std::process::id()));
424 std::fs::write(&tmp, generate_block(&test_settings())).unwrap();
425 assert_eq!(
426 check(&test_settings(), &tmp).unwrap(),
427 CheckResult::MatchesGenerated
428 );
429 let _ = std::fs::remove_file(&tmp);
430 }
431
432 #[test]
433 fn check_reports_drifted_for_a_stale_block() {
434 let tmp =
435 std::env::temp_dir().join(format!("amont-agents-md-test-{}-drift", std::process::id()));
436 std::fs::write(&tmp, format!("{START}\nstale\n{END}\n")).unwrap();
437 assert_eq!(check(&test_settings(), &tmp).unwrap(), CheckResult::Drifted);
438 let _ = std::fs::remove_file(&tmp);
439 }
440}