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