use std::collections::VecDeque;
use std::future::Future;
use std::io;
use std::path::{Component, Path};
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
use futures_io::AsyncWrite;
use ostrya_core::{Checksum, Commit, DirMeta};
use crate::error::{Error, Result};
use crate::file::{FileKind, FileObject};
use crate::mtree::{ChildKind, ChildRef, MutableTree};
use crate::transaction::Transaction;
use crate::write::{ContentWriter, FileMeta};
const MAX_SYMLINK_DEPTH: usize = 40;
#[derive(Clone)]
enum Comp {
Normal(String),
Parent,
}
enum WalkEnd {
Dir(Vec<String>),
Leaf {
parent: Vec<String>,
name: String,
checksum: Checksum,
},
}
#[derive(Debug, Clone, Copy, Default)]
pub enum RootDirmeta {
#[default]
Reconcile,
KeepLeft,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct MergeOptions {
pub allow_overwrite: bool,
pub follow_symlinks: bool,
pub root_dirmeta: RootDirmeta,
pub symlink_target_dirmeta: RootDirmeta,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StagingEntry {
File {
name: String,
checksum: Checksum,
},
Dir {
name: String,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StagingLookup {
Absent,
File {
checksum: Checksum,
},
Dir,
}
pub struct StagingTree<'txn> {
txn: &'txn Transaction,
tree: Arc<Mutex<MutableTree>>,
writers: Arc<AtomicUsize>,
implied_dirmeta: Option<DirMeta>,
}
impl Transaction {
pub async fn staging_tree(&self, source: Option<&Commit>) -> Result<StagingTree<'_>> {
let tree = match source {
None => MutableTree::new(),
Some(commit) => {
MutableTree::hydrate(self.repo(), commit.root_dirtree, commit.root_dirmeta).await?
}
};
Ok(StagingTree::from_tree(self, tree))
}
pub fn staging_tree_from_mutable_tree(&self, source: MutableTree) -> StagingTree<'_> {
StagingTree::from_tree(self, source)
}
}
impl<'txn> StagingTree<'txn> {
fn from_tree(txn: &'txn Transaction, tree: MutableTree) -> StagingTree<'txn> {
StagingTree {
txn,
tree: Arc::new(Mutex::new(tree)),
writers: Arc::new(AtomicUsize::new(0)),
implied_dirmeta: None,
}
}
pub fn with_implied_dirmeta(mut self, meta: DirMeta) -> StagingTree<'txn> {
self.implied_dirmeta = Some(meta);
self
}
pub fn close(self) -> Result<MutableTree> {
let outstanding = self.writers.load(Ordering::Acquire);
if outstanding != 0 {
return Err(Error::Staging(format!(
"cannot close the staging tree: {outstanding} file writer(s) still outstanding"
)));
}
let mut guard = self.tree.lock().unwrap();
Ok(std::mem::take(&mut *guard))
}
pub async fn write_file(&self, path: &Path, meta: &FileMeta) -> Result<StagedFileWriter<'txn>> {
let (parent, name) = self.resolve_write_parent(path).await?;
self.check_writable_leaf(&parent, &name)?;
let writer = self.txn.content_writer(None, meta).await?;
{
let tree = self.tree.lock().unwrap();
if tree.dir_at(&parent).is_none() {
return Err(Error::Staging(dir_gone(&parent)));
}
self.writers.fetch_add(1, Ordering::AcqRel);
}
Ok(StagedFileWriter {
tree: self.tree.clone(),
writers: self.writers.clone(),
writer: Some(writer),
parent,
name,
})
}
pub async fn write_file_content(
&self,
path: &Path,
meta: &FileMeta,
content: &[u8],
) -> Result<()> {
let (parent, name) = self.resolve_write_parent(path).await?;
self.check_writable_leaf(&parent, &name)?;
let checksum = self.txn.write_regfile_inline(None, meta, content).await?;
self.with_dir_mut(&parent, |dir| dir.replace_file(&name, checksum))
}
pub async fn make_dir(&self, path: &Path, meta: &DirMeta) -> Result<()> {
let (parent, name) = self.resolve_parent(path).await?;
if !matches!(self.peek(&parent, &name)?, ChildKind::Absent) {
return Err(entry_exists(&parent, &name));
}
let dirmeta = self.stage_dirmeta(meta).await?;
self.with_dir_mut(&parent, |dir| {
if !matches!(dir.child_kind(&name), ChildKind::Absent) {
return Err(entry_exists(&parent, &name));
}
dir.insert_empty_dir(&name, Some(dirmeta));
Ok(())
})
}
pub async fn make_dir_all(&self, path: &Path, meta: &DirMeta) -> Result<()> {
self.walk_creating(components_of(path)?, meta, true).await?;
Ok(())
}
async fn walk_creating(
&self,
comps: Vec<Comp>,
meta: &DirMeta,
refuse_final_symlink: bool,
) -> Result<Vec<String>> {
let mut dirmeta: Option<Checksum> = None;
let mut cur: Vec<String> = Vec::new();
let total = comps.len();
for (idx, comp) in comps.into_iter().enumerate() {
let is_final = idx + 1 == total;
let name = match comp {
Comp::Parent => {
cur.pop();
continue;
}
Comp::Normal(name) => name,
};
match self.peek(&cur, &name)? {
ChildKind::Dir | ChildKind::LazyDir { .. } => {
self.ensure_child_dir(&cur, &name).await?;
cur.push(name);
}
ChildKind::Absent => {
let dm = match dirmeta {
Some(dm) => dm,
None => {
let dm = self.stage_dirmeta(meta).await?;
dirmeta = Some(dm);
dm
}
};
self.with_dir_mut(&cur, |dir| {
match dir.child_kind(&name) {
ChildKind::Absent => dir.insert_empty_dir(&name, Some(dm)),
ChildKind::File(_) => {
return Err(Error::NotADirectory {
path: join(&cur, &name),
});
}
ChildKind::Dir | ChildKind::LazyDir { .. } => {}
}
Ok(())
})?;
self.ensure_child_dir(&cur, &name).await?;
cur.push(name);
}
ChildKind::File(checksum) => {
let obj = self.txn.load_file_staged_first(&checksum).await?;
match obj.kind {
FileKind::Symlink { target } => {
if refuse_final_symlink && is_final {
return Err(entry_exists(&cur, &name));
}
let link = join(&cur, &name);
cur = match self.resolve_symlink_dir(&cur, &target).await {
Ok(dir) => dir,
Err(Error::PathNotFound { .. }) => {
return Err(Error::DanglingSymlink { path: link, target });
}
Err(e) => return Err(e),
};
}
FileKind::Regular { .. } => {
return Err(Error::NotADirectory {
path: join(&cur, &name),
});
}
}
}
}
}
Ok(cur)
}
pub async fn ensure_dir(&self, path: &Path, meta: &DirMeta) -> Result<()> {
if components_of(path)?.is_empty() {
let new_dirmeta = self.txn.dirmeta_checksum(meta)?;
if self.with_dir(&[], |dir| dir.metadata_checksum())? == Some(new_dirmeta) {
return Ok(());
}
let dirmeta = self.stage_dirmeta(meta).await?;
return self.with_dir_mut(&[], |dir| {
dir.set_metadata_checksum(dirmeta);
Ok(())
});
}
let (parent, name) = self.resolve_write_parent(path).await?;
let new_dirmeta = self.txn.dirmeta_checksum(meta)?;
let unchanged = match self.peek(&parent, &name)? {
ChildKind::File(_) => {
return Err(Error::NotADirectory {
path: join(&parent, &name),
});
}
ChildKind::Absent => false,
ChildKind::LazyDir { dirmeta, .. } => dirmeta == new_dirmeta,
ChildKind::Dir => {
let mut child = parent.clone();
child.push(name.clone());
self.with_dir(&child, |dir| dir.metadata_checksum())? == Some(new_dirmeta)
}
};
if unchanged {
return Ok(());
}
let dirmeta = self.stage_dirmeta(meta).await?;
self.with_dir_mut(&parent, |dir| match dir.child_kind(&name) {
ChildKind::Absent => {
dir.insert_empty_dir(&name, Some(dirmeta));
Ok(())
}
ChildKind::Dir | ChildKind::LazyDir { .. } => dir.set_child_dirmeta(&name, dirmeta),
ChildKind::File(_) => Err(Error::NotADirectory {
path: join(&parent, &name),
}),
})
}
pub async fn symlink(&self, path: &Path, target: &Path, meta: &FileMeta) -> Result<()> {
let (parent, name) = self.resolve_write_parent(path).await?;
self.check_writable_leaf(&parent, &name)?;
let target = target
.to_str()
.ok_or_else(|| Error::Staging("symlink target is not valid UTF-8".into()))?;
let checksum = self.txn.write_symlink(target, meta, None).await?;
self.with_dir_mut(&parent, |dir| dir.replace_file(&name, checksum))
}
pub async fn hardlink(&self, path: &Path, target: &Path) -> Result<()> {
let checksum = match self
.walk_from(Vec::new(), components_of(target)?, false)
.await?
{
WalkEnd::Leaf { checksum, .. } => checksum,
WalkEnd::Dir(dir) => {
return Err(Error::Staging(format!(
"cannot hardlink from {}: the source is a directory",
spell_path(&dir)
)));
}
};
let (parent, name) = self.resolve_write_parent(path).await?;
self.check_writable_leaf(&parent, &name)?;
self.with_dir_mut(&parent, |dir| dir.replace_file(&name, checksum))
}
pub async fn place_object(&self, path: &Path, checksum: &Checksum) -> Result<()> {
let (parent, name) = self.resolve_write_parent(path).await?;
self.with_dir_mut(&parent, |dir| match dir.child_kind(&name) {
ChildKind::Absent => dir.replace_file(&name, *checksum),
ChildKind::File(existing) if existing == *checksum => Ok(()),
ChildKind::File(_) => Err(Error::MergeConflict(format!(
"placed object differs at {}",
join(&parent, &name)
))),
ChildKind::Dir | ChildKind::LazyDir { .. } => Err(Error::MergeConflict(format!(
"an object cannot overwrite the directory at {}",
join(&parent, &name)
))),
})
}
pub async fn remove(&self, path: &Path, allow_noent: bool) -> Result<()> {
let (parent, name) = match self.resolve_parent(path).await {
Ok(resolved) => resolved,
Err(Error::PathNotFound { .. } | Error::DanglingSymlink { .. }) if allow_noent => {
return Ok(());
}
Err(e) => return Err(e),
};
self.with_dir_mut(&parent, |dir| match dir.child_kind(&name) {
ChildKind::Absent if allow_noent => Ok(()),
ChildKind::Absent => Err(Error::PathNotFound {
path: join(&parent, &name),
}),
_ => {
self.check_no_live_writers(&format!("remove {}", join(&parent, &name)))?;
dir.remove(&name, true)
}
})
}
pub async fn clear_dir(&self, path: &Path, allow_noent: bool) -> Result<()> {
let (parent, name) = match self.resolve_parent(path).await {
Ok(resolved) => resolved,
Err(Error::PathNotFound { .. } | Error::DanglingSymlink { .. }) if allow_noent => {
return Ok(());
}
Err(e) => return Err(e),
};
self.with_dir_mut(&parent, |dir| match dir.child_kind(&name) {
ChildKind::Absent if allow_noent => Ok(()),
ChildKind::Absent => Err(Error::PathNotFound {
path: join(&parent, &name),
}),
ChildKind::File(_) => Err(Error::NotADirectory {
path: join(&parent, &name),
}),
ChildKind::Dir => {
self.check_no_live_writers(&format!(
"clear the directory at {}",
join(&parent, &name)
))?;
let child = dir
.dir_at_mut(std::slice::from_ref(&name))
.expect("a loaded child under the same lock acquisition");
child.clear_children();
Ok(())
}
ChildKind::LazyDir { dirmeta, .. } => {
self.check_no_live_writers(&format!(
"clear the directory at {}",
join(&parent, &name)
))?;
dir.insert_empty_dir(&name, Some(dirmeta));
Ok(())
}
})
}
pub async fn rename(&self, from: &Path, to: &Path) -> Result<()> {
let (from_parent, from_name) = self.resolve_parent(from).await?;
let (to_parent, to_name) = self.resolve_write_parent(to).await?;
let mut from_path = from_parent.clone();
from_path.push(from_name.clone());
if to_parent.starts_with(&from_path) {
return Err(Error::Staging(format!(
"cannot rename {} to {}: the destination is under the moved entry",
spell_path(&from_path),
join(&to_parent, &to_name)
)));
}
let mut tree = self.tree.lock().unwrap();
let to_dir = tree
.dir_at(&to_parent)
.ok_or_else(|| Error::Staging(dir_gone(&to_parent)))?;
if !matches!(to_dir.child_kind(&to_name), ChildKind::Absent) {
return Err(entry_exists(&to_parent, &to_name));
}
let from_dir = tree
.dir_at_mut(&from_parent)
.ok_or_else(|| Error::Staging(dir_gone(&from_parent)))?;
if matches!(from_dir.child_kind(&from_name), ChildKind::Absent) {
return Err(Error::PathNotFound {
path: join(&from_parent, &from_name),
});
}
self.check_no_live_writers(&format!(
"rename {} to {}",
join(&from_parent, &from_name),
join(&to_parent, &to_name)
))?;
let entry = from_dir
.take_child(&from_name)
.expect("an entry present under the same lock acquisition");
tree.dir_at_mut(&to_parent)
.expect("a destination parent present under the same lock acquisition")
.insert_child(&to_name, entry)
.expect("a fresh name in a present directory under the same lock acquisition");
Ok(())
}
pub async fn lookup(&self, path: &Path, follow_symlinks: bool) -> Result<StagingLookup> {
match self
.walk_from(Vec::new(), components_of(path)?, follow_symlinks)
.await
{
Ok(WalkEnd::Dir(_)) => Ok(StagingLookup::Dir),
Ok(WalkEnd::Leaf { checksum, .. }) => Ok(StagingLookup::File { checksum }),
Err(Error::PathNotFound { .. }) => Ok(StagingLookup::Absent),
Err(e) => Err(e),
}
}
pub async fn read_file(&self, path: &Path, follow_symlinks: bool) -> Result<FileObject> {
match self
.walk_from(Vec::new(), components_of(path)?, follow_symlinks)
.await?
{
WalkEnd::Leaf { checksum, .. } => self.txn.load_file_staged_first(&checksum).await,
WalkEnd::Dir(dir) => Err(Error::Staging(format!(
"{} is a directory, not a file",
spell_path(&dir)
))),
}
}
pub async fn read_dir(&self, path: &Path, follow_symlinks: bool) -> Result<Vec<StagingEntry>> {
let dir_path = match self
.walk_from(Vec::new(), components_of(path)?, follow_symlinks)
.await?
{
WalkEnd::Dir(p) => p,
WalkEnd::Leaf {
parent: dir, name, ..
} => {
return Err(Error::NotADirectory {
path: join(&dir, &name),
});
}
};
self.with_dir(&dir_path, |dir| {
let mut entries = Vec::new();
for (name, checksum) in dir.file_entries() {
entries.push(StagingEntry::File {
name: name.to_owned(),
checksum,
});
}
for (name, _child) in dir.dir_entries() {
entries.push(StagingEntry::Dir {
name: name.to_owned(),
});
}
entries
})
}
pub async fn merge(&self, other: &MutableTree, opts: MergeOptions) -> Result<()> {
self.merge_at(Path::new("."), other, opts).await
}
pub async fn merge_at(
&self,
base: &Path,
other: &MutableTree,
opts: MergeOptions,
) -> Result<()> {
let base_path = self.resolve_merge_base(base).await?;
merge_into(
self,
base_path,
RightDir::Mutable(other),
&opts,
opts.root_dirmeta,
)
.await
}
async fn stage_dirmeta(&self, meta: &DirMeta) -> Result<Checksum> {
self.txn.write_dirmeta(meta).await
}
fn check_no_live_writers(&self, action: &str) -> Result<()> {
let outstanding = self.writers.load(Ordering::Acquire);
if outstanding != 0 {
return Err(Error::Staging(format!(
"cannot {action}: {outstanding} file writer(s) still outstanding"
)));
}
Ok(())
}
fn check_writable_leaf(&self, parent: &[String], name: &str) -> Result<()> {
match self.peek(parent, name)? {
ChildKind::Dir | ChildKind::LazyDir { .. } => {
Err(Error::ReplaceDirWithFile(name.to_owned()))
}
_ => Ok(()),
}
}
async fn resolve_merge_base(&self, base: &Path) -> Result<Vec<String>> {
let comps = components_of(base)?;
let Some(meta) = &self.implied_dirmeta else {
return match self.walk_from(Vec::new(), comps, true).await? {
WalkEnd::Dir(dir) => Ok(dir),
WalkEnd::Leaf { parent, name, .. } => Err(Error::NotADirectory {
path: join(&parent, &name),
}),
};
};
self.walk_creating(comps, meta, false).await
}
fn insert_merged_dir(
&self,
parent: &[String],
name: &str,
dirmeta: Option<Checksum>,
allow_overwrite: bool,
) -> Result<()> {
self.with_dir_mut(parent, |dir| {
if matches!(
dir.child_kind(name),
ChildKind::Dir | ChildKind::LazyDir { .. }
) {
if !allow_overwrite {
return Err(Error::MergeConflict(format!(
"a directory appeared at {} after the merge read the name",
join(parent, name)
)));
}
self.check_no_live_writers(&format!(
"drop the directory at {}",
join(parent, name)
))?;
}
dir.insert_empty_dir(name, dirmeta);
Ok(())
})
}
async fn resolve_write_parent(&self, path: &Path) -> Result<(Vec<String>, String)> {
let Some(meta) = &self.implied_dirmeta else {
return self.resolve_parent(path).await;
};
let (init, name) = split_final(path)?;
let parent = self.walk_creating(init, meta, false).await?;
Ok((parent, name))
}
async fn resolve_parent(&self, path: &Path) -> Result<(Vec<String>, String)> {
let (init, name) = split_final(path)?;
let parent = match self.walk_from(Vec::new(), init, true).await? {
WalkEnd::Dir(dir) => dir,
WalkEnd::Leaf {
parent: dir, name, ..
} => {
return Err(Error::NotADirectory {
path: join(&dir, &name),
});
}
};
Ok((parent, name))
}
async fn resolve_symlink_dir(&self, base: &[String], target: &str) -> Result<Vec<String>> {
let (absolute, comps) = split_target(target)?;
let start = if absolute { Vec::new() } else { base.to_vec() };
match self.walk_from(start, comps, true).await? {
WalkEnd::Dir(dir) => Ok(dir),
WalkEnd::Leaf {
parent: dir, name, ..
} => Err(Error::NotADirectory {
path: join(&dir, &name),
}),
}
}
async fn walk_from(
&self,
start: Vec<String>,
comps: Vec<Comp>,
follow_final: bool,
) -> Result<WalkEnd> {
let mut cur = start;
let mut pending: VecDeque<Comp> = comps.into();
let mut symlink_depth = 0usize;
let mut open_symlinks: Vec<(String, String, usize)> = Vec::new();
while let Some(comp) = pending.pop_front() {
while open_symlinks
.last()
.is_some_and(|(_, _, mark)| pending.len() < *mark)
{
open_symlinks.pop();
}
let is_final = pending.is_empty();
let name = match comp {
Comp::Parent => {
cur.pop();
continue;
}
Comp::Normal(name) => name,
};
match self.peek(&cur, &name)? {
ChildKind::Absent => {
return Err(match open_symlinks.last() {
Some((path, target, _)) => Error::DanglingSymlink {
path: path.clone(),
target: target.clone(),
},
None => Error::PathNotFound {
path: join(&cur, &name),
},
});
}
ChildKind::Dir | ChildKind::LazyDir { .. } => {
self.ensure_child_dir(&cur, &name).await?;
cur.push(name);
}
ChildKind::File(checksum) => {
if is_final && !follow_final {
return Ok(WalkEnd::Leaf {
parent: cur,
name,
checksum,
});
}
let obj = self.txn.load_file_staged_first(&checksum).await?;
match obj.kind {
FileKind::Symlink { target } => {
symlink_depth += 1;
if symlink_depth > MAX_SYMLINK_DEPTH {
return Err(Error::SymlinkLoop {
path: join(&cur, &name),
});
}
let (absolute, target_comps) = split_target(&target)?;
let mark = pending.len();
open_symlinks.push((join(&cur, &name), target.clone(), mark));
if absolute {
cur.clear();
}
for comp in target_comps.into_iter().rev() {
pending.push_front(comp);
}
}
FileKind::Regular { .. } => {
if is_final {
return Ok(WalkEnd::Leaf {
parent: cur,
name,
checksum,
});
}
return Err(Error::NotADirectory {
path: join(&cur, &name),
});
}
}
}
}
}
Ok(WalkEnd::Dir(cur))
}
async fn ensure_child_dir(&self, path: &[String], name: &str) -> Result<()> {
loop {
let (kind, repo) = {
let tree = self.tree.lock().unwrap();
let dir = tree
.dir_at(path)
.ok_or_else(|| Error::Staging(dir_gone(path)))?;
(dir.child_kind(name), dir.repo())
};
match kind {
ChildKind::Dir => return Ok(()),
ChildKind::LazyDir { dirtree, dirmeta } => {
let repo = repo.ok_or_else(|| {
Error::Staging(format!(
"cannot hydrate {}: no repository handle",
join(path, name)
))
})?;
let loaded = MutableTree::hydrate(&repo, dirtree, dirmeta).await?;
let mut tree = self.tree.lock().unwrap();
if let Some(dir) = tree.dir_at_mut(path)
&& matches!(dir.child_kind(name), ChildKind::LazyDir { .. })
{
dir.install_hydrated_child(name, loaded);
}
}
ChildKind::File(_) => {
return Err(Error::NotADirectory {
path: join(path, name),
});
}
ChildKind::Absent => {
return Err(Error::PathNotFound {
path: join(path, name),
});
}
}
}
}
fn peek(&self, path: &[String], name: &str) -> Result<ChildKind> {
let tree = self.tree.lock().unwrap();
let dir = tree
.dir_at(path)
.ok_or_else(|| Error::Staging(dir_gone(path)))?;
Ok(dir.child_kind(name))
}
fn with_dir<R>(&self, path: &[String], f: impl FnOnce(&MutableTree) -> R) -> Result<R> {
let tree = self.tree.lock().unwrap();
let dir = tree
.dir_at(path)
.ok_or_else(|| Error::Staging(dir_gone(path)))?;
Ok(f(dir))
}
fn with_dir_mut<R>(
&self,
path: &[String],
f: impl FnOnce(&mut MutableTree) -> Result<R>,
) -> Result<R> {
let mut tree = self.tree.lock().unwrap();
let dir = tree
.dir_at_mut(path)
.ok_or_else(|| Error::Staging(dir_gone(path)))?;
f(dir)
}
}
enum RightDir<'a> {
Mutable(&'a MutableTree),
Committed {
txn: &'a Transaction,
dirtree: Checksum,
dirmeta: Checksum,
},
}
impl<'a> RightDir<'a> {
fn dirmeta(&self) -> Option<Checksum> {
match self {
RightDir::Mutable(tree) => tree.metadata_checksum(),
RightDir::Committed { dirmeta, .. } => Some(*dirmeta),
}
}
async fn entries(
&self,
txn: &'a Transaction,
) -> Result<(Vec<(String, Checksum)>, Vec<(String, RightDir<'a>)>)> {
match self {
RightDir::Mutable(tree) => {
let tree: &'a MutableTree = tree;
let files = tree
.file_entries()
.map(|(name, checksum)| (name.to_owned(), checksum))
.collect();
let dirs = tree
.dir_entries()
.map(|(name, child)| {
let view = match child {
ChildRef::Loaded(sub) => RightDir::Mutable(sub),
ChildRef::Lazy { dirtree, dirmeta } => RightDir::Committed {
txn,
dirtree,
dirmeta,
},
};
(name.to_owned(), view)
})
.collect();
Ok((files, dirs))
}
RightDir::Committed { txn, dirtree, .. } => {
let txn: &'a Transaction = txn;
let dt = txn.load_dirtree_staged_first(dirtree).await?;
let files = dt.files.into_iter().collect();
let dirs = dt
.dirs
.into_iter()
.map(|(name, child_dirtree, child_dirmeta)| {
(
name,
RightDir::Committed {
txn,
dirtree: child_dirtree,
dirmeta: child_dirmeta,
},
)
})
.collect();
Ok((files, dirs))
}
}
}
}
type MergeFuture<'a> = Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
fn merge_into<'a>(
st: &'a StagingTree<'_>,
left_path: Vec<String>,
right: RightDir<'a>,
opts: &'a MergeOptions,
root_dirmeta: RootDirmeta,
) -> MergeFuture<'a> {
Box::pin(async move {
if matches!(root_dirmeta, RootDirmeta::Reconcile)
&& let Some(right_dm) = right.dirmeta()
{
let left_dm = {
let tree = st.tree.lock().unwrap();
match tree.dir_at(&left_path) {
Some(dir) => dir.metadata_checksum(),
None => return Err(Error::Staging(dir_gone(&left_path))),
}
};
match left_dm {
Some(left) if left == right_dm => {}
Some(_) if !opts.allow_overwrite => {
return Err(Error::MergeConflict(format!(
"directory metadata differs at {}",
spell_path(&left_path)
)));
}
_ => {
st.with_dir_mut(&left_path, |dir| {
dir.set_metadata_checksum(right_dm);
Ok(())
})?;
}
}
}
let (rfiles, rdirs) = right.entries(st.txn).await?;
for (name, right_csum) in rfiles {
match st.peek(&left_path, &name)? {
ChildKind::Absent => {
st.with_dir_mut(&left_path, |dir| dir.replace_file(&name, right_csum))?;
}
ChildKind::File(left_csum) if left_csum == right_csum => {}
ChildKind::File(_) => {
if !opts.allow_overwrite {
return Err(Error::MergeConflict(format!(
"file differs at {}",
join(&left_path, &name)
)));
}
st.with_dir_mut(&left_path, |dir| dir.replace_file(&name, right_csum))?;
}
ChildKind::Dir | ChildKind::LazyDir { .. } => {
if !opts.allow_overwrite {
return Err(Error::MergeConflict(format!(
"a file cannot overwrite the directory at {}",
join(&left_path, &name)
)));
}
st.with_dir_mut(&left_path, |dir| {
st.check_no_live_writers(&format!(
"drop the directory at {}",
join(&left_path, &name)
))?;
dir.remove(&name, true)?;
dir.replace_file(&name, right_csum)
})?;
}
}
}
for (name, right_child) in rdirs {
match st.peek(&left_path, &name)? {
ChildKind::Absent => {
st.insert_merged_dir(
&left_path,
&name,
right_child.dirmeta(),
opts.allow_overwrite,
)?;
let mut child_path = left_path.clone();
child_path.push(name);
merge_into(st, child_path, right_child, opts, RootDirmeta::Reconcile).await?;
}
ChildKind::Dir | ChildKind::LazyDir { .. } => {
st.ensure_child_dir(&left_path, &name).await?;
let mut child_path = left_path.clone();
child_path.push(name);
merge_into(st, child_path, right_child, opts, RootDirmeta::Reconcile).await?;
}
ChildKind::File(left_csum) => {
if opts.follow_symlinks {
let obj = st.txn.load_file_staged_first(&left_csum).await?;
if let FileKind::Symlink { target } = obj.kind {
let target_dir = st.resolve_symlink_dir(&left_path, &target).await?;
merge_into(
st,
target_dir,
right_child,
opts,
opts.symlink_target_dirmeta,
)
.await?;
continue;
}
}
if !opts.allow_overwrite {
return Err(Error::MergeConflict(format!(
"a directory cannot overwrite the file at {}",
join(&left_path, &name)
)));
}
st.insert_merged_dir(
&left_path,
&name,
right_child.dirmeta(),
opts.allow_overwrite,
)?;
let mut child_path = left_path.clone();
child_path.push(name);
merge_into(st, child_path, right_child, opts, RootDirmeta::Reconcile).await?;
}
}
}
Ok(())
})
}
pub struct StagedFileWriter<'txn> {
tree: Arc<Mutex<MutableTree>>,
writers: Arc<AtomicUsize>,
writer: Option<ContentWriter<'txn>>,
parent: Vec<String>,
name: String,
}
impl StagedFileWriter<'_> {
pub async fn finish(mut self) -> Result<()> {
let writer = self.writer.take().expect("writer present until finish");
let outcome = match writer.finish().await {
Ok(checksum) => {
let mut tree = self.tree.lock().unwrap();
match tree.dir_at_mut(&self.parent) {
Some(dir) => dir.replace_file(&self.name, checksum),
None => Err(Error::Staging(dir_gone(&self.parent))),
}
}
Err(e) => Err(e),
};
self.writers.fetch_sub(1, Ordering::AcqRel);
outcome
}
}
impl Drop for StagedFileWriter<'_> {
fn drop(&mut self) {
if self.writer.is_some() {
self.writers.fetch_sub(1, Ordering::AcqRel);
}
}
}
impl AsyncWrite for StagedFileWriter<'_> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
match &mut self.get_mut().writer {
Some(writer) => Pin::new(writer).poll_write(cx, buf),
None => Poll::Ready(Ok(0)),
}
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
match &mut self.get_mut().writer {
Some(writer) => Pin::new(writer).poll_flush(cx),
None => Poll::Ready(Ok(())),
}
}
fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
self.poll_flush(cx)
}
}
#[cfg(feature = "tokio")]
impl ostrya_rt::tokio_io::AsyncWrite for StagedFileWriter<'_> {
fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<io::Result<usize>> {
AsyncWrite::poll_write(self, cx, buf)
}
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
AsyncWrite::poll_flush(self, cx)
}
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
AsyncWrite::poll_close(self, cx)
}
}
fn components_of(path: &Path) -> Result<Vec<Comp>> {
path.components()
.filter_map(|c| match c {
Component::Normal(part) => Some(
part.to_str()
.map(|s| Comp::Normal(s.to_owned()))
.ok_or_else(|| {
Error::Staging(format!(
"path component is not valid UTF-8: {}",
path.display()
))
}),
),
Component::ParentDir => Some(Ok(Comp::Parent)),
Component::RootDir | Component::CurDir | Component::Prefix(_) => None,
})
.collect()
}
fn split_final(path: &Path) -> Result<(Vec<Comp>, String)> {
let mut comps = components_of(path)?;
let name = match comps.pop() {
Some(Comp::Normal(name)) => name,
Some(Comp::Parent) => {
return Err(Error::Staging(format!("{} ends in `..`", path.display())));
}
None => {
return Err(Error::Staging(format!(
"{} has no final component",
path.display()
)));
}
};
Ok((comps, name))
}
fn split_target(target: &str) -> Result<(bool, Vec<Comp>)> {
Ok((target.starts_with('/'), components_of(Path::new(target))?))
}
fn join(path: &[String], name: &str) -> String {
if path.is_empty() {
name.to_owned()
} else {
format!("{}/{}", path.join("/"), name)
}
}
fn spell_path(path: &[String]) -> String {
if path.is_empty() {
".".to_owned()
} else {
path.join("/")
}
}
fn dir_gone(path: &[String]) -> String {
format!("directory {} is no longer present", spell_path(path))
}
fn entry_exists(parent: &[String], name: &str) -> Error {
Error::EntryExists {
path: join(parent, name),
}
}
const _: fn() = || {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<StagingTree<'static>>();
assert_send_sync::<StagedFileWriter<'static>>();
assert_send_sync::<StagingEntry>();
assert_send_sync::<StagingLookup>();
assert_send_sync::<MergeOptions>();
assert_send_sync::<RootDirmeta>();
};
#[cfg(feature = "tokio")]
const _: fn() = || {
fn assert_tokio_write<T: ostrya_rt::tokio_io::AsyncWrite>() {}
assert_tokio_write::<StagedFileWriter<'static>>();
};