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, PublishHooks, 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    /// Commands `release` runs before and after registry uploads. Omit to run
142    /// no publish hooks.
143    #[serde(default)]
144    #[garde(dive)]
145    pub publish: PublishHooks,
146    /// The Version PR's title and commit message. Omit for
147    /// `chore(release): version packages` as both.
148    #[serde(default)]
149    pub proposal: Proposal,
150    /// Whose names changelog entries never credit. Omit to list no one.
151    #[serde(default)]
152    pub changelog: Changelog,
153    /// Where served-file templates live. Omit for the convention.
154    #[serde(default)]
155    #[garde(dive)]
156    pub templates: Templates,
157    /// How release tags are named. Omit for `v{version}`: one tag when every
158    /// released package shares a version. Put `{name}` in the template for one
159    /// tag (and one Release) per package.
160    #[serde(default)]
161    #[garde(dive)]
162    pub tags: Tags,
163    /// Version spellings, named once and listed by the files that carry them,
164    /// so a spelling three files share is written once.
165    #[serde(default)]
166    #[garde(custom(every_pattern_says_where_the_version_goes))]
167    #[garde(custom(every_pattern_bounds_the_version))]
168    #[garde(custom(every_pattern_is_listed))]
169    pub patterns: BTreeMap<String, PinPattern>,
170    /// Collocated tool pins rewritten when `package` is bumped.
171    #[serde(default)]
172    #[garde(dive)]
173    pub pins: Vec<Pin>,
174}
175
176impl Config {
177    /// Read and validate the file at `path`.
178    ///
179    /// This parses the schema and checks that any `packslip.manifest` parses
180    /// as TOML. Callers inside a git checkout should use
181    /// `verctl_release::forge::load_config` (or call
182    /// [`Config::verify_packslip_tracked`]) to also verify that
183    /// `packslip.manifest` is tracked by git.
184    ///
185    /// # Errors
186    ///
187    /// Returns an error when the file cannot be read, when its YAML does not
188    /// match the schema, or when validation fails. Each complaint names the
189    /// line it comes from.
190    pub fn load(path: &Path) -> Result<Self> {
191        let config = Self::from_input(Input::read(path)?)?;
192        config.packslip_manifest_is_sound(&root_of(path))?;
193        Ok(config)
194    }
195
196    /// The `packslip.manifest` must be a file git tracks, so the release
197    /// workflow, which checks out the commit, reads it there, and it must
198    /// parse as a TOML table. Only `load` checks: `parse` reads text in
199    /// memory and has no tree to check.
200    fn packslip_manifest_is_sound(&self, root: &Path) -> Result<()> {
201        let Some(manifest) = self
202            .packslip
203            .as_ref()
204            .and_then(|packslip| packslip.manifest.as_ref())
205        else {
206            return Ok(());
207        };
208        read_packslip_manifest(&root.join(manifest), manifest).map(drop)
209    }
210
211    /// Verify that `packslip.manifest`, when configured, is among the paths git
212    /// tracks.
213    ///
214    /// # Errors
215    ///
216    /// Returns an error naming `packslip.manifest` when it is not in `tracked`.
217    pub fn verify_packslip_tracked(&self, tracked: &[PathBuf]) -> Result<()> {
218        let Some(manifest) = self
219            .packslip
220            .as_ref()
221            .and_then(|packslip| packslip.manifest.as_ref())
222        else {
223            return Ok(());
224        };
225        let plain = |path: &Path| {
226            path.components()
227                .filter(|part| !matches!(part, Component::CurDir))
228                .collect::<PathBuf>()
229        };
230        let wanted = plain(manifest);
231        let is_tracked = tracked.iter().any(|known| plain(known) == wanted);
232        ensure!(
233            is_tracked,
234            "packslip.manifest: {} is not a file git tracks; commit it, or remove `packslip.manifest`",
235            manifest.display()
236        );
237        Ok(())
238    }
239
240    /// A config from text in memory, named as the file a repo writes.
241    ///
242    /// # Errors
243    ///
244    /// Returns an error when `raw` does not match the schema or fails
245    /// validation, as described for [`Config::load`].
246    pub fn parse(raw: &str) -> Result<Self> {
247        Self::from_input(Input::new(".ctl/ver.yaml", raw))
248    }
249
250    /// The one parse boundary. ctl-core's declared input reads the shape and
251    /// validates it once against the whole document, placing each complaint
252    /// on its line. A document is therefore read exactly one way.
253    ///
254    /// `assets.targets` is the one flattened map whose entries garde dives
255    /// into, so it is declared here, and a target's problem names the path
256    /// the file contains.
257    fn from_input(input: Input) -> Result<Self> {
258        let input = input.flattened(FieldPath::root().key("assets").key("targets"));
259        let mut config: Self = input.parse()?;
260        input.check(&config, &config)?;
261        config.resolve_patterns();
262        Ok(config)
263    }
264
265    /// Turn every pin's `patterns` ids into the patterns they name, so no
266    /// consumer looks an id up again. Validation already proved every name
267    /// resolves, which is why this cannot fail.
268    fn resolve_patterns(&mut self) {
269        let declared = self.patterns.clone();
270        for pin in &mut self.pins {
271            pin.patterns = pin
272                .pattern_ids
273                .iter()
274                .filter_map(|id| declared.get(id).cloned())
275                .collect();
276        }
277    }
278
279    /// The `release_workflow` a file that sets none gets.
280    fn default_release_workflow() -> String {
281        "release.yml".to_owned()
282    }
283
284    /// The `trusted_publishing_only` default when omitted.
285    const fn default_trusted_publishing_only() -> bool {
286        true
287    }
288
289    /// Whether `package` enforces crates.io `trustpub_only`: its own override,
290    /// or else the top-level `trusted_publishing_only` setting (default
291    /// `true`).
292    #[must_use]
293    pub fn trusted_publishing_only_of(&self, package: &PackageSpec) -> bool {
294        package
295            .trusted_publishing_only
296            .unwrap_or(self.trusted_publishing_only)
297    }
298
299    /// The crates.io logins `package` must list as owners: its own `owners`,
300    /// or else the top-level list. `None` when neither is set, so the package
301    /// has no owner proof.
302    #[must_use]
303    pub fn owners_of<'a>(&'a self, package: &'a PackageSpec) -> Option<&'a [String]> {
304        package.owners.as_deref().or(self.owners.as_deref())
305    }
306
307    /// The package declared as `name`.
308    ///
309    /// # Errors
310    ///
311    /// Returns an error when no declared package has that name.
312    pub fn find(&self, name: &str) -> Result<&PackageSpec> {
313        self.packages
314            .iter()
315            .find(|package| package.name == name)
316            .with_context(|| format!("package {name:?} is not in verctl config"))
317    }
318
319    /// The spec for `name`: a stock driver, a declared one, or a declared one
320    /// over the stock.
321    #[must_use]
322    pub fn driver_spec(&self, name: &str) -> Option<DriverSpec> {
323        match (DriverSpec::stock(name), self.drivers.get(name)) {
324            (Some(stock), Some(over)) => Some(stock.merge(over.clone())),
325            (Some(stock), None) => Some(stock),
326            (None, Some(over)) => Some(over.clone()),
327            (None, None) => None,
328        }
329    }
330}
331
332#[cfg(test)]
333mod tests;