Something went wrong. Try again.
A terminal UI for Libby libbui.vinnymac.dev
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353//! Library path templates such as `Ebooks/{Author}/{Title}/{Title}`.//!//! A template is split on `/` into segments before any value is//! substituted, so a value can never introduce a separator, and every//! rendered segment goes through [`crate::sanitize::component`], so `..`,//! absolute paths and drive letters in titles are inert. A segment whose//! tokens all render empty (a book without a series) is dropped rather than//! becoming a `_` directory. The result is always a relative path strictly//! inside the library root.
use std::path::PathBuf;
use crate::sanitize;
/// A token a template may use.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Token { /// `{Title}` Title, /// `{Author}` Author, /// `{Series}` Series, /// `{SeriesIndex}` SeriesIndex, /// `{Year}` Year, /// `{TitleId}` TitleId,}
impl Token { fn parse(name: &str) -> Option<Self> { Some(match name { "Title" => Self::Title, "Author" => Self::Author, "Series" => Self::Series, "SeriesIndex" => Self::SeriesIndex, "Year" => Self::Year, "TitleId" => Self::TitleId, _ => return None, }) }}
/// Values substituted into a template. Empty strings count as absent.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct Values<'a> { /// Book title. pub title: &'a str, /// Primary author. pub author: &'a str, /// Series name. pub series: &'a str, /// Position in the series, already formatted (e.g. `"3"` or `"2.5"`). pub series_index: &'a str, /// Publication year. pub year: &'a str, /// Libby title id; always present, used as the last-resort name. pub title_id: &'a str,}
impl Values<'_> { fn get(&self, token: Token) -> &str { match token { Token::Title => self.title, Token::Author => self.author, Token::Series => self.series, Token::SeriesIndex => self.series_index, Token::Year => self.year, Token::TitleId => self.title_id, } }}
#[derive(Debug, Clone, PartialEq, Eq)]enum Piece { Literal(String), Token(Token),}
/// A parsed path template.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Template { segments: Vec<Vec<Piece>>,}
/// Why a template string was rejected.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]pub enum TemplateError { /// `{Something}` is not a known token. #[error( "unknown token {{{0}}}; known tokens are {{Title}} {{Author}} {{Series}} {{SeriesIndex}} {{Year}} {{TitleId}}" )] UnknownToken(String), /// A `{` without a matching `}` or a stray `}`. #[error("unbalanced brace in template")] UnbalancedBrace, /// The template is absolute or contains a `.`/`..` segment. #[error("template must be a relative path without `.` or `..` segments")] NotRelative, /// The template has no segments at all. #[error("template is empty")] Empty,}
impl Template { /// Parses `text`. Both `/` and `\` separate segments. /// /// # Errors /// See [`TemplateError`]. pub fn parse(text: &str) -> Result<Self, TemplateError> { if text.starts_with(['/', '\\']) || text.get(1..2) == Some(":") { return Err(TemplateError::NotRelative); } let mut segments = Vec::new(); for raw in text.split(['/', '\\']) { if raw.is_empty() { continue; } if raw.trim() == "." || raw.trim() == ".." { return Err(TemplateError::NotRelative); } segments.push(parse_segment(raw)?); } if segments.is_empty() { return Err(TemplateError::Empty); } Ok(Self { segments }) }
/// Renders the template to a relative path (without extension). /// /// A segment that uses tokens but whose tokens all render empty is /// dropped together with its literal text (`{Series} #{SeriesIndex}` /// for a book without a series disappears rather than becoming `#`). If every segment drops out, the sanitized title id is /// used so the result is never empty. pub fn render(&self, values: &Values<'_>) -> PathBuf { let mut out = PathBuf::new(); for segment in &self.segments { if let Some(component) = render_segment(segment, values) { out.push(component); } } if out.as_os_str().is_empty() { out.push(sanitize::component(values.title_id)); } out }}
fn parse_segment(raw: &str) -> Result<Vec<Piece>, TemplateError> { let mut pieces = Vec::new(); let mut rest = raw; while !rest.is_empty() { match rest.find(['{', '}']) { None => { pieces.push(Piece::Literal(rest.to_owned())); break; } Some(i) => { let (lit, tail) = rest.split_at(i); if !lit.is_empty() { pieces.push(Piece::Literal(lit.to_owned())); } if tail.starts_with('}') { return Err(TemplateError::UnbalancedBrace); } let close = tail.find('}').ok_or(TemplateError::UnbalancedBrace)?; let name = tail.get(1..close).unwrap_or(""); if name.contains('{') { return Err(TemplateError::UnbalancedBrace); } let token = Token::parse(name) .ok_or_else(|| TemplateError::UnknownToken(name.to_owned()))?; pieces.push(Piece::Token(token)); rest = tail.get(close + 1..).unwrap_or(""); } } } Ok(pieces)}
fn render_segment(pieces: &[Piece], values: &Values<'_>) -> Option<String> { let has_tokens = pieces.iter().any(|p| matches!(p, Piece::Token(_))); let any_value = pieces.iter().any(|p| match p { // A value of only dots and spaces (`..`) sanitizes to nothing, so it // counts as absent rather than producing a `_` directory. Piece::Token(t) => !values .get(*t) .trim_matches(|c: char| c.is_whitespace() || c == '.') .is_empty(), Piece::Literal(_) => false, }); if has_tokens && !any_value { return None; } let mut text = String::new(); for piece in pieces { match piece { Piece::Literal(l) => text.push_str(l), Piece::Token(t) => text.push_str(values.get(*t).trim()), } } Some(sanitize::component(&text))}
#[cfg(test)]mod tests { #![allow(clippy::unwrap_used)] use super::*; use std::path::{Component, Path};
fn values() -> Values<'static> { Values { title: "Dune", author: "Frank Herbert", series: "Dune Chronicles", series_index: "1", year: "1965", title_id: "12345", } }
fn render(t: &str, v: &Values<'_>) -> PathBuf { Template::parse(t).unwrap().render(v) }
#[test] fn default_template() { assert_eq!( render("Ebooks/{Author}/{Title}/{Title}", &values()), PathBuf::from("Ebooks/Frank Herbert/Dune/Dune") ); }
#[test] fn render_table() { let mut no_series = values(); no_series.series = ""; no_series.series_index = ""; let hostile = Values { title: "../../etc/passwd", author: "/root", series: "C:\\Windows", series_index: "..", year: "", title_id: "1", }; let empty = Values { title_id: "77", ..Values::default() }; let full = values(); let cases: Vec<(&str, &Values<'_>, &str)> = vec![ ( "{Author}/{Series}/{Title}", &no_series, "Frank Herbert/Dune", ), ( "{Series} {SeriesIndex} - {Title}", &full, "Dune Chronicles 1 - Dune", ), ("{Series} #{SeriesIndex}/{Title}", &no_series, "Dune"), ("{Title} ({Year})", &full, "Dune (1965)"), ("{TitleId}", &full, "12345"), ("{Author}/{Title}", &hostile, "root/etc passwd"), ("{Series}/{SeriesIndex}", &hostile, "C Windows"), ("{Author}/{Title}", &empty, "77"), ("Books//{Title}", &full, "Books/Dune"), ("Books\\{Title}", &full, "Books/Dune"), ]; for (t, v, want) in cases { assert_eq!(render(t, v), PathBuf::from(want), "template {t:?}"); } }
#[test] fn rendered_paths_never_escape() { let nasty = [ "..", ".", "/", "\\", "../..", "/etc", "C:", "a/../../b", "~", "\u{0}", ]; for a in nasty { for t in nasty { let v = Values { title: t, author: a, series: a, series_index: t, year: a, title_id: t, }; let p = render("{Author}/{Series}{SeriesIndex}/{Title}{Year}/{TitleId}", &v); assert!(!p.as_os_str().is_empty()); assert!(p.is_relative(), "{p:?}"); assert!( p.components().all(|c| matches!(c, Component::Normal(_))), "{p:?}" ); assert!(Path::new("/root").join(&p).starts_with("/root")); } } }
#[test] fn parse_errors() { assert_eq!( Template::parse("{Nope}").unwrap_err(), TemplateError::UnknownToken("Nope".into()) ); assert_eq!( Template::parse("{Title").unwrap_err(), TemplateError::UnbalancedBrace ); assert_eq!( Template::parse("Title}").unwrap_err(), TemplateError::UnbalancedBrace ); assert_eq!( Template::parse("{{Title}}").unwrap_err(), TemplateError::UnbalancedBrace ); assert_eq!( Template::parse("/abs/{Title}").unwrap_err(), TemplateError::NotRelative ); assert_eq!( Template::parse("C:/{Title}").unwrap_err(), TemplateError::NotRelative ); assert_eq!( Template::parse("a/../{Title}").unwrap_err(), TemplateError::NotRelative ); assert_eq!(Template::parse("").unwrap_err(), TemplateError::Empty); assert_eq!( Template::parse("//").unwrap_err(), TemplateError::NotRelative ); }}