use std::path::Path;
use ostrya_core::Checksum;
use crate::error::{Error, Result};
use crate::repo::Repo;
#[derive(Debug, Clone)]
pub struct RepoTree {
repo: Repo,
dirtree: Checksum,
dirmeta: Checksum,
}
#[derive(Debug, Clone)]
pub enum TreeEntry {
File {
name: String,
checksum: Checksum,
},
Dir {
name: String,
tree: RepoTree,
},
}
impl Repo {
pub async fn read_commit(&self, rev: &str) -> Result<(RepoTree, Checksum)> {
let checksum = self
.resolve_rev(rev, false)
.await?
.ok_or_else(|| Error::RefNotFound(rev.to_owned()))?;
let (commit, _) = self.load_commit(&checksum).await?;
let tree = RepoTree {
repo: self.clone(),
dirtree: commit.root_dirtree,
dirmeta: commit.root_dirmeta,
};
Ok((tree, checksum))
}
}
impl RepoTree {
pub(crate) fn from_parts(repo: Repo, dirtree: Checksum, dirmeta: Checksum) -> RepoTree {
RepoTree {
repo,
dirtree,
dirmeta,
}
}
pub fn dirtree_checksum(&self) -> &Checksum {
&self.dirtree
}
pub fn dirmeta_checksum(&self) -> &Checksum {
&self.dirmeta
}
pub async fn read_dir(&self) -> Result<Vec<TreeEntry>> {
let dirtree = self.repo.load_dirtree(&self.dirtree).await?;
let mut entries = Vec::with_capacity(dirtree.files.len() + dirtree.dirs.len());
for (name, checksum) in dirtree.files {
entries.push(TreeEntry::File { name, checksum });
}
for (name, tree, meta) in dirtree.dirs {
entries.push(TreeEntry::Dir {
name,
tree: RepoTree {
repo: self.repo.clone(),
dirtree: tree,
dirmeta: meta,
},
});
}
Ok(entries)
}
pub async fn lookup(&self, path: &Path) -> Result<Option<TreeEntry>> {
let components = normalize(path);
if components.is_empty() {
return Ok(None);
}
let mut current = self.clone();
for (index, component) in components.iter().enumerate() {
let is_last = index + 1 == components.len();
let dirtree = current.repo.load_dirtree(¤t.dirtree).await?;
if let Ok(pos) = dirtree
.dirs
.binary_search_by(|(name, _, _)| name.as_str().cmp(component))
{
let (name, tree, meta) = &dirtree.dirs[pos];
let child = RepoTree {
repo: current.repo.clone(),
dirtree: *tree,
dirmeta: *meta,
};
if is_last {
return Ok(Some(TreeEntry::Dir {
name: name.clone(),
tree: child,
}));
}
current = child;
continue;
}
if is_last
&& let Ok(pos) = dirtree
.files
.binary_search_by(|(name, _)| name.as_str().cmp(component))
{
let (name, checksum) = &dirtree.files[pos];
return Ok(Some(TreeEntry::File {
name: name.clone(),
checksum: *checksum,
}));
}
return Ok(None);
}
Ok(None)
}
}
fn normalize(path: &Path) -> Vec<String> {
use std::path::Component;
path.components()
.filter_map(|c| match c {
Component::Normal(part) => Some(part.to_string_lossy().into_owned()),
_ => None,
})
.collect()
}
const _: fn() = || {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<RepoTree>();
assert_send_sync::<TreeEntry>();
};