use std::process::Command;
use anyhow::{bail, Context, Result};
use chrono::TimeZone;
pub const UNITS: [&str; 2] = ["scx_loader.service", "scx.service"];
pub struct LogLine {
pub time: String,
pub priority: u8,
pub text: String,
pub continuation: bool,
}
pub fn fetch(unit: &str, previous_boot: bool) -> Result<Vec<LogLine>> {
let boot = if previous_boot { "-1" } else { "0" };
let output = Command::new("journalctl")
.args([
"--unit",
unit,
"--boot",
boot,
"--output=json",
"--no-pager",
"--quiet",
])
.output()
.context("failed to run journalctl — is this a systemd system?")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let stderr = stderr.trim();
bail!(
"journalctl failed{}{}",
if stderr.is_empty() { "" } else { ": " },
stderr
);
}
let stdout = String::from_utf8_lossy(&output.stdout);
Ok(parse_entries(&stdout))
}
fn parse_entries(stdout: &str) -> Vec<LogLine> {
let mut lines = Vec::new();
for raw in stdout.lines() {
if raw.is_empty() {
continue;
}
let Ok(entry) = serde_json::from_str::<serde_json::Value>(raw) else {
continue;
};
let priority = entry
.get("PRIORITY")
.and_then(|p| p.as_str())
.and_then(|p| p.parse().ok())
.unwrap_or(6);
let time = entry
.get("__REALTIME_TIMESTAMP")
.and_then(|t| t.as_str())
.and_then(|t| t.parse::<i64>().ok())
.map(format_local_time)
.unwrap_or_default();
let message = match entry.get("MESSAGE") {
Some(serde_json::Value::String(s)) => s.clone(),
Some(serde_json::Value::Array(bytes)) => {
let raw: Vec<u8> = bytes
.iter()
.filter_map(|b| b.as_u64().and_then(|b| u8::try_from(b).ok()))
.collect();
String::from_utf8_lossy(&raw).into_owned()
}
_ => continue,
};
for (i, text) in message.lines().enumerate() {
lines.push(LogLine {
time: if i == 0 { time.clone() } else { String::new() },
priority,
text: text.to_owned(),
continuation: i > 0,
});
}
}
lines
}
fn format_local_time(usec: i64) -> String {
chrono::Local
.timestamp_opt(usec / 1_000_000, 0)
.single()
.map(|dt| dt.format("%H:%M:%S").to_string())
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_priority_with_info_default() {
let entries = parse_entries(concat!(
r#"{"PRIORITY":"3","MESSAGE":"boom"}"#,
"\n",
r#"{"MESSAGE":"plain"}"#,
));
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].priority, 3);
assert_eq!(entries[1].priority, 6);
}
#[test]
fn flattens_multiline_messages() {
let entries = parse_entries(
r#"{"PRIORITY":"6","MESSAGE":"Opts {\n verbose: 0,\n}","__REALTIME_TIMESTAMP":"1753000000000000"}"#,
);
assert_eq!(entries.len(), 3);
assert!(!entries[0].continuation);
assert!(entries[1].continuation && entries[2].continuation);
assert!(entries[1].time.is_empty());
assert_eq!(entries[1].text, " verbose: 0,");
assert_eq!(entries[2].priority, 6);
}
#[test]
fn decodes_byte_array_messages() {
let entries = parse_entries(r#"{"MESSAGE":[104,105]}"#);
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].text, "hi");
}
#[test]
fn skips_malformed_and_empty_lines() {
let entries = parse_entries("not json\n\n{\"MESSAGE\":\"ok\"}\n{\"NO_MESSAGE\":true}");
assert_eq!(entries.len(), 1);
assert_eq!(entries[0].text, "ok");
}
}