verctl-core 0.9.7

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

use ctl_core::validate;

use super::{
    ArtifactTable, AssetFormat, AssetTarget, Assets, Config, Generated, PackageSpec, Packslip,
    VendoredTarget,
};
use crate::asset_rules as assets;

/// Two targets under one archive name would overwrite each other, and `tar
/// czf` writes only a gzipped tarball.
pub(super) fn one_archive_per_target(archive: &str, config: &Config) -> garde::Result {
    validate::one_file_name(archive, config)?;
    if !archive.contains("{id}") {
        return Err(garde::Error::new(
            "must contain {id}, or every target writes the same archive",
        ));
    }
    if !archive.ends_with(".tar.gz") {
        return Err(garde::Error::new(
            "must end in .tar.gz, the only archive verctl writes",
        ));
    }
    Ok(())
}

/// A brace left after the known placeholders is a typo that would reach a tag
/// or a file name unchanged. The tag takes no `{id}`, since every target
/// uploads to one Release.
pub(super) fn only_placeholders(
    allowed: &'static [&'static str],
) -> impl Fn(&str, &Config) -> garde::Result {
    move |template, _| {
        let rest = allowed
            .iter()
            .fold(template.to_owned(), |rest, placeholder| {
                rest.replace(placeholder, "")
            });
        if rest.contains(['{', '}']) {
            return Err(garde::Error::new(format!(
                "has a '{{' or '}}' that is not {}",
                allowed.join(", ")
            )));
        }
        Ok(())
    }
}

/// `{name}`, `{version}`, and `{id}` are substituted into `archive` and
/// `dir` after the load checked those templates. A value containing a path
/// separator or a parent step would therefore move the archive or the packed
/// directory outside the repository.
pub(super) fn one_plain_name(value: &str, _: &Config) -> garde::Result {
    if value.is_empty() || value == "." || value == ".." || value.contains(['/', '\\']) {
        return Err(garde::Error::new(format!(
            "{value:?} must be one plain name, with no / or \\ and not . or .."
        )));
    }
    Ok(())
}

pub(super) fn every_key_is_one_plain_name<V>(
    map: &BTreeMap<String, V>,
    config: &Config,
) -> garde::Result {
    map.keys().try_for_each(|key| one_plain_name(key, config))
}

pub(super) fn at_least_one_target(
    targets: &BTreeMap<String, VendoredTarget>,
    _: &Config,
) -> garde::Result {
    if targets.is_empty() {
        return Err(garde::Error::new("must declare at least one target"));
    }
    Ok(())
}

/// A target's asset file name is `{bin}`, `{version}`, `{os}`, `{arch}`, and
/// `{id}` in one plain file name.
pub(super) fn an_asset_name(template: &str, config: &Config) -> garde::Result {
    validate::one_file_name(template, config)?;
    only_placeholders(&["{bin}", "{version}", "{os}", "{arch}", "{id}"])(template, config)
}

/// Cross-field rules on each declared asset target.
pub(super) fn asset_targets_are_sound(
    targets: &BTreeMap<String, AssetTarget>,
    _: &Config,
) -> garde::Result {
    assets::targets_problem(targets)
        .map_or_else(|| Ok(()), |problem| Err(garde::Error::new(problem)))
}

/// A target's tarball name is `{bin}`, `{version}`, `{os}`, and `{arch}` in a
/// plain `.tar.gz` file name, for `format: tar.gz`.
pub(super) fn a_tarball_name(template: &str, config: &Config) -> garde::Result {
    validate::one_file_name(template, config)?;
    only_placeholders(&["{bin}", "{version}", "{os}", "{arch}"])(template, config)?;
    if !template.ends_with(".tar.gz") {
        return Err(garde::Error::new(
            "must end in .tar.gz, the only archive verctl writes for tarball",
        ));
    }
    Ok(())
}

/// Two targets that render one name would overwrite each other's asset, so
/// the load names both. The built-in targets count: `linux-x64: {}` renders
/// `{bin}_{version}_linux_x64.tar.gz`.
#[expect(
    clippy::ref_option,
    reason = "garde passes the field as it is declared"
)]
pub(super) fn every_tarball_is_its_own(assets: &Option<Assets>, config: &Config) -> garde::Result {
    let Some(assets) = assets else {
        return Ok(());
    };
    let Some(package) = config.packages.first() else {
        return Ok(());
    };
    let bin = assets.bin.as_deref().unwrap_or(&package.name);
    if let Some((first, second, name)) = assets::asset_name_clash(assets, bin) {
        return Err(garde::Error::new(format!(
            "assets.{first} and assets.{second} both write {name}: set `name` on one of them"
        )));
    }
    Ok(())
}

/// The bundle is an asset of the Release that carries the tarballs, so a
/// `packslip` without a target to carry has no Release to sign.
#[expect(
    clippy::ref_option,
    reason = "garde passes the field as it is declared"
)]
pub(super) fn packslip_needs_assets(packslip: &Option<Packslip>, config: &Config) -> garde::Result {
    let has_targets = config
        .assets
        .as_ref()
        .is_some_and(|assets| !assets.targets.is_empty());
    if packslip.is_some() && !has_targets {
        return Err(garde::Error::new(
            "needs at least one assets target: the bundle is an asset of the Release that carries the tarballs",
        ));
    }
    Ok(())
}

/// The table of a target's `packslip` reaches the release.toml unread. This
/// refuses only the `path` verctl writes. The table's own parse refuses a value
/// TOML cannot express.
pub(super) fn a_packslip_table(table: &ArtifactTable, _: &Config) -> garde::Result {
    if table.contains_key("path") {
        return Err(garde::Error::new(
            "sets `packslip.path`, the tarball's own path, which verctl writes: delete it",
        ));
    }
    Ok(())
}

/// Every `assets.generated` path, expanded for each target, stays inside the
/// tarball and names a file nothing else in it names.
pub(super) fn generated_paths_are_sound(_: &[Generated], config: &Config) -> garde::Result {
    let Some(assets) = &config.assets else {
        return Ok(());
    };
    let Some(package) = config.packages.first() else {
        return Ok(());
    };
    let bin = assets.bin.as_deref().unwrap_or(&package.name);
    assets::generated_problem(assets, bin)
        .map_or_else(|| Ok(()), |problem| Err(garde::Error::new(problem)))
}

#[expect(
    clippy::ref_option,
    reason = "garde passes the field as it is declared"
)]
pub(super) fn dir_comes_with_files(dir: &Option<PathBuf>, config: &Config) -> garde::Result {
    let packs_files = config.assets.as_ref().is_some_and(|assets| {
        if !assets.files.is_empty() {
            return true;
        }
        let mut archive_targets = assets
            .targets
            .values()
            .filter(|target| target.format != AssetFormat::Raw && !target.external)
            .peekable();
        archive_targets.peek().is_some() && archive_targets.all(|target| target.files.is_some())
    });
    if dir.is_some() && !packs_files {
        return Err(garde::Error::new(
            "must come with files, the paths packed from it, or a files list on every target",
        ));
    }
    Ok(())
}

#[expect(
    clippy::ref_option,
    reason = "garde passes the field as it is declared"
)]
pub(super) fn target_files_come_with_dir(
    files: &Option<Vec<PathBuf>>,
    config: &Config,
) -> garde::Result {
    let has_dir = config
        .assets
        .as_ref()
        .is_some_and(|assets| assets.dir.is_some());
    if files.is_some() && !has_dir {
        return Err(garde::Error::new(
            "must come with assets.dir, the directory they are packed from",
        ));
    }
    Ok(())
}

pub(super) fn files_come_with_dir(files: &[PathBuf], config: &Config) -> garde::Result {
    let has_dir = config
        .assets
        .as_ref()
        .is_some_and(|assets| assets.dir.is_some());
    if !files.is_empty() && !has_dir {
        return Err(garde::Error::new(
            "must come with dir, the directory they are packed from",
        ));
    }
    Ok(())
}

#[expect(
    clippy::ref_option,
    reason = "garde passes the field as it is declared"
)]
pub(super) fn binary_is_not_beside_files(
    binary: &Option<String>,
    config: &Config,
) -> garde::Result {
    let (Some(_), Some(assets)) = (binary, config.assets.as_ref()) else {
        return Ok(());
    };
    if let Some(id) = assets
        .targets
        .iter()
        .find_map(|(id, target)| target.files.is_some().then_some(id))
    {
        return Err(garde::Error::new(format!(
            "must be omitted when assets.{id}.files lists what the tarball contains; list the binary in files",
        )));
    }
    if assets.dir.is_some() || !assets.files.is_empty() {
        return Err(garde::Error::new(
            "must be omitted when dir and files list what the tarball contains; list the binary in files",
        ));
    }
    Ok(())
}

pub(super) fn runner_is_declared(runner: &str, config: &Config) -> garde::Result {
    if config.runners.contains_key(runner) {
        return Ok(());
    }
    let declared = config.runners.keys().cloned().collect::<Vec<_>>();
    Err(garde::Error::new(format!(
        "{runner:?} is not declared in runners ({})",
        if declared.is_empty() {
            "none declared".to_owned()
        } else {
            format!("declared: {}", declared.join(", "))
        }
    )))
}

/// A config that releases no package and vendors nothing has nothing to do.
pub(super) fn something_to_release(packages: &[PackageSpec], config: &Config) -> garde::Result {
    if packages.is_empty() && config.vendored.is_empty() {
        return Err(garde::Error::new(
            "must declare at least one package, or a vendored set",
        ));
    }
    Ok(())
}