Skip to main content

verctl_core/
config.rs

1use std::collections::BTreeMap;
2use std::path::{Component, Path, PathBuf};
3
4use anyhow::{Context, Result, ensure};
5use ctl_core::input::{FieldPath, Input};
6use garde::Validate;
7use serde::Deserialize;
8
9use crate::publisher_spec::PublisherSpec;
10
11mod artifact_table;
12mod assets;
13mod deserialize;
14mod package;
15mod sections;
16mod validate;
17mod validate_assets;
18
19pub use artifact_table::ArtifactTable;
20pub use assets::{
21    AssetFormat, AssetTarget, Assets, Attest, Generated, Job, Packslip, Runner, Vendored,
22    VendoredTarget, read_packslip_manifest,
23};
24pub use package::{
25    CommandField, Current, DriverSpec, PackageSpec, Prerelease, Publish, PublishOptions,
26    stock_driver,
27};
28#[cfg(test)]
29use sections::ARITY;
30pub use sections::{
31    Changelog, DIR, FILE, NAME_PLACEHOLDER, Occurrences, PLACEHOLDER, Pin, PinPattern, Prepare,
32    Proposal, ReleaseCheck, Tags, Templates, root_of,
33};
34use validate::{
35    a_marker_names_no_driver, a_prerelease_is_lowercase_letters, a_workflow_file_name,
36    each_release_check_once, every_pattern_bounds_the_version, every_pattern_is_listed,
37    every_pattern_says_where_the_version_goes, no_unknown_package_keys, no_version_label,
38    none_is_not_a_publisher, owners_are_logins, package_owners_are_logins,
39    publish_options_fit_the_publisher, python_names_its_publisher, release_only_names_no_registry,
40};
41use validate_assets::{
42    every_key_is_one_plain_name, every_tarball_is_its_own, packslip_needs_assets,
43    something_to_release,
44};
45
46/// The whole file, and the context every rule in it is checked against. A
47/// pattern is only unused, and an id only unknown, relative to the rest of the
48/// config. `Config::parse` reads the shape with serde and then validates it
49/// once, here, so a complaint names the field that has to change.
50///
51/// A section verctl does not know stops the load instead of being dropped.
52/// Ignoring `pattern:` for `patterns:` would ship a release with the pins it
53/// declares never rewritten.
54#[derive(Debug, Clone, Deserialize, Default, Validate)]
55#[serde(deny_unknown_fields)]
56#[garde(context(Self as config))]
57#[garde(allow_unvalidated)]
58#[non_exhaustive]
59pub struct Config {
60    /// Custom drivers by name. A stock name (`cargo`, `npm`, `pyproject`,
61    /// `go`, `version`) is overridden field by field.
62    #[serde(default)]
63    pub drivers: BTreeMap<String, DriverSpec>,
64    /// What this repo releases. Omit only when the repo declares `vendored`;
65    /// a config with neither has nothing to do.
66    #[serde(default)]
67    #[garde(
68        custom(something_to_release),
69        custom(no_unknown_package_keys),
70        custom(release_only_names_no_registry),
71        custom(publish_options_fit_the_publisher),
72        custom(python_names_its_publisher),
73        custom(a_marker_names_no_driver),
74        custom(a_prerelease_is_lowercase_letters),
75        custom(package_owners_are_logins)
76    )]
77    pub packages: Vec<PackageSpec>,
78    /// The crates.io logins every package's crates must list as owners, which
79    /// `check registry` proves. A package's own `owners` replaces it. When
80    /// omitted here and on a package, that package has no owner proof.
81    #[serde(default)]
82    #[garde(inner(custom(owners_are_logins)))]
83    pub owners: Option<Vec<String>>,
84    /// Whether crates.io crates must disable API-token publishing
85    /// (`trustpub_only = true`). Defaults to `true`; set `false` here or on a
86    /// package to allow API-token publishes.
87    #[serde(default = "Config::default_trusted_publishing_only")]
88    pub trusted_publishing_only: bool,
89    /// The file under `.github/workflows/` whose run publishes, which a
90    /// crates.io trusted publisher entry must name for `check trust` to pass.
91    /// crates.io matches the entry against the calling workflow that the OIDC
92    /// token's `workflow_ref` claim names
93    /// (`crates_io_trustpub/src/github/workflows.rs`), so a reusable workflow
94    /// it calls does not count. When omitted, it is `release.yml`, the caller
95    /// file the template renders.
96    #[serde(default = "Config::default_release_workflow")]
97    #[garde(custom(a_workflow_file_name))]
98    pub release_workflow: String,
99    /// The checks `release` and `release --dry-run` run before the first
100    /// write, from `registry` and `trust`. Only registry state can change
101    /// between the merge and the release, so the checks that prove anything
102    /// else run before the merge and are not listed here. `trust` runs only
103    /// when `VERCTL_OWNER_TOKEN` contains an owner's token, and is reported as
104    /// skipped otherwise. When omitted, it is `[registry, trust]`; `[]` runs
105    /// no check.
106    #[serde(default = "ReleaseCheck::default_list")]
107    #[garde(custom(each_release_check_once))]
108    pub release_checks: Vec<ReleaseCheck>,
109    /// Publish recipes by name, for a package's `publisher` to select.
110    #[serde(default)]
111    #[garde(custom(none_is_not_a_publisher))]
112    pub publishers: BTreeMap<String, PublisherSpec>,
113    /// Machines, declared once and named. Entirely repo-owned: verctl ships no
114    /// built-in names.
115    #[serde(default)]
116    #[garde(dive)]
117    pub runners: BTreeMap<String, Runner>,
118    /// Release tarball recipe. Omit for libraries.
119    #[serde(default)]
120    #[garde(dive, custom(every_tarball_is_its_own))]
121    pub assets: Option<Assets>,
122    /// The packslip the Release carries. When it is set, the Release that
123    /// carries the tarballs also carries `packslip.sigstore.json`, signed by
124    /// the release workflow. `{}` signs a packslip that lists `assets.bin`
125    /// and attests the tarballs. Omit to publish no packslip.
126    #[serde(default)]
127    #[garde(dive, custom(packslip_needs_assets))]
128    pub packslip: Option<Packslip>,
129    /// Asset sets built from someone else's source at its own version, by
130    /// name. Omit when the repo vendors nothing.
131    #[serde(default)]
132    #[garde(custom(every_key_is_one_plain_name), dive)]
133    pub vendored: BTreeMap<String, Vendored>,
134    /// PR and push validation. Empty means one `verify` on `ubuntu-26.04`.
135    #[serde(default)]
136    pub ci: BTreeMap<String, Job>,
137    /// Work done after the version bumps.
138    #[serde(default)]
139    #[garde(custom(no_version_label))]
140    pub prepare: Prepare,
141    /// The Version PR's title and commit message. Omit for
142    /// `chore(release): version packages` as both.
143    #[serde(default)]
144    pub proposal: Proposal,
145    /// Whose names changelog entries never credit. Omit to list no one.
146    #[serde(default)]
147    pub changelog: Changelog,
148    /// Where served-file templates live. Omit for the convention.
149    #[serde(default)]
150    #[garde(dive)]
151    pub templates: Templates,
152    /// How release tags are named. Omit for `v{version}`: one tag when every
153    /// released package shares a version. Put `{name}` in the template for one
154    /// tag (and one Release) per package.
155    #[serde(default)]
156    #[garde(dive)]
157    pub tags: Tags,
158    /// Version spellings, named once and listed by the files that carry them,
159    /// so a spelling three files share is written once.
160    #[serde(default)]
161    #[garde(custom(every_pattern_says_where_the_version_goes))]
162    #[garde(custom(every_pattern_bounds_the_version))]
163    #[garde(custom(every_pattern_is_listed))]
164    pub patterns: BTreeMap<String, PinPattern>,
165    /// Collocated tool pins rewritten when `package` is bumped.
166    #[serde(default)]
167    #[garde(dive)]
168    pub pins: Vec<Pin>,
169}
170
171impl Config {
172    /// Read and validate the file at `path`.
173    ///
174    /// This parses the schema and checks that any `packslip.manifest` parses
175    /// as TOML. Callers inside a git checkout should use
176    /// `verctl_release::forge::load_config` (or call
177    /// [`Config::verify_packslip_tracked`]) to also verify that
178    /// `packslip.manifest` is tracked by git.
179    ///
180    /// # Errors
181    ///
182    /// Returns an error when the file cannot be read, when its YAML does not
183    /// match the schema, or when validation fails. Each complaint names the
184    /// line it comes from.
185    pub fn load(path: &Path) -> Result<Self> {
186        let config = Self::from_input(Input::read(path)?)?;
187        config.packslip_manifest_is_sound(&root_of(path))?;
188        Ok(config)
189    }
190
191    /// The `packslip.manifest` must be a file git tracks, so the release
192    /// workflow, which checks out the commit, reads it there, and it must
193    /// parse as a TOML table. Only `load` checks: `parse` reads text in
194    /// memory and has no tree to check.
195    fn packslip_manifest_is_sound(&self, root: &Path) -> Result<()> {
196        let Some(manifest) = self
197            .packslip
198            .as_ref()
199            .and_then(|packslip| packslip.manifest.as_ref())
200        else {
201            return Ok(());
202        };
203        read_packslip_manifest(&root.join(manifest), manifest).map(drop)
204    }
205
206    /// Verify that `packslip.manifest`, when configured, is among the paths git
207    /// tracks.
208    ///
209    /// # Errors
210    ///
211    /// Returns an error naming `packslip.manifest` when it is not in `tracked`.
212    pub fn verify_packslip_tracked(&self, tracked: &[PathBuf]) -> Result<()> {
213        let Some(manifest) = self
214            .packslip
215            .as_ref()
216            .and_then(|packslip| packslip.manifest.as_ref())
217        else {
218            return Ok(());
219        };
220        let plain = |path: &Path| {
221            path.components()
222                .filter(|part| !matches!(part, Component::CurDir))
223                .collect::<PathBuf>()
224        };
225        let wanted = plain(manifest);
226        let is_tracked = tracked.iter().any(|known| plain(known) == wanted);
227        ensure!(
228            is_tracked,
229            "packslip.manifest: {} is not a file git tracks; commit it, or remove `packslip.manifest`",
230            manifest.display()
231        );
232        Ok(())
233    }
234
235    /// A config from text in memory, named as the file a repo writes.
236    ///
237    /// # Errors
238    ///
239    /// Returns an error when `raw` does not match the schema or fails
240    /// validation, as described for [`Config::load`].
241    pub fn parse(raw: &str) -> Result<Self> {
242        Self::from_input(Input::new(".ctl/ver.yaml", raw))
243    }
244
245    /// The one parse boundary. ctl-core's declared input reads the shape and
246    /// validates it once against the whole document, placing each complaint
247    /// on its line. A document is therefore read exactly one way.
248    ///
249    /// `assets.targets` is the one flattened map whose entries garde dives
250    /// into, so it is declared here, and a target's problem names the path
251    /// the file contains.
252    fn from_input(input: Input) -> Result<Self> {
253        let input = input.flattened(FieldPath::root().key("assets").key("targets"));
254        let mut config: Self = input.parse()?;
255        input.check(&config, &config)?;
256        config.resolve_patterns();
257        Ok(config)
258    }
259
260    /// Turn every pin's `patterns` ids into the patterns they name, so no
261    /// consumer looks an id up again. Validation already proved every name
262    /// resolves, which is why this cannot fail.
263    fn resolve_patterns(&mut self) {
264        let declared = self.patterns.clone();
265        for pin in &mut self.pins {
266            pin.patterns = pin
267                .pattern_ids
268                .iter()
269                .filter_map(|id| declared.get(id).cloned())
270                .collect();
271        }
272    }
273
274    /// The `release_workflow` a file that sets none gets.
275    fn default_release_workflow() -> String {
276        "release.yml".to_owned()
277    }
278
279    /// The `trusted_publishing_only` default when omitted.
280    const fn default_trusted_publishing_only() -> bool {
281        true
282    }
283
284    /// Whether `package` enforces crates.io `trustpub_only`: its own override,
285    /// or else the top-level `trusted_publishing_only` setting (default
286    /// `true`).
287    #[must_use]
288    pub fn trusted_publishing_only_of(&self, package: &PackageSpec) -> bool {
289        package
290            .trusted_publishing_only
291            .unwrap_or(self.trusted_publishing_only)
292    }
293
294    /// The crates.io logins `package` must list as owners: its own `owners`,
295    /// or else the top-level list. `None` when neither is set, so the package
296    /// has no owner proof.
297    #[must_use]
298    pub fn owners_of<'a>(&'a self, package: &'a PackageSpec) -> Option<&'a [String]> {
299        package.owners.as_deref().or(self.owners.as_deref())
300    }
301
302    /// The package declared as `name`.
303    ///
304    /// # Errors
305    ///
306    /// Returns an error when no declared package has that name.
307    pub fn find(&self, name: &str) -> Result<&PackageSpec> {
308        self.packages
309            .iter()
310            .find(|package| package.name == name)
311            .with_context(|| format!("package {name:?} is not in verctl config"))
312    }
313
314    /// The spec for `name`: a stock driver, a declared one, or a declared one
315    /// over the stock.
316    #[must_use]
317    pub fn driver_spec(&self, name: &str) -> Option<DriverSpec> {
318        match (DriverSpec::stock(name), self.drivers.get(name)) {
319            (Some(stock), Some(over)) => Some(stock.merge(over.clone())),
320            (Some(stock), None) => Some(stock),
321            (None, Some(over)) => Some(over.clone()),
322            (None, None) => None,
323        }
324    }
325}
326
327#[cfg(test)]
328mod tests;