use std::path::Path;
use std::time::SystemTime;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Baseline {
LastSave,
SessionStart,
GitHead,
}
impl Baseline {
pub const ALL: [Baseline; 3] = [Baseline::LastSave, Baseline::SessionStart, Baseline::GitHead];
pub fn title(self) -> &'static str {
match self {
Baseline::LastSave => "Since the last save",
Baseline::SessionStart => "Since the session started",
Baseline::GitHead => "Since the last commit",
}
}
}
pub fn is_json(path: &Path) -> bool {
path.extension().is_some_and(|e| e == "json")
}
pub fn read(path: &Path) -> (String, Option<SystemTime>) {
(std::fs::read_to_string(path).unwrap_or_default(), std::fs::metadata(path).and_then(|m| m.modified()).ok())
}
pub fn git_head(path: &Path) -> Option<String> {
let dir = path.parent()?;
let name = path.file_name()?.to_str()?;
let out =
std::process::Command::new("git").arg("-C").arg(dir).arg("show").arg(format!("HEAD:./{name}")).output().ok()?;
out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned())
}
fn sorted(value: serde_json::Value) -> serde_json::Value {
use serde_json::Value;
match value {
Value::Object(map) => {
let mut entries: Vec<(String, Value)> = map.into_iter().map(|(k, v)| (k, sorted(v))).collect();
entries.sort_by(|a, b| a.0.cmp(&b.0));
Value::Object(entries.into_iter().collect())
}
Value::Array(items) => Value::Array(items.into_iter().map(sorted).collect()),
other => other,
}
}
pub fn normalise(text: &str, json: bool) -> String {
if json && let Ok(v) = serde_json::from_str::<serde_json::Value>(text) {
let mut s = serde_json::to_string_pretty(&sorted(v)).unwrap_or_default();
s.push('\n');
return s;
}
text.to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn json_compares_by_key() {
let a = normalise(r#"{"b":1,"a":2}"#, true);
let b = normalise("{\n \"a\": 2,\n \"b\": 1\n}", true);
assert_eq!(a, b, "reordered keys are not changes");
assert_eq!(normalise("not json", true), "not json");
assert!(is_json(Path::new("session.json")) && !is_json(Path::new("notes.md")));
assert_eq!(Baseline::ALL.len(), 3);
}
}