From 0f0677a272a3142fd39abb75e294a6329de01051 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Sun, 15 Nov 2026 15:42:24 -0500 Subject: [PATCH] wip(cli): scriptable subcommands, output handle, exit codes and cli strings --- Cargo.lock | 1 + crates/libbui/Cargo.toml | 1 + crates/libbui/locales/en-US/cli.ftl | 172 ++++++ crates/libbui/src/app/mod.rs | 10 +- crates/libbui/src/cli.rs | 39 -- crates/libbui/src/cli/account.rs | 734 ++++++++++++++++++++++++ crates/libbui/src/cli/account/tests.rs | 1 + crates/libbui/src/cli/doctor.rs | 357 ++++++++++++ crates/libbui/src/cli/download.rs | 509 ++++++++++++++++ crates/libbui/src/cli/download/tests.rs | 1 + crates/libbui/src/cli/exit.rs | 135 +++++ crates/libbui/src/cli/local.rs | 225 ++++++++ crates/libbui/src/cli/mod.rs | 379 ++++++++++++ crates/libbui/src/cli/output.rs | 334 +++++++++++ crates/libbui/src/cli/session.rs | 86 +++ crates/libbui/src/cli/table.rs | 215 +++++++ crates/libbui/src/main.rs | 17 +- crates/libbui/src/services.rs | 10 + crates/libbui/src/startup.rs | 35 +- 19 files changed, 3207 insertions(+), 54 deletions(-) create mode 100644 crates/libbui/locales/en-US/cli.ftl delete mode 100644 crates/libbui/src/cli.rs create mode 100644 crates/libbui/src/cli/account.rs create mode 100644 crates/libbui/src/cli/account/tests.rs create mode 100644 crates/libbui/src/cli/doctor.rs create mode 100644 crates/libbui/src/cli/download.rs create mode 100644 crates/libbui/src/cli/download/tests.rs create mode 100644 crates/libbui/src/cli/exit.rs create mode 100644 crates/libbui/src/cli/local.rs create mode 100644 crates/libbui/src/cli/mod.rs create mode 100644 crates/libbui/src/cli/output.rs create mode 100644 crates/libbui/src/cli/session.rs create mode 100644 crates/libbui/src/cli/table.rs diff --git a/Cargo.lock b/Cargo.lock index 0ea627f..3da8893 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1924,6 +1924,7 @@ dependencies = [ "thiserror 2.0.21", "tokio", "tokio-util", + "toml", "tracing", "tui-input", "unicode-segmentation", diff --git a/crates/libbui/Cargo.toml b/crates/libbui/Cargo.toml index 3e8a14d..48e31c7 100644 --- a/crates/libbui/Cargo.toml +++ b/crates/libbui/Cargo.toml @@ -32,6 +32,7 @@ reqwest = { workspace = true } url = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } +toml = { workspace = true } jiff = { workspace = true } secrecy = { workspace = true } thiserror = { workspace = true } diff --git a/crates/libbui/locales/en-US/cli.ftl b/crates/libbui/locales/en-US/cli.ftl new file mode 100644 index 0000000..1d3fe70 --- /dev/null +++ b/crates/libbui/locales/en-US/cli.ftl @@ -0,0 +1,172 @@ +### The scriptable command line (`libbui loans`, `libbui download`, …). +### Results go to standard output; notes, progress and errors to standard +### error. Keep table headings short: they share one terminal line. + +## Errors and exit +cli-error = libbui: { $message } +cli-not-paired = This device is not paired with Libby. Run `libbui pair` (or open libbui) first. +cli-interrupted = Interrupted. +cli-io-failed = Could not write the output: { $reason } +cli-client-failed = Could not set up the network client: { $reason } +cli-save-pairing-failed = Could not save the Libby pairing: { $reason } +cli-write-failed = Could not write { $path }: { $reason } +cli-engine-failed = The download queue stopped: { $reason } +cli-bad-template = The [templates] setting is invalid: { $reason } +cli-unknown = unknown + +## Prompts +cli-confirm = { $question } [y/N] +cli-confirm-yes = yes + +## Pairing +cli-pair-howto = In Libby, open the menu, choose “Copy To Another Device”, and type the eight-digit code it shows. +cli-pair-prompt = Setup code: +cli-pair-no-code = No setup code given. +cli-pair-bad-code = A setup code is eight digits, like 1234 5678. +cli-paired = { $count -> + [one] Paired. libbui can see one library card: + *[other] Paired. libbui can see { $count } library cards: +} +cli-unpair-question = Forget the Libby pairing on this device? +cli-unpair-needs-yes = Unpairing needs confirmation; pass --yes when not running in a terminal. +cli-unpair-kept = Kept the pairing. +cli-unpair-nothing = This device is not paired; nothing to forget. +cli-unpaired = Forgot the pairing. Your loans and holds are unchanged; pair again with `libbui pair`. + +## Cards +cli-no-such-card = No card matches “{ $card }”. Your cards: { $cards } +cli-choose-card = You have several cards; choose one with --card. Your cards: { $cards } +cli-card-no-library = Card { $card } has no library to borrow from. +cli-card-gone = Card { $card } is no longer on your account. +cli-count-of = { $used }/{ $limit } + +## Table headings +cli-col-id = ID +cli-col-title = TITLE +cli-col-author = AUTHOR +cli-col-kind = KIND +cli-col-library = LIBRARY +cli-col-due = DUE +cli-col-get = GET +cli-col-status = STATUS +cli-col-card = CARD +cli-col-key = KEY +cli-col-loans = LOANS +cli-col-holds = HOLDS +cli-col-what = WHAT +cli-col-path = PATH +cli-col-check = CHECK +cli-col-detail = DETAIL + +## Listings +cli-no-loans = No loans. +cli-no-holds = No holds. +cli-due = { $date } ({ $left }) +cli-libby-only = Libby only +cli-hold-ready = Ready to borrow +cli-hold-suspended = Suspended +cli-hold-position = #{ $position } in line +cli-hold-position-wait = #{ $position } in line, about { $days -> + [one] { $days } day + *[other] { $days } days +} +cli-hold-waiting = Waiting + +## Search +cli-available = Available +cli-holdable = Wait list +cli-unavailable = Not available +cli-wait-days = { $days -> + [one] Wait ~{ $days } day + *[other] Wait ~{ $days } days +} +cli-search-need-library = Choose a library with --library KEY (the name in its libbyapp.com address), or pair first. +cli-search-empty = Nothing found at { $library }. +cli-search-summary = { $shown } of { $total } results (page { $page }) at { $library }. +cli-search-next = More with --page { $page }. + +## Loans and holds +cli-not-on-loan = { $id } is not one of your loans. +cli-already-on-loan = “{ $title }” is already on loan. +cli-already-on-hold = “{ $title }” is already on hold. +cli-loan-limit = You have as many loans as { $library } allows. +cli-hold-limit = You have as many holds as { $library } allows. +cli-not-available = “{ $title }” is not available right now. Place a hold with `libbui hold { $id }`. +cli-borrowed = Borrowed “{ $title }”, due { $date }. +cli-returned = Returned “{ $title }”. +cli-renewed = Renewed “{ $title }”, now due { $date }. +cli-renew-not-yet = “{ $title }” can be renewed from { $date }. +cli-renew-not-renewable = “{ $title }” cannot be renewed. +cli-hold-placed = Placed a hold on “{ $title }” ({ $status }). + +## Downloads +cli-download-choose-card = { $id } is on loan on several cards; choose one with --card. +cli-download-libby-only = Skipped “{ $title }”: it can only be read or played in Libby. +cli-download-already = Skipped “{ $title }”: already in your library at { $path } (use --force to download again). +cli-download-no-format = Skipped “{ $title }”: the library does not offer { $format } for it. +cli-download-nothing = Nothing to download: none of these titles is offered as a file. +cli-download-done = Saved “{ $title }” to { $path } +cli-download-failed = Failed “{ $title }”: { $reason } +cli-download-removed = it was removed from the queue. +cli-download-cancelled = it was cancelled. +cli-download-interrupted = Interrupted. Partial downloads are kept; run the same command again to resume. +cli-download-summary = { $done } downloaded, { $failed } failed, { $skipped } skipped. +cli-progress = [{ $index }/{ $count }] { $title } { $size } { $speed } +cli-progress-of = { $received } of { $total } +cli-progress-speed = { $speed }/s +cli-progress-state = [{ $index }/{ $count }] { $title } { $state } + +## Paths and config +cli-path-config = config file +cli-path-identity = pairing +cli-path-logs = logs +cli-path-cache = cache +cli-path-covers = covers +cli-path-state = state +cli-path-queue = download queue +cli-path-index = library index +cli-path-downloads = downloads +cli-config-invalid = The configuration is invalid: { $reason } +cli-config-defaults = No file at { $path }; these are the defaults. +cli-config-exists = { $path } already exists. Pass --force to replace it. +cli-config-written = Wrote { $path } + +## Doctor +cli-doctor-ok = ok +cli-doctor-warn = warn +cli-doctor-fail = FAIL +cli-doctor-info = info +cli-doctor-term-unset = TERM is not set +cli-doctor-color-true = 24-bit colour +cli-doctor-color-16 = 16 colours (set COLORTERM=truecolor if your terminal supports more) +cli-doctor-color-none = no colour; libbui uses the mono theme +cli-doctor-color-none-asked = no colour, as NO_COLOR asks; libbui uses the mono theme +cli-doctor-unicode-yes = UTF-8 ({ $locale }) +cli-doctor-unicode-no = locale { $locale } may not be UTF-8; try --ascii if lines look broken +cli-doctor-unicode-windows = Windows terminals are UTF-8 capable; try --ascii if lines look broken +cli-doctor-images-off = covers are off (images = "off") +cli-doctor-images-halfblocks = covers use half-blocks (images = "halfblocks") +cli-doctor-images-guess = covers will likely use the { $protocol } protocol (confirmed with the terminal at startup) +cli-doctor-images-fallback = no graphics protocol recognised; covers will use half-blocks unless the terminal answers at startup +cli-doctor-multiplexer = inside tmux or screen: graphics need passthrough; half-blocks always work +cli-doctor-size = { $cols }×{ $rows } +cli-doctor-size-small = { $cols }×{ $rows } is below the { $min_cols }×{ $min_rows } libbui needs +cli-doctor-size-unknown = not a terminal +cli-doctor-config-missing = no file at { $path }; using defaults +cli-doctor-keymap = { $count -> + [0] default key bindings + [one] one key binding override + *[other] { $count } key binding overrides +} +cli-doctor-downloads-not-dir = { $path } exists but is not a folder +cli-doctor-downloads-later = { $path } (created on the first download) +cli-doctor-paired = paired (saved { $date }) +cli-doctor-unpaired = not paired; run `libbui pair` +cli-doctor-online-ok = { $count -> + [one] Libby answered; one card + *[other] Libby answered; { $count } cards +} +cli-doctor-online-no-config = skipped: fix the configuration first +cli-doctor-summary-ok = Everything looks fine. +cli-doctor-summary-warn = Usable, with notes above. +cli-doctor-summary-fail = Something needs fixing; see FAIL above. diff --git a/crates/libbui/src/app/mod.rs b/crates/libbui/src/app/mod.rs index 36e4bec..c80134e 100644 --- a/crates/libbui/src/app/mod.rs +++ b/crates/libbui/src/app/mod.rs @@ -1317,7 +1317,7 @@ fn is_text(key: KeyEvent) -> bool { /// Lower is better: files anyone can read before files tied to Adobe, and /// reflowable EPUB before fixed-layout PDF. -const fn preference(kind: DownloadKind) -> u8 { +pub(crate) const fn preference(kind: DownloadKind) -> u8 { match kind { DownloadKind::EpubOpen => 0, DownloadKind::PdfOpen => 1, @@ -1326,7 +1326,13 @@ const fn preference(kind: DownloadKind) -> u8 { } } -fn job_spec(loan: &Loan, format: &FormatId, kind: DownloadKind, media: Option<&Media>) -> JobSpec { +/// The queue entry for downloading `loan` in `format`. +pub(crate) fn job_spec( + loan: &Loan, + format: &FormatId, + kind: DownloadKind, + media: Option<&Media>, +) -> JobSpec { let file_kind = match kind { DownloadKind::EpubOpen => FileKind::Epub, DownloadKind::PdfOpen => FileKind::Pdf, diff --git a/crates/libbui/src/cli.rs b/crates/libbui/src/cli.rs deleted file mode 100644 index c99f683..0000000 --- a/crates/libbui/src/cli.rs +++ /dev/null @@ -1,39 +0,0 @@ -//! Command-line arguments. - -use std::path::PathBuf; - -use clap::Parser; - -/// Browse, borrow and download from your library, in the terminal. -#[derive(Debug, Clone, Parser)] -#[command(name = "libbui", version, about, long_about = None)] -pub struct Args { - /// Read configuration from this file instead of the default location. - #[arg(long, value_name = "FILE", env = "LIBBUI_CONFIG")] - pub config: Option, - - /// Colour theme: auto, dark, light, ansi, high-contrast or mono. - #[arg(long, value_name = "NAME", env = "LIBBUI_THEME")] - pub theme: Option, - - /// Interface language, as a BCP 47 tag such as en-US. - #[arg(long, value_name = "TAG", env = "LIBBUI_LANG")] - pub lang: Option, - - /// Draw with ASCII characters only. - #[arg(long)] - pub ascii: bool, - - /// Leave the mouse to the terminal (keeps native text selection). - #[arg(long)] - pub no_mouse: bool, - - /// Log filter, such as `info` or `libbui=debug,libby=trace`. - #[arg( - long, - value_name = "FILTER", - env = "LIBBUI_LOG", - default_value = "info" - )] - pub log: String, -} diff --git a/crates/libbui/src/cli/account.rs b/crates/libbui/src/cli/account.rs new file mode 100644 index 0000000..b28f59c --- /dev/null +++ b/crates/libbui/src/cli/account.rs @@ -0,0 +1,734 @@ +//! The commands that talk to Libby: pairing, listings, search, and the loan +//! and hold actions. +//! +//! Each command makes the fewest account requests it can, one at a time +//! (the client paces them), and checks what it already knows before asking: +//! a title already on loan is not borrowed again, a loan that cannot be +//! renewed yet is not sent to the library. + +use std::sync::Arc; + +use jiff::Timestamp; +use jiff::tz::TimeZone; +use libbui_core::config::Config; +use libby::models::{Card, DownloadKind, Hold, Loan, Media, MediaKind, SyncState}; +use libby::{BorrowOptions, LibraryKey, SearchQuery, TitleId}; +use serde::Serialize; + +use super::exit::Failure; +use super::output::Io; +use super::session::Session; +use super::table::{Column, Table}; +use super::{Command, Env, Kind, ListArgs, PairArgs, SearchArgs, TitleArgs, UnpairArgs}; +use crate::api::Api; +use crate::t; +use crate::ui::when; + +/// What every account command needs. +pub(crate) struct Ctx<'a> { + /// Libby. + pub api: &'a dyn Api, + /// The configuration in effect. + pub config: &'a Config, + /// The time the command started. + pub now: Timestamp, + /// The zone dates are shown in. + pub zone: TimeZone, +} + +impl std::fmt::Debug for Ctx<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Ctx").field("now", &self.now).finish_non_exhaustive() + } +} + +/// Runs an account command against the real client. +pub(crate) async fn run(command: Command, env: &Env, io: &mut Io<'_>) -> Result<(), Failure> { + let config = env.config()?; + let session = Session::open(env, &config)?; + if let Command::Unpair(args) = &command { + return unpair(&session, args, io); + } + let cx = Ctx { + api: session.client(), + config: &config, + now: Timestamp::now(), + zone: TimeZone::system(), + }; + let outcome = match command { + Command::Pair(args) => pair(&cx, &args, io).await, + Command::Loans(args) => loans(&cx, &args, io).await, + Command::Holds(args) => holds(&cx, &args, io).await, + Command::Cards(args) => cards(&cx, args.json, io).await, + Command::Search(args) => search(&cx, &args, io).await, + Command::Borrow(args) => borrow(&cx, &args, io).await, + Command::Return(args) => return_loan(&cx, &args, io).await, + Command::Hold(args) => hold(&cx, &args, io).await, + Command::Renew(args) => renew(&cx, &args, io).await, + Command::Download(args) => { + let api: Arc = Arc::new(session.client().clone()); + let engine = super::download::EngineSetup::for_env(env, &config, args.dir.as_deref())?; + let interrupt = async { + // If Ctrl-C cannot be watched, the download still runs; it + // just cannot be interrupted gracefully. + if tokio::signal::ctrl_c().await.is_err() { + std::future::pending::<()>().await; + } + }; + super::download::run(&cx, api, &args, engine, interrupt, io).await + } + Command::Paths(_) + | Command::Config { .. } + | Command::Completions { .. } + | Command::Doctor(_) + | Command::Unpair(_) => unreachable!("handled before the account commands"), + }; + // A token refreshed along the way is saved even if the command failed. + let saved = session.persist(); + outcome.and(saved) +} + +// ── Pairing ──────────────────────────────────────────────────────────────── + +/// `libbui pair [CODE]`. +pub(crate) async fn pair(cx: &Ctx<'_>, args: &PairArgs, io: &mut Io<'_>) -> Result<(), Failure> { + let raw = match &args.code { + Some(code) => Some(code.clone()), + None if io.caps.in_tty => { + io.note(&t!("cli-pair-howto"))?; + io.ask(&t!("cli-pair-prompt"))? + } + None => io.read_line()?, + }; + let code: String = raw + .unwrap_or_default() + .chars() + .filter(|c| !c.is_whitespace()) + .collect(); + if code.is_empty() { + return Err(Failure::Usage(t!("cli-pair-no-code"))); + } + if code.len() != 8 || !code.bytes().all(|b| b.is_ascii_digit()) { + return Err(Failure::Usage(t!("cli-pair-bad-code"))); + } + let state = cx.api.redeem_code(&code).await?; + let rows: Vec = state.cards.iter().map(CardRow::from).collect(); + if args.output.json { + return io.json(&serde_json::json!({ "paired": true, "cards": rows })); + } + io.note(&t!("cli-paired", count = rows.len()))?; + card_table(&rows).print(io) +} + +/// `libbui unpair`. +fn unpair(session: &Session, args: &UnpairArgs, io: &mut Io<'_>) -> Result<(), Failure> { + if !session.has_identity() { + return io.note(&t!("cli-unpair-nothing")); + } + if !args.yes { + if !io.caps.in_tty { + return Err(Failure::Usage(t!("cli-unpair-needs-yes"))); + } + if !io.confirm(&t!("cli-unpair-question"))? { + return io.note(&t!("cli-unpair-kept")); + } + } + session.forget()?; + io.note(&t!("cli-unpaired")) +} + +// ── Listings ─────────────────────────────────────────────────────────────── + +/// Syncs, insisting on a pairing first so an unpaired device makes no +/// request at all. +async fn sync(cx: &Ctx<'_>) -> Result { + if !cx.api.is_linked() { + return Err(Failure::NotPaired); + } + let state = cx.api.sync().await?; + if state.is_linked() { + Ok(state) + } else { + Err(Failure::NotPaired) + } +} + +/// Whether `card` is the one the person named, by id or library key. +fn is_card(card: &Card, wanted: &str) -> bool { + card.id.as_str() == wanted + || card + .advantage_key + .as_ref() + .is_some_and(|key| key.as_str().eq_ignore_ascii_case(wanted)) +} + +fn card_list(state: &SyncState) -> String { + state + .cards + .iter() + .map(|card| match &card.advantage_key { + Some(key) => format!("{} ({key})", card.id), + None => card.id.to_string(), + }) + .collect::>() + .join(", ") +} + +/// The card named by `--card`, else the only card, else `default_card`. +fn pick_card<'s>( + state: &'s SyncState, + wanted: Option<&str>, + config: &Config, +) -> Result<&'s Card, Failure> { + if let Some(wanted) = wanted { + return state + .cards + .iter() + .find(|card| is_card(card, wanted)) + .ok_or_else(|| { + Failure::Usage(t!("cli-no-such-card", card = wanted, cards = card_list(state))) + }); + } + if let [only] = state.cards.as_slice() { + return Ok(only); + } + config + .default_card + .as_deref() + .and_then(|wanted| state.cards.iter().find(|card| is_card(card, wanted))) + .ok_or_else(|| Failure::Usage(t!("cli-choose-card", cards = card_list(state)))) +} + +/// `--card` as a filter: `None` keeps everything. +fn card_filter<'s>(state: &'s SyncState, wanted: Option<&str>) -> Result, Failure> { + wanted.map(|wanted| pick_card(state, Some(wanted), &Config::default())).transpose() +} + +fn library_name(state: &SyncState, card: &libby::CardId) -> String { + state + .card(card) + .map_or_else(|| card.to_string(), |card| card.library.name.clone()) +} + +pub(crate) fn kind_word(kind: &MediaKind) -> String { + match kind { + MediaKind::Ebook => t!("kind-ebook"), + MediaKind::Audiobook => t!("kind-audiobook"), + MediaKind::Magazine => t!("kind-magazine"), + MediaKind::Other(other) => other.clone(), + } +} + +/// The most open downloadable format of a loan. +pub(crate) fn best_download(loan: &Loan) -> Option<(libby::FormatId, DownloadKind)> { + loan.downloadable_formats() + .into_iter() + .min_by_key(|(_, kind)| crate::app::preference(*kind)) + .map(|(format, kind)| (format.id.clone(), kind)) +} + +fn get_word(kind: Option) -> String { + kind.map_or_else( + || t!("cli-libby-only"), + |kind| kind.file_extension().to_uppercase(), + ) +} + +#[derive(Debug, Serialize)] +struct CardRow { + card_id: String, + name: Option, + library: String, + library_key: Option, + loans: Option, + loan_limit: Option, + holds: Option, + hold_limit: Option, +} + +impl From<&Card> for CardRow { + fn from(card: &Card) -> Self { + let counts = card.counts.as_ref(); + let limits = card.limits.as_ref(); + Self { + card_id: card.id.to_string(), + name: card.card_name.clone(), + library: card.library.name.clone(), + library_key: card.advantage_key.as_ref().map(ToString::to_string), + loans: counts.and_then(|c| c.loan), + loan_limit: limits.and_then(|l| l.loan), + holds: counts.and_then(|c| c.hold), + hold_limit: limits.and_then(|l| l.hold), + } + } +} + +fn of(used: Option, limit: Option) -> String { + match (used, limit) { + (Some(used), Some(limit)) => t!("cli-count-of", used = used, limit = limit), + (Some(used), None) => used.to_string(), + _ => t!("cli-unknown"), + } +} + +fn card_table(rows: &[CardRow]) -> Table { + let mut table = Table::new(vec![ + Column::fixed(t!("cli-col-card")), + Column::flexible(t!("cli-col-library")), + Column::fixed(t!("cli-col-key")), + Column::fixed(t!("cli-col-loans")), + Column::fixed(t!("cli-col-holds")), + ]); + for row in rows { + table.row(vec![ + row.card_id.clone(), + row.library.clone(), + row.library_key.clone().unwrap_or_default(), + of(row.loans, row.loan_limit), + of(row.holds, row.hold_limit), + ]); + } + table +} + +/// `libbui cards`. +pub(crate) async fn cards(cx: &Ctx<'_>, json: bool, io: &mut Io<'_>) -> Result<(), Failure> { + let state = sync(cx).await?; + let rows: Vec = state.cards.iter().map(CardRow::from).collect(); + if json { + return io.json(&rows); + } + card_table(&rows).print(io) +} + +#[derive(Debug, Serialize)] +struct LoanRow { + title_id: String, + title: String, + author: Option, + kind: String, + card_id: String, + library: String, + checked_out: Option, + expires: Timestamp, + renewable: bool, + renewable_on: Option, + /// The format `download` would fetch, or `null` when the title can only + /// be read or heard in Libby. + download_format: Option, + formats: Vec, +} + +fn loan_row(state: &SyncState, loan: &Loan, now: Timestamp) -> LoanRow { + LoanRow { + title_id: loan.title_id.to_string(), + title: loan.title.clone(), + author: loan.first_creator_name.clone(), + kind: loan.kind.as_str().to_owned(), + card_id: loan.card_id.to_string(), + library: library_name(state, &loan.card_id), + checked_out: loan.checkout_date, + expires: loan.expire_date, + renewable: loan.is_renewable(now), + renewable_on: loan.renewable_on, + download_format: best_download(loan).map(|(format, _)| format.to_string()), + formats: loan.formats.iter().map(|f| f.id.to_string()).collect(), + } +} + +/// `libbui loans`. +pub(crate) async fn loans(cx: &Ctx<'_>, args: &ListArgs, io: &mut Io<'_>) -> Result<(), Failure> { + let state = sync(cx).await?; + let only = card_filter(&state, args.card.as_deref())?; + let loans: Vec<&Loan> = state + .loans + .iter() + .filter(|loan| only.is_none_or(|card| card.id == loan.card_id)) + .collect(); + if args.output.json { + let rows: Vec = loans.iter().map(|l| loan_row(&state, l, cx.now)).collect(); + return io.json(&rows); + } + if loans.is_empty() { + return io.note(&t!("cli-no-loans")); + } + let mut table = Table::new(vec![ + Column::fixed(t!("cli-col-id")), + Column::flexible(t!("cli-col-title")), + Column::flexible(t!("cli-col-author")), + Column::fixed(t!("cli-col-kind")), + Column::flexible(t!("cli-col-library")), + Column::fixed(t!("cli-col-due")), + Column::fixed(t!("cli-col-get")), + ]); + for loan in loans { + let due = t!( + "cli-due", + date = when::date_in(loan.expire_date, &cx.zone), + left = when::left(loan.expire_date, cx.now) + ); + table.row(vec![ + loan.title_id.to_string(), + loan.title.clone(), + loan.first_creator_name.clone().unwrap_or_default(), + kind_word(&loan.kind), + library_name(&state, &loan.card_id), + due, + get_word(best_download(loan).map(|(_, kind)| kind)), + ]); + } + table.print(io) +} + +#[derive(Debug, Serialize)] +struct HoldRow { + title_id: String, + title: String, + author: Option, + kind: String, + card_id: String, + library: String, + ready: bool, + suspended: bool, + position: Option, + copies: Option, + estimated_wait_days: Option, + placed: Option, +} + +fn hold_row(state: &SyncState, hold: &Hold) -> HoldRow { + HoldRow { + title_id: hold.title_id.to_string(), + title: hold.title.clone(), + author: hold.first_creator_name.clone(), + kind: hold.kind.as_str().to_owned(), + card_id: hold.card_id.to_string(), + library: library_name(state, &hold.card_id), + ready: hold.is_ready(), + suspended: hold.is_suspended(), + position: hold.hold_list_position, + copies: hold.owned_copies, + estimated_wait_days: hold.estimated_wait_days, + placed: hold.placed_date, + } +} + +fn hold_status(hold: &Hold) -> String { + if hold.is_ready() { + return t!("cli-hold-ready"); + } + if hold.is_suspended() { + return t!("cli-hold-suspended"); + } + match (hold.hold_list_position, hold.estimated_wait_days) { + (Some(position), Some(days)) if days > 0 => { + t!("cli-hold-position-wait", position = position, days = days) + } + (Some(position), _) => t!("cli-hold-position", position = position), + (None, _) => t!("cli-hold-waiting"), + } +} + +/// `libbui holds`. +pub(crate) async fn holds(cx: &Ctx<'_>, args: &ListArgs, io: &mut Io<'_>) -> Result<(), Failure> { + let state = sync(cx).await?; + let only = card_filter(&state, args.card.as_deref())?; + let holds: Vec<&Hold> = state + .holds + .iter() + .filter(|hold| only.is_none_or(|card| card.id == hold.card_id)) + .collect(); + if args.output.json { + let rows: Vec = holds.iter().map(|h| hold_row(&state, h)).collect(); + return io.json(&rows); + } + if holds.is_empty() { + return io.note(&t!("cli-no-holds")); + } + let mut table = Table::new(vec![ + Column::fixed(t!("cli-col-id")), + Column::flexible(t!("cli-col-title")), + Column::flexible(t!("cli-col-author")), + Column::fixed(t!("cli-col-kind")), + Column::flexible(t!("cli-col-library")), + Column::fixed(t!("cli-col-status")), + ]); + for hold in holds { + table.row(vec![ + hold.title_id.to_string(), + hold.title.clone(), + hold.first_creator_name.clone().unwrap_or_default(), + kind_word(&hold.kind), + library_name(&state, &hold.card_id), + hold_status(hold), + ]); + } + table.print(io) +} + +// ── Search ───────────────────────────────────────────────────────────────── + +#[derive(Debug, Serialize)] +struct SearchRow { + title_id: String, + title: String, + author: Option, + kind: String, + available: Option, + available_copies: Option, + owned_copies: Option, + holds: Option, + estimated_wait_days: Option, + download_format: Option, + formats: Vec, +} + +fn media_download(media: &Media) -> Option { + media + .formats + .iter() + .filter_map(|format| format.access().download_kind()) + .min_by_key(|kind| crate::app::preference(*kind)) +} + +fn availability(media: &Media) -> String { + let a = &media.availability; + if a.is_available == Some(true) { + return t!("cli-available"); + } + match a.estimated_wait_days { + Some(days) if days > 0 => t!("cli-wait-days", days = days), + _ if a.is_holdable == Some(true) => t!("cli-holdable"), + _ => t!("cli-unavailable"), + } +} + +/// The library to search: `--library`, `default_library`, or the default +/// card's library (one sync). +async fn search_library(cx: &Ctx<'_>, args: &SearchArgs) -> Result { + if let Some(key) = args.library.as_ref().or(cx.config.default_library.as_ref()) { + return Ok(LibraryKey::new(key.as_str())); + } + if !cx.api.is_linked() { + return Err(Failure::Usage(t!("cli-search-need-library"))); + } + let state = sync(cx).await?; + let card = match pick_card(&state, None, cx.config) { + Ok(card) => card, + // Several cards and no default: searching the first is what the + // interface does too. + Err(_) => state.cards.first().ok_or(Failure::NotPaired)?, + }; + card.advantage_key + .clone() + .ok_or_else(|| Failure::Usage(t!("cli-search-need-library"))) +} + +/// `libbui search`. +pub(crate) async fn search(cx: &Ctx<'_>, args: &SearchArgs, io: &mut Io<'_>) -> Result<(), Failure> { + let library = search_library(cx, args).await?; + let mut query = SearchQuery::new() + .text(args.query.join(" ")) + .available_only(args.available) + .per_page(args.limit) + .page(args.page); + if let Some(kind) = args.kind { + query = query.media_type(match kind { + Kind::Ebook => MediaKind::Ebook, + Kind::Audiobook => MediaKind::Audiobook, + Kind::Magazine => MediaKind::Magazine, + }); + } + let page = cx.api.search(&library, &query).await?; + if args.output.json { + let items: Vec = page + .items + .iter() + .map(|media| SearchRow { + title_id: media.id.to_string(), + title: media.title.clone(), + author: media.first_creator_name.clone(), + kind: media.kind.as_str().to_owned(), + available: media.availability.is_available, + available_copies: media.availability.available_copies, + owned_copies: media.availability.owned_copies, + holds: media.availability.holds_count, + estimated_wait_days: media.availability.estimated_wait_days, + download_format: media_download(media).map(|kind| kind.format_id().to_string()), + formats: media.formats.iter().map(|f| f.id.to_string()).collect(), + }) + .collect(); + return io.json(&serde_json::json!({ + "library": library.as_str(), + "total": page.total_items, + "page": args.page, + "next_page": page.next_page(), + "items": items, + })); + } + if page.items.is_empty() { + return io.note(&t!("cli-search-empty", library = library.as_str())); + } + let mut table = Table::new(vec![ + Column::fixed(t!("cli-col-id")), + Column::flexible(t!("cli-col-title")), + Column::flexible(t!("cli-col-author")), + Column::fixed(t!("cli-col-kind")), + Column::fixed(t!("cli-col-status")), + Column::fixed(t!("cli-col-get")), + ]); + for media in &page.items { + table.row(vec![ + media.id.to_string(), + media.title.clone(), + media.first_creator_name.clone().unwrap_or_default(), + kind_word(&media.kind), + availability(media), + get_word(media_download(media)), + ]); + } + table.print(io)?; + io.note(&t!( + "cli-search-summary", + shown = page.items.len(), + total = page.total_items, + page = args.page, + library = library.as_str() + ))?; + if let Some(next) = page.next_page() { + io.note(&t!("cli-search-next", page = next))?; + } + Ok(()) +} + +// ── Actions ──────────────────────────────────────────────────────────────── + +/// The loan of `title` the person means: on `--card` if given; it must be +/// unambiguous. +fn the_loan<'s>(state: &'s SyncState, title: &TitleId, card: Option<&str>) -> Result<&'s Loan, Failure> { + let only = card_filter(state, card)?; + let loans: Vec<&Loan> = state + .loans + .iter() + .filter(|loan| &loan.title_id == title) + .filter(|loan| only.is_none_or(|card| card.id == loan.card_id)) + .collect(); + match loans.as_slice() { + [] => Err(Failure::Failed(t!("cli-not-on-loan", id = title.as_str()))), + [loan] => Ok(loan), + _ => Err(Failure::Usage(t!("cli-choose-card", cards = card_list(state)))), + } +} + +fn single_loan(cx: &Ctx<'_>, state: &SyncState, loan: &Loan, json: bool, io: &mut Io<'_>, message: &str) -> Result<(), Failure> { + if json { + return io.json(&loan_row(state, loan, cx.now)); + } + io.line(message) +} + +/// `libbui borrow`. +pub(crate) async fn borrow(cx: &Ctx<'_>, args: &TitleArgs, io: &mut Io<'_>) -> Result<(), Failure> { + let title = TitleId::new(args.title_id.as_str()); + let state = sync(cx).await?; + if let Some(loan) = state.loans.iter().find(|loan| loan.title_id == title) { + return Err(Failure::Failed(t!("cli-already-on-loan", title = loan.title.as_str()))); + } + let card = pick_card(&state, args.card.as_deref(), cx.config)?; + if card.has_loan_room() == Some(false) { + return Err(Failure::Failed(t!("cli-loan-limit", library = card.library.name.as_str()))); + } + let library = card + .advantage_key + .as_ref() + .ok_or_else(|| Failure::Failed(t!("cli-card-no-library", card = card.id.as_str())))?; + let media = cx.api.library_media(library, &title).await?; + if media.availability.is_available == Some(false) { + return Err(Failure::Failed(t!( + "cli-not-available", + title = media.title.as_str(), + id = title.as_str() + ))); + } + let loan = cx + .api + .borrow(card, &title, &media.kind, BorrowOptions::default()) + .await?; + let message = t!( + "cli-borrowed", + title = loan.title.as_str(), + date = when::date_in(loan.expire_date, &cx.zone) + ); + single_loan(cx, &state, &loan, args.output.json, io, &message) +} + +/// `libbui return`. +pub(crate) async fn return_loan(cx: &Ctx<'_>, args: &TitleArgs, io: &mut Io<'_>) -> Result<(), Failure> { + let title = TitleId::new(args.title_id.as_str()); + let state = sync(cx).await?; + let loan = the_loan(&state, &title, args.card.as_deref())?; + cx.api.return_loan(&loan.card_id, &title).await?; + if args.output.json { + return io.json(&serde_json::json!({ + "returned": true, + "title_id": title.as_str(), + "card_id": loan.card_id.as_str(), + })); + } + io.line(&t!("cli-returned", title = loan.title.as_str())) +} + +/// `libbui renew`. +pub(crate) async fn renew(cx: &Ctx<'_>, args: &TitleArgs, io: &mut Io<'_>) -> Result<(), Failure> { + let title = TitleId::new(args.title_id.as_str()); + let state = sync(cx).await?; + let loan = the_loan(&state, &title, args.card.as_deref())?; + if !loan.is_renewable(cx.now) { + return Err(Failure::Failed(match loan.renewable_on { + Some(from) if from > cx.now => t!( + "cli-renew-not-yet", + title = loan.title.as_str(), + date = when::date_in(from, &cx.zone) + ), + _ => t!("cli-renew-not-renewable", title = loan.title.as_str()), + })); + } + let card = state + .card(&loan.card_id) + .ok_or_else(|| Failure::Failed(t!("cli-card-gone", card = loan.card_id.as_str())))?; + let renewed = cx.api.renew(card, loan).await?; + let message = t!( + "cli-renewed", + title = renewed.title.as_str(), + date = when::date_in(renewed.expire_date, &cx.zone) + ); + single_loan(cx, &state, &renewed, args.output.json, io, &message) +} + +/// `libbui hold`. +pub(crate) async fn hold(cx: &Ctx<'_>, args: &TitleArgs, io: &mut Io<'_>) -> Result<(), Failure> { + let title = TitleId::new(args.title_id.as_str()); + let state = sync(cx).await?; + if let Some(loan) = state.loans.iter().find(|loan| loan.title_id == title) { + return Err(Failure::Failed(t!("cli-already-on-loan", title = loan.title.as_str()))); + } + if let Some(hold) = state.holds.iter().find(|hold| hold.title_id == title) { + return Err(Failure::Failed(t!("cli-already-on-hold", title = hold.title.as_str()))); + } + let card = pick_card(&state, args.card.as_deref(), cx.config)?; + if card.has_hold_room() == Some(false) { + return Err(Failure::Failed(t!("cli-hold-limit", library = card.library.name.as_str()))); + } + let hold = cx.api.place_hold(&card.id, &title).await?; + if args.output.json { + return io.json(&hold_row(&state, &hold)); + } + io.line(&t!( + "cli-hold-placed", + title = hold.title.as_str(), + status = hold_status(&hold) + )) +} + +#[cfg(test)] +mod tests; diff --git a/crates/libbui/src/cli/account/tests.rs b/crates/libbui/src/cli/account/tests.rs new file mode 100644 index 0000000..07c2880 --- /dev/null +++ b/crates/libbui/src/cli/account/tests.rs @@ -0,0 +1 @@ +//! Tests. diff --git a/crates/libbui/src/cli/doctor.rs b/crates/libbui/src/cli/doctor.rs new file mode 100644 index 0000000..fa843a4 --- /dev/null +++ b/crates/libbui/src/cli/doctor.rs @@ -0,0 +1,357 @@ +//! `libbui doctor`: what libbui sees of this terminal and setup. +//! +//! Everything is read from the environment and local files; nothing is +//! sent anywhere unless `--online` is given, and then only one sync. +//! The graphics protocol is a guess from well-known environment variables: +//! the interface asks the terminal itself at startup, which a command whose +//! output may be piped must not do. + +use std::path::Path; + +use libbui_core::config::{Config, Images}; +use libbui_core::identity::{FileStore, SecretStore}; +use libbui_core::template::Template; +use serde::Serialize; + +use super::exit::{FAILURE, Failure}; +use super::output::{Io, Tone}; +use super::session::Session; +use super::table::{Column, Table}; +use super::{DoctorArgs, Env}; +use crate::keymap::Keymap; +use crate::t; +use crate::theme::ColorDepth; + +/// How a check came out. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum Status { + /// Fine. + Ok, + /// Works, but could be better. + Warn, + /// Broken. + Fail, + /// Just so you know. + Info, +} + +impl Status { + fn word(self) -> String { + match self { + Self::Ok => t!("cli-doctor-ok"), + Self::Warn => t!("cli-doctor-warn"), + Self::Fail => t!("cli-doctor-fail"), + Self::Info => t!("cli-doctor-info"), + } + } + + fn tone(self) -> Tone { + match self { + Self::Ok => Tone::Good, + Self::Warn => Tone::Warn, + Self::Fail => Tone::Bad, + Self::Info => Tone::Muted, + } + } +} + +/// One line of the report. +#[derive(Debug, Clone, Serialize)] +pub(crate) struct Check { + /// Stable id, for scripts. + pub id: &'static str, + /// How it came out. + pub status: Status, + /// What was found. + pub detail: String, +} + +fn check(id: &'static str, status: Status, detail: String) -> Check { + Check { id, status, detail } +} + +/// The terminal checks, from environment variables only. +pub(crate) fn terminal(lookup: &dyn Fn(&str) -> Option, size: Option<(u16, u16)>, images: &Images) -> Vec { + let mut checks = Vec::new(); + let term = lookup("TERM").unwrap_or_default(); + checks.push(check( + "term", + if term.is_empty() || term == "dumb" { Status::Warn } else { Status::Info }, + if term.is_empty() { t!("cli-doctor-term-unset") } else { term.clone() }, + )); + + let depth = ColorDepth::detect(|name| lookup(name)); + let (status, detail) = match depth { + ColorDepth::TrueColor => (Status::Ok, t!("cli-doctor-color-true")), + ColorDepth::Ansi16 => (Status::Info, t!("cli-doctor-color-16")), + ColorDepth::None if lookup("NO_COLOR").is_some_and(|v| !v.is_empty()) => { + (Status::Info, t!("cli-doctor-color-none-asked")) + } + ColorDepth::None => (Status::Warn, t!("cli-doctor-color-none")), + }; + checks.push(check("color", status, detail)); + + let locale = ["LC_ALL", "LC_CTYPE", "LANG"] + .iter() + .find_map(|name| lookup(name).filter(|v| !v.is_empty())); + let utf8 = locale.as_deref().is_some_and(|l| { + let l = l.to_ascii_lowercase(); + l.contains("utf-8") || l.contains("utf8") + }); + checks.push(match (cfg!(windows), utf8) { + (true, _) => check("unicode", Status::Info, t!("cli-doctor-unicode-windows")), + (false, true) => check("unicode", Status::Ok, t!("cli-doctor-unicode-yes", locale = locale.unwrap_or_default())), + (false, false) => check( + "unicode", + Status::Warn, + t!("cli-doctor-unicode-no", locale = locale.unwrap_or_else(|| t!("cli-unknown"))), + ), + }); + + let (status, detail) = match images { + Images::Off => (Status::Info, t!("cli-doctor-images-off")), + Images::Halfblocks => (Status::Info, t!("cli-doctor-images-halfblocks")), + Images::Auto => match graphics_guess(lookup) { + Some(protocol) => (Status::Ok, t!("cli-doctor-images-guess", protocol = protocol)), + None => (Status::Info, t!("cli-doctor-images-fallback")), + }, + }; + checks.push(check("images", status, detail)); + if lookup("TMUX").is_some() || term.starts_with("screen") || term.starts_with("tmux") { + checks.push(check("multiplexer", Status::Info, t!("cli-doctor-multiplexer"))); + } + + let (min_cols, min_rows) = crate::app::MIN_SIZE; + checks.push(match size { + Some((cols, rows)) if cols >= min_cols && rows >= min_rows => check( + "size", + Status::Ok, + t!("cli-doctor-size", cols = cols, rows = rows), + ), + Some((cols, rows)) => check( + "size", + Status::Warn, + t!("cli-doctor-size-small", cols = cols, rows = rows, min_cols = min_cols, min_rows = min_rows), + ), + None => check("size", Status::Info, t!("cli-doctor-size-unknown")), + }); + checks +} + +/// The image protocol a terminal is known for, from its environment. +fn graphics_guess(lookup: &dyn Fn(&str) -> Option) -> Option<&'static str> { + let term = lookup("TERM").unwrap_or_default(); + let program = lookup("TERM_PROGRAM").unwrap_or_default(); + if lookup("KITTY_WINDOW_ID").is_some() || term == "xterm-kitty" || term == "xterm-ghostty" || program == "ghostty" { + return Some("kitty"); + } + match program.as_str() { + "iTerm.app" | "WezTerm" | "vscode" => return Some("iterm2"), + _ => {} + } + if lookup("KONSOLE_VERSION").is_some() { + return Some("kitty"); + } + if term.starts_with("foot") || term.contains("mlterm") || term.contains("sixel") || lookup("WT_SESSION").is_some() { + return Some("sixel"); + } + None +} + +/// The configuration and pairing checks. +fn setup(env: &Env) -> (Vec, Option) { + let mut checks = Vec::new(); + let file = &env.config_file; + let config = match Config::load(file) { + Ok(config) => { + checks.push(if file.exists() { + check("config", Status::Ok, file.display().to_string()) + } else { + check("config", Status::Info, t!("cli-doctor-config-missing", path = file.display().to_string())) + }); + Some(config) + } + Err(error) => { + checks.push(check("config", Status::Fail, error.to_string())); + None + } + }; + if let Some(config) = &config { + checks.push(match Keymap::with_overrides(&config.keymap) { + Ok(_) => check("keymap", Status::Ok, t!("cli-doctor-keymap", count = config.keymap.len())), + Err(error) => check("keymap", Status::Fail, error.to_string()), + }); + checks.push(match Template::parse(&config.templates.ebook) { + Ok(_) => check("template", Status::Ok, config.templates.ebook.clone()), + Err(error) => check("template", Status::Fail, error.to_string()), + }); + let dir = config.download_dir(&env.paths); + checks.push(download_dir(&dir)); + } + let store = FileStore::new(env.paths.identity_file()); + checks.push(match store.load() { + Ok(Some(stored)) => check( + "pairing", + Status::Ok, + t!("cli-doctor-paired", date = crate::ui::when::date(stored.saved_at)), + ), + Ok(None) => check("pairing", Status::Warn, t!("cli-doctor-unpaired")), + Err(error) => check("pairing", Status::Fail, error.to_string()), + }); + (checks, config) +} + +fn download_dir(dir: &Path) -> Check { + let shown = dir.display().to_string(); + match std::fs::metadata(dir) { + Ok(meta) if meta.is_dir() => check("downloads", Status::Ok, shown), + Ok(_) => check("downloads", Status::Fail, t!("cli-doctor-downloads-not-dir", path = shown)), + Err(_) => check("downloads", Status::Info, t!("cli-doctor-downloads-later", path = shown)), + } +} + +/// `libbui doctor`. +pub(crate) async fn run(env: &Env, args: &DoctorArgs, log: &str, io: &mut Io<'_>) -> Result<(), Failure> { + let mut checks = vec![check("version", Status::Info, env!("CARGO_PKG_VERSION").to_owned())]; + let (setup_checks, config) = setup(env); + let images = config.as_ref().map_or(Images::Auto, |c| c.images.clone()); + let size = crossterm::terminal::size().ok(); + checks.extend(terminal(&|name| std::env::var(name).ok(), size, &images)); + checks.extend(setup_checks); + + if args.online { + checks.push(online(env, config.as_ref(), log).await); + } + + if args.output.json { + io.json(&checks)?; + } else { + let mut table = Table::new(vec![ + Column::fixed(t!("cli-col-check")), + Column::fixed(t!("cli-col-status")), + Column::flexible(t!("cli-col-detail")), + ]); + for c in &checks { + table.row(vec![c.id.to_owned(), c.status.word(), c.detail.clone()]); + } + // Paint after measuring would break alignment; the status word + // carries the meaning on its own. + table.print(io)?; + let worst = checks + .iter() + .map(|c| c.status) + .find(|s| *s == Status::Fail) + .or_else(|| checks.iter().map(|c| c.status).find(|s| *s == Status::Warn)); + let summary = match worst { + Some(Status::Fail) => io.paint(Status::Fail.tone(), &t!("cli-doctor-summary-fail")), + Some(Status::Warn) => io.paint(Status::Warn.tone(), &t!("cli-doctor-summary-warn")), + _ => io.paint(Status::Ok.tone(), &t!("cli-doctor-summary-ok")), + }; + io.note(&summary)?; + } + if checks.iter().any(|c| c.status == Status::Fail) { + Err(Failure::Reported(FAILURE)) + } else { + Ok(()) + } +} + +/// One sync, to see whether the pairing still works. +async fn online(env: &Env, config: Option<&Config>, log: &str) -> Check { + let Some(config) = config else { + return check("online", Status::Fail, t!("cli-doctor-online-no-config")); + }; + let _log = libbui_core::logging::init(&env.paths, log); + let session = match Session::open(env, config) { + Ok(session) => session, + Err(failure) => return check("online", Status::Fail, failure.message().unwrap_or_default()), + }; + if !session.has_identity() { + return check("online", Status::Warn, t!("cli-doctor-unpaired")); + } + let result = crate::api::Api::sync(session.client()).await; + let _ = session.persist(); + match result { + Ok(state) if state.is_linked() => check("online", Status::Ok, t!("cli-doctor-online-ok", count = state.cards.len())), + Ok(_) => check("online", Status::Fail, t!("cli-not-paired")), + Err(error) => match Failure::from(error) { + Failure::NotPaired => check("online", Status::Fail, t!("cli-not-paired")), + other => check("online", Status::Fail, other.message().unwrap_or_default()), + }, + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + + fn lookup(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option { + move |name| pairs.iter().find(|(k, _)| *k == name).map(|(_, v)| (*v).to_owned()) + } + + fn find<'a>(checks: &'a [Check], id: &str) -> &'a Check { + checks.iter().find(|c| c.id == id).unwrap() + } + + #[test] + fn a_modern_terminal_is_all_good() { + let env = lookup(&[ + ("TERM", "xterm-kitty"), + ("COLORTERM", "truecolor"), + ("LANG", "en_US.UTF-8"), + ]); + let checks = terminal(&env, Some((120, 40)), &Images::Auto); + assert_eq!(find(&checks, "color").status, Status::Ok); + assert_eq!(find(&checks, "images").detail, t!("cli-doctor-images-guess", protocol = "kitty")); + assert_eq!(find(&checks, "size").status, Status::Ok); + if !cfg!(windows) { + assert_eq!(find(&checks, "unicode").status, Status::Ok); + } + } + + #[test] + fn a_bare_terminal_gets_advice() { + let env = lookup(&[("TERM", "dumb"), ("LANG", "C")]); + let checks = terminal(&env, Some((40, 10)), &Images::Auto); + assert_eq!(find(&checks, "term").status, Status::Warn); + assert_eq!(find(&checks, "color").status, Status::Warn); + assert_eq!(find(&checks, "size").status, Status::Warn); + if !cfg!(windows) { + assert_eq!(find(&checks, "unicode").status, Status::Warn); + } + } + + #[test] + fn no_color_is_respected_not_flagged() { + let env = lookup(&[("TERM", "xterm-256color"), ("NO_COLOR", "1")]); + let checks = terminal(&env, None, &Images::Off); + assert_eq!(find(&checks, "color").status, Status::Info); + assert_eq!(find(&checks, "images").detail, t!("cli-doctor-images-off")); + } + + #[test] + fn graphics_are_guessed_from_well_known_variables() { + assert_eq!(graphics_guess(&lookup(&[("TERM_PROGRAM", "iTerm.app")])), Some("iterm2")); + assert_eq!(graphics_guess(&lookup(&[("TERM", "foot")])), Some("sixel")); + assert_eq!(graphics_guess(&lookup(&[("TERM", "xterm-256color")])), None); + } + + #[test] + fn setup_reports_a_broken_config_and_no_pairing() { + let dir = tempfile::tempdir().unwrap(); + let paths = libbui_core::paths::Paths::rooted_at(dir.path()); + std::fs::create_dir_all(&paths.config_dir).unwrap(); + std::fs::write(paths.config_file(), "theme = \n").unwrap(); + let env = Env { + config_file: paths.config_file(), + paths, + }; + let (checks, config) = setup(&env); + assert!(config.is_none()); + assert_eq!(find(&checks, "config").status, Status::Fail); + assert_eq!(find(&checks, "pairing").status, Status::Warn); + } +} diff --git a/crates/libbui/src/cli/download.rs b/crates/libbui/src/cli/download.rs new file mode 100644 index 0000000..fe2efef --- /dev/null +++ b/crates/libbui/src/cli/download.rs @@ -0,0 +1,509 @@ +//! `libbui download`: the download engine, headless. +//! +//! The same engine as the interface's Downloads tab, with the same boundary: +//! only open EPUB and PDF files and Adobe `.acsm` tokens are fetched, saved +//! as served. Everything else is reported as "Libby only" and skipped. +//! +//! The command keeps its own queue file (under the state directory's `cli` +//! folder) so it never starts, pauses or removes jobs the interface queued. +//! Finished books go into the shared library index, so the interface sees +//! them. An interrupted run leaves its jobs paused; running the same command +//! again resumes them. + +use std::collections::{BTreeMap, BTreeSet}; +use std::future::Future; +use std::path::Path; +use std::sync::Arc; + +use libbui_core::config::Config; +use libbui_core::download::{Engine, EngineHandle, Event, Job, JobId, JobState, Settings}; +use libbui_core::library::{LibraryIndex, Presence}; +use libbui_core::paths::Paths; +use libby::models::{DownloadKind, Loan}; +use libby::{FormatId, TitleId}; +use serde::Serialize; +use tokio::sync::mpsc::UnboundedReceiver; + +use super::account::{Ctx, best_download}; +use super::exit::Failure; +use super::output::{Io, Tone}; +use super::{DownloadArgs, Env}; +use crate::api::Api; +use crate::services::LoanResolver; +use crate::t; +use crate::ui::text::{bytes, truncate, width}; + +/// Where and how the engine runs. +#[derive(Debug, Clone)] +pub(crate) struct EngineSetup { + /// Paths, with the state directory moved to the command's own folder. + pub paths: Paths, + /// Library folder, template, concurrency, sidecars. + pub settings: Settings, + /// The plain HTTP client for content (never the account client). + pub client: reqwest::Client, +} + +impl EngineSetup { + /// The real setup for `env`, with `dir` replacing `download_dir`. + pub(crate) fn for_env(env: &Env, config: &Config, dir: Option<&Path>) -> Result { + let mut settings = Settings::from_config(config, &env.paths) + .map_err(|error| Failure::Failed(t!("cli-bad-template", reason = error.to_string())))?; + if let Some(dir) = dir { + settings.library_dir = env.paths.expand_tilde(dir); + } + let client = crate::startup::content_client() + .map_err(|error| Failure::Failed(t!("cli-client-failed", reason = error.to_string())))?; + Ok(Self { + paths: cli_paths(&env.paths), + settings, + client, + }) + } +} + +/// `paths` with the download queue moved to the command line's own file. +pub(crate) fn cli_paths(paths: &Paths) -> Paths { + let mut paths = paths.clone(); + paths.state_dir = paths.state_dir.join("cli"); + paths +} + +/// What happened to one title. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +enum Outcome { + /// Saved; `path` says where. + Done, + /// Already in the library (use `--force` to fetch again). + AlreadyDownloaded, + /// Can only be read or heard in Libby. + LibbyOnly, + /// The requested `--format` is not offered for this loan. + NoSuchFormat, + /// The download failed. + Failed, + /// Stopped by Ctrl-C; running the command again resumes it. + Paused, +} + +#[derive(Debug, Clone, Serialize)] +struct Report { + title_id: String, + title: String, + outcome: Outcome, + format: Option, + path: Option, + reason: Option, +} + +impl Report { + fn new(loan: &Loan, outcome: Outcome) -> Self { + Self { + title_id: loan.title_id.to_string(), + title: loan.title.clone(), + outcome, + format: None, + path: None, + reason: None, + } + } +} + +/// The plan: which loans to fetch in which format, and which to skip. +fn plan<'s>( + loans: &'s [Loan], + args: &DownloadArgs, + card: Option<&libby::CardId>, + index: &LibraryIndex, +) -> Result<(Vec<(&'s Loan, FormatId, DownloadKind)>, Vec), Failure> { + let on_card = |loan: &&Loan| card.is_none_or(|card| &loan.card_id == card); + let chosen: Vec<&Loan> = if args.all { + loans.iter().filter(on_card).collect() + } else { + let mut chosen = Vec::new(); + let mut seen = BTreeSet::new(); + for id in &args.titles { + if !seen.insert(id.as_str()) { + continue; + } + let title = TitleId::new(id.as_str()); + let mut matches = loans.iter().filter(|loan| loan.title_id == title).filter(on_card); + match (matches.next(), matches.next()) { + (Some(loan), None) => chosen.push(loan), + (None, _) => return Err(Failure::Failed(t!("cli-not-on-loan", id = id.as_str()))), + (Some(_), Some(_)) => return Err(Failure::Usage(t!("cli-download-choose-card", id = id.as_str()))), + } + } + chosen + }; + let wanted = args.format.as_deref().map(FormatId::new); + let mut fetch = Vec::new(); + let mut skipped = Vec::new(); + for loan in chosen { + let choice = match &wanted { + Some(wanted) => { + let offered = loan + .downloadable_formats() + .into_iter() + .find(|(format, _)| &format.id == wanted) + .map(|(format, kind)| (format.id.clone(), kind)); + match offered { + Some(choice) => Some(choice), + None if best_download(loan).is_some() => { + let mut report = Report::new(loan, Outcome::NoSuchFormat); + report.format = Some(wanted.to_string()); + skipped.push(report); + continue; + } + None => None, + } + } + None => best_download(loan), + }; + let Some((format, kind)) = choice else { + skipped.push(Report::new(loan, Outcome::LibbyOnly)); + continue; + }; + let present = index + .for_title(loan.title_id.as_str()) + .find(|entry| entry.presence() == Presence::Present); + if let (Some(entry), false) = (present, args.force) { + let mut report = Report::new(loan, Outcome::AlreadyDownloaded); + report.path = Some(entry.path.display().to_string()); + skipped.push(report); + continue; + } + fetch.push((loan, format, kind)); + } + Ok((fetch, skipped)) +} + +/// Runs `download`. `interrupt` resolves when the person presses Ctrl-C. +pub(crate) async fn run( + cx: &Ctx<'_>, + api: Arc, + args: &DownloadArgs, + setup: EngineSetup, + interrupt: impl Future, + io: &mut Io<'_>, +) -> Result<(), Failure> { + if !cx.api.is_linked() { + return Err(Failure::NotPaired); + } + let state = cx.api.sync().await?; + if !state.is_linked() { + return Err(Failure::NotPaired); + } + let card = match args.card.as_deref() { + Some(wanted) => Some( + state + .cards + .iter() + .find(|card| { + card.id.as_str() == wanted + || card.advantage_key.as_ref().is_some_and(|key| key.as_str().eq_ignore_ascii_case(wanted)) + }) + .map(|card| card.id.clone()) + .ok_or_else(|| Failure::Usage(t!("cli-no-such-card", card = wanted, cards = String::new())))?, + ), + None => None, + }; + let index = LibraryIndex::load(setup.paths.library_index_file()) + .map_err(|error| Failure::Failed(error.to_string()))?; + let (fetch, mut reports) = plan(&state.loans, args, card.as_ref(), &index)?; + + for report in &reports { + let line = match report.outcome { + Outcome::LibbyOnly => t!("cli-download-libby-only", title = report.title.as_str()), + Outcome::AlreadyDownloaded => t!( + "cli-download-already", + title = report.title.as_str(), + path = report.path.clone().unwrap_or_default() + ), + Outcome::NoSuchFormat => t!( + "cli-download-no-format", + title = report.title.as_str(), + format = report.format.clone().unwrap_or_default() + ), + Outcome::Done | Outcome::Failed | Outcome::Paused => continue, + }; + let line = io.paint(Tone::Muted, &line); + io.note(&line)?; + } + + if fetch.is_empty() { + let any_present = reports.iter().any(|r| r.outcome == Outcome::AlreadyDownloaded); + if args.output.json { + io.json(&reports)?; + } + if any_present && reports.iter().all(|r| r.outcome == Outcome::AlreadyDownloaded) { + return Ok(()); + } + let message = if reports.is_empty() { t!("cli-no-loans") } else { t!("cli-download-nothing") }; + return Err(Failure::Failed(message)); + } + + let resolver = Arc::new(LoanResolver::with_loans(api, state.loans.clone())); + let (engine, events) = Engine::start(&setup.paths, setup.settings, resolver, setup.client) + .map_err(|error| Failure::Failed(error.to_string()))?; + let outcome = drive(cx, &engine, events, &fetch, interrupt, io).await; + let shutdown = engine.shutdown().await; + let mut finished = outcome?; + shutdown.map_err(|error| Failure::Failed(error.to_string()))?; + + let interrupted = finished.iter().any(|r| r.outcome == Outcome::Paused); + let failed = finished.iter().filter(|r| r.outcome == Outcome::Failed).count(); + let done = finished.iter().filter(|r| r.outcome == Outcome::Done).count(); + reports.append(&mut finished); + if args.output.json { + io.json(&reports)?; + } else { + io.note(&t!("cli-download-summary", done = done, failed = failed, skipped = reports.len() - done - failed))?; + } + if interrupted { + Err(Failure::Interrupted) + } else if failed > 0 { + Err(Failure::Reported(super::exit::FAILURE)) + } else { + Ok(()) + } +} + +/// Queues the jobs and follows them until each one finishes or Ctrl-C. +async fn drive( + cx: &Ctx<'_>, + engine: &EngineHandle, + mut events: UnboundedReceiver, + fetch: &[(&Loan, FormatId, DownloadKind)], + interrupt: impl Future, + io: &mut Io<'_>, +) -> Result, Failure> { + // Jobs left by an earlier run: resume the ones asked for again, drop the + // rest (this queue only ever holds the current batch). + let leftovers = engine.snapshot().await.map_err(engine_failure)?; + let mut pending: BTreeMap = BTreeMap::new(); + let mut reused = BTreeSet::new(); + for job in leftovers { + let asked = fetch.iter().find(|(loan, format, _)| { + loan.title_id.as_str() == job.spec.title_id && format.as_str() == job.spec.format_id + }); + match (asked, &job.state) { + (Some((loan, _, _)), JobState::Paused) => { + engine.resume(job.id()).await.map_err(engine_failure)?; + pending.insert(job.id().clone(), loan); + reused.insert(job.spec.title_id.clone()); + } + (Some((loan, _, _)), JobState::Failed { .. } | JobState::Cancelled) => { + engine.retry(job.id()).await.map_err(engine_failure)?; + pending.insert(job.id().clone(), loan); + reused.insert(job.spec.title_id.clone()); + } + (Some((loan, _, _)), state) if !state.is_terminal() => { + pending.insert(job.id().clone(), loan); + reused.insert(job.spec.title_id.clone()); + } + _ => { + engine.remove(job.id()).await.map_err(engine_failure)?; + } + } + } + for (loan, format, kind) in fetch { + if reused.contains(loan.title_id.as_str()) { + continue; + } + let spec = crate::app::job_spec(loan, format, *kind, None); + let job = engine.enqueue(spec).await.map_err(engine_failure)?; + pending.insert(job.id().clone(), loan); + } + let total = pending.len(); + let mut progress = Progress::new(io.caps.err_tty, total); + let mut reports = Vec::new(); + tokio::pin!(interrupt); + + while !pending.is_empty() { + let event = tokio::select! { + event = events.recv() => event, + () = &mut interrupt => { + progress.clear(io)?; + for (id, loan) in std::mem::take(&mut pending) { + // Pausing keeps the partial file for the next run. + if let Err(error) = engine.pause(&id).await { + tracing::warn!(%error, "could not pause a download on interrupt"); + } + reports.push(Report::new(loan, Outcome::Paused)); + } + io.note(&t!("cli-download-interrupted"))?; + break; + } + }; + let Some(event) = event else { + return Err(engine_failure(libbui_core::download::EngineError::Stopped)); + }; + match event { + Event::Progress(sample) => { + if let Some(loan) = pending.get(&sample.id) { + progress.update(io, loan, sample.received, sample.total, sample.bytes_per_sec)?; + } + } + Event::Added(job) | Event::Changed(job) => { + let Some(loan) = pending.get(job.id()).copied() else { + continue; + }; + if let Some(report) = settle(&job, loan) { + pending.remove(job.id()); + progress.finished(io, &report, cx)?; + reports.push(report); + } else { + progress.state(io, loan, &job)?; + } + } + Event::Removed(job) => { + if let Some(loan) = pending.remove(job.id()) { + let mut report = Report::new(loan, Outcome::Failed); + report.reason = Some(t!("cli-download-removed")); + progress.finished(io, &report, cx)?; + reports.push(report); + } + } + Event::PersistFailed { message } => { + progress.clear(io)?; + io.note(&t!("download-persist-failed", reason = message))?; + } + } + } + progress.clear(io)?; + Ok(reports) +} + +fn engine_failure(error: libbui_core::download::EngineError) -> Failure { + Failure::Failed(t!("cli-engine-failed", reason = error.to_string())) +} + +/// The report for a job that has finished, or `None` while it runs. +fn settle(job: &Job, loan: &Loan) -> Option { + let (outcome, path, reason) = match &job.state { + JobState::Done { path, .. } => (Outcome::Done, Some(path.display().to_string()), None), + JobState::Failed { message, .. } => (Outcome::Failed, None, Some(message.clone())), + JobState::Cancelled => (Outcome::Failed, None, Some(t!("cli-download-cancelled"))), + _ => return None, + }; + Some(Report { + format: Some(job.spec.format_id.clone()), + path, + reason, + ..Report::new(loan, outcome) + }) +} + +/// Progress on standard error: one line redrawn in place on a terminal, +/// a line per finished title otherwise. No spinner: the byte counts move. +#[derive(Debug)] +struct Progress { + live: bool, + total: usize, + finished: usize, + drawn: bool, +} + +impl Progress { + fn new(live: bool, total: usize) -> Self { + Self { + live, + total, + finished: 0, + drawn: false, + } + } + + fn draw(&mut self, io: &mut Io<'_>, text: &str) -> Result<(), Failure> { + if !self.live { + return Ok(()); + } + let text = truncate(text, io.caps.width.saturating_sub(1).max(1), "…"); + write!(io.err, "\r\x1b[2K{text}")?; + io.err.flush()?; + self.drawn = width(&text) > 0; + Ok(()) + } + + fn clear(&mut self, io: &mut Io<'_>) -> Result<(), Failure> { + if self.drawn { + write!(io.err, "\r\x1b[2K")?; + io.err.flush()?; + self.drawn = false; + } + Ok(()) + } + + fn update( + &mut self, + io: &mut Io<'_>, + loan: &Loan, + received: u64, + total: Option, + speed: f64, + ) -> Result<(), Failure> { + let size = match total { + Some(total) => t!("cli-progress-of", received = bytes(received), total = bytes(total)), + None => bytes(received), + }; + let line = t!( + "cli-progress", + index = self.finished + 1, + count = self.total, + title = loan.title.as_str(), + size = size, + speed = speed_text(speed) + ); + self.draw(io, &line) + } + + fn state(&mut self, io: &mut Io<'_>, loan: &Loan, job: &Job) -> Result<(), Failure> { + let line = t!( + "cli-progress-state", + index = self.finished + 1, + count = self.total, + title = loan.title.as_str(), + state = job.state.name() + ); + self.draw(io, &line) + } + + fn finished(&mut self, io: &mut Io<'_>, report: &Report, _cx: &Ctx<'_>) -> Result<(), Failure> { + self.clear(io)?; + self.finished += 1; + let line = match report.outcome { + Outcome::Done => { + let line = t!( + "cli-download-done", + title = report.title.as_str(), + path = report.path.clone().unwrap_or_default() + ); + io.paint(Tone::Good, &line) + } + _ => { + let line = t!( + "cli-download-failed", + title = report.title.as_str(), + reason = report.reason.clone().unwrap_or_default() + ); + io.paint(Tone::Bad, &line) + } + }; + io.note(&line) + } +} + +fn speed_text(bytes_per_sec: f64) -> String { + if bytes_per_sec < 1.0 { + return String::new(); + } + // Speeds are far below u64::MAX; the cast only drops the fraction. + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] + let whole = bytes_per_sec as u64; + t!("cli-progress-speed", speed = bytes(whole)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/libbui/src/cli/download/tests.rs b/crates/libbui/src/cli/download/tests.rs new file mode 100644 index 0000000..07c2880 --- /dev/null +++ b/crates/libbui/src/cli/download/tests.rs @@ -0,0 +1 @@ +//! Tests. diff --git a/crates/libbui/src/cli/exit.rs b/crates/libbui/src/cli/exit.rs new file mode 100644 index 0000000..204ad01 --- /dev/null +++ b/crates/libbui/src/cli/exit.rs @@ -0,0 +1,135 @@ +//! Exit codes and the failures that lead to them. +//! +//! Scripts branch on these, so they are stable: `0` success, `1` the command +//! failed, `2` it was used wrongly (clap uses `2` for its own usage errors +//! too), `3` this device is not paired with Libby, `130` interrupted. + +use std::io::{self, Write}; +use std::process::ExitCode; + +use crate::t; + +/// Everything worked. +pub const OK: u8 = 0; +/// The command ran and failed, or nothing could be done. +pub const FAILURE: u8 = 1; +/// The command line or the input was wrong. +pub const USAGE: u8 = 2; +/// This device is not paired with a Libby account. +pub const NOT_PAIRED: u8 = 3; +/// Stopped by Ctrl-C. +pub const INTERRUPTED: u8 = 130; + +/// Why a command did not succeed. +#[derive(Debug)] +pub enum Failure { + /// The command failed; the message says why. + Failed(String), + /// The command was used wrongly; the message says how to use it. + Usage(String), + /// The account commands need a pairing first. + NotPaired, + /// Stopped by Ctrl-C. + Interrupted, + /// The reader of standard output went away (`libbui loans | head`). + /// Not an error: there is nobody left to tell. + BrokenPipe, + /// The command already explained itself; only the code is left. + Reported(u8), +} + +impl Failure { + /// The exit code. + #[must_use] + pub fn code(&self) -> u8 { + match self { + Self::Failed(_) => FAILURE, + Self::Usage(_) => USAGE, + Self::NotPaired => NOT_PAIRED, + Self::Interrupted => INTERRUPTED, + Self::BrokenPipe => OK, + Self::Reported(code) => *code, + } + } + + /// What to tell the person, if anything. + #[must_use] + pub fn message(&self) -> Option { + match self { + Self::Failed(message) | Self::Usage(message) => Some(message.clone()), + Self::NotPaired => Some(t!("cli-not-paired")), + Self::Interrupted => Some(t!("cli-interrupted")), + Self::BrokenPipe | Self::Reported(_) => None, + } + } +} + +impl From for Failure { + fn from(error: io::Error) -> Self { + if error.kind() == io::ErrorKind::BrokenPipe { + Self::BrokenPipe + } else { + Self::Failed(t!("cli-io-failed", reason = error.to_string())) + } + } +} + +impl From for Failure { + fn from(error: libby::Error) -> Self { + if error.needs_pairing() { + Self::NotPaired + } else { + Self::Failed(crate::app::errors::describe(&error)) + } + } +} + +/// Reports `outcome` on `err` and turns it into the process exit code. +pub fn finish(outcome: Result<(), Failure>, err: &mut dyn Write) -> ExitCode { + let failure = match outcome { + Ok(()) => return ExitCode::from(OK), + Err(failure) => failure, + }; + if let Some(message) = failure.message() { + // Standard error is the last channel there is; if it is gone too, + // the exit code still carries the outcome. + let _ = writeln!(err, "{}", t!("cli-error", message = message)); + } + ExitCode::from(failure.code()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn codes_are_distinct_and_stable() { + assert_eq!(Failure::Failed(String::new()).code(), 1); + assert_eq!(Failure::Usage(String::new()).code(), 2); + assert_eq!(Failure::NotPaired.code(), 3); + assert_eq!(Failure::Interrupted.code(), 130); + assert_eq!(Failure::BrokenPipe.code(), 0); + } + + #[test] + fn a_closed_pipe_is_quiet() { + let failure = Failure::from(io::Error::from(io::ErrorKind::BrokenPipe)); + assert!(matches!(failure, Failure::BrokenPipe)); + assert_eq!(failure.message(), None); + } + + #[test] + fn an_unlinked_identity_means_not_paired() { + assert!(matches!( + Failure::from(libby::Error::Unlinked), + Failure::NotPaired + )); + } + + #[test] + fn failures_are_reported_on_stderr() { + let mut err = Vec::new(); + let _ = finish(Err(Failure::Failed("boom".into())), &mut err); + assert_eq!(String::from_utf8(err).unwrap_or_default(), "libbui: boom\n"); + } +} diff --git a/crates/libbui/src/cli/local.rs b/crates/libbui/src/cli/local.rs new file mode 100644 index 0000000..1dabf7e --- /dev/null +++ b/crates/libbui/src/cli/local.rs @@ -0,0 +1,225 @@ +//! Commands that only touch local files: `paths`, `config`, `completions`. +//! None of them makes a network request or starts logging. + +use std::path::Path; + +use clap::CommandFactory; +use libbui_core::config::{Config, DEFAULT_CONFIG_TOML}; +use serde::Serialize; + +use super::exit::Failure; +use super::output::{Io, Tone}; +use super::table::{Column, Table}; +use super::{Args, ConfigCommand, Env, JsonArg}; +use crate::t; + +#[derive(Debug, Serialize)] +struct PathsReport { + config_file: String, + identity_file: String, + log_dir: String, + cache_dir: String, + covers_dir: String, + state_dir: String, + queue_file: String, + library_index: String, + download_dir: String, +} + +fn shown(path: &Path) -> String { + path.display().to_string() +} + +/// `libbui paths`. +pub(crate) fn paths(env: &Env, args: &JsonArg, io: &mut Io<'_>) -> Result<(), Failure> { + // The download folder comes from the config; a broken config is still + // worth locating, so fall back to the default and say so. + let (download_dir, config_note) = match env.config() { + Ok(config) => (config.download_dir(&env.paths), None), + Err(Failure::Failed(reason)) => (env.paths.default_download_dir.clone(), Some(reason)), + Err(other) => return Err(other), + }; + let p = &env.paths; + let report = PathsReport { + config_file: shown(&env.config_file), + identity_file: shown(&p.identity_file()), + log_dir: shown(&p.log_dir), + cache_dir: shown(&p.cache_dir), + covers_dir: shown(&p.covers_dir()), + state_dir: shown(&p.state_dir), + queue_file: shown(&p.queue_file()), + library_index: shown(&p.library_index_file()), + download_dir: shown(&download_dir), + }; + if args.json { + io.json(&report)?; + } else { + let mut table = Table::new(vec![ + Column::fixed(t!("cli-col-what")), + Column::fixed(t!("cli-col-path")), + ]); + for (key, value) in [ + ("cli-path-config", &report.config_file), + ("cli-path-identity", &report.identity_file), + ("cli-path-logs", &report.log_dir), + ("cli-path-cache", &report.cache_dir), + ("cli-path-covers", &report.covers_dir), + ("cli-path-state", &report.state_dir), + ("cli-path-queue", &report.queue_file), + ("cli-path-index", &report.library_index), + ("cli-path-downloads", &report.download_dir), + ] { + table.row(vec![t!(key), value.clone()]); + } + table.print(io)?; + } + if let Some(reason) = config_note { + let line = io.paint(Tone::Warn, &t!("cli-config-invalid", reason = reason)); + io.note(&line)?; + } + Ok(()) +} + +/// `libbui config …`. +pub(crate) fn config(env: &Env, action: ConfigCommand, io: &mut Io<'_>) -> Result<(), Failure> { + let file = &env.config_file; + match action { + ConfigCommand::Path => io.line(&shown(file)), + ConfigCommand::Show { output } => { + let config = env.config()?; + if output.json { + io.json(&config) + } else { + let text = toml::to_string_pretty(&config) + .map_err(|error| Failure::Failed(error.to_string()))?; + if !file.exists() { + io.note(&t!("cli-config-defaults", path = shown(file)))?; + } + write_text(io, &text) + } + } + ConfigCommand::Init { force } => { + if file.exists() && !force { + return Err(Failure::Failed(t!("cli-config-exists", path = shown(file)))); + } + // The commented template must stay loadable; a test enforces it + // in libbui-core, and checking here costs nothing. + Config::parse(DEFAULT_CONFIG_TOML, file).map_err(|error| Failure::Failed(error.to_string()))?; + if let Some(dir) = file.parent() { + std::fs::create_dir_all(dir).map_err(|error| { + Failure::Failed(t!("cli-write-failed", path = shown(dir), reason = error.to_string())) + })?; + } + std::fs::write(file, DEFAULT_CONFIG_TOML).map_err(|error| { + Failure::Failed(t!("cli-write-failed", path = shown(file), reason = error.to_string())) + })?; + io.note(&t!("cli-config-written", path = shown(file))) + } + } +} + +fn write_text(io: &mut Io<'_>, text: &str) -> Result<(), Failure> { + io.out.write_all(text.as_bytes())?; + if !text.ends_with('\n') { + io.line("")?; + } + Ok(()) +} + +/// `libbui completions SHELL`. +pub(crate) fn completions(shell: clap_complete::Shell, io: &mut Io<'_>) -> Result<(), Failure> { + let mut command = Args::command(); + let mut buffer = Vec::new(); + clap_complete::generate(shell, &mut command, "libbui", &mut buffer); + io.out.write_all(&buffer)?; + Ok(()) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use libbui_core::paths::Paths; + + use super::*; + use crate::cli::output::{Caps, Captured}; + + fn env(root: &Path) -> Env { + let paths = Paths::rooted_at(root); + Env { + config_file: paths.config_file(), + paths, + } + } + + #[test] + fn config_init_writes_the_template_once() { + let dir = tempfile::tempdir().unwrap(); + let env = env(dir.path()); + let mut captured = Captured::default(); + config(&env, ConfigCommand::Init { force: false }, &mut captured.io(Caps::plain())).unwrap(); + let written = std::fs::read_to_string(&env.config_file).unwrap(); + assert_eq!(written, DEFAULT_CONFIG_TOML); + + let again = config(&env, ConfigCommand::Init { force: false }, &mut captured.io(Caps::plain())); + assert!(matches!(again, Err(Failure::Failed(_)))); + config(&env, ConfigCommand::Init { force: true }, &mut captured.io(Caps::plain())).unwrap(); + } + + #[test] + fn config_show_reports_a_broken_file_with_its_line() { + let dir = tempfile::tempdir().unwrap(); + let env = env(dir.path()); + std::fs::create_dir_all(&env.paths.config_dir).unwrap(); + std::fs::write(&env.config_file, "mouse = 3\n").unwrap(); + let mut captured = Captured::default(); + let error = config( + &env, + ConfigCommand::Show { output: JsonArg::default() }, + &mut captured.io(Caps::plain()), + ) + .unwrap_err(); + let Failure::Failed(message) = error else { panic!("{error:?}") }; + assert!(message.contains(":1:"), "{message}"); + assert!(message.contains("mouse"), "{message}"); + } + + #[test] + fn config_show_json_round_trips() { + let dir = tempfile::tempdir().unwrap(); + let env = env(dir.path()); + let mut captured = Captured::default(); + config( + &env, + ConfigCommand::Show { output: JsonArg { json: true } }, + &mut captured.io(Caps::plain()), + ) + .unwrap(); + let value: serde_json::Value = serde_json::from_str(&captured.stdout()).unwrap(); + assert_eq!(value["account_gap_ms"], 1000); + assert!(captured.stderr().is_empty()); + } + + #[test] + fn paths_lists_every_location() { + let dir = tempfile::tempdir().unwrap(); + let env = env(dir.path()); + let mut captured = Captured::default(); + paths(&env, &JsonArg { json: true }, &mut captured.io(Caps::plain())).unwrap(); + let value: serde_json::Value = serde_json::from_str(&captured.stdout()).unwrap(); + let root = dir.path().display().to_string(); + for key in ["config_file", "identity_file", "log_dir", "queue_file", "download_dir"] { + assert!(value[key].as_str().unwrap().starts_with(&root), "{key}: {value}"); + } + } + + #[test] + fn completions_name_the_subcommands() { + let mut captured = Captured::default(); + completions(clap_complete::Shell::Bash, &mut captured.io(Caps::plain())).unwrap(); + let script = captured.stdout(); + for command in ["loans", "download", "doctor", "completions"] { + assert!(script.contains(command), "{command}"); + } + } +} diff --git a/crates/libbui/src/cli/mod.rs b/crates/libbui/src/cli/mod.rs new file mode 100644 index 0000000..1024d21 --- /dev/null +++ b/crates/libbui/src/cli/mod.rs @@ -0,0 +1,379 @@ +//! The command line: arguments, and the scriptable subcommands that run +//! without the interface. +//! +//! `libbui` alone opens the interface. Every subcommand reuses the same +//! crates as the interface (the [`Api`] seam, the download engine, the +//! config and identity stores) and writes through [`output::Io`] rather +//! than printing, so each one can be driven from a test with a fake Libby +//! and a byte buffer. +//! +//! Exit codes are part of the interface and documented in the README: +//! [`exit::OK`], [`exit::FAILURE`], [`exit::USAGE`], [`exit::NOT_PAIRED`] +//! and [`exit::INTERRUPTED`]. + +mod account; +mod doctor; +mod download; +pub mod exit; +mod local; +pub mod output; +mod session; +mod table; + +use std::path::PathBuf; +use std::process::ExitCode; + +use clap::{Args as ClapArgs, Parser, Subcommand, ValueEnum}; +use libbui_core::config::Config; +use libbui_core::paths::Paths; + +use self::exit::Failure; +use self::output::Io; + +/// Browse, borrow and download from your library, in the terminal. +/// +/// Run without a command to open the interface. +#[derive(Debug, Clone, Parser)] +#[command(name = "libbui", version, about, long_about = None)] +#[command(after_help = "Exit codes: 0 ok, 1 failure, 2 usage, 3 not paired, 130 interrupted.")] +pub struct Args { + /// Read configuration from this file instead of the default location. + #[arg(long, value_name = "FILE", env = "LIBBUI_CONFIG", global = true)] + pub config: Option, + + /// Colour theme: auto, dark, light, ansi, high-contrast or mono. + #[arg(long, value_name = "NAME", env = "LIBBUI_THEME")] + pub theme: Option, + + /// Interface language, as a BCP 47 tag such as en-US. + #[arg(long, value_name = "TAG", env = "LIBBUI_LANG", global = true)] + pub lang: Option, + + /// Draw with ASCII characters only. + #[arg(long)] + pub ascii: bool, + + /// Leave the mouse to the terminal (keeps native text selection). + #[arg(long)] + pub no_mouse: bool, + + /// Log filter, such as `info` or `libbui=debug,libby=trace`. + #[arg( + long, + value_name = "FILTER", + env = "LIBBUI_LOG", + default_value = "info", + global = true + )] + pub log: String, + + /// Plain command output without colour. NO_COLOR does the same. + #[arg(long, global = true)] + pub no_color: bool, + + /// A scriptable command; without one, the interface opens. + #[command(subcommand)] + pub command: Option, +} + +/// The scriptable commands. +#[derive(Debug, Clone, Subcommand)] +pub enum Command { + /// Pair this device with your Libby account using a setup code. + /// + /// In Libby, open the menu, choose "Copy To Another Device" and use the + /// eight-digit code it shows. Without CODE, it is read from the terminal + /// (or one line of standard input), which keeps it out of your shell + /// history. + Pair(PairArgs), + /// Forget the pairing stored on this device. + Unpair(UnpairArgs), + /// List your loans. + Loans(ListArgs), + /// List your holds. + Holds(ListArgs), + /// List your library cards. + Cards(JsonArg), + /// Search a library's catalogue. + Search(SearchArgs), + /// Borrow a title. + Borrow(TitleArgs), + /// Return a loan early. + Return(TitleArgs), + /// Place a hold on a title. + Hold(TitleArgs), + /// Renew a loan. + Renew(TitleArgs), + /// Download loans the library offers as a file (open EPUB or PDF, or an + /// Adobe .acsm token). Titles that can only be read or heard in Libby are + /// skipped. + Download(DownloadArgs), + /// Show where libbui keeps its files. + Paths(JsonArg), + /// Create, show or locate the configuration file. + Config { + /// What to do. + #[command(subcommand)] + action: ConfigCommand, + }, + /// Print a shell completion script. + Completions { + /// The shell to complete for. + shell: clap_complete::Shell, + }, + /// Check the terminal, configuration and pairing. + Doctor(DoctorArgs), +} + +/// `--json`. +#[derive(Debug, Clone, Default, ClapArgs)] +pub struct JsonArg { + /// Print JSON instead of a table. + #[arg(long)] + pub json: bool, +} + +/// Arguments of `pair`. +#[derive(Debug, Clone, ClapArgs)] +pub struct PairArgs { + /// The eight-digit setup code from Libby. Spaces are ignored. + pub code: Option, + #[command(flatten)] + pub output: JsonArg, +} + +/// Arguments of `unpair`. +#[derive(Debug, Clone, ClapArgs)] +pub struct UnpairArgs { + /// Do not ask for confirmation. + #[arg(long, short)] + pub yes: bool, +} + +/// Arguments of `loans` and `holds`. +#[derive(Debug, Clone, Default, ClapArgs)] +pub struct ListArgs { + /// Only this card (its id or library key). + #[arg(long, value_name = "CARD")] + pub card: Option, + #[command(flatten)] + pub output: JsonArg, +} + +/// The kinds of title a search can be narrowed to. +#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)] +pub enum Kind { + /// Ebooks. + Ebook, + /// Audiobooks. + Audiobook, + /// Magazines. + Magazine, +} + +/// Arguments of `search`. +#[derive(Debug, Clone, ClapArgs)] +pub struct SearchArgs { + /// What to look for: a title, an author, a series or an ISBN. + #[arg(required = true, num_args = 1..)] + pub query: Vec, + /// Only this kind of title. + #[arg(long, value_enum)] + pub kind: Option, + /// Only titles you could borrow right now. + #[arg(long)] + pub available: bool, + /// The library to search, by key (the name in its libbyapp.com address). + /// Defaults to `default_library`, then your first card's library. + #[arg(long, value_name = "KEY")] + pub library: Option, + /// Results per page. + #[arg(long, value_name = "N", default_value_t = 24, value_parser = clap::value_parser!(u32).range(1..=100))] + pub limit: u32, + /// Which page of results. + #[arg(long, value_name = "N", default_value_t = 1, value_parser = clap::value_parser!(u32).range(1..))] + pub page: u32, + #[command(flatten)] + pub output: JsonArg, +} + +/// Arguments of `borrow`, `return`, `hold` and `renew`. +#[derive(Debug, Clone, ClapArgs)] +pub struct TitleArgs { + /// The title's id, as shown by `loans`, `holds` or `search`. + #[arg(value_name = "TITLE_ID")] + pub title_id: String, + /// The card to use (its id or library key) when you have several. + #[arg(long, value_name = "CARD")] + pub card: Option, + #[command(flatten)] + pub output: JsonArg, +} + +/// Arguments of `download`. +#[derive(Debug, Clone, ClapArgs)] +pub struct DownloadArgs { + /// The loans to download, by title id. + #[arg(value_name = "TITLE_ID", required_unless_present = "all", conflicts_with = "all")] + pub titles: Vec, + /// Download every loan that can be downloaded. + #[arg(long)] + pub all: bool, + /// Only loans on this card (its id or library key). + #[arg(long, value_name = "CARD")] + pub card: Option, + /// The format to download, such as `ebook-epub-open`. Defaults to the + /// most open one: EPUB, then PDF, then an Adobe .acsm token. + #[arg(long, value_name = "ID")] + pub format: Option, + /// Put books under this folder instead of the configured download_dir. + #[arg(long, value_name = "PATH")] + pub dir: Option, + /// Download again even if the book is already in your library. + #[arg(long)] + pub force: bool, + #[command(flatten)] + pub output: JsonArg, +} + +/// Arguments of `doctor`. +#[derive(Debug, Clone, Default, ClapArgs)] +pub struct DoctorArgs { + /// Also ask Libby whether the pairing still works (one request). + #[arg(long)] + pub online: bool, + #[command(flatten)] + pub output: JsonArg, +} + +/// `config` actions. +#[derive(Debug, Clone, Subcommand)] +pub enum ConfigCommand { + /// Write a commented default configuration file. + Init { + /// Replace an existing file. + #[arg(long)] + force: bool, + }, + /// Print the configuration in effect. + Show { + #[command(flatten)] + output: JsonArg, + }, + /// Print the configuration file's path. + Path, +} + +/// Where the command runs: files, configuration and the clock. +#[derive(Debug, Clone)] +pub(crate) struct Env { + /// Where libbui keeps its files. + pub paths: Paths, + /// The configuration file in use. + pub config_file: PathBuf, +} + +impl Env { + /// Reads the configuration; an invalid file is an error, never ignored. + pub(crate) fn config(&self) -> Result { + Config::load(&self.config_file).map_err(|error| Failure::Failed(error.to_string())) + } +} + +/// Runs a subcommand against the real terminal, files and network, and +/// returns the process exit code. +pub async fn run(args: &Args, command: Command) -> ExitCode { + crate::i18n::init(args.lang.as_deref()); + let caps = output::Caps::detect(args.no_color); + let mut stdout = std::io::BufWriter::new(std::io::stdout()); + let mut stderr = std::io::stderr(); + let mut stdin = std::io::stdin().lock(); + let mut io = Io { + out: &mut stdout, + err: &mut stderr, + input: &mut stdin, + caps, + }; + let outcome = match Paths::discover() { + Ok(paths) => { + let env = Env { + config_file: args.config.clone().unwrap_or_else(|| paths.config_file()), + paths, + }; + dispatch(args, command, &env, &mut io).await + } + Err(error) => Err(Failure::Failed(error.to_string())), + }; + let outcome = outcome.and_then(|()| io.flush()); + exit::finish(outcome, io.err) +} + +async fn dispatch(args: &Args, command: Command, env: &Env, io: &mut Io<'_>) -> Result<(), Failure> { + match command { + Command::Paths(output) => local::paths(env, &output, io), + Command::Config { action } => local::config(env, action, io), + Command::Completions { shell } => local::completions(shell, io), + Command::Doctor(doctor) => doctor::run(env, &doctor, &args.log, io).await, + network => { + let _log = libbui_core::logging::init(&env.paths, &args.log) + .map_err(|error| Failure::Failed(error.to_string()))?; + account::run(network, env, io).await + } + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use clap::CommandFactory; + + use super::*; + + #[test] + fn the_definition_is_consistent() { + Args::command().debug_assert(); + } + + #[test] + fn no_command_opens_the_interface() { + let args = Args::try_parse_from(["libbui", "--ascii"]).unwrap(); + assert!(args.command.is_none()); + assert!(args.ascii); + } + + #[test] + fn global_flags_work_after_the_command() { + let args = + Args::try_parse_from(["libbui", "loans", "--json", "--config", "/c.toml"]).unwrap(); + assert_eq!(args.config, Some(PathBuf::from("/c.toml"))); + let Some(Command::Loans(list)) = args.command else { + panic!("{:?}", args.command) + }; + assert!(list.output.json); + } + + #[test] + fn download_needs_titles_or_all_but_not_both() { + assert!(Args::try_parse_from(["libbui", "download"]).is_err()); + assert!(Args::try_parse_from(["libbui", "download", "--all", "123"]).is_err()); + assert!(Args::try_parse_from(["libbui", "download", "--all"]).is_ok()); + assert!(Args::try_parse_from(["libbui", "download", "1", "2"]).is_ok()); + } + + #[test] + fn search_limits_are_checked() { + assert!(Args::try_parse_from(["libbui", "search", "dune", "--limit", "0"]).is_err()); + assert!(Args::try_parse_from(["libbui", "search", "dune", "--limit", "101"]).is_err()); + let args = Args::try_parse_from([ + "libbui", "search", "the", "dispossessed", "--kind", "ebook", "--page", "2", + ]) + .unwrap(); + let Some(Command::Search(search)) = args.command else { + panic!() + }; + assert_eq!(search.query, ["the", "dispossessed"]); + assert_eq!(search.kind, Some(Kind::Ebook)); + assert_eq!((search.limit, search.page), (24, 2)); + } +} diff --git a/crates/libbui/src/cli/output.rs b/crates/libbui/src/cli/output.rs new file mode 100644 index 0000000..bb7b7ad --- /dev/null +++ b/crates/libbui/src/cli/output.rs @@ -0,0 +1,334 @@ +//! The command line's only way to the terminal. +//! +//! `print_stdout` and `print_stderr` are denied crate-wide so nothing can +//! scribble over the interface. Commands write through an [`Io`] instead: +//! results to `out`, progress, notes and prompts to `err`. Tests hand in +//! byte buffers. + +use std::io::{self, BufRead, IsTerminal, Write}; + +use serde::Serialize; + +use super::exit::Failure; +use crate::t; + +/// What the terminal can do, decided once at startup. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Caps { + /// Style standard output with colour and bold. + pub color: bool, + /// Standard output is a terminal (tables may be fitted to its width). + pub out_tty: bool, + /// Standard error is a terminal (progress may redraw in place). + pub err_tty: bool, + /// Standard input is a terminal (prompts are possible). + pub in_tty: bool, + /// Terminal width in columns. + pub width: usize, +} + +impl Caps { + /// Plain, non-interactive output 80 columns wide: what tests use. + #[must_use] + pub fn plain() -> Self { + Self { + color: false, + out_tty: false, + err_tty: false, + in_tty: false, + width: 80, + } + } + + /// Looks at the real terminal and environment. + #[must_use] + pub fn detect(no_color: bool) -> Self { + let out_tty = io::stdout().is_terminal(); + let width = crossterm::terminal::size().map_or(80, |(columns, _)| usize::from(columns)); + Self { + color: wants_color(no_color, out_tty, |name| std::env::var(name).ok()), + out_tty, + err_tty: io::stderr().is_terminal(), + in_tty: io::stdin().is_terminal(), + width, + } + } +} + +/// Colour only for a terminal that asked for none of `--no-color`, +/// `NO_COLOR` (any non-empty value, per no-color.org) or `TERM=dumb`. +fn wants_color(no_color: bool, out_tty: bool, lookup: impl Fn(&str) -> Option) -> bool { + !no_color + && out_tty + && lookup("NO_COLOR").is_none_or(|value| value.is_empty()) + && lookup("TERM").as_deref() != Some("dumb") +} + +/// A text style for command output. Every styled word is also a word, so +/// nothing depends on colour alone. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Tone { + /// Column headings. + Heading, + /// Something worked. + Good, + /// Worth a look. + Warn, + /// Something failed. + Bad, + /// Secondary detail. + Muted, +} + +impl Tone { + fn sgr(self) -> &'static str { + match self { + Self::Heading => "1", + Self::Good => "32", + Self::Warn => "33", + Self::Bad => "31", + Self::Muted => "2", + } + } +} + +/// Standard output, standard error and standard input. +pub struct Io<'a> { + /// Results. + pub out: &'a mut dyn Write, + /// Progress, notes, prompts and errors. + pub err: &'a mut dyn Write, + /// Answers to prompts and piped-in codes. + pub input: &'a mut dyn BufRead, + /// What the terminal can do. + pub caps: Caps, +} + +impl std::fmt::Debug for Io<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Io").field("caps", &self.caps).finish_non_exhaustive() + } +} + +impl Io<'_> { + /// `text` in `tone` when colour is on, else as is. + #[must_use] + pub fn paint(&self, tone: Tone, text: &str) -> String { + if self.caps.color && !text.is_empty() { + format!("\x1b[{}m{text}\x1b[0m", tone.sgr()) + } else { + text.to_owned() + } + } + + /// Writes one line of results. + /// + /// # Errors + /// The write failed (a closed pipe becomes [`Failure::BrokenPipe`]). + pub fn line(&mut self, text: &str) -> Result<(), Failure> { + writeln!(self.out, "{text}")?; + Ok(()) + } + + /// Writes a note to standard error. + /// + /// # Errors + /// The write failed. + pub fn note(&mut self, text: &str) -> Result<(), Failure> { + writeln!(self.err, "{text}")?; + Ok(()) + } + + /// Writes `value` as pretty JSON followed by a newline. + /// + /// # Errors + /// The value could not be encoded, or the write failed. + pub fn json(&mut self, value: &T) -> Result<(), Failure> { + serde_json::to_writer_pretty(&mut *self.out, value).map_err(|error| { + if error.is_io() { + Failure::from(io::Error::from( + error.io_error_kind().unwrap_or(io::ErrorKind::Other), + )) + } else { + Failure::Failed(t!("cli-io-failed", reason = error.to_string())) + } + })?; + self.line("") + } + + /// Asks a question on standard error and reads one line of answer. + /// `None` when input has ended. + /// + /// # Errors + /// Reading or writing failed. + pub fn ask(&mut self, prompt: &str) -> Result, Failure> { + write!(self.err, "{prompt} ")?; + self.err.flush()?; + self.read_line() + } + + /// Reads one line of standard input without prompting. `None` when + /// input has ended. + /// + /// # Errors + /// Reading failed. + pub fn read_line(&mut self) -> Result, Failure> { + let mut answer = String::new(); + if self.input.read_line(&mut answer)? == 0 { + return Ok(None); + } + Ok(Some(answer.trim().to_owned())) + } + + /// Asks a yes/no question; anything but a yes is a no. + /// + /// # Errors + /// Reading or writing failed. + pub fn confirm(&mut self, question: &str) -> Result { + let answer = self.ask(&t!("cli-confirm", question = question))?; + let yes = t!("cli-confirm-yes"); + Ok(answer.is_some_and(|answer| { + let answer = answer.to_lowercase(); + !answer.is_empty() && yes.to_lowercase().starts_with(&answer) + })) + } + + /// Flushes both streams. + /// + /// # Errors + /// The flush failed. + pub fn flush(&mut self) -> Result<(), Failure> { + self.out.flush()?; + self.err.flush()?; + Ok(()) + } +} + +/// Buffers that stand in for the terminal in tests. +#[cfg(test)] +#[derive(Debug, Default)] +pub(crate) struct Captured { + pub out: Vec, + pub err: Vec, + pub input: io::Cursor>, +} + +#[cfg(test)] +impl Captured { + /// With `input` waiting on standard input. + pub fn with_input(input: &str) -> Self { + Self { + input: io::Cursor::new(input.as_bytes().to_vec()), + ..Self::default() + } + } + + /// An [`Io`] over the buffers. + pub fn io(&mut self, caps: Caps) -> Io<'_> { + Io { + out: &mut self.out, + err: &mut self.err, + input: &mut self.input, + caps, + } + } + + /// What was written to standard output. + pub fn stdout(&self) -> String { + String::from_utf8_lossy(&self.out).into_owned() + } + + /// What was written to standard error. + pub fn stderr(&self) -> String { + String::from_utf8_lossy(&self.err).into_owned() + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + + fn env(pairs: &[(&str, &str)]) -> impl Fn(&str) -> Option { + let pairs: Vec<(String, String)> = pairs + .iter() + .map(|(k, v)| ((*k).to_owned(), (*v).to_owned())) + .collect(); + move |name| { + pairs + .iter() + .find(|(k, _)| k == name) + .map(|(_, v)| v.clone()) + } + } + + #[test] + fn colour_needs_a_terminal_and_no_opt_out() { + assert!(wants_color(false, true, env(&[]))); + assert!(!wants_color(false, false, env(&[]))); + assert!(!wants_color(true, true, env(&[]))); + assert!(!wants_color(false, true, env(&[("NO_COLOR", "1")]))); + assert!(!wants_color(false, true, env(&[("NO_COLOR", "0")]))); + assert!(wants_color(false, true, env(&[("NO_COLOR", "")]))); + assert!(!wants_color(false, true, env(&[("TERM", "dumb")]))); + } + + #[test] + fn paint_is_plain_without_colour() { + let mut captured = Captured::default(); + let io = captured.io(Caps::plain()); + assert_eq!(io.paint(Tone::Bad, "failed"), "failed"); + let io = Io { + caps: Caps { + color: true, + ..Caps::plain() + }, + ..io + }; + assert_eq!(io.paint(Tone::Bad, "failed"), "\x1b[31mfailed\x1b[0m"); + } + + #[test] + fn confirm_takes_yes_and_its_prefixes_only() { + for (input, expected) in [ + ("y\n", true), + ("YES\n", true), + ("n\n", false), + ("\n", false), + ("", false), + ("yesterday\n", false), + ] { + let mut captured = Captured::with_input(input); + let mut io = captured.io(Caps::plain()); + assert_eq!(io.confirm("Go?").unwrap(), expected, "{input:?}"); + } + } + + #[test] + fn a_closed_pipe_surfaces_as_broken_pipe() { + struct Closed; + impl Write for Closed { + fn write(&mut self, _: &[u8]) -> io::Result { + Err(io::ErrorKind::BrokenPipe.into()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } + } + let mut out = Closed; + let mut err = Vec::new(); + let mut input = io::Cursor::new(Vec::new()); + let mut io = Io { + out: &mut out, + err: &mut err, + input: &mut input, + caps: Caps::plain(), + }; + assert!(matches!(io.line("x"), Err(Failure::BrokenPipe))); + assert!(matches!( + io.json(&serde_json::json!({"a": 1})), + Err(Failure::BrokenPipe) + )); + } +} diff --git a/crates/libbui/src/cli/session.rs b/crates/libbui/src/cli/session.rs new file mode 100644 index 0000000..6939a68 --- /dev/null +++ b/crates/libbui/src/cli/session.rs @@ -0,0 +1,86 @@ +//! The Libby client for one command, and the identity file behind it. +//! +//! The interface saves the identity whenever the client publishes a new one. +//! A command is short-lived, so instead it compares what it loaded with what +//! the client holds at the end and saves the difference once (a token +//! refresh, or a pairing). + +use libbui_core::config::Config; +use libbui_core::identity::{FileStore, SecretStore, StoredIdentity}; +use libby::{Client, Identity}; +use secrecy::ExposeSecret; + +use super::Env; +use super::exit::Failure; +use crate::t; + +/// A client carrying the stored identity, if any. +#[derive(Debug)] +pub(crate) struct Session { + client: Client, + store: FileStore, + loaded: Option, +} + +impl Session { + /// Loads the identity and builds the client. + pub(crate) fn open(env: &Env, config: &Config) -> Result { + let store = FileStore::new(env.paths.identity_file()); + let loaded = store + .load() + .map_err(|error| Failure::Failed(error.to_string()))?; + let client = crate::startup::libby_client(config).map_err(|error| { + Failure::Failed(t!("cli-client-failed", reason = error.to_string())) + })?; + if let Some(stored) = &loaded { + client.set_identity(Some(Identity::new( + stored.token.clone(), + stored.chip.clone(), + ))); + } + Ok(Self { + client, + store, + loaded, + }) + } + + /// The client. + pub(crate) fn client(&self) -> &Client { + &self.client + } + + /// Whether an identity is stored (no network involved). + pub(crate) fn has_identity(&self) -> bool { + self.loaded.is_some() + } + + /// Deletes the stored identity. + pub(crate) fn forget(&self) -> Result<(), Failure> { + self.store + .clear() + .map_err(|error| Failure::Failed(error.to_string())) + } + + /// Saves the client's identity if it changed since it was loaded. + pub(crate) fn persist(&self) -> Result<(), Failure> { + let Some(current) = self.client.identity() else { + // The client never drops an identity on its own; nothing to do. + return Ok(()); + }; + let unchanged = self.loaded.as_ref().is_some_and(|loaded| { + loaded.chip == current.chip() + && loaded.token.expose_secret() == current.token().expose_secret() + }); + if unchanged { + return Ok(()); + } + self.store + .save(&StoredIdentity { + token: current.token().clone(), + chip: current.chip().to_owned(), + saved_at: jiff::Timestamp::now(), + }) + .map_err(|error| Failure::Failed(t!("cli-save-pairing-failed", reason = error.to_string()))) + } +} diff --git a/crates/libbui/src/cli/table.rs b/crates/libbui/src/cli/table.rs new file mode 100644 index 0000000..32ba982 --- /dev/null +++ b/crates/libbui/src/cli/table.rs @@ -0,0 +1,215 @@ +//! Aligned text tables for people. +//! +//! Columns are measured in terminal cells, so CJK titles line up. On a +//! terminal the table is fitted to its width by shortening the columns +//! marked as flexible (titles, authors, libraries); piped output is never +//! cut, so `grep` sees whole titles. Machines should use `--json`. + +use super::exit::Failure; +use super::output::{Io, Tone}; +use crate::ui::text::{truncate, width}; + +const GAP: &str = " "; +const ELLIPSIS: &str = "…"; +/// A flexible column is never squeezed below this. +const MIN_FLEX: usize = 8; + +/// One column. +#[derive(Debug, Clone)] +pub struct Column { + heading: String, + flexible: bool, +} + +impl Column { + /// A column that keeps its full width (ids, dates, counts). + pub fn fixed(heading: impl Into) -> Self { + Self { + heading: heading.into(), + flexible: false, + } + } + + /// A column that may be shortened to fit the terminal. + pub fn flexible(heading: impl Into) -> Self { + Self { + heading: heading.into(), + flexible: true, + } + } +} + +/// A table being built. +#[derive(Debug, Clone)] +pub struct Table { + columns: Vec, + rows: Vec>, +} + +impl Table { + /// An empty table with these columns. + pub fn new(columns: Vec) -> Self { + Self { + columns, + rows: Vec::new(), + } + } + + /// Adds a row; it must have one cell per column. + /// + /// # Panics + /// When the row has the wrong number of cells: a bug in the caller. + pub fn row(&mut self, cells: Vec) { + assert_eq!( + cells.len(), + self.columns.len(), + "a table row needs one cell per column" + ); + // Server text is sanitized by the models, but a stray tab or newline + // would still break the alignment. + let cells = cells + .into_iter() + .map(|cell| cell.replace(['\t', '\n', '\r'], " ")) + .collect(); + self.rows.push(cells); + } + + /// Column widths, shortened to `limit` cells in total if given. + fn widths(&self, limit: Option) -> Vec { + let mut widths: Vec = self + .columns + .iter() + .enumerate() + .map(|(index, column)| { + self.rows + .iter() + .map(|row| row.get(index).map_or(0, |cell| width(cell))) + .chain(std::iter::once(width(&column.heading))) + .max() + .unwrap_or(0) + }) + .collect(); + let Some(limit) = limit else { + return widths; + }; + let total = |widths: &[usize]| { + widths.iter().sum::() + GAP.len() * widths.len().saturating_sub(1) + }; + while total(&widths) > limit { + // Shorten the widest flexible column that still has room to give. + let widest = widths + .iter() + .enumerate() + .filter(|(index, w)| { + self.columns.get(*index).is_some_and(|c| c.flexible) && **w > MIN_FLEX + }) + .max_by_key(|(_, w)| **w) + .map(|(index, _)| index); + match widest.and_then(|index| widths.get_mut(index)) { + Some(w) => *w -= 1, + // Nothing left to give: let the terminal wrap. + None => break, + } + } + widths + } + + /// Writes the table to standard output. + /// + /// # Errors + /// The write failed. + pub fn print(&self, io: &mut Io<'_>) -> Result<(), Failure> { + let limit = io.caps.out_tty.then_some(io.caps.width); + let widths = self.widths(limit); + let headings: Vec = self.columns.iter().map(|c| c.heading.clone()).collect(); + let heading = render(&headings, &widths); + let heading = io.paint(Tone::Heading, &heading); + io.line(&heading)?; + for row in &self.rows { + io.line(&render(row, &widths))?; + } + Ok(()) + } +} + +fn render(cells: &[String], widths: &[usize]) -> String { + let last = cells.len().saturating_sub(1); + let mut line = String::new(); + for (index, (cell, &column)) in cells.iter().zip(widths).enumerate() { + let cell = truncate(cell, column, ELLIPSIS); + line.push_str(&cell); + if index < last { + line.push_str(&" ".repeat(column.saturating_sub(width(&cell)))); + line.push_str(GAP); + } + } + line +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + use crate::cli::output::{Caps, Captured}; + + fn sample() -> Table { + let mut table = Table::new(vec![ + Column::fixed("ID"), + Column::flexible("TITLE"), + Column::fixed("DUE"), + ]); + table.row(vec![ + "1000001".into(), + "The Left Hand of Darkness".into(), + "2026-11-22".into(), + ]); + table.row(vec!["1000006".into(), "三体".into(), "2026-12-01".into()]); + table + } + + #[test] + fn columns_align_by_cells_not_characters() { + let mut captured = Captured::default(); + sample().print(&mut captured.io(Caps::plain())).unwrap(); + insta::assert_snapshot!(captured.stdout(), @r" + ID TITLE DUE + 1000001 The Left Hand of Darkness 2026-11-22 + 1000006 三体 2026-12-01 + "); + } + + #[test] + fn a_terminal_squeezes_flexible_columns() { + let mut captured = Captured::default(); + let caps = Caps { + out_tty: true, + width: 32, + ..Caps::plain() + }; + sample().print(&mut captured.io(caps)).unwrap(); + let out = captured.stdout(); + assert!(out.lines().all(|line| width(line) <= 32), "{out}"); + assert!(out.contains("The Left…"), "{out}"); + } + + #[test] + fn piped_output_is_never_cut() { + let mut captured = Captured::default(); + let caps = Caps { + width: 20, + ..Caps::plain() + }; + sample().print(&mut captured.io(caps)).unwrap(); + assert!(captured.stdout().contains("The Left Hand of Darkness")); + } + + #[test] + fn control_characters_cannot_break_rows() { + let mut table = Table::new(vec![Column::fixed("A"), Column::fixed("B")]); + table.row(vec!["x\ny".into(), "z".into()]); + let mut captured = Captured::default(); + table.print(&mut captured.io(Caps::plain())).unwrap(); + assert_eq!(captured.stdout().lines().count(), 2); + } +} diff --git a/crates/libbui/src/main.rs b/crates/libbui/src/main.rs index 0b97fe3..0649c10 100644 --- a/crates/libbui/src/main.rs +++ b/crates/libbui/src/main.rs @@ -1,11 +1,20 @@ -//! The `libbui` binary. +//! The `libbui` binary: the interface, or one scriptable command. + +use std::process::ExitCode; use clap::Parser; use color_eyre::eyre::Result; use libbui::cli::Args; #[tokio::main] -async fn main() -> Result<()> { - color_eyre::install()?; - libbui::startup::launch(Args::parse()).await +async fn main() -> Result { + let mut args = Args::parse(); + match args.command.take() { + Some(command) => Ok(libbui::cli::run(&args, command).await), + None => { + color_eyre::install()?; + libbui::startup::launch(args).await?; + Ok(ExitCode::SUCCESS) + } + } } diff --git a/crates/libbui/src/services.rs b/crates/libbui/src/services.rs index 1575653..fe8ecae 100644 --- a/crates/libbui/src/services.rs +++ b/crates/libbui/src/services.rs @@ -117,6 +117,16 @@ impl LoanResolver { } } + /// A resolver that already knows `loans` (from a sync the caller just + /// made), so the first job costs no extra request. + #[must_use] + pub fn with_loans(api: Arc, loans: Vec) -> Self { + Self { + api, + loans: Mutex::new(loans), + } + } + fn known(&self, title: &TitleId, card: &CardId) -> Option { let loans = self.loans.lock().ok()?; loans diff --git a/crates/libbui/src/startup.rs b/crates/libbui/src/startup.rs index 73785ef..44b5799 100644 --- a/crates/libbui/src/startup.rs +++ b/crates/libbui/src/startup.rs @@ -48,11 +48,8 @@ pub async fn launch(args: Args) -> Result<()> { // The account client, carrying the stored identity if there is one. let store = Arc::new(FileStore::new(paths.identity_file())); - let client = Client::new(ClientConfig { - account_gap: Duration::from_millis(config.account_gap_ms), - ..ClientConfig::default() - }) - .map_err(|error| eyre!("could not set up the Libby client: {error}"))?; + let client = + libby_client(&config).map_err(|error| eyre!("could not set up the Libby client: {error}"))?; if let Some(stored) = store .load() .wrap_err("could not read the saved Libby pairing")? @@ -63,10 +60,7 @@ pub async fn launch(args: Args) -> Result<()> { let api: Arc = Arc::new(client); // Downloads never carry the account token: a separate, bare client. - let content = reqwest::Client::builder() - .user_agent(concat!("libbui/", env!("CARGO_PKG_VERSION"))) - .build() - .wrap_err("could not set up the download client")?; + let content = content_client().wrap_err("could not set up the download client")?; let settings = download::Settings::from_config(&config, &paths) .wrap_err_with(|| format!("invalid [templates] in {}", config_file.display()))?; let resolver = Arc::new(LoanResolver::new(Arc::clone(&api))); @@ -130,6 +124,29 @@ pub async fn launch(args: Args) -> Result<()> { outcome.wrap_err("the terminal stopped responding") } +/// The Libby client, paced as the configuration asks. Shared by the +/// interface and the scriptable commands so both are equally polite. +/// +/// # Errors +/// The HTTP client could not be built (no TLS roots, for example). +pub fn libby_client(config: &Config) -> libby::Result { + Client::new(ClientConfig { + account_gap: Duration::from_millis(config.account_gap_ms), + ..ClientConfig::default() + }) +} + +/// The HTTP client for book files and covers. Downloads never carry the +/// account token, so this is a separate, bare client. +/// +/// # Errors +/// The HTTP client could not be built. +pub fn content_client() -> reqwest::Result { + reqwest::Client::builder() + .user_agent(concat!("libbui/", env!("CARGO_PKG_VERSION"))) + .build() +} + /// Saves the identity whenever it changes (pairing, token refresh) and /// forgets it when the device is unlinked. async fn keep_identity(client: Client, store: Arc) { -- knotmirror 0.0.1