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