Files
wanderbooks/crates/ledger-cli/src/main.rs
T
swaitsandClaude Fable 5.2 344b3b4abe feat: the window and the server say each new state in words; a proof cut short is made again; the proof does not mistake the books' own recovery for a changed head
- books ahead of the folder (as after a restore from an older backup) offer a
  new backup set beside the old one, at the person's request: books.back_up_now
  new_set, back-up --new-set, a button in the Backups window
- a key file lost from a sealed destination stops backups and asks for the
  passphrase; plain is written only after an explicit removal, which the record
  keeps (a damaged record falls back to what the folder itself holds)
- a restore that is not of the newest backup says so first, in the warning
  colour, with both dates and how many backups it passes over
- a folder a sync service keeps (or may) is said in plain words at set-up and
  in the window: one computer only, kept offline, a second computer its own
- a drill that finds only an older whole backup fails in words
- a manifest whose proof was cut short is marked unproven and proven by the
  next backup, even one with nothing new; a saved backup file is proven whole
  before it is given its name
- the proof compares the journal its pieces make with the head the manifest
  records before the books open, and lets opening add only after it
- the restore tests are split from backups.rs to keep each under a minute; the
  clone-of-an-old-git-backup test builds the working tree without git

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-21 20:07:38 -07:00

887 lines
32 KiB
Rust

//! `wanderbooks`: the one executable (plan D-22). Its modes are the
//! viewer (`gui`), the books server (`server`: the one way books are
//! served, D-44), the host and the agents' bridge (`host`, `mcp`), and the
//! owner's commands (`setup`, `books`, `connect`, `token`, `passphrase`,
//! `serve`, `close`, `doctor`, `upload`, `download`). A build without the
//! `gui` feature (the server-only build for another machine) has no
//! viewer.
//!
//! From nothing to the first post: `wanderbooks setup`, `wanderbooks books
//! create ID`, `wanderbooks connect claude --book ID` (then talk to the
//! agent).
//!
//! On Windows the executable is built for the GUI subsystem, so starting
//! it from the Start Menu opens no console window; `console` gives a
//! command run in a terminal its words back (WB-pkg-2).
#![cfg_attr(all(windows, feature = "gui"), windows_subsystem = "windows")]
mod console;
use std::env;
use std::io::Write;
use std::path::PathBuf;
/// Every third-party licence the program must travel with, built into it
/// by the build (`just notices`; scripts/notices.sh). `wanderbooks
/// licenses` prints it.
const NOTICES: &str = include_str!("../../../THIRD-PARTY-NOTICES.txt");
fn print_usage() {
eprintln!("usage: wanderbooks setup [--root PATH] [--home DIR]");
eprintln!(" wanderbooks gui [BOOK | --root PATH --book ID]");
eprintln!(
" wanderbooks books list | create ID | adopt DATA-DIR --id ID | restore BACKUP | back-up ID | upgrade ID | put-aside ID DATA-DIR [PATH...]"
);
eprintln!(" wanderbooks connect claude|codex --book ID");
eprintln!(
" wanderbooks token create --book ID | list | revoke --book ID | check --book ID | print --book ID"
);
eprintln!(" wanderbooks mcp --book ID [--token NAME]");
eprintln!(" wanderbooks passphrase");
eprintln!(" wanderbooks upload --book ID [--token NAME] UPLOAD [--] FILE");
eprintln!(" wanderbooks download --book ID [--token NAME] ATTACHMENT --to FOLDER");
eprintln!(" wanderbooks serve | close | doctor");
eprintln!(" wanderbooks update [--check] | rollback");
eprintln!(" wanderbooks licenses");
eprintln!();
eprintln!(" setup make the books' private folder (only your account can open it)");
eprintln!(" gui open the live, read-only view of the books (a book of the data root)");
eprintln!(
" books list, start, adopt, restore, back up or upgrade books (`books --help`)"
);
eprintln!(" connect let Claude Code or Codex reach the books");
eprintln!(" token make, list or revoke an agent's token for books (`token --help`)");
eprintln!(" mcp an agent's way to the books, over stdio (what `connect` registers)");
eprintln!(" passphrase set or change the owner passphrase (typed at a terminal)");
eprintln!(" upload send a file for an upload an agent began (books.begin_upload)");
eprintln!(" download save a copy of a stored file or of one the books handed over");
eprintln!(" serve hold the books open until Ctrl-C");
eprintln!(" close close the books now: everything holding them lets go");
eprintln!(" doctor whether the books are open, what holds them, what went wrong");
eprintln!(" update bring this program to the newest release (`rollback` goes back)");
eprintln!(" licenses the licences of the libraries and fonts this program includes");
}
/// The viewer's arguments for `wanderbooks gui ARGS` (plan 3.6): a lone
/// word names the book of the data root to show (`--book`), never a
/// folder; nothing, the root's book; anything else is the viewer's own
/// flags, passed as they are.
#[cfg(feature = "gui")]
fn gui_args(args: Vec<String>) -> Vec<String> {
match args.as_slice() {
[book] if !book.starts_with('-') => vec!["--book".into(), book.clone()],
_ => args,
}
}
/// The viewer's owner (ledger-gui owner.rs): its Books menu, done as the
/// command line does it (the books server, the agents' own commands).
#[cfg(feature = "gui")]
struct ViewerOwner {
common: ledger_host::commands::Common,
/// The books server this window runs, a child process of it (plan P15
/// 3.1): started with the window, closed with it. All of what is done
/// with it is `AppHost`'s, which the tests drive.
server: ledger_host::app_server::AppHost,
/// Web assistants: the switch per company, the address and the line to
/// the relay (ledger-host web.rs), in this window's process: the line
/// ends with the window.
web: ledger_host::web::WebAssistants,
}
#[cfg(feature = "gui")]
impl ViewerOwner {
fn new(common: ledger_host::commands::Common) -> Self {
let server = ledger_host::app_server::AppHost::new(common.root.clone());
let web = ledger_host::web::WebAssistants::new(common.root.clone());
Self {
common,
server,
web,
}
}
}
#[cfg(feature = "gui")]
impl ledger_gui::owner::Owner for ViewerOwner {
fn serves(&self) -> bool {
true
}
fn serve_start(&self, open: &[String]) -> Result<(), String> {
self.server.start(open)?;
// What was on when the window closed is on again, for the
// companies that are open.
self.web.restore(&self.server, open);
Ok(())
}
fn serve_host_holds(&self) -> bool {
ledger_host::commands::a_host_holds(self.common.root.as_deref())
}
fn serve_close_host(&self) -> Result<String, String> {
ledger_host::commands::close_the_host(self.common.root.as_deref())
}
fn serve_open(&self, book: &str) -> Result<Option<String>, String> {
let opened = self.server.open_book(book)?;
self.web.restore(&self.server, &[book.to_string()]);
Ok(opened)
}
fn serve_close(&self, book: &str) -> Result<Option<String>, String> {
self.server.close_book(book)
}
fn serve_not_open(&self, wanted: &[String]) -> Vec<(String, String)> {
self.server.not_open(wanted)
}
fn serve_stop(&self) -> Result<Option<String>, String> {
// The line closes first: nothing arrives for books that are closing.
self.web.shutdown();
self.server.stop(ledger_host::app_server::STOP_WAIT)
}
fn serve_exited(&self) -> Option<String> {
self.server.exited()
}
fn serve_roster(&self) -> Result<ledger_gui::owner::Roster, String> {
use ledger_gui::owner::{Assistant, LastCall, Roster, TokenRow};
let roster = self.server.roster(std::time::Duration::from_secs(3))?;
let mut assistants = Vec::new();
for book in roster.sessions {
for s in book.sessions {
assistants.push(Assistant {
book: book.book.clone(),
token: s.token,
client_name: s.client_name,
client_version: s.client_version,
model: s.agent.and_then(|a| a.model),
connected_at: s.connected_at,
running: s.running,
last: s.last.map(|l| LastCall {
tool: l.tool,
outcome: l.outcome,
at: l.at,
}),
});
}
}
let tokens = roster
.tokens
.into_iter()
.map(|t| TokenRow {
id: t.id,
book: t.book,
name: t.name,
scopes: t.scopes,
created: t.created,
})
.collect();
// The web assistants waiting, and those allowed: nothing when the
// remote door was never turned on.
let web = self
.server
.web_roster(std::time::Duration::from_secs(3))
.unwrap_or_default();
let web_pending = web
.pending
.into_iter()
.map(|p| ledger_gui::owner::WebRequest {
id: p.id,
book: p.book,
client_name: p.client_name,
known_host: p.known_host,
code: p.code,
redirect: p.redirect,
redirect_host: p.redirect_host,
from: p.from,
wants_post: p.wants_post,
expires_in_secs: p.expires_in_secs,
})
.collect();
let web_approvals = web
.approvals
.into_iter()
.map(|a| ledger_gui::owner::WebApproval {
id: a.id,
book: a.book,
label: a.label,
token_id: a.token_id,
may_post: a.may_post,
last_used: a.last_used,
})
.collect();
Ok(Roster {
assistants,
tokens,
web_pending,
web_approvals,
})
}
fn web_decide(&self, id: &str, approve: bool, post: bool) -> Result<String, String> {
self.server.web_decide(id, approve, post)
}
fn web_set_post(&self, approval: &str, post: bool) -> Result<String, String> {
self.server.web_set_post(approval, post)
}
fn web_state(&self, book: &str) -> Option<ledger_gui::owner::WebConnect> {
use ledger_gui::owner::WebStep;
let s = self.web.state(book);
Some(ledger_gui::owner::WebConnect {
on: s.on,
step: match s.step {
ledger_link::Step::Off => WebStep::Off,
ledger_link::Step::GettingAddress => WebStep::GettingAddress,
ledger_link::Step::Connecting => WebStep::Connecting,
ledger_link::Step::GettingCertificate => WebStep::GettingCertificate,
ledger_link::Step::Connected => WebStep::Connected,
},
address: s.address,
connector: s.connector,
words: s.words,
problem: s.problem,
needs_person: s.needs_person,
kept: s.kept,
})
}
fn web_turn_on(&self, book: &str) -> Result<String, String> {
self.web.turn_on(&self.server, book)
}
fn web_turn_off(&self, book: &str) -> Result<String, String> {
self.web.turn_off(&self.server, book)
}
fn web_new_address(&self, _book: &str) -> Result<String, String> {
self.web.new_address(&self.server)
}
fn serve_revoke(&self, book: &str, name: &str, id: &str) -> Result<String, String> {
self.server.revoke_token(book, name, id)
}
fn command_line(&self, words: &[&str]) -> Result<String, String> {
ledger_host::commands::command_line(&self.common, words)
}
fn make_key(&self, book: &str) -> Result<bool, String> {
use ledger_store::auth::Scope;
// What a page-made key may do: read, draft and post; never admin.
ledger_host::commands::ensure_key(
&self.common,
book,
&[Scope::Read, Scope::Write, Scope::Post],
)
}
fn claude_desktop_extension(
&self,
book: &str,
company: &str,
) -> Result<ledger_gui::owner::ExtensionMade, String> {
let made = ledger_host::extension::claude_desktop_extension(&self.common, book, company)?;
Ok(ledger_gui::owner::ExtensionMade {
file: made.path.display().to_string(),
folder: made.folder.display().to_string(),
})
}
fn new_books(&self, id: &str, currency: &str) -> Result<String, String> {
ledger_host::commands::new_books_and_home(&self.common, id, currency)
}
fn back_up_now(&self, book: &str) -> Result<Vec<String>, String> {
ledger_host::commands::back_up_now(&self.common, book, false, false)
}
fn start_new_backup_set(&self, book: &str) -> Result<Vec<String>, String> {
ledger_host::commands::back_up_now(&self.common, book, false, true)
}
fn backup_state(&self, book: &str) -> Result<ledger_gui::owner::BackupState, String> {
let s = ledger_host::commands::backup_standing(&self.common, book)?;
Ok(ledger_gui::owner::BackupState {
lines: ledger_host::commands::backup_words(&s),
folder: s.folder.clone(),
sealed: s.sealed,
ahead: s.error_kind.as_deref() == Some("ahead"),
})
}
fn set_up_backups(
&self,
book: &str,
folder: Option<String>,
passphrase: Option<ledger_gui::owner::Secret>,
remove_passphrase: bool,
) -> Result<Vec<String>, String> {
ledger_host::commands::backup_setup(
&self.common,
book,
folder,
passphrase.map(|p| p.0.clone()),
remove_passphrase,
)
}
fn save_backup(&self, book: &str, file: &str) -> Result<Vec<String>, String> {
ledger_host::commands::backup_save(&self.common, book, file)
}
fn plan_restore(
&self,
source: &str,
id: Option<String>,
replace: bool,
passphrase: Option<ledger_gui::owner::Secret>,
) -> Result<ledger_gui::owner::RestorePlan, String> {
let pass = passphrase.map(|p| ledger_mcp::admin::Passphrase(p.0.clone()));
let p =
ledger_host::commands::plan_restore(&self.common, source, id, replace, false, pass)?;
Ok(ledger_gui::owner::RestorePlan {
source: p.source,
passphrase: p
.passphrase
.as_ref()
.map(|p| ledger_gui::owner::Secret(p.0.clone())),
id: p.id,
replace: p.replace,
head: p.head,
lines: p.lines,
})
}
fn restore(&self, plan: &ledger_gui::owner::RestorePlan) -> Result<Vec<String>, String> {
ledger_host::commands::carry_out_restore(
&self.common,
&ledger_host::commands::RestorePlan {
source: plan.source.clone(),
passphrase: plan
.passphrase
.as_ref()
.map(|p| ledger_mcp::admin::Passphrase(p.0.clone())),
id: plan.id.clone(),
replace: plan.replace,
head: plan.head.clone(),
origin: None,
lines: plan.lines.clone(),
},
)
}
fn connect(&self, agent: ledger_gui::owner::Agent, book: &str) -> Result<Vec<String>, String> {
let agent = match agent {
ledger_gui::owner::Agent::Claude => "claude",
ledger_gui::owner::Agent::Codex => "codex",
};
ledger_host::commands::connect_and_home(&self.common, agent, book)
}
fn first_run(&self) -> ledger_gui::owner::FirstRun {
let s = ledger_host::commands::first_run_state(&self.common);
ledger_gui::owner::FirstRun {
root: s.root,
books: s.books,
passphrase_set: s.passphrase_set,
}
}
fn set_up(&self) -> Result<Vec<String>, String> {
ledger_host::commands::set_up_root(&self.common)
}
fn set_passphrase(&self, new: &str) -> Result<(), String> {
ledger_host::commands::set_first_passphrase(&self.common, new)
}
/// Nothing: the window's server holds the books for as long as the
/// window runs, a company at a time (`serve_open`), and no host does.
fn hold(&self, _book: &str) {}
fn agent_start(
&self,
agent: ledger_gui::owner::Agent,
book: &str,
) -> Result<ledger_gui::owner::AgentStart, String> {
use ledger_gui::owner::{AgentStart, Installer};
let agent = match agent {
ledger_gui::owner::Agent::Claude => "claude",
ledger_gui::owner::Agent::Codex => "codex",
};
Ok(match ledger_host::commands::start_agent(agent, book)? {
ledger_host::commands::AgentStart::Ready {
label,
program,
args,
dir,
env,
} => AgentStart::Ready {
label: label.to_string(),
program,
args,
dir,
env,
},
ledger_host::commands::AgentStart::Missing(i) => AgentStart::Missing(Installer {
label: i.label.to_string(),
command: i.command.to_string(),
page: i.page.to_string(),
}),
})
}
/// Handed to the window's own server as an admin request: there is
/// no host here, and so no lease socket to ask (app_server.rs
/// INVARIANT 10).
fn upgrade_format(&self, book: &str, passphrase: &str) -> Result<Vec<String>, String> {
self.server.upgrade_format(book, passphrase)
}
fn update_waiting(&self) -> Option<ledger_gui::owner::UpdateWaiting> {
ledger_host::commands::update_waiting(&self.common).map(|u| {
ledger_gui::owner::UpdateWaiting {
version: u.version,
staged_at: u.staged_at,
}
})
}
fn newer_version(&self) -> Option<ledger_gui::owner::NewerVersion> {
ledger_host::commands::newer_version(&self.common).map(|(version, page)| {
ledger_gui::owner::NewerVersion {
version,
page: page.to_string(),
}
})
}
fn check_for_updates(&self) -> Result<Vec<String>, String> {
ledger_host::commands::check_for_updates(&self.common).map(|l| vec![l])
}
fn apply_update(&self) -> Result<Vec<String>, String> {
ledger_host::commands::apply_update(&self.common).map(|l| vec![l])
}
}
/// `wanderbooks gui`: the viewer, in this process. For books of the data
/// root it holds them open while it runs, and its Books menu acts on them.
#[cfg(feature = "gui")]
fn run_gui(args: Vec<String>) -> i32 {
let args = gui_args(args);
{
let value = |flag: &str| {
// The last given, as the viewer reads it.
args.iter()
.rposition(|a| a == flag)
.and_then(|i| args.get(i + 1))
.cloned()
};
// Only the viewer's own flags for books of the data root, each with
// its value: anything else (help, a mistake, the demo) holds
// nothing.
let mut known = true;
let mut rest = args.iter();
while let Some(a) = rest.next() {
if !matches!(a.as_str(), "--root" | "--book" | "--today") || rest.next().is_none() {
known = false;
break;
}
}
let root = value("--root").map(PathBuf::from);
if known {
// The viewer asks about a format upgrade in its own window, makes
// the first books when there are none, and starts the agent in
// its dock.
let common = ledger_host::commands::Common {
root: root.clone(),
..Default::default()
};
// The window runs the books server itself, as a child process
// (plan P15 3.1), once it knows which companies it opens: no
// host is started for it.
ledger_gui::owner::set_owner(std::sync::Arc::new(ViewerOwner::new(common)));
}
}
match ledger_gui::run("wanderbooks gui", args) {
Ok(()) => 0,
Err(e) => match e.downcast_ref::<ledger_gui::Exit>() {
Some(exit) => exit.0,
None => {
eprintln!("error: {e}");
1
}
},
}
}
/// `wanderbooks gui` in a build without the viewer.
#[cfg(not(feature = "gui"))]
fn run_gui(_args: Vec<String>) -> i32 {
eprintln!("error: this wanderbooks is the server-only build: it has no viewer");
2
}
/// `wanderbooks setup [--root PATH] [--home DIR]`: make the books'
/// private folder (plan 3.4): `--root` if given, else
/// `$XDG_DATA_HOME/wanderbooks`, else the platform's default under the
/// account's home (`--home`, else the system's user records). The folder's
/// location is never printed: nothing an agent is shown names it.
fn run_setup(args: Vec<String>) -> i32 {
let mut root: Option<PathBuf> = None;
let mut home: Option<PathBuf> = None;
let mut args = args.into_iter();
while let Some(arg) = args.next() {
let slot = match arg.as_str() {
"--root" => &mut root,
"--home" => &mut home,
"--help" | "-h" => {
eprintln!("usage: wanderbooks setup [--root PATH] [--home DIR]");
eprintln!(
" --root where the books' private folder goes (default: your data folder)"
);
eprintln!(" --home the account's home (default: from the system's user records)");
return 0;
}
other => {
eprintln!("unknown argument: {other}");
eprintln!("usage: wanderbooks setup [--root PATH] [--home DIR]");
return 2;
}
};
match args.next() {
Some(value) => *slot = Some(PathBuf::from(value)),
None => {
eprintln!("error: {arg} needs a path");
return 1;
}
}
}
let account = ledger_store::root::account_home().ok();
let home = match home.or_else(|| account.clone()) {
Some(home) => home,
None => {
eprintln!("error: {}", ledger_store::root::RootError::NoHome);
return 1;
}
};
if account.as_ref() != Some(&home) {
eprintln!(
"note: --home isn't this account's home, so this account's books server won't \
look there (tests and unusual setups only)"
);
}
// XDG_DATA_HOME is this account's, for this account's home: with
// another home given (tests), it is never read, so it can't aim at
// this account's real books.
let xdg = if account.as_ref() == Some(&home) {
env::var_os("XDG_DATA_HOME").map(PathBuf::from)
} else {
None
};
match ledger_store::root::Root::setup(&home, root.as_deref(), xdg.as_deref()) {
Ok((found, report)) => {
let what = if report.created {
"made"
} else if report.tightened {
"already there; made private again (other users could open it)"
} else {
"already there"
};
println!("The books' private folder: {what}. Only your account can open it.");
if report.recorded {
println!("It isn't in the default place, so where it is was noted for next time.");
}
owner_passphrase(&found)
}
Err(e) => {
eprintln!("error: {e}");
1
}
}
}
/// After setup: the owner passphrase, asked for at a terminal if none is
/// set yet; elsewhere (a script, an agent) only said how to set it.
fn owner_passphrase(root: &ledger_store::root::Root) -> i32 {
let auth = match root.auth_dir() {
Ok(dir) => dir,
Err(e) => {
eprintln!("error: {e}");
return 1;
}
};
match ledger_store::passphrase::is_set(&auth) {
Ok(true) => return 0,
Ok(false) => {}
Err(e) => {
eprintln!("error: {e}");
return 1;
}
}
if !std::io::IsTerminal::is_terminal(&std::io::stdin()) {
println!("No owner passphrase yet: set one in a terminal with `wanderbooks passphrase`.");
return 0;
}
println!(
"Now the owner passphrase: what the books ask you for before anything only you may do."
);
match ledger_host::commands::set_passphrase_at_terminal(&auth) {
Ok(()) => {
println!("The owner passphrase is set.");
0
}
Err(why) => {
eprintln!(
"error: {why}. The folder is made; set the passphrase with `wanderbooks passphrase`."
);
1
}
}
}
/// `wanderbooks server`: the books server for the data root, on its
/// local sockets (plan 3.9). The host starts it.
fn run_server(args: Vec<String>) -> i32 {
// Whoever started the server, it holds none of that program's pipes or
// sockets: a server still closing after its starter has gone must not
// keep them open.
ledger_host::host::close_stray_descriptors();
match ledger_mcp::local::run("wanderbooks server", args) {
Ok(()) => 0,
Err(e) => match e.downcast_ref::<ledger_mcp::Exit>() {
Some(exit) => exit.0,
None => {
eprintln!("error: {e}");
1
}
},
}
}
/// `wanderbooks licenses`: the third-party notices compiled into the
/// program. It opens no books and reads no file: what it prints is part of
/// this binary. A pipe that closes early (`| head`) is how the reader
/// finished, not an error, so a write error is ignored.
fn run_licenses(args: Vec<String>) -> i32 {
if !args.is_empty() {
eprintln!("usage: wanderbooks licenses");
return 2;
}
let mut out = std::io::stdout().lock();
let header = format!(
"wanderbooks {} is licensed under MIT OR Apache-2.0.\n\n",
env!("CARGO_PKG_VERSION")
);
let _ = out.write_all(header.as_bytes());
let _ = out.write_all(NOTICES.as_bytes());
0
}
/// The modes that open and hold the books (plan 3.9): the host, the
/// agents' bridge, and the owner's commands.
fn run_local(mode: &str, args: Vec<String>) -> i32 {
let prog = format!("wanderbooks {mode}");
let result = match mode {
"host" => ledger_host::host::run(&prog, args),
"mcp" => ledger_host::bridge::run(&prog, args),
"serve" => ledger_host::commands::serve(&prog, args),
"close" => ledger_host::commands::close(&prog, args),
"doctor" => ledger_host::commands::doctor(&prog, args),
"token" => ledger_host::commands::token(&prog, args),
"connect" => ledger_host::commands::connect(&prog, args),
"passphrase" => ledger_host::commands::passphrase(&prog, args),
#[cfg(unix)]
"update" => {
ledger_host::update::update(&prog, ledger_host::update::program_version(), args)
}
#[cfg(unix)]
"rollback" => ledger_host::update::rollback(&prog, args),
// Updates replace a running program's file in place, which Windows
// forbids: its updater is P11a step 5.
#[cfg(not(unix))]
"update" | "rollback" => {
eprintln!("error: `{mode}` is not built for Windows yet (P11a step 5)");
return 2;
}
_ => ledger_host::commands::books(&prog, args),
};
match result {
Ok(()) => 0,
Err(e) => match e.downcast_ref::<ledger_host::Exit>() {
Some(exit) => exit.0,
None => {
eprintln!("error: {e}");
1
}
},
}
}
/// `upload` and `download`: the agent's file commands, whose words may
/// be paths that aren't text.
fn run_files(mode: &str, args: Vec<std::ffi::OsString>) -> i32 {
let prog = format!("wanderbooks {mode}");
let result = match mode {
"upload" => ledger_host::commands::upload(&prog, args),
_ => ledger_host::commands::download(&prog, args),
};
match result {
Ok(()) => 0,
Err(e) => match e.downcast_ref::<ledger_host::Exit>() {
Some(exit) => exit.0,
None => {
eprintln!("error: {e}");
1
}
},
}
}
/// Whether the program was launched with nothing to say and no terminal
/// to say it to: a menu entry, a double-click, an AppImage (whose launcher
/// runs the desktop file's command and appends what it was given, so the
/// desktop file says plain `wanderbooks`). At a terminal it is the usage,
/// as ever.
fn is_bare_launch(words: &[String], stdin_is_terminal: bool) -> bool {
words.is_empty() && !stdin_is_terminal
}
fn main() {
ledger_host::set_program_version(env!("CARGO_PKG_VERSION"));
// A file's path may be any name the system takes: the file commands
// get the words as given. Everything else is text.
let given: Vec<std::ffi::OsString> = env::args_os().skip(1).collect();
if let Some(mode @ ("upload" | "download")) = given.first().and_then(|m| m.to_str()) {
let mode = mode.to_string();
std::process::exit(run_files(&mode, given[1..].to_vec()));
}
let Ok(words) = given
.into_iter()
.map(std::ffi::OsString::into_string)
.collect::<Result<Vec<String>, _>>()
else {
eprintln!("error: an argument isn't UTF-8 text");
std::process::exit(2);
};
// A command run in a terminal prints there; the app (no words) opens
// no console at all (console.rs).
if !words.is_empty() {
console::attach_parent_console();
}
// A bare launch is the viewer.
if is_bare_launch(&words, std::io::IsTerminal::is_terminal(&std::io::stdin())) {
std::process::exit(run_gui(Vec::new()));
}
// The modes run in this process and take their own flags.
let mut all = words.clone().into_iter();
match all.next().as_deref() {
Some("gui") => std::process::exit(run_gui(all.collect())),
Some("setup") => std::process::exit(run_setup(all.collect())),
Some("server") => std::process::exit(run_server(all.collect())),
Some("licenses") => std::process::exit(run_licenses(all.collect())),
Some(
mode @ ("host" | "mcp" | "serve" | "close" | "books" | "doctor" | "token" | "connect"
| "passphrase" | "update" | "rollback"),
) => {
let mode = mode.to_string();
std::process::exit(run_local(&mode, all.collect()))
}
_ => {}
}
if words.first().is_some_and(|w| w == "--help" || w == "-h") {
print_usage();
return;
}
// The books-folder scaffold is gone (P2 slice 8): said plainly.
if let Some(gone @ ("new" | "init")) = words.first().map(String::as_str) {
eprintln!(
"`wanderbooks {gone}` is gone: books now live in a private folder. Start them with `wanderbooks setup`, `wanderbooks books create ID` and `wanderbooks connect claude --book ID`."
);
std::process::exit(2);
}
// A mode named after a flag: it must come first.
match words.iter().map(String::as_str).find(|w| {
matches!(
*w,
"gui"
| "setup"
| "server"
| "host"
| "mcp"
| "serve"
| "connect"
| "close"
| "books"
| "doctor"
| "token"
| "passphrase"
| "update"
| "rollback"
| "upload"
| "download"
| "licenses"
)
}) {
Some(mode) => {
eprintln!("`{mode}` must come first: wanderbooks {mode} [its own flags]");
std::process::exit(2);
}
_ => {
print_usage();
std::process::exit(2);
}
}
}
#[cfg(all(test, feature = "gui"))]
mod gui_args_tests {
use super::gui_args;
fn v(args: &[&str]) -> Vec<String> {
args.iter().map(|a| a.to_string()).collect()
}
#[test]
fn a_lone_word_names_a_book_never_a_folder() {
assert_eq!(gui_args(v(&["acme"])), v(&["--book", "acme"]));
assert_eq!(gui_args(v(&["."])), v(&["--book", "."]));
assert_eq!(gui_args(v(&[])), v(&[]));
}
#[test]
fn flags_and_anything_else_pass_as_they_are() {
for args in [
v(&["--demo"]),
v(&["--root", "x"]),
v(&["a", "b"]),
v(&["--help"]),
] {
assert_eq!(gui_args(args.clone()), args);
}
}
}
#[cfg(test)]
mod bare_launch_tests {
use super::is_bare_launch;
#[test]
fn only_nothing_at_all_with_no_terminal_is_the_viewer() {
assert!(is_bare_launch(&[], false));
// At a terminal it is the usage, as ever.
assert!(!is_bare_launch(&[], true));
// Anything said is a mode or a mistake, never the viewer.
assert!(!is_bare_launch(&["--help".to_string()], false));
assert!(!is_bare_launch(&["update".to_string()], false));
}
}