cornerlibstone 0.1.0

Lib Cornerstone — a zero-dependency foundation for building command-line tools in Rust: argument parsing, nested subcommands, themeable help in multiple presets, structured errors and exit codes, config loading, interactive prompts, shell-completion and man/markdown generation, logging, JSON output, and root/destructive-operation guards.
Documentation
//! The context handed to every command body. It bundles the parsed arguments
//! with the global state (quiet, verbose, dry-run, json) and convenience methods
//! for output and guards, so a command body reads as pure logic.

use crate::error::{Error, Result};
use crate::guard;
use crate::out;
use crate::parse::Matches;

/// Global switches resolved before the command runs.
#[derive(Debug, Clone, Copy, Default)]
pub struct Globals {
    pub quiet: bool,
    pub verbose: u8,
    pub json: bool,
    pub dry_run: bool,
    pub sudo: bool,
}

/// Everything a command body needs. Borrow-friendly: methods take `&self`.
pub struct Ctx {
    pub app_name: String,
    pub command: String,
    matches: Matches,
    pub globals: Globals,
}

impl Ctx {
    pub(crate) fn new(app_name: String, command: String, matches: Matches, globals: Globals) -> Self {
        Ctx {
            app_name,
            command,
            matches,
            globals,
        }
    }

    // ---- argument access ----

    /// A required positional argument.
    pub fn arg(&self, name: &str) -> Result<&str> {
        self.matches.arg(name)
    }
    /// An optional positional argument.
    pub fn arg_opt(&self, name: &str) -> Option<&str> {
        self.matches.arg_opt(name)
    }
    /// All values of a variadic positional.
    pub fn args(&self, name: &str) -> Vec<String> {
        self.matches.args(name)
    }
    /// Whether a boolean flag was set.
    pub fn flag(&self, long: &str) -> bool {
        self.matches.flag(long)
    }
    /// A value flag, if present (or its default).
    pub fn value(&self, long: &str) -> Option<&str> {
        self.matches.value(long)
    }
    /// A value flag parsed into any `FromStr` type.
    pub fn value_as<T: std::str::FromStr>(&self, long: &str) -> Result<Option<T>> {
        match self.matches.value(long) {
            None => Ok(None),
            Some(v) => v
                .parse::<T>()
                .map(Some)
                .map_err(|_| Error::usage(format!("invalid value for --{}: {}", long, v))),
        }
    }

    // ---- global state ----

    pub fn is_dry_run(&self) -> bool {
        self.globals.dry_run
    }
    pub fn is_json(&self) -> bool {
        self.globals.json
    }

    // ---- output convenience (delegate to out::) ----

    pub fn info<S: AsRef<str>>(&self, msg: S) {
        out::info(msg);
    }
    pub fn success<S: AsRef<str>>(&self, msg: S) {
        out::success(msg);
    }
    pub fn warn<S: AsRef<str>>(&self, msg: S) {
        out::warn(msg);
    }
    pub fn debug<S: AsRef<str>>(&self, level: u8, msg: S) {
        out::debug(level, msg);
    }

    /// Standard success return for a command that finished a unit of work.
    pub fn ok<S: AsRef<str>>(&self, msg: S) -> Result<()> {
        self.success(msg);
        Ok(())
    }

    /// Print a line only when not in dry-run, prefixing with the theme's
    /// dry-run marker when it is, so a dry run narrates what it *would* do.
    pub fn action<S: AsRef<str>>(&self, msg: S) {
        if self.globals.dry_run {
            let t = crate::theme::active();
            out::info(format!(
                "{} {}",
                crate::style::Color::Yellow.paint(&t.dry_run_prefix),
                msg.as_ref()
            ));
        } else {
            out::info(msg);
        }
    }

    // ---- guards ----

    /// Enforce a root requirement using the resolved `--sudo` global.
    pub fn require_root(&self) -> Result<()> {
        guard::require_root(self.globals.sudo)
    }

    /// Enforce destructive confirmation. `confirmed` is typically
    /// `ctx.flag(DEFAULT_CONFIRM_FLAG)` (or your themed confirm-flag name).
    pub fn require_confirmation(&self, confirmed: bool) -> Result<()> {
        guard::require_confirmation(confirmed, self.globals.dry_run)
    }
}