Skip to main content

DeckBuilder

Struct DeckBuilder 

Source
pub struct DeckBuilder { /* private fields */ }
Expand description

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

§Example

use ankit_builder::DeckBuilder;

// Load from TOML file
let builder = DeckBuilder::from_file("vocabulary.toml")?;

// Generate .apkg file
builder.write_apkg("vocabulary.apkg")?;

§Async Example (AnkiConnect)

use ankit_builder::DeckBuilder;

let builder = DeckBuilder::from_file("vocabulary.toml")?;
let result = builder.import_connect().await?;
println!("Created {} notes", result.notes_created);

Implementations§

Source§

impl DeckBuilder

Source

pub fn new(definition: DeckDefinition) -> Self

Create a new builder from a deck definition.

Use this when you have a programmatically constructed DeckDefinition. For loading from TOML, prefer from_file() or parse().

§Example
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();
Source

pub fn from_file(path: impl AsRef<Path>) -> Result<Self>

Load a deck definition from a TOML file.

§Errors

Returns an error if the file cannot be read or contains invalid TOML.

§Example
use ankit_builder::DeckBuilder;

let builder = DeckBuilder::from_file("my_deck.toml")?;
println!("Loaded deck: {}", builder.definition().package.name);
Source

pub fn parse(content: &str) -> Result<Self>

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");
Source

pub fn media_base_path(self, path: impl AsRef<Path>) -> Self

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
use ankit_builder::DeckBuilder;

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")?;
Source

pub fn definition(&self) -> &DeckDefinition

Get the underlying deck definition.

Use this to inspect the parsed TOML structure, including package metadata, models, decks, and notes.

§Example
use ankit_builder::DeckBuilder;

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());
Source

pub fn write_apkg(&self, path: impl AsRef<Path>) -> Result<()>

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
use ankit_builder::DeckBuilder;

let builder = DeckBuilder::from_file("vocabulary.toml")?;
builder.write_apkg("vocabulary.apkg")?;
println!("Created vocabulary.apkg");
Source

pub async fn import_connect(&self) -> Result<ImportResult>

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
use ankit_builder::DeckBuilder;

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);
Source

pub async fn import_connect_batch(&self) -> Result<ImportResult>

Import the deck definition via AnkiConnect in batch mode.

More efficient than 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
use ankit_builder::DeckBuilder;

let builder = DeckBuilder::from_file("large_deck.toml")?;
let result = builder.import_connect_batch().await?;
println!("Imported {} notes", result.notes_created);
Source

pub async fn diff_connect(&self) -> Result<DeckDiff>

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
use ankit_builder::DeckBuilder;

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());
}
Source

pub async fn diff_connect_with_client( &self, client: &AnkiClient, ) -> Result<DeckDiff>

Compare the TOML definition against Anki using a custom client.

Like diff_connect() but allows using a custom AnkiClient with non-default settings.

Source

pub async fn plan_sync(&self) -> Result<SyncPlan>

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().

§Requirements
  • Anki must be running with the AnkiConnect add-on installed
§Example
use ankit_builder::DeckBuilder;

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);
Source

pub async fn plan_sync_with_client( &self, client: &AnkiClient, ) -> Result<SyncPlan>

Plan sync using a custom client.

Like plan_sync() but allows using a custom AnkiClient with non-default settings.

Source

pub async fn sync(&self, strategy: SyncStrategy) -> Result<SyncResult>

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
use ankit_builder::{DeckBuilder, SyncStrategy};

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")?;
}
Source

pub async fn sync_with_client( &self, client: &AnkiClient, strategy: SyncStrategy, ) -> Result<SyncResult>

Execute sync using a custom client.

Like sync() but allows using a custom AnkiClient with non-default settings.

Source

pub async fn from_anki(client: &AnkiClient, deck_name: &str) -> Result<Self>

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
use ankit::AnkiClient;
use ankit_builder::DeckBuilder;

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")?;
Source

pub fn write_toml(&self, path: impl AsRef<Path>) -> Result<()>

Write the deck definition to a TOML file.

Convenience method that calls DeckDefinition::write_toml().

§Example
use ankit_builder::DeckBuilder;

let builder = DeckBuilder::from_file("deck.toml")?;
builder.write_toml("deck_copy.toml")?;

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more