onevcs/rules.rs
1//! The rules file: how each repository publishes a change.
2//!
3//! YAML, first match wins. A rule matches on the host/owner/name of an identity
4//! or on a checkout path, and contributes whichever of the two policy fields it
5//! sets; anything it leaves unset comes from [`RulesFile::default`].
6//!
7//! What *verifies* a change is not here and never comes back. The repository's own
8//! merge path is the verifier — the host's required checks for an identity that
9//! publishes through a change request, the `pre-push` hook for one that publishes
10//! `local-direct` — and a second tier beside it front-ran the real one and threw the
11//! answer away.
12//!
13//! **These two fields are the whole of how an identity publishes.** The registry
14//! records nothing about it: it used to infer a workflow and a repository type from
15//! whether the origin had a host, and every verb that routed on them — the merge
16//! train's gate, the merge-path coverage verdict, the handoff naming the verb for a
17//! complete branch — routes on `publication` now, with `approvals` carrying the
18//! review requirement the repository type never actually carried. A rule matching an
19//! organisation (`host` and `owner`) is that organisation's default, and one adding a
20//! `name` is the per-repository override; nothing else is needed to say that one
21//! hosted repository lands locally while its siblings open change requests.
22//!
23//! Nothing here declares `deny_unknown_fields`, so a file a *newer* build wrote
24//! loads on this one: the keys it understands decide the policy and the rest are
25//! ignored. What that trades away is a typo being caught, and it is traded
26//! deliberately — an older build refusing an operator's whole rules file stops every
27//! verb on the host. A key this build refuses *by name* is unaffected: the `gate:`
28//! version 3 removed is refused where the file is loaded, which is also the only
29//! place that knows which version declared it.
30
31use clap::ValueEnum;
32use serde::{Deserialize, Serialize};
33
34/// A rules file, as it is stored on disk.
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36pub struct RulesFile {
37 /// The schema version: `1` is this shape without `trailer_prefix`, `2` with it,
38 /// `3` without `gate`.
39 // llmlint: ignore[boundary_inputs_validated] which versions this build can read is the
40 // loader's question rather than this type's, and it answers it: it refuses one below
41 // the oldest it reads, refuses a trailer_prefix in a version that predates the key,
42 // drops a `gate:` from a version that still had one before this type ever sees it, and
43 // refuses one by name at the version that removed it. The shape is enforced here — an
44 // undeclared publication or approvals value, or a missing default, is rejected at this
45 // boundary and asserted in tests/contract.rs.
46 pub version: u32,
47 /// The prefix every provenance trailer key carries, written and read.
48 ///
49 /// Unset is [`TrailerPrefix::default`], which is what this crate has always
50 /// written. A host whose branches were preserved by something spelling those
51 /// keys differently sets the prefix it already wrote, and this build then
52 /// recognizes, lists, and recovers that work — the prefix is the whole hook,
53 /// and no particular value of it means anything here.
54 #[serde(default, skip_serializing_if = "Option::is_none")]
55 pub trailer_prefix: Option<TrailerPrefix>,
56 /// The rules, in priority order: the first one that matches wins.
57 pub rules: Vec<Rule>,
58 /// The policy for a repository no rule matches.
59 pub default: Policy,
60}
61
62/// The prefix every provenance trailer key is spelled under.
63///
64/// The check is in the conversion, so a rules file naming a prefix that could not
65/// spell a git trailer key does not deserialize at all — the marker is written and
66/// read from one value, and a value neither side can find again is unrepresentable
67/// rather than representable-and-noticed-later.
68#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
69#[serde(try_from = "String", into = "String")]
70pub struct TrailerPrefix(String);
71
72/// The prefix itself, quoted — never the wrapper. Every refusal that names one
73/// writes it with `{:?}`, and a derived `Debug` would spell each of them
74/// `TrailerPrefix("Onevcs-")` at an operator rather than the value they configured.
75impl std::fmt::Debug for TrailerPrefix {
76 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
77 std::fmt::Debug::fmt(&self.0, f)
78 }
79}
80
81impl Default for TrailerPrefix {
82 /// The prefix this crate has always written, for a host that configures none.
83 fn default() -> Self {
84 TrailerPrefix(crate::provenance::DEFAULT_PREFIX.to_owned())
85 }
86}
87
88impl TryFrom<String> for TrailerPrefix {
89 type Error = String;
90
91 fn try_from(value: String) -> std::result::Result<Self, Self::Error> {
92 match crate::provenance::validate_prefix(&value) {
93 Ok(()) => Ok(TrailerPrefix(value)),
94 Err(reason) => Err(format!(
95 "{value:?} cannot spell a git trailer key: {reason}"
96 )),
97 }
98 }
99}
100
101impl From<TrailerPrefix> for String {
102 fn from(prefix: TrailerPrefix) -> Self {
103 prefix.0
104 }
105}
106
107impl std::ops::Deref for TrailerPrefix {
108 type Target = str;
109
110 fn deref(&self) -> &str {
111 &self.0
112 }
113}
114
115impl std::fmt::Display for TrailerPrefix {
116 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117 f.write_str(&self.0)
118 }
119}
120
121/// One rule: what it matches, and which parts of the policy it sets.
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123pub struct Rule {
124 /// What this rule applies to.
125 #[serde(rename = "match")]
126 pub r#match: RuleMatch,
127 /// How a change is published. Unset falls back to the default policy.
128 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub publication: Option<MergePolicy>,
130 /// Whether approvals are required. Unset falls back to the default policy.
131 #[serde(default, skip_serializing_if = "Option::is_none")]
132 pub approvals: Option<Approvals>,
133 /// How this rule's change requests take the draft lifecycle. Each key it leaves
134 /// unset falls back to the default policy's, and then to the shipped default.
135 #[serde(default, skip_serializing_if = "Option::is_none")]
136 pub drafts: Option<Drafts>,
137}
138
139/// What a rule applies to. Every field is optional; the ones that are set must
140/// all match.
141#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
142pub struct RuleMatch {
143 /// The identity's host, e.g. `github.com`.
144 #[serde(default, skip_serializing_if = "Option::is_none")]
145 pub host: Option<String>,
146 /// The identity's owner, e.g. `acme-corp`.
147 #[serde(default, skip_serializing_if = "Option::is_none")]
148 pub owner: Option<String>,
149 /// The repository name; `*` matches any.
150 #[serde(default, skip_serializing_if = "Option::is_none")]
151 pub name: Option<String>,
152 /// A checkout path glob, e.g. `~/projects/*`.
153 #[serde(default, skip_serializing_if = "Option::is_none")]
154 pub path: Option<String>,
155}
156
157/// A complete policy: every field a rule may set, all of them decided.
158///
159/// `drafts` is the one exception to "decided": each of its keys has a shipped
160/// default, so a `default:` that names none of them is complete, and the resolution
161/// reports which layer decided each key.
162#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
163pub struct Policy {
164 /// How a change is published.
165 pub publication: MergePolicy,
166 /// Whether approvals are required.
167 pub approvals: Approvals,
168 /// How a change request takes the draft lifecycle, where the file says.
169 #[serde(default, skip_serializing_if = "Option::is_none")]
170 pub drafts: Option<Drafts>,
171}
172
173/// The `drafts:` mapping a rule and `default:` may carry: how a publication's change
174/// request takes the draft lifecycle.
175///
176/// Every change request a publication carrying no draft reason opens starts as a
177/// draft while its required checks run, and is lifted to ready or kept a draft once
178/// they settle — by the identity's `publication` and `approvals`, which stay the
179/// whole of the routing. These two keys only switch the lifecycle and its one
180/// warning; neither says what a green change does.
181///
182/// Unlike the rest of the file, this mapping **refuses a key it does not know**, by
183/// name, where the file is loaded: it is new, nothing wrote a later key into it, and
184/// a misspelt `disable:` read as absent would leave an operator believing they had
185/// opted out. A file that carries no `drafts:` at all is read exactly as it was, and
186/// an older build ignores the whole block — which is that build's pre-draft
187/// behaviour, so no version bump is owed.
188#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
189#[serde(deny_unknown_fields)]
190pub struct Drafts {
191 /// `true` opens change requests ready, as before the lifecycle, while an explicit
192 /// held or release-awaiting draft keeps working. Shipped default `false`.
193 #[serde(default, skip_serializing_if = "Option::is_none")]
194 pub disabled: Option<bool>,
195 /// Whether lifting a draft early — its required checks never ran on it, which is
196 /// what a workflow that skips drafts looks like — prints one warning line on
197 /// stderr. Shipped default `true`.
198 #[serde(default, skip_serializing_if = "Option::is_none")]
199 pub warn_on_early_lift: Option<bool>,
200}
201
202/// How a change reaches the base branch.
203///
204/// A per-run explicit policy may narrow this (`change-auto` to `change-open`) but
205/// never widen it past [`Approvals::Required`].
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ValueEnum)]
207#[serde(rename_all = "kebab-case")]
208#[value(rename_all = "kebab-case")]
209pub enum MergePolicy {
210 /// Merged in a local checkout and pushed; no change request is opened.
211 LocalDirect,
212 /// A change request is opened and left open — as a draft while its checks run,
213 /// then ready, or kept a draft for its user's review where approvals are
214 /// required.
215 ChangeOpen,
216 /// A change request is opened and set to merge itself once its checks pass.
217 ChangeAuto,
218 /// A change request is opened and merged immediately.
219 ChangeDirect,
220}
221
222impl MergePolicy {
223 /// This policy narrowed to `requested`, or the reason that would widen it.
224 ///
225 /// The rule belongs to the rules system rather than to any one implementation
226 /// of [`Vcs`](crate::Vcs): a supplied implementation publishing under a policy
227 /// of its own applies this, rather than a restatement of it that could drift.
228 /// The direction is not symmetric and cannot be made so — widening is how work
229 /// reaches a base branch without the review its repository requires, and no
230 /// later step notices.
231 pub fn narrow(self, requested: MergePolicy) -> crate::Result<MergePolicy> {
232 crate::policy::narrow_publication(self, requested)
233 }
234}
235
236/// Whether a change needs someone else's approval before it may merge.
237///
238/// The review requirement, and the only place it is stated: a repository whose
239/// changes are reviewed before they land says so here, under a rule that matches it,
240/// and nothing infers it from where the repository is hosted.
241#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
242#[serde(rename_all = "lowercase")]
243pub enum Approvals {
244 /// At least one approval is required.
245 Required,
246 /// No approval is required.
247 None,
248}