ctl-core 0.6.12

Shared clap chassis for the *ctl CLIs
Documentation
//! Garde rules every declared schema shares, so a repository's config and a
//! template's own exports are held to the same rules and complain the same
//! way.
//!
//! Each one is a `#[garde(custom(…))]` rule: it runs at the boundary, on a
//! fully parsed value, and garde names the field that failed. They are generic
//! over the context, so the same rule works in a schema validated against
//! nothing and in one validated against the whole document.

use std::path::{Component, Path};

/// Somewhere a repository may write: relative, and never upward out of the
/// tree. A rooted path without a drive (`\x` on Windows) or a drive-relative
/// one (`C:x`) is not absolute, yet joining it replaces the repository root,
/// so any root or prefix component is refused too.
///
/// # Errors
///
/// "must stay inside the repository" for an absolute or rooted path, one
/// with a drive prefix, or one with `..`.
pub fn inside_the_repo<C>(path: &Path, _: &C) -> garde::Result {
    if path.is_absolute()
        || path.components().any(|part| {
            matches!(
                part,
                Component::ParentDir | Component::RootDir | Component::Prefix(_)
            )
        })
    {
        return Err(garde::Error::new("must stay inside the repository"));
    }
    Ok(())
}

/// A list a schema needs something in, complaining in the repository's own
/// words: `at_least_one("label")` says "must declare at least one label".
pub fn at_least_one<T, C>(noun: &'static str) -> impl Fn(&[T], &C) -> garde::Result {
    move |items, _| {
        if items.is_empty() {
            return Err(garde::Error::new(format!(
                "must declare at least one {noun}"
            )));
        }
        Ok(())
    }
}

/// A value a schema cannot do without, told what it is for, so the complaint
/// reads like a sentence: "cannot be empty — it is what marks a template".
pub fn cannot_be_empty<C>(because: &'static str) -> impl Fn(&str, &C) -> garde::Result {
    move |value, _| {
        if value.is_empty() {
            return Err(garde::Error::new(format!("cannot be empty — {because}")));
        }
        Ok(())
    }
}

/// One file name, so a name cannot smuggle in the path it was separated from.
///
/// # Errors
///
/// "must be one file name" for a name with a directory part.
pub fn one_file_name<C>(name: &str, _: &C) -> garde::Result {
    let path = Path::new(name);
    if path.file_name().is_none_or(|only| only != name) {
        return Err(garde::Error::new("must be one file name"));
    }
    Ok(())
}