verctl-core 0.9.7

Core configuration, manifest, fragment, changelog, and version domain logic for verctl
Documentation
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
use std::ffi::OsStr;
use std::fmt;
use std::path::{Path, PathBuf};

use anyhow::{Result, bail, ensure};
use ctl_core::validate::{cannot_be_empty, inside_the_repo};
use garde::Validate;
use serde::de::{IgnoredAny, MapAccess, Visitor};
use serde::{Deserialize, Serialize, de};

use super::Config;
use super::validate::{
    each_id_is_declared, no_id_is_listed_twice, non_empty_hook_argv, something_to_rewrite,
    tag_template_placeholders,
};

/// A file that serves a package version and must track it.
#[derive(Debug, Clone, Deserialize, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config as config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Pin {
    /// The file, relative to the directory containing `.ctl/`.
    #[garde(custom(inside_the_repo))]
    pub file: PathBuf,
    /// A mise `[tools]` entry, in a file that parses as TOML. Its own
    /// `?ref=v…` includes move with it.
    pub tool: Option<String>,
    /// `patterns` ids this file lists, so the file a spelling belongs to is
    /// written down instead of implied by table placement.
    #[serde(default, rename = "patterns")]
    #[garde(
        custom(each_id_is_declared),
        custom(no_id_is_listed_twice),
        custom(something_to_rewrite(self.tool.as_deref()))
    )]
    pub pattern_ids: Vec<String>,
    /// The patterns those ids name, filled in by `Config::load`, the only way
    /// to build a pin that rewrites anything.
    #[serde(skip)]
    pub patterns: Vec<PinPattern>,
    /// The package whose version this file serves.
    pub package: String,
}

/// A check `release` runs before its first write, as `release_checks` names
/// it.
///
/// Not `#[non_exhaustive]`: the release proof matches every check, so a new
/// one fails its build until it runs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase", try_from = "String")]
pub enum ReleaseCheck {
    /// `check registry`: each crates.io crate exists and lists its owners.
    Registry,
    /// `check trust`: each crates.io crate has a trusted publisher naming
    /// the repository and `release_workflow`.
    Trust,
}

impl ReleaseCheck {
    /// Every check, in the order the proof runs them.
    pub const ALL: [Self; 2] = [Self::Registry, Self::Trust];

    /// The name `.ctl/ver.yaml` and the report use.
    #[must_use]
    pub const fn name(self) -> &'static str {
        match self {
            Self::Registry => "registry",
            Self::Trust => "trust",
        }
    }

    /// The `release_checks` a file that sets none gets: every check.
    pub(super) fn default_list() -> Vec<Self> {
        Self::ALL.to_vec()
    }
}

/// A name outside the set fails here, naming the field and the names it
/// takes. serde's own wording names neither, because a parse problem carries
/// no field path.
impl TryFrom<String> for ReleaseCheck {
    type Error = String;

    fn try_from(name: String) -> Result<Self, Self::Error> {
        Self::ALL
            .into_iter()
            .find(|check| check.name() == name)
            .ok_or_else(|| {
                format!(
                    "release_checks lists {name:?}, which release does not run; use registry or trust, the checks that can change after the merge"
                )
            })
    }
}

/// The directory every ctl CLI shares, so a repo root gains one entry however
/// many of them it uses. verctl owns the files it names here and nothing else.
pub const DIR: &str = ".ctl";

/// verctl's declarations, named after the task an operator runs (`mise run
/// ver`) rather than after the crate that reads them.
pub const FILE: &str = ".ctl/ver.yaml";

/// The directory a config governs: what every `path` in it is relative to.
///
/// Declarations sit in `<root>/.ctl/`, so the directory containing the file is
/// a level too deep and its parent is the root. `-c crates/foo/.ctl/ver.yaml`
/// therefore still governs `crates/foo`. A file outside a `.ctl` directory is
/// read where it sits, which is what an ad-hoc `-c` requires.
#[must_use]
pub fn root_of(config: &Path) -> PathBuf {
    let dir = here(config.parent());
    if dir.file_name() == Some(OsStr::new(DIR)) {
        return here(dir.parent()).to_path_buf();
    }
    dir.to_path_buf()
}

fn here(path: Option<&Path>) -> &Path {
    path.filter(|path| !path.as_os_str().is_empty())
        .unwrap_or_else(|| Path::new("."))
}

/// What a `pins` pattern puts where the version goes.
pub const PLACEHOLDER: &str = "{version}";

/// What a tag template puts where the package name goes.
pub const NAME_PLACEHOLDER: &str = "{name}";

/// How release tags are named. The arity falls out of the template: no
/// `{name}` means one tag for the release; `{name}` means one tag per package.
#[derive(Debug, Clone, Deserialize, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[non_exhaustive]
pub struct Tags {
    /// Literal text with `{version}` and optionally `{name}`. Defaults to
    /// `v{version}`, so a repo that writes nothing keeps today's behaviour.
    #[serde(default = "Tags::default_template")]
    #[garde(
        custom(cannot_be_empty(
            r#"it is the shape of every release tag, like "v{version}" or "{name}@{version}""#
        )),
        custom(tag_template_placeholders)
    )]
    pub template: String,
}

impl Tags {
    fn default_template() -> String {
        format!("v{PLACEHOLDER}")
    }

    /// Whether the template names the package, so each package gets its own
    /// tag.
    #[must_use]
    pub fn uses_name(&self) -> bool {
        self.template.contains(NAME_PLACEHOLDER)
    }

    /// Substitute `{version}` and, when given, `{name}`. The load already
    /// proved those are the only braces, so a leftover `{` here is a bug.
    ///
    /// # Errors
    ///
    /// Returns an error when the template needs `{name}` and `name` is `None`,
    /// or when braces remain after substitution.
    pub fn render(&self, version: &str, name: Option<&str>) -> Result<String> {
        let mut out = self.template.replace(PLACEHOLDER, version);
        if let Some(name) = name {
            out = out.replace(NAME_PLACEHOLDER, name);
        } else if out.contains(NAME_PLACEHOLDER) {
            bail!(
                "tags.template {:?} needs {NAME_PLACEHOLDER} but no package name was given",
                self.template
            );
        }
        ensure!(
            !out.contains('{') && !out.contains('}'),
            "tags.template {:?} still has braces after substitution",
            self.template
        );
        Ok(out)
    }
}

impl Default for Tags {
    fn default() -> Self {
        Self {
            template: Self::default_template(),
        }
    }
}

/// Where the templates for served files live, and how they are marked. The
/// defaults are the whole convention: a repo that follows it writes nothing.
#[derive(Debug, Clone, Deserialize, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config))]
#[non_exhaustive]
pub struct Templates {
    /// The directory every template lives in, flat. Each one declares its own
    /// target, so nothing sits beside the file it generates.
    #[serde(default = "Templates::default_source")]
    #[garde(custom(inside_the_repo))]
    pub source: PathBuf,
    /// What marks a source file as a template of its target.
    #[serde(default = "Templates::default_suffix")]
    #[garde(custom(cannot_be_empty(
        r#"it is what marks a file in the source tree as a template, like ".jinja""#
    )))]
    pub suffix: String,
}

impl Templates {
    fn default_source() -> PathBuf {
        Path::new(DIR).join("templates")
    }

    fn default_suffix() -> String {
        ".jinja".to_owned()
    }
}

impl Default for Templates {
    fn default() -> Self {
        Self {
            source: Self::default_source(),
            suffix: Self::default_suffix(),
        }
    }
}

/// One version spelling in a file, and how often the file may say it.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct PinPattern {
    /// The text around a version, `{version}` where the version is. Literal
    /// text instead of a regex, so nothing about the file's format is
    /// assumed. Exactly one placeholder, checked over `patterns` so the
    /// complaint names the id.
    ///
    /// A side is bounded when the text between `{version}` and the pattern's
    /// edge contains a character that is not a digit, `.`, `-`, or `+`. The
    /// character next to `{version}` must not be a digit, or a `.` with a
    /// digit beyond it.
    ///
    /// Under `whole_line` the line start or end bounds a side whose literal is
    /// empty. The load refuses a pattern with an open side.
    pub r#match: String,
    /// How often the file must say it. A pin that lost its only mention, or
    /// drifted to one nobody declared, fails the release rather than serving
    /// a stale version.
    #[serde(default)]
    pub occurrences: Occurrences,
    /// Whether the match is a whole line rather than text inside one.
    ///
    /// When unset, a pattern matches anywhere, which is what an inline
    /// spelling needs: `github:org/tool@1.2.3` is inside a longer line.
    ///
    /// A pattern that owns its line sets this flag instead of anchoring on
    /// whatever text happens to be next to it. The alternative is spelling the
    /// neighbour into `match`, which then breaks when the neighbour moves.
    ///
    /// The flag also makes a partial version fail instead of rewriting,
    /// because a line ending in `0.1.1_local` does not end where the version
    /// does.
    #[serde(default)]
    pub whole_line: bool,
}

/// How many times a pattern must match. A count is not always the useful
/// shape. A document whose examples come and go needs "one or more".
/// Retiring a spelling needs "none".
#[derive(Debug, Clone, Copy, Default)]
#[non_exhaustive]
pub enum Occurrences {
    /// Exactly one. What a pin normally is, so it is the default.
    #[default]
    Once,
    /// One or more, however many. For a file whose mentions grow and shrink
    /// on their own, where only "still tracked" is worth asserting.
    Many,
    /// None. A spelling that must stay gone, so its return fails a release
    /// instead of being served.
    Never,
    /// Exactly this many, for a file that says it a known number of times.
    Exactly(usize),
    /// This many or more.
    AtLeast(usize),
}

/// The vocabulary, spelled out. A derived enum cannot read both shapes a repo
/// writes. An unbounded word is a plain scalar. A bound is a mapping that a
/// newtype variant would only accept as a YAML tag (`!exactly 2`).
///
/// Untagged reads both and then reports "matched no variant", naming a type
/// nobody wrote. So the arity is read here and reports errors in the words a
/// repo uses.
pub(super) const ARITY: &str = "once, many, never, {exactly: N}, or {at_least: N}";

impl<'de> Deserialize<'de> for Occurrences {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_any(OccurrencesVisitor)
    }
}

struct OccurrencesVisitor;

impl<'de> Visitor<'de> for OccurrencesVisitor {
    type Value = Occurrences;

    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{ARITY}")
    }

    fn visit_str<E: de::Error>(self, v: &str) -> Result<Occurrences, E> {
        match v {
            "once" => Ok(Occurrences::Once),
            "many" => Ok(Occurrences::Many),
            "never" => Ok(Occurrences::Never),
            _ => Err(E::custom(format!("must be {ARITY}"))),
        }
    }

    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Occurrences, A::Error> {
        use serde::de::Error;
        let wrong = || A::Error::custom(format!("must be {ARITY}"));
        let key: String = map.next_key()?.ok_or_else(wrong)?;
        #[expect(
            clippy::map_err_ignore,
            reason = "the report names the accepted shapes; the number parse error adds nothing"
        )]
        let count: usize = map.next_value().map_err(|_| wrong())?;
        if map.next_key::<IgnoredAny>()?.is_some() {
            return Err(wrong());
        }
        match key.as_str() {
            "exactly" => Ok(Occurrences::Exactly(count)),
            "at_least" => Ok(Occurrences::AtLeast(count)),
            _ => Err(wrong()),
        }
    }
}

impl Occurrences {
    /// Whether `found` occurrences satisfy this rule.
    #[must_use]
    pub const fn allows(self, found: usize) -> bool {
        match self {
            Self::Once => found == 1,
            Self::Many => found >= 1,
            Self::Never => found == 0,
            Self::Exactly(count) => found == count,
            Self::AtLeast(count) => found >= count,
        }
    }
}

impl fmt::Display for Occurrences {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Once => f.write_str("exactly once"),
            Self::Many => f.write_str("one or more"),
            Self::Never => f.write_str("never"),
            Self::Exactly(count) => write!(f, "exactly {count} times"),
            Self::AtLeast(count) => write!(f, "{count} or more times"),
        }
    }
}

/// Whose names changelog entries never credit. Release notes credit no
/// maintainer, and only this list identifies who one is: GitHub's
/// `author_association` reads a private organization member as `CONTRIBUTOR`
/// through an App token.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Changelog {
    /// GitHub logins never credited: maintainers and the Apps that open pull
    /// requests. Omit to list no one.
    #[serde(default)]
    pub internal_authors: Vec<String>,
}

impl Changelog {
    /// Whether `login` is listed, ignoring case as GitHub logins do.
    #[must_use]
    pub fn is_internal(&self, login: &str) -> bool {
        self.internal_authors
            .iter()
            .any(|listed| listed.eq_ignore_ascii_case(login))
    }
}

/// Extra work after version bumps, committed on the Version PR.
///
/// Unknown keys fail the load, as in every other block.
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Prepare {
    /// argv after all bumps (for example `["mise", "run", "version-sync"]`).
    pub after: Option<Vec<String>>,
    /// Extra paths `after` may write. Anything else dirty fails.
    #[serde(default)]
    pub stage: Vec<String>,
    /// Collect gitignored paths that match `stage`. Off by default.
    #[serde(default)]
    pub stage_ignored: bool,
    /// Removed: the Version PR is not labeled, since nothing reads the label.
    /// Kept only for files that still set it. Such a file fails the load with
    /// a message to delete it, instead of serde's bare unknown-field error.
    /// `true` when the key is present with any value, null included;
    /// absent means the file is current.
    #[serde(default, deserialize_with = "key_present")]
    pub(super) version_label: bool,
}

/// Whether a key is present, whatever its value. serde reads an explicit null
/// into `Option::None`, the same as an absent key. An `Option` therefore
/// contains the same value for `version_label: ~` as for a file that never set
/// it. serde calls this only when the key is in the document.
fn key_present<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<bool, D::Error> {
    IgnoredAny::deserialize(deserializer).map(|_| true)
}

/// Commands `release` runs around the registry uploads.
///
/// Unknown keys fail the load, as in every other block.
#[derive(Debug, Clone, Deserialize, Default, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Config as config))]
#[non_exhaustive]
pub struct PublishHooks {
    /// argv run once after versions are proved on HEAD and before the first
    /// publisher upload. A non-zero exit stops the run with nothing published.
    /// Omit to run no pre-publish hook.
    #[garde(inner(custom(non_empty_hook_argv)))]
    pub before: Option<Vec<String>>,
    /// argv run once after every package in the release has published. Omit to
    /// run no post-publish hook.
    #[garde(inner(custom(non_empty_hook_argv)))]
    pub after: Option<Vec<String>>,
}

/// The Version PR's title and commit message.
///
/// Both default to what verctl wrote before the block existed, so a
/// repository that sets neither sees the same pull request.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct Proposal {
    /// The pull request title. Unset or empty means
    /// [`Proposal::DEFAULT_TITLE`].
    #[serde(default)]
    pub title: Option<String>,
    /// The commit message on the Version PR branch. Unset or empty means the
    /// resolved title.
    #[serde(default)]
    pub commit_message: Option<String>,
}

impl Proposal {
    /// The title used when `title` is unset or empty.
    pub const DEFAULT_TITLE: &'static str = "chore(release): version packages";

    /// The resolved title: the configured one, or [`Proposal::DEFAULT_TITLE`].
    #[must_use]
    pub fn title(&self) -> &str {
        self.title
            .as_deref()
            .filter(|title| !title.is_empty())
            .unwrap_or(Self::DEFAULT_TITLE)
    }

    /// The resolved commit message: the configured one, or the title.
    #[must_use]
    pub fn commit_message(&self) -> &str {
        self.commit_message
            .as_deref()
            .filter(|message| !message.is_empty())
            .unwrap_or_else(|| self.title())
    }
}