use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
#[cfg(feature = "receive")]
use std::sync::Arc;
use ostrya_core::{Checksum, Ref, RefPattern, RefSelector};
use rustix::fs::FileType;
use rustix::io::Errno;
use crate::access::{AccessRules, Namespace, ReadAccess};
use crate::archive::resolve_alias;
use crate::config::{remote, repo, valid_remote_name};
use crate::error::{Error, Result};
use crate::repo::Repo;
use crate::repo_fs::{FsError, FsResultExt, Publish, Reason, RepoDir, RepoLayout, TempLink};
use crate::summary::SelectionFloor;
use crate::transaction::Transaction;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CollectionRefEntry {
pub collection: String,
pub name: String,
pub commit: Checksum,
pub local: bool,
pub remote: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RefAlias {
pub name: Ref,
pub target: Option<Ref>,
pub body: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RefFileState {
Absent,
Commit(Checksum),
Alias,
NotARef(&'static str),
}
pub(crate) struct RefWrite {
target: Ref,
checksum: Option<Checksum>,
expected: Option<Option<Checksum>>,
}
pub(crate) struct ResolvedRef {
name: Ref,
relpath: String,
checksum: Option<Checksum>,
expected: Option<Option<Checksum>>,
}
impl Transaction {
pub fn set_ref(&self, r: &Ref, checksum: Option<&Checksum>) {
self.refs.lock().unwrap().push(RefWrite {
target: r.clone(),
checksum: checksum.copied(),
expected: None,
});
}
pub fn set_ref_expecting(&self, r: &Ref, expected: Option<&Checksum>, new: Option<&Checksum>) {
self.refs.lock().unwrap().push(RefWrite {
target: r.clone(),
checksum: new.copied(),
expected: Some(expected.copied()),
});
}
pub(crate) fn resolve_ref_queue(&self) -> Result<Vec<ResolvedRef>> {
let own = self.repo().config().collection_id();
let queue = std::mem::take(&mut *self.refs.lock().unwrap());
queue
.into_iter()
.map(|w| {
let relpath = ref_relpath(own, &w.target)?;
Ok(ResolvedRef {
name: w.target.canonical(own),
relpath,
checksum: w.checksum,
expected: w.expected,
})
})
.collect()
}
}
pub(crate) fn check_resolved_refs_blocking(root: &RepoDir, refs: &[ResolvedRef]) -> Result<()> {
let not_writable = |r: &ResolvedRef, reason: String| Error::RefNotWritable {
name: r.name.to_string(),
reason,
};
let mut removed: HashSet<&str> = HashSet::new();
for r in refs {
match r.expected {
None => match lstat_ref_state(root, &r.relpath)? {
Some(RefFileState::Alias) => {
return Err(not_writable(r, NAMES_AN_ALIAS.to_owned()));
}
Some(RefFileState::NotARef(reason))
if !(reason == PASSES_THROUGH_A_FILE
&& r.checksum.is_none()
&& parent_paths(&r.relpath).any(|p| removed.contains(p))) =>
{
return Err(not_writable(r, reason.to_owned()));
}
_ => {}
},
Some(expected) => {
let current = match ref_file_state(root, &r.relpath)? {
RefFileState::Absent => None,
RefFileState::Commit(c) => Some(c),
RefFileState::Alias => {
return Err(not_writable(r, NAMES_AN_ALIAS.to_owned()));
}
RefFileState::NotARef(reason) => {
return Err(not_writable(r, reason.to_owned()));
}
};
if current != expected {
return Err(Error::RefMismatch {
name: r.name.to_string(),
expected,
current,
});
}
}
}
if r.checksum.is_none() {
removed.insert(&r.relpath);
}
}
let entries: Vec<(&str, bool)> = refs
.iter()
.map(|r| (r.relpath.as_str(), r.checksum.is_some()))
.collect();
if let Some((outer, inner)) = nested_ref_paths(&entries) {
return Err(not_writable(
&refs[outer],
format!(
"names a directory of ref {} of the same transaction",
refs[inner].name
),
));
}
Ok(())
}
pub(crate) fn ref_changes_blocking(
root: &RepoDir,
refs: &[ResolvedRef],
) -> Vec<crate::pull::RefChange> {
let mut paths = Vec::with_capacity(refs.len());
let mut index: HashMap<&str, usize> = HashMap::with_capacity(refs.len());
for r in refs {
let at = *index.entry(r.relpath.as_str()).or_insert_with(|| {
paths.push((r, None, None));
paths.len() - 1
});
let path = &mut paths[at];
path.1 = r.checksum;
path.2 = path.2.or(r.expected);
}
paths
.into_iter()
.filter_map(|(first, new, expected)| {
let new = new?;
let old = expected.unwrap_or_else(|| {
root.read_capped(&first.relpath, REF_READ_CAP)
.ok()
.and_then(|bytes| parse_ref_content(&bytes).ok())
});
(old != Some(new)).then(|| crate::pull::RefChange {
name: first.name.clone(),
old,
new,
})
})
.collect()
}
fn parent_paths(path: &str) -> impl Iterator<Item = &str> {
std::iter::successors(Some(path), |p| p.rsplit_once('/').map(|(parent, _)| parent)).skip(1)
}
pub(crate) fn nested_ref_paths(entries: &[(&str, bool)]) -> Option<(usize, usize)> {
let mut paths: HashMap<&str, (usize, bool)> = HashMap::new();
for (i, &(path, writes)) in entries.iter().enumerate() {
paths.entry(path).or_insert((i, false)).1 |= writes;
}
entries
.iter()
.enumerate()
.find_map(|(inner, &(path, inner_writes))| {
parent_paths(path).find_map(|parent| match paths.get(parent) {
Some(&(outer, outer_writes)) if outer_writes || inner_writes => {
Some((outer, inner))
}
_ => None,
})
})
}
pub(crate) fn write_resolved_refs_blocking(
root: &RepoDir,
refs: &[ResolvedRef],
fsync: bool,
) -> Result<()> {
let mut dirs = Vec::new();
let written = refs.iter().try_for_each(|r| match r.checksum {
Some(checksum) => put_ref_file_blocking(root, &r.relpath, checksum, fsync, &mut dirs),
None => remove_ref_blocking(root, &r.relpath, fsync, &mut dirs),
});
if !fsync {
return written;
}
let synced = sync_ref_dirs(root, dirs);
written.and(synced)
}
const REF_READ_CAP: u64 = 4096;
impl Repo {
pub async fn resolve_rev(&self, rev: &str, allow_noent: bool) -> Result<Option<Checksum>> {
Ok(self
.resolve_rev_kind(rev, allow_noent)
.await?
.map(|(checksum, _)| checksum))
}
pub(crate) async fn resolve_rev_kind(
&self,
rev: &str,
allow_noent: bool,
) -> Result<Option<(Checksum, RevKind)>> {
let (base, generations) = split_ancestry(rev);
let Some((mut checksum, kind)) = self.resolve_base_rev(base, allow_noent).await? else {
return Ok(None);
};
for _ in 0..generations {
let (commit, _) = self.load_commit(&checksum).await?;
checksum = commit.parent.ok_or(Error::NoParentCommit(checksum))?;
}
Ok(Some((checksum, kind)))
}
async fn resolve_base_rev(
&self,
rev: &str,
allow_noent: bool,
) -> Result<Option<(Checksum, RevKind)>> {
if let Ok(checksum) = Checksum::from_hex_lower(rev) {
return Ok(Some((checksum, RevKind::Checksum)));
}
if is_abbreviated_checksum(rev) {
let repo = self.clone();
let prefix = rev.to_owned();
match ostrya_rt::unblock(move || match_abbreviated(repo.objects(), &prefix)).await? {
AbbrevMatch::One(checksum) => return Ok(Some((checksum, RevKind::Checksum))),
AbbrevMatch::Ambiguous => return Err(Error::AmbiguousRefspec(rev.to_owned())),
AbbrevMatch::None => {}
}
}
let r: Ref = rev.parse()?;
let relpath = ref_relpath(self.config().collection_id(), &r)?;
match self.resolve_named_tip(rev.to_owned(), relpath).await? {
Some(checksum) => Ok(Some((checksum, RevKind::Ref))),
None if allow_noent => Ok(None),
None => Err(Error::RefNotFound(rev.to_owned())),
}
}
pub async fn resolve_ref_tip(&self, r: &Ref) -> Result<Option<Checksum>> {
let relpath = ref_relpath(self.config().collection_id(), r)?;
self.resolve_named_tip(r.to_string(), relpath).await
}
pub(crate) async fn resolve_relpath_tip(&self, relpath: String) -> Result<Option<Checksum>> {
self.resolve_named_tip(relpath.clone(), relpath).await
}
async fn resolve_named_tip(&self, name: String, relpath: String) -> Result<Option<Checksum>> {
let repo = self.clone();
ostrya_rt::unblock(move || read_ref_tip(repo.root_dir(), &name, &relpath)).await
}
pub(crate) fn resolve_relpath_tip_blocking(&self, relpath: &str) -> Result<Option<Checksum>> {
read_ref_tip(self.root_dir(), relpath, relpath)
}
#[cfg(feature = "receive")]
pub(crate) async fn resolve_relpath_tips(
&self,
relpaths: Arc<[String]>,
) -> Result<Vec<Option<Checksum>>> {
let repo = self.clone();
ostrya_rt::unblock(move || {
let root = repo.root_dir();
relpaths
.iter()
.map(|p| {
if let Some(RefFileState::Absent | RefFileState::NotARef(_)) =
lstat_ref_state(root, p)?
{
return Ok(None);
}
match read_ref_tip(root, p, p) {
Err(Error::NotARef { .. }) => Ok(None),
other => other,
}
})
.collect()
})
.await
}
#[cfg(feature = "receive")]
#[allow(clippy::type_complexity)]
pub(crate) async fn read_ref_states(
&self,
relpaths: Arc<[String]>,
tip: Option<&str>,
) -> Result<(Vec<RefFileState>, Option<Result<Option<Checksum>>>)> {
let tip = tip.map(|refspec| refspec_to_relpath(refspec).map(|p| (refspec.to_owned(), p)));
let repo = self.clone();
ostrya_rt::unblock(move || {
let root = repo.root_dir();
let states = relpaths
.iter()
.map(|p| ref_file_state(root, p))
.collect::<Result<Vec<_>>>()?;
let tip = tip.map(|named| {
let (name, relpath) = named?;
read_ref_tip(root, &name, &relpath)
});
Ok((states, tip))
})
.await
}
pub async fn list_refs(&self, prefix: Option<&str>) -> Result<Vec<(String, Checksum)>> {
let repo = self.clone();
let mut refs =
ostrya_rt::unblock(move || collect_heads(&repo, open_refs(&repo)?.as_ref(), &|_| true))
.await?;
if let Some(prefix) = prefix {
refs.retain(|(name, _)| ref_prefixes(name).any(|part| part == prefix));
}
refs.sort_by(|a, b| a.0.cmp(&b.0));
Ok(refs)
}
pub(crate) async fn list_head_names(&self) -> Result<Vec<String>> {
let repo = self.clone();
let mut names =
ostrya_rt::unblock(move || collect_head_names(&repo, open_refs(&repo)?.as_ref()))
.await?;
names.sort();
Ok(names)
}
pub async fn list_refs_where(
&self,
keep: impl Fn(&Ref) -> bool + Send + 'static,
) -> Result<Vec<(Ref, Checksum)>> {
let repo = self.clone();
let own = self.config().collection_id().map(str::to_owned);
ostrya_rt::unblock(move || {
let refs = open_refs(&repo)?;
let mut heads = collect_heads(&repo, refs.as_ref(), &|name| keep(&Ref::local(name)))?;
heads.sort_by(|a, b| a.0.cmp(&b.0));
let skip = |path: &str| {
!path.contains('/')
&& (Some(path) == own.as_deref() || !ostrya_core::is_valid_collection_id(path))
};
let keep_mirror = |path: &str| {
path.split_once('/')
.is_some_and(|(id, name)| keep(&Ref::collection(id, name)))
};
let mut mirrors = collect_mirrors(&repo, refs.as_ref(), &skip, &keep_mirror)?;
mirrors.sort_unstable_by(|a, b| (&a.0, &a.1).cmp(&(&b.0, &b.1)));
let mut out = Vec::with_capacity(heads.len() + mirrors.len());
out.extend(heads.into_iter().map(|(name, c)| (Ref::local(name), c)));
out.extend(
mirrors
.into_iter()
.map(|(id, name, c)| (Ref::collection(id, name), c)),
);
Ok(out)
})
.await
}
pub(crate) async fn select_refs(
&self,
refs: &RefSelector,
collections: Option<&RefSelector>,
access: &ReadAccess,
cap: Option<u64>,
) -> Result<RefSelection> {
let repo = self.clone();
let refs = refs.clone();
let collections = collections.cloned();
let access = access.clone();
ostrya_rt::unblock(move || {
let mut floor = SelectionFloor::new(cap);
let mut selection = RefSelection::default();
let reads_local = !selects_no_name(&refs) && access.reads_local_refs();
let refs_dir = if reads_local || collections.is_some() {
open_refs(&repo)?
} else {
None
};
collect_local_selected(
&repo,
refs_dir.as_ref(),
&refs,
&access,
&mut floor,
&mut selection,
)?;
if let Some(collections) = &collections
&& let Some(mirrors) = open_top_in(refs_dir.as_ref(), MIRRORS_DIR)?
{
collect_collections_selected(
&repo,
&mirrors,
collections,
&access,
&mut floor,
&mut selection,
)?;
}
Ok(selection)
})
.await
}
pub async fn list_remote_refs(&self) -> Result<Vec<(String, Checksum)>> {
let repo = self.clone();
let mut refs = ostrya_rt::unblock(move || collect_remotes(&repo)).await?;
refs.sort_by(|a, b| a.0.cmp(&b.0));
Ok(refs)
}
pub async fn list_mirror_refs(&self) -> Result<Vec<(String, String, Checksum)>> {
let repo = self.clone();
ostrya_rt::unblock(move || {
collect_mirrors(&repo, open_refs(&repo)?.as_ref(), &|_| false, &|_| true)
})
.await
}
pub async fn list_collection_refs(&self) -> Result<Vec<CollectionRefEntry>> {
let config = self.config();
let own = config.collection_id();
let mut remotes = BTreeMap::new();
for section in config.sections::<remote::Group>() {
let name = section.name();
if !valid_remote_name(name) {
continue;
}
if let Ok(Some(id)) = section.get::<remote::CollectionId>()
&& ostrya_core::is_valid_collection_id(&id)
&& Some(id.as_str()) != own
{
remotes.insert(name.to_owned(), id);
}
}
let heads = match own {
Some(_) => self.list_refs(None).await?,
None => Vec::new(),
};
let mut all = self.collection_refs_over(&heads, own).await?;
if remotes.is_empty() {
return Ok(all);
}
let repo = self.clone();
let refs = ostrya_rt::unblock(move || collect_remote_collections(&repo, &remotes)).await?;
all.extend(
refs.into_iter()
.map(|(remote, collection, name, commit)| CollectionRefEntry {
collection,
name,
commit,
local: false,
remote: Some(remote),
}),
);
all.sort_by(|a, b| (&a.collection, &a.name).cmp(&(&b.collection, &b.name)));
all.dedup_by(|a, b| a.collection == b.collection && a.name == b.name);
Ok(all)
}
pub async fn list_collection_refs_in(
&self,
collection_id: &str,
refs: &RefSelector,
) -> Result<Vec<(String, Checksum)>> {
if !ostrya_core::is_valid_collection_id(collection_id) {
return Err(Error::InvalidRefspec(collection_id.to_owned()));
}
if selects_no_name(refs) {
return Ok(Vec::new());
}
let own = self.config().collection_id();
if own == Some(collection_id) {
let selection = self
.select_refs(refs, None, self.implicit_reads(), None)
.await?;
return Ok(selection.local);
}
let mut entries: Vec<String> = refs
.positive()
.iter()
.map(|pattern| format!("{collection_id}/{}", pattern.as_str()))
.collect();
if entries.is_empty() {
entries.push(format!("{collection_id}/**"));
}
entries.extend(
refs.negative()
.iter()
.map(|pattern| format!("!{collection_id}/{}", pattern.as_str())),
);
let collections = RefSelector::parse(entries.iter().map(String::as_str))?;
let repo = self.clone();
let id = collection_id.to_owned();
ostrya_rt::unblock(move || {
let everyone = repo.implicit_reads();
let Some(rules) = everyone.collection_rules(&id) else {
return Ok(Vec::new());
};
let Some(mirrors) = open_ref_top(&repo, MIRRORS_DIR)? else {
return Ok(Vec::new());
};
let mut floor = SelectionFloor::new(None);
let mut selection = RefSelection::default();
collect_collection_selected(
&repo,
&mirrors,
&CollectionWalk::new(&collections),
&id,
rules,
everyone,
&mut floor,
&mut selection,
)?;
Ok(selection.collections.remove(&id).unwrap_or_default())
})
.await
}
pub(crate) async fn collection_refs_over(
&self,
heads: &[(String, Checksum)],
skip: Option<&str>,
) -> Result<Vec<CollectionRefEntry>> {
let mut all = Vec::new();
if let Some(collection) = self.config().collection_id().map(str::to_owned) {
for (name, commit) in heads {
all.push(CollectionRefEntry {
collection: collection.clone(),
name: name.clone(),
commit: *commit,
local: true,
remote: None,
});
}
}
let repo = self.clone();
let skip = skip.map(str::to_owned);
let mirrors = ostrya_rt::unblock(move || {
let refs = open_refs(&repo)?;
collect_mirrors(
&repo,
refs.as_ref(),
&|path| Some(path) == skip.as_deref(),
&|_| true,
)
})
.await?;
for (collection, name, commit) in mirrors {
all.push(CollectionRefEntry {
collection,
name,
commit,
local: false,
remote: None,
});
}
all.sort_by(|a, b| (&a.collection, &a.name).cmp(&(&b.collection, &b.name)));
Ok(all)
}
pub async fn list_ref_aliases(&self) -> Result<Vec<RefAlias>> {
let repo = self.clone();
let mut aliases = ostrya_rt::unblock(move || collect_aliases(&repo)).await?;
aliases.sort_by_cached_key(|alias| alias.name.to_string());
Ok(aliases)
}
pub async fn check_refs_path(&self, relpath: &str) -> Result<()> {
let path = format!("refs/{relpath}");
let repo = self.clone();
ostrya_rt::unblock(move || match repo.root_dir().exists(&path) {
Err(FsError::Invalid {
reason: Reason::NotDirectory,
..
}) => Err(Error::Io(Errno::NOTDIR.into())),
Err(
e @ FsError::Invalid {
reason: Reason::Symlink,
..
},
) => Err(e.into()),
_ => Ok(()),
})
.await
}
pub async fn ref_path_has_entry(&self, r: &Ref) -> Result<bool> {
let relpath = ref_relpath(self.config().collection_id(), r)?;
let repo = self.clone();
ostrya_rt::unblock(move || {
Ok(!matches!(
lstat_ref_state(repo.root_dir(), &relpath)?,
Some(RefFileState::Absent)
))
})
.await
}
pub async fn set_ref_immediate(&self, r: &Ref, checksum: Option<&Checksum>) -> Result<()> {
let own = self.config().collection_id();
let relpath = ref_relpath(own, r)?;
let name = r.clone().canonical(own).to_string();
self.write_ref_relpath(name, relpath, checksum).await
}
pub async fn remove_refs_immediate(&self, refs: &[Ref]) -> Result<()> {
if refs.is_empty() {
return Ok(());
}
let own = self.config().collection_id();
let resolved = refs
.iter()
.map(|r| {
Ok(ResolvedRef {
relpath: ref_relpath(own, r)?,
name: r.clone().canonical(own),
checksum: None,
expected: None,
})
})
.collect::<Result<Vec<_>>>()?;
let fsync = self.config().get::<repo::Fsync>()?;
self.write_locked(move |repo| {
let root = repo.root_dir();
check_resolved_refs_blocking(root, &resolved)?;
let mut dirs = Vec::new();
let removed = resolved
.iter()
.try_for_each(|r| remove_ref_blocking(root, &r.relpath, fsync, &mut dirs));
removed.and(sync_ref_dirs(root, dirs))
})
.await
}
async fn write_ref_relpath(
&self,
name: String,
relpath: String,
checksum: Option<&Checksum>,
) -> Result<()> {
let fsync = self.config().get::<repo::Fsync>()?;
let checksum = checksum.copied();
self.write_locked(move |repo| {
write_ref_blocking(repo.root_dir(), &name, &relpath, checksum, fsync)
})
.await
}
pub async fn set_ref_alias_immediate(&self, alias: &Ref, target: &Ref) -> Result<()> {
let fsync = self.config().get::<repo::Fsync>()?;
let own = self.config().collection_id();
let relpath = ref_relpath(own, alias)?;
let target = ref_relpath(own, target)?;
let name = alias.clone().canonical(own).to_string();
self.write_locked(move |repo| {
write_alias_blocking(repo.root_dir(), &name, &relpath, &target, fsync)
})
.await
}
pub async fn remove_ref_alias_immediate(&self, alias: &Ref) -> Result<()> {
let fsync = self.config().get::<repo::Fsync>()?;
let own = self.config().collection_id();
let relpath = ref_relpath(own, alias)?;
let name = alias.clone().canonical(own).to_string();
self.write_locked(move |repo| {
let root = repo.root_dir();
let mut dirs = Vec::new();
let removed = remove_alias_blocking(root, &name, &relpath, fsync, &mut dirs);
removed.and(sync_ref_dirs(root, dirs))
})
.await
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RevKind {
Checksum,
Ref,
}
fn split_ancestry(rev: &str) -> (&str, usize) {
let base = rev.trim_end_matches('^');
(base, rev.len() - base.len())
}
fn is_abbreviated_checksum(rev: &str) -> bool {
!rev.is_empty()
&& rev.len() < 64
&& rev
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
enum AbbrevMatch {
None,
One(Checksum),
Ambiguous,
}
fn match_abbreviated(objects: &RepoDir, prefix: &str) -> Result<AbbrevMatch> {
let mut found: Option<Checksum> = None;
if prefix.len() >= 2 {
let (fanout, within) = prefix.split_at(2);
if scan_fanout(objects, fanout, within, &mut found)? {
return Ok(AbbrevMatch::Ambiguous);
}
} else {
for entry in objects.list()? {
let Ok(fanout) = std::str::from_utf8(&entry.name) else {
continue;
};
if fanout.len() != 2 || !fanout.bytes().all(|b| b.is_ascii_hexdigit()) {
continue;
}
if !fanout.starts_with(prefix) {
continue;
}
if scan_fanout(objects, fanout, "", &mut found)? {
return Ok(AbbrevMatch::Ambiguous);
}
}
}
Ok(match found {
Some(checksum) => AbbrevMatch::One(checksum),
None => AbbrevMatch::None,
})
}
fn scan_fanout(
objects: &RepoDir,
fanout: &str,
within: &str,
found: &mut Option<Checksum>,
) -> Result<bool> {
let Some(dir) = objects.open_dir(fanout).optional()? else {
return Ok(false);
};
for entry in dir.list()? {
let Some(checksum) = std::str::from_utf8(&entry.name)
.ok()
.and_then(|entry| matching_commit(fanout, entry, within))
else {
continue;
};
if found.replace(checksum).is_some() {
return Ok(true);
}
}
Ok(false)
}
fn matching_commit(fanout: &str, entry: &str, within: &str) -> Option<Checksum> {
let (rest, ext) = entry.rsplit_once('.')?;
if ext != "commit" || rest.len() != 62 || !rest.starts_with(within) {
return None;
}
Checksum::from_hex_lower(&format!("{fanout}{rest}")).ok()
}
pub(crate) fn relative_link(from_relpath: &str, to_relpath: &str) -> String {
let from: Vec<&str> = from_relpath.split('/').collect();
let to: Vec<&str> = to_relpath.split('/').collect();
let from_dir = &from[..from.len() - 1];
let common = from_dir
.iter()
.zip(&to[..to.len() - 1])
.take_while(|(a, b)| a == b)
.count();
let mut parts = vec![".."; from_dir.len() - common];
parts.extend_from_slice(&to[common..]);
parts.join("/")
}
fn collect_heads(
repo: &Repo,
refs: Option<&RepoDir>,
keep: &dyn Fn(&str) -> bool,
) -> Result<Vec<(String, Checksum)>> {
let Some(heads) = open_top_in(refs, HEADS_DIR)? else {
return Ok(Vec::new());
};
let mut out = Vec::new();
walk_ref_dir(&heads, "", &mut |entry| {
if !keep(entry.path) {
return Ok(());
}
if let Some((bytes, _)) = read_listed_ref(repo.root_dir(), HEADS_DIR, &entry, None)? {
out.push((entry.path.to_owned(), parse_ref_content(&bytes)?));
}
Ok(())
})?;
Ok(out)
}
fn collect_head_names(repo: &Repo, refs: Option<&RepoDir>) -> Result<Vec<String>> {
let Some(heads) = open_top_in(refs, HEADS_DIR)? else {
return Ok(Vec::new());
};
let mut out = Vec::new();
walk_ref_dir(&heads, "", &mut |entry| {
let holds_ref = match entry.file_type {
FileType::RegularFile => true,
FileType::Symlink => match read_alias_body(&entry)? {
Some(body) => {
let link_dir = match entry.path.rsplit_once('/') {
Some((dir, _)) => format!("{HEADS_DIR}/{dir}"),
None => HEADS_DIR.to_owned(),
};
match resolve_alias(&link_dir, body.as_bytes()) {
Some(target) => alias_target_is_ref(repo.root_dir(), &target)?,
None => false,
}
}
None => false,
},
_ => false,
};
if holds_ref {
out.push(entry.path.to_owned());
}
Ok(())
})?;
Ok(out)
}
pub(crate) const HEADS_DIR: &str = "refs/heads";
pub(crate) const MIRRORS_DIR: &str = "refs/mirrors";
pub(crate) const REMOTES_DIR: &str = "refs/remotes";
#[derive(Default)]
pub(crate) struct RefSelection {
pub(crate) local: Vec<(String, Checksum)>,
pub(crate) collections: BTreeMap<String, Vec<(String, Checksum)>>,
pub(crate) invalid_dirs: Vec<String>,
pub(crate) local_aliases: HashMap<String, String>,
pub(crate) collection_aliases: BTreeMap<String, HashMap<String, String>>,
}
impl RefSelection {
pub(crate) fn readable(&self, access: &ReadAccess) -> RefSelection {
let mut out = RefSelection::default();
if access.reads_local_refs() {
for (name, commit) in &self.local {
if !access.can_read(&Namespace::Local, name) {
continue;
}
if let Some(target) = self.local_aliases.get(name)
&& !access.can_read_path(target)
{
continue;
}
out.local.push((name.clone(), *commit));
}
}
for (id, refs) in &self.collections {
let Some(rules) = access.collection_rules(id) else {
continue;
};
if !rules.gives_read() {
continue;
}
let aliases = self.collection_aliases.get(id);
let names: Vec<(String, Checksum)> = refs
.iter()
.filter(|(name, _)| {
crate::access::reads(rules, name)
&& aliases
.and_then(|aliases| aliases.get(name))
.is_none_or(|target| access.can_read_path(target))
})
.cloned()
.collect();
if !names.is_empty() {
out.collections.insert(id.clone(), names);
}
}
out
}
}
fn collect_local_selected(
repo: &Repo,
refs: Option<&RepoDir>,
selector: &RefSelector,
access: &ReadAccess,
floor: &mut SelectionFloor,
selection: &mut RefSelection,
) -> Result<()> {
if selects_no_name(selector) || !access.reads_local_refs() {
return Ok(());
}
let mut local = BTreeMap::new();
if let Some(heads) = open_top_in(refs, HEADS_DIR)? {
collect_dir_selected(
repo, HEADS_DIR, &heads, selector, access, floor, &mut local, selection,
)?;
}
selection.local = local.into_iter().collect();
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn collect_dir_selected(
repo: &Repo,
root: &str,
dir: &RepoDir,
selector: &RefSelector,
access: &ReadAccess,
floor: &mut SelectionFloor,
out: &mut BTreeMap<String, Checksum>,
selection: &mut RefSelection,
) -> Result<()> {
let mut take = |entry: RefEntry<'_>| -> Result<()> {
if out.contains_key(entry.path)
|| selector.negative().iter().any(|p| p.matches(entry.path))
|| !access.can_read(&Namespace::Local, entry.path)
{
return Ok(());
}
if let Some((bytes, target)) = read_listed_ref(repo.root_dir(), root, &entry, Some(access))?
{
let commit = parse_ref_content(&bytes)?;
floor.add_ref(entry.path)?;
out.insert(entry.path.to_owned(), commit);
if let Some(target) = target {
selection
.local_aliases
.insert(entry.path.to_owned(), target);
}
}
Ok(())
};
match access.local_rules() {
Some(rules) if selector.positive().is_empty() => {
let covers = negative_covers(selector);
walk_readable(dir, rules, &|dir| dir_is_covered(&covers, dir), &mut take)
}
_ => walk_selected(dir, selector, &mut take),
}
}
fn collect_collections_selected(
repo: &Repo,
mirrors: &RepoDir,
selector: &RefSelector,
access: &ReadAccess,
floor: &mut SelectionFloor,
selection: &mut RefSelection,
) -> Result<()> {
let own = repo.config().collection_id();
let walk = CollectionWalk::new(selector);
let mut readable = BTreeMap::new();
for entry in mirrors.list()? {
let Ok(name) = String::from_utf8(entry.name) else {
continue;
};
refuse_top_symlink(MIRRORS_DIR, &name, entry.file_type)?;
if Some(name.as_str()) == own || entry.file_type != FileType::Directory {
continue;
}
if !ostrya_core::is_valid_collection_id(&name) {
selection.invalid_dirs.push(name);
continue;
}
if !walk.reaches(&name) {
continue;
}
if let Some(rules) = access.collection_rules(&name)
&& rules.gives_read()
{
readable.insert(name, rules);
}
}
selection.invalid_dirs.sort();
selection.invalid_dirs.dedup();
for (id, rules) in &readable {
collect_collection_selected(repo, mirrors, &walk, id, rules, access, floor, selection)?;
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn collect_collection_selected(
repo: &Repo,
mirrors: &RepoDir,
walk: &CollectionWalk<'_>,
id: &str,
rules: &AccessRules,
access: &ReadAccess,
floor: &mut SelectionFloor,
selection: &mut RefSelection,
) -> Result<()> {
let mut names: BTreeMap<String, Checksum> = BTreeMap::new();
let mut aliases = HashMap::new();
let mut take = |entry: RefEntry<'_>| -> Result<()> {
let Some((_, name)) = entry.path.split_once('/') else {
return Ok(());
};
if names.contains_key(name)
|| walk
.selector
.negative()
.iter()
.any(|p| p.matches(entry.path))
|| !crate::access::reads(rules, name)
{
return Ok(());
}
if let Some((bytes, target)) =
read_listed_ref(repo.root_dir(), MIRRORS_DIR, &entry, Some(access))?
{
let commit = parse_ref_content(&bytes)?;
if names.is_empty() {
floor.add_collection(id)?;
}
floor.add_ref(name)?;
names.insert(name.to_owned(), commit);
if let Some(target) = target {
aliases.insert(name.to_owned(), target);
}
}
Ok(())
};
walk.walk(mirrors, id, rules, &mut take)?;
if !aliases.is_empty() {
selection.collection_aliases.insert(id.to_owned(), aliases);
}
if !names.is_empty() {
selection
.collections
.insert(id.to_owned(), names.into_iter().collect());
}
Ok(())
}
fn walk_selected(
dir: &RepoDir,
selector: &RefSelector,
take: &mut dyn FnMut(RefEntry<'_>) -> Result<()>,
) -> Result<()> {
let covers = negative_covers(selector);
let skip = |dir: &str| dir_is_covered(&covers, dir);
if selector.positive().is_empty() {
walk_ref_dir_skipping(dir, "", &skip, &mut &mut *take)?;
} else {
let split: Vec<(&RefPattern, Vec<&str>)> = uncovered_patterns(selector.positive())
.into_iter()
.map(|pattern| (pattern, pattern.as_str().split('/').collect()))
.collect();
let patterns: Vec<(&RefPattern, &[&str])> = split
.iter()
.map(|(pattern, parts)| (*pattern, parts.as_slice()))
.collect();
walk_ref_patterns(dir, "", &patterns, &skip, take)?;
}
Ok(())
}
fn walk_readable(
dir: &RepoDir,
rules: &AccessRules,
skip: &dyn Fn(&str) -> bool,
take: &mut dyn FnMut(RefEntry<'_>) -> Result<()>,
) -> Result<()> {
let positive: Vec<RefPattern> = rules
.allow
.iter()
.filter(|item| item.gives_read())
.map(|item| item.pattern.clone())
.collect();
let covers: Vec<Vec<&str>> = rules
.deny
.iter()
.filter_map(|pattern| covering_lead(pattern.as_str()))
.collect();
let skip = |dir: &str| skip(dir) || dir_is_covered(&covers, dir);
for pattern in uncovered_patterns(&positive) {
let parts: Vec<&str> = pattern.as_str().split('/').collect();
walk_ref_pattern(dir, "", &parts, pattern, &skip, take)?;
}
Ok(())
}
struct CollectionWalk<'a> {
selector: &'a RefSelector,
covers: Vec<Vec<&'a str>>,
patterns: Vec<(&'a RefPattern, Vec<&'a str>)>,
literal_ids: Option<BTreeSet<&'a str>>,
}
impl<'a> CollectionWalk<'a> {
fn new(selector: &'a RefSelector) -> CollectionWalk<'a> {
let patterns: Vec<(&RefPattern, Vec<&str>)> = uncovered_patterns(selector.positive())
.into_iter()
.map(|pattern| (pattern, pattern.as_str().split('/').collect()))
.collect();
let literal = patterns
.iter()
.all(|(_, parts)| parts[0] != "*" && parts[0] != "**");
let literal_ids = literal.then(|| {
patterns
.iter()
.filter(|(_, parts)| parts.len() > 1)
.map(|(_, parts)| parts[0])
.collect()
});
CollectionWalk {
selector,
covers: negative_covers(selector),
patterns,
literal_ids,
}
}
fn reaches(&self, id: &str) -> bool {
if dir_is_covered(&self.covers, id) {
return false;
}
if self.selector.positive().is_empty() {
return true;
}
match &self.literal_ids {
Some(ids) => ids.contains(id),
None => self
.patterns
.iter()
.any(|(_, parts)| first_part_reaches(parts, id)),
}
}
fn walk(
&self,
mirrors: &RepoDir,
id: &str,
rules: &AccessRules,
take: &mut dyn FnMut(RefEntry<'_>) -> Result<()>,
) -> Result<()> {
let skip = |dir: &str| dir_is_covered(&self.covers, dir);
let Some(sub) = mirrors.open_dir(id).optional_dir()? else {
return Ok(());
};
if self.selector.positive().is_empty() {
let skip = |dir: &str| skip(&format!("{id}/{dir}"));
return walk_readable(&sub, rules, &skip, &mut |entry| {
let path = format!("{id}/{}", entry.path);
take(RefEntry {
path: &path,
..entry
})
});
}
let mut below: Vec<(&RefPattern, &[&str])> = Vec::new();
for (pattern, parts) in &self.patterns {
if !first_part_reaches(parts, id) {
continue;
}
match parts.split_first() {
Some((&"**", _)) => {
walk_ref_dir_skipping(&sub, id, &skip, &mut |entry| {
if pattern.matches(entry.path) {
take(entry)
} else {
Ok(())
}
})?;
}
Some((_, rest)) => below.push((*pattern, rest)),
None => {}
}
}
walk_ref_patterns(&sub, id, &below, &skip, take)
}
}
fn first_part_reaches(parts: &[&str], id: &str) -> bool {
match parts.split_first() {
Some((&"**", _)) => true,
Some((first, rest)) => !rest.is_empty() && (*first == "*" || *first == id),
None => false,
}
}
fn selects_no_name(selector: &RefSelector) -> bool {
selector.negative().iter().any(|p| p.as_str() == "**")
}
fn negative_covers(selector: &RefSelector) -> Vec<Vec<&str>> {
selector
.negative()
.iter()
.filter_map(|pattern| covering_lead(pattern.as_str()))
.collect()
}
pub(crate) fn read_listed_ref(
root: &RepoDir,
top: &str,
entry: &RefEntry<'_>,
access: Option<&ReadAccess>,
) -> Result<Option<(Vec<u8>, Option<String>)>> {
if !entry.can_hold_ref() {
return Ok(None);
}
let symlink = entry.file_type == FileType::Symlink;
let body = match read_ref_entry(entry.dir, entry.name, symlink) {
Ok(RefEntryRead::File(bytes)) => return Ok(Some((bytes, None))),
Ok(RefEntryRead::Alias(body)) => body,
Err(
FsError::Absent { .. }
| FsError::Invalid {
reason: Reason::NotRegular(_) | Reason::NotDirectory,
..
},
) => return Ok(None),
Err(e) => return Err(e.into()),
};
let link_dir = match entry.path.rsplit_once('/') {
Some((dir, _)) => format!("{top}/{dir}"),
None => top.to_owned(),
};
let Some(target) = resolve_alias(&link_dir, &body) else {
return Ok(None);
};
if access.is_some_and(|access| !access.can_read_path(&target)) {
return Ok(None);
}
match read_alias_target(root, &target)? {
AliasTarget::Ref(bytes) => Ok(Some((bytes, Some(target)))),
AliasTarget::Absent | AliasTarget::Broken(_) => Ok(None),
}
}
fn collect_remotes(repo: &Repo) -> Result<Vec<(String, Checksum)>> {
let Some(remotes) = open_ref_top(repo, REMOTES_DIR)? else {
return Ok(Vec::new());
};
let mut out = Vec::new();
walk_ref_dir(&remotes, "", &mut |entry| {
refuse_top_symlink(REMOTES_DIR, entry.path, entry.file_type)?;
let Some((bytes, _)) = read_listed_ref(repo.root_dir(), REMOTES_DIR, &entry, None)? else {
return Ok(());
};
let checksum = parse_ref_content(&bytes)?;
if let Some((remote, ref_name)) = entry.path.split_once('/') {
out.push((format!("{remote}:{ref_name}"), checksum));
}
Ok(())
})?;
Ok(out)
}
fn collect_remote_collections(
repo: &Repo,
remotes: &BTreeMap<String, String>,
) -> Result<Vec<(String, String, String, Checksum)>> {
let Some(dir) = open_ref_top(repo, REMOTES_DIR)? else {
return Ok(Vec::new());
};
let mut out = Vec::new();
for (remote, collection) in remotes {
let Some(sub) = dir.open_dir(remote).optional_dir()? else {
continue;
};
let top = format!("{REMOTES_DIR}/{remote}");
walk_ref_dir(&sub, "", &mut |entry| {
if let Some((bytes, _)) = read_listed_ref(repo.root_dir(), &top, &entry, None)? {
let checksum = parse_ref_content(&bytes)?;
out.push((
remote.clone(),
collection.clone(),
entry.path.to_owned(),
checksum,
));
}
Ok(())
})?;
}
Ok(out)
}
fn collect_aliases(repo: &Repo) -> Result<Vec<RefAlias>> {
let own = repo.config().collection_id();
let mut out = Vec::new();
let refs = open_refs(repo)?;
let alias = |top: &str, entry: &RefEntry<'_>, name: Ref| -> Result<Option<RefAlias>> {
let Some(body) = read_alias_body(entry)? else {
return Ok(None);
};
let link_dir = match entry.path.rsplit_once('/') {
Some((dir, _)) => format!("{top}/{dir}"),
None => top.to_owned(),
};
let target = resolve_alias(&link_dir, body.as_bytes())
.and_then(|path| listed_alias_target(own, &path));
Ok(Some(RefAlias { name, target, body }))
};
if let Some(heads) = open_top_in(refs.as_ref(), HEADS_DIR)? {
walk_ref_dir(&heads, "", &mut |entry| {
if entry.file_type != FileType::Symlink {
return Ok(());
}
let name = Ref::local(entry.path);
out.extend(alias(HEADS_DIR, &entry, name)?);
Ok(())
})?;
}
if let Some(remotes) = open_top_in(refs.as_ref(), REMOTES_DIR)? {
walk_ref_dir(&remotes, "", &mut |entry| {
refuse_top_symlink(REMOTES_DIR, entry.path, entry.file_type)?;
if entry.file_type != FileType::Symlink {
return Ok(());
}
if let Some((remote, ref_name)) = entry.path.split_once('/') {
let name = Ref::remote(remote, ref_name);
out.extend(alias(REMOTES_DIR, &entry, name)?);
}
Ok(())
})?;
}
if let Some(mirrors) = open_top_in(refs.as_ref(), MIRRORS_DIR)? {
let skip = |path: &str| !path.contains('/') && Some(path) == own;
walk_ref_dir_skipping(&mirrors, "", &skip, &mut |entry| {
refuse_top_symlink(MIRRORS_DIR, entry.path, entry.file_type)?;
if entry.file_type != FileType::Symlink {
return Ok(());
}
if let Some((id, ref_name)) = entry.path.split_once('/') {
let name = Ref::collection(id, ref_name);
out.extend(alias(MIRRORS_DIR, &entry, name)?);
}
Ok(())
})?;
}
Ok(out)
}
fn listed_alias_target(own: Option<&str>, path: &str) -> Option<Ref> {
let below = path.strip_prefix("refs/")?;
let r = if let Some(name) = below.strip_prefix("heads/") {
Ref::local(name)
} else if let Some(rest) = below.strip_prefix("remotes/") {
let (remote, name) = rest.split_once('/')?;
Ref::remote(remote, name)
} else {
let rest = below.strip_prefix("mirrors/")?;
let (id, name) = rest.split_once('/')?;
if Some(id) == own {
return None;
}
Ref::collection(id, name)
};
r.validate().is_ok().then_some(r)
}
pub(crate) fn open_ref_top(repo: &Repo, top: &str) -> Result<Option<RepoDir>> {
open_top_in(open_refs(repo)?.as_ref(), top)
}
pub(crate) fn open_refs(repo: &Repo) -> Result<Option<RepoDir>> {
Ok(repo.root_dir().open_layout(RepoLayout::Refs).optional()?)
}
pub(crate) fn open_top_in(refs: Option<&RepoDir>, top: &str) -> Result<Option<RepoDir>> {
let Some(refs) = refs else {
return Ok(None);
};
let name = top.strip_prefix("refs/").unwrap_or(top);
Ok(refs.open_dir(name).optional()?)
}
pub(crate) fn refuse_top_symlink(top: &str, path: &str, file_type: FileType) -> Result<()> {
if file_type == FileType::Symlink && !path.contains('/') {
return Err(FsError::Invalid {
path: format!("{top}/{path}"),
reason: Reason::Symlink,
}
.into());
}
Ok(())
}
fn collect_mirrors(
repo: &Repo,
refs: Option<&RepoDir>,
skip: &dyn Fn(&str) -> bool,
keep: &dyn Fn(&str) -> bool,
) -> Result<Vec<(String, String, Checksum)>> {
let Some(mirrors) = open_top_in(refs, MIRRORS_DIR)? else {
return Ok(Vec::new());
};
let mut out = Vec::new();
walk_ref_dir_skipping(&mirrors, "", skip, &mut |entry| {
refuse_top_symlink(MIRRORS_DIR, entry.path, entry.file_type)?;
if !keep(entry.path) {
return Ok(());
}
let Some((bytes, _)) = read_listed_ref(repo.root_dir(), MIRRORS_DIR, &entry, None)? else {
return Ok(());
};
let checksum = parse_ref_content(&bytes)?;
if let Some((collection, ref_name)) = entry.path.split_once('/') {
out.push((collection.to_owned(), ref_name.to_owned(), checksum));
}
Ok(())
})?;
Ok(out)
}
pub(crate) struct RefEntry<'a> {
pub(crate) dir: &'a RepoDir,
pub(crate) name: &'a str,
pub(crate) path: &'a str,
pub(crate) file_type: FileType,
}
impl RefEntry<'_> {
pub(crate) fn can_hold_ref(&self) -> bool {
matches!(self.file_type, FileType::RegularFile | FileType::Symlink)
}
}
pub(crate) fn walk_ref_dir(
dir: &RepoDir,
prefix: &str,
visit: &mut impl FnMut(RefEntry<'_>) -> Result<()>,
) -> Result<()> {
walk_ref_dir_skipping(dir, prefix, &|_| false, visit)
}
fn walk_ref_dir_skipping(
dir: &RepoDir,
prefix: &str,
skip: &dyn Fn(&str) -> bool,
visit: &mut impl FnMut(RefEntry<'_>) -> Result<()>,
) -> Result<()> {
for entry in dir.list()? {
let Ok(name) = String::from_utf8(entry.name) else {
continue;
};
let mut file_type = entry.file_type;
let path = if prefix.is_empty() {
name.clone()
} else {
format!("{prefix}/{name}")
};
if file_type == FileType::Directory {
if skip(&path) {
continue;
}
if let Some(sub) = dir.open_dir(&name).optional_walked_dir()? {
walk_ref_dir_skipping(&sub, &path, skip, visit)?;
continue;
}
match entry_type(dir, &name)? {
Some(now) if now != FileType::Directory => file_type = now,
_ => continue,
}
}
visit(RefEntry {
dir,
name: &name,
path: &path,
file_type,
})?;
}
Ok(())
}
fn walk_ref_patterns(
dir: &RepoDir,
prefix: &str,
patterns: &[(&RefPattern, &[&str])],
skip: &dyn Fn(&str) -> bool,
visit: &mut dyn FnMut(RefEntry<'_>) -> Result<()>,
) -> Result<()> {
let mut literal: BTreeMap<&str, Vec<(&RefPattern, &[&str])>> = BTreeMap::new();
for &(pattern, parts) in patterns {
match parts.split_first() {
Some((first, rest)) if *first != "*" && *first != "**" => {
literal.entry(first).or_default().push((pattern, rest));
}
Some(_) => walk_ref_pattern(dir, prefix, parts, pattern, skip, visit)?,
None => {}
}
}
for (name, group) in literal {
let Some(file_type) = entry_type(dir, name)? else {
continue;
};
let path = if prefix.is_empty() {
name.to_owned()
} else {
format!("{prefix}/{name}")
};
if file_type == FileType::Directory {
let below: Vec<(&RefPattern, &[&str])> = group
.into_iter()
.filter(|(_, rest)| !rest.is_empty())
.collect();
if !below.is_empty()
&& !skip(&path)
&& let Some(sub) = dir.open_dir(name).optional_walked_dir()?
{
walk_ref_patterns(&sub, &path, &below, skip, visit)?;
}
} else if group.iter().any(|(_, rest)| rest.is_empty()) {
visit(RefEntry {
dir,
name,
path: &path,
file_type,
})?;
}
}
Ok(())
}
fn walk_ref_pattern(
dir: &RepoDir,
prefix: &str,
parts: &[&str],
pattern: &RefPattern,
skip: &dyn Fn(&str) -> bool,
visit: &mut dyn FnMut(RefEntry<'_>) -> Result<()>,
) -> Result<()> {
let Some((first, rest)) = parts.split_first() else {
return Ok(());
};
if *first == "**" {
return walk_ref_dir_skipping(dir, prefix, skip, &mut |entry| {
if rest.is_empty() || pattern.matches(entry.path) {
visit(entry)
} else {
Ok(())
}
});
}
let entries: Vec<(String, FileType)> = if *first == "*" {
dir.list()?
.into_iter()
.filter_map(|entry| Some((String::from_utf8(entry.name).ok()?, entry.file_type)))
.collect()
} else {
entry_type(dir, first)?
.map(|file_type| ((*first).to_owned(), file_type))
.into_iter()
.collect()
};
for (name, file_type) in entries {
let path = if prefix.is_empty() {
name.clone()
} else {
format!("{prefix}/{name}")
};
match (file_type == FileType::Directory, rest.is_empty()) {
(true, false) if !skip(&path) => {
if let Some(sub) = dir.open_dir(&name).optional_walked_dir()? {
walk_ref_pattern(&sub, &path, rest, pattern, skip, visit)?;
}
}
(false, true) => visit(RefEntry {
dir,
name: &name,
path: &path,
file_type,
})?,
_ => {}
}
}
Ok(())
}
fn covering_lead(text: &str) -> Option<Vec<&str>> {
let lead = if text == "**" {
""
} else {
text.strip_suffix("/**")?
};
let parts: Vec<&str> = if lead.is_empty() {
Vec::new()
} else {
lead.split('/').collect()
};
if parts.contains(&"**") {
return None;
}
Some(parts)
}
fn dir_is_covered(covers: &[Vec<&str>], dir: &str) -> bool {
covers.iter().any(|lead| {
let mut parts = dir.split('/');
lead.iter()
.all(|l| parts.next().is_some_and(|part| *l == "*" || *l == part))
})
}
fn uncovered_patterns(patterns: &[RefPattern]) -> Vec<&RefPattern> {
let leads: Vec<(usize, &str)> = patterns
.iter()
.enumerate()
.filter_map(|(i, q)| {
let text = q.as_str();
let lead = if text == "**" {
""
} else {
&text[..text.strip_suffix("/**")?.len() + 1]
};
let literal = lead.split('/').all(|part| part != "*" && part != "**");
literal.then_some((i, lead))
})
.collect();
let mut seen: HashSet<&str> = HashSet::new();
patterns
.iter()
.filter(|p| {
let text = p.as_str();
let repeat = !seen.insert(text);
!repeat
&& !leads.iter().any(|(j, lead)| {
patterns[*j].as_str() != text
&& text.len() > lead.len()
&& text.starts_with(lead)
})
})
.collect()
}
fn entry_type(dir: &RepoDir, name: &str) -> Result<Option<FileType>> {
match dir.lstat(name) {
Ok(stat) => Ok(Some(stat.file_type)),
Err(FsError::Absent { .. }) => Ok(None),
Err(FsError::Io(e)) if e.raw_os_error() == Some(Errno::NAMETOOLONG.raw_os_error()) => {
Ok(None)
}
Err(e) => Err(e.into()),
}
}
fn read_alias_body(entry: &RefEntry<'_>) -> Result<Option<String>> {
if entry.file_type != FileType::Symlink {
return Ok(None);
}
let body = match read_ref_entry(entry.dir, entry.name, true) {
Ok(RefEntryRead::Alias(body)) => body,
Ok(RefEntryRead::File(_)) => return Ok(None),
Err(
FsError::Absent { .. }
| FsError::Invalid {
reason: Reason::NotRegular(_) | Reason::NotDirectory,
..
},
) => return Ok(None),
Err(e) => return Err(e.into()),
};
Ok(String::from_utf8(body).ok())
}
enum RefEntryRead {
File(Vec<u8>),
Alias(Vec<u8>),
}
fn read_ref_entry(
dir: &RepoDir,
path: &str,
symlink: bool,
) -> std::result::Result<RefEntryRead, FsError> {
let mut symlink = symlink;
let mut restarted = false;
loop {
if !symlink {
match dir.read_capped(path, REF_READ_CAP) {
Err(FsError::Invalid {
reason: Reason::Symlink,
..
}) => {}
other => return other.map(RefEntryRead::File),
}
}
match dir.read_link(path, REF_READ_CAP) {
Err(FsError::Io(e))
if !restarted && e.raw_os_error() == Some(Errno::INVAL.raw_os_error()) =>
{
restarted = true;
symlink = false;
}
other => return other.map(RefEntryRead::Alias),
}
}
}
enum AliasTarget {
Ref(Vec<u8>),
Absent,
Broken(&'static str),
}
fn read_alias_target(root: &RepoDir, target: &str) -> Result<AliasTarget> {
let stat = match root.lstat(target) {
Ok(stat) => stat,
Err(e) => return alias_target_error(e),
};
match stat.file_type {
FileType::RegularFile => {}
FileType::Symlink => return Ok(AliasTarget::Broken(ALIAS_TO_AN_ALIAS)),
_ => return Ok(AliasTarget::Broken(ALIAS_TO_NO_FILE)),
}
match root.read_capped(target, REF_READ_CAP) {
Ok(bytes) => Ok(AliasTarget::Ref(bytes)),
Err(FsError::Invalid {
reason: Reason::NotRegular(_),
..
}) => Ok(AliasTarget::Broken(ALIAS_TO_NO_FILE)),
Err(e) => alias_target_error(e),
}
}
fn alias_target_is_ref(root: &RepoDir, target: &str) -> Result<bool> {
match root.lstat(target) {
Ok(stat) => Ok(stat.file_type == FileType::RegularFile),
Err(e) => alias_target_error(e).map(|_| false),
}
}
fn alias_target_error(e: FsError) -> Result<AliasTarget> {
match e {
FsError::Absent { .. }
| FsError::Invalid {
reason: Reason::NotDirectory,
..
} => Ok(AliasTarget::Absent),
FsError::Invalid {
reason: Reason::Symlink,
..
} => Ok(AliasTarget::Broken(ALIAS_THROUGH_A_SYMLINK)),
e => Err(e.into()),
}
}
fn read_ref_tip(root: &RepoDir, name: &str, relpath: &str) -> Result<Option<Checksum>> {
match read_ref(root, name, relpath)? {
Some(bytes) => Ok(Some(parse_ref_content(&bytes)?)),
None => Ok(None),
}
}
fn read_ref(root: &RepoDir, name: &str, relpath: &str) -> Result<Option<Vec<u8>>> {
let body = match read_ref_entry(root, relpath, false).optional_ref(name)? {
None => return Ok(None),
Some(RefEntryRead::File(bytes)) => return Ok(Some(bytes)),
Some(RefEntryRead::Alias(body)) => body,
};
let broken = |reason: &str| Error::NotARef {
name: name.to_owned(),
reason: reason.to_owned(),
};
let Some(target) = resolve_alias(ref_parent(relpath), &body) else {
return Err(broken(ALIAS_OUTSIDE_REFS));
};
match read_alias_target(root, &target)? {
AliasTarget::Ref(bytes) => Ok(Some(bytes)),
AliasTarget::Absent => Ok(None),
AliasTarget::Broken(reason) => Err(broken(reason)),
}
}
const PASSES_THROUGH_A_FILE: &str = "passes through a file";
const PASSES_THROUGH_AN_ALIAS: &str = "passes through an alias";
const NAMES_A_DIRECTORY: &str = "names a directory";
const NAMES_A_SPECIAL_FILE: &str = "names a special file";
const NAMES_AN_ALIAS: &str = "names an alias";
const TARGETS_AN_ALIAS: &str = "targets an alias";
const ALIAS_OUTSIDE_REFS: &str = "is an alias whose target is not a relative path inside refs/";
const ALIAS_TO_AN_ALIAS: &str = "is an alias to an alias";
const ALIAS_THROUGH_A_SYMLINK: &str = "is an alias whose target passes through a symlink";
const ALIAS_TO_NO_FILE: &str = "is an alias to an entry that is not a regular file";
fn lstat_ref_state(root: &RepoDir, relpath: &str) -> Result<Option<RefFileState>> {
let stat = match root.lstat(relpath) {
Ok(stat) => stat,
Err(e) => return unreached_state(e).map(Some),
};
Ok(match stat.file_type {
FileType::RegularFile => None,
FileType::Symlink => Some(RefFileState::Alias),
FileType::Directory => Some(RefFileState::NotARef(NAMES_A_DIRECTORY)),
_ => Some(RefFileState::NotARef(NAMES_A_SPECIAL_FILE)),
})
}
fn unreached_state(e: FsError) -> Result<RefFileState> {
match e {
FsError::Absent { .. } => Ok(RefFileState::Absent),
FsError::Invalid {
reason: Reason::Symlink,
..
} => Ok(RefFileState::NotARef(PASSES_THROUGH_AN_ALIAS)),
FsError::Invalid {
reason: Reason::NotDirectory,
..
} => Ok(RefFileState::NotARef(PASSES_THROUGH_A_FILE)),
e => Err(e.into()),
}
}
fn ref_file_state(root: &RepoDir, relpath: &str) -> Result<RefFileState> {
if let Some(state) = lstat_ref_state(root, relpath)? {
return Ok(state);
}
match root.read_capped(relpath, REF_READ_CAP) {
Ok(bytes) => Ok(RefFileState::Commit(parse_ref_content(&bytes)?)),
Err(FsError::Invalid {
reason: Reason::NotRegular(FileType::Directory),
..
}) => Ok(RefFileState::NotARef(NAMES_A_DIRECTORY)),
Err(FsError::Invalid {
reason: Reason::NotRegular(_),
..
}) => Ok(RefFileState::NotARef(NAMES_A_SPECIAL_FILE)),
Err(FsError::Invalid {
reason: Reason::Symlink,
..
}) => Ok(RefFileState::Alias),
Err(e) => unreached_state(e),
}
}
pub(crate) fn parse_ref_content(bytes: &[u8]) -> Result<Checksum> {
let text = std::str::from_utf8(bytes)
.map_err(|_| Error::InvalidFormat("ref content is not valid UTF-8".into()))?;
Ok(Checksum::from_hex(text.trim())?)
}
pub fn validate_refspec(refspec: &str) -> Result<()> {
if ostrya_core::is_refspec(refspec) {
Ok(())
} else {
Err(Error::InvalidRefspec(refspec.to_owned()))
}
}
#[cfg_attr(not(feature = "receive"), allow(dead_code))]
pub(crate) fn refspec_to_relpath(refspec: &str) -> Result<String> {
validate_refspec(refspec)?;
Ok(match refspec.split_once(':') {
Some((remote, name)) => format!("refs/remotes/{remote}/{name}"),
None => format!("refs/heads/{refspec}"),
})
}
pub(crate) fn listed_name_addresses_it(name: &str, top: &str, path: &str) -> bool {
match name.split_once(':') {
Some((remote, rest)) => {
top == "refs/remotes"
&& ostrya_core::is_ref_name_component(remote)
&& is_ref_path(rest)
&& path
.split_once('/')
.is_some_and(|(dir, below)| dir == remote && below == rest)
}
None => top == "refs/heads" && is_ref_path(name) && path == name,
}
}
pub(crate) fn check_ref_path(name: &str) -> Result<()> {
if is_ref_path(name) {
Ok(())
} else {
Err(Error::InvalidRefspec(name.to_owned()))
}
}
pub(crate) fn ref_prefixes(name: &str) -> impl Iterator<Item = &str> {
name.match_indices('/')
.map(|(end, _)| &name[..end])
.chain(std::iter::once(name))
}
pub(crate) use ostrya_core::is_ref_component as is_component;
pub(crate) use ostrya_core::is_ref_name as is_ref_path;
pub(crate) fn ref_relpath(own: Option<&str>, r: &Ref) -> Result<String> {
r.validate()?;
Ok(match r {
Ref::Local { name } => format!("{HEADS_DIR}/{name}"),
Ref::Remote { remote, name } => format!("refs/remotes/{remote}/{name}"),
Ref::Collection { id, name } if Some(id.as_str()) == own => {
format!("{HEADS_DIR}/{name}")
}
Ref::Collection { id, name } => format!("{MIRRORS_DIR}/{id}/{name}"),
})
}
pub(crate) fn refspec_ref(refspec: &str) -> Ref {
match refspec.split_once(':') {
Some((remote, name)) => Ref::remote(remote, name),
None => Ref::local(refspec),
}
}
fn write_ref_blocking(
root: &RepoDir,
name: &str,
relpath: &str,
checksum: Option<Checksum>,
fsync: bool,
) -> Result<()> {
let mut dirs = Vec::new();
let written = put_ref_blocking(root, name, relpath, checksum, fsync, &mut dirs);
written.and(sync_ref_dirs(root, dirs))
}
pub(crate) fn put_ref_blocking(
root: &RepoDir,
name: &str,
relpath: &str,
checksum: Option<Checksum>,
fsync: bool,
dirs: &mut Vec<String>,
) -> Result<()> {
let reason = match lstat_ref_state(root, relpath)? {
Some(RefFileState::Alias) => Some(NAMES_AN_ALIAS),
Some(RefFileState::NotARef(PASSES_THROUGH_AN_ALIAS)) => Some(PASSES_THROUGH_AN_ALIAS),
_ => None,
};
if let Some(reason) = reason {
return Err(Error::RefNotWritable {
name: name.to_owned(),
reason: reason.to_owned(),
});
}
match checksum {
Some(checksum) => put_ref_file_blocking(root, relpath, checksum, fsync, dirs),
None => remove_ref_blocking(root, relpath, fsync, dirs),
}
}
fn remove_ref_blocking(
root: &RepoDir,
relpath: &str,
fsync: bool,
dirs: &mut Vec<String>,
) -> Result<()> {
if root.remove_file(relpath, false)? && fsync {
dirs.push(ref_parent(relpath).to_owned());
}
Ok(())
}
fn open_refs_for_write(root: &RepoDir, fsync: bool) -> Result<RepoDir> {
match root.open_layout(RepoLayout::Refs) {
Err(FsError::Absent { .. }) => Ok(root.ensure_layout(RepoLayout::Refs, fsync)?),
opened => Ok(opened?),
}
}
fn ensure_ref_parent<'p>(
refs: &RepoDir,
relpath: &'p str,
fsync: bool,
) -> Result<(RepoDir, &'p str)> {
let Some((parent, leaf)) = relpath
.strip_prefix("refs/")
.and_then(|rel| rel.rsplit_once('/'))
else {
return Err(Error::InvalidInput(format!("not a ref path: {relpath}")));
};
Ok((refs.ensure_dir(parent, fsync)?, leaf))
}
fn put_ref_file_blocking(
root: &RepoDir,
relpath: &str,
checksum: Checksum,
fsync: bool,
dirs: &mut Vec<String>,
) -> Result<()> {
let refs = open_refs_for_write(root, fsync)?;
let temp = refs.stage_atomic(format!("{}\n", checksum.to_hex()).as_bytes(), fsync)?;
let (parent, leaf) = ensure_ref_parent(&refs, relpath, fsync)?;
temp.publish(&parent, leaf, Publish::Replace, false)?;
if fsync {
dirs.push(ref_parent(relpath).to_owned());
}
Ok(())
}
fn sort_dirs_deepest_first(dirs: &mut Vec<String>) {
let depth = |dir: &str| {
if dir == ROOT_DIR {
0
} else {
dir.split('/').count()
}
};
dirs.sort_by(|a, b| depth(b).cmp(&depth(a)).then_with(|| a.cmp(b)));
dirs.dedup();
}
const ROOT_DIR: &str = ".";
fn sync_recorded_dir(root: &RepoDir, dir: &str) -> Result<()> {
if dir == ROOT_DIR {
root.sync()?;
} else {
root.sync_dir(dir)?;
}
Ok(())
}
fn sync_ref_dirs(root: &RepoDir, mut dirs: Vec<String>) -> Result<()> {
sort_dirs_deepest_first(&mut dirs);
for dir in &dirs {
sync_recorded_dir(root, dir)?;
}
Ok(())
}
pub(crate) fn sync_dirs_all(root: &RepoDir, mut dirs: Vec<String>) -> Result<()> {
sort_dirs_deepest_first(&mut dirs);
let mut first = Ok(());
for dir in &dirs {
let synced = sync_recorded_dir(root, dir);
#[cfg(test)]
test_syncs::record(std::os::fd::AsFd::as_fd(root));
if first.is_ok() {
first = synced;
}
}
first
}
#[cfg(test)]
pub(crate) mod test_syncs {
use std::os::fd::BorrowedFd;
use std::sync::Mutex;
type Record = ((u64, u64), bool);
static SYNCS: Mutex<Vec<Record>> = Mutex::new(Vec::new());
pub(crate) fn record(repo_fd: BorrowedFd<'_>) {
let held = crate::lock::update_lock_held_in_process(repo_fd);
if let Ok(stat) = rustix::fs::fstat(repo_fd) {
SYNCS
.lock()
.unwrap()
.push(((stat.st_dev, stat.st_ino), held));
}
}
fn syncs(root: &std::path::Path) -> Vec<bool> {
use std::os::unix::fs::MetadataExt;
let meta = std::fs::metadata(root).unwrap();
let key = (meta.dev(), meta.ino());
let syncs = SYNCS.lock().unwrap();
syncs
.iter()
.filter(|(k, _)| *k == key)
.map(|(_, held)| *held)
.collect()
}
pub(crate) fn forget(root: &std::path::Path) {
use std::os::unix::fs::MetadataExt;
let meta = std::fs::metadata(root).unwrap();
let key = (meta.dev(), meta.ino());
SYNCS.lock().unwrap().retain(|(k, _)| *k != key);
}
pub(crate) fn count(root: &std::path::Path) -> usize {
syncs(root).len()
}
pub(crate) fn unlocked(root: &std::path::Path) -> usize {
syncs(root).into_iter().filter(|held| !held).count()
}
}
fn write_alias_blocking(
root: &RepoDir,
name: &str,
relpath: &str,
target: &str,
fsync: bool,
) -> Result<()> {
let mut dirs = Vec::new();
let written = put_alias_blocking(root, name, relpath, target, fsync, &mut dirs);
written.and(sync_ref_dirs(root, dirs))
}
pub(crate) fn put_alias_blocking(
root: &RepoDir,
name: &str,
relpath: &str,
target: &str,
fsync: bool,
dirs: &mut Vec<String>,
) -> Result<()> {
let refuse = |reason: &str| {
Err(Error::RefNotWritable {
name: name.to_owned(),
reason: reason.to_owned(),
})
};
if passes_through_an_alias(root, relpath)? {
return refuse(PASSES_THROUGH_AN_ALIAS);
}
if target == relpath {
return refuse(TARGETS_AN_ALIAS);
}
match lstat_ref_state(root, target)? {
Some(RefFileState::Alias) => return refuse(TARGETS_AN_ALIAS),
Some(RefFileState::NotARef(PASSES_THROUGH_AN_ALIAS)) => {
return refuse(PASSES_THROUGH_AN_ALIAS);
}
_ => {}
}
let link = TempLink::create(root, &relative_link(relpath, target))?;
let (parent, leaf) = ensure_ref_parent(&open_refs_for_write(root, fsync)?, relpath, fsync)?;
link.publish(&parent, leaf, Publish::Replace, false)?;
if fsync {
dirs.push(ref_parent(relpath).to_owned());
}
Ok(())
}
fn passes_through_an_alias(root: &RepoDir, relpath: &str) -> Result<bool> {
match root.exists(relpath) {
Ok(_)
| Err(FsError::Invalid {
reason: Reason::NotDirectory,
..
}) => Ok(false),
Err(FsError::Invalid {
reason: Reason::Symlink,
..
}) => Ok(true),
Err(e) => Err(e.into()),
}
}
pub(crate) fn remove_alias_blocking(
root: &RepoDir,
name: &str,
relpath: &str,
fsync: bool,
dirs: &mut Vec<String>,
) -> Result<()> {
let reason = match lstat_ref_state(root, relpath)? {
Some(RefFileState::Absent) => return Ok(()),
Some(RefFileState::Alias) => return remove_ref_blocking(root, relpath, fsync, dirs),
Some(RefFileState::NotARef(reason)) => reason,
None | Some(RefFileState::Commit(_)) => "names a ref file",
};
Err(Error::RefNotWritable {
name: name.to_owned(),
reason: reason.to_owned(),
})
}
pub(crate) fn check_refs_to_delete_blocking<K: std::fmt::Display>(
root: &RepoDir,
refs: &[(K, Checksum)],
relpath: impl Fn(&K) -> Result<String>,
) -> Result<()> {
for (key, _) in refs {
if passes_through_an_alias(root, &relpath(key)?)? {
return Err(Error::RefNotWritable {
name: key.to_string(),
reason: PASSES_THROUGH_AN_ALIAS.to_owned(),
});
}
}
Ok(())
}
pub(crate) fn delete_matching_refs_blocking<K: std::fmt::Display>(
root: &RepoDir,
refs: Vec<(K, Checksum)>,
relpath: impl Fn(&K) -> Result<String>,
fsync: bool,
) -> Result<Vec<K>> {
check_refs_to_delete_blocking(root, &refs, &relpath)?;
let mut removed = Vec::with_capacity(refs.len());
let mut parents: Vec<String> = Vec::new();
let mut held: HashSet<String> = HashSet::new();
for (key, target) in refs {
let relpath = relpath(&key)?;
let current = match read_ref(root, &relpath, &relpath) {
Err(Error::NotARef { .. }) => None,
read => read?,
};
if let Some(bytes) = current
&& parse_ref_content(&bytes)? != target
{
continue;
}
if root.remove_file(&relpath, false)? && fsync {
let parent = ref_parent(&relpath);
if !held.contains(parent) {
held.insert(parent.to_owned());
parents.push(parent.to_owned());
}
}
removed.push(key);
}
for parent in &parents {
root.sync_dir(parent).optional()?;
}
Ok(removed)
}
fn ref_parent(relpath: &str) -> &str {
relpath.rsplit_once('/').map_or(ROOT_DIR, |(dir, _)| dir)
}
#[cfg(test)]
mod tests {
use ostrya_core::RepoMode;
use rustix::fs::{Mode, OFlags};
use super::*;
#[test]
fn refspec_maps_local_and_remote() {
assert_eq!(
refspec_to_relpath("test/main").unwrap(),
"refs/heads/test/main"
);
assert_eq!(
refspec_to_relpath("origin:test/main").unwrap(),
"refs/remotes/origin/test/main"
);
}
#[test]
fn refspec_rejects_traversal() {
for bad in [
"",
"..",
"a/../b",
"/a",
"a/",
"a//b",
"a/..",
"origin:../escape",
"a b",
"a*",
"-a",
"a/.b",
"a^b",
"a~b",
"origin:a:b",
"origin:a b",
"o r:main",
"o*:main",
"-o:main",
".o:main",
"o~:main",
"a/b:x",
":x",
"origin:",
] {
let err = refspec_to_relpath(bad).unwrap_err();
assert!(
matches!(&err, Error::InvalidRefspec(name) if name == bad),
"should reject {bad:?}, got {err}"
);
}
assert!(validate_refspec("test/main").is_ok());
assert!(validate_refspec("origin:test/main").is_ok());
for good in [
"a.",
"a..b",
"_a",
"a_b",
"1a",
"A",
"\u{e9}",
"a/\u{e9}b",
"\u{e9}:main",
] {
assert!(validate_refspec(good).is_ok(), "should accept {good:?}");
}
}
fn patterns(texts: &[&str]) -> Vec<RefPattern> {
texts
.iter()
.map(|text| RefPattern::parse(text).unwrap())
.collect()
}
#[test]
fn a_covered_pattern_is_dropped() {
let kept = |texts: &[&str]| -> Vec<String> {
let all = patterns(texts);
uncovered_patterns(&all)
.iter()
.map(|p| p.as_str().to_owned())
.collect()
};
assert_eq!(
kept(&["a/b", "a/**", "a/*/c", "ab", "a"]),
["a/**", "ab", "a"]
);
assert_eq!(kept(&["a/b", "a/b", "a/**", "a/**"]), ["a/**"]);
assert_eq!(kept(&["x/y", "x/y"]), ["x/y"]);
assert_eq!(kept(&["a/b/**", "a/**", "a/b/c"]), ["a/**"]);
assert_eq!(kept(&["a/*/**", "a/b/c"]), ["a/*/**", "a/b/c"]);
assert_eq!(kept(&["a/**/c", "a/**", "a/**/c"]), ["a/**"]);
assert_eq!(kept(&["a/**/c", "b/**/c"]), ["a/**/c", "b/**/c"]);
assert_eq!(kept(&["**", "a", "b/*"]), ["**"]);
assert_eq!(kept(&["*", "a/b"]), ["*", "a/b"]);
}
#[test]
fn a_negative_pattern_covers_a_directory() {
let covers: Vec<Vec<&str>> = ["a/c/**", "*/x/**", "**/q", "a/**/**", "k/**"]
.iter()
.filter_map(|text| covering_lead(text))
.collect();
assert_eq!(covers, [vec!["a", "c"], vec!["*", "x"], vec!["k"]]);
for dir in ["a/c", "a/c/d", "z/x", "k", "k/j/i"] {
assert!(dir_is_covered(&covers, dir), "{dir}");
}
for dir in ["a", "a/b", "b/c", "z", "kk", "z/y"] {
assert!(!dir_is_covered(&covers, dir), "{dir}");
}
assert!(dir_is_covered(&[Vec::new()], "any"));
}
#[test]
fn ref_relpath_names_the_ref_it_rejects() {
for (r, label) in [
(
Ref::collection("org.example.Foo", "a/../b"),
"@org.example.Foo:a/../b",
),
(Ref::collection("a", "main"), "@a:main"),
(Ref::local("a/../b"), "a/../b"),
(Ref::local("origin:main"), "origin:main"),
(Ref::remote("o/r", "main"), "o/r:main"),
(
Ref::collection("org.example.B", "-bad"),
"@org.example.B:-bad",
),
] {
let err = ref_relpath(None, &r).unwrap_err();
assert!(
matches!(&err, Error::InvalidRefspec(name) if name == label),
"{err}"
);
}
let longest = format!("org.{}", "a".repeat(251));
assert_eq!(longest.len(), ostrya_core::MAX_COLLECTION_ID_LEN);
assert!(ref_relpath(None, &Ref::collection(longest.as_str(), "main")).is_ok());
let too_long = format!("org.{}", "a".repeat(252));
let err = ref_relpath(None, &Ref::collection(too_long.as_str(), "main")).unwrap_err();
assert!(
matches!(&err, Error::InvalidRefspec(name) if *name == format!("@{too_long}:main")),
"{err}"
);
}
#[test]
fn a_refspec_reads_as_a_ref_with_no_check() {
assert_eq!(refspec_ref("a/b"), Ref::local("a/b"));
assert_eq!(refspec_ref("origin:a/b"), Ref::remote("origin", "a/b"));
assert_eq!(refspec_ref("o:a:b"), Ref::remote("o", "a:b"));
let at = refspec_ref("@org.example.A:x");
assert_eq!(at, Ref::remote("@org.example.A", "x"));
assert!(at.validate().is_err());
}
#[test]
fn splits_the_ancestry_suffix() {
assert_eq!(split_ancestry("test/main"), ("test/main", 0));
assert_eq!(split_ancestry("test/main^"), ("test/main", 1));
assert_eq!(split_ancestry("test/main^^^"), ("test/main", 3));
assert_eq!(split_ancestry("^"), ("", 1));
}
#[test]
fn builds_the_alias_link_body() {
assert_eq!(
relative_link("refs/heads/alias", "refs/heads/test/main"),
"test/main"
);
assert_eq!(relative_link("refs/heads/p/q", "refs/heads/one"), "../one");
assert_eq!(relative_link("refs/heads/a/b", "refs/heads/a"), "../a");
assert_eq!(
relative_link("refs/heads/alias", "refs/remotes/origin/main"),
"../remotes/origin/main"
);
}
const ADDRESSABILITY_CASES: &[(&str, &str, &str, bool)] = &[
("main", "refs/heads", "main", true),
("test/main", "refs/heads", "test/main", true),
("foo:bar", "refs/heads", "foo:bar", false),
("a/b:c", "refs/heads", "a/b:c", false),
("main", "refs/heads", "other", false),
("a/../b", "refs/heads", "a/../b", false),
("", "refs/heads", "", false),
("origin:main", "refs/remotes", "origin/main", true),
("a:pool/x", "refs/remotes", "a:pool/x", false),
("a:pool/x", "refs/remotes", "a/pool/x", true),
("origin:foo:bar", "refs/remotes", "origin/foo:bar", false),
("a:b:main", "refs/remotes", "a:b/main", false),
("a:b:main", "refs/remotes", "a/b:main", false),
("a b", "refs/heads", "a b", false),
("-a", "refs/heads", "-a", false),
("a/.b", "refs/heads", "a/.b", false),
("a*", "refs/heads", "a*", false),
("origin:a b", "refs/remotes", "origin/a b", false),
("o r:main", "refs/remotes", "o r/main", false),
("-o:main", "refs/remotes", "-o/main", false),
(".o:main", "refs/remotes", ".o/main", false),
("o~:main", "refs/remotes", "o~/main", false),
("\u{e9}:main", "refs/remotes", "\u{e9}/main", true),
("stray", "refs/remotes", "stray", false),
(":x:main", "refs/remotes", ":x/main", false),
("..:main", "refs/remotes", "../main", false),
("origin:a/../b", "refs/remotes", "origin/a/../b", false),
(
"org.example.Coll/mm",
"refs/mirrors",
"org.example.Coll/mm",
false,
),
("origin:main", "refs/mirrors", "origin/main", false),
];
#[test]
fn a_listed_name_addresses_its_own_file_only_where_the_mapping_returns_it() {
for (name, top, path, expected) in ADDRESSABILITY_CASES {
assert_eq!(
listed_name_addresses_it(name, top, path),
*expected,
"{name:?} under {top:?} at {path:?}"
);
}
}
#[test]
fn the_addressability_predicate_agrees_with_the_refspec_mapping() {
for (name, top, path, _) in ADDRESSABILITY_CASES {
assert_eq!(
listed_name_addresses_it(name, top, path),
refspec_to_relpath(name).ok() == Some(format!("{top}/{path}")),
"{name:?} under {top:?} at {path:?}"
);
}
}
#[test]
fn parses_ref_content_with_newline() {
let hex = "b3c8e8525e8a5c3409bf6e6db5f5d656da77ae76d08cbc4f8b75b71879757a89";
let checksum = parse_ref_content(format!("{hex}\n").as_bytes()).unwrap();
assert_eq!(checksum.to_hex(), hex);
assert!(parse_ref_content(b"not-a-checksum\n").is_err());
}
struct Root {
dir: std::path::PathBuf,
}
impl Root {
fn new(label: &str) -> Root {
let dir = std::env::temp_dir().join(format!(
"ostrya-refs-{label}-{}-{}",
std::process::id(),
crate::write::unique()
));
std::fs::create_dir_all(dir.join("refs/heads")).unwrap();
Root { dir }
}
fn handle(&self) -> RepoDir {
RepoDir::open_root(rustix::fs::CWD, &self.dir).unwrap()
}
}
impl Drop for Root {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
}
}
fn ref_text(commit: &Checksum) -> String {
format!("{}\n", commit.to_hex())
}
fn mkfifo(path: &std::path::Path) {
rustix::fs::mknodat(
rustix::fs::CWD,
path,
FileType::Fifo,
Mode::from_raw_mode(0o644),
0,
)
.unwrap();
}
fn assert_not_a_ref<T: std::fmt::Debug>(result: Result<T>, reason: &str, what: &str) {
match result {
Err(Error::NotARef { reason: r, .. }) => assert_eq!(r, reason, "{what}"),
other => panic!("{what}: {other:?}"),
}
}
fn assert_invalid<T: std::fmt::Debug>(result: Result<T>, text: &str, what: &str) {
match result {
Err(Error::InvalidFormat(message)) => {
assert!(message.contains(text), "{what}: {message}");
}
other => panic!("{what}: {other:?}"),
}
}
#[test]
fn a_listed_ref_file_that_is_an_alias_at_the_open_takes_the_alias_rule() {
let root = Root::new("listed-alias");
ostrya_rt::block_on(async {
let repo = Repo::create(
&root.dir.join("repo"),
crate::CreateOptions::new(RepoMode::Archive),
)
.await
.unwrap();
let commit = Checksum::from_bytes([7; 32]);
let heads = root.dir.join("repo/refs/heads");
std::fs::write(heads.join("secret"), ref_text(&commit)).unwrap();
std::fs::create_dir(heads.join("pub")).unwrap();
std::os::unix::fs::symlink("../secret", heads.join("pub/a")).unwrap();
let dir = open_ref_top(&repo, HEADS_DIR)
.unwrap()
.unwrap()
.open_dir("pub")
.unwrap();
let entry = RefEntry {
dir: &dir,
name: "a",
path: "pub/a",
file_type: FileType::RegularFile,
};
let reader = |allow: &str| {
let text = format!(
"[core]\nrepo_version=1\nmode=archive-z2\n\
[ex-ostrya client \"c\"]\nauth=anonymous\nallow={allow}\n"
);
let config = crate::RepoConfig::parse(&text).unwrap();
let access = crate::access::ClientAccess::from_config(&config).unwrap();
ReadAccess::new(
std::sync::Arc::new(access),
crate::access::AuthItem::Anonymous,
None,
)
};
let root_dir = repo.root_dir();
let hidden =
read_listed_ref(root_dir, HEADS_DIR, &entry, Some(&reader("r:pub/**"))).unwrap();
assert_eq!(hidden, None);
let (read, target) =
read_listed_ref(root_dir, HEADS_DIR, &entry, Some(&reader("r:**")))
.unwrap()
.unwrap();
assert_eq!(parse_ref_content(&read).unwrap(), commit);
assert_eq!(target.as_deref(), Some("refs/heads/secret"));
});
}
#[test]
fn a_listed_ref_entry_that_is_a_fifo_or_a_socket_gives_no_ref() {
let root = Root::new("listed-fifo");
let (fifo, _socket) = special_ref_entries(&root);
for (name, file_type) in [
("fifo", FileType::Fifo),
("fifo", FileType::RegularFile),
("sock", FileType::Socket),
("sock", FileType::RegularFile),
] {
let result = read_without_wait(&root.dir, &fifo, name, move |root| {
let dir = root
.open_layout(RepoLayout::Refs)
.unwrap()
.open_dir("heads")
.unwrap();
let entry = RefEntry {
dir: &dir,
name,
path: name,
file_type,
};
read_listed_ref(root, HEADS_DIR, &entry, None).map(|r| r.is_none())
});
assert!(result.unwrap(), "{name} as {file_type:?}");
}
}
#[test]
fn a_listed_alias_that_is_gone_or_no_symlink_at_the_read_gives_no_alias() {
let root = Root::new("listed-alias-gone");
let heads = root.dir.join("refs/heads");
let commit = Checksum::from_bytes([7; 32]);
std::fs::write(heads.join("file"), ref_text(&commit)).unwrap();
std::fs::create_dir(heads.join("dir")).unwrap();
let handle = root.handle();
let dir = handle
.open_layout(RepoLayout::Refs)
.unwrap()
.open_dir("heads")
.unwrap();
for name in ["gone", "file", "dir"] {
let entry = RefEntry {
dir: &dir,
name,
path: name,
file_type: FileType::Symlink,
};
assert_eq!(read_alias_body(&entry).unwrap(), None, "{name}");
}
}
fn read_without_wait<T: Send + 'static>(
dir: &std::path::Path,
fifo: &std::path::Path,
what: &str,
read: impl FnOnce(&RepoDir) -> T + Send + 'static,
) -> T {
let (tx, rx) = std::sync::mpsc::channel();
let dir = dir.to_owned();
std::thread::spawn(move || {
let root = RepoDir::open_root(rustix::fs::CWD, &dir).unwrap();
let _ = tx.send(read(&root));
});
let timeout = std::time::Duration::from_secs(10);
let Ok(result) = rx.recv_timeout(timeout) else {
let _ = rustix::fs::open(
fifo,
OFlags::WRONLY | OFlags::NONBLOCK | OFlags::CLOEXEC,
Mode::empty(),
);
let _ = rx.recv_timeout(timeout);
panic!("{what}: the open waits on the FIFO");
};
result
}
fn special_ref_entries(root: &Root) -> (std::path::PathBuf, std::os::unix::net::UnixListener) {
let heads = root.dir.join("refs/heads");
let fifo = heads.join("fifo");
mkfifo(&fifo);
std::os::unix::fs::symlink("fifo", heads.join("to-fifo")).unwrap();
let short = root.dir.join("s");
let socket = std::os::unix::net::UnixListener::bind(&short).unwrap();
std::fs::rename(&short, heads.join("sock")).unwrap();
std::os::unix::fs::symlink("sock", heads.join("to-sock")).unwrap();
std::os::unix::fs::symlink("/dev/null", heads.join("null")).unwrap();
std::fs::create_dir(heads.join("dir")).unwrap();
std::os::unix::fs::symlink("dir", heads.join("to-dir")).unwrap();
(fifo, socket)
}
#[test]
fn a_direct_read_of_a_fifo_a_socket_or_a_directory_is_not_a_ref() {
let root = Root::new("special");
let (fifo, _socket) = special_ref_entries(&root);
for (name, reason) in [
("fifo", "is not a regular file"),
("sock", "is not a regular file"),
("dir", "is not a regular file"),
("to-fifo", ALIAS_TO_NO_FILE),
("to-sock", ALIAS_TO_NO_FILE),
("to-dir", ALIAS_TO_NO_FILE),
("null", ALIAS_OUTSIDE_REFS),
] {
let relpath = format!("refs/heads/{name}");
let result = read_without_wait(&root.dir, &fifo, name, move |root| {
read_ref(root, name, &relpath)
});
assert_not_a_ref(result, reason, name);
}
let commit = Checksum::from_bytes([1; 32]);
std::fs::write(root.dir.join("refs/heads/main"), ref_text(&commit)).unwrap();
let read = read_ref_tip(&root.handle(), "main", "refs/heads/main").unwrap();
assert_eq!(read, Some(commit));
}
#[test]
fn the_ref_state_of_a_fifo_a_socket_or_a_directory_is_no_ref() {
let root = Root::new("special-state");
let (fifo, _socket) = special_ref_entries(&root);
for (name, reason) in [
("fifo", "names a special file"),
("sock", "names a special file"),
("dir", "names a directory"),
] {
let relpath = format!("refs/heads/{name}");
let (lstat, checked) = read_without_wait(&root.dir, &fifo, name, move |root| {
(
lstat_ref_state(root, &relpath),
ref_file_state(root, &relpath),
)
});
let state = RefFileState::NotARef(reason);
assert_eq!(lstat.unwrap(), Some(state), "{name}");
assert_eq!(checked.unwrap(), state, "{name}");
}
}
#[test]
fn the_ref_state_of_a_path_below_an_alias_is_no_ref() {
use std::os::unix::fs::symlink;
let root = Root::new("below-alias");
let heads = root.dir.join("refs/heads");
let content = ref_text(&Checksum::from_bytes([1; 32]));
std::fs::create_dir(heads.join("d0")).unwrap();
std::fs::write(heads.join("d0/x"), &content).unwrap();
std::fs::write(heads.join("file"), &content).unwrap();
symlink("nosuch", heads.join("dangling")).unwrap();
symlink("d0", heads.join("to-dir")).unwrap();
symlink("file", heads.join("to-file")).unwrap();
let fifo = heads.join("fifo");
mkfifo(&fifo);
let alias = RefFileState::NotARef(PASSES_THROUGH_AN_ALIAS);
let file = RefFileState::NotARef(PASSES_THROUGH_A_FILE);
for (relpath, state) in [
("refs/heads/dangling/x", alias),
("refs/heads/to-dir/x", alias),
("refs/heads/to-dir/deeper/x", alias),
("refs/heads/to-file/x", alias),
("refs/heads/file/x", file),
("refs/heads/fifo/x", file),
("refs/heads/dangling", RefFileState::Alias),
("refs/heads/to-dir", RefFileState::Alias),
("refs/heads/nosuch/x", RefFileState::Absent),
] {
let (lstat, checked) = read_without_wait(&root.dir, &fifo, relpath, move |root| {
(
lstat_ref_state(root, relpath),
ref_file_state(root, relpath),
)
});
assert_eq!(lstat.unwrap(), Some(state), "{relpath}");
assert_eq!(checked.unwrap(), state, "{relpath}");
}
for top in ["refs/heads", "refs"] {
let root = Root::new("below-alias-top");
let real = root.dir.join("real");
std::fs::rename(root.dir.join(top), &real).unwrap();
let link = if top == "refs" { "real" } else { "../real" };
symlink(link, root.dir.join(top)).unwrap();
let main = if top == "refs" {
"real/heads/main"
} else {
"real/main"
};
std::fs::write(root.dir.join(main), &content).unwrap();
let handle = root.handle();
for relpath in ["refs/heads/main", "refs/heads/sub/x"] {
assert_eq!(
lstat_ref_state(&handle, relpath).unwrap(),
Some(alias),
"{top}: {relpath}"
);
assert_eq!(
ref_file_state(&handle, relpath).unwrap(),
alias,
"{top}: {relpath}"
);
}
}
}
async fn archive_repo(path: &std::path::Path) -> Repo {
Repo::create(path, crate::CreateOptions::new(RepoMode::Archive))
.await
.unwrap()
}
#[test]
fn an_alias_that_breaks_the_alias_rule_names_no_ref() {
use std::os::unix::fs::symlink;
let root = Root::new("alias-rule");
let path = root.dir.join("repo");
let repo = ostrya_rt::block_on(archive_repo(&path));
let commit = Checksum::from_bytes([3; 32]);
let outside = root.dir.join("outside-ref");
std::fs::write(&outside, ref_text(&commit)).unwrap();
std::fs::write(path.join("inrepo-ref"), ref_text(&commit)).unwrap();
let mirror = format!("{MIRRORS_DIR}/org.example.Other");
let dirs = [HEADS_DIR, "refs/remotes/o", mirror.as_str()];
for dir in dirs {
let dir = path.join(dir);
std::fs::create_dir_all(dir.join("real")).unwrap();
std::fs::write(dir.join("real/main"), ref_text(&commit)).unwrap();
symlink("real", dir.join("linked")).unwrap();
symlink("real/main", dir.join("good")).unwrap();
symlink(dir.join("real/main"), dir.join("absin")).unwrap();
symlink(&outside, dir.join("absout")).unwrap();
symlink("../../../inrepo-ref", dir.join("relroot")).unwrap();
symlink("../../../../outside-ref", dir.join("relout")).unwrap();
symlink("linked/main", dir.join("through")).unwrap();
symlink("good", dir.join("chain")).unwrap();
symlink("self", dir.join("self")).unwrap();
}
for dir in [&dirs[1], &dirs[2]] {
let dir = path.join(dir);
for name in ["relroot", "relout"] {
std::fs::remove_file(dir.join(name)).unwrap();
}
symlink("../../../../inrepo-ref", dir.join("relroot")).unwrap();
symlink("../../../../../outside-ref", dir.join("relout")).unwrap();
}
let broken = [
("absin", ALIAS_OUTSIDE_REFS),
("absout", ALIAS_OUTSIDE_REFS),
("relroot", ALIAS_OUTSIDE_REFS),
("relout", ALIAS_OUTSIDE_REFS),
("through", ALIAS_THROUGH_A_SYMLINK),
("chain", ALIAS_TO_AN_ALIAS),
("self", ALIAS_TO_AN_ALIAS),
];
ostrya_rt::block_on(async {
for (name, reason) in broken {
let result = repo.resolve_ref_tip(&Ref::local(name)).await;
assert_not_a_ref(result, reason, name);
let result = repo.resolve_rev(name, true).await;
assert_not_a_ref(result, reason, name);
let result = repo.resolve_ref_tip(&Ref::remote("o", name)).await;
assert_not_a_ref(result, reason, name);
}
assert_eq!(
repo.resolve_ref_tip(&Ref::local("good")).await.unwrap(),
Some(commit)
);
let names = |refs: Vec<(String, Checksum)>| -> Vec<String> {
refs.into_iter().map(|(name, _)| name).collect()
};
assert_eq!(
names(repo.list_refs(None).await.unwrap()),
["good", "real/main"]
);
assert_eq!(
names(repo.list_remote_refs().await.unwrap()),
["o:good", "o:real/main"]
);
let mut mirrors: Vec<String> = repo
.list_mirror_refs()
.await
.unwrap()
.into_iter()
.map(|(_, name, _)| name)
.collect();
mirrors.sort();
assert_eq!(mirrors, ["good", "real/main"]);
let selector = RefSelector::parse(["**"]).unwrap();
let selection = repo
.select_refs(&selector, Some(&selector), repo.implicit_reads(), None)
.await
.unwrap();
assert_eq!(names(selection.local), ["good", "real/main"]);
assert_eq!(
names(selection.collections["org.example.Other"].clone()),
["good", "real/main"]
);
let mut all: Vec<String> = repo
.list_all_refs()
.await
.unwrap()
.into_iter()
.map(|listed| listed.name)
.collect();
all.sort();
assert_eq!(
all,
[
"good",
"o:good",
"o:real/main",
"org.example.Other/good",
"org.example.Other/real/main",
"real/main",
]
);
});
}
#[test]
fn an_alias_to_an_absent_target_reads_as_absent() {
use std::os::unix::fs::symlink;
let root = Root::new("alias-absent");
let path = root.dir.join("repo");
let repo = ostrya_rt::block_on(archive_repo(&path));
let heads = path.join("refs/heads");
std::fs::write(heads.join("file"), ref_text(&Checksum::from_bytes([4; 32]))).unwrap();
symlink("nosuch", heads.join("gone")).unwrap();
symlink("file/below", heads.join("below")).unwrap();
ostrya_rt::block_on(async {
for name in ["gone", "below"] {
assert_eq!(
repo.resolve_ref_tip(&Ref::local(name)).await.unwrap(),
None,
"{name}"
);
assert_eq!(repo.resolve_rev(name, true).await.unwrap(), None);
assert!(matches!(
repo.resolve_rev(name, false).await,
Err(Error::RefNotFound(_))
));
}
assert_eq!(repo.list_refs(None).await.unwrap().len(), 1);
});
}
#[test]
fn a_ref_file_over_its_cap_fails_the_read() {
let root = Root::new("ref-cap");
let path = root.dir.join("repo");
let repo = ostrya_rt::block_on(archive_repo(&path));
let commit = Checksum::from_bytes([5; 32]);
let heads = path.join("refs/heads");
let padded = |len: usize| {
let mut text = ref_text(&commit);
text.push_str(&" ".repeat(len - text.len()));
text
};
std::fs::write(heads.join("x"), padded(4096)).unwrap();
ostrya_rt::block_on(async {
assert_eq!(
repo.resolve_ref_tip(&Ref::local("x")).await.unwrap(),
Some(commit)
);
assert_eq!(
repo.list_refs(None).await.unwrap(),
[("x".to_owned(), commit)]
);
std::fs::write(heads.join("x"), padded(4097)).unwrap();
let cap = "refs/heads/x is larger than its cap of 4096 bytes";
assert_invalid(repo.resolve_ref_tip(&Ref::local("x")).await, cap, "tip");
assert_invalid(repo.resolve_rev("x", false).await, cap, "rev");
assert_invalid(repo.list_refs(None).await, cap, "list");
assert_invalid(repo.list_all_refs().await, cap, "all");
std::os::unix::fs::symlink("x", heads.join("al")).unwrap();
assert_invalid(repo.resolve_ref_tip(&Ref::local("al")).await, cap, "alias");
});
}
#[test]
fn the_walk_of_the_head_names_gives_the_names_of_the_listing() {
use std::os::unix::fs::symlink;
let root = Root::new("head-names");
let path = root.dir.join("repo");
let repo = ostrya_rt::block_on(archive_repo(&path));
let commit = Checksum::from_bytes([8; 32]);
let heads = path.join("refs/heads");
std::fs::create_dir(heads.join("real")).unwrap();
std::fs::write(heads.join("real/main"), ref_text(&commit)).unwrap();
std::fs::write(heads.join("top"), ref_text(&commit)).unwrap();
symlink("real/main", heads.join("good")).unwrap();
symlink("good", heads.join("chain")).unwrap();
symlink("nosuch", heads.join("dangling")).unwrap();
symlink("real", heads.join("to-dir")).unwrap();
symlink("/dev/null", heads.join("null")).unwrap();
mkfifo(&heads.join("fifo"));
symlink("fifo", heads.join("to-fifo")).unwrap();
let short = root.dir.join("s");
let _socket = std::os::unix::net::UnixListener::bind(&short).unwrap();
std::fs::rename(&short, heads.join("sock")).unwrap();
ostrya_rt::block_on(async {
let listed: Vec<String> = repo
.list_refs(None)
.await
.unwrap()
.into_iter()
.map(|(name, _)| name)
.collect();
assert_eq!(listed, ["good", "real/main", "top"]);
assert_eq!(repo.list_head_names().await.unwrap(), listed);
std::fs::write(heads.join("junk"), b"junk\n").unwrap();
assert!(matches!(
repo.list_refs(None).await,
Err(Error::Core(ostrya_core::Error::InvalidChecksum(_)))
));
assert_eq!(
repo.list_head_names().await.unwrap(),
["good", "junk", "real/main", "top"]
);
});
}
#[test]
fn a_symlink_at_a_ref_directory_fails_the_read_and_the_write() {
use std::os::unix::fs::symlink;
let commit = Checksum::from_bytes([6; 32]);
let id = "org.example.Other";
for (dir, r) in [
("refs", Ref::local("main")),
(HEADS_DIR, Ref::local("main")),
("refs/remotes/o", Ref::remote("o", "main")),
(
"refs/mirrors/org.example.Other",
Ref::collection(id, "main"),
),
] {
let root = Root::new("ref-dir-link");
let path = root.dir.join("repo");
let repo = ostrya_rt::block_on(archive_repo(&path));
std::fs::create_dir_all(path.join(dir)).unwrap();
let rel = ref_relpath(None, &r).unwrap();
std::fs::create_dir_all(path.join(&rel).parent().unwrap()).unwrap();
std::fs::write(path.join(&rel), ref_text(&commit)).unwrap();
let real = root.dir.join("real");
std::fs::rename(path.join(dir), &real).unwrap();
symlink(&real, path.join(dir)).unwrap();
let symlinked = "passes through a symlink";
ostrya_rt::block_on(async {
assert_invalid(repo.resolve_ref_tip(&r).await, symlinked, dir);
assert_invalid(repo.list_all_refs().await, symlinked, dir);
let all = RefSelector::parse(["**"]).unwrap();
match dir {
"refs" | HEADS_DIR => {
assert_invalid(repo.list_refs(None).await, symlinked, dir);
assert_invalid(repo.list_refs_where(|_| true).await, symlinked, dir);
assert_invalid(repo.list_ref_aliases().await, symlinked, dir);
}
"refs/remotes/o" => {
let remotes =
BTreeMap::from([("o".to_owned(), "org.example.O".to_owned())]);
assert_invalid(collect_remote_collections(&repo, &remotes), symlinked, dir);
assert_invalid(repo.list_remote_refs().await, symlinked, dir);
assert_invalid(repo.list_ref_aliases().await, symlinked, dir);
}
_ => {
let listed = repo.list_collection_refs_in(id, &all).await;
assert_invalid(listed, symlinked, dir);
assert_invalid(repo.list_mirror_refs().await, symlinked, dir);
assert_invalid(repo.list_collection_refs().await, symlinked, dir);
assert_invalid(repo.list_refs_where(|_| true).await, symlinked, dir);
assert_invalid(repo.list_refs_where(|_| false).await, symlinked, dir);
let selected = repo
.select_refs(&all, Some(&all), repo.implicit_reads(), None)
.await;
assert_invalid(selected.map(|_| ()), symlinked, dir);
assert_invalid(repo.list_ref_aliases().await, symlinked, dir);
}
}
let written = repo.set_ref_immediate(&r, Some(&commit)).await;
match written {
Err(Error::RefNotWritable { reason, .. }) => {
assert_eq!(reason, PASSES_THROUGH_AN_ALIAS, "{dir}");
}
other => panic!("{dir}: {other:?}"),
}
});
}
}
#[test]
fn an_alias_write_refuses_a_target_that_is_an_alias() {
let root = Root::new("alias-write");
let path = root.dir.join("repo");
let repo = ostrya_rt::block_on(archive_repo(&path));
let heads = path.join("refs/heads");
ostrya_rt::block_on(async {
let commit = Checksum::from_bytes([8; 32]);
repo.set_ref_immediate(&Ref::local("main"), Some(&commit))
.await
.unwrap();
repo.set_ref_alias_immediate(&Ref::local("al1"), &Ref::local("main"))
.await
.unwrap();
std::fs::create_dir(heads.join("d")).unwrap();
std::os::unix::fs::symlink("d", heads.join("dl")).unwrap();
for (target, reason) in [
("al1", TARGETS_AN_ALIAS),
("al2", TARGETS_AN_ALIAS),
("dl/x", PASSES_THROUGH_AN_ALIAS),
] {
match repo
.set_ref_alias_immediate(&Ref::local("al2"), &Ref::local(target))
.await
{
Err(Error::RefNotWritable { name, reason: r }) => {
assert_eq!((name.as_str(), r.as_str()), ("al2", reason), "{target}");
}
other => panic!("{target}: {other:?}"),
}
assert!(
std::fs::symlink_metadata(heads.join("al2")).is_err(),
"{target}"
);
}
repo.set_ref_alias_immediate(&Ref::local("al3"), &Ref::local("nosuch"))
.await
.unwrap();
assert_eq!(
std::fs::read_link(heads.join("al3")).unwrap(),
std::path::Path::new("nosuch")
);
});
}
fn temp_entries(root: &std::path::Path) -> usize {
std::fs::read_dir(root.join("tmp"))
.unwrap()
.filter(|entry| {
let name = entry.as_ref().unwrap().file_name();
name.to_string_lossy().starts_with(".ostrya-tmp-")
})
.count()
}
#[test]
fn a_ref_write_puts_its_temp_file_in_tmp() {
let root = Root::new("temp-file");
let handle = root.handle();
let checksum = Some(Checksum::from_bytes([7; 32]));
let mut dirs = Vec::new();
put_ref_blocking(&handle, "a/x", "refs/heads/a/x", checksum, true, &mut dirs).unwrap();
assert_eq!(dirs, ["refs/heads/a"]);
assert_eq!(temp_entries(&root.dir), 0);
let long = "r".repeat(256);
let name = format!("new/deep/{long}");
let mut dirs = Vec::new();
let relpath = format!("refs/heads/{name}");
put_ref_blocking(&handle, &name, &relpath, checksum, true, &mut dirs).unwrap_err();
assert!(dirs.is_empty(), "{dirs:?}");
assert!(root.dir.join("refs/heads/new/deep").is_dir());
assert_eq!(temp_entries(&root.dir), 0);
}
#[test]
fn the_ref_listings_do_not_open_a_fifo_entry() {
let root = Root::new("listing-fifo");
let repo = ostrya_rt::block_on(Repo::create(
&root.dir.join("repo"),
crate::CreateOptions::new(RepoMode::Archive),
))
.unwrap();
let fifos: Vec<std::path::PathBuf> = [
"refs/heads/fifo",
"refs/remotes/o/fifo",
"refs/mirrors/org.example.Other/fifo",
]
.iter()
.map(|rel| {
let fifo = root.dir.join("repo").join(rel);
std::fs::create_dir_all(fifo.parent().unwrap()).unwrap();
rustix::fs::mknodat(
rustix::fs::CWD,
&fifo,
FileType::Fifo,
Mode::from_raw_mode(0o644),
0,
)
.unwrap();
fifo
})
.collect();
let (task_tx, task_rx) = std::sync::mpsc::channel();
let (open_tx, open_rx) = std::sync::mpsc::channel();
for fifo in &fifos {
let (task_tx, open_tx, fifo) = (task_tx.clone(), open_tx.clone(), fifo.clone());
std::thread::spawn(move || {
task_tx
.send(std::fs::read_link("/proc/thread-self").unwrap())
.unwrap();
let _ = rustix::fs::open(&fifo, OFlags::WRONLY | OFlags::CLOEXEC, Mode::empty());
let _ = open_tx.send(());
});
}
let release = |waiting: usize| {
let readers: Vec<_> = fifos
.iter()
.map(|fifo| {
rustix::fs::open(
fifo,
OFlags::RDONLY | OFlags::NONBLOCK | OFlags::CLOEXEC,
Mode::empty(),
)
.unwrap()
})
.collect();
for _ in 0..waiting {
let _ = open_rx.recv_timeout(std::time::Duration::from_secs(10));
}
drop(readers);
};
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
for _ in &fifos {
let task = task_rx
.recv_timeout(std::time::Duration::from_secs(10))
.unwrap();
let stat = std::path::Path::new("/proc").join(task).join("stat");
loop {
let text = std::fs::read_to_string(&stat).unwrap();
let state = text.rsplit_once(") ").map(|(_, rest)| &rest[..1]);
if state == Some("S") {
break;
}
if std::time::Instant::now() > deadline {
release(fifos.len());
panic!("a writer does not wait in its open: {text}");
}
std::thread::sleep(std::time::Duration::from_millis(5));
}
}
let remotes = BTreeMap::from([("o".to_owned(), "org.example.O".to_owned())]);
let heads = collect_heads(&repo, open_refs(&repo).unwrap().as_ref(), &|_| true);
let remote_refs = collect_remotes(&repo);
let remote_collections = collect_remote_collections(&repo, &remotes);
let mirrors = collect_mirrors(
&repo,
open_refs(&repo).unwrap().as_ref(),
&|_| false,
&|_| true,
);
let all = ostrya_rt::block_on(repo.list_all_refs());
std::thread::sleep(std::time::Duration::from_millis(200));
let ended = open_rx.try_iter().count();
release(fifos.len() - ended);
assert_eq!(ended, 0, "a listing opened a FIFO");
assert!(heads.unwrap().is_empty());
assert!(remote_refs.unwrap().is_empty());
assert!(remote_collections.unwrap().is_empty());
assert!(mirrors.unwrap().is_empty());
assert!(all.unwrap().is_empty());
}
#[test]
fn the_ref_listings_leave_out_a_special_entry_that_the_permissions_refuse() {
if rustix::process::geteuid().is_root() {
eprintln!("skipped: the root user opens a FIFO with mode 000");
return;
}
let root = Root::new("listing-locked");
let repo_dir = root.dir.join("repo");
let repo = ostrya_rt::block_on(Repo::create(
&repo_dir,
crate::CreateOptions::new(RepoMode::Archive),
))
.unwrap();
let commit = Checksum::from_bytes([1; 32]);
let dirs = [
"refs/heads",
"refs/remotes/o",
"refs/mirrors/org.example.Other",
];
for dir in dirs {
let dir = repo_dir.join(dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("main"), format!("{}\n", commit.to_hex())).unwrap();
rustix::fs::mknodat(
rustix::fs::CWD,
dir.join("locked"),
FileType::Fifo,
Mode::empty(),
0,
)
.unwrap();
}
let remotes = BTreeMap::from([("o".to_owned(), "org.example.O".to_owned())]);
assert_eq!(
collect_heads(&repo, open_refs(&repo).unwrap().as_ref(), &|_| true).unwrap(),
[("main".to_owned(), commit)]
);
assert_eq!(
collect_remotes(&repo).unwrap(),
[("o:main".to_owned(), commit)]
);
assert_eq!(
collect_remote_collections(&repo, &remotes).unwrap(),
[(
"o".to_owned(),
"org.example.O".to_owned(),
"main".to_owned(),
commit
)]
);
assert_eq!(
collect_mirrors(
&repo,
open_refs(&repo).unwrap().as_ref(),
&|_| false,
&|_| true
)
.unwrap(),
[("org.example.Other".to_owned(), "main".to_owned(), commit)]
);
let mut all: Vec<(String, Checksum)> = ostrya_rt::block_on(repo.list_all_refs())
.unwrap()
.into_iter()
.map(|listed| (listed.name, listed.checksum))
.collect();
all.sort();
assert_eq!(
all,
[
("main".to_owned(), commit),
("o:main".to_owned(), commit),
("org.example.Other/main".to_owned(), commit),
]
);
for dir in dirs {
let relpath = format!("{dir}/locked");
match read_ref(repo.root_dir(), "locked", &relpath) {
Err(Error::Io(e)) => {
assert_eq!(e.kind(), std::io::ErrorKind::PermissionDenied, "{dir}");
}
other => panic!("{dir}: {other:?}"),
}
}
}
const OWN: &str = "org.example.Os";
const NAME: &str = "os/stable";
async fn own_repo(path: &std::path::Path) -> Repo {
Repo::create(
path,
crate::CreateOptions::new(RepoMode::Archive).collection_id(OWN),
)
.await
.unwrap()
}
#[test]
fn the_implicit_read_access_takes_the_collection_id_of_the_repository() {
let root = Root::new("implicit-reads");
ostrya_rt::block_on(async {
let repo = own_repo(&root.dir.join("repo")).await;
let reads = repo.implicit_reads();
assert_eq!(reads.access().namespace(Some(OWN)), Namespace::Local);
assert!(reads.can_read_path(&format!("refs/heads/{NAME}")));
assert!(!reads.can_read_path(&format!("refs/mirrors/{OWN}/{NAME}")));
});
}
#[test]
fn a_collection_ref_of_the_own_id_maps_to_the_local_path() {
let path = |own, id, name| ref_relpath(own, &Ref::collection(id, name));
assert_eq!(
path(Some(OWN), OWN, NAME).unwrap(),
format!("refs/heads/{NAME}")
);
assert_eq!(
path(Some(OWN), "org.example.Other", NAME).unwrap(),
format!("refs/mirrors/org.example.Other/{NAME}")
);
assert_eq!(
path(None, OWN, NAME).unwrap(),
format!("refs/mirrors/{OWN}/{NAME}")
);
assert_eq!(
ref_relpath(Some(OWN), &Ref::local(NAME)).unwrap(),
format!("refs/heads/{NAME}")
);
assert_eq!(
ref_relpath(Some(OWN), &Ref::remote("origin", NAME)).unwrap(),
format!("refs/remotes/origin/{NAME}")
);
for name in ["../x", "origin:x"] {
let err = path(Some(OWN), OWN, name).unwrap_err();
assert!(
matches!(&err, Error::InvalidRefspec(label) if *label == format!("@{OWN}:{name}")),
"{err:?}"
);
}
}
#[test]
fn sync_dirs_all_runs_each_sync_past_a_failure() {
let root = Root::new("sync-all");
std::fs::create_dir_all(root.dir.join("refs/heads/a")).unwrap();
std::fs::write(root.dir.join("refs/heads/a/file"), b"").unwrap();
let dirs = vec![
".".to_owned(),
"refs/heads".to_owned(),
"refs/heads/a/file".to_owned(),
"refs/heads/a".to_owned(),
];
let before = test_syncs::count(&root.dir);
let err = sync_dirs_all(&root.handle(), dirs).unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(text) if text == "refs/heads/a/file is not a directory"),
"{err:?}"
);
assert_eq!(test_syncs::count(&root.dir), before + 4);
}
#[test]
fn a_failed_alias_write_leaves_no_temp_entry() {
let root = Root::new("alias-failed");
let handle = root.handle();
std::fs::write(root.dir.join("refs/heads/file"), b"").unwrap();
let mut dirs = Vec::new();
let err = put_alias_blocking(
&handle,
"file/deep/alias",
"refs/heads/file/deep/alias",
"refs/heads/main",
true,
&mut dirs,
)
.unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(text) if text.ends_with("is not a directory")),
"{err:?}"
);
assert!(dirs.is_empty());
std::fs::create_dir_all(root.dir.join("refs/heads/other/deep/alias/x")).unwrap();
let err = put_alias_blocking(
&handle,
"other/deep/alias",
"refs/heads/other/deep/alias",
"refs/heads/main",
true,
&mut dirs,
)
.unwrap_err();
assert!(matches!(&err, Error::Io(_)), "{err:?}");
assert!(dirs.is_empty());
assert_eq!(temp_entries(&root.dir), 0);
}
}