library

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 15, 2026 License: MIT Imports: 24 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package library indexes a directory tree of books and searches it.

Files on disk are the source of truth. This index is a derived cache: it can be deleted at any time and rebuilt by rescanning, and nothing in it is authoritative except the shelves, which are mirrored to TOML for exactly that reason.

Index

Constants

This section is empty.

Variables

View Source
var ErrNotFound = errors.New("library: book not found")

ErrNotFound is returned when a lookup matches no book.

View Source
var ErrShelfNotFound = errors.New("library: shelf not found")

ErrShelfNotFound is returned when a shelf name does not exist.

Functions

func CompileQuery

func CompileQuery(query string) (string, []any, error)

CompileQuery turns a query string into a SQL condition and its arguments. Exported so the sync planner can resolve a shelf's saved query without duplicating the parser.

func FoldPath

func FoldPath(p string) string

FoldPath returns a case-folded, normalized form for collision detection.

Case matters here on every platform, not just the case-insensitive ones: the device's FAT32 SD card is case-insensitive regardless of the host, so two books that differ only in case will collide on the device even when they coexist happily on a Linux workstation.

func HashFile

func HashFile(path string) (string, error)

HashFile is the exported form, used by the sync engine to hash the bytes it is about to send.

func NormalizePath

func NormalizePath(p string) string

NormalizePath canonicalizes a filesystem path for storage in the index.

This exists because of a genuine cross-platform hazard rather than tidiness. APFS returns filenames decomposed (NFD), while Linux filesystems generally hold whatever bytes were written, usually composed (NFC). "Ursula Le Guin" written on Linux and read on macOS produces different byte sequences for the same name, so a library scanned on both machines would accumulate duplicate rows for every book with a non-ASCII character in its path.

Everything stored or compared inside shelf is NFC. The raw OS-native form is used only for the actual syscall, which is why callers open files with the path the walk gave them, not with this one.

func NormalizeString

func NormalizeString(s string) string

NormalizeString applies the same normalization to metadata text, so that a title typed one way matches a title stored the other.

func RenderTemplate

func RenderTemplate(tmpl string, b *Book) (string, error)

RenderTemplate produces a relative, slash-separated path (without extension) for a book.

func SameFile

func SameFile(a, b string) bool

SameFile reports whether two paths refer to the same entry, accounting for normalization differences between platforms.

func SanitizeComponent

func SanitizeComponent(s string) string

SanitizeComponent makes a single path component safe for a FAT32 volume.

This runs at import rather than at sync time on purpose. A name that has to be rewritten during transfer would change the book's device path, and every path change costs the reader their position in that book.

func SanitizePath

func SanitizePath(p string) string

SanitizePath sanitizes every component of a slash-separated relative path.

func ValidFATName

func ValidFATName(s string) (bool, string)

ValidFATName reports whether a component is already safe for FAT32, and why not when it is not. Used by the sync planner to warn before transferring.

Types

type Book

type Book struct {
	ID     int64
	SHA256 string
	// DocID is the KOReader partial-MD5 that reading progress is keyed by.
	DocID       string
	Path        string // absolute, canonical, NFC-normalized
	Size        int64
	MTimeUnix   int64
	Format      Format
	Title       string
	AuthorSort  string
	Authors     []string
	Series      string
	SeriesIndex float64
	Language    string
	Publisher   string
	PubDate     string
	Identifiers map[string]string
	AddedUnix   int64
	Tags        []string
	Cover       []byte
	MetaJSON    string
}

Book is one indexed file.

func (*Book) DisplayAuthor

func (b *Book) DisplayAuthor() string

DisplayAuthor returns the best available author string.

func (*Book) DisplayTitle

func (b *Book) DisplayTitle() string

DisplayTitle falls back to the filename for books with no title metadata, since an empty column in a book list is useless.

type DB

type DB struct {
	// contains filtered or unexported fields
}

DB is an open library index.

func Open

func Open(path string) (*DB, error)

Open opens the index at path, creating or rebuilding it as needed.

A schema mismatch or a corrupt file is not an error: the index is derived data, so it is discarded and recreated. The caller is expected to rescan.

func (*DB) AddToShelf

func (db *DB) AddToShelf(name string, paths []string) error

AddToShelf adds books to a manual shelf by path.

func (*DB) All

func (db *DB) All() ([]*Book, error)

All returns every indexed book, sorted by author then series then title.

func (*DB) Authors

func (db *DB) Authors() ([]GroupCount, error)

Authors returns every author_sort in the library with its book count.

Grouped on author_sort rather than the authors list: a book with two authors has one sort key, and browsing wants one row per shelf-neighbour, not one per contributor. Books with no author at all are left out — an "" heading is a dead end to click on.

func (*DB) ByID

func (db *DB) ByID(id int64) (*Book, error)

ByID looks up a book by index id.

func (*DB) ByPath

func (db *DB) ByPath(path string) (*Book, error)

ByPath looks up a book by filesystem path.

func (*DB) BySHA256

func (db *DB) BySHA256(sum string) ([]*Book, error)

BySHA256 returns every book whose content hash matches. More than one result means the library holds duplicate files, which is allowed.

func (*DB) Close

func (db *DB) Close() error

Close closes the index.

func (*DB) Count

func (db *DB) Count() (int, error)

Count returns the number of indexed books.

func (*DB) CreateShelf

func (db *DB) CreateShelf(s Shelf) error

CreateShelf adds a shelf.

func (*DB) Delete

func (db *DB) Delete(path string) error

Delete removes a book from the index by path. Removing a row never touches the file: the index is a cache, and only explicit user commands delete books.

func (*DB) DeleteShelf

func (db *DB) DeleteShelf(name string) error

DeleteShelf removes a shelf by name.

func (*DB) Duplicates

func (db *DB) Duplicates() ([][]*Book, error)

Duplicates returns groups of books that share a content hash.

The index deliberately allows the same file to exist at several paths, so this reports them rather than the schema forbidding them.

func (*DB) GetShelf

func (db *DB) GetShelf(name string) (*Shelf, error)

GetShelf looks up one shelf by name.

func (*DB) Import

func (db *DB) Import(ctx context.Context, root string, sources []string, opts ImportOptions) ([]ImportResult, error)

Import places files into the library according to the naming template.

This is one of only two operations that may decide a book's path; the other is `shelf organize`. Metadata edits never move files, because a moved book loses its reading position on the device.

func (*DB) ListShelves

func (db *DB) ListShelves() ([]*Shelf, error)

ListShelves returns every shelf, sorted by name.

func (*DB) LoadShelves

func (db *DB) LoadShelves(path string) error

LoadShelves reads the TOML file and replaces the index's shelf tables with its contents. Call after opening an index that may be stale or freshly built.

func (*DB) Path

func (db *DB) Path() string

Path is the index file location.

func (*DB) RebuildFTS

func (db *DB) RebuildFTS() error

RebuildFTS regenerates the full-text index from the books table. Used by `shelf scan --deep` and as a repair for an index that predates a schema fix.

func (*DB) RemoveFromShelf

func (db *DB) RemoveFromShelf(name string, paths []string) error

RemoveFromShelf removes books from a manual shelf by path.

func (*DB) SaveShelves

func (db *DB) SaveShelves(path string) error

SaveShelves writes every shelf to TOML atomically.

func (*DB) Scan

func (db *DB) Scan(ctx context.Context, root string, opts ScanOptions) (*ScanResult, error)

Scan walks root and brings the index into agreement with what is on disk.

Change detection is by (size, mtime); files whose stat data is unchanged are not opened at all. This is what makes a rescan of a large library cheap.

func (*DB) Search

func (db *DB) Search(query string, opts SearchOptions) ([]*Book, error)

Search returns books matching a query string.

An empty query returns the whole library, which is what `shelf ls` with no arguments should do.

func (*DB) Series

func (db *DB) Series() ([]GroupCount, error)

Series returns every series in the library with its book count.

func (*DB) ShelfBooks

func (db *DB) ShelfBooks(name string) ([]*Book, error)

ShelfBooks resolves a shelf to its current book set.

Query shelves are re-evaluated on every call, so a saved search reflects the library as it is now rather than as it was when the shelf was created.

func (*DB) ShelfNames

func (db *DB) ShelfNames() ([]string, error)

ShelfNames lists shelf names, sorted.

func (*DB) Snapshot

func (db *DB) Snapshot() (PathIndex, error)

Snapshot loads the stat-level state of every indexed book. Scanning compares against this in memory rather than issuing a query per file.

func (*DB) Stats

func (db *DB) Stats() (Stats, error)

Stats computes the library summary.

func (*DB) Tags

func (db *DB) Tags() ([]TagCount, error)

Tags returns every tag in the library with its book count, most used first.

func (*DB) Upsert

func (db *DB) Upsert(b *Book) error

Upsert inserts or updates a book by path, replacing its tags.

type Filter

type Filter struct {
	Field FilterField
	Value string
}

Filter is an exact-match predicate on one field.

type FilterField

type FilterField string

FilterField names the fields an exact filter can apply to. A closed set, because each one compiles to a hand-written SQL predicate.

const (
	FilterAuthor FilterField = "author"
	FilterSeries FilterField = "series"
	FilterTag    FilterField = "tag"
)

type Format

type Format string

Format identifies a book's container format.

const (
	FormatEPUB Format = "epub"
	FormatTXT  Format = "txt"
	FormatXTC  Format = "xtc" // Xteink native; opaque passthrough
	FormatPDF  Format = "pdf" // source format only; converted before sync
)

func FormatOf

func FormatOf(path string) (Format, bool)

FormatOf classifies a file by extension.

func (Format) SyncableToDevice

func (f Format) SyncableToDevice() bool

SyncableToDevice reports whether the firmware can render this format directly. PDF is indexed but must be converted before it reaches a device.

type GroupCount

type GroupCount struct {
	Value string `json:"value"`
	Count int    `json:"count"`
}

GroupCount is one value of a browse dimension and how many books share it.

type ImportMode

type ImportMode string

ImportMode selects what happens to the source file.

const (
	ImportCopy ImportMode = "copy"
	ImportMove ImportMode = "move"
	ImportLink ImportMode = "link" // hard link, falling back to copy
)

type ImportOptions

type ImportOptions struct {
	Mode     ImportMode
	Template string
	// DryRun computes destinations without touching the filesystem.
	DryRun bool
	// Overwrite permits replacing an existing destination file.
	Overwrite bool
}

ImportOptions controls an import.

type ImportResult

type ImportResult struct {
	Source string
	Dest   string
	Action string // imported | would-import | skipped
	Err    error
}

ImportResult describes what happened to one file.

type PathIndex

type PathIndex map[string]PathState

PathIndex is the (size, mtime) snapshot a scan compares against to decide which files need rehashing.

type PathState

type PathState struct {
	ID        int64
	Size      int64
	MTimeUnix int64
	SHA256    string
}

PathState is what the index knows about a file without opening it.

type ScanAction

type ScanAction string

ScanAction is what a scan did with one file.

const (
	ActionAdded     ScanAction = "added"
	ActionUpdated   ScanAction = "updated"
	ActionUnchanged ScanAction = "unchanged"
	ActionRemoved   ScanAction = "removed"
	ActionSkipped   ScanAction = "skipped"
	ActionFailed    ScanAction = "failed"
)

type ScanError

type ScanError struct {
	Path string
	Err  error
}

ScanError records a file that could not be indexed. One bad book must not abort a scan of ten thousand.

func (ScanError) Error

func (e ScanError) Error() string

func (ScanError) Unwrap

func (e ScanError) Unwrap() error

type ScanOptions

type ScanOptions struct {
	// Deep rehashes and re-reads metadata for every file, ignoring the
	// (size, mtime) fast path. Use after an external tool has edited books.
	Deep bool

	// Covers extracts cover thumbnails. Scanning without covers is
	// substantially faster on a large library.
	Covers bool

	// Progress, when set, is called as each file is processed.
	Progress func(ScanProgress)
}

ScanOptions controls a library scan.

type ScanProgress

type ScanProgress struct {
	Path   string
	Action ScanAction
	Err    error
}

ScanProgress reports a single file's outcome during a scan.

type ScanResult

type ScanResult struct {
	Added     int
	Updated   int
	Unchanged int
	Removed   int
	Skipped   int
	Errors    []ScanError
}

ScanResult summarizes a completed scan.

type SearchOptions

type SearchOptions struct {
	Limit  int
	Offset int
	// OrderBy overrides the default author/series/title ordering.
	OrderBy string

	// Filter narrows to an exact value of one field.
	//
	// Separate from the query text on purpose. Browsing by author or tag means
	// filtering on a value that came out of book metadata, and the query lexer
	// ends a quoted string at the first matching quote with no escape — an
	// author like O'Brien "Bob" cannot be expressed in query syntax at all.
	// Binding the value as a parameter sidesteps the question.
	Filter *Filter
}

SearchOptions tunes a search.

type Shelf

type Shelf struct {
	ID    int64     `toml:"-"`
	Name  string    `toml:"name"`
	Kind  ShelfKind `toml:"kind"`
	Query string    `toml:"query,omitempty"`
	// Members holds book paths for manual shelves. Paths, not index ids,
	// because the index is a cache that can be rebuilt from scratch.
	Members []string `toml:"members,omitempty"`
}

Shelf is a named set of books, and the unit that syncs to a device.

type ShelfKind

type ShelfKind string

ShelfKind distinguishes the two ways a shelf decides what it contains.

const (
	// KindQuery is a saved search, re-evaluated every time it is used.
	KindQuery ShelfKind = "query"
	// KindManual is an explicit set of books.
	KindManual ShelfKind = "manual"
)

type Stats

type Stats struct {
	Books   int            `json:"books"`
	Authors int            `json:"authors"`
	Series  int            `json:"series"`
	Tags    int            `json:"tags"`
	Bytes   int64          `json:"bytes"`
	Formats map[Format]int `json:"formats"`
}

Stats summarises the whole library.

One call rather than five, because the TUI header redraws on every keystroke and a header that costs a round of separate queries per frame is a header that makes scrolling feel slow.

type TagCount

type TagCount struct {
	Tag   string `json:"tag"`
	Count int    `json:"count"`
}

TagCount is a tag and how many books carry it.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL