sc-lint 0.8.8

Top-level CLI composition root for the sc-lint tool family.
Documentation
//! Shared parsing for per-step child environment and working directory.

use std::collections::BTreeMap;
use std::path::Component;
use std::path::PathBuf;

#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct StepExecError {
    pub(crate) kind: StepExecErrorKind,
    pub(crate) field: String,
    pub(crate) cause: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum StepExecErrorKind {
    Env,
    Cwd,
    DuplicateEnvKey,
}

impl StepExecError {
    pub(crate) fn message(&self, subject: &str) -> String {
        format!("{subject} {}", self.cause)
    }
}

pub(crate) fn parse_env(
    value: Option<&toml::Value>,
) -> Result<BTreeMap<String, String>, StepExecError> {
    let Some(value) = value else {
        return Ok(BTreeMap::new());
    };
    let invalid = || StepExecError {
        kind: StepExecErrorKind::Env,
        field: "env".to_owned(),
        cause: "env must be a table of strings".to_owned(),
    };
    let toml::Value::Table(table) = value else {
        return Err(invalid());
    };
    let mut env = BTreeMap::new();
    for (key, value) in table {
        if key.is_empty() || key.contains('=') || key.contains('\0') {
            return Err(StepExecError {
                kind: StepExecErrorKind::Env,
                field: format!("env.{key}"),
                cause: format!("env key `{key}` is empty or contains `=` or NUL"),
            });
        }
        let toml::Value::String(value) = value else {
            return Err(StepExecError {
                kind: StepExecErrorKind::Env,
                field: format!("env.{key}"),
                cause: "env must be a table of strings".to_owned(),
            });
        };
        env.insert(key.clone(), value.clone());
    }
    Ok(env)
}

pub(crate) fn parse_cwd(value: Option<&toml::Value>) -> Result<Option<PathBuf>, StepExecError> {
    let Some(value) = value else {
        return Ok(None);
    };
    let relative = value.as_str().map(PathBuf::from).filter(|path| {
        !path.as_os_str().is_empty()
            && path
                .components()
                .all(|component| matches!(component, Component::Normal(_) | Component::CurDir))
    });
    relative.map(Some).ok_or_else(|| StepExecError {
        kind: StepExecErrorKind::Cwd,
        field: "cwd".to_owned(),
        cause: "cwd must be a non-empty repo-root-relative path without `..`".to_owned(),
    })
}