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 pub handed_to_cluster: &'a [String],
50 pub land: &'a crate::rehearsal::LandEnv,
53 pub audits: &'a crate::hooks::audit::Ledger,
56 pub source_worktree: Option<&'a std::path::Path>,
59}
60
61pub type HookFn = fn(&Ctx) -> Verdict;
62
63pub const ENTRYPOINTS: &[(&str, HookFn)] = &[
66 ("pre-commit", dispatch::pre_commit),
67 ("pre-push", dispatch::pre_push),
68 ("commit-msg", |ctx| {
75 if !dispatch::conventions_apply(ctx.settings, ctx.manifest) {
76 return Verdict::Proceed;
77 }
78 hooks::commit_msg::run(ctx.settings, ctx.args)
79 }),
80 ("prepare-commit-msg", |ctx| {
81 if !dispatch::conventions_apply(ctx.settings, ctx.manifest) {
82 return Verdict::Proceed;
83 }
84 hooks::prepare_commit_msg::run(ctx.args)
85 }),
86 ("post-commit", |ctx| {
87 hooks::post_commit::run(ctx.settings, ctx)
88 }),
89 ("post-rewrite", |ctx| {
92 hooks::post_rewrite::run(ctx.settings, ctx)
93 }),
94];
95
96const MID_OPERATION: &[GitState] = &[
115 GitState::Merge,
116 GitState::Rebase,
117 GitState::CherryPick,
118 GitState::Revert,
119];
120
121pub const CHECKS: &[Builtin] = &[
122 Builtin {
127 name: "pre-commit-agents-md",
128 stage: Stage::PreCommit,
129 scope: Scope::ALWAYS.not_during(MID_OPERATION),
130 severity: Severity::Warn,
131 fix: Fix::Rewrite,
132 reach: Reach::Convention,
133 run: |ctx| hooks::agents_md_drift::run(ctx.settings),
134 },
135 Builtin {
136 name: "pre-commit-argo-lint",
137 stage: Stage::PreCommit,
138 scope: Scope::new(
139 hooks::k8s::EXTS,
140 &["kustomization.yaml", "kustomization.yml"],
141 )
142 .not_during(MID_OPERATION),
143 severity: Severity::Block,
144 fix: Fix::None,
145 reach: Reach::Convention,
146 run: |ctx| hooks::k8s::argo_lint(ctx.settings, ctx.args),
147 },
148 Builtin {
149 name: "pre-commit-ban-terms",
150 stage: Stage::PreCommit,
151 scope: Scope::files(hooks::ban_terms::EXTS),
152 severity: Severity::Block,
153 fix: Fix::None,
154 reach: Reach::Safety,
155 run: |ctx| hooks::ban_terms::run(ctx.settings, ctx.name, ctx.args),
156 },
157 Builtin {
162 name: "pre-commit-branch-pattern",
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_pattern::early(ctx.settings),
169 },
170 Builtin {
175 name: "pre-commit-branch-protect",
176 stage: Stage::PreCommit,
177 scope: Scope::ALWAYS,
178 severity: Severity::Warn,
179 fix: Fix::None,
180 reach: Reach::Convention,
181 run: |ctx| hooks::branch_protect::early(ctx.settings),
182 },
183 Builtin {
184 name: "pre-commit-cargo-fmt",
185 stage: Stage::PreCommit,
186 scope: Scope::new(hooks::rust_tools::EXTS, &["Cargo.toml"]).not_during(MID_OPERATION),
187 severity: Severity::Block,
188 fix: Fix::Rewrite,
189 reach: Reach::Convention,
190 run: |ctx| hooks::rust_tools::fmt(ctx.settings, ctx.args),
191 },
192 Builtin {
193 name: "pre-commit-clippy",
194 stage: Stage::PreCommit,
195 scope: Scope::new(hooks::rust_tools::EXTS, &["Cargo.toml"]).not_during(MID_OPERATION),
200 severity: Severity::Block,
201 fix: Fix::None,
202 reach: Reach::Convention,
203 run: |ctx| hooks::rust_tools::clippy(ctx.settings, ctx.args),
204 },
205 Builtin {
206 name: "pre-commit-go-vet",
207 stage: Stage::PreCommit,
208 scope: Scope::new(hooks::go_tools::EXTS, &["go.mod"]).not_during(MID_OPERATION),
209 severity: Severity::Block,
210 fix: Fix::None,
211 reach: Reach::Convention,
212 run: |ctx| hooks::go_tools::vet(ctx.settings, ctx.args),
213 },
214 Builtin {
215 name: "pre-commit-gofmt",
216 stage: Stage::PreCommit,
217 scope: Scope::new(hooks::go_tools::EXTS, &["go.mod"]).not_during(MID_OPERATION),
218 severity: Severity::Block,
219 fix: Fix::Rewrite,
220 reach: Reach::Convention,
221 run: |ctx| hooks::go_tools::fmt(ctx.settings, ctx.args),
222 },
223 Builtin {
224 name: "pre-commit-kube-linter",
225 stage: Stage::PreCommit,
226 scope: Scope::new(
227 hooks::k8s::EXTS,
228 &[".kube-linter*.yaml", ".kube-linter*.yml"],
229 )
230 .not_during(MID_OPERATION),
231 severity: Severity::Block,
232 fix: Fix::None,
233 reach: Reach::Convention,
234 run: |ctx| hooks::k8s::kube_linter(ctx.settings, ctx.args),
235 },
236 Builtin {
237 name: "pre-commit-kubeconform",
238 stage: Stage::PreCommit,
239 scope: Scope::new(
240 hooks::k8s::EXTS,
241 &["kustomization.yaml", "kustomization.yml"],
242 )
243 .not_during(MID_OPERATION),
244 severity: Severity::Block,
245 fix: Fix::None,
246 reach: Reach::Convention,
247 run: |ctx| hooks::k8s::kubeconform(ctx.settings, ctx.args),
248 },
249 Builtin {
250 name: "pre-commit-large-files",
251 stage: Stage::PreCommit,
252 scope: Scope::ALWAYS,
253 severity: Severity::Block,
254 fix: Fix::None,
255 reach: Reach::Safety,
256 run: |ctx| hooks::large_files::staged(ctx.settings),
257 },
258 Builtin {
259 name: "pre-commit-lint-js",
260 stage: Stage::PreCommit,
261 scope: Scope::new(hooks::lint_js::EXTS, &["package.json"]).not_during(MID_OPERATION),
262 severity: Severity::Block,
263 fix: Fix::None,
264 reach: Reach::Convention,
265 run: |ctx| hooks::lint_js::run(ctx.settings, ctx.args),
266 },
267 Builtin {
268 name: "pre-commit-lint-json-yaml",
269 stage: Stage::PreCommit,
270 scope: Scope::files(hooks::lint_json_yaml::EXTS).not_during(MID_OPERATION),
271 severity: Severity::Block,
272 fix: Fix::None,
273 reach: Reach::Convention,
274 run: |ctx| hooks::lint_json_yaml::run(ctx.settings, ctx.args),
275 },
276 Builtin {
282 name: "pre-commit-manifest-trust",
283 stage: Stage::PreCommit,
284 scope: Scope::named(&[crate::manifest::MANIFEST, crate::names::old::MANIFEST])
287 .not_during(MID_OPERATION),
288 severity: Severity::Block,
289 fix: Fix::None,
290 reach: Reach::Safety,
291 run: |ctx| hooks::manifest_trust::run(ctx.settings, ctx.manifest),
292 },
293 Builtin {
294 name: "pre-commit-merge-conflict",
295 stage: Stage::PreCommit,
296 scope: Scope::ALWAYS,
297 severity: Severity::Block,
298 fix: Fix::None,
299 reach: Reach::Safety,
300 run: |ctx| hooks::merge_conflict::run(ctx.settings, ctx.name, ctx.args),
301 },
302 Builtin {
303 name: "pre-commit-package-lock",
304 stage: Stage::PreCommit,
305 scope: Scope::new(&[], &["package.json"]),
306 severity: Severity::Block,
307 fix: Fix::None,
308 reach: Reach::Convention,
309 run: |ctx| hooks::package_lock::run(ctx.settings, ctx.args),
310 },
311 Builtin {
312 name: "pre-commit-prettier",
313 stage: Stage::PreCommit,
314 scope: Scope::new(
315 &[],
316 &[
319 ".prettierrc",
320 ".prettierrc.json",
321 ".prettierrc.yml",
322 ".prettierrc.yaml",
323 ".prettierrc.js",
324 ".prettierrc.cjs",
325 ".prettierrc.mjs",
326 ".prettierrc.toml",
327 "prettier.config.js",
328 "prettier.config.mjs",
329 "prettier.config.cjs",
330 ],
331 )
332 .not_during(MID_OPERATION),
333 severity: Severity::Block,
334 fix: Fix::Rewrite,
335 reach: Reach::Convention,
336 run: |ctx| hooks::prettier::run(ctx.settings, ctx.args),
337 },
338 Builtin {
339 name: "pre-commit-pyright",
340 stage: Stage::PreCommit,
341 scope: Scope::new(
342 hooks::python_tools::EXTS,
343 &[
344 "pyrightconfig.json",
345 "pyrightconfig.jsonc",
346 "pyproject.toml",
347 ],
348 )
349 .not_during(MID_OPERATION),
350 severity: Severity::Block,
351 fix: Fix::None,
352 reach: Reach::Convention,
353 run: |ctx| hooks::python_tools::pyright(ctx.settings, ctx.args),
354 },
355 Builtin {
356 name: "pre-commit-ruff",
357 stage: Stage::PreCommit,
358 scope: Scope::new(
359 hooks::python_tools::EXTS,
360 &["ruff.toml", ".ruff.toml", "pyproject.toml"],
361 )
362 .not_during(MID_OPERATION),
363 severity: Severity::Block,
364 fix: Fix::Rewrite,
365 reach: Reach::Convention,
366 run: |ctx| hooks::python_tools::ruff(ctx.settings, ctx.args),
367 },
368 Builtin {
372 name: "pre-commit-secrets",
373 stage: Stage::PreCommit,
374 scope: Scope::ALWAYS,
375 severity: Severity::Block,
376 fix: Fix::None,
377 reach: Reach::Safety,
378 run: |ctx| hooks::secrets::staged(ctx.settings),
379 },
380 Builtin {
386 name: "pre-commit-tree-parity",
387 stage: Stage::PreCommit,
388 scope: Scope {
389 files: hooks::k8s::EXTS,
390 names: &[crate::manifest::MANIFEST, crate::names::old::MANIFEST],
391 dirs: &[],
392 opt_in: &[crate::manifest::MANIFEST, crate::names::old::MANIFEST],
393 not_during: MID_OPERATION,
394 },
395 severity: Severity::Block,
396 fix: Fix::None,
397 reach: Reach::Convention,
398 run: |ctx| hooks::tree_parity::run(ctx.settings),
399 },
400 Builtin {
401 name: "pre-commit-usual-name",
402 stage: Stage::PreCommit,
403 scope: Scope::ALWAYS,
404 severity: Severity::Block,
405 fix: Fix::None,
406 reach: Reach::Convention,
407 run: |ctx| hooks::usual_name::run(ctx.args),
408 },
409 Builtin {
410 name: "pre-commit-shellcheck",
411 stage: Stage::PreCommit,
412 scope: Scope::files(hooks::shellcheck::EXTS).not_during(MID_OPERATION),
415 severity: Severity::Block,
416 fix: Fix::None,
417 reach: Reach::Convention,
418 run: |ctx| hooks::shellcheck::run(ctx.settings, ctx.args),
419 },
420 Builtin {
421 name: "pre-commit-hadolint",
422 stage: Stage::PreCommit,
423 scope: Scope::named(hooks::hadolint::NAMES).not_during(MID_OPERATION),
427 severity: Severity::Block,
428 fix: Fix::None,
429 reach: Reach::Convention,
430 run: |ctx| hooks::hadolint::run(ctx.settings, ctx.args),
431 },
432 Builtin {
433 name: "pre-commit-helm-lint",
434 stage: Stage::PreCommit,
435 scope: Scope::new(hooks::helm::EXTS, hooks::helm::MARKERS).not_during(MID_OPERATION),
438 severity: Severity::Block,
439 fix: Fix::None,
440 reach: Reach::Convention,
441 run: |ctx| hooks::helm::run(ctx.settings, ctx.args),
442 },
443 Builtin {
444 name: "pre-commit-yamllint",
445 stage: Stage::PreCommit,
446 scope: Scope::new(
447 hooks::yamllint::EXTS,
448 &[".yamllint.yaml", ".yamllint.yml", ".yamllint"],
449 )
450 .not_during(MID_OPERATION),
451 severity: Severity::Block,
452 fix: Fix::None,
453 reach: Reach::Convention,
454 run: |ctx| hooks::yamllint::run(ctx.settings, ctx.args),
455 },
456 Builtin {
458 name: "pre-push-branch-protect",
459 stage: Stage::PrePush,
460 scope: Scope::ALWAYS,
461 severity: Severity::Block,
462 fix: Fix::None,
463 reach: Reach::Convention,
464 run: |ctx| hooks::branch_protect::run(ctx.settings, ctx.push.get()),
465 },
466 Builtin {
467 name: "pre-push-branch-pattern",
468 stage: Stage::PrePush,
469 scope: Scope::ALWAYS,
470 severity: Severity::Block,
471 fix: Fix::None,
472 reach: Reach::Convention,
473 run: |ctx| hooks::branch_pattern::run(ctx.settings, ctx.push.get(), ctx.args),
474 },
475 Builtin {
476 name: "pre-push-secrets",
477 stage: Stage::PrePush,
478 scope: Scope::ALWAYS,
479 severity: Severity::Block,
480 fix: Fix::None,
481 reach: Reach::Safety,
482 run: |ctx| hooks::secrets::pushed(ctx.settings, ctx.push.get()),
483 },
484 Builtin {
485 name: "pre-push-pull-rebase",
486 stage: Stage::PrePush,
487 scope: Scope::ALWAYS.not_during(&[GitState::Rebase, GitState::Merge]),
488 severity: Severity::Block,
489 fix: Fix::None,
490 reach: Reach::Convention,
491 run: |ctx| hooks::pull_rebase::run(ctx.settings, ctx.push.get(), ctx.args),
492 },
493 Builtin {
500 name: "pre-push-audit-go",
501 stage: Stage::PrePush,
502 scope: Scope::new(&[], &["go.sum"]),
503 severity: Severity::Block,
504 fix: Fix::None,
505 reach: Reach::Convention,
506 run: |ctx| hooks::audit::go(ctx),
507 },
508 Builtin {
512 name: "pre-push-audit-js",
513 stage: Stage::PrePush,
514 scope: Scope::new(&[], &["package-lock.json", "pnpm-lock.yaml"]),
515 severity: Severity::Block,
516 fix: Fix::None,
517 reach: Reach::Convention,
518 run: |ctx| hooks::audit::js(ctx),
519 },
520 Builtin {
525 name: "pre-push-audit-python",
526 stage: Stage::PrePush,
527 scope: Scope::new(&[], &["requirements.txt", "pyproject.toml"]),
528 severity: Severity::Block,
529 fix: Fix::None,
530 reach: Reach::Convention,
531 run: |ctx| hooks::audit::python(ctx),
532 },
533 Builtin {
534 name: "pre-push-audit-rust",
535 stage: Stage::PrePush,
536 scope: Scope::new(&[], &["Cargo.lock"]),
537 severity: Severity::Block,
538 fix: Fix::None,
539 reach: Reach::Convention,
540 run: |ctx| hooks::audit::rust(ctx),
541 },
542 Builtin {
543 name: "pre-push-run-tests-js",
544 stage: Stage::PrePush,
545 scope: Scope::new(hooks::run_tests::JS_EXTS, &["package.json"])
546 .not_during(&[GitState::Bisect, GitState::Rebase]),
547 severity: Severity::Block,
548 fix: Fix::None,
549 reach: Reach::Convention,
550 run: |ctx| hooks::run_tests::run(ctx.settings, ctx.push.get(), ctx.manifest, ctx.name),
551 },
552 Builtin {
553 name: "pre-push-cargo-test",
554 stage: Stage::PrePush,
555 scope: Scope::new(hooks::rust_tools::RUST_PATHS, &["Cargo.toml"])
556 .not_during(&[GitState::Bisect, GitState::Rebase]),
557 severity: Severity::Block,
558 fix: Fix::None,
559 reach: Reach::Convention,
560 run: |ctx| hooks::rust_tools::test(ctx.settings, ctx.push.get(), ctx.name),
561 },
562 Builtin {
563 name: "pre-push-go-test",
564 stage: Stage::PrePush,
565 scope: Scope::new(hooks::go_tools::GO_PATHS, &["go.mod"])
566 .not_during(&[GitState::Bisect, GitState::Rebase]),
567 severity: Severity::Block,
568 fix: Fix::None,
569 reach: Reach::Convention,
570 run: |ctx| hooks::go_tools::test(ctx.settings, ctx.push.get(), ctx.name),
571 },
572 Builtin {
573 name: "pre-push-pytest",
574 stage: Stage::PrePush,
575 scope: Scope::new(hooks::python_tools::EXTS, &["pytest.ini", "conftest.py"])
576 .not_during(&[GitState::Bisect, GitState::Rebase]),
577 severity: Severity::Block,
578 fix: Fix::None,
579 reach: Reach::Convention,
580 run: |ctx| hooks::python_tools::pytest(ctx.settings, ctx.push.get(), ctx.name),
581 },
582];
583
584pub fn severity_of(settings: &crate::config::Settings, check: &dyn Check) -> Severity {
590 effective_override(settings, None, check.name()).unwrap_or_else(|| check.severity())
591}
592
593pub fn severity_key(check: &str) -> String {
595 format!("greengate.severity.{check}")
596}
597
598#[derive(Debug, Default, Clone)]
609pub struct Overrides(std::collections::BTreeMap<String, (Severity, Source)>);
610
611#[derive(Debug, Clone, Copy, PartialEq, Eq)]
615pub enum Source {
616 Config,
617 Policy,
618}
619
620impl Source {
621 pub fn as_str(self) -> &'static str {
622 match self {
623 Source::Config => "config",
624 Source::Policy => "policy",
625 }
626 }
627}
628
629impl Overrides {
630 pub fn read(settings: &crate::config::Settings) -> Overrides {
637 let policy = settings.policy();
638 match crate::git::stdout(&[
639 "config",
640 "--show-scope",
641 "--get-regexp",
642 r"^greengate\.severity\.",
643 ]) {
644 Some(scoped) => Overrides::from_scoped(&scoped, policy),
645 None => Overrides::from_plain_with_policy_below(
649 crate::git::stdout(&["config", "--get-regexp", r"^greengate\.severity\."]),
650 policy,
651 ),
652 }
653 }
654
655 pub fn from_scoped(scoped: &str, policy: &crate::policy::Policy) -> Overrides {
662 let mut below = String::new();
663 let mut above = String::new();
664 for line in scoped.lines() {
665 let Some((scope, rest)) = line.split_once('\t') else {
666 continue;
667 };
668 match scope {
669 "system" | "global" => {
670 below.push_str(rest);
671 below.push('\n');
672 }
673 _ => {
674 above.push_str(rest);
675 above.push('\n');
676 }
677 }
678 }
679 let mut o = Overrides::default();
680 o.fold_plain(&below, Source::Config);
681 o.fold_policy(policy);
682 o.fold_plain(&above, Source::Config);
683 o
684 }
685
686 pub fn from_plain_with_policy_below(
691 plain: Option<String>,
692 policy: &crate::policy::Policy,
693 ) -> Overrides {
694 let mut o = Overrides::default();
695 o.fold_policy(policy);
696 o.fold_plain(plain.as_deref().unwrap_or_default(), Source::Config);
697 o
698 }
699
700 fn fold_policy(&mut self, policy: &crate::policy::Policy) {
703 for (target, severity) in &policy.severities {
704 self.0.insert(target.clone(), (*severity, Source::Policy));
705 }
706 }
707
708 fn fold_plain(&mut self, text: &str, source: Source) {
712 for line in text.lines() {
713 let Some((key, value)) = line.split_once(' ') else {
714 continue;
715 };
716 let Some(check) = key.strip_prefix("greengate.severity.") else {
717 continue;
718 };
719 match Severity::parse(value.trim()) {
720 Some(sev) => {
721 self.0.insert(check.to_string(), (sev, source));
722 }
723 None => {
724 self.0.remove(check);
725 }
726 }
727 }
728 }
729
730 pub fn from_config(out: Option<String>) -> Overrides {
738 let mut o = Overrides::default();
739 o.fold_plain(out.as_deref().unwrap_or_default(), Source::Config);
740 o
741 }
742
743 pub fn applied_to(&self, check: &str) -> Option<(&str, Severity)> {
750 self.applied_with_source(check)
751 .map(|(pattern, severity, _)| (pattern, severity))
752 }
753
754 pub fn applied_with_source(&self, check: &str) -> Option<(&str, Severity, Source)> {
758 self.0
759 .iter()
760 .filter_map(|(pattern, (severity, source))| {
761 crate::names_check(check, pattern)
762 .map(|m| (m, pattern.as_str(), *severity, *source))
763 })
764 .max_by_key(|(m, _, _, _)| *m)
765 .map(|(_, pattern, severity, source)| (pattern, severity, source))
766 }
767
768 pub fn of(&self, check: &dyn Check) -> Severity {
770 self.applied_to(check.name())
771 .map(|(_, severity)| severity)
772 .unwrap_or_else(|| check.severity())
773 }
774}
775
776#[cfg(test)]
777mod precedence {
778 use super::{Overrides, Severity};
779
780 fn overrides(lines: &[&str]) -> Overrides {
781 let text = lines
782 .iter()
783 .map(|l| format!("greengate.severity.{l}\n"))
784 .collect::<String>();
785 Overrides::from_config(Some(text))
786 }
787
788 #[test]
792 fn the_more_specific_key_wins() {
793 let both = overrides(&["pre-commit warn", "pre-commit-clippy block"]);
794 assert_eq!(
795 both.applied_to("pre-commit-clippy"),
796 Some(("pre-commit-clippy", Severity::Block)),
797 "a full id beats its trigger"
798 );
799 assert_eq!(
800 both.applied_to("pre-commit-shellcheck"),
801 Some(("pre-commit", Severity::Warn)),
802 "and the trigger still governs every check it did not exempt"
803 );
804 }
805
806 #[test]
809 fn the_three_ways_to_name_a_check_are_ranked() {
810 let all = overrides(&["pre-commit warn", "clippy block", "pre-commit-clippy warn"]);
811 assert_eq!(
812 all.applied_to("pre-commit-clippy"),
813 Some(("pre-commit-clippy", Severity::Warn))
814 );
815
816 let no_full = overrides(&["pre-commit warn", "clippy block"]);
817 assert_eq!(
818 no_full.applied_to("pre-commit-clippy"),
819 Some(("clippy", Severity::Block)),
820 "a short name beats a trigger"
821 );
822 }
823
824 #[test]
827 fn a_key_that_names_no_check_applies_to_nothing() {
828 let typo = overrides(&["clipy warn", "e warn", " warn"]);
829 assert_eq!(typo.applied_to("pre-commit-clippy"), None);
830 }
831}
832
833pub fn effective_override(
843 settings: &crate::config::Settings,
844 repo: Option<&Path>,
845 check: &str,
846) -> Option<Severity> {
847 overrides_in(settings, repo)
848 .applied_to(check)
849 .map(|(_, s)| s)
850}
851
852pub fn effective_key(
858 settings: &crate::config::Settings,
859 repo: Option<&Path>,
860 check: &str,
861) -> Option<String> {
862 overrides_in(settings, repo)
863 .applied_to(check)
864 .map(|(pattern, _)| pattern.to_string())
865}
866
867fn overrides_in(settings: &crate::config::Settings, repo: Option<&Path>) -> Overrides {
868 match repo {
869 None => Overrides::read(settings),
873 Some(dir) => Overrides::from_config(crate::git::stdout_in(
877 dir,
878 &["config", "--get-regexp", r"^greengate\.severity\."],
879 )),
880 }
881}
882
883pub fn stage_checks(stage: Stage) -> impl Iterator<Item = &'static Builtin> {
885 CHECKS.iter().filter(move |check| check.stage == stage)
886}
887
888pub fn push_twin_scope(short: &str) -> Option<(&'static str, Scope)> {
895 let mut push = stage_checks(Stage::PrePush);
896 let twin = push
897 .find(|check| check.pairing_name() == short)
898 .or_else(|| {
899 hooks::run_tests::is_gate_script(short)
900 .then(|| stage_checks(Stage::PrePush).find(|c| c.name() == "pre-push-run-tests-js"))
901 .flatten()
902 });
903 twin.map(|check| (check.name(), check.scope()))
904}
905
906pub fn all_stage_checks<'a>(
913 stage: Stage,
914 manifest: &'a crate::manifest::Manifest,
915) -> Vec<&'a dyn Check> {
916 let mut out: Vec<&'a dyn Check> = stage_checks(stage)
917 .map(|check| check as &dyn Check)
918 .collect();
919 out.extend(
920 manifest
921 .externals
922 .iter()
923 .filter(|external| external.stage == stage)
924 .map(|external| external as &dyn Check),
925 );
926 out
927}
928
929pub fn lookup(name: &str, manifest: &crate::manifest::Manifest) -> Option<HookFn> {
930 if let Some((_, f)) = ENTRYPOINTS.iter().find(|(n, _)| *n == name) {
931 return Some(*f);
932 }
933 if CHECKS.iter().any(|check| check.name == name)
940 || manifest
941 .externals
942 .iter()
943 .any(|external| external.id == name)
944 {
945 return Some(|ctx: &Ctx| {
946 let check = one_named(ctx.name, ctx.manifest).expect("checked above");
947 let _slot = crate::host_slots::enter_check(check.name(), check.weight());
950 Verdict::blocking(matches!(
951 (check.run(ctx), severity_of(ctx.settings, check)),
952 (Outcome::Failed, Severity::Block)
953 ))
954 });
955 }
956 None
957}
958
959pub fn one_named<'a>(name: &str, manifest: &'a crate::manifest::Manifest) -> Option<&'a dyn Check> {
963 if let Some(builtin) = CHECKS.iter().find(|check| check.name == name) {
964 return Some(builtin);
965 }
966 manifest
967 .externals
968 .iter()
969 .find(|external| external.id == name)
970 .map(|external| external as &dyn Check)
971}
972
973#[cfg(test)]
974mod tests {
975 use super::{lookup, Overrides, Reach, Severity, Stage, CHECKS, ENTRYPOINTS};
976 use crate::names::BIN;
977 use std::collections::BTreeSet;
978
979 #[test]
986 fn the_batch_agrees_with_the_authority() {
987 let d = std::env::temp_dir().join(format!("ov-{}", std::process::id()));
988 let _ = std::fs::remove_dir_all(&d);
989 std::fs::create_dir_all(&d).unwrap();
990 let git = |args: &[&str]| {
991 std::process::Command::new("git")
992 .args(args)
993 .current_dir(&d)
994 .output()
995 .expect("git");
996 };
997 git(&["init", "-q", "--template=", "."]);
998 let key = "greengate.severity.pre-commit-merge-conflict";
999 git(&["config", "--add", key, "warn"]);
1000 git(&["config", "--add", key, "block"]);
1001
1002 let raw = std::process::Command::new("git")
1003 .args(["config", "--get-regexp", r"^greengate\.severity\."])
1004 .current_dir(&d)
1005 .output()
1006 .expect("git");
1007 let batch = Overrides::from_config(Some(
1008 String::from_utf8_lossy(&raw.stdout).trim().to_string(),
1009 ));
1010 let authority =
1011 crate::git::stdout_in(&d, &["config", "--get", key]).and_then(|v| Severity::parse(&v));
1012 let _ = std::fs::remove_dir_all(&d);
1013
1014 assert_eq!(
1015 authority,
1016 Some(Severity::Block),
1017 "git applies the last entry"
1018 );
1019 assert_eq!(
1020 batch.0.get("pre-commit-merge-conflict").map(|(s, _)| *s),
1021 authority,
1022 "the batch reader disagreed with `--get`"
1023 );
1024 }
1025
1026 #[test]
1030 fn an_unrecognised_value_clears_rather_than_overrides() {
1031 let o = Overrides::from_config(Some(
1032 "greengate.severity.a warn\ngreengate.severity.a advisory\ngreengate.severity.b warn"
1033 .to_string(),
1034 ));
1035 assert_eq!(o.0.get("a"), None, "a typo must not leave `warn` standing");
1036 assert_eq!(o.0.get("b").map(|(s, _)| *s), Some(Severity::Warn));
1037 }
1038
1039 #[test]
1040 fn names_are_unique_across_entrypoints_and_checks() {
1041 let mut seen = BTreeSet::new();
1042 for n in ENTRYPOINTS
1043 .iter()
1044 .map(|(n, _)| *n)
1045 .chain(CHECKS.iter().map(|check| check.name))
1046 {
1047 assert!(seen.insert(n), "duplicate registration: {n}");
1048 }
1049 }
1050
1051 #[test]
1053 fn the_shipped_shims_are_exactly_the_git_invoked_hooks() {
1054 let dir = concat!(env!("CARGO_MANIFEST_DIR"), "/../../templates/hooks");
1055 let mut shipped: Vec<String> = std::fs::read_dir(dir)
1056 .expect("templates/hooks")
1057 .flatten()
1058 .map(|entry| entry.file_name().to_string_lossy().into_owned())
1059 .collect();
1060 shipped.sort();
1061 assert_eq!(
1062 shipped,
1063 vec![
1064 "commit-msg",
1065 "post-commit",
1066 "post-rewrite",
1067 "pre-commit",
1068 "pre-push",
1069 "prepare-commit-msg"
1070 ]
1071 );
1072 let none = crate::manifest::Manifest::default();
1073 for name in &shipped {
1074 assert!(
1075 lookup(name, &none).is_some(),
1076 "shipped shim {name:?} has no handler"
1077 );
1078 }
1079 }
1080
1081 #[test]
1084 fn every_check_is_reachable_by_name() {
1085 let none = crate::manifest::Manifest::default();
1086 for check in CHECKS {
1087 assert!(
1088 lookup(check.name, &none).is_some(),
1089 "{} not reachable",
1090 check.name
1091 );
1092 }
1093 assert!(lookup("pre-commit-not-a-check", &none).is_none());
1094 }
1095
1096 #[test]
1098 fn pre_push_runs_cheapest_first() {
1099 let order: Vec<&str> = super::stage_checks(Stage::PrePush)
1100 .map(|check| check.name)
1101 .collect();
1102 assert_eq!(
1103 order,
1104 vec![
1105 "pre-push-branch-protect",
1106 "pre-push-branch-pattern",
1107 "pre-push-secrets",
1108 "pre-push-pull-rebase",
1109 "pre-push-audit-go",
1110 "pre-push-audit-js",
1111 "pre-push-audit-python",
1112 "pre-push-audit-rust",
1113 "pre-push-run-tests-js",
1114 "pre-push-cargo-test",
1115 "pre-push-go-test",
1116 "pre-push-pytest",
1117 ]
1118 );
1119 }
1120
1121 enum Consumes {
1127 All,
1128 Exts(&'static [&'static str]),
1129 }
1130
1131 const CONSUMED: &[(&str, Consumes)] = &[
1145 (
1146 "pre-commit-argo-lint",
1147 Consumes::Exts(crate::hooks::k8s::EXTS),
1148 ),
1149 (
1153 "pre-commit-ban-terms",
1154 Consumes::Exts(crate::hooks::ban_terms::EXTS),
1155 ),
1156 (
1157 "pre-commit-cargo-fmt",
1158 Consumes::Exts(crate::hooks::rust_tools::EXTS),
1159 ),
1160 (
1161 "pre-commit-clippy",
1162 Consumes::Exts(crate::hooks::rust_tools::RUST_PATHS),
1163 ),
1164 (
1165 "pre-commit-go-vet",
1166 Consumes::Exts(crate::hooks::go_tools::GO_PATHS),
1167 ),
1168 (
1169 "pre-commit-gofmt",
1170 Consumes::Exts(crate::hooks::go_tools::EXTS),
1171 ),
1172 (
1173 "pre-commit-kube-linter",
1174 Consumes::Exts(crate::hooks::k8s::EXTS),
1175 ),
1176 (
1177 "pre-commit-kubeconform",
1178 Consumes::Exts(crate::hooks::k8s::EXTS),
1179 ),
1180 (
1181 "pre-commit-lint-js",
1182 Consumes::Exts(crate::hooks::lint_js::EXTS),
1183 ),
1184 (
1185 "pre-commit-lint-json-yaml",
1186 Consumes::Exts(crate::hooks::lint_json_yaml::EXTS),
1187 ),
1188 ("pre-commit-merge-conflict", Consumes::All),
1189 ("pre-commit-package-lock", Consumes::All),
1190 (
1194 "pre-commit-prettier",
1195 Consumes::Exts(crate::hooks::prettier::EXTS),
1196 ),
1197 (
1198 "pre-commit-pyright",
1199 Consumes::Exts(crate::hooks::python_tools::EXTS),
1200 ),
1201 (
1202 "pre-commit-ruff",
1203 Consumes::Exts(crate::hooks::python_tools::EXTS),
1204 ),
1205 ("pre-commit-usual-name", Consumes::All),
1206 (
1207 "pre-commit-yamllint",
1208 Consumes::Exts(crate::hooks::yamllint::EXTS),
1209 ),
1210 (
1211 "pre-commit-shellcheck",
1212 Consumes::Exts(crate::hooks::shellcheck::EXTS),
1213 ),
1214 (
1215 "pre-commit-hadolint",
1216 Consumes::Exts(crate::hooks::hadolint::NAMES),
1217 ),
1218 (
1219 "pre-commit-helm-lint",
1220 Consumes::Exts(crate::hooks::helm::EXTS),
1221 ),
1222 ("pre-commit-large-files", Consumes::All),
1223 ("pre-commit-secrets", Consumes::All),
1224 ("pre-push-secrets", Consumes::All),
1225 ("pre-push-branch-protect", Consumes::All),
1226 ("pre-push-branch-pattern", Consumes::All),
1227 ("pre-push-pull-rebase", Consumes::All),
1228 (
1229 "pre-push-run-tests-js",
1230 Consumes::Exts(crate::hooks::run_tests::JS_EXTS),
1231 ),
1232 (
1233 "pre-push-pytest",
1234 Consumes::Exts(crate::hooks::python_tools::EXTS),
1235 ),
1236 (
1237 "pre-push-cargo-test",
1238 Consumes::Exts(crate::hooks::rust_tools::RUST_PATHS),
1239 ),
1240 (
1241 "pre-push-go-test",
1242 Consumes::Exts(crate::hooks::go_tools::GO_PATHS),
1243 ),
1244 (
1246 "pre-commit-tree-parity",
1247 Consumes::Exts(crate::hooks::k8s::EXTS),
1248 ),
1249 ];
1250
1251 #[test]
1262 fn no_check_declares_a_file_type_it_does_not_consume() {
1263 for (name, _) in CONSUMED {
1264 assert!(
1265 CHECKS.iter().any(|check| check.name == *name),
1266 "CONSUMED names {name:?}, which is not a check"
1267 );
1268 }
1269 for check in CHECKS {
1270 let entry = CONSUMED.iter().find(|(name, _)| *name == check.name);
1271 if check.scope.files.is_empty() && entry.is_none() {
1272 continue;
1273 }
1274 let Some((_, consumes)) = entry else {
1275 panic!(
1276 "{} declares scope.files {:?} but is missing from CONSUMED — \
1277 say what it actually reads",
1278 check.name, check.scope.files
1279 );
1280 };
1281 let Consumes::Exts(consumed) = consumes else {
1282 continue; };
1284 for ext in check.scope.files {
1285 assert!(
1286 consumed.contains(ext),
1287 "{} declares {ext:?} in its scope but never asks for it — \
1288 `{BIN} list` would report a coverage the check does not have",
1289 check.name
1290 );
1291 }
1292 }
1293 }
1294
1295 #[test]
1307 fn a_push_suite_declares_every_path_it_consumes() {
1308 for name in ["pre-push-cargo-test", "pre-push-go-test", "pre-push-pytest"] {
1309 let check = CHECKS.iter().find(|c| c.name == name).expect(name);
1310 let Some((_, Consumes::Exts(consumed))) = CONSUMED.iter().find(|(n, _)| *n == name)
1311 else {
1312 panic!("{name} must consume an explicit file set");
1313 };
1314 for path in *consumed {
1315 assert!(
1316 check.scope.files.contains(path),
1317 "{name} runs for {path:?} but does not declare it: a push \
1318 touching only {path:?} would be rehearsed as nothing to do, \
1319 run at push time, and never stamped"
1320 );
1321 }
1322 }
1323 }
1324
1325 const HAS_FIXING_CODE: &[(&str, bool)] = &[
1334 ("pre-commit-agents-md", true),
1335 ("pre-commit-argo-lint", false),
1336 ("pre-commit-ban-terms", false),
1337 ("pre-commit-branch-pattern", false),
1338 ("pre-commit-branch-protect", false),
1339 ("pre-commit-cargo-fmt", true),
1340 ("pre-commit-clippy", false),
1341 ("pre-commit-go-vet", false),
1342 ("pre-commit-gofmt", true),
1343 ("pre-commit-kube-linter", false),
1344 ("pre-commit-kubeconform", false),
1345 ("pre-commit-lint-js", false),
1346 ("pre-commit-lint-json-yaml", false),
1347 ("pre-commit-manifest-trust", false),
1348 ("pre-commit-merge-conflict", false),
1349 ("pre-commit-package-lock", false),
1350 ("pre-commit-prettier", true),
1351 ("pre-commit-pyright", false),
1352 ("pre-commit-ruff", true),
1353 ("pre-commit-tree-parity", false),
1354 ("pre-commit-usual-name", false),
1355 ("pre-commit-yamllint", false),
1356 ("pre-commit-shellcheck", false),
1357 ("pre-commit-hadolint", false),
1358 ("pre-commit-helm-lint", false),
1359 ("pre-commit-large-files", false),
1360 ("pre-commit-secrets", false),
1361 ("pre-push-secrets", false),
1362 ("pre-push-branch-protect", false),
1363 ("pre-push-branch-pattern", false),
1364 ("pre-push-pull-rebase", false),
1365 ("pre-push-audit-go", false),
1366 ("pre-push-audit-js", false),
1367 ("pre-push-audit-python", false),
1368 ("pre-push-audit-rust", false),
1369 ("pre-push-run-tests-js", false),
1370 ("pre-push-cargo-test", false),
1371 ("pre-push-go-test", false),
1372 ("pre-push-pytest", false),
1373 ];
1374
1375 #[test]
1378 fn every_rewrite_declaration_has_a_fixer() {
1379 let declared: BTreeSet<&str> = CHECKS
1380 .iter()
1381 .filter(|check| check.fix == super::Fix::Rewrite)
1382 .map(|check| check.name)
1383 .collect();
1384 let implemented: BTreeSet<&str> = HAS_FIXING_CODE
1385 .iter()
1386 .filter(|(_, has)| *has)
1387 .map(|(name, _)| *name)
1388 .collect();
1389 assert_eq!(
1390 declared, implemented,
1391 "a check declaring Fix::Rewrite with no fixer lies to `{BIN} list --json`, \
1392 and a check with a fixer that does not declare it can never be reached"
1393 );
1394
1395 let listed: BTreeSet<&str> = HAS_FIXING_CODE.iter().map(|(name, _)| *name).collect();
1398 let all: BTreeSet<&str> = CHECKS.iter().map(|check| check.name).collect();
1399 assert_eq!(listed, all, "HAS_FIXING_CODE does not cover CHECKS");
1400 }
1401
1402 #[test]
1413 fn the_safety_net_is_exactly_the_low_false_positive_set() {
1414 let safety: Vec<&str> = CHECKS
1415 .iter()
1416 .filter(|c| c.reach == Reach::Safety)
1417 .map(|c| c.name)
1418 .collect();
1419 assert_eq!(
1420 safety,
1421 vec![
1422 "pre-commit-ban-terms",
1423 "pre-commit-large-files",
1424 "pre-commit-manifest-trust",
1425 "pre-commit-merge-conflict",
1426 "pre-commit-secrets",
1427 "pre-push-secrets",
1428 ]
1429 );
1430 }
1431
1432 #[test]
1433 fn every_check_declares_a_stage_and_a_scope() {
1434 assert_eq!(CHECKS.len(), 39);
1435 let pre_commit = super::stage_checks(Stage::PreCommit).count();
1436 let pre_push = super::stage_checks(Stage::PrePush).count();
1437 assert_eq!(
1438 pre_commit + pre_push,
1439 CHECKS.len(),
1440 "every check has a stage"
1441 );
1442 }
1443}