Skip to main content

kitchen_services/
changes.rs

1//! What the Changes panel compares: the files that say what a project is and how its analysis
2//! was done (`session.json`, `pipeline.json`, `project.json`), read and normalised, and what they
3//! are compared against ([`Baseline`]). kitchen-shell's `ChangesPanel` draws the diffs.
4
5use std::path::Path;
6use std::time::SystemTime;
7
8/// What the watched files are compared against.
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
10pub enum Baseline {
11    /// The files as last saved.
12    LastSave,
13    /// The files when the agent session started.
14    SessionStart,
15    /// The files in the last git commit (when the project is a repository).
16    GitHead,
17}
18
19impl Baseline {
20    /// Every baseline, in the menu's order.
21    pub const ALL: [Baseline; 3] = [Baseline::LastSave, Baseline::SessionStart, Baseline::GitHead];
22
23    /// As the menu says it.
24    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
33/// Whether `path` is JSON (compared by key, not by line order).
34pub fn is_json(path: &Path) -> bool {
35    path.extension().is_some_and(|e| e == "json")
36}
37
38/// The file's text (empty when it cannot be read) and when it was last modified.
39pub 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
43/// The file in the last commit of the repository it is in (`None` when it is not in one, or not
44/// committed).
45pub 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
53/// `value` with every object's keys sorted, whatever order serde_json keeps keys in (its
54/// `preserve_order` feature, turned on by another crate in a larger build, keeps them as read).
55fn 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
68/// `text` as pretty JSON with sorted keys when it is JSON, else as is (so a proposal and the file
69/// compare line by line, and the accepted hunks make a valid file).
70pub 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}