Skip to main content

surjection_core/store/
diff.rs

1//! Diffs between two store revisions (SPEC 9.3).
2//!
3//! - **Semantic**: per entity, the fields added, removed or changed
4//!   (`env.GITHUB_TOOLSETS: "repos" -> "repos,issues"`). TOML files are
5//!   compared field by field (tables, inline ones included, flattened to
6//!   dotted paths; arrays as one value); references are shown as written,
7//!   since the store holds references only. Other text (skill content) is
8//!   a unified diff.
9//! - **Raw**: the unified git diff.
10
11use std::collections::BTreeMap;
12use std::fmt::Write as _;
13use std::path::Path;
14
15use git2::{DiffFormat, DiffOptions, Tree};
16use similar::TextDiff;
17
18use crate::error::CoreError;
19use crate::store::{CommitId, Store, git_error};
20
21/// How an entity file changed.
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum ChangeKind {
24    Added,
25    Removed,
26    Changed,
27}
28
29impl ChangeKind {
30    pub const fn as_str(self) -> &'static str {
31        match self {
32            ChangeKind::Added => "added",
33            ChangeKind::Removed => "removed",
34            ChangeKind::Changed => "changed",
35        }
36    }
37}
38
39/// One field of a TOML entity: absent on the side that lacks it. Values
40/// are TOML text (`"repos"`, `["-y", "pkg"]`, `60`).
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct FieldChange {
43    /// Dotted path (`env.GITHUB_TOOLSETS`, `secrets.GITHUB_PAT.ref`).
44    pub field: String,
45    pub before: Option<String>,
46    pub after: Option<String>,
47}
48
49/// One changed store file, named by its entity.
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct EntityChange {
52    /// `server/github`, `secrets`, `skill/review`, `machine/<id>`, or the
53    /// file name for files of no entity.
54    pub entity: String,
55    /// Store-relative file.
56    pub file: String,
57    pub kind: ChangeKind,
58    /// Field changes of a TOML file.
59    pub fields: Vec<FieldChange>,
60    /// Unified diff of a file that is not TOML (or does not parse); a note
61    /// for binary content.
62    pub text: Option<String>,
63}
64
65/// The entity a store file belongs to (the `Surjection-Entity` trailer
66/// value); the file name for store-level files.
67pub fn entity_of(file: &str) -> String {
68    let mut parts = file.split('/');
69    let first = parts.next().unwrap_or_default();
70    let second = parts.next();
71    let stem = |name: &str| name.strip_suffix(".toml").unwrap_or(name).to_owned();
72    match (first, second) {
73        ("servers", Some(name)) => format!("server/{}", stem(name)),
74        ("skill-meta", Some(name)) => format!("skill/{}", stem(name)),
75        ("skills", Some(id)) => format!("skill/{id}"),
76        ("projects", Some(id)) => format!("project/{id}"),
77        ("machines", Some(name)) => {
78            let name = name.strip_suffix(".applied.toml").unwrap_or(name);
79            format!("machine/{}", stem(name))
80        }
81        (name, None) => stem(name),
82        _ => file.to_owned(),
83    }
84}
85
86/// The `Surjection-Entity` trailers of a commit changing `files`: each known
87/// entity once, in file order.
88pub fn trailer_entities(files: &[String]) -> Vec<String> {
89    let mut entities: Vec<String> = Vec::new();
90    for file in files {
91        let entity = entity_of(file);
92        if !crate::store::entity_paths(&entity).is_empty() && !entities.contains(&entity) {
93            entities.push(entity);
94        }
95    }
96    entities
97}
98
99impl Store<'_> {
100    /// The semantic diff from `from` (`None`: the empty store) to `to`,
101    /// ordered by file.
102    pub fn semantic_diff(
103        &self,
104        from: Option<&CommitId>,
105        to: &CommitId,
106    ) -> Result<Vec<EntityChange>, CoreError> {
107        let old = from.map(|id| self.revision(id)).transpose()?;
108        let new = self.revision(to)?;
109        let mut changes = Vec::new();
110        for file in self.changed_between(from, to)? {
111            let before = match &old {
112                Some(old) => old.read_bytes(&file)?,
113                None => None,
114            };
115            let after = new.read_bytes(&file)?;
116            changes.push(file_change(&file, before.as_deref(), after.as_deref()));
117        }
118        Ok(changes)
119    }
120
121    /// The unified git diff from `from` (`None`: the empty store) to `to`.
122    pub fn raw_diff(&self, from: Option<&CommitId>, to: &CommitId) -> Result<String, CoreError> {
123        let old = self.tree_of(from)?;
124        let new = self.tree_of(Some(to))?;
125        let diff = self
126            .repo
127            .diff_tree_to_tree(old.as_ref(), new.as_ref(), Some(&mut DiffOptions::new()))
128            .map_err(git_error)?;
129        let mut out = Vec::new();
130        diff.print(DiffFormat::Patch, |_, _, line| {
131            if matches!(line.origin(), '+' | '-' | ' ') {
132                out.push(line.origin() as u8);
133            }
134            out.extend_from_slice(line.content());
135            true
136        })
137        .map_err(git_error)?;
138        Ok(String::from_utf8_lossy(&out).into_owned())
139    }
140
141    /// Files that differ between `from` (`None`: the empty store) and `to`.
142    fn changed_between(
143        &self,
144        from: Option<&CommitId>,
145        to: &CommitId,
146    ) -> Result<Vec<String>, CoreError> {
147        match from {
148            Some(from) => self.changed_files(from, to),
149            None => self.revision(to)?.files(),
150        }
151    }
152
153    fn tree_of(&self, id: Option<&CommitId>) -> Result<Option<Tree<'_>>, CoreError> {
154        let Some(id) = id else {
155            return Ok(None);
156        };
157        let oid = git2::Oid::from_str(id.as_str()).map_err(git_error)?;
158        let commit = self.repo.find_commit(oid).map_err(git_error)?;
159        commit.tree().map(Some).map_err(git_error)
160    }
161}
162
163fn file_change(file: &str, before: Option<&[u8]>, after: Option<&[u8]>) -> EntityChange {
164    let kind = match (before, after) {
165        (None, _) => ChangeKind::Added,
166        (_, None) => ChangeKind::Removed,
167        _ => ChangeKind::Changed,
168    };
169    let mut change = EntityChange {
170        entity: entity_of(file),
171        file: file.to_owned(),
172        kind,
173        fields: Vec::new(),
174        text: None,
175    };
176    let text = |bytes: Option<&[u8]>| -> Option<Option<String>> {
177        match bytes {
178            None => Some(None),
179            Some(bytes) => std::str::from_utf8(bytes).ok().map(|s| Some(s.to_owned())),
180        }
181    };
182    let (Some(old), Some(new)) = (text(before), text(after)) else {
183        change.text = Some("binary file changed".to_owned());
184        return change;
185    };
186    if Path::new(file).extension().is_some_and(|ext| ext == "toml") {
187        let parse = |text: &Option<String>| -> Option<BTreeMap<String, String>> {
188            match text {
189                None => Some(BTreeMap::new()),
190                Some(text) => text
191                    .parse::<toml::Table>()
192                    .ok()
193                    .map(|table| flatten(&table)),
194            }
195        };
196        if let (Some(old_fields), Some(new_fields)) = (parse(&old), parse(&new)) {
197            change.fields = field_changes(&old_fields, &new_fields);
198            if change.fields.is_empty() {
199                change.text = Some("only comments or formatting changed".to_owned());
200            }
201            return change;
202        }
203    }
204    let (old, new) = (old.unwrap_or_default(), new.unwrap_or_default());
205    change.text = Some(
206        TextDiff::from_lines(&old, &new)
207            .unified_diff()
208            .context_radius(3)
209            .header(&format!("a/{file}"), &format!("b/{file}"))
210            .to_string(),
211    );
212    change
213}
214
215/// Leaves of `table` by dotted path; arrays and inline values are leaves.
216fn flatten(table: &toml::Table) -> BTreeMap<String, String> {
217    fn walk(prefix: &str, table: &toml::Table, out: &mut BTreeMap<String, String>) {
218        for (key, value) in table {
219            let path = if prefix.is_empty() {
220                key_text(key)
221            } else {
222                format!("{prefix}.{}", key_text(key))
223            };
224            match value {
225                toml::Value::Table(inner) => walk(&path, inner, out),
226                other => {
227                    out.insert(path, other.to_string());
228                }
229            }
230        }
231    }
232    let mut out = BTreeMap::new();
233    walk("", table, &mut out);
234    out
235}
236
237/// A key as written in a dotted path: bare when it can be, else quoted.
238fn key_text(key: &str) -> String {
239    let bare = !key.is_empty()
240        && key
241            .bytes()
242            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-');
243    if bare {
244        key.to_owned()
245    } else {
246        toml::Value::String(key.to_owned()).to_string()
247    }
248}
249
250fn field_changes(
251    old: &BTreeMap<String, String>,
252    new: &BTreeMap<String, String>,
253) -> Vec<FieldChange> {
254    let mut paths: Vec<&String> = old.keys().chain(new.keys()).collect();
255    paths.sort();
256    paths.dedup();
257    paths
258        .into_iter()
259        .filter(|path| old.get(*path) != new.get(*path))
260        .map(|path| FieldChange {
261            field: path.clone(),
262            before: old.get(path).cloned(),
263            after: new.get(path).cloned(),
264        })
265        .collect()
266}
267
268/// The changes as text, one block per file:
269///
270/// ```text
271/// server/github: changed (servers/github.toml)
272///   env.GITHUB_TOOLSETS: "repos" -> "repos,issues"
273///   + tags = ["dev"]
274///   - description = "Old"
275/// ```
276pub fn render(changes: &[EntityChange]) -> String {
277    let mut out = String::new();
278    for change in changes {
279        let _ = writeln!(
280            out,
281            "{}: {} ({})",
282            change.entity,
283            change.kind.as_str(),
284            change.file
285        );
286        for field in &change.fields {
287            let _ = match (&field.before, &field.after) {
288                (Some(before), Some(after)) => {
289                    writeln!(out, "  {}: {before} -> {after}", field.field)
290                }
291                (None, Some(after)) => writeln!(out, "  + {} = {after}", field.field),
292                (Some(before), None) => writeln!(out, "  - {} = {before}", field.field),
293                (None, None) => Ok(()),
294            };
295        }
296        if let Some(text) = &change.text {
297            for line in text.lines() {
298                let _ = writeln!(out, "  {line}");
299            }
300        }
301    }
302    out
303}