verctl-core 0.9.7

Core configuration, manifest, fragment, changelog, and version domain logic for verctl
Documentation
use std::collections::BTreeMap;
use std::path::{Component, Path, PathBuf};

use anyhow::{Context, Result, ensure};
use ctl_core::input::{FieldPath, Input};
use garde::Validate;
use serde::Deserialize;

use crate::publisher_spec::PublisherSpec;

mod artifact_table;
mod assets;
mod deserialize;
mod package;
mod sections;
mod steps;
mod validate;
mod validate_assets;
mod validate_steps;

pub use artifact_table::ArtifactTable;
pub use assets::{
    AssetFormat, AssetTarget, Assets, Attest, Generated, Job, Packslip, Runner, Vendored,
    VendoredTarget, read_packslip_manifest,
};
pub use package::{
    CommandField, Current, DriverSpec, PackageSpec, Prerelease, Publish, PublishOptions,
    stock_driver,
};
#[cfg(test)]
use sections::ARITY;
pub use sections::{
    Changelog, DIR, FILE, NAME_PLACEHOLDER, Occurrences, PLACEHOLDER, Pin, PinPattern, Prepare,
    Proposal, PublishHooks, ReleaseCheck, Tags, Templates, root_of,
};
pub use steps::{AttachPoints, EcosystemSpec, StepSpec};
use validate::{
    a_marker_names_no_driver, a_prerelease_is_lowercase_letters, a_workflow_file_name,
    each_release_check_once, every_pattern_bounds_the_version, every_pattern_is_listed,
    every_pattern_says_where_the_version_goes, no_unknown_package_keys, no_version_label,
    none_is_not_a_publisher, owners_are_logins, package_owners_are_logins,
    publish_options_fit_the_publisher, python_names_its_publisher, release_only_names_no_registry,
};
use validate_assets::{
    every_key_is_one_plain_name, every_tarball_is_its_own, packslip_needs_assets,
    something_to_release,
};
use validate_steps::{
    ecosystems_are_valid, every_step_is_referenced, package_blocks_are_valid,
    steps_are_well_formed, top_level_at_is_valid,
};

/// The whole file, and the context every rule in it is checked against. A
/// pattern is only unused, and an id only unknown, relative to the rest of the
/// config. `Config::parse` reads the shape with serde and then validates it
/// once, here, so a complaint names the field that has to change.
///
/// A section verctl does not know stops the load instead of being dropped.
/// Ignoring `pattern:` for `patterns:` would ship a release with the pins it
/// declares never rewritten.
#[derive(Debug, Clone, Deserialize, Default, Validate)]
#[serde(deny_unknown_fields)]
#[garde(context(Self as config))]
#[garde(allow_unvalidated)]
#[non_exhaustive]
pub struct Config {
    /// Custom drivers by name. A stock name (`cargo`, `npm`, `pyproject`,
    /// `go`, `version`) is overridden field by field.
    #[serde(default)]
    pub drivers: BTreeMap<String, DriverSpec>,
    /// What this repo releases. Omit only when the repo declares `vendored`;
    /// a config with neither has nothing to do.
    #[serde(default)]
    #[garde(
        custom(something_to_release),
        custom(no_unknown_package_keys),
        custom(release_only_names_no_registry),
        custom(publish_options_fit_the_publisher),
        custom(python_names_its_publisher),
        custom(a_marker_names_no_driver),
        custom(a_prerelease_is_lowercase_letters),
        custom(package_owners_are_logins),
        custom(package_blocks_are_valid)
    )]
    pub packages: Vec<PackageSpec>,
    /// The crates.io logins every package's crates must list as owners, which
    /// `check registry` proves. A package's own `owners` replaces it. When
    /// omitted here and on a package, that package has no owner proof.
    #[serde(default)]
    #[garde(inner(custom(owners_are_logins)))]
    pub owners: Option<Vec<String>>,
    /// Whether crates.io crates must disable API-token publishing
    /// (`trustpub_only = true`). Defaults to `true`; set `false` here or on a
    /// package to allow API-token publishes.
    #[serde(default = "Config::default_trusted_publishing_only")]
    pub trusted_publishing_only: bool,
    /// The file under `.github/workflows/` whose run publishes, which a
    /// crates.io trusted publisher entry must name for `check trust` to pass.
    /// crates.io matches the entry against the calling workflow that the OIDC
    /// token's `workflow_ref` claim names
    /// (`crates_io_trustpub/src/github/workflows.rs`), so a reusable workflow
    /// it calls does not count. When omitted, it is `release.yml`, the caller
    /// file the template renders.
    #[serde(default = "Config::default_release_workflow")]
    #[garde(custom(a_workflow_file_name))]
    pub release_workflow: String,
    /// The checks `release` and `release --dry-run` run before the first
    /// write, from `registry` and `trust`. Only registry state can change
    /// between the merge and the release, so the checks that prove anything
    /// else run before the merge and are not listed here. `trust` runs only
    /// when `VERCTL_OWNER_TOKEN` contains an owner's token, and is reported as
    /// skipped otherwise. When omitted, it is `[registry, trust]`; `[]` runs
    /// no check.
    #[serde(default = "ReleaseCheck::default_list")]
    #[garde(custom(each_release_check_once))]
    pub release_checks: Vec<ReleaseCheck>,
    /// Publish recipes by name, for a package's `publisher` to select.
    #[serde(default)]
    #[garde(custom(none_is_not_a_publisher))]
    pub publishers: BTreeMap<String, PublisherSpec>,
    /// Machines, declared once and named. Entirely repo-owned: verctl ships no
    /// built-in names.
    #[serde(default)]
    #[garde(dive)]
    pub runners: BTreeMap<String, Runner>,
    /// Release tarball recipe. Omit for libraries.
    #[serde(default)]
    #[garde(dive, custom(every_tarball_is_its_own))]
    pub assets: Option<Assets>,
    /// The packslip the Release carries. When it is set, the Release that
    /// carries the tarballs also carries `packslip.sigstore.json`, signed by
    /// the release workflow. `{}` signs a packslip that lists `assets.bin`
    /// and attests the tarballs. Omit to publish no packslip.
    #[serde(default)]
    #[garde(dive, custom(packslip_needs_assets))]
    pub packslip: Option<Packslip>,
    /// Asset sets built from someone else's source at its own version, by
    /// name. Omit when the repo vendors nothing.
    #[serde(default)]
    #[garde(custom(every_key_is_one_plain_name), dive)]
    pub vendored: BTreeMap<String, Vendored>,
    /// PR and push validation. Empty means one `verify` on `ubuntu-26.04`.
    #[serde(default)]
    pub ci: BTreeMap<String, Job>,
    /// Work done after the version bumps.
    #[serde(default)]
    #[garde(custom(no_version_label))]
    pub prepare: Prepare,
    /// Commands `release` runs before and after registry uploads. Omit to run
    /// no publish hooks.
    #[serde(default)]
    #[garde(dive)]
    pub publish: PublishHooks,
    /// The Version PR's title and commit message. Omit for
    /// `chore(release): version packages` as both.
    #[serde(default)]
    pub proposal: Proposal,
    /// Whose names changelog entries never credit. Omit to list no one.
    #[serde(default)]
    pub changelog: Changelog,
    /// Where served-file templates live. Omit for the convention.
    #[serde(default)]
    #[garde(dive)]
    pub templates: Templates,
    /// How release tags are named. Omit for `v{version}`: one tag when every
    /// released package shares a version. Put `{name}` in the template for one
    /// tag (and one Release) per package.
    #[serde(default)]
    #[garde(dive)]
    pub tags: Tags,
    /// Version spellings, named once and listed by the files that carry them,
    /// so a spelling three files share is written once.
    #[serde(default)]
    #[garde(custom(every_pattern_says_where_the_version_goes))]
    #[garde(custom(every_pattern_bounds_the_version))]
    #[garde(custom(every_pattern_is_listed))]
    pub patterns: BTreeMap<String, PinPattern>,
    /// Collocated tool pins rewritten when `package` is bumped.
    #[serde(default)]
    #[garde(dive)]
    pub pins: Vec<Pin>,
    /// Named extension steps referenced from `at`, package block overrides,
    /// and `ecosystems`. Omit when no custom steps are needed.
    #[serde(default)]
    #[garde(dive, custom(steps_are_well_formed), custom(every_step_is_referenced))]
    pub steps: BTreeMap<String, StepSpec>,
    /// Run-wide lifecycle points (`version`, `verify`, `released`) where named
    /// steps attach. Omit to run no run-wide steps.
    #[serde(default)]
    #[garde(custom(top_level_at_is_valid))]
    pub at: AttachPoints,
    /// Repository-declared ecosystems built from named steps for each release
    /// block. Omit when built-in ecosystems cover every package.
    #[serde(default)]
    #[garde(custom(ecosystems_are_valid))]
    pub ecosystems: BTreeMap<String, EcosystemSpec>,
}

impl Config {
    /// Read and validate the file at `path`.
    ///
    /// This parses the schema and checks that any `packslip.manifest` parses
    /// as TOML. Callers inside a git checkout should use
    /// `verctl_release::forge::load_config` (or call
    /// [`Config::verify_packslip_tracked`]) to also verify that
    /// `packslip.manifest` is tracked by git.
    ///
    /// # Errors
    ///
    /// Returns an error when the file cannot be read, when its YAML does not
    /// match the schema, or when validation fails. Each complaint names the
    /// line it comes from.
    pub fn load(path: &Path) -> Result<Self> {
        let config = Self::from_input(Input::read(path)?)?;
        config.packslip_manifest_is_sound(&root_of(path))?;
        Ok(config)
    }

    /// The `packslip.manifest` must be a file git tracks, so the release
    /// workflow, which checks out the commit, reads it there, and it must
    /// parse as a TOML table. Only `load` checks: `parse` reads text in
    /// memory and has no tree to check.
    fn packslip_manifest_is_sound(&self, root: &Path) -> Result<()> {
        let Some(manifest) = self
            .packslip
            .as_ref()
            .and_then(|packslip| packslip.manifest.as_ref())
        else {
            return Ok(());
        };
        read_packslip_manifest(&root.join(manifest), manifest).map(drop)
    }

    /// Verify that `packslip.manifest`, when configured, is among the paths git
    /// tracks.
    ///
    /// # Errors
    ///
    /// Returns an error naming `packslip.manifest` when it is not in `tracked`.
    pub fn verify_packslip_tracked(&self, tracked: &[PathBuf]) -> Result<()> {
        let Some(manifest) = self
            .packslip
            .as_ref()
            .and_then(|packslip| packslip.manifest.as_ref())
        else {
            return Ok(());
        };
        let plain = |path: &Path| {
            path.components()
                .filter(|part| !matches!(part, Component::CurDir))
                .collect::<PathBuf>()
        };
        let wanted = plain(manifest);
        let is_tracked = tracked.iter().any(|known| plain(known) == wanted);
        ensure!(
            is_tracked,
            "packslip.manifest: {} is not a file git tracks; commit it, or remove `packslip.manifest`",
            manifest.display()
        );
        Ok(())
    }

    /// A config from text in memory, named as the file a repo writes.
    ///
    /// # Errors
    ///
    /// Returns an error when `raw` does not match the schema or fails
    /// validation, as described for [`Config::load`].
    pub fn parse(raw: &str) -> Result<Self> {
        Self::from_input(Input::new(".ctl/ver.yaml", raw))
    }

    /// The one parse boundary. ctl-core's declared input reads the shape and
    /// validates it once against the whole document, placing each complaint
    /// on its line. A document is therefore read exactly one way.
    ///
    /// `assets.targets` is the one flattened map whose entries garde dives
    /// into, so it is declared here, and a target's problem names the path
    /// the file contains.
    fn from_input(input: Input) -> Result<Self> {
        let input = input.flattened(FieldPath::root().key("assets").key("targets"));
        let mut config: Self = input.parse()?;
        input.check(&config, &config)?;
        config.resolve_patterns();
        Ok(config)
    }

    /// Turn every pin's `patterns` ids into the patterns they name, so no
    /// consumer looks an id up again. Validation already proved every name
    /// resolves, which is why this cannot fail.
    fn resolve_patterns(&mut self) {
        let declared = self.patterns.clone();
        for pin in &mut self.pins {
            pin.patterns = pin
                .pattern_ids
                .iter()
                .filter_map(|id| declared.get(id).cloned())
                .collect();
        }
    }

    /// The `release_workflow` a file that sets none gets.
    fn default_release_workflow() -> String {
        "release.yml".to_owned()
    }

    /// The `trusted_publishing_only` default when omitted.
    const fn default_trusted_publishing_only() -> bool {
        true
    }

    /// Whether `package` enforces crates.io `trustpub_only`: its own override,
    /// or else the top-level `trusted_publishing_only` setting (default
    /// `true`).
    #[must_use]
    pub fn trusted_publishing_only_of(&self, package: &PackageSpec) -> bool {
        package
            .trusted_publishing_only
            .unwrap_or(self.trusted_publishing_only)
    }

    /// The crates.io logins `package` must list as owners: its own `owners`,
    /// or else the top-level list. `None` when neither is set, so the package
    /// has no owner proof.
    #[must_use]
    pub fn owners_of<'a>(&'a self, package: &'a PackageSpec) -> Option<&'a [String]> {
        package.owners.as_deref().or(self.owners.as_deref())
    }

    /// The package declared as `name`.
    ///
    /// # Errors
    ///
    /// Returns an error when no declared package has that name.
    pub fn find(&self, name: &str) -> Result<&PackageSpec> {
        self.packages
            .iter()
            .find(|package| package.name == name)
            .with_context(|| format!("package {name:?} is not in verctl config"))
    }

    /// The spec for `name`: a stock driver, a declared one, or a declared one
    /// over the stock.
    #[must_use]
    pub fn driver_spec(&self, name: &str) -> Option<DriverSpec> {
        match (DriverSpec::stock(name), self.drivers.get(name)) {
            (Some(stock), Some(over)) => Some(stock.merge(over.clone())),
            (Some(stock), None) => Some(stock),
            (None, Some(over)) => Some(over.clone()),
            (None, None) => None,
        }
    }
}

#[cfg(test)]
mod tests;