kitchen_services/
changes.rs1use std::path::Path;
6use std::time::SystemTime;
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum Baseline {
11 LastSave,
13 SessionStart,
15 GitHead,
17}
18
19impl Baseline {
20 pub const ALL: [Baseline; 3] = [Baseline::LastSave, Baseline::SessionStart, Baseline::GitHead];
22
23 pub fn title(self) -> &'static str {
25 match self {
26 Baseline::LastSave => "Since the last save",
27 Baseline::SessionStart => "Since the session started",
28 Baseline::GitHead => "Since the last commit",
29 }
30 }
31}
32
33pub fn is_json(path: &Path) -> bool {
35 path.extension().is_some_and(|e| e == "json")
36}
37
38pub fn read(path: &Path) -> (String, Option<SystemTime>) {
40 (std::fs::read_to_string(path).unwrap_or_default(), std::fs::metadata(path).and_then(|m| m.modified()).ok())
41}
42
43pub fn git_head(path: &Path) -> Option<String> {
46 let dir = path.parent()?;
47 let name = path.file_name()?.to_str()?;
48 let out =
49 std::process::Command::new("git").arg("-C").arg(dir).arg("show").arg(format!("HEAD:./{name}")).output().ok()?;
50 out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned())
51}
52
53fn sorted(value: serde_json::Value) -> serde_json::Value {
56 use serde_json::Value;
57 match value {
58 Value::Object(map) => {
59 let mut entries: Vec<(String, Value)> = map.into_iter().map(|(k, v)| (k, sorted(v))).collect();
60 entries.sort_by(|a, b| a.0.cmp(&b.0));
61 Value::Object(entries.into_iter().collect())
62 }
63 Value::Array(items) => Value::Array(items.into_iter().map(sorted).collect()),
64 other => other,
65 }
66}
67
68pub fn normalise(text: &str, json: bool) -> String {
71 if json && let Ok(v) = serde_json::from_str::<serde_json::Value>(text) {
72 let mut s = serde_json::to_string_pretty(&sorted(v)).unwrap_or_default();
73 s.push('\n');
74 return s;
75 }
76 text.to_string()
77}
78
79#[cfg(test)]
80mod tests {
81 use super::*;
82
83 #[test]
84 fn json_compares_by_key() {
85 let a = normalise(r#"{"b":1,"a":2}"#, true);
86 let b = normalise("{\n \"a\": 2,\n \"b\": 1\n}", true);
87 assert_eq!(a, b, "reordered keys are not changes");
88 assert_eq!(normalise("not json", true), "not json");
89 assert!(is_json(Path::new("session.json")) && !is_json(Path::new("notes.md")));
90 assert_eq!(Baseline::ALL.len(), 3);
91 }
92}