bookclerk_naming

Development These docs follow the development version and change with every merge.

Last updated View as Markdown

Port of Libation's NamingTemplate tag template naming engine.

Because it derives from Libation, this crate is licensed under GPL-3.0-only rather than the workspace's AGPL-3.0-or-later.

Audience

Host acquire / settings code that expands folder and file templates. Guest plugins do not depend on this crate.

Upstream lives in FileManager.NamingTemplate (class NamingTemplate); the book/property tags and formatters come from LibationFileManager.Templates. This crate targets classic / Chardonnay parity for property tags, conditionals, and the text / number / list / name / series / date formatters.

Current Libation templates use <tag->…<-tag> conditionals. Older Libation forms are still accepted for compatibility: <if series>…<end if>, %asin%, and bare <asin> tags.

Style: docs/contributing/code-documentation.md.

Example

use bookclerk_naming::{expand_template, BookContext, Contributor};

let book = BookContext {
    isbn: "B00X".into(),
    title_with_subtitle: Some("A Study in Scarlet".into()),
    authors: vec![Contributor::new("Arthur Conan Doyle", None)],
    ..Default::default()
};
let out = expand_template("<author> - <title> [<id>]", &book, None).unwrap();
assert_eq!(out, "Arthur Conan Doyle - A Study in Scarlet [B00X]");
Item Kind Summary
BookContext struct All data required to evaluate a naming template for a book.
ChapterContext struct Per-chapter context for chapter file / title templates.
Contributor struct An author or narrator (parsed lazily into name components).
Series struct A series membership.
TemplatePart struct A single evaluated fragment of a template.
Template struct A parsed, reusable naming template.
ContentKind enum The kind of content a book represents.
NamingError enum Errors produced while parsing or evaluating a template.
expand_template function Parse and evaluate template in one step.
apply_path_replacements function Apply classic Libation ReplacementCharacters rules to input.
remove_spaces function Collapse whitespace across an ordered list of path-segment part strings, mirroring Bookclerk's Templates.RemoveSpaces:
expand_filename function Evaluate template into a single sanitised filename component.
expand_folder function Evaluate a folder template into its sanitised path segments.
property_tag_names function Returns (tag_name, supports_format_specifier) for every Chardonnay property tag.
require_call_number function Checks that templates name every edition apart: the folder template, or both the file and the chapter-file templates, always write <call number>. Two editions of a title (an abridged and an unabridged recording, two narrators' readings) would otherwise share one path.
Result type alias A convenient result alias for this crate.

Re-exports

Structs

BookContext

pub struct BookContext {
    pub isbn: String,
    pub call_number: String,
    pub title: Option<String>,
    pub subtitle: Option<String>,
    pub title_with_subtitle: Option<String>,
    pub authors: Vec<Contributor>,
    pub narrators: Vec<Contributor>,
    pub series: Vec<Series>,
    pub tags: Vec<String>,
    pub account: Option<String>,
    pub account_nickname: Option<String>,
    pub locale: Option<String>,
    pub language: Option<String>,
    pub year_published: Option<i32>,
    pub published_at: Option<NaiveDateTime>,
    pub purchased_at: Option<NaiveDateTime>,
    pub file_date: Option<NaiveDateTime>,
    pub length_minutes: Option<f64>,
    pub bitrate: Option<i64>,
    pub samplerate: Option<i64>,
    pub channels: Option<i64>,
    pub codec: Option<String>,
    pub is_abridged: bool,
    pub content_kind: ContentKind,
    pub publisher: Option<String>,
    pub categories: Vec<String>,
    pub bookclerk_version: Option<String>,
    pub file_version: Option<String>,
}

All data required to evaluate a naming template for a book.

Fields

  • isbn: Canonical title id (ISBN / ASIN fallback) — used by <id>.
  • call_number: The edition's short Bookclerk id — used by <call number>. Unique per edition in the library, and shared by every store copy of it, so a path that carries it never names two editions.
  • title: Audible title (no subtitle) — used by <audible title> and <title short>.
  • subtitle: Audible subtitle — used by <audible subtitle>.
  • title_with_subtitle: Full title with subtitle — used by <title>. Falls back to Self::title.
  • authors: Authors in display order for <author> / <authors> / <first author>.
  • narrators: Narrators in display order for <narrator> / <narrators>.
  • series: Series memberships for <series> / <series#> / conditionals.
  • tags: Free-form tags for <tags> / [tag] search parity helpers.
  • account: Store account id string for <account> when set.
  • account_nickname: Operator nickname for the account (<account nickname>).
  • locale: Marketplace / locale code (us, uk, …) for <locale>.
  • language: Content language for <language>.
  • year_published: Publication year for <year> (Gregorian calendar).
  • published_at: Publication date — used by <pub date>.
  • purchased_at: Date added to the account — used by <date added>.
  • file_date: File date — used by <file date>.
  • length_minutes: Runtime in minutes for <duration> / related tags (may be fractional).
  • bitrate: Audio bitrate in kbps when known.
  • samplerate: Sample rate in Hz when known.
  • channels: Channel count when known (1 = mono, 2 = stereo).
  • codec: Codec / container label when known (aac, mp3, …).
  • is_abridged: Whether the title is abridged (<abridged> conditional).
  • content_kind: Book vs podcast/episode classification for podcast-aware templates.
  • publisher: Publisher imprint for <publisher>.
  • categories: Genre / category labels for <genre> / <categories>.
  • bookclerk_version: Bookclerk package version string for <bookclerk version> when set.
  • file_version: Liberated file / encoding version tag for <file version> when set.

Implements: Clone, Debug, Default

ChapterContext

pub struct ChapterContext {
    pub chapter_number: u32,
    pub chapter_count: u32,
    pub chapter_title: Option<String>,
    pub file_date: Option<NaiveDateTime>,
}

Per-chapter context for chapter file / title templates.

Fields

  • chapter_number: 1-based chapter position (<ch#>).
  • chapter_count: Total number of chapters (<ch count>).
  • chapter_title: Chapter title (<ch title>).
  • file_date: Optional chapter file date override (<file date>).

Implements: Clone, Debug, Default

Contributor

pub struct Contributor {
    pub name: String,
    pub id: Option<String>,
}

An author or narrator (parsed lazily into name components).

Fields

  • name: Display name as shown in templates (<author>, <narrator>, …).
  • id: Optional store-native person id when known.

Contributor::new

pub fn new(name: impl Into<String>, id: Option<String>) -> Self

Build a contributor from a display name and optional store id.

Implements: Clone, Debug, Default

Series

pub struct Series {
    pub name: String,
    pub order: Option<String>,
    pub id: Option<String>,
}

A series membership.

Fields

  • name: Series display name (<series>, <first series>, …).
  • order: Raw order string (e.g. "1", "1-5", "6").
  • id: Optional store-native series id when known.

Series::new

pub fn new(name: impl Into<String>, order: Option<String>, id: Option<String>) -> Self

Build a series membership from name, optional order, and optional id.

Implements: Clone, Debug, Default

TemplatePart

pub struct TemplatePart {
    pub value: String,
    pub is_literal: bool,
}

A single evaluated fragment of a template.

Fields

  • value: The rendered text.
  • is_literal: true for literal template text, false for a resolved tag value.

Implements: Clone, Debug, Eq, PartialEq

Template

pub struct Template {
    /* private fields */
}

A parsed, reusable naming template.

Template::parse

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

Parse a template string.

Errors

Returns NamingError::Parse if the template is fundamentally invalid.

Template::evaluate

pub fn evaluate(&self, book: &BookContext, chapter: Option<&ChapterContext>) -> String

Evaluate the template against a book (and optional chapter) context, returning the concatenated result string.

Template::evaluate_parts

pub fn evaluate_parts(
    &self,
    book: &BookContext,
    chapter: Option<&ChapterContext>,
) -> Vec<TemplatePart>

Evaluate the template into its individual TemplateParts, preserving whether each fragment came from literal text or a resolved tag. This is useful for path building where literal / should create directories but tag values should not.

Implements: Clone, Debug

Enums

ContentKind

pub enum ContentKind {
    Book,
    Episode,
    Podcast,
    PodcastParent,
}

The kind of content a book represents.

Variants

  • Book: Ordinary audiobook title (default).
  • Episode: Podcast episode acquired as a child of a show.
  • Podcast: Podcast show / feed treated as a liberatable title.
  • PodcastParent: Parent podcast container (show) without a single episode payload.

Implements: Clone, Copy, Debug, Default, Eq, PartialEq

NamingError

pub enum NamingError {
    Parse(String),
    MissingCallNumber,
}

Errors produced while parsing or evaluating a template.

Variants

  • Parse: The template string could not be parsed.
  • MissingCallNumber: Neither the folder template nor both file templates always write <call number> (require_call_number).

Implements: Clone, Debug, Display, Eq, Error, PartialEq

Functions

expand_template

pub fn expand_template(
    template: &str,
    book: &BookContext,
    chapter: Option<&ChapterContext>,
) -> Result<String>

Parse and evaluate template in one step.

Errors

Returns NamingError::Parse if the template is fundamentally invalid.

apply_path_replacements

pub fn apply_path_replacements(input: &str, rules: &[ReplacementRule]) -> String

Apply classic Libation ReplacementCharacters rules to input.

remove_spaces

pub fn remove_spaces(parts: &[String]) -> String

Collapse whitespace across an ordered list of path-segment part strings, mirroring Bookclerk's Templates.RemoveSpaces:

  • leading / trailing parts that are entirely whitespace are dropped,
  • the first part is left-trimmed and the last part is right-trimmed,
  • runs of spaces inside each part are collapsed to a single space, and
  • a doubled space straddling a part boundary is collapsed.

The parts are then concatenated into the final segment string.

expand_filename

pub fn expand_filename(
    template: &str,
    book: &BookContext,
    chapter: Option<&ChapterContext>,
    rules: &[ReplacementRule],
) -> Result<String>

Evaluate template into a single sanitised filename component.

Every part (literal and tag) has the replacement rules applied to it, then whitespace is collapsed with remove_spaces, matching the output of Bookclerk's FileTemplate.GetFilename for one path segment. Passing an empty rules slice performs no character replacement (useful for exact tag-output assertions).

Errors

Returns NamingError::Parse if the template is fundamentally invalid.

expand_folder

pub fn expand_folder(
    template: &str,
    book: &BookContext,
    chapter: Option<&ChapterContext>,
    rules: &[ReplacementRule],
) -> Result<Vec<String>>

Evaluate a folder template into its sanitised path segments.

Literal / characters delimit directories (like Bookclerk's FolderTemplate), while / produced by a tag value is replaced via rules. Each resulting segment is space-collapsed with remove_spaces; empty segments are dropped.

Errors

Returns NamingError::Parse if the template is fundamentally invalid.

Panics

Panics when an internal invariant does not hold.

property_tag_names

pub fn property_tag_names() -> &'static [(&'static str, bool)]

Returns (tag_name, supports_format_specifier) for every Chardonnay property tag.

require_call_number

pub fn require_call_number(folder: &str, file: &str, chapter_file: &str) -> Result<()>

Checks that templates name every edition apart: the folder template, or both the file and the chapter-file templates, always write <call number>. Two editions of a title (an abridged and an unabridged recording, two narrators' readings) would otherwise share one path.

Arguments

  • folder, file, chapter_file - The resolved folder, file and chapter-file templates.

Errors

Returns NamingError::MissingCallNumber when no such placement holds, and NamingError::Parse when a template does not parse.

Type aliases

Result

pub type Result<T> = Result<T, NamingError>;

A convenient result alias for this crate.

Generated from crates/bookclerk-naming at main · View as Markdown