use std::fmt;
use std::time::SystemTime;
use crate::clock::unix_millis;
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Explained {
pub settings: Vec<Line>,
pub notes: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Line {
pub path: String,
pub value: String,
pub from: String,
pub over: Vec<String>,
pub given: Vec<Given>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Given {
pub value: String,
pub from: Origin,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Origin {
Declaration,
#[non_exhaustive]
Layer { place: usize },
#[non_exhaustive]
File { path: String },
#[non_exhaustive]
Env { variable: String, dotenv: Option<String>, file: Option<String> },
#[non_exhaustive]
Change { version: i64, at: SystemTime },
}
impl fmt::Display for Origin {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Origin::Declaration => f.write_str("the declaration"),
Origin::Layer { place } => write!(f, "layer {place}"),
Origin::File { path } => f.write_str(path),
Origin::Env { variable, dotenv: Some(dotenv), .. } => write!(f, "{variable} in {dotenv}"),
Origin::Env { variable, file: Some(file), .. } => write!(f, "{variable}, {file}"),
Origin::Env { variable, .. } => f.write_str(variable),
Origin::Change { version, at } => write!(f, "a change, version {version}, {}", utc(*at)),
}
}
}
fn utc(at: SystemTime) -> String {
let millis = unix_millis(at);
let (days, seconds) = (millis.div_euclid(86_400_000), millis.rem_euclid(86_400_000) / 1000);
let (year, month, day) = crate::clock::civil_from_days(days);
let (hour, minute, second) = (seconds / 3600, seconds % 3600 / 60, seconds % 60);
format!("{year:04}-{month:02}-{day:02} {hour:02}:{minute:02}:{second:02} UTC")
}
impl fmt::Display for Explained {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let width = |column: fn(&Line) -> &str| self.settings.iter().map(|line| column(line).len()).max().unwrap_or(0);
let (path, value, from) = (width(|line| &line.path), width(|line| &line.value), width(|line| &line.from));
for line in &self.settings {
let over = if line.over.is_empty() { String::new() } else { format!(" over {}", line.over.join(", ")) };
let row = format!("{:path$} {:value$} {:from$}{over}", line.path, line.value, line.from);
writeln!(f, "{}", row.trim_end())?;
}
for note in &self.notes {
writeln!(f, "{note}")?;
}
Ok(())
}
}