ctl-core 0.7.0

A framework for clap programs: typed results, help, and terminal or JSON output
Documentation
//! Files a CLI generates into a repository from templates, each template
//! declaring its own target path and mode.
//!
//! A template declares its target in Jinja's own syntax, as top-level
//! `{%- set -%}` exports, instead of a manifest beside it or a mirrored
//! directory tree:
//!
//! ```jinja
//! {%- set path = "tasks/toy" -%}
//! {%- set executable = true -%}
//! #!/usr/bin/env bash
//! #MISE tools = { "github:example/toy" = "{{ versions["toy"] }}" }
//! ```
//!
//! `path` is the directory, the repository root when omitted. `name` is the
//! file name, the template's own name without its suffix when omitted, so most
//! templates declare one line. `executable` is the one mode bit git records
//! for a regular file: when omitted, 0644. Trim declarations with `{%- … -%}`
//! so a shebang stays on line one. Any other export is the template's own.
//!
//! Rendering uses [`surface::environment`](crate::surface::environment):
//! undefined names fail, the trailing newline is kept, and ctl-core's shared
//! fragments are available. Which templates a repository has, and what
//! context they see, stay with the CLI that generates them.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::{fmt, fs, io};

use garde::Validate;
use minijinja::value::Value;
use minijinja::{Environment, State};
use serde::{Deserialize, Serialize};

use crate::validate::{inside_the_repo, one_file_name};

/// What a template declares about the file it becomes, read as one schema
/// from its exports and checked once.
#[derive(Debug, Deserialize, Validate)]
#[garde(allow_unvalidated)]
struct Declared {
    #[serde(default)]
    #[garde(custom(inside_the_repo))]
    path: PathBuf,
    /// Seeded with the template's own name before parsing, so never absent.
    #[garde(custom(one_file_name))]
    name: String,
    #[serde(default)]
    executable: bool,
}

/// A rendered template and the file it becomes, checked and not yet written.
///
/// [`render`] builds one. Read it with [`Self::target`], [`Self::body`], and
/// [`Self::executable`], or write it with [`Self::write`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Served {
    target: PathBuf,
    body: String,
    executable: bool,
}

/// Why a template could not be rendered or written, naming the template.
///
/// `Display` prints `template: message`.
///
/// A file that could not be written keeps its [`io::ErrorKind`], which
/// [`Self::io_failure`] returns. So a caller can treat a refused permission
/// apart from a full disk. A field can join this type in a minor release.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct ServeError {
    /// The template, as the caller named it. A write error names the target
    /// path instead.
    pub template: String,
    /// What went wrong, in words a user can act on.
    pub message: String,
    /// The I/O failure, for a file that could not be written.
    io_failure: Option<io::ErrorKind>,
}

impl ServeError {
    /// A refusal of `template` that no I/O error caused.
    const fn refusal(template: String, message: String) -> Self {
        Self {
            template,
            message,
            io_failure: None,
        }
    }

    /// A failure of `template` that `error` caused, described by `message`.
    fn failed_io(template: String, message: String, error: &io::Error) -> Self {
        Self {
            io_failure: Some(error.kind()),
            ..Self::refusal(template, message)
        }
    }

    /// The I/O failure when the file or a directory above it could not be
    /// written or resolved, such as
    /// [`io::ErrorKind::PermissionDenied`]. `None` for a template that did not
    /// render or declared a target it may not write.
    #[must_use]
    pub const fn io_failure(&self) -> Option<io::ErrorKind> {
        self.io_failure
    }
}

impl fmt::Display for ServeError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}: {}", self.template, self.message)
    }
}

impl std::error::Error for ServeError {}

/// Render one template with `context`, and read the target path, name, and
/// mode it declares.
///
/// `template` names the template, usually its path relative to the
/// repository. Its file name minus `suffix` is the default target name.
///
/// # Errors
///
/// Returns a [`ServeError`] in any of these cases:
///
/// - the file name does not end in `suffix`;
/// - the template does not parse or render;
/// - its declarations do not fit the schema, such as a `path` outside the
///   repository, a `name` that is not one file name, or a wrongly typed value.
pub fn render(
    template: &Path,
    source: &str,
    suffix: &str,
    context: &impl Serialize,
) -> Result<Served, ServeError> {
    let failed = |message: String| ServeError::refusal(template.display().to_string(), message);
    let own_name = template
        .file_name()
        .and_then(|name| name.to_str())
        .and_then(|name| name.strip_suffix(suffix))
        .filter(|name| !name.is_empty())
        .ok_or_else(|| failed(format!("template name does not end in {suffix}")))?;
    let environment: Environment<'static> = crate::surface::environment()
        .map_err(|error| failed(format!("register ctl-core fragments: {error}")))?;
    let name = template.display().to_string();
    let compiled = environment
        .template_from_named_str(&name, source)
        .map_err(|error| failed(format!("parse: {error}")))?;
    let captured = compiled
        .render_captured(Value::from_serialize(context))
        .map_err(|error| failed(format!("render: {error}")))?;
    let declared = declarations(captured.state(), own_name)
        .map_err(|message| failed(format!("declarations: {message}")))?;
    Ok(Served {
        target: declared.path.join(&declared.name),
        body: captured.output().to_owned(),
        executable: declared.executable,
    })
}

/// The schema read out of an evaluated template at once, over a seeded
/// `name`. Undefined and `none` exports count as unsaid.
fn declarations(state: &State<'_, '_>, own_name: &str) -> Result<Declared, String> {
    let mut exports: BTreeMap<&str, Value> = state
        .exports()
        .into_iter()
        .filter_map(|name| state.lookup(name).map(|value| (name, value)))
        .filter(|(_, value)| !value.is_undefined() && !value.is_none())
        .collect();
    exports
        .entry("name")
        .or_insert_with(|| Value::from(own_name));
    let declared = Declared::deserialize(Value::from_serialize(&exports))
        .map_err(|error| error.to_string())?;
    declared.validate().map_err(|report| report.to_string())?;
    Ok(declared)
}

impl Served {
    /// Where the file goes, relative to the repository root.
    #[must_use]
    pub fn target(&self) -> &Path {
        &self.target
    }

    /// The rendered text.
    #[must_use]
    pub fn body(&self) -> &str {
        &self.body
    }

    /// Whether the file is written 0755 rather than 0644.
    #[must_use]
    pub fn executable(&self) -> bool {
        self.executable
    }

    /// Write the file under `root`, creating its directories, and set its mode
    /// on Unix. Returns the full path.
    ///
    /// # Errors
    ///
    /// Returns a [`ServeError`] in any of these cases:
    ///
    /// - the target or a directory above it is a symlink, which could point
    ///   outside the repository;
    /// - the created directory does not resolve inside `root`;
    /// - the file or its directories cannot be written.
    pub fn write(&self, root: &Path) -> Result<PathBuf, ServeError> {
        let failed =
            |message: String| ServeError::refusal(self.target.display().to_string(), message);
        let io_failed = |message: String, error: &io::Error| {
            ServeError::failed_io(self.target.display().to_string(), message, error)
        };
        let mut walked = root.to_path_buf();
        for part in self.target.components() {
            walked.push(part);
            if fs::symlink_metadata(&walked).is_ok_and(|meta| meta.file_type().is_symlink()) {
                return Err(failed(format!(
                    "{} must not be a symlink",
                    walked.strip_prefix(root).unwrap_or(&walked).display()
                )));
            }
        }
        let path = root.join(&self.target);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).map_err(|error| {
                io_failed(format!("create {}: {error}", parent.display()), &error)
            })?;
            let inside = fs::canonicalize(root)
                .and_then(|real_root| Ok(fs::canonicalize(parent)?.starts_with(real_root)))
                .map_err(|error| {
                    io_failed(format!("resolve {}: {error}", parent.display()), &error)
                })?;
            if !inside {
                return Err(failed("target must stay inside the repository".to_owned()));
            }
        }
        fs::write(&path, &self.body)
            .map_err(|error| io_failed(format!("write: {error}"), &error))?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = if self.executable { 0o755 } else { 0o644 };
            fs::set_permissions(&path, fs::Permissions::from_mode(mode))
                .map_err(|error| io_failed(format!("chmod: {error}"), &error))?;
        }
        Ok(path)
    }
}