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
//! Committed repo policy — the team's decisions, shipped with the repository.
//!
//! `amont.conf` could always ADD checks; it could never say anything about
//! the built-ins, so "clippy is warn-only here" meant every teammate running
//! the same `git config` incantation, unverified. `severity` and `skip`
//! lines close that: committed, reviewed like code, and trust-gated exactly
//! like declared checks — a repository you cloned to read cannot weaken your
//! safety net until you consent.
//!
//! Precedence is a specificity ladder decided per KEY: built-in default <
//! system config < global config < POLICY < local config < worktree <
//! command-line. Between different keys naming the same check, specificity
//! (full id > short name > trigger) decides, whatever the source — a local
//! `greengate.severity.pre-commit warn` must never be unbeatable by policy, and
//! a policy full-id beats a local trigger. Skips are a UNION of all sources:
//! there is no unskip mechanism anywhere, so ordering has nothing to decide.
//!
//! There is no store. A `Policy` is owned by the [`crate::config::Settings`]
//! each entrypoint builds after `manifest::load`, and borrowed from there —
//! the shape `Ctx` already used for `manifest` and `push`.
//!
//! It WAS a process-global `OnceLock`, which was correct for the hook path
//! (one process, one repository) and wrong as a contract: a multi-repo walker
//! had to KNOW not to seed it, `amont-fleet` carried that knowledge as a
//! comment, and no test could assert the rule because asserting it would have
//! meant seeding it. Now the rule needs no remembering — a scanner cannot
//! corrupt a store that does not exist. Every RULE here stays a pure function
//! over `&Policy`.
use crate::check::Severity;
use crate::manifest::{Line, PolicyLine};
/// What a trusted manifest's policy lines add up to.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Policy {
/// `(target, severity)` in file order — later lines overwrite earlier
/// ones at fold time, matching git config's own precedence rule.
pub severities: Vec<(String, Severity)>,
/// Skip targets, resolved by the same three-way naming `hook.skip` uses.
pub skips: Vec<String>,
/// Committed defaults for allowlisted config keys, by FULL git key
/// (`greengate.timeout`). Values are raw strings — GIT parses them at read
/// time (`config::typed_literal`), so no second config dialect exists.
pub settings: std::collections::BTreeMap<String, String>,
}
impl Policy {
pub fn is_empty(&self) -> bool {
self.severities.is_empty() && self.skips.is_empty() && self.settings.is_empty()
}
/// Collect the policy from parsed lines, and say which targets name
/// nothing — validated here, over the WHOLE file, because `parse_line`
/// sees only earlier lines and a `severity smoke warn` written above its
/// own `pre-commit smoke …` declaration would be wrongly refused.
///
/// The naming universe is built-ins plus the file's CHECK lines only
/// (`Line::is_check`) — a `tool ruff …` pin must not make
/// `severity ruff warn` look valid, and `Broken` lines count because a
/// broken line still produces a check id that `hook.skip` can reach.
///
/// An unmatched target is a NOTE, not a `Line::Broken` — a broken line
/// manufactures a check named after itself, and a phantom
/// `pre-commit-clipy` helps nobody.
pub fn from_lines(lines: &[Line]) -> (Policy, Vec<String>) {
Policy::from_lines_of(lines, crate::manifest::MANIFEST)
}
/// [`Policy::from_lines`] for the file named `manifest`, which the notes
/// name.
pub fn from_lines_of(lines: &[Line], manifest: &str) -> (Policy, Vec<String>) {
let mut policy = Policy::default();
let mut notes = Vec::new();
let names_something = |target: &str| {
crate::registry::CHECKS
.iter()
.any(|c| crate::names_check(c.name, target).is_some())
|| lines
.iter()
.filter(|l| l.is_check())
.any(|l| crate::names_check(&l.id(), target).is_some())
};
for line in lines {
let Line::Policy { what, lineno } = line else {
continue;
};
let target = match what {
PolicyLine::Severity { target, .. } | PolicyLine::Skip { target } => target,
PolicyLine::Set { key, value } => {
// Allowlisted at parse; later lines overwrite earlier
// ones, the same rule config itself applies.
policy.settings.insert(key.clone(), value.clone());
continue;
}
};
if !names_something(target) {
let kind = match what {
PolicyLine::Severity { .. } => "severity",
PolicyLine::Skip { .. } => "skip",
// Set lines took the `continue` above; unreachable here.
PolicyLine::Set { .. } => unreachable!("set lines have no target"),
};
notes.push(format!(
"{manifest}:{lineno}: {kind} {target:?} names no check here"
));
continue;
}
match what {
PolicyLine::Severity { target, severity } => {
policy.severities.push((target.clone(), *severity));
}
PolicyLine::Skip { target } => policy.skips.push(target.clone()),
PolicyLine::Set { .. } => unreachable!("set lines have no target"),
}
}
(policy, notes)
}
}
/// The union `hook.skip` resolution sees: machine skips plus policy skips.
/// A union and not a ladder — nothing anywhere can UN-skip, so there is no
/// conflict for ordering to settle.
pub fn union_skips(config_skips: Vec<String>, policy: &Policy) -> Vec<String> {
let mut all = config_skips;
for s in &policy.skips {
if !all.contains(s) {
all.push(s.clone());
}
}
all
}
#[cfg(test)]
mod tests {
use super::*;
use crate::manifest::parse_lines;
#[test]
fn collects_severities_and_skips_in_file_order() {
let lines = parse_lines(
"severity clippy warn\nskip yamllint\nseverity pre-push-cargo-test block\n",
);
let (p, notes) = Policy::from_lines(&lines);
assert!(notes.is_empty(), "{notes:?}");
assert_eq!(
p.severities,
vec![
("clippy".to_string(), Severity::Warn),
("pre-push-cargo-test".to_string(), Severity::Block),
]
);
assert_eq!(p.skips, vec!["yamllint".to_string()]);
}
/// A target can be a declared check — including one written BELOW the
/// policy line, which is why validation is a whole-file pass.
#[test]
fn a_declared_check_below_the_policy_line_still_validates() {
let lines =
parse_lines("severity smoke warn\npre-commit smoke * block ./smoke.sh\n");
let (p, notes) = Policy::from_lines(&lines);
assert!(notes.is_empty(), "{notes:?}");
assert_eq!(p.severities.len(), 1);
}
/// A tool pin must not lend its name to the validation universe.
#[test]
fn a_tool_pin_does_not_validate_a_policy_target() {
let lines = parse_lines("tool ruffian 0.4\nseverity ruffian warn\n");
let (p, notes) = Policy::from_lines(&lines);
assert!(p.severities.is_empty());
assert_eq!(notes.len(), 1, "{notes:?}");
assert!(notes[0].contains("names no check here"), "{notes:?}");
assert!(notes[0].contains("greengate.conf:2"), "{notes:?}");
}
/// A typo is a note with a position, never a phantom check.
#[test]
fn an_unmatched_target_is_a_note_not_a_check() {
let lines = parse_lines("severity clipy warn\n");
let (p, notes) = Policy::from_lines(&lines);
assert!(p.is_empty());
assert_eq!(
notes,
vec!["greengate.conf:1: severity \"clipy\" names no check here"]
);
}
/// Triggers and short names resolve exactly as `hook.skip` resolves them.
#[test]
fn triggers_and_short_names_are_valid_targets() {
let lines = parse_lines("skip pre-commit\nseverity ban-terms warn\n");
let (p, notes) = Policy::from_lines(&lines);
assert!(notes.is_empty(), "{notes:?}");
assert_eq!(p.skips, vec!["pre-commit".to_string()]);
assert_eq!(p.severities.len(), 1);
}
#[test]
fn union_adds_policy_skips_without_duplicating() {
let p = Policy {
severities: Vec::new(),
skips: vec!["yamllint".into(), "clippy".into()],
settings: std::collections::BTreeMap::new(),
};
let got = union_skips(vec!["clippy".into()], &p);
assert_eq!(got, vec!["clippy".to_string(), "yamllint".to_string()]);
}
}