Skip to main content

nibkeep_node/library/trees/
write.rs

1//! Writing trees: a tree into a folder of its own, as it is, at a revision or as of a
2//! moment; an older version or a deleted file into the copy; and what undoes a revision,
3//! merged three ways with what came later. Writing never follows a link, never writes
4//! outside the tree's folder or into `.nib`, a `.git` or the library's own folder, and never
5//! loses a copy's edits that are not committed: a restore keeps them beside the copy, and
6//! nothing else writes over them ([technical design: trees]).
7//!
8//! [technical design: trees]: ../../../../../docs/Technical-design.md#15-trees
9
10use std::collections::{BTreeMap, BTreeSet};
11use std::fs::{self, File};
12use std::io::{self, Write as _};
13use std::path::{Path, PathBuf};
14use std::time::SystemTime;
15
16use nibkeep_base::{EntityId, SpaceId};
17use nibkeep_crypto::rand_core::CryptoRng;
18use nibkeep_model::Value;
19use nibkeep_std::{ON_DEVICE, PATH, ROOT_OF, TREE_ROOT};
20
21use super::history::{READ_LIMIT, TreePoint};
22use super::index::{Entry, Version};
23use super::locate::{Blocked, Located, located, place_for_new};
24use super::paths::{fits_this_system, is_reserved};
25use super::walk::{Found, FoundKind, hash_found, look, nanos, open_found};
26use super::{TREE_TYPES, TreeState, version_of};
27use crate::NodeError;
28use crate::library::Library;
29use crate::library::checkouts::{
30	copy_checked, put_in_place, remove_leftover, sync_folder_of, temporary_for,
31};
32use crate::library::entities::NewValue;
33
34/// What writing a tree, or part of one, wrote.
35#[derive(Clone, Debug, Default, PartialEq, Eq)]
36pub struct Written {
37	/// The paths written, in order.
38	pub written: Vec<String>,
39	/// The paths not written, with why: a name that this system cannot write, something in
40	/// the way, or content that a purge took away.
41	pub skipped: Vec<(String, String)>,
42	/// The secret files not written, as this replica cannot read them: its secrets are
43	/// locked, or not on this device
44	/// ([technical design: secrets in trees](../../../docs/Technical-design.md#151-secrets-in-trees)).
45	pub sealed: Vec<String>,
46	/// The copies with edits not committed that a restore moved beside their paths before it
47	/// wrote there, each path with where its edits are now, as Mercurial's revert keeps them:
48	/// `NAME.orig`, or the first free of `NAME.orig-2` and on.
49	pub aside: Vec<(String, String)>,
50}
51
52/// What removing files from a tree's copy did, as Git's rm does: the copies deleted, for the
53/// next commit to record as deleted.
54#[derive(Clone, Debug, Default, PartialEq, Eq)]
55pub struct CopiesRemoved {
56	/// The paths whose copies it deleted, or that were gone already, in order.
57	pub removed: Vec<String>,
58	/// The paths whose copies stay, with why: one that changed meanwhile, that cannot be
59	/// reached, or that was never written here.
60	pub skipped: Vec<(String, String)>,
61}
62
63/// What undoing a revision wrote into the copy.
64#[derive(Clone, Debug, Default, PartialEq, Eq)]
65pub struct Reverted {
66	/// The paths written: versions from before the revision, or merged with later ones.
67	pub written: Vec<String>,
68	/// The paths deleted: files and links that the revision added.
69	pub deleted: Vec<String>,
70	/// The moves undone, from where to where.
71	pub moved: Vec<(String, String)>,
72	/// The paths where what came later clashes with undoing the revision: text with Git's
73	/// conflict markers, or another file with the version from before written beside it.
74	pub conflicts: Vec<String>,
75	/// The paths left as they are, with why, whose part of the revision is not undone.
76	pub skipped: Vec<(String, String)>,
77}
78
79/// What is written at a path: a version, or bytes made here, such as a merge; of a secret
80/// file, read with the secrets alone, and written for its owner alone.
81pub(super) enum Content<'a> {
82	Version(&'a Version),
83	Bytes(&'a [u8], bool),
84	Secret(&'a Version),
85	SecretBytes(&'a [u8], bool),
86}
87
88impl<'a> Content<'a> {
89	/// A version of a file, secret or not.
90	pub(super) fn of(version: &'a Version, secret: bool) -> Self {
91		if secret {
92			Self::Secret(version)
93		} else {
94			Self::Version(version)
95		}
96	}
97
98	/// Bytes made here of a file, secret or not, executable or not.
99	pub(super) fn bytes(bytes: &'a [u8], executable: bool, secret: bool) -> Self {
100		if secret {
101			Self::SecretBytes(bytes, executable)
102		} else {
103			Self::Bytes(bytes, executable)
104		}
105	}
106}
107
108/// Where writing goes: the tree's folder, and the folders that no path of it reaches.
109#[derive(Clone, Copy)]
110pub(super) struct Place<'a> {
111	pub(super) root: &'a Path,
112	pub(super) apart: &'a [PathBuf],
113}
114
115impl Library {
116	/// Writes a tree into `folder`, empty or new, at a point of its history: as it is, which
117	/// becomes this device's copy of it, with its root recorded; or at a revision, or as of a
118	/// moment, which is a picture of the past and no copy, never over one.
119	///
120	/// # Errors
121	///
122	/// Returns [`NodeError::NotATree`] if `tree` is none, [`NodeError::FolderNotEmpty`] if
123	/// the folder holds anything, [`NodeError::TreeHereAlready`] if the tree as it is is asked
124	/// for and this device has a copy of it already, [`NodeError::TreeInTree`] or
125	/// [`NodeError::NotATreeFolder`] if the folder is in a tree's, the library's or Git's,
126	/// and an error if writing or saving fails.
127	pub fn write_tree(
128		&mut self,
129		space: SpaceId,
130		tree: EntityId,
131		folder: &Path,
132		at: TreePoint,
133		wall_millis: u64,
134		rng: &mut impl CryptoRng,
135	) -> Result<Written, NodeError> {
136		let tree = self.check_tree(space, tree)?;
137		// Taken before the copy is looked for, so that two writes of the tree as it is never
138		// both make one.
139		let locked = if at == TreePoint::Now {
140			self.check_not_revoked(space)?;
141			let locked = self.lock_trees()?;
142			if let Some(root) = self.roots_here(space)?.remove(&tree) {
143				return Err(NodeError::TreeHereAlready(root));
144			}
145			Some(locked)
146		} else {
147			None
148		};
149		// The place is checked before anything is made there.
150		self.check_new_place(folder)?;
151		match fs::read_dir(folder) {
152			Ok(mut entries) => {
153				if entries.next().is_some() {
154					return Err(NodeError::FolderNotEmpty(folder.to_path_buf()));
155				}
156			}
157			Err(error) if error.kind() == io::ErrorKind::NotFound => {
158				fs::create_dir_all(folder).map_err(NodeError::file(folder))?;
159			}
160			Err(error) => return Err(NodeError::file(folder)(error)),
161		}
162		let root = self.checked_new_root(space, folder)?;
163		let state = self.tree_state_at(space, tree, at)?;
164		let apart = self.apart();
165		let place = Place {
166			root: &root,
167			apart: &apart,
168		};
169		let read_at = nanos(SystemTime::now()).unwrap_or(0);
170		let mut written = Written {
171			sealed: state.sealed.keys().cloned().collect(),
172			..Written::default()
173		};
174		let mut entries = Vec::new();
175		for (path, current) in &state.by_path {
176			let Some(version) = &current.version else {
177				let why = "its content was purged".to_owned();
178				written.skipped.push((path.clone(), why));
179				continue;
180			};
181			let content = Content::of(version, state.is_secret(current.entity));
182			match self.write_new(space, place, path, &content) {
183				Ok(found) => {
184					written.written.push(path.clone());
185					entries.push((
186						path.clone(),
187						Entry {
188							entity: current.entity,
189							version: version.clone(),
190							size: found.size,
191							modified: found.modified,
192							read_at,
193						},
194					));
195				}
196				Err(why) => written.skipped.push((path.clone(), why)),
197			}
198		}
199		if locked.is_some() {
200			self.install_standard(space, &TREE_TYPES, wall_millis, rng)?;
201			let (root_entity, operations) = self.new_entity(
202				space,
203				&[TREE_ROOT],
204				vec![
205					NewValue::new(ROOT_OF, Value::Reference(tree)),
206					NewValue::new(ON_DEVICE, Value::Reference(self.info.device)),
207					NewValue::new(PATH, Value::Text(root.to_string_lossy().into_owned())),
208				],
209				rng,
210			)?;
211			self.commit(space, operations, wall_millis, rng)?;
212			let mut index = self.index()?;
213			index.change(tree, &[], &entries)?;
214			self.note_secrets(space, (tree, &index), &state, &entries)?;
215			index.set_root(tree, root_entity, &root)?;
216			index.know(tree)?;
217			// The copy holds the parts of commits not yet whole, which updates then keep.
218			let cut: Vec<EntityId> = self
219				.cut_short(space, tree)?
220				.into_iter()
221				.map(|cut| cut.revision)
222				.collect();
223			index.take_parts(tree, &cut)?;
224		}
225		Ok(written)
226	}
227
228	/// Writes into the copy of a tree on this device the file or link at `path`, or what is
229	/// in the folder at `path`, as it was at a point of the tree's history; as it is, a file
230	/// deleted from the tree comes back too. It records nothing: committing it does, after
231	/// the person checked it. A copy with edits that are not committed, its executable bit
232	/// too, is moved beside its path first, and marked, so that no commit takes it in
233	/// ([`Written::aside`]).
234	///
235	/// # Errors
236	///
237	/// Returns [`NodeError::NotInTree`] if the tree held nothing there then,
238	/// [`NodeError::EditedCopy`] if a copy to write over cannot be read, and an error if
239	/// the index cannot be read or written.
240	pub fn restore_in_tree(
241		&self,
242		space: SpaceId,
243		tree: EntityId,
244		path: &str,
245		at: TreePoint,
246	) -> Result<Written, NodeError> {
247		let _locked = self.lock_trees()?;
248		let root = self.root_here(space, tree)?;
249		let index = self.index()?;
250		let entries = index.entries(tree)?;
251		let now = self.tree_state(space, tree)?;
252		let then = self.tree_state_at(space, tree, at)?;
253		let apart = self.apart();
254		let place = Place {
255			root: &root,
256			apart: &apart,
257		};
258		let under = |candidate: &str| {
259			path.is_empty() || candidate == path || candidate.starts_with(&format!("{path}/"))
260		};
261		let take = |(candidate, current): (&String, &super::Current)| {
262			let secret = then.is_secret(current.entity);
263			(candidate.clone(), current.version.clone(), secret)
264		};
265		let mut chosen: Vec<(String, Option<Version>, bool)> = then
266			.by_path
267			.iter()
268			.filter(|(candidate, _)| under(candidate))
269			.map(take)
270			.collect();
271		if chosen.is_empty() && at == TreePoint::Now {
272			chosen = then
273				.deleted
274				.iter()
275				.filter(|(candidate, _)| under(candidate))
276				.map(take)
277				.collect();
278		}
279		let sealed: Vec<String> = then
280			.sealed
281			.keys()
282			.filter(|candidate| under(candidate))
283			.cloned()
284			.collect();
285		if chosen.is_empty() && sealed.is_empty() {
286			return Err(NodeError::NotInTree(path.to_owned()));
287		}
288		// Every copy is looked at before anything is written.
289		let mut plan = Vec::new();
290		let mut written = Written {
291			sealed,
292			..Written::default()
293		};
294		for (candidate, version, secret) in chosen {
295			let Some(version) = version else {
296				let why = "its content was purged".to_owned();
297				written.skipped.push((candidate, why));
298				continue;
299			};
300			if secret && !self.secrets_unlocked(space) {
301				written.sealed.push(candidate);
302				continue;
303			}
304			match located(&root, &candidate, &apart) {
305				Located::Absent => plan.push((candidate, version, secret, None)),
306				Located::Unknown(why) => written.skipped.push((candidate, why)),
307				Located::Here(on_disk) => {
308					let found =
309						look(&on_disk).map_err(|_| NodeError::EditedCopy(candidate.clone()))?;
310					let holds = copy_version(&found);
311					if holds.as_ref() == Some(&version) {
312						continue;
313					}
314					let recorded = recorded_version(&entries, &now, &candidate);
315					let unedited = holds
316						.as_ref()
317						.zip(recorded)
318						.is_some_and(|(holds, recorded)| same_version(&found, holds, recorded));
319					plan.push((candidate, version, secret, Some((found, !unedited))));
320				}
321			}
322		}
323		written.sealed.sort();
324		for (candidate, version, secret, there) in plan {
325			let content = Content::of(&version, secret);
326			let done = match &there {
327				None => self.write_new(space, place, &candidate, &content).map(drop),
328				Some((found, false)) => self.write_over(space, found, &content),
329				Some((found, true)) => {
330					// Never beside it at a path of the tree's, then or now.
331					let held = |name: &str| {
332						now.by_path.contains_key(name)
333							|| then.by_path.contains_key(name)
334							|| entries.contains_key(name)
335					};
336					let edited = (candidate.as_str(), found);
337					let at = (&index, tree, place);
338					self.write_keeping_edits(space, at, (edited, &held), &content)?
339						.map(|beside| written.aside.push((candidate.clone(), beside)))
340				}
341			};
342			match done {
343				Ok(()) => written.written.push(candidate),
344				Err(why) => written.skipped.push((candidate, why)),
345			}
346		}
347		Ok(written)
348	}
349
350	/// Writes `content` at `path`, whose copy `found` has edits not committed, once the copy
351	/// is moved beside it ([`set_aside`]); where writing fails, the copy goes back. Returns
352	/// where the edits are, or why nothing was written.
353	fn write_keeping_edits(
354		&self,
355		space: SpaceId,
356		(index, tree, place): (&super::index::Index, EntityId, Place<'_>),
357		((path, found), held): ((&str, &Found), Held<'_>),
358		content: &Content<'_>,
359	) -> Result<Result<String, String>, NodeError> {
360		let beside = match set_aside(index, (tree, place), (path, held), found)? {
361			Ok(beside) => beside,
362			Err(why) => return Ok(Err(why)),
363		};
364		match self.write_new(space, place, path, content) {
365			Ok(_) => Ok(Ok(beside)),
366			Err(why) => {
367				bring_back(index, (tree, place), (path, &beside), found)?;
368				Ok(Err(why))
369			}
370		}
371	}
372
373	/// Deletes from the copy of a tree on this device the file or link at each of `paths`,
374	/// or the tree's files and links in the folder there, the whole copy for an empty path,
375	/// and the folders they leave empty, as Git's rm does: what the next commit records as
376	/// deleted. It records nothing. A copy with edits that are not committed stays, unless
377	/// `force`, and so does whatever the tree does not hold; every copy is looked at before
378	/// any is deleted.
379	///
380	/// # Errors
381	///
382	/// Returns [`NodeError::UnsafePath`] if a path leaves the tree, [`NodeError::NotInTree`]
383	/// if the tree holds nothing at one, [`NodeError::EditedCopy`] if a copy has edits not
384	/// committed, or cannot be read, and an error if the index cannot be read.
385	pub fn remove_in_tree(
386		&self,
387		space: SpaceId,
388		tree: EntityId,
389		paths: &[String],
390		force: bool,
391	) -> Result<CopiesRemoved, NodeError> {
392		if let Some(path) = paths
393			.iter()
394			.find(|path| !path.is_empty() && !super::is_safe_tree_path(path))
395		{
396			return Err(NodeError::UnsafePath(path.clone()));
397		}
398		let _locked = self.lock_trees()?;
399		let root = self.root_here(space, tree)?;
400		let entries = self.index()?.entries(tree)?;
401		let now = self.tree_state(space, tree)?;
402		let apart = self.apart();
403		let under = |path: &str, candidate: &str| {
404			path.is_empty() || candidate == path || candidate.starts_with(&format!("{path}/"))
405		};
406		if let Some(path) = paths
407			.iter()
408			.find(|path| !now.by_path.keys().any(|candidate| under(path, candidate)))
409		{
410			return Err(NodeError::NotInTree(path.clone()));
411		}
412		let chosen: Vec<&String> = now
413			.by_path
414			.keys()
415			.filter(|candidate| paths.iter().any(|path| under(path, candidate)))
416			.collect();
417		let mut removed = CopiesRemoved::default();
418		let mut plan = Vec::new();
419		for candidate in chosen {
420			match located(&root, candidate, &apart) {
421				Located::Absent if entries.contains_key(candidate) => {
422					removed.removed.push(candidate.clone());
423				}
424				Located::Absent => {
425					let why = "its copy was never written here".to_owned();
426					removed.skipped.push((candidate.clone(), why));
427				}
428				Located::Unknown(why) => removed.skipped.push((candidate.clone(), why)),
429				Located::Here(on_disk) => {
430					let found =
431						look(&on_disk).map_err(|_| NodeError::EditedCopy(candidate.clone()))?;
432					let unedited = copy_version(&found)
433						.zip(recorded_version(&entries, &now, candidate))
434						.is_some_and(|(holds, recorded)| same_version(&found, &holds, recorded));
435					if !unedited && !force {
436						return Err(NodeError::EditedCopy(candidate.clone()));
437					}
438					plan.push((candidate.clone(), found));
439				}
440			}
441		}
442		for (candidate, found) in plan {
443			// Deleted only if it is still the copy read, as a save made meanwhile replaces it.
444			if !still_the_copy(&found) {
445				let why = "it changed meanwhile".to_owned();
446				removed.skipped.push((candidate, why));
447				continue;
448			}
449			match fs::remove_file(&found.on_disk) {
450				Ok(()) => {
451					sync_folder_of(&found.on_disk);
452					remove_emptied(&root, &found.on_disk);
453					removed.removed.push(candidate);
454				}
455				Err(error) => removed.skipped.push((candidate, error.to_string())),
456			}
457		}
458		removed.removed.sort();
459		Ok(removed)
460	}
461
462	/// Writes into the copy of a tree on this device what undoes a revision, and only that,
463	/// as `git revert --no-commit` does: each file it changed goes back to its version
464	/// before it, merged three ways with what later revisions changed; files it moved go
465	/// back, files it deleted come back, and files it added go. It records nothing. What it
466	/// cannot undo, it lists with why.
467	///
468	/// # Errors
469	///
470	/// Returns [`NodeError::NoRevision`] if the revision is not the tree's,
471	/// [`NodeError::EditedCopy`] if a copy it would change has edits not committed,
472	/// [`NodeError::TreeStale`] if a copy it would change is behind the tree, which an update
473	/// brings first, and an error if the space cannot be read or writing fails.
474	pub fn revert_in_tree(
475		&self,
476		space: SpaceId,
477		tree: EntityId,
478		revision: EntityId,
479	) -> Result<Reverted, NodeError> {
480		let _locked = self.lock_trees()?;
481		let root = self.root_here(space, tree)?;
482		let index = self.index()?;
483		let entries = index.entries(tree)?;
484		let changes = self.revision_changes(space, tree, revision)?;
485		let Some(&last) = changes.last() else {
486			return Err(NodeError::NoRevision(revision.to_string()));
487		};
488		let parts: BTreeSet<_> = changes.iter().copied().collect();
489		let (after, before) = self.tree_states_of_changes(space, tree, last, &parts)?;
490		let now = self.tree_state(space, tree)?;
491		let apart = self.apart();
492		let place = Place {
493			root: &root,
494			apart: &apart,
495		};
496		let mut reverted = Reverted::default();
497		let plan = undoing(&before, &after, &now, &mut reverted);
498		// Every copy it changes holds what the tree holds now, edits committed, executable
499		// bits too: it never writes over edits, as `git revert` refuses to, nor undoes a
500		// revision on a copy that is behind, which would leave later revisions out.
501		let mut behind = Vec::new();
502		for path in plan.touched() {
503			let Located::Here(on_disk) = located(&root, path, &apart) else {
504				continue;
505			};
506			let Ok(found) = look(&on_disk) else {
507				return Err(NodeError::EditedCopy(path.to_owned()));
508			};
509			let holds = copy_version(&found);
510			let committed = holds
511				.as_ref()
512				.zip(entries.get(path).map(|entry| &entry.version))
513				.is_some_and(|(holds, entry)| same_version(&found, holds, entry));
514			let current = now
515				.by_path
516				.get(path)
517				.and_then(|current| current.version.as_ref());
518			let up_to_date = holds
519				.as_ref()
520				.zip(current)
521				.is_some_and(|(holds, current)| same_version(&found, holds, current));
522			if !up_to_date && committed {
523				behind.push(path.to_owned());
524			} else if !up_to_date {
525				return Err(NodeError::EditedCopy(path.to_owned()));
526			}
527		}
528		if !behind.is_empty() {
529			return Err(NodeError::TreeStale(behind));
530		}
531		// First what is in the way goes, then what moved goes back, then what was deleted
532		// comes back, then edits are undone: the order in which no step meets another's.
533		for (path, added) in &plan.additions {
534			undo_addition(place, (path, added.as_ref()), &mut reverted);
535		}
536		let at = undo_moves(place, &plan.moves, &mut reverted);
537		for (path, version) in &plan.deletions {
538			let Some(version) = version else {
539				let why = "its content was purged".to_owned();
540				reverted.skipped.push((path.clone(), why));
541				continue;
542			};
543			let content = Content::of(version, plan.secret.contains(path));
544			match self.write_new(space, place, path, &content) {
545				Ok(_) => reverted.written.push(path.clone()),
546				Err(why) => reverted.skipped.push((path.clone(), why)),
547			}
548		}
549		let short = &revision.to_string()[..8];
550		for (path, versions) in &plan.edits {
551			let secret = plan.secret.contains(path);
552			let path = at.get(path).unwrap_or(path);
553			if let Some(beside) = self.undo_edit(
554				space,
555				(place, short),
556				(path, secret),
557				versions,
558				&mut reverted,
559			) {
560				index.mark(
561					tree,
562					&beside,
563					"NibKeep wrote it, the version from before a reverted revision",
564				)?;
565			}
566		}
567		Ok(reverted)
568	}
569
570	/// Refuses a folder to write a tree into, before anything is made there: in a folder
571	/// that some system reads as `.git` or `.nib`, in the library's own, or in or around a
572	/// tree's folder on this device, of any space.
573	fn check_new_place(&self, folder: &Path) -> Result<(), NodeError> {
574		// Where it is, as the file system resolves the part of it that is there.
575		let mut existing = folder;
576		let mut rest = Vec::new();
577		let resolved = loop {
578			if let Ok(resolved) = fs::canonicalize(existing) {
579				break crate::library::files::plain(resolved);
580			}
581			let (Some(name), Some(parent)) = (existing.file_name(), existing.parent()) else {
582				return Err(NodeError::NotATreeFolder(folder.to_path_buf()));
583			};
584			rest.push(name);
585			existing = parent;
586		};
587		let mut full = resolved;
588		full.extend(rest.iter().rev());
589		let reserved = full.components().any(|component| match component {
590			std::path::Component::Normal(name) => is_reserved(&name.to_string_lossy()),
591			_ => false,
592		});
593		if reserved || self.apart().iter().any(|apart| full.starts_with(apart)) {
594			return Err(NodeError::NotATreeFolder(full));
595		}
596		for &space in self.spaces.keys() {
597			for other in self.roots_here(space)?.values() {
598				if full.starts_with(other) || other.starts_with(&full) {
599					return Err(NodeError::TreeInTree(full));
600				}
601			}
602		}
603		Ok(())
604	}
605}
606
607/// What undoing a revision does, decided before anything is written: the copies of what it
608/// added to delete, with the versions it added; the moves to undo; the files it deleted to
609/// write back; and the edits to undo, each with its version before and after the revision,
610/// by the path where the copy is now.
611#[derive(Debug, Default)]
612struct Undoing {
613	additions: Vec<(String, Option<Version>)>,
614	moves: Vec<(String, String)>,
615	deletions: Vec<(String, Option<Version>)>,
616	edits: Vec<(String, (Version, Version))>,
617	/// The paths of deletions and edits that are of secret files.
618	secret: BTreeSet<String>,
619}
620
621impl Undoing {
622	/// The paths whose copies it changes, as they are now.
623	fn touched(&self) -> impl Iterator<Item = &String> {
624		self.additions
625			.iter()
626			.map(|(path, _)| path)
627			.chain(self.moves.iter().map(|(from, _)| from))
628			.chain(self.edits.iter().map(|(path, _)| path))
629	}
630}
631
632/// What undoing a revision does, from the tree before it, after it, and now; a file whose
633/// path another holds now too, as when two devices added one path, is listed in `reverted`
634/// as skipped, as which copy is its own is not known.
635fn undoing(
636	before: &TreeState,
637	after: &TreeState,
638	now: &TreeState,
639	reverted: &mut Reverted,
640) -> Undoing {
641	let mut plan = Undoing::default();
642	let entities: BTreeSet<EntityId> = before
643		.by_entity
644		.keys()
645		.chain(after.by_entity.keys())
646		.copied()
647		.collect();
648	for entity in entities {
649		let is = version_of(now, entity);
650		if let Some((path, _)) = &is
651			&& now
652				.by_path
653				.get(path)
654				.is_some_and(|current| current.entity != entity)
655		{
656			let why = "another file competes for its path; update the copy first".to_owned();
657			reverted.skipped.push((path.clone(), why));
658			continue;
659		}
660		match (version_of(before, entity), version_of(after, entity)) {
661			(None, Some((_, added))) => {
662				if let Some((path, _)) = is {
663					plan.additions.push((path, added));
664				}
665			}
666			(Some((path, version)), None) => {
667				if is.is_none() {
668					if before.is_secret(entity) {
669						plan.secret.insert(path.clone());
670					}
671					plan.deletions.push((path, version));
672				}
673			}
674			(Some((was_path, was)), Some((became_path, became))) => {
675				if was_path == became_path && was == became {
676					// The revision did not change it.
677					continue;
678				}
679				let Some((path, _)) = is else {
680					let why = "it was deleted since".to_owned();
681					reverted.skipped.push((became_path, why));
682					continue;
683				};
684				if was_path != became_path && path == became_path {
685					plan.moves.push((path.clone(), was_path));
686				}
687				if let (Some(was), Some(became)) = (was, became)
688					&& was != became
689				{
690					if after.is_secret(entity) {
691						plan.secret.insert(path.clone());
692					}
693					plan.edits.push((path, (was, became)));
694				}
695			}
696			(None, None) => {}
697		}
698	}
699	plan
700}
701
702/// Undoes a revision's addition of a file: deletes its copy, if it is as the revision left
703/// it; one that later revisions changed stays, as a conflict.
704fn undo_addition(
705	place: Place<'_>,
706	(path, added): (&String, Option<&Version>),
707	reverted: &mut Reverted,
708) {
709	let on_disk = match located(place.root, path, place.apart) {
710		Located::Here(on_disk) => on_disk,
711		Located::Absent => return,
712		Located::Unknown(why) => {
713			reverted.skipped.push((path.clone(), why));
714			return;
715		}
716	};
717	let unchanged = look(&on_disk).is_ok_and(|found| {
718		copy_version(&found)
719			.zip(added)
720			.is_some_and(|(holds, added)| same_version(&found, &holds, added))
721	});
722	if !unchanged {
723		reverted.conflicts.push(path.clone());
724		return;
725	}
726	match fs::remove_file(&on_disk) {
727		Ok(()) => {
728			sync_folder_of(&on_disk);
729			reverted.deleted.push(path.clone());
730		}
731		Err(error) => reverted.skipped.push((path.clone(), error.to_string())),
732	}
733}
734
735/// Undoes moves, all at once, as [`undo_moves_at`] does them.
736fn undo_moves(
737	place: Place<'_>,
738	moves: &[(String, String)],
739	reverted: &mut Reverted,
740) -> BTreeMap<String, String> {
741	let at = undo_moves_at(place, moves, &mut reverted.skipped);
742	reverted
743		.moved
744		.extend(at.iter().map(|(from, to)| (from.clone(), to.clone())));
745	at
746}
747
748/// Moves copies, all at once: each goes to a name of its own beside it first, then to where
749/// it goes, so that swaps, chains and changes of case alone never meet each other. Returns
750/// where each copy went, by where it was; what could not move is in `skipped`, with why.
751/// Where a move puts a copy aside while the others are moved: a temporary name of its own,
752/// never one that writing a file at its path uses and clears.
753pub(super) fn aside_for(source: &Path) -> PathBuf {
754	let name = source.file_name().map(std::ffi::OsStr::as_encoded_bytes);
755	let mut hasher = blake3::Hasher::new();
756	hasher.update(b"moved aside\0");
757	hasher.update(name.unwrap_or_default());
758	let digest = hasher.finalize().to_hex();
759	source.with_file_name(format!(".nib-tree-{}", &digest[..16]))
760}
761
762/// Puts back the copies that a move cut short left aside, where their paths are free.
763pub(super) fn bring_back_aside<'a>(place: Place<'_>, paths: impl Iterator<Item = &'a String>) {
764	for path in paths {
765		if located(place.root, path, place.apart) != Located::Absent {
766			continue;
767		}
768		let source = place.root.join(path);
769		let aside = aside_for(&source);
770		if fs::symlink_metadata(&aside).is_ok()
771			&& fs::symlink_metadata(&source).is_err()
772			&& fs::rename(&aside, &source).is_ok()
773		{
774			sync_folder_of(&source);
775		}
776	}
777}
778
779/// Removes the folders above `deleted`, below the tree's folder `root`, that its deletion
780/// left empty, from the innermost, each saved into the folder that held it.
781fn remove_emptied(root: &Path, deleted: &Path) {
782	for folder in deleted.ancestors().skip(1) {
783		if folder == root || !folder.starts_with(root) || fs::remove_dir(folder).is_err() {
784			break;
785		}
786		sync_folder_of(folder);
787	}
788}
789
790/// Whether the tree holds a path, then or now, which no copy set aside may take.
791type Held<'a> = &'a dyn Fn(&str) -> bool;
792
793/// Whether the copy that `found` is is still as it was read: the same file, of the same size
794/// and time, as a save made meanwhile replaces it.
795pub(super) fn still_the_copy(found: &Found) -> bool {
796	look(&found.on_disk).is_ok_and(|now| {
797		now.identity == found.identity && now.size == found.size && now.modified == found.modified
798	})
799}
800
801/// Moves the copy that `found` is, with edits not committed, beside its path `path`, before
802/// a restore writes there: as `NAME.orig`, or the first free of `NAME.orig-2` to
803/// `NAME.orig-99` that is no path `held` by the tree, marked first, so that no commit takes
804/// it in, whatever stops the restore; and only if it is still the copy read. Returns where it
805/// is now, or why it stays.
806fn set_aside(
807	index: &super::index::Index,
808	(tree, place): (EntityId, Place<'_>),
809	(path, held): (&str, Held<'_>),
810	found: &Found,
811) -> Result<Result<String, String>, NodeError> {
812	let Some(beside) = (1..=99)
813		.map(|number| match number {
814			1 => format!("{path}.orig"),
815			_ => format!("{path}.orig-{number}"),
816		})
817		.find(|name| !held(name) && located(place.root, name, place.apart) == Located::Absent)
818	else {
819		return Ok(Err(format!(
820			"{path}.orig and the names after it are taken, so its edits stay"
821		)));
822	};
823	index.mark(
824		tree,
825		&beside,
826		"NibKeep wrote it, the edits a restore took from the copy",
827	)?;
828	let moved = if still_the_copy(found) {
829		move_into_place(place, &found.on_disk, &beside)
830	} else {
831		Err("it changed meanwhile".to_owned())
832	};
833	if let Err(why) = moved {
834		index.unmark(tree, std::slice::from_ref(&beside))?;
835		return Ok(Err(why));
836	}
837	Ok(Ok(beside))
838}
839
840/// Puts back at `path` the edits that [`set_aside`] moved to `beside`, where nothing came
841/// meanwhile, once writing the version there failed, and takes the mark away.
842fn bring_back(
843	index: &super::index::Index,
844	(tree, place): (EntityId, Place<'_>),
845	(path, beside): (&str, &str),
846	found: &Found,
847) -> Result<(), NodeError> {
848	if located(place.root, path, place.apart) == Located::Absent
849		&& fs::rename(place.root.join(beside), &found.on_disk).is_ok()
850	{
851		sync_folder_of(&found.on_disk);
852		index.unmark(tree, &[beside.to_owned()])?;
853	}
854	Ok(())
855}
856
857pub(super) fn undo_moves_at(
858	place: Place<'_>,
859	moves: &[(String, String)],
860	skipped: &mut Vec<(String, String)>,
861) -> BTreeMap<String, String> {
862	let mut aside = Vec::new();
863	for (from, to) in moves {
864		let source = match located(place.root, from, place.apart) {
865			Located::Here(source) => source,
866			Located::Absent => {
867				skipped.push((from.clone(), "its copy is not here".to_owned()));
868				continue;
869			}
870			Located::Unknown(why) => {
871				skipped.push((from.clone(), why));
872				continue;
873			}
874		};
875		let temporary = aside_for(&source);
876		if fs::symlink_metadata(&temporary).is_ok() || fs::rename(&source, &temporary).is_err() {
877			skipped.push((from.clone(), "it could not be moved".to_owned()));
878			continue;
879		}
880		aside.push((from, to, source, temporary));
881	}
882	let mut at = BTreeMap::new();
883	for (from, to, source, temporary) in aside {
884		match move_into_place(place, &temporary, to) {
885			Ok(()) => {
886				// Saved before the index records the move, which a power cut must not keep
887				// without it.
888				sync_folder_of(&source);
889				at.insert(from.clone(), to.clone());
890			}
891			Err(why) => {
892				// Back where it was, as nothing took its place meanwhile.
893				let _ = fs::rename(&temporary, &source);
894				skipped.push((from.clone(), why));
895			}
896		}
897	}
898	at
899}
900
901impl Library {
902	/// Undoes a revision's edit of the file whose copy is at `path`: writes its version from
903	/// before, or that version merged three ways with what later revisions changed. Returns
904	/// the path it wrote the version from before at, beside the copy, if the merge could not.
905	fn undo_edit(
906		&self,
907		space: SpaceId,
908		(place, short): (Place<'_>, &str),
909		(path, secret): (&str, bool),
910		(before, after): &(Version, Version),
911		reverted: &mut Reverted,
912	) -> Option<String> {
913		if secret && !self.secrets_unlocked(space) {
914			let why = "a secret file, which is written only with the secrets unlocked".to_owned();
915			reverted.skipped.push((path.to_owned(), why));
916			return None;
917		}
918		let on_disk = match located(place.root, path, place.apart) {
919			Located::Here(on_disk) => on_disk,
920			Located::Absent => {
921				let why = "its copy is not here".to_owned();
922				reverted.skipped.push((path.to_owned(), why));
923				return None;
924			}
925			Located::Unknown(why) => {
926				reverted.skipped.push((path.to_owned(), why));
927				return None;
928			}
929		};
930		let found = match look(&on_disk) {
931			Ok(found) => found,
932			Err(why) => {
933				reverted.skipped.push((path.to_owned(), why));
934				return None;
935			}
936		};
937		match self.merge_back(space, &found, (before, after), secret) {
938			Ok(Merged::Unchanged) => {}
939			Ok(Merged::Clean(content)) => {
940				match self.write_over(space, &found, &content.as_content(secret)) {
941					Ok(()) => reverted.written.push(path.to_owned()),
942					Err(why) => reverted.skipped.push((path.to_owned(), why)),
943				}
944			}
945			Ok(Merged::Clashed(content)) => {
946				match self.write_over(space, &found, &content.as_content(secret)) {
947					Ok(()) => reverted.conflicts.push(path.to_owned()),
948					Err(why) => reverted.skipped.push((path.to_owned(), why)),
949				}
950			}
951			Ok(Merged::Beside) => {
952				let beside = format!("{path}.before-{short}");
953				match self.write_new(space, place, &beside, &Content::of(before, secret)) {
954					Ok(_) => {
955						reverted.conflicts.push(path.to_owned());
956						return Some(beside);
957					}
958					Err(why) => reverted.skipped.push((path.to_owned(), why)),
959				}
960			}
961			Err(why) => reverted.skipped.push((path.to_owned(), why)),
962		}
963		None
964	}
965
966	/// What undoing an edit makes of a copy: the version from before, if the copy holds what
967	/// the revision made; or else that version merged three ways with what the copy holds,
968	/// byte by byte, so that text in any encoding stays as it is. The executable bit merges
969	/// three ways too: what later revisions set stays.
970	fn merge_back(
971		&self,
972		space: SpaceId,
973		found: &Found,
974		(before, after): (&Version, &Version),
975		secret: bool,
976	) -> Result<Merged, String> {
977		let holds = copy_version(found).ok_or("it cannot be read")?;
978		let (
979			Version::File {
980				content: was,
981				executable: was_executable,
982			},
983			Version::File {
984				content: became,
985				executable: became_executable,
986			},
987		) = (before, after)
988		else {
989			// Links: the target from before, if the copy holds the revision's.
990			return Ok(if holds == *before {
991				Merged::Unchanged
992			} else if same_content(&holds, after) {
993				Merged::Clean(Owned::Version(before.clone()))
994			} else {
995				Merged::Beside
996			});
997		};
998		let holds_executable = found.executable.unwrap_or(*became_executable);
999		let executable = if holds_executable == *became_executable {
1000			*was_executable
1001		} else {
1002			holds_executable
1003		};
1004		let wanted = Version::File {
1005			content: *was,
1006			executable,
1007		};
1008		if holds == wanted {
1009			return Ok(Merged::Unchanged);
1010		}
1011		if same_content(&holds, after) {
1012			return Ok(Merged::Clean(Owned::Version(wanted)));
1013		}
1014		if found.kind != FoundKind::File {
1015			return Ok(Merged::Beside);
1016		}
1017		let was_bytes = self.version_bytes(space, was, secret).ok().flatten();
1018		let became_bytes = self.version_bytes(space, became, secret).ok().flatten();
1019		let mut ours = Vec::new();
1020		let read = open_found(found)
1021			.and_then(|file| {
1022				io::Read::read_to_end(&mut io::Read::take(file, READ_LIMIT + 1), &mut ours)
1023			})
1024			.map_err(|error| error.to_string())?;
1025		let (Some(was_bytes), Some(became_bytes), true) =
1026			(was_bytes, became_bytes, read as u64 <= READ_LIMIT)
1027		else {
1028			// Too large to merge, or a version this device does not hold.
1029			return Ok(Merged::Beside);
1030		};
1031		let text = [&was_bytes, &became_bytes, &ours]
1032			.iter()
1033			.all(|bytes| super::diff::is_text(bytes));
1034		if !text {
1035			return Ok(Merged::Beside);
1036		}
1037		Ok(match diffy::merge_bytes(&became_bytes, &ours, &was_bytes) {
1038			Ok(merged) => Merged::Clean(Owned::Bytes(merged, executable)),
1039			Err(clashed) => Merged::Clashed(Owned::Bytes(clashed, executable)),
1040		})
1041	}
1042
1043	/// Writes `content` at the path `path` of the tree at the place's folder, where nothing
1044	/// is: never through a link, outside the folder, or into `.nib`, a `.git` or the
1045	/// library's own folder. Returns what is there then, or why nothing was written.
1046	pub(super) fn write_new(
1047		&self,
1048		space: SpaceId,
1049		place: Place<'_>,
1050		path: &str,
1051		content: &Content<'_>,
1052	) -> Result<Found, String> {
1053		if !path.split('/').all(fits_this_system) {
1054			return Err("this system cannot write its name".to_owned());
1055		}
1056		let blocked = |why| match why {
1057			Blocked::Taken => "something is in its place".to_owned(),
1058			Blocked::Unsafe => "its way goes through a link, or into the library".to_owned(),
1059		};
1060		let target = place_for_new(place.root, path, place.apart).map_err(blocked)?;
1061		if let Some(parent) = target.parent() {
1062			make_folders(parent).map_err(|error| error.to_string())?;
1063			// What made the folders may have raced a link into them.
1064			if place_for_new(place.root, path, place.apart).as_ref() != Ok(&target) {
1065				return Err("its way goes through a link".to_owned());
1066			}
1067		}
1068		let temporary = temporary_for(&target, "tree");
1069		remove_leftover(&temporary);
1070		let made = self
1071			.write_temporary(space, content, &temporary)
1072			.and_then(|()| put_in_place(&temporary, &target).map_err(|error| error.to_string()));
1073		if made.is_err() {
1074			remove_leftover(&temporary);
1075		}
1076		made?;
1077		look(&target)
1078	}
1079
1080	/// Writes `content` over the copy that `found` is, if it is still that copy, as it was
1081	/// read: written beside it first, then put in its place at once, so that the copy stays
1082	/// as it is if writing fails.
1083	pub(super) fn write_over(
1084		&self,
1085		space: SpaceId,
1086		found: &Found,
1087		content: &Content<'_>,
1088	) -> Result<(), String> {
1089		let target = &found.on_disk;
1090		let temporary = temporary_for(target, "tree");
1091		remove_leftover(&temporary);
1092		let placed = self
1093			.write_temporary(space, content, &temporary)
1094			.and_then(|()| {
1095				if !still_the_copy(found) {
1096					return Err("it changed meanwhile".to_owned());
1097				}
1098				fs::rename(&temporary, target).map_err(|error| error.to_string())
1099			});
1100		if placed.is_err() {
1101			remove_leftover(&temporary);
1102		} else {
1103			sync_folder_of(target);
1104		}
1105		placed
1106	}
1107
1108	/// Writes `content` at `temporary`, which nothing is at: a link, or a file saved to the
1109	/// disk, executable as it says.
1110	fn write_temporary(
1111		&self,
1112		space: SpaceId,
1113		content: &Content<'_>,
1114		temporary: &Path,
1115	) -> Result<(), String> {
1116		match content {
1117			Content::Version(Version::Link { target })
1118			| Content::Secret(Version::Link { target }) => make_link(target, temporary),
1119			Content::Version(Version::File {
1120				content,
1121				executable,
1122			}) => self
1123				.blob_into(space, content, temporary)
1124				.and_then(|()| set_executable(temporary, *executable)),
1125			Content::Secret(Version::File {
1126				content,
1127				executable,
1128			}) => self
1129				.secret_blob_into(space, content, temporary)
1130				.and_then(|()| set_executable(temporary, *executable)),
1131			Content::Bytes(bytes, executable) => bytes_into(bytes, temporary, false)
1132				.and_then(|()| set_executable(temporary, *executable)),
1133			Content::SecretBytes(bytes, executable) => bytes_into(bytes, temporary, true)
1134				.and_then(|()| set_executable(temporary, *executable)),
1135		}
1136	}
1137
1138	/// Writes the content of a secret file with the hash `content`, from the store, into the
1139	/// new file `temporary`, which only its owner may read on Unix, checked against its hash,
1140	/// and saves it to the disk: only with the secrets unlocked, and only content sealed for
1141	/// the secrets.
1142	fn secret_blob_into(
1143		&self,
1144		space: SpaceId,
1145		content: &nibkeep_base::Hash,
1146		temporary: &Path,
1147	) -> Result<(), String> {
1148		if !self.secrets_unlocked(space) {
1149			return Err(
1150				"a secret file, which is written only with the secrets unlocked".to_owned(),
1151			);
1152		}
1153		let open = self.space(space).map_err(|error| error.to_string())?;
1154		let gone = || "this device holds no copy of its content".to_owned();
1155		if !open.stored.has_secret_blob_key(content) || !open.stored.holds_blob(content) {
1156			return Err(gone());
1157		}
1158		let mut reader = open.stored.open_blob(content).map_err(|_| gone())?;
1159		let mut file = new_file(temporary, true).map_err(|error| error.to_string())?;
1160		let matches =
1161			copy_checked(&mut reader, &mut file, content).map_err(|error| error.to_string())?;
1162		if !matches {
1163			return Err("its content does not match its hash".to_owned());
1164		}
1165		file.sync_all().map_err(|error| error.to_string())
1166	}
1167
1168	/// The content with the hash `content` of a version, as this device holds it, if no larger
1169	/// than a merge reads: of a secret file only with the secrets unlocked, and only content
1170	/// sealed for the secrets; of another, only content sealed for every replica.
1171	pub(super) fn version_bytes(
1172		&self,
1173		space: SpaceId,
1174		content: &nibkeep_base::Hash,
1175		secret: bool,
1176	) -> Result<Option<Vec<u8>>, NodeError> {
1177		if !secret {
1178			return self.content_bytes(space, content);
1179		}
1180		if !self.secrets_unlocked(space) {
1181			return Ok(None);
1182		}
1183		let open = self.space(space)?;
1184		if !open.stored.has_secret_blob_key(content) || !open.stored.holds_blob(content) {
1185			return Ok(None);
1186		}
1187		let reader = open.stored.open_blob(content)?;
1188		let mut bytes = Vec::new();
1189		let read = io::Read::read_to_end(&mut io::Read::take(reader, READ_LIMIT + 1), &mut bytes)
1190			.map_err(|_| NodeError::Store(nibkeep_store::StoreError::DamagedBlob))?;
1191		if read as u64 > READ_LIMIT || nibkeep_base::Hash::of(&bytes) != *content {
1192			return Ok(None);
1193		}
1194		Ok(Some(bytes))
1195	}
1196
1197	/// Writes the content with the hash `content`, from the store, into the new file
1198	/// `temporary`, checked against its hash, and saves it to the disk.
1199	fn blob_into(
1200		&self,
1201		space: SpaceId,
1202		content: &nibkeep_base::Hash,
1203		temporary: &Path,
1204	) -> Result<(), String> {
1205		let open = self.space(space).map_err(|error| error.to_string())?;
1206		// Only content sealed for every replica: a secret file's copy of the same content is
1207		// sealed for the secrets, and never written in plain.
1208		if !open.stored.holds_ordinary_blob(content) {
1209			return Err("this device holds no copy of its content".to_owned());
1210		}
1211		let mut reader = open
1212			.stored
1213			.open_blob(content)
1214			.map_err(|_| "this device holds no copy of its content".to_owned())?;
1215		let mut file = File::create_new(temporary).map_err(|error| error.to_string())?;
1216		let matches =
1217			copy_checked(&mut reader, &mut file, content).map_err(|error| error.to_string())?;
1218		if !matches {
1219			return Err("its content does not match its hash".to_owned());
1220		}
1221		file.sync_all().map_err(|error| error.to_string())
1222	}
1223}
1224
1225/// Makes `folder` and the folders above it that are missing, each saved into the folder that
1226/// holds it, so that a power cut never keeps a copy recorded in a folder that it loses.
1227pub(super) fn make_folders(folder: &Path) -> io::Result<()> {
1228	let missing: Vec<&Path> = folder
1229		.ancestors()
1230		.take_while(|at| fs::symlink_metadata(at).is_err())
1231		.collect();
1232	fs::create_dir_all(folder)?;
1233	for made in missing.iter().rev() {
1234		sync_folder_of(made);
1235	}
1236	Ok(())
1237}
1238
1239/// Moves what is at `temporary`, beside a copy, to the path `to` of the tree, which must be
1240/// free: never through a link, into the library, nor onto something.
1241fn move_into_place(place: Place<'_>, temporary: &Path, to: &str) -> Result<(), String> {
1242	let blocked = |_| "something is in its place".to_owned();
1243	let target = place_for_new(place.root, to, place.apart).map_err(blocked)?;
1244	if let Some(parent) = target.parent() {
1245		make_folders(parent).map_err(|error| error.to_string())?;
1246	}
1247	// What made the folders may have raced a link into them, or something into its place.
1248	if place_for_new(place.root, to, place.apart).as_ref() != Ok(&target) {
1249		return Err("something is in its place".to_owned());
1250	}
1251	fs::rename(temporary, &target).map_err(|error| error.to_string())?;
1252	sync_folder_of(&target);
1253	Ok(())
1254}
1255
1256/// What undoing an edit makes of a copy.
1257enum Merged {
1258	/// The copy holds the version from before already.
1259	Unchanged,
1260	/// What to write, cleanly.
1261	Clean(Owned),
1262	/// What to write, with Git's conflict markers where edits clash.
1263	Clashed(Owned),
1264	/// The copy stays as it is, and the version from before goes beside it.
1265	Beside,
1266}
1267
1268/// Content to write that this module owns.
1269enum Owned {
1270	Version(Version),
1271	Bytes(Vec<u8>, bool),
1272}
1273
1274impl Owned {
1275	fn as_content(&self, secret: bool) -> Content<'_> {
1276		match self {
1277			Self::Version(version) => Content::of(version, secret),
1278			Self::Bytes(bytes, executable) => Content::bytes(bytes, *executable, secret),
1279		}
1280	}
1281}
1282
1283/// The version that this copy last held as the index says, or else, as the tree holds it.
1284fn recorded_version<'a>(
1285	entries: &'a BTreeMap<String, Entry>,
1286	now: &'a TreeState,
1287	path: &str,
1288) -> Option<&'a Version> {
1289	entries.get(path).map(|entry| &entry.version).or_else(|| {
1290		now.by_path
1291			.get(path)
1292			.and_then(|current| current.version.as_ref())
1293	})
1294}
1295
1296/// The version that a copy holds, as reading it tells; `None` if it cannot be read.
1297pub(super) fn copy_version(found: &Found) -> Option<Version> {
1298	match &found.kind {
1299		FoundKind::Link(target) => Some(Version::Link {
1300			target: target.clone(),
1301		}),
1302		FoundKind::File => hash_found(found).ok().map(|content| Version::File {
1303			content,
1304			executable: found.executable.unwrap_or(false),
1305		}),
1306	}
1307}
1308
1309/// Whether a copy holds `recorded`: the same content or target, and where the system keeps
1310/// executable bits, the same bit.
1311pub(super) fn same_version(found: &Found, holds: &Version, recorded: &Version) -> bool {
1312	if found.executable.is_some() {
1313		holds == recorded
1314	} else {
1315		same_content(holds, recorded)
1316	}
1317}
1318
1319/// Whether two versions hold the same content or target, whatever their executable bits.
1320fn same_content(a: &Version, b: &Version) -> bool {
1321	super::compare::same_content(a, b)
1322}
1323
1324/// Writes bytes into the new file `temporary`, which only its owner may read on Unix if
1325/// `private` says so, and saves it to the disk.
1326fn bytes_into(bytes: &[u8], temporary: &Path, private: bool) -> Result<(), String> {
1327	let mut file = new_file(temporary, private).map_err(|error| error.to_string())?;
1328	file.write_all(bytes)
1329		.and_then(|()| file.sync_all())
1330		.map_err(|error| error.to_string())
1331}
1332
1333/// Makes the new file `temporary`, which only its owner may read on Unix if `private` says
1334/// so.
1335fn new_file(temporary: &Path, private: bool) -> io::Result<File> {
1336	let mut options = File::options();
1337	options.write(true).create_new(true);
1338	#[cfg(unix)]
1339	if private {
1340		std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
1341	}
1342	#[cfg(not(unix))]
1343	let _ = private;
1344	options.open(temporary)
1345}
1346
1347/// Makes a file executable, or not, where the system keeps the bit.
1348#[cfg_attr(
1349	not(unix),
1350	expect(clippy::unnecessary_wraps, reason = "it can fail only on Unix")
1351)]
1352fn set_executable(path: &Path, executable: bool) -> Result<(), String> {
1353	#[cfg(unix)]
1354	{
1355		use std::os::unix::fs::PermissionsExt;
1356		let mode = fs::metadata(path)
1357			.map_err(|error| error.to_string())?
1358			.permissions()
1359			.mode();
1360		let mode = if executable {
1361			mode | ((mode & 0o444) >> 2)
1362		} else {
1363			mode & !0o111
1364		};
1365		fs::set_permissions(path, fs::Permissions::from_mode(mode))
1366			.map_err(|error| error.to_string())
1367	}
1368	#[cfg(not(unix))]
1369	{
1370		let _ = (path, executable);
1371		Ok(())
1372	}
1373}
1374
1375/// Makes a symbolic link at `at` to `target`, as it was written; where the system cannot,
1376/// as Windows without leave, says so.
1377fn make_link(target: &str, at: &Path) -> Result<(), String> {
1378	#[cfg(unix)]
1379	{
1380		std::os::unix::fs::symlink(target, at).map_err(|error| error.to_string())
1381	}
1382	#[cfg(windows)]
1383	{
1384		std::os::windows::fs::symlink_file(target.replace('/', "\\"), at)
1385			.map_err(|error| format!("this system made no link: {error}"))
1386	}
1387	#[cfg(not(any(unix, windows)))]
1388	{
1389		let _ = (target, at);
1390		Err("this system makes no links".to_owned())
1391	}
1392}