use std::io::{Read, Write};
use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use ostrya_core::{Checksum, RepoMode};
use rustix::fs::{AtFlags, FileType, Mode, OFlags};
use rustix::io::Errno;
use crate::error::{Error, Result};
use crate::perm;
use crate::repo::Repo;
use crate::transaction::Transaction;
use crate::traverse::read_dir_names;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CollectionRef {
pub collection_id: Option<String>,
pub ref_name: String,
}
impl CollectionRef {
pub fn new(collection_id: impl Into<String>, ref_name: impl Into<String>) -> CollectionRef {
CollectionRef {
collection_id: Some(collection_id.into()),
ref_name: ref_name.into(),
}
}
pub fn local(ref_name: impl Into<String>) -> CollectionRef {
CollectionRef {
collection_id: None,
ref_name: ref_name.into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RefAlias {
pub refspec: String,
pub target: String,
}
enum QueuedRef {
Ref(String),
Collection(CollectionRef),
}
impl QueuedRef {
fn relpath(&self) -> Result<String> {
match self {
QueuedRef::Ref(refspec) => refspec_to_relpath(refspec),
QueuedRef::Collection(cref) => collection_ref_to_relpath(cref),
}
}
}
pub(crate) struct RefWrite {
target: QueuedRef,
checksum: Option<Checksum>,
}
impl Transaction {
pub fn set_ref(&self, refspec: &str, checksum: Option<&Checksum>) {
self.refs.lock().unwrap().push(RefWrite {
target: QueuedRef::Ref(refspec.to_owned()),
checksum: checksum.copied(),
});
}
pub fn set_collection_ref(&self, cref: &CollectionRef, checksum: Option<&Checksum>) {
self.refs.lock().unwrap().push(RefWrite {
target: QueuedRef::Collection(cref.clone()),
checksum: checksum.copied(),
});
}
pub(crate) fn resolve_ref_queue(&self) -> Result<Vec<(String, Option<Checksum>)>> {
let queue = self.refs.lock().unwrap();
queue
.iter()
.map(|w| Ok((w.target.relpath()?, w.checksum)))
.collect()
}
pub(crate) async fn write_resolved_refs(
&self,
refs: &[(String, Option<Checksum>)],
) -> Result<()> {
if refs.is_empty() {
return Ok(());
}
let (fsync, _) = self.fsync_flags()?;
let repo_mode = self.repo().mode();
let repo_fd = self.repo().repo_fd().try_clone_to_owned()?;
let refs = refs.to_vec();
ostrya_rt::unblock(move || {
for (relpath, checksum) in &refs {
write_ref_blocking(repo_fd.as_fd(), relpath, *checksum, fsync, repo_mode)?;
}
Ok(())
})
.await
}
}
const REF_READ_CAP: u64 = 4096;
impl Repo {
pub async fn resolve_rev(&self, rev: &str, allow_noent: bool) -> Result<Option<Checksum>> {
let (base, generations) = split_ancestry(rev);
let Some(mut checksum) = 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))
}
async fn resolve_base_rev(&self, rev: &str, allow_noent: bool) -> Result<Option<Checksum>> {
if let Ok(checksum) = Checksum::from_hex_lower(rev) {
return Ok(Some(checksum));
}
if is_abbreviated_checksum(rev) {
let repo = self.clone();
let prefix = rev.to_owned();
match ostrya_rt::unblock(move || match_abbreviated(repo.objects_fd(), &prefix)).await? {
AbbrevMatch::One(checksum) => return Ok(Some(checksum)),
AbbrevMatch::Ambiguous => return Err(Error::AmbiguousRefspec(rev.to_owned())),
AbbrevMatch::None => {}
}
}
match self.resolve_ref_tip(rev).await? {
Some(checksum) => Ok(Some(checksum)),
None if allow_noent => Ok(None),
None => Err(Error::RefNotFound(rev.to_owned())),
}
}
pub async fn resolve_ref_tip(&self, refspec: &str) -> Result<Option<Checksum>> {
let relpath = refspec_to_relpath(refspec)?;
let repo = self.clone();
let bytes = ostrya_rt::unblock(move || read_ref_file(repo.repo_fd(), &relpath)).await?;
match bytes {
Some(bytes) => Ok(Some(parse_ref_content(&bytes)?)),
None => Ok(None),
}
}
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)).await?;
if let Some(prefix) = prefix {
let nested = format!("{prefix}/");
refs.retain(|(name, _)| name == prefix || name.starts_with(&nested));
}
refs.sort_by(|a, b| a.0.cmp(&b.0));
Ok(refs)
}
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)).await
}
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(|a, b| a.refspec.cmp(&b.refspec));
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 rustix::fs::statat(repo.repo_fd(), &path, AtFlags::SYMLINK_NOFOLLOW) {
Err(Errno::NOTDIR) => Err(Error::Io(Errno::NOTDIR.into())),
_ => Ok(()),
}
})
.await
}
pub async fn set_ref_immediate(
&self,
refspec: &str,
checksum: Option<&Checksum>,
) -> Result<()> {
let relpath = refspec_to_relpath(refspec)?;
self.write_ref_relpath(relpath, checksum).await
}
pub async fn set_collection_ref_immediate(
&self,
cref: &CollectionRef,
checksum: Option<&Checksum>,
) -> Result<()> {
let relpath = collection_ref_to_relpath(cref)?;
self.write_ref_relpath(relpath, checksum).await
}
async fn write_ref_relpath(&self, relpath: String, checksum: Option<&Checksum>) -> Result<()> {
let fsync = self.config().fsync()?;
let repo_mode = self.mode();
let checksum = checksum.copied();
let repo_fd = self.repo_fd().try_clone_to_owned()?;
ostrya_rt::unblock(move || {
write_ref_blocking(repo_fd.as_fd(), &relpath, checksum, fsync, repo_mode)
})
.await
}
pub async fn set_ref_alias_immediate(&self, refspec: &str, target: &str) -> Result<()> {
let fsync = self.config().fsync()?;
let repo_mode = self.mode();
let relpath = refspec_to_relpath(refspec)?;
let link = relative_link(&relpath, &refspec_to_relpath(target)?);
let repo_fd = self.repo_fd().try_clone_to_owned()?;
ostrya_rt::unblock(move || {
write_alias_blocking(repo_fd.as_fd(), &relpath, &link, fsync, repo_mode)
})
.await
}
}
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_fd: BorrowedFd<'_>, 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_fd, fanout, within, &mut found)? {
return Ok(AbbrevMatch::Ambiguous);
}
} else {
for fanout in read_dir_names(objects_fd)? {
if fanout.len() != 2 || !fanout.bytes().all(|b| b.is_ascii_hexdigit()) {
continue;
}
if !fanout.starts_with(prefix) {
continue;
}
if scan_fanout(objects_fd, &fanout, "", &mut found)? {
return Ok(AbbrevMatch::Ambiguous);
}
}
}
Ok(match found {
Some(checksum) => AbbrevMatch::One(checksum),
None => AbbrevMatch::None,
})
}
fn scan_fanout(
objects_fd: BorrowedFd<'_>,
fanout: &str,
within: &str,
found: &mut Option<Checksum>,
) -> Result<bool> {
let dir = match rustix::fs::openat(
objects_fd,
fanout,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
) {
Ok(fd) => fd,
Err(Errno::NOENT) => return Ok(false),
Err(e) => return Err(Error::Io(e.into())),
};
for entry in read_dir_names(dir.as_fd())? {
let Some(checksum) = 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()
}
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) -> Result<Vec<(String, Checksum)>> {
let Some(heads) = open_refs_dir(repo, "refs/heads")? else {
return Ok(Vec::new());
};
let mut out = Vec::new();
walk_ref_dir(heads.as_fd(), "", &mut |entry| {
if let Some(bytes) = read_ref_file(entry.dir, entry.name)? {
out.push((entry.path.to_owned(), parse_ref_content(&bytes)?));
}
Ok(())
})?;
Ok(out)
}
fn collect_remotes(repo: &Repo) -> Result<Vec<(String, Checksum)>> {
let Some(remotes) = open_refs_dir(repo, "refs/remotes")? else {
return Ok(Vec::new());
};
let mut out = Vec::new();
walk_ref_dir(remotes.as_fd(), "", &mut |entry| {
let Some(bytes) = read_ref_file(entry.dir, entry.name)? 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_aliases(repo: &Repo) -> Result<Vec<RefAlias>> {
let mut out = Vec::new();
if let Some(heads) = open_refs_dir(repo, "refs/heads")? {
walk_ref_dir(heads.as_fd(), "", &mut |entry| {
if let Some(target) = read_alias_target(&entry)? {
out.push(RefAlias {
refspec: entry.path.to_owned(),
target,
});
}
Ok(())
})?;
}
if let Some(remotes) = open_refs_dir(repo, "refs/remotes")? {
walk_ref_dir(remotes.as_fd(), "", &mut |entry| {
if let Some(target) = read_alias_target(&entry)?
&& let Some((remote, ref_name)) = entry.path.split_once('/')
{
out.push(RefAlias {
refspec: format!("{remote}:{ref_name}"),
target,
});
}
Ok(())
})?;
}
Ok(out)
}
fn open_refs_dir(repo: &Repo, relpath: &str) -> Result<Option<OwnedFd>> {
match rustix::fs::openat(
repo.repo_fd(),
relpath,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
) {
Ok(fd) => Ok(Some(fd)),
Err(Errno::NOENT) => Ok(None),
Err(e) => Err(Error::Io(e.into())),
}
}
fn collect_mirrors(repo: &Repo) -> Result<Vec<(String, String, Checksum)>> {
let Some(mirrors) = open_refs_dir(repo, "refs/mirrors")? else {
return Ok(Vec::new());
};
let mut out = Vec::new();
walk_ref_dir(mirrors.as_fd(), "", &mut |entry| {
let Some(bytes) = read_ref_file(entry.dir, entry.name)? 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: BorrowedFd<'a>,
pub(crate) name: &'a str,
pub(crate) path: &'a str,
pub(crate) file_type: FileType,
}
pub(crate) fn walk_ref_dir(
dir: BorrowedFd<'_>,
prefix: &str,
visit: &mut impl FnMut(RefEntry<'_>) -> Result<()>,
) -> Result<()> {
for name in read_dir_names(dir)? {
let stat = match rustix::fs::statat(dir, name.as_str(), AtFlags::SYMLINK_NOFOLLOW) {
Ok(stat) => stat,
Err(Errno::NOENT) => continue, Err(e) => return Err(Error::Io(e.into())),
};
let path = if prefix.is_empty() {
name.clone()
} else {
format!("{prefix}/{name}")
};
let file_type = FileType::from_raw_mode(stat.st_mode);
if file_type == FileType::Directory {
let sub = rustix::fs::openat(
dir,
name.as_str(),
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)
.map_err(|e| Error::Io(e.into()))?;
walk_ref_dir(sub.as_fd(), &path, visit)?;
} else {
visit(RefEntry {
dir,
name: &name,
path: &path,
file_type,
})?;
}
}
Ok(())
}
fn read_alias_target(entry: &RefEntry<'_>) -> Result<Option<String>> {
if entry.file_type != FileType::Symlink {
return Ok(None);
}
let target = rustix::fs::readlinkat(entry.dir, entry.name, Vec::new())
.map_err(|e| Error::Io(e.into()))?;
Ok(target.into_string().ok())
}
fn read_ref_file(
dir: rustix::fd::BorrowedFd<'_>,
relpath: &str,
) -> std::io::Result<Option<Vec<u8>>> {
let fd = match rustix::fs::openat(
dir,
relpath,
OFlags::RDONLY | OFlags::CLOEXEC,
Mode::empty(),
) {
Ok(fd) => fd,
Err(Errno::NOENT) => return Ok(None),
Err(e) => return Err(e.into()),
};
let mut buf = Vec::new();
std::fs::File::from(fd)
.take(REF_READ_CAP)
.read_to_end(&mut buf)?;
Ok(Some(buf))
}
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<()> {
refspec_to_relpath(refspec).map(drop)
}
fn refspec_to_relpath(refspec: &str) -> Result<String> {
if let Some((remote, name)) = refspec.split_once(':') {
if !is_component(remote) || !is_ref_path(name) {
return Err(Error::InvalidRefspec(refspec.to_owned()));
}
Ok(format!("refs/remotes/{remote}/{name}"))
} else {
if !is_ref_path(refspec) {
return Err(Error::InvalidRefspec(refspec.to_owned()));
}
Ok(format!("refs/heads/{refspec}"))
}
}
pub(crate) fn check_ref_path(name: &str) -> Result<()> {
if is_ref_path(name) {
Ok(())
} else {
Err(Error::InvalidRefspec(name.to_owned()))
}
}
fn is_ref_path(name: &str) -> bool {
!name.is_empty() && name.split('/').all(is_component)
}
fn is_component(component: &str) -> bool {
!(component.is_empty()
|| component == "."
|| component == ".."
|| component.contains('/')
|| component.contains('\0'))
}
fn collection_ref_to_relpath(cref: &CollectionRef) -> Result<String> {
let name = &cref.ref_name;
match &cref.collection_id {
Some(collection_id) => {
if !is_component(collection_id) || !is_ref_path(name) {
return Err(Error::InvalidRefspec(format!("{collection_id}:{name}")));
}
Ok(format!("refs/mirrors/{collection_id}/{name}"))
}
None => {
if !is_ref_path(name) {
return Err(Error::InvalidRefspec(name.to_owned()));
}
Ok(format!("refs/heads/{name}"))
}
}
}
const REF_FILE_MODE: u32 = 0o644;
const REF_DIR_MODE: u32 = 0o777;
fn write_ref_blocking(
repo_fd: BorrowedFd<'_>,
relpath: &str,
checksum: Option<Checksum>,
fsync: bool,
repo_mode: RepoMode,
) -> Result<()> {
let Some(checksum) = checksum else {
return match rustix::fs::unlinkat(repo_fd, relpath, AtFlags::empty()) {
Ok(()) => {
if fsync {
sync_ref_parent(repo_fd, relpath)?;
}
Ok(())
}
Err(Errno::NOENT) => Ok(()),
Err(e) => Err(e.into()),
};
};
let created = create_ref_parents(repo_fd, relpath, repo_mode)?;
let content = format!("{}\n", checksum.to_hex());
let tmp = format!(
"{relpath}.tmp-{}-{}",
std::process::id(),
crate::write::unique()
);
let fd = rustix::fs::openat(
repo_fd,
tmp.as_str(),
OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::CLOEXEC | OFlags::NOFOLLOW,
Mode::from_raw_mode(REF_FILE_MODE),
)?;
let write_and_rename = || -> Result<()> {
let mut file = std::fs::File::from(fd);
file.write_all(content.as_bytes())?;
file.flush()?;
rustix::fs::fchmod(file.as_fd(), Mode::from_raw_mode(REF_FILE_MODE))?;
if fsync {
rustix::fs::fdatasync(file.as_fd())?;
}
drop(file);
rustix::fs::renameat(repo_fd, tmp.as_str(), repo_fd, relpath)?;
if fsync {
sync_ref_parent(repo_fd, relpath)?;
sync_created_ref_parents(repo_fd, &created)?;
}
Ok(())
};
write_and_rename().inspect_err(|_| {
let _ = rustix::fs::unlinkat(repo_fd, tmp.as_str(), AtFlags::empty());
})
}
fn write_alias_blocking(
repo_fd: BorrowedFd<'_>,
relpath: &str,
link: &str,
fsync: bool,
repo_mode: RepoMode,
) -> Result<()> {
let created = create_ref_parents(repo_fd, relpath, repo_mode)?;
let tmp = format!(
"{relpath}.tmp-{}-{}",
std::process::id(),
crate::write::unique()
);
rustix::fs::symlinkat(link, repo_fd, tmp.as_str())?;
rustix::fs::renameat(repo_fd, tmp.as_str(), repo_fd, relpath).inspect_err(|_| {
let _ = rustix::fs::unlinkat(repo_fd, tmp.as_str(), AtFlags::empty());
})?;
if fsync {
sync_ref_parent(repo_fd, relpath)?;
sync_created_ref_parents(repo_fd, &created)?;
}
Ok(())
}
fn sync_ref_parent(repo_fd: BorrowedFd<'_>, relpath: &str) -> Result<()> {
let parent = relpath.rsplit_once('/').map_or(".", |(dir, _)| dir);
let dir = rustix::fs::openat(
repo_fd,
parent,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)?;
rustix::fs::fsync(dir.as_fd())?;
Ok(())
}
fn create_ref_parents(
repo_fd: BorrowedFd<'_>,
relpath: &str,
repo_mode: RepoMode,
) -> Result<Vec<String>> {
let mut created = Vec::new();
let mut acc = String::new();
let mut components: Vec<&str> = relpath.split('/').collect();
components.pop(); for component in components {
if !acc.is_empty() {
acc.push('/');
}
acc.push_str(component);
match rustix::fs::mkdirat(repo_fd, acc.as_str(), Mode::from_raw_mode(REF_DIR_MODE)) {
Ok(()) => {
perm::force_created_dir(repo_fd, acc.as_str(), repo_mode)?;
created.push(acc.clone());
}
Err(Errno::EXIST) => {}
Err(e) => return Err(e.into()),
}
}
Ok(created)
}
fn sync_created_ref_parents(repo_fd: BorrowedFd<'_>, created: &[String]) -> Result<()> {
for dir in created.iter().rev() {
sync_ref_parent(repo_fd, dir)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
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: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());
}
#[test]
fn collection_ref_names_the_pair_it_rejects() {
let err = collection_ref_to_relpath(&CollectionRef::new("org.example.Foo", "a/../b"))
.unwrap_err();
assert!(
matches!(&err, Error::InvalidRefspec(name) if name == "org.example.Foo:a/../b"),
"{err}"
);
let err = collection_ref_to_relpath(&CollectionRef::local("a/../b")).unwrap_err();
assert!(
matches!(&err, Error::InvalidRefspec(name) if name == "a/../b"),
"{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"
);
}
#[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());
}
}