1mod commit;
13mod compare;
14mod diff;
15mod git;
16mod history;
17mod index;
18mod locate;
19mod paths;
20mod repositories;
21mod secrecy;
22mod update;
23mod walk;
24mod write;
25
26use std::cell::RefCell;
27use std::collections::{BTreeMap, BTreeSet};
28use std::fs::{self, File};
29use std::io;
30use std::path::{Path, PathBuf};
31
32use nibkeep_base::{EntityId, Hash, SpaceId};
33use nibkeep_crypto::rand_core::CryptoRng;
34use nibkeep_model::storage::Statements as _;
35use nibkeep_model::{FieldName, Name, Statement, TypeName, Value, fields};
36use nibkeep_std::{
37 COMMITTED_IN, CONTENT, EXECUTABLE, FILE, GIT_REPOSITORY, IN_TREE, LINK_TARGET, ON_DEVICE,
38 PARTS, PATH, REVISION, ROOT_OF, SECRET_CONTENT, SECRET_FILE, SYMBOLIC_LINK, TREE, TREE_PATH,
39 TREE_ROOT,
40};
41
42use nibkeep_log::{ChangeId, Log};
43use nibkeep_store::{LogFile, StateFile};
44
45use self::commit::moving;
46use self::index::{Entry, INDEX_CONTEXT, Index, SecretVersions, Version};
47use self::locate::{Blocked, Listings, Located, located, located_in, place_for_new};
48pub use self::repositories::{CloneFolder, GitRepository, RecordedRepository, ToClone};
49use super::Library;
50use super::entities::NewValue;
51use crate::NodeError;
52
53pub use self::diff::FileDiff;
54pub use self::history::{BlameLine, TreeLogEntry, TreePoint};
55pub use self::paths::is_safe_tree_path;
56pub use self::update::Updated;
57pub use self::write::{CopiesRemoved, Reverted, Written};
58
59const LOCK: &str = "trees.lock";
62
63const TREE_TYPES: [TypeName; 7] = [
65 TREE,
66 TREE_ROOT,
67 FILE,
68 SECRET_FILE,
69 SYMBOLIC_LINK,
70 REVISION,
71 GIT_REPOSITORY,
72];
73
74#[derive(Clone, Debug, PartialEq, Eq)]
76pub struct Tree {
77 pub id: EntityId,
79 pub name: Option<String>,
81 pub root: Option<PathBuf>,
83}
84
85#[derive(Clone, Debug, PartialEq, Eq)]
87pub struct TreeEntry {
88 pub entity: EntityId,
90 pub path: String,
92 pub kind: TreeEntryKind,
94}
95
96#[derive(Clone, Debug, PartialEq, Eq)]
98pub enum TreeEntryKind {
99 File {
101 content: Option<Hash>,
103 executable: bool,
105 },
106 Link {
108 target: String,
110 },
111 Sealed,
116}
117
118#[derive(Clone, Debug, PartialEq, Eq)]
120pub struct TreeChange {
121 pub path: String,
123 pub change: Change,
125}
126
127#[derive(Clone, Debug, PartialEq, Eq)]
129pub enum Change {
130 New,
132 Edited,
135 Executable(bool),
137 Deleted,
139 Moved {
141 from: String,
143 },
144 Unknown,
147}
148
149#[derive(Clone, Debug, PartialEq, Eq)]
152pub struct TreeStatus {
153 pub tree: EntityId,
155 pub root: PathBuf,
157 pub changes: Vec<TreeChange>,
159 pub behind: Vec<String>,
162 pub competing: Vec<String>,
165 pub skipped: Vec<(String, String)>,
167 pub cut_short: Vec<CutShort>,
170 pub read: usize,
172 pub repositories: Vec<String>,
175 pub secret: Vec<String>,
180 pub sealed: Vec<String>,
183}
184
185#[derive(Clone, Debug, Default, PartialEq, Eq)]
190pub struct TreeSecrets {
191 pub secret: Vec<String>,
193 pub sealed: Vec<String>,
195 pub looking_secret: Vec<String>,
198}
199
200#[derive(Clone, Debug, PartialEq, Eq)]
205pub struct InTree {
206 pub tree: EntityId,
208 pub path: Option<String>,
212}
213
214#[derive(Clone, Debug, Default, PartialEq, Eq)]
217pub struct MadeSecret {
218 pub purged: Vec<Hash>,
221 pub kept: Vec<Hash>,
224}
225
226#[derive(Clone, Debug, PartialEq, Eq)]
228pub struct CutShort {
229 pub revision: EntityId,
231 pub parts: u64,
233 pub made: u64,
235}
236
237#[derive(Clone, Debug, PartialEq, Eq)]
239pub struct Commit<'a> {
240 message: Option<&'a str>,
241 paths: Vec<String>,
242 force: bool,
243 cut_after: Option<usize>,
244 repositories: Option<Repositories<'a>>,
245 secret: Vec<String>,
246 ordinary: Vec<String>,
247 leave_secrets: bool,
248}
249
250#[derive(Clone, Copy)]
252enum Repositories<'a> {
253 Given(&'a [GitRepository]),
255 Read(&'a dyn Fn(&[String]) -> Vec<GitRepository>),
257}
258
259impl std::fmt::Debug for Repositories<'_> {
260 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
261 match self {
262 Self::Given(repositories) => {
263 formatter.debug_tuple("Given").field(repositories).finish()
264 }
265 Self::Read(_) => formatter.write_str("Read"),
266 }
267 }
268}
269
270impl PartialEq for Repositories<'_> {
271 fn eq(&self, other: &Self) -> bool {
272 match (self, other) {
273 (Self::Given(a), Self::Given(b)) => a == b,
274 (Self::Read(a), Self::Read(b)) => std::ptr::addr_eq(*a, *b),
275 _ => false,
276 }
277 }
278}
279
280impl Eq for Repositories<'_> {}
281
282impl<'a> Commit<'a> {
283 #[must_use]
285 pub fn new(message: Option<&'a str>) -> Self {
286 Self {
287 message,
288 paths: Vec::new(),
289 force: false,
290 cut_after: None,
291 repositories: None,
292 secret: Vec::new(),
293 ordinary: Vec::new(),
294 leave_secrets: false,
295 }
296 }
297
298 #[must_use]
302 pub fn with_repositories(mut self, repositories: &'a [GitRepository]) -> Self {
303 self.repositories = Some(Repositories::Given(repositories));
304 self
305 }
306
307 #[must_use]
311 pub fn with_repositories_read_by(
312 mut self,
313 read: &'a dyn Fn(&[String]) -> Vec<GitRepository>,
314 ) -> Self {
315 self.repositories = Some(Repositories::Read(read));
316 self
317 }
318
319 #[must_use]
322 pub fn with_paths(mut self, paths: Vec<String>) -> Self {
323 self.paths = paths;
324 self
325 }
326
327 #[must_use]
330 pub fn with_force(mut self) -> Self {
331 self.force = true;
332 self
333 }
334
335 #[must_use]
340 pub fn with_secret(mut self, paths: Vec<String>) -> Self {
341 self.secret = paths;
342 self
343 }
344
345 #[must_use]
347 pub fn with_ordinary(mut self, paths: Vec<String>) -> Self {
348 self.ordinary = paths;
349 self
350 }
351
352 #[must_use]
355 pub fn leaving_secrets(mut self) -> Self {
356 self.leave_secrets = true;
357 self
358 }
359
360 #[must_use]
363 pub fn cut_after(mut self, parts: usize) -> Self {
364 self.cut_after = Some(parts);
365 self
366 }
367}
368
369#[derive(Clone, Debug, Default, PartialEq, Eq)]
371pub struct Committed {
372 pub revision: Option<EntityId>,
374 pub parts: usize,
379 pub changes: Vec<TreeChange>,
381 pub repositories: Vec<TreeChange>,
383 pub secret: Vec<String>,
385 pub left: Vec<String>,
388 pub unprotected: Vec<String>,
391 pub made_secret: Vec<EntityId>,
394}
395
396#[derive(Clone, Debug, PartialEq, Eq)]
398pub struct StartPreview {
399 pub files: usize,
401 pub bytes: u64,
403 pub repositories: Vec<String>,
406}
407
408#[derive(Clone, Debug, PartialEq, Eq)]
410pub struct TreeStarted {
411 pub tree: EntityId,
413 pub root: PathBuf,
415 pub committed: Committed,
417}
418
419#[derive(Clone, Debug)]
421struct Current {
422 entity: EntityId,
423 version: Option<Version>,
425}
426
427#[derive(Debug, Default)]
429struct TreeState {
430 by_path: BTreeMap<String, Current>,
431 by_entity: BTreeMap<EntityId, String>,
432 competing: BTreeSet<String>,
433 deleted: BTreeMap<String, Current>,
436 own: BTreeMap<EntityId, Option<Version>>,
439 versions: BTreeMap<EntityId, Vec<Version>>,
442 paths: BTreeMap<EntityId, Vec<String>>,
445 contested: BTreeMap<EntityId, Vec<String>>,
450 secret: BTreeSet<EntityId>,
452 sealed: BTreeMap<String, EntityId>,
455 secret_paths: BTreeSet<String>,
457}
458
459impl TreeState {
460 fn fill_sealed(&mut self, entries: &BTreeMap<String, Entry>) {
465 for (path, entity) in std::mem::take(&mut self.sealed) {
466 let Some(entry) = entries.values().find(|entry| entry.entity == entity) else {
467 self.sealed.insert(path, entity);
468 continue;
469 };
470 let version = Some(entry.version.clone());
471 self.own.insert(entity, version.clone());
472 if self.by_path.contains_key(&path) {
473 self.competing.insert(path.clone());
474 } else {
475 self.by_path
476 .insert(path.clone(), Current { entity, version });
477 }
478 self.by_entity.insert(entity, path);
479 }
480 }
481
482 fn is_secret(&self, entity: EntityId) -> bool {
484 self.secret.contains(&entity)
485 }
486
487 fn holds(&self, path: &str, entity: EntityId, version: &Version) -> bool {
489 self.at(entity, path) && self.has_version(entity, version)
490 }
491
492 fn at(&self, entity: EntityId, path: &str) -> bool {
494 self.by_entity.get(&entity).is_some_and(|at| at == path)
495 || self
496 .paths
497 .get(&entity)
498 .is_some_and(|paths| paths.iter().any(|at| at == path))
499 }
500
501 fn has_version(&self, entity: EntityId, version: &Version) -> bool {
504 match self.versions.get(&entity) {
508 Some(all) => all.contains(version),
509 None => self
510 .own
511 .get(&entity)
512 .is_some_and(|own| own.as_ref() == Some(version)),
513 }
514 }
515}
516
517impl Library {
518 pub fn would_start_tree(
525 &self,
526 space: SpaceId,
527 folder: &Path,
528 ) -> Result<StartPreview, NodeError> {
529 let root = self.checked_new_root(space, folder)?;
530 let walked = walk::walk(&root, &BTreeSet::new(), &self.apart());
531 Ok(StartPreview {
532 files: walked.found.len(),
533 bytes: walked.found.values().map(|found| found.size).sum(),
534 repositories: walked.repositories,
535 })
536 }
537
538 pub fn start_tree(
550 &mut self,
551 space: SpaceId,
552 folder: &Path,
553 message: Option<&str>,
554 wall_millis: u64,
555 rng: &mut impl CryptoRng,
556 ) -> Result<TreeStarted, NodeError> {
557 self.start_tree_with(space, folder, &Commit::new(message), wall_millis, rng)
558 }
559
560 pub fn start_tree_with(
567 &mut self,
568 space: SpaceId,
569 folder: &Path,
570 commit: &Commit<'_>,
571 wall_millis: u64,
572 rng: &mut impl CryptoRng,
573 ) -> Result<TreeStarted, NodeError> {
574 self.check_not_revoked(space)?;
575 let _locked = self.lock_trees()?;
576 let root = self.checked_new_root(space, folder)?;
577 self.install_standard(space, &TREE_TYPES, wall_millis, rng)?;
578 let name = root
579 .file_name()
580 .map(|name| name.to_string_lossy().into_owned())
581 .filter(|name| !name.is_empty());
582 let mut values = Vec::new();
583 if let Some(name) = name {
584 values.push(NewValue::new(fields::NAME, Value::Name(Name::new(&name))));
585 }
586 let (tree, founded) = self.new_entity(space, &[TREE], values, rng)?;
587 let (root_entity, rooted) = self.new_entity(
588 space,
589 &[TREE_ROOT],
590 vec![
591 NewValue::new(ROOT_OF, Value::Reference(tree)),
592 NewValue::new(ON_DEVICE, Value::Reference(self.info.device)),
593 NewValue::new(PATH, Value::Text(root.to_string_lossy().into_owned())),
594 ],
595 rng,
596 )?;
597 let founding = vec![(Some(tree), founded), (None, rooted)];
600 let committed =
601 self.commit_in(space, (tree, &root), commit, founding, (wall_millis, rng))?;
602 self.index()?.set_root(tree, root_entity, &root)?;
603 Ok(TreeStarted {
604 tree,
605 root,
606 committed,
607 })
608 }
609
610 pub fn trees(&self, space: SpaceId) -> Result<Vec<Tree>, NodeError> {
617 let open = self.space(space)?;
618 let state = open.stored.log().state();
619 let roots = self.roots_here(space)?;
620 let mut trees = Vec::new();
621 for tree in super::entities::with_type(&open.stored, &TREE)? {
622 let tree = state.canonical(tree)?;
623 if state.is_deleted(tree)? || trees.iter().any(|known: &Tree| known.id == tree) {
624 continue;
625 }
626 trees.push(Tree {
627 id: tree,
628 name: self.name(space, tree)?,
629 root: roots.get(&tree).cloned(),
630 });
631 }
632 trees.sort_by(|a, b| a.name.cmp(&b.name).then(a.id.cmp(&b.id)));
633 Ok(trees)
634 }
635
636 pub fn tree_at(&self, space: SpaceId, folder: &Path) -> Result<Option<Tree>, NodeError> {
642 let Some(folder) = resolved(folder) else {
643 return Ok(None);
644 };
645 let roots = self.roots_here(space)?;
646 let Some((&tree, root)) = roots.iter().find(|(_, root)| folder.starts_with(root)) else {
647 return Ok(None);
648 };
649 Ok(Some(Tree {
650 id: tree,
651 name: self.name(space, tree)?,
652 root: Some(root.clone()),
653 }))
654 }
655
656 pub fn tree_entries(
663 &self,
664 space: SpaceId,
665 tree: EntityId,
666 ) -> Result<Vec<TreeEntry>, NodeError> {
667 let state = self.tree_state(space, tree)?;
668 let mut entries: Vec<TreeEntry> = state
669 .by_path
670 .into_iter()
671 .map(|(path, current)| TreeEntry {
672 entity: current.entity,
673 path,
674 kind: match current.version {
675 Some(Version::Link { target }) => TreeEntryKind::Link { target },
676 Some(Version::File {
677 content,
678 executable,
679 }) => TreeEntryKind::File {
680 content: Some(content),
681 executable,
682 },
683 None => TreeEntryKind::File {
684 content: None,
685 executable: false,
686 },
687 },
688 })
689 .chain(state.sealed.into_iter().map(|(path, entity)| TreeEntry {
690 entity,
691 path,
692 kind: TreeEntryKind::Sealed,
693 }))
694 .collect();
695 entries.sort_by(|a, b| a.path.cmp(&b.path));
696 Ok(entries)
697 }
698
699 pub fn tree_status(&self, space: SpaceId, tree: EntityId) -> Result<TreeStatus, NodeError> {
712 let _locked = self.lock_trees()?;
713 let root = self.root_here(space, tree)?;
714 let mut index = self.index()?;
715 let purged = self.learn_purges(space, &index)?;
716 let state = self.tree_state(space, tree)?;
717 let apart = self.apart();
718 settle_tree((tree, &root, &apart), &mut index, (&purged, &state))?;
719 self.follow_cut_short(space, (tree, &root, &apart), &mut index, &state)?;
720 let read_new = !purged.is_empty();
723 let compared = self.compare(space, (tree, &root), &state, &index, (&purged, read_new))?;
724 index.change(tree, &compared.forgotten, &compared.refreshed)?;
725 self.note_secrets(space, (tree, &index), &state, &compared.refreshed)?;
726 index.unmark(tree, &compared.unmarked)?;
727 if compared.known {
728 index.know(tree)?;
729 }
730 Ok(TreeStatus {
731 tree,
732 root,
733 changes: compared
734 .pending
735 .iter()
736 .map(|pending| TreeChange {
737 path: pending.path.clone(),
738 change: pending.change.clone(),
739 })
740 .collect(),
741 secret: compared
742 .pending
743 .iter()
744 .filter(|pending| pending.secret)
745 .map(|pending| pending.path.clone())
746 .collect(),
747 sealed: state.sealed.keys().cloned().collect(),
748 behind: compared.behind.into_iter().collect(),
749 competing: state.competing.into_iter().collect(),
750 skipped: compared
751 .skipped
752 .into_iter()
753 .chain(compared.marked)
754 .collect(),
755 cut_short: self.cut_short(space, tree)?,
756 read: compared.read,
757 repositories: compared.repositories,
758 })
759 }
760
761 pub fn commit_tree(
780 &mut self,
781 space: SpaceId,
782 tree: EntityId,
783 commit: &Commit<'_>,
784 wall_millis: u64,
785 rng: &mut impl CryptoRng,
786 ) -> Result<Committed, NodeError> {
787 self.check_not_revoked(space)?;
788 let _locked = self.lock_trees()?;
789 let root = self.root_here(space, tree)?;
790 self.install_standard(space, &TREE_TYPES, wall_millis, rng)?;
791 self.commit_in(space, (tree, &root), commit, Vec::new(), (wall_millis, rng))
792 }
793
794 pub fn tree_secrets(&self, space: SpaceId, tree: EntityId) -> Result<TreeSecrets, NodeError> {
803 let tree = self.check_tree(space, tree)?;
804 let state = self.tree_state(space, tree)?;
805 let rules = match self.root_here(space, tree) {
806 Ok(root) => {
807 let index = self.index()?;
808 let left_out = self.left_out(space, tree, &root, &index)?;
809 secrecy::Rules::of_copy(&walk::walk(&root, &left_out, &self.apart()).found)
810 }
811 Err(_) => secrecy::Rules::built_in(),
812 };
813 let mut listed = TreeSecrets {
814 sealed: state.sealed.keys().cloned().collect(),
815 ..TreeSecrets::default()
816 };
817 for (path, current) in &state.by_path {
818 if state.is_secret(current.entity) {
819 listed.secret.push(path.clone());
820 } else if matches!(current.version, Some(Version::File { .. })) && rules.is_secret(path)
821 {
822 listed.looking_secret.push(path.clone());
823 }
824 }
825 listed.secret.extend(listed.sealed.iter().cloned());
826 listed.secret.sort();
827 listed.secret.dedup();
828 Ok(listed)
829 }
830
831 pub fn secret_file_in_tree(
842 &self,
843 space: SpaceId,
844 file: EntityId,
845 ) -> Result<Option<InTree>, NodeError> {
846 self.space(space)?.stored.reading(|stored| {
847 let state = stored.log().state();
848 let file = state.canonical(file)?;
849 let Secrecy::Of(tree) = secret_file_of(state, file)? else {
850 return Ok(None);
851 };
852 let mut statements = state.current(file, &TREE_PATH)?;
853 statements.sort_by_key(|statement| statement.id);
854 let path = statements
855 .iter()
856 .find_map(|statement| match &statement.value {
857 Value::Text(path) => Some(path.clone()),
858 _ => None,
859 })
860 .filter(|path| is_safe_tree_path(path));
861 Ok(Some(InTree { tree, path }))
862 })
863 }
864
865 pub fn would_purge_made_secret(
875 &self,
876 space: SpaceId,
877 file: EntityId,
878 ) -> Result<MadeSecret, NodeError> {
879 let mut contents: Vec<(Option<nibkeep_time::Timestamp>, Hash)> = Vec::new();
880 {
881 let state = self.space(space)?.stored.log().state();
882 if !state.is_deleted(state.canonical(file)?)? {
883 return Ok(MadeSecret::default());
884 }
885 for id in state.storage().of_field(file, &CONTENT)? {
886 if let Some(recorded) = state.storage().get(id)?
887 && let Value::Blob(content) = recorded.statement.value
888 && contents.iter().all(|(_, known)| *known != content)
889 {
890 contents.push((state.recorded(id)?, content));
891 }
892 }
893 }
894 contents.sort();
895 let mut made = MadeSecret::default();
896 for (_, content) in contents {
897 let purge = self.purgeable(space, file, &CONTENT, Some(&Value::Blob(content)))?;
898 if purge.also.is_empty() {
899 made.purged.push(content);
900 } else {
901 made.kept.push(content);
902 }
903 }
904 Ok(made)
905 }
906
907 pub fn purge_made_secret(
915 &mut self,
916 space: SpaceId,
917 file: EntityId,
918 wall_millis: u64,
919 rng: &mut impl CryptoRng,
920 ) -> Result<MadeSecret, NodeError> {
921 let made = self.would_purge_made_secret(space, file)?;
922 for content in &made.purged {
923 let value = Value::Blob(*content);
924 self.purge(space, file, &CONTENT, Some(&value), wall_millis, rng)?;
925 }
926 Ok(made)
927 }
928
929 pub fn move_in_tree(
940 &mut self,
941 space: SpaceId,
942 tree: EntityId,
943 (from, to): (&str, &str),
944 wall_millis: u64,
945 rng: &mut impl CryptoRng,
946 ) -> Result<Committed, NodeError> {
947 self.check_not_revoked(space)?;
948 let _locked = self.lock_trees()?;
949 let root = self.root_here(space, tree)?;
950 if !is_safe_tree_path(to) || !to.split('/').all(paths::fits_this_system) {
951 return Err(NodeError::UnsafePath(to.to_owned()));
952 }
953 self.install_standard(space, &TREE_TYPES, wall_millis, rng)?;
954 let state = self.tree_state(space, tree)?;
955 let mut index = self.index()?;
956 let entries = index.entries(tree)?;
957 let under = |path: &str| path == from || path.starts_with(&format!("{from}/"));
958 let moved_to = |path: &str| format!("{to}{}", &path[from.len()..]);
959 let moved: Vec<(String, String, EntityId)> = state
961 .by_entity
962 .iter()
963 .filter(|(_, path)| under(path))
964 .map(|(entity, path)| (path.clone(), moved_to(path), *entity))
965 .collect();
966 if moved.is_empty() {
967 return Err(NodeError::NotInTree(from.to_owned()));
968 }
969 if to == from || to.starts_with(&format!("{from}/")) {
970 return Err(NodeError::UnsafePath(to.to_owned()));
971 }
972 let clashes = |path: &String| {
975 path == to || path.starts_with(&format!("{to}/")) || to.starts_with(&format!("{path}/"))
976 };
977 if state.by_path.keys().chain(entries.keys()).any(clashes) {
978 return Err(NodeError::PlaceTaken(root.join(to)));
979 }
980 let apart = self.apart();
981 let Located::Here(source) = located(&root, from, &apart) else {
982 return Err(NodeError::NotInTree(from.to_owned()));
983 };
984 if self
987 .left_out(space, tree, &root, &index)?
988 .iter()
989 .any(|path| under(path))
990 {
991 return Err(NodeError::HoldsOtherCopies(from.to_owned()));
992 }
993 let blocked = |why| match why {
994 Blocked::Taken => NodeError::PlaceTaken(root.join(to)),
995 Blocked::Unsafe => NodeError::UnsafePath(to.to_owned()),
996 };
997 let target = place_for_new(&root, to, &apart).map_err(blocked)?;
998 if let Some(parent) = target.parent() {
999 write::make_folders(parent).map_err(NodeError::file(parent))?;
1000 if place_for_new(&root, to, &apart).as_ref() != Ok(&target) {
1002 return Err(NodeError::UnsafePath(to.to_owned()));
1003 }
1004 }
1005 fs::rename(&source, &target).map_err(NodeError::file(&source))?;
1006 save_move(&source, &target);
1007 let mut parts: Vec<(EntityId, Vec<nibkeep_model::Operation>)> = Vec::new();
1008 let mut changes = Vec::new();
1009 let mut removed = Vec::new();
1010 let mut set = Vec::new();
1011 {
1012 let open = self.space(space)?;
1013 let space_state = open.stored.log().state();
1014 for (old, new, entity) in &moved {
1015 parts.push((*entity, moving(space_state, *entity, old, new, rng)?));
1016 changes.push(TreeChange {
1017 path: new.clone(),
1018 change: Change::Moved { from: old.clone() },
1019 });
1020 }
1021 for (old, entry) in entries.iter().filter(|(path, _)| under(path)) {
1023 removed.push(old.clone());
1024 set.push((moved_to(old), entry.clone()));
1025 }
1026 }
1027 let count = parts.len() + 1;
1030 let saved = self.batch_whole(space, |library| {
1031 let (revision, made) = library.revision_operations(space, tree, None, count, rng)?;
1032 library.commit(space, made, wall_millis, rng)?;
1033 for (entity, operations) in parts {
1034 let operations =
1035 library.part_operations(space, revision, entity, operations, rng)?;
1036 library.commit(space, operations, wall_millis, rng)?;
1037 }
1038 Ok(revision)
1039 });
1040 let revision = match saved {
1041 Ok(revision) => revision,
1042 Err(error) => {
1043 let _ = fs::rename(&target, &source);
1045 return Err(error);
1046 }
1047 };
1048 changes.sort_by(|a, b| a.path.cmp(&b.path));
1049 changes.dedup();
1050 index.change(tree, &removed, &set)?;
1051 Ok(Committed {
1052 revision: Some(revision),
1053 parts: count,
1054 changes,
1055 ..Committed::default()
1056 })
1057 }
1058}
1059
1060impl Library {
1061 fn checked_new_root(&self, space: SpaceId, folder: &Path) -> Result<PathBuf, NodeError> {
1065 let root = fs::canonicalize(folder).map_err(NodeError::file(folder))?;
1066 let root = super::files::plain(root);
1067 if !root.is_dir() {
1068 return Err(NodeError::file(&root)(io::ErrorKind::NotADirectory.into()));
1069 }
1070 let in_reserved = root.components().any(|component| match component {
1073 std::path::Component::Normal(name) => paths::is_reserved(&name.to_string_lossy()),
1074 _ => false,
1075 });
1076 if in_reserved || self.apart().iter().any(|apart| root.starts_with(apart)) {
1077 return Err(NodeError::NotATreeFolder(root));
1078 }
1079 let _ = space;
1080 for &any in self.spaces.keys() {
1081 for other in self.roots_here(any)?.values() {
1082 if root.starts_with(other) || other.starts_with(&root) {
1083 return Err(NodeError::TreeInTree(root));
1084 }
1085 }
1086 }
1087 if fs::symlink_metadata(root.join(".git")).is_ok() || walk::is_bare(&root) {
1088 return Err(NodeError::GitRepositoryHere(root));
1089 }
1090 Ok(root)
1091 }
1092
1093 fn roots_here(&self, space: SpaceId) -> Result<BTreeMap<EntityId, PathBuf>, NodeError> {
1099 let open = self.space(space)?;
1100 let state = open.stored.log().state();
1101 let alive = |entity: EntityId| -> Result<bool, NodeError> {
1102 Ok(!state.is_deleted(state.canonical(entity)?)?)
1103 };
1104 let mut roots = BTreeMap::new();
1105 let recorded = if self.directory().join(index::INDEX).exists() {
1106 self.index()?.roots()?
1107 } else {
1108 BTreeMap::new()
1109 };
1110 for (tree, (root, folder)) in &recorded {
1111 let in_space = !state.types(*root)?.is_empty();
1112 if in_space && alive(*root)? && alive(*tree)? {
1113 roots.insert(state.canonical(*tree)?, folder.clone());
1114 }
1115 }
1116 let this_replica = self.replica.signing.verifying_key();
1117 for root in open
1118 .stored
1119 .find(&ON_DEVICE, &Value::Reference(self.info.device))?
1120 {
1121 let root = state.canonical(root)?;
1122 if state.is_deleted(root)? || !state.types(root)?.contains(&TREE_ROOT) {
1123 continue;
1124 }
1125 let mut values = BTreeMap::new();
1126 let mut own = true;
1127 for field in [&ROOT_OF, &ON_DEVICE, &PATH] {
1128 let mut current = state.current(root, field)?;
1129 current.sort_by_key(|statement| statement.id);
1130 for statement in ¤t {
1131 own &= open.stored.log().author_of(statement.id)? == Some(this_replica);
1132 }
1133 let first = current.first().map(|statement| statement.value.clone());
1134 values.insert(field.clone(), first);
1135 }
1136 let (true, Some(Some(Value::Reference(tree))), Some(Some(Value::Text(path)))) =
1137 (own, values.remove(&ROOT_OF), values.remove(&PATH))
1138 else {
1139 continue;
1140 };
1141 let tree = state.canonical(tree)?;
1142 if alive(tree)? {
1143 roots.entry(tree).or_insert_with(|| PathBuf::from(path));
1144 }
1145 }
1146 Ok(roots)
1147 }
1148
1149 pub(crate) fn in_any_tree(&self, folder: &Path) -> Result<bool, NodeError> {
1151 let Some(folder) = resolved(folder) else {
1152 return Ok(false);
1153 };
1154 for &space in self.spaces.keys() {
1155 if self
1156 .roots_here(space)?
1157 .values()
1158 .any(|root| folder.starts_with(root))
1159 {
1160 return Ok(true);
1161 }
1162 }
1163 Ok(false)
1164 }
1165
1166 pub(super) fn check_tree(&self, space: SpaceId, tree: EntityId) -> Result<EntityId, NodeError> {
1168 let state = self.space(space)?.stored.log().state();
1169 let tree = state.canonical(tree)?;
1170 if state.is_deleted(tree)? || !state.types(tree)?.contains(&TREE) {
1171 return Err(NodeError::NotATree(tree.to_string()));
1172 }
1173 Ok(tree)
1174 }
1175
1176 fn root_here(&self, space: SpaceId, tree: EntityId) -> Result<PathBuf, NodeError> {
1179 let tree = self.space(space)?.stored.log().state().canonical(tree)?;
1180 let root = self
1181 .roots_here(space)?
1182 .remove(&tree)
1183 .ok_or_else(|| NodeError::NoTreeHere(tree.to_string()))?;
1184 if !fs::symlink_metadata(&root).is_ok_and(|metadata| metadata.is_dir()) {
1185 return Err(NodeError::TreeFolderGone(root));
1186 }
1187 Ok(root)
1188 }
1189
1190 fn index(&self) -> Result<Index, NodeError> {
1192 Index::open(self.directory(), &self.derived_key(INDEX_CONTEXT))
1193 }
1194
1195 fn index_if_any(&self) -> Result<Option<Index>, NodeError> {
1198 if fs::symlink_metadata(self.directory().join(index::INDEX)).is_err() {
1199 return Ok(None);
1200 }
1201 self.index().map(Some)
1202 }
1203
1204 fn device_name_of(
1207 &self,
1208 space: SpaceId,
1209 statement: nibkeep_base::StatementId,
1210 ) -> Option<String> {
1211 let named = || -> Result<Option<String>, NodeError> {
1212 let Some(author) = self.author_of(space, statement)? else {
1213 return Ok(None);
1214 };
1215 let personal = self.personal_space();
1216 let roster = self.space(personal)?.stored.log().state();
1217 let device = roster
1218 .current(author.replica, &nibkeep_governance::ON_DEVICE)?
1219 .into_iter()
1220 .find_map(|statement| statement.value.as_reference());
1221 match device {
1222 Some(device) => self.name(personal, device),
1223 None => Ok(None),
1224 }
1225 };
1226 named().ok().flatten()
1227 }
1228
1229 fn try_lock_trees(&self) -> Result<Option<File>, NodeError> {
1232 let path = self.directory().join(LOCK);
1233 let file = File::options()
1234 .create(true)
1235 .truncate(false)
1236 .write(true)
1237 .open(&path)
1238 .map_err(NodeError::file(&path))?;
1239 match file.try_lock() {
1240 Ok(()) => Ok(Some(file)),
1241 Err(std::fs::TryLockError::WouldBlock) => Ok(None),
1242 Err(std::fs::TryLockError::Error(error)) => Err(NodeError::file(&path)(error)),
1243 }
1244 }
1245
1246 fn lock_trees(&self) -> Result<File, NodeError> {
1248 let path = self.directory().join(LOCK);
1249 let file = File::options()
1250 .create(true)
1251 .truncate(false)
1252 .write(true)
1253 .open(&path)
1254 .map_err(NodeError::file(&path))?;
1255 file.lock().map_err(NodeError::file(&path))?;
1256 Ok(file)
1257 }
1258
1259 fn tree_state(&self, space: SpaceId, tree: EntityId) -> Result<TreeState, NodeError> {
1264 let open = self.space(space)?;
1265 let readable = self.secrets_unlocked(space);
1266 let mut read = open.stored.reading(|stored| {
1267 let log = stored.log();
1268 let state = log.state();
1269 let entities = tree_entities(state, tree)?;
1270 read_tree_state(state, tree, &entities, (Some(&Changes::of(log)), readable))
1271 })?;
1272 if !read.sealed.is_empty()
1273 && let Some(index) = self.index_if_any()?
1274 {
1275 read.fill_sealed(&index.entries(tree)?);
1276 }
1277 Ok(read)
1278 }
1279
1280 fn note_secrets(
1284 &self,
1285 space: SpaceId,
1286 (tree, index): (EntityId, &Index),
1287 state: &TreeState,
1288 set: &[(String, Entry)],
1289 ) -> Result<(), NodeError> {
1290 let versions = set.iter().filter_map(|(_, entry)| match entry.version {
1291 Version::File { content, .. } if state.is_secret(entry.entity) => {
1292 Some((entry.entity, content))
1293 }
1294 _ => None,
1295 });
1296 self.note_secret_versions(space, (tree, index), versions)
1297 }
1298
1299 fn note_secret_versions(
1301 &self,
1302 space: SpaceId,
1303 (tree, index): (EntityId, &Index),
1304 versions: impl IntoIterator<Item = (EntityId, Hash)>,
1305 ) -> Result<(), NodeError> {
1306 let log = self.space(space)?.stored.log();
1307 for (entity, content) in versions {
1308 let sealed: BTreeSet<Hash> = log
1309 .blob_keys(&content)
1310 .filter(|(sealed, _)| log.is_secret_blob(sealed))
1311 .map(|(sealed, _)| *sealed)
1312 .collect();
1313 index.note_secret(tree, (entity, content), &sealed)?;
1314 }
1315 Ok(())
1316 }
1317
1318 fn left_out(
1321 &self,
1322 space: SpaceId,
1323 tree: EntityId,
1324 root: &Path,
1325 index: &Index,
1326 ) -> Result<BTreeSet<String>, NodeError> {
1327 let mut left_out: BTreeSet<String> = index.marked(tree)?.into_keys().collect();
1328 for checkout in self.checkouts(space)? {
1329 if let Ok(relative) = checkout.path.strip_prefix(root)
1330 && let Ok(path) = paths::tree_path_of(relative)
1331 {
1332 left_out.insert(path);
1333 }
1334 }
1335 Ok(left_out)
1336 }
1337
1338 fn apart(&self) -> Vec<PathBuf> {
1340 self.library_directory()
1341 .and_then(|directory| fs::canonicalize(directory).ok())
1342 .map(super::files::plain)
1343 .into_iter()
1344 .collect()
1345 }
1346
1347 fn is_purged(
1353 &self,
1354 space: SpaceId,
1355 entry: &Entry,
1356 secret_versions: &SecretVersions,
1357 ) -> Result<bool, NodeError> {
1358 let Version::File { content, .. } = entry.version else {
1359 return Ok(false);
1360 };
1361 let log = self.space(space)?.stored.log();
1362 if let Some(sealed) = secret_versions.get(&(entry.entity, content)) {
1363 if sealed.is_empty() {
1364 return Ok(false);
1365 }
1366 for sealed in sealed {
1367 if !nibkeep_log::History::is_blob_purged(log.history(), sealed)? {
1368 return Ok(false);
1369 }
1370 }
1371 return Ok(true);
1372 }
1373 let state = log.state();
1374 if secret_file_of(state, entry.entity)? != Secrecy::Ordinary {
1375 return Ok(false);
1376 }
1377 if log
1378 .blob_keys(&content)
1379 .any(|(sealed, _)| !log.is_secret_blob(sealed))
1380 {
1381 return Ok(false);
1382 }
1383 for entity in state.merged(state.canonical(entry.entity)?)? {
1384 for id in state.storage().of_field(entity, &CONTENT)? {
1385 if state
1386 .statement(id)?
1387 .is_some_and(|statement| statement.value == Value::Blob(content))
1388 {
1389 return Ok(false);
1390 }
1391 }
1392 }
1393 Ok(true)
1394 }
1395
1396 fn purges_of(&self, space: SpaceId) -> Result<usize, NodeError> {
1399 let log = self.space(space)?.stored.log();
1400 Ok(nibkeep_log::History::purged_blobs(log.history())?.len())
1401 }
1402
1403 fn learn_purges(&self, space: SpaceId, index: &Index) -> Result<Purged, NodeError> {
1408 let purges = self.purges_of(space)?;
1409 let roots = self.roots_here(space)?;
1410 let mut secret_versions = SecretVersions::new();
1411 for tree in roots.keys() {
1412 secret_versions.extend(index.secret_versions(*tree)?);
1413 }
1414 if index.settled(space)? != Some(purges) {
1415 let mut learned = BTreeSet::new();
1416 let mut learned_secrets = BTreeSet::new();
1417 for tree in roots.keys() {
1418 for entry in index.entries(*tree)?.values() {
1419 if let Version::File { content, .. } = entry.version
1420 && self.is_purged(space, entry, &secret_versions)?
1421 {
1422 if secret_versions.contains_key(&(entry.entity, content)) {
1423 learned_secrets.insert(content);
1424 } else {
1425 learned.insert(content);
1426 }
1427 }
1428 }
1429 }
1430 index.add_purged(&learned)?;
1431 index.add_purged_secrets(&learned_secrets)?;
1432 index.set_settled(space, purges)?;
1433 }
1434 Ok(Purged {
1435 ordinary: index.purged()?,
1436 secret: index.purged_secrets()?,
1437 secret_versions,
1438 })
1439 }
1440
1441 pub(crate) fn note_purged(
1444 &self,
1445 space: SpaceId,
1446 (contents, secret): (&BTreeSet<Hash>, bool),
1447 ) -> Result<(), NodeError> {
1448 if contents.is_empty() || self.roots_here(space)?.is_empty() {
1449 return Ok(());
1450 }
1451 let _locked = self.lock_trees()?;
1452 let index = self.index()?;
1453 if secret {
1454 index.add_purged_secrets(contents)
1455 } else {
1456 index.add_purged(contents)
1457 }
1458 }
1459
1460 pub(crate) fn tree_copies_holding(
1465 &self,
1466 space: SpaceId,
1467 contents: &BTreeSet<Hash>,
1468 secret: bool,
1469 ) -> Result<Vec<(PathBuf, bool)>, NodeError> {
1470 let roots = self.roots_here(space)?;
1471 let mut holding = Vec::new();
1472 if roots.is_empty() || contents.is_empty() {
1473 return Ok(holding);
1474 }
1475 let index = self.index()?;
1476 for (tree, root) in roots {
1477 let secret_versions = index.secret_versions(tree)?;
1478 for (path, entry) in index.entries(tree)? {
1479 let Version::File { content, .. } = entry.version else {
1480 continue;
1481 };
1482 if !contents.contains(&content)
1483 || secret_versions.contains_key(&(entry.entity, content)) != secret
1484 {
1485 continue;
1486 }
1487 let Located::Here(on_disk) = located(&root, &path, &self.apart()) else {
1488 continue;
1489 };
1490 if let Ok(at) = walk::look(&on_disk)
1491 && at.kind == walk::FoundKind::File
1492 {
1493 let edited = walk::hash_found(&at).map_or(true, |found| found != content);
1494 holding.push((on_disk, edited));
1495 }
1496 }
1497 }
1498 holding.sort();
1499 Ok(holding)
1500 }
1501
1502 pub(crate) fn settle_trees_in(&self, space: SpaceId) -> Result<Vec<PathBuf>, NodeError> {
1508 let roots = self.roots_here(space)?;
1509 if roots.is_empty() {
1510 return Ok(Vec::new());
1511 }
1512 let mut index = self.index()?;
1513 if index.settled(space)? == Some(self.purges_of(space)?) {
1514 return Ok(Vec::new());
1515 }
1516 let Some(_locked) = self.try_lock_trees()? else {
1517 return Ok(Vec::new());
1518 };
1519 let purged = self.learn_purges(space, &index)?;
1520 let apart = self.apart();
1521 let mut deleted = Vec::new();
1522 for (tree, root) in roots {
1523 if fs::symlink_metadata(&root).is_ok_and(|metadata| metadata.is_dir()) {
1524 let state = self.tree_state(space, tree)?;
1525 let settling = (&purged, &state);
1526 let place = (tree, root.as_path(), apart.as_slice());
1527 deleted.extend(settle_tree(place, &mut index, settling)?);
1528 }
1529 }
1530 Ok(deleted)
1531 }
1532
1533 fn cut_short(&self, space: SpaceId, tree: EntityId) -> Result<Vec<CutShort>, NodeError> {
1537 let open = self.space(space)?;
1538 let state = open.stored.log().state();
1539 let mut commits = Vec::new();
1541 for revision in open.stored.find(&IN_TREE, &Value::Reference(tree))? {
1542 if !state.types(revision)?.contains(&REVISION) {
1543 continue;
1544 }
1545 let first = |field: &FieldName| -> Result<Option<Statement>, NodeError> {
1546 Ok(state
1547 .current(revision, field)?
1548 .into_iter()
1549 .min_by_key(|statement| statement.id)
1550 .map(std::borrow::Cow::into_owned))
1551 };
1552 let Some(in_tree) = first(&IN_TREE)? else {
1553 continue;
1554 };
1555 let parts = match first(&PARTS)?.map(|statement| statement.value) {
1556 Some(Value::Integer(parts)) => u64::try_from(parts).ok(),
1557 _ => None,
1558 };
1559 let made_at = state.recorded(in_tree.id)?;
1562 let made_by = open.stored.log().author_of(in_tree.id)?;
1563 commits.push((revision, made_by, made_at, parts));
1564 }
1565 let mut last: Vec<(
1568 nibkeep_crypto::VerifyingKey,
1569 Option<nibkeep_time::Timestamp>,
1570 )> = Vec::new();
1571 for (_, made_by, made_at, _) in &commits {
1572 let Some(made_by) = made_by else {
1573 continue;
1574 };
1575 match last.iter_mut().find(|(by, _)| by == made_by) {
1576 Some((_, at)) => *at = (*at).max(*made_at),
1577 None => last.push((*made_by, *made_at)),
1578 }
1579 }
1580 let mut cut = Vec::new();
1581 for (revision, made_by, made_at, parts) in commits {
1582 let Some(parts) = parts else {
1583 continue;
1584 };
1585 let later = made_by
1586 .is_some_and(|made_by| last.iter().any(|(by, at)| *by == made_by && *at > made_at));
1587 if later {
1588 continue;
1589 }
1590 let here = history::parts_here(state, revision)?.len() + 1;
1591 let made = u64::try_from(here).unwrap_or(u64::MAX);
1592 if made < parts {
1593 cut.push(CutShort {
1594 revision,
1595 parts,
1596 made,
1597 });
1598 }
1599 }
1600 Ok(cut)
1601 }
1602}
1603
1604fn settle_tree(
1612 (tree, root, apart): (EntityId, &Path, &[PathBuf]),
1613 index: &mut Index,
1614 (purged, state): (&Purged, &TreeState),
1615) -> Result<Vec<PathBuf>, NodeError> {
1616 let mut deleted = Vec::new();
1617 let mut removed = Vec::new();
1618 if purged.is_empty() {
1619 return Ok(deleted);
1620 }
1621 let entries = index.entries(tree)?;
1622 let mut holding: Vec<(String, Option<Hash>, bool)> = entries
1627 .iter()
1628 .filter_map(|(path, entry)| match entry.version {
1629 Version::File { content, .. } if purged.holds(entry) => {
1630 Some((path.clone(), Some(content), purged.is_secret(entry)))
1631 }
1632 _ => None,
1633 })
1634 .collect();
1635 holding.extend(
1636 state
1637 .by_path
1638 .iter()
1639 .filter(|(path, current)| current.version.is_none() && !entries.contains_key(*path))
1640 .map(|(path, current)| (path.clone(), None, state.is_secret(current.entity))),
1641 );
1642 for (path, content, secret) in holding {
1643 let on_disk = match located(root, &path, apart) {
1644 Located::Here(on_disk) => on_disk,
1645 Located::Absent => {
1646 removed.push(path);
1647 continue;
1648 }
1649 Located::Unknown(_) => continue,
1650 };
1651 let Ok(at) = walk::look(&on_disk) else {
1652 continue;
1653 };
1654 if at.kind != walk::FoundKind::File {
1655 removed.push(path);
1657 continue;
1658 }
1659 match walk::hash_found(&at) {
1660 Ok(found)
1661 if content.map_or(purged.contains(&found, secret), |content| found == content) =>
1662 {
1663 let unchanged = walk::look(&on_disk).is_ok_and(|now| {
1666 now.identity == at.identity
1667 && now.size == at.size
1668 && now.modified == at.modified
1669 });
1670 if unchanged && fs::remove_file(&on_disk).is_ok() {
1671 super::checkouts::sync_folder_of(&on_disk);
1672 deleted.push(on_disk);
1673 removed.push(path);
1674 }
1675 }
1676 Ok(_) => removed.push(path),
1677 Err(_) => {}
1678 }
1679 }
1680 index.change(tree, &removed, &[])?;
1681 Ok(deleted)
1682}
1683
1684fn save_move(source: &Path, target: &Path) {
1687 super::checkouts::sync_folder_of(source);
1688 super::checkouts::sync_folder_of(target);
1689}
1690
1691impl Library {
1692 fn follow_cut_short(
1706 &self,
1707 space: SpaceId,
1708 (tree, root, apart): (EntityId, &Path, &[PathBuf]),
1709 index: &mut Index,
1710 state: &TreeState,
1711 ) -> Result<(), NodeError> {
1712 let entries = index.entries(tree)?;
1713 write::bring_back_aside(write::Place { root, apart }, entries.keys());
1714 let read_at = walk::nanos(std::time::SystemTime::now()).unwrap_or(0);
1716 let listings = Listings::apart(apart);
1717 let at = |path: &str| located_in(&listings, root, path);
1718 let gone = |path: &str| at(path) == Located::Absent;
1719 let holding = |path: &str, (entity, version): (EntityId, &Version)| {
1720 let Located::Here(on_disk) = at(path) else {
1721 return None;
1722 };
1723 let found = walk::look(&on_disk).ok()?;
1724 let holds = write::copy_version(&found)?;
1725 write::same_version(&found, &holds, version).then(|| Entry {
1726 entity,
1727 version: version.clone(),
1728 size: found.size,
1729 modified: found.modified,
1730 read_at,
1731 })
1732 };
1733 let mut removed: Vec<String> = Vec::new();
1734 let mut set: BTreeMap<String, Entry> = BTreeMap::new();
1735 let writing = index.writing(tree)?;
1736 for (path, entity, version) in &writing {
1737 let recorded = entries
1738 .get(path)
1739 .is_some_and(|entry| entry.entity == *entity && entry.version == *version);
1740 if recorded {
1741 continue;
1742 }
1743 let Some(written) = holding(path, (*entity, version)) else {
1744 continue;
1745 };
1746 removed.extend(
1748 entries
1749 .iter()
1750 .filter(|(from, entry)| entry.entity == *entity && *from != path && gone(from))
1751 .map(|(from, _)| from.clone()),
1752 );
1753 set.insert(path.clone(), written);
1754 }
1755 let changed = |path: &str, entry: Option<&Entry>| match (at(path), entry) {
1758 (Located::Here(on_disk), Some(entry)) => {
1759 walk::look(&on_disk).is_ok_and(|found| !entry.untouched(found.size, found.modified))
1760 }
1761 (Located::Here(_), None) => index.knows(tree).unwrap_or(false),
1762 (Located::Absent, Some(_)) => true,
1763 _ => false,
1764 };
1765 for (path, entity, version) in self.committed_here(space, &entries, state, &changed)? {
1766 let from = entries
1767 .iter()
1768 .find(|(_, entry)| entry.entity == entity)
1769 .map(|(from, _)| from.clone());
1770 let moved = from.as_ref().filter(|from| **from != path);
1771 if set.contains_key(&path)
1772 || moved.is_some_and(|from| !gone(from) || entries.contains_key(&path))
1773 {
1774 continue;
1775 }
1776 removed.extend(moved.cloned());
1777 let entry = Entry {
1779 entity,
1780 version,
1781 size: 0,
1782 modified: None,
1783 read_at,
1784 };
1785 set.insert(path, entry);
1786 }
1787 for (path, entry) in &entries {
1788 let Some(now_at) = state.by_entity.get(&entry.entity) else {
1789 continue;
1790 };
1791 if now_at == path
1792 || entries.contains_key(now_at)
1793 || set.contains_key(now_at)
1794 || removed.contains(path)
1795 || !gone(path)
1796 {
1797 continue;
1798 }
1799 let Some(moved) = holding(now_at, (entry.entity, &entry.version)) else {
1800 continue;
1801 };
1802 removed.push(path.clone());
1803 set.insert(now_at.clone(), moved);
1804 }
1805 let set: Vec<(String, Entry)> = set.into_iter().collect();
1806 index.change(tree, &removed, &set)?;
1807 self.note_secrets(space, (tree, index), state, &set)?;
1809 if !writing.is_empty() {
1810 index.forget_writing(tree)?;
1811 }
1812 Ok(())
1813 }
1814
1815 fn committed_here(
1821 &self,
1822 space: SpaceId,
1823 entries: &BTreeMap<String, Entry>,
1824 state: &TreeState,
1825 changed: &dyn Fn(&str, Option<&Entry>) -> bool,
1826 ) -> Result<Vec<(String, EntityId, Version)>, NodeError> {
1827 let indexed: BTreeMap<EntityId, (&String, &Entry)> = entries
1828 .iter()
1829 .map(|(path, entry)| (entry.entity, (path, entry)))
1830 .collect();
1831 let differing: Vec<(String, EntityId, Version)> = state
1832 .by_entity
1833 .iter()
1834 .filter(|(entity, path)| {
1835 !state.competing.contains(*path)
1836 && !state.paths.contains_key(*entity)
1837 && state
1838 .versions
1839 .get(*entity)
1840 .is_none_or(|versions| versions.len() < 2)
1841 })
1842 .filter_map(|(entity, path)| {
1843 let version = state.own.get(entity).cloned().flatten()?;
1844 let differs = match indexed.get(entity) {
1845 Some((at, entry)) => {
1846 (*at != path || entry.version != version) && changed(at, Some(entry))
1847 }
1848 None => changed(path, None),
1849 };
1850 differs.then(|| (path.clone(), *entity, version))
1851 })
1852 .collect();
1853 if differing.is_empty() {
1854 return Ok(differing);
1855 }
1856 let open = self.space(space)?;
1857 let log = open.stored.log();
1858 let state_now = log.state();
1859 let me = self.replica.signing.verifying_key();
1860 let change_of = |id| -> Result<Option<Hash>, NodeError> {
1861 Ok(state_now
1862 .storage()
1863 .get(id)?
1864 .and_then(|recorded| recorded.change))
1865 };
1866 let fields = [
1867 &TREE_PATH,
1868 &CONTENT,
1869 &SECRET_CONTENT,
1870 &LINK_TARGET,
1871 &EXECUTABLE,
1872 ];
1873 let mut own = Vec::new();
1874 for (path, entity, version) in differing {
1875 let mut last = None;
1878 for field in fields {
1879 for statement in state_now.current(entity, field)? {
1880 let at = state_now.recorded(statement.id)?;
1881 if last.as_ref().is_none_or(|(when, _)| at > *when) {
1882 last = Some((at, statement.id));
1883 }
1884 }
1885 }
1886 let Some((_, newest)) = last else {
1887 continue;
1888 };
1889 let change = change_of(newest)?;
1890 let mut in_commit = false;
1891 for part in state_now.current(entity, &COMMITTED_IN)? {
1892 in_commit |= change.is_some() && change_of(part.id)? == change;
1893 }
1894 if in_commit && log.author_of(newest)? == Some(me) {
1895 own.push((path, entity, version));
1896 }
1897 }
1898 Ok(own)
1899 }
1900}
1901
1902#[derive(Debug, Default)]
1908struct Purged {
1909 ordinary: BTreeSet<Hash>,
1910 secret: BTreeSet<Hash>,
1911 secret_versions: SecretVersions,
1914}
1915
1916impl Purged {
1917 fn is_empty(&self) -> bool {
1919 self.ordinary.is_empty() && self.secret.is_empty()
1920 }
1921
1922 fn contains(&self, content: &Hash, secret: bool) -> bool {
1924 if secret {
1925 self.secret.contains(content)
1926 } else {
1927 self.ordinary.contains(content)
1928 }
1929 }
1930
1931 fn is_secret(&self, entry: &Entry) -> bool {
1933 matches!(entry.version, Version::File { content, .. }
1934 if self.secret_versions.contains_key(&(entry.entity, content)))
1935 }
1936
1937 fn holds(&self, entry: &Entry) -> bool {
1939 match entry.version {
1940 Version::File { content, .. } => self.contains(&content, self.is_secret(entry)),
1941 Version::Link { .. } => false,
1942 }
1943 }
1944}
1945
1946fn version_of(state: &TreeState, entity: EntityId) -> Option<(String, Option<Version>)> {
1949 let path = state.by_entity.get(&entity)?;
1950 Some((path.clone(), state.own.get(&entity).cloned().flatten()))
1951}
1952
1953fn tree_entities<S: nibkeep_model::storage::Statements>(
1956 state: &nibkeep_model::State<S>,
1957 tree: EntityId,
1958) -> Result<Vec<EntityId>, NodeError>
1959where
1960 NodeError: From<S::Error>,
1961{
1962 let tree = state.canonical(tree)?;
1963 let mut entities = BTreeSet::new();
1964 for id in state.storage().referring_to(tree)? {
1967 if let Some(recorded) = state.storage().get(id)?
1968 && recorded.statement.field == IN_TREE
1969 {
1970 entities.insert(state.canonical(recorded.statement.entity)?);
1971 }
1972 }
1973 Ok(entities.into_iter().collect())
1974}
1975
1976pub(super) struct Changes<'a> {
1980 log: &'a Log<StateFile, LogFile>,
1981 built_on: RefCell<BTreeMap<Hash, BTreeSet<Hash>>>,
1982}
1983
1984impl<'a> Changes<'a> {
1985 pub(super) fn of(log: &'a Log<StateFile, LogFile>) -> Self {
1987 Self {
1988 log,
1989 built_on: RefCell::default(),
1990 }
1991 }
1992
1993 fn saw(&self, earlier: Hash, later: Hash) -> Result<bool, NodeError> {
1996 if earlier == later {
1997 return Ok(true);
1998 }
1999 if let Some(built_on) = self.built_on.borrow().get(&later) {
2000 return Ok(built_on.contains(&earlier));
2001 }
2002 let mut built_on = BTreeSet::new();
2003 let mut waiting = vec![ChangeId::from_hash(later)];
2004 while let Some(id) = waiting.pop() {
2005 let Some(change) = self.log.change(id)? else {
2006 continue;
2007 };
2008 for parent in change.parents() {
2009 if built_on.insert(*parent.hash()) {
2010 waiting.push(*parent);
2011 }
2012 }
2013 }
2014 let saw = built_on.contains(&earlier);
2015 self.built_on.borrow_mut().insert(later, built_on);
2016 Ok(saw)
2017 }
2018
2019 fn purged(&self, change: Hash) -> Result<bool, NodeError> {
2022 let status = nibkeep_log::History::status(self.log.history(), ChangeId::from_hash(change))?;
2023 Ok(status == Some(nibkeep_log::Status::Ignored))
2024 }
2025}
2026
2027fn read_tree_state<S: nibkeep_model::storage::Statements>(
2033 state: &nibkeep_model::State<S>,
2034 tree: EntityId,
2035 entities: &[EntityId],
2036 (changes, readable): (Option<&Changes<'_>>, bool),
2037) -> Result<TreeState, NodeError>
2038where
2039 NodeError: From<S::Error>,
2040{
2041 let tree = state.canonical(tree)?;
2042 let mut read = TreeState::default();
2043 let mut deleted_at: BTreeMap<String, nibkeep_time::Timestamp> = BTreeMap::new();
2045 for &entity in entities {
2046 let Some((is_link, is_secret)) = kind_in_tree(state, entity, tree)? else {
2047 continue;
2048 };
2049 let values = |field: &FieldName| -> Result<Vec<Value>, NodeError> {
2050 let mut statements = state.current(entity, field)?;
2051 statements.sort_by_key(|statement| statement.id);
2052 Ok(statements
2053 .into_iter()
2054 .map(|statement| statement.value.clone())
2055 .collect())
2056 };
2057 let texts = |field: &FieldName| -> Result<Vec<String>, NodeError> {
2058 Ok(values(field)?
2059 .into_iter()
2060 .filter_map(|value| match value {
2061 Value::Text(text) => Some(text),
2062 _ => None,
2063 })
2064 .collect())
2065 };
2066 let paths = distinct(texts(&TREE_PATH)?);
2067 if is_secret {
2068 read.secret.insert(entity);
2069 read.secret_paths.extend(all_paths(state, entity)?);
2070 }
2071 let Some(path) = paths.first().cloned() else {
2072 continue;
2073 };
2074 if !is_safe_tree_path(&path) {
2075 continue;
2076 }
2077 let all: Vec<Version> = if is_link {
2078 texts(&LINK_TARGET)?
2079 .into_iter()
2080 .map(|target| Version::Link { target })
2081 .collect()
2082 } else {
2083 let executable = values(&EXECUTABLE)?.contains(&Value::Boolean(true));
2084 let field = if is_secret { &SECRET_CONTENT } else { &CONTENT };
2085 values(field)?
2086 .into_iter()
2087 .filter_map(|value| match value {
2088 Value::Blob(content) => Some(Version::File {
2089 content,
2090 executable,
2091 }),
2092 _ => None,
2093 })
2094 .collect()
2095 };
2096 let all = distinct(all);
2097 let competing = all.len() > 1;
2098 let version = all.first().cloned();
2099 let deleted = state.is_deleted(entity)?;
2100 if is_secret && version.is_none() && !deleted && !readable {
2101 read.sealed.insert(path, entity);
2103 continue;
2104 }
2105 let unseen = match changes {
2106 Some(changes) if deleted && version.is_some() => {
2108 unseen_deletions(state, entity, changes)?
2109 }
2110 _ => None,
2111 };
2112 if let Some(deletions) = unseen {
2113 read.contested.insert(entity, deletions);
2114 read.competing.insert(path.clone());
2115 } else if deleted {
2116 note_deleted(
2117 state,
2118 (&mut read, &mut deleted_at),
2119 path,
2120 Current { entity, version },
2121 )?;
2122 continue;
2123 }
2124 if competing {
2126 read.competing.insert(path.clone());
2127 read.versions.insert(entity, all);
2128 }
2129 read.own.insert(entity, version.clone());
2130 if paths.len() > 1 {
2131 read.competing.extend(paths.iter().cloned());
2132 read.paths.insert(entity, paths.clone());
2133 }
2134 if read.by_path.contains_key(&path) {
2135 read.competing.insert(path.clone());
2136 } else {
2137 read.by_path
2138 .insert(path.clone(), Current { entity, version });
2139 }
2140 read.by_entity.insert(entity, path);
2141 }
2142 Ok(read)
2143}
2144
2145fn distinct<T: PartialEq>(values: Vec<T>) -> Vec<T> {
2148 let mut kept = Vec::new();
2149 for value in values {
2150 if !kept.contains(&value) {
2151 kept.push(value);
2152 }
2153 }
2154 kept
2155}
2156
2157fn note_deleted<S: nibkeep_model::storage::Statements>(
2159 state: &nibkeep_model::State<S>,
2160 (read, deleted_at): (
2161 &mut TreeState,
2162 &mut BTreeMap<String, nibkeep_time::Timestamp>,
2163 ),
2164 path: String,
2165 deleted: Current,
2166) -> Result<(), NodeError>
2167where
2168 NodeError: From<S::Error>,
2169{
2170 let when = state
2171 .current(deleted.entity, &fields::DELETED)?
2172 .iter()
2173 .filter_map(|statement| state.recorded(statement.id).ok().flatten())
2174 .max();
2175 let later = match (when, deleted_at.get(&path)) {
2176 (Some(when), Some(known)) => when > *known,
2177 (Some(_) | None, None) => true,
2178 (None, Some(_)) => false,
2179 };
2180 if later {
2181 if let Some(when) = when {
2182 deleted_at.insert(path.clone(), when);
2183 }
2184 read.deleted.insert(path, deleted);
2185 }
2186 Ok(())
2187}
2188
2189fn unseen_deletions<S: nibkeep_model::storage::Statements>(
2195 state: &nibkeep_model::State<S>,
2196 entity: EntityId,
2197 changes: &Changes<'_>,
2198) -> Result<Option<Vec<String>>, NodeError>
2199where
2200 NodeError: From<S::Error>,
2201{
2202 let mut deletions = Vec::new();
2203 for statement in state.current(entity, &fields::DELETED)? {
2204 if statement.value != Value::Boolean(true) {
2205 continue;
2206 }
2207 let Some(change) = state
2209 .storage()
2210 .get(statement.id)?
2211 .and_then(|recorded| recorded.change)
2212 else {
2213 return Ok(None);
2214 };
2215 deletions.push((deletion_key(statement.id), change));
2216 }
2217 if deletions.is_empty() {
2218 return Ok(None);
2219 }
2220 for field in [
2221 &CONTENT,
2222 &SECRET_CONTENT,
2223 &LINK_TARGET,
2224 &EXECUTABLE,
2225 &TREE_PATH,
2226 ] {
2227 for statement in state.current(entity, field)? {
2228 let Some(recorded) = state.storage().get(statement.id)? else {
2229 continue;
2230 };
2231 let (Some(change), None) = (recorded.change, recorded.restated) else {
2232 continue;
2233 };
2234 if changes.purged(change)? {
2235 continue;
2236 }
2237 let mut seen = false;
2238 for (_, deletion) in &deletions {
2239 if changes.saw(change, *deletion)? {
2240 seen = true;
2241 break;
2242 }
2243 }
2244 if !seen {
2245 return Ok(Some(deletions.into_iter().map(|(key, _)| key).collect()));
2246 }
2247 }
2248 }
2249 Ok(None)
2250}
2251
2252fn kind_in_tree<S: nibkeep_model::storage::Statements>(
2257 state: &nibkeep_model::State<S>,
2258 entity: EntityId,
2259 tree: EntityId,
2260) -> Result<Option<(bool, bool)>, NodeError>
2261where
2262 NodeError: From<S::Error>,
2263{
2264 match secret_file_of(state, entity)? {
2265 Secrecy::Of(of) if of == tree => return Ok(Some((false, true))),
2266 Secrecy::Of(_) | Secrecy::OfNone => return Ok(None),
2267 Secrecy::Ordinary => {}
2268 }
2269 let mut in_tree = false;
2270 for statement in state.current(entity, &IN_TREE)? {
2271 if let Value::Reference(of) = statement.value {
2272 in_tree |= state.canonical(of)? == tree;
2273 }
2274 }
2275 if !in_tree {
2276 return Ok(None);
2277 }
2278 let types = state.types(entity)?;
2279 let is_link = types.contains(&SYMBOLIC_LINK);
2280 Ok((is_link || types.contains(&FILE)).then_some((is_link, false)))
2281}
2282
2283type Earliest = Option<(
2286 (Option<nibkeep_time::Timestamp>, nibkeep_base::StatementId),
2287 Value,
2288 Option<Hash>,
2289)>;
2290
2291#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2293enum Secrecy {
2294 Ordinary,
2296 Of(EntityId),
2298 OfNone,
2301}
2302
2303fn secret_file_of<S: nibkeep_model::storage::Statements>(
2309 state: &nibkeep_model::State<S>,
2310 entity: EntityId,
2311) -> Result<Secrecy, NodeError>
2312where
2313 NodeError: From<S::Error>,
2314{
2315 let storage = state.storage();
2316 let earliest = |field: &FieldName,
2318 keep: &dyn Fn(&Value) -> bool|
2319 -> Result<Option<(Value, Option<Hash>)>, NodeError> {
2320 let mut first: Earliest = None;
2321 for id in storage.of_field(entity, field)? {
2322 let Some(recorded) = storage.get(id)? else {
2323 continue;
2324 };
2325 if !keep(&recorded.statement.value) {
2326 continue;
2327 }
2328 let at = (state.recorded(id)?, id);
2329 if first.as_ref().is_none_or(|(known, _, _)| at < *known) {
2330 first = Some((at, recorded.statement.value.clone(), recorded.change));
2331 }
2332 }
2333 Ok(first.map(|(_, value, change)| (value, change)))
2334 };
2335 let secret_type = SECRET_FILE;
2336 if earliest(&fields::TYPE, &|value| {
2337 value.as_text() == Some(secret_type.as_str())
2338 })?
2339 .is_none()
2340 {
2341 return Ok(Secrecy::Ordinary);
2342 }
2343 let Some((_, made_in)) = earliest(&fields::TYPE, &|_| true)? else {
2345 return Ok(Secrecy::OfNone);
2346 };
2347 match earliest(&IN_TREE, &|value| matches!(value, Value::Reference(_)))? {
2348 Some((Value::Reference(tree), Some(change))) if made_in == Some(change) => {
2349 Ok(Secrecy::Of(state.canonical(tree)?))
2350 }
2351 _ => Ok(Secrecy::OfNone),
2352 }
2353}
2354
2355fn all_paths<S: nibkeep_model::storage::Statements>(
2357 state: &nibkeep_model::State<S>,
2358 entity: EntityId,
2359) -> Result<Vec<String>, NodeError>
2360where
2361 NodeError: From<S::Error>,
2362{
2363 let storage = state.storage();
2364 let mut paths = Vec::new();
2365 for id in storage.of_field(entity, &TREE_PATH)? {
2366 if let Some(recorded) = storage.get(id)?
2367 && let Value::Text(path) = &recorded.statement.value
2368 {
2369 paths.push(path.clone());
2370 }
2371 }
2372 Ok(paths)
2373}
2374
2375fn deletion_key(statement: nibkeep_base::StatementId) -> String {
2378 format!("deleted {statement}")
2379}
2380
2381pub fn tree_path_at(root: &Path, path: &Path) -> Result<String, NodeError> {
2390 let shown = || path.display().to_string();
2391 let mut existing = path;
2394 let mut rest = Vec::new();
2395 if let (Some(std::path::Component::Normal(name)), Some(parent)) =
2396 (path.components().next_back(), path.parent())
2397 {
2398 rest.push(name);
2399 existing = parent;
2400 }
2401 let resolved = loop {
2402 if let Some(resolved) = resolved(existing) {
2403 break resolved;
2404 }
2405 rest.push(
2406 existing
2407 .file_name()
2408 .ok_or_else(|| NodeError::NotInTree(shown()))?,
2409 );
2410 existing = existing
2411 .parent()
2412 .ok_or_else(|| NodeError::NotInTree(shown()))?;
2413 };
2414 let mut full = resolved;
2415 full.extend(rest.iter().rev());
2416 let relative = full
2417 .strip_prefix(root)
2418 .map_err(|_| NodeError::NotInTree(shown()))?;
2419 if relative.as_os_str().is_empty() {
2420 return Ok(String::new());
2421 }
2422 paths::tree_path_of(relative).map_err(|_| NodeError::UnsafePath(shown()))
2423}
2424
2425fn resolved(folder: &Path) -> Option<PathBuf> {
2427 fs::canonicalize(folder).ok().map(super::files::plain)
2428}