Skip to main content

ankit_builder/
diff.rs

1//! Diff TOML definition vs Anki state.
2//!
3//! This module provides functionality to compare a TOML deck definition
4//! against the live state in Anki, showing what's different.
5//!
6//! # Example
7//!
8//! ```no_run
9//! use ankit_builder::DeckBuilder;
10//!
11//! # async fn example() -> ankit_builder::Result<()> {
12//! let builder = DeckBuilder::from_file("deck.toml")?;
13//! let diff = builder.diff_connect().await?;
14//!
15//! println!("Notes only in TOML: {}", diff.toml_only.len());
16//! println!("Notes only in Anki: {}", diff.anki_only.len());
17//! println!("Modified notes: {}", diff.modified.len());
18//! println!("Unchanged notes: {}", diff.unchanged);
19//! # Ok(())
20//! # }
21//! ```
22
23use std::collections::HashMap;
24
25use ankit::AnkiClient;
26use serde::Serialize;
27
28use crate::error::Result;
29use crate::schema::{DeckDefinition, NoteDef};
30
31/// Result of comparing a TOML definition against Anki state.
32#[derive(Debug, Clone, Default, Serialize)]
33pub struct DeckDiff {
34    /// Notes in TOML but not in Anki.
35    pub toml_only: Vec<NoteDiff>,
36    /// Notes in Anki but not in TOML.
37    pub anki_only: Vec<NoteDiff>,
38    /// Notes that exist in both but have differences.
39    pub modified: Vec<ModifiedNote>,
40    /// Number of notes that are identical.
41    pub unchanged: usize,
42}
43
44/// A note that exists in only one place.
45#[derive(Debug, Clone, Serialize)]
46pub struct NoteDiff {
47    /// The note ID (only set for Anki notes).
48    pub note_id: Option<i64>,
49    /// Model (note type) name.
50    pub model: String,
51    /// Deck name.
52    pub deck: String,
53    /// Value of the first field (used as identifier).
54    pub first_field: String,
55    /// Tags on the note.
56    pub tags: Vec<String>,
57}
58
59/// A note that exists in both TOML and Anki but has differences.
60#[derive(Debug, Clone, Serialize)]
61pub struct ModifiedNote {
62    /// The Anki note ID.
63    pub note_id: i64,
64    /// Value of the first field (used as identifier).
65    pub first_field: String,
66    /// Model name.
67    pub model: String,
68    /// Fields that differ between TOML and Anki.
69    pub field_changes: Vec<FieldChange>,
70    /// Tag changes between TOML and Anki.
71    pub tag_changes: TagChanges,
72}
73
74/// A field that differs between TOML and Anki.
75#[derive(Debug, Clone, Serialize)]
76pub struct FieldChange {
77    /// Field name.
78    pub field: String,
79    /// Value in TOML definition.
80    pub toml_value: String,
81    /// Value in Anki.
82    pub anki_value: String,
83}
84
85/// Tag differences between TOML and Anki.
86#[derive(Debug, Clone, Default, Serialize)]
87pub struct TagChanges {
88    /// Tags in TOML but not in Anki.
89    pub added: Vec<String>,
90    /// Tags in Anki but not in TOML.
91    pub removed: Vec<String>,
92}
93
94impl TagChanges {
95    /// Check if there are any tag changes.
96    pub fn is_empty(&self) -> bool {
97        self.added.is_empty() && self.removed.is_empty()
98    }
99}
100
101/// Compares a TOML deck definition against Anki state.
102pub struct DeckDiffer<'a> {
103    client: &'a AnkiClient,
104    definition: &'a DeckDefinition,
105}
106
107impl<'a> DeckDiffer<'a> {
108    /// Create a new differ with the given client and definition.
109    pub fn new(client: &'a AnkiClient, definition: &'a DeckDefinition) -> Self {
110        Self { client, definition }
111    }
112
113    /// Compute the diff between TOML and Anki.
114    ///
115    /// Uses the first field value (normalized) as the key for matching
116    /// notes between TOML and Anki.
117    pub async fn diff(&self) -> Result<DeckDiff> {
118        let mut result = DeckDiff::default();
119
120        // Get all decks in the definition
121        let deck_names: Vec<&str> = self
122            .definition
123            .decks
124            .iter()
125            .map(|d| d.name.as_str())
126            .collect();
127
128        // Build a map of TOML notes by (deck, model, first_field_normalized)
129        let mut toml_notes: HashMap<NoteKey, &NoteDef> = HashMap::new();
130        for note in &self.definition.notes {
131            let model = self.definition.get_model(&note.model);
132            if let Some(model) = model {
133                if let Some(first_field_name) = model.fields.first() {
134                    let first_field_value = note
135                        .fields
136                        .get(first_field_name)
137                        .cloned()
138                        .unwrap_or_default();
139                    let key = NoteKey {
140                        deck: note.deck.clone(),
141                        model: note.model.clone(),
142                        first_field: normalize_key(&first_field_value),
143                    };
144                    toml_notes.insert(key, note);
145                }
146            }
147        }
148
149        // Fetch notes from Anki for each deck
150        let mut anki_notes: HashMap<NoteKey, AnkiNote> = HashMap::new();
151
152        for deck_name in &deck_names {
153            let query = format!("deck:\"{}\"", deck_name);
154            let note_ids = self.client.notes().find(&query).await?;
155
156            if note_ids.is_empty() {
157                continue;
158            }
159
160            let note_infos = self.client.notes().info(&note_ids).await?;
161
162            for note in note_infos {
163                // Get first field value
164                let first_field_value = get_first_field_value(&note.fields);
165                let key = NoteKey {
166                    deck: deck_name.to_string(),
167                    model: note.model_name.clone(),
168                    first_field: normalize_key(&first_field_value),
169                };
170
171                // Convert fields to simple HashMap
172                let fields: HashMap<String, String> = note
173                    .fields
174                    .iter()
175                    .map(|(name, field)| (name.clone(), field.value.clone()))
176                    .collect();
177
178                anki_notes.insert(
179                    key,
180                    AnkiNote {
181                        note_id: note.note_id,
182                        model_name: note.model_name,
183                        fields,
184                        tags: note.tags,
185                        first_field_value,
186                    },
187                );
188            }
189        }
190
191        // Compare TOML notes against Anki
192        for (key, toml_note) in &toml_notes {
193            if let Some(anki_note) = anki_notes.get(key) {
194                // Note exists in both - check for modifications
195                let (field_changes, tag_changes) = self.compare_note(toml_note, anki_note);
196
197                if field_changes.is_empty() && tag_changes.is_empty() {
198                    result.unchanged += 1;
199                } else {
200                    result.modified.push(ModifiedNote {
201                        note_id: anki_note.note_id,
202                        first_field: anki_note.first_field_value.clone(),
203                        model: anki_note.model_name.clone(),
204                        field_changes,
205                        tag_changes,
206                    });
207                }
208            } else {
209                // Note only in TOML
210                let model = self.definition.get_model(&toml_note.model);
211                let first_field = if let Some(model) = model {
212                    model
213                        .fields
214                        .first()
215                        .and_then(|f| toml_note.fields.get(f))
216                        .cloned()
217                        .unwrap_or_default()
218                } else {
219                    String::new()
220                };
221
222                result.toml_only.push(NoteDiff {
223                    note_id: None,
224                    model: toml_note.model.clone(),
225                    deck: toml_note.deck.clone(),
226                    first_field,
227                    tags: toml_note.tags.clone(),
228                });
229            }
230        }
231
232        // Find notes only in Anki
233        for (key, anki_note) in &anki_notes {
234            if !toml_notes.contains_key(key) {
235                result.anki_only.push(NoteDiff {
236                    note_id: Some(anki_note.note_id),
237                    model: anki_note.model_name.clone(),
238                    deck: key.deck.clone(),
239                    first_field: anki_note.first_field_value.clone(),
240                    tags: anki_note.tags.clone(),
241                });
242            }
243        }
244
245        Ok(result)
246    }
247
248    /// Compare a TOML note against an Anki note.
249    fn compare_note(
250        &self,
251        toml_note: &NoteDef,
252        anki_note: &AnkiNote,
253    ) -> (Vec<FieldChange>, TagChanges) {
254        let mut field_changes = Vec::new();
255
256        // Compare fields
257        let model = self.definition.get_model(&toml_note.model);
258        if let Some(model) = model {
259            for field_name in &model.fields {
260                let toml_value = toml_note
261                    .fields
262                    .get(field_name)
263                    .cloned()
264                    .unwrap_or_default();
265                let anki_value = anki_note
266                    .fields
267                    .get(field_name)
268                    .cloned()
269                    .unwrap_or_default();
270
271                if toml_value != anki_value {
272                    field_changes.push(FieldChange {
273                        field: field_name.clone(),
274                        toml_value,
275                        anki_value,
276                    });
277                }
278            }
279        }
280
281        // Compare tags
282        let toml_tags: std::collections::HashSet<_> = toml_note.tags.iter().collect();
283        let anki_tags: std::collections::HashSet<_> = anki_note.tags.iter().collect();
284
285        let added: Vec<String> = toml_tags
286            .difference(&anki_tags)
287            .map(|s| (*s).clone())
288            .collect();
289        let removed: Vec<String> = anki_tags
290            .difference(&toml_tags)
291            .map(|s| (*s).clone())
292            .collect();
293
294        let tag_changes = TagChanges { added, removed };
295
296        (field_changes, tag_changes)
297    }
298}
299
300/// Key for identifying a note (deck + model + first field).
301#[derive(Debug, Clone, Hash, Eq, PartialEq)]
302struct NoteKey {
303    deck: String,
304    model: String,
305    first_field: String,
306}
307
308/// Temporary struct for Anki note data.
309struct AnkiNote {
310    note_id: i64,
311    model_name: String,
312    fields: HashMap<String, String>,
313    tags: Vec<String>,
314    first_field_value: String,
315}
316
317/// Normalize a key value for comparison.
318///
319/// - Trims whitespace
320/// - Converts to lowercase
321/// - Strips HTML tags
322fn normalize_key(value: &str) -> String {
323    let trimmed = value.trim();
324    let lower = trimmed.to_lowercase();
325    strip_html(&lower)
326}
327
328/// Strip HTML tags from a string.
329fn strip_html(s: &str) -> String {
330    let mut result = String::with_capacity(s.len());
331    let mut in_tag = false;
332
333    for c in s.chars() {
334        match c {
335            '<' => in_tag = true,
336            '>' => in_tag = false,
337            _ if !in_tag => result.push(c),
338            _ => {}
339        }
340    }
341
342    result
343}
344
345/// Get the first field value from a note's fields map.
346fn get_first_field_value(fields: &HashMap<String, ankit::NoteField>) -> String {
347    // Find the field with order 0
348    fields
349        .values()
350        .find(|f| f.order == 0)
351        .map(|f| f.value.clone())
352        .unwrap_or_default()
353}
354
355#[cfg(test)]
356mod tests {
357    use super::*;
358
359    #[test]
360    fn test_normalize_key() {
361        assert_eq!(normalize_key("  Hello World  "), "hello world");
362        assert_eq!(normalize_key("<b>Bold</b>"), "bold");
363        assert_eq!(normalize_key("  <i>Italic</i>  "), "italic");
364    }
365
366    #[test]
367    fn test_normalize_key_nested_html() {
368        assert_eq!(normalize_key("<div><p>Nested</p></div>"), "nested");
369        assert_eq!(normalize_key("<a href='url'>Link</a>"), "link");
370    }
371
372    #[test]
373    fn test_normalize_key_empty() {
374        assert_eq!(normalize_key(""), "");
375        assert_eq!(normalize_key("   "), "");
376        assert_eq!(normalize_key("<>"), "");
377    }
378
379    #[test]
380    fn test_strip_html() {
381        assert_eq!(strip_html("<p>Hello</p>"), "Hello");
382        assert_eq!(strip_html("<b>Bold</b> text"), "Bold text");
383        assert_eq!(strip_html("No tags"), "No tags");
384    }
385
386    #[test]
387    fn test_strip_html_unclosed_tags() {
388        assert_eq!(strip_html("<p>Unclosed"), "Unclosed");
389        assert_eq!(strip_html("Text<br>More"), "TextMore");
390    }
391
392    #[test]
393    fn test_strip_html_attributes() {
394        assert_eq!(strip_html("<a href=\"url\">Link</a>"), "Link");
395        assert_eq!(
396            strip_html("<div class=\"foo\" id=\"bar\">Content</div>"),
397            "Content"
398        );
399    }
400
401    #[test]
402    fn test_tag_changes_is_empty() {
403        let empty = TagChanges::default();
404        assert!(empty.is_empty());
405
406        let with_added = TagChanges {
407            added: vec!["new".to_string()],
408            removed: vec![],
409        };
410        assert!(!with_added.is_empty());
411
412        let with_removed = TagChanges {
413            added: vec![],
414            removed: vec!["old".to_string()],
415        };
416        assert!(!with_removed.is_empty());
417    }
418
419    #[test]
420    fn test_tag_changes_both() {
421        let both = TagChanges {
422            added: vec!["new".to_string()],
423            removed: vec!["old".to_string()],
424        };
425        assert!(!both.is_empty());
426    }
427
428    #[test]
429    fn test_deck_diff_default() {
430        let diff = DeckDiff::default();
431        assert!(diff.toml_only.is_empty());
432        assert!(diff.anki_only.is_empty());
433        assert!(diff.modified.is_empty());
434        assert_eq!(diff.unchanged, 0);
435    }
436
437    #[test]
438    fn test_note_diff_construction() {
439        let note = NoteDiff {
440            note_id: Some(12345),
441            model: "Basic".to_string(),
442            deck: "Test".to_string(),
443            first_field: "Question".to_string(),
444            tags: vec!["tag1".to_string(), "tag2".to_string()],
445        };
446
447        assert_eq!(note.note_id, Some(12345));
448        assert_eq!(note.model, "Basic");
449        assert_eq!(note.deck, "Test");
450        assert_eq!(note.first_field, "Question");
451        assert_eq!(note.tags.len(), 2);
452    }
453
454    #[test]
455    fn test_field_change_construction() {
456        let change = FieldChange {
457            field: "Back".to_string(),
458            toml_value: "TOML answer".to_string(),
459            anki_value: "Anki answer".to_string(),
460        };
461
462        assert_eq!(change.field, "Back");
463        assert_eq!(change.toml_value, "TOML answer");
464        assert_eq!(change.anki_value, "Anki answer");
465    }
466
467    #[test]
468    fn test_modified_note_construction() {
469        let modified = ModifiedNote {
470            note_id: 67890,
471            first_field: "Word".to_string(),
472            model: "Vocabulary".to_string(),
473            field_changes: vec![FieldChange {
474                field: "Definition".to_string(),
475                toml_value: "new def".to_string(),
476                anki_value: "old def".to_string(),
477            }],
478            tag_changes: TagChanges {
479                added: vec!["updated".to_string()],
480                removed: vec![],
481            },
482        };
483
484        assert_eq!(modified.note_id, 67890);
485        assert_eq!(modified.first_field, "Word");
486        assert_eq!(modified.model, "Vocabulary");
487        assert_eq!(modified.field_changes.len(), 1);
488        assert!(!modified.tag_changes.is_empty());
489    }
490
491    #[test]
492    fn test_note_key_equality() {
493        let key1 = NoteKey {
494            deck: "Test".to_string(),
495            model: "Basic".to_string(),
496            first_field: "hello".to_string(),
497        };
498
499        let key2 = NoteKey {
500            deck: "Test".to_string(),
501            model: "Basic".to_string(),
502            first_field: "hello".to_string(),
503        };
504
505        let key3 = NoteKey {
506            deck: "Test".to_string(),
507            model: "Basic".to_string(),
508            first_field: "world".to_string(),
509        };
510
511        assert_eq!(key1, key2);
512        assert_ne!(key1, key3);
513    }
514
515    #[test]
516    fn test_note_key_hash() {
517        use std::collections::HashSet;
518
519        let key1 = NoteKey {
520            deck: "Test".to_string(),
521            model: "Basic".to_string(),
522            first_field: "hello".to_string(),
523        };
524
525        let key2 = NoteKey {
526            deck: "Test".to_string(),
527            model: "Basic".to_string(),
528            first_field: "hello".to_string(),
529        };
530
531        let mut set = HashSet::new();
532        set.insert(key1);
533        assert!(set.contains(&key2));
534    }
535}