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