ankit-builder 0.1.0

TOML-based Anki deck builder with .apkg generation and AnkiConnect import
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
//! TOML-based Anki deck builder with .apkg generation and AnkiConnect import.
//!
//! This crate provides a unified way to define Anki decks using TOML and then either:
//! - Generate .apkg files for direct import into Anki
//! - Import directly into a running Anki instance via AnkiConnect
//!
//! # Features
//!
//! - `apkg` (default): Enable .apkg file generation
//! - `connect` (default): Enable AnkiConnect import
//!
//! # Example TOML Format
//!
//! ```toml
//! [package]
//! name = "Spanish Vocabulary"
//! version = "1.0.0"
//! author = "Your Name"
//!
//! [[models]]
//! name = "Basic Spanish"
//! fields = ["Spanish", "English", "Example"]
//!
//! [[models.templates]]
//! name = "Spanish -> English"
//! front = "{{Spanish}}"
//! back = "{{FrontSide}}<hr>{{English}}"
//!
//! [[decks]]
//! name = "Spanish::Vocabulary"
//! description = "Core Spanish vocabulary"
//!
//! [[notes]]
//! deck = "Spanish::Vocabulary"
//! model = "Basic Spanish"
//! tags = ["chapter1"]
//!
//! [notes.fields]
//! Spanish = "el gato"
//! English = "the cat"
//! Example = "El gato es negro."
//! ```
//!
//! # Usage
//!
//! ## Generate .apkg file
//!
//! ```no_run
//! use ankit_builder::{DeckDefinition, ApkgBuilder};
//!
//! let definition = DeckDefinition::from_file("my_deck.toml").unwrap();
//! let builder = ApkgBuilder::new(definition);
//! builder.write_to_file("my_deck.apkg").unwrap();
//! ```
//!
//! ## Import via AnkiConnect
//!
//! ```no_run
//! use ankit_builder::{DeckDefinition, ConnectImporter};
//!
//! # async fn example() -> ankit_builder::Result<()> {
//! let definition = DeckDefinition::from_file("my_deck.toml")?;
//! let importer = ConnectImporter::new(definition);
//! let result = importer.import().await?;
//! println!("Created {} notes", result.notes_created);
//! # Ok(())
//! # }
//! ```

#![warn(missing_docs)]
#![warn(clippy::all)]

pub mod cloze;
pub mod error;
pub mod markdown;
pub mod schema;

#[cfg(feature = "apkg")]
mod sql;

#[cfg(feature = "apkg")]
mod apkg;

#[cfg(feature = "connect")]
mod connect;

#[cfg(feature = "connect")]
mod diff;

#[cfg(feature = "connect")]
mod export;

#[cfg(feature = "connect")]
mod sync;

pub use error::{Error, Result};
pub use schema::{DeckDef, DeckDefinition, MediaDef, ModelDef, NoteDef, PackageInfo, TemplateDef};

#[cfg(feature = "apkg")]
pub use apkg::ApkgBuilder;

#[cfg(feature = "connect")]
pub use connect::{ConnectImporter, ImportResult};

#[cfg(feature = "connect")]
pub use diff::{DeckDiff, FieldChange, ModifiedNote, NoteDiff, TagChanges};

#[cfg(feature = "connect")]
pub use export::DeckExporter;

#[cfg(feature = "connect")]
pub use sync::{
    ConflictResolution, ResolvedConflict, SyncConflict, SyncError, SyncNote, SyncPlan, SyncResult,
    SyncStrategy, SyncedNote,
};

/// Unified builder that can output to either .apkg or AnkiConnect.
///
/// `DeckBuilder` provides a high-level interface for working with deck definitions,
/// supporting both offline `.apkg` file generation and live import via AnkiConnect.
///
/// # Features
///
/// - `apkg` (default): Enable `.apkg` file generation via [`write_apkg()`](Self::write_apkg)
/// - `connect` (default): Enable AnkiConnect import via [`import_connect()`](Self::import_connect)
///
/// # Example
///
/// ```no_run
/// use ankit_builder::DeckBuilder;
///
/// # fn main() -> ankit_builder::Result<()> {
/// // Load from TOML file
/// let builder = DeckBuilder::from_file("vocabulary.toml")?;
///
/// // Generate .apkg file
/// builder.write_apkg("vocabulary.apkg")?;
/// # Ok(())
/// # }
/// ```
///
/// # Async Example (AnkiConnect)
///
/// ```no_run
/// use ankit_builder::DeckBuilder;
///
/// # async fn example() -> ankit_builder::Result<()> {
/// let builder = DeckBuilder::from_file("vocabulary.toml")?;
/// let result = builder.import_connect().await?;
/// println!("Created {} notes", result.notes_created);
/// # Ok(())
/// # }
/// ```
pub struct DeckBuilder {
    definition: DeckDefinition,
    #[cfg(feature = "apkg")]
    media_base_path: Option<std::path::PathBuf>,
}

impl DeckBuilder {
    /// Create a new builder from a deck definition.
    ///
    /// Use this when you have a programmatically constructed [`DeckDefinition`].
    /// For loading from TOML, prefer [`from_file()`](Self::from_file) or
    /// [`parse()`](Self::parse).
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ankit_builder::DeckBuilder;
    ///
    /// // Typically you would load from TOML:
    /// let builder = DeckBuilder::from_file("deck.toml").unwrap();
    ///
    /// // Or parse from a string:
    /// let toml = r#"
    /// [package]
    /// name = "My Deck"
    /// version = "1.0.0"
    /// "#;
    /// let builder = DeckBuilder::parse(toml).unwrap();
    /// ```
    pub fn new(definition: DeckDefinition) -> Self {
        Self {
            definition,
            #[cfg(feature = "apkg")]
            media_base_path: None,
        }
    }

    /// Load a deck definition from a TOML file.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be read or contains invalid TOML.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ankit_builder::DeckBuilder;
    ///
    /// # fn main() -> ankit_builder::Result<()> {
    /// let builder = DeckBuilder::from_file("my_deck.toml")?;
    /// println!("Loaded deck: {}", builder.definition().package.name);
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self> {
        let definition = DeckDefinition::from_file(path)?;
        Ok(Self::new(definition))
    }

    /// Load a deck definition from a TOML string.
    ///
    /// Useful for testing or when the TOML content is embedded or dynamically generated.
    ///
    /// # Errors
    ///
    /// Returns an error if the string contains invalid TOML.
    ///
    /// # Example
    ///
    /// ```
    /// use ankit_builder::DeckBuilder;
    ///
    /// let toml = r#"
    /// [package]
    /// name = "Test Deck"
    /// version = "1.0.0"
    ///
    /// [[models]]
    /// name = "Basic"
    /// fields = ["Front", "Back"]
    ///
    /// [[models.templates]]
    /// name = "Card 1"
    /// front = "{{Front}}"
    /// back = "{{Back}}"
    ///
    /// [[decks]]
    /// name = "Test Deck"
    /// "#;
    ///
    /// let builder = DeckBuilder::parse(toml).unwrap();
    /// assert_eq!(builder.definition().package.name, "Test Deck");
    /// ```
    pub fn parse(content: &str) -> Result<Self> {
        let definition = DeckDefinition::parse(content)?;
        Ok(Self::new(definition))
    }

    /// Set the base path for resolving media file paths.
    ///
    /// When your TOML definition references media files with relative paths,
    /// this sets the directory from which those paths are resolved.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ankit_builder::DeckBuilder;
    ///
    /// # fn main() -> ankit_builder::Result<()> {
    /// let builder = DeckBuilder::from_file("decks/vocabulary.toml")?
    ///     .media_base_path("decks/media");
    ///
    /// // Media files like "audio.mp3" will be loaded from "decks/media/audio.mp3"
    /// builder.write_apkg("vocabulary.apkg")?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "apkg")]
    pub fn media_base_path(mut self, path: impl AsRef<std::path::Path>) -> Self {
        self.media_base_path = Some(path.as_ref().to_path_buf());
        self
    }

    /// Get the underlying deck definition.
    ///
    /// Use this to inspect the parsed TOML structure, including package metadata,
    /// models, decks, and notes.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ankit_builder::DeckBuilder;
    ///
    /// # fn main() -> ankit_builder::Result<()> {
    /// let builder = DeckBuilder::from_file("my_deck.toml")?;
    /// let def = builder.definition();
    ///
    /// println!("Package: {} v{}", def.package.name, def.package.version);
    /// println!("Models: {}", def.models.len());
    /// println!("Decks: {}", def.decks.len());
    /// println!("Notes: {}", def.notes.len());
    /// # Ok(())
    /// # }
    /// ```
    pub fn definition(&self) -> &DeckDefinition {
        &self.definition
    }

    /// Write the deck definition to an `.apkg` file.
    ///
    /// Generates a complete Anki package file that can be imported directly
    /// into Anki via File > Import. The generated file includes all notes,
    /// cards, and referenced media files.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The output path cannot be written to
    /// - Media files referenced in the definition cannot be read
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ankit_builder::DeckBuilder;
    ///
    /// # fn main() -> ankit_builder::Result<()> {
    /// let builder = DeckBuilder::from_file("vocabulary.toml")?;
    /// builder.write_apkg("vocabulary.apkg")?;
    /// println!("Created vocabulary.apkg");
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "apkg")]
    pub fn write_apkg(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
        let mut builder = ApkgBuilder::new(self.definition.clone());
        if let Some(ref media_path) = self.media_base_path {
            builder = builder.media_base_path(media_path);
        }
        builder.write_to_file(path)
    }

    /// Import the deck definition via AnkiConnect.
    ///
    /// Imports notes one at a time into a running Anki instance. Creates
    /// any missing decks automatically.
    ///
    /// # Requirements
    ///
    /// - Anki must be running with the AnkiConnect add-on installed
    /// - Note types (models) must already exist in Anki
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Cannot connect to Anki (not running or AnkiConnect not installed)
    /// - A referenced model does not exist in Anki
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ankit_builder::DeckBuilder;
    ///
    /// # async fn example() -> ankit_builder::Result<()> {
    /// let builder = DeckBuilder::from_file("vocabulary.toml")?;
    /// let result = builder.import_connect().await?;
    ///
    /// println!("Decks created: {}", result.decks_created);
    /// println!("Notes created: {}", result.notes_created);
    /// println!("Notes skipped: {}", result.notes_skipped);
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "connect")]
    pub async fn import_connect(&self) -> Result<ImportResult> {
        let importer = ConnectImporter::new(self.definition.clone());
        importer.import().await
    }

    /// Import the deck definition via AnkiConnect in batch mode.
    ///
    /// More efficient than [`import_connect()`](Self::import_connect) for large
    /// decks as it uses a single API call to add all notes.
    ///
    /// # Requirements
    ///
    /// - Anki must be running with the AnkiConnect add-on installed
    /// - Note types (models) must already exist in Anki
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ankit_builder::DeckBuilder;
    ///
    /// # async fn example() -> ankit_builder::Result<()> {
    /// let builder = DeckBuilder::from_file("large_deck.toml")?;
    /// let result = builder.import_connect_batch().await?;
    /// println!("Imported {} notes", result.notes_created);
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "connect")]
    pub async fn import_connect_batch(&self) -> Result<ImportResult> {
        let importer = ConnectImporter::new(self.definition.clone());
        importer.import_batch().await
    }

    /// Compare the TOML definition against the live state in Anki.
    ///
    /// Shows what's different between the TOML definition and Anki:
    /// - Notes only in TOML (would be added on import)
    /// - Notes only in Anki (exist in Anki but not in TOML)
    /// - Modified notes (exist in both but have differences)
    ///
    /// Uses the first field value (normalized) as the key for matching notes.
    ///
    /// # Requirements
    ///
    /// - Anki must be running with the AnkiConnect add-on installed
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ankit_builder::DeckBuilder;
    ///
    /// # async fn example() -> ankit_builder::Result<()> {
    /// let builder = DeckBuilder::from_file("deck.toml")?;
    /// let diff = builder.diff_connect().await?;
    ///
    /// println!("Notes only in TOML: {}", diff.toml_only.len());
    /// println!("Notes only in Anki: {}", diff.anki_only.len());
    /// println!("Modified notes: {}", diff.modified.len());
    /// println!("Unchanged notes: {}", diff.unchanged);
    ///
    /// for note in &diff.modified {
    ///     println!("Modified: {} ({} field changes)",
    ///         note.first_field, note.field_changes.len());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "connect")]
    pub async fn diff_connect(&self) -> Result<DeckDiff> {
        let client = ankit::AnkiClient::new();
        self.diff_connect_with_client(&client).await
    }

    /// Compare the TOML definition against Anki using a custom client.
    ///
    /// Like [`diff_connect()`](Self::diff_connect) but allows using a custom
    /// [`AnkiClient`](ankit::AnkiClient) with non-default settings.
    #[cfg(feature = "connect")]
    pub async fn diff_connect_with_client(&self, client: &ankit::AnkiClient) -> Result<DeckDiff> {
        let differ = diff::DeckDiffer::new(client, &self.definition);
        differ.diff().await
    }

    /// Plan what sync would do without executing it.
    ///
    /// Returns a [`SyncPlan`] showing:
    /// - Notes that would be pushed from TOML to Anki
    /// - Notes that would be pulled from Anki to TOML
    /// - Notes that have conflicts (modified in both places)
    /// - Count of unchanged notes
    ///
    /// Use this to preview sync changes before applying them with [`sync()`](Self::sync).
    ///
    /// # Requirements
    ///
    /// - Anki must be running with the AnkiConnect add-on installed
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ankit_builder::DeckBuilder;
    ///
    /// # async fn example() -> ankit_builder::Result<()> {
    /// let builder = DeckBuilder::from_file("deck.toml")?;
    /// let plan = builder.plan_sync().await?;
    ///
    /// println!("Would push: {} notes", plan.to_push.len());
    /// println!("Would pull: {} notes", plan.to_pull.len());
    /// println!("Conflicts: {} notes", plan.conflicts.len());
    /// println!("Unchanged: {} notes", plan.unchanged);
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "connect")]
    pub async fn plan_sync(&self) -> Result<SyncPlan> {
        let client = ankit::AnkiClient::new();
        self.plan_sync_with_client(&client).await
    }

    /// Plan sync using a custom client.
    ///
    /// Like [`plan_sync()`](Self::plan_sync) but allows using a custom
    /// [`AnkiClient`](ankit::AnkiClient) with non-default settings.
    #[cfg(feature = "connect")]
    pub async fn plan_sync_with_client(&self, client: &ankit::AnkiClient) -> Result<SyncPlan> {
        let syncer = sync::DeckSyncer::new(client, self.definition.clone());
        syncer.plan().await
    }

    /// Execute bidirectional sync with Anki.
    ///
    /// Synchronizes the TOML definition with Anki according to the given strategy:
    /// - Pushes new notes from TOML to Anki (if `push_new_notes` is true)
    /// - Pulls new notes from Anki to TOML (if `pull_new_notes` is true)
    /// - Resolves conflicts according to the conflict resolution strategy
    ///
    /// Returns a [`SyncResult`] containing:
    /// - Notes that were pushed to Anki
    /// - Notes that were pulled (available in `updated_definition`)
    /// - Conflicts that were resolved or skipped
    /// - Any errors that occurred
    ///
    /// # Requirements
    ///
    /// - Anki must be running with the AnkiConnect add-on installed
    /// - Note types (models) must exist in Anki for pushing new notes
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ankit_builder::{DeckBuilder, SyncStrategy};
    ///
    /// # async fn example() -> ankit_builder::Result<()> {
    /// let builder = DeckBuilder::from_file("deck.toml")?;
    ///
    /// // Push-only sync (TOML -> Anki)
    /// let result = builder.sync(SyncStrategy::push_only()).await?;
    /// println!("Pushed {} notes", result.pushed.len());
    ///
    /// // Pull-only sync (Anki -> TOML)
    /// let result = builder.sync(SyncStrategy::pull_only()).await?;
    /// if let Some(updated_def) = result.updated_definition {
    ///     updated_def.write_toml("deck_updated.toml")?;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "connect")]
    pub async fn sync(&self, strategy: SyncStrategy) -> Result<SyncResult> {
        let client = ankit::AnkiClient::new();
        self.sync_with_client(&client, strategy).await
    }

    /// Execute sync using a custom client.
    ///
    /// Like [`sync()`](Self::sync) but allows using a custom
    /// [`AnkiClient`](ankit::AnkiClient) with non-default settings.
    #[cfg(feature = "connect")]
    pub async fn sync_with_client(
        &self,
        client: &ankit::AnkiClient,
        strategy: SyncStrategy,
    ) -> Result<SyncResult> {
        let syncer = sync::DeckSyncer::new(client, self.definition.clone());
        syncer.sync(strategy).await
    }

    /// Export a deck from Anki to a [`DeckBuilder`].
    ///
    /// Fetches all notes in the specified deck from a running Anki instance
    /// via AnkiConnect and creates a `DeckBuilder` that can be used to write
    /// to TOML or .apkg files.
    ///
    /// # Requirements
    ///
    /// - Anki must be running with the AnkiConnect add-on installed
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ankit::AnkiClient;
    /// use ankit_builder::DeckBuilder;
    ///
    /// # async fn example() -> ankit_builder::Result<()> {
    /// let client = AnkiClient::new();
    /// let builder = DeckBuilder::from_anki(&client, "Japanese::Vocabulary").await?;
    ///
    /// // Write to TOML
    /// builder.definition().write_toml("japanese.toml")?;
    ///
    /// // Or write to .apkg
    /// builder.write_apkg("japanese.apkg")?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "connect")]
    pub async fn from_anki(client: &ankit::AnkiClient, deck_name: &str) -> Result<Self> {
        let exporter = DeckExporter::new(client);
        let definition = exporter.export_deck(deck_name).await?;
        Ok(Self::new(definition))
    }

    /// Write the deck definition to a TOML file.
    ///
    /// Convenience method that calls [`DeckDefinition::write_toml()`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ankit_builder::DeckBuilder;
    ///
    /// # fn main() -> ankit_builder::Result<()> {
    /// let builder = DeckBuilder::from_file("deck.toml")?;
    /// builder.write_toml("deck_copy.toml")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn write_toml(&self, path: impl AsRef<std::path::Path>) -> Result<()> {
        self.definition.write_toml(path)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    const EXAMPLE_TOML: &str = r#"
[package]
name = "Test Deck"
version = "1.0.0"

[[models]]
name = "Basic"
fields = ["Front", "Back"]

[[models.templates]]
name = "Card 1"
front = "{{Front}}"
back = "{{FrontSide}}<hr>{{Back}}"

[[decks]]
name = "Test Deck"
description = "A test deck"

[[notes]]
deck = "Test Deck"
model = "Basic"
tags = ["test"]

[notes.fields]
Front = "What is 2+2?"
Back = "4"

[[notes]]
deck = "Test Deck"
model = "Basic"

[notes.fields]
Front = "Capital of France?"
Back = "Paris"
"#;

    #[test]
    fn test_deck_builder_parse() {
        let builder = DeckBuilder::parse(EXAMPLE_TOML).unwrap();
        assert_eq!(builder.definition().package.name, "Test Deck");
        assert_eq!(builder.definition().notes.len(), 2);
    }

    #[test]
    #[cfg(feature = "apkg")]
    fn test_write_apkg() {
        let builder = DeckBuilder::parse(EXAMPLE_TOML).unwrap();
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("test.apkg");
        builder.write_apkg(&path).unwrap();
        assert!(path.exists());
    }
}