1use std::ffi::OsString;
15use std::path::Path;
16
17use crate::check::{
18 Builtin, Check, Fix, GitState, Outcome, Reach, Scope, Severity, Stage, Verdict,
19};
20use crate::pushrefs::PushRefs;
21use crate::{dispatch, hooks};
22
23pub struct Ctx<'a> {
27 pub name: &'a str,
29 pub args: &'a [OsString],
31 pub hooks_dir: &'a Path,
34 pub push: &'a PushRefs,
37 pub manifest: &'a crate::manifest::Manifest,
41 pub settings: &'a crate::config::Settings,
46}
47
48pub type HookFn = fn(&Ctx) -> Verdict;
49
50pub const ENTRYPOINTS: &[(&str, HookFn)] = &[
53 ("pre-commit", dispatch::pre_commit),
54 ("pre-push", dispatch::pre_push),
55 ("commit-msg", |ctx| {
62 if !dispatch::conventions_apply(ctx.settings, ctx.manifest) {
63 return Verdict::Proceed;
64 }
65 hooks::commit_msg::run(ctx.settings, ctx.args)
66 }),
67 ("prepare-commit-msg", |ctx| {
68 if !dispatch::conventions_apply(ctx.settings, ctx.manifest) {
69 return Verdict::Proceed;
70 }
71 hooks::prepare_commit_msg::run(ctx.args)
72 }),
73 ("post-commit", |ctx| {
74 hooks::post_commit::run(ctx.settings, ctx)
75 }),
76 ("post-rewrite", |ctx| {
79 hooks::post_rewrite::run(ctx.settings, ctx)
80 }),
81];
82
83const MID_OPERATION: &[GitState] = &[
102 GitState::Merge,
103 GitState::Rebase,
104 GitState::CherryPick,
105 GitState::Revert,
106];
107
108pub const CHECKS: &[Builtin] = &[
109 Builtin {
114 name: "pre-commit-agents-md",
115 stage: Stage::PreCommit,
116 scope: Scope::ALWAYS.not_during(MID_OPERATION),
117 severity: Severity::Warn,
118 fix: Fix::Rewrite,
119 reach: Reach::Convention,
120 run: |ctx| hooks::agents_md_drift::run(ctx.settings),
121 },
122 Builtin {
123 name: "pre-commit-argo-lint",
124 stage: Stage::PreCommit,
125 scope: Scope::new(
126 hooks::k8s::EXTS,
127 &["kustomization.yaml", "kustomization.yml"],
128 )
129 .not_during(MID_OPERATION),
130 severity: Severity::Block,
131 fix: Fix::None,
132 reach: Reach::Convention,
133 run: |ctx| hooks::k8s::argo_lint(ctx.settings, ctx.args),
134 },
135 Builtin {
136 name: "pre-commit-ban-terms",
137 stage: Stage::PreCommit,
138 scope: Scope::files(hooks::ban_terms::EXTS),
139 severity: Severity::Block,
140 fix: Fix::None,
141 reach: Reach::Safety,
142 run: |ctx| hooks::ban_terms::run(ctx.settings, ctx.name, ctx.args),
143 },
144 Builtin {
149 name: "pre-commit-branch-pattern",
150 stage: Stage::PreCommit,
151 scope: Scope::ALWAYS,
152 severity: Severity::Warn,
153 fix: Fix::None,
154 reach: Reach::Convention,
155 run: |ctx| hooks::branch_pattern::early(ctx.settings),
156 },
157 Builtin {
162 name: "pre-commit-branch-protect",
163 stage: Stage::PreCommit,
164 scope: Scope::ALWAYS,
165 severity: Severity::Warn,
166 fix: Fix::None,
167 reach: Reach::Convention,
168 run: |ctx| hooks::branch_protect::early(ctx.settings),
169 },
170 Builtin {
171 name: "pre-commit-cargo-fmt",
172 stage: Stage::PreCommit,
173 scope: Scope::new(hooks::rust_tools::EXTS, &["Cargo.toml"]).not_during(MID_OPERATION),
174 severity: Severity::Block,
175 fix: Fix::Rewrite,
176 reach: Reach::Convention,
177 run: |ctx| hooks::rust_tools::fmt(ctx.settings, ctx.args),
178 },
179 Builtin {
180 name: "pre-commit-clippy",
181 stage: Stage::PreCommit,
182 scope: Scope::new(hooks::rust_tools::EXTS, &["Cargo.toml"]).not_during(MID_OPERATION),
183 severity: Severity::Block,
184 fix: Fix::None,
185 reach: Reach::Convention,
186 run: |ctx| hooks::rust_tools::clippy(ctx.settings, ctx.args),
187 },
188 Builtin {
189 name: "pre-commit-go-vet",
190 stage: Stage::PreCommit,
191 scope: Scope::new(hooks::go_tools::EXTS, &["go.mod"]).not_during(MID_OPERATION),
192 severity: Severity::Block,
193 fix: Fix::None,
194 reach: Reach::Convention,
195 run: |ctx| hooks::go_tools::vet(ctx.settings, ctx.args),
196 },
197 Builtin {
198 name: "pre-commit-gofmt",
199 stage: Stage::PreCommit,
200 scope: Scope::new(hooks::go_tools::EXTS, &["go.mod"]).not_during(MID_OPERATION),
201 severity: Severity::Block,
202 fix: Fix::Rewrite,
203 reach: Reach::Convention,
204 run: |ctx| hooks::go_tools::fmt(ctx.settings, ctx.args),
205 },
206 Builtin {
207 name: "pre-commit-kube-linter",
208 stage: Stage::PreCommit,
209 scope: Scope::new(
210 hooks::k8s::EXTS,
211 &[".kube-linter*.yaml", ".kube-linter*.yml"],
212 )
213 .not_during(MID_OPERATION),
214 severity: Severity::Block,
215 fix: Fix::None,
216 reach: Reach::Convention,
217 run: |ctx| hooks::k8s::kube_linter(ctx.settings, ctx.args),
218 },
219 Builtin {
220 name: "pre-commit-kubeconform",
221 stage: Stage::PreCommit,
222 scope: Scope::new(
223 hooks::k8s::EXTS,
224 &["kustomization.yaml", "kustomization.yml"],
225 )
226 .not_during(MID_OPERATION),
227 severity: Severity::Block,
228 fix: Fix::None,
229 reach: Reach::Convention,
230 run: |ctx| hooks::k8s::kubeconform(ctx.settings, ctx.args),
231 },
232 Builtin {
233 name: "pre-commit-large-files",
234 stage: Stage::PreCommit,
235 scope: Scope::ALWAYS,
236 severity: Severity::Block,
237 fix: Fix::None,
238 reach: Reach::Safety,
239 run: |ctx| hooks::large_files::staged(ctx.settings),
240 },
241 Builtin {
242 name: "pre-commit-lint-js",
243 stage: Stage::PreCommit,
244 scope: Scope::new(hooks::lint_js::EXTS, &["package.json"]).not_during(MID_OPERATION),
245 severity: Severity::Block,
246 fix: Fix::None,
247 reach: Reach::Convention,
248 run: |ctx| hooks::lint_js::run(ctx.settings, ctx.args),
249 },
250 Builtin {
251 name: "pre-commit-lint-json-yaml",
252 stage: Stage::PreCommit,
253 scope: Scope::files(hooks::lint_json_yaml::EXTS).not_during(MID_OPERATION),
254 severity: Severity::Block,
255 fix: Fix::None,
256 reach: Reach::Convention,
257 run: |ctx| hooks::lint_json_yaml::run(ctx.settings, ctx.args),
258 },
259 Builtin {
265 name: "pre-commit-manifest-trust",
266 stage: Stage::PreCommit,
267 scope: Scope::named(&[crate::manifest::MANIFEST]).not_during(MID_OPERATION),
268 severity: Severity::Block,
269 fix: Fix::None,
270 reach: Reach::Safety,
271 run: |ctx| hooks::manifest_trust::run(ctx.settings, ctx.manifest),
272 },
273 Builtin {
274 name: "pre-commit-merge-conflict",
275 stage: Stage::PreCommit,
276 scope: Scope::ALWAYS,
277 severity: Severity::Block,
278 fix: Fix::None,
279 reach: Reach::Safety,
280 run: |ctx| hooks::merge_conflict::run(ctx.settings, ctx.name, ctx.args),
281 },
282 Builtin {
283 name: "pre-commit-package-lock",
284 stage: Stage::PreCommit,
285 scope: Scope::new(&[], &["package.json"]),
286 severity: Severity::Block,
287 fix: Fix::None,
288 reach: Reach::Convention,
289 run: |ctx| hooks::package_lock::run(ctx.settings, ctx.args),
290 },
291 Builtin {
292 name: "pre-commit-prettier",
293 stage: Stage::PreCommit,
294 scope: Scope::new(
295 &[],
296 &[
297 ".prettierrc",
298 ".prettierrc.json",
299 ".prettierrc.yml",
300 ".prettierrc.yaml",
301 ".prettierrc.js",
302 "prettier.config.js",
303 ],
304 )
305 .not_during(MID_OPERATION),
306 severity: Severity::Block,
307 fix: Fix::Rewrite,
308 reach: Reach::Convention,
309 run: |ctx| hooks::prettier::run(ctx.settings, ctx.args),
310 },
311 Builtin {
312 name: "pre-commit-pyright",
313 stage: Stage::PreCommit,
314 scope: Scope::new(
315 hooks::python_tools::EXTS,
316 &[
317 "pyrightconfig.json",
318 "pyrightconfig.jsonc",
319 "pyproject.toml",
320 ],
321 )
322 .not_during(MID_OPERATION),
323 severity: Severity::Block,
324 fix: Fix::None,
325 reach: Reach::Convention,
326 run: |ctx| hooks::python_tools::pyright(ctx.settings, ctx.args),
327 },
328 Builtin {
329 name: "pre-commit-ruff",
330 stage: Stage::PreCommit,
331 scope: Scope::new(
332 hooks::python_tools::EXTS,
333 &["ruff.toml", ".ruff.toml", "pyproject.toml"],
334 )
335 .not_during(MID_OPERATION),
336 severity: Severity::Block,
337 fix: Fix::Rewrite,
338 reach: Reach::Convention,
339 run: |ctx| hooks::python_tools::ruff(ctx.settings, ctx.args),
340 },
341 Builtin {
345 name: "pre-commit-secrets",
346 stage: Stage::PreCommit,
347 scope: Scope::ALWAYS,
348 severity: Severity::Block,
349 fix: Fix::None,
350 reach: Reach::Safety,
351 run: |ctx| hooks::secrets::staged(ctx.settings),
352 },
353 Builtin {
357 name: "pre-commit-tree-parity",
358 stage: Stage::PreCommit,
359 scope: Scope {
360 files: hooks::k8s::EXTS,
361 names: &[crate::manifest::MANIFEST],
362 opt_in: &[crate::manifest::MANIFEST],
363 not_during: MID_OPERATION,
364 },
365 severity: Severity::Block,
366 fix: Fix::None,
367 reach: Reach::Convention,
368 run: |ctx| hooks::tree_parity::run(ctx.settings),
369 },
370 Builtin {
371 name: "pre-commit-usual-name",
372 stage: Stage::PreCommit,
373 scope: Scope::ALWAYS,
374 severity: Severity::Block,
375 fix: Fix::None,
376 reach: Reach::Convention,
377 run: |ctx| hooks::usual_name::run(ctx.args),
378 },
379 Builtin {
380 name: "pre-commit-shellcheck",
381 stage: Stage::PreCommit,
382 scope: Scope::files(hooks::shellcheck::EXTS).not_during(MID_OPERATION),
385 severity: Severity::Block,
386 fix: Fix::None,
387 reach: Reach::Convention,
388 run: |ctx| hooks::shellcheck::run(ctx.settings, ctx.args),
389 },
390 Builtin {
391 name: "pre-commit-hadolint",
392 stage: Stage::PreCommit,
393 scope: Scope::named(hooks::hadolint::NAMES).not_during(MID_OPERATION),
397 severity: Severity::Block,
398 fix: Fix::None,
399 reach: Reach::Convention,
400 run: |ctx| hooks::hadolint::run(ctx.settings, ctx.args),
401 },
402 Builtin {
403 name: "pre-commit-helm-lint",
404 stage: Stage::PreCommit,
405 scope: Scope::new(hooks::helm::EXTS, hooks::helm::MARKERS).not_during(MID_OPERATION),
408 severity: Severity::Block,
409 fix: Fix::None,
410 reach: Reach::Convention,
411 run: |ctx| hooks::helm::run(ctx.settings, ctx.args),
412 },
413 Builtin {
414 name: "pre-commit-yamllint",
415 stage: Stage::PreCommit,
416 scope: Scope::new(
417 hooks::yamllint::EXTS,
418 &[".yamllint.yaml", ".yamllint.yml", ".yamllint"],
419 )
420 .not_during(MID_OPERATION),
421 severity: Severity::Block,
422 fix: Fix::None,
423 reach: Reach::Convention,
424 run: |ctx| hooks::yamllint::run(ctx.settings, ctx.args),
425 },
426 Builtin {
428 name: "pre-push-branch-protect",
429 stage: Stage::PrePush,
430 scope: Scope::ALWAYS,
431 severity: Severity::Block,
432 fix: Fix::None,
433 reach: Reach::Convention,
434 run: |ctx| hooks::branch_protect::run(ctx.settings, ctx.push.get()),
435 },
436 Builtin {
437 name: "pre-push-branch-pattern",
438 stage: Stage::PrePush,
439 scope: Scope::ALWAYS,
440 severity: Severity::Block,
441 fix: Fix::None,
442 reach: Reach::Convention,
443 run: |ctx| hooks::branch_pattern::run(ctx.settings, ctx.push.get(), ctx.args),
444 },
445 Builtin {
446 name: "pre-push-secrets",
447 stage: Stage::PrePush,
448 scope: Scope::ALWAYS,
449 severity: Severity::Block,
450 fix: Fix::None,
451 reach: Reach::Safety,
452 run: |ctx| hooks::secrets::pushed(ctx.settings, ctx.push.get()),
453 },
454 Builtin {
455 name: "pre-push-pull-rebase",
456 stage: Stage::PrePush,
457 scope: Scope::ALWAYS.not_during(&[GitState::Rebase, GitState::Merge]),
458 severity: Severity::Block,
459 fix: Fix::None,
460 reach: Reach::Convention,
461 run: |ctx| hooks::pull_rebase::run(ctx.settings, ctx.args),
462 },
463 Builtin {
470 name: "pre-push-audit-go",
471 stage: Stage::PrePush,
472 scope: Scope::new(&[], &["go.sum"]),
473 severity: Severity::Block,
474 fix: Fix::None,
475 reach: Reach::Convention,
476 run: |ctx| hooks::audit::go(ctx.settings, ctx.push.get()),
477 },
478 Builtin {
482 name: "pre-push-audit-js",
483 stage: Stage::PrePush,
484 scope: Scope::new(&[], &["package-lock.json", "pnpm-lock.yaml"]),
485 severity: Severity::Block,
486 fix: Fix::None,
487 reach: Reach::Convention,
488 run: |ctx| hooks::audit::js(ctx.settings, ctx.push.get()),
489 },
490 Builtin {
495 name: "pre-push-audit-python",
496 stage: Stage::PrePush,
497 scope: Scope::new(&[], &["requirements.txt", "pyproject.toml"]),
498 severity: Severity::Block,
499 fix: Fix::None,
500 reach: Reach::Convention,
501 run: |ctx| hooks::audit::python(ctx.settings, ctx.push.get()),
502 },
503 Builtin {
504 name: "pre-push-audit-rust",
505 stage: Stage::PrePush,
506 scope: Scope::new(&[], &["Cargo.lock"]),
507 severity: Severity::Block,
508 fix: Fix::None,
509 reach: Reach::Convention,
510 run: |ctx| hooks::audit::rust(ctx.settings, ctx.push.get()),
511 },
512 Builtin {
513 name: "pre-push-run-tests-js",
514 stage: Stage::PrePush,
515 scope: Scope::new(hooks::run_tests::JS_EXTS, &["package.json"])
516 .not_during(&[GitState::Bisect, GitState::Rebase]),
517 severity: Severity::Block,
518 fix: Fix::None,
519 reach: Reach::Convention,
520 run: |ctx| {
521 hooks::run_tests::run(
522 ctx.settings,
523 ctx.push.get(),
524 &ctx.manifest.externals,
525 ctx.name,
526 )
527 },
528 },
529 Builtin {
530 name: "pre-push-cargo-test",
531 stage: Stage::PrePush,
532 scope: Scope::new(hooks::rust_tools::EXTS, &["Cargo.toml"])
533 .not_during(&[GitState::Bisect, GitState::Rebase]),
534 severity: Severity::Block,
535 fix: Fix::None,
536 reach: Reach::Convention,
537 run: |ctx| hooks::rust_tools::test(ctx.settings, ctx.push.get(), ctx.name),
538 },
539 Builtin {
540 name: "pre-push-go-test",
541 stage: Stage::PrePush,
542 scope: Scope::new(hooks::go_tools::EXTS, &["go.mod"])
543 .not_during(&[GitState::Bisect, GitState::Rebase]),
544 severity: Severity::Block,
545 fix: Fix::None,
546 reach: Reach::Convention,
547 run: |ctx| hooks::go_tools::test(ctx.settings, ctx.push.get(), ctx.name),
548 },
549 Builtin {
550 name: "pre-push-pytest",
551 stage: Stage::PrePush,
552 scope: Scope::new(hooks::python_tools::EXTS, &["pytest.ini", "conftest.py"])
553 .not_during(&[GitState::Bisect, GitState::Rebase]),
554 severity: Severity::Block,
555 fix: Fix::None,
556 reach: Reach::Convention,
557 run: |ctx| hooks::python_tools::pytest(ctx.settings, ctx.push.get(), ctx.name),
558 },
559];
560
561pub fn severity_of(settings: &crate::config::Settings, check: &dyn Check) -> Severity {
567 effective_override(settings, None, check.name()).unwrap_or_else(|| check.severity())
568}
569
570pub fn severity_key(check: &str) -> String {
572 format!("amont.severity.{check}")
573}
574
575#[derive(Debug, Default, Clone)]
586pub struct Overrides(std::collections::BTreeMap<String, (Severity, Source)>);
587
588#[derive(Debug, Clone, Copy, PartialEq, Eq)]
592pub enum Source {
593 Config,
594 Policy,
595}
596
597impl Source {
598 pub fn as_str(self) -> &'static str {
599 match self {
600 Source::Config => "config",
601 Source::Policy => "policy",
602 }
603 }
604}
605
606impl Overrides {
607 pub fn read(settings: &crate::config::Settings) -> Overrides {
614 let policy = settings.policy();
615 match crate::git::stdout(&[
616 "config",
617 "--show-scope",
618 "--get-regexp",
619 r"^amont\.severity\.",
620 ]) {
621 Some(scoped) => Overrides::from_scoped(&scoped, policy),
622 None => Overrides::from_plain_with_policy_below(
626 crate::git::stdout(&["config", "--get-regexp", r"^amont\.severity\."]),
627 policy,
628 ),
629 }
630 }
631
632 pub fn from_scoped(scoped: &str, policy: &crate::policy::Policy) -> Overrides {
639 let mut below = String::new();
640 let mut above = String::new();
641 for line in scoped.lines() {
642 let Some((scope, rest)) = line.split_once('\t') else {
643 continue;
644 };
645 match scope {
646 "system" | "global" => {
647 below.push_str(rest);
648 below.push('\n');
649 }
650 _ => {
651 above.push_str(rest);
652 above.push('\n');
653 }
654 }
655 }
656 let mut o = Overrides::default();
657 o.fold_plain(&below, Source::Config);
658 o.fold_policy(policy);
659 o.fold_plain(&above, Source::Config);
660 o
661 }
662
663 pub fn from_plain_with_policy_below(
668 plain: Option<String>,
669 policy: &crate::policy::Policy,
670 ) -> Overrides {
671 let mut o = Overrides::default();
672 o.fold_policy(policy);
673 o.fold_plain(plain.as_deref().unwrap_or_default(), Source::Config);
674 o
675 }
676
677 fn fold_policy(&mut self, policy: &crate::policy::Policy) {
680 for (target, severity) in &policy.severities {
681 self.0.insert(target.clone(), (*severity, Source::Policy));
682 }
683 }
684
685 fn fold_plain(&mut self, text: &str, source: Source) {
689 for line in text.lines() {
690 let Some((key, value)) = line.split_once(' ') else {
691 continue;
692 };
693 let Some(check) = key.strip_prefix("amont.severity.") else {
694 continue;
695 };
696 match Severity::parse(value.trim()) {
697 Some(sev) => {
698 self.0.insert(check.to_string(), (sev, source));
699 }
700 None => {
701 self.0.remove(check);
702 }
703 }
704 }
705 }
706
707 pub fn from_config(out: Option<String>) -> Overrides {
715 let mut o = Overrides::default();
716 o.fold_plain(out.as_deref().unwrap_or_default(), Source::Config);
717 o
718 }
719
720 pub fn applied_to(&self, check: &str) -> Option<(&str, Severity)> {
727 self.applied_with_source(check)
728 .map(|(pattern, severity, _)| (pattern, severity))
729 }
730
731 pub fn applied_with_source(&self, check: &str) -> Option<(&str, Severity, Source)> {
735 self.0
736 .iter()
737 .filter_map(|(pattern, (severity, source))| {
738 crate::names_check(check, pattern)
739 .map(|m| (m, pattern.as_str(), *severity, *source))
740 })
741 .max_by_key(|(m, _, _, _)| *m)
742 .map(|(_, pattern, severity, source)| (pattern, severity, source))
743 }
744
745 pub fn of(&self, check: &dyn Check) -> Severity {
747 self.applied_to(check.name())
748 .map(|(_, severity)| severity)
749 .unwrap_or_else(|| check.severity())
750 }
751}
752
753#[cfg(test)]
754mod precedence {
755 use super::{Overrides, Severity};
756
757 fn overrides(lines: &[&str]) -> Overrides {
758 let text = lines
759 .iter()
760 .map(|l| format!("amont.severity.{l}\n"))
761 .collect::<String>();
762 Overrides::from_config(Some(text))
763 }
764
765 #[test]
769 fn the_more_specific_key_wins() {
770 let both = overrides(&["pre-commit warn", "pre-commit-clippy block"]);
771 assert_eq!(
772 both.applied_to("pre-commit-clippy"),
773 Some(("pre-commit-clippy", Severity::Block)),
774 "a full id beats its trigger"
775 );
776 assert_eq!(
777 both.applied_to("pre-commit-shellcheck"),
778 Some(("pre-commit", Severity::Warn)),
779 "and the trigger still governs every check it did not exempt"
780 );
781 }
782
783 #[test]
786 fn the_three_ways_to_name_a_check_are_ranked() {
787 let all = overrides(&["pre-commit warn", "clippy block", "pre-commit-clippy warn"]);
788 assert_eq!(
789 all.applied_to("pre-commit-clippy"),
790 Some(("pre-commit-clippy", Severity::Warn))
791 );
792
793 let no_full = overrides(&["pre-commit warn", "clippy block"]);
794 assert_eq!(
795 no_full.applied_to("pre-commit-clippy"),
796 Some(("clippy", Severity::Block)),
797 "a short name beats a trigger"
798 );
799 }
800
801 #[test]
804 fn a_key_that_names_no_check_applies_to_nothing() {
805 let typo = overrides(&["clipy warn", "e warn", " warn"]);
806 assert_eq!(typo.applied_to("pre-commit-clippy"), None);
807 }
808}
809
810pub fn effective_override(
820 settings: &crate::config::Settings,
821 repo: Option<&Path>,
822 check: &str,
823) -> Option<Severity> {
824 overrides_in(settings, repo)
825 .applied_to(check)
826 .map(|(_, s)| s)
827}
828
829pub fn effective_key(
835 settings: &crate::config::Settings,
836 repo: Option<&Path>,
837 check: &str,
838) -> Option<String> {
839 overrides_in(settings, repo)
840 .applied_to(check)
841 .map(|(pattern, _)| pattern.to_string())
842}
843
844fn overrides_in(settings: &crate::config::Settings, repo: Option<&Path>) -> Overrides {
845 match repo {
846 None => Overrides::read(settings),
850 Some(dir) => Overrides::from_config(crate::git::stdout_in(
854 dir,
855 &["config", "--get-regexp", r"^amont\.severity\."],
856 )),
857 }
858}
859
860pub fn stage_checks(stage: Stage) -> impl Iterator<Item = &'static Builtin> {
862 CHECKS.iter().filter(move |check| check.stage == stage)
863}
864
865pub fn all_stage_checks<'a>(
872 stage: Stage,
873 manifest: &'a crate::manifest::Manifest,
874) -> Vec<&'a dyn Check> {
875 let mut out: Vec<&'a dyn Check> = stage_checks(stage)
876 .map(|check| check as &dyn Check)
877 .collect();
878 out.extend(
879 manifest
880 .externals
881 .iter()
882 .filter(|external| external.stage == stage)
883 .map(|external| external as &dyn Check),
884 );
885 out
886}
887
888pub fn lookup(name: &str, manifest: &crate::manifest::Manifest) -> Option<HookFn> {
889 if let Some((_, f)) = ENTRYPOINTS.iter().find(|(n, _)| *n == name) {
890 return Some(*f);
891 }
892 if CHECKS.iter().any(|check| check.name == name)
899 || manifest
900 .externals
901 .iter()
902 .any(|external| external.id == name)
903 {
904 return Some(|ctx: &Ctx| {
905 let check = one_named(ctx.name, ctx.manifest).expect("checked above");
906 Verdict::blocking(matches!(
907 (check.run(ctx), severity_of(ctx.settings, check)),
908 (Outcome::Failed, Severity::Block)
909 ))
910 });
911 }
912 None
913}
914
915pub fn one_named<'a>(name: &str, manifest: &'a crate::manifest::Manifest) -> Option<&'a dyn Check> {
919 if let Some(builtin) = CHECKS.iter().find(|check| check.name == name) {
920 return Some(builtin);
921 }
922 manifest
923 .externals
924 .iter()
925 .find(|external| external.id == name)
926 .map(|external| external as &dyn Check)
927}
928
929#[cfg(test)]
930mod tests {
931 use super::{lookup, Overrides, Reach, Severity, Stage, CHECKS, ENTRYPOINTS};
932 use std::collections::BTreeSet;
933
934 #[test]
941 fn the_batch_agrees_with_the_authority() {
942 let d = std::env::temp_dir().join(format!("ov-{}", std::process::id()));
943 let _ = std::fs::remove_dir_all(&d);
944 std::fs::create_dir_all(&d).unwrap();
945 let git = |args: &[&str]| {
946 std::process::Command::new("git")
947 .args(args)
948 .current_dir(&d)
949 .output()
950 .expect("git");
951 };
952 git(&["init", "-q", "--template=", "."]);
953 let key = "amont.severity.pre-commit-merge-conflict";
954 git(&["config", "--add", key, "warn"]);
955 git(&["config", "--add", key, "block"]);
956
957 let raw = std::process::Command::new("git")
958 .args(["config", "--get-regexp", r"^amont\.severity\."])
959 .current_dir(&d)
960 .output()
961 .expect("git");
962 let batch = Overrides::from_config(Some(
963 String::from_utf8_lossy(&raw.stdout).trim().to_string(),
964 ));
965 let authority =
966 crate::git::stdout_in(&d, &["config", "--get", key]).and_then(|v| Severity::parse(&v));
967 let _ = std::fs::remove_dir_all(&d);
968
969 assert_eq!(
970 authority,
971 Some(Severity::Block),
972 "git applies the last entry"
973 );
974 assert_eq!(
975 batch.0.get("pre-commit-merge-conflict").map(|(s, _)| *s),
976 authority,
977 "the batch reader disagreed with `--get`"
978 );
979 }
980
981 #[test]
985 fn an_unrecognised_value_clears_rather_than_overrides() {
986 let o = Overrides::from_config(Some(
987 "amont.severity.a warn\namont.severity.a advisory\namont.severity.b warn".to_string(),
988 ));
989 assert_eq!(o.0.get("a"), None, "a typo must not leave `warn` standing");
990 assert_eq!(o.0.get("b").map(|(s, _)| *s), Some(Severity::Warn));
991 }
992
993 #[test]
994 fn names_are_unique_across_entrypoints_and_checks() {
995 let mut seen = BTreeSet::new();
996 for n in ENTRYPOINTS
997 .iter()
998 .map(|(n, _)| *n)
999 .chain(CHECKS.iter().map(|check| check.name))
1000 {
1001 assert!(seen.insert(n), "duplicate registration: {n}");
1002 }
1003 }
1004
1005 #[test]
1007 fn the_shipped_shims_are_exactly_the_git_invoked_hooks() {
1008 let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../templates/hooks");
1009 let mut shipped: Vec<String> = std::fs::read_dir(dir)
1010 .expect("templates/hooks")
1011 .flatten()
1012 .map(|entry| entry.file_name().to_string_lossy().into_owned())
1013 .collect();
1014 shipped.sort();
1015 assert_eq!(
1016 shipped,
1017 vec![
1018 "commit-msg",
1019 "post-commit",
1020 "post-rewrite",
1021 "pre-commit",
1022 "pre-push",
1023 "prepare-commit-msg"
1024 ]
1025 );
1026 let none = crate::manifest::Manifest::default();
1027 for name in &shipped {
1028 assert!(
1029 lookup(name, &none).is_some(),
1030 "shipped shim {name:?} has no handler"
1031 );
1032 }
1033 }
1034
1035 #[test]
1038 fn every_check_is_reachable_by_name() {
1039 let none = crate::manifest::Manifest::default();
1040 for check in CHECKS {
1041 assert!(
1042 lookup(check.name, &none).is_some(),
1043 "{} not reachable",
1044 check.name
1045 );
1046 }
1047 assert!(lookup("pre-commit-not-a-check", &none).is_none());
1048 }
1049
1050 #[test]
1052 fn pre_push_runs_cheapest_first() {
1053 let order: Vec<&str> = super::stage_checks(Stage::PrePush)
1054 .map(|check| check.name)
1055 .collect();
1056 assert_eq!(
1057 order,
1058 vec![
1059 "pre-push-branch-protect",
1060 "pre-push-branch-pattern",
1061 "pre-push-secrets",
1062 "pre-push-pull-rebase",
1063 "pre-push-audit-go",
1064 "pre-push-audit-js",
1065 "pre-push-audit-python",
1066 "pre-push-audit-rust",
1067 "pre-push-run-tests-js",
1068 "pre-push-cargo-test",
1069 "pre-push-go-test",
1070 "pre-push-pytest",
1071 ]
1072 );
1073 }
1074
1075 enum Consumes {
1081 All,
1082 Exts(&'static [&'static str]),
1083 }
1084
1085 const CONSUMED: &[(&str, Consumes)] = &[
1099 (
1100 "pre-commit-argo-lint",
1101 Consumes::Exts(crate::hooks::k8s::EXTS),
1102 ),
1103 (
1107 "pre-commit-ban-terms",
1108 Consumes::Exts(crate::hooks::ban_terms::EXTS),
1109 ),
1110 (
1111 "pre-commit-cargo-fmt",
1112 Consumes::Exts(crate::hooks::rust_tools::EXTS),
1113 ),
1114 (
1115 "pre-commit-clippy",
1116 Consumes::Exts(crate::hooks::rust_tools::RUST_PATHS),
1117 ),
1118 (
1119 "pre-commit-go-vet",
1120 Consumes::Exts(crate::hooks::go_tools::GO_PATHS),
1121 ),
1122 (
1123 "pre-commit-gofmt",
1124 Consumes::Exts(crate::hooks::go_tools::EXTS),
1125 ),
1126 (
1127 "pre-commit-kube-linter",
1128 Consumes::Exts(crate::hooks::k8s::EXTS),
1129 ),
1130 (
1131 "pre-commit-kubeconform",
1132 Consumes::Exts(crate::hooks::k8s::EXTS),
1133 ),
1134 (
1135 "pre-commit-lint-js",
1136 Consumes::Exts(crate::hooks::lint_js::EXTS),
1137 ),
1138 (
1139 "pre-commit-lint-json-yaml",
1140 Consumes::Exts(crate::hooks::lint_json_yaml::EXTS),
1141 ),
1142 ("pre-commit-merge-conflict", Consumes::All),
1143 ("pre-commit-package-lock", Consumes::All),
1144 (
1148 "pre-commit-prettier",
1149 Consumes::Exts(crate::hooks::prettier::EXTS),
1150 ),
1151 (
1152 "pre-commit-pyright",
1153 Consumes::Exts(crate::hooks::python_tools::EXTS),
1154 ),
1155 (
1156 "pre-commit-ruff",
1157 Consumes::Exts(crate::hooks::python_tools::EXTS),
1158 ),
1159 ("pre-commit-usual-name", Consumes::All),
1160 (
1161 "pre-commit-yamllint",
1162 Consumes::Exts(crate::hooks::yamllint::EXTS),
1163 ),
1164 (
1165 "pre-commit-shellcheck",
1166 Consumes::Exts(crate::hooks::shellcheck::EXTS),
1167 ),
1168 (
1169 "pre-commit-hadolint",
1170 Consumes::Exts(crate::hooks::hadolint::NAMES),
1171 ),
1172 (
1173 "pre-commit-helm-lint",
1174 Consumes::Exts(crate::hooks::helm::EXTS),
1175 ),
1176 ("pre-commit-large-files", Consumes::All),
1177 ("pre-commit-secrets", Consumes::All),
1178 ("pre-push-secrets", Consumes::All),
1179 ("pre-push-branch-protect", Consumes::All),
1180 ("pre-push-branch-pattern", Consumes::All),
1181 ("pre-push-pull-rebase", Consumes::All),
1182 (
1183 "pre-push-run-tests-js",
1184 Consumes::Exts(crate::hooks::run_tests::JS_EXTS),
1185 ),
1186 (
1187 "pre-push-pytest",
1188 Consumes::Exts(crate::hooks::python_tools::EXTS),
1189 ),
1190 (
1191 "pre-push-cargo-test",
1192 Consumes::Exts(crate::hooks::rust_tools::RUST_PATHS),
1193 ),
1194 (
1195 "pre-push-go-test",
1196 Consumes::Exts(crate::hooks::go_tools::GO_PATHS),
1197 ),
1198 (
1200 "pre-commit-tree-parity",
1201 Consumes::Exts(crate::hooks::k8s::EXTS),
1202 ),
1203 ];
1204
1205 #[test]
1216 fn no_check_declares_a_file_type_it_does_not_consume() {
1217 for (name, _) in CONSUMED {
1218 assert!(
1219 CHECKS.iter().any(|check| check.name == *name),
1220 "CONSUMED names {name:?}, which is not a check"
1221 );
1222 }
1223 for check in CHECKS {
1224 let entry = CONSUMED.iter().find(|(name, _)| *name == check.name);
1225 if check.scope.files.is_empty() && entry.is_none() {
1226 continue;
1227 }
1228 let Some((_, consumes)) = entry else {
1229 panic!(
1230 "{} declares scope.files {:?} but is missing from CONSUMED — \
1231 say what it actually reads",
1232 check.name, check.scope.files
1233 );
1234 };
1235 let Consumes::Exts(consumed) = consumes else {
1236 continue; };
1238 for ext in check.scope.files {
1239 assert!(
1240 consumed.contains(ext),
1241 "{} declares {ext:?} in its scope but never asks for it — \
1242 `amont list` would report a coverage the check does not have",
1243 check.name
1244 );
1245 }
1246 }
1247 }
1248
1249 const HAS_FIXING_CODE: &[(&str, bool)] = &[
1258 ("pre-commit-agents-md", true),
1259 ("pre-commit-argo-lint", false),
1260 ("pre-commit-ban-terms", false),
1261 ("pre-commit-branch-pattern", false),
1262 ("pre-commit-branch-protect", false),
1263 ("pre-commit-cargo-fmt", true),
1264 ("pre-commit-clippy", false),
1265 ("pre-commit-go-vet", false),
1266 ("pre-commit-gofmt", true),
1267 ("pre-commit-kube-linter", false),
1268 ("pre-commit-kubeconform", false),
1269 ("pre-commit-lint-js", false),
1270 ("pre-commit-lint-json-yaml", false),
1271 ("pre-commit-manifest-trust", false),
1272 ("pre-commit-merge-conflict", false),
1273 ("pre-commit-package-lock", false),
1274 ("pre-commit-prettier", true),
1275 ("pre-commit-pyright", false),
1276 ("pre-commit-ruff", true),
1277 ("pre-commit-tree-parity", false),
1278 ("pre-commit-usual-name", false),
1279 ("pre-commit-yamllint", false),
1280 ("pre-commit-shellcheck", false),
1281 ("pre-commit-hadolint", false),
1282 ("pre-commit-helm-lint", false),
1283 ("pre-commit-large-files", false),
1284 ("pre-commit-secrets", false),
1285 ("pre-push-secrets", false),
1286 ("pre-push-branch-protect", false),
1287 ("pre-push-branch-pattern", false),
1288 ("pre-push-pull-rebase", false),
1289 ("pre-push-audit-go", false),
1290 ("pre-push-audit-js", false),
1291 ("pre-push-audit-python", false),
1292 ("pre-push-audit-rust", false),
1293 ("pre-push-run-tests-js", false),
1294 ("pre-push-cargo-test", false),
1295 ("pre-push-go-test", false),
1296 ("pre-push-pytest", false),
1297 ];
1298
1299 #[test]
1302 fn every_rewrite_declaration_has_a_fixer() {
1303 let declared: BTreeSet<&str> = CHECKS
1304 .iter()
1305 .filter(|check| check.fix == super::Fix::Rewrite)
1306 .map(|check| check.name)
1307 .collect();
1308 let implemented: BTreeSet<&str> = HAS_FIXING_CODE
1309 .iter()
1310 .filter(|(_, has)| *has)
1311 .map(|(name, _)| *name)
1312 .collect();
1313 assert_eq!(
1314 declared, implemented,
1315 "a check declaring Fix::Rewrite with no fixer lies to `amont list --json`, \
1316 and a check with a fixer that does not declare it can never be reached"
1317 );
1318
1319 let listed: BTreeSet<&str> = HAS_FIXING_CODE.iter().map(|(name, _)| *name).collect();
1322 let all: BTreeSet<&str> = CHECKS.iter().map(|check| check.name).collect();
1323 assert_eq!(listed, all, "HAS_FIXING_CODE does not cover CHECKS");
1324 }
1325
1326 #[test]
1337 fn the_safety_net_is_exactly_the_low_false_positive_set() {
1338 let safety: Vec<&str> = CHECKS
1339 .iter()
1340 .filter(|c| c.reach == Reach::Safety)
1341 .map(|c| c.name)
1342 .collect();
1343 assert_eq!(
1344 safety,
1345 vec![
1346 "pre-commit-ban-terms",
1347 "pre-commit-large-files",
1348 "pre-commit-manifest-trust",
1349 "pre-commit-merge-conflict",
1350 "pre-commit-secrets",
1351 "pre-push-secrets",
1352 ]
1353 );
1354 }
1355
1356 #[test]
1357 fn every_check_declares_a_stage_and_a_scope() {
1358 assert_eq!(CHECKS.len(), 39);
1359 let pre_commit = super::stage_checks(Stage::PreCommit).count();
1360 let pre_push = super::stage_checks(Stage::PrePush).count();
1361 assert_eq!(
1362 pre_commit + pre_push,
1363 CHECKS.len(),
1364 "every check has a stage"
1365 );
1366 }
1367}