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
//! Safety guards for privileged and destructive operations, implementing the
//! workflow standard: `--sudo` paired with a real root check, a self-documenting
//! confirmation flag, and `--dry-run` support surfaced through the context.
//!
//! The confirmation flag name and refusal wording are read from the active
//! [`crate::theme::Theme`], so a tool can reword them without touching this code.

use crate::error::{Error, Result};

/// The default long confirmation flag for destructive operations. Overridable
/// per-tool via [`crate::theme::Theme::confirm_flag`].
pub const DEFAULT_CONFIRM_FLAG: &str =
    "i-understand-this-is-permanent-i-have-saved-my-important-data";

/// Return the current effective user id (0 == root) on unix.
#[cfg(unix)]
pub fn uid() -> u32 {
    extern "C" {
        fn geteuid() -> u32;
    }
    unsafe { geteuid() }
}

#[cfg(not(unix))]
pub fn uid() -> u32 {
    // Non-unix: we can't check root the same way; treat as non-root so callers
    // must handle privilege another way.
    1
}

/// True when running as root.
pub fn is_root() -> bool {
    uid() == 0
}

/// Enforce that a root operation was both requested (`--sudo`) and is actually
/// running as root. Returns a permission error otherwise.
pub fn require_root(sudo_flag_present: bool) -> Result<()> {
    if !sudo_flag_present {
        return Err(Error::permission(
            "this operation needs root; re-run with --sudo",
        ));
    }
    if !is_root() {
        return Err(Error::permission(
            "--sudo was given but the process is not root; re-run under sudo",
        )
        .note("try: sudo <command> --sudo ..."));
    }
    Ok(())
}

/// Enforce that a destructive operation was explicitly confirmed. `confirmed`
/// is whether the confirmation flag was present. When `dry_run` is set,
/// confirmation is not required because nothing is written. The refusal message
/// and flag name come from the active theme.
pub fn require_confirmation(confirmed: bool, dry_run: bool) -> Result<()> {
    if dry_run || confirmed {
        return Ok(());
    }
    let theme = crate::theme::active();
    Err(Error::cancelled(theme.confirm_refusal_message())
        .note("or preview safely with --dry-run"))
}