Skip to main content

ankit_builder/
export.rs

1//! Export decks from Anki to TOML format.
2//!
3//! This module provides functionality to pull decks from Anki via AnkiConnect
4//! and export them to the TOML format used by ankit-builder.
5//!
6//! # Example
7//!
8//! ```no_run
9//! use ankit::AnkiClient;
10//! use ankit_builder::DeckExporter;
11//!
12//! # async fn example() -> ankit_builder::Result<()> {
13//! let client = AnkiClient::new();
14//! let exporter = DeckExporter::new(&client);
15//!
16//! // Export a deck to DeckDefinition
17//! let definition = exporter.export_deck("Japanese::Vocabulary").await?;
18//!
19//! // Write to TOML file
20//! definition.write_toml("japanese.toml")?;
21//! # Ok(())
22//! # }
23//! ```
24
25use std::collections::{HashMap, HashSet};
26use std::path::Path;
27
28use ankit::AnkiClient;
29
30use crate::error::{Error, Result};
31use crate::schema::{DeckDef, DeckDefinition, ModelDef, NoteDef, PackageInfo, TemplateDef};
32
33/// Exports decks from Anki to TOML format.
34///
35/// Uses AnkiConnect to fetch deck contents and convert them to a
36/// [`DeckDefinition`] that can be serialized to TOML.
37pub struct DeckExporter<'a> {
38    client: &'a AnkiClient,
39}
40
41impl<'a> DeckExporter<'a> {
42    /// Create a new exporter with the given AnkiConnect client.
43    pub fn new(client: &'a AnkiClient) -> Self {
44        Self { client }
45    }
46
47    /// Export a deck to a [`DeckDefinition`].
48    ///
49    /// Fetches all notes in the specified deck, along with the models (note types)
50    /// they use, and converts them to a TOML-compatible definition.
51    ///
52    /// # Arguments
53    ///
54    /// * `deck_name` - The name of the deck to export (supports hierarchical names like "Parent::Child")
55    ///
56    /// # Example
57    ///
58    /// ```no_run
59    /// use ankit::AnkiClient;
60    /// use ankit_builder::DeckExporter;
61    ///
62    /// # async fn example() -> ankit_builder::Result<()> {
63    /// let client = AnkiClient::new();
64    /// let exporter = DeckExporter::new(&client);
65    ///
66    /// let definition = exporter.export_deck("My Deck").await?;
67    /// println!("Exported {} notes", definition.notes.len());
68    /// # Ok(())
69    /// # }
70    /// ```
71    pub async fn export_deck(&self, deck_name: &str) -> Result<DeckDefinition> {
72        // Find all notes in the deck
73        let query = format!("deck:\"{}\"", deck_name);
74        let note_ids = self.client.notes().find(&query).await?;
75
76        if note_ids.is_empty() {
77            // Return empty definition with just the deck
78            return Ok(DeckDefinition {
79                package: PackageInfo {
80                    name: deck_name.to_string(),
81                    version: "1.0.0".to_string(),
82                    author: None,
83                    description: None,
84                },
85                models: Vec::new(),
86                decks: vec![DeckDef {
87                    name: deck_name.to_string(),
88                    description: None,
89                    id: None,
90                }],
91                notes: Vec::new(),
92                media: Vec::new(),
93            });
94        }
95
96        // Get note info
97        let note_infos = self.client.notes().info(&note_ids).await?;
98
99        // Collect unique model names
100        let model_names: HashSet<String> =
101            note_infos.iter().map(|n| n.model_name.clone()).collect();
102
103        // Fetch model details
104        let mut models = Vec::new();
105        for model_name in &model_names {
106            let model_def = self.fetch_model(model_name).await?;
107            models.push(model_def);
108        }
109
110        // Convert notes to NoteDef
111        let notes: Vec<NoteDef> = note_infos
112            .iter()
113            .map(|note| {
114                let fields: HashMap<String, String> = note
115                    .fields
116                    .iter()
117                    .map(|(name, field)| (name.clone(), field.value.clone()))
118                    .collect();
119
120                NoteDef {
121                    deck: deck_name.to_string(),
122                    model: note.model_name.clone(),
123                    fields,
124                    tags: note.tags.clone(),
125                    guid: None,
126                    note_id: Some(note.note_id),
127                }
128            })
129            .collect();
130
131        Ok(DeckDefinition {
132            package: PackageInfo {
133                name: deck_name.to_string(),
134                version: "1.0.0".to_string(),
135                author: None,
136                description: None,
137            },
138            models,
139            decks: vec![DeckDef {
140                name: deck_name.to_string(),
141                description: None,
142                id: None,
143            }],
144            notes,
145            media: Vec::new(),
146        })
147    }
148
149    /// Export multiple decks to a single [`DeckDefinition`].
150    ///
151    /// Useful for exporting a parent deck and its children, or a set of related decks.
152    ///
153    /// # Arguments
154    ///
155    /// * `deck_names` - The names of the decks to export
156    /// * `package_name` - The name for the package (used in `[package]` section)
157    ///
158    /// # Example
159    ///
160    /// ```no_run
161    /// use ankit::AnkiClient;
162    /// use ankit_builder::DeckExporter;
163    ///
164    /// # async fn example() -> ankit_builder::Result<()> {
165    /// let client = AnkiClient::new();
166    /// let exporter = DeckExporter::new(&client);
167    ///
168    /// let definition = exporter
169    ///     .export_decks(&["Japanese::N5", "Japanese::N4"], "Japanese JLPT")
170    ///     .await?;
171    /// # Ok(())
172    /// # }
173    /// ```
174    pub async fn export_decks(
175        &self,
176        deck_names: &[&str],
177        package_name: &str,
178    ) -> Result<DeckDefinition> {
179        let mut all_notes = Vec::new();
180        let mut model_names: HashSet<String> = HashSet::new();
181        let mut decks = Vec::new();
182
183        for deck_name in deck_names {
184            // Find all notes in this deck
185            let query = format!("deck:\"{}\"", deck_name);
186            let note_ids = self.client.notes().find(&query).await?;
187
188            // Add deck to list
189            decks.push(DeckDef {
190                name: deck_name.to_string(),
191                description: None,
192                id: None,
193            });
194
195            if note_ids.is_empty() {
196                continue;
197            }
198
199            // Get note info
200            let note_infos = self.client.notes().info(&note_ids).await?;
201
202            // Collect model names
203            for note in &note_infos {
204                model_names.insert(note.model_name.clone());
205            }
206
207            // Convert notes
208            for note in note_infos {
209                let fields: HashMap<String, String> = note
210                    .fields
211                    .iter()
212                    .map(|(name, field)| (name.clone(), field.value.clone()))
213                    .collect();
214
215                all_notes.push(NoteDef {
216                    deck: deck_name.to_string(),
217                    model: note.model_name.clone(),
218                    fields,
219                    tags: note.tags,
220                    guid: None,
221                    note_id: Some(note.note_id),
222                });
223            }
224        }
225
226        // Fetch model details
227        let mut models = Vec::new();
228        for model_name in &model_names {
229            let model_def = self.fetch_model(model_name).await?;
230            models.push(model_def);
231        }
232
233        Ok(DeckDefinition {
234            package: PackageInfo {
235                name: package_name.to_string(),
236                version: "1.0.0".to_string(),
237                author: None,
238                description: None,
239            },
240            models,
241            decks,
242            notes: all_notes,
243            media: Vec::new(),
244        })
245    }
246
247    /// Fetch model definition from Anki.
248    async fn fetch_model(&self, model_name: &str) -> Result<ModelDef> {
249        // Get field names
250        let fields = self.client.models().field_names(model_name).await?;
251
252        // Get templates
253        let templates_map = self.client.models().templates(model_name).await?;
254        let templates: Vec<TemplateDef> = templates_map
255            .into_iter()
256            .map(|(name, template)| TemplateDef {
257                name,
258                front: template.front,
259                back: template.back,
260            })
261            .collect();
262
263        // Get CSS styling
264        let styling = self.client.models().styling(model_name).await?;
265        let css = if styling.css.is_empty() {
266            None
267        } else {
268            Some(styling.css)
269        };
270
271        Ok(ModelDef {
272            name: model_name.to_string(),
273            fields,
274            templates,
275            css,
276            sort_field: None,
277            id: None,
278            markdown_fields: vec![],
279            model_type: None,
280        })
281    }
282}
283
284impl DeckDefinition {
285    /// Write the deck definition to a TOML file.
286    ///
287    /// # Example
288    ///
289    /// ```no_run
290    /// use ankit_builder::DeckDefinition;
291    ///
292    /// # fn example() -> ankit_builder::Result<()> {
293    /// let definition = DeckDefinition::from_file("input.toml")?;
294    /// // ... modify definition ...
295    /// definition.write_toml("output.toml")?;
296    /// # Ok(())
297    /// # }
298    /// ```
299    pub fn write_toml(&self, path: impl AsRef<Path>) -> Result<()> {
300        let content = self.to_toml()?;
301        std::fs::write(path, content)?;
302        Ok(())
303    }
304
305    /// Serialize the deck definition to a TOML string.
306    ///
307    /// # Example
308    ///
309    /// ```no_run
310    /// use ankit_builder::DeckDefinition;
311    ///
312    /// # fn example() -> ankit_builder::Result<()> {
313    /// let definition = DeckDefinition::from_file("input.toml")?;
314    /// let toml_string = definition.to_toml()?;
315    /// println!("{}", toml_string);
316    /// # Ok(())
317    /// # }
318    /// ```
319    pub fn to_toml(&self) -> Result<String> {
320        toml::to_string_pretty(self).map_err(|e| Error::TomlSerialize(e.to_string()))
321    }
322}
323
324#[cfg(test)]
325mod tests {
326    use super::*;
327
328    #[test]
329    fn test_to_toml_roundtrip() {
330        let toml_input = r#"
331[package]
332name = "Test Deck"
333version = "1.0.0"
334
335[[models]]
336name = "Basic"
337fields = ["Front", "Back"]
338
339[[models.templates]]
340name = "Card 1"
341front = "{{Front}}"
342back = "{{Back}}"
343
344[[decks]]
345name = "Test Deck"
346
347[[notes]]
348deck = "Test Deck"
349model = "Basic"
350tags = ["test"]
351
352[notes.fields]
353Front = "Question"
354Back = "Answer"
355"#;
356
357        let definition = DeckDefinition::parse(toml_input).unwrap();
358        let toml_output = definition.to_toml().unwrap();
359
360        // Parse the output and verify it matches
361        let definition2 = DeckDefinition::parse(&toml_output).unwrap();
362        assert_eq!(definition.package.name, definition2.package.name);
363        assert_eq!(definition.models.len(), definition2.models.len());
364        assert_eq!(definition.notes.len(), definition2.notes.len());
365    }
366
367    #[test]
368    fn test_note_id_serialization() {
369        let toml_input = r#"
370[package]
371name = "Test"
372version = "1.0.0"
373
374[[models]]
375name = "Basic"
376fields = ["Front", "Back"]
377
378[[models.templates]]
379name = "Card 1"
380front = "{{Front}}"
381back = "{{Back}}"
382
383[[decks]]
384name = "Test"
385
386[[notes]]
387deck = "Test"
388model = "Basic"
389note_id = 1234567890
390
391[notes.fields]
392Front = "Q"
393Back = "A"
394"#;
395
396        // Parse TOML with note_id
397        let definition = DeckDefinition::parse(toml_input).unwrap();
398        assert_eq!(definition.notes[0].note_id, Some(1234567890));
399
400        // Serialize and verify note_id is preserved
401        let toml_output = definition.to_toml().unwrap();
402        assert!(
403            toml_output.contains("note_id = 1234567890"),
404            "note_id should be in output: {}",
405            toml_output
406        );
407
408        // Roundtrip
409        let definition2 = DeckDefinition::parse(&toml_output).unwrap();
410        assert_eq!(definition2.notes[0].note_id, Some(1234567890));
411    }
412
413    #[test]
414    fn test_note_id_omitted_when_none() {
415        let toml_input = r#"
416[package]
417name = "Test"
418version = "1.0.0"
419
420[[models]]
421name = "Basic"
422fields = ["Front", "Back"]
423
424[[models.templates]]
425name = "Card 1"
426front = "{{Front}}"
427back = "{{Back}}"
428
429[[decks]]
430name = "Test"
431
432[[notes]]
433deck = "Test"
434model = "Basic"
435
436[notes.fields]
437Front = "Q"
438Back = "A"
439"#;
440
441        let definition = DeckDefinition::parse(toml_input).unwrap();
442        assert_eq!(definition.notes[0].note_id, None);
443
444        // Serialize and verify note_id is NOT in output
445        let toml_output = definition.to_toml().unwrap();
446        assert!(
447            !toml_output.contains("note_id"),
448            "note_id should be omitted when None: {}",
449            toml_output
450        );
451    }
452}