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
//! Logging: a leveled logger separate from the user-facing [`crate::out`]
//! helpers. `out` is for what the user reads; `log` is for diagnostics that can
//! also be written to a file. Levels map to verbosity: `-v` enables debug, `-vv`
//! enables trace. A file sink, if set, always records every level regardless of
//! console verbosity, so a quiet run still leaves a full trace on disk.

use crate::style as s;
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::sync::Mutex;
use std::sync::OnceLock;

/// Severity levels, ordered.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Level {
    Error,
    Warn,
    Info,
    Debug,
    Trace,
}

impl Level {
    fn label(self) -> &'static str {
        match self {
            Level::Error => "ERROR",
            Level::Warn => "WARN",
            Level::Info => "INFO",
            Level::Debug => "DEBUG",
            Level::Trace => "TRACE",
        }
    }
    fn paint(self, text: &str) -> String {
        match self {
            Level::Error => s::red(text),
            Level::Warn => s::yellow(text),
            Level::Info => s::cyan(text),
            Level::Debug => s::gray(text),
            Level::Trace => s::dim(text),
        }
    }
}

struct Sink {
    file: Mutex<File>,
}

static SINK: OnceLock<Sink> = OnceLock::new();

/// Attach a file sink. Every log record is appended, with a millisecond
/// timestamp, regardless of console verbosity. Call once at startup. Returns an
/// error if the file can't be opened.
pub fn set_file(path: &str) -> crate::error::Result<()> {
    let file = OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)
        .map_err(|e| crate::error::Error::msg(format!("cannot open log file {}: {}", path, e)))?;
    let _ = SINK.set(Sink {
        file: Mutex::new(file),
    });
    Ok(())
}

/// The console level derived from verbosity: 0 → Info, 1 → Debug, 2+ → Trace.
fn console_level() -> Level {
    match crate::out::verbosity() {
        0 => Level::Info,
        1 => Level::Debug,
        _ => Level::Trace,
    }
}

/// Emit a log record at `level`. Goes to stderr if within console verbosity and
/// not quiet; always goes to the file sink if one is attached.
pub fn log(level: Level, msg: &str) {
    // File sink: unconditional.
    if let Some(sink) = SINK.get() {
        let ts = timestamp();
        if let Ok(mut f) = sink.file.lock() {
            let _ = writeln!(f, "{} {:<5} {}", ts, level.label(), msg);
        }
    }
    // Console: gated by verbosity and quiet.
    if crate::out::is_quiet() && level > Level::Warn {
        return;
    }
    if level <= console_level() {
        eprintln!("{} {}", level.paint(level.label()), msg);
    }
}

pub fn error(msg: &str) {
    log(Level::Error, msg);
}
pub fn warn(msg: &str) {
    log(Level::Warn, msg);
}
pub fn info(msg: &str) {
    log(Level::Info, msg);
}
pub fn debug(msg: &str) {
    log(Level::Debug, msg);
}
pub fn trace(msg: &str) {
    log(Level::Trace, msg);
}

/// A simple millisecond timestamp (seconds since the Unix epoch with millis),
/// avoiding a chrono dependency. Format: `<secs>.<millis>`.
fn timestamp() -> String {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default();
    format!("{}.{:03}", now.as_secs(), now.subsec_millis())
}