use std::fmt;
use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use std::sync::{Arc, OnceLock};
use ostrya_core::{Checksum, ObjectType, RepoMode};
use rustix::fs::{AtFlags, FileType, Statx, StatxAttributes, StatxFlags};
use rustix::io::Errno;
use crate::error::Error;
mod dir;
mod lock;
mod named;
mod read;
mod temp;
mod write;
pub(crate) use dir::list_fd;
pub(crate) use lock::{try_lock, unlock};
pub(crate) use named::{Named, ensure_named_dir, open_named, put_named, remove_named};
pub(crate) use read::{link_xattrs_at, verity_digest, xattr, xattrs};
pub(crate) use temp::{TempFile, TempLink};
pub(crate) use write::{Cloned, clone_or_copy, link, rename};
#[derive(Debug)]
pub(crate) enum FsError {
Absent {
path: String,
},
Exists,
Invalid {
path: String,
reason: Reason,
},
Io(std::io::Error),
}
#[derive(Debug, Clone, Copy)]
pub(crate) enum Reason {
Symlink,
Escape,
NotDirectory,
NotRegular(FileType),
TooLarge {
cap: u64,
},
ParentDir,
}
impl fmt::Display for Reason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Reason::Symlink => {
f.write_str("passes through a symlink; ostrya refuses a symlink in the repository")
}
Reason::Escape => f.write_str("resolves outside the repository"),
Reason::NotDirectory => f.write_str("is not a directory"),
Reason::NotRegular(_) => f.write_str("is not a regular file"),
Reason::TooLarge { cap } => write!(f, "is larger than its cap of {cap} bytes"),
Reason::ParentDir => {
f.write_str("has a `..` component, which a relative path in a config cannot have")
}
}
}
}
impl FsError {
pub(crate) fn at(errno: Errno, path: String) -> FsError {
let reason = match errno {
Errno::NOENT => return FsError::Absent { path },
Errno::EXIST => return FsError::Exists,
Errno::LOOP => Reason::Symlink,
Errno::XDEV => Reason::Escape,
Errno::NOTDIR => Reason::NotDirectory,
other => return FsError::Io(other.into()),
};
FsError::Invalid { path, reason }
}
pub(crate) fn into_object_error(self, checksum: &Checksum, ty: ObjectType) -> Error {
match self {
FsError::Absent { .. } => Error::ObjectNotFound {
checksum: *checksum,
ty,
},
other => other.into(),
}
}
}
impl From<FsError> for Error {
fn from(err: FsError) -> Error {
match err {
FsError::Io(e) => Error::Io(e),
FsError::Invalid { path, reason } => Error::InvalidFormat(format!("{path} {reason}")),
FsError::Absent { path } => Error::Io(std::io::Error::new(
std::io::ErrorKind::NotFound,
format!("{path} does not exist"),
)),
FsError::Exists => Error::Io(std::io::Error::from(Errno::EXIST)),
}
}
}
pub(crate) trait FsResultExt<T> {
fn optional(self) -> Result<Option<T>, FsError>;
fn optional_dir(self) -> Result<Option<T>, FsError>;
fn optional_walked_dir(self) -> Result<Option<T>, FsError>;
fn optional_ref(self, name: &str) -> Result<Option<T>, Error>;
}
impl<T> FsResultExt<T> for Result<T, FsError> {
fn optional(self) -> Result<Option<T>, FsError> {
match self {
Ok(value) => Ok(Some(value)),
Err(FsError::Absent { .. }) => Ok(None),
Err(err) => Err(err),
}
}
fn optional_dir(self) -> Result<Option<T>, FsError> {
match self {
Err(FsError::Invalid {
reason: Reason::NotDirectory,
..
}) => Ok(None),
other => other.optional(),
}
}
fn optional_walked_dir(self) -> Result<Option<T>, FsError> {
match self {
Err(FsError::Invalid {
reason: Reason::Symlink,
..
}) => Ok(None),
other => other.optional_dir(),
}
}
fn optional_ref(self, name: &str) -> Result<Option<T>, Error> {
match self {
Ok(value) => Ok(Some(value)),
Err(
FsError::Absent { .. }
| FsError::Invalid {
reason: Reason::NotDirectory,
..
},
) => Ok(None),
Err(FsError::Invalid {
reason: Reason::NotRegular(_),
..
}) => Err(Error::NotARef {
name: name.to_owned(),
reason: "is not a regular file".to_owned(),
}),
Err(err) => Err(err.into()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum RepoLayout {
Root,
Objects,
Staging,
Tmp,
Refs,
State,
Extensions,
Deltas,
DeltaIndexes,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum TempHome {
Tmp,
OwnDir,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct LayoutRules {
pub(crate) path: Option<&'static str>,
pub(crate) dir_mode: u32,
pub(crate) below_mode: Option<u32>,
pub(crate) file_mode: Option<u32>,
pub(crate) shared_dir_mode: u32,
pub(crate) shared_file_mode: Option<u32>,
pub(crate) temp_home: TempHome,
pub(crate) init_children: &'static [&'static str],
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) created_at_init: bool,
}
impl RepoLayout {
pub(crate) const fn rules(self) -> LayoutRules {
match self {
RepoLayout::Root => LayoutRules {
path: None,
dir_mode: 0o775,
below_mode: None,
file_mode: None,
shared_dir_mode: 0o2770,
shared_file_mode: None,
temp_home: TempHome::Tmp,
init_children: &[],
created_at_init: true,
},
RepoLayout::Objects => LayoutRules {
path: Some("objects"),
dir_mode: 0o775,
below_mode: Some(0o777),
file_mode: None,
shared_dir_mode: 0o2770,
shared_file_mode: None,
temp_home: TempHome::Tmp,
init_children: &[],
created_at_init: true,
},
RepoLayout::Staging => LayoutRules {
path: None,
dir_mode: 0o775,
below_mode: None,
file_mode: None,
shared_dir_mode: 0o2770,
shared_file_mode: None,
temp_home: TempHome::OwnDir,
init_children: &[],
created_at_init: false,
},
RepoLayout::Tmp => LayoutRules {
path: Some("tmp"),
dir_mode: 0o775,
below_mode: Some(0o775),
file_mode: Some(0o600),
shared_dir_mode: 0o2770,
shared_file_mode: Some(0o660),
temp_home: TempHome::OwnDir,
init_children: &["cache"],
created_at_init: true,
},
RepoLayout::Refs => LayoutRules {
path: Some("refs"),
dir_mode: 0o775,
below_mode: Some(0o777),
file_mode: Some(0o644),
shared_dir_mode: 0o2770,
shared_file_mode: Some(0o644),
temp_home: TempHome::Tmp,
init_children: &["heads", "remotes", "mirrors"],
created_at_init: true,
},
RepoLayout::State => LayoutRules {
path: Some("state"),
dir_mode: 0o775,
below_mode: None,
file_mode: Some(0o644),
shared_dir_mode: 0o2770,
shared_file_mode: Some(0o644),
temp_home: TempHome::Tmp,
init_children: &[],
created_at_init: true,
},
RepoLayout::Extensions => LayoutRules {
path: Some("extensions"),
dir_mode: 0o775,
below_mode: Some(0o775),
file_mode: Some(0o644),
shared_dir_mode: 0o2770,
shared_file_mode: Some(0o644),
temp_home: TempHome::Tmp,
init_children: &[],
created_at_init: true,
},
RepoLayout::Deltas => LayoutRules {
path: Some("deltas"),
dir_mode: 0o755,
below_mode: Some(0o755),
file_mode: Some(0o644),
shared_dir_mode: 0o2770,
shared_file_mode: Some(0o640),
temp_home: TempHome::Tmp,
init_children: &[],
created_at_init: false,
},
RepoLayout::DeltaIndexes => LayoutRules {
path: Some("delta-indexes"),
dir_mode: 0o755,
below_mode: Some(0o755),
file_mode: Some(0o644),
shared_dir_mode: 0o2770,
shared_file_mode: Some(0o640),
temp_home: TempHome::Tmp,
init_children: &[],
created_at_init: false,
},
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum RootFile {
Config,
Summary,
SummarySig,
Lock,
UpdateLock,
#[cfg_attr(not(feature = "verify-gpg"), allow(dead_code))]
Keyring(String),
}
impl RootFile {
pub(crate) fn name(&self) -> &str {
match self {
RootFile::Config => "config",
RootFile::Summary => "summary",
RootFile::SummarySig => "summary.sig",
RootFile::Lock => ".lock",
RootFile::UpdateLock => ".update.lock",
RootFile::Keyring(name) => {
debug_assert!(
!name.is_empty() && !name.contains('/') && name != "." && name != "..",
"a keyring name is one path component: {name:?}"
);
name
}
}
}
pub(crate) fn file_mode(&self) -> u32 {
match self {
RootFile::Lock | RootFile::UpdateLock => 0o660,
RootFile::Config | RootFile::Summary | RootFile::SummarySig | RootFile::Keyring(_) => {
0o644
}
}
}
pub(crate) fn shared_file_mode(&self) -> u32 {
match self {
RootFile::Lock | RootFile::UpdateLock => 0o660,
RootFile::Config | RootFile::Summary | RootFile::SummarySig | RootFile::Keyring(_) => {
0o644
}
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct RepoDir {
fd: Arc<OwnedFd>,
kind: RepoLayout,
ctx: Arc<RepoContext>,
path: DirPath,
}
#[derive(Debug, Clone)]
enum DirPath {
Fixed(&'static str),
Nested {
base: &'static str,
rel: Arc<str>,
},
}
#[derive(Debug)]
struct RepoContext {
root: Arc<OwnedFd>,
tmp: OnceLock<Arc<OwnedFd>>,
mode: Option<RepoMode>,
}
impl RepoDir {
pub(crate) fn from_root_fd(fd: OwnedFd) -> RepoDir {
let fd = Arc::new(fd);
RepoDir {
ctx: Arc::new(RepoContext {
root: Arc::clone(&fd),
tmp: OnceLock::new(),
mode: None,
}),
fd,
kind: RepoLayout::Root,
path: DirPath::Fixed(""),
}
}
pub(crate) fn with_repo_mode(mut self, mode: RepoMode) -> RepoDir {
if let Some(ctx) = Arc::get_mut(&mut self.ctx) {
ctx.mode = Some(mode);
return self;
}
RepoDir {
ctx: Arc::new(RepoContext {
root: Arc::clone(&self.ctx.root),
tmp: self.ctx.tmp.clone(),
mode: Some(mode),
}),
fd: self.fd,
kind: self.kind,
path: self.path,
}
}
pub(crate) fn kind(&self) -> RepoLayout {
self.kind
}
#[cfg(test)]
pub(crate) fn repo_mode(&self) -> Option<RepoMode> {
self.ctx.mode
}
pub(crate) fn file_mode(&self) -> Option<u32> {
let rules = self.kind.rules();
if self.ctx.is_shared() {
rules.shared_file_mode
} else {
rules.file_mode
}
}
}
impl AsFd for RepoDir {
fn as_fd(&self) -> BorrowedFd<'_> {
self.fd.as_fd()
}
}
const _: fn() = || {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<RepoDir>();
assert_send_sync::<FsError>();
assert_send_sync::<Opened>();
assert_send_sync::<ObjectEntry>();
assert_send_sync::<TempFile>();
assert_send_sync::<TempLink>();
assert_send_sync::<Publish>();
assert_send_sync::<Published>();
};
#[derive(Debug, Clone, Copy)]
pub(crate) struct Stat {
pub(crate) file_type: FileType,
pub(crate) mode: u32,
pub(crate) uid: u32,
pub(crate) gid: u32,
pub(crate) size: u64,
pub(crate) dev: u64,
pub(crate) ino: u64,
pub(crate) mtime_sec: i64,
pub(crate) mtime_nsec: u32,
pub(crate) ctime_sec: i64,
pub(crate) ctime_nsec: u32,
pub(crate) verity: bool,
}
#[derive(Debug)]
pub(crate) struct Entry {
pub(crate) name: Vec<u8>,
pub(crate) file_type: FileType,
}
#[derive(Debug)]
pub(crate) struct Opened {
pub(crate) file: std::fs::File,
pub(crate) stat: Stat,
}
#[derive(Debug)]
pub(crate) enum ObjectEntry {
Regular(Opened),
Symlink(Vec<u8>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Publish {
KeepExisting,
Replace,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Published {
Created,
Existed,
}
const STAT_FIELDS: StatxFlags = StatxFlags::TYPE
.union(StatxFlags::MODE)
.union(StatxFlags::UID)
.union(StatxFlags::GID)
.union(StatxFlags::SIZE)
.union(StatxFlags::INO)
.union(StatxFlags::MTIME)
.union(StatxFlags::CTIME);
pub(crate) fn stat_fd(fd: BorrowedFd<'_>) -> Result<Stat, FsError> {
let stx = rustix::fs::statx(fd, "", AtFlags::EMPTY_PATH, STAT_FIELDS)
.map_err(|errno| FsError::Io(errno.into()))?;
Ok(stat_from_statx(&stx))
}
pub(crate) fn fs_space(fd: BorrowedFd<'_>) -> Result<(u64, u64), FsError> {
let stat = rustix::fs::fstatvfs(fd).map_err(|errno| FsError::Io(errno.into()))?;
Ok((
stat.f_bavail.saturating_mul(stat.f_frsize),
stat.f_blocks.saturating_mul(stat.f_frsize),
))
}
fn stat_from_statx(stx: &Statx) -> Stat {
let mode = u32::from(stx.stx_mode);
Stat {
file_type: FileType::from_raw_mode(mode),
mode,
uid: stx.stx_uid,
gid: stx.stx_gid,
size: stx.stx_size,
dev: rustix::fs::makedev(stx.stx_dev_major, stx.stx_dev_minor),
ino: stx.stx_ino,
mtime_sec: stx.stx_mtime.tv_sec,
mtime_nsec: stx.stx_mtime.tv_nsec,
ctime_sec: stx.stx_ctime.tv_sec,
ctime_nsec: stx.stx_ctime.tv_nsec,
verity: stx.stx_attributes.contains(StatxAttributes::VERITY),
}
}
#[cfg(test)]
pub(crate) struct TestDir {
path: std::path::PathBuf,
fd: OwnedFd,
}
#[cfg(test)]
impl TestDir {
pub(crate) fn new(tag: &str) -> TestDir {
TestDir::new_in(&std::env::temp_dir(), tag)
}
pub(crate) fn new_in(base: &std::path::Path, tag: &str) -> TestDir {
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(0);
let n = NEXT.fetch_add(1, Ordering::Relaxed);
let path = base.join(format!("ostrya-repo-fs-{tag}-{}-{n}", std::process::id()));
std::fs::create_dir(&path).unwrap();
let fd = rustix::fs::open(
&path,
rustix::fs::OFlags::RDONLY
| rustix::fs::OFlags::DIRECTORY
| rustix::fs::OFlags::CLOEXEC,
rustix::fs::Mode::empty(),
)
.unwrap();
TestDir { path, fd }
}
pub(crate) fn path(&self) -> &std::path::Path {
&self.path
}
pub(crate) fn fd(&self) -> BorrowedFd<'_> {
self.fd.as_fd()
}
}
#[cfg(test)]
impl Drop for TestDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.path);
}
}
#[cfg(test)]
fn root(dir: &TestDir) -> RepoDir {
RepoDir::from_root_fd(rustix::io::dup(dir.fd()).unwrap())
}
#[cfg(test)]
fn invalid<T: fmt::Debug>(result: Result<T, FsError>) -> (String, Reason) {
match result {
Err(FsError::Invalid { path, reason }) => (path, reason),
other => panic!("{other:?}"),
}
}
#[cfg(test)]
fn io_err<T: fmt::Debug>(result: Result<T, FsError>) -> std::io::Error {
match result {
Err(FsError::Io(e)) => e,
other => panic!("{other:?}"),
}
}
#[cfg(test)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FaultStep {
Open,
Fchmod,
}
#[cfg(test)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HookPoint {
Descend,
Walk,
Getdents,
Entry,
TempName,
NamedCreated,
Tmpfile,
LockOpen,
LockCreate,
}
#[cfg(test)]
type Hook = Box<dyn FnMut(&[u8])>;
#[cfg(test)]
#[derive(Default)]
struct Faults {
fail_after_mkdir: Option<(FaultStep, Errno)>,
force_eexist: bool,
no_tmpfile: bool,
no_rename_noreplace: bool,
reflink_error: Option<Errno>,
hooks: Vec<(HookPoint, Hook)>,
unknown_type: bool,
synced: Option<Vec<(u64, u64)>>,
}
#[cfg(test)]
thread_local! {
static FAULTS: std::cell::RefCell<Faults> = std::cell::RefCell::default();
}
#[cfg(test)]
struct FaultReset;
#[cfg(test)]
impl Drop for FaultReset {
fn drop(&mut self) {
FAULTS.with(|f| *f.borrow_mut() = Faults::default());
}
}
#[cfg(test)]
fn set_faults(set: impl FnOnce(&mut Faults)) -> FaultReset {
FAULTS.with(|f| set(&mut f.borrow_mut()));
FaultReset
}
#[cfg(test)]
fn set_hook(point: HookPoint, hook: impl FnMut(&[u8]) + 'static) -> FaultReset {
set_faults(|f| f.hooks.push((point, Box::new(hook))))
}
#[cfg(test)]
fn record_syncs() -> FaultReset {
set_faults(|f| f.synced = Some(Vec::new()))
}
#[cfg(test)]
fn take_synced() -> Vec<(u64, u64)> {
FAULTS.with(|f| {
f.borrow_mut()
.synced
.as_mut()
.map(std::mem::take)
.expect("the thread records its syncs")
})
}
#[cfg(test)]
fn refs(dir: &TestDir) -> RepoDir {
root(dir).ensure_layout(RepoLayout::Refs, false).unwrap()
}
#[cfg(test)]
fn temp_names(dir: &TestDir) -> Vec<String> {
names_with(&dir.path().join("tmp"), temp::TEMP_PREFIX)
}
#[cfg(test)]
fn names_with(path: &std::path::Path, prefix: &str) -> Vec<String> {
std::fs::read_dir(path)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.filter(|name| name.starts_with(prefix))
.collect()
}
#[cfg(test)]
fn mode_of(path: &std::path::Path) -> u32 {
use std::os::unix::fs::MetadataExt;
std::fs::symlink_metadata(path).unwrap().mode() & 0o7777
}
#[cfg(test)]
fn id_of(path: &std::path::Path) -> (u64, u64) {
use std::os::unix::fs::MetadataExt;
let meta = std::fs::symlink_metadata(path).unwrap();
(meta.dev(), meta.ino())
}
#[cfg(test)]
fn is_symlink(path: &std::path::Path) -> bool {
std::fs::symlink_metadata(path)
.unwrap()
.file_type()
.is_symlink()
}
#[cfg(test)]
fn reference_mode(parent: &std::path::Path, request: u32) -> u32 {
use std::os::unix::fs::DirBuilderExt;
let path = parent.join(".reference-mode");
std::fs::DirBuilder::new()
.mode(request)
.create(&path)
.unwrap();
let mode = mode_of(&path);
std::fs::remove_dir(&path).unwrap();
mode
}
#[cfg(test)]
fn reference_file_mode(parent: &std::path::Path, request: u32) -> u32 {
use std::os::unix::fs::OpenOptionsExt;
let path = parent.join(".reference-file-mode");
std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(request)
.open(&path)
.unwrap();
let mode = mode_of(&path);
std::fs::remove_file(&path).unwrap();
mode
}
#[cfg(test)]
fn mkfifo(path: &std::path::Path) {
rustix::fs::mknodat(
rustix::fs::CWD,
path,
FileType::Fifo,
rustix::fs::Mode::from_raw_mode(0o600),
0,
)
.unwrap();
}
#[cfg(test)]
fn without_block<T: Send + 'static>(
fifo: &std::path::Path,
f: impl FnOnce() -> T + Send + 'static,
) -> T {
use std::sync::mpsc::{self, RecvTimeoutError};
use std::time::Duration;
let (tx, rx) = mpsc::channel();
let worker = std::thread::spawn(move || {
let _ = tx.send(f());
});
match rx.recv_timeout(Duration::from_secs(10)) {
Ok(value) => {
worker.join().unwrap();
value
}
Err(RecvTimeoutError::Disconnected) => match worker.join() {
Err(panic) => std::panic::resume_unwind(panic),
Ok(()) => unreachable!("the worker sends a value before it ends"),
},
Err(RecvTimeoutError::Timeout) => {
let _ = rustix::fs::open(
fifo,
rustix::fs::OFlags::WRONLY
| rustix::fs::OFlags::NONBLOCK
| rustix::fs::OFlags::CLOEXEC,
rustix::fs::Mode::empty(),
);
panic!("a read of the FIFO {} blocked", fifo.display());
}
}
}
#[cfg(test)]
mod tests {
use std::os::fd::AsRawFd;
use std::os::unix::fs::MetadataExt;
use rustix::fs::{Mode, OFlags};
use super::*;
const ALL_LAYOUTS: [RepoLayout; 9] = [
RepoLayout::Root,
RepoLayout::Objects,
RepoLayout::Staging,
RepoLayout::Tmp,
RepoLayout::Refs,
RepoLayout::State,
RepoLayout::Extensions,
RepoLayout::Deltas,
RepoLayout::DeltaIndexes,
];
fn checksum() -> Checksum {
Checksum::from_hex(&"ab".repeat(32)).unwrap()
}
fn has_errno(err: &Error, errno: Errno) -> bool {
matches!(err, Error::Io(e) if e.raw_os_error() == Some(errno.raw_os_error()))
}
fn reason_cases() -> [(Reason, &'static str); 7] {
[
(
Reason::Symlink,
"passes through a symlink; ostrya refuses a symlink in the repository",
),
(Reason::Escape, "resolves outside the repository"),
(Reason::NotDirectory, "is not a directory"),
(
Reason::NotRegular(FileType::Directory),
"is not a regular file",
),
(
Reason::TooLarge { cap: 1024 },
"is larger than its cap of 1024 bytes",
),
(
Reason::TooLarge { cap: u64::MAX },
"is larger than its cap of 18446744073709551615 bytes",
),
(
Reason::ParentDir,
"has a `..` component, which a relative path in a config cannot have",
),
]
}
fn invalid(path: &str, reason: Reason) -> FsError {
FsError::Invalid {
path: path.to_owned(),
reason,
}
}
fn absent(path: &str) -> FsError {
FsError::Absent {
path: path.to_owned(),
}
}
#[test]
fn each_errno_maps_to_its_kind_and_keeps_the_path() {
let path = "refs/heads/main";
assert!(matches!(
FsError::at(Errno::NOENT, path.to_owned()),
FsError::Absent { path: p } if p == path
));
assert!(matches!(
FsError::at(Errno::EXIST, path.to_owned()),
FsError::Exists
));
assert!(matches!(
FsError::at(Errno::LOOP, path.to_owned()),
FsError::Invalid { path: p, reason: Reason::Symlink } if p == path
));
assert!(matches!(
FsError::at(Errno::XDEV, path.to_owned()),
FsError::Invalid { path: p, reason: Reason::Escape } if p == path
));
assert!(matches!(
FsError::at(Errno::NOTDIR, path.to_owned()),
FsError::Invalid { path: p, reason: Reason::NotDirectory } if p == path
));
for errno in [Errno::NOSYS, Errno::PERM, Errno::ACCESS, Errno::NXIO] {
match FsError::at(errno, path.to_owned()) {
FsError::Io(e) => assert_eq!(e.raw_os_error(), Some(errno.raw_os_error())),
other => panic!("{errno:?} gave {other:?}"),
}
}
}
#[test]
fn layout_paths() {
let expected: [(RepoLayout, Option<&str>); 9] = [
(RepoLayout::Root, None),
(RepoLayout::Objects, Some("objects")),
(RepoLayout::Staging, None),
(RepoLayout::Tmp, Some("tmp")),
(RepoLayout::Refs, Some("refs")),
(RepoLayout::State, Some("state")),
(RepoLayout::Extensions, Some("extensions")),
(RepoLayout::Deltas, Some("deltas")),
(RepoLayout::DeltaIndexes, Some("delta-indexes")),
];
for (kind, path) in expected {
assert_eq!(kind.rules().path, path, "path of {kind:?}");
}
}
#[test]
fn layout_modes() {
let expected: [(RepoLayout, u32, Option<u32>, Option<u32>); 9] = [
(RepoLayout::Root, 0o775, None, None),
(RepoLayout::Objects, 0o775, Some(0o777), None),
(RepoLayout::Staging, 0o775, None, None),
(RepoLayout::Tmp, 0o775, Some(0o775), Some(0o600)),
(RepoLayout::Refs, 0o775, Some(0o777), Some(0o644)),
(RepoLayout::State, 0o775, None, Some(0o644)),
(RepoLayout::Extensions, 0o775, Some(0o775), Some(0o644)),
(RepoLayout::Deltas, 0o755, Some(0o755), Some(0o644)),
(RepoLayout::DeltaIndexes, 0o755, Some(0o755), Some(0o644)),
];
for (kind, dir, below, file) in expected {
let rules = kind.rules();
assert_eq!(rules.dir_mode, dir, "dir mode of {kind:?}");
assert_eq!(rules.below_mode, below, "below mode of {kind:?}");
assert_eq!(rules.file_mode, file, "file mode of {kind:?}");
}
}
#[test]
fn layout_shared_modes() {
let expected: [(RepoLayout, Option<u32>); 9] = [
(RepoLayout::Root, None),
(RepoLayout::Objects, None),
(RepoLayout::Staging, None),
(RepoLayout::Tmp, Some(0o660)),
(RepoLayout::Refs, Some(0o644)),
(RepoLayout::State, Some(0o644)),
(RepoLayout::Extensions, Some(0o644)),
(RepoLayout::Deltas, Some(0o640)),
(RepoLayout::DeltaIndexes, Some(0o640)),
];
for (kind, file) in expected {
let rules = kind.rules();
assert_eq!(rules.shared_dir_mode, 0o2770, "shared dir mode of {kind:?}");
assert_eq!(rules.shared_file_mode, file, "shared file mode of {kind:?}");
}
}
#[test]
fn layout_temp_homes() {
for kind in ALL_LAYOUTS {
let expected = match kind {
RepoLayout::Staging | RepoLayout::Tmp => TempHome::OwnDir,
_ => TempHome::Tmp,
};
assert_eq!(kind.rules().temp_home, expected, "temp home of {kind:?}");
}
}
#[test]
fn layout_init_children_and_created_at_init() {
let expected: [(RepoLayout, &[&str], bool); 9] = [
(RepoLayout::Root, &[], true),
(RepoLayout::Objects, &[], true),
(RepoLayout::Staging, &[], false),
(RepoLayout::Tmp, &["cache"], true),
(RepoLayout::Refs, &["heads", "remotes", "mirrors"], true),
(RepoLayout::State, &[], true),
(RepoLayout::Extensions, &[], true),
(RepoLayout::Deltas, &[], false),
(RepoLayout::DeltaIndexes, &[], false),
];
for (kind, children, at_init) in expected {
let rules = kind.rules();
assert_eq!(rules.init_children, children, "init children of {kind:?}");
assert_eq!(rules.created_at_init, at_init, "created at init: {kind:?}");
}
}
#[test]
fn root_files_have_their_names_and_modes() {
let expected: [(RootFile, &str, u32, u32); 7] = [
(RootFile::Config, "config", 0o644, 0o644),
(RootFile::Summary, "summary", 0o644, 0o644),
(RootFile::SummarySig, "summary.sig", 0o644, 0o644),
(RootFile::Lock, ".lock", 0o660, 0o660),
(RootFile::UpdateLock, ".update.lock", 0o660, 0o660),
(
RootFile::Keyring("origin.trustedkeys.gpg".into()),
"origin.trustedkeys.gpg",
0o644,
0o644,
),
(
RootFile::Keyring("gpgkeys.gpg".into()),
"gpgkeys.gpg",
0o644,
0o644,
),
];
for (file, name, mode, shared) in expected {
assert_eq!(file.name(), name);
assert_eq!(file.file_mode(), mode, "mode of {name}");
assert_eq!(file.shared_file_mode(), shared, "shared mode of {name}");
}
}
#[test]
fn an_absent_entry_gives_not_found_with_the_path() {
let err = Error::from(absent("state/x"));
match &err {
Error::Io(e) => {
assert_eq!(e.kind(), std::io::ErrorKind::NotFound);
assert_eq!(e.raw_os_error(), None);
assert_eq!(e.to_string(), "state/x does not exist");
}
other => panic!("{other:?}"),
}
}
#[test]
fn an_invalid_entry_gives_invalid_format_with_the_path_and_the_reason() {
for (reason, text) in reason_cases() {
assert_eq!(reason.to_string(), text);
let err = Error::from(invalid("state/x", reason));
let expected = format!("state/x {text}");
assert!(
matches!(&err, Error::InvalidFormat(m) if *m == expected),
"{err:?}"
);
}
}
#[test]
fn an_io_error_keeps_its_errno() {
let err = Error::from(FsError::Io(Errno::ACCESS.into()));
assert!(has_errno(&err, Errno::ACCESS), "{err:?}");
}
#[test]
fn an_existing_entry_gives_eexist() {
let err = Error::from(FsError::Exists);
assert!(has_errno(&err, Errno::EXIST), "{err:?}");
}
#[test]
fn optional_gives_none_for_an_absent_entry_alone() {
assert!(matches!(Ok::<u8, FsError>(5).optional(), Ok(Some(5))));
assert!(matches!(
Err::<u8, _>(absent("state/x")).optional(),
Ok(None)
));
assert!(matches!(
Err::<u8, _>(FsError::Exists).optional(),
Err(FsError::Exists)
));
for (reason, text) in reason_cases() {
match Err::<u8, _>(invalid("state/x", reason)).optional() {
Err(FsError::Invalid { path, reason }) => {
assert_eq!(path, "state/x");
assert_eq!(reason.to_string(), text);
}
other => panic!("{other:?}"),
}
}
match Err::<u8, _>(FsError::Io(Errno::ACCESS.into())).optional() {
Err(FsError::Io(e)) => assert_eq!(e.raw_os_error(), Some(Errno::ACCESS.raw_os_error())),
other => panic!("{other:?}"),
}
}
#[test]
fn optional_dir_gives_none_for_an_entry_that_is_no_directory() {
let dir = TestDir::new("optional-dir");
let refs = refs(&dir);
let top = dir.path().join("refs");
std::fs::create_dir(top.join("real")).unwrap();
std::os::unix::fs::symlink("real", top.join("link")).unwrap();
std::fs::write(top.join("file"), b"").unwrap();
let open = |name: &str| refs.open_dir(name);
assert!(open("real").optional_dir().unwrap().is_some());
assert!(open("real").optional_walked_dir().unwrap().is_some());
for name in ["file", "file/below", "absent"] {
assert!(open(name).optional_dir().unwrap().is_none(), "{name}");
}
assert!(open("link").optional_walked_dir().unwrap().is_none());
let (path, reason) = super::invalid(open("link").optional_dir());
assert_eq!(path, "refs/link");
assert!(matches!(reason, Reason::Symlink), "{reason:?}");
}
#[test]
fn an_absent_ref_or_a_ref_below_a_file_is_no_ref() {
assert!(matches!(
Ok::<u8, FsError>(5).optional_ref("main"),
Ok(Some(5))
));
let ok = Err::<u8, _>(absent("refs/heads/main"))
.optional_ref("main")
.unwrap();
assert!(ok.is_none());
let ok = Err::<u8, _>(invalid("refs/heads/main/sub", Reason::NotDirectory))
.optional_ref("main/sub")
.unwrap();
assert!(ok.is_none());
}
#[test]
fn a_ref_that_is_not_a_regular_file_gives_not_a_ref() {
let err = Err::<u8, _>(invalid(
"refs/heads/main",
Reason::NotRegular(FileType::Fifo),
))
.optional_ref("main")
.unwrap_err();
assert!(
matches!(&err, Error::NotARef { name, reason }
if name == "main" && reason == "is not a regular file"),
"{err:?}"
);
}
#[test]
fn a_ref_through_a_symlink_or_an_escape_or_too_large_gives_invalid_format() {
let cases = [
(
Reason::Symlink,
"refs/heads/main passes through a symlink; ostrya refuses a symlink in the repository",
),
(
Reason::Escape,
"refs/heads/main resolves outside the repository",
),
(
Reason::TooLarge { cap: 4096 },
"refs/heads/main is larger than its cap of 4096 bytes",
),
];
for (reason, expected) in cases {
let err = Err::<u8, _>(invalid("refs/heads/main", reason))
.optional_ref("main")
.unwrap_err();
assert!(
matches!(&err, Error::InvalidFormat(m) if m == expected),
"{err:?}"
);
}
}
#[test]
fn a_ref_keeps_an_io_errno_and_gives_eexist_for_an_existing_entry() {
let err = Err::<u8, _>(FsError::Io(Errno::ACCESS.into()))
.optional_ref("main")
.unwrap_err();
assert!(has_errno(&err, Errno::ACCESS), "{err:?}");
let err = Err::<u8, _>(FsError::Exists)
.optional_ref("main")
.unwrap_err();
assert!(has_errno(&err, Errno::EXIST), "{err:?}");
}
#[test]
fn an_absent_object_gives_object_not_found() {
let sum = checksum();
let err = absent("objects/ab/ab.commit").into_object_error(&sum, ObjectType::Commit);
assert!(
matches!(&err, Error::ObjectNotFound { checksum, ty: ObjectType::Commit } if *checksum == sum),
"{err:?}"
);
}
#[test]
fn an_object_error_of_each_other_kind_gives_the_common_conversion() {
let sum = checksum();
for (reason, text) in reason_cases() {
let err =
invalid("objects/ab/ab.commit", reason).into_object_error(&sum, ObjectType::Commit);
let expected = format!("objects/ab/ab.commit {text}");
assert!(
matches!(&err, Error::InvalidFormat(m) if *m == expected),
"{err:?}"
);
}
let err = FsError::Io(Errno::ACCESS.into()).into_object_error(&sum, ObjectType::Commit);
assert!(has_errno(&err, Errno::ACCESS), "{err:?}");
let err = FsError::Exists.into_object_error(&sum, ObjectType::Commit);
assert!(has_errno(&err, Errno::EXIST), "{err:?}");
}
#[test]
fn from_root_fd_gives_a_root_handle_with_no_mode() {
let dir = TestDir::new("root-fd");
let fd = rustix::io::dup(dir.fd()).unwrap();
let raw = fd.as_raw_fd();
let repo = RepoDir::from_root_fd(fd);
assert_eq!(repo.kind(), RepoLayout::Root);
assert_eq!(repo.repo_mode(), None);
assert_eq!(repo.as_fd().as_raw_fd(), raw);
assert_eq!(repo.ctx.root.as_raw_fd(), raw);
}
#[test]
fn with_repo_mode_keeps_the_descriptor_and_sets_the_mode() {
let dir = TestDir::new("repo-mode");
let fd = rustix::io::dup(dir.fd()).unwrap();
let raw = fd.as_raw_fd();
let repo = RepoDir::from_root_fd(fd).with_repo_mode(RepoMode::BareUser);
assert_eq!(repo.kind(), RepoLayout::Root);
assert_eq!(repo.repo_mode(), Some(RepoMode::BareUser));
assert_eq!(repo.as_fd().as_raw_fd(), raw);
assert_eq!(repo.ctx.root.as_raw_fd(), raw);
}
fn root_with_tmp(dir: &TestDir) -> (RepoDir, Arc<OwnedFd>) {
let repo = RepoDir::from_root_fd(rustix::io::dup(dir.fd()).unwrap());
let tmp = Arc::new(rustix::io::dup(dir.fd()).unwrap());
repo.ctx.tmp.set(Arc::clone(&tmp)).unwrap();
(repo, tmp)
}
#[test]
fn with_repo_mode_sets_the_mode_in_place_for_the_sole_owner() {
let dir = TestDir::new("repo-mode-sole");
let (repo, tmp) = root_with_tmp(&dir);
let ctx = Arc::as_ptr(&repo.ctx);
let repo = repo.with_repo_mode(RepoMode::BareUserShared);
assert!(std::ptr::eq(Arc::as_ptr(&repo.ctx), ctx), "one context");
assert_eq!(repo.repo_mode(), Some(RepoMode::BareUserShared));
assert!(Arc::ptr_eq(repo.ctx.tmp.get().unwrap(), &tmp));
}
#[test]
fn with_repo_mode_gives_a_shared_handle_a_new_context() {
let dir = TestDir::new("repo-mode-shared");
let (repo, tmp) = root_with_tmp(&dir);
let other = repo.clone();
let repo = repo.with_repo_mode(RepoMode::Archive);
assert!(!Arc::ptr_eq(&repo.ctx, &other.ctx), "a new context");
assert_eq!(repo.repo_mode(), Some(RepoMode::Archive));
assert_eq!(other.repo_mode(), None);
assert!(Arc::ptr_eq(&repo.fd, &other.fd));
assert!(Arc::ptr_eq(&repo.ctx.root, &other.ctx.root));
assert!(Arc::ptr_eq(repo.ctx.tmp.get().unwrap(), &tmp));
assert!(Arc::ptr_eq(other.ctx.tmp.get().unwrap(), &tmp));
}
#[test]
fn stat_fd_reads_a_regular_file() {
use std::os::unix::fs::PermissionsExt;
let dir = TestDir::new("stat-file");
let path = dir.path().join("file");
std::fs::write(&path, b"twelve bytes").unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o640)).unwrap();
let fd = rustix::fs::openat(
dir.fd(),
"file",
OFlags::RDONLY | OFlags::CLOEXEC,
Mode::empty(),
)
.unwrap();
let stat = stat_fd(fd.as_fd()).unwrap();
let meta = std::fs::symlink_metadata(&path).unwrap();
assert_eq!(stat.file_type, FileType::RegularFile);
assert_eq!(stat.mode & 0o7777, 0o640);
assert_eq!(stat.mode, meta.mode());
assert_eq!(stat.uid, meta.uid());
assert_eq!(stat.gid, meta.gid());
assert_eq!(stat.size, 12);
assert_eq!(stat.size, meta.size());
assert_eq!(stat.dev, meta.dev());
assert_eq!(stat.ino, meta.ino());
assert_eq!(stat.mtime_sec, meta.mtime());
assert_eq!(i64::from(stat.mtime_nsec), meta.mtime_nsec());
assert_eq!(
(stat.ctime_sec, i64::from(stat.ctime_nsec)),
(meta.ctime(), meta.ctime_nsec())
);
assert!(!stat.verity);
}
#[test]
fn stat_fd_reads_a_directory() {
let dir = TestDir::new("stat-dir");
let stat = stat_fd(dir.fd()).unwrap();
let meta = std::fs::symlink_metadata(dir.path()).unwrap();
assert_eq!(stat.file_type, FileType::Directory);
assert_eq!(stat.mode, meta.mode());
assert_eq!(stat.ino, meta.ino());
}
#[test]
fn stat_fd_reads_a_symlink_opened_with_o_path() {
let dir = TestDir::new("stat-link");
std::os::unix::fs::symlink("nowhere", dir.path().join("link")).unwrap();
let fd = rustix::fs::openat(
dir.fd(),
"link",
OFlags::PATH | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)
.unwrap();
let stat = stat_fd(fd.as_fd()).unwrap();
assert_eq!(stat.file_type, FileType::Symlink);
}
#[test]
fn fs_space_reads_the_space_of_the_file_system() {
let dir = TestDir::new("fs-space");
let (available, total) = fs_space(dir.fd()).unwrap();
let stat = rustix::fs::fstatvfs(dir.fd()).unwrap();
assert_eq!(total, stat.f_blocks * stat.f_frsize);
assert!(available <= total);
}
#[test]
fn test_dir_removes_its_tree_on_drop() {
let dir = TestDir::new("drop");
let path = dir.path().to_owned();
std::fs::create_dir(path.join("sub")).unwrap();
std::fs::write(path.join("sub/file"), b"x").unwrap();
assert!(path.is_dir());
drop(dir);
assert!(!path.exists());
}
}