use crate::ontology::resolve::Reading;
use std::collections::BTreeMap;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Colour {
Blue,
Cyan,
Green,
Yellow,
Red,
Magenta,
White,
Grey,
}
impl Colour {
fn code(self) -> &'static str {
match self {
Colour::Blue => "[34m",
Colour::Cyan => "[36m",
Colour::Green => "[32m",
Colour::Yellow => "[33m",
Colour::Red => "[31m",
Colour::Magenta => "[35m",
Colour::White => "[97m",
Colour::Grey => "[90m",
}
}
pub fn paint(self, text: &str, colour: bool) -> String {
if colour {
format!("{}{text}[0m", self.code())
} else {
text.to_string()
}
}
}
pub struct ArtLine(pub &'static str, pub Colour);
pub fn logo() -> Vec<ArtLine> {
#[cfg(windows)]
{
vec![
ArtLine(" ,.=:!!t3Z3z., ", Colour::Red),
ArtLine(" :tt:::tt333EE3 ", Colour::Red),
ArtLine(" Et:::ztt33EEEL @Ee.,", Colour::Green),
ArtLine(" ;tt:::tt333EE7 ;EEEEE.", Colour::Green),
ArtLine(" :Et:::zt333EEQ. $EEEEE.", Colour::Blue),
ArtLine(" it::::tt333EEF @EEEEEE.", Colour::Blue),
ArtLine(" ;3=*^```\"*4EEV :EEEEEEE.", Colour::Yellow),
ArtLine(" ,.=::::!t=., ` @EEEEEEE.", Colour::Yellow),
]
}
#[cfg(target_os = "linux")]
{
vec![
ArtLine(" _nnnn_ ", Colour::White),
ArtLine(" dGGGGMMb ", Colour::White),
ArtLine(" @p~qp~~qMb ", Colour::White),
ArtLine(" M|@||@) M| ", Colour::Yellow),
ArtLine(" @,----.JM| ", Colour::Yellow),
ArtLine(" JS^\\__/ qKL ", Colour::White),
ArtLine(" dZP qKRb ", Colour::White),
ArtLine(" dZP qKKb ", Colour::White),
ArtLine(" fZP SMMb ", Colour::White),
ArtLine(" HZM MMMM ", Colour::White),
ArtLine(" FqM MMMM ", Colour::Yellow),
ArtLine(" __| \". |\\dS\"qML ", Colour::Yellow),
]
}
#[cfg(target_os = "macos")]
{
vec![
ArtLine(" c.' ", Colour::Green),
ArtLine(" ,xNMM. ", Colour::Green),
ArtLine(" .OMMMMo ", Colour::Yellow),
ArtLine(" lMM\" ", Colour::Yellow),
ArtLine(" .;loddo:. .olloddol;. ", Colour::Red),
ArtLine("cKMMMMMMMMMMNWMMMMMMMMMM0:", Colour::Red),
ArtLine(".KMMMMMMMMMMMMMMMMMMMMMMMWd", Colour::Magenta),
ArtLine(" XMMMMMMMMMMMMMMMMMMMMMMMX.", Colour::Magenta),
ArtLine(" .XMMMMMMMMMMMMMMMMMMMMMMk ", Colour::Blue),
ArtLine(" .XMMMMMMMMMMMMMMMMMMMMX. ", Colour::Blue),
ArtLine(" kMMMMMMMMMMMMMMMMMMd ", Colour::Cyan),
ArtLine(" ;KMMMMMMMWXXWMMMMMk. ", Colour::Cyan),
]
}
#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
{
vec![
ArtLine(" +-------+ ", Colour::Cyan),
ArtLine(" | ..... | ", Colour::Cyan),
ArtLine(" | ..... | ", Colour::Cyan),
ArtLine(" +-------+ ", Colour::Cyan),
]
}
}
fn art_width(art: &[ArtLine]) -> usize {
art.iter().map(|l| l.0.chars().count()).max().unwrap_or(0)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Line {
pub label: String,
pub value: Option<String>,
pub reason: Option<String>,
}
impl Line {
pub fn render(&self) -> String {
match (&self.value, &self.reason) {
(Some(v), _) => v.clone(),
(None, Some(r)) => format!("unknown — {r}"),
(None, None) => "unknown".to_string(),
}
}
}
fn find<'a>(readings: &'a [Reading], id: &str) -> Option<&'a Reading> {
readings.iter().find(|r| r.id == id)
}
pub fn temperatures(readings: &[Reading]) -> Vec<&Reading> {
let mut out: Vec<&Reading> = readings
.iter()
.filter(|r| r.unit == Some(crate::ontology::Unit::Celsius))
.collect();
out.sort_by(|a, b| a.id.cmp(&b.id));
out
}
pub fn power(readings: &[Reading]) -> Vec<&Reading> {
let mut out: Vec<&Reading> = readings
.iter()
.filter(|r| r.id.starts_with("power.") || r.id.contains(".power."))
.collect();
out.sort_by(|a, b| a.id.cmp(&b.id));
out
}
fn line(
readings: &[Reading],
label: &str,
id: &str,
fmt: impl Fn(&serde_json::Value) -> String,
) -> Line {
match find(readings, id) {
Some(r) => match &r.value {
Some(v) => Line {
label: label.to_string(),
value: Some(fmt(v)),
reason: None,
},
None => Line {
label: label.to_string(),
value: None,
reason: Some(
r.note
.clone()
.unwrap_or_else(|| "no reason recorded".to_string()),
),
},
},
None => Line {
label: label.to_string(),
value: None,
reason: Some(format!("{id} is not in this snapshot")),
},
}
}
fn as_text(v: &serde_json::Value) -> String {
v.as_str()
.map(str::to_string)
.unwrap_or_else(|| v.to_string())
}
fn as_bytes(v: &serde_json::Value) -> String {
let Some(b) = v.as_f64() else {
return as_text(v);
};
const UNITS: [&str; 5] = ["B", "KiB", "MiB", "GiB", "TiB"];
let mut n = b;
let mut i = 0;
while n >= 1024.0 && i + 1 < UNITS.len() {
n /= 1024.0;
i += 1;
}
format!("{n:.1} {}", UNITS[i])
}
fn as_percent(v: &serde_json::Value) -> String {
match v.as_f64() {
Some(p) => format!("{p:.1}%"),
None => as_text(v),
}
}
pub fn summary(readings: &[Reading]) -> Vec<Line> {
let mut out = vec![
line(readings, "OS", "system.os.name", as_text),
line(readings, "OS version", "system.os.version", as_text),
line(readings, "OS build", "system.os.build", as_text),
line(readings, "Model", "board.firmware.product", as_text),
line(readings, "Host", "system.hostname", as_text),
line(readings, "Kernel", "system.kernel.version", as_text),
line(readings, "Arch", "system.architecture", as_text),
line(readings, "Uptime", "system.uptime", |v| match v.as_f64() {
Some(s) => {
let secs = s as u64;
format!("{}h {}m", secs / 3600, (secs % 3600) / 60)
}
None => as_text(v),
}),
line(readings, "CPU", "cpu.model", as_text),
line(readings, "Cores", "cpu.cores.physical", as_text),
line(readings, "Threads", "cpu.cores.logical", as_text),
line(readings, "CPU usage", "cpu.total.utilization", as_percent),
line(readings, "Memory", "memory.total", as_bytes),
line(readings, "Mem used", "memory.utilization", as_percent),
];
let mut adapters: BTreeMap<usize, Line> = BTreeMap::new();
for r in readings
.iter()
.filter(|r| r.id.starts_with("gpu.") && r.id.ends_with(".name"))
{
if let Some(n) = r.id.split('.').nth(1).and_then(|s| s.parse::<usize>().ok()) {
adapters.insert(
n,
Line {
label: String::new(),
value: r.value.as_ref().map(as_text),
reason: r.note.clone(),
},
);
}
}
for r in readings {
let index =
r.id.strip_prefix("gpu.")
.and_then(|s| s.strip_suffix(".<unreadable>"))
.and_then(|s| s.parse::<usize>().ok());
if let Some(n) = index {
adapters.entry(n).or_insert_with(|| Line {
label: String::new(),
value: None,
reason: Some(
r.note
.clone()
.unwrap_or_else(|| "this adapter could not be read".to_string()),
),
});
}
}
if adapters.is_empty() {
let backend_failure = readings
.iter()
.find(|r| r.id.starts_with("gpu.backend.") && r.id.ends_with(".<unreadable>"));
let reason = find(readings, "gpu.<unreadable>")
.or(backend_failure)
.or_else(|| find(readings, "gpu.<none>"))
.and_then(|r| r.note.clone())
.unwrap_or_else(|| "no gpu readings in this snapshot".to_string());
out.push(Line {
label: "GPU".into(),
value: None,
reason: Some(reason),
});
} else {
for (n, mut line) in adapters {
line.label = if n == 0 {
"GPU".into()
} else {
format!("GPU {n}")
};
out.push(line);
}
}
out
}
pub fn render_plain(readings: &[Reading], colour: bool) -> String {
let lines = summary(readings);
let width = lines
.iter()
.map(|l| l.label.chars().count())
.max()
.unwrap_or(0);
let mut out = String::new();
for l in &lines {
let label = Colour::Cyan.paint(&l.label, colour);
let pad = width.saturating_sub(l.label.chars().count());
let value = match &l.value {
Some(v) => Colour::White.paint(v, colour),
None => Colour::Grey.paint(&l.render(), colour),
};
out.push_str(&format!(
"{label}{:pad$} {value}
",
"",
pad = pad
));
}
out
}
pub fn render(readings: &[Reading], colour: bool) -> String {
let art = logo();
let lines = summary(readings);
let label_width = lines
.iter()
.map(|l| l.label.chars().count())
.max()
.unwrap_or(0);
let art_width = art_width(&art);
let mut out = String::new();
let rows = art.len().max(lines.len());
for i in 0..rows {
let (art_text, art_colour) = match art.get(i) {
Some(ArtLine(t, c)) => (*t, Some(*c)),
None => ("", None),
};
let pad = art_width.saturating_sub(art_text.chars().count());
let left = match art_colour {
Some(c) => c.paint(art_text, colour),
None => art_text.to_string(),
};
match lines.get(i) {
Some(l) => {
let label = Colour::Cyan.paint(&l.label, colour);
let label_pad = label_width.saturating_sub(l.label.chars().count());
let value = match (&l.value, &l.reason) {
(Some(v), _) => Colour::White.paint(v, colour),
(None, _) => Colour::Grey.paint(&l.render(), colour),
};
out.push_str(&format!(
"{left}{:pad$} {label}{:label_pad$} {value}
",
"",
"",
pad = pad,
label_pad = label_pad
));
}
None => out.push_str(&format!(
"{left}
"
)),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ontology::{Provenance, Unit};
fn measured(id: &str, v: serde_json::Value) -> Reading {
Reading {
id: id.into(),
value: Some(v),
provenance: Provenance::Measured,
unit: Some(Unit::Text),
note: None,
}
}
fn unavailable(id: &str, why: &str) -> Reading {
Reading {
id: id.into(),
value: None,
provenance: Provenance::Unavailable,
unit: None,
note: Some(why.into()),
}
}
#[test]
fn an_unreadable_field_prints_the_reason_rather_than_a_dash() {
let readings = [unavailable(
"cpu.model",
"the platform CPU reader failed: permission denied",
)];
let lines = summary(&readings);
let cpu = lines.iter().find(|l| l.label == "CPU").unwrap();
assert!(cpu.value.is_none());
let rendered = cpu.render();
assert!(
rendered.contains("permission denied"),
"a summary that prints a dash makes a reader guess whether the \
machine lacks the thing or ironmon lacks the reader: {rendered}"
);
}
#[test]
fn no_gpu_and_no_gpu_reader_render_differently() {
let absent = [unavailable("gpu.<none>", "no GPU detected on this machine")];
let unreadable = [unavailable("gpu.<unreadable>", "GPU enumeration failed")];
let a = summary(&absent);
let b = summary(&unreadable);
let ga = a.iter().find(|l| l.label == "GPU").unwrap().render();
let gb = b.iter().find(|l| l.label == "GPU").unwrap().render();
assert_ne!(
ga, gb,
"buying a graphics card and filing a bug are different responses, and \
the summary is where most people will look first"
);
assert!(ga.contains("no GPU detected"));
assert!(gb.contains("enumeration failed"));
}
#[test]
fn a_present_gpu_is_named() {
let readings = [measured("gpu.0.name", serde_json::json!("RTX 4090"))];
let lines = summary(&readings);
let gpu = lines.iter().find(|l| l.label == "GPU").unwrap();
assert_eq!(gpu.value.as_deref(), Some("RTX 4090"));
}
#[test]
fn a_failed_adapter_is_listed_beside_a_readable_one() {
let readings = [
measured("gpu.0.name", serde_json::json!("A")),
unavailable("gpu.1.<unreadable>", "NVML: driver not loaded"),
];
let gpu: Vec<Line> = summary(&readings)
.into_iter()
.filter(|l| l.label.starts_with("GPU"))
.collect();
assert_eq!(gpu.len(), 2, "the failed adapter must not be dropped");
assert_eq!(gpu[1].label, "GPU 1");
assert_eq!(gpu[1].value, None);
assert!(gpu[1].render().contains("NVML: driver not loaded"));
}
#[test]
fn a_failed_backend_is_not_counted_as_a_gpu() {
let beside = [
measured("gpu.0.name", serde_json::json!("A")),
unavailable("gpu.backend.amd.<unreadable>", "ROCm: no HIP runtime"),
];
let gpu: Vec<Line> = summary(&beside)
.into_iter()
.filter(|l| l.label.starts_with("GPU"))
.collect();
assert_eq!(gpu.len(), 1, "the backend row must not become a GPU line");
let alone = [unavailable(
"gpu.backend.amd.<unreadable>",
"ROCm: no HIP runtime",
)];
let gpu: Vec<Line> = summary(&alone)
.into_iter()
.filter(|l| l.label.starts_with("GPU"))
.collect();
assert_eq!(gpu.len(), 1);
assert!(gpu[0].render().contains("ROCm: no HIP runtime"));
}
#[test]
fn a_non_numeric_memory_value_is_shown_not_zeroed() {
let readings = [measured("memory.total", serde_json::json!("unknown size"))];
let mem = summary(&readings)
.into_iter()
.find(|l| l.label == "Memory")
.unwrap();
assert_eq!(mem.value.as_deref(), Some("unknown size"));
}
#[test]
fn several_gpus_are_all_listed() {
let readings = [
measured("gpu.0.name", serde_json::json!("A")),
measured("gpu.1.name", serde_json::json!("B")),
];
let labels: Vec<String> = summary(&readings)
.into_iter()
.filter(|l| l.label.starts_with("GPU"))
.map(|l| l.label)
.collect();
assert_eq!(labels, vec!["GPU", "GPU 1"]);
}
#[test]
fn status_includes_reported_os_version_build_and_hardware_model() {
let readings = [
measured("system.os.name", serde_json::json!("macOS")),
measured("system.os.version", serde_json::json!("test-version")),
measured("system.os.build", serde_json::json!("test-build")),
measured("board.firmware.product", serde_json::json!("Mac mini")),
measured("cpu.model", serde_json::json!("Apple M1")),
];
let text = render_plain(&readings, false);
for value in [
"macOS",
"test-version",
"test-build",
"Mac mini",
"Apple M1",
] {
assert!(text.contains(value), "{text}");
}
}
#[test]
fn a_missing_id_says_so_rather_than_claiming_it_was_unreadable() {
let lines = summary(&[]);
let cpu = lines.iter().find(|l| l.label == "CPU").unwrap();
assert!(cpu.render().contains("not in this snapshot"));
}
#[test]
fn colour_off_produces_plain_text() {
let readings = [measured("cpu.model", serde_json::json!("x"))];
for rendered in [render(&readings, false), render_plain(&readings, false)] {
assert!(
!rendered.contains('\u{1b}'),
"escape codes survived with colour off: {}",
rendered.escape_debug()
);
}
}
#[test]
fn colour_on_closes_every_sequence_it_opens() {
let readings = [measured("cpu.model", serde_json::json!("x"))];
let rendered = render_plain(&readings, true);
assert!(rendered.contains('\u{1b}'));
let opens = rendered.matches("\u{1b}[").count();
let resets = rendered.matches("\u{1b}[0m").count();
assert_eq!(
opens - resets,
resets,
"every opening sequence needs its reset, or colour bleeds into the \
terminal after the command exits"
);
}
#[test]
fn columns_line_up_whether_or_not_colour_is_on() {
let readings = [
measured("cpu.model", serde_json::json!("a")),
measured("system.hostname", serde_json::json!("b")),
];
let plain = render_plain(&readings, false);
let coloured = render_plain(&readings, true);
let stripped: String = {
let mut out = String::new();
let mut chars = coloured.chars();
while let Some(c) = chars.next() {
if c == '\u{1b}' {
for c2 in chars.by_ref() {
if c2 == 'm' {
break;
}
}
} else {
out.push(c);
}
}
out
};
assert_eq!(
stripped, plain,
"colour changed the layout, which means padding was computed over \
escape codes"
);
}
#[test]
fn every_art_line_declares_a_colour_and_has_content() {
let art = logo();
assert!(!art.is_empty(), "this platform has no art at all");
for ArtLine(text, _) in &art {
assert!(!text.is_empty(), "an empty art line renders as a blank row");
}
}
#[test]
fn bytes_render_at_a_readable_scale() {
assert_eq!(as_bytes(&serde_json::json!(1024)), "1.0 KiB");
assert_eq!(as_bytes(&serde_json::json!(1_073_741_824u64)), "1.0 GiB");
assert_eq!(as_bytes(&serde_json::json!(100_547_727_360u64)), "93.6 GiB");
}
#[test]
fn the_logo_and_the_summary_both_survive_being_longer() {
let many: Vec<Reading> = (0..20)
.map(|i| measured(&format!("gpu.{i}.name"), serde_json::json!("G")))
.collect();
let rendered = render(&many, false);
assert!(rendered.lines().count() >= 20);
let none = render(&[], false);
assert!(none.lines().count() >= logo().len());
}
fn declared_readings() -> Vec<Reading> {
crate::ontology::Ontology::build()
.entities
.values()
.map(|e| Reading {
id: e.id.clone(),
value: None,
provenance: crate::ontology::Provenance::Unavailable,
unit: e.unit,
note: None,
})
.collect()
}
#[test]
fn temperature_selection_spans_every_subsystem_that_declares_one() {
let declared = declared_readings();
let temps = temperatures(&declared);
assert!(
!temps.is_empty(),
"the ontology declares temperature entities; none were selected"
);
for r in &temps {
assert_eq!(
r.unit,
Some(crate::ontology::Unit::Celsius),
"{} was selected as a temperature and is not measured in celsius",
r.id
);
}
let prefixes: std::collections::BTreeSet<&str> = temps
.iter()
.filter_map(|r| r.id.split('.').next())
.collect();
assert!(
prefixes.len() > 1,
concat!(
"every temperature came from one subsystem ({:?}). That is what ",
"the defect looked like: the CPU/motherboard reader alone, ",
"reporting no sensors on a machine with GPU and disk sensors ",
"it never consulted."
),
prefixes
);
}
#[test]
fn power_selection_reaches_past_hwmon_rails() {
let declared = declared_readings();
let power = power(&declared);
assert!(
!power.is_empty(),
"the ontology declares power entities; none were selected"
);
assert!(
power.iter().any(|r| r.id.contains(".power.")),
concat!(
"no per-device power reading was selected; `ironmon cli power` ",
"would again report nothing on a platform without hwmon rails"
)
);
}
}