use std::{
fs::{self, File, OpenOptions},
io::Write,
path::{Path, PathBuf},
sync::{Mutex, OnceLock},
time::{SystemTime, UNIX_EPOCH},
};
static LOGGER: OnceLock<Mutex<Option<File>>> = OnceLock::new();
const MAX_LOG_BYTES: u64 = 1024 * 1024;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Level {
Info,
Warn,
Error,
Debug,
}
impl Level {
fn tag(self) -> &'static str {
match self {
Level::Info => "INFO ",
Level::Warn => "WARN ",
Level::Error => "ERROR",
Level::Debug => "DEBUG",
}
}
}
#[must_use]
pub(crate) fn default_log_path() -> Option<PathBuf> {
dirs::home_dir().map(|home| home.join(".govmr").join("govmr.log"))
}
#[must_use]
pub(crate) fn read_lines() -> Vec<String> {
let Some(path) = default_log_path() else {
return Vec::new();
};
fs::read_to_string(&path)
.map(|contents| contents.lines().map(str::to_string).collect())
.unwrap_or_default()
}
pub(crate) fn init() {
if let Some(path) = default_log_path() {
init_in(&path);
}
}
pub(crate) fn init_in(path: &Path) {
LOGGER.get_or_init(|| Mutex::new(open_log(path)));
}
pub(crate) fn rotate_if_oversized(path: &Path) {
if let Ok(meta) = fs::metadata(path)
&& meta.len() > MAX_LOG_BYTES
{
let old = path.with_extension("log.old");
let _ = fs::rename(path, old);
}
}
pub(crate) fn log(level: Level, message: &str) {
let Some(logger) = LOGGER.get() else { return };
let Ok(mut guard) = logger.lock() else { return };
let Some(file) = guard.as_mut() else { return };
let line = format!("{} {} {}\n", timestamp(), level.tag(), message);
let _ = file.write_all(line.as_bytes());
let _ = file.flush();
}
#[allow(dead_code)]
pub(crate) fn message_of(line: &str) -> &str {
let rest = line.get(TIMESTAMP_LEN..).unwrap_or(line);
for tag in [
Level::Info.tag(),
Level::Warn.tag(),
Level::Error.tag(),
Level::Debug.tag(),
] {
if let Some(msg) = rest.strip_prefix(tag) {
return msg.trim_start();
}
}
rest
}
#[allow(dead_code)]
const TIMESTAMP_LEN: usize = 21;
pub(crate) fn info(message: &str) {
log(Level::Info, message);
}
pub(crate) fn warn(message: &str) {
log(Level::Warn, message);
}
pub(crate) fn error(message: &str) {
log(Level::Error, message);
}
pub(crate) fn debug(message: &str) {
log(Level::Debug, message);
}
fn open_log(path: &Path) -> Option<File> {
rotate_if_oversized(path);
if let Some(parent) = path.parent() {
let _ = fs::create_dir_all(parent);
}
OpenOptions::new().create(true).append(true).open(path).ok()
}
fn timestamp() -> String {
let secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX));
format_unix(secs)
}
fn format_unix(total_secs: i64) -> String {
let days = total_secs.div_euclid(86_400);
let secs = total_secs.rem_euclid(86_400);
let (hour, minute, second) = (secs / 3600, (secs % 3600) / 60, secs % 60);
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let base_year = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = if month <= 2 { base_year + 1 } else { base_year };
format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02}Z")
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
use std::{
path::PathBuf,
sync::atomic::{AtomicU64, Ordering},
};
static COUNTER: AtomicU64 = AtomicU64::new(0);
fn temp_dir() -> PathBuf {
let n = COUNTER.fetch_add(1, Ordering::SeqCst);
let dir = std::env::temp_dir().join(format!(
"govmr-log-test-{}-{}-{}",
std::process::id(),
n,
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn writes_timestamped_level_lines() {
let path = temp_dir().join("govmr.log");
init_in(&path); info("operation: install go1.22.0");
error("operation failed: invalid gzip header");
let raw = fs::read_to_string(&path).unwrap();
assert!(raw.contains("INFO operation: install go1.22.0"));
assert!(raw.contains("ERROR operation failed: invalid gzip header"));
let first = raw.lines().next().unwrap();
assert_eq!(&first[4..5], "-");
assert_eq!(&first[7..8], "-");
assert_eq!(&first[10..11], " ");
assert_eq!(&first[13..14], ":");
assert_eq!(first.get(19..20), Some("Z"));
}
#[test]
fn rotation_moves_oversized_log_aside() {
let dir = temp_dir();
let path = dir.join("govmr.log");
fs::write(&path, vec![b'x'; 1024 * 1024 + 1]).unwrap();
rotate_if_oversized(&path);
assert!(!path.exists(), "oversized log must be rotated away");
assert!(
dir.join("govmr.log.old").exists(),
"rotation target missing"
);
}
#[test]
fn rotation_leaves_small_logs_alone() {
let dir = temp_dir();
let path = dir.join("govmr.log");
std::fs::write(&path, "tiny log\n").unwrap();
rotate_if_oversized(&path);
assert!(path.exists(), "small logs must not rotate");
}
}