verctl-core 0.9.1

Core configuration, manifest, fragment, changelog, and version domain logic for verctl
Documentation
//! Pure asset target naming, built-in target metadata, and generated-file path
//! validation rules shared by configuration validation and asset planning.

use std::collections::BTreeMap;

use crate::config::{AssetTarget, Assets};

/// The default tarball name template when a target sets none.
pub const DEFAULT_TARBALL: &str = "{bin}_{version}_{os}_{arch}.tar.gz";

/// The placeholders an `assets.generated` path may use.
pub const GENERATED_PLACEHOLDERS: [&str; 5] = ["{bin}", "{id}", "{os}", "{arch}", "{triple}"];

/// A platform built into verctl. A repo that wants the usual values writes
/// only its name. Every field is a default the repo may override.
#[derive(Clone, Copy, Debug)]
pub struct DeclaredTargets {
    /// Target identifier, such as `darwin-arm64`.
    pub id: &'static str,
    /// Default runner labels.
    pub labels: &'static [&'static str],
    /// Operating system name.
    pub os: &'static str,
    /// CPU architecture name.
    pub arch: &'static str,
    /// Rust target triple.
    pub triple: &'static str,
}

/// Built-in target defaults.
pub const KNOWN: &[DeclaredTargets] = &[
    DeclaredTargets {
        id: "darwin-arm64",
        labels: &["xcode-27"],
        os: "darwin",
        arch: "arm64",
        triple: "aarch64-apple-darwin",
    },
    DeclaredTargets {
        id: "linux-x64",
        labels: &["ubuntu-26.04"],
        os: "linux",
        arch: "x64",
        triple: "x86_64-unknown-linux-gnu",
    },
];

/// Comma-separated list of built-in target ids.
#[must_use]
pub fn known_ids() -> String {
    KNOWN
        .iter()
        .map(|known| known.id)
        .collect::<Vec<_>>()
        .join(", ")
}

/// The file name of the tarball for a target at `version`: `template`, or
/// `{bin}_{version}_{os}_{arch}.tar.gz` when the target sets none, with
/// `macos` for `darwin`.
#[must_use]
pub fn tarball_name(
    template: Option<&str>,
    bin: &str,
    version: &str,
    os: &str,
    arch: &str,
) -> String {
    let os = if os == "darwin" { "macos" } else { os };
    template
        .unwrap_or(DEFAULT_TARBALL)
        .replace("{bin}", bin)
        .replace("{version}", version)
        .replace("{os}", os)
        .replace("{arch}", arch)
}

/// The os and arch a target's tarball name renders: the target's own, else its
/// built-in record's.
#[must_use]
pub fn platform<'a>(id: &str, spec: &'a AssetTarget) -> Option<(&'a str, &'a str)> {
    let known = KNOWN.iter().find(|known| known.id == id);
    let os = spec.os.as_deref().or(known.map(|known| known.os))?;
    let arch = spec.arch.as_deref().or(known.map(|known| known.arch))?;
    Some((os, arch))
}

/// The target triple a target builds for: its own, else its built-in record's.
#[must_use]
pub fn triple<'a>(id: &str, spec: &'a AssetTarget) -> Option<&'a str> {
    let known = KNOWN.iter().find(|known| known.id == id);
    spec.triple.as_deref().or(known.map(|known| known.triple))
}

/// The ids of two targets that render one tarball name, with that name, or
/// `None` when every target has its own.
#[must_use]
pub fn tarball_clash(assets: &Assets, bin: &str) -> Option<(String, String, String)> {
    let mut named: BTreeMap<String, &str> = BTreeMap::new();
    for (id, spec) in &assets.targets {
        let Some((os, arch)) = platform(id, spec) else {
            continue;
        };
        let name = tarball_name(spec.tarball.as_deref(), bin, "{version}", os, arch);
        if let Some(first) = named.insert(name.clone(), id) {
            return Some((first.to_owned(), id.clone(), name));
        }
    }
    None
}

/// The first reason an `assets.generated` path of `assets` is wrong, in the
/// words the load reports, or `None` when every path is sound.
#[must_use]
pub fn generated_problem(assets: &Assets, bin: &str) -> Option<String> {
    for (at, entry) in assets.generated.iter().enumerate() {
        let rest = GENERATED_PLACEHOLDERS
            .iter()
            .fold(entry.path.clone(), |rest, placeholder| {
                rest.replace(placeholder, "")
            });
        if rest.contains(['{', '}']) {
            return Some(format!(
                "assets.generated[{at}].path {:?} has a '{{' or '}}' that is not {}",
                entry.path,
                GENERATED_PLACEHOLDERS.join(", ")
            ));
        }
    }
    for (id, spec) in &assets.targets {
        let (Some((os, arch)), Some(triple)) = (platform(id, spec), triple(id, spec)) else {
            continue;
        };
        let ctx = BTreeMap::from([
            ("bin", bin.to_owned()),
            ("id", id.clone()),
            ("os", os.to_owned()),
            ("arch", arch.to_owned()),
            ("triple", triple.to_owned()),
        ]);
        let packed: Vec<String> = if assets.dir.is_some() {
            spec.files
                .as_ref()
                .unwrap_or(&assets.files)
                .iter()
                .map(|file| expand_one(&file.display().to_string(), &ctx))
                .collect()
        } else {
            vec![bin.to_owned()]
        };
        let mut seen: Vec<(usize, Vec<String>)> = Vec::new();
        for (at, entry) in assets.generated.iter().enumerate() {
            let expanded = expand_one(&entry.path, &ctx);
            let named = format!("assets.generated[{at}].path {:?} (target {id})", entry.path);
            if let Some(reason) = unsafe_path(&expanded) {
                return Some(format!("{named} {reason}"));
            }
            let parts = plain_parts(&expanded);
            if parts.is_empty() {
                return Some(format!("{named} names the tarball's directory, not a file"));
            }
            if let Some((other, _)) = seen.iter().find(|(_, taken)| overlaps(taken, &parts)) {
                return Some(format!(
                    "{named} equals, contains, or sits under assets.generated[{other}].path: each names its own file"
                ));
            }
            if let Some(file) = packed.iter().find(|file| {
                let taken = plain_parts(file);
                !taken.is_empty() && overlaps(&taken, &parts)
            }) {
                return Some(format!(
                    "{named} would replace {file:?}, which the tarball already packs"
                ));
            }
            seen.push((at, parts));
        }
    }
    None
}

/// Expand `{key}` placeholders in `part` using `ctx`.
#[must_use]
pub fn expand_one(part: &str, ctx: &BTreeMap<&str, String>) -> String {
    let mut out = part.to_owned();
    for (key, value) in ctx {
        out = out.replace(&format!("{{{key}}}"), value);
    }
    out
}

/// Why `path` could leave the tarball or name a file two ways, or `None`.
#[must_use]
pub fn unsafe_path(path: &str) -> Option<String> {
    if path.is_empty() {
        return Some("is empty".to_owned());
    }
    if path.starts_with('/') {
        return Some("is absolute: write it relative to the tarball's directory".to_owned());
    }
    if path.ends_with('/') {
        return Some("ends in /: it names a directory, not a file".to_owned());
    }
    let mut parts = path.split('/');
    if parts.clone().any(|part| part == "..") {
        return Some("has a .. component, which leaves the tarball's directory".to_owned());
    }
    if let Some(part) = parts.clone().find(|part| part.starts_with('-')) {
        return Some(format!(
            "has the component {part:?}, which starts with '-': tar would read it as an option"
        ));
    }
    parts
        .find(|part| {
            !part
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
        })
        .map(|part| {
            format!(
                "has the component {part:?}: use only ASCII letters, digits, '.', '_', and '-', so no spelling names one file two ways"
            )
        })
}

/// The components of `path` that name something: no `.`, and no empty one from
/// a repeated separator.
#[must_use]
pub fn components(path: &str) -> Vec<&str> {
    path.split('/')
        .filter(|part| !part.is_empty() && *part != ".")
        .collect()
}

/// [`components`] with ASCII case folded.
#[must_use]
pub fn plain_parts(path: &str) -> Vec<String> {
    components(path)
        .into_iter()
        .map(str::to_ascii_lowercase)
        .collect()
}

/// Whether one of the two component lists equals or begins with the other.
#[must_use]
pub fn overlaps(left: &[String], right: &[String]) -> bool {
    left.starts_with(right) || right.starts_with(left)
}