Skip to main content

ankit_builder/
lib.rs

1//! TOML-based Anki deck builder with .apkg generation and AnkiConnect import.
2//!
3//! This crate provides a unified way to define Anki decks using TOML and then either:
4//! - Generate .apkg files for direct import into Anki
5//! - Import directly into a running Anki instance via AnkiConnect
6//!
7//! # Features
8//!
9//! - `apkg` (default): Enable .apkg file generation
10//! - `connect` (default): Enable AnkiConnect import
11//!
12//! # Example TOML Format
13//!
14//! ```toml
15//! [package]
16//! name = "Spanish Vocabulary"
17//! version = "1.0.0"
18//! author = "Your Name"
19//!
20//! [[models]]
21//! name = "Basic Spanish"
22//! fields = ["Spanish", "English", "Example"]
23//!
24//! [[models.templates]]
25//! name = "Spanish -> English"
26//! front = "{{Spanish}}"
27//! back = "{{FrontSide}}<hr>{{English}}"
28//!
29//! [[decks]]
30//! name = "Spanish::Vocabulary"
31//! description = "Core Spanish vocabulary"
32//!
33//! [[notes]]
34//! deck = "Spanish::Vocabulary"
35//! model = "Basic Spanish"
36//! tags = ["chapter1"]
37//!
38//! [notes.fields]
39//! Spanish = "el gato"
40//! English = "the cat"
41//! Example = "El gato es negro."
42//! ```
43//!
44//! # Usage
45//!
46//! ## Generate .apkg file
47//!
48//! ```no_run
49//! use ankit_builder::{DeckDefinition, ApkgBuilder};
50//!
51//! let definition = DeckDefinition::from_file("my_deck.toml").unwrap();
52//! let builder = ApkgBuilder::new(definition);
53//! builder.write_to_file("my_deck.apkg").unwrap();
54//! ```
55//!
56//! ## Import via AnkiConnect
57//!
58//! ```no_run
59//! use ankit_builder::{DeckDefinition, ConnectImporter};
60//!
61//! # async fn example() -> ankit_builder::Result<()> {
62//! let definition = DeckDefinition::from_file("my_deck.toml")?;
63//! let importer = ConnectImporter::new(definition);
64//! let result = importer.import().await?;
65//! println!("Created {} notes", result.notes_created);
66//! # Ok(())
67//! # }
68//! ```
69
70#![warn(missing_docs)]
71#![warn(clippy::all)]
72
73pub mod cloze;
74pub mod error;
75pub mod markdown;
76pub mod schema;
77
78#[cfg(feature = "apkg")]
79mod sql;
80
81#[cfg(feature = "apkg")]
82mod apkg;
83
84#[cfg(feature = "connect")]
85mod connect;
86
87#[cfg(feature = "connect")]
88mod diff;
89
90#[cfg(feature = "connect")]
91mod export;
92
93#[cfg(feature = "connect")]
94mod sync;
95
96pub use error::{Error, Result};
97pub use schema::{DeckDef, DeckDefinition, MediaDef, ModelDef, NoteDef, PackageInfo, TemplateDef};
98
99#[cfg(feature = "apkg")]
100pub use apkg::ApkgBuilder;
101
102#[cfg(feature = "connect")]
103pub use connect::{ConnectImporter, ImportResult};
104
105#[cfg(feature = "connect")]
106pub use diff::{DeckDiff, FieldChange, ModifiedNote, NoteDiff, TagChanges};
107
108#[cfg(feature = "connect")]
109pub use export::DeckExporter;
110
111#[cfg(feature = "connect")]
112pub use sync::{
113    ConflictResolution, ResolvedConflict, SyncConflict, SyncError, SyncNote, SyncPlan, SyncResult,
114    SyncStrategy, SyncedNote,
115};
116
117/// Unified builder that can output to either .apkg or AnkiConnect.
118///
119/// `DeckBuilder` provides a high-level interface for working with deck definitions,
120/// supporting both offline `.apkg` file generation and live import via AnkiConnect.
121///
122/// # Features
123///
124/// - `apkg` (default): Enable `.apkg` file generation via [`write_apkg()`](Self::write_apkg)
125/// - `connect` (default): Enable AnkiConnect import via [`import_connect()`](Self::import_connect)
126///
127/// # Example
128///
129/// ```no_run
130/// use ankit_builder::DeckBuilder;
131///
132/// # fn main() -> ankit_builder::Result<()> {
133/// // Load from TOML file
134/// let builder = DeckBuilder::from_file("vocabulary.toml")?;
135///
136/// // Generate .apkg file
137/// builder.write_apkg("vocabulary.apkg")?;
138/// # Ok(())
139/// # }
140/// ```
141///
142/// # Async Example (AnkiConnect)
143///
144/// ```no_run
145/// use ankit_builder::DeckBuilder;
146///
147/// # async fn example() -> ankit_builder::Result<()> {
148/// let builder = DeckBuilder::from_file("vocabulary.toml")?;
149/// let result = builder.import_connect().await?;
150/// println!("Created {} notes", result.notes_created);
151/// # Ok(())
152/// # }
153/// ```
154pub struct DeckBuilder {
155    definition: DeckDefinition,
156    #[cfg(feature = "apkg")]
157    media_base_path: Option<std::path::PathBuf>,
158}
159
160impl DeckBuilder {
161    /// Create a new builder from a deck definition.
162    ///
163    /// Use this when you have a programmatically constructed [`DeckDefinition`].
164    /// For loading from TOML, prefer [`from_file()`](Self::from_file) or
165    /// [`parse()`](Self::parse).
166    ///
167    /// # Example
168    ///
169    /// ```no_run
170    /// use ankit_builder::DeckBuilder;
171    ///
172    /// // Typically you would load from TOML:
173    /// let builder = DeckBuilder::from_file("deck.toml").unwrap();
174    ///
175    /// // Or parse from a string:
176    /// let toml = r#"
177    /// [package]
178    /// name = "My Deck"
179    /// version = "1.0.0"
180    /// "#;
181    /// let builder = DeckBuilder::parse(toml).unwrap();
182    /// ```
183    pub fn new(definition: DeckDefinition) -> Self {
184        Self {
185            definition,
186            #[cfg(feature = "apkg")]
187            media_base_path: None,
188        }
189    }
190
191    /// Load a deck definition from a TOML file.
192    ///
193    /// # Errors
194    ///
195    /// Returns an error if the file cannot be read or contains invalid TOML.
196    ///
197    /// # Example
198    ///
199    /// ```no_run
200    /// use ankit_builder::DeckBuilder;
201    ///
202    /// # fn main() -> ankit_builder::Result<()> {
203    /// let builder = DeckBuilder::from_file("my_deck.toml")?;
204    /// println!("Loaded deck: {}", builder.definition().package.name);
205    /// # Ok(())
206    /// # }
207    /// ```
208    pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self> {
209        let definition = DeckDefinition::from_file(path)?;
210        Ok(Self::new(definition))
211    }
212
213    /// Load a deck definition from a TOML string.
214    ///
215    /// Useful for testing or when the TOML content is embedded or dynamically generated.
216    ///
217    /// # Errors
218    ///
219    /// Returns an error if the string contains invalid TOML.
220    ///
221    /// # Example
222    ///
223    /// ```
224    /// use ankit_builder::DeckBuilder;
225    ///
226    /// let toml = r#"
227    /// [package]
228    /// name = "Test Deck"
229    /// version = "1.0.0"
230    ///
231    /// [[models]]
232    /// name = "Basic"
233    /// fields = ["Front", "Back"]
234    ///
235    /// [[models.templates]]
236    /// name = "Card 1"
237    /// front = "{{Front}}"
238    /// back = "{{Back}}"
239    ///
240    /// [[decks]]
241    /// name = "Test Deck"
242    /// "#;
243    ///
244    /// let builder = DeckBuilder::parse(toml).unwrap();
245    /// assert_eq!(builder.definition().package.name, "Test Deck");
246    /// ```
247    pub fn parse(content: &str) -> Result<Self> {
248        let definition = DeckDefinition::parse(content)?;
249        Ok(Self::new(definition))
250    }
251
252    /// Set the base path for resolving media file paths.
253    ///
254    /// When your TOML definition references media files with relative paths,
255    /// this sets the directory from which those paths are resolved.
256    ///
257    /// # Example
258    ///
259    /// ```no_run
260    /// use ankit_builder::DeckBuilder;
261    ///
262    /// # fn main() -> ankit_builder::Result<()> {
263    /// let builder = DeckBuilder::from_file("decks/vocabulary.toml")?
264    ///     .media_base_path("decks/media");
265    ///
266    /// // Media files like "audio.mp3" will be loaded from "decks/media/audio.mp3"
267    /// builder.write_apkg("vocabulary.apkg")?;
268    /// # Ok(())
269    /// # }
270    /// ```
271    #[cfg(feature = "apkg")]
272    pub fn media_base_path(mut self, path: impl AsRef<std::path::Path>) -> Self {
273        self.media_base_path = Some(path.as_ref().to_path_buf());
274        self
275    }
276
277    /// Get the underlying deck definition.
278    ///
279    /// Use this to inspect the parsed TOML structure, including package metadata,
280    /// models, decks, and notes.
281    ///
282    /// # Example
283    ///
284    /// ```no_run
285    /// use ankit_builder::DeckBuilder;
286    ///
287    /// # fn main() -> ankit_builder::Result<()> {
288    /// let builder = DeckBuilder::from_file("my_deck.toml")?;
289    /// let def = builder.definition();
290    ///
291    /// println!("Package: {} v{}", def.package.name, def.package.version);
292    /// println!("Models: {}", def.models.len());
293    /// println!("Decks: {}", def.decks.len());
294    /// println!("Notes: {}", def.notes.len());
295    /// # Ok(())
296    /// # }
297    /// ```
298    pub fn definition(&self) -> &DeckDefinition {
299        &self.definition
300    }
301
302    /// Write the deck definition to an `.apkg` file.
303    ///
304    /// Generates a complete Anki package file that can be imported directly
305    /// into Anki via File > Import. The generated file includes all notes,
306    /// cards, and referenced media files.
307    ///
308    /// # Errors
309    ///
310    /// Returns an error if:
311    /// - The output path cannot be written to
312    /// - Media files referenced in the definition cannot be read
313    ///
314    /// # Example
315    ///
316    /// ```no_run
317    /// use ankit_builder::DeckBuilder;
318    ///
319    /// # fn main() -> ankit_builder::Result<()> {
320    /// let builder = DeckBuilder::from_file("vocabulary.toml")?;
321    /// builder.write_apkg("vocabulary.apkg")?;
322    /// println!("Created vocabulary.apkg");
323    /// # Ok(())
324    /// # }
325    /// ```
326    #[cfg(feature = "apkg")]
327    pub fn write_apkg(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
328        let mut builder = ApkgBuilder::new(self.definition.clone());
329        if let Some(ref media_path) = self.media_base_path {
330            builder = builder.media_base_path(media_path);
331        }
332        builder.write_to_file(path)
333    }
334
335    /// Import the deck definition via AnkiConnect.
336    ///
337    /// Imports notes one at a time into a running Anki instance. Creates
338    /// any missing decks automatically.
339    ///
340    /// # Requirements
341    ///
342    /// - Anki must be running with the AnkiConnect add-on installed
343    /// - Note types (models) must already exist in Anki
344    ///
345    /// # Errors
346    ///
347    /// Returns an error if:
348    /// - Cannot connect to Anki (not running or AnkiConnect not installed)
349    /// - A referenced model does not exist in Anki
350    ///
351    /// # Example
352    ///
353    /// ```no_run
354    /// use ankit_builder::DeckBuilder;
355    ///
356    /// # async fn example() -> ankit_builder::Result<()> {
357    /// let builder = DeckBuilder::from_file("vocabulary.toml")?;
358    /// let result = builder.import_connect().await?;
359    ///
360    /// println!("Decks created: {}", result.decks_created);
361    /// println!("Notes created: {}", result.notes_created);
362    /// println!("Notes skipped: {}", result.notes_skipped);
363    /// # Ok(())
364    /// # }
365    /// ```
366    #[cfg(feature = "connect")]
367    pub async fn import_connect(&self) -> Result<ImportResult> {
368        let importer = ConnectImporter::new(self.definition.clone());
369        importer.import().await
370    }
371
372    /// Import the deck definition via AnkiConnect in batch mode.
373    ///
374    /// More efficient than [`import_connect()`](Self::import_connect) for large
375    /// decks as it uses a single API call to add all notes.
376    ///
377    /// # Requirements
378    ///
379    /// - Anki must be running with the AnkiConnect add-on installed
380    /// - Note types (models) must already exist in Anki
381    ///
382    /// # Example
383    ///
384    /// ```no_run
385    /// use ankit_builder::DeckBuilder;
386    ///
387    /// # async fn example() -> ankit_builder::Result<()> {
388    /// let builder = DeckBuilder::from_file("large_deck.toml")?;
389    /// let result = builder.import_connect_batch().await?;
390    /// println!("Imported {} notes", result.notes_created);
391    /// # Ok(())
392    /// # }
393    /// ```
394    #[cfg(feature = "connect")]
395    pub async fn import_connect_batch(&self) -> Result<ImportResult> {
396        let importer = ConnectImporter::new(self.definition.clone());
397        importer.import_batch().await
398    }
399
400    /// Compare the TOML definition against the live state in Anki.
401    ///
402    /// Shows what's different between the TOML definition and Anki:
403    /// - Notes only in TOML (would be added on import)
404    /// - Notes only in Anki (exist in Anki but not in TOML)
405    /// - Modified notes (exist in both but have differences)
406    ///
407    /// Uses the first field value (normalized) as the key for matching notes.
408    ///
409    /// # Requirements
410    ///
411    /// - Anki must be running with the AnkiConnect add-on installed
412    ///
413    /// # Example
414    ///
415    /// ```no_run
416    /// use ankit_builder::DeckBuilder;
417    ///
418    /// # async fn example() -> ankit_builder::Result<()> {
419    /// let builder = DeckBuilder::from_file("deck.toml")?;
420    /// let diff = builder.diff_connect().await?;
421    ///
422    /// println!("Notes only in TOML: {}", diff.toml_only.len());
423    /// println!("Notes only in Anki: {}", diff.anki_only.len());
424    /// println!("Modified notes: {}", diff.modified.len());
425    /// println!("Unchanged notes: {}", diff.unchanged);
426    ///
427    /// for note in &diff.modified {
428    ///     println!("Modified: {} ({} field changes)",
429    ///         note.first_field, note.field_changes.len());
430    /// }
431    /// # Ok(())
432    /// # }
433    /// ```
434    #[cfg(feature = "connect")]
435    pub async fn diff_connect(&self) -> Result<DeckDiff> {
436        let client = ankit::AnkiClient::new();
437        self.diff_connect_with_client(&client).await
438    }
439
440    /// Compare the TOML definition against Anki using a custom client.
441    ///
442    /// Like [`diff_connect()`](Self::diff_connect) but allows using a custom
443    /// [`AnkiClient`](ankit::AnkiClient) with non-default settings.
444    #[cfg(feature = "connect")]
445    pub async fn diff_connect_with_client(&self, client: &ankit::AnkiClient) -> Result<DeckDiff> {
446        let differ = diff::DeckDiffer::new(client, &self.definition);
447        differ.diff().await
448    }
449
450    /// Plan what sync would do without executing it.
451    ///
452    /// Returns a [`SyncPlan`] showing:
453    /// - Notes that would be pushed from TOML to Anki
454    /// - Notes that would be pulled from Anki to TOML
455    /// - Notes that have conflicts (modified in both places)
456    /// - Count of unchanged notes
457    ///
458    /// Use this to preview sync changes before applying them with [`sync()`](Self::sync).
459    ///
460    /// # Requirements
461    ///
462    /// - Anki must be running with the AnkiConnect add-on installed
463    ///
464    /// # Example
465    ///
466    /// ```no_run
467    /// use ankit_builder::DeckBuilder;
468    ///
469    /// # async fn example() -> ankit_builder::Result<()> {
470    /// let builder = DeckBuilder::from_file("deck.toml")?;
471    /// let plan = builder.plan_sync().await?;
472    ///
473    /// println!("Would push: {} notes", plan.to_push.len());
474    /// println!("Would pull: {} notes", plan.to_pull.len());
475    /// println!("Conflicts: {} notes", plan.conflicts.len());
476    /// println!("Unchanged: {} notes", plan.unchanged);
477    /// # Ok(())
478    /// # }
479    /// ```
480    #[cfg(feature = "connect")]
481    pub async fn plan_sync(&self) -> Result<SyncPlan> {
482        let client = ankit::AnkiClient::new();
483        self.plan_sync_with_client(&client).await
484    }
485
486    /// Plan sync using a custom client.
487    ///
488    /// Like [`plan_sync()`](Self::plan_sync) but allows using a custom
489    /// [`AnkiClient`](ankit::AnkiClient) with non-default settings.
490    #[cfg(feature = "connect")]
491    pub async fn plan_sync_with_client(&self, client: &ankit::AnkiClient) -> Result<SyncPlan> {
492        let syncer = sync::DeckSyncer::new(client, self.definition.clone());
493        syncer.plan().await
494    }
495
496    /// Execute bidirectional sync with Anki.
497    ///
498    /// Synchronizes the TOML definition with Anki according to the given strategy:
499    /// - Pushes new notes from TOML to Anki (if `push_new_notes` is true)
500    /// - Pulls new notes from Anki to TOML (if `pull_new_notes` is true)
501    /// - Resolves conflicts according to the conflict resolution strategy
502    ///
503    /// Returns a [`SyncResult`] containing:
504    /// - Notes that were pushed to Anki
505    /// - Notes that were pulled (available in `updated_definition`)
506    /// - Conflicts that were resolved or skipped
507    /// - Any errors that occurred
508    ///
509    /// # Requirements
510    ///
511    /// - Anki must be running with the AnkiConnect add-on installed
512    /// - Note types (models) must exist in Anki for pushing new notes
513    ///
514    /// # Example
515    ///
516    /// ```no_run
517    /// use ankit_builder::{DeckBuilder, SyncStrategy};
518    ///
519    /// # async fn example() -> ankit_builder::Result<()> {
520    /// let builder = DeckBuilder::from_file("deck.toml")?;
521    ///
522    /// // Push-only sync (TOML -> Anki)
523    /// let result = builder.sync(SyncStrategy::push_only()).await?;
524    /// println!("Pushed {} notes", result.pushed.len());
525    ///
526    /// // Pull-only sync (Anki -> TOML)
527    /// let result = builder.sync(SyncStrategy::pull_only()).await?;
528    /// if let Some(updated_def) = result.updated_definition {
529    ///     updated_def.write_toml("deck_updated.toml")?;
530    /// }
531    /// # Ok(())
532    /// # }
533    /// ```
534    #[cfg(feature = "connect")]
535    pub async fn sync(&self, strategy: SyncStrategy) -> Result<SyncResult> {
536        let client = ankit::AnkiClient::new();
537        self.sync_with_client(&client, strategy).await
538    }
539
540    /// Execute sync using a custom client.
541    ///
542    /// Like [`sync()`](Self::sync) but allows using a custom
543    /// [`AnkiClient`](ankit::AnkiClient) with non-default settings.
544    #[cfg(feature = "connect")]
545    pub async fn sync_with_client(
546        &self,
547        client: &ankit::AnkiClient,
548        strategy: SyncStrategy,
549    ) -> Result<SyncResult> {
550        let syncer = sync::DeckSyncer::new(client, self.definition.clone());
551        syncer.sync(strategy).await
552    }
553
554    /// Export a deck from Anki to a [`DeckBuilder`].
555    ///
556    /// Fetches all notes in the specified deck from a running Anki instance
557    /// via AnkiConnect and creates a `DeckBuilder` that can be used to write
558    /// to TOML or .apkg files.
559    ///
560    /// # Requirements
561    ///
562    /// - Anki must be running with the AnkiConnect add-on installed
563    ///
564    /// # Example
565    ///
566    /// ```no_run
567    /// use ankit::AnkiClient;
568    /// use ankit_builder::DeckBuilder;
569    ///
570    /// # async fn example() -> ankit_builder::Result<()> {
571    /// let client = AnkiClient::new();
572    /// let builder = DeckBuilder::from_anki(&client, "Japanese::Vocabulary").await?;
573    ///
574    /// // Write to TOML
575    /// builder.definition().write_toml("japanese.toml")?;
576    ///
577    /// // Or write to .apkg
578    /// builder.write_apkg("japanese.apkg")?;
579    /// # Ok(())
580    /// # }
581    /// ```
582    #[cfg(feature = "connect")]
583    pub async fn from_anki(client: &ankit::AnkiClient, deck_name: &str) -> Result<Self> {
584        let exporter = DeckExporter::new(client);
585        let definition = exporter.export_deck(deck_name).await?;
586        Ok(Self::new(definition))
587    }
588
589    /// Write the deck definition to a TOML file.
590    ///
591    /// Convenience method that calls [`DeckDefinition::write_toml()`].
592    ///
593    /// # Example
594    ///
595    /// ```no_run
596    /// use ankit_builder::DeckBuilder;
597    ///
598    /// # fn main() -> ankit_builder::Result<()> {
599    /// let builder = DeckBuilder::from_file("deck.toml")?;
600    /// builder.write_toml("deck_copy.toml")?;
601    /// # Ok(())
602    /// # }
603    /// ```
604    pub fn write_toml(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
605        self.definition.write_toml(path)
606    }
607}
608
609#[cfg(test)]
610mod tests {
611    use super::*;
612
613    const EXAMPLE_TOML: &str = r#"
614[package]
615name = "Test Deck"
616version = "1.0.0"
617
618[[models]]
619name = "Basic"
620fields = ["Front", "Back"]
621
622[[models.templates]]
623name = "Card 1"
624front = "{{Front}}"
625back = "{{FrontSide}}<hr>{{Back}}"
626
627[[decks]]
628name = "Test Deck"
629description = "A test deck"
630
631[[notes]]
632deck = "Test Deck"
633model = "Basic"
634tags = ["test"]
635
636[notes.fields]
637Front = "What is 2+2?"
638Back = "4"
639
640[[notes]]
641deck = "Test Deck"
642model = "Basic"
643
644[notes.fields]
645Front = "Capital of France?"
646Back = "Paris"
647"#;
648
649    #[test]
650    fn test_deck_builder_parse() {
651        let builder = DeckBuilder::parse(EXAMPLE_TOML).unwrap();
652        assert_eq!(builder.definition().package.name, "Test Deck");
653        assert_eq!(builder.definition().notes.len(), 2);
654    }
655
656    #[test]
657    #[cfg(feature = "apkg")]
658    fn test_write_apkg() {
659        let builder = DeckBuilder::parse(EXAMPLE_TOML).unwrap();
660        let dir = tempfile::tempdir().unwrap();
661        let path = dir.path().join("test.apkg");
662        builder.write_apkg(&path).unwrap();
663        assert!(path.exists());
664    }
665}