Skip to main content

verctl_core/
config.rs

1use std::collections::{BTreeMap, BTreeSet};
2use std::ffi::OsStr;
3use std::path::{Component, Path, PathBuf};
4use std::str::FromStr;
5use std::{fmt, fs};
6
7use anyhow::{Context, Result, bail, ensure};
8use ctl_core::input::{FieldPath, Input};
9use ctl_core::validate;
10use ctl_core::validate::{at_least_one, cannot_be_empty, inside_the_repo};
11use garde::Validate;
12use serde::de::value::MapAccessDeserializer;
13use serde::de::{IgnoredAny, MapAccess, SeqAccess, Visitor};
14use serde::{Deserialize, Serialize, de};
15
16use crate::driver::{CommandSpec, Driver, Format, Text};
17use crate::publisher_spec::{self as publisher, PublisherSpec, RELEASE_ONLY};
18use crate::{asset_rules as assets, detect};
19
20/// A driver's read or write step: a mise task or an argv.
21#[derive(Debug, Clone, Deserialize)]
22#[serde(untagged)]
23#[non_exhaustive]
24pub enum CommandField {
25    /// A `mise run` task name.
26    Mise(String),
27    /// A program and its arguments, run without a shell.
28    Argv(Vec<String>),
29}
30
31impl CommandField {
32    fn into_spec(self) -> Result<CommandSpec> {
33        match self {
34            Self::Mise(task) => {
35                if task.is_empty() {
36                    bail!("mise task name is empty");
37                }
38                Ok(CommandSpec::Mise(task))
39            }
40            Self::Argv(argv) => {
41                ensure!(!argv.is_empty(), "driver argv is empty");
42                Ok(CommandSpec::Argv(argv))
43            }
44        }
45    }
46}
47
48/// A version driver as declared, before it becomes a [`Driver`]. `format` and
49/// `keys` edit the manifest in place. `read` and `write` run commands instead
50/// and take precedence.
51#[derive(Debug, Clone, Default, Deserialize)]
52#[non_exhaustive]
53pub struct DriverSpec {
54    /// `toml` or `json`, edited at `keys`. `gomod` (the `// vX.Y.Z` comment on
55    /// a `go.mod` module line) and `version` (a file containing only the
56    /// version) take no keys.
57    pub format: Option<String>,
58    /// Key paths containing the version, tried in order.
59    pub keys: Option<Vec<String>>,
60    /// Command that takes the manifest on stdin and prints the version.
61    pub read: Option<CommandField>,
62    /// Command that takes the manifest on stdin and prints it with the new
63    /// version.
64    pub write: Option<CommandField>,
65    /// Command run after the bumps, such as a lockfile refresh. Inferred from
66    /// the tree for stock manifests when omitted.
67    pub after: Option<String>,
68}
69
70impl DriverSpec {
71    /// Build the [`Driver`]. `name` only labels the errors.
72    ///
73    /// # Errors
74    ///
75    /// Returns an error when a `read` and `write` pair has an empty mise task
76    /// name or an empty argv. Without that pair, it returns an error when
77    /// `format` is missing or not `toml`, `json`, `gomod`, or `version`, when
78    /// `keys` is missing or empty for `toml` or `json`, or when `gomod` or
79    /// `version` has `keys`.
80    pub fn into_driver(self, name: &str) -> Result<Driver> {
81        if let (Some(read), Some(write)) = (self.read, self.write) {
82            return Ok(Driver::Command {
83                read: read.into_spec()?,
84                write: write.into_spec()?,
85                after: self.after,
86            });
87        }
88        let format = match self.format.as_deref() {
89            Some("toml") => Format::Toml,
90            Some("json") => Format::Json,
91            Some(text @ ("gomod" | "version")) => {
92                ensure!(
93                    self.keys.is_none(),
94                    "driver {name:?} has format {text}, which reads the whole file and takes no keys"
95                );
96                let text = if text == "gomod" {
97                    Text::GoMod
98                } else {
99                    Text::Version
100                };
101                return Ok(Driver::Text {
102                    text,
103                    after: self.after,
104                });
105            }
106            Some(other) => bail!("driver {name:?} has unknown format {other:?}"),
107            None => bail!("driver {name:?} needs format+keys or read+write"),
108        };
109        let keys = self
110            .keys
111            .filter(|keys| !keys.is_empty())
112            .with_context(|| format!("driver {name:?} needs keys"))?;
113        Ok(Driver::Path {
114            format,
115            keys,
116            after: self.after,
117        })
118    }
119
120    fn stock(name: &str) -> Option<Self> {
121        match name {
122            "cargo" => Some(Self {
123                format: Some("toml".into()),
124                keys: Some(vec![
125                    "workspace.package.version".into(),
126                    "package.version".into(),
127                ]),
128                ..Self::default()
129            }),
130            "npm" => Some(Self {
131                format: Some("json".into()),
132                keys: Some(vec!["version".into()]),
133                ..Self::default()
134            }),
135            "pyproject" => Some(Self {
136                format: Some("toml".into()),
137                keys: Some(vec!["project.version".into()]),
138                ..Self::default()
139            }),
140            "go" => Some(Self {
141                format: Some("gomod".into()),
142                ..Self::default()
143            }),
144            "version" => Some(Self {
145                format: Some("version".into()),
146                ..Self::default()
147            }),
148            _ => None,
149        }
150    }
151
152    fn merge(self, over: Self) -> Self {
153        Self {
154            format: over.format.or(self.format),
155            keys: over.keys.or(self.keys),
156            read: over.read.or(self.read),
157            write: over.write.or(self.write),
158            after: over.after.or(self.after),
159        }
160    }
161}
162
163/// One released package: its manifest, how that manifest contains the version,
164/// and how it is published.
165#[derive(Debug, Clone, Deserialize)]
166#[non_exhaustive]
167pub struct PackageSpec {
168    /// The name fragments, tags, and the changelog use for the package.
169    pub name: String,
170    /// The manifest, relative to the directory containing `.ctl/`.
171    pub path: PathBuf,
172    /// A `drivers` entry or stock driver name. Omit to infer it from the
173    /// manifest file name.
174    pub driver: Option<String>,
175    /// Stock `cargo` / `bun`, a `publishers` key, or omit to infer. `none`
176    /// releases the package on GitHub only: tag, Release, and assets, with no
177    /// registry upload.
178    pub publisher: Option<String>,
179    /// Pretty noun (`crate`, `package`, `wheel`). Defaults from the publisher.
180    pub noun: Option<String>,
181    /// How the package is published, beyond what its manifest implies.
182    ///
183    /// A mapping contains options of the publisher the package resolves to,
184    /// which keeps its upload command and its registry check: `verify: false`
185    /// for cargo. A list replaces the whole upload command, and the registry
186    /// check goes with it unless `query` is set. When omitted, the publisher
187    /// runs with its defaults.
188    #[serde(default)]
189    pub publish: Option<Publish>,
190    /// Fills the publisher's `{registry}` placeholder and is named in the plan.
191    /// Empty means none.
192    pub registry: Option<String>,
193    /// Asks the registry whether a version is published, in place of the
194    /// publisher's query or the crates.io index read. When omitted, the
195    /// publisher decides; an empty list turns the check off for this package.
196    pub query: Option<Vec<String>>,
197    /// Package CHANGELOG.md. Defaults to next to the manifest.
198    pub changelog: Option<PathBuf>,
199    /// Lets this package leave `0.0.0` with a `minor` fragment, so its first
200    /// release is `0.1.0`. When omitted, a package at `0.0.0` takes only
201    /// `patch` and first releases `0.0.1`. Inert once the package has released.
202    #[serde(default)]
203    pub first_minor: bool,
204    /// The tag of the candidate versions this package releases, such as `rc`:
205    /// `verctl version` writes `<base>-<tag>.<count>` while it is set. When
206    /// omitted, the package releases stable versions, and a current prerelease
207    /// version becomes the stable one.
208    pub prerelease: Option<Prerelease>,
209    /// The version is on one marker line of the file, such as
210    /// `# version: 1.2.0`, `// version: 1.2.0`, or `<!-- version: 1.2.0 -->`.
211    /// So a file of any type can be a package, such as one reusable workflow
212    /// or one script.
213    ///
214    /// When unset, a file is read by its stock or named driver, and a stray
215    /// marker line in it means nothing. It takes no `driver` or driver fields,
216    /// and with no publisher the package releases on GitHub only.
217    #[serde(default)]
218    pub marker: bool,
219    /// The crates.io logins this package's crates must list as owners, which
220    /// `check registry` proves. It replaces the top-level `owners` for this
221    /// package. When omitted, the package expects the top-level list.
222    pub owners: Option<Vec<String>>,
223    /// Inline driver fields. They override the named driver's.
224    #[serde(flatten)]
225    pub spec: DriverSpec,
226    /// Every key under the package that no field above reads. A struct that
227    /// flattens another cannot deny unknown fields, so this map collects them
228    /// and `no_unknown_package_keys` refuses the load when it contains one.
229    #[serde(flatten)]
230    #[expect(
231        clippy::zero_sized_map_values,
232        reason = "the keys are all that is read, and serde has no set to flatten into"
233    )]
234    unknown: BTreeMap<String, IgnoredAny>,
235}
236
237/// The tag of a candidate version: lowercase ASCII letters.
238///
239/// Letters keep `<tag>.<count>` a valid semver prerelease with a separate
240/// numeric count, keep the tag a valid npm dist-tag, and make tags compare in
241/// semver order as words do (`alpha < beta < rc`). A package's rule in
242/// `a_prerelease_is_lowercase_letters` refuses any other tag at load, so a
243/// tag read from a loaded config always passes [`Prerelease::is_valid`].
244#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
245#[serde(transparent)]
246pub struct Prerelease(String);
247
248impl Prerelease {
249    /// A tag, or the reason `tag` is not one.
250    ///
251    /// # Errors
252    ///
253    /// Returns an error when `tag` is empty or contains anything but lowercase
254    /// ASCII letters.
255    pub fn new(tag: &str) -> Result<Self> {
256        let tag = Self(tag.to_owned());
257        ensure!(tag.is_valid(), "{}", Self::RULE);
258        Ok(tag)
259    }
260
261    /// The tag as written.
262    #[must_use]
263    pub fn as_str(&self) -> &str {
264        &self.0
265    }
266
267    /// Whether the tag is one or more lowercase ASCII letters, and neither `x`
268    /// nor `latest`.
269    #[must_use]
270    pub fn is_valid(&self) -> bool {
271        !self.0.is_empty()
272            && !matches!(self.0.as_str(), "x" | "latest")
273            && self.0.bytes().all(|byte| byte.is_ascii_lowercase())
274    }
275
276    /// Two words are refused besides the letter rule. npm reads `x` alone as
277    /// the version range "any" and refuses it as a dist-tag. `latest` is the
278    /// dist-tag every plain install resolves, so a candidate under it would
279    /// reach every consumer.
280    const RULE: &'static str = "a prerelease tag is lowercase ASCII letters only, such as rc, beta, or next; never x, which npm reads as a version range, and never latest, which every plain install resolves; remove digits, dots, and capitals";
281}
282
283impl PackageSpec {
284    /// The upload command this package wrote in place of its publisher's.
285    #[must_use]
286    pub fn publish_command(&self) -> Option<&[String]> {
287        match &self.publish {
288            Some(Publish::Command(argv)) => Some(argv),
289            Some(Publish::Options(_)) | None => None,
290        }
291    }
292
293    /// The options this package wrote for its publisher.
294    #[must_use]
295    pub fn publish_options(&self) -> Option<&PublishOptions> {
296        match &self.publish {
297            Some(Publish::Options(options)) => Some(options),
298            Some(Publish::Command(_)) | None => None,
299        }
300    }
301
302    /// The package changelog, resolved against `root`.
303    #[must_use]
304    pub fn changelog_path(&self, root: &Path) -> PathBuf {
305        if let Some(path) = &self.changelog {
306            return root.join(path);
307        }
308        root.join(&self.path)
309            .parent()
310            .unwrap_or(root)
311            .join("CHANGELOG.md")
312    }
313
314    /// The version driver. It is the stock or named driver with this package's
315    /// own fields over it. A lockfile follow-up is inferred when none is set.
316    ///
317    /// # Errors
318    ///
319    /// Returns an error when the merged driver is incomplete or invalid, as
320    /// described for [`DriverSpec::into_driver`]. A package whose file is
321    /// not `Cargo.toml`, `package.json`, `pyproject.toml`, `go.mod`, or
322    /// `VERSION` needs a driver of its own.
323    pub fn resolve(&self, config: &Config, root: &Path) -> Result<Driver> {
324        if self.marker {
325            return Ok(Driver::Text {
326                text: Text::Marker,
327                after: self.spec.after.clone(),
328            });
329        }
330        let inferred = self
331            .path
332            .file_name()
333            .and_then(|name| name.to_str())
334            .and_then(stock_name_for_file);
335        let driver_name = self.driver.as_deref().or(inferred);
336        let mut spec = driver_name
337            .and_then(|name| config.driver_spec(name))
338            .unwrap_or_default();
339        spec = spec.merge(self.spec.clone());
340        if spec.after.is_none() {
341            spec.after = detect::follow_up(&root.join(&self.path));
342        }
343        spec.into_driver(driver_name.unwrap_or(self.name.as_str()))
344    }
345
346    /// The version this package's file contains now, read through its driver.
347    /// Every command that reads a current version reads it here, so each
348    /// error shows the package and its file.
349    ///
350    /// # Errors
351    ///
352    /// Returns an error naming the package when its driver cannot be
353    /// resolved, its file cannot be read, or the driver finds no version in
354    /// it.
355    pub fn current(&self, config: &Config, root: &Path) -> Result<Current> {
356        let path = root.join(&self.path);
357        let context = || format!("package {}: {}", self.name, path.display());
358        let driver = self.resolve(config, root).with_context(context)?;
359        let raw = driver.source(&path).with_context(context)?;
360        let version = driver.read(&raw).with_context(context)?.trim().to_owned();
361        Ok(Current {
362            driver,
363            path,
364            raw,
365            version,
366        })
367    }
368}
369
370/// Publisher options as a package wrote them: each key with its value, not
371/// yet read by the publisher they belong to.
372pub type PublishOptions = BTreeMap<String, serde_json::Value>;
373
374/// What a package wrote under `publish`.
375#[derive(Debug, Clone, PartialEq, Eq)]
376#[non_exhaustive]
377pub enum Publish {
378    /// Options of the publisher the package resolves to. The publisher reads
379    /// them, so an option another publisher has is an error at load.
380    Options(PublishOptions),
381    /// The whole upload command, run in place of the publisher's.
382    Command(Vec<String>),
383}
384
385/// Untagged reads both shapes and then reports "matched no variant", naming a
386/// type nobody wrote. So the shape is read here and reported in the words a
387/// repo uses.
388const PUBLISH_SHAPES: &str =
389    "a mapping of publisher options, or a list that is the whole upload command";
390
391impl<'de> Deserialize<'de> for Publish {
392    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
393        deserializer.deserialize_any(PublishVisitor)
394    }
395}
396
397struct PublishVisitor;
398
399impl<'de> Visitor<'de> for PublishVisitor {
400    type Value = Publish;
401
402    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
403        write!(formatter, "{PUBLISH_SHAPES}")
404    }
405
406    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Publish, A::Error> {
407        let mut argv = Vec::new();
408        while let Some(part) = seq.next_element::<String>()? {
409            argv.push(part);
410        }
411        Ok(Publish::Command(argv))
412    }
413
414    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Publish, A::Error> {
415        let mut options = PublishOptions::new();
416        while let Some((key, value)) = map.next_entry::<String, serde_json::Value>()? {
417            options.insert(key, value);
418        }
419        Ok(Publish::Options(options))
420    }
421}
422
423/// A package's version as its file contains it now, from
424/// [`PackageSpec::current`].
425#[derive(Debug, Clone)]
426#[non_exhaustive]
427pub struct Current {
428    /// The driver that read the version and writes the next one.
429    pub driver: Driver,
430    /// The version file, joined to the repository root.
431    pub path: PathBuf,
432    /// The file's text: empty for a `VERSION` file that does not exist yet.
433    pub raw: String,
434    /// The version, trimmed.
435    pub version: String,
436}
437
438/// One machine, declared once under `runners`. The key names it; this
439/// is how GitHub finds it. Every label is required at once, so a three-label
440/// runner is one machine carrying three labels, not three machines.
441#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
442#[serde(deny_unknown_fields)]
443#[garde(context(Config))]
444#[non_exhaustive]
445pub struct Runner {
446    /// Every label at once. A machine with none cannot be found at all.
447    #[garde(custom(at_least_one("label")))]
448    pub labels: Vec<String>,
449}
450
451/// One job, declared under `ci`. The key names it; `runners` names the
452/// machines from `runners` it runs on, one check each. No `os`/`arch`/
453/// `triple`: validation runs a machine's checks, it does not cross-compile.
454#[derive(Debug, Clone, Deserialize, Default)]
455#[serde(deny_unknown_fields)]
456#[non_exhaustive]
457pub struct Job {
458    /// Names from `runners` this job runs on. Omit for one `ubuntu-26.04`
459    /// machine.
460    pub runners: Option<Vec<String>>,
461}
462
463/// Native GitHub Release tarballs, plus the recipe every target shares. Omit
464/// for libraries. Each named sub-mapping is one target.
465///
466/// A tarball contains the one `binary`, or the `files` packed from `dir`. Use
467/// `files` when a release needs more than its binary, such as a second
468/// executable, a service unit, or a licence. A target that ships other files
469/// lists its own `files`, which replace the shared list for that target.
470#[derive(Debug, Clone, Deserialize, Default, Validate)]
471#[garde(context(Config))]
472#[garde(allow_unvalidated)]
473#[non_exhaustive]
474pub struct Assets {
475    /// The binary name. Defaults to the first package's name.
476    pub bin: Option<String>,
477    /// Ran once per target before `build`. Stock rust recipe uses rustup.
478    pub prepare: Option<Vec<String>>,
479    /// How to produce the binary. Stock rust recipe is `cargo build --release`.
480    pub build: Option<Vec<String>>,
481    /// Path to the built binary, with `{bin}`, `{triple}`, `{os}`, and
482    /// `{arch}`. Omit for `target/{triple}/release/{bin}`. Unused when `dir`
483    /// and `files` specify what to pack, so it may not be set beside them.
484    #[garde(custom(binary_is_not_beside_files))]
485    pub binary: Option<String>,
486    /// The directory `files` are packed from, relative to the directory
487    /// containing `.ctl/`, with the same placeholders as `binary`. Omit, with
488    /// `files`, to pack the one `binary`.
489    #[serde(default)]
490    #[garde(custom(dir_comes_with_files), inner(custom(inside_the_repo)))]
491    pub dir: Option<PathBuf>,
492    /// Paths under `dir` packed into the tarball of every target that lists
493    /// none of its own, with the same placeholders. Each keeps its place under
494    /// `dir`. A directory is packed whole. Omit, with `dir`, to pack the one
495    /// `binary`, or when every target lists its own.
496    #[serde(default)]
497    #[garde(custom(files_come_with_dir), inner(custom(inside_the_repo)))]
498    pub files: Vec<PathBuf>,
499    /// Files written from a command's output and packed into the tarball of
500    /// every target beside the binary, such as a usage spec or a man page the
501    /// built binary prints. Omit when the tarball contains nothing generated.
502    #[serde(default)]
503    #[garde(dive, custom(generated_paths_are_sound))]
504    pub generated: Vec<Generated>,
505    /// Every remaining sub-mapping: `assets.linux-x64` and friends. A typo'd
506    /// recipe key lands here and fails as an unknown target, loudly. The
507    /// map is flattened, so garde names a target's field
508    /// `assets.targets.<id>`, though the file has no `targets` key.
509    /// [`Config::load`] declares this field to ctl-core as flattened,
510    /// so a problem names `assets.<id>` and lands on that key's line.
511    #[serde(flatten)]
512    #[garde(dive)]
513    pub targets: BTreeMap<String, AssetTarget>,
514}
515
516impl Assets {
517    /// The keys under `assets` that are settings, every other key being a
518    /// target id. A reader that takes only the target ids of an old config
519    /// leaves these out.
520    pub const SETTINGS: [&'static str; 7] = [
521        "bin",
522        "prepare",
523        "build",
524        "binary",
525        "dir",
526        "files",
527        "generated",
528    ];
529}
530
531/// One file `release asset` writes from a command's output and packs into a
532/// tarball. A host that installs the tarball then gets a file it cannot
533/// generate at install time, such as a man page, which mise installs only from
534/// a file.
535#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
536#[serde(deny_unknown_fields)]
537#[garde(context(Config))]
538#[garde(allow_unvalidated)]
539#[non_exhaustive]
540pub struct Generated {
541    /// Where the file lands under the directory the tarball is cut from, with
542    /// `{bin}`, `{id}`, `{os}`, `{arch}`, and `{triple}`. The load checks it
543    /// for each target: it stays inside the tarball, names one file, and
544    /// replaces nothing the tarball packs.
545    pub path: String,
546    /// The command whose standard output is the file's content, run without a
547    /// shell. `{binary}` is the binary the target built, or the one
548    /// `--prebuilt-self` staged, and the placeholders of `path` and
549    /// `{version}` are replaced too.
550    #[garde(custom(at_least_one("argument")))]
551    pub run: Vec<String>,
552}
553
554/// One build target: the platform it produces and the single machine that
555/// builds it. One tarball, one machine, so `runner` is not a list.
556#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Default, Validate)]
557#[serde(deny_unknown_fields)]
558#[garde(context(Config))]
559#[garde(allow_unvalidated)]
560#[non_exhaustive]
561pub struct AssetTarget {
562    /// Name from `runners` of the machine that builds this target.
563    pub runner: Option<String>,
564    /// Operating system name. Defaults from a known target id.
565    pub os: Option<String>,
566    /// CPU architecture name. Defaults from a known target id.
567    pub arch: Option<String>,
568    /// Target triple. Defaults from a known target id.
569    pub triple: Option<String>,
570    /// Ran before `build` for this target alone, in place of the shared
571    /// `assets.prepare`, with the same placeholders. Use it when one platform
572    /// needs a toolchain the others do not, such as a musl C compiler.
573    pub prepare: Option<Vec<String>>,
574    /// How to produce this target's binary, in place of the shared
575    /// `assets.build`, with the same placeholders.
576    pub build: Option<Vec<String>>,
577    /// The tarball's file name, with `{bin}`, `{version}`, `{os}`, and
578    /// `{arch}`, where `{os}` renders `macos` for `darwin`. Omit for
579    /// `{bin}_{version}_{os}_{arch}.tar.gz`. Set it when two targets share an
580    /// os and an arch, such as a glibc and a musl build, which would otherwise
581    /// render one name.
582    #[garde(inner(custom(a_tarball_name)))]
583    pub tarball: Option<String>,
584    /// The paths this target's tarball contains under `assets.dir`, in place of
585    /// `assets.files`, with the same placeholders. Use it when a platform
586    /// ships other files, such as a tool that builds only on Linux. Unset,
587    /// the target packs `assets.files`; an empty list would pack nothing.
588    #[serde(default)]
589    #[garde(
590        custom(target_files_come_with_dir),
591        inner(custom(at_least_one("file")), inner(custom(inside_the_repo)))
592    )]
593    pub files: Option<Vec<PathBuf>>,
594    /// A table copied unread into this target's `[[artifact]]` entry of the
595    /// packslip release.toml, such as `requires: { os_min: "11.0" }`. packslip
596    /// reads and validates every key in it, so a key packslip adds later needs
597    /// no verctl code. The entry's `path` is the tarball's, which verctl
598    /// writes, so the table sets none. Omit to add nothing to the entry.
599    #[serde(default)]
600    #[garde(custom(a_packslip_table))]
601    pub packslip: ArtifactTable,
602}
603
604/// The table a target's `packslip` adds to its `[[artifact]]` entry, as the
605/// TOML the release.toml carries. It is empty when the target sets none.
606///
607/// The load converts the YAML once, so the writer never converts it again
608/// and no value TOML cannot express reaches it.
609#[derive(Debug, Clone, Default)]
610pub struct ArtifactTable(toml_edit::Table);
611
612impl ArtifactTable {
613    /// Each key with its value, in key order.
614    pub fn entries(&self) -> impl Iterator<Item = (&str, &toml_edit::Item)> {
615        self.0.iter()
616    }
617
618    /// Whether the table sets `key`.
619    #[must_use]
620    pub fn contains_key(&self, key: &str) -> bool {
621        self.0.contains_key(key)
622    }
623
624    /// The value of `key`, when the table sets it.
625    #[must_use]
626    pub fn get(&self, key: &str) -> Option<&toml_edit::Item> {
627        self.0.get(key)
628    }
629}
630
631/// The TOML text of the table, one line per key.
632impl fmt::Display for ArtifactTable {
633    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
634        fmt::Display::fmt(&self.0, f)
635    }
636}
637
638/// Two tables are equal when they render the same text.
639impl PartialEq for ArtifactTable {
640    fn eq(&self, other: &Self) -> bool {
641        self.to_string() == other.to_string()
642    }
643}
644
645impl Eq for ArtifactTable {}
646
647impl<'de> Deserialize<'de> for ArtifactTable {
648    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
649        let table = serde_json::Map::<String, serde_json::Value>::deserialize(deserializer)?;
650        toml_table(&table).map(Self).map_err(de::Error::custom)
651    }
652}
653
654/// How the Release's packslip is made: the committed file that names what
655/// ships, and whether the tarballs are attested.
656///
657/// A mapping, so a repository changes one part without restating the other.
658/// The path form `packslip: <path>` is refused with the mapping to write.
659#[derive(Debug, Clone, Default, PartialEq, Eq, Validate)]
660#[garde(context(Config))]
661#[garde(allow_unvalidated)]
662#[non_exhaustive]
663pub struct Packslip {
664    /// A packslip release.toml, relative to the directory containing `.ctl/`,
665    /// that names what does not change per release: the executables and the
666    /// resources that ship beside them. [`Config::load`] checks that git tracks
667    /// the file and that it parses as a TOML table. Omit to list `assets.bin`
668    /// and no resource.
669    #[garde(inner(custom(inside_the_repo)))]
670    pub manifest: Option<PathBuf>,
671    /// How the tarballs are attested. Omit for `true`.
672    pub attest: Attest,
673    /// The public key that verifies a key-signed bundle: the line of the
674    /// `release.pub` that `packslip keygen` wrote. packslip cannot derive it
675    /// from the secret key, and the bundle carries only a hash of it. The
676    /// release needs it when it signs with a key, and keyless signing ignores
677    /// it. Omit when the release signs keyless.
678    #[garde(inner(custom(a_public_key_line)))]
679    pub pubkey: Option<String>,
680}
681
682/// A `packslip.pubkey` that has text in it.
683fn a_public_key_line(line: &str, _: &Config) -> garde::Result {
684    if line.trim().is_empty() {
685        return Err(garde::Error::new(
686            "cannot be empty — it is the line of the release.pub that `packslip keygen` wrote",
687        ));
688    }
689    Ok(())
690}
691
692/// The keys a `packslip` mapping reads, once its value is known to be one.
693#[derive(Deserialize)]
694#[serde(deny_unknown_fields)]
695struct PackslipKeys {
696    #[serde(default)]
697    manifest: Option<PathBuf>,
698    #[serde(default)]
699    attest: Attest,
700    #[serde(default)]
701    pubkey: Option<String>,
702}
703
704impl<'de> Deserialize<'de> for Packslip {
705    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
706        deserializer.deserialize_any(PackslipVisitor)
707    }
708}
709
710struct PackslipVisitor;
711
712impl<'de> Visitor<'de> for PackslipVisitor {
713    type Value = Packslip;
714
715    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
716        formatter.write_str("a mapping of `manifest`, `attest` and `pubkey`")
717    }
718
719    fn visit_str<E: de::Error>(self, v: &str) -> Result<Packslip, E> {
720        Err(E::custom(format!(
721            "packslip is a mapping now: write `packslip: {{ manifest: {v} }}`"
722        )))
723    }
724
725    fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Packslip, A::Error> {
726        let keys = PackslipKeys::deserialize(MapAccessDeserializer::new(map))?;
727        Ok(Packslip {
728            manifest: keys.manifest,
729            attest: keys.attest,
730            pubkey: keys.pubkey,
731        })
732    }
733}
734
735/// Where the tarballs' build provenance is attested, which the packslip
736/// links by digest.
737#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
738#[non_exhaustive]
739pub enum Attest {
740    /// The `publish` job attests the tarballs this run built.
741    #[default]
742    True,
743    /// Each asset job attests its own tarball as it builds it, so a
744    /// hand-written workflow whose jobs attest needs no step in `publish`.
745    Link,
746    /// Nothing is attested or linked.
747    False,
748}
749
750impl Attest {
751    /// The word a file, a flag, and a plan output write.
752    #[must_use]
753    pub const fn as_str(self) -> &'static str {
754        match self {
755            Self::True => "true",
756            Self::Link => "link",
757            Self::False => "false",
758        }
759    }
760}
761
762impl fmt::Display for Attest {
763    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
764        f.write_str(self.as_str())
765    }
766}
767
768impl FromStr for Attest {
769    type Err = String;
770
771    fn from_str(word: &str) -> Result<Self, String> {
772        match word {
773            "true" => Ok(Self::True),
774            "link" => Ok(Self::Link),
775            "false" => Ok(Self::False),
776            other => Err(format!(
777                "packslip.attest must be true, link, or false, not {other:?}"
778            )),
779        }
780    }
781}
782
783impl Serialize for Attest {
784    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
785        serializer.serialize_str(self.as_str())
786    }
787}
788
789impl<'de> Deserialize<'de> for Attest {
790    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
791        deserializer.deserialize_any(AttestVisitor)
792    }
793}
794
795struct AttestVisitor;
796
797impl Visitor<'_> for AttestVisitor {
798    type Value = Attest;
799
800    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
801        formatter.write_str("packslip.attest: true, link, or false")
802    }
803
804    fn visit_bool<E: de::Error>(self, v: bool) -> Result<Attest, E> {
805        Ok(if v { Attest::True } else { Attest::False })
806    }
807
808    fn visit_str<E: de::Error>(self, v: &str) -> Result<Attest, E> {
809        v.parse().map_err(E::custom)
810    }
811}
812
813/// Release assets built from someone else's source, at that source's version,
814/// such as a library built from a pinned upstream release. Mise can then
815/// install it as a `github:` tool. The key is the set's `{name}`. Fragments
816/// never bump it, and `release` never reads it; `status --vendored <name>`
817/// plans it, and `release asset <target> --vendored <name>` builds and uploads
818/// it.
819#[derive(Debug, Clone, Deserialize, Validate)]
820#[serde(deny_unknown_fields)]
821#[garde(context(Config))]
822#[garde(allow_unvalidated)]
823#[non_exhaustive]
824pub struct Vendored {
825    /// The upstream version, written by hand: `{version}` in every template.
826    #[garde(
827        custom(cannot_be_empty("it names the release and the archives")),
828        custom(one_plain_name)
829    )]
830    pub version: String,
831    /// Release tag, with `{name}` and `{version}`. Omit for
832    /// `{name}-{version}`.
833    #[serde(default = "Vendored::default_tag")]
834    #[garde(
835        custom(cannot_be_empty("it names the release")),
836        custom(only_placeholders(&["{name}", "{version}"]))
837    )]
838    pub tag: String,
839    /// Archive file name, with `{name}`, `{version}`, and `{id}`. Omit for
840    /// `{name}-{version}-{id}.tar.gz`.
841    #[serde(default = "Vendored::default_archive")]
842    #[garde(
843        custom(one_archive_per_target),
844        custom(only_placeholders(&["{name}", "{version}", "{id}"]))
845    )]
846    pub archive: String,
847    /// Run once per target before packing. It uses no shell, and `{name}`,
848    /// `{version}`, and `{id}` are replaced. Omit when an earlier workflow step
849    /// builds.
850    #[serde(default)]
851    pub build: Vec<String>,
852    /// The directory the files are packed from, relative to the directory
853    /// containing `.ctl/`, with the same placeholders.
854    #[garde(custom(inside_the_repo))]
855    pub dir: PathBuf,
856    /// Paths under `dir` packed into the archive, each kept at its place under
857    /// `dir`. A directory is packed whole.
858    #[garde(custom(at_least_one("file")), inner(custom(inside_the_repo)))]
859    pub files: Vec<PathBuf>,
860    /// The Release body, a file relative to the directory containing `.ctl/`.
861    /// Omit for a Release with no body.
862    #[garde(inner(custom(inside_the_repo)))]
863    pub notes: Option<PathBuf>,
864    /// One entry per platform; the key is `{id}`, such as `linux-x64`.
865    #[garde(custom(at_least_one_target), custom(every_key_is_one_plain_name), dive)]
866    pub targets: BTreeMap<String, VendoredTarget>,
867}
868
869impl Vendored {
870    fn default_tag() -> String {
871        "{name}-{version}".to_owned()
872    }
873
874    fn default_archive() -> String {
875        "{name}-{version}-{id}.tar.gz".to_owned()
876    }
877}
878
879/// One platform of a vendored set and the single machine that builds it.
880#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Validate)]
881#[serde(deny_unknown_fields)]
882#[garde(context(Config))]
883#[non_exhaustive]
884pub struct VendoredTarget {
885    /// Name from `runners` of the machine that builds this target. verctl
886    /// has no built-in vendored platform, so there is no default machine.
887    #[garde(custom(runner_is_declared))]
888    pub runner: String,
889}
890
891/// Two targets under one archive name would overwrite each other, and `tar
892/// czf` writes only a gzipped tarball.
893fn one_archive_per_target(archive: &str, config: &Config) -> garde::Result {
894    validate::one_file_name(archive, config)?;
895    if !archive.contains("{id}") {
896        return Err(garde::Error::new(
897            "must contain {id}, or every target writes the same archive",
898        ));
899    }
900    if !archive.ends_with(".tar.gz") {
901        return Err(garde::Error::new(
902            "must end in .tar.gz, the only archive verctl writes",
903        ));
904    }
905    Ok(())
906}
907
908/// A brace left after the known placeholders is a typo that would reach a tag
909/// or a file name unchanged. The tag takes no `{id}`, since every target
910/// uploads to one Release.
911fn only_placeholders(allowed: &'static [&'static str]) -> impl Fn(&str, &Config) -> garde::Result {
912    move |template, _| {
913        let rest = allowed
914            .iter()
915            .fold(template.to_owned(), |rest, placeholder| {
916                rest.replace(placeholder, "")
917            });
918        if rest.contains(['{', '}']) {
919            return Err(garde::Error::new(format!(
920                "has a '{{' or '}}' that is not {}",
921                allowed.join(", ")
922            )));
923        }
924        Ok(())
925    }
926}
927
928/// `{name}`, `{version}`, and `{id}` are substituted into `archive` and
929/// `dir` after the load checked those templates. A value containing a path
930/// separator or a parent step would therefore move the archive or the packed
931/// directory outside the repository.
932fn one_plain_name(value: &str, _: &Config) -> garde::Result {
933    if value.is_empty() || value == "." || value == ".." || value.contains(['/', '\\']) {
934        return Err(garde::Error::new(format!(
935            "{value:?} must be one plain name, with no / or \\ and not . or .."
936        )));
937    }
938    Ok(())
939}
940
941fn every_key_is_one_plain_name<V>(map: &BTreeMap<String, V>, config: &Config) -> garde::Result {
942    map.keys().try_for_each(|key| one_plain_name(key, config))
943}
944
945fn at_least_one_target(targets: &BTreeMap<String, VendoredTarget>, _: &Config) -> garde::Result {
946    if targets.is_empty() {
947        return Err(garde::Error::new("must declare at least one target"));
948    }
949    Ok(())
950}
951
952/// A target's tarball name is `{bin}`, `{version}`, `{os}`, and `{arch}` in a
953/// plain `.tar.gz` file name, the one archive `release asset` writes.
954fn a_tarball_name(template: &str, config: &Config) -> garde::Result {
955    validate::one_file_name(template, config)?;
956    only_placeholders(&["{bin}", "{version}", "{os}", "{arch}"])(template, config)?;
957    if !template.ends_with(".tar.gz") {
958        return Err(garde::Error::new(
959            "must end in .tar.gz, the only archive verctl writes",
960        ));
961    }
962    Ok(())
963}
964
965/// Two targets that render one name would overwrite each other's tarball, so
966/// the load names both. The built-in targets count: `linux-x64: {}` renders
967/// `{bin}_{version}_linux_x64.tar.gz`.
968#[expect(
969    clippy::ref_option,
970    reason = "garde passes the field as it is declared"
971)]
972fn every_tarball_is_its_own(assets: &Option<Assets>, config: &Config) -> garde::Result {
973    let Some(assets) = assets else {
974        return Ok(());
975    };
976    let Some(package) = config.packages.first() else {
977        return Ok(());
978    };
979    let bin = assets.bin.as_deref().unwrap_or(&package.name);
980    if let Some((first, second, name)) = assets::tarball_clash(assets, bin) {
981        return Err(garde::Error::new(format!(
982            "assets.{first} and assets.{second} both write {name}: set `tarball` on one of them"
983        )));
984    }
985    Ok(())
986}
987
988/// The bundle is an asset of the Release that carries the tarballs, so a
989/// `packslip` without a target to carry has no Release to sign.
990#[expect(
991    clippy::ref_option,
992    reason = "garde passes the field as it is declared"
993)]
994fn packslip_needs_assets(packslip: &Option<Packslip>, config: &Config) -> garde::Result {
995    let has_targets = config
996        .assets
997        .as_ref()
998        .is_some_and(|assets| !assets.targets.is_empty());
999    if packslip.is_some() && !has_targets {
1000        return Err(garde::Error::new(
1001            "needs at least one assets target: the bundle is an asset of the Release that carries the tarballs",
1002        ));
1003    }
1004    Ok(())
1005}
1006
1007/// The release.toml that `packslip.manifest` names, read from `path` and
1008/// parsed, with `named` as the path its errors show.
1009///
1010/// A manifest sets no `artifact`, since the path of an entry changes every
1011/// version. A target's `packslip` table replaces it.
1012///
1013/// # Errors
1014///
1015/// Returns an error when the file cannot be read, is not a TOML table, or sets
1016/// `artifact`.
1017pub fn read_packslip_manifest(path: &Path, named: &Path) -> Result<toml_edit::DocumentMut> {
1018    let text = fs::read_to_string(path)
1019        .with_context(|| format!("packslip.manifest: read {}", named.display()))?;
1020    let document = text
1021        .parse::<toml_edit::DocumentMut>()
1022        .with_context(|| format!("packslip.manifest: {} is not a TOML table", named.display()))?;
1023    ensure!(
1024        !document.contains_key("artifact"),
1025        "packslip.manifest: {} sets `artifact`, whose paths change every version: set a target's table under `assets.<id>.packslip` instead",
1026        named.display()
1027    );
1028    Ok(document)
1029}
1030
1031/// The table of a target's `packslip` reaches the release.toml unread. This
1032/// refuses only the `path` verctl writes. The table's own parse refuses a value
1033/// TOML cannot express.
1034fn a_packslip_table(table: &ArtifactTable, _: &Config) -> garde::Result {
1035    if table.contains_key("path") {
1036        return Err(garde::Error::new(
1037            "sets `packslip.path`, the tarball's own path, which verctl writes: delete it",
1038        ));
1039    }
1040    Ok(())
1041}
1042
1043/// `table` as TOML, key for key, so a target's `packslip` reaches the
1044/// release.toml the way the file wrote it.
1045///
1046/// # Errors
1047///
1048/// Returns the key and the reason when a value has no TOML form: `null`, or
1049/// an integer beyond TOML's range.
1050fn toml_table(
1051    table: &serde_json::Map<String, serde_json::Value>,
1052) -> Result<toml_edit::Table, String> {
1053    let mut converted = toml_edit::Table::new();
1054    for (key, value) in table {
1055        let value = toml_value(value).map_err(|reason| format!("{key}: {reason}"))?;
1056        converted.insert(key, toml_edit::Item::Value(value));
1057    }
1058    Ok(converted)
1059}
1060
1061fn toml_value(value: &serde_json::Value) -> Result<toml_edit::Value, String> {
1062    match value {
1063        serde_json::Value::Null => Err("null has no TOML form: delete the key".to_owned()),
1064        serde_json::Value::Bool(flag) => Ok((*flag).into()),
1065        serde_json::Value::Number(number) => match (number.as_i64(), number.as_f64()) {
1066            (Some(integer), _) => Ok(integer.into()),
1067            (None, Some(float)) if number.is_f64() => Ok(float.into()),
1068            _ => Err(format!("{number} is beyond the integers TOML supports")),
1069        },
1070        serde_json::Value::String(text) => Ok(text.as_str().into()),
1071        serde_json::Value::Array(items) => {
1072            let mut array = toml_edit::Array::new();
1073            for item in items {
1074                array.push(toml_value(item)?);
1075            }
1076            Ok(array.into())
1077        }
1078        serde_json::Value::Object(entries) => {
1079            let mut inline = toml_edit::InlineTable::new();
1080            for (key, entry) in entries {
1081                let entry = toml_value(entry).map_err(|reason| format!("{key}: {reason}"))?;
1082                inline.insert(key.as_str(), entry);
1083            }
1084            Ok(inline.into())
1085        }
1086    }
1087}
1088
1089/// Every `assets.generated` path, expanded for each target, stays inside the
1090/// tarball and names a file nothing else in it names.
1091fn generated_paths_are_sound(_: &[Generated], config: &Config) -> garde::Result {
1092    let Some(assets) = &config.assets else {
1093        return Ok(());
1094    };
1095    let Some(package) = config.packages.first() else {
1096        return Ok(());
1097    };
1098    let bin = assets.bin.as_deref().unwrap_or(&package.name);
1099    assets::generated_problem(assets, bin)
1100        .map_or_else(|| Ok(()), |problem| Err(garde::Error::new(problem)))
1101}
1102
1103/// `dir` without `files` would pack nothing for a target that lists none of
1104/// its own, so `dir` comes with the shared `files` or a list on every target.
1105#[expect(
1106    clippy::ref_option,
1107    reason = "garde passes the field as it is declared"
1108)]
1109fn dir_comes_with_files(dir: &Option<PathBuf>, config: &Config) -> garde::Result {
1110    let packs_files = config.assets.as_ref().is_some_and(|assets| {
1111        !assets.files.is_empty()
1112            || (!assets.targets.is_empty()
1113                && assets.targets.values().all(|target| target.files.is_some()))
1114    });
1115    if dir.is_some() && !packs_files {
1116        return Err(garde::Error::new(
1117            "must come with files, the paths packed from it, or a files list on every target",
1118        ));
1119    }
1120    Ok(())
1121}
1122
1123/// A target's `files` are packed from `assets.dir`, so they need it.
1124#[expect(
1125    clippy::ref_option,
1126    reason = "garde passes the field as it is declared"
1127)]
1128fn target_files_come_with_dir(files: &Option<Vec<PathBuf>>, config: &Config) -> garde::Result {
1129    let has_dir = config
1130        .assets
1131        .as_ref()
1132        .is_some_and(|assets| assets.dir.is_some());
1133    if files.is_some() && !has_dir {
1134        return Err(garde::Error::new(
1135            "must come with assets.dir, the directory they are packed from",
1136        ));
1137    }
1138    Ok(())
1139}
1140
1141/// `files` without `dir` have no place to be packed from.
1142fn files_come_with_dir(files: &[PathBuf], config: &Config) -> garde::Result {
1143    let has_dir = config
1144        .assets
1145        .as_ref()
1146        .is_some_and(|assets| assets.dir.is_some());
1147    if !files.is_empty() && !has_dir {
1148        return Err(garde::Error::new(
1149            "must come with dir, the directory they are packed from",
1150        ));
1151    }
1152    Ok(())
1153}
1154
1155/// A `binary` beside `dir` and `files`, shared or on a target, would never
1156/// be read, and a reader would take it for what the tarball contains. The
1157/// message shows the first target whose own `files` conflict, so a config
1158/// with several targets points at one list.
1159#[expect(
1160    clippy::ref_option,
1161    reason = "garde passes the field as it is declared"
1162)]
1163fn binary_is_not_beside_files(binary: &Option<String>, config: &Config) -> garde::Result {
1164    let (Some(_), Some(assets)) = (binary, config.assets.as_ref()) else {
1165        return Ok(());
1166    };
1167    if let Some(id) = assets
1168        .targets
1169        .iter()
1170        .find_map(|(id, target)| target.files.is_some().then_some(id))
1171    {
1172        return Err(garde::Error::new(format!(
1173            "must be omitted when assets.{id}.files lists what the tarball contains; list the binary in files",
1174        )));
1175    }
1176    if assets.dir.is_some() || !assets.files.is_empty() {
1177        return Err(garde::Error::new(
1178            "must be omitted when dir and files list what the tarball contains; list the binary in files",
1179        ));
1180    }
1181    Ok(())
1182}
1183
1184fn runner_is_declared(runner: &str, config: &Config) -> garde::Result {
1185    if config.runners.contains_key(runner) {
1186        return Ok(());
1187    }
1188    let declared = config.runners.keys().cloned().collect::<Vec<_>>();
1189    Err(garde::Error::new(format!(
1190        "{runner:?} is not declared in runners ({})",
1191        if declared.is_empty() {
1192            "none declared".to_owned()
1193        } else {
1194            format!("declared: {}", declared.join(", "))
1195        }
1196    )))
1197}
1198
1199/// A config that releases no package and vendors nothing has nothing to do.
1200fn something_to_release(packages: &[PackageSpec], config: &Config) -> garde::Result {
1201    if packages.is_empty() && config.vendored.is_empty() {
1202        return Err(garde::Error::new(
1203            "must declare at least one package, or a vendored set",
1204        ));
1205    }
1206    Ok(())
1207}
1208
1209/// The whole file, and the context every rule in it is checked against. A
1210/// pattern is only unused, and an id only unknown, relative to the rest of the
1211/// config. `Config::parse` reads the shape with serde and then validates it
1212/// once, here, so a complaint names the field that has to change.
1213///
1214/// A section verctl does not know stops the load instead of being dropped.
1215/// Ignoring `pattern:` for `patterns:` would ship a release with the pins it
1216/// declares never rewritten.
1217#[derive(Debug, Clone, Deserialize, Default, Validate)]
1218#[serde(deny_unknown_fields)]
1219#[garde(context(Self as config))]
1220#[garde(allow_unvalidated)]
1221#[non_exhaustive]
1222pub struct Config {
1223    /// Custom drivers by name. A stock name (`cargo`, `npm`, `pyproject`,
1224    /// `go`, `version`) is overridden field by field.
1225    #[serde(default)]
1226    pub drivers: BTreeMap<String, DriverSpec>,
1227    /// What this repo releases. Omit only when the repo declares `vendored`;
1228    /// a config with neither has nothing to do.
1229    #[serde(default)]
1230    #[garde(
1231        custom(something_to_release),
1232        custom(no_unknown_package_keys),
1233        custom(release_only_names_no_registry),
1234        custom(publish_options_fit_the_publisher),
1235        custom(python_names_its_publisher),
1236        custom(a_marker_names_no_driver),
1237        custom(a_prerelease_is_lowercase_letters),
1238        custom(package_owners_are_logins)
1239    )]
1240    pub packages: Vec<PackageSpec>,
1241    /// The crates.io logins every package's crates must list as owners, which
1242    /// `check registry` proves. A package's own `owners` replaces it. When
1243    /// omitted here and on a package, that package has no owner proof.
1244    #[serde(default)]
1245    #[garde(inner(custom(owners_are_logins)))]
1246    pub owners: Option<Vec<String>>,
1247    /// The file under `.github/workflows/` whose run publishes, which a
1248    /// crates.io trusted publisher entry must name for `check trust` to pass.
1249    /// crates.io matches the entry against the calling workflow that the OIDC
1250    /// token's `workflow_ref` claim names
1251    /// (`crates_io_trustpub/src/github/workflows.rs`), so a reusable workflow
1252    /// it calls does not count. When omitted, it is `release.yml`, the caller
1253    /// file the template renders.
1254    #[serde(default = "Config::default_release_workflow")]
1255    #[garde(custom(a_workflow_file_name))]
1256    pub release_workflow: String,
1257    /// The checks `release` and `release --dry-run` run before the first
1258    /// write, from `registry` and `trust`. Only registry state can change
1259    /// between the merge and the release, so the checks that prove anything
1260    /// else run before the merge and are not listed here. `trust` runs only
1261    /// when `VERCTL_OWNER_TOKEN` contains an owner's token, and is reported as
1262    /// skipped otherwise. When omitted, it is `[registry, trust]`; `[]` runs
1263    /// no check.
1264    #[serde(default = "ReleaseCheck::default_list")]
1265    #[garde(custom(each_release_check_once))]
1266    pub release_checks: Vec<ReleaseCheck>,
1267    /// Publish recipes by name, for a package's `publisher` to select.
1268    #[serde(default)]
1269    #[garde(custom(none_is_not_a_publisher))]
1270    pub publishers: BTreeMap<String, PublisherSpec>,
1271    /// Machines, declared once and named. Entirely repo-owned: verctl ships no
1272    /// built-in names.
1273    #[serde(default)]
1274    #[garde(dive)]
1275    pub runners: BTreeMap<String, Runner>,
1276    /// Release tarball recipe. Omit for libraries.
1277    #[serde(default)]
1278    #[garde(dive, custom(every_tarball_is_its_own))]
1279    pub assets: Option<Assets>,
1280    /// The packslip the Release carries. When it is set, the Release that
1281    /// carries the tarballs also carries `packslip.sigstore.json`, signed by
1282    /// the release workflow. `{}` signs a packslip that lists `assets.bin`
1283    /// and attests the tarballs. Omit to publish no packslip.
1284    #[serde(default)]
1285    #[garde(dive, custom(packslip_needs_assets))]
1286    pub packslip: Option<Packslip>,
1287    /// Asset sets built from someone else's source at its own version, by
1288    /// name. Omit when the repo vendors nothing.
1289    #[serde(default)]
1290    #[garde(custom(every_key_is_one_plain_name), dive)]
1291    pub vendored: BTreeMap<String, Vendored>,
1292    /// PR and push validation. Empty means one `verify` on `ubuntu-26.04`.
1293    #[serde(default)]
1294    pub ci: BTreeMap<String, Job>,
1295    /// Work done after the version bumps.
1296    #[serde(default)]
1297    #[garde(custom(no_version_label))]
1298    pub prepare: Prepare,
1299    /// The Version PR's title and commit message. Omit for
1300    /// `chore(release): version packages` as both.
1301    #[serde(default)]
1302    pub proposal: Proposal,
1303    /// Whose names changelog entries never credit. Omit to list no one.
1304    #[serde(default)]
1305    pub changelog: Changelog,
1306    /// Where served-file templates live. Omit for the convention.
1307    #[serde(default)]
1308    #[garde(dive)]
1309    pub templates: Templates,
1310    /// How release tags are named. Omit for `v{version}`: one tag when every
1311    /// released package shares a version. Put `{name}` in the template for one
1312    /// tag (and one Release) per package.
1313    #[serde(default)]
1314    #[garde(dive)]
1315    pub tags: Tags,
1316    /// Version spellings, named once and listed by the files that carry them,
1317    /// so a spelling three files share is written once.
1318    #[serde(default)]
1319    #[garde(custom(every_pattern_says_where_the_version_goes))]
1320    #[garde(custom(every_pattern_bounds_the_version))]
1321    #[garde(custom(every_pattern_is_listed))]
1322    pub patterns: BTreeMap<String, PinPattern>,
1323    /// Collocated tool pins rewritten when `package` is bumped.
1324    #[serde(default)]
1325    #[garde(dive)]
1326    pub pins: Vec<Pin>,
1327}
1328
1329/// Where the version goes, said once: no placeholder is a spelling that tracks
1330/// nothing, two is a spelling with no single version to put anywhere.
1331fn every_pattern_says_where_the_version_goes(
1332    patterns: &BTreeMap<String, PinPattern>,
1333    _: &Config,
1334) -> garde::Result {
1335    for (id, pattern) in patterns {
1336        let found = pattern.r#match.matches(PLACEHOLDER).count();
1337        if found != 1 {
1338            return Err(garde::Error::new(format!(
1339                "{id}: match says {PLACEHOLDER} {found} times, and must say it once"
1340            )));
1341        }
1342    }
1343    Ok(())
1344}
1345
1346/// Where the version starts and ends, as the pattern declares it.
1347/// `{version}` is a version verctl writes: digits and dots, then an optional
1348/// candidate prerelease `-<tag>.<count>`. Without literal text on each side
1349/// that a version cannot contain, the pattern could end a version early or
1350/// start it late.
1351///
1352/// For example, `v{version}.5x` reads `v1.2.3.5x` as 1.2.3 and keeps `.5x`
1353/// after the new version. The file cannot settle it, because
1354/// `download/v{version}-linux` against `download/v1.2.3-linux-x64.tar.gz` is a
1355/// correct pin of 1.2.3.
1356fn every_pattern_bounds_the_version(
1357    patterns: &BTreeMap<String, PinPattern>,
1358    _: &Config,
1359) -> garde::Result {
1360    for (id, pattern) in patterns {
1361        let Some((before, after)) = pattern.r#match.split_once(PLACEHOLDER) else {
1362            continue;
1363        };
1364        if after.contains(PLACEHOLDER) {
1365            continue;
1366        }
1367        if let Some(problem) = unbounded(before, after, pattern) {
1368            return Err(garde::Error::new(format!("{id}: {problem}")));
1369        }
1370    }
1371    Ok(())
1372}
1373
1374/// What leaves one side of the placeholder open, if anything does.
1375///
1376/// A side's literal is the text between `{version}` and the pattern's edge on
1377/// that side. A version and its prerelease or build contain only digits, `.`,
1378/// `-`, and `+`. So the side is bounded when its literal contains some other
1379/// character. Under `whole_line` the line start or end bounds a side whose
1380/// literal is empty.
1381///
1382/// The character next to `{version}` also matters. A digit there, or a `.`
1383/// with a digit beyond it, lets the regex end a version early or start it
1384/// late. `v{version}.5x` reads `v1.2.3.5x` as 1.2.3, so that side is open.
1385fn unbounded(before: &str, after: &str, pattern: &PinPattern) -> Option<String> {
1386    let sides = [
1387        (
1388            before,
1389            before.chars().rev().collect::<String>(),
1390            "before",
1391            "starts",
1392        ),
1393        (after, after.to_owned(), "after", "ends"),
1394    ];
1395    for (text, outward, side, edge) in sides {
1396        if text.is_empty() {
1397            if pattern.whole_line {
1398                continue;
1399            }
1400            return Some(format!(
1401                "nothing {side} {PLACEHOLDER} marks where the version {edge}: add the text {side} it to match, or set whole_line: true"
1402            ));
1403        }
1404        if text
1405            .chars()
1406            .all(|next| matches!(next, '0'..='9' | '.' | '-' | '+'))
1407        {
1408            return Some(format!(
1409                "{text:?} {side} {PLACEHOLDER} contains only digits, '.', '-', and '+', which a version can continue into: add more of the text {side} it to match"
1410            ));
1411        }
1412        let mut nearest = outward.chars();
1413        if matches!(
1414            (nearest.next(), nearest.next()),
1415            (Some('0'..='9'), _) | (Some('.'), Some('0'..='9'))
1416        ) {
1417            return Some(format!(
1418                "{text:?} {side} {PLACEHOLDER} puts a digit, or a '.' and a digit, next to the version, so a longer version would match only in part: put a character other than a digit or '.' next to {PLACEHOLDER}"
1419            ));
1420        }
1421    }
1422    None
1423}
1424
1425/// A declared pattern nothing lists is dead configuration instead of a spare.
1426/// It reads like a tracked spelling while no file is checked against it.
1427fn every_pattern_is_listed(
1428    patterns: &BTreeMap<String, PinPattern>,
1429    config: &Config,
1430) -> garde::Result {
1431    let listed: BTreeSet<&str> = config
1432        .pins
1433        .iter()
1434        .flat_map(|pin| pin.pattern_ids.iter().map(String::as_str))
1435        .collect();
1436    for id in patterns.keys() {
1437        if !listed.contains(id.as_str()) {
1438            return Err(garde::Error::new(format!(
1439                "{id:?} is declared and no pin lists it"
1440            )));
1441        }
1442    }
1443    Ok(())
1444}
1445
1446/// A file that serves a package version and must track it.
1447#[derive(Debug, Clone, Deserialize, Validate)]
1448#[serde(deny_unknown_fields)]
1449#[garde(context(Config as config))]
1450#[garde(allow_unvalidated)]
1451#[non_exhaustive]
1452pub struct Pin {
1453    /// The file, relative to the directory containing `.ctl/`.
1454    #[garde(custom(inside_the_repo))]
1455    pub file: PathBuf,
1456    /// A mise `[tools]` entry, in a file that parses as TOML. Its own
1457    /// `?ref=v…` includes move with it.
1458    pub tool: Option<String>,
1459    /// `patterns` ids this file lists, so the file a spelling belongs to is
1460    /// written down instead of implied by table placement.
1461    #[serde(default, rename = "patterns")]
1462    #[garde(
1463        custom(each_id_is_declared),
1464        custom(no_id_is_listed_twice),
1465        custom(something_to_rewrite(self.tool.as_deref()))
1466    )]
1467    pub pattern_ids: Vec<String>,
1468    /// The patterns those ids name, filled in by `Config::load`, the only way
1469    /// to build a pin that rewrites anything.
1470    #[serde(skip)]
1471    pub patterns: Vec<PinPattern>,
1472    /// The package whose version this file serves.
1473    pub package: String,
1474}
1475
1476/// A name is only a name if something declares it. `none` names release-only
1477/// packages. A `publishers.none` recipe could never run, because every package
1478/// that names it uploads nothing.
1479fn none_is_not_a_publisher(
1480    publishers: &BTreeMap<String, PublisherSpec>,
1481    _: &Config,
1482) -> garde::Result {
1483    if publishers.contains_key(RELEASE_ONLY) {
1484        return Err(garde::Error::new(
1485            "publishers.none is reserved for release-only packages; rename that publisher",
1486        ));
1487    }
1488    Ok(())
1489}
1490
1491/// A key under a package that nothing reads. Ignoring `publsher: none` would
1492/// publish a package to its registry that the file meant to release on GitHub
1493/// only.
1494fn no_unknown_package_keys(packages: &[PackageSpec], _: &Config) -> garde::Result {
1495    for package in packages {
1496        if !package.unknown.is_empty() {
1497            let keys: Vec<&str> = package.unknown.keys().map(String::as_str).collect();
1498            return Err(garde::Error::new(format!(
1499                "package {:?} has {} verctl does not read: {}; check the spelling",
1500                package.name,
1501                if keys.len() == 1 { "a key" } else { "keys" },
1502                keys.join(", ")
1503            )));
1504        }
1505    }
1506    Ok(())
1507}
1508
1509/// The problem with an `owners` list, if it has one: a list with no login
1510/// proves nothing, and a login listed twice is a typo or a stale edit.
1511fn owners_problem(owners: &[String]) -> Option<String> {
1512    if owners.is_empty() {
1513        return Some(
1514            "must list at least one crates.io login; omit the key to expect no owners".to_owned(),
1515        );
1516    }
1517    let mut seen = BTreeSet::new();
1518    owners
1519        .iter()
1520        .find(|login| !seen.insert(login.as_str()))
1521        .map(|login| format!("lists {login:?} twice; remove one"))
1522}
1523
1524/// The top-level `owners`, when set.
1525fn owners_are_logins(owners: &[String], _: &Config) -> garde::Result {
1526    owners_problem(owners).map_or_else(|| Ok(()), |problem| Err(garde::Error::new(problem)))
1527}
1528
1529/// Each package's own `owners`, named as `packages[<name>].owners`, because
1530/// the field is on one entry of the list.
1531fn package_owners_are_logins(packages: &[PackageSpec], _: &Config) -> garde::Result {
1532    for package in packages {
1533        if let Some(problem) = package.owners.as_deref().and_then(owners_problem) {
1534            return Err(garde::Error::new(format!(
1535                "packages[{name}].owners {problem}",
1536                name = package.name
1537            )));
1538        }
1539    }
1540    Ok(())
1541}
1542
1543/// A check `release` runs before its first write, as `release_checks` names
1544/// it.
1545///
1546/// Not `#[non_exhaustive]`: the release proof matches every check, so a new
1547/// one fails its build until it runs.
1548#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
1549#[serde(rename_all = "lowercase", try_from = "String")]
1550pub enum ReleaseCheck {
1551    /// `check registry`: each crates.io crate exists and lists its owners.
1552    Registry,
1553    /// `check trust`: each crates.io crate has a trusted publisher naming
1554    /// the repository and `release_workflow`.
1555    Trust,
1556}
1557
1558impl ReleaseCheck {
1559    /// Every check, in the order the proof runs them.
1560    pub const ALL: [Self; 2] = [Self::Registry, Self::Trust];
1561
1562    /// The name `.ctl/ver.yaml` and the report use.
1563    #[must_use]
1564    pub const fn name(self) -> &'static str {
1565        match self {
1566            Self::Registry => "registry",
1567            Self::Trust => "trust",
1568        }
1569    }
1570
1571    /// The `release_checks` a file that sets none gets: every check.
1572    fn default_list() -> Vec<Self> {
1573        Self::ALL.to_vec()
1574    }
1575}
1576
1577/// A name outside the set fails here, naming the field and the names it
1578/// takes. serde's own wording names neither, because a parse problem carries
1579/// no field path.
1580impl TryFrom<String> for ReleaseCheck {
1581    type Error = String;
1582
1583    fn try_from(name: String) -> Result<Self, Self::Error> {
1584        Self::ALL
1585            .into_iter()
1586            .find(|check| check.name() == name)
1587            .ok_or_else(|| {
1588                format!(
1589                    "release_checks lists {name:?}, which release does not run; use registry or trust, the checks that can change after the merge"
1590                )
1591            })
1592    }
1593}
1594
1595/// `release_checks` names each check once: a repeated name is a typo or a
1596/// stale edit.
1597fn each_release_check_once(checks: &[ReleaseCheck], _: &Config) -> garde::Result {
1598    let mut seen = BTreeSet::new();
1599    checks
1600        .iter()
1601        .find(|check| !seen.insert(check.name()))
1602        .map_or_else(
1603            || Ok(()),
1604            |check| {
1605                Err(garde::Error::new(format!(
1606                    "lists {:?} twice; remove one",
1607                    check.name()
1608                )))
1609            },
1610        )
1611}
1612
1613/// `release_workflow` is the file name crates.io compares, so a path or a
1614/// file that is not a workflow could never match an entry.
1615fn a_workflow_file_name(name: &str, config: &Config) -> garde::Result {
1616    if validate::one_file_name(name, config).is_err() {
1617        return Err(garde::Error::new(
1618            "must be a file name under .github/workflows/, such as release.yml, with no directory",
1619        ));
1620    }
1621    if !Path::new(name)
1622        .extension()
1623        .is_some_and(|extension| extension == "yml" || extension == "yaml")
1624    {
1625        return Err(garde::Error::new(
1626            "must name a workflow file, ending in .yml or .yaml",
1627        ));
1628    }
1629    Ok(())
1630}
1631
1632/// A candidate tag that is not lowercase ASCII letters. `rc1` would make the
1633/// version `0.8.0-rc1.1`, which counts on no further, and `rc.1` would hide
1634/// the count inside the tag.
1635fn a_prerelease_is_lowercase_letters(packages: &[PackageSpec], _: &Config) -> garde::Result {
1636    for package in packages {
1637        if let Some(tag) = package.prerelease.as_ref().filter(|tag| !tag.is_valid()) {
1638            return Err(garde::Error::new(format!(
1639                "package {:?} has prerelease {:?}, which is not a tag; {}",
1640                package.name,
1641                tag.as_str(),
1642                Prerelease::RULE
1643            )));
1644        }
1645    }
1646    Ok(())
1647}
1648
1649/// `publisher: none`, declared or inferred from its version source, uploads
1650/// nothing. A registry or an upload command on the same package would be a
1651/// setting nothing reads.
1652fn release_only_names_no_registry(packages: &[PackageSpec], config: &Config) -> garde::Result {
1653    for package in packages {
1654        if publisher::publisher_name(config, package) == RELEASE_ONLY
1655            && (package.registry.is_some() || package.publish.is_some())
1656        {
1657            return Err(garde::Error::new(format!(
1658                "package {:?} has publisher: none, which uploads to no registry; remove its registry and publish",
1659                package.name
1660            )));
1661        }
1662    }
1663    Ok(())
1664}
1665
1666/// An option belongs to one publisher. One the package's publisher does not
1667/// have would be a setting nothing reads, so it fails here, in that
1668/// publisher's words.
1669fn publish_options_fit_the_publisher(packages: &[PackageSpec], config: &Config) -> garde::Result {
1670    for package in packages {
1671        if let Err(problem) = publisher::check_options(config, package) {
1672            return Err(garde::Error::new(problem));
1673        }
1674    }
1675    Ok(())
1676}
1677
1678/// `marker: true` shows where the version is, so a `driver` or driver fields
1679/// beside it would be a second answer nothing reads. `after` is the
1680/// exception: it is what runs after the bump, not where the version is.
1681fn a_marker_names_no_driver(packages: &[PackageSpec], _: &Config) -> garde::Result {
1682    for package in packages {
1683        let spec = &package.spec;
1684        if package.marker
1685            && (package.driver.is_some()
1686                || spec.format.is_some()
1687                || spec.keys.is_some()
1688                || spec.read.is_some()
1689                || spec.write.is_some())
1690        {
1691            return Err(garde::Error::new(format!(
1692                "package {:?} has marker: true, which reads the version from its marker line; remove its driver, format, keys, read, and write",
1693                package.name
1694            )));
1695        }
1696    }
1697    Ok(())
1698}
1699
1700/// verctl has no stock Python publisher, so a `pyproject.toml` package that
1701/// names none would release a tag while nothing reached the Python Package
1702/// Index. It names one, through `publisher`, `publish`, or a `publishers`
1703/// entry under its own name, or says `publisher: none` to release on GitHub
1704/// only.
1705fn python_names_its_publisher(packages: &[PackageSpec], config: &Config) -> garde::Result {
1706    for package in packages {
1707        if package.path.file_name() == Some(OsStr::new("pyproject.toml"))
1708            && package.publisher.is_none()
1709            && package.publish_command().is_none()
1710            && !config.publishers.contains_key(&package.name)
1711        {
1712            return Err(garde::Error::new(format!(
1713                "package {:?} needs a publisher: verctl has no stock Python publisher; set publisher to a publishers entry, or to none to release on GitHub only",
1714                package.name
1715            )));
1716        }
1717    }
1718    Ok(())
1719}
1720
1721fn each_id_is_declared(ids: &[String], config: &Config) -> garde::Result {
1722    for id in ids {
1723        if !config.patterns.contains_key(id) {
1724            return Err(garde::Error::new(format!("no patterns.{id}")));
1725        }
1726    }
1727    Ok(())
1728}
1729
1730/// Listing a spelling twice does not set a count: arity belongs to the pattern.
1731fn no_id_is_listed_twice(ids: &[String], _: &Config) -> garde::Result {
1732    let mut seen = BTreeSet::new();
1733    for id in ids {
1734        if !seen.insert(id.as_str()) {
1735            return Err(garde::Error::new(format!("lists {id:?} twice")));
1736        }
1737    }
1738    Ok(())
1739}
1740
1741/// A pin with neither a `tool` nor a pattern names a file and asks for nothing.
1742fn something_to_rewrite(tool: Option<&str>) -> impl Fn(&[String], &Config) -> garde::Result + '_ {
1743    move |ids, _| {
1744        if tool.is_some() || !ids.is_empty() {
1745            return Ok(());
1746        }
1747        Err(garde::Error::new("needs a tool or a pattern to rewrite"))
1748    }
1749}
1750
1751/// The directory every ctl CLI shares, so a repo root gains one entry however
1752/// many of them it uses. verctl owns the files it names here and nothing else.
1753pub const DIR: &str = ".ctl";
1754
1755/// verctl's declarations, named after the task an operator runs (`mise run
1756/// ver`) rather than after the crate that reads them.
1757pub const FILE: &str = ".ctl/ver.yaml";
1758
1759/// The directory a config governs: what every `path` in it is relative to.
1760///
1761/// Declarations sit in `<root>/.ctl/`, so the directory containing the file is
1762/// a level too deep and its parent is the root. `-c crates/foo/.ctl/ver.yaml`
1763/// therefore still governs `crates/foo`. A file outside a `.ctl` directory is
1764/// read where it sits, which is what an ad-hoc `-c` requires.
1765#[must_use]
1766pub fn root_of(config: &Path) -> PathBuf {
1767    let dir = here(config.parent());
1768    if dir.file_name() == Some(OsStr::new(DIR)) {
1769        return here(dir.parent()).to_path_buf();
1770    }
1771    dir.to_path_buf()
1772}
1773
1774fn here(path: Option<&Path>) -> &Path {
1775    path.filter(|path| !path.as_os_str().is_empty())
1776        .unwrap_or_else(|| Path::new("."))
1777}
1778
1779/// What a `pins` pattern puts where the version goes.
1780pub const PLACEHOLDER: &str = "{version}";
1781
1782/// What a tag template puts where the package name goes.
1783pub const NAME_PLACEHOLDER: &str = "{name}";
1784
1785/// How release tags are named. The arity falls out of the template: no
1786/// `{name}` means one tag for the release; `{name}` means one tag per package.
1787#[derive(Debug, Clone, Deserialize, Validate)]
1788#[serde(deny_unknown_fields)]
1789#[garde(context(Config))]
1790#[non_exhaustive]
1791pub struct Tags {
1792    /// Literal text with `{version}` and optionally `{name}`. Defaults to
1793    /// `v{version}`, so a repo that writes nothing keeps today's behaviour.
1794    #[serde(default = "Tags::default_template")]
1795    #[garde(
1796        custom(cannot_be_empty(
1797            "it is the shape of every release tag, like \"v{version}\" or \"{name}@{version}\""
1798        )),
1799        custom(tag_template_placeholders)
1800    )]
1801    pub template: String,
1802}
1803
1804impl Tags {
1805    fn default_template() -> String {
1806        format!("v{PLACEHOLDER}")
1807    }
1808
1809    /// Whether the template names the package, so each package gets its own
1810    /// tag.
1811    #[must_use]
1812    pub fn uses_name(&self) -> bool {
1813        self.template.contains(NAME_PLACEHOLDER)
1814    }
1815
1816    /// Substitute `{version}` and, when given, `{name}`. The load already
1817    /// proved those are the only braces, so a leftover `{` here is a bug.
1818    ///
1819    /// # Errors
1820    ///
1821    /// Returns an error when the template needs `{name}` and `name` is `None`,
1822    /// or when braces remain after substitution.
1823    pub fn render(&self, version: &str, name: Option<&str>) -> Result<String> {
1824        let mut out = self.template.replace(PLACEHOLDER, version);
1825        if let Some(name) = name {
1826            out = out.replace(NAME_PLACEHOLDER, name);
1827        } else if out.contains(NAME_PLACEHOLDER) {
1828            bail!(
1829                "tags.template {:?} needs {NAME_PLACEHOLDER} but no package name was given",
1830                self.template
1831            );
1832        }
1833        ensure!(
1834            !out.contains('{') && !out.contains('}'),
1835            "tags.template {:?} still has braces after substitution",
1836            self.template
1837        );
1838        Ok(out)
1839    }
1840}
1841
1842impl Default for Tags {
1843    fn default() -> Self {
1844        Self {
1845            template: Self::default_template(),
1846        }
1847    }
1848}
1849
1850/// A tag template may only say `{version}` and `{name}`, must say at least one
1851/// of them, and must say `{version}`. A name with no version cannot date a
1852/// release.
1853fn tag_template_placeholders(template: &str, _: &Config) -> garde::Result {
1854    let mut saw_version = false;
1855    let mut saw_name = false;
1856    let mut rest = template;
1857    while let Some(start) = rest.find('{') {
1858        let after = &rest[start + 1..];
1859        let Some(end) = after.find('}') else {
1860            return Err(garde::Error::new("has an opening '{' with no closing '}'"));
1861        };
1862        let name = &after[..end];
1863        match name {
1864            "version" => saw_version = true,
1865            "name" => saw_name = true,
1866            _ => {
1867                return Err(garde::Error::new(format!(
1868                    "names {{{name}}}, and the only placeholders are {PLACEHOLDER} and {NAME_PLACEHOLDER}"
1869                )));
1870            }
1871        }
1872        rest = &after[end + 1..];
1873    }
1874    if !saw_version && !saw_name {
1875        return Err(garde::Error::new(format!(
1876            "has no placeholder — put {PLACEHOLDER} where the version goes"
1877        )));
1878    }
1879    if !saw_version {
1880        return Err(garde::Error::new(format!(
1881            "must say {PLACEHOLDER} — a tag with only {NAME_PLACEHOLDER} cannot date a release"
1882        )));
1883    }
1884    let leftover = template
1885        .replace(PLACEHOLDER, "")
1886        .replace(NAME_PLACEHOLDER, "");
1887    if leftover.contains('{') || leftover.contains('}') {
1888        return Err(garde::Error::new(format!(
1889            "has a '{{' or '}}' that is not {PLACEHOLDER} or {NAME_PLACEHOLDER}"
1890        )));
1891    }
1892    let _ = saw_name;
1893    Ok(())
1894}
1895
1896/// Where the templates for served files live, and how they are marked. The
1897/// defaults are the whole convention: a repo that follows it writes nothing.
1898#[derive(Debug, Clone, Deserialize, Validate)]
1899#[serde(deny_unknown_fields)]
1900#[garde(context(Config))]
1901#[non_exhaustive]
1902pub struct Templates {
1903    /// The directory every template lives in, flat. Each one declares its own
1904    /// target, so nothing sits beside the file it generates.
1905    #[serde(default = "Templates::default_source")]
1906    #[garde(custom(inside_the_repo))]
1907    pub source: PathBuf,
1908    /// What marks a source file as a template of its target.
1909    #[serde(default = "Templates::default_suffix")]
1910    #[garde(custom(cannot_be_empty(
1911        "it is what marks a file in the source tree as a template, like \".jinja\""
1912    )))]
1913    pub suffix: String,
1914}
1915
1916impl Templates {
1917    fn default_source() -> PathBuf {
1918        Path::new(DIR).join("templates")
1919    }
1920
1921    fn default_suffix() -> String {
1922        ".jinja".to_owned()
1923    }
1924}
1925
1926impl Default for Templates {
1927    fn default() -> Self {
1928        Self {
1929            source: Self::default_source(),
1930            suffix: Self::default_suffix(),
1931        }
1932    }
1933}
1934
1935/// One version spelling in a file, and how often the file may say it.
1936#[derive(Debug, Clone, Deserialize)]
1937#[serde(deny_unknown_fields)]
1938#[non_exhaustive]
1939pub struct PinPattern {
1940    /// The text around a version, `{version}` where the version is. Literal
1941    /// text instead of a regex, so nothing about the file's format is
1942    /// assumed. Exactly one placeholder, checked over `patterns` so the
1943    /// complaint names the id.
1944    ///
1945    /// A side is bounded when the text between `{version}` and the pattern's
1946    /// edge contains a character that is not a digit, `.`, `-`, or `+`. The
1947    /// character next to `{version}` must not be a digit, or a `.` with a
1948    /// digit beyond it.
1949    ///
1950    /// Under `whole_line` the line start or end bounds a side whose literal is
1951    /// empty. The load refuses a pattern with an open side.
1952    pub r#match: String,
1953    /// How often the file must say it. A pin that lost its only mention, or
1954    /// drifted to one nobody declared, fails the release rather than serving
1955    /// a stale version.
1956    #[serde(default)]
1957    pub occurrences: Occurrences,
1958    /// Whether the match is a whole line rather than text inside one.
1959    ///
1960    /// When unset, a pattern matches anywhere, which is what an inline
1961    /// spelling needs: `github:org/tool@1.2.3` is inside a longer line.
1962    ///
1963    /// A pattern that owns its line sets this flag instead of anchoring on
1964    /// whatever text happens to be next to it. The alternative is spelling the
1965    /// neighbour into `match`, which then breaks when the neighbour moves.
1966    ///
1967    /// The flag also makes a partial version fail instead of rewriting,
1968    /// because a line ending in `0.1.1_local` does not end where the version
1969    /// does.
1970    #[serde(default)]
1971    pub whole_line: bool,
1972}
1973
1974/// How many times a pattern must match. A count is not always the useful
1975/// shape. A document whose examples come and go needs "one or more".
1976/// Retiring a spelling needs "none".
1977#[derive(Debug, Clone, Copy, Default)]
1978#[non_exhaustive]
1979pub enum Occurrences {
1980    /// Exactly one. What a pin normally is, so it is the default.
1981    #[default]
1982    Once,
1983    /// One or more, however many. For a file whose mentions grow and shrink
1984    /// on their own, where only "still tracked" is worth asserting.
1985    Many,
1986    /// None. A spelling that must stay gone, so its return fails a release
1987    /// instead of being served.
1988    Never,
1989    /// Exactly this many, for a file that says it a known number of times.
1990    Exactly(usize),
1991    /// This many or more.
1992    AtLeast(usize),
1993}
1994
1995/// The vocabulary, spelled out. A derived enum cannot read both shapes a repo
1996/// writes. An unbounded word is a plain scalar. A bound is a mapping that a
1997/// newtype variant would only accept as a YAML tag (`!exactly 2`).
1998///
1999/// Untagged reads both and then reports "matched no variant", naming a type
2000/// nobody wrote. So the arity is read here and reports errors in the words a
2001/// repo uses.
2002const ARITY: &str = "once, many, never, {exactly: N}, or {at_least: N}";
2003
2004impl<'de> Deserialize<'de> for Occurrences {
2005    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2006        deserializer.deserialize_any(OccurrencesVisitor)
2007    }
2008}
2009
2010struct OccurrencesVisitor;
2011
2012impl<'de> Visitor<'de> for OccurrencesVisitor {
2013    type Value = Occurrences;
2014
2015    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2016        write!(formatter, "{ARITY}")
2017    }
2018
2019    fn visit_str<E: de::Error>(self, v: &str) -> Result<Occurrences, E> {
2020        match v {
2021            "once" => Ok(Occurrences::Once),
2022            "many" => Ok(Occurrences::Many),
2023            "never" => Ok(Occurrences::Never),
2024            _ => Err(E::custom(format!("must be {ARITY}"))),
2025        }
2026    }
2027
2028    fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Occurrences, A::Error> {
2029        use serde::de::Error;
2030        let wrong = || A::Error::custom(format!("must be {ARITY}"));
2031        let key: String = map.next_key()?.ok_or_else(wrong)?;
2032        #[expect(
2033            clippy::map_err_ignore,
2034            reason = "the report names the accepted shapes; the number parse error adds nothing"
2035        )]
2036        let count: usize = map.next_value().map_err(|_| wrong())?;
2037        if map.next_key::<IgnoredAny>()?.is_some() {
2038            return Err(wrong());
2039        }
2040        match key.as_str() {
2041            "exactly" => Ok(Occurrences::Exactly(count)),
2042            "at_least" => Ok(Occurrences::AtLeast(count)),
2043            _ => Err(wrong()),
2044        }
2045    }
2046}
2047
2048impl Occurrences {
2049    /// Whether `found` occurrences satisfy this rule.
2050    #[must_use]
2051    pub const fn allows(self, found: usize) -> bool {
2052        match self {
2053            Self::Once => found == 1,
2054            Self::Many => found >= 1,
2055            Self::Never => found == 0,
2056            Self::Exactly(count) => found == count,
2057            Self::AtLeast(count) => found >= count,
2058        }
2059    }
2060}
2061
2062impl fmt::Display for Occurrences {
2063    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2064        match self {
2065            Self::Once => f.write_str("exactly once"),
2066            Self::Many => f.write_str("one or more"),
2067            Self::Never => f.write_str("never"),
2068            Self::Exactly(count) => write!(f, "exactly {count} times"),
2069            Self::AtLeast(count) => write!(f, "{count} or more times"),
2070        }
2071    }
2072}
2073
2074/// Whose names changelog entries never credit. Release notes credit no
2075/// maintainer, and only this list identifies who one is: GitHub's
2076/// `author_association` reads a private organization member as `CONTRIBUTOR`
2077/// through an App token.
2078#[derive(Debug, Clone, Default, Deserialize)]
2079#[serde(deny_unknown_fields)]
2080#[non_exhaustive]
2081pub struct Changelog {
2082    /// GitHub logins never credited: maintainers and the Apps that open pull
2083    /// requests. Omit to list no one.
2084    #[serde(default)]
2085    pub internal_authors: Vec<String>,
2086}
2087
2088impl Changelog {
2089    /// Whether `login` is listed, ignoring case as GitHub logins do.
2090    #[must_use]
2091    pub fn is_internal(&self, login: &str) -> bool {
2092        self.internal_authors
2093            .iter()
2094            .any(|listed| listed.eq_ignore_ascii_case(login))
2095    }
2096}
2097
2098/// Extra work after version bumps, committed on the Version PR.
2099///
2100/// Unknown keys fail the load, as in every other block.
2101#[derive(Debug, Clone, Deserialize, Default)]
2102#[serde(deny_unknown_fields)]
2103#[non_exhaustive]
2104pub struct Prepare {
2105    /// argv after all bumps (for example `["mise", "run", "version-sync"]`).
2106    pub after: Option<Vec<String>>,
2107    /// Extra paths `after` may write. Anything else dirty fails.
2108    #[serde(default)]
2109    pub stage: Vec<String>,
2110    /// Collect gitignored paths that match `stage`. Off by default.
2111    #[serde(default)]
2112    pub stage_ignored: bool,
2113    /// Removed: the Version PR is not labeled, since nothing reads the label.
2114    /// Kept only for files that still set it. Such a file fails the load with
2115    /// a message to delete it, instead of serde's bare unknown-field error.
2116    /// `true` when the key is present with any value, null included;
2117    /// absent means the file is current.
2118    #[serde(default, deserialize_with = "key_present")]
2119    version_label: bool,
2120}
2121
2122/// Whether a key is present, whatever its value. serde reads an explicit null
2123/// into `Option::None`, the same as an absent key. An `Option` therefore
2124/// contains the same value for `version_label: ~` as for a file that never set
2125/// it. serde calls this only when the key is in the document.
2126fn key_present<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<bool, D::Error> {
2127    IgnoredAny::deserialize(deserializer).map(|_| true)
2128}
2129
2130/// The Version PR's title and commit message.
2131///
2132/// Both default to what verctl wrote before the block existed, so a
2133/// repository that sets neither sees the same pull request.
2134#[derive(Debug, Clone, Default, Deserialize)]
2135#[serde(deny_unknown_fields)]
2136#[non_exhaustive]
2137pub struct Proposal {
2138    /// The pull request title. Unset or empty means
2139    /// [`Proposal::DEFAULT_TITLE`].
2140    #[serde(default)]
2141    pub title: Option<String>,
2142    /// The commit message on the Version PR branch. Unset or empty means the
2143    /// resolved title.
2144    #[serde(default)]
2145    pub commit_message: Option<String>,
2146}
2147
2148impl Proposal {
2149    /// The title used when `title` is unset or empty.
2150    pub const DEFAULT_TITLE: &'static str = "chore(release): version packages";
2151
2152    /// The resolved title: the configured one, or [`Proposal::DEFAULT_TITLE`].
2153    #[must_use]
2154    pub fn title(&self) -> &str {
2155        self.title
2156            .as_deref()
2157            .filter(|title| !title.is_empty())
2158            .unwrap_or(Self::DEFAULT_TITLE)
2159    }
2160
2161    /// The resolved commit message: the configured one, or the title.
2162    #[must_use]
2163    pub fn commit_message(&self) -> &str {
2164        self.commit_message
2165            .as_deref()
2166            .filter(|message| !message.is_empty())
2167            .unwrap_or_else(|| self.title())
2168    }
2169}
2170
2171/// `prepare.version_label` labeled the Version PR until nothing read the
2172/// label; a file that still sets it is told to delete it.
2173fn no_version_label(prepare: &Prepare, _: &Config) -> garde::Result {
2174    if prepare.version_label {
2175        return Err(garde::Error::new(
2176            "prepare.version_label is removed: the Version PR is no longer labeled; delete this key",
2177        ));
2178    }
2179    Ok(())
2180}
2181
2182impl Config {
2183    /// Read and validate the file at `path`.
2184    ///
2185    /// This parses the schema and checks that any `packslip.manifest` parses
2186    /// as TOML. Callers inside a git checkout should use
2187    /// `verctl_release::forge::load_config` (or call
2188    /// [`Config::verify_packslip_tracked`]) to also verify that
2189    /// `packslip.manifest` is tracked by git.
2190    ///
2191    /// # Errors
2192    ///
2193    /// Returns an error when the file cannot be read, when its YAML does not
2194    /// match the schema, or when validation fails. Each complaint names the
2195    /// line it comes from.
2196    pub fn load(path: &Path) -> Result<Self> {
2197        let config = Self::from_input(Input::read(path)?)?;
2198        config.packslip_manifest_is_sound(&root_of(path))?;
2199        Ok(config)
2200    }
2201
2202    /// The `packslip.manifest` must be a file git tracks, so the release
2203    /// workflow, which checks out the commit, reads it there, and it must
2204    /// parse as a TOML table. Only `load` checks: `parse` reads text in
2205    /// memory and has no tree to check.
2206    fn packslip_manifest_is_sound(&self, root: &Path) -> Result<()> {
2207        let Some(manifest) = self
2208            .packslip
2209            .as_ref()
2210            .and_then(|packslip| packslip.manifest.as_ref())
2211        else {
2212            return Ok(());
2213        };
2214        read_packslip_manifest(&root.join(manifest), manifest).map(drop)
2215    }
2216
2217    /// Verify that `packslip.manifest`, when configured, is among the paths git
2218    /// tracks.
2219    ///
2220    /// # Errors
2221    ///
2222    /// Returns an error naming `packslip.manifest` when it is not in `tracked`.
2223    pub fn verify_packslip_tracked(&self, tracked: &[PathBuf]) -> Result<()> {
2224        let Some(manifest) = self
2225            .packslip
2226            .as_ref()
2227            .and_then(|packslip| packslip.manifest.as_ref())
2228        else {
2229            return Ok(());
2230        };
2231        let plain = |path: &Path| {
2232            path.components()
2233                .filter(|part| !matches!(part, Component::CurDir))
2234                .collect::<PathBuf>()
2235        };
2236        let wanted = plain(manifest);
2237        let is_tracked = tracked.iter().any(|known| plain(known) == wanted);
2238        ensure!(
2239            is_tracked,
2240            "packslip.manifest: {} is not a file git tracks; commit it, or remove `packslip.manifest`",
2241            manifest.display()
2242        );
2243        Ok(())
2244    }
2245
2246    /// A config from text in memory, named as the file a repo writes.
2247    ///
2248    /// # Errors
2249    ///
2250    /// Returns an error when `raw` does not match the schema or fails
2251    /// validation, as described for [`Config::load`].
2252    pub fn parse(raw: &str) -> Result<Self> {
2253        Self::from_input(Input::new(".ctl/ver.yaml", raw))
2254    }
2255
2256    /// The one parse boundary. ctl-core's declared input reads the shape and
2257    /// validates it once against the whole document, placing each complaint
2258    /// on its line. A document is therefore read exactly one way.
2259    ///
2260    /// `assets.targets` is the one flattened map whose entries garde dives
2261    /// into, so it is declared here, and a target's problem names the path
2262    /// the file contains.
2263    fn from_input(input: Input) -> Result<Self> {
2264        let input = input.flattened(FieldPath::root().key("assets").key("targets"));
2265        let mut config: Self = input.parse()?;
2266        input.check(&config, &config)?;
2267        config.resolve_patterns();
2268        Ok(config)
2269    }
2270
2271    /// Turn every pin's `patterns` ids into the patterns they name, so no
2272    /// consumer looks an id up again. Validation already proved every name
2273    /// resolves, which is why this cannot fail.
2274    fn resolve_patterns(&mut self) {
2275        let declared = self.patterns.clone();
2276        for pin in &mut self.pins {
2277            pin.patterns = pin
2278                .pattern_ids
2279                .iter()
2280                .filter_map(|id| declared.get(id).cloned())
2281                .collect();
2282        }
2283    }
2284
2285    /// The `release_workflow` a file that sets none gets.
2286    fn default_release_workflow() -> String {
2287        "release.yml".to_owned()
2288    }
2289
2290    /// The crates.io logins `package` must list as owners: its own `owners`,
2291    /// or else the top-level list. `None` when neither is set, so the package
2292    /// has no owner proof.
2293    #[must_use]
2294    pub fn owners_of<'a>(&'a self, package: &'a PackageSpec) -> Option<&'a [String]> {
2295        package.owners.as_deref().or(self.owners.as_deref())
2296    }
2297
2298    /// The package declared as `name`.
2299    ///
2300    /// # Errors
2301    ///
2302    /// Returns an error when no declared package has that name.
2303    pub fn find(&self, name: &str) -> Result<&PackageSpec> {
2304        self.packages
2305            .iter()
2306            .find(|package| package.name == name)
2307            .with_context(|| format!("package {name:?} is not in verctl config"))
2308    }
2309
2310    /// The spec for `name`: a stock driver, a declared one, or a declared one
2311    /// over the stock.
2312    #[must_use]
2313    pub fn driver_spec(&self, name: &str) -> Option<DriverSpec> {
2314        match (DriverSpec::stock(name), self.drivers.get(name)) {
2315            (Some(stock), Some(over)) => Some(stock.merge(over.clone())),
2316            (Some(stock), None) => Some(stock),
2317            (None, Some(over)) => Some(over.clone()),
2318            (None, None) => None,
2319        }
2320    }
2321}
2322
2323fn stock_name_for_file(file_name: &str) -> Option<&'static str> {
2324    match file_name {
2325        "Cargo.toml" => Some("cargo"),
2326        "package.json" => Some("npm"),
2327        "pyproject.toml" => Some("pyproject"),
2328        "go.mod" => Some("go"),
2329        "VERSION" => Some("version"),
2330        _ => None,
2331    }
2332}
2333
2334/// Build a stock [`Driver`] by its built-in name (`cargo`, `npm`, `pyproject`,
2335/// `go`, or `version`).
2336///
2337/// # Errors
2338///
2339/// Returns an error when `name` is not a built-in driver or its specification
2340/// cannot be compiled.
2341pub fn stock_driver(name: &str) -> Result<Driver> {
2342    DriverSpec::stock(name)
2343        .with_context(|| format!("unknown stock driver {name:?}"))?
2344        .into_driver(name)
2345}
2346
2347#[cfg(test)]
2348mod tests {
2349    use indoc::{formatdoc, indoc};
2350
2351    use super::*;
2352
2353    /// A whole config, so what is under test is what a repo actually writes.
2354    fn load(body: &str) -> Result<Config> {
2355        Config::parse(body)
2356    }
2357
2358    /// The one package every fixture below needs, and nothing else.
2359    const PACKAGE: &str = indoc! {"
2360        packages:
2361          - name: demo
2362            path: Cargo.toml
2363    "};
2364
2365    /// `publisher: none` uploads nothing, so a registry or an upload command
2366    /// beside it fails the load instead of being ignored.
2367    #[test]
2368    fn a_release_only_package_names_no_registry() {
2369        let config = load(indoc! {"
2370            packages:
2371              - name: demo
2372                path: Cargo.toml
2373                publisher: none
2374        "})
2375        .unwrap();
2376        assert_eq!(config.packages[0].publisher.as_deref(), Some("none"));
2377        let error = load(&formatdoc! {r#"
2378            {PACKAGE}
2379            publishers:
2380              none:
2381                argv: ["true"]
2382        "#})
2383        .expect_err("publishers.none is reserved");
2384        assert!(
2385            format!("{error:#}").contains("publishers.none is reserved"),
2386            "{error:#}"
2387        );
2388        for extra in ["registry: crates-io", "publish: [cargo, publish]"] {
2389            let error = load(&formatdoc! {"
2390                packages:
2391                  - name: demo
2392                    path: Cargo.toml
2393                    publisher: none
2394                    {extra}
2395            "})
2396            .expect_err(extra);
2397            assert!(
2398                format!("{error:#}").contains("has publisher: none"),
2399                "{extra}: {error:#}"
2400            );
2401        }
2402    }
2403
2404    /// `packslip` is a mapping of `manifest`, `attest` and `pubkey`, and the
2405    /// path form it replaced fails with the mapping to write.
2406    #[test]
2407    fn packslip_is_a_mapping_and_the_path_form_shows_it() {
2408        let with = |packslip: &str| {
2409            load(&formatdoc! {"
2410                {PACKAGE}
2411                assets:
2412                  linux-x64: {{}}
2413                packslip: {packslip}
2414            "})
2415        };
2416        let both = with("{ manifest: .ctl/packslip.toml, attest: link }").unwrap();
2417        let both = both.packslip.expect("packslip");
2418        assert_eq!(
2419            both.manifest.as_deref(),
2420            Some(Path::new(".ctl/packslip.toml"))
2421        );
2422        assert_eq!(both.attest, Attest::Link);
2423        let off = with("{ attest: false }")
2424            .unwrap()
2425            .packslip
2426            .expect("packslip");
2427        assert_eq!((off.manifest, off.attest), (None, Attest::False));
2428        let empty = with("{}").unwrap().packslip.expect("packslip");
2429        assert_eq!(
2430            (empty.manifest, empty.attest, empty.pubkey),
2431            (None, Attest::True, None)
2432        );
2433        let keyed = with("{ pubkey: RWQexample }")
2434            .unwrap()
2435            .packslip
2436            .expect("packslip");
2437        assert_eq!(keyed.pubkey.as_deref(), Some("RWQexample"));
2438        let report = format!("{:#}", with(".ctl/packslip.toml").expect_err("path form"));
2439        assert!(
2440            report.contains("packslip: { manifest: .ctl/packslip.toml }"),
2441            "{report}"
2442        );
2443    }
2444
2445    /// A `pubkey` with no text in it fails the load, naming the field.
2446    #[test]
2447    fn a_blank_pubkey_fails_the_load() {
2448        for blank in ["''", "'  '"] {
2449            let error = load(&formatdoc! {"
2450                {PACKAGE}
2451                assets:
2452                  linux-x64: {{}}
2453                packslip: {{ pubkey: {blank} }}
2454            "})
2455            .expect_err(blank);
2456            let report = format!("{error:#}");
2457            assert!(report.contains("packslip.pubkey"), "{blank}: {report}");
2458            assert!(report.contains("cannot be empty"), "{blank}: {report}");
2459        }
2460    }
2461
2462    /// An `attest` that is not `true`, `link`, or `false` names the field and
2463    /// the three values.
2464    #[test]
2465    fn an_unknown_attest_mode_names_the_three_values() {
2466        let error = load(&formatdoc! {"
2467            {PACKAGE}
2468            assets:
2469              linux-x64: {{}}
2470            packslip: {{ attest: maybe }}
2471        "})
2472        .expect_err("maybe is no mode");
2473        let report = format!("{error:#}");
2474        assert!(report.contains("packslip.attest"), "{report}");
2475        assert!(report.contains("true, link, or false"), "{report}");
2476    }
2477
2478    /// A target's `packslip` table is kept as written, and renders as TOML.
2479    #[test]
2480    fn a_target_packslip_table_is_kept_unread() {
2481        let config = load(&formatdoc! {r#"
2482            {PACKAGE}
2483            assets:
2484              darwin-arm64:
2485                packslip:
2486                  requires: {{ os_min: "11.0" }}
2487        "#})
2488        .unwrap();
2489        let table = config.assets.expect("assets").targets["darwin-arm64"]
2490            .packslip
2491            .clone();
2492        assert_eq!(table.to_string(), "requires = { os_min = \"11.0\" }\n");
2493    }
2494
2495    /// A target that sets no `packslip` has an empty table.
2496    #[test]
2497    fn a_target_without_a_packslip_table_has_an_empty_one() {
2498        let config = load(&formatdoc! {"
2499            {PACKAGE}
2500            assets:
2501              linux-x64: {{}}
2502        "})
2503        .unwrap();
2504        let table = &config.assets.expect("assets").targets["linux-x64"].packslip;
2505        assert_eq!(table.entries().count(), 0);
2506    }
2507
2508    /// The tarball's `path` is verctl's to write, and TOML has no null.
2509    #[test]
2510    fn a_target_packslip_table_refuses_a_path_and_a_null() {
2511        for (key, said) in [
2512            ("path: elsewhere.tar.gz", "packslip.path"),
2513            ("requires: ~", "null has no TOML form"),
2514        ] {
2515            let error = load(&formatdoc! {"
2516                {PACKAGE}
2517                assets:
2518                  darwin-arm64:
2519                    packslip:
2520                      {key}
2521            "})
2522            .expect_err(key);
2523            let report = format!("{error:#}");
2524            assert!(report.contains(said), "{key}: {report}");
2525        }
2526    }
2527
2528    /// A candidate tag is lowercase letters. Another spelling fails the load,
2529    /// naming the package and the field.
2530    #[test]
2531    fn a_prerelease_is_lowercase_letters() {
2532        for tag in ["rc", "alpha", "beta", "next", "canary"] {
2533            let config = load(&formatdoc! {"
2534                packages:
2535                  - name: demo
2536                    path: Cargo.toml
2537                    prerelease: {tag}
2538            "})
2539            .expect(tag);
2540            let spec = config.find("demo").expect("demo");
2541            assert_eq!(spec.prerelease.as_ref().map(Prerelease::as_str), Some(tag));
2542        }
2543        for tag in ["rc1", "RC", "rc.1", "1", "x", "latest", "\"\""] {
2544            let error = load(&formatdoc! {"
2545                packages:
2546                  - name: demo
2547                    path: Cargo.toml
2548                    prerelease: {tag}
2549            "})
2550            .expect_err(tag);
2551            let message = format!("{error:#}");
2552            assert!(
2553                message.contains("package \"demo\" has prerelease")
2554                    && message.contains("lowercase ASCII letters"),
2555                "{tag}: {message}"
2556            );
2557        }
2558    }
2559
2560    /// `marker: true` already marks where the version is. A driver beside it
2561    /// fails the load instead of being ignored. `after` still applies.
2562    #[test]
2563    fn a_marker_names_no_driver() {
2564        for extra in [
2565            "driver: cargo",
2566            "format: toml",
2567            "keys: [project.version]",
2568            "read: [cat]",
2569            "write: [cat]",
2570        ] {
2571            let error = load(&formatdoc! {"
2572                packages:
2573                  - name: ci
2574                    path: ci.yml
2575                    marker: true
2576                    {extra}
2577            "})
2578            .expect_err(extra);
2579            assert!(
2580                format!("{error:#}").contains("has marker: true"),
2581                "{extra}: {error:#}"
2582            );
2583        }
2584        load(indoc! {"
2585            packages:
2586              - name: ci
2587                path: ci.yml
2588                marker: true
2589                after: mise run render
2590        "})
2591        .expect("after runs beside a marker");
2592    }
2593
2594    /// No stock recipe uploads to the Python Package Index, so a Python
2595    /// package names its publisher, or `none`, before anything is released.
2596    #[test]
2597    fn a_python_package_names_its_publisher() {
2598        let error = load(indoc! {"
2599            packages:
2600              - name: demo
2601                path: pyproject.toml
2602        "})
2603        .expect_err("no publisher");
2604        assert!(
2605            format!("{error:#}").contains("needs a publisher"),
2606            "{error:#}"
2607        );
2608        for named in [
2609            "publisher: none",
2610            "publish: [uv, publish]",
2611            "publisher: pypi",
2612        ] {
2613            load(&formatdoc! {"
2614                packages:
2615                  - name: demo
2616                    path: pyproject.toml
2617                    {named}
2618                publishers:
2619                  pypi:
2620                    argv: [uv, publish]
2621            "})
2622            .unwrap_or_else(|error| panic!("{named}: {error:#}"));
2623        }
2624        load(indoc! {"
2625            packages:
2626              - name: demo
2627                path: pyproject.toml
2628            publishers:
2629              demo:
2630                argv: [uv, publish]
2631        "})
2632        .expect("a publishers entry under the package name");
2633    }
2634
2635    /// A `path` is relative to the repository, not to the directory the
2636    /// declarations happen to sit in, so `.ctl` never lands in front of it.
2637    #[test]
2638    fn the_root_is_the_directory_holding_the_ctl_dir() {
2639        let cases = [
2640            (".ctl/ver.yaml", "."),
2641            ("crates/foo/.ctl/ver.yaml", "crates/foo"),
2642            ("/srv/repo/.ctl/ver.yaml", "/srv/repo"),
2643            ("ver.yaml", "."),
2644            ("/tmp/scratch/ver.yaml", "/tmp/scratch"),
2645        ];
2646        for (config, expected) in cases {
2647            assert_eq!(root_of(Path::new(config)), Path::new(expected), "{config}");
2648        }
2649    }
2650
2651    /// Every arity a repo can write, in the spelling it writes it.
2652    #[test]
2653    fn every_occurrence_form_parses_and_means_what_it_says() {
2654        let config = load(&formatdoc! {r#"
2655            {PACKAGE}
2656            patterns:
2657              omitted:
2658                match: "a@{{version}} --"
2659              once:
2660                match: "b@{{version}} --"
2661                occurrences: once
2662              many:
2663                match: "c@{{version}} --"
2664                occurrences: many
2665              never:
2666                match: "d@{{version}} --"
2667                occurrences: never
2668              twice:
2669                match: "e@{{version}} --"
2670                occurrences: {{exactly: 2}}
2671              floor:
2672                match: "f@{{version}} --"
2673                occurrences: {{at_least: 2}}
2674
2675            pins:
2676              - file: README.md
2677                package: demo
2678                patterns: [omitted, once, many, never, twice, floor]
2679        "#})
2680        .unwrap();
2681        let allowed: Vec<Vec<usize>> = config.pins[0]
2682            .patterns
2683            .iter()
2684            .map(|pattern| (0..4).filter(|n| pattern.occurrences.allows(*n)).collect())
2685            .collect();
2686        assert_eq!(
2687            allowed,
2688            [
2689                vec![1],       // omitted: exactly once
2690                vec![1],       // once
2691                vec![1, 2, 3], // many
2692                vec![0],       // never
2693                vec![2],       // exactly 2
2694                vec![2, 3],    // at least 2
2695            ]
2696        );
2697    }
2698
2699    /// A section verctl does not know is a typo. A typo that loads is a
2700    /// release that does none of what the section was meant to do.
2701    #[test]
2702    fn a_misspelled_section_stops_the_load() {
2703        let error = load(&formatdoc! {r#"
2704            {PACKAGE}
2705            pattern:
2706              install:
2707                match: "demo@{{version}} --"
2708        "#})
2709        .expect_err("pattern is not a section");
2710        assert!(format!("{error:#}").contains("pattern"), "{error:#}");
2711    }
2712
2713    /// A bound is one key and its number. A second key means the arity was
2714    /// mistyped, and falling through to whichever variant the first key
2715    /// satisfies would pin a count nobody wrote.
2716    #[test]
2717    fn a_bound_with_a_second_key_is_not_the_bound_it_starts_with() {
2718        let error = load(&formatdoc! {r#"
2719            {PACKAGE}
2720            patterns:
2721              wrong:
2722                match: "a@{{version}} --"
2723                occurrences: {{exactly: 2, at_leats: 3}}
2724
2725            pins:
2726              - file: README.md
2727                package: demo
2728                patterns: [wrong]
2729        "#})
2730        .expect_err("at_leats is not a key");
2731        assert!(format!("{error:#}").contains(ARITY), "{error:#}");
2732    }
2733
2734    /// A count that is not a whole number is the same mistake as a wrong
2735    /// key. It is reported in the same words instead of serde's.
2736    #[test]
2737    fn a_bound_with_a_bad_count_names_the_arity() {
2738        for count in ["-1", "many"] {
2739            let error = load(&formatdoc! {r#"
2740                {PACKAGE}
2741                patterns:
2742                  wrong:
2743                    match: "a@{{version}} --"
2744                    occurrences: {{exactly: {count}}}
2745
2746                pins:
2747                  - file: README.md
2748                    package: demo
2749                    patterns: [wrong]
2750            "#})
2751            .expect_err("the count is not a whole number");
2752            assert!(format!("{error:#}").contains(ARITY), "{count}: {error:#}");
2753        }
2754    }
2755
2756    #[test]
2757    fn an_unknown_arity_is_not_silently_a_default() {
2758        let broken = load(&formatdoc! {r#"
2759            {PACKAGE}
2760            patterns:
2761              wrong:
2762                match: "a@{{version}} --"
2763                occurrences: sometimes
2764
2765            pins:
2766              - file: README.md
2767                package: demo
2768                patterns: [wrong]
2769        "#});
2770        let _ = broken.expect_err("unknown occurrences");
2771    }
2772
2773    /// One spelling, named once, carried by two files: what ids are for.
2774    #[test]
2775    fn one_named_pattern_serves_every_file_that_lists_it() {
2776        let config = load(&formatdoc! {r#"
2777            {PACKAGE}
2778            patterns:
2779              install:
2780                match: "demo@{{version}} --"
2781              mention:
2782                match: "v{{version}} --"
2783                occurrences: many
2784
2785            pins:
2786              - file: README.md
2787                package: demo
2788                patterns: [install, mention]
2789              - file: docs/install.md
2790                package: demo
2791                patterns: [install]
2792        "#})
2793        .unwrap();
2794        let carried: Vec<Vec<&str>> = config
2795            .pins
2796            .iter()
2797            .map(|pin| {
2798                pin.patterns
2799                    .iter()
2800                    .map(|pattern| pattern.r#match.as_str())
2801                    .collect()
2802            })
2803            .collect();
2804        assert_eq!(
2805            carried,
2806            [
2807                vec!["demo@{version} --", "v{version} --"],
2808                vec!["demo@{version} --"]
2809            ],
2810            "each file carries the patterns it lists, in the order it lists them"
2811        );
2812    }
2813
2814    /// Each side of `{version}` needs text a version cannot contain, or the
2815    /// line under `whole_line`. Every refusal names the pattern and the side.
2816    #[test]
2817    fn a_pattern_marks_where_the_version_starts_and_ends() {
2818        let only = "contains only digits, '.', '-', and '+'";
2819        let cases = [
2820            ("name-{version}.tar.gz", false, None),
2821            ("download/v{version}-linux", false, None),
2822            ("v{version}.tar", false, None),
2823            ("demo@{version} --", false, None),
2824            ("`demo@{version}`", false, None),
2825            ("verctl-{version}", true, None),
2826            ("version: {version}", true, None),
2827            ("{version}", true, None),
2828            (
2829                "{version}",
2830                false,
2831                Some("nothing before {version}".to_owned()),
2832            ),
2833            (
2834                "verctl-{version}",
2835                false,
2836                Some("nothing after {version}".to_owned()),
2837            ),
2838            (
2839                "version: {version}",
2840                false,
2841                Some("skill: nothing after {version}".to_owned()),
2842            ),
2843            (
2844                "verctl@{version}.",
2845                false,
2846                Some(format!("\".\" after {{version}} {only}")),
2847            ),
2848            (
2849                "v{version}-",
2850                false,
2851                Some(format!("\"-\" after {{version}} {only}")),
2852            ),
2853            (
2854                "v{version}+",
2855                false,
2856                Some(format!("\"+\" after {{version}} {only}")),
2857            ),
2858            (
2859                "-{version}",
2860                false,
2861                Some(format!("\"-\" before {{version}} {only}")),
2862            ),
2863            (
2864                "{version}.1",
2865                false,
2866                Some("nothing before {version}".to_owned()),
2867            ),
2868            (
2869                "{version}.1",
2870                true,
2871                Some(format!("\".1\" after {{version}} {only}")),
2872            ),
2873            (
2874                "version: {version}-",
2875                true,
2876                Some(format!("\"-\" after {{version}} {only}")),
2877            ),
2878        ];
2879        assert_bounds(cases);
2880    }
2881
2882    /// A digit, or a `.` and a digit, next to `{version}` lets a longer version
2883    /// match in part, whatever the rest of the literal contains.
2884    #[test]
2885    fn a_digit_next_to_the_version_leaves_the_side_open() {
2886        let near = "puts a digit, or a '.' and a digit, next to the version";
2887        assert_bounds([
2888            ("v{version}.tar", false, None),
2889            ("v{version}-1x", false, None),
2890            (
2891                "v{version}.5x",
2892                false,
2893                Some(format!("\".5x\" after {{version}} {near}")),
2894            ),
2895            (
2896                "v{version}1x",
2897                false,
2898                Some(format!("\"1x\" after {{version}} {near}")),
2899            ),
2900            (
2901                "x1.{version}-linux",
2902                false,
2903                Some(format!("\"x1.\" before {{version}} {near}")),
2904            ),
2905            (
2906                "x1{version}-linux",
2907                false,
2908                Some(format!("\"x1\" before {{version}} {near}")),
2909            ),
2910            (
2911                "{version}.1x",
2912                true,
2913                Some(format!("\".1x\" after {{version}} {near}")),
2914            ),
2915        ]);
2916    }
2917
2918    /// Loads one `skill` pattern per case and checks that it loads, or that
2919    /// the refusal names the needle.
2920    fn assert_bounds<const N: usize>(cases: [(&str, bool, Option<String>); N]) {
2921        for (text, whole_line, refusal) in cases {
2922            let loaded = load(&formatdoc! {"
2923                {PACKAGE}
2924                patterns:
2925                  skill:
2926                    match: '{text}'
2927                    whole_line: {whole_line}
2928
2929                pins:
2930                  - file: README.md
2931                    package: demo
2932                    patterns: [skill]
2933            "});
2934            match (loaded, refusal) {
2935                (Ok(_), None) => {}
2936                (Err(error), Some(needle)) => {
2937                    let report = format!("{error:#}");
2938                    assert!(report.contains(needle.as_str()), "{text}: {report}");
2939                }
2940                (outcome, _) => panic!("{text} (whole_line: {whole_line}): {outcome:?}"),
2941            }
2942        }
2943    }
2944
2945    /// Every rule the schema declares, each naming what a repo has to fix.
2946    #[test]
2947    #[expect(
2948        clippy::too_many_lines,
2949        reason = "one case per rule; a table, not logic"
2950    )]
2951    fn a_config_that_breaks_a_rule_stops_the_load() {
2952        let cases = [
2953            (
2954                "an id no patterns section declares",
2955                formatdoc! {r#"
2956                    {PACKAGE}
2957                    patterns:
2958                      install:
2959                        match: "demo@{{version}} --"
2960
2961                    pins:
2962                      - file: README.md
2963                        package: demo
2964                        patterns: [install, instal]
2965                "#},
2966                "pins[0].pattern_ids: no patterns.instal",
2967            ),
2968            (
2969                "the same id listed twice",
2970                formatdoc! {r#"
2971                    {PACKAGE}
2972                    patterns:
2973                      install:
2974                        match: "demo@{{version}} --"
2975
2976                    pins:
2977                      - file: README.md
2978                        package: demo
2979                        patterns: [install, install]
2980                "#},
2981                r#"pins[0].pattern_ids: lists "install" twice"#,
2982            ),
2983            (
2984                "a pattern no pin lists",
2985                formatdoc! {r#"
2986                    {PACKAGE}
2987                    patterns:
2988                      install:
2989                        match: "demo@{{version}} --"
2990                      orphan:
2991                        match: "old@{{version}} --"
2992
2993                    pins:
2994                      - file: README.md
2995                        package: demo
2996                        patterns: [install]
2997                "#},
2998                r#"patterns: "orphan" is declared and no pin lists it"#,
2999            ),
3000            (
3001                "a pin with nothing to rewrite",
3002                formatdoc! {"
3003                    {PACKAGE}
3004                    pins:
3005                      - file: README.md
3006                        package: demo
3007                "},
3008                "pins[0].pattern_ids: needs a tool or a pattern to rewrite",
3009            ),
3010            (
3011                "a spelling with nowhere to put the version",
3012                formatdoc! {r#"
3013                    {PACKAGE}
3014                    patterns:
3015                      install:
3016                        match: "demo@1.2.3"
3017
3018                    pins:
3019                      - file: README.md
3020                        package: demo
3021                        patterns: [install]
3022                "#},
3023                "patterns: install: match says {version} 0 times",
3024            ),
3025            (
3026                "a pin reaching out of the repository",
3027                formatdoc! {r#"
3028                    {PACKAGE}
3029                    patterns:
3030                      install:
3031                        match: "demo@{{version}} --"
3032
3033                    pins:
3034                      - file: ../elsewhere/README.md
3035                        package: demo
3036                        patterns: [install]
3037                "#},
3038                "pins[0].file: must stay inside the repository",
3039            ),
3040            (
3041                "a machine no label can find",
3042                formatdoc! {"
3043                    {PACKAGE}
3044                    runners:
3045                      ghost:
3046                        labels: []
3047                "},
3048                "runners.ghost.labels: must declare at least one label",
3049            ),
3050            (
3051                "a suffix that makes every file a template",
3052                formatdoc! {r#"
3053                    {PACKAGE}
3054                    templates:
3055                      suffix: ""
3056                "#},
3057                "templates.suffix: cannot be empty — it is what marks a file",
3058            ),
3059            (
3060                "a tag template naming a placeholder that does not exist",
3061                formatdoc! {r#"
3062                    {PACKAGE}
3063                    tags:
3064                      template: "v{{ver}}"
3065                "#},
3066                "tags.template: names {ver}, and the only placeholders are {version} and {name}",
3067            ),
3068            (
3069                "a tag template with no placeholder",
3070                formatdoc! {r#"
3071                    {PACKAGE}
3072                    tags:
3073                      template: "latest"
3074                "#},
3075                "tags.template: has no placeholder",
3076            ),
3077            (
3078                "a tag template with only the package name",
3079                formatdoc! {r#"
3080                    {PACKAGE}
3081                    tags:
3082                      template: "{{name}}"
3083                "#},
3084                "tags.template: must say {version}",
3085            ),
3086            (
3087                "an empty tag template",
3088                formatdoc! {r#"
3089                    {PACKAGE}
3090                    tags:
3091                      template: ""
3092                "#},
3093                "tags.template: cannot be empty",
3094            ),
3095            (
3096                "a tag template with a leftover brace",
3097                formatdoc! {r#"
3098                    {PACKAGE}
3099                    tags:
3100                      template: "v{{version}}}}"
3101                "#},
3102                "tags.template: has a '{' or '}' that is not {version} or {name}",
3103            ),
3104        ];
3105        for (scenario, body, expected) in cases {
3106            let error = load(&body).expect_err(scenario);
3107            assert!(
3108                format!("{error:#}").contains(expected),
3109                "{scenario}: {error:#}"
3110            );
3111        }
3112    }
3113
3114    /// A vendored set with every required key over one declared machine and
3115    /// no package, plus `extra` as one more key of the set.
3116    fn vendored(extra: &str) -> String {
3117        formatdoc! {"
3118            runners:
3119              linux:
3120                labels: [ubuntu-26.04]
3121            vendored:
3122              lib:
3123                version: 1.4.0
3124                dir: out
3125                files: [lib]
3126                targets:
3127                  linux-x64:
3128                    runner: linux
3129                {extra}
3130        "}
3131    }
3132
3133    #[test]
3134    fn a_vendored_set_alone_is_a_config_and_takes_the_default_names() {
3135        let config = load(&vendored("")).unwrap();
3136        assert!(config.packages.is_empty());
3137        let set = &config.vendored["lib"];
3138        assert_eq!(set.tag, "{name}-{version}");
3139        assert_eq!(set.archive, "{name}-{version}-{id}.tar.gz");
3140        assert_eq!(set.build, Vec::<String>::new());
3141        assert_eq!(set.notes, None);
3142    }
3143
3144    #[test]
3145    fn a_config_with_no_package_and_no_vendored_set_fails() {
3146        let error = load("runners: {}\n").unwrap_err();
3147        assert!(
3148            format!("{error:#}").contains("must declare at least one package, or a vendored set"),
3149            "{error:#}"
3150        );
3151    }
3152
3153    #[test]
3154    fn a_vendored_set_without_targets_fails() {
3155        let error = load(indoc! {"
3156            vendored:
3157              lib:
3158                version: 1.4.0
3159                dir: out
3160                files: [lib]
3161                targets: {}
3162        "})
3163        .unwrap_err();
3164        assert!(
3165            format!("{error:#}").contains("must declare at least one target"),
3166            "{error:#}"
3167        );
3168    }
3169
3170    #[test]
3171    fn a_vendored_set_rejects_what_it_cannot_publish() {
3172        let base = vendored("");
3173        let cases = [
3174            (
3175                "archive without the target",
3176                vendored("archive: lib.tar.gz"),
3177                "must contain {id}",
3178            ),
3179            (
3180                "archive in another format",
3181                vendored("archive: \"{id}.zip\""),
3182                "must end in .tar.gz",
3183            ),
3184            (
3185                "archive in a directory",
3186                vendored("archive: \"dist/{id}.tar.gz\""),
3187                "must be one file name",
3188            ),
3189            (
3190                "archive with a typo",
3191                vendored("archive: \"{ids}.tar.gz\""),
3192                "that is not {name}, {version}, {id}",
3193            ),
3194            (
3195                "tag that varies by target",
3196                vendored("tag: \"lib-{id}\""),
3197                "that is not {name}, {version}",
3198            ),
3199            ("empty tag", vendored("tag: \"\""), "cannot be empty"),
3200            (
3201                "notes outside the repo",
3202                vendored("notes: ../notes.md"),
3203                "must stay inside the repository",
3204            ),
3205            ("unknown key", vendored("bin: lib"), "bin"),
3206            (
3207                "empty version",
3208                base.replace("version: 1.4.0", "version: \"\""),
3209                "cannot be empty",
3210            ),
3211            (
3212                "dir outside the repo",
3213                base.replace("dir: out", "dir: /tmp"),
3214                "must stay inside the repository",
3215            ),
3216            (
3217                "no files",
3218                base.replace("files: [lib]", "files: []"),
3219                "must declare at least one file",
3220            ),
3221            (
3222                "a file outside the repo",
3223                base.replace("files: [lib]", "files: [../secret]"),
3224                "must stay inside the repository",
3225            ),
3226            (
3227                "version with a path separator",
3228                base.replace("version: 1.4.0", "version: 1.4/../../x"),
3229                "must be one plain name",
3230            ),
3231            (
3232                "target key with a parent step",
3233                base.replace("linux-x64:", "\"..\":"),
3234                "must be one plain name",
3235            ),
3236            (
3237                "target key with a path separator",
3238                base.replace("linux-x64:", "a/b:"),
3239                "must be one plain name",
3240            ),
3241            (
3242                "set name with a path separator",
3243                base.replace("  lib:", "  \"../lib\":"),
3244                "must be one plain name",
3245            ),
3246            (
3247                "undeclared machine",
3248                base.replace("runner: linux", "runner: big"),
3249                "\"big\" is not declared in runners (declared: linux)",
3250            ),
3251        ];
3252        for (scenario, body, expected) in cases {
3253            let error = load(&body).expect_err(scenario);
3254            assert!(
3255                format!("{error:#}").contains(expected),
3256                "{scenario}: {error:#}"
3257            );
3258        }
3259    }
3260
3261    /// The package config followed by `section`, an `assets` mapping.
3262    fn assets(section: &str) -> String {
3263        format!("{PACKAGE}{section}")
3264    }
3265
3266    #[test]
3267    fn asset_files_are_packed_from_their_dir() {
3268        let config = load(&assets(indoc! {"
3269            assets:
3270              dir: target/{triple}/release
3271              files: [demo, demod, LICENSE]
3272              linux-x64: {}
3273        "}))
3274        .unwrap();
3275        let recipe = config.assets.unwrap();
3276        assert_eq!(recipe.dir, Some(PathBuf::from("target/{triple}/release")));
3277        assert_eq!(
3278            recipe.files,
3279            [
3280                PathBuf::from("demo"),
3281                PathBuf::from("demod"),
3282                PathBuf::from("LICENSE")
3283            ]
3284        );
3285        assert_eq!(recipe.targets.keys().collect::<Vec<_>>(), ["linux-x64"]);
3286    }
3287
3288    #[test]
3289    fn a_target_lists_its_own_files() {
3290        let config = load(&assets(indoc! {"
3291            assets:
3292              dir: out/{triple}
3293              darwin-arm64:
3294                files: [proof]
3295              linux-x64:
3296                files: [bench, proof]
3297        "}))
3298        .unwrap();
3299        let recipe = config.assets.unwrap();
3300        assert_eq!(recipe.files, Vec::<PathBuf>::new());
3301        assert_eq!(
3302            recipe.targets["darwin-arm64"].files,
3303            Some(vec![PathBuf::from("proof")])
3304        );
3305        assert_eq!(
3306            recipe.targets["linux-x64"].files,
3307            Some(vec![PathBuf::from("bench"), PathBuf::from("proof")])
3308        );
3309    }
3310
3311    #[test]
3312    fn asset_files_reject_what_they_cannot_pack() {
3313        let cases = [
3314            (
3315                "dir without files",
3316                indoc! {"
3317                    assets:
3318                      dir: out
3319                      linux-x64: {}
3320                "},
3321                "must come with files",
3322            ),
3323            (
3324                "dir with no files",
3325                indoc! {"
3326                    assets:
3327                      dir: out
3328                      files: []
3329                      linux-x64: {}
3330                "},
3331                "must come with files",
3332            ),
3333            (
3334                "files without dir",
3335                indoc! {"
3336                    assets:
3337                      files: [demo]
3338                      linux-x64: {}
3339                "},
3340                "must come with dir",
3341            ),
3342            (
3343                "binary beside files",
3344                indoc! {"
3345                    assets:
3346                      binary: out/{bin}
3347                      dir: out
3348                      files: [demo]
3349                      linux-x64: {}
3350                "},
3351                "list the binary in files",
3352            ),
3353            (
3354                "dir outside the repo",
3355                indoc! {"
3356                    assets:
3357                      dir: /tmp
3358                      files: [demo]
3359                      linux-x64: {}
3360                "},
3361                "must stay inside the repository",
3362            ),
3363            (
3364                "a file outside the repo",
3365                indoc! {"
3366                    assets:
3367                      dir: out
3368                      files: [../secret]
3369                      linux-x64: {}
3370                "},
3371                "must stay inside the repository",
3372            ),
3373        ];
3374        for (scenario, section, expected) in cases {
3375            let error = load(&assets(section)).expect_err(scenario);
3376            assert!(
3377                format!("{error:#}").contains(expected),
3378                "{scenario}: {error:#}"
3379            );
3380        }
3381    }
3382
3383    #[test]
3384    fn asset_target_files_reject_what_they_cannot_pack() {
3385        let cases = [
3386            (
3387                "target files without dir",
3388                indoc! {"
3389                    assets:
3390                      linux-x64:
3391                        files: [demo]
3392                "},
3393                "assets.linux-x64.files: must come with assets.dir",
3394            ),
3395            (
3396                "an empty target list",
3397                indoc! {"
3398                    assets:
3399                      dir: out
3400                      files: [demo]
3401                      linux-x64:
3402                        files: []
3403                "},
3404                "assets.linux-x64.files: must declare at least one file",
3405            ),
3406            (
3407                "binary beside target files",
3408                indoc! {"
3409                    assets:
3410                      binary: out/{bin}
3411                      darwin-arm64: {}
3412                      linux-x64:
3413                        files: [demo]
3414                "},
3415                "assets.binary: must be omitted when assets.linux-x64.files lists what the tarball contains",
3416            ),
3417            (
3418                "a target file outside the repo",
3419                indoc! {"
3420                    assets:
3421                      dir: out
3422                      linux-x64:
3423                        files: [../secret]
3424                "},
3425                "assets.linux-x64.files[0]: must stay inside the repository",
3426            ),
3427            (
3428                "dir with a target that lists no files",
3429                indoc! {"
3430                    assets:
3431                      dir: out
3432                      darwin-arm64: {}
3433                      linux-x64:
3434                        files: [demo]
3435                "},
3436                "must come with files",
3437            ),
3438        ];
3439        for (scenario, section, expected) in cases {
3440            let error = load(&assets(section)).expect_err(scenario);
3441            assert!(
3442                format!("{error:#}").contains(expected),
3443                "{scenario}: {error:#}"
3444            );
3445        }
3446    }
3447
3448    /// The targets map is flattened under `assets`, so the file has no
3449    /// `targets` key. The problem names the path the file contains and sits on
3450    /// the line of `files`, the sixth after the three package lines.
3451    #[test]
3452    fn an_asset_target_problem_sits_on_its_own_line() {
3453        let error = load(&assets(indoc! {"
3454            assets:
3455              linux-x64:
3456                files: [demo]
3457        "}))
3458        .expect_err("target files without dir");
3459        assert!(
3460            format!("{error:#}")
3461                .contains(".ctl/ver.yaml:6:12: assets.linux-x64.files: must come with assets.dir"),
3462            "{error:#}"
3463        );
3464    }
3465
3466    const ONE_PACKAGE: &str = indoc! {"
3467        packages:
3468          - name: demo
3469            path: Cargo.toml
3470    "};
3471
3472    #[test]
3473    fn a_proposal_left_out_is_todays_title_and_message() {
3474        let config = load(ONE_PACKAGE).unwrap();
3475        assert_eq!(config.proposal.title(), "chore(release): version packages");
3476        assert_eq!(
3477            config.proposal.commit_message(),
3478            "chore(release): version packages"
3479        );
3480    }
3481
3482    #[test]
3483    fn a_title_alone_is_also_the_commit_message() {
3484        let config = load(&formatdoc! {"
3485            {ONE_PACKAGE}proposal:
3486              title: 'chore: release'
3487        "})
3488        .unwrap();
3489        assert_eq!(config.proposal.title(), "chore: release");
3490        assert_eq!(config.proposal.commit_message(), "chore: release");
3491    }
3492
3493    #[test]
3494    fn an_empty_title_and_message_are_unset() {
3495        let config = load(&formatdoc! {"
3496            {ONE_PACKAGE}proposal:
3497              title: ''
3498              commit_message: ''
3499        "})
3500        .unwrap();
3501        assert_eq!(config.proposal.title(), "chore(release): version packages");
3502        assert_eq!(
3503            config.proposal.commit_message(),
3504            "chore(release): version packages"
3505        );
3506    }
3507
3508    #[test]
3509    fn a_commit_message_differs_from_the_title() {
3510        let config = load(&formatdoc! {"
3511            {ONE_PACKAGE}proposal:
3512              title: 'chore: release'
3513              commit_message: 'chore: release [skip ci]'
3514        "})
3515        .unwrap();
3516        assert_eq!(config.proposal.title(), "chore: release");
3517        assert_eq!(config.proposal.commit_message(), "chore: release [skip ci]");
3518    }
3519
3520    #[test]
3521    fn a_version_label_is_refused_with_what_to_do() {
3522        for value in [" release", "", " ~", " null"] {
3523            let error = load(&formatdoc! {"
3524                {ONE_PACKAGE}prepare:
3525                  version_label:{value}
3526            "})
3527            .unwrap_err();
3528            let error = format!("{error:#}");
3529            assert!(
3530                error.contains("prepare.version_label is removed"),
3531                "{value:?}: {error}"
3532            );
3533            assert!(error.contains("no longer labeled"), "{value:?}: {error}");
3534            assert!(error.contains("delete this key"), "{value:?}: {error}");
3535        }
3536    }
3537
3538    /// A misspelled key under a package, whether its own or a flattened
3539    /// driver field, fails the load and names the key and the package.
3540    #[test]
3541    fn an_unknown_key_under_a_package_fails() {
3542        for (line, key) in [
3543            ("publsher: none", "publsher"),
3544            ("foramt: toml", "foramt"),
3545            ("keys: [package.version]\n    kes: [x]", "kes"),
3546        ] {
3547            let error = load(&formatdoc! {"
3548                packages:
3549                  - name: demo
3550                    path: Cargo.toml
3551                    {line}
3552            "})
3553            .unwrap_err();
3554            let error = format!("{error:#}");
3555            assert!(error.contains(key), "{line}: {error}");
3556            assert!(error.contains("\"demo\""), "{line}: {error}");
3557        }
3558        load(indoc! {"
3559            packages:
3560              - name: demo
3561                path: Cargo.toml
3562                format: toml
3563                keys: [package.version]
3564                publisher: none
3565        "})
3566        .unwrap();
3567    }
3568
3569    #[test]
3570    fn an_unknown_key_under_a_pin_fails() {
3571        let error = load(&formatdoc! {"
3572            {ONE_PACKAGE}pins:
3573              - file: README.md
3574                package: demo
3575                tool: github:acme/demo
3576                pattern: [readme]
3577        "})
3578        .unwrap_err();
3579        assert!(format!("{error:#}").contains("pattern"), "{error:#}");
3580    }
3581
3582    #[test]
3583    fn an_unknown_key_under_a_pattern_fails() {
3584        let error = load(&formatdoc! {"
3585            {ONE_PACKAGE}patterns:
3586              readme:
3587                match: 'demo@{{version}} in CI'
3588                ocurrences: many
3589            pins:
3590              - file: README.md
3591                package: demo
3592                patterns: [readme]
3593        "})
3594        .unwrap_err();
3595        assert!(format!("{error:#}").contains("ocurrences"), "{error:#}");
3596    }
3597
3598    #[test]
3599    fn an_unknown_key_under_prepare_fails() {
3600        let error = load(&formatdoc! {"
3601            {ONE_PACKAGE}prepare:
3602              stages: [docs]
3603        "})
3604        .unwrap_err();
3605        assert!(format!("{error:#}").contains("stages"), "{error:#}");
3606    }
3607
3608    #[test]
3609    fn an_unknown_key_under_proposal_fails() {
3610        let error = load(&formatdoc! {"
3611            {ONE_PACKAGE}proposal:
3612              label: release
3613        "})
3614        .unwrap_err();
3615        assert!(format!("{error:#}").contains("label"), "{error:#}");
3616    }
3617
3618    #[test]
3619    fn publish_reads_options_or_a_whole_command() {
3620        let config = load(indoc! {"
3621            packages:
3622              - name: demo
3623                path: Cargo.toml
3624                publish:
3625                  verify: false
3626              - name: tool
3627                path: tool/pyproject.toml
3628                publish: [uv, publish]
3629              - name: quiet
3630                path: quiet/Cargo.toml
3631                publish: []
3632        "})
3633        .unwrap();
3634        let options = config.packages[0].publish_options().unwrap();
3635        assert_eq!(options.get("verify"), Some(&serde_json::Value::Bool(false)));
3636        assert_eq!(config.packages[0].publish_command(), None);
3637        assert_eq!(
3638            config.packages[1].publish_command(),
3639            Some(["uv".to_owned(), "publish".to_owned()].as_slice())
3640        );
3641        assert_eq!(config.packages[2].publish_command(), Some([].as_slice()));
3642    }
3643
3644    #[test]
3645    fn publish_of_another_shape_names_both() {
3646        let error = load(indoc! {"
3647            packages:
3648              - name: demo
3649                path: Cargo.toml
3650                publish: fast
3651        "})
3652        .unwrap_err();
3653        assert!(
3654            format!("{error:#}").contains(
3655                "a mapping of publisher options, or a list that is the whole upload command"
3656            ),
3657            "{error:#}"
3658        );
3659    }
3660
3661    /// Each option belongs to the publisher the package resolves to from the
3662    /// file alone, and the load names what to remove.
3663    #[test]
3664    fn options_are_checked_against_the_publisher_at_load() {
3665        for (yaml, message) in [
3666            (
3667                indoc! {"
3668                    packages:
3669                      - name: web
3670                        path: package.json
3671                        publish:
3672                          verify: false
3673                "},
3674                r#"package "web" publishes with bun, which has no publish options; remove publish.verify"#,
3675            ),
3676            (
3677                indoc! {"
3678                    packages:
3679                      - name: demo
3680                        path: Cargo.toml
3681                        publish:
3682                          allow_dirty: true
3683                "},
3684                r#"package "demo": cargo has no publish option "allow_dirty"; its options are: verify"#,
3685            ),
3686            (
3687                indoc! {"
3688                    packages:
3689                      - name: demo
3690                        path: Cargo.toml
3691                        publish:
3692                          verify: no thanks
3693                "},
3694                r#"package "demo": publish.verify is true or false"#,
3695            ),
3696            (
3697                indoc! {"
3698                    publishers:
3699                      cargo:
3700                        argv: [cargo, publish, --workspace]
3701                    packages:
3702                      - name: demo
3703                        path: Cargo.toml
3704                        publish:
3705                          verify: false
3706                "},
3707                r#"package "demo": publishers.cargo replaces the upload command, which takes no options; remove publish, or the argv"#,
3708            ),
3709        ] {
3710            let error = load(yaml).unwrap_err();
3711            assert!(format!("{error:#}").contains(message), "{error:#}");
3712        }
3713    }
3714
3715    /// Two packages, `core` and `app`, under `top` and with `app` set to
3716    /// `app` (each a line of YAML, or empty).
3717    fn with_owners(top: &str, app: &str) -> Result<Config> {
3718        load(&formatdoc! {"
3719            {top}
3720            packages:
3721              - name: core
3722                path: core/Cargo.toml
3723              - name: app
3724                path: app/Cargo.toml
3725                {app}
3726        "})
3727    }
3728
3729    /// The top-level `owners` applies to every package, and a package's own
3730    /// list replaces it for that package alone. With neither, a package has
3731    /// no owner proof.
3732    #[test]
3733    fn owners_default_to_the_top_level_list() {
3734        let config = with_owners("owners: [any-victor]", "").unwrap();
3735        for name in ["core", "app"] {
3736            let package = config.find(name).unwrap();
3737            assert_eq!(
3738                config.owners_of(package),
3739                Some(["any-victor".to_owned()].as_slice()),
3740                "{name}"
3741            );
3742        }
3743        let config = with_owners("owners: [any-victor]", "owners: [any-victor, alice]").unwrap();
3744        assert_eq!(
3745            config.owners_of(config.find("app").unwrap()),
3746            Some(["any-victor".to_owned(), "alice".to_owned()].as_slice())
3747        );
3748        assert_eq!(
3749            config.owners_of(config.find("core").unwrap()),
3750            Some(["any-victor".to_owned()].as_slice())
3751        );
3752        let config = with_owners("", "").unwrap();
3753        assert_eq!(config.owners_of(config.find("app").unwrap()), None);
3754    }
3755
3756    /// An empty list or a login listed twice fails the load and names the
3757    /// field, at the top level and on a package.
3758    #[test]
3759    fn an_empty_or_repeated_owners_list_fails_naming_the_field() {
3760        for (top, app, expected) in [
3761            (
3762                "owners: []",
3763                "",
3764                "owners: must list at least one crates.io login",
3765            ),
3766            (
3767                "owners: [any-victor, any-victor]",
3768                "",
3769                r#"owners: lists "any-victor" twice"#,
3770            ),
3771            (
3772                "",
3773                "owners: []",
3774                "packages[app].owners must list at least one crates.io login",
3775            ),
3776            (
3777                "owners: [any-victor]",
3778                "owners: [alice, alice]",
3779                r#"packages[app].owners lists "alice" twice"#,
3780            ),
3781        ] {
3782            let error = format!("{:#}", with_owners(top, app).unwrap_err());
3783            assert!(error.contains(expected), "{top} {app}: {error}");
3784        }
3785    }
3786
3787    /// `release_workflow` is `release.yml` when omitted, takes another file
3788    /// name, and refuses a path or a file that is not a workflow, naming the
3789    /// field.
3790    #[test]
3791    fn release_workflow_is_a_workflow_file_name() {
3792        assert_eq!(load(PACKAGE).unwrap().release_workflow, "release.yml");
3793        for name in ["self-release.yml", "publish.yaml"] {
3794            let config = load(&formatdoc! {"
3795                {PACKAGE}release_workflow: {name}
3796            "})
3797            .unwrap();
3798            assert_eq!(config.release_workflow, name);
3799        }
3800        for (name, problem) in [
3801            (
3802                ".github/workflows/release.yml",
3803                "be a file name under .github/workflows/",
3804            ),
3805            (
3806                "release.toml",
3807                "name a workflow file, ending in .yml or .yaml",
3808            ),
3809            ("\"\"", "be a file name under .github/workflows/"),
3810        ] {
3811            let error = load(&formatdoc! {"
3812                {PACKAGE}release_workflow: {name}
3813            "})
3814            .unwrap_err();
3815            let error = format!("{error:#}");
3816            assert!(
3817                error.contains(&format!("release_workflow: must {problem}")),
3818                "{name}: {error}"
3819            );
3820        }
3821    }
3822
3823    /// `release_checks` is `[registry, trust]` when omitted, takes `[]` and
3824    /// any one name, and refuses a name listed twice or one release does not
3825    /// run, naming the field.
3826    #[test]
3827    fn release_checks_name_the_checks_release_runs() {
3828        assert_eq!(
3829            load(PACKAGE).unwrap().release_checks,
3830            [ReleaseCheck::Registry, ReleaseCheck::Trust]
3831        );
3832        for (list, expected) in [
3833            ("[]", [].as_slice()),
3834            ("[registry]", [ReleaseCheck::Registry].as_slice()),
3835            (
3836                "[trust, registry]",
3837                [ReleaseCheck::Trust, ReleaseCheck::Registry].as_slice(),
3838            ),
3839        ] {
3840            let config = load(&formatdoc! {"
3841                {PACKAGE}release_checks: {list}
3842            "})
3843            .unwrap();
3844            assert_eq!(config.release_checks, expected, "{list}");
3845        }
3846        let error = format!(
3847            "{:#}",
3848            load(&formatdoc! {"
3849                {PACKAGE}release_checks: [registry, registry]
3850            "})
3851            .unwrap_err()
3852        );
3853        assert!(
3854            error.contains(r#"release_checks: lists "registry" twice"#),
3855            "{error}"
3856        );
3857        let error = format!(
3858            "{:#}",
3859            load(&formatdoc! {"
3860                {PACKAGE}release_checks: [versions]
3861            "})
3862            .unwrap_err()
3863        );
3864        for name in ["release_checks", "versions", "registry", "trust"] {
3865            assert!(error.contains(name), "{name}: {error}");
3866        }
3867    }
3868}