use std::collections::{BTreeMap, BTreeSet};
use std::fs::{self, File};
use std::io::{self, Write as _};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use nibkeep_base::{EntityId, SpaceId};
use nibkeep_crypto::rand_core::CryptoRng;
use nibkeep_model::Value;
use nibkeep_std::{ON_DEVICE, PATH, ROOT_OF, TREE_ROOT};
use super::history::{READ_LIMIT, TreePoint};
use super::index::{Entry, Version};
use super::locate::{Blocked, Located, located, place_for_new};
use super::paths::{fits_this_system, is_reserved};
use super::walk::{Found, FoundKind, hash_found, look, nanos, open_found};
use super::{TREE_TYPES, TreeState, version_of};
use crate::NodeError;
use crate::library::Library;
use crate::library::checkouts::{
copy_checked, put_in_place, remove_leftover, sync_folder_of, temporary_for,
};
use crate::library::entities::NewValue;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Written {
pub written: Vec<String>,
pub skipped: Vec<(String, String)>,
pub sealed: Vec<String>,
pub aside: Vec<(String, String)>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CopiesRemoved {
pub removed: Vec<String>,
pub skipped: Vec<(String, String)>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Reverted {
pub written: Vec<String>,
pub deleted: Vec<String>,
pub moved: Vec<(String, String)>,
pub conflicts: Vec<String>,
pub skipped: Vec<(String, String)>,
}
pub(super) enum Content<'a> {
Version(&'a Version),
Bytes(&'a [u8], bool),
Secret(&'a Version),
SecretBytes(&'a [u8], bool),
}
impl<'a> Content<'a> {
pub(super) fn of(version: &'a Version, secret: bool) -> Self {
if secret {
Self::Secret(version)
} else {
Self::Version(version)
}
}
pub(super) fn bytes(bytes: &'a [u8], executable: bool, secret: bool) -> Self {
if secret {
Self::SecretBytes(bytes, executable)
} else {
Self::Bytes(bytes, executable)
}
}
}
#[derive(Clone, Copy)]
pub(super) struct Place<'a> {
pub(super) root: &'a Path,
pub(super) apart: &'a [PathBuf],
}
impl Library {
pub fn write_tree(
&mut self,
space: SpaceId,
tree: EntityId,
folder: &Path,
at: TreePoint,
wall_millis: u64,
rng: &mut impl CryptoRng,
) -> Result<Written, NodeError> {
let tree = self.check_tree(space, tree)?;
let locked = if at == TreePoint::Now {
self.check_not_revoked(space)?;
let locked = self.lock_trees()?;
if let Some(root) = self.roots_here(space)?.remove(&tree) {
return Err(NodeError::TreeHereAlready(root));
}
Some(locked)
} else {
None
};
self.check_new_place(folder)?;
match fs::read_dir(folder) {
Ok(mut entries) => {
if entries.next().is_some() {
return Err(NodeError::FolderNotEmpty(folder.to_path_buf()));
}
}
Err(error) if error.kind() == io::ErrorKind::NotFound => {
fs::create_dir_all(folder).map_err(NodeError::file(folder))?;
}
Err(error) => return Err(NodeError::file(folder)(error)),
}
let root = self.checked_new_root(space, folder)?;
let state = self.tree_state_at(space, tree, at)?;
let apart = self.apart();
let place = Place {
root: &root,
apart: &apart,
};
let read_at = nanos(SystemTime::now()).unwrap_or(0);
let mut written = Written {
sealed: state.sealed.keys().cloned().collect(),
..Written::default()
};
let mut entries = Vec::new();
for (path, current) in &state.by_path {
let Some(version) = ¤t.version else {
let why = "its content was purged".to_owned();
written.skipped.push((path.clone(), why));
continue;
};
let content = Content::of(version, state.is_secret(current.entity));
match self.write_new(space, place, path, &content) {
Ok(found) => {
written.written.push(path.clone());
entries.push((
path.clone(),
Entry {
entity: current.entity,
version: version.clone(),
size: found.size,
modified: found.modified,
read_at,
},
));
}
Err(why) => written.skipped.push((path.clone(), why)),
}
}
if locked.is_some() {
self.install_standard(space, &TREE_TYPES, wall_millis, rng)?;
let (root_entity, operations) = 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,
)?;
self.commit(space, operations, wall_millis, rng)?;
let mut index = self.index()?;
index.change(tree, &[], &entries)?;
self.note_secrets(space, (tree, &index), &state, &entries)?;
index.set_root(tree, root_entity, &root)?;
index.know(tree)?;
let cut: Vec<EntityId> = self
.cut_short(space, tree)?
.into_iter()
.map(|cut| cut.revision)
.collect();
index.take_parts(tree, &cut)?;
}
Ok(written)
}
pub fn restore_in_tree(
&self,
space: SpaceId,
tree: EntityId,
path: &str,
at: TreePoint,
) -> Result<Written, NodeError> {
let _locked = self.lock_trees()?;
let root = self.root_here(space, tree)?;
let index = self.index()?;
let entries = index.entries(tree)?;
let now = self.tree_state(space, tree)?;
let then = self.tree_state_at(space, tree, at)?;
let apart = self.apart();
let place = Place {
root: &root,
apart: &apart,
};
let under = |candidate: &str| {
path.is_empty() || candidate == path || candidate.starts_with(&format!("{path}/"))
};
let take = |(candidate, current): (&String, &super::Current)| {
let secret = then.is_secret(current.entity);
(candidate.clone(), current.version.clone(), secret)
};
let mut chosen: Vec<(String, Option<Version>, bool)> = then
.by_path
.iter()
.filter(|(candidate, _)| under(candidate))
.map(take)
.collect();
if chosen.is_empty() && at == TreePoint::Now {
chosen = then
.deleted
.iter()
.filter(|(candidate, _)| under(candidate))
.map(take)
.collect();
}
let sealed: Vec<String> = then
.sealed
.keys()
.filter(|candidate| under(candidate))
.cloned()
.collect();
if chosen.is_empty() && sealed.is_empty() {
return Err(NodeError::NotInTree(path.to_owned()));
}
let mut plan = Vec::new();
let mut written = Written {
sealed,
..Written::default()
};
for (candidate, version, secret) in chosen {
let Some(version) = version else {
let why = "its content was purged".to_owned();
written.skipped.push((candidate, why));
continue;
};
if secret && !self.secrets_unlocked(space) {
written.sealed.push(candidate);
continue;
}
match located(&root, &candidate, &apart) {
Located::Absent => plan.push((candidate, version, secret, None)),
Located::Unknown(why) => written.skipped.push((candidate, why)),
Located::Here(on_disk) => {
let found =
look(&on_disk).map_err(|_| NodeError::EditedCopy(candidate.clone()))?;
let holds = copy_version(&found);
if holds.as_ref() == Some(&version) {
continue;
}
let recorded = recorded_version(&entries, &now, &candidate);
let unedited = holds
.as_ref()
.zip(recorded)
.is_some_and(|(holds, recorded)| same_version(&found, holds, recorded));
plan.push((candidate, version, secret, Some((found, !unedited))));
}
}
}
written.sealed.sort();
for (candidate, version, secret, there) in plan {
let content = Content::of(&version, secret);
let done = match &there {
None => self.write_new(space, place, &candidate, &content).map(drop),
Some((found, false)) => self.write_over(space, found, &content),
Some((found, true)) => {
let held = |name: &str| {
now.by_path.contains_key(name)
|| then.by_path.contains_key(name)
|| entries.contains_key(name)
};
let edited = (candidate.as_str(), found);
let at = (&index, tree, place);
self.write_keeping_edits(space, at, (edited, &held), &content)?
.map(|beside| written.aside.push((candidate.clone(), beside)))
}
};
match done {
Ok(()) => written.written.push(candidate),
Err(why) => written.skipped.push((candidate, why)),
}
}
Ok(written)
}
fn write_keeping_edits(
&self,
space: SpaceId,
(index, tree, place): (&super::index::Index, EntityId, Place<'_>),
((path, found), held): ((&str, &Found), Held<'_>),
content: &Content<'_>,
) -> Result<Result<String, String>, NodeError> {
let beside = match set_aside(index, (tree, place), (path, held), found)? {
Ok(beside) => beside,
Err(why) => return Ok(Err(why)),
};
match self.write_new(space, place, path, content) {
Ok(_) => Ok(Ok(beside)),
Err(why) => {
bring_back(index, (tree, place), (path, &beside), found)?;
Ok(Err(why))
}
}
}
pub fn remove_in_tree(
&self,
space: SpaceId,
tree: EntityId,
paths: &[String],
force: bool,
) -> Result<CopiesRemoved, NodeError> {
if let Some(path) = paths
.iter()
.find(|path| !path.is_empty() && !super::is_safe_tree_path(path))
{
return Err(NodeError::UnsafePath(path.clone()));
}
let _locked = self.lock_trees()?;
let root = self.root_here(space, tree)?;
let entries = self.index()?.entries(tree)?;
let now = self.tree_state(space, tree)?;
let apart = self.apart();
let under = |path: &str, candidate: &str| {
path.is_empty() || candidate == path || candidate.starts_with(&format!("{path}/"))
};
if let Some(path) = paths
.iter()
.find(|path| !now.by_path.keys().any(|candidate| under(path, candidate)))
{
return Err(NodeError::NotInTree(path.clone()));
}
let chosen: Vec<&String> = now
.by_path
.keys()
.filter(|candidate| paths.iter().any(|path| under(path, candidate)))
.collect();
let mut removed = CopiesRemoved::default();
let mut plan = Vec::new();
for candidate in chosen {
match located(&root, candidate, &apart) {
Located::Absent if entries.contains_key(candidate) => {
removed.removed.push(candidate.clone());
}
Located::Absent => {
let why = "its copy was never written here".to_owned();
removed.skipped.push((candidate.clone(), why));
}
Located::Unknown(why) => removed.skipped.push((candidate.clone(), why)),
Located::Here(on_disk) => {
let found =
look(&on_disk).map_err(|_| NodeError::EditedCopy(candidate.clone()))?;
let unedited = copy_version(&found)
.zip(recorded_version(&entries, &now, candidate))
.is_some_and(|(holds, recorded)| same_version(&found, &holds, recorded));
if !unedited && !force {
return Err(NodeError::EditedCopy(candidate.clone()));
}
plan.push((candidate.clone(), found));
}
}
}
for (candidate, found) in plan {
if !still_the_copy(&found) {
let why = "it changed meanwhile".to_owned();
removed.skipped.push((candidate, why));
continue;
}
match fs::remove_file(&found.on_disk) {
Ok(()) => {
sync_folder_of(&found.on_disk);
remove_emptied(&root, &found.on_disk);
removed.removed.push(candidate);
}
Err(error) => removed.skipped.push((candidate, error.to_string())),
}
}
removed.removed.sort();
Ok(removed)
}
pub fn revert_in_tree(
&self,
space: SpaceId,
tree: EntityId,
revision: EntityId,
) -> Result<Reverted, NodeError> {
let _locked = self.lock_trees()?;
let root = self.root_here(space, tree)?;
let index = self.index()?;
let entries = index.entries(tree)?;
let changes = self.revision_changes(space, tree, revision)?;
let Some(&last) = changes.last() else {
return Err(NodeError::NoRevision(revision.to_string()));
};
let parts: BTreeSet<_> = changes.iter().copied().collect();
let (after, before) = self.tree_states_of_changes(space, tree, last, &parts)?;
let now = self.tree_state(space, tree)?;
let apart = self.apart();
let place = Place {
root: &root,
apart: &apart,
};
let mut reverted = Reverted::default();
let plan = undoing(&before, &after, &now, &mut reverted);
let mut behind = Vec::new();
for path in plan.touched() {
let Located::Here(on_disk) = located(&root, path, &apart) else {
continue;
};
let Ok(found) = look(&on_disk) else {
return Err(NodeError::EditedCopy(path.to_owned()));
};
let holds = copy_version(&found);
let committed = holds
.as_ref()
.zip(entries.get(path).map(|entry| &entry.version))
.is_some_and(|(holds, entry)| same_version(&found, holds, entry));
let current = now
.by_path
.get(path)
.and_then(|current| current.version.as_ref());
let up_to_date = holds
.as_ref()
.zip(current)
.is_some_and(|(holds, current)| same_version(&found, holds, current));
if !up_to_date && committed {
behind.push(path.to_owned());
} else if !up_to_date {
return Err(NodeError::EditedCopy(path.to_owned()));
}
}
if !behind.is_empty() {
return Err(NodeError::TreeStale(behind));
}
for (path, added) in &plan.additions {
undo_addition(place, (path, added.as_ref()), &mut reverted);
}
let at = undo_moves(place, &plan.moves, &mut reverted);
for (path, version) in &plan.deletions {
let Some(version) = version else {
let why = "its content was purged".to_owned();
reverted.skipped.push((path.clone(), why));
continue;
};
let content = Content::of(version, plan.secret.contains(path));
match self.write_new(space, place, path, &content) {
Ok(_) => reverted.written.push(path.clone()),
Err(why) => reverted.skipped.push((path.clone(), why)),
}
}
let short = &revision.to_string()[..8];
for (path, versions) in &plan.edits {
let secret = plan.secret.contains(path);
let path = at.get(path).unwrap_or(path);
if let Some(beside) = self.undo_edit(
space,
(place, short),
(path, secret),
versions,
&mut reverted,
) {
index.mark(
tree,
&beside,
"NibKeep wrote it, the version from before a reverted revision",
)?;
}
}
Ok(reverted)
}
fn check_new_place(&self, folder: &Path) -> Result<(), NodeError> {
let mut existing = folder;
let mut rest = Vec::new();
let resolved = loop {
if let Ok(resolved) = fs::canonicalize(existing) {
break crate::library::files::plain(resolved);
}
let (Some(name), Some(parent)) = (existing.file_name(), existing.parent()) else {
return Err(NodeError::NotATreeFolder(folder.to_path_buf()));
};
rest.push(name);
existing = parent;
};
let mut full = resolved;
full.extend(rest.iter().rev());
let reserved = full.components().any(|component| match component {
std::path::Component::Normal(name) => is_reserved(&name.to_string_lossy()),
_ => false,
});
if reserved || self.apart().iter().any(|apart| full.starts_with(apart)) {
return Err(NodeError::NotATreeFolder(full));
}
for &space in self.spaces.keys() {
for other in self.roots_here(space)?.values() {
if full.starts_with(other) || other.starts_with(&full) {
return Err(NodeError::TreeInTree(full));
}
}
}
Ok(())
}
}
#[derive(Debug, Default)]
struct Undoing {
additions: Vec<(String, Option<Version>)>,
moves: Vec<(String, String)>,
deletions: Vec<(String, Option<Version>)>,
edits: Vec<(String, (Version, Version))>,
secret: BTreeSet<String>,
}
impl Undoing {
fn touched(&self) -> impl Iterator<Item = &String> {
self.additions
.iter()
.map(|(path, _)| path)
.chain(self.moves.iter().map(|(from, _)| from))
.chain(self.edits.iter().map(|(path, _)| path))
}
}
fn undoing(
before: &TreeState,
after: &TreeState,
now: &TreeState,
reverted: &mut Reverted,
) -> Undoing {
let mut plan = Undoing::default();
let entities: BTreeSet<EntityId> = before
.by_entity
.keys()
.chain(after.by_entity.keys())
.copied()
.collect();
for entity in entities {
let is = version_of(now, entity);
if let Some((path, _)) = &is
&& now
.by_path
.get(path)
.is_some_and(|current| current.entity != entity)
{
let why = "another file competes for its path; update the copy first".to_owned();
reverted.skipped.push((path.clone(), why));
continue;
}
match (version_of(before, entity), version_of(after, entity)) {
(None, Some((_, added))) => {
if let Some((path, _)) = is {
plan.additions.push((path, added));
}
}
(Some((path, version)), None) => {
if is.is_none() {
if before.is_secret(entity) {
plan.secret.insert(path.clone());
}
plan.deletions.push((path, version));
}
}
(Some((was_path, was)), Some((became_path, became))) => {
if was_path == became_path && was == became {
continue;
}
let Some((path, _)) = is else {
let why = "it was deleted since".to_owned();
reverted.skipped.push((became_path, why));
continue;
};
if was_path != became_path && path == became_path {
plan.moves.push((path.clone(), was_path));
}
if let (Some(was), Some(became)) = (was, became)
&& was != became
{
if after.is_secret(entity) {
plan.secret.insert(path.clone());
}
plan.edits.push((path, (was, became)));
}
}
(None, None) => {}
}
}
plan
}
fn undo_addition(
place: Place<'_>,
(path, added): (&String, Option<&Version>),
reverted: &mut Reverted,
) {
let on_disk = match located(place.root, path, place.apart) {
Located::Here(on_disk) => on_disk,
Located::Absent => return,
Located::Unknown(why) => {
reverted.skipped.push((path.clone(), why));
return;
}
};
let unchanged = look(&on_disk).is_ok_and(|found| {
copy_version(&found)
.zip(added)
.is_some_and(|(holds, added)| same_version(&found, &holds, added))
});
if !unchanged {
reverted.conflicts.push(path.clone());
return;
}
match fs::remove_file(&on_disk) {
Ok(()) => {
sync_folder_of(&on_disk);
reverted.deleted.push(path.clone());
}
Err(error) => reverted.skipped.push((path.clone(), error.to_string())),
}
}
fn undo_moves(
place: Place<'_>,
moves: &[(String, String)],
reverted: &mut Reverted,
) -> BTreeMap<String, String> {
let at = undo_moves_at(place, moves, &mut reverted.skipped);
reverted
.moved
.extend(at.iter().map(|(from, to)| (from.clone(), to.clone())));
at
}
pub(super) fn aside_for(source: &Path) -> PathBuf {
let name = source.file_name().map(std::ffi::OsStr::as_encoded_bytes);
let mut hasher = blake3::Hasher::new();
hasher.update(b"moved aside\0");
hasher.update(name.unwrap_or_default());
let digest = hasher.finalize().to_hex();
source.with_file_name(format!(".nib-tree-{}", &digest[..16]))
}
pub(super) fn bring_back_aside<'a>(place: Place<'_>, paths: impl Iterator<Item = &'a String>) {
for path in paths {
if located(place.root, path, place.apart) != Located::Absent {
continue;
}
let source = place.root.join(path);
let aside = aside_for(&source);
if fs::symlink_metadata(&aside).is_ok()
&& fs::symlink_metadata(&source).is_err()
&& fs::rename(&aside, &source).is_ok()
{
sync_folder_of(&source);
}
}
}
fn remove_emptied(root: &Path, deleted: &Path) {
for folder in deleted.ancestors().skip(1) {
if folder == root || !folder.starts_with(root) || fs::remove_dir(folder).is_err() {
break;
}
sync_folder_of(folder);
}
}
type Held<'a> = &'a dyn Fn(&str) -> bool;
pub(super) fn still_the_copy(found: &Found) -> bool {
look(&found.on_disk).is_ok_and(|now| {
now.identity == found.identity && now.size == found.size && now.modified == found.modified
})
}
fn set_aside(
index: &super::index::Index,
(tree, place): (EntityId, Place<'_>),
(path, held): (&str, Held<'_>),
found: &Found,
) -> Result<Result<String, String>, NodeError> {
let Some(beside) = (1..=99)
.map(|number| match number {
1 => format!("{path}.orig"),
_ => format!("{path}.orig-{number}"),
})
.find(|name| !held(name) && located(place.root, name, place.apart) == Located::Absent)
else {
return Ok(Err(format!(
"{path}.orig and the names after it are taken, so its edits stay"
)));
};
index.mark(
tree,
&beside,
"NibKeep wrote it, the edits a restore took from the copy",
)?;
let moved = if still_the_copy(found) {
move_into_place(place, &found.on_disk, &beside)
} else {
Err("it changed meanwhile".to_owned())
};
if let Err(why) = moved {
index.unmark(tree, std::slice::from_ref(&beside))?;
return Ok(Err(why));
}
Ok(Ok(beside))
}
fn bring_back(
index: &super::index::Index,
(tree, place): (EntityId, Place<'_>),
(path, beside): (&str, &str),
found: &Found,
) -> Result<(), NodeError> {
if located(place.root, path, place.apart) == Located::Absent
&& fs::rename(place.root.join(beside), &found.on_disk).is_ok()
{
sync_folder_of(&found.on_disk);
index.unmark(tree, &[beside.to_owned()])?;
}
Ok(())
}
pub(super) fn undo_moves_at(
place: Place<'_>,
moves: &[(String, String)],
skipped: &mut Vec<(String, String)>,
) -> BTreeMap<String, String> {
let mut aside = Vec::new();
for (from, to) in moves {
let source = match located(place.root, from, place.apart) {
Located::Here(source) => source,
Located::Absent => {
skipped.push((from.clone(), "its copy is not here".to_owned()));
continue;
}
Located::Unknown(why) => {
skipped.push((from.clone(), why));
continue;
}
};
let temporary = aside_for(&source);
if fs::symlink_metadata(&temporary).is_ok() || fs::rename(&source, &temporary).is_err() {
skipped.push((from.clone(), "it could not be moved".to_owned()));
continue;
}
aside.push((from, to, source, temporary));
}
let mut at = BTreeMap::new();
for (from, to, source, temporary) in aside {
match move_into_place(place, &temporary, to) {
Ok(()) => {
sync_folder_of(&source);
at.insert(from.clone(), to.clone());
}
Err(why) => {
let _ = fs::rename(&temporary, &source);
skipped.push((from.clone(), why));
}
}
}
at
}
impl Library {
fn undo_edit(
&self,
space: SpaceId,
(place, short): (Place<'_>, &str),
(path, secret): (&str, bool),
(before, after): &(Version, Version),
reverted: &mut Reverted,
) -> Option<String> {
if secret && !self.secrets_unlocked(space) {
let why = "a secret file, which is written only with the secrets unlocked".to_owned();
reverted.skipped.push((path.to_owned(), why));
return None;
}
let on_disk = match located(place.root, path, place.apart) {
Located::Here(on_disk) => on_disk,
Located::Absent => {
let why = "its copy is not here".to_owned();
reverted.skipped.push((path.to_owned(), why));
return None;
}
Located::Unknown(why) => {
reverted.skipped.push((path.to_owned(), why));
return None;
}
};
let found = match look(&on_disk) {
Ok(found) => found,
Err(why) => {
reverted.skipped.push((path.to_owned(), why));
return None;
}
};
match self.merge_back(space, &found, (before, after), secret) {
Ok(Merged::Unchanged) => {}
Ok(Merged::Clean(content)) => {
match self.write_over(space, &found, &content.as_content(secret)) {
Ok(()) => reverted.written.push(path.to_owned()),
Err(why) => reverted.skipped.push((path.to_owned(), why)),
}
}
Ok(Merged::Clashed(content)) => {
match self.write_over(space, &found, &content.as_content(secret)) {
Ok(()) => reverted.conflicts.push(path.to_owned()),
Err(why) => reverted.skipped.push((path.to_owned(), why)),
}
}
Ok(Merged::Beside) => {
let beside = format!("{path}.before-{short}");
match self.write_new(space, place, &beside, &Content::of(before, secret)) {
Ok(_) => {
reverted.conflicts.push(path.to_owned());
return Some(beside);
}
Err(why) => reverted.skipped.push((path.to_owned(), why)),
}
}
Err(why) => reverted.skipped.push((path.to_owned(), why)),
}
None
}
fn merge_back(
&self,
space: SpaceId,
found: &Found,
(before, after): (&Version, &Version),
secret: bool,
) -> Result<Merged, String> {
let holds = copy_version(found).ok_or("it cannot be read")?;
let (
Version::File {
content: was,
executable: was_executable,
},
Version::File {
content: became,
executable: became_executable,
},
) = (before, after)
else {
return Ok(if holds == *before {
Merged::Unchanged
} else if same_content(&holds, after) {
Merged::Clean(Owned::Version(before.clone()))
} else {
Merged::Beside
});
};
let holds_executable = found.executable.unwrap_or(*became_executable);
let executable = if holds_executable == *became_executable {
*was_executable
} else {
holds_executable
};
let wanted = Version::File {
content: *was,
executable,
};
if holds == wanted {
return Ok(Merged::Unchanged);
}
if same_content(&holds, after) {
return Ok(Merged::Clean(Owned::Version(wanted)));
}
if found.kind != FoundKind::File {
return Ok(Merged::Beside);
}
let was_bytes = self.version_bytes(space, was, secret).ok().flatten();
let became_bytes = self.version_bytes(space, became, secret).ok().flatten();
let mut ours = Vec::new();
let read = open_found(found)
.and_then(|file| {
io::Read::read_to_end(&mut io::Read::take(file, READ_LIMIT + 1), &mut ours)
})
.map_err(|error| error.to_string())?;
let (Some(was_bytes), Some(became_bytes), true) =
(was_bytes, became_bytes, read as u64 <= READ_LIMIT)
else {
return Ok(Merged::Beside);
};
let text = [&was_bytes, &became_bytes, &ours]
.iter()
.all(|bytes| super::diff::is_text(bytes));
if !text {
return Ok(Merged::Beside);
}
Ok(match diffy::merge_bytes(&became_bytes, &ours, &was_bytes) {
Ok(merged) => Merged::Clean(Owned::Bytes(merged, executable)),
Err(clashed) => Merged::Clashed(Owned::Bytes(clashed, executable)),
})
}
pub(super) fn write_new(
&self,
space: SpaceId,
place: Place<'_>,
path: &str,
content: &Content<'_>,
) -> Result<Found, String> {
if !path.split('/').all(fits_this_system) {
return Err("this system cannot write its name".to_owned());
}
let blocked = |why| match why {
Blocked::Taken => "something is in its place".to_owned(),
Blocked::Unsafe => "its way goes through a link, or into the library".to_owned(),
};
let target = place_for_new(place.root, path, place.apart).map_err(blocked)?;
if let Some(parent) = target.parent() {
make_folders(parent).map_err(|error| error.to_string())?;
if place_for_new(place.root, path, place.apart).as_ref() != Ok(&target) {
return Err("its way goes through a link".to_owned());
}
}
let temporary = temporary_for(&target, "tree");
remove_leftover(&temporary);
let made = self
.write_temporary(space, content, &temporary)
.and_then(|()| put_in_place(&temporary, &target).map_err(|error| error.to_string()));
if made.is_err() {
remove_leftover(&temporary);
}
made?;
look(&target)
}
pub(super) fn write_over(
&self,
space: SpaceId,
found: &Found,
content: &Content<'_>,
) -> Result<(), String> {
let target = &found.on_disk;
let temporary = temporary_for(target, "tree");
remove_leftover(&temporary);
let placed = self
.write_temporary(space, content, &temporary)
.and_then(|()| {
if !still_the_copy(found) {
return Err("it changed meanwhile".to_owned());
}
fs::rename(&temporary, target).map_err(|error| error.to_string())
});
if placed.is_err() {
remove_leftover(&temporary);
} else {
sync_folder_of(target);
}
placed
}
fn write_temporary(
&self,
space: SpaceId,
content: &Content<'_>,
temporary: &Path,
) -> Result<(), String> {
match content {
Content::Version(Version::Link { target })
| Content::Secret(Version::Link { target }) => make_link(target, temporary),
Content::Version(Version::File {
content,
executable,
}) => self
.blob_into(space, content, temporary)
.and_then(|()| set_executable(temporary, *executable)),
Content::Secret(Version::File {
content,
executable,
}) => self
.secret_blob_into(space, content, temporary)
.and_then(|()| set_executable(temporary, *executable)),
Content::Bytes(bytes, executable) => bytes_into(bytes, temporary, false)
.and_then(|()| set_executable(temporary, *executable)),
Content::SecretBytes(bytes, executable) => bytes_into(bytes, temporary, true)
.and_then(|()| set_executable(temporary, *executable)),
}
}
fn secret_blob_into(
&self,
space: SpaceId,
content: &nibkeep_base::Hash,
temporary: &Path,
) -> Result<(), String> {
if !self.secrets_unlocked(space) {
return Err(
"a secret file, which is written only with the secrets unlocked".to_owned(),
);
}
let open = self.space(space).map_err(|error| error.to_string())?;
let gone = || "this device holds no copy of its content".to_owned();
if !open.stored.has_secret_blob_key(content) || !open.stored.holds_blob(content) {
return Err(gone());
}
let mut reader = open.stored.open_blob(content).map_err(|_| gone())?;
let mut file = new_file(temporary, true).map_err(|error| error.to_string())?;
let matches =
copy_checked(&mut reader, &mut file, content).map_err(|error| error.to_string())?;
if !matches {
return Err("its content does not match its hash".to_owned());
}
file.sync_all().map_err(|error| error.to_string())
}
pub(super) fn version_bytes(
&self,
space: SpaceId,
content: &nibkeep_base::Hash,
secret: bool,
) -> Result<Option<Vec<u8>>, NodeError> {
if !secret {
return self.content_bytes(space, content);
}
if !self.secrets_unlocked(space) {
return Ok(None);
}
let open = self.space(space)?;
if !open.stored.has_secret_blob_key(content) || !open.stored.holds_blob(content) {
return Ok(None);
}
let reader = open.stored.open_blob(content)?;
let mut bytes = Vec::new();
let read = io::Read::read_to_end(&mut io::Read::take(reader, READ_LIMIT + 1), &mut bytes)
.map_err(|_| NodeError::Store(nibkeep_store::StoreError::DamagedBlob))?;
if read as u64 > READ_LIMIT || nibkeep_base::Hash::of(&bytes) != *content {
return Ok(None);
}
Ok(Some(bytes))
}
fn blob_into(
&self,
space: SpaceId,
content: &nibkeep_base::Hash,
temporary: &Path,
) -> Result<(), String> {
let open = self.space(space).map_err(|error| error.to_string())?;
if !open.stored.holds_ordinary_blob(content) {
return Err("this device holds no copy of its content".to_owned());
}
let mut reader = open
.stored
.open_blob(content)
.map_err(|_| "this device holds no copy of its content".to_owned())?;
let mut file = File::create_new(temporary).map_err(|error| error.to_string())?;
let matches =
copy_checked(&mut reader, &mut file, content).map_err(|error| error.to_string())?;
if !matches {
return Err("its content does not match its hash".to_owned());
}
file.sync_all().map_err(|error| error.to_string())
}
}
pub(super) fn make_folders(folder: &Path) -> io::Result<()> {
let missing: Vec<&Path> = folder
.ancestors()
.take_while(|at| fs::symlink_metadata(at).is_err())
.collect();
fs::create_dir_all(folder)?;
for made in missing.iter().rev() {
sync_folder_of(made);
}
Ok(())
}
fn move_into_place(place: Place<'_>, temporary: &Path, to: &str) -> Result<(), String> {
let blocked = |_| "something is in its place".to_owned();
let target = place_for_new(place.root, to, place.apart).map_err(blocked)?;
if let Some(parent) = target.parent() {
make_folders(parent).map_err(|error| error.to_string())?;
}
if place_for_new(place.root, to, place.apart).as_ref() != Ok(&target) {
return Err("something is in its place".to_owned());
}
fs::rename(temporary, &target).map_err(|error| error.to_string())?;
sync_folder_of(&target);
Ok(())
}
enum Merged {
Unchanged,
Clean(Owned),
Clashed(Owned),
Beside,
}
enum Owned {
Version(Version),
Bytes(Vec<u8>, bool),
}
impl Owned {
fn as_content(&self, secret: bool) -> Content<'_> {
match self {
Self::Version(version) => Content::of(version, secret),
Self::Bytes(bytes, executable) => Content::bytes(bytes, *executable, secret),
}
}
}
fn recorded_version<'a>(
entries: &'a BTreeMap<String, Entry>,
now: &'a TreeState,
path: &str,
) -> Option<&'a Version> {
entries.get(path).map(|entry| &entry.version).or_else(|| {
now.by_path
.get(path)
.and_then(|current| current.version.as_ref())
})
}
pub(super) fn copy_version(found: &Found) -> Option<Version> {
match &found.kind {
FoundKind::Link(target) => Some(Version::Link {
target: target.clone(),
}),
FoundKind::File => hash_found(found).ok().map(|content| Version::File {
content,
executable: found.executable.unwrap_or(false),
}),
}
}
pub(super) fn same_version(found: &Found, holds: &Version, recorded: &Version) -> bool {
if found.executable.is_some() {
holds == recorded
} else {
same_content(holds, recorded)
}
}
fn same_content(a: &Version, b: &Version) -> bool {
super::compare::same_content(a, b)
}
fn bytes_into(bytes: &[u8], temporary: &Path, private: bool) -> Result<(), String> {
let mut file = new_file(temporary, private).map_err(|error| error.to_string())?;
file.write_all(bytes)
.and_then(|()| file.sync_all())
.map_err(|error| error.to_string())
}
fn new_file(temporary: &Path, private: bool) -> io::Result<File> {
let mut options = File::options();
options.write(true).create_new(true);
#[cfg(unix)]
if private {
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
}
#[cfg(not(unix))]
let _ = private;
options.open(temporary)
}
#[cfg_attr(
not(unix),
expect(clippy::unnecessary_wraps, reason = "it can fail only on Unix")
)]
fn set_executable(path: &Path, executable: bool) -> Result<(), String> {
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = fs::metadata(path)
.map_err(|error| error.to_string())?
.permissions()
.mode();
let mode = if executable {
mode | ((mode & 0o444) >> 2)
} else {
mode & !0o111
};
fs::set_permissions(path, fs::Permissions::from_mode(mode))
.map_err(|error| error.to_string())
}
#[cfg(not(unix))]
{
let _ = (path, executable);
Ok(())
}
}
fn make_link(target: &str, at: &Path) -> Result<(), String> {
#[cfg(unix)]
{
std::os::unix::fs::symlink(target, at).map_err(|error| error.to_string())
}
#[cfg(windows)]
{
std::os::windows::fs::symlink_file(target.replace('/', "\\"), at)
.map_err(|error| format!("this system made no link: {error}"))
}
#[cfg(not(any(unix, windows)))]
{
let _ = (target, at);
Err("this system makes no links".to_owned())
}
}