verctl-core 0.9.7

Core configuration, manifest, fragment, changelog, and version domain logic for verctl
Documentation
//! Machines: declared once under `runners`, named by every job.
//!
//! A runner is one machine, and `labels` is how GitHub finds it.
//! GitHub matches every label at once, so `["self-hosted", "linux", "x64"]`
//! is a single machine carrying three labels.
//! Nothing here resolves a *label*.
//! Verctl has no way to learn which machines carry which, so labels pass
//! through as written.
//!
//! A runner *name*, by contrast, resolves here or fails here. It never reaches
//! GitHub. Only its labels do.

use std::collections::{BTreeMap, BTreeSet};

use anyhow::{Result, bail, ensure};

use crate::config::{Config, Runner};

/// A machine after resolution: the name it was declared under, and the labels
/// that go straight into `runs-on:`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Machine {
    /// The name the machine was declared under.
    pub name: String,
    /// Straight into `runs-on:`.
    pub labels: Vec<String>,
}

/// Check every declared machine before any job names one, so a broken
/// `runners` entry fails even when nothing uses it yet.
///
/// # Errors
///
/// Returns an error when a runner has no labels, an empty label, or a repeated
/// label.
pub fn declared(config: &Config) -> Result<()> {
    for (name, runner) in &config.runners {
        validate(name, runner)?;
    }
    Ok(())
}

fn validate(name: &str, runner: &Runner) -> Result<()> {
    ensure!(
        !runner.labels.is_empty(),
        "runner {name:?}: labels must name at least one label"
    );
    let mut seen = BTreeSet::new();
    for label in &runner.labels {
        ensure!(
            !label.trim().is_empty(),
            "runner {name:?}: labels has an empty label"
        );
        ensure!(
            seen.insert(label.as_str()),
            "runner {name:?}: label {label:?} is repeated"
        );
    }
    Ok(())
}

/// The machines a job named. `None` (field omitted) takes `default_labels`
/// under the name `default_name`.
///
/// # Errors
///
/// Returns an error when `named` is present but empty or names a machine
/// twice. It also fails for a machine that is not declared or that fails the
/// label checks of [`declared`].
pub fn of(
    config: &Config,
    kind: &str,
    job: &str,
    named: Option<&Vec<String>>,
    default_name: &str,
    default_labels: &[&str],
) -> Result<Vec<Machine>> {
    let Some(named) = named else {
        return Ok(vec![Machine {
            name: default_name.to_owned(),
            labels: default_labels
                .iter()
                .map(|label| (*label).to_owned())
                .collect(),
        }]);
    };
    ensure!(
        !named.is_empty(),
        "{kind} {job:?}: runners must name at least one machine"
    );
    let mut machines = Vec::new();
    let mut seen = BTreeSet::new();
    for name in named {
        ensure!(
            seen.insert(name.as_str()),
            "{kind} {job:?}: machine {name:?} is named twice"
        );
        machines.push(one(config, kind, job, name)?);
    }
    Ok(machines)
}

/// One machine by name. An undeclared name cannot be guessed at: verctl would
/// be inventing a label GitHub has never seen.
///
/// # Errors
///
/// Returns an error when `name` is not declared under `runners`, or when its
/// labels are empty, contain an empty label, or repeat one.
pub fn one(config: &Config, kind: &str, job: &str, name: &str) -> Result<Machine> {
    let Some(runner) = config.runners.get(name) else {
        bail!(
            "{kind} {job:?}: machine {name:?} is not declared in runners ({})",
            declared_names(&config.runners)
        );
    };
    validate(name, runner)?;
    Ok(Machine {
        name: name.to_owned(),
        labels: runner.labels.clone(),
    })
}

fn declared_names(runners: &BTreeMap<String, Runner>) -> String {
    if runners.is_empty() {
        return "none declared".to_owned();
    }
    format!(
        "declared: {}",
        runners.keys().cloned().collect::<Vec<_>>().join(", ")
    )
}

/// The check name for `job` on `machine` within `machines`. One machine needs
/// no disambiguation; several would land as same-named checks, each hiding the
/// others.
#[must_use]
pub fn check_name(job: &str, machine: &str, machines: &[Machine]) -> String {
    if machines.len() > 1 {
        format!("{job} ({machine})")
    } else {
        job.to_owned()
    }
}

#[cfg(test)]
mod tests;