1use 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#[derive(Clone, Debug, PartialEq, Eq)]
41pub struct GitRepository {
42 pub path: String,
44 pub remotes: Vec<(String, String)>,
47 pub branch: Option<String>,
49 pub upstream: Option<String>,
51 pub commit: Option<String>,
53}
54
55#[derive(Clone, Debug, PartialEq, Eq)]
57pub struct RecordedRepository {
58 pub entity: EntityId,
60 pub path: String,
62 pub remotes: Vec<(String, String)>,
64 pub branch: Option<String>,
66 pub upstream: Option<String>,
68 pub pinned: Option<String>,
70 pub here: bool,
72}
73
74#[derive(Clone, Debug, PartialEq, Eq)]
77pub struct ToClone {
78 pub entity: EntityId,
80 pub path: String,
82 pub remote: String,
85 pub address: String,
87 pub others: Vec<(String, String)>,
89 pub branch: Option<String>,
91 pub pinned: Option<String>,
93 pub recorded_by: String,
95 pub refused: Option<String>,
97}
98
99#[derive(Clone, Debug, PartialEq, Eq)]
102pub struct CloneFolder {
103 pub folder: PathBuf,
105 pub made: Vec<PathBuf>,
107}
108
109#[derive(Clone, Debug)]
111pub(super) struct Recorded {
112 pub(super) entity: EntityId,
113 pub(super) path: String,
114 remotes: BTreeMap<String, Vec<(String, StatementId)>>,
117 branch: Option<String>,
118 upstream: Option<String>,
119 pinned: Option<String>,
120 statements: Vec<StatementId>,
123}
124
125#[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 fn of(repository: &GitRepository) -> Self {
138 let remotes = recordable_remotes(repository);
139 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 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 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#[derive(Default)]
197pub(super) struct Plan {
198 pub(super) operations: Vec<(EntityId, Vec<Operation>)>,
200 pub(super) changes: Vec<TreeChange>,
201 pub(super) hold: Vec<(String, EntityId, String)>,
203 pub(super) forget: Vec<String>,
205}
206
207pub(super) struct Scope<'a> {
210 pub(super) root: &'a Path,
211 pub(super) apart: &'a [PathBuf],
212 pub(super) paths: &'a [String],
213}
214
215pub(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
295fn 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
310fn 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 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
391fn 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
405fn 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
422fn last_name(path: &str) -> &str {
424 path.rsplit('/').next().unwrap_or(path)
425}
426
427fn folders_of(path: &str) -> impl Iterator<Item = &str> {
429 path.match_indices('/').map(move |(at, _)| &path[..at])
430}
431
432fn 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 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 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 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 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 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 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 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 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 (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 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 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 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 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 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 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 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 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 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 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 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 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 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}