Something went wrong. Try again.
Plaintext Records, Organized and Verifiable. CLI + Library for managing plaintext information
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977//! The structural mutations: `new`, `attach`, `mv`, `reparent`, `reorder`,//! `rm`, `restore`, `clear-deletions`, `duplicate`.//!//! Every verb here changes where a document sits in the containment tree, and//! every one that may mint an ID ensures a registry exists *before* the//! workspace is built over it — a route's synthesized nodes are `create`d and//! mint on the same terms as the leaf. A parent is named the same way in all//! of them ([`plan_placement`]): a path, an `id:` handle, or an `@`-route//! that `-p` may extend, so a route is only ever another way to name a//! parent and never a different kind of operation.
use std::path::{Path, PathBuf};use std::process::ExitCode;
use prov::{ FileIndex, Layout, Mapping, Minter, RoutePlan, StdFs, Value, Workspace, block_on, edit, link,};
use crate::about::refresh_about;use crate::cli::{AttachArgs, NewArgs};use crate::clock::now_rfc3339;use crate::session::{Ctx, Session, TargetSpec, load, parse_target, resolve_target, ws_rel};use crate::{AnyError, CmdResult};
/// Where a structural command puts a document, decided but not yet made:/// a parent that already exists, or a route or filing entry whose missing/// nodes are built only by [`apply_placement`].////// The two halves are separate so that a command can find every reason it/// would refuse between them. A `-p` route used to be built as it was/// resolved, so a command that then refused — a leaf collision in `new`, a/// missing payload in `attach`, a cycle in `reparent` — left index nodes/// nobody had asked for; and `mv --in` moved the file before it resolved its/// parent at all.enum Placement { /// A parent that already exists: a path, an id, or a route that resolved /// whole. Exists(PathBuf), /// A route with segments still to build (`-p`). Route(RoutePlan), /// A filing entry with containers still to build. Filed(prov::FilingPlan),}
impl Placement { /// The parent the document lands under once the placement is applied. fn parent(&self) -> &Path { match self { Placement::Exists(parent) => parent, Placement::Route(plan) => &plan.terminal, Placement::Filed(plan) => &plan.parent, } }
/// Refuse, before anything is written, a reparent of `child` under this /// placement that [`Workspace::reparent`] would refuse after it. A /// placement still to be built is judged at its deepest existing node: /// whatever the route builds sits beneath that, so a cycle through it is a /// cycle through the nodes too. fn check_reparent(&self, session: &Session, child: &Path) -> Result<(), AnyError> { let anchor = match self { Placement::Exists(parent) => parent, Placement::Route(plan) if plan.is_complete() => &plan.terminal, Placement::Route(plan) => { let deepest = plan.resolved.last().unwrap_or(&plan.terminal); if prov::link::normalize(deepest) == prov::link::normalize(child) { return Err(format!( "cannot reparent {} into {} — the route would build it inside {}, \ so the move would detach both from the tree", child.display(), plan.terminal.display(), child.display(), ) .into()); } deepest } Placement::Filed(plan) => &plan.parent, }; block_on(session.ws.check_reparent(child, anchor))?; Ok(()) }}
/// Resolve a `--in DOC` / `--under ROUTE` placement to the parent document it/// names, writing nothing. A `--dry-run` prints the route's plan here and/// still hands back the placement — as if `-p` had been given, since the/// preview is of what `-p` would build — so the caller makes every refusal/// the real run would make before saying what it would do. It used to stop/// once the plan was printed, so a dry run through a route reported success/// for a command the real run refuses.////// Shared by `new`, `attach`, `reparent`, and `mv`, because a route is only/// ever another way to *name* a parent — never a different kind of operation./// Three copies of the -p/--dry-run policy would drift, and the drift would be/// silent (each command deciding on its own what a missing segment means).////// Synthesized nodes are `create`d by [`apply_placement`], so they mint IDs on/// the same terms as any other document — a caller that mints must open the/// session with [`Session::open_for_mutation`], so the registry exists/// *before* the placement is applied and not merely before its own write.fn plan_placement( session: &Session, target: &str, parents: bool, layout: Layout, dry_run: bool,) -> Result<Placement, AnyError> { let route = match parse_target(target) { // A path or an id names a parent that must already exist — it has no // segments to synthesize. `-p` still applies to the *leaf* (idempotent // create, handled by the caller), so it is allowed here, just inert for // the parent. TargetSpec::Path(_) | TargetSpec::Id(_) => { let resolved = resolve_target(target)?; let parent = ws_rel(&session.ctx, &resolved)?; // Named here rather than left to the write, which fails with a // bare "No such file or directory" that does not say which file. if !session.ws.fs_path(&parent).is_file() { return Err(format!( "--in {target}: {} does not exist in this workspace", parent.display() ) .into()); } return Ok(Placement::Exists(parent)); } TargetSpec::Route(route) => route, }; let segments = Workspace::<StdFs>::route_segments(route); let plan = block_on( session .ws .plan_route(&session.ctx.root_doc, &segments, layout), )?; if dry_run { show_route_plan(route, &plan); if plan.is_complete() { eprintln!( "\nnothing to create; the route resolves to {}", plan.terminal.display() ); } else if !parents { eprintln!( "\n{} segment(s) missing — re-run with -p to create them", plan.synthesize.len() ); } } if plan.is_complete() { return Ok(Placement::Exists(plan.terminal)); } if !parents && !dry_run { // Name the first missing segment and where the walk got to: the useful // half of the error is *how far* the route resolved. let missing = &plan.synthesize[0]; return Err(format!( "@{route} stops at {}: no child titled {:?}\n\ re-run with -p to create the missing segment(s), or --dry-run to preview", missing.parent.display(), missing.title, ) .into()); } Ok(Placement::Route(plan))}
/// Build what a [`Placement`] still lacks and return the parent it names./// The caller has made every check it can by now: this is the first write.fn apply_placement(session: &mut Session, placement: Placement) -> Result<PathBuf, AnyError> { match placement { Placement::Exists(parent) => Ok(parent), Placement::Route(plan) => { let terminal = block_on(session.ws.apply_route(&plan))?; // Synthesized route parents are incidental to the command's result // (the leaf), so their creation is narration → stderr; the // caller's stdout is the terminal. for synth in &plan.synthesize { eprintln!("created {} ({:?})", synth.path.display(), synth.title); } session.commit()?; Ok(terminal) } Placement::Filed(plan) => { let filed = block_on(session.ws.apply_file(&plan, &Mapping::new()))?; for (made, index) in filed.created.iter().zip(&plan.create) { eprintln!("created {} ({:?})", made.display(), index.title); } if !filed.created.is_empty() { session.commit()?; } Ok(filed.parent) } }}
/// The name of the one filing entry that names `kind` — what `--filed`/// files through. An error naming the entries when none, or several, do.fn filing_entry_for_kind(session: &Session, kind: prov::RecordKind) -> Result<String, AnyError> { use prov::filing::KindFiling; match prov::filing::filing_for_kind(&session.ctx.config.filing, kind) { KindFiling::One(spec) => Ok(spec.name.clone()), KindFiling::Unclaimed => Err(format!( "no filing entry names `kind: {}` — declare one, or name a parent with --in", kind.as_str() ) .into()), KindFiling::Ambiguous(specs) => Err(format!( "several filing entries name `kind: {}` ({}) — name one with --filing", kind.as_str(), specs .iter() .map(|s| s.name.as_str()) .collect::<Vec<_>>() .join(", ") ) .into()), }}
/// Where `new --filing <name>` puts the document: the container the/// workspace's filing entry names for it, found or made/// ([`Workspace::file`](prov::Workspace::file)), planned and not yet/// made — [`apply_placement`] makes it. A `--dry-run` prints the plan and/// hands it back, for the caller's refusals to be made of it.////// The value it is filed by is the one the document is about to open with —/// its creation stamp and every `--set` — since that is what the entry's/// field chain will read off it afterwards. A field's starting value is not/// part of it: which declaration governs, and so what it starts with, depends/// on the container, which is what is being decided.fn file_placement( session: &Session, filing: &str, sets: &[(String, Value)], now: &prov::Now, dry_run: bool,) -> Result<Placement, AnyError> { let Some(spec) = session .ctx .config .filing .iter() .find(|spec| spec.name == filing) .cloned() else { let declared: Vec<&str> = session .ctx .config .filing .iter() .map(|spec| spec.name.as_str()) .collect(); return Err(match declared.as_slice() { [] => format!("no filing entry named `{filing}` — this workspace declares none"), names => format!( "no filing entry named `{filing}` (declared: {})", names.join(", ") ), } .into()); }; let mut meta = Mapping::new(); if let Some((created, value)) = session.ctx.config.stamp_value(prov::Stamp::Create, now) { meta.insert(created.to_string(), Value::String(value)); } for (key, value) in sets { prov::meta::insert_path(&mut meta, key, value.clone()); } let plan = block_on( session .ws .plan_file(&session.ctx.root_doc, &spec, &Value::Mapping(meta)), )?; if dry_run { eprintln!("filing {filing:?} under {}", plan.anchor.display()); for index in &plan.create { eprintln!( " would create {} ({:?})", index.path.display(), index.title ); } eprintln!(" files in {}", plan.parent.display()); } Ok(Placement::Filed(plan))}
/// Print a route plan without applying it: what resolved, what is missing, and/// where the missing nodes would land. Shared by `--dry-run` and the error a/// missing route raises without `-p`, so the two describe the plan identically.fn show_route_plan(route: &str, plan: &RoutePlan) { eprintln!("route {route:?}"); for (depth, node) in plan.resolved.iter().enumerate() { eprintln!( " {:indent$}{} (exists)", "", node.display(), indent = depth * 2 ); } let base = plan.resolved.len(); for (depth, synth) in plan.synthesize.iter().enumerate() { eprintln!( " {:indent$}{} (create, titled {:?})", "", synth.path.display(), synth.title, indent = (base + depth) * 2 ); }}
/// Create a document under a parent named by `--in` — a path, an `id:` handle,/// or an `@`-route through the containment tree (optionally with `-p` to create/// the route segments that don't exist yet). The addressing mode is carried by/// the value itself (see [`parse_target`]), not by a per-mode flag.pub(crate) fn cmd_new(args: NewArgs) -> CmdResult { let NewArgs { title, in_target, filing, filed, parents, layout, dry_run, as_path, ext, set, } = args; let (title, layout) = (title.as_str(), Layout::from(layout)); let (as_path, ext, set) = (as_path.as_deref(), ext.as_deref(), set.as_slice()); // Parsed before anything is written, so a malformed `--set` refuses the // command rather than leaving a document created without it. let sets = parse_sets(set)?; // Authoring a reference that registers mints IDs, as does an eager policy, // and a route's synthesized nodes mint on the same terms as the leaf — so // the mutating open, which bootstraps the registry first. A dry run writes // nothing and must not bootstrap one either. let mut session = if dry_run { Session::open()? } else { Session::open_for_mutation()? };
// Resolve the parent. A path `--in` is already a path; a `@`-route walks the // tree from the root, and (with `-p`) plans what it doesn't find. Either way // the rest of this function is unchanged — a route is just another way to // *name* a parent, never a different kind of creation. Nothing the plan // lacks is built until every check on the leaf below has passed. // One reading of the clock for the whole command, so the document is // filed by the same instant it is stamped with. let now = crate::clock::now(); let by_kind = if filed { Some(filing_entry_for_kind(&session, prov::RecordKind::Page)?) } else { None }; let placement = match ( in_target.as_deref(), filing.as_deref().or(by_kind.as_deref()), ) { (Some(target), _) => plan_placement(&session, target, parents, layout, dry_run)?, (None, Some(filing)) => file_placement(&session, filing, &sets, &now, dry_run)?, (None, None) => { return Err( "name a parent with --in, or a filing entry with --filing or --filed".into(), ); } }; let parent_rel = placement.parent().to_path_buf();
// The new document's path: an explicit `--as` wins; otherwise a readable // filename derived from the title — `slug(title).<ext>` beside the parent, // where the extension is `--ext` or the workspace's content format. The title // itself is always recorded in metadata (structure lives there, not the name). let path = match as_path { Some(p) => ws_rel(&session.ctx, p)?, None => { let extension = ext .map(str::to_owned) .unwrap_or_else(|| session.ctx.config.content_format.extension().to_string()); let name = format!("{}.{extension}", link::slug(title)); parent_rel.parent().unwrap_or(Path::new("")).join(name) } }; // Leaf idempotency (`-p`): a target that already exists as the *same* // document (same title) is a no-op — `mkdir -p` for the leaf, completing the // route-parent `-p` above, so a daily-note cron can re-run the same command. // A path held by a *different*-titled document is a real collision and still // errors. Without `-p`, an existing leaf errors as before (via `create`). if parents && session.ws.fs_path(&path).exists() { let (_, existing) = load(&session.ws.fs_path(&path))?; if existing.meta.get("title").and_then(Value::as_str) != Some(title) { return Err(format!( "{} already exists with a different title — refusing to reuse it \ (pick another title, or --as to name a different file)", path.display() ) .into()); } if dry_run { eprintln!( "exists: {} (in {}) — no-op", path.display(), parent_rel.display() ); return Ok(ExitCode::SUCCESS); } // Ensure the containment link both ways (idempotent; refuses a contested // parent), so an existing-but-unlinked file converges too. The contract is // the *result*, not the action: an idempotent no-op still yields the path. let parent_rel = apply_placement(&mut session, placement)?; block_on(session.ws.adopt(&path, &parent_rel))?; session.commit()?; eprintln!("exists: {} (in {})", path.display(), parent_rel.display()); println!("{}", path.display()); return Ok(ExitCode::SUCCESS); } // Without `-p` the create below refuses an occupied path — but only after // a filing entry has built its containers, so the refusal is made here. if !parents && session.ws.fs_path(&path).exists() { return Err(prov::Error::AlreadyExists(path).into()); } if dry_run { eprintln!( "would create {} (in {})", path.display(), parent_rel.display() ); return Ok(ExitCode::SUCCESS); } let parent_rel = apply_placement(&mut session, placement)?; // (The session is the one opened above — reusing it keeps any IDs a route // just minted in the same in-memory index this create registers into.) let opening = opening_fields(&session.ctx, &session.ws, &parent_rel, sets, &now)?; let created = block_on( session .ws .create_with_fields(&path, &parent_rel, title, &opening), )?; session.commit()?; // A separated child is a pair — the metadata node the parent links, plus its // prose body file. Name both in the narration so it is clear two files were // written; stdout carries only the node (the linkable document). match &created.body { Some(body) => { eprintln!( "created {} (in {})", created.node.display(), parent_rel.display() ); eprintln!(" body: {}", body.display()); } None => eprintln!( "created {} (in {})", created.node.display(), parent_rel.display() ), } println!("{}", created.node.display()); Ok(ExitCode::SUCCESS)}
/// The `--set KEY=VALUE` pairs, typed like `set`'s value. A pair without an/// `=` is a refusal, not an empty value.fn parse_sets(set: &[String]) -> Result<Vec<(String, Value)>, AnyError> { let mut out = Vec::with_capacity(set.len()); for pair in set { let Some((key, value)) = pair.split_once('=') else { return Err(format!("--set {pair}: expected KEY=VALUE").into()); }; let key = key.trim(); if key.is_empty() { return Err(format!("--set {pair}: expected KEY=VALUE").into()); } out.push((key.to_string(), edit::infer_scalar(value).into())); } Ok(out)}
/// The fields a document made by `new` under `parent` opens with, beyond the/// ones prov authors itself, in the order they are written: the workspace's/// `created` stamp — the same clock and format as `updated`, and the library/// is as clockless here as it is there — then each `fields.<name>.default`/// whose declaration governs a child of `parent` (a `status: open` declared/// under `Tasks` reaches a task and not the readme beside the index), then/// every `--set`, which overrides a default of the same name.////// Only the document `new` names gets these. The index nodes a route with/// `-p` synthesizes on the way are made by the library's route walk, and a/// `status: open` meant for a task is not meant for the month index above it.////// Which declaration governs is found by climbing from `parent` to the root,/// not by resolving every scope over the whole tree: `new` adds one document/// under one parent, and should read as much of the workspace as that takes.fn opening_fields( ctx: &Ctx, ws: &Workspace<StdFs, Minter, FileIndex>, parent: &Path, sets: Vec<(String, Value)>, now: &prov::Now,) -> Result<Mapping, AnyError> { let mut fields = Mapping::new(); if let Some((created, value)) = ctx.config.stamp_value(prov::Stamp::Create, now) { fields.insert(created.to_string(), Value::String(value)); } for (name, value) in block_on(ws.defaults_for_child(&ctx.root_doc, &ctx.config, parent))? { fields.insert(name, value); } for (key, value) in sets { fields.insert(key, value); } Ok(fields)}
/// Attach an arbitrary file — or, with `--all`, every loose file under the/// workspace — minting a metadata sidecar and linking it under a parent/// (default: the workspace root). Mirrors [`cmd_new`] — an id-registering/// reference style or an eager policy mints IDs, so a registry is ensured first.pub(crate) fn cmd_attach(args: AttachArgs) -> CmdResult { let AttachArgs { payload, in_target, filed, parents, layout, opaque, all, recursive, manifest, no_hash, verbatim, inline, field, demote, promote, } = args; if field.is_some() && !(inline || demote) { return Err("--field applies only with --inline or --demote".into()); } if demote || promote { return cmd_attach_move( payload.as_deref(), in_target.as_deref(), field.as_deref(), demote, ); } let (payload, in_target, layout) = ( payload.as_deref(), in_target.as_deref(), Layout::from(layout), ); let hash = !no_hash; if recursive && !all { return Err("--recursive only applies with --all".into()); } let mut session = Session::open_for_mutation()?; // Every refusal the arguments can earn is made before a route or a filing // entry builds the parent: an attach that is going to refuse must not // leave index nodes behind it. if filed && payload.is_none() { return Err("--filed files one payload; name it".into()); } if all && payload.is_some() { return Err("pass a file or --all, not both".into()); } let payload_rel = match payload { Some(payload) => { let rel = ws_rel(&session.ctx, payload)?; if !session.ws.fs_path(&rel).exists() { return Err(prov::Error::NotFound(rel).into()); } Some(rel) } None if all => None, None => return Err("specify a file to attach, or pass --all".into()), }; // Default the parent to the workspace root — the common "attach this to my // workspace" case names no parent at all. Otherwise it is resolved exactly as // every other command resolves one, so an `@`-route `--in` works here too. // `--filed` asks the filing entry that names the payload's kind instead. let placement = match in_target { None if filed => { let Some(payload) = payload else { unreachable!("refused above"); }; let kind = if manifest { prov::RecordKind::Manifest } else { prov::payload_kind(payload) }; let entry = filing_entry_for_kind(&session, kind)?; let now = crate::clock::now(); file_placement(&session, &entry, &[], &now, false)? } None => Placement::Exists(session.ctx.root_doc.clone()), Some(t) => plan_placement(&session, t, parents, layout, false)?, }; // The library's own refusals of the payload, asked before the placement // builds anything: an attach it refuses — a payload already attached, a // prov document without `--opaque`, a file where a manifest wants a // directory — used to be found only once a route had built its nodes. // (`--all` attaches what it finds, reporting each refusal and going on.) if let Some(payload_rel) = &payload_rel { if manifest { block_on(session.ws.check_attach_manifest(payload_rel))?; } else { block_on(session.ws.check_attach(payload_rel, opaque))?; } } let parent_rel = apply_placement(&mut session, placement)?;
// The inline form: the file is owned by the document `--in` names, as a // row in its metadata, and gets no sidecar. `check_attach` above already // refused what this would refuse of the payload itself. if inline { let Some(payload_rel) = &payload_rel else { unreachable!("--inline conflicts with --all"); }; let at = block_on( session .ws .attach_inline(payload_rel, &parent_rel, field.as_deref()), )?; session.commit()?; eprintln!( "attached {} inline (at {at} in {})", payload_rel.display(), parent_rel.display() ); println!("{}", parent_rel.display()); return Ok(ExitCode::SUCCESS); }
if all { // Bounded to reached directories by default; `--recursive` sweeps the // whole tree (a pure asset dump you know is all attachments). let loose = if recursive { block_on(session.ws.loose_attachments())? } else { block_on(session.ws.loose_attachments_in(&session.ctx.root_doc))? }; if loose.is_empty() { eprintln!("no loose files to attach"); return Ok(ExitCode::SUCCESS); } let mut attached = 0usize; for p in &loose { match block_on(session.ws.attach(p, &parent_rel)) { Ok(node) => { eprintln!("attached {} (sidecar {})", p.display(), node.display()); println!("{}", node.display()); attached += 1; } Err(e) => eprintln!("prov: could not attach {}: {e}", p.display()), } } session.commit()?; eprintln!("attached {attached} file(s) under {}", parent_rel.display()); return Ok(ExitCode::SUCCESS); }
let (Some(payload), Some(payload_rel)) = (payload, payload_rel) else { unreachable!("a payload is named whenever --all is not"); };
// The bulk form: the positional is a directory, and it gains one node and // one list rather than a sidecar per file. if manifest { let node = block_on(session.ws.attach_manifest_claiming( &payload_rel, &parent_rel, None, hash, verbatim, ))?; session.commit()?; let (manifest_doc, listed) = block_on(session.ws.manifest_of(&node))? .map(|(doc, m)| (doc, m.files.len())) .unwrap_or_default(); eprintln!( "covered {} ({listed} file(s) in {}, node {} in {})", payload.display(), manifest_doc.display(), node.display(), parent_rel.display() ); println!("{}", node.display()); return Ok(ExitCode::SUCCESS); }
let node = if opaque { block_on(session.ws.attach_opaque(&payload_rel, &parent_rel))? } else { block_on(session.ws.attach(&payload_rel, &parent_rel))? }; session.commit()?; eprintln!( "attached {} (sidecar {} in {})", payload.display(), node.display(), parent_rel.display() ); println!("{}", node.display()); Ok(ExitCode::SUCCESS)}
/// `attach --demote` and `attach --promote`: move a file between a card of/// its own and a row in the document that shows it.fn cmd_attach_move( payload: Option<&Path>, in_target: Option<&str>, field: Option<&str>, demote: bool,) -> CmdResult { let Some(payload) = payload else { return Err("name the card or file to move".into()); }; let mut session = Session::open_for_mutation()?; let rel = ws_rel(&session.ctx, payload)?; if !session.ws.fs_path(&rel).exists() { return Err(prov::Error::NotFound(rel).into()); } let target = match in_target { Some(t) => Some(ws_rel(&session.ctx, &resolve_target(t)?)?), None => None, }; if demote { let (into, at) = block_on(session.ws.demote(&rel, target.as_deref(), field))?; session.commit()?; eprintln!( "demoted {} to a row (at {at} in {})", rel.display(), into.display() ); println!("{}", into.display()); } else { let node = block_on(session.ws.promote(&rel, target.as_deref()))?; session.commit()?; eprintln!("promoted {} to a card ({})", rel.display(), node.display()); println!("{}", node.display()); } Ok(ExitCode::SUCCESS)}
pub(crate) fn cmd_mv( from: &str, to: &Path, in_target: Option<&str>, parents: bool, layout: Layout,) -> CmdResult { let from_resolved = resolve_target(from)?; // `rename` mints nothing, but `--under -p` synthesizes nodes with `create`, // which does — so a registry has to exist before the route runs, exactly as in // `new`/`reparent`. Plain `mv` skips this and stays as cheap as it was. let mut session = if in_target.is_some() { Session::open_for_mutation()? } else { Session::open()? }; let from_rel = ws_rel(&session.ctx, &from_resolved)?; let to_rel = ws_rel(&session.ctx, to)?;
// The parent is resolved, and the reparent's own refusals asked, before // the rename: a move refused for its parent must not have moved the file. // It used to be the other way round, which left a document at its new // path without the parent it was moved to join. The reparent is asked of // `from` — the path it holds until the rename — since the rename carries // every link that decides whether it would refuse. let placement = match in_target { Some(target) => { let placement = plan_placement(&session, target, parents, layout, false)?; if session.ws.fs_path(&from_rel).is_dir() { return Err(format!( "--in {target}: {} is a directory, and only a document has a parent", from_rel.display() ) .into()); } placement.check_reparent(&session, &from_rel)?; Some(placement) } None => None, };
// `rename` makes its own refusals (an occupied destination, a nested // workspace's edge) before it writes, and is the first write here, so a // route `-p` would build is built only once the move has landed. block_on(session.ws.rename(&from_rel, &to_rel))?; eprintln!("moved {} -> {}", from_resolved.display(), to.display());
// The move first, then the reparent — in that order because `rename` has // already retargeted every inbound link, so the parent the reparent removes is // found at the document's *new* path. Doing it the other way would reparent a // path that is about to stop existing. if let Some(placement) = placement { let parent_rel = apply_placement(&mut session, placement)?; if block_on(session.ws.reparent(&to_rel, &parent_rel))? != prov::Reparented::Unchanged { eprintln!("reparented {} -> in {}", to.display(), parent_rel.display()); } } session.commit()?; // The document's new location is the handle a caller acts on next. println!("{}", to_rel.display()); Ok(ExitCode::SUCCESS)}
pub(crate) fn cmd_reparent( path: &str, in_target: &str, parents: bool, layout: Layout, dry_run: bool,) -> CmdResult { // Resolved before the session opens, as in `reorder`: a route or an id // opens a session of its own to look itself up. let path_resolved = resolve_target(path)?; // A route's synthesized nodes are `create`d and so mint on the same terms as // any other document — the registry must exist before the route is applied. // (The reparent itself authors links too, which an id-authoring workspace // registers.) A dry run writes nothing and must not bootstrap one either. let mut session = if dry_run { Session::open()? } else { Session::open_for_mutation()? }; let placement = plan_placement(&session, in_target, parents, layout, dry_run)?; let path_rel = ws_rel(&session.ctx, &path_resolved)?; // `reparent` refuses before it writes, but a route `-p` builds its nodes // before there is a parent to reparent under — so the refusal is asked // first, while nothing has been built. placement.check_reparent(&session, &path_rel)?; // The preview is made here, after the refusals and before the first // write, however the parent was named. A path or an id used to fall // through to the reparent and commit it; a route used to stop once its // plan was printed, before the refusals. if dry_run { eprintln!( "would reparent {} -> in {}", path_rel.display(), placement.parent().display() ); return Ok(ExitCode::SUCCESS); } let parent_rel = apply_placement(&mut session, placement)?; let path_rel = ws_rel(&session.ctx, &resolve_target(path)?)?; let outcome = block_on(session.ws.reparent(&path_rel, &parent_rel))?; session.commit()?; // Say which of the three happened. "reparented" for a run that wrote // nothing is how a workspace full of half-linked documents survives a // repair pass that reported success on every one of them. match outcome { prov::Reparented::Moved => eprintln!( "reparented {} -> in {}", path_rel.display(), parent_rel.display() ), prov::Reparented::Linked => eprintln!( "{} already claimed {} — added the missing entry in {}", path_rel.display(), parent_rel.display(), parent_rel.display() ), prov::Reparented::Unchanged => eprintln!( "{} is already in {}, both ways — nothing to do", path_rel.display(), parent_rel.display() ), } println!("{}", path_rel.display()); Ok(ExitCode::SUCCESS)}
pub(crate) fn cmd_reorder(parent: &str, children: &[String]) -> CmdResult { // Nothing here authors a link, so nothing can mint: an ordinary session, as // for `rm`. Every target is resolved before the session opens, since a // route or an id opens one of its own to look itself up. let parent_resolved = resolve_target(parent)?; let children_resolved = children .iter() .map(|child| resolve_target(child)) .collect::<Result<Vec<_>, _>>()?; let mut session = Session::open()?; let parent_rel = ws_rel(&session.ctx, &parent_resolved)?; let order = children_resolved .iter() .map(|child| ws_rel(&session.ctx, child)) .collect::<Result<Vec<_>, _>>()?; let outcome = block_on(session.ws.reorder(&parent_rel, &order))?; session.commit()?; // As with `reparent`: a run that wrote nothing says so, rather than // reporting a change the file did not see. match outcome { prov::Reordered::Moved => eprintln!("reordered {}", parent_rel.display()), prov::Reordered::Unchanged => eprintln!( "{} already holds that order — nothing to do", parent_rel.display() ), } println!("{}", parent_rel.display()); Ok(ExitCode::SUCCESS)}
pub(crate) fn cmd_rm(path: &str, force: bool) -> CmdResult { let resolved = resolve_target(path)?; let mut session = Session::open()?; let target = ws_rel(&session.ctx, &resolved)?;
// The `record_deletions` axis reaches the library through `Settings`, so the // one verb covers both postures; what the CLI adds is the clock, which the // library takes as an argument rather than reading. let recorded = session.ctx.config.record_deletions; let now = now_rfc3339(); let danglers = block_on(session.ws.delete_with( &target, force, recorded.then_some(now.as_str()), prov::Diagnosis::Report, ))?; session.commit()?; if recorded { println!( "deleted {} (recorded; `prov restore` relinks it once the file is back)", resolved.display() ); } else { println!("deleted {}", resolved.display()); } // The first recorded delete *bootstraps* the log and adds the root's // `deletions` pointer — another machinery file the page lists. A no-op on // every later delete, since the pointer already exists. refresh_about(&session.ctx.root_dir)?; for finding in &danglers { eprintln!("warning: now dangling — {finding}"); } Ok(ExitCode::SUCCESS)}
pub(crate) fn cmd_restore(path: &str) -> CmdResult { let mut session = Session::open()?; // The path names a document that was deleted, so it cannot be // `resolve_target`-ed — that reads the file, and under the ordinary restore // the caller has only just put one back there. Take it as given, relative to // the workspace root. let from = ws_rel(&session.ctx, Path::new(path))?; block_on(session.ws.restore(&from, &session.ctx.root_doc))?; session.commit()?; eprintln!("restored {}", from.display()); println!("{}", from.display()); Ok(ExitCode::SUCCESS)}
pub(crate) fn cmd_clear_deletions() -> CmdResult { let mut session = Session::open()?; let forgotten = block_on(session.ws.clear_deletions(&session.ctx.root_doc))?; session.commit()?; // A bulk operation yields no object to name — narration only, stdout stays // empty. eprintln!("forgot {forgotten} deletion record(s)"); Ok(ExitCode::SUCCESS)}
pub(crate) fn cmd_duplicate(source: &str) -> CmdResult { let resolved = resolve_target(source)?; // Attaching the copy authors the parent's spanning entry, which mints an ID // when that style registers (or under an eager policy) — same as `new`. let mut session = Session::open_for_mutation()?; let copy = block_on(session.ws.duplicate(&ws_rel(&session.ctx, &resolved)?))?; session.commit()?; eprintln!("duplicated {} -> {}", resolved.display(), copy.display()); println!("{}", copy.display()); Ok(ExitCode::SUCCESS)}