Cotton code
106 lines · 5.1 KB · RustRaw
//! `cotton-ledger pass` — one pass of the lane ledger over this Mac, for//! the claims sweep (launchd, every six hours), which reads the//! owner's drops and the sessions' fates over Cotton MCP before it and writes//! the Disk tool's rows after it.//!//!     cotton-ledger pass --machine <name> --device-id <id> --reserve-gb <gb> \//!         --drops <file: JSON list of claim ids> --sessions <file: JSON {session id: "live" | "ended"}> \//!         [--tmp <dir>] [--user-tmp <dir>]//!//! `--tmp` and `--user-tmp` replace the two temporary folders the adopt scan//! reads (`/private/tmp` and `$TMPDIR`), so a test's pass sees only its own.//!//! The pass is `cotton_client::ci::ledger::pass` over the real disk//! (`ci::ledger_mac`), exactly as the old Mac app ran it: it adopts, measures//! and removes on this Mac. What it prints on stdout is one JSON object: the//! log lines, the rows it leaves (`held`, `released`, as//! `ci::ledger_rows` makes them), the claim ids that `vanished` or were//! `forgotten`, and the `loose` notes for the owner. A session the file does//! not name is Unknown, which keeps its claims under the budget rule.use std::collections::{BTreeMap, BTreeSet};use std::path::PathBuf;use std::process::ExitCode;use cotton_client::ci::ledger::{SessionFate, Spool};use cotton_client::ci::{ledger_mac, ledger_rows};use serde_json::{json, Map, Value};fn main() -> ExitCode {    match pass(std::env::args().skip(1).collect()) {        Ok(out) => {            println!("{out}");            ExitCode::SUCCESS        }        Err(said) => {            eprintln!("cotton-ledger: {said}");            ExitCode::FAILURE        }    }}fn pass(args: Vec<String>) -> Result<Value, String> {    let (verb, rest) = args.split_first().ok_or("usage: cotton-ledger pass --machine … --device-id … --reserve-gb … --drops … --sessions …")?;    if verb != "pass" {        return Err(format!("no command {verb}"));    }    let mut given = BTreeMap::new();    let mut words = rest.iter();    while let Some(flag) = words.next() {        let name = flag.strip_prefix("--").ok_or_else(|| format!("unknown argument {flag}"))?;        let value = words.next().ok_or_else(|| format!("{flag} needs a value"))?;        given.insert(name.to_string(), value.clone());    }    let take = |name: &str| given.get(name).cloned().ok_or_else(|| format!("--{name} is required"));    let machine = take("machine")?;    let device_id = take("device-id")?;    let reserve_gb: f64 = take("reserve-gb")?.parse().map_err(|_| "--reserve-gb is a number")?;    let read = |name: &str| -> Result<Value, String> {        let path = take(name)?;        let text = std::fs::read_to_string(&path).map_err(|error| format!("--{name} {path}: {error}"))?;        serde_json::from_str(&text).map_err(|error| format!("--{name} {path}: {error}"))    };    let drops: BTreeSet<String> = serde_json::from_value(read("drops")?).map_err(|_| "--drops is a JSON list of claim ids")?;    let sessions: BTreeMap<String, String> =        serde_json::from_value(read("sessions")?).map_err(|_| "--sessions is a JSON object of session id to live or ended")?;    let home = std::env::var_os("HOME").map(PathBuf::from).ok_or("no home folder")?;    let spool = Spool::at_home(&home);    let mut roots = ledger_mac::roots_at(&home);    if let Some(tmp) = given.get("tmp") {        roots.tmp = PathBuf::from(tmp);    }    if let Some(user_tmp) = given.get("user-tmp") {        roots.user_tmp = PathBuf::from(user_tmp);    }    // The real Cotton's folder is never a claim's to take, whoever asks.    let protected = vec![home.join("CottonDB")];    let live = ledger_mac::liveness(&roots, cotton_client::git::discover::discover_git().as_deref());    let working = ledger_mac::working_of(&ledger_mac::build_lock_pids());    let fate = |session: &str| match sessions.get(session).map(String::as_str) {        Some("live") => SessionFate::Live,        Some("ended") => SessionFate::Ended,        _ => SessionFate::Unknown,    };    let report = ledger_mac::run(&spool, &roots, &protected, reserve_gb, &working, &live, &drops, &fate);    let mirror = ledger_rows::Mirror { device_id: &device_id, machine: &machine, home: &home, now: chrono::Utc::now() };    let rows = |rows: Vec<(String, Map<String, Value>)>| -> Vec<Value> {        rows.into_iter().map(|(claim_id, data)| json!({ "claim_id": claim_id, "data": data })).collect()    };    let mut lines = ledger_mac::said(&report);    if live.unread {        lines.insert(0, "ledger: what is alive on this Mac could not be read \u{2014} this pass removes nothing".into());    }    Ok(json!({        "lines": lines,        "held": rows(ledger_rows::held_rows(&mirror, &report)),        "released": rows(ledger_rows::released_rows(&mirror, &report)),        "vanished": report.vanished,        "forgotten": report.forgotten,        "loose": ledger_rows::loose_notes(&mirror, &report).into_iter()            .map(|note| json!({ "key": note.key, "text": note.text, "context": note.context })).collect::<Vec<_>>(),        "free_before_gb": report.free_before_gb,        "free_after_gb": report.free_after_gb,    }))}