Skip to main content

nibkeep_cli/
trees.rs

1//! Trees: folders whose files NibKeep keeps with every version, as Git keeps a working tree
2//! ([technical design: trees]). Their commands are named as Git, Mercurial, Subversion, Fossil
3//! and Jujutsu name theirs, and each works in the tree whose folder on this device holds the
4//! current folder, unless it names one; `nib init` in a library starts one.
5//!
6//! [technical design: trees]: ../../../docs/Technical-design.md#15-trees
7
8use std::fs;
9use std::io::Write;
10use std::path::{Path, PathBuf};
11
12use clap::Subcommand;
13use nibkeep_base::EntityId;
14use nibkeep_git::Git;
15use nibkeep_node::{
16	BlameLine, Change, Commit, Committed, FileDiff, Library, NodeError, Reverted, ToClone, Tree,
17	TreeChange, TreeLogEntry, TreePoint, TreeSecrets, TreeStatus, Updated, Written,
18};
19use serde_json::json;
20
21use crate::output::{count, moment_text, print_json, short, shown};
22use crate::{CliError, Environment, Timings, absolute, current_dir};
23use nibkeep_node::pointer::{self, Settled};
24
25/// The commands of trees, named as Git, Mercurial, Subversion, Fossil and Jujutsu name
26/// theirs, so that whoever knows one of them knows these: each works in the tree whose
27/// folder holds the current folder, unless it names one.
28#[derive(Debug, Subcommand)]
29pub enum TreeCommand {
30	/// Records what changed in the tree's copy here as one revision.
31	///
32	/// It records what changed, or what changed at the paths given, with a message or
33	/// without: new files, new versions, moves, deletions and executable bits; and the Git
34	/// repositories in it, as your Git describes them: their remotes, with no credential,
35	/// branch, and commit if pinned. New files need no adding first, and a file gone from
36	/// one path and found with the same content at another moved. Every version is kept.
37	/// What changed elsewhere since the copy was written is refused, unless --force records
38	/// it on top. A new file is secret if its name is one such as `.env` or a private
39	/// key's, or a `.nibsecret` file names it, in Git's syntax for `.gitignore`: it is
40	/// sealed for the secrets, whose passphrase this asks for, and stays secret for good.
41	/// With --pin or --unpin, it records only that.
42	#[command(visible_alias = "ci")]
43	Commit {
44		/// The files and folders to commit; without them, everything that changed.
45		#[arg(conflicts_with_all = ["pin", "unpin"])]
46		paths: Vec<PathBuf>,
47		/// Commits everything that changed, as without paths: Git's -a.
48		#[arg(short, long, conflicts_with = "paths")]
49		all: bool,
50		/// The revision's message.
51		#[arg(short, long)]
52		message: Option<String>,
53		/// Records on top what changed elsewhere since the copy was written, which history
54		/// keeps, and copies edited from a version this device does not know.
55		#[arg(long)]
56		force: bool,
57		/// Takes in this new file as a secret file, though no name or .nibsecret makes it
58		/// one; or makes this committed file secret: a new secret file, and its old versions
59		/// purged everywhere once you agree.
60		#[arg(long, value_name = "PATH")]
61		secret: Vec<PathBuf>,
62		/// Takes in this new file as an ordinary file, though it would be secret.
63		#[arg(long, value_name = "PATH")]
64		ordinary: Vec<PathBuf>,
65		/// Commits the rest where a secret file's change waits for the secrets, as on a
66		/// device that does not hold them.
67		#[arg(long)]
68		leave_secrets: bool,
69		/// Pins the Git repository in this folder at the commit it has checked out, as a
70		/// revision of its own: writing the tree elsewhere then clones it at that commit, and
71		/// commits keep it as Git says it is.
72		#[arg(
73			long,
74			value_name = "FOLDER",
75			conflicts_with_all = ["all", "message", "force", "secret", "ordinary", "leave_secrets", "unpin"]
76		)]
77		pin: Option<PathBuf>,
78		/// Takes away the pin of the Git repository in this folder, as a revision of its own:
79		/// clones then take the branch as its remote has it.
80		#[arg(
81			long,
82			value_name = "FOLDER",
83			conflicts_with_all = ["all", "message", "force", "secret", "ordinary", "leave_secrets"]
84		)]
85		unpin: Option<PathBuf>,
86	},
87	/// Moves a file or a folder, on the disk and in the tree at once.
88	///
89	/// A folder moves with everything in it, as a revision of its own: its history follows
90	/// it. Nothing is moved onto what is there, out of the tree, or into `.nib` or a
91	/// `.git`.
92	#[command(visible_alias = "rename")]
93	Mv {
94		/// Where it is.
95		from: PathBuf,
96		/// Where it goes.
97		to: PathBuf,
98	},
99	/// Deletes copies of the tree's files here, for the next commit.
100	///
101	/// It deletes the copies at the paths given, or in the folders given, and the folders
102	/// they leave empty: the next commit records them as deleted. A
103	/// copy with edits not committed stays, unless --force, and so do files that the tree does
104	/// not hold. It records nothing.
105	#[command(visible_alias = "remove")]
106	Rm {
107		/// The files and folders.
108		#[arg(required = true)]
109		paths: Vec<PathBuf>,
110		/// Takes folders, as Git's -r; they are taken without it too.
111		#[arg(short, long)]
112		recursive: bool,
113		/// Deletes copies with edits not committed too, which are then lost.
114		#[arg(short, long)]
115		force: bool,
116	},
117	/// Lists the changes to the tree, or to one file, newest first.
118	///
119	/// The changes to the file at the path given are followed across its moves: when each
120	/// was made, by whom, and its revision's message. A change made otherwise, such as with
121	/// nib edit, is listed without one.
122	Log {
123		/// The file or link, as the tree names it now.
124		path: Option<PathBuf>,
125		/// The tree, by its name or ID, instead of the one here; paths are then the tree's.
126		#[arg(long, value_name = "TREE")]
127		tree: Option<String>,
128	},
129	/// Shows how the copy here differs from the tree, or two revisions.
130	///
131	/// It shows what a commit would record, with the lines of text that changed. With a
132	/// revision, how the tree differs from it to the tree now; with two, from the first to
133	/// the second, as their authors had the tree. A secret file shows only that it changed,
134	/// unless --secrets asks for its lines. What one revision changed, nib show shows.
135	Diff {
136		/// The revision to compare from.
137		#[arg(conflicts_with_all = ["since", "until"])]
138		from: Option<String>,
139		/// The revision to compare to.
140		to: Option<String>,
141		/// The revision to compare from, as Mercurial, Fossil and Jujutsu name it.
142		#[arg(long = "from", id = "since", value_name = "REVISION")]
143		since: Option<String>,
144		/// The revision to compare to, with --from.
145		#[arg(long = "to", id = "until", value_name = "REVISION", requires = "since")]
146		until: Option<String>,
147		/// The tree, by its name or ID, instead of the one here.
148		#[arg(long, value_name = "TREE")]
149		tree: Option<String>,
150		/// Shows the lines of secret files too, asking for the secrets' passphrase.
151		#[arg(long)]
152		secrets: bool,
153	},
154	/// Names the revision and author that last changed each line.
155	///
156	/// For each line of the file at the path given, it follows every version the file had,
157	/// wherever it was then.
158	#[command(visible_alias = "annotate")]
159	Blame {
160		/// The file, as the tree names it now.
161		path: PathBuf,
162		/// The tree, by its name or ID, instead of the one here; the path is then the tree's.
163		#[arg(long, value_name = "TREE")]
164		tree: Option<String>,
165		/// Blames a secret file too, asking for the secrets' passphrase.
166		#[arg(long)]
167		secrets: bool,
168	},
169	/// Writes a file into the copy here as it was, or as the tree has it.
170	///
171	/// It writes the file at the path given, or what is in the folder, as it was at a
172	/// revision or as of a moment; without either, as the tree has it, a file deleted
173	/// from the tree too. A copy with edits not committed is moved beside it first, as
174	/// NAME.orig, so that its edits are kept. It records nothing: commit what it wrote once
175	/// you checked it.
176	Restore {
177		/// The file or folder, as the tree named it then.
178		path: PathBuf,
179		/// The revision whose author's tree to take it from.
180		#[arg(short = 'r', long, value_name = "REVISION", conflicts_with = "as_of")]
181		at: Option<String>,
182		/// The moment as of which the library recorded it: a day, which means its end, or a
183		/// moment, such as 2026-10-10T20:00, in local time unless it gives its offset.
184		#[arg(long, value_name = "WHEN", value_parser = crate::parse_moment)]
185		as_of: Option<crate::Moment>,
186	},
187	/// Writes into the copy here what undoes a revision.
188	///
189	/// It writes that only, as Git's revert and Mercurial's backout do: each file it
190	/// changed goes back to its version before it, merged three ways with what later
191	/// revisions changed; files it moved go back, files it deleted come back, and files it
192	/// added go. Where later edits clash, text gets Git's conflict markers, and other files
193	/// the version from before beside them. It records nothing: commit what it wrote once
194	/// you checked it.
195	#[command(visible_alias = "backout")]
196	Revert {
197		/// The revision, by its ID or the start of it.
198		revision: String,
199	},
200	/// Brings the copy here to the tree as your other devices left it.
201	///
202	/// It brings what has reached this device: writes new versions, moves, additions and
203	/// deletions, and merges your edits with newer versions. Where versions compete, as
204	/// when two devices committed one file apart, text is merged three ways, with Git's
205	/// conflict markers where edits clash, and anything else stays as it is, with the other
206	/// version beside it as NAME.conflict-DEVICE. A file edited here and deleted elsewhere
207	/// stays. Nothing is recorded: committing what it wrote settles what competed. A commit
208	/// in several parts waits until all its parts have arrived. The Git repositories that
209	/// this copy lacks are listed, with where they come from, and cloned with your Git once
210	/// you agree. Secret files are written with the secrets unlocked, readable only by you;
211	/// a secret file moved elsewhere, and a .nibsecret that lost lines, are written once
212	/// you agree. nib pull syncs first.
213	#[command(visible_alias = "up")]
214	Update {
215		/// Writes what parts have arrived of a commit whose other parts have not.
216		#[arg(long)]
217		partial: bool,
218		/// Clones the Git repositories added elsewhere without asking.
219		#[arg(long, conflicts_with = "no_clone")]
220		clone: bool,
221		/// Clones no Git repository, and lists those it would.
222		#[arg(long)]
223		no_clone: bool,
224	},
225	/// Writes a tree into a folder, as it is or as it was.
226	///
227	/// The folder is empty or new, by default one named after the tree in the current
228	/// folder: as it is, which becomes this device's copy of it, as on a device that joined
229	/// the library, with its Git repositories cloned once you agree; or with --at or
230	/// --as-of, a picture of the past, which is no copy to commit from.
231	Clone {
232		/// The tree, by its name or ID.
233		tree: String,
234		/// The folder.
235		folder: Option<PathBuf>,
236		/// The revision whose author's tree to write.
237		#[arg(short = 'r', long, value_name = "REVISION", conflicts_with = "as_of")]
238		at: Option<String>,
239		/// The moment as of which the library recorded the tree to write.
240		#[arg(long, value_name = "WHEN", value_parser = crate::parse_moment)]
241		as_of: Option<crate::Moment>,
242		/// Clones the tree's Git repositories without asking.
243		#[arg(long, conflicts_with = "no_clone")]
244		clone: bool,
245		/// Clones no Git repository, and lists those it would.
246		#[arg(long)]
247		no_clone: bool,
248	},
249}
250
251/// Whether to clone: yes or no as the person said with --clone or --no-clone, or ask.
252fn clone_choice(clone: bool, no_clone: bool) -> Option<bool> {
253	match (clone, no_clone) {
254		(true, _) => Some(true),
255		(_, true) => Some(false),
256		_ => None,
257	}
258}
259
260/// What became of a Git repository that a tree records and its copy here does not hold.
261#[derive(Debug)]
262enum Cloning {
263	/// Cloned.
264	Cloned,
265	/// Not cloned, as the person did not agree.
266	NotAgreed,
267	/// Refused, with why.
268	Refused(String),
269	/// Failed, with what was said.
270	Failed(String),
271}
272
273/// Lists the Git repositories that the copy of `tree` here does not hold, and clones those
274/// the engine allows once the person agrees, or as --clone or --no-clone said; never for a
275/// program that reads --json, unless --clone.
276fn clone_step<E: Environment>(
277	library: &Library,
278	tree: EntityId,
279	choice: Option<bool>,
280	json: bool,
281	environment: &mut E,
282) -> Result<Vec<(ToClone, Cloning)>, CliError> {
283	let space = library.default_space();
284	let to_clone = library.repositories_to_clone(space, tree)?;
285	let allowed: Vec<&ToClone> = to_clone
286		.iter()
287		.filter(|repository| repository.refused.is_none())
288		.collect();
289	let agreed = match choice {
290		Some(choice) => choice,
291		None if json || allowed.is_empty() => false,
292		None => {
293			use std::fmt::Write as _;
294			let mut question =
295				String::from("Clone these Git repositories, with your Git and its credentials?\n");
296			for repository in &allowed {
297				let _ = writeln!(
298					question,
299					"  {} from {} ({}), recorded by {}",
300					shown(&repository.path),
301					shown(&repository.address),
302					shown(&repository.remote),
303					shown(&repository.recorded_by)
304				);
305				for (name, address) in &repository.others {
306					let _ = writeln!(
307						question,
308						"    and the remote {} at {}",
309						shown(name),
310						shown(address)
311					);
312				}
313			}
314			question.push_str("[y/N] ");
315			environment
316				.ask(&question)?
317				.is_some_and(|answer| matches!(answer.trim().to_lowercase().as_str(), "y" | "yes"))
318		}
319	};
320	let mut results = Vec::with_capacity(to_clone.len());
321	for repository in to_clone {
322		let outcome = if let Some(why) = &repository.refused {
323			Cloning::Refused(why.clone())
324		} else if !agreed {
325			Cloning::NotAgreed
326		} else {
327			clone_one(
328				library,
329				tree,
330				&repository,
331				&Git::from_template(&environment.git()),
332			)
333		};
334		results.push((repository, outcome));
335	}
336	Ok(results)
337}
338
339/// Clones one repository into the folder the engine makes for it. A clone that fails is
340/// removed, with the folders made for it, as nothing in them is the person's; one whose
341/// branch no remote has takes the remote's own branch instead.
342fn clone_one(library: &Library, tree: EntityId, repository: &ToClone, git: &Git) -> Cloning {
343	let space = library.default_space();
344	let mut place = match library.prepare_clone(space, tree, repository) {
345		Ok(place) => place,
346		Err(error) => return Cloning::Failed(error.to_string()),
347	};
348	let mut cloned = git.clone(repository, &place.folder);
349	if let Err(why) = &cloned
350		&& repository.branch.is_some()
351		&& why.contains("not found in upstream")
352	{
353		remove_clone(&place);
354		let without_branch = ToClone {
355			branch: None,
356			..repository.clone()
357		};
358		match library.prepare_clone(space, tree, repository) {
359			Ok(again) => {
360				place = again;
361				cloned = git.clone(&without_branch, &place.folder);
362			}
363			// What is in the place now is not this clone's: it stays.
364			Err(error) => return Cloning::Failed(error.to_string()),
365		}
366	}
367	match cloned {
368		Ok(()) => {
369			let Some(described) = git.describe_one(&place.folder, &repository.path) else {
370				remove_clone(&place);
371				return Cloning::Failed("Git cannot read the clone".to_owned());
372			};
373			// Moved or deleted elsewhere meanwhile: the clone goes, and an update tells.
374			if let Err(error) = library.repository_cloned(space, tree, (repository, &described)) {
375				remove_clone(&place);
376				return Cloning::Failed(error.to_string());
377			}
378			Cloning::Cloned
379		}
380		Err(why) => {
381			remove_clone(&place);
382			Cloning::Failed(why)
383		}
384	}
385}
386
387/// Removes a clone that failed, and the folders made for it, from the innermost, each only
388/// if nothing else came into it meanwhile: a folder in which Git made no repository is
389/// removed only if it is empty, as what is in it is not the clone's.
390fn remove_clone(place: &nibkeep_node::CloneFolder) {
391	if fs::symlink_metadata(place.folder.join(".git")).is_ok_and(|metadata| metadata.is_dir()) {
392		let _ = fs::remove_dir_all(&place.folder);
393	} else {
394		let _ = fs::remove_dir(&place.folder);
395	}
396	for folder in place.made.iter().rev() {
397		if fs::remove_dir(folder).is_err() {
398			break;
399		}
400	}
401}
402
403/// The results of cloning, for --json.
404fn clones_json(clones: &[(ToClone, Cloning)]) -> Vec<serde_json::Value> {
405	clones
406		.iter()
407		.map(|(repository, outcome)| {
408			let (state, why) = match outcome {
409				Cloning::Cloned => ("cloned", None),
410				Cloning::NotAgreed => ("to clone", None),
411				Cloning::Refused(why) => ("refused", Some(why.as_str())),
412				Cloning::Failed(why) => ("failed", Some(why.as_str())),
413			};
414			json!({
415				"path": repository.path,
416				"remote": repository.remote,
417				"address": repository.address,
418				"recorded_by": repository.recorded_by,
419				"state": state,
420				"why": why,
421			})
422		})
423		.collect()
424}
425
426/// Prints the results of cloning, one a line.
427fn clones_text(clones: &[(ToClone, Cloning)], output: &mut dyn Write) -> Result<(), CliError> {
428	for (repository, outcome) in clones {
429		let path = shown(&repository.path);
430		let from = format!(
431			"from {} ({}), recorded by {}",
432			shown(&repository.address),
433			shown(&repository.remote),
434			shown(&repository.recorded_by)
435		);
436		match outcome {
437			Cloning::Cloned => writeln!(output, "cloned    {path}, {from}")?,
438			Cloning::NotAgreed => writeln!(
439				output,
440				"to clone  {path}, {from}: nib update --clone clones it"
441			)?,
442			Cloning::Refused(why) => writeln!(output, "not cloned {path}: {}", shown(why))?,
443			Cloning::Failed(why) => writeln!(output, "could not clone {path}: {}", shown(why))?,
444		}
445	}
446	Ok(())
447}
448
449/// What a status says of the Git repositories in a tree's copy: what a commit would record
450/// of them, and the work that only this computer holds, by path.
451#[derive(Debug, Default)]
452struct Repositories {
453	changes: Vec<TreeChange>,
454	work: Vec<(String, Vec<String>)>,
455}
456
457/// Reads with Git what the repositories that a status found hold, against the tree.
458fn repositories_here<E: Environment>(
459	library: &Library,
460	(tree, root): (EntityId, &Path),
461	status: &TreeStatus,
462	environment: &E,
463) -> Result<Repositories, CliError> {
464	if status.repositories.is_empty() {
465		return Ok(Repositories::default());
466	}
467	let space = library.default_space();
468	let git = Git::from_template(&environment.git());
469	let described = git.describe(root, &status.repositories);
470	let changes = library.repository_changes(space, tree, (&status.repositories, &described))?;
471	let pinned: std::collections::BTreeMap<String, String> = library
472		.tree_repositories(space, tree)?
473		.into_iter()
474		.filter_map(|recorded| recorded.pinned.map(|pinned| (recorded.path, pinned)))
475		.collect();
476	let mut work = Vec::new();
477	for path in &status.repositories {
478		let found = git.work_only_here(&root.join(path), pinned.get(path).map(String::as_str));
479		if !found.is_empty() {
480			work.push((path.clone(), found));
481		}
482	}
483	Ok(Repositories { changes, work })
484}
485
486/// Prints what a commit recorded, or would record, of Git repositories.
487fn repositories_text(changes: &[TreeChange], output: &mut dyn Write) -> Result<(), CliError> {
488	for change in changes {
489		let path = &shown(&change.path);
490		match &change.change {
491			Change::New => writeln!(output, "new       {path}, a Git repository")?,
492			Change::Deleted => writeln!(output, "deleted   {path}, a Git repository")?,
493			Change::Moved { from } => {
494				writeln!(
495					output,
496					"moved     {path}, from {}, a Git repository",
497					shown(from)
498				)?;
499			}
500			_ => writeln!(
501				output,
502				"edited    {path}, a Git repository's remotes, branch or pinned commit"
503			)?,
504		}
505	}
506	Ok(())
507}
508
509/// Runs a command of trees, of the library in `library_folder`, in the space of the tree it
510/// works on.
511pub(crate) fn tree_command<E: Environment>(
512	library: &mut Library,
513	(library_folder, command): (&Path, &TreeCommand),
514	json: bool,
515	(environment, timings): (&mut E, &mut Timings),
516	output: &mut dyn Write,
517) -> Result<(), CliError> {
518	choose_tree_space(library, named_tree(command), environment)?;
519	match command {
520		TreeCommand::Commit {
521			pin: Some(folder), ..
522		} => pin_command(library, (folder, false), json, environment, output),
523		TreeCommand::Commit {
524			unpin: Some(folder),
525			..
526		} => pin_command(library, (folder, true), json, environment, output),
527		commit @ TreeCommand::Commit { .. } => {
528			commit_command(library, commit, json, (environment, timings), output)
529		}
530		TreeCommand::Mv { from, to } => {
531			let (tree, root) = tree_here(library, environment)?;
532			let from = nibkeep_node::tree_path_at(&root, &absolute(from, environment)?)?;
533			let to = nibkeep_node::tree_path_at(&root, &absolute(to, environment)?)?;
534			let now = environment.now();
535			let space = library.default_space();
536			let moved =
537				library.move_in_tree(space, tree.id, (&from, &to), now, environment.rng())?;
538			if json {
539				return committed_output((&moved, &0), json, output);
540			}
541			let revision = moved.revision.map_or_else(String::new, |revision| {
542				format!(", as revision {}", short(revision))
543			});
544			writeln!(output, "Moved {from} to {to}{revision}")?;
545			Ok(())
546		}
547		TreeCommand::Rm { paths, force, .. } => {
548			rm_command(library, (paths, *force), json, environment, output)
549		}
550		read @ (TreeCommand::Log { .. } | TreeCommand::Diff { .. } | TreeCommand::Blame { .. }) => {
551			read_command(library, read, json, (environment, timings), output)
552		}
553		back => back_command(
554			library,
555			(library_folder, back),
556			json,
557			(environment, timings),
558			output,
559		),
560	}
561}
562
563/// Runs `nib status --secrets`: lists the tree's secret files, and its ordinary files that
564/// look secret.
565pub(crate) fn secrets_command<E: Environment>(
566	library: &mut Library,
567	json: bool,
568	environment: &mut E,
569	output: &mut dyn Write,
570) -> Result<(), CliError> {
571	choose_tree_space(library, None, environment)?;
572	let (tree, _) = tree_here(library, environment)?;
573	let listed = library.tree_secrets(library.default_space(), tree.id)?;
574	secrets_output(&listed, json, output)
575}
576
577/// Runs `nib init` in the library in `library_folder`: makes the folder given, or the
578/// current one, a tree, once the person agrees, unless `yes`.
579pub(crate) fn init_command<E: Environment>(
580	library: &mut Library,
581	(library_folder, (folder, message, yes)): (&Path, (Option<&Path>, Option<&str>, bool)),
582	json: bool,
583	(environment, timings): (&mut E, &mut Timings),
584	output: &mut dyn Write,
585) -> Result<(), CliError> {
586	let folder = match folder {
587		Some(folder) => absolute(folder, environment)?,
588		None => current_dir(environment)?,
589	};
590	if rewrite_pointer(
591		library,
592		(library_folder, &folder),
593		json,
594		environment,
595		output,
596	)? {
597		return Ok(());
598	}
599	let start = (folder.as_path(), message, yes);
600	start_command(
601		library,
602		(library_folder, start),
603		json,
604		(environment, timings),
605		output,
606	)
607}
608
609/// Settles the `.nib` file of the tree whose folder is `folder` already, and says so: writes it
610/// again if commands there need it to find the library in `library_folder` and it does not
611/// name it, as after a crash, or after the library's folder moved; or takes away one that
612/// they do not need, which would take them over, as one copied there with the folder. Whether
613/// it did either.
614fn rewrite_pointer<E: Environment>(
615	library: &Library,
616	(library_folder, folder): (&Path, &Path),
617	json: bool,
618	environment: &E,
619	output: &mut dyn Write,
620) -> Result<bool, CliError> {
621	let Ok(root) = nibkeep_node::resolved_path(folder) else {
622		return Ok(false);
623	};
624	let Some((space, tree)) = pointer::tree_rooted_at(library, &root)? else {
625		return Ok(false);
626	};
627	let ceiling = environment.ceiling();
628	if pointer::needed(&root, library_folder, ceiling.as_deref())
629		&& pointer::names(&root, library_folder)
630	{
631		return Ok(false);
632	}
633	let settled = pointer::settle(&root, library_folder, ceiling.as_deref())?;
634	if settled == Settled::Nothing {
635		return Ok(false);
636	}
637	if json {
638		// As a tree that starts prints, with nothing committed.
639		let (written, taken_away) = pointer_json(&settled);
640		print_json(
641			&json!({
642				"tree": tree.id.to_string(),
643				"root": root.display().to_string(),
644				"revision": null,
645				"parts": 0,
646				"changes": [],
647				"repositories": [],
648				"secret": [],
649				"pointer": written,
650				"pointer_taken_away": taken_away,
651			}),
652			output,
653		)?;
654		return Ok(true);
655	}
656	let name = library
657		.name(space, tree.id)?
658		.unwrap_or_else(|| short(tree.id));
659	if matches!(settled, Settled::Written(_)) {
660		writeln!(
661			output,
662			"Wrote .nib again into {}, the tree {name}'s folder, {TELLS}",
663			root.display()
664		)?;
665	} else {
666		writeln!(
667			output,
668			"Took away .nib from {}, the tree {name}'s folder, {NEEDLESS}",
669			root.display()
670		)?;
671	}
672	Ok(true)
673}
674
675/// What the `.nib` file in the folder of a tree outside the library's folder is for.
676const TELLS: &str = "which tells nib there which library to use";
677
678/// Why a tree's folder inside the library's folder keeps no `.nib` file.
679const NEEDLESS: &str = "where nib finds the library without it";
680
681/// Settles the `.nib` file of the tree whose folder on this device is `root`, as commands
682/// there need it to find the library in `library_folder` ([`pointer::settle`]).
683fn settle_pointer<E: Environment>(
684	root: &Path,
685	library_folder: &Path,
686	environment: &E,
687) -> Result<Settled, CliError> {
688	let ceiling = environment.ceiling();
689	Ok(pointer::settle(root, library_folder, ceiling.as_deref())?)
690}
691
692/// The `.nib` file written, and the one taken away, for programs.
693fn pointer_json(settled: &Settled) -> (Option<String>, Option<String>) {
694	match settled {
695		Settled::Written(file) => (Some(file.display().to_string()), None),
696		Settled::TakenAway(file) => (None, Some(file.display().to_string())),
697		Settled::Nothing => (None, None),
698	}
699}
700
701/// Prints what it did with the `.nib` file of a tree's folder.
702fn pointer_text(settled: &Settled, output: &mut dyn Write) -> Result<(), CliError> {
703	match settled {
704		Settled::Written(_) => writeln!(output, "Wrote .nib into the tree's folder, {TELLS}")?,
705		Settled::TakenAway(_) => {
706			writeln!(output, "Took away .nib from the tree's folder, {NEEDLESS}")?;
707		}
708		Settled::Nothing => {}
709	}
710	Ok(())
711}
712
713/// Whether the current folder is in a tree's folder on this device, of the space chosen, or
714/// else of any space, which it chooses.
715pub(crate) fn in_tree_here<E: Environment>(
716	library: &mut Library,
717	environment: &E,
718) -> Result<bool, CliError> {
719	// A current folder that is gone, as when --library names the library, is in no tree.
720	let Ok(here) = current_dir(environment) else {
721		return Ok(false);
722	};
723	choose_tree_space(library, None, environment)?;
724	Ok(library
725		.tree_at(library.default_space(), &here)?
726		.is_some_and(|tree| tree.root.is_some()))
727}
728
729/// Runs `nib status` in a tree's folder: what changed in its copy here, and in the tree
730/// elsewhere.
731pub(crate) fn status_command<E: Environment>(
732	library: &mut Library,
733	json: bool,
734	environment: &E,
735	output: &mut dyn Write,
736) -> Result<(), CliError> {
737	let (tree, root) = tree_here(library, environment)?;
738	let status = library.tree_status(library.default_space(), tree.id)?;
739	let repositories = repositories_here(library, (tree.id, &root), &status, environment)?;
740	status_output((&status, &repositories), json, output)
741}
742
743/// Runs what `nib update` does, as `nib pull` does once it synced.
744pub(crate) fn update_here<E: Environment>(
745	library: &mut Library,
746	(partial, clone, no_clone): (bool, bool, bool),
747	json: bool,
748	(environment, timings): (&mut E, &mut Timings),
749	output: &mut dyn Write,
750) -> Result<(), CliError> {
751	choose_tree_space(library, None, environment)?;
752	let update = (partial, clone_choice(clone, no_clone));
753	update_command(library, update, json, (environment, timings), output)
754}
755
756/// The tree that a command names, if it names one.
757fn named_tree(command: &TreeCommand) -> Option<&str> {
758	match command {
759		TreeCommand::Clone { tree, .. } => Some(tree.as_str()),
760		TreeCommand::Log { tree, .. }
761		| TreeCommand::Diff { tree, .. }
762		| TreeCommand::Blame { tree, .. } => tree.as_deref(),
763		_ => None,
764	}
765}
766
767/// Runs `nib rm`: deletes the copies of the tree's files at the paths given, for the next
768/// commit to record.
769fn rm_command<E: Environment>(
770	library: &Library,
771	(paths, force): (&[PathBuf], bool),
772	json: bool,
773	environment: &E,
774	output: &mut dyn Write,
775) -> Result<(), CliError> {
776	let (tree, root) = tree_here(library, environment)?;
777	let mut in_tree = Vec::with_capacity(paths.len());
778	for path in paths {
779		in_tree.push(nibkeep_node::tree_path_at(
780			&root,
781			&absolute(path, environment)?,
782		)?);
783	}
784	let removed = library.remove_in_tree(library.default_space(), tree.id, &in_tree, force)?;
785	let skipped = removed
786		.skipped
787		.iter()
788		.map(|(path, why)| json!({ "path": path, "why": why }));
789	if json {
790		return print_json(
791			&json!({
792				"removed": removed.removed,
793				"skipped": skipped.collect::<Vec<_>>(),
794			}),
795			output,
796		);
797	}
798	for path in &removed.removed {
799		writeln!(output, "removed   {}", shown(path))?;
800	}
801	for (path, why) in &removed.skipped {
802		writeln!(output, "skipped   {}: {}", shown(path), shown(why))?;
803	}
804	writeln!(output, "Nothing is recorded: nib commit records it.")?;
805	Ok(())
806}
807
808/// Runs `nib commit`: records what changed in the tree's copy here, or at the paths
809/// given; where a secret file's change needs the secrets, asks for their passphrase, or sets
810/// them up, and commits again; then asks whether to purge the old versions of the files it
811/// made secret.
812fn commit_command<E: Environment>(
813	library: &mut Library,
814	command: &TreeCommand,
815	json: bool,
816	(environment, timings): (&mut E, &mut Timings),
817	output: &mut dyn Write,
818) -> Result<(), CliError> {
819	let TreeCommand::Commit {
820		paths,
821		message,
822		force,
823		secret,
824		ordinary,
825		leave_secrets,
826		..
827	} = command
828	else {
829		return Ok(());
830	};
831	let (tree, root) = tree_here(library, environment)?;
832	let in_tree = |paths: &[PathBuf], environment: &E| -> Result<Vec<String>, CliError> {
833		let mut in_tree = Vec::with_capacity(paths.len());
834		for path in paths {
835			let path = absolute(path, environment)?;
836			in_tree.push(nibkeep_node::tree_path_at(&root, &path)?);
837		}
838		Ok(in_tree)
839	};
840	let paths_in_tree = in_tree(paths, environment)?;
841	let secret = in_tree(secret, environment)?;
842	let ordinary = in_tree(ordinary, environment)?;
843	let space = library.default_space();
844	// What Git says of the repositories that the commit finds, for it to record.
845	let git = Git::from_template(&environment.git());
846	let read = |found: &[String]| git.describe(&root, found);
847	let mut commit = Commit::new(message.as_deref())
848		.with_paths(paths_in_tree)
849		.with_repositories_read_by(&read)
850		.with_secret(secret)
851		.with_ordinary(ordinary);
852	if *force {
853		commit = commit.with_force();
854	}
855	if *leave_secrets {
856		commit = commit.leaving_secrets();
857	}
858	let now = environment.now();
859	let committed = match library.commit_tree(space, tree.id, &commit, now, environment.rng()) {
860		Err(NodeError::SecretsNeeded(paths)) => {
861			let refused = NodeError::SecretsNeeded(paths);
862			secrets_for(library, (environment, timings), refused)?;
863			let now = environment.now();
864			library.commit_tree(space, tree.id, &commit, now, environment.rng())?
865		}
866		committed => committed?,
867	};
868	let purged = purge_made_secret(library, &committed, json, environment)?;
869	committed_output((&committed, &purged), json, output)
870}
871
872/// Runs `nib update`: brings the copy here to the tree, the secrets unlocked if a
873/// person is there to type their passphrase, and writes what it held back once the person
874/// agrees; then clones the Git repositories the copy lacks.
875fn update_command<E: Environment>(
876	library: &mut Library,
877	(partial, cloning): (bool, Option<bool>),
878	json: bool,
879	(environment, timings): (&mut E, &mut Timings),
880	output: &mut dyn Write,
881) -> Result<(), CliError> {
882	let (tree, _) = tree_here(library, environment)?;
883	secrets_if_asked(library, tree.id, (environment, timings))?;
884	let space = library.default_space();
885	let mut updated = library.update_tree(space, tree.id, partial)?;
886	if !updated.held.is_empty() && !json {
887		let question = format!(
888			"Changes from other devices that could expose secrets: {}. Write them? [y/N] ",
889			updated.held.join(", ")
890		);
891		let agreed = environment
892			.ask(&question)?
893			.is_some_and(|answer| matches!(answer.trim().to_lowercase().as_str(), "y" | "yes"));
894		if agreed {
895			let then = library.update_tree_agreeing(space, tree.id, partial)?;
896			merge_updates(&mut updated, then);
897		}
898	}
899	let clones = clone_step(library, tree.id, cloning, json, environment)?;
900	updated_output((&updated, &clones), json, output)
901}
902
903/// Unlocks the secrets for a command that needs them, asking for their passphrase, or sets
904/// them up with a passphrase of their own where the library has none; where nobody can type
905/// one, as for a script or an AI agent, fails as `refused` says.
906fn secrets_for<E: Environment>(
907	library: &mut Library,
908	(environment, timings): (&mut E, &mut Timings),
909	refused: NodeError,
910) -> Result<(), CliError> {
911	match crate::unlock_secrets(library, true, environment, timings) {
912		Ok(()) => Ok(()),
913		Err(CliError::Io(_)) => Err(refused.into()),
914		Err(error) => Err(error),
915	}
916}
917
918/// Unlocks the secrets, if a person is there to type their passphrase, before a command
919/// writes a tree that holds secret files: without them, it writes the rest.
920fn secrets_if_asked<E: Environment>(
921	library: &mut Library,
922	tree: EntityId,
923	(environment, timings): (&mut E, &mut Timings),
924) -> Result<(), CliError> {
925	let space = library.default_space();
926	if !environment.can_ask()
927		|| library.secrets_unlocked(space)
928		|| library.secrets_protection()?.is_none()
929		|| library.tree_secrets(space, tree)?.secret.is_empty()
930	{
931		return Ok(());
932	}
933	crate::unlock_secrets(library, false, environment, timings)
934}
935
936/// Asks, for each ordinary file that a commit made secret, whether to purge its old
937/// versions everywhere, for good: their contents that no other file holds. Without a
938/// person to ask, nothing is purged. Returns how many contents were purged.
939fn purge_made_secret<E: Environment>(
940	library: &mut Library,
941	committed: &Committed,
942	json: bool,
943	environment: &mut E,
944) -> Result<usize, CliError> {
945	let space = library.default_space();
946	let mut purged = 0;
947	for &file in &committed.made_secret {
948		let made = library.would_purge_made_secret(space, file)?;
949		if made.purged.is_empty() || json {
950			continue;
951		}
952		let name = library.name(space, file)?.unwrap_or_else(|| short(file));
953		let kept = if made.kept.is_empty() {
954			String::new()
955		} else {
956			format!(
957				"; {} that other files hold stay",
958				count(made.kept.len(), "content", "contents")
959			)
960		};
961		let question = format!(
962			"The old versions of {name} hold {} that the secrets did not protect{kept}. Purge them on every device, for good? [y/N] ",
963			count(made.purged.len(), "content", "contents"),
964		);
965		let agreed = environment
966			.ask(&question)?
967			.is_some_and(|answer| matches!(answer.trim().to_lowercase().as_str(), "y" | "yes"));
968		if agreed {
969			let now = environment.now();
970			purged += library
971				.purge_made_secret(space, file, now, environment.rng())?
972				.purged
973				.len();
974		}
975	}
976	Ok(purged)
977}
978
979/// Chooses the space of the tree that a command works on, where --space chose none: the
980/// space of the tree it names, or else of the tree whose folder the current folder is in. A
981/// tree is started in the space chosen, or else in the personal space.
982fn choose_tree_space<E: Environment>(
983	library: &mut Library,
984	named: Option<&str>,
985	environment: &E,
986) -> Result<(), CliError> {
987	if library.chosen_space().is_some() {
988		return Ok(());
989	}
990	let space = if let Some(named) = named {
991		Some(library.locate(named)?.0)
992	} else {
993		let here = current_dir(environment)?;
994		let mut found = None;
995		for space in library.spaces() {
996			if library.tree_at(space, &here)?.is_some() {
997				found = Some(space);
998				break;
999			}
1000		}
1001		found
1002	};
1003	if space.is_some() {
1004		library.choose_space(space)?;
1005	}
1006	Ok(())
1007}
1008
1009/// Runs `nib commit --pin` or `--unpin`: pins the repository in a folder at the commit it has
1010/// checked out, or takes its pin away.
1011fn pin_command<E: Environment>(
1012	library: &mut Library,
1013	(path, unpin): (&Path, bool),
1014	json: bool,
1015	environment: &mut E,
1016	output: &mut dyn Write,
1017) -> Result<(), CliError> {
1018	let (tree, root) = tree_here(library, environment)?;
1019	let folder = absolute(path, environment)?;
1020	let path = nibkeep_node::tree_path_at(&root, &folder)?;
1021	let commit = if unpin {
1022		None
1023	} else {
1024		Some(
1025			Git::from_template(&environment.git())
1026				.head(&folder)
1027				.ok_or(CliError::NoGitCommit(folder))?,
1028		)
1029	};
1030	let now = environment.now();
1031	let space = library.default_space();
1032	let pinned = library.pin_repository(
1033		space,
1034		tree.id,
1035		&path,
1036		commit.as_deref(),
1037		now,
1038		environment.rng(),
1039	)?;
1040	if json {
1041		return committed_output((&pinned, &0), json, output);
1042	}
1043	let revision = pinned.revision.map_or_else(
1044		|| ", as it was".to_owned(),
1045		|revision| format!(", as revision {}", short(revision)),
1046	);
1047	match commit {
1048		Some(commit) => writeln!(output, "Pinned {path} at {}{revision}", &commit[..12])?,
1049		None => writeln!(output, "Unpinned {path}{revision}")?,
1050	}
1051	Ok(())
1052}
1053
1054/// Runs the commands that read a tree's history: log, diff and blame; outside every tree's
1055/// folder, with the tree named.
1056fn read_command<E: Environment>(
1057	library: &mut Library,
1058	command: &TreeCommand,
1059	json: bool,
1060	(environment, timings): (&mut E, &mut Timings),
1061	output: &mut dyn Write,
1062) -> Result<(), CliError> {
1063	match command {
1064		TreeCommand::Log { path, tree } => {
1065			let (tree, root) = named_or_here(library, tree.as_deref(), environment)?;
1066			let path = match path {
1067				Some(path) => Some(path_given(path, root.as_deref(), environment)?),
1068				None => None,
1069			};
1070			let log = library.tree_log(library.default_space(), tree, path.as_deref())?;
1071			log_output(&log, json, &environment.time_zone(), output)
1072		}
1073		TreeCommand::Diff {
1074			from,
1075			to,
1076			since,
1077			until,
1078			tree,
1079			secrets,
1080		} => {
1081			let (tree, _) = named_or_here(library, tree.as_deref(), environment)?;
1082			let space = library.default_space();
1083			if *secrets && !library.secrets_unlocked(space) {
1084				secrets_for(library, (environment, timings), NodeError::SecretsLocked)?;
1085			}
1086			let (from, to) = (
1087				from.as_ref().or(since.as_ref()),
1088				to.as_ref().or(until.as_ref()),
1089			);
1090			let between = match (from, to) {
1091				(None, _) => None,
1092				(Some(from), to) => {
1093					let from = TreePoint::Revision(library.find_entity(space, from)?);
1094					let to = match to {
1095						Some(to) => TreePoint::Revision(library.find_entity(space, to)?),
1096						None => TreePoint::Now,
1097					};
1098					Some((from, to))
1099				}
1100			};
1101			let diffs = library.tree_diff_with(space, tree, between, *secrets)?;
1102			if json {
1103				return print_json(&diff_json(&diffs), output);
1104			}
1105			diff_text(&diffs, output)
1106		}
1107		TreeCommand::Blame {
1108			path,
1109			tree,
1110			secrets,
1111		} => {
1112			let (tree, root) = named_or_here(library, tree.as_deref(), environment)?;
1113			let path = path_given(path, root.as_deref(), environment)?;
1114			let space = library.default_space();
1115			if *secrets && !library.secrets_unlocked(space) {
1116				secrets_for(library, (environment, timings), NodeError::SecretsLocked)?;
1117			}
1118			let blame = library.tree_blame_with(space, tree, &path, *secrets)?;
1119			blame_output(&blame, json, &environment.time_zone(), output)
1120		}
1121		_ => Ok(()),
1122	}
1123}
1124
1125/// Runs the commands that write a tree, or into its copy: update, restore, revert and
1126/// clone, of the library in `library_folder`.
1127fn back_command<E: Environment>(
1128	library: &mut Library,
1129	(library_folder, command): (&Path, &TreeCommand),
1130	json: bool,
1131	(environment, timings): (&mut E, &mut Timings),
1132	output: &mut dyn Write,
1133) -> Result<(), CliError> {
1134	match command {
1135		TreeCommand::Update {
1136			partial,
1137			clone,
1138			no_clone,
1139		} => {
1140			let update = (*partial, clone_choice(*clone, *no_clone));
1141			update_command(library, update, json, (environment, timings), output)
1142		}
1143		TreeCommand::Restore { path, at, as_of } => {
1144			let (tree, root) = tree_here(library, environment)?;
1145			secrets_if_asked(library, tree.id, (environment, timings))?;
1146			let path = nibkeep_node::tree_path_at(&root, &absolute(path, environment)?)?;
1147			let point = point_given(library, (at.as_deref(), *as_of), environment)?;
1148			let written =
1149				library.restore_in_tree(library.default_space(), tree.id, &path, point)?;
1150			written_output(&written, "restored ", json, output)?;
1151			if !json {
1152				writeln!(
1153					output,
1154					"Nothing is recorded: nib commit records what you keep."
1155				)?;
1156			}
1157			Ok(())
1158		}
1159		TreeCommand::Revert { revision } => {
1160			let (tree, _) = tree_here(library, environment)?;
1161			secrets_if_asked(library, tree.id, (environment, timings))?;
1162			let reverted = library
1163				.locate(revision)
1164				.and_then(|(space, found)| library.revert_in_tree(space, tree.id, found));
1165			match reverted {
1166				Ok(reverted) => reverted_output(&reverted, json, output),
1167				// A path, as the revert of Mercurial, Subversion and Fossil takes, is for
1168				// restore.
1169				Err(_)
1170					if fs::symlink_metadata(absolute(Path::new(revision), environment)?)
1171						.is_ok() =>
1172				{
1173					Err(CliError::RevertTakesRevision(revision.clone()))
1174				}
1175				Err(error) => Err(error.into()),
1176			}
1177		}
1178		clone @ TreeCommand::Clone { .. } => clone_command(
1179			library,
1180			(library_folder, clone),
1181			json,
1182			(environment, timings),
1183			output,
1184		),
1185		_ => Ok(()),
1186	}
1187}
1188
1189/// Runs `nib clone`: writes a tree into a folder, as this device's copy of it, or as a
1190/// picture of the past. A copy names the library in `library_folder`, where commands in its
1191/// folder would not find it otherwise.
1192fn clone_command<E: Environment>(
1193	library: &mut Library,
1194	(library_folder, command): (&Path, &TreeCommand),
1195	json: bool,
1196	(environment, timings): (&mut E, &mut Timings),
1197	output: &mut dyn Write,
1198) -> Result<(), CliError> {
1199	let TreeCommand::Clone {
1200		tree,
1201		folder,
1202		at,
1203		as_of,
1204		clone,
1205		no_clone,
1206	} = command
1207	else {
1208		return Ok(());
1209	};
1210	let (space, tree) = library.locate(tree)?;
1211	secrets_if_asked(library, tree, (environment, timings))?;
1212	let folder = match folder {
1213		Some(folder) => absolute(folder, environment)?,
1214		None => current_dir(environment)?.join(folder_named_after(library, space, tree)?),
1215	};
1216	let point = point_given(library, (at.as_deref(), *as_of), environment)?;
1217	let now = environment.now();
1218	let written = library.write_tree(space, tree, &folder, point, now, environment.rng())?;
1219	// A picture of the past clones nothing, and is no tree's folder; this device's copy
1220	// clones what the person agrees.
1221	let (clones, settled) = if point == TreePoint::Now {
1222		let root = nibkeep_node::resolved_path(&folder)?;
1223		let settled = settle_pointer(&root, library_folder, environment)?;
1224		let clones = clone_step(
1225			library,
1226			tree,
1227			clone_choice(*clone, *no_clone),
1228			json,
1229			environment,
1230		)?;
1231		(clones, settled)
1232	} else {
1233		(Vec::new(), Settled::Nothing)
1234	};
1235	if json {
1236		let (pointer, taken_away) = pointer_json(&settled);
1237		return print_json(
1238			&json!({
1239				"written": written.written,
1240				"skipped": written
1241					.skipped
1242					.iter()
1243					.map(|(path, why)| json!({ "path": path, "why": why }))
1244					.collect::<Vec<_>>(),
1245				"sealed": written.sealed,
1246				"repositories": clones_json(&clones),
1247				"pointer": pointer,
1248				"pointer_taken_away": taken_away,
1249			}),
1250			output,
1251		);
1252	}
1253	let copy = if point == TreePoint::Now {
1254		", which is this device's copy of it"
1255	} else {
1256		", a picture of the past, which is no copy"
1257	};
1258	writeln!(
1259		output,
1260		"Wrote {} into {}{copy}",
1261		count(written.written.len(), "file", "files"),
1262		folder.display()
1263	)?;
1264	for (path, why) in &written.skipped {
1265		writeln!(output, "skipped   {path}: {why}")?;
1266	}
1267	sealed_text(&written.sealed, output)?;
1268	clones_text(&clones, output)?;
1269	pointer_text(&settled, output)
1270}
1271
1272/// The name of the folder that `nib clone` writes a tree into when none is given: the
1273/// tree's name, if it is a name a folder can have, or else the start of its ID.
1274fn folder_named_after(
1275	library: &Library,
1276	space: nibkeep_base::SpaceId,
1277	tree: EntityId,
1278) -> Result<String, CliError> {
1279	let named = library.name(space, tree)?.filter(|name| {
1280		!name.is_empty()
1281			&& name != "."
1282			&& name != ".."
1283			&& !name.contains(['/', '\\'])
1284			&& !name.contains(char::is_control)
1285	});
1286	Ok(named.unwrap_or_else(|| short(tree)))
1287}
1288
1289/// Takes into what a first update did what a second one did once the person agreed to
1290/// what the first held back.
1291fn merge_updates(first: &mut Updated, then: Updated) {
1292	first.written.extend(then.written);
1293	first.moved.extend(then.moved);
1294	first.deleted.extend(then.deleted);
1295	first.merged.extend(then.merged);
1296	first.conflicts.extend(then.conflicts);
1297	first.kept = then.kept;
1298	first.contested = then.contested;
1299	first.skipped = then.skipped;
1300	first.waiting = then.waiting;
1301	first.held = then.held;
1302	first.sealed = then.sealed;
1303	for list in [
1304		&mut first.written,
1305		&mut first.deleted,
1306		&mut first.merged,
1307		&mut first.conflicts,
1308	] {
1309		list.sort();
1310		list.dedup();
1311	}
1312	first.moved.sort();
1313	first.moved.dedup();
1314}
1315
1316/// Prints the secret files not written, as this device cannot read them.
1317fn sealed_text(sealed: &[String], output: &mut dyn Write) -> Result<(), CliError> {
1318	for path in sealed {
1319		writeln!(
1320			output,
1321			"sealed    {}: a secret file, not written here, as the secrets are locked or not on this device",
1322			shown(path)
1323		)?;
1324	}
1325	Ok(())
1326}
1327
1328/// Prints a tree's secret files, and its ordinary files that look secret.
1329fn secrets_output(
1330	listed: &TreeSecrets,
1331	json: bool,
1332	output: &mut dyn Write,
1333) -> Result<(), CliError> {
1334	if json {
1335		return print_json(
1336			&json!({
1337				"secret": listed.secret,
1338				"sealed": listed.sealed,
1339				"looking_secret": listed.looking_secret,
1340			}),
1341			output,
1342		);
1343	}
1344	if listed.secret.is_empty() && listed.looking_secret.is_empty() {
1345		writeln!(output, "The tree has no secret files")?;
1346		return Ok(());
1347	}
1348	for path in &listed.secret {
1349		if listed.sealed.contains(path) {
1350			writeln!(
1351				output,
1352				"secret    {}, not written here, as the secrets are locked or not on this device",
1353				shown(path)
1354			)?;
1355		} else {
1356			writeln!(output, "secret    {}", shown(path))?;
1357		}
1358	}
1359	for path in &listed.looking_secret {
1360		writeln!(
1361			output,
1362			"ordinary  {}, which looks secret: nib commit --secret {} makes it a secret file",
1363			shown(path),
1364			shown(path)
1365		)?;
1366	}
1367	Ok(())
1368}
1369
1370/// The tree named, by its name or ID, with its folder here if it has one; or else the tree
1371/// whose folder here holds the current folder.
1372fn named_or_here<E: Environment>(
1373	library: &Library,
1374	named: Option<&str>,
1375	environment: &E,
1376) -> Result<(EntityId, Option<PathBuf>), CliError> {
1377	if let Some(named) = named {
1378		let tree = library.find_entity(library.default_space(), named)?;
1379		Ok((tree, None))
1380	} else {
1381		let (tree, root) = tree_here(library, environment).map_err(|error| match error {
1382			CliError::NotInTree(here) => CliError::NoTreeHere(here),
1383			error => error,
1384		})?;
1385		Ok((tree.id, Some(root)))
1386	}
1387}
1388
1389/// A path given on the command line, as the tree names it: relative to the current folder
1390/// in the tree's folder here, or, for a tree named, as the tree names it.
1391fn path_given<E: Environment>(
1392	path: &Path,
1393	root: Option<&Path>,
1394	environment: &E,
1395) -> Result<String, CliError> {
1396	match root {
1397		Some(root) => Ok(nibkeep_node::tree_path_at(
1398			root,
1399			&absolute(path, environment)?,
1400		)?),
1401		None => Ok(path.to_string_lossy().replace('\\', "/")),
1402	}
1403}
1404
1405/// The point of a tree's history given on the command line: a revision, a moment, or now.
1406fn point_given<E: Environment>(
1407	library: &Library,
1408	(at, as_of): (Option<&str>, Option<crate::Moment>),
1409	environment: &E,
1410) -> Result<TreePoint, CliError> {
1411	if let Some(revision) = at {
1412		return Ok(TreePoint::Revision(
1413			library.find_entity(library.default_space(), revision)?,
1414		));
1415	}
1416	if let Some(moment) = as_of {
1417		let (millis, _) = moment.resolve(&environment.time_zone())?;
1418		return Ok(TreePoint::AsOf(millis.unwrap_or(0)));
1419	}
1420	Ok(TreePoint::Now)
1421}
1422
1423/// Starts a tree, as `nib init` in a library does: asks the person first, unless `yes`,
1424/// then starts the tree in `folder`, and names the library in `library_folder` there, where
1425/// commands in the tree's folder would not find it otherwise.
1426fn start_command<E: Environment>(
1427	library: &mut Library,
1428	(library_folder, (folder, message, yes)): (&Path, (&Path, Option<&str>, bool)),
1429	json: bool,
1430	(environment, timings): (&mut E, &mut Timings),
1431	output: &mut dyn Write,
1432) -> Result<(), CliError> {
1433	let space = library.default_space();
1434	let preview = library.would_start_tree(space, folder)?;
1435	// Nothing starts where the file that names the library could not go.
1436	let ceiling = environment.ceiling();
1437	if let Ok(root) = nibkeep_node::resolved_path(folder)
1438		&& pointer::needed(&root, library_folder, ceiling.as_deref())
1439	{
1440		pointer::check_place(&root)?;
1441	}
1442	// With --json, nib runs for a program, which is not asked.
1443	if !yes {
1444		let repositories = if preview.repositories.is_empty() {
1445			String::new()
1446		} else {
1447			format!(
1448				", and {} recorded by their remotes",
1449				count(
1450					preview.repositories.len(),
1451					"Git repository",
1452					"Git repositories"
1453				)
1454			)
1455		};
1456		let question = format!(
1457			"{} in {} ({}) become the tree's copies{repositories}: a purge of a file's content deletes its copy where it was not edited. Start the tree? [y/N] ",
1458			count(preview.files, "file", "files"),
1459			folder.display(),
1460			bytes(preview.bytes),
1461		);
1462		let answer = if json {
1463			None
1464		} else {
1465			environment.ask(&question)?
1466		};
1467		let agreed = answer
1468			.is_some_and(|answer| matches!(answer.trim().to_lowercase().as_str(), "y" | "yes"));
1469		if !agreed {
1470			return Err(CliError::UnconfirmedStart);
1471		}
1472	}
1473	let described = Git::from_template(&environment.git()).describe(folder, &preview.repositories);
1474	let commit = Commit::new(message).with_repositories(&described);
1475	let now = environment.now();
1476	let started = match library.start_tree_with(space, folder, &commit, now, environment.rng()) {
1477		Err(NodeError::SecretsNeeded(paths)) => {
1478			secrets_for(
1479				library,
1480				(environment, timings),
1481				NodeError::SecretsNeeded(paths),
1482			)?;
1483			let now = environment.now();
1484			library.start_tree_with(space, folder, &commit, now, environment.rng())?
1485		}
1486		started => started?,
1487	};
1488	let settled = settle_pointer(&started.root, library_folder, environment)?;
1489	if json {
1490		let (pointer, taken_away) = pointer_json(&settled);
1491		return print_json(
1492			&json!({
1493				"tree": started.tree.to_string(),
1494				"root": started.root.display().to_string(),
1495				"revision": revision_json(&started.committed),
1496				"parts": started.committed.parts,
1497				"changes": changes_json(&started.committed.changes),
1498				"repositories": changes_json(&started.committed.repositories),
1499				"secret": started.committed.secret,
1500				"pointer": pointer,
1501				"pointer_taken_away": taken_away,
1502			}),
1503			output,
1504		);
1505	}
1506	let name = library
1507		.name(space, started.tree)?
1508		.unwrap_or_else(|| short(started.tree));
1509	let as_revision = started
1510		.committed
1511		.revision
1512		.map_or_else(String::new, |revision| {
1513			format!("as revision {}", short(revision))
1514		});
1515	writeln!(
1516		output,
1517		"Started the tree {name} in {}: {}, committed {as_revision}",
1518		started.root.display(),
1519		count(started.committed.changes.len(), "file", "files"),
1520	)?;
1521	secret_text(&started.committed, output)?;
1522	repositories_text(&started.committed.repositories, output)?;
1523	pointer_text(&settled, output)
1524}
1525
1526/// Prints what a commit did of secret files: those it sealed for the secrets, those it
1527/// left, and the ordinary files that hold a secret file's content.
1528fn secret_text(committed: &Committed, output: &mut dyn Write) -> Result<(), CliError> {
1529	for path in &committed.secret {
1530		writeln!(output, "secret    {}, sealed for the secrets", shown(path))?;
1531	}
1532	for path in &committed.left {
1533		writeln!(
1534			output,
1535			"left      {}: a secret file's change, which waits for the secrets",
1536			shown(path)
1537		)?;
1538	}
1539	for path in &committed.unprotected {
1540		writeln!(
1541			output,
1542			"plain     {}: holds a secret file's content, which the secrets do not protect here",
1543			shown(path)
1544		)?;
1545	}
1546	Ok(())
1547}
1548
1549/// The tree whose folder on this device holds the current folder, and that folder.
1550fn tree_here<E: Environment>(
1551	library: &Library,
1552	environment: &E,
1553) -> Result<(Tree, PathBuf), CliError> {
1554	let here = current_dir(environment)?;
1555	let tree = library
1556		.tree_at(library.default_space(), &here)?
1557		.ok_or_else(|| CliError::NotInTree(here.clone()))?;
1558	let root = tree.root.clone().ok_or(CliError::NotInTree(here))?;
1559	Ok((tree, root))
1560}
1561
1562/// Prints what changed in a tree's copy, and in the tree elsewhere.
1563fn status_output(
1564	(status, repositories): (&TreeStatus, &Repositories),
1565	json: bool,
1566	output: &mut dyn Write,
1567) -> Result<(), CliError> {
1568	if json {
1569		let skipped: Vec<serde_json::Value> = status
1570			.skipped
1571			.iter()
1572			.map(|(path, why)| json!({ "path": path, "why": why }))
1573			.collect();
1574		let cut_short: Vec<serde_json::Value> = status
1575			.cut_short
1576			.iter()
1577			.map(|cut| {
1578				json!({
1579					"revision": cut.revision.to_string(),
1580					"parts": cut.parts,
1581					"made": cut.made,
1582				})
1583			})
1584			.collect();
1585		return print_json(
1586			&json!({
1587				"tree": status.tree.to_string(),
1588				"root": status.root.display().to_string(),
1589				"changes": changes_json(&status.changes),
1590				"behind": status.behind,
1591				"competing": status.competing,
1592				"skipped": skipped,
1593				"cut_short": cut_short,
1594				"secret": status.secret,
1595				"sealed": status.sealed,
1596				"read": status.read,
1597				"repositories": changes_json(&repositories.changes),
1598				"only_here": repositories
1599					.work
1600					.iter()
1601					.map(|(path, work)| json!({ "path": path, "work": work }))
1602					.collect::<Vec<_>>(),
1603			}),
1604			output,
1605		);
1606	}
1607	let nothing = status.changes.is_empty()
1608		&& status.behind.is_empty()
1609		&& status.competing.is_empty()
1610		&& status.skipped.is_empty()
1611		&& status.cut_short.is_empty()
1612		&& status.sealed.is_empty()
1613		&& repositories.changes.is_empty()
1614		&& repositories.work.is_empty();
1615	if nothing {
1616		writeln!(output, "Nothing changed in the tree's copy here")?;
1617		return Ok(());
1618	}
1619	changes_text(&status.changes, output)?;
1620	for path in &status.secret {
1621		writeln!(
1622			output,
1623			"secret    {}, which a commit seals for the secrets",
1624			shown(path)
1625		)?;
1626	}
1627	sealed_text(&status.sealed, output)?;
1628	repositories_text(&repositories.changes, output)?;
1629	for (path, work) in &repositories.work {
1630		writeln!(output, "only here {}: {}", shown(path), work.join(", "))?;
1631	}
1632	for path in &status.behind {
1633		writeln!(
1634			output,
1635			"elsewhere {}, changed in the tree since this copy",
1636			shown(path)
1637		)?;
1638	}
1639	for path in &status.competing {
1640		writeln!(
1641			output,
1642			"competing {}, which devices changed apart",
1643			shown(path)
1644		)?;
1645	}
1646	for (path, why) in &status.skipped {
1647		writeln!(output, "skipped   {}: {}", shown(path), shown(why))?;
1648	}
1649	for cut in &status.cut_short {
1650		writeln!(
1651			output,
1652			"cut short revision {}: {} of {} parts; the next commit takes in the rest",
1653			short(cut.revision),
1654			cut.made,
1655			cut.parts
1656		)?;
1657	}
1658	Ok(())
1659}
1660
1661/// Prints what a commit recorded, and how many contents it purged of files it made secret.
1662fn committed_output(
1663	(committed, purged): (&Committed, &usize),
1664	json: bool,
1665	output: &mut dyn Write,
1666) -> Result<(), CliError> {
1667	if json {
1668		return print_json(
1669			&json!({
1670				"revision": revision_json(committed),
1671				"parts": committed.parts,
1672				"changes": changes_json(&committed.changes),
1673				"repositories": changes_json(&committed.repositories),
1674				"secret": committed.secret,
1675				"left": committed.left,
1676				"unprotected": committed.unprotected,
1677				"made_secret": committed
1678					.made_secret
1679					.iter()
1680					.map(ToString::to_string)
1681					.collect::<Vec<_>>(),
1682			}),
1683			output,
1684		);
1685	}
1686	let Some(revision) = committed.revision.map(short) else {
1687		writeln!(output, "Nothing to commit")?;
1688		return secret_text(committed, output);
1689	};
1690	// The repositories' changes count with the files', as both are listed below.
1691	let recorded = committed.changes.len() + committed.repositories.len();
1692	let changes = count(recorded, "change", "changes");
1693	writeln!(output, "Committed {changes} as revision {revision}")?;
1694	changes_text(&committed.changes, output)?;
1695	secret_text(committed, output)?;
1696	if *purged > 0 {
1697		writeln!(
1698			output,
1699			"Purged {} of the old versions of files made secret",
1700			count(*purged, "content", "contents")
1701		)?;
1702	} else if !committed.made_secret.is_empty() {
1703		writeln!(
1704			output,
1705			"The old versions of {} made secret stay readable on every device, as nothing purged them",
1706			count(committed.made_secret.len(), "file", "files")
1707		)?;
1708	}
1709	repositories_text(&committed.repositories, output)
1710}
1711
1712/// Prints changes, one a line, as a word and a path, ordered by what they are and then by
1713/// path: deletions first, then moves, new files, versions and executable bits.
1714fn changes_text(changes: &[TreeChange], output: &mut dyn Write) -> Result<(), CliError> {
1715	let mut ordered: Vec<&TreeChange> = changes.iter().collect();
1716	ordered.sort_by_key(|change| (rank(&change.change), change.path.as_str()));
1717	for change in ordered {
1718		let path = &shown(&change.path);
1719		match &change.change {
1720			Change::New => writeln!(output, "new       {path}")?,
1721			Change::Edited => writeln!(output, "edited    {path}")?,
1722			Change::Executable(true) => writeln!(output, "executable {path}")?,
1723			Change::Executable(false) => writeln!(output, "no longer executable {path}")?,
1724			Change::Deleted => writeln!(output, "deleted   {path}")?,
1725			Change::Moved { from } => writeln!(output, "moved     {path}, from {}", shown(from))?,
1726			Change::Unknown => writeln!(
1727				output,
1728				"edited    {path}, from a version this device does not know"
1729			)?,
1730		}
1731	}
1732	Ok(())
1733}
1734
1735/// The order changes are shown in.
1736fn rank(change: &Change) -> u8 {
1737	match change {
1738		Change::Deleted => 0,
1739		Change::Moved { .. } => 1,
1740		Change::New => 2,
1741		Change::Edited | Change::Unknown => 3,
1742		Change::Executable(_) => 4,
1743	}
1744}
1745
1746/// Changes in JSON.
1747fn changes_json(changes: &[TreeChange]) -> Vec<serde_json::Value> {
1748	changes
1749		.iter()
1750		.map(|change| {
1751			let (what, from, executable) = match &change.change {
1752				Change::New => ("new", None, None),
1753				Change::Edited => ("edited", None, None),
1754				Change::Executable(executable) => ("executable", None, Some(*executable)),
1755				Change::Deleted => ("deleted", None, None),
1756				Change::Moved { from } => ("moved", Some(from.as_str()), None),
1757				Change::Unknown => ("unknown", None, None),
1758			};
1759			let mut shown = json!({ "path": change.path, "change": what });
1760			if let Some(from) = from {
1761				shown["from"] = json!(from);
1762			}
1763			if let Some(executable) = executable {
1764				shown["executable"] = json!(executable);
1765			}
1766			shown
1767		})
1768		.collect()
1769}
1770
1771/// The revision of a commit in JSON, if it made one.
1772fn revision_json(committed: &Committed) -> Option<String> {
1773	committed.revision.map(|revision| revision.to_string())
1774}
1775
1776/// A number of bytes, as a person reads it.
1777fn bytes(bytes: u64) -> String {
1778	const UNITS: [&str; 4] = ["KB", "MB", "GB", "TB"];
1779	if bytes < 1_000 {
1780		return count(
1781			usize::try_from(bytes).unwrap_or(usize::MAX),
1782			"byte",
1783			"bytes",
1784		);
1785	}
1786	let mut value = u128::from(bytes);
1787	let mut unit = 0;
1788	while value >= 1_000_000 && unit < UNITS.len() - 1 {
1789		value /= 1_000;
1790		unit += 1;
1791	}
1792	// One decimal, from what is left in thousands.
1793	let tenths = value / 100;
1794	format!("{}.{} {}", tenths / 10, tenths % 10, UNITS[unit])
1795}
1796
1797/// Who made a change, for people: the user's name, and the AI agent through which they
1798/// made it, if one did.
1799fn who(author: Option<&nibkeep_node::Author>) -> String {
1800	let Some(author) = author else {
1801		return "unknown".to_owned();
1802	};
1803	let user = author
1804		.user
1805		.name
1806		.clone()
1807		.unwrap_or_else(|| "unknown".to_owned());
1808	match &author.ai_agent {
1809		Some(ai_agent) => format!("{user}, through {ai_agent}"),
1810		None => user,
1811	}
1812}
1813
1814/// Who made a change, in JSON.
1815fn author_json(author: Option<&nibkeep_node::Author>) -> serde_json::Value {
1816	author.map_or(serde_json::Value::Null, |author| {
1817		json!({
1818			"user": author.user.id.to_string(),
1819			"name": author.user.name,
1820			"replica": author.replica.to_string(),
1821			"ai_agent": author.ai_agent,
1822		})
1823	})
1824}
1825
1826/// A moment in JSON: milliseconds since 1970, in RFC 3339, in UTC.
1827fn moment_json(millis: u64) -> serde_json::Value {
1828	i64::try_from(millis)
1829		.ok()
1830		.and_then(|millis| jiff::Timestamp::from_millisecond(millis).ok())
1831		.map_or_else(|| json!(millis), |timestamp| json!(timestamp.to_string()))
1832}
1833
1834/// Prints a tree's log: each change, newest first, with its revision, time, author and
1835/// message, and what it did.
1836fn log_output(
1837	log: &[TreeLogEntry],
1838	json: bool,
1839	zone: &jiff::tz::TimeZone,
1840	output: &mut dyn Write,
1841) -> Result<(), CliError> {
1842	if json {
1843		let entries: Vec<serde_json::Value> = log
1844			.iter()
1845			.map(|entry| {
1846				json!({
1847					"change": entry.change,
1848					"at": moment_json(entry.at),
1849					"author": author_json(entry.author.as_ref()),
1850					"revision": entry.revision.map(|revision| revision.to_string()),
1851					"message": entry.message,
1852					"arrived": entry.part.map(|(arrived, parts)| json!({ "parts": arrived, "of": parts })),
1853					"changes": changes_json(&entry.changes),
1854				})
1855			})
1856			.collect();
1857		return print_json(&json!(entries), output);
1858	}
1859	for (number, entry) in log.iter().enumerate() {
1860		if number > 0 {
1861			writeln!(output)?;
1862		}
1863		let what = match entry.revision {
1864			Some(revision) => format!("revision {}", short(revision)),
1865			None => format!("change {}", entry.change.get(..8).unwrap_or(&entry.change)),
1866		};
1867		let part = entry.part.map_or_else(String::new, |(arrived, parts)| {
1868			format!(", {arrived} of {parts} parts so far")
1869		});
1870		writeln!(
1871			output,
1872			"{what}  {}  {}{part}",
1873			moment_text(entry.at, zone),
1874			who(entry.author.as_ref())
1875		)?;
1876		if let Some(message) = &entry.message {
1877			for line in message.lines() {
1878				writeln!(output, "    {line}")?;
1879			}
1880		}
1881		let mut changes = Vec::new();
1882		changes_text(&entry.changes, &mut changes)?;
1883		for line in String::from_utf8_lossy(&changes).lines() {
1884			writeln!(output, "  {line}")?;
1885		}
1886	}
1887	Ok(())
1888}
1889
1890/// A diff, for --json.
1891pub(crate) fn diff_json(diffs: &[FileDiff]) -> serde_json::Value {
1892	let shown: Vec<serde_json::Value> = diffs
1893		.iter()
1894		.map(|diff| {
1895			let mut shown = changes_json(&[TreeChange {
1896				path: diff.path.clone(),
1897				change: diff.change.clone(),
1898			}])
1899			.remove(0);
1900			shown["patch"] = json!(diff.patch);
1901			shown["binary"] = json!(diff.binary);
1902			shown["secret"] = json!(diff.secret);
1903			shown
1904		})
1905		.collect();
1906	json!(shown)
1907}
1908
1909/// Prints a diff: each file's change, and the lines of text that changed.
1910pub(crate) fn diff_text(diffs: &[FileDiff], output: &mut dyn Write) -> Result<(), CliError> {
1911	if diffs.is_empty() {
1912		writeln!(output, "No differences")?;
1913		return Ok(());
1914	}
1915	for diff in diffs {
1916		changes_text(
1917			&[TreeChange {
1918				path: diff.path.clone(),
1919				change: diff.change.clone(),
1920			}],
1921			output,
1922		)?;
1923		if let Some(patch) = &diff.patch {
1924			write!(output, "{patch}")?;
1925		} else if diff.secret {
1926			writeln!(
1927				output,
1928				"  a secret file; nib diff --secrets shows its lines"
1929			)?;
1930		} else if diff.binary {
1931			writeln!(output, "  versions differ; not text")?;
1932		}
1933	}
1934	Ok(())
1935}
1936
1937/// Prints blame: each line with the revision, author and time that last changed it.
1938fn blame_output(
1939	blame: &[BlameLine],
1940	json: bool,
1941	zone: &jiff::tz::TimeZone,
1942	output: &mut dyn Write,
1943) -> Result<(), CliError> {
1944	if json {
1945		let lines: Vec<serde_json::Value> = blame
1946			.iter()
1947			.map(|line| {
1948				json!({
1949					"text": line.text,
1950					"revision": line.revision.map(|revision| revision.to_string()),
1951					"author": author_json(line.author.as_ref()),
1952					"at": moment_json(line.at),
1953				})
1954			})
1955			.collect();
1956		return print_json(&json!(lines), output);
1957	}
1958	let names: Vec<String> = blame.iter().map(|line| who(line.author.as_ref())).collect();
1959	let width = names
1960		.iter()
1961		.map(|name| name.chars().count())
1962		.max()
1963		.unwrap_or(0);
1964	for (line, name) in blame.iter().zip(&names) {
1965		let revision = line.revision.map_or_else(|| "--------".to_owned(), short);
1966		writeln!(
1967			output,
1968			"{revision}  {name:<width$}  {}  {}",
1969			moment_text(line.at, zone),
1970			line.text
1971		)?;
1972	}
1973	Ok(())
1974}
1975
1976/// Prints what writing wrote, each path after `word`, and what it skipped, with why.
1977fn written_output(
1978	written: &Written,
1979	word: &str,
1980	json: bool,
1981	output: &mut dyn Write,
1982) -> Result<(), CliError> {
1983	if json {
1984		let skipped: Vec<serde_json::Value> = written
1985			.skipped
1986			.iter()
1987			.map(|(path, why)| json!({ "path": path, "why": why }))
1988			.collect();
1989		let aside: Vec<serde_json::Value> = written
1990			.aside
1991			.iter()
1992			.map(|(path, to)| json!({ "path": path, "to": to }))
1993			.collect();
1994		return print_json(
1995			&json!({
1996				"written": written.written,
1997				"skipped": skipped,
1998				"sealed": written.sealed,
1999				"aside": aside,
2000			}),
2001			output,
2002		);
2003	}
2004	for path in &written.written {
2005		match written.aside.iter().find(|(at, _)| at == path) {
2006			Some((_, beside)) => writeln!(output, "{word} {path}, your edits kept as {beside}")?,
2007			None => writeln!(output, "{word} {path}")?,
2008		}
2009	}
2010	for (path, why) in &written.skipped {
2011		writeln!(output, "skipped   {path}: {why}")?;
2012	}
2013	sealed_text(&written.sealed, output)
2014}
2015
2016/// Prints what undoing a revision wrote.
2017fn reverted_output(
2018	reverted: &Reverted,
2019	json: bool,
2020	output: &mut dyn Write,
2021) -> Result<(), CliError> {
2022	if json {
2023		let skipped: Vec<serde_json::Value> = reverted
2024			.skipped
2025			.iter()
2026			.map(|(path, why)| json!({ "path": path, "why": why }))
2027			.collect();
2028		let moved: Vec<serde_json::Value> = reverted
2029			.moved
2030			.iter()
2031			.map(|(from, to)| json!({ "from": from, "to": to }))
2032			.collect();
2033		return print_json(
2034			&json!({
2035				"written": reverted.written,
2036				"deleted": reverted.deleted,
2037				"moved": moved,
2038				"conflicts": reverted.conflicts,
2039				"skipped": skipped,
2040			}),
2041			output,
2042		);
2043	}
2044	for (from, to) in &reverted.moved {
2045		writeln!(output, "moved     {to}, back from {from}")?;
2046	}
2047	for path in &reverted.deleted {
2048		writeln!(output, "deleted   {path}")?;
2049	}
2050	for path in &reverted.written {
2051		writeln!(output, "written   {path}")?;
2052	}
2053	for path in &reverted.conflicts {
2054		writeln!(output, "conflict  {path}")?;
2055	}
2056	for (path, why) in &reverted.skipped {
2057		writeln!(output, "skipped   {path}: {why}")?;
2058	}
2059	writeln!(
2060		output,
2061		"Nothing is recorded: nib commit records what you keep."
2062	)?;
2063	Ok(())
2064}
2065
2066/// Prints what updating the copy did.
2067fn updated_output(
2068	(updated, clones): (&Updated, &[(ToClone, Cloning)]),
2069	json: bool,
2070	output: &mut dyn Write,
2071) -> Result<(), CliError> {
2072	let with_why = |list: &[(String, String)]| -> Vec<serde_json::Value> {
2073		list.iter()
2074			.map(|(path, why)| json!({ "path": path, "why": why }))
2075			.collect()
2076	};
2077	if json {
2078		let moved: Vec<serde_json::Value> = updated
2079			.moved
2080			.iter()
2081			.map(|(from, to)| json!({ "from": from, "to": to }))
2082			.collect();
2083		let waiting: Vec<serde_json::Value> = updated
2084			.waiting
2085			.iter()
2086			.map(
2087				|cut| json!({ "revision": cut.revision.to_string(), "parts": cut.parts, "made": cut.made }),
2088			)
2089			.collect();
2090		return print_json(
2091			&json!({
2092				"written": updated.written,
2093				"moved": moved,
2094				"deleted": updated.deleted,
2095				"merged": updated.merged,
2096				"conflicts": updated.conflicts,
2097				"contested": updated.contested,
2098				"kept": with_why(&updated.kept),
2099				"skipped": with_why(&updated.skipped),
2100				"waiting": waiting,
2101				"held": updated.held,
2102				"sealed": updated.sealed,
2103				"repositories": clones_json(clones),
2104			}),
2105			output,
2106		);
2107	}
2108	let nothing = updated.written.is_empty()
2109		&& updated.contested.is_empty()
2110		&& updated.moved.is_empty()
2111		&& updated.deleted.is_empty()
2112		&& updated.merged.is_empty()
2113		&& updated.conflicts.is_empty()
2114		&& updated.kept.is_empty()
2115		&& updated.skipped.is_empty()
2116		&& updated.waiting.is_empty()
2117		&& updated.held.is_empty()
2118		&& updated.sealed.is_empty()
2119		&& clones.is_empty();
2120	if nothing {
2121		writeln!(output, "The copy here has the tree as it is")?;
2122		return Ok(());
2123	}
2124	for (from, to) in &updated.moved {
2125		writeln!(output, "moved     {}, from {}", shown(to), shown(from))?;
2126	}
2127	for path in &updated.deleted {
2128		writeln!(output, "deleted   {}", shown(path))?;
2129	}
2130	for path in &updated.written {
2131		writeln!(output, "written   {}", shown(path))?;
2132	}
2133
2134	for path in &updated.merged {
2135		writeln!(output, "merged    {}, to commit", shown(path))?;
2136	}
2137	for path in &updated.conflicts {
2138		writeln!(output, "conflict  {}", shown(path))?;
2139	}
2140	for path in &updated.contested {
2141		writeln!(
2142			output,
2143			"competing {}: deleted on one device while changed on another; a commit keeps it, unless it is deleted first",
2144			shown(path)
2145		)?;
2146	}
2147	for (path, why) in &updated.kept {
2148		writeln!(output, "kept      {}: {}", shown(path), shown(why))?;
2149	}
2150	for (path, why) in &updated.skipped {
2151		writeln!(output, "skipped   {}: {}", shown(path), shown(why))?;
2152	}
2153	for cut in &updated.waiting {
2154		writeln!(
2155			output,
2156			"waiting   revision {}: {} of {} parts have arrived",
2157			short(cut.revision),
2158			cut.made,
2159			cut.parts
2160		)?;
2161	}
2162	for held in &updated.held {
2163		writeln!(
2164			output,
2165			"held      {}: changed elsewhere, which could expose a secret; written once you agree",
2166			shown(held)
2167		)?;
2168	}
2169	sealed_text(&updated.sealed, output)?;
2170	clones_text(clones, output)
2171}