verctl_core/config/sections.rs
1use std::ffi::OsStr;
2use std::fmt;
3use std::path::{Path, PathBuf};
4
5use anyhow::{Result, bail, ensure};
6use ctl_core::validate::{cannot_be_empty, inside_the_repo};
7use garde::Validate;
8use serde::de::{IgnoredAny, MapAccess, Visitor};
9use serde::{Deserialize, Serialize, de};
10
11use super::Config;
12use super::validate::{
13 each_id_is_declared, no_id_is_listed_twice, non_empty_hook_argv, something_to_rewrite,
14 tag_template_placeholders,
15};
16
17/// A file that serves a package version and must track it.
18#[derive(Debug, Clone, Deserialize, Validate)]
19#[serde(deny_unknown_fields)]
20#[garde(context(Config as config))]
21#[garde(allow_unvalidated)]
22#[non_exhaustive]
23pub struct Pin {
24 /// The file, relative to the directory containing `.ctl/`.
25 #[garde(custom(inside_the_repo))]
26 pub file: PathBuf,
27 /// A mise `[tools]` entry, in a file that parses as TOML. Its own
28 /// `?ref=v…` includes move with it.
29 pub tool: Option<String>,
30 /// `patterns` ids this file lists, so the file a spelling belongs to is
31 /// written down instead of implied by table placement.
32 #[serde(default, rename = "patterns")]
33 #[garde(
34 custom(each_id_is_declared),
35 custom(no_id_is_listed_twice),
36 custom(something_to_rewrite(self.tool.as_deref()))
37 )]
38 pub pattern_ids: Vec<String>,
39 /// The patterns those ids name, filled in by `Config::load`, the only way
40 /// to build a pin that rewrites anything.
41 #[serde(skip)]
42 pub patterns: Vec<PinPattern>,
43 /// The package whose version this file serves.
44 pub package: String,
45}
46
47/// A check `release` runs before its first write, as `release_checks` names
48/// it.
49///
50/// Not `#[non_exhaustive]`: the release proof matches every check, so a new
51/// one fails its build until it runs.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
53#[serde(rename_all = "lowercase", try_from = "String")]
54pub enum ReleaseCheck {
55 /// `check registry`: each crates.io crate exists and lists its owners.
56 Registry,
57 /// `check trust`: each crates.io crate has a trusted publisher naming
58 /// the repository and `release_workflow`.
59 Trust,
60}
61
62impl ReleaseCheck {
63 /// Every check, in the order the proof runs them.
64 pub const ALL: [Self; 2] = [Self::Registry, Self::Trust];
65
66 /// The name `.ctl/ver.yaml` and the report use.
67 #[must_use]
68 pub const fn name(self) -> &'static str {
69 match self {
70 Self::Registry => "registry",
71 Self::Trust => "trust",
72 }
73 }
74
75 /// The `release_checks` a file that sets none gets: every check.
76 pub(super) fn default_list() -> Vec<Self> {
77 Self::ALL.to_vec()
78 }
79}
80
81/// A name outside the set fails here, naming the field and the names it
82/// takes. serde's own wording names neither, because a parse problem carries
83/// no field path.
84impl TryFrom<String> for ReleaseCheck {
85 type Error = String;
86
87 fn try_from(name: String) -> Result<Self, Self::Error> {
88 Self::ALL
89 .into_iter()
90 .find(|check| check.name() == name)
91 .ok_or_else(|| {
92 format!(
93 "release_checks lists {name:?}, which release does not run; use registry or trust, the checks that can change after the merge"
94 )
95 })
96 }
97}
98
99/// The directory every ctl CLI shares, so a repo root gains one entry however
100/// many of them it uses. verctl owns the files it names here and nothing else.
101pub const DIR: &str = ".ctl";
102
103/// verctl's declarations, named after the task an operator runs (`mise run
104/// ver`) rather than after the crate that reads them.
105pub const FILE: &str = ".ctl/ver.yaml";
106
107/// The directory a config governs: what every `path` in it is relative to.
108///
109/// Declarations sit in `<root>/.ctl/`, so the directory containing the file is
110/// a level too deep and its parent is the root. `-c crates/foo/.ctl/ver.yaml`
111/// therefore still governs `crates/foo`. A file outside a `.ctl` directory is
112/// read where it sits, which is what an ad-hoc `-c` requires.
113#[must_use]
114pub fn root_of(config: &Path) -> PathBuf {
115 let dir = here(config.parent());
116 if dir.file_name() == Some(OsStr::new(DIR)) {
117 return here(dir.parent()).to_path_buf();
118 }
119 dir.to_path_buf()
120}
121
122fn here(path: Option<&Path>) -> &Path {
123 path.filter(|path| !path.as_os_str().is_empty())
124 .unwrap_or_else(|| Path::new("."))
125}
126
127/// What a `pins` pattern puts where the version goes.
128pub const PLACEHOLDER: &str = "{version}";
129
130/// What a tag template puts where the package name goes.
131pub const NAME_PLACEHOLDER: &str = "{name}";
132
133/// How release tags are named. The arity falls out of the template: no
134/// `{name}` means one tag for the release; `{name}` means one tag per package.
135#[derive(Debug, Clone, Deserialize, Validate)]
136#[serde(deny_unknown_fields)]
137#[garde(context(Config))]
138#[non_exhaustive]
139pub struct Tags {
140 /// Literal text with `{version}` and optionally `{name}`. Defaults to
141 /// `v{version}`, so a repo that writes nothing keeps today's behaviour.
142 #[serde(default = "Tags::default_template")]
143 #[garde(
144 custom(cannot_be_empty(
145 r#"it is the shape of every release tag, like "v{version}" or "{name}@{version}""#
146 )),
147 custom(tag_template_placeholders)
148 )]
149 pub template: String,
150}
151
152impl Tags {
153 fn default_template() -> String {
154 format!("v{PLACEHOLDER}")
155 }
156
157 /// Whether the template names the package, so each package gets its own
158 /// tag.
159 #[must_use]
160 pub fn uses_name(&self) -> bool {
161 self.template.contains(NAME_PLACEHOLDER)
162 }
163
164 /// Substitute `{version}` and, when given, `{name}`. The load already
165 /// proved those are the only braces, so a leftover `{` here is a bug.
166 ///
167 /// # Errors
168 ///
169 /// Returns an error when the template needs `{name}` and `name` is `None`,
170 /// or when braces remain after substitution.
171 pub fn render(&self, version: &str, name: Option<&str>) -> Result<String> {
172 let mut out = self.template.replace(PLACEHOLDER, version);
173 if let Some(name) = name {
174 out = out.replace(NAME_PLACEHOLDER, name);
175 } else if out.contains(NAME_PLACEHOLDER) {
176 bail!(
177 "tags.template {:?} needs {NAME_PLACEHOLDER} but no package name was given",
178 self.template
179 );
180 }
181 ensure!(
182 !out.contains('{') && !out.contains('}'),
183 "tags.template {:?} still has braces after substitution",
184 self.template
185 );
186 Ok(out)
187 }
188}
189
190impl Default for Tags {
191 fn default() -> Self {
192 Self {
193 template: Self::default_template(),
194 }
195 }
196}
197
198/// Where the templates for served files live, and how they are marked. The
199/// defaults are the whole convention: a repo that follows it writes nothing.
200#[derive(Debug, Clone, Deserialize, Validate)]
201#[serde(deny_unknown_fields)]
202#[garde(context(Config))]
203#[non_exhaustive]
204pub struct Templates {
205 /// The directory every template lives in, flat. Each one declares its own
206 /// target, so nothing sits beside the file it generates.
207 #[serde(default = "Templates::default_source")]
208 #[garde(custom(inside_the_repo))]
209 pub source: PathBuf,
210 /// What marks a source file as a template of its target.
211 #[serde(default = "Templates::default_suffix")]
212 #[garde(custom(cannot_be_empty(
213 r#"it is what marks a file in the source tree as a template, like ".jinja""#
214 )))]
215 pub suffix: String,
216}
217
218impl Templates {
219 fn default_source() -> PathBuf {
220 Path::new(DIR).join("templates")
221 }
222
223 fn default_suffix() -> String {
224 ".jinja".to_owned()
225 }
226}
227
228impl Default for Templates {
229 fn default() -> Self {
230 Self {
231 source: Self::default_source(),
232 suffix: Self::default_suffix(),
233 }
234 }
235}
236
237/// One version spelling in a file, and how often the file may say it.
238#[derive(Debug, Clone, Deserialize)]
239#[serde(deny_unknown_fields)]
240#[non_exhaustive]
241pub struct PinPattern {
242 /// The text around a version, `{version}` where the version is. Literal
243 /// text instead of a regex, so nothing about the file's format is
244 /// assumed. Exactly one placeholder, checked over `patterns` so the
245 /// complaint names the id.
246 ///
247 /// A side is bounded when the text between `{version}` and the pattern's
248 /// edge contains a character that is not a digit, `.`, `-`, or `+`. The
249 /// character next to `{version}` must not be a digit, or a `.` with a
250 /// digit beyond it.
251 ///
252 /// Under `whole_line` the line start or end bounds a side whose literal is
253 /// empty. The load refuses a pattern with an open side.
254 pub r#match: String,
255 /// How often the file must say it. A pin that lost its only mention, or
256 /// drifted to one nobody declared, fails the release rather than serving
257 /// a stale version.
258 #[serde(default)]
259 pub occurrences: Occurrences,
260 /// Whether the match is a whole line rather than text inside one.
261 ///
262 /// When unset, a pattern matches anywhere, which is what an inline
263 /// spelling needs: `github:org/tool@1.2.3` is inside a longer line.
264 ///
265 /// A pattern that owns its line sets this flag instead of anchoring on
266 /// whatever text happens to be next to it. The alternative is spelling the
267 /// neighbour into `match`, which then breaks when the neighbour moves.
268 ///
269 /// The flag also makes a partial version fail instead of rewriting,
270 /// because a line ending in `0.1.1_local` does not end where the version
271 /// does.
272 #[serde(default)]
273 pub whole_line: bool,
274}
275
276/// How many times a pattern must match. A count is not always the useful
277/// shape. A document whose examples come and go needs "one or more".
278/// Retiring a spelling needs "none".
279#[derive(Debug, Clone, Copy, Default)]
280#[non_exhaustive]
281pub enum Occurrences {
282 /// Exactly one. What a pin normally is, so it is the default.
283 #[default]
284 Once,
285 /// One or more, however many. For a file whose mentions grow and shrink
286 /// on their own, where only "still tracked" is worth asserting.
287 Many,
288 /// None. A spelling that must stay gone, so its return fails a release
289 /// instead of being served.
290 Never,
291 /// Exactly this many, for a file that says it a known number of times.
292 Exactly(usize),
293 /// This many or more.
294 AtLeast(usize),
295}
296
297/// The vocabulary, spelled out. A derived enum cannot read both shapes a repo
298/// writes. An unbounded word is a plain scalar. A bound is a mapping that a
299/// newtype variant would only accept as a YAML tag (`!exactly 2`).
300///
301/// Untagged reads both and then reports "matched no variant", naming a type
302/// nobody wrote. So the arity is read here and reports errors in the words a
303/// repo uses.
304pub(super) const ARITY: &str = "once, many, never, {exactly: N}, or {at_least: N}";
305
306impl<'de> Deserialize<'de> for Occurrences {
307 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
308 deserializer.deserialize_any(OccurrencesVisitor)
309 }
310}
311
312struct OccurrencesVisitor;
313
314impl<'de> Visitor<'de> for OccurrencesVisitor {
315 type Value = Occurrences;
316
317 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
318 write!(formatter, "{ARITY}")
319 }
320
321 fn visit_str<E: de::Error>(self, v: &str) -> Result<Occurrences, E> {
322 match v {
323 "once" => Ok(Occurrences::Once),
324 "many" => Ok(Occurrences::Many),
325 "never" => Ok(Occurrences::Never),
326 _ => Err(E::custom(format!("must be {ARITY}"))),
327 }
328 }
329
330 fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Occurrences, A::Error> {
331 use serde::de::Error;
332 let wrong = || A::Error::custom(format!("must be {ARITY}"));
333 let key: String = map.next_key()?.ok_or_else(wrong)?;
334 #[expect(
335 clippy::map_err_ignore,
336 reason = "the report names the accepted shapes; the number parse error adds nothing"
337 )]
338 let count: usize = map.next_value().map_err(|_| wrong())?;
339 if map.next_key::<IgnoredAny>()?.is_some() {
340 return Err(wrong());
341 }
342 match key.as_str() {
343 "exactly" => Ok(Occurrences::Exactly(count)),
344 "at_least" => Ok(Occurrences::AtLeast(count)),
345 _ => Err(wrong()),
346 }
347 }
348}
349
350impl Occurrences {
351 /// Whether `found` occurrences satisfy this rule.
352 #[must_use]
353 pub const fn allows(self, found: usize) -> bool {
354 match self {
355 Self::Once => found == 1,
356 Self::Many => found >= 1,
357 Self::Never => found == 0,
358 Self::Exactly(count) => found == count,
359 Self::AtLeast(count) => found >= count,
360 }
361 }
362}
363
364impl fmt::Display for Occurrences {
365 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
366 match self {
367 Self::Once => f.write_str("exactly once"),
368 Self::Many => f.write_str("one or more"),
369 Self::Never => f.write_str("never"),
370 Self::Exactly(count) => write!(f, "exactly {count} times"),
371 Self::AtLeast(count) => write!(f, "{count} or more times"),
372 }
373 }
374}
375
376/// Whose names changelog entries never credit. Release notes credit no
377/// maintainer, and only this list identifies who one is: GitHub's
378/// `author_association` reads a private organization member as `CONTRIBUTOR`
379/// through an App token.
380#[derive(Debug, Clone, Default, Deserialize)]
381#[serde(deny_unknown_fields)]
382#[non_exhaustive]
383pub struct Changelog {
384 /// GitHub logins never credited: maintainers and the Apps that open pull
385 /// requests. Omit to list no one.
386 #[serde(default)]
387 pub internal_authors: Vec<String>,
388}
389
390impl Changelog {
391 /// Whether `login` is listed, ignoring case as GitHub logins do.
392 #[must_use]
393 pub fn is_internal(&self, login: &str) -> bool {
394 self.internal_authors
395 .iter()
396 .any(|listed| listed.eq_ignore_ascii_case(login))
397 }
398}
399
400/// Extra work after version bumps, committed on the Version PR.
401///
402/// Unknown keys fail the load, as in every other block.
403#[derive(Debug, Clone, Deserialize, Default)]
404#[serde(deny_unknown_fields)]
405#[non_exhaustive]
406pub struct Prepare {
407 /// argv after all bumps (for example `["mise", "run", "version-sync"]`).
408 pub after: Option<Vec<String>>,
409 /// Extra paths `after` may write. Anything else dirty fails.
410 #[serde(default)]
411 pub stage: Vec<String>,
412 /// Collect gitignored paths that match `stage`. Off by default.
413 #[serde(default)]
414 pub stage_ignored: bool,
415 /// Removed: the Version PR is not labeled, since nothing reads the label.
416 /// Kept only for files that still set it. Such a file fails the load with
417 /// a message to delete it, instead of serde's bare unknown-field error.
418 /// `true` when the key is present with any value, null included;
419 /// absent means the file is current.
420 #[serde(default, deserialize_with = "key_present")]
421 pub(super) version_label: bool,
422}
423
424/// Whether a key is present, whatever its value. serde reads an explicit null
425/// into `Option::None`, the same as an absent key. An `Option` therefore
426/// contains the same value for `version_label: ~` as for a file that never set
427/// it. serde calls this only when the key is in the document.
428fn key_present<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<bool, D::Error> {
429 IgnoredAny::deserialize(deserializer).map(|_| true)
430}
431
432/// Commands `release` runs around the registry uploads.
433///
434/// Unknown keys fail the load, as in every other block.
435#[derive(Debug, Clone, Deserialize, Default, Validate)]
436#[serde(deny_unknown_fields)]
437#[garde(context(Config as config))]
438#[non_exhaustive]
439pub struct PublishHooks {
440 /// argv run once after versions are proved on HEAD and before the first
441 /// publisher upload. A non-zero exit stops the run with nothing published.
442 /// Omit to run no pre-publish hook.
443 #[garde(inner(custom(non_empty_hook_argv)))]
444 pub before: Option<Vec<String>>,
445 /// argv run once after every package in the release has published. Omit to
446 /// run no post-publish hook.
447 #[garde(inner(custom(non_empty_hook_argv)))]
448 pub after: Option<Vec<String>>,
449}
450
451/// The Version PR's title and commit message.
452///
453/// Both default to what verctl wrote before the block existed, so a
454/// repository that sets neither sees the same pull request.
455#[derive(Debug, Clone, Default, Deserialize)]
456#[serde(deny_unknown_fields)]
457#[non_exhaustive]
458pub struct Proposal {
459 /// The pull request title. Unset or empty means
460 /// [`Proposal::DEFAULT_TITLE`].
461 #[serde(default)]
462 pub title: Option<String>,
463 /// The commit message on the Version PR branch. Unset or empty means the
464 /// resolved title.
465 #[serde(default)]
466 pub commit_message: Option<String>,
467}
468
469impl Proposal {
470 /// The title used when `title` is unset or empty.
471 pub const DEFAULT_TITLE: &'static str = "chore(release): version packages";
472
473 /// The resolved title: the configured one, or [`Proposal::DEFAULT_TITLE`].
474 #[must_use]
475 pub fn title(&self) -> &str {
476 self.title
477 .as_deref()
478 .filter(|title| !title.is_empty())
479 .unwrap_or(Self::DEFAULT_TITLE)
480 }
481
482 /// The resolved commit message: the configured one, or the title.
483 #[must_use]
484 pub fn commit_message(&self) -> &str {
485 self.commit_message
486 .as_deref()
487 .filter(|message| !message.is_empty())
488 .unwrap_or_else(|| self.title())
489 }
490}