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