Skip to main content

fetchium_core/monitor/
diff.rs

1//! Content diff computation using the `similar` crate (Phase 5, PRD §10, Mode G).
2
3use serde::{Deserialize, Serialize};
4use similar::{ChangeTag, TextDiff};
5
6/// A single line change in a content diff.
7#[derive(Debug, Clone, Serialize, Deserialize)]
8pub enum DiffLine {
9    Added(String),
10    Removed(String),
11    Equal(String),
12}
13
14/// The result of a content diff comparison.
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct ContentDiff {
17    /// Number of added lines.
18    pub additions: usize,
19    /// Number of removed lines.
20    pub deletions: usize,
21    /// Similarity ratio between old and new content (0.0 = totally different, 1.0 = identical).
22    pub similarity: f32,
23    /// Sequence of line changes.
24    pub changes: Vec<DiffLine>,
25}
26
27impl ContentDiff {
28    /// Whether there were any meaningful changes.
29    pub fn has_changes(&self) -> bool {
30        self.additions > 0 || self.deletions > 0
31    }
32
33    /// Render the diff as a unified-diff-style string.
34    pub fn to_unified_string(&self) -> String {
35        let mut out = String::new();
36        for change in &self.changes {
37            match change {
38                DiffLine::Added(line) => out.push_str(&format!("+ {line}")),
39                DiffLine::Removed(line) => out.push_str(&format!("- {line}")),
40                DiffLine::Equal(_) => {} // omit unchanged lines for brevity
41            }
42        }
43        out
44    }
45}
46
47/// Compute a human-readable diff between two content strings (line-based).
48pub fn compute_diff(old: &str, new: &str) -> ContentDiff {
49    let diff = TextDiff::from_lines(old, new);
50    let mut additions = 0usize;
51    let mut deletions = 0usize;
52    let mut changes = Vec::new();
53
54    for change in diff.iter_all_changes() {
55        let line = change.to_string();
56        match change.tag() {
57            ChangeTag::Insert => {
58                additions += 1;
59                changes.push(DiffLine::Added(line));
60            }
61            ChangeTag::Delete => {
62                deletions += 1;
63                changes.push(DiffLine::Removed(line));
64            }
65            ChangeTag::Equal => {
66                changes.push(DiffLine::Equal(line));
67            }
68        }
69    }
70
71    ContentDiff {
72        additions,
73        deletions,
74        similarity: diff.ratio(),
75        changes,
76    }
77}
78
79/// Compute a summary diff showing only changed sections (context = 2 lines).
80pub fn compute_diff_summary(old: &str, new: &str) -> ContentDiff {
81    let diff = TextDiff::from_lines(old, new);
82    let mut additions = 0usize;
83    let mut deletions = 0usize;
84    let mut changes = Vec::new();
85
86    for change in diff.iter_all_changes() {
87        let line = change.to_string();
88        match change.tag() {
89            ChangeTag::Insert => {
90                additions += 1;
91                changes.push(DiffLine::Added(line));
92            }
93            ChangeTag::Delete => {
94                deletions += 1;
95                changes.push(DiffLine::Removed(line));
96            }
97            ChangeTag::Equal => {} // skip unchanged in summary mode
98        }
99    }
100
101    ContentDiff {
102        additions,
103        deletions,
104        similarity: diff.ratio(),
105        changes,
106    }
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112
113    #[test]
114    fn identical_content_no_changes() {
115        let diff = compute_diff("line one\nline two\n", "line one\nline two\n");
116        assert!(!diff.has_changes());
117        assert!((diff.similarity - 1.0).abs() < 0.01);
118        assert_eq!(diff.additions, 0);
119        assert_eq!(diff.deletions, 0);
120    }
121
122    #[test]
123    fn single_line_addition() {
124        let diff = compute_diff("line one\n", "line one\nline two\n");
125        assert!(diff.has_changes());
126        assert_eq!(diff.additions, 1);
127        assert_eq!(diff.deletions, 0);
128    }
129
130    #[test]
131    fn single_line_deletion() {
132        let diff = compute_diff("line one\nline two\n", "line one\n");
133        assert!(diff.has_changes());
134        assert_eq!(diff.additions, 0);
135        assert_eq!(diff.deletions, 1);
136    }
137
138    #[test]
139    fn completely_different_low_similarity() {
140        let diff = compute_diff("aaaa bbbb cccc", "xxxx yyyy zzzz");
141        assert!(diff.similarity < 0.5, "similarity={}", diff.similarity);
142    }
143
144    #[test]
145    fn unified_string_shows_added_removed() {
146        let diff = compute_diff("old line\n", "new line\n");
147        let s = diff.to_unified_string();
148        assert!(s.contains("- ") || s.contains("+ "));
149    }
150}