Skip to main content

nibkeep_node/library/trees/
repositories.rs

1//! The Git repositories in a tree: references, recorded by their remotes, branches, the
2//! remote that a branch follows, and the commit only if the person pinned it, as `nib` reads
3//! them from the person's own Git; never file by file. The engine knows nothing of Git: it
4//! records what `nib` gives it, with no credential, and says what a clone may take from what
5//! other devices recorded ([technical design: trees]).
6//!
7//! Each copy keeps what Git said of each repository when it last recorded or cloned it, so
8//! that a commit records only what changed here since: devices whose clones differ, as one
9//! that took fewer remotes, never undo each other's records.
10//!
11//! [technical design: trees]: ../../../../../docs/Technical-design.md#15-trees
12
13use std::collections::{BTreeMap, BTreeSet};
14use std::fs;
15use std::path::{Path, PathBuf};
16
17use getrandom::SysRng;
18use getrandom::rand_core::UnwrapErr;
19use nibkeep_base::{EntityId, SpaceId, StatementId};
20use nibkeep_crypto::rand_core::CryptoRng;
21use nibkeep_model::storage::Statements;
22use nibkeep_model::{FieldName, Name, Operation, State, Value, fields};
23use nibkeep_std::{
24	GIT_BRANCH, GIT_COMMIT, GIT_REMOTE, GIT_REPOSITORY, GIT_UPSTREAM, IN_TREE, TREE_PATH,
25};
26
27use super::commit::{clearing, deleting, moving, replacing};
28use super::git::{cloneable, is_commit, is_safe_name, recordable_address};
29use super::index::Index;
30use super::locate::{Blocked, Located, located, place_for_new};
31use super::walk::walk;
32use super::{Change, Committed, TREE_TYPES, TreeChange, is_safe_tree_path, tree_entities};
33use crate::NodeError;
34use crate::library::Library;
35use crate::library::entities::NewValue;
36use crate::library::policies;
37
38/// What Git says of a repository in a tree's copy: what `nib` reads from the person's Git,
39/// and gives a commit to record.
40#[derive(Clone, Debug, PartialEq, Eq)]
41pub struct GitRepository {
42	/// The folder that holds it, as a path in the tree.
43	pub path: String,
44	/// Its remotes, each by its name and address, credentials and all: a commit takes them
45	/// out.
46	pub remotes: Vec<(String, String)>,
47	/// The branch it has checked out, if any.
48	pub branch: Option<String>,
49	/// The name of the remote that the branch follows, if it follows one.
50	pub upstream: Option<String>,
51	/// The commit it has checked out, in full, which a commit records if it is pinned.
52	pub commit: Option<String>,
53}
54
55/// A Git repository that a tree records.
56#[derive(Clone, Debug, PartialEq, Eq)]
57pub struct RecordedRepository {
58	/// Its entity.
59	pub entity: EntityId,
60	/// Its folder, as a path in the tree.
61	pub path: String,
62	/// Its remotes, each by its name and address, ordered by name.
63	pub remotes: Vec<(String, String)>,
64	/// Its branch.
65	pub branch: Option<String>,
66	/// The remote that its branch follows.
67	pub upstream: Option<String>,
68	/// The commit it is pinned at, if the person pinned it.
69	pub pinned: Option<String>,
70	/// Whether this device's copy of the tree holds it.
71	pub here: bool,
72}
73
74/// A repository that this device's copy of a tree does not hold: what a clone would take,
75/// and where it comes from, or why it may not be cloned.
76#[derive(Clone, Debug, PartialEq, Eq)]
77pub struct ToClone {
78	/// Its entity, which [`Library::prepare_clone`] and [`Library::repository_cloned`] take.
79	pub entity: EntityId,
80	/// Its folder, as a path in the tree.
81	pub path: String,
82	/// The remote to clone from: of those a clone may take, the one its branch follows, or
83	/// else `origin`, or else the first by name.
84	pub remote: String,
85	/// That remote's address.
86	pub address: String,
87	/// The other remotes to add, those a clone may take.
88	pub others: Vec<(String, String)>,
89	/// The branch to check out.
90	pub branch: Option<String>,
91	/// The commit to check out the branch at, if it is pinned.
92	pub pinned: Option<String>,
93	/// The device whose replica recorded the address, as the space names it.
94	pub recorded_by: String,
95	/// Why it may not be cloned, if it may not.
96	pub refused: Option<String>,
97}
98
99/// The folder that a clone goes into, made empty, with the folders made for it: what to
100/// remove, from the innermost, if the clone fails.
101#[derive(Clone, Debug, PartialEq, Eq)]
102pub struct CloneFolder {
103	/// The folder, empty.
104	pub folder: PathBuf,
105	/// The folders made to hold it, from the outermost, none of which was there.
106	pub made: Vec<PathBuf>,
107}
108
109/// A repository as the space records it, with the statements that say so.
110#[derive(Clone, Debug)]
111pub(super) struct Recorded {
112	pub(super) entity: EntityId,
113	pub(super) path: String,
114	/// Its remotes, by name, each with every address recorded for it and its statement,
115	/// competing values too, the smallest statement's first: the one a clone takes.
116	remotes: BTreeMap<String, Vec<(String, StatementId)>>,
117	branch: Option<String>,
118	upstream: Option<String>,
119	pinned: Option<String>,
120	/// Every statement that says what it is, where, or what a clone takes: who made them
121	/// tells whether a clone may trust them.
122	statements: Vec<StatementId>,
123}
124
125/// What Git said of a repository when this copy last recorded or cloned it: what a commit
126/// tells what changed here from.
127#[derive(Clone, Debug, Default, PartialEq, Eq)]
128struct Snapshot {
129	remotes: BTreeMap<String, String>,
130	branch: Option<String>,
131	upstream: Option<String>,
132	head: Option<String>,
133}
134
135impl Snapshot {
136	/// What Git says now.
137	fn of(repository: &GitRepository) -> Self {
138		let remotes = recordable_remotes(repository);
139		// Git takes an address there too: only a remote's name is recorded.
140		let upstream = repository
141			.upstream
142			.clone()
143			.filter(|upstream| remotes.contains_key(upstream));
144		Self {
145			remotes,
146			branch: repository.branch.clone(),
147			upstream,
148			head: repository.commit.clone(),
149		}
150	}
151
152	/// As the index keeps it: a line for each remote, then the branch, upstream and commit,
153	/// none of which holds a line break.
154	fn to_record(&self) -> String {
155		let mut lines: Vec<String> = self
156			.remotes
157			.iter()
158			.map(|(name, address)| format!("remote {name} {address}"))
159			.collect();
160		for (key, value) in [
161			("branch", &self.branch),
162			("upstream", &self.upstream),
163			("head", &self.head),
164		] {
165			if let Some(value) = value.as_ref().filter(|value| !value.contains('\n')) {
166				lines.push(format!("{key} {value}"));
167			}
168		}
169		lines.join("\n")
170	}
171
172	/// As the index keeps it.
173	fn from_record(record: &str) -> Self {
174		let mut snapshot = Self::default();
175		for line in record.lines() {
176			let Some((key, rest)) = line.split_once(' ') else {
177				continue;
178			};
179			match key {
180				"remote" => {
181					if let Some((name, address)) = rest.split_once(' ') {
182						snapshot.remotes.insert(name.to_owned(), address.to_owned());
183					}
184				}
185				"branch" => snapshot.branch = Some(rest.to_owned()),
186				"upstream" => snapshot.upstream = Some(rest.to_owned()),
187				"head" => snapshot.head = Some(rest.to_owned()),
188				_ => {}
189			}
190		}
191		snapshot
192	}
193}
194
195/// What a commit records of a tree's repositories, and what it changes in the index.
196#[derive(Default)]
197pub(super) struct Plan {
198	/// What it records, by the repository each is about.
199	pub(super) operations: Vec<(EntityId, Vec<Operation>)>,
200	pub(super) changes: Vec<TreeChange>,
201	/// The repositories this copy holds after it, by path, with what Git said of each.
202	pub(super) hold: Vec<(String, EntityId, String)>,
203	/// The paths of repositories it no longer holds.
204	pub(super) forget: Vec<String>,
205}
206
207/// Where a commit's plan of repositories looks: the copy's folder, the folders apart, and
208/// the paths chosen, all of them if empty.
209pub(super) struct Scope<'a> {
210	pub(super) root: &'a Path,
211	pub(super) apart: &'a [PathBuf],
212	pub(super) paths: &'a [String],
213}
214
215/// The repositories that a tree records, by their entities, in the order of their paths.
216pub(super) fn read_repositories<S: Statements>(
217	state: &State<S>,
218	tree: EntityId,
219	entities: &[EntityId],
220) -> Result<Vec<Recorded>, NodeError>
221where
222	NodeError: From<S::Error>,
223{
224	let tree = state.canonical(tree)?;
225	let mut recorded = Vec::new();
226	for &entity in entities {
227		if !state.types(entity)?.contains(&GIT_REPOSITORY) || state.is_deleted(entity)? {
228			continue;
229		}
230		let mut in_tree = false;
231		for statement in state.current(entity, &IN_TREE)? {
232			if let Value::Reference(of) = statement.value {
233				in_tree |= state.canonical(of)? == tree;
234			}
235		}
236		if !in_tree {
237			continue;
238		}
239		let first = |field: &FieldName| -> Result<Option<String>, NodeError> {
240			let mut statements = state.current(entity, field)?;
241			statements.sort_by_key(|statement| statement.id);
242			Ok(statements
243				.into_iter()
244				.find_map(|statement| match &statement.value {
245					Value::Text(text) => Some(text.clone()),
246					_ => None,
247				}))
248		};
249		let Some(path) = first(&TREE_PATH)? else {
250			continue;
251		};
252		let mut remotes: BTreeMap<String, Vec<(String, StatementId)>> = BTreeMap::new();
253		let mut current = state.current(entity, &GIT_REMOTE)?;
254		current.sort_by_key(|statement| statement.id);
255		for statement in current {
256			if let Value::Text(text) = &statement.value
257				&& let Some((name, address)) = text.split_once(' ')
258			{
259				remotes
260					.entry(name.to_owned())
261					.or_default()
262					.push((address.to_owned(), statement.id));
263			}
264		}
265		let mut statements = Vec::new();
266		for field in [
267			IN_TREE,
268			TREE_PATH,
269			GIT_REMOTE,
270			GIT_BRANCH,
271			GIT_UPSTREAM,
272			GIT_COMMIT,
273		] {
274			statements.extend(
275				state
276					.current(entity, &field)?
277					.iter()
278					.map(|statement| statement.id),
279			);
280		}
281		recorded.push(Recorded {
282			entity,
283			path,
284			remotes,
285			branch: first(&GIT_BRANCH)?,
286			upstream: first(&GIT_UPSTREAM)?,
287			pinned: first(&GIT_COMMIT)?,
288			statements,
289		});
290	}
291	recorded.sort_by(|a, b| a.path.cmp(&b.path));
292	Ok(recorded)
293}
294
295/// The remotes of what Git says, as they are recorded: with no credential, by name, and
296/// none whose name could not be told from its address, nor any with a control character.
297fn recordable_remotes(repository: &GitRepository) -> BTreeMap<String, String> {
298	let plain = |text: &str| !text.chars().any(char::is_control);
299	repository
300		.remotes
301		.iter()
302		.filter(|(name, address)| {
303			!name.is_empty() && !name.contains(char::is_whitespace) && plain(name) && plain(address)
304		})
305		.map(|(name, address)| (name.clone(), recordable_address(address)))
306		.filter(|(_, address)| !address.contains(char::is_whitespace))
307		.collect()
308}
309
310/// Adds to `plan` what records what changed of a repository here since `before`: remotes
311/// added, changed or removed here, the branch and upstream if they changed here, and the
312/// commit of a pinned one if it moved here. What changed elsewhere stays.
313fn changed<S: Statements>(
314	state: &State<S>,
315	(recorded, repository, before): (&Recorded, &GitRepository, &Snapshot),
316	plan: &mut Plan,
317	rng: &mut impl CryptoRng,
318) -> Result<(), NodeError>
319where
320	NodeError: From<S::Error>,
321{
322	let entity = recorded.entity;
323	let now = Snapshot::of(repository);
324	let mut operations = Vec::new();
325	// Only the remotes added, changed or removed here: other devices' stay, competing
326	// values too, unless this one records the name again.
327	let mut retracted = Vec::new();
328	for (name, address) in &now.remotes {
329		if before.remotes.get(name) == Some(address) {
330			continue;
331		}
332		let values = recorded.remotes.get(name).map_or_default(Vec::as_slice);
333		retracted.extend(
334			values
335				.iter()
336				.filter(|(other, _)| other != address)
337				.map(|(_, statement)| *statement),
338		);
339		if !values.iter().any(|(other, _)| other == address) {
340			let value = Value::Text(format!("{name} {address}"));
341			operations.push(policies::assert(entity, GIT_REMOTE, value, rng));
342		}
343	}
344	for name in before.remotes.keys() {
345		if !now.remotes.contains_key(name)
346			&& let Some(values) = recorded.remotes.get(name)
347		{
348			retracted.extend(values.iter().map(|(_, statement)| *statement));
349		}
350	}
351	if !retracted.is_empty() {
352		operations.push(Operation::retract(entity, retracted));
353	}
354	for (field, here, then, recorded) in [
355		(GIT_BRANCH, &now.branch, &before.branch, &recorded.branch),
356		(
357			GIT_UPSTREAM,
358			&now.upstream,
359			&before.upstream,
360			&recorded.upstream,
361		),
362	] {
363		if here != then && here != recorded {
364			match here {
365				Some(value) => {
366					let value = Value::Text(value.clone());
367					operations.push(replacing(state, entity, field, value, rng)?);
368				}
369				None => operations.extend(clearing(state, entity, &field)?),
370			}
371		}
372	}
373	if recorded.pinned.is_some()
374		&& let Some(commit) = now.head.as_ref().filter(|commit| is_commit(commit))
375		&& before.head.as_ref() != Some(commit)
376		&& recorded.pinned.as_ref() != Some(commit)
377	{
378		let value = Value::Text(commit.clone());
379		operations.push(replacing(state, entity, GIT_COMMIT, value, rng)?);
380	}
381	if !operations.is_empty() {
382		plan.operations.push((entity, operations));
383		plan.changes.push(TreeChange {
384			path: repository.path.clone(),
385			change: Change::Edited,
386		});
387	}
388	Ok(())
389}
390
391/// Whether a path of a tree is inside a folder that holds a Git repository here, or that
392/// the tree records as one, or one the index marks: a clone never goes into another.
393fn inside_repository(
394	root: &Path,
395	path: &str,
396	(recorded, marked): (&[Recorded], &BTreeMap<String, String>),
397) -> bool {
398	folders_of(path).any(|folder| {
399		marked.contains_key(folder)
400			|| recorded.iter().any(|other| other.path == folder)
401			|| fs::symlink_metadata(root.join(folder).join(".git")).is_ok()
402	})
403}
404
405/// Whether the repository this copy held at `path` is surely gone from here, as the disk
406/// says: no folder there, or one with no `.git` any longer. A folder that cannot be
407/// read says nothing.
408fn gone_here(scope: &Scope<'_>, path: &str) -> bool {
409	match located(scope.root, path, scope.apart) {
410		Located::Absent => true,
411		Located::Here(folder) => {
412			fs::symlink_metadata(&folder).is_ok_and(|metadata| metadata.is_dir())
413				&& matches!(
414					fs::symlink_metadata(folder.join(".git")),
415					Err(error) if error.kind() == std::io::ErrorKind::NotFound
416				)
417		}
418		Located::Unknown(_) => false,
419	}
420}
421
422/// The last name of a tree's path.
423fn last_name(path: &str) -> &str {
424	path.rsplit('/').next().unwrap_or(path)
425}
426
427/// The folders that hold `path` in a tree, from the outermost.
428fn folders_of(path: &str) -> impl Iterator<Item = &str> {
429	path.match_indices('/').map(move |(at, _)| &path[..at])
430}
431
432/// Whether `path` is one of `paths`, or in a folder that one of them names.
433fn within(path: &str, paths: &[String]) -> bool {
434	paths.is_empty()
435		|| paths.iter().any(|given| {
436			given.is_empty() || path == given || path.starts_with(&format!("{given}/"))
437		})
438}
439
440impl Library {
441	/// The repositories that a tree records, in the order of their paths, each with whether
442	/// this device's copy holds it.
443	///
444	/// # Errors
445	///
446	/// Returns an error if the space or the index cannot be read.
447	pub fn tree_repositories(
448		&self,
449		space: SpaceId,
450		tree: EntityId,
451	) -> Result<Vec<RecordedRepository>, NodeError> {
452		let held: BTreeSet<EntityId> = match self.index_if_any()? {
453			Some(index) => index
454				.repositories(tree)?
455				.into_values()
456				.map(|(entity, _)| entity)
457				.collect(),
458			None => BTreeSet::new(),
459		};
460		Ok(self
461			.recorded_repositories(space, tree)?
462			.into_iter()
463			.map(|recorded| RecordedRepository {
464				entity: recorded.entity,
465				here: held.contains(&recorded.entity),
466				path: recorded.path,
467				remotes: recorded
468					.remotes
469					.into_iter()
470					.filter_map(|(name, values)| {
471						values
472							.into_iter()
473							.next()
474							.map(|(address, _)| (name, address))
475					})
476					.collect(),
477				branch: recorded.branch,
478				upstream: recorded.upstream,
479				pinned: recorded.pinned,
480			})
481			.collect())
482	}
483
484	/// The folders of the copy of a tree on this device that hold Git repositories, by
485	/// their paths in the tree: what `nib` asks Git about before a commit. The folder is
486	/// walked, and nothing is read.
487	///
488	/// # Errors
489	///
490	/// Returns [`NodeError::NoTreeHere`] if the tree has no folder on this device, and an
491	/// error if the space or the index cannot be read.
492	pub fn tree_repository_folders(
493		&self,
494		space: SpaceId,
495		tree: EntityId,
496	) -> Result<Vec<String>, NodeError> {
497		let root = self.root_here(space, tree)?;
498		let index = self.index()?;
499		let left_out = self.left_out(space, tree, &root, &index)?;
500		Ok(walk(&root, &left_out, &self.apart()).repositories)
501	}
502
503	/// The repositories that a tree records, as the space says.
504	pub(super) fn recorded_repositories(
505		&self,
506		space: SpaceId,
507		tree: EntityId,
508	) -> Result<Vec<Recorded>, NodeError> {
509		let open = self.space(space)?;
510		open.stored.reading(|stored| {
511			let state = stored.log().state();
512			let entities = tree_entities(state, tree)?;
513			read_repositories(state, tree, &entities)
514		})
515	}
516
517	/// What a commit would record of a tree's repositories, for a status: of those `found`
518	/// in the copy, what Git says of them, in `described`, as [`Library::commit_tree`]
519	/// records it with [`Commit::with_repositories`](super::Commit::with_repositories).
520	///
521	/// # Errors
522	///
523	/// Returns [`NodeError::NoTreeHere`] if the tree has no folder on this device, and an
524	/// error if the space or the index cannot be read.
525	pub fn repository_changes(
526		&self,
527		space: SpaceId,
528		tree: EntityId,
529		(found, described): (&[String], &[GitRepository]),
530	) -> Result<Vec<TreeChange>, NodeError> {
531		let root = self.root_here(space, tree)?;
532		let apart = self.apart();
533		let index = self.index()?;
534		let scope = Scope {
535			root: &root,
536			apart: &apart,
537			paths: &[],
538		};
539		// The statements it would make are thrown away: any randomness will do.
540		let mut rng = UnwrapErr(SysRng);
541		let plan =
542			self.plan_repositories(space, (tree, &index, &scope), (found, described), &mut rng)?;
543		Ok(plan.changes)
544	}
545
546	/// What a commit records of a tree's repositories: of those `found` in the copy, what
547	/// Git says of them, in `described`, against what the tree records and what this copy
548	/// last recorded or cloned of each. A repository found that Git did not describe stays
549	/// as it is. One this copy held whose folder is surely gone, or no longer holds a
550	/// repository, moved, if one found new has the remotes it had, or else is deleted; a
551	/// move counts if either of its ends is chosen, as a file's does. One found where this
552	/// copy held a repository that moved or was deleted elsewhere is left for the person.
553	pub(super) fn plan_repositories(
554		&self,
555		space: SpaceId,
556		(tree, index, scope): (EntityId, &Index, &Scope<'_>),
557		(found, described): (&[String], &[GitRepository]),
558		rng: &mut impl CryptoRng,
559	) -> Result<Plan, NodeError> {
560		let recorded = self.recorded_repositories(space, tree)?;
561		let by_path: BTreeMap<&str, &Recorded> = recorded
562			.iter()
563			.map(|recorded| (recorded.path.as_str(), recorded))
564			.collect();
565		let by_entity: BTreeMap<EntityId, &Recorded> = recorded
566			.iter()
567			.map(|recorded| (recorded.entity, recorded))
568			.collect();
569		let held = index.repositories(tree)?;
570		let found: BTreeSet<&str> = found.iter().map(String::as_str).collect();
571		let mut plan = Plan::default();
572		let mut new = Vec::new();
573		let open = self.space(space)?;
574		let state = open.stored.log().state();
575		for repository in described {
576			let path = repository.path.as_str();
577			if !found.contains(path) || !is_safe_tree_path(path) {
578				continue;
579			}
580			let now = Snapshot::of(repository).to_record();
581			if let Some((entity, record)) = held.get(path) {
582				// Moved or deleted elsewhere: the person settles it, not a commit.
583				if let Some(recorded) = by_entity
584					.get(entity)
585					.filter(|recorded| recorded.path == path)
586					&& within(path, scope.paths)
587				{
588					let before = Snapshot::from_record(record);
589					changed(state, (recorded, repository, &before), &mut plan, rng)?;
590					plan.hold.push((path.to_owned(), *entity, now));
591				}
592				continue;
593			}
594			match by_path.get(path) {
595				// Where the tree records it, as a clone made outside NibKeep or a lost index
596				// leaves it: held from now on, and nothing recorded.
597				Some(recorded) => plan.hold.push((path.to_owned(), recorded.entity, now)),
598				None => new.push(repository),
599			}
600		}
601		for (path, (entity, record)) in &held {
602			if found.contains(path.as_str()) || !gone_here(scope, path) {
603				continue;
604			}
605			let recorded = by_entity
606				.get(entity)
607				.filter(|recorded| recorded.path == *path);
608			let before = Snapshot::from_record(record);
609			let moved = recorded.and_then(|_| {
610				new.iter().position(|repository| {
611					!before.remotes.is_empty() && recordable_remotes(repository) == before.remotes
612				})
613			});
614			let chosen = |other: &str| within(path, scope.paths) || within(other, scope.paths);
615			match (recorded, moved) {
616				(Some(recorded), Some(position)) if chosen(&new[position].path) => {
617					let repository = new.remove(position);
618					plan.forget.push(path.clone());
619					let mut operations = moving(state, *entity, path, &repository.path, rng)?;
620					let mut edits = Plan::default();
621					changed(state, (recorded, repository, &before), &mut edits, rng)?;
622					operations.extend(edits.operations.into_iter().flat_map(|(_, edits)| edits));
623					plan.operations.push((*entity, operations));
624					let now = Snapshot::of(repository).to_record();
625					plan.hold.push((repository.path.clone(), *entity, now));
626					plan.changes.push(TreeChange {
627						path: repository.path.clone(),
628						change: Change::Moved { from: path.clone() },
629					});
630				}
631				// A move to a place not chosen waits for a commit that chooses it.
632				(Some(_), Some(position)) => {
633					new.remove(position);
634				}
635				(Some(_), None) if within(path, scope.paths) => {
636					plan.forget.push(path.clone());
637					plan.operations
638						.push((*entity, vec![deleting(*entity, rng)]));
639					plan.changes.push(TreeChange {
640						path: path.clone(),
641						change: Change::Deleted,
642					});
643				}
644				(None, _) if within(path, scope.paths) => plan.forget.push(path.clone()),
645				(Some(_) | None, _) => {}
646			}
647		}
648		for repository in new {
649			if !within(&repository.path, scope.paths) {
650				continue;
651			}
652			let (entity, operations) = self.new_repository(space, tree, repository, rng)?;
653			plan.operations.push((entity, operations));
654			let now = Snapshot::of(repository).to_record();
655			plan.hold.push((repository.path.clone(), entity, now));
656			plan.changes.push(TreeChange {
657				path: repository.path.clone(),
658				change: Change::New,
659			});
660		}
661		plan.changes.sort_by(|a, b| a.path.cmp(&b.path));
662		Ok(plan)
663	}
664
665	/// The operations that record a repository found new.
666	fn new_repository(
667		&self,
668		space: SpaceId,
669		tree: EntityId,
670		repository: &GitRepository,
671		rng: &mut impl CryptoRng,
672	) -> Result<(EntityId, Vec<Operation>), NodeError> {
673		let mut values = vec![
674			NewValue::new(
675				fields::NAME,
676				Value::Name(Name::new(last_name(&repository.path))),
677			),
678			NewValue::new(IN_TREE, Value::Reference(tree)),
679			NewValue::new(TREE_PATH, Value::Text(repository.path.clone())),
680		];
681		let said = Snapshot::of(repository);
682		for (name, address) in &said.remotes {
683			values.push(NewValue::new(
684				GIT_REMOTE,
685				Value::Text(format!("{name} {address}")),
686			));
687		}
688		if let Some(branch) = said.branch {
689			values.push(NewValue::new(GIT_BRANCH, Value::Text(branch)));
690		}
691		if let Some(upstream) = said.upstream {
692			values.push(NewValue::new(GIT_UPSTREAM, Value::Text(upstream)));
693		}
694		self.new_entity(space, &[GIT_REPOSITORY], values, rng)
695	}
696
697	/// Pins the repository at `path` of a tree at `commit`, a full commit as Git names it,
698	/// or with `None` takes its pin away, as a revision of its own: a pinned repository is
699	/// cloned at that commit, and commits keep it as Git says it is.
700	///
701	/// # Errors
702	///
703	/// Returns [`NodeError::NoRepository`] if the tree records no repository at `path`,
704	/// [`NodeError::NotACommit`] if `commit` is no full commit, and an error if saving
705	/// fails.
706	pub fn pin_repository(
707		&mut self,
708		space: SpaceId,
709		tree: EntityId,
710		path: &str,
711		commit: Option<&str>,
712		wall_millis: u64,
713		rng: &mut impl CryptoRng,
714	) -> Result<Committed, NodeError> {
715		self.check_not_revoked(space)?;
716		let _locked = self.lock_trees()?;
717		let recorded = self
718			.recorded_repositories(space, tree)?
719			.into_iter()
720			.find(|recorded| recorded.path == path)
721			.ok_or_else(|| NodeError::NoRepository(path.to_owned()))?;
722		if let Some(commit) = commit
723			&& !is_commit(commit)
724		{
725			return Err(NodeError::NotACommit(commit.to_owned()));
726		}
727		if recorded.pinned.as_deref() == commit {
728			return Ok(Committed::default());
729		}
730		self.install_standard(space, &TREE_TYPES, wall_millis, rng)?;
731		let operations = {
732			let state = self.space(space)?.stored.log().state();
733			match commit {
734				Some(commit) => {
735					let value = Value::Text(commit.to_owned());
736					vec![replacing(state, recorded.entity, GIT_COMMIT, value, rng)?]
737				}
738				None => clearing(state, recorded.entity, &GIT_COMMIT)?,
739			}
740		};
741		let message = match commit {
742			Some(commit) => format!("Pin {path} at {}", &commit[..12]),
743			None => format!("Unpin {path}"),
744		};
745		// A commit of two parts, saved all or none: its revision, and the pin (technical design:
746		// one entity per change).
747		let revision = self.batch_whole(space, |library| {
748			let (revision, made) =
749				library.revision_operations(space, tree, Some(&message), 2, rng)?;
750			library.commit(space, made, wall_millis, rng)?;
751			let entity = recorded.entity;
752			let operations = library.part_operations(space, revision, entity, operations, rng)?;
753			library.commit(space, operations, wall_millis, rng)?;
754			Ok(revision)
755		})?;
756		Ok(Committed {
757			revision: Some(revision),
758			parts: 2,
759			changes: Vec::new(),
760			repositories: vec![TreeChange {
761				path: path.to_owned(),
762				change: Change::Edited,
763			}],
764			..Committed::default()
765		})
766	}
767
768	/// The repositories that a tree records and this device's copy does not hold, whose
769	/// folders are not there: what writing or updating the copy would clone, each with the
770	/// remote it comes from and the device that recorded it, or why it may not be cloned.
771	/// One deleted here, which the index says the copy held, is not listed.
772	///
773	/// # Errors
774	///
775	/// Returns [`NodeError::NoTreeHere`] if the tree has no folder on this device, and an
776	/// error if the space or the index cannot be read.
777	pub fn repositories_to_clone(
778		&self,
779		space: SpaceId,
780		tree: EntityId,
781	) -> Result<Vec<ToClone>, NodeError> {
782		let root = self.root_here(space, tree)?;
783		let apart = self.apart();
784		let index = self.index()?;
785		let held: BTreeSet<EntityId> = index
786			.repositories(tree)?
787			.into_values()
788			.map(|(entity, _)| entity)
789			.collect();
790		let marked = index.marked(tree)?;
791		let recorded = self.recorded_repositories(space, tree)?;
792		let mut to_clone = Vec::new();
793		for repository in &recorded {
794			if held.contains(&repository.entity) || marked.contains_key(&repository.path) {
795				continue;
796			}
797			// A folder there is left as it is; one inside another repository, or that cannot
798			// be looked at, is listed with why it may not be cloned.
799			let there = is_safe_tree_path(&repository.path)
800				&& matches!(located(&root, &repository.path, &apart), Located::Here(_));
801			if there {
802				continue;
803			}
804			let nested = inside_repository(&root, &repository.path, (&recorded, &marked));
805			to_clone.push(self.to_clone(space, repository, nested));
806		}
807		Ok(to_clone)
808	}
809
810	/// Whether a person's replica made a statement: one that the space lists and has not
811	/// revoked, and no AI agent's. One it cannot tell is not trusted.
812	fn made_by_person(&self, space: SpaceId, statement: StatementId) -> bool {
813		let Ok(open) = self.space(space) else {
814			return false;
815		};
816		open.stored
817			.reading(|stored| -> Result<bool, NodeError> {
818				let log = stored.log();
819				let Some(key) = log.author_of(statement)? else {
820					return Ok(false);
821				};
822				Ok(log.is_listed(&key, &open.keys)?
823					&& !log.is_revoked(&key, &open.keys)?
824					&& !log.is_ai_agent(&key, &open.keys)?)
825			})
826			.unwrap_or(false)
827	}
828
829	/// What a clone of a recorded repository takes, or why it may not: never what an AI
830	/// agent's replica, or one the space does not know, recorded of it.
831	fn to_clone(&self, space: SpaceId, recorded: &Recorded, nested: bool) -> ToClone {
832		let trusted = recorded
833			.statements
834			.iter()
835			.all(|statement| self.made_by_person(space, *statement));
836		let may_take = |name: &str, address: &str| is_safe_name(name) && cloneable(address).is_ok();
837		// The address a clone takes of a remote: of the statement with the smallest ID.
838		let first = |name: &str| {
839			recorded
840				.remotes
841				.get(name)
842				.and_then(|values| values.first())
843				.map(|(address, statement)| (address.clone(), *statement))
844		};
845		// Of the remotes a clone may take: the one the branch follows, or else `origin`, or
846		// else the first by name.
847		let preferred: Vec<&String> = recorded
848			.upstream
849			.iter()
850			.filter(|upstream| recorded.remotes.contains_key(*upstream))
851			.chain(
852				recorded
853					.remotes
854					.get_key_value("origin")
855					.map(|(name, _)| name),
856			)
857			.chain(recorded.remotes.keys())
858			.collect();
859		let chosen = preferred
860			.iter()
861			.find(|name| first(name).is_some_and(|(address, _)| may_take(name, &address)))
862			.or_else(|| preferred.first())
863			.map(|name| (*name).clone());
864		let (remote, address, statement) = match chosen
865			.as_ref()
866			.and_then(|name| first(name).map(|first| (name, first)))
867		{
868			Some((name, (address, statement))) => (name.clone(), address.clone(), Some(statement)),
869			None => (String::new(), String::new(), None),
870		};
871		let refused = if statement.is_none() {
872			Some("it has no remote".to_owned())
873		} else if !is_safe_tree_path(&recorded.path) || recorded.path.contains(char::is_control) {
874			Some("its path is not one a tree may hold".to_owned())
875		} else if !trusted {
876			Some(
877				"an AI agent's replica, or one this library does not know, recorded part of it"
878					.to_owned(),
879			)
880		} else if nested {
881			Some("it is inside another Git repository".to_owned())
882		} else if let Err(why) = cloneable(&address) {
883			Some(why.to_owned())
884		} else if !is_safe_name(&remote) {
885			Some("its remote's name could be read as an option".to_owned())
886		} else if recorded
887			.branch
888			.as_ref()
889			.is_some_and(|branch| !is_safe_name(branch))
890		{
891			Some("its branch's name could be read as an option".to_owned())
892		} else if recorded
893			.pinned
894			.as_ref()
895			.is_some_and(|pinned| !is_commit(pinned))
896		{
897			Some("its pinned commit is not one".to_owned())
898		} else {
899			None
900		};
901		let others = recorded
902			.remotes
903			.keys()
904			.filter(|name| **name != remote)
905			.filter_map(|name| first(name).map(|(other, _)| (name.clone(), other)))
906			.filter(|(name, other)| may_take(name, other))
907			.collect();
908		let recorded_by = statement
909			.and_then(|statement| self.device_name_of(space, statement))
910			.unwrap_or_else(|| "elsewhere".to_owned());
911		ToClone {
912			entity: recorded.entity,
913			path: recorded.path.clone(),
914			remote,
915			address,
916			others,
917			branch: recorded.branch.clone(),
918			pinned: recorded.pinned.clone(),
919			recorded_by,
920			refused,
921		}
922	}
923
924	/// Makes the folder that a clone goes into, empty, once its place is checked as a file's
925	/// is, parents and all: never through a link, outside the tree's folder, into `.nib`, a
926	/// `.git` or the library's own folder, nor inside another Git repository. What the tree
927	/// records must still be what `to` says, as the person agreed to it.
928	///
929	/// # Errors
930	///
931	/// Returns [`NodeError::RepositoryChanged`] if the record is no longer what `to` says,
932	/// or a clone may not take it now, [`NodeError::UnsafePath`] if its place is no safe
933	/// one, [`NodeError::PlaceTaken`] if something is there, and an error if a folder cannot
934	/// be made.
935	pub fn prepare_clone(
936		&self,
937		space: SpaceId,
938		tree: EntityId,
939		to: &ToClone,
940	) -> Result<CloneFolder, NodeError> {
941		let _locked = self.lock_trees()?;
942		let root = self.root_here(space, tree)?;
943		let apart = self.apart();
944		let all = self.recorded_repositories(space, tree)?;
945		let marked = self.index()?.marked(tree)?;
946		let changed = || NodeError::RepositoryChanged(to.path.clone());
947		let recorded = all
948			.iter()
949			.find(|recorded| recorded.entity == to.entity)
950			.ok_or_else(changed)?;
951		let path = recorded.path.as_str();
952		let nested = inside_repository(&root, path, (&all, &marked));
953		// As it was asked about, and still one a clone may take.
954		let now = self.to_clone(space, recorded, nested);
955		if now != *to || now.refused.is_some() {
956			return Err(changed());
957		}
958		if !is_safe_tree_path(path) || path.contains(char::is_control) {
959			return Err(NodeError::UnsafePath(path.to_owned()));
960		}
961		let blocked = |why| match why {
962			Blocked::Taken => NodeError::PlaceTaken(root.join(path)),
963			Blocked::Unsafe => NodeError::UnsafePath(path.to_owned()),
964		};
965		let target = place_for_new(&root, path, &apart).map_err(blocked)?;
966		let mut made: Vec<PathBuf> = target
967			.ancestors()
968			.skip(1)
969			.take_while(|folder| folder.starts_with(&root) && *folder != root)
970			.filter(|folder| fs::symlink_metadata(folder).is_err())
971			.map(Path::to_path_buf)
972			.collect();
973		made.reverse();
974		if let Some(parent) = target.parent() {
975			fs::create_dir_all(parent).map_err(NodeError::file(parent))?;
976		}
977		// What made the folders may have raced a link into them.
978		if place_for_new(&root, path, &apart).map_err(blocked)? != target {
979			return Err(NodeError::UnsafePath(path.to_owned()));
980		}
981		fs::create_dir(&target).map_err(|error| match error.kind() {
982			std::io::ErrorKind::AlreadyExists => NodeError::PlaceTaken(target.clone()),
983			_ => NodeError::file(&target)(error),
984		})?;
985		Ok(CloneFolder {
986			folder: target,
987			made,
988		})
989	}
990
991	/// Notes that this device's copy of a tree holds the repository that `to` names, as a
992	/// clone made it at its path, with what Git says of the clone, `described`: no longer
993	/// one to clone, and one whose folder gone later is deleted.
994	///
995	/// # Errors
996	///
997	/// Returns [`NodeError::RepositoryChanged`] if the tree no longer records it at that
998	/// path, as when another device moved or deleted it meanwhile, and an error if the index
999	/// cannot be written.
1000	pub fn repository_cloned(
1001		&self,
1002		space: SpaceId,
1003		tree: EntityId,
1004		(to, described): (&ToClone, &GitRepository),
1005	) -> Result<(), NodeError> {
1006		let _locked = self.lock_trees()?;
1007		let still = self
1008			.recorded_repositories(space, tree)?
1009			.into_iter()
1010			.any(|recorded| recorded.entity == to.entity && recorded.path == to.path);
1011		if !still {
1012			return Err(NodeError::RepositoryChanged(to.path.clone()));
1013		}
1014		let record = Snapshot::of(described).to_record();
1015		self.index()?
1016			.hold_repository(tree, &to.path, (to.entity, &record))
1017	}
1018}
1019
1020#[cfg(test)]
1021mod tests {
1022	use super::{GitRepository, Snapshot, folders_of};
1023
1024	#[test]
1025	fn what_git_said_is_kept_and_read_back_as_it_was() {
1026		let said = Snapshot::of(&GitRepository {
1027			path: "proj".to_owned(),
1028			remotes: vec![
1029				(
1030					"origin".to_owned(),
1031					"https://u:t@example.com/p.git".to_owned(),
1032				),
1033				(
1034					"bad name".to_owned(),
1035					"https://example.com/x.git".to_owned(),
1036				),
1037				("lines".to_owned(), "https://example.com/\ny.git".to_owned()),
1038			],
1039			branch: Some("main".to_owned()),
1040			upstream: Some("origin".to_owned()),
1041			commit: Some("a".repeat(40)),
1042		});
1043		assert_eq!(said.remotes.len(), 1);
1044		assert_eq!(said.remotes["origin"], "https://example.com/p.git");
1045		assert_eq!(Snapshot::from_record(&said.to_record()), said);
1046	}
1047
1048	#[test]
1049	fn a_path_s_folders_are_listed_from_the_outermost() {
1050		assert_eq!(folders_of("a/b/c").collect::<Vec<_>>(), ["a", "a/b"]);
1051		assert_eq!(folders_of("c").count(), 0);
1052	}
1053}