mod commit;
mod compare;
mod diff;
mod git;
mod history;
mod index;
mod locate;
mod paths;
mod repositories;
mod secrecy;
mod update;
mod walk;
mod write;
use std::cell::RefCell;
use std::collections::{BTreeMap, BTreeSet};
use std::fs::{self, File};
use std::io;
use std::path::{Path, PathBuf};
use nibkeep_base::{EntityId, Hash, SpaceId};
use nibkeep_crypto::rand_core::CryptoRng;
use nibkeep_model::storage::Statements as _;
use nibkeep_model::{FieldName, Name, Statement, TypeName, Value, fields};
use nibkeep_std::{
COMMITTED_IN, CONTENT, EXECUTABLE, FILE, GIT_REPOSITORY, IN_TREE, LINK_TARGET, ON_DEVICE,
PARTS, PATH, REVISION, ROOT_OF, SECRET_CONTENT, SECRET_FILE, SYMBOLIC_LINK, TREE, TREE_PATH,
TREE_ROOT,
};
use nibkeep_log::{ChangeId, Log};
use nibkeep_store::{LogFile, StateFile};
use self::commit::moving;
use self::index::{Entry, INDEX_CONTEXT, Index, SecretVersions, Version};
use self::locate::{Blocked, Listings, Located, located, located_in, place_for_new};
pub use self::repositories::{CloneFolder, GitRepository, RecordedRepository, ToClone};
use super::Library;
use super::entities::NewValue;
use crate::NodeError;
pub use self::diff::FileDiff;
pub use self::history::{BlameLine, TreeLogEntry, TreePoint};
pub use self::paths::is_safe_tree_path;
pub use self::update::Updated;
pub use self::write::{CopiesRemoved, Reverted, Written};
const LOCK: &str = "trees.lock";
const TREE_TYPES: [TypeName; 7] = [
TREE,
TREE_ROOT,
FILE,
SECRET_FILE,
SYMBOLIC_LINK,
REVISION,
GIT_REPOSITORY,
];
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Tree {
pub id: EntityId,
pub name: Option<String>,
pub root: Option<PathBuf>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TreeEntry {
pub entity: EntityId,
pub path: String,
pub kind: TreeEntryKind,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TreeEntryKind {
File {
content: Option<Hash>,
executable: bool,
},
Link {
target: String,
},
Sealed,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TreeChange {
pub path: String,
pub change: Change,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Change {
New,
Edited,
Executable(bool),
Deleted,
Moved {
from: String,
},
Unknown,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TreeStatus {
pub tree: EntityId,
pub root: PathBuf,
pub changes: Vec<TreeChange>,
pub behind: Vec<String>,
pub competing: Vec<String>,
pub skipped: Vec<(String, String)>,
pub cut_short: Vec<CutShort>,
pub read: usize,
pub repositories: Vec<String>,
pub secret: Vec<String>,
pub sealed: Vec<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct TreeSecrets {
pub secret: Vec<String>,
pub sealed: Vec<String>,
pub looking_secret: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct InTree {
pub tree: EntityId,
pub path: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct MadeSecret {
pub purged: Vec<Hash>,
pub kept: Vec<Hash>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CutShort {
pub revision: EntityId,
pub parts: u64,
pub made: u64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Commit<'a> {
message: Option<&'a str>,
paths: Vec<String>,
force: bool,
cut_after: Option<usize>,
repositories: Option<Repositories<'a>>,
secret: Vec<String>,
ordinary: Vec<String>,
leave_secrets: bool,
}
#[derive(Clone, Copy)]
enum Repositories<'a> {
Given(&'a [GitRepository]),
Read(&'a dyn Fn(&[String]) -> Vec<GitRepository>),
}
impl std::fmt::Debug for Repositories<'_> {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Given(repositories) => {
formatter.debug_tuple("Given").field(repositories).finish()
}
Self::Read(_) => formatter.write_str("Read"),
}
}
}
impl PartialEq for Repositories<'_> {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::Given(a), Self::Given(b)) => a == b,
(Self::Read(a), Self::Read(b)) => std::ptr::addr_eq(*a, *b),
_ => false,
}
}
}
impl Eq for Repositories<'_> {}
impl<'a> Commit<'a> {
#[must_use]
pub fn new(message: Option<&'a str>) -> Self {
Self {
message,
paths: Vec::new(),
force: false,
cut_after: None,
repositories: None,
secret: Vec::new(),
ordinary: Vec::new(),
leave_secrets: false,
}
}
#[must_use]
pub fn with_repositories(mut self, repositories: &'a [GitRepository]) -> Self {
self.repositories = Some(Repositories::Given(repositories));
self
}
#[must_use]
pub fn with_repositories_read_by(
mut self,
read: &'a dyn Fn(&[String]) -> Vec<GitRepository>,
) -> Self {
self.repositories = Some(Repositories::Read(read));
self
}
#[must_use]
pub fn with_paths(mut self, paths: Vec<String>) -> Self {
self.paths = paths;
self
}
#[must_use]
pub fn with_force(mut self) -> Self {
self.force = true;
self
}
#[must_use]
pub fn with_secret(mut self, paths: Vec<String>) -> Self {
self.secret = paths;
self
}
#[must_use]
pub fn with_ordinary(mut self, paths: Vec<String>) -> Self {
self.ordinary = paths;
self
}
#[must_use]
pub fn leaving_secrets(mut self) -> Self {
self.leave_secrets = true;
self
}
#[must_use]
pub fn cut_after(mut self, parts: usize) -> Self {
self.cut_after = Some(parts);
self
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Committed {
pub revision: Option<EntityId>,
pub parts: usize,
pub changes: Vec<TreeChange>,
pub repositories: Vec<TreeChange>,
pub secret: Vec<String>,
pub left: Vec<String>,
pub unprotected: Vec<String>,
pub made_secret: Vec<EntityId>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StartPreview {
pub files: usize,
pub bytes: u64,
pub repositories: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TreeStarted {
pub tree: EntityId,
pub root: PathBuf,
pub committed: Committed,
}
#[derive(Clone, Debug)]
struct Current {
entity: EntityId,
version: Option<Version>,
}
#[derive(Debug, Default)]
struct TreeState {
by_path: BTreeMap<String, Current>,
by_entity: BTreeMap<EntityId, String>,
competing: BTreeSet<String>,
deleted: BTreeMap<String, Current>,
own: BTreeMap<EntityId, Option<Version>>,
versions: BTreeMap<EntityId, Vec<Version>>,
paths: BTreeMap<EntityId, Vec<String>>,
contested: BTreeMap<EntityId, Vec<String>>,
secret: BTreeSet<EntityId>,
sealed: BTreeMap<String, EntityId>,
secret_paths: BTreeSet<String>,
}
impl TreeState {
fn fill_sealed(&mut self, entries: &BTreeMap<String, Entry>) {
for (path, entity) in std::mem::take(&mut self.sealed) {
let Some(entry) = entries.values().find(|entry| entry.entity == entity) else {
self.sealed.insert(path, entity);
continue;
};
let version = Some(entry.version.clone());
self.own.insert(entity, version.clone());
if self.by_path.contains_key(&path) {
self.competing.insert(path.clone());
} else {
self.by_path
.insert(path.clone(), Current { entity, version });
}
self.by_entity.insert(entity, path);
}
}
fn is_secret(&self, entity: EntityId) -> bool {
self.secret.contains(&entity)
}
fn holds(&self, path: &str, entity: EntityId, version: &Version) -> bool {
self.at(entity, path) && self.has_version(entity, version)
}
fn at(&self, entity: EntityId, path: &str) -> bool {
self.by_entity.get(&entity).is_some_and(|at| at == path)
|| self
.paths
.get(&entity)
.is_some_and(|paths| paths.iter().any(|at| at == path))
}
fn has_version(&self, entity: EntityId, version: &Version) -> bool {
match self.versions.get(&entity) {
Some(all) => all.contains(version),
None => self
.own
.get(&entity)
.is_some_and(|own| own.as_ref() == Some(version)),
}
}
}
impl Library {
pub fn would_start_tree(
&self,
space: SpaceId,
folder: &Path,
) -> Result<StartPreview, NodeError> {
let root = self.checked_new_root(space, folder)?;
let walked = walk::walk(&root, &BTreeSet::new(), &self.apart());
Ok(StartPreview {
files: walked.found.len(),
bytes: walked.found.values().map(|found| found.size).sum(),
repositories: walked.repositories,
})
}
pub fn start_tree(
&mut self,
space: SpaceId,
folder: &Path,
message: Option<&str>,
wall_millis: u64,
rng: &mut impl CryptoRng,
) -> Result<TreeStarted, NodeError> {
self.start_tree_with(space, folder, &Commit::new(message), wall_millis, rng)
}
pub fn start_tree_with(
&mut self,
space: SpaceId,
folder: &Path,
commit: &Commit<'_>,
wall_millis: u64,
rng: &mut impl CryptoRng,
) -> Result<TreeStarted, NodeError> {
self.check_not_revoked(space)?;
let _locked = self.lock_trees()?;
let root = self.checked_new_root(space, folder)?;
self.install_standard(space, &TREE_TYPES, wall_millis, rng)?;
let name = root
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.filter(|name| !name.is_empty());
let mut values = Vec::new();
if let Some(name) = name {
values.push(NewValue::new(fields::NAME, Value::Name(Name::new(&name))));
}
let (tree, founded) = self.new_entity(space, &[TREE], values, rng)?;
let (root_entity, rooted) = self.new_entity(
space,
&[TREE_ROOT],
vec![
NewValue::new(ROOT_OF, Value::Reference(tree)),
NewValue::new(ON_DEVICE, Value::Reference(self.info.device)),
NewValue::new(PATH, Value::Text(root.to_string_lossy().into_owned())),
],
rng,
)?;
let founding = vec![(Some(tree), founded), (None, rooted)];
let committed =
self.commit_in(space, (tree, &root), commit, founding, (wall_millis, rng))?;
self.index()?.set_root(tree, root_entity, &root)?;
Ok(TreeStarted {
tree,
root,
committed,
})
}
pub fn trees(&self, space: SpaceId) -> Result<Vec<Tree>, NodeError> {
let open = self.space(space)?;
let state = open.stored.log().state();
let roots = self.roots_here(space)?;
let mut trees = Vec::new();
for tree in super::entities::with_type(&open.stored, &TREE)? {
let tree = state.canonical(tree)?;
if state.is_deleted(tree)? || trees.iter().any(|known: &Tree| known.id == tree) {
continue;
}
trees.push(Tree {
id: tree,
name: self.name(space, tree)?,
root: roots.get(&tree).cloned(),
});
}
trees.sort_by(|a, b| a.name.cmp(&b.name).then(a.id.cmp(&b.id)));
Ok(trees)
}
pub fn tree_at(&self, space: SpaceId, folder: &Path) -> Result<Option<Tree>, NodeError> {
let Some(folder) = resolved(folder) else {
return Ok(None);
};
let roots = self.roots_here(space)?;
let Some((&tree, root)) = roots.iter().find(|(_, root)| folder.starts_with(root)) else {
return Ok(None);
};
Ok(Some(Tree {
id: tree,
name: self.name(space, tree)?,
root: Some(root.clone()),
}))
}
pub fn tree_entries(
&self,
space: SpaceId,
tree: EntityId,
) -> Result<Vec<TreeEntry>, NodeError> {
let state = self.tree_state(space, tree)?;
let mut entries: Vec<TreeEntry> = state
.by_path
.into_iter()
.map(|(path, current)| TreeEntry {
entity: current.entity,
path,
kind: match current.version {
Some(Version::Link { target }) => TreeEntryKind::Link { target },
Some(Version::File {
content,
executable,
}) => TreeEntryKind::File {
content: Some(content),
executable,
},
None => TreeEntryKind::File {
content: None,
executable: false,
},
},
})
.chain(state.sealed.into_iter().map(|(path, entity)| TreeEntry {
entity,
path,
kind: TreeEntryKind::Sealed,
}))
.collect();
entries.sort_by(|a, b| a.path.cmp(&b.path));
Ok(entries)
}
pub fn tree_status(&self, space: SpaceId, tree: EntityId) -> Result<TreeStatus, NodeError> {
let _locked = self.lock_trees()?;
let root = self.root_here(space, tree)?;
let mut index = self.index()?;
let purged = self.learn_purges(space, &index)?;
let state = self.tree_state(space, tree)?;
let apart = self.apart();
settle_tree((tree, &root, &apart), &mut index, (&purged, &state))?;
self.follow_cut_short(space, (tree, &root, &apart), &mut index, &state)?;
let read_new = !purged.is_empty();
let compared = self.compare(space, (tree, &root), &state, &index, (&purged, read_new))?;
index.change(tree, &compared.forgotten, &compared.refreshed)?;
self.note_secrets(space, (tree, &index), &state, &compared.refreshed)?;
index.unmark(tree, &compared.unmarked)?;
if compared.known {
index.know(tree)?;
}
Ok(TreeStatus {
tree,
root,
changes: compared
.pending
.iter()
.map(|pending| TreeChange {
path: pending.path.clone(),
change: pending.change.clone(),
})
.collect(),
secret: compared
.pending
.iter()
.filter(|pending| pending.secret)
.map(|pending| pending.path.clone())
.collect(),
sealed: state.sealed.keys().cloned().collect(),
behind: compared.behind.into_iter().collect(),
competing: state.competing.into_iter().collect(),
skipped: compared
.skipped
.into_iter()
.chain(compared.marked)
.collect(),
cut_short: self.cut_short(space, tree)?,
read: compared.read,
repositories: compared.repositories,
})
}
pub fn commit_tree(
&mut self,
space: SpaceId,
tree: EntityId,
commit: &Commit<'_>,
wall_millis: u64,
rng: &mut impl CryptoRng,
) -> Result<Committed, NodeError> {
self.check_not_revoked(space)?;
let _locked = self.lock_trees()?;
let root = self.root_here(space, tree)?;
self.install_standard(space, &TREE_TYPES, wall_millis, rng)?;
self.commit_in(space, (tree, &root), commit, Vec::new(), (wall_millis, rng))
}
pub fn tree_secrets(&self, space: SpaceId, tree: EntityId) -> Result<TreeSecrets, NodeError> {
let tree = self.check_tree(space, tree)?;
let state = self.tree_state(space, tree)?;
let rules = match self.root_here(space, tree) {
Ok(root) => {
let index = self.index()?;
let left_out = self.left_out(space, tree, &root, &index)?;
secrecy::Rules::of_copy(&walk::walk(&root, &left_out, &self.apart()).found)
}
Err(_) => secrecy::Rules::built_in(),
};
let mut listed = TreeSecrets {
sealed: state.sealed.keys().cloned().collect(),
..TreeSecrets::default()
};
for (path, current) in &state.by_path {
if state.is_secret(current.entity) {
listed.secret.push(path.clone());
} else if matches!(current.version, Some(Version::File { .. })) && rules.is_secret(path)
{
listed.looking_secret.push(path.clone());
}
}
listed.secret.extend(listed.sealed.iter().cloned());
listed.secret.sort();
listed.secret.dedup();
Ok(listed)
}
pub fn secret_file_in_tree(
&self,
space: SpaceId,
file: EntityId,
) -> Result<Option<InTree>, NodeError> {
self.space(space)?.stored.reading(|stored| {
let state = stored.log().state();
let file = state.canonical(file)?;
let Secrecy::Of(tree) = secret_file_of(state, file)? else {
return Ok(None);
};
let mut statements = state.current(file, &TREE_PATH)?;
statements.sort_by_key(|statement| statement.id);
let path = statements
.iter()
.find_map(|statement| match &statement.value {
Value::Text(path) => Some(path.clone()),
_ => None,
})
.filter(|path| is_safe_tree_path(path));
Ok(Some(InTree { tree, path }))
})
}
pub fn would_purge_made_secret(
&self,
space: SpaceId,
file: EntityId,
) -> Result<MadeSecret, NodeError> {
let mut contents: Vec<(Option<nibkeep_time::Timestamp>, Hash)> = Vec::new();
{
let state = self.space(space)?.stored.log().state();
if !state.is_deleted(state.canonical(file)?)? {
return Ok(MadeSecret::default());
}
for id in state.storage().of_field(file, &CONTENT)? {
if let Some(recorded) = state.storage().get(id)?
&& let Value::Blob(content) = recorded.statement.value
&& contents.iter().all(|(_, known)| *known != content)
{
contents.push((state.recorded(id)?, content));
}
}
}
contents.sort();
let mut made = MadeSecret::default();
for (_, content) in contents {
let purge = self.purgeable(space, file, &CONTENT, Some(&Value::Blob(content)))?;
if purge.also.is_empty() {
made.purged.push(content);
} else {
made.kept.push(content);
}
}
Ok(made)
}
pub fn purge_made_secret(
&mut self,
space: SpaceId,
file: EntityId,
wall_millis: u64,
rng: &mut impl CryptoRng,
) -> Result<MadeSecret, NodeError> {
let made = self.would_purge_made_secret(space, file)?;
for content in &made.purged {
let value = Value::Blob(*content);
self.purge(space, file, &CONTENT, Some(&value), wall_millis, rng)?;
}
Ok(made)
}
pub fn move_in_tree(
&mut self,
space: SpaceId,
tree: EntityId,
(from, to): (&str, &str),
wall_millis: u64,
rng: &mut impl CryptoRng,
) -> Result<Committed, NodeError> {
self.check_not_revoked(space)?;
let _locked = self.lock_trees()?;
let root = self.root_here(space, tree)?;
if !is_safe_tree_path(to) || !to.split('/').all(paths::fits_this_system) {
return Err(NodeError::UnsafePath(to.to_owned()));
}
self.install_standard(space, &TREE_TYPES, wall_millis, rng)?;
let state = self.tree_state(space, tree)?;
let mut index = self.index()?;
let entries = index.entries(tree)?;
let under = |path: &str| path == from || path.starts_with(&format!("{from}/"));
let moved_to = |path: &str| format!("{to}{}", &path[from.len()..]);
let moved: Vec<(String, String, EntityId)> = state
.by_entity
.iter()
.filter(|(_, path)| under(path))
.map(|(entity, path)| (path.clone(), moved_to(path), *entity))
.collect();
if moved.is_empty() {
return Err(NodeError::NotInTree(from.to_owned()));
}
if to == from || to.starts_with(&format!("{from}/")) {
return Err(NodeError::UnsafePath(to.to_owned()));
}
let clashes = |path: &String| {
path == to || path.starts_with(&format!("{to}/")) || to.starts_with(&format!("{path}/"))
};
if state.by_path.keys().chain(entries.keys()).any(clashes) {
return Err(NodeError::PlaceTaken(root.join(to)));
}
let apart = self.apart();
let Located::Here(source) = located(&root, from, &apart) else {
return Err(NodeError::NotInTree(from.to_owned()));
};
if self
.left_out(space, tree, &root, &index)?
.iter()
.any(|path| under(path))
{
return Err(NodeError::HoldsOtherCopies(from.to_owned()));
}
let blocked = |why| match why {
Blocked::Taken => NodeError::PlaceTaken(root.join(to)),
Blocked::Unsafe => NodeError::UnsafePath(to.to_owned()),
};
let target = place_for_new(&root, to, &apart).map_err(blocked)?;
if let Some(parent) = target.parent() {
write::make_folders(parent).map_err(NodeError::file(parent))?;
if place_for_new(&root, to, &apart).as_ref() != Ok(&target) {
return Err(NodeError::UnsafePath(to.to_owned()));
}
}
fs::rename(&source, &target).map_err(NodeError::file(&source))?;
save_move(&source, &target);
let mut parts: Vec<(EntityId, Vec<nibkeep_model::Operation>)> = Vec::new();
let mut changes = Vec::new();
let mut removed = Vec::new();
let mut set = Vec::new();
{
let open = self.space(space)?;
let space_state = open.stored.log().state();
for (old, new, entity) in &moved {
parts.push((*entity, moving(space_state, *entity, old, new, rng)?));
changes.push(TreeChange {
path: new.clone(),
change: Change::Moved { from: old.clone() },
});
}
for (old, entry) in entries.iter().filter(|(path, _)| under(path)) {
removed.push(old.clone());
set.push((moved_to(old), entry.clone()));
}
}
let count = parts.len() + 1;
let saved = self.batch_whole(space, |library| {
let (revision, made) = library.revision_operations(space, tree, None, count, rng)?;
library.commit(space, made, wall_millis, rng)?;
for (entity, operations) in parts {
let operations =
library.part_operations(space, revision, entity, operations, rng)?;
library.commit(space, operations, wall_millis, rng)?;
}
Ok(revision)
});
let revision = match saved {
Ok(revision) => revision,
Err(error) => {
let _ = fs::rename(&target, &source);
return Err(error);
}
};
changes.sort_by(|a, b| a.path.cmp(&b.path));
changes.dedup();
index.change(tree, &removed, &set)?;
Ok(Committed {
revision: Some(revision),
parts: count,
changes,
..Committed::default()
})
}
}
impl Library {
fn checked_new_root(&self, space: SpaceId, folder: &Path) -> Result<PathBuf, NodeError> {
let root = fs::canonicalize(folder).map_err(NodeError::file(folder))?;
let root = super::files::plain(root);
if !root.is_dir() {
return Err(NodeError::file(&root)(io::ErrorKind::NotADirectory.into()));
}
let in_reserved = root.components().any(|component| match component {
std::path::Component::Normal(name) => paths::is_reserved(&name.to_string_lossy()),
_ => false,
});
if in_reserved || self.apart().iter().any(|apart| root.starts_with(apart)) {
return Err(NodeError::NotATreeFolder(root));
}
let _ = space;
for &any in self.spaces.keys() {
for other in self.roots_here(any)?.values() {
if root.starts_with(other) || other.starts_with(&root) {
return Err(NodeError::TreeInTree(root));
}
}
}
if fs::symlink_metadata(root.join(".git")).is_ok() || walk::is_bare(&root) {
return Err(NodeError::GitRepositoryHere(root));
}
Ok(root)
}
fn roots_here(&self, space: SpaceId) -> Result<BTreeMap<EntityId, PathBuf>, NodeError> {
let open = self.space(space)?;
let state = open.stored.log().state();
let alive = |entity: EntityId| -> Result<bool, NodeError> {
Ok(!state.is_deleted(state.canonical(entity)?)?)
};
let mut roots = BTreeMap::new();
let recorded = if self.directory().join(index::INDEX).exists() {
self.index()?.roots()?
} else {
BTreeMap::new()
};
for (tree, (root, folder)) in &recorded {
let in_space = !state.types(*root)?.is_empty();
if in_space && alive(*root)? && alive(*tree)? {
roots.insert(state.canonical(*tree)?, folder.clone());
}
}
let this_replica = self.replica.signing.verifying_key();
for root in open
.stored
.find(&ON_DEVICE, &Value::Reference(self.info.device))?
{
let root = state.canonical(root)?;
if state.is_deleted(root)? || !state.types(root)?.contains(&TREE_ROOT) {
continue;
}
let mut values = BTreeMap::new();
let mut own = true;
for field in [&ROOT_OF, &ON_DEVICE, &PATH] {
let mut current = state.current(root, field)?;
current.sort_by_key(|statement| statement.id);
for statement in ¤t {
own &= open.stored.log().author_of(statement.id)? == Some(this_replica);
}
let first = current.first().map(|statement| statement.value.clone());
values.insert(field.clone(), first);
}
let (true, Some(Some(Value::Reference(tree))), Some(Some(Value::Text(path)))) =
(own, values.remove(&ROOT_OF), values.remove(&PATH))
else {
continue;
};
let tree = state.canonical(tree)?;
if alive(tree)? {
roots.entry(tree).or_insert_with(|| PathBuf::from(path));
}
}
Ok(roots)
}
pub(crate) fn in_any_tree(&self, folder: &Path) -> Result<bool, NodeError> {
let Some(folder) = resolved(folder) else {
return Ok(false);
};
for &space in self.spaces.keys() {
if self
.roots_here(space)?
.values()
.any(|root| folder.starts_with(root))
{
return Ok(true);
}
}
Ok(false)
}
pub(super) fn check_tree(&self, space: SpaceId, tree: EntityId) -> Result<EntityId, NodeError> {
let state = self.space(space)?.stored.log().state();
let tree = state.canonical(tree)?;
if state.is_deleted(tree)? || !state.types(tree)?.contains(&TREE) {
return Err(NodeError::NotATree(tree.to_string()));
}
Ok(tree)
}
fn root_here(&self, space: SpaceId, tree: EntityId) -> Result<PathBuf, NodeError> {
let tree = self.space(space)?.stored.log().state().canonical(tree)?;
let root = self
.roots_here(space)?
.remove(&tree)
.ok_or_else(|| NodeError::NoTreeHere(tree.to_string()))?;
if !fs::symlink_metadata(&root).is_ok_and(|metadata| metadata.is_dir()) {
return Err(NodeError::TreeFolderGone(root));
}
Ok(root)
}
fn index(&self) -> Result<Index, NodeError> {
Index::open(self.directory(), &self.derived_key(INDEX_CONTEXT))
}
fn index_if_any(&self) -> Result<Option<Index>, NodeError> {
if fs::symlink_metadata(self.directory().join(index::INDEX)).is_err() {
return Ok(None);
}
self.index().map(Some)
}
fn device_name_of(
&self,
space: SpaceId,
statement: nibkeep_base::StatementId,
) -> Option<String> {
let named = || -> Result<Option<String>, NodeError> {
let Some(author) = self.author_of(space, statement)? else {
return Ok(None);
};
let personal = self.personal_space();
let roster = self.space(personal)?.stored.log().state();
let device = roster
.current(author.replica, &nibkeep_governance::ON_DEVICE)?
.into_iter()
.find_map(|statement| statement.value.as_reference());
match device {
Some(device) => self.name(personal, device),
None => Ok(None),
}
};
named().ok().flatten()
}
fn try_lock_trees(&self) -> Result<Option<File>, NodeError> {
let path = self.directory().join(LOCK);
let file = File::options()
.create(true)
.truncate(false)
.write(true)
.open(&path)
.map_err(NodeError::file(&path))?;
match file.try_lock() {
Ok(()) => Ok(Some(file)),
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
Err(std::fs::TryLockError::Error(error)) => Err(NodeError::file(&path)(error)),
}
}
fn lock_trees(&self) -> Result<File, NodeError> {
let path = self.directory().join(LOCK);
let file = File::options()
.create(true)
.truncate(false)
.write(true)
.open(&path)
.map_err(NodeError::file(&path))?;
file.lock().map_err(NodeError::file(&path))?;
Ok(file)
}
fn tree_state(&self, space: SpaceId, tree: EntityId) -> Result<TreeState, NodeError> {
let open = self.space(space)?;
let readable = self.secrets_unlocked(space);
let mut read = open.stored.reading(|stored| {
let log = stored.log();
let state = log.state();
let entities = tree_entities(state, tree)?;
read_tree_state(state, tree, &entities, (Some(&Changes::of(log)), readable))
})?;
if !read.sealed.is_empty()
&& let Some(index) = self.index_if_any()?
{
read.fill_sealed(&index.entries(tree)?);
}
Ok(read)
}
fn note_secrets(
&self,
space: SpaceId,
(tree, index): (EntityId, &Index),
state: &TreeState,
set: &[(String, Entry)],
) -> Result<(), NodeError> {
let versions = set.iter().filter_map(|(_, entry)| match entry.version {
Version::File { content, .. } if state.is_secret(entry.entity) => {
Some((entry.entity, content))
}
_ => None,
});
self.note_secret_versions(space, (tree, index), versions)
}
fn note_secret_versions(
&self,
space: SpaceId,
(tree, index): (EntityId, &Index),
versions: impl IntoIterator<Item = (EntityId, Hash)>,
) -> Result<(), NodeError> {
let log = self.space(space)?.stored.log();
for (entity, content) in versions {
let sealed: BTreeSet<Hash> = log
.blob_keys(&content)
.filter(|(sealed, _)| log.is_secret_blob(sealed))
.map(|(sealed, _)| *sealed)
.collect();
index.note_secret(tree, (entity, content), &sealed)?;
}
Ok(())
}
fn left_out(
&self,
space: SpaceId,
tree: EntityId,
root: &Path,
index: &Index,
) -> Result<BTreeSet<String>, NodeError> {
let mut left_out: BTreeSet<String> = index.marked(tree)?.into_keys().collect();
for checkout in self.checkouts(space)? {
if let Ok(relative) = checkout.path.strip_prefix(root)
&& let Ok(path) = paths::tree_path_of(relative)
{
left_out.insert(path);
}
}
Ok(left_out)
}
fn apart(&self) -> Vec<PathBuf> {
self.library_directory()
.and_then(|directory| fs::canonicalize(directory).ok())
.map(super::files::plain)
.into_iter()
.collect()
}
fn is_purged(
&self,
space: SpaceId,
entry: &Entry,
secret_versions: &SecretVersions,
) -> Result<bool, NodeError> {
let Version::File { content, .. } = entry.version else {
return Ok(false);
};
let log = self.space(space)?.stored.log();
if let Some(sealed) = secret_versions.get(&(entry.entity, content)) {
if sealed.is_empty() {
return Ok(false);
}
for sealed in sealed {
if !nibkeep_log::History::is_blob_purged(log.history(), sealed)? {
return Ok(false);
}
}
return Ok(true);
}
let state = log.state();
if secret_file_of(state, entry.entity)? != Secrecy::Ordinary {
return Ok(false);
}
if log
.blob_keys(&content)
.any(|(sealed, _)| !log.is_secret_blob(sealed))
{
return Ok(false);
}
for entity in state.merged(state.canonical(entry.entity)?)? {
for id in state.storage().of_field(entity, &CONTENT)? {
if state
.statement(id)?
.is_some_and(|statement| statement.value == Value::Blob(content))
{
return Ok(false);
}
}
}
Ok(true)
}
fn purges_of(&self, space: SpaceId) -> Result<usize, NodeError> {
let log = self.space(space)?.stored.log();
Ok(nibkeep_log::History::purged_blobs(log.history())?.len())
}
fn learn_purges(&self, space: SpaceId, index: &Index) -> Result<Purged, NodeError> {
let purges = self.purges_of(space)?;
let roots = self.roots_here(space)?;
let mut secret_versions = SecretVersions::new();
for tree in roots.keys() {
secret_versions.extend(index.secret_versions(*tree)?);
}
if index.settled(space)? != Some(purges) {
let mut learned = BTreeSet::new();
let mut learned_secrets = BTreeSet::new();
for tree in roots.keys() {
for entry in index.entries(*tree)?.values() {
if let Version::File { content, .. } = entry.version
&& self.is_purged(space, entry, &secret_versions)?
{
if secret_versions.contains_key(&(entry.entity, content)) {
learned_secrets.insert(content);
} else {
learned.insert(content);
}
}
}
}
index.add_purged(&learned)?;
index.add_purged_secrets(&learned_secrets)?;
index.set_settled(space, purges)?;
}
Ok(Purged {
ordinary: index.purged()?,
secret: index.purged_secrets()?,
secret_versions,
})
}
pub(crate) fn note_purged(
&self,
space: SpaceId,
(contents, secret): (&BTreeSet<Hash>, bool),
) -> Result<(), NodeError> {
if contents.is_empty() || self.roots_here(space)?.is_empty() {
return Ok(());
}
let _locked = self.lock_trees()?;
let index = self.index()?;
if secret {
index.add_purged_secrets(contents)
} else {
index.add_purged(contents)
}
}
pub(crate) fn tree_copies_holding(
&self,
space: SpaceId,
contents: &BTreeSet<Hash>,
secret: bool,
) -> Result<Vec<(PathBuf, bool)>, NodeError> {
let roots = self.roots_here(space)?;
let mut holding = Vec::new();
if roots.is_empty() || contents.is_empty() {
return Ok(holding);
}
let index = self.index()?;
for (tree, root) in roots {
let secret_versions = index.secret_versions(tree)?;
for (path, entry) in index.entries(tree)? {
let Version::File { content, .. } = entry.version else {
continue;
};
if !contents.contains(&content)
|| secret_versions.contains_key(&(entry.entity, content)) != secret
{
continue;
}
let Located::Here(on_disk) = located(&root, &path, &self.apart()) else {
continue;
};
if let Ok(at) = walk::look(&on_disk)
&& at.kind == walk::FoundKind::File
{
let edited = walk::hash_found(&at).map_or(true, |found| found != content);
holding.push((on_disk, edited));
}
}
}
holding.sort();
Ok(holding)
}
pub(crate) fn settle_trees_in(&self, space: SpaceId) -> Result<Vec<PathBuf>, NodeError> {
let roots = self.roots_here(space)?;
if roots.is_empty() {
return Ok(Vec::new());
}
let mut index = self.index()?;
if index.settled(space)? == Some(self.purges_of(space)?) {
return Ok(Vec::new());
}
let Some(_locked) = self.try_lock_trees()? else {
return Ok(Vec::new());
};
let purged = self.learn_purges(space, &index)?;
let apart = self.apart();
let mut deleted = Vec::new();
for (tree, root) in roots {
if fs::symlink_metadata(&root).is_ok_and(|metadata| metadata.is_dir()) {
let state = self.tree_state(space, tree)?;
let settling = (&purged, &state);
let place = (tree, root.as_path(), apart.as_slice());
deleted.extend(settle_tree(place, &mut index, settling)?);
}
}
Ok(deleted)
}
fn cut_short(&self, space: SpaceId, tree: EntityId) -> Result<Vec<CutShort>, NodeError> {
let open = self.space(space)?;
let state = open.stored.log().state();
let mut commits = Vec::new();
for revision in open.stored.find(&IN_TREE, &Value::Reference(tree))? {
if !state.types(revision)?.contains(&REVISION) {
continue;
}
let first = |field: &FieldName| -> Result<Option<Statement>, NodeError> {
Ok(state
.current(revision, field)?
.into_iter()
.min_by_key(|statement| statement.id)
.map(std::borrow::Cow::into_owned))
};
let Some(in_tree) = first(&IN_TREE)? else {
continue;
};
let parts = match first(&PARTS)?.map(|statement| statement.value) {
Some(Value::Integer(parts)) => u64::try_from(parts).ok(),
_ => None,
};
let made_at = state.recorded(in_tree.id)?;
let made_by = open.stored.log().author_of(in_tree.id)?;
commits.push((revision, made_by, made_at, parts));
}
let mut last: Vec<(
nibkeep_crypto::VerifyingKey,
Option<nibkeep_time::Timestamp>,
)> = Vec::new();
for (_, made_by, made_at, _) in &commits {
let Some(made_by) = made_by else {
continue;
};
match last.iter_mut().find(|(by, _)| by == made_by) {
Some((_, at)) => *at = (*at).max(*made_at),
None => last.push((*made_by, *made_at)),
}
}
let mut cut = Vec::new();
for (revision, made_by, made_at, parts) in commits {
let Some(parts) = parts else {
continue;
};
let later = made_by
.is_some_and(|made_by| last.iter().any(|(by, at)| *by == made_by && *at > made_at));
if later {
continue;
}
let here = history::parts_here(state, revision)?.len() + 1;
let made = u64::try_from(here).unwrap_or(u64::MAX);
if made < parts {
cut.push(CutShort {
revision,
parts,
made,
});
}
}
Ok(cut)
}
}
fn settle_tree(
(tree, root, apart): (EntityId, &Path, &[PathBuf]),
index: &mut Index,
(purged, state): (&Purged, &TreeState),
) -> Result<Vec<PathBuf>, NodeError> {
let mut deleted = Vec::new();
let mut removed = Vec::new();
if purged.is_empty() {
return Ok(deleted);
}
let entries = index.entries(tree)?;
let mut holding: Vec<(String, Option<Hash>, bool)> = entries
.iter()
.filter_map(|(path, entry)| match entry.version {
Version::File { content, .. } if purged.holds(entry) => {
Some((path.clone(), Some(content), purged.is_secret(entry)))
}
_ => None,
})
.collect();
holding.extend(
state
.by_path
.iter()
.filter(|(path, current)| current.version.is_none() && !entries.contains_key(*path))
.map(|(path, current)| (path.clone(), None, state.is_secret(current.entity))),
);
for (path, content, secret) in holding {
let on_disk = match located(root, &path, apart) {
Located::Here(on_disk) => on_disk,
Located::Absent => {
removed.push(path);
continue;
}
Located::Unknown(_) => continue,
};
let Ok(at) = walk::look(&on_disk) else {
continue;
};
if at.kind != walk::FoundKind::File {
removed.push(path);
continue;
}
match walk::hash_found(&at) {
Ok(found)
if content.map_or(purged.contains(&found, secret), |content| found == content) =>
{
let unchanged = walk::look(&on_disk).is_ok_and(|now| {
now.identity == at.identity
&& now.size == at.size
&& now.modified == at.modified
});
if unchanged && fs::remove_file(&on_disk).is_ok() {
super::checkouts::sync_folder_of(&on_disk);
deleted.push(on_disk);
removed.push(path);
}
}
Ok(_) => removed.push(path),
Err(_) => {}
}
}
index.change(tree, &removed, &[])?;
Ok(deleted)
}
fn save_move(source: &Path, target: &Path) {
super::checkouts::sync_folder_of(source);
super::checkouts::sync_folder_of(target);
}
impl Library {
fn follow_cut_short(
&self,
space: SpaceId,
(tree, root, apart): (EntityId, &Path, &[PathBuf]),
index: &mut Index,
state: &TreeState,
) -> Result<(), NodeError> {
let entries = index.entries(tree)?;
write::bring_back_aside(write::Place { root, apart }, entries.keys());
let read_at = walk::nanos(std::time::SystemTime::now()).unwrap_or(0);
let listings = Listings::apart(apart);
let at = |path: &str| located_in(&listings, root, path);
let gone = |path: &str| at(path) == Located::Absent;
let holding = |path: &str, (entity, version): (EntityId, &Version)| {
let Located::Here(on_disk) = at(path) else {
return None;
};
let found = walk::look(&on_disk).ok()?;
let holds = write::copy_version(&found)?;
write::same_version(&found, &holds, version).then(|| Entry {
entity,
version: version.clone(),
size: found.size,
modified: found.modified,
read_at,
})
};
let mut removed: Vec<String> = Vec::new();
let mut set: BTreeMap<String, Entry> = BTreeMap::new();
let writing = index.writing(tree)?;
for (path, entity, version) in &writing {
let recorded = entries
.get(path)
.is_some_and(|entry| entry.entity == *entity && entry.version == *version);
if recorded {
continue;
}
let Some(written) = holding(path, (*entity, version)) else {
continue;
};
removed.extend(
entries
.iter()
.filter(|(from, entry)| entry.entity == *entity && *from != path && gone(from))
.map(|(from, _)| from.clone()),
);
set.insert(path.clone(), written);
}
let changed = |path: &str, entry: Option<&Entry>| match (at(path), entry) {
(Located::Here(on_disk), Some(entry)) => {
walk::look(&on_disk).is_ok_and(|found| !entry.untouched(found.size, found.modified))
}
(Located::Here(_), None) => index.knows(tree).unwrap_or(false),
(Located::Absent, Some(_)) => true,
_ => false,
};
for (path, entity, version) in self.committed_here(space, &entries, state, &changed)? {
let from = entries
.iter()
.find(|(_, entry)| entry.entity == entity)
.map(|(from, _)| from.clone());
let moved = from.as_ref().filter(|from| **from != path);
if set.contains_key(&path)
|| moved.is_some_and(|from| !gone(from) || entries.contains_key(&path))
{
continue;
}
removed.extend(moved.cloned());
let entry = Entry {
entity,
version,
size: 0,
modified: None,
read_at,
};
set.insert(path, entry);
}
for (path, entry) in &entries {
let Some(now_at) = state.by_entity.get(&entry.entity) else {
continue;
};
if now_at == path
|| entries.contains_key(now_at)
|| set.contains_key(now_at)
|| removed.contains(path)
|| !gone(path)
{
continue;
}
let Some(moved) = holding(now_at, (entry.entity, &entry.version)) else {
continue;
};
removed.push(path.clone());
set.insert(now_at.clone(), moved);
}
let set: Vec<(String, Entry)> = set.into_iter().collect();
index.change(tree, &removed, &set)?;
self.note_secrets(space, (tree, index), state, &set)?;
if !writing.is_empty() {
index.forget_writing(tree)?;
}
Ok(())
}
fn committed_here(
&self,
space: SpaceId,
entries: &BTreeMap<String, Entry>,
state: &TreeState,
changed: &dyn Fn(&str, Option<&Entry>) -> bool,
) -> Result<Vec<(String, EntityId, Version)>, NodeError> {
let indexed: BTreeMap<EntityId, (&String, &Entry)> = entries
.iter()
.map(|(path, entry)| (entry.entity, (path, entry)))
.collect();
let differing: Vec<(String, EntityId, Version)> = state
.by_entity
.iter()
.filter(|(entity, path)| {
!state.competing.contains(*path)
&& !state.paths.contains_key(*entity)
&& state
.versions
.get(*entity)
.is_none_or(|versions| versions.len() < 2)
})
.filter_map(|(entity, path)| {
let version = state.own.get(entity).cloned().flatten()?;
let differs = match indexed.get(entity) {
Some((at, entry)) => {
(*at != path || entry.version != version) && changed(at, Some(entry))
}
None => changed(path, None),
};
differs.then(|| (path.clone(), *entity, version))
})
.collect();
if differing.is_empty() {
return Ok(differing);
}
let open = self.space(space)?;
let log = open.stored.log();
let state_now = log.state();
let me = self.replica.signing.verifying_key();
let change_of = |id| -> Result<Option<Hash>, NodeError> {
Ok(state_now
.storage()
.get(id)?
.and_then(|recorded| recorded.change))
};
let fields = [
&TREE_PATH,
&CONTENT,
&SECRET_CONTENT,
&LINK_TARGET,
&EXECUTABLE,
];
let mut own = Vec::new();
for (path, entity, version) in differing {
let mut last = None;
for field in fields {
for statement in state_now.current(entity, field)? {
let at = state_now.recorded(statement.id)?;
if last.as_ref().is_none_or(|(when, _)| at > *when) {
last = Some((at, statement.id));
}
}
}
let Some((_, newest)) = last else {
continue;
};
let change = change_of(newest)?;
let mut in_commit = false;
for part in state_now.current(entity, &COMMITTED_IN)? {
in_commit |= change.is_some() && change_of(part.id)? == change;
}
if in_commit && log.author_of(newest)? == Some(me) {
own.push((path, entity, version));
}
}
Ok(own)
}
}
#[derive(Debug, Default)]
struct Purged {
ordinary: BTreeSet<Hash>,
secret: BTreeSet<Hash>,
secret_versions: SecretVersions,
}
impl Purged {
fn is_empty(&self) -> bool {
self.ordinary.is_empty() && self.secret.is_empty()
}
fn contains(&self, content: &Hash, secret: bool) -> bool {
if secret {
self.secret.contains(content)
} else {
self.ordinary.contains(content)
}
}
fn is_secret(&self, entry: &Entry) -> bool {
matches!(entry.version, Version::File { content, .. }
if self.secret_versions.contains_key(&(entry.entity, content)))
}
fn holds(&self, entry: &Entry) -> bool {
match entry.version {
Version::File { content, .. } => self.contains(&content, self.is_secret(entry)),
Version::Link { .. } => false,
}
}
}
fn version_of(state: &TreeState, entity: EntityId) -> Option<(String, Option<Version>)> {
let path = state.by_entity.get(&entity)?;
Some((path.clone(), state.own.get(&entity).cloned().flatten()))
}
fn tree_entities<S: nibkeep_model::storage::Statements>(
state: &nibkeep_model::State<S>,
tree: EntityId,
) -> Result<Vec<EntityId>, NodeError>
where
NodeError: From<S::Error>,
{
let tree = state.canonical(tree)?;
let mut entities = BTreeSet::new();
for id in state.storage().referring_to(tree)? {
if let Some(recorded) = state.storage().get(id)?
&& recorded.statement.field == IN_TREE
{
entities.insert(state.canonical(recorded.statement.entity)?);
}
}
Ok(entities.into_iter().collect())
}
pub(super) struct Changes<'a> {
log: &'a Log<StateFile, LogFile>,
built_on: RefCell<BTreeMap<Hash, BTreeSet<Hash>>>,
}
impl<'a> Changes<'a> {
pub(super) fn of(log: &'a Log<StateFile, LogFile>) -> Self {
Self {
log,
built_on: RefCell::default(),
}
}
fn saw(&self, earlier: Hash, later: Hash) -> Result<bool, NodeError> {
if earlier == later {
return Ok(true);
}
if let Some(built_on) = self.built_on.borrow().get(&later) {
return Ok(built_on.contains(&earlier));
}
let mut built_on = BTreeSet::new();
let mut waiting = vec![ChangeId::from_hash(later)];
while let Some(id) = waiting.pop() {
let Some(change) = self.log.change(id)? else {
continue;
};
for parent in change.parents() {
if built_on.insert(*parent.hash()) {
waiting.push(*parent);
}
}
}
let saw = built_on.contains(&earlier);
self.built_on.borrow_mut().insert(later, built_on);
Ok(saw)
}
fn purged(&self, change: Hash) -> Result<bool, NodeError> {
let status = nibkeep_log::History::status(self.log.history(), ChangeId::from_hash(change))?;
Ok(status == Some(nibkeep_log::Status::Ignored))
}
}
fn read_tree_state<S: nibkeep_model::storage::Statements>(
state: &nibkeep_model::State<S>,
tree: EntityId,
entities: &[EntityId],
(changes, readable): (Option<&Changes<'_>>, bool),
) -> Result<TreeState, NodeError>
where
NodeError: From<S::Error>,
{
let tree = state.canonical(tree)?;
let mut read = TreeState::default();
let mut deleted_at: BTreeMap<String, nibkeep_time::Timestamp> = BTreeMap::new();
for &entity in entities {
let Some((is_link, is_secret)) = kind_in_tree(state, entity, tree)? else {
continue;
};
let values = |field: &FieldName| -> Result<Vec<Value>, NodeError> {
let mut statements = state.current(entity, field)?;
statements.sort_by_key(|statement| statement.id);
Ok(statements
.into_iter()
.map(|statement| statement.value.clone())
.collect())
};
let texts = |field: &FieldName| -> Result<Vec<String>, NodeError> {
Ok(values(field)?
.into_iter()
.filter_map(|value| match value {
Value::Text(text) => Some(text),
_ => None,
})
.collect())
};
let paths = distinct(texts(&TREE_PATH)?);
if is_secret {
read.secret.insert(entity);
read.secret_paths.extend(all_paths(state, entity)?);
}
let Some(path) = paths.first().cloned() else {
continue;
};
if !is_safe_tree_path(&path) {
continue;
}
let all: Vec<Version> = if is_link {
texts(&LINK_TARGET)?
.into_iter()
.map(|target| Version::Link { target })
.collect()
} else {
let executable = values(&EXECUTABLE)?.contains(&Value::Boolean(true));
let field = if is_secret { &SECRET_CONTENT } else { &CONTENT };
values(field)?
.into_iter()
.filter_map(|value| match value {
Value::Blob(content) => Some(Version::File {
content,
executable,
}),
_ => None,
})
.collect()
};
let all = distinct(all);
let competing = all.len() > 1;
let version = all.first().cloned();
let deleted = state.is_deleted(entity)?;
if is_secret && version.is_none() && !deleted && !readable {
read.sealed.insert(path, entity);
continue;
}
let unseen = match changes {
Some(changes) if deleted && version.is_some() => {
unseen_deletions(state, entity, changes)?
}
_ => None,
};
if let Some(deletions) = unseen {
read.contested.insert(entity, deletions);
read.competing.insert(path.clone());
} else if deleted {
note_deleted(
state,
(&mut read, &mut deleted_at),
path,
Current { entity, version },
)?;
continue;
}
if competing {
read.competing.insert(path.clone());
read.versions.insert(entity, all);
}
read.own.insert(entity, version.clone());
if paths.len() > 1 {
read.competing.extend(paths.iter().cloned());
read.paths.insert(entity, paths.clone());
}
if read.by_path.contains_key(&path) {
read.competing.insert(path.clone());
} else {
read.by_path
.insert(path.clone(), Current { entity, version });
}
read.by_entity.insert(entity, path);
}
Ok(read)
}
fn distinct<T: PartialEq>(values: Vec<T>) -> Vec<T> {
let mut kept = Vec::new();
for value in values {
if !kept.contains(&value) {
kept.push(value);
}
}
kept
}
fn note_deleted<S: nibkeep_model::storage::Statements>(
state: &nibkeep_model::State<S>,
(read, deleted_at): (
&mut TreeState,
&mut BTreeMap<String, nibkeep_time::Timestamp>,
),
path: String,
deleted: Current,
) -> Result<(), NodeError>
where
NodeError: From<S::Error>,
{
let when = state
.current(deleted.entity, &fields::DELETED)?
.iter()
.filter_map(|statement| state.recorded(statement.id).ok().flatten())
.max();
let later = match (when, deleted_at.get(&path)) {
(Some(when), Some(known)) => when > *known,
(Some(_) | None, None) => true,
(None, Some(_)) => false,
};
if later {
if let Some(when) = when {
deleted_at.insert(path.clone(), when);
}
read.deleted.insert(path, deleted);
}
Ok(())
}
fn unseen_deletions<S: nibkeep_model::storage::Statements>(
state: &nibkeep_model::State<S>,
entity: EntityId,
changes: &Changes<'_>,
) -> Result<Option<Vec<String>>, NodeError>
where
NodeError: From<S::Error>,
{
let mut deletions = Vec::new();
for statement in state.current(entity, &fields::DELETED)? {
if statement.value != Value::Boolean(true) {
continue;
}
let Some(change) = state
.storage()
.get(statement.id)?
.and_then(|recorded| recorded.change)
else {
return Ok(None);
};
deletions.push((deletion_key(statement.id), change));
}
if deletions.is_empty() {
return Ok(None);
}
for field in [
&CONTENT,
&SECRET_CONTENT,
&LINK_TARGET,
&EXECUTABLE,
&TREE_PATH,
] {
for statement in state.current(entity, field)? {
let Some(recorded) = state.storage().get(statement.id)? else {
continue;
};
let (Some(change), None) = (recorded.change, recorded.restated) else {
continue;
};
if changes.purged(change)? {
continue;
}
let mut seen = false;
for (_, deletion) in &deletions {
if changes.saw(change, *deletion)? {
seen = true;
break;
}
}
if !seen {
return Ok(Some(deletions.into_iter().map(|(key, _)| key).collect()));
}
}
}
Ok(None)
}
fn kind_in_tree<S: nibkeep_model::storage::Statements>(
state: &nibkeep_model::State<S>,
entity: EntityId,
tree: EntityId,
) -> Result<Option<(bool, bool)>, NodeError>
where
NodeError: From<S::Error>,
{
match secret_file_of(state, entity)? {
Secrecy::Of(of) if of == tree => return Ok(Some((false, true))),
Secrecy::Of(_) | Secrecy::OfNone => return Ok(None),
Secrecy::Ordinary => {}
}
let mut in_tree = false;
for statement in state.current(entity, &IN_TREE)? {
if let Value::Reference(of) = statement.value {
in_tree |= state.canonical(of)? == tree;
}
}
if !in_tree {
return Ok(None);
}
let types = state.types(entity)?;
let is_link = types.contains(&SYMBOLIC_LINK);
Ok((is_link || types.contains(&FILE)).then_some((is_link, false)))
}
type Earliest = Option<(
(Option<nibkeep_time::Timestamp>, nibkeep_base::StatementId),
Value,
Option<Hash>,
)>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Secrecy {
Ordinary,
Of(EntityId),
OfNone,
}
fn secret_file_of<S: nibkeep_model::storage::Statements>(
state: &nibkeep_model::State<S>,
entity: EntityId,
) -> Result<Secrecy, NodeError>
where
NodeError: From<S::Error>,
{
let storage = state.storage();
let earliest = |field: &FieldName,
keep: &dyn Fn(&Value) -> bool|
-> Result<Option<(Value, Option<Hash>)>, NodeError> {
let mut first: Earliest = None;
for id in storage.of_field(entity, field)? {
let Some(recorded) = storage.get(id)? else {
continue;
};
if !keep(&recorded.statement.value) {
continue;
}
let at = (state.recorded(id)?, id);
if first.as_ref().is_none_or(|(known, _, _)| at < *known) {
first = Some((at, recorded.statement.value.clone(), recorded.change));
}
}
Ok(first.map(|(_, value, change)| (value, change)))
};
let secret_type = SECRET_FILE;
if earliest(&fields::TYPE, &|value| {
value.as_text() == Some(secret_type.as_str())
})?
.is_none()
{
return Ok(Secrecy::Ordinary);
}
let Some((_, made_in)) = earliest(&fields::TYPE, &|_| true)? else {
return Ok(Secrecy::OfNone);
};
match earliest(&IN_TREE, &|value| matches!(value, Value::Reference(_)))? {
Some((Value::Reference(tree), Some(change))) if made_in == Some(change) => {
Ok(Secrecy::Of(state.canonical(tree)?))
}
_ => Ok(Secrecy::OfNone),
}
}
fn all_paths<S: nibkeep_model::storage::Statements>(
state: &nibkeep_model::State<S>,
entity: EntityId,
) -> Result<Vec<String>, NodeError>
where
NodeError: From<S::Error>,
{
let storage = state.storage();
let mut paths = Vec::new();
for id in storage.of_field(entity, &TREE_PATH)? {
if let Some(recorded) = storage.get(id)?
&& let Value::Text(path) = &recorded.statement.value
{
paths.push(path.clone());
}
}
Ok(paths)
}
fn deletion_key(statement: nibkeep_base::StatementId) -> String {
format!("deleted {statement}")
}
pub fn tree_path_at(root: &Path, path: &Path) -> Result<String, NodeError> {
let shown = || path.display().to_string();
let mut existing = path;
let mut rest = Vec::new();
if let (Some(std::path::Component::Normal(name)), Some(parent)) =
(path.components().next_back(), path.parent())
{
rest.push(name);
existing = parent;
}
let resolved = loop {
if let Some(resolved) = resolved(existing) {
break resolved;
}
rest.push(
existing
.file_name()
.ok_or_else(|| NodeError::NotInTree(shown()))?,
);
existing = existing
.parent()
.ok_or_else(|| NodeError::NotInTree(shown()))?;
};
let mut full = resolved;
full.extend(rest.iter().rev());
let relative = full
.strip_prefix(root)
.map_err(|_| NodeError::NotInTree(shown()))?;
if relative.as_os_str().is_empty() {
return Ok(String::new());
}
paths::tree_path_of(relative).map_err(|_| NodeError::UnsafePath(shown()))
}
fn resolved(folder: &Path) -> Option<PathBuf> {
fs::canonicalize(folder).ok().map(super::files::plain)
}