use std::collections::{HashMap, HashSet};
use std::ffi::{OsStr, OsString};
use std::future::Future;
use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::Arc;
use futures_lite::AsyncReadExt;
use futures_lite::future::zip;
use ostrya_core::{
Checksum, ContentHasher, DirMeta, DirTree, FileHeader, ObjectName, Xattrs, loose_path,
};
use ostrya_rt::File as RtFile;
use rustix::fs::{AtFlags, Dir, FileType, Mode, OFlags};
use rustix::io::Errno;
use sha2::{Digest, Sha256};
use crate::error::{Error, Result};
use crate::ingest::{adjust_meta, to_dirmeta};
use crate::modifier::{CommitModifierFlags, Owner};
use crate::object;
use crate::repo::Repo;
use crate::write::FileMeta;
const HASH_CHUNK: usize = 64 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiffChange {
Added,
Removed,
Modified,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiffEntry {
pub change: DiffChange,
pub path: String,
}
#[derive(Debug, Clone, Copy)]
pub enum DiffSide<'a> {
Commit(&'a Checksum),
Directory(&'a Path),
}
#[derive(Debug, Clone, Copy, Default)]
pub struct DiffOptions {
pub skip_xattrs: bool,
pub owner_uid: Option<u32>,
pub owner_gid: Option<u32>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DiffStats {
pub from_objects: usize,
pub to_objects: usize,
pub common_objects: usize,
pub common_bytes: u64,
}
enum Side {
Repo(Checksum),
Local(LocalDir),
}
struct LocalDir {
root: Arc<OwnedFd>,
rel: PathBuf,
path: PathBuf,
}
impl LocalDir {
fn at(&self) -> &Path {
if self.rel.as_os_str().is_empty() {
Path::new(".")
} else {
&self.rel
}
}
fn child(&self, name: &OsStr) -> LocalDir {
LocalDir {
root: self.root.clone(),
rel: self.rel.join(name),
path: self.path.join(name),
}
}
}
struct SideEntry {
name: OsString,
kind: EntryKind,
}
enum SideList {
Repo(Vec<SideEntry>),
Local(Vec<RawEntry>),
}
impl SideList {
fn classes(&self) -> Vec<(&OsStr, Class)> {
match self {
SideList::Repo(entries) => entries
.iter()
.map(|entry| {
let class = match entry.kind {
EntryKind::Dir { .. } => Class::Dir,
_ => Class::Content,
};
(entry.name.as_os_str(), class)
})
.collect(),
SideList::Local(raw) => raw
.iter()
.map(|entry| (entry.name.as_os_str(), entry.kind.class()))
.collect(),
}
}
}
enum EntryKind {
Content(Checksum),
Dir { meta: Checksum, dirtree: Checksum },
File { meta: FileMeta, size: u64 },
Symlink { meta: FileMeta, target: Vec<u8> },
LocalDir { meta: FileMeta },
Other(FileMeta),
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Class {
Dir,
Content,
File,
Symlink,
Other,
}
fn classes_pair(left: Class, right: Class) -> bool {
matches!(
(left, right),
(Class::Dir, Class::Dir)
| (Class::Other, Class::Other)
| (Class::File, Class::File)
| (Class::Symlink, Class::Symlink)
| (
Class::Content,
Class::Content | Class::File | Class::Symlink
)
| (Class::File | Class::Symlink, Class::Content)
)
}
#[derive(Default)]
struct Lists {
modified: Vec<String>,
removed: Vec<String>,
added: Vec<String>,
}
type WalkFuture<'a> = Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
impl Repo {
pub async fn diff(
&self,
from: DiffSide<'_>,
to: DiffSide<'_>,
options: &DiffOptions,
) -> Result<Vec<DiffEntry>> {
let from_root = self.open_side(from).await?;
let to_root = self.open_side(to).await?;
let mut lists = Lists::default();
walk(
self,
from_root,
to_root,
OsString::new(),
options,
&mut lists,
)
.await?;
let mut out =
Vec::with_capacity(lists.modified.len() + lists.removed.len() + lists.added.len());
out.extend(entries(DiffChange::Modified, lists.modified));
out.extend(entries(DiffChange::Removed, lists.removed));
out.extend(entries(DiffChange::Added, lists.added));
Ok(out)
}
pub async fn diff_commits(&self, from: &Checksum, to: &Checksum) -> Result<Vec<DiffEntry>> {
self.diff(
DiffSide::Commit(from),
DiffSide::Commit(to),
&DiffOptions::default(),
)
.await
}
pub async fn diff_stats(&self, from: &Checksum, to: &Checksum) -> Result<DiffStats> {
let from_set = self.traverse_commit(from, 0).await?;
let to_set = self.traverse_commit(to, 0).await?;
let common: Vec<ObjectName> = from_set.intersection(&to_set).copied().collect();
let common_objects = common.len();
let repo = self.clone();
let mode = self.mode();
let common_bytes = ostrya_rt::unblock(move || {
let dir = repo.objects_fd();
let mut total = 0u64;
for name in &common {
let path = loose_path(&name.checksum, name.ty, mode);
match object::object_size(dir, &path) {
Ok(size) => total += size,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
return Err(Error::ObjectNotFound {
checksum: name.checksum,
ty: name.ty,
});
}
Err(err) => return Err(Error::Io(err)),
}
}
Ok(total)
})
.await?;
Ok(DiffStats {
from_objects: from_set.len(),
to_objects: to_set.len(),
common_objects,
common_bytes,
})
}
async fn open_side(&self, side: DiffSide<'_>) -> Result<Side> {
match side {
DiffSide::Commit(commit) => {
let (commit, _) = self.load_commit(commit).await?;
Ok(Side::Repo(commit.root_dirtree))
}
DiffSide::Directory(path) => {
let owned = path.to_path_buf();
let fd = ostrya_rt::unblock(move || {
rustix::fs::open(
&owned,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)
.map_err(|err| path_error("opendir", &owned, err))
})
.await?;
Ok(Side::Local(LocalDir {
root: Arc::new(fd),
rel: PathBuf::new(),
path: path.to_path_buf(),
}))
}
}
}
}
fn walk<'a>(
repo: &'a Repo,
from: Side,
to: Side,
prefix: OsString,
options: &'a DiffOptions,
out: &'a mut Lists,
) -> WalkFuture<'a> {
Box::pin(async move {
let (from_list, to_list) = zip(read_list(repo, &from), read_list(repo, &to)).await;
let (from_list, to_list) = (from_list?, to_list?);
let wanted = paired_names(&from_list, &to_list, options);
let (from_entries, to_entries) = zip(
shape(&from, from_list, &wanted, options, Owner::default()),
shape(&to, to_list, &wanted, options, to_owner(options)),
)
.await;
let (from_entries, to_entries) = (from_entries?, to_entries?);
let index: HashMap<&OsStr, usize> = to_entries
.iter()
.enumerate()
.map(|(at, entry)| (entry.name.as_os_str(), at))
.collect();
let held: HashSet<&OsStr> = from_entries
.iter()
.map(|entry| entry.name.as_os_str())
.collect();
for entry in &from_entries {
let path = join(&prefix, &entry.name);
let Some(other) = index.get(entry.name.as_os_str()).map(|at| &to_entries[*at]) else {
out.removed.push(render(&path));
continue;
};
match (&entry.kind, &other.kind) {
(
EntryKind::Dir { .. } | EntryKind::LocalDir { .. },
EntryKind::Dir { .. } | EntryKind::LocalDir { .. },
) => {
if dirmeta_differs(&entry.kind, &other.kind)? {
out.modified.push(render(&path));
}
if let (
EntryKind::Dir { dirtree: left, .. },
EntryKind::Dir { dirtree: right, .. },
) = (&entry.kind, &other.kind)
&& left == right
{
continue;
}
let child_from = descend(&from, entry)?;
let child_to = descend(&to, other)?;
walk(repo, child_from, child_to, path, options, out).await?;
}
(EntryKind::Other(left), EntryKind::Other(right)) => {
if !meta_eq(left, right) {
out.modified.push(render(&path));
}
}
(
EntryKind::File {
meta: left,
size: left_size,
},
EntryKind::File {
meta: right,
size: right_size,
},
) => {
if !meta_eq(left, right) || left_size != right_size {
out.modified.push(render(&path));
} else {
let (a, b) = zip(
hash_local_file(&from, &entry.name, left),
hash_local_file(&to, &entry.name, right),
)
.await;
if a? != b? {
out.modified.push(render(&path));
}
}
}
(
EntryKind::Symlink {
meta: left,
target: left_target,
},
EntryKind::Symlink {
meta: right,
target: right_target,
},
) => {
if !meta_eq(left, right) || left_target != right_target {
out.modified.push(render(&path));
}
}
(
EntryKind::Content(_),
EntryKind::Content(_) | EntryKind::File { .. } | EntryKind::Symlink { .. },
)
| (EntryKind::File { .. } | EntryKind::Symlink { .. }, EntryKind::Content(_)) => {
let (left, right) = zip(
content_checksum(&from, &entry.name, &entry.kind),
content_checksum(&to, &entry.name, &other.kind),
)
.await;
match (left?, right?) {
(Some(left), Some(right)) if left == right => {}
_ => out.modified.push(render(&path)),
}
}
_ => out.modified.push(render(&path)),
}
}
for entry in &to_entries {
if held.contains(entry.name.as_os_str()) {
continue;
}
let path = join(&prefix, &entry.name);
out.added.push(render(&path));
if matches!(
entry.kind,
EntryKind::Dir { .. } | EntryKind::LocalDir { .. }
) {
let child = descend(&to, entry)?;
collect_added(repo, child, path, options, out).await?;
}
}
Ok(())
})
}
fn collect_added<'a>(
repo: &'a Repo,
dir: Side,
prefix: OsString,
options: &'a DiffOptions,
out: &'a mut Lists,
) -> WalkFuture<'a> {
Box::pin(async move {
let list = read_list(repo, &dir).await?;
let entries = shape(&dir, list, &HashSet::new(), options, to_owner(options)).await?;
for entry in &entries {
let path = join(&prefix, &entry.name);
out.added.push(render(&path));
if matches!(
entry.kind,
EntryKind::Dir { .. } | EntryKind::LocalDir { .. }
) {
let child = descend(&dir, entry)?;
collect_added(repo, child, path, options, out).await?;
}
}
Ok(())
})
}
fn paired_names(from: &SideList, to: &SideList, options: &DiffOptions) -> HashSet<OsString> {
let local = matches!(from, SideList::Local(_)) || matches!(to, SideList::Local(_));
if options.skip_xattrs || !local {
return HashSet::new();
}
let to_classes: HashMap<&OsStr, Class> = to.classes().into_iter().collect();
from.classes()
.into_iter()
.filter(|(name, class)| {
to_classes
.get(name)
.is_some_and(|other| classes_pair(*class, *other))
})
.map(|(name, _)| name.to_owned())
.collect()
}
fn join(prefix: &OsStr, name: &OsStr) -> OsString {
let mut path = prefix.to_owned();
path.push("/");
path.push(name);
path
}
fn render(path: &OsStr) -> String {
path.to_string_lossy().into_owned()
}
fn to_owner(options: &DiffOptions) -> Owner {
Owner {
uid: options.owner_uid,
gid: options.owner_gid,
}
}
fn meta_eq(a: &FileMeta, b: &FileMeta) -> bool {
a.uid == b.uid && a.gid == b.gid && a.mode == b.mode && a.xattrs == b.xattrs
}
fn dirmeta_differs(left: &EntryKind, right: &EntryKind) -> Result<bool> {
match (left, right) {
(EntryKind::Dir { meta: a, .. }, EntryKind::Dir { meta: b, .. }) => Ok(a != b),
(EntryKind::LocalDir { meta: a }, EntryKind::LocalDir { meta: b }) => Ok(!meta_eq(a, b)),
(EntryKind::Dir { meta: a, .. }, EntryKind::LocalDir { meta: b })
| (EntryKind::LocalDir { meta: b }, EntryKind::Dir { meta: a, .. }) => {
Ok(*a != dirmeta_checksum(&to_dirmeta(b))?)
}
_ => Err(Error::InvalidFormat(
"a directory metadata comparison outside a pair of directories".into(),
)),
}
}
async fn read_list(repo: &Repo, side: &Side) -> Result<SideList> {
match side {
Side::Repo(dirtree) => Ok(SideList::Repo(repo_entries(
&repo.load_dirtree(dirtree).await?,
))),
Side::Local(dir) => {
let root = dir.root.clone();
let at = dir.at().to_path_buf();
let path = dir.path.clone();
let raw = ostrya_rt::unblock(move || {
let fd = rustix::fs::openat(
root.as_fd(),
&at,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)
.map_err(|err| path_error("opendir", &path, err))?;
snapshot_dir(fd.as_fd(), &path)
})
.await?;
Ok(SideList::Local(raw))
}
}
}
async fn shape(
side: &Side,
list: SideList,
wanted: &HashSet<OsString>,
options: &DiffOptions,
owner: Owner,
) -> Result<Vec<SideEntry>> {
let raw = match list {
SideList::Repo(entries) => return Ok(entries),
SideList::Local(raw) => raw,
};
let Side::Local(dir) = side else {
return Err(Error::InvalidFormat(
"a filesystem listing outside a directory side".into(),
));
};
let mut xattrs: HashMap<usize, Xattrs> = HashMap::new();
if !options.skip_xattrs {
let asked: Vec<(usize, OsString)> = raw
.iter()
.enumerate()
.filter(|(_, entry)| wanted.contains(entry.name.as_os_str()))
.map(|(at, entry)| (at, entry.name.clone()))
.collect();
if !asked.is_empty() {
let root = dir.root.clone();
let rel = dir.rel.clone();
let path = dir.path.clone();
xattrs =
ostrya_rt::unblock(move || read_xattrs(root.as_fd(), &rel, &path, asked)).await?;
}
}
Ok(raw
.into_iter()
.enumerate()
.map(|(at, entry)| {
local_entry(
entry,
xattrs.remove(&at).unwrap_or_else(Xattrs::empty),
owner,
)
})
.collect())
}
fn repo_entries(dirtree: &DirTree) -> Vec<SideEntry> {
let mut entries = Vec::with_capacity(dirtree.files.len() + dirtree.dirs.len());
for (name, checksum) in &dirtree.files {
entries.push(SideEntry {
name: OsString::from(name.clone()),
kind: EntryKind::Content(*checksum),
});
}
for (name, sub, meta) in &dirtree.dirs {
entries.push(SideEntry {
name: OsString::from(name.clone()),
kind: EntryKind::Dir {
meta: *meta,
dirtree: *sub,
},
});
}
entries
}
fn local_entry(raw: RawEntry, xattrs: Xattrs, owner: Owner) -> SideEntry {
let base = FileMeta {
uid: raw.uid,
gid: raw.gid,
mode: raw.mode,
xattrs,
};
let is_symlink = matches!(raw.kind, RawKind::Symlink(_));
let meta = adjust_meta(CommitModifierFlags::empty(), owner, base, is_symlink);
let kind = match raw.kind {
RawKind::Dir => EntryKind::LocalDir { meta },
RawKind::Regular => EntryKind::File {
meta,
size: raw.size,
},
RawKind::Symlink(target) => EntryKind::Symlink { meta, target },
RawKind::Other => EntryKind::Other(meta),
};
SideEntry {
name: raw.name,
kind,
}
}
fn dirmeta_checksum(meta: &DirMeta) -> Result<Checksum> {
Ok(Checksum::from_bytes(
Sha256::digest(meta.serialize()?).into(),
))
}
async fn content_checksum(side: &Side, name: &OsStr, kind: &EntryKind) -> Result<Option<Checksum>> {
match kind {
EntryKind::Content(checksum) => Ok(Some(*checksum)),
EntryKind::File { meta, .. } => Ok(Some(hash_local_file(side, name, meta).await?)),
EntryKind::Symlink { meta, target } => {
let Ok(target) = std::str::from_utf8(target) else {
return Ok(None);
};
let header = local_header(meta, target);
Ok(Some(ContentHasher::new(&header)?.finish()))
}
_ => Err(Error::InvalidFormat(
"a directory compared as a content object".into(),
)),
}
}
fn local_header(meta: &FileMeta, symlink_target: &str) -> FileHeader {
FileHeader {
uid: meta.uid,
gid: meta.gid,
mode: meta.mode,
symlink_target: symlink_target.to_owned(),
xattrs: meta.xattrs.clone(),
}
}
async fn hash_local_file(side: &Side, name: &OsStr, meta: &FileMeta) -> Result<Checksum> {
let Side::Local(dir) = side else {
return Err(Error::InvalidFormat(
"a filesystem entry outside a directory side".into(),
));
};
let mut hasher = ContentHasher::new(&local_header(meta, ""))?;
let root = dir.root.clone();
let at = dir.rel.join(name);
let path = dir.path.join(name);
let (rest, mut buf, filled) =
ostrya_rt::unblock(move || open_and_read(root.as_fd(), &at, &path)).await?;
hasher.update(&buf[..filled]);
if let Some(fd) = rest {
let mut file = RtFile::from(fd);
loop {
let read = file.read(&mut buf).await.map_err(Error::Io)?;
if read == 0 {
break;
}
hasher.update(&buf[..read]);
}
}
Ok(hasher.finish())
}
fn open_and_read(
root: BorrowedFd<'_>,
at: &Path,
path: &Path,
) -> Result<(Option<OwnedFd>, Vec<u8>, usize)> {
use std::io::Read;
let fd = rustix::fs::openat(
root,
at,
OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)
.map_err(|err| path_error("open", path, err))?;
let mut file = std::fs::File::from(fd);
let mut buf = vec![0u8; HASH_CHUNK];
let mut filled = 0;
while filled < HASH_CHUNK {
let read = file.read(&mut buf[filled..]).map_err(Error::Io)?;
if read == 0 {
return Ok((None, buf, filled));
}
filled += read;
}
Ok((Some(OwnedFd::from(file)), buf, filled))
}
fn descend(side: &Side, entry: &SideEntry) -> Result<Side> {
match side {
Side::Repo(_) => {
let EntryKind::Dir { dirtree, .. } = &entry.kind else {
return Err(Error::InvalidFormat(
"a committed directory with no directory tree object".into(),
));
};
Ok(Side::Repo(*dirtree))
}
Side::Local(dir) => Ok(Side::Local(dir.child(&entry.name))),
}
}
struct RawEntry {
name: OsString,
kind: RawKind,
uid: u32,
gid: u32,
mode: u32,
size: u64,
}
enum RawKind {
Dir,
Regular,
Symlink(Vec<u8>),
Other,
}
impl RawKind {
fn class(&self) -> Class {
match self {
RawKind::Dir => Class::Dir,
RawKind::Regular => Class::File,
RawKind::Symlink(_) => Class::Symlink,
RawKind::Other => Class::Other,
}
}
}
fn snapshot_dir(dir: BorrowedFd<'_>, path: &Path) -> Result<Vec<RawEntry>> {
let mut entries = Vec::new();
for entry in Dir::read_from(dir).map_err(|err| path_error("opendir", path, err))? {
let entry = entry.map_err(|err| path_error("readdir", path, err))?;
let raw = entry.file_name();
if raw == c"." || raw == c".." {
continue;
}
let name = OsStr::from_bytes(raw.to_bytes()).to_owned();
let stat = rustix::fs::statat(dir, raw, AtFlags::SYMLINK_NOFOLLOW)
.map_err(|err| path_error("stat", &path.join(&name), err))?;
let kind = match FileType::from_raw_mode(stat.st_mode) {
FileType::Directory => RawKind::Dir,
FileType::RegularFile => RawKind::Regular,
FileType::Symlink => RawKind::Symlink(
rustix::fs::readlinkat(dir, raw, Vec::new())
.map_err(|err| path_error("readlink", &path.join(&name), err))?
.into_bytes(),
),
_ => RawKind::Other,
};
entries.push(RawEntry {
name,
kind,
uid: stat.st_uid,
gid: stat.st_gid,
mode: stat.st_mode,
size: stat.st_size.max(0) as u64,
});
}
Ok(entries)
}
fn read_xattrs(
root: BorrowedFd<'_>,
rel: &Path,
path: &Path,
asked: Vec<(usize, OsString)>,
) -> Result<HashMap<usize, Xattrs>> {
let mut out = HashMap::with_capacity(asked.len());
for (at, name) in asked {
let xattrs = object::read_link_xattrs(root, rel.join(&name)).map_err(|err| match err {
Error::Io(io) => path_error_io("getxattr", &path.join(&name), &io),
other => other,
})?;
out.insert(at, xattrs);
}
Ok(out)
}
fn path_error(call: &str, path: &Path, err: Errno) -> Error {
path_error_io(call, path, &std::io::Error::from(err))
}
fn path_error_io(call: &str, path: &Path, err: &std::io::Error) -> Error {
let reason = err.to_string();
let reason = match reason.find(" (os error ") {
Some(cut) => &reason[..cut],
None => reason.as_str(),
};
Error::Io(std::io::Error::new(
err.kind(),
format!("{call}({}): {reason}", path.display()),
))
}
fn entries(change: DiffChange, paths: Vec<String>) -> impl Iterator<Item = DiffEntry> {
paths
.into_iter()
.map(move |path| DiffEntry { change, path })
}