use std::future::Future;
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd};
use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::sync::Arc;
use futures_lite::AsyncReadExt;
use ostrya_core::{Checksum, Commit, DirMeta, ObjectType, RepoMode, Xattrs, loose_path};
use ostrya_rt::{File as RtFile, FileReader};
use rustix::fs::{AtFlags, CWD, Dir, FileType, Gid, Mode, OFlags, RenameFlags, Uid};
use rustix::io::Errno;
use crate::error::{Error, Result};
use crate::file::{FileKind, FileObject, Payload};
use crate::ingest::join_path;
use crate::modifier::{DevInoCache, FilterResult};
use crate::read::{CommitState, object_path_error};
use crate::repo::Repo;
use crate::repo_fs::{self, FsError, Published};
use crate::tree::{Comp, RepoTree, TreeEntry};
use crate::write::{FileMeta, TempKind};
const PERM_MASK: u32 = 0o7777;
const USER_PERM_MASK: u32 = 0o1777;
const BAREUSERONLY_DIR_MASK: u32 = 0o775;
const HASH_CHUNK: usize = 64 * 1024;
const TRANSIENT_DIR_MODE: u32 = 0o700;
const OPAQUE_MARKER: &str = ".wh..wh..opq";
const WHITEOUT_PREFIX: &str = ".wh.";
const PASSTHROUGH_PREFIX: &str = ".ostree-wh.";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CheckoutMode {
#[default]
None,
User,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OverwriteMode {
#[default]
None,
UnionFiles,
AddFiles,
UnionIdentical,
}
pub type CheckoutFilterFn = Box<dyn FnMut(&Path, &FileMeta) -> FilterResult + Send>;
pub struct CheckoutOptions {
pub mode: CheckoutMode,
pub overwrite: OverwriteMode,
pub subpath: Option<PathBuf>,
pub enable_fsync: bool,
pub force_copy: bool,
pub require_hardlinks: bool,
pub bareuseronly_dirs: bool,
pub process_whiteouts: bool,
pub process_passthrough_whiteouts: bool,
pub devino_cache: Option<DevInoCache>,
pub filter: Option<CheckoutFilterFn>,
}
impl Default for CheckoutOptions {
fn default() -> CheckoutOptions {
CheckoutOptions {
mode: CheckoutMode::None,
overwrite: OverwriteMode::None,
subpath: None,
enable_fsync: false,
force_copy: false,
require_hardlinks: false,
bareuseronly_dirs: false,
process_whiteouts: false,
process_passthrough_whiteouts: false,
devino_cache: None,
filter: None,
}
}
}
impl CheckoutOptions {
pub fn new(mode: CheckoutMode) -> CheckoutOptions {
CheckoutOptions {
mode,
..CheckoutOptions::default()
}
}
}
impl Repo {
pub async fn checkout_at(
&self,
opts: &mut CheckoutOptions,
dest_dir: BorrowedFd<'_>,
dest_path: &Path,
commit: &Checksum,
) -> Result<()> {
let policy = Policy::new(self.mode(), opts);
if policy.overwrite == OverwriteMode::UnionIdentical && !policy.require_hardlinks {
return Err(Error::Checkout(
"union-identical requires require_hardlinks".into(),
));
}
if policy.require_hardlinks && policy.force_copy {
return Err(Error::Checkout(
"require_hardlinks and force_copy are mutually exclusive".into(),
));
}
let (commit_obj, state) = self.load_commit(commit).await?;
if state == CommitState::Partial {
return Err(Error::Checkout(format!(
"commit {} is partial; checkout needs a complete commit",
commit.to_hex()
)));
}
let target = resolve_target(self, &commit_obj, opts.subpath.as_deref()).await?;
match target {
Target::Dir { dirtree, dirmeta } => {
let dm = self.load_dirmeta(&dirmeta).await?;
if let Some(filter) = &mut opts.filter {
let fm = FileMeta {
uid: dm.uid,
gid: dm.gid,
mode: dm.mode,
xattrs: dm.xattrs.clone(),
};
if filter(Path::new("/"), &fm) == FilterResult::Skip {
return Ok(());
}
}
let (parent_fd, name) = open_dest_parent(dest_dir, dest_path)?;
let (dir_fd, fresh) = match &name {
Some(n) => create_dest_dir(
parent_fd.as_fd(),
n,
policy.overwrite,
widens_type_conflict(policy),
)?,
None => (parent_fd.as_fd().try_clone_to_owned()?, false),
};
checkout_dir(
self,
opts,
policy,
DirNode {
dir_fd,
dirtree,
dirmeta: dm,
fresh,
base_path: "/".to_owned(),
},
)
.await?;
}
Target::File {
name: entry_name,
checksum,
} => {
let (parent_fd, name) = open_dest_parent(dest_dir, dest_path)?;
let dir_name = name.ok_or_else(|| {
Error::Checkout("a file subpath needs a named destination directory".into())
})?;
let (dir_fd, _fresh) =
create_dest_dir(parent_fd.as_fd(), &dir_name, policy.overwrite, false)?;
let (obj, payload) = load_entry(self, policy, &checksum).await?;
let entry = Entry { obj: &obj, payload };
checkout_entry(self, opts, policy, dir_fd.as_fd(), &entry_name, entry).await?;
if policy.enable_fsync {
fsync_dir(dir_fd).await?;
}
}
}
Ok(())
}
}
enum Target {
Dir {
dirtree: Checksum,
dirmeta: Checksum,
},
File { name: String, checksum: Checksum },
}
async fn resolve_target(repo: &Repo, commit: &Commit, subpath: Option<&Path>) -> Result<Target> {
let root = Target::Dir {
dirtree: commit.root_dirtree,
dirmeta: commit.root_dirmeta,
};
let Some(sub) = subpath else {
return Ok(root);
};
if is_root_path(sub) {
return Ok(root);
}
let tree = RepoTree::from_parts(repo.clone(), commit.root_dirtree, commit.root_dirmeta);
match tree.lookup(sub).await? {
Some(TreeEntry::Dir { tree, .. }) => Ok(Target::Dir {
dirtree: *tree.dirtree_checksum(),
dirmeta: *tree.dirmeta_checksum(),
}),
Some(TreeEntry::File { name, checksum }) => Ok(Target::File { name, checksum }),
None => Err(unresolved_subpath(&tree, sub).await),
}
}
async fn unresolved_subpath(tree: &RepoTree, sub: &Path) -> Error {
let not_found = || Error::SubpathNotFound(sub.to_path_buf());
let components = crate::tree::normalize(sub);
let Some(leading) = components.len().checked_sub(1) else {
return not_found();
};
let mut current = tree.clone();
for component in &components[..leading] {
let Comp::Normal(component) = component else {
return not_found();
};
match current.lookup(Path::new(component)).await {
Ok(Some(TreeEntry::Dir { tree, .. })) => current = tree,
Ok(Some(TreeEntry::File { .. })) => {
return Error::SubpathNotADirectory(sub.to_path_buf());
}
Ok(None) => return not_found(),
Err(e) => return e,
}
}
not_found()
}
pub(crate) fn is_root_path(p: &Path) -> bool {
use std::path::Component;
!p.components().any(|c| matches!(c, Component::Normal(_)))
}
fn open_dest_parent(
dest_dir: BorrowedFd<'_>,
dest_path: &Path,
) -> Result<(OwnedFd, Option<String>)> {
match dest_path.file_name() {
Some(name) => {
let name = name
.to_str()
.ok_or_else(|| Error::Checkout("destination name is not valid UTF-8".into()))?
.to_owned();
let parent_fd = match dest_path.parent() {
Some(p) if !p.as_os_str().is_empty() => rustix::fs::openat(
dest_dir,
p,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)?,
_ => dest_dir.try_clone_to_owned()?,
};
Ok((parent_fd, Some(name)))
}
None => Ok((dest_dir.try_clone_to_owned()?, None)),
}
}
type CheckoutFuture<'a> = Pin<Box<dyn Future<Output = Result<()>> + Send + 'a>>;
struct DirNode {
dir_fd: OwnedFd,
dirtree: Checksum,
dirmeta: DirMeta,
fresh: bool,
base_path: String,
}
fn checkout_dir<'a>(
repo: &'a Repo,
opts: &'a mut CheckoutOptions,
policy: Policy,
node: DirNode,
) -> CheckoutFuture<'a> {
Box::pin(async move {
let DirNode {
dir_fd,
dirtree: dirtree_csum,
dirmeta,
fresh,
base_path,
} = node;
check_hardlink_device(repo, policy, dir_fd.as_fd())?;
let dirtree = repo.load_dirtree(&dirtree_csum).await?;
if !fresh
&& policy.process_whiteouts
&& dirtree.files.iter().any(|(n, _)| n == OPAQUE_MARKER)
{
let d = dir_fd.as_fd().try_clone_to_owned()?;
ostrya_rt::unblock(move || clear_dir(d.as_fd())).await?;
}
for (name, checksum) in &dirtree.files {
let (obj, payload) = load_entry(repo, policy, checksum).await?;
if let Some(filter) = &mut opts.filter {
let cb_path = join_path(&base_path, name);
let fm = FileMeta {
uid: obj.uid,
gid: obj.gid,
mode: obj.mode,
xattrs: obj.xattrs.clone(),
};
if filter(Path::new(&cb_path), &fm) == FilterResult::Skip {
continue;
}
}
let entry = Entry { obj: &obj, payload };
checkout_entry(repo, &mut *opts, policy, dir_fd.as_fd(), name, entry).await?;
}
for (name, sub_dirtree, sub_dirmeta) in &dirtree.dirs {
let dm = repo.load_dirmeta(sub_dirmeta).await?;
let cb_path = join_path(&base_path, name);
if let Some(filter) = &mut opts.filter {
let fm = FileMeta {
uid: dm.uid,
gid: dm.gid,
mode: dm.mode,
xattrs: dm.xattrs.clone(),
};
if filter(Path::new(&cb_path), &fm) == FilterResult::Skip {
continue;
}
}
let (child_fd, child_fresh) = create_dest_dir(
dir_fd.as_fd(),
name,
policy.overwrite,
widens_type_conflict(policy),
)?;
checkout_dir(
repo,
&mut *opts,
policy,
DirNode {
dir_fd: child_fd,
dirtree: *sub_dirtree,
dirmeta: dm,
fresh: child_fresh,
base_path: cb_path,
},
)
.await?;
}
if fresh {
let d = dir_fd.as_fd().try_clone_to_owned()?;
let effective = policy.effective;
let masked = policy.bareuseronly_dirs;
ostrya_rt::unblock(move || apply_dir_metadata(d.as_fd(), effective, masked, &dirmeta))
.await?;
}
if policy.enable_fsync {
fsync_dir(dir_fd).await?;
}
Ok(())
})
}
async fn load_entry(
repo: &Repo,
policy: Policy,
checksum: &Checksum,
) -> Result<(FileObject, Option<Payload>)> {
if hardlink_regular(policy) {
Ok((repo.load_file(checksum).await?, None))
} else {
repo.open_file(checksum).await
}
}
struct Entry<'o> {
obj: &'o FileObject,
payload: Option<Payload>,
}
async fn checkout_entry(
repo: &Repo,
opts: &mut CheckoutOptions,
policy: Policy,
dir_fd: BorrowedFd<'_>,
name: &str,
entry: Entry<'_>,
) -> Result<()> {
let obj = entry.obj;
match whiteout_verdict(policy, name, obj)? {
Some(Whiteout::Drop) => Ok(()),
Some(Whiteout::Remove(target)) => {
let d = dir_fd.try_clone_to_owned()?;
ostrya_rt::unblock(move || remove_dir_entry(d.as_fd(), &target)).await
}
Some(Whiteout::Device(target)) => place_whiteout_device(policy, dir_fd, &target, obj).await,
None => checkout_file(repo, opts, policy, dir_fd, name, entry).await,
}
}
async fn checkout_file(
repo: &Repo,
opts: &mut CheckoutOptions,
policy: Policy,
dir_fd: BorrowedFd<'_>,
name: &str,
entry: Entry<'_>,
) -> Result<()> {
let obj = entry.obj;
if require_hardlinks_refuses(policy, obj) {
return Err(Error::RequireHardlinks(name.to_owned()));
}
match &obj.kind {
FileKind::Symlink { target } => {
place_symlink(repo, policy, dir_fd, name, obj, target).await
}
FileKind::Regular { .. } => place_regular(repo, opts, policy, dir_fd, name, entry).await,
}
}
enum Whiteout {
Drop,
Remove(String),
Device(String),
}
fn whiteout_verdict(policy: Policy, name: &str, obj: &FileObject) -> Result<Option<Whiteout>> {
if !matches!(obj.kind, FileKind::Regular { .. }) {
return Ok(None);
}
if policy.process_whiteouts {
if name == OPAQUE_MARKER {
return Ok(Some(Whiteout::Drop));
}
if let Some(target) = name.strip_prefix(WHITEOUT_PREFIX) {
if target.is_empty() {
return Err(Error::Checkout(format!(
"{WHITEOUT_PREFIX}: the whiteout names no entry"
)));
}
return Ok(Some(Whiteout::Remove(target.to_owned())));
}
}
if policy.process_passthrough_whiteouts
&& let Some(target) = name.strip_prefix(PASSTHROUGH_PREFIX)
{
if target.is_empty() {
return Err(Error::Checkout(format!(
"{PASSTHROUGH_PREFIX}: the overlayfs whiteout names no entry"
)));
}
return Ok(Some(Whiteout::Device(target.to_owned())));
}
Ok(None)
}
async fn place_whiteout_device(
policy: Policy,
dir_fd: BorrowedFd<'_>,
name: &str,
obj: &FileObject,
) -> Result<()> {
let remove_existing = match pre_check(dir_fd, name, policy.overwrite, false)? {
Disposition::Skip | Disposition::Check(_) => return Ok(()),
Disposition::Error => return Err(collision(name)),
Disposition::Place => false,
Disposition::Overwrite => true,
};
let plan = PlaceWhiteoutDevice {
dir: dir_fd.try_clone_to_owned()?,
name: name.to_owned(),
effective: policy.effective,
uid: obj.uid,
gid: obj.gid,
mode: obj.mode & PERM_MASK,
xattrs: obj.xattrs.clone(),
remove_existing,
};
ostrya_rt::unblock(move || place_whiteout_device_blocking(plan)).await
}
struct PlaceWhiteoutDevice {
dir: OwnedFd,
name: String,
effective: CheckoutMode,
uid: u32,
gid: u32,
mode: u32,
xattrs: Xattrs,
remove_existing: bool,
}
fn place_whiteout_device_blocking(plan: PlaceWhiteoutDevice) -> Result<()> {
if plan.remove_existing {
remove_dir_entry(plan.dir.as_fd(), &plan.name)?;
}
match rustix::fs::mknodat(
plan.dir.as_fd(),
plan.name.as_str(),
FileType::CharacterDevice,
Mode::from_raw_mode(plan.mode),
rustix::fs::makedev(0, 0),
) {
Ok(()) => {}
Err(Errno::EXIST) => return Err(collision(&plan.name)),
Err(e) => return Err(e.into()),
}
if plan.effective == CheckoutMode::None {
for (name, value) in plan.xattrs.iter() {
crate::write::set_link_xattr(plan.dir.as_fd(), &plan.name, name, value).map_err(
|err| {
Error::Checkout(format!(
"{}: setting the extended attribute {}: {}",
plan.name,
xattr_name(name),
reason(err),
))
},
)?;
}
rustix::fs::chownat(
plan.dir.as_fd(),
plan.name.as_str(),
Some(Uid::from_raw(plan.uid)),
Some(Gid::from_raw(plan.gid)),
AtFlags::SYMLINK_NOFOLLOW,
)?;
rustix::fs::chmodat(
plan.dir.as_fd(),
plan.name.as_str(),
Mode::from_raw_mode(plan.mode),
AtFlags::empty(),
)?;
}
Ok(())
}
fn xattr_name(name: &[u8]) -> String {
String::from_utf8_lossy(name.strip_suffix(&[0]).unwrap_or(name)).into_owned()
}
fn reason(err: Error) -> String {
let text = match &err {
Error::Io(io) => io.to_string(),
other => other.to_string(),
};
match text.find(" (os error ") {
Some(cut) => text[..cut].to_owned(),
None => text,
}
}
async fn place_regular(
repo: &Repo,
opts: &mut CheckoutOptions,
policy: Policy,
dir_fd: BorrowedFd<'_>,
name: &str,
entry: Entry<'_>,
) -> Result<()> {
let Entry { obj, payload } = entry;
let checksum = obj.checksum();
let remove_existing =
match pre_check(dir_fd, name, policy.overwrite, widens_type_conflict(policy))? {
Disposition::Skip => return Ok(()),
Disposition::Error => return Err(collision(name)),
Disposition::Place => false,
Disposition::Overwrite => true,
Disposition::Check(st) => {
if destination_is_identical(repo, policy, dir_fd, name, &st, obj).await? {
return Ok(());
}
return Err(collision(name));
}
};
if hardlink_regular_object(policy, obj) {
match try_link_object(repo, dir_fd, name, checksum, remove_existing).await? {
Some((dev, ino)) => {
record_devino(opts, dev, ino, checksum);
return Ok(());
}
None if policy.require_hardlinks => {
return hardlink_across_devices(repo, dir_fd);
}
None => {}
}
}
let dir = Arc::new(dir_fd.try_clone_to_owned()?);
let (temp, kind) = crate::write::open_temp(&dir)?;
if !(policy.repo_mode != RepoMode::Archive && matches!(obj.kind, FileKind::Regular { size: 0 }))
{
copy_object(repo, obj, payload, &temp, policy).await?;
}
let plan = FinishCopy {
dir,
name: name.to_owned(),
temp,
kind,
effective: policy.effective,
uid: obj.uid,
gid: obj.gid,
mode: obj.mode,
xattrs: obj.xattrs.clone(),
enable_fsync: policy.enable_fsync,
remove_existing,
};
let (dev, ino) = ostrya_rt::unblock(move || finish_copy_blocking(plan)).await?;
record_devino(opts, dev, ino, checksum);
Ok(())
}
async fn place_symlink(
repo: &Repo,
policy: Policy,
dir_fd: BorrowedFd<'_>,
name: &str,
obj: &FileObject,
target: &str,
) -> Result<()> {
let checksum = obj.checksum();
let remove_existing =
match pre_check(dir_fd, name, policy.overwrite, widens_type_conflict(policy))? {
Disposition::Skip => return Ok(()),
Disposition::Error => return Err(collision(name)),
Disposition::Place => false,
Disposition::Overwrite => true,
Disposition::Check(st) => {
if destination_is_identical(repo, policy, dir_fd, name, &st, obj).await? {
return Ok(());
}
return Err(collision(name));
}
};
if hardlink_symlink(policy) {
match try_link_object(repo, dir_fd, name, checksum, remove_existing).await? {
Some(_) => return Ok(()),
None if policy.require_hardlinks => {
return hardlink_across_devices(repo, dir_fd);
}
None => {}
}
}
let plan = RecreateSymlink {
dir: dir_fd.try_clone_to_owned()?,
name: name.to_owned(),
target: target.to_owned(),
effective: policy.effective,
uid: obj.uid,
gid: obj.gid,
xattrs: obj.xattrs.clone(),
remove_existing,
};
ostrya_rt::unblock(move || recreate_symlink_blocking(plan)).await
}
fn record_devino(opts: &mut CheckoutOptions, dev: u64, ino: u64, checksum: &Checksum) {
if let Some(cache) = &mut opts.devino_cache {
cache.insert(dev, ino, *checksum);
}
}
enum Disposition {
Place,
Overwrite,
Skip,
Check(rustix::fs::Stat),
Error,
}
fn pre_check(
dir_fd: BorrowedFd<'_>,
name: &str,
overwrite: OverwriteMode,
widen_type_conflict: bool,
) -> Result<Disposition> {
let st = match rustix::fs::statat(dir_fd, name, AtFlags::SYMLINK_NOFOLLOW) {
Ok(st) => st,
Err(Errno::NOENT) => return Ok(Disposition::Place),
Err(e) => return Err(e.into()),
};
Ok(match overwrite {
OverwriteMode::None => Disposition::Error,
OverwriteMode::UnionFiles => {
if FileType::from_raw_mode(st.st_mode) == FileType::Directory && !widen_type_conflict {
Disposition::Error
} else {
Disposition::Overwrite
}
}
OverwriteMode::AddFiles => Disposition::Skip,
OverwriteMode::UnionIdentical => Disposition::Check(st),
})
}
async fn loose_object_stat(repo: &Repo, checksum: &Checksum) -> Result<(u64, u64, u32)> {
let path = loose_path(checksum, ObjectType::File, repo.mode());
let repo = repo.clone();
let checksum = *checksum;
ostrya_rt::unblock(move || {
let st = repo
.objects()
.lstat(&path)
.map_err(|e| e.into_object_error(&checksum, ObjectType::File))?;
Ok((st.dev, st.ino, st.mode & PERM_MASK))
})
.await
}
async fn destination_is_identical(
repo: &Repo,
policy: Policy,
dir_fd: BorrowedFd<'_>,
name: &str,
st: &rustix::fs::Stat,
obj: &FileObject,
) -> Result<bool> {
match &obj.kind {
FileKind::Symlink { target } => {
if FileType::from_raw_mode(st.st_mode) != FileType::Symlink {
return Ok(false);
}
let link = rustix::fs::readlinkat(dir_fd, name, Vec::new())?;
Ok(link.as_bytes() == target.as_bytes())
}
FileKind::Regular { size } => {
if FileType::from_raw_mode(st.st_mode) != FileType::RegularFile {
return Ok(false);
}
let (dev, ino, obj_perm) = loose_object_stat(repo, obj.checksum()).await?;
if st.st_dev == dev && st.st_ino == ino {
return Ok(true);
}
if u64::try_from(st.st_size).ok() != Some(*size) {
return Ok(false);
}
if st.st_mode & PERM_MASK != obj_perm {
return Ok(false);
}
let fd = rustix::fs::openat(
dir_fd,
name,
OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)?;
let meta = FileMeta {
uid: st.st_uid,
gid: st.st_gid,
mode: st.st_mode,
xattrs: crate::ingest::read_all_xattrs(fd.as_fd())?,
};
let header = crate::write::canonical_header(policy.repo_mode, meta.regular_header());
if header != crate::write::canonical_header(policy.repo_mode, obj.header()) {
return Ok(false);
}
let checksum = hash_destination_file(fd, &header, *size).await?;
Ok(checksum == *obj.checksum())
}
}
}
async fn hash_destination_file(
fd: OwnedFd,
header: &ostrya_core::FileHeader,
size: u64,
) -> Result<Checksum> {
let mut hasher = ostrya_core::ContentHasher::new(header)?;
let mut file = FileReader::with_len_hint(std::fs::File::from(fd), size);
let mut buf = vec![
0u8;
usize::try_from(size)
.unwrap_or(HASH_CHUNK)
.clamp(1, HASH_CHUNK)
];
loop {
let n = file.read(&mut buf).await?;
if n == 0 {
break;
}
hasher.update(&buf[..n]);
}
Ok(hasher.finish())
}
fn create_dest_dir(
parent: BorrowedFd<'_>,
name: &str,
overwrite: OverwriteMode,
widen_type_conflict: bool,
) -> Result<(OwnedFd, bool)> {
match rustix::fs::mkdirat(parent, name, Mode::from_raw_mode(TRANSIENT_DIR_MODE)) {
Ok(()) => Ok((open_fresh_dir(parent, name)?, true)),
Err(Errno::EXIST) => {
let st = rustix::fs::statat(parent, name, AtFlags::SYMLINK_NOFOLLOW)?;
if FileType::from_raw_mode(st.st_mode) != FileType::Directory && widen_type_conflict {
unlink_entry(parent, name, false)?;
rustix::fs::mkdirat(parent, name, Mode::from_raw_mode(TRANSIENT_DIR_MODE))?;
return Ok((open_fresh_dir(parent, name)?, true));
}
if overwrite != OverwriteMode::None && is_symlink(st.st_mode) {
return Ok((open_dir_following(parent, name)?, false));
}
if FileType::from_raw_mode(st.st_mode) != FileType::Directory {
return Err(Error::Checkout(format!(
"{name}: destination entry exists and is not a directory"
)));
}
match overwrite {
OverwriteMode::None => Err(Error::Checkout(format!(
"{name}: destination directory already exists"
))),
_ => Ok((open_dir(parent, name)?, false)),
}
}
Err(e) => Err(e.into()),
}
}
fn open_fresh_dir(parent: BorrowedFd<'_>, name: &str) -> Result<OwnedFd> {
let fd = open_dir(parent, name)?;
rustix::fs::fchmod(&fd, Mode::from_raw_mode(TRANSIENT_DIR_MODE))?;
Ok(fd)
}
fn is_symlink(mode: u32) -> bool {
FileType::from_raw_mode(mode) == FileType::Symlink
}
fn open_dir_following(parent: BorrowedFd<'_>, name: &str) -> Result<OwnedFd> {
Ok(rustix::fs::openat(
parent,
name,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)?)
}
fn open_dir(parent: BorrowedFd<'_>, name: &str) -> Result<OwnedFd> {
Ok(rustix::fs::openat(
parent,
name,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)?)
}
async fn try_link_object(
repo: &Repo,
dir_fd: BorrowedFd<'_>,
name: &str,
checksum: &Checksum,
remove_existing: bool,
) -> Result<Option<(u64, u64)>> {
let objects = repo.objects().clone();
let dir = dir_fd.try_clone_to_owned()?;
let loose = loose_path(checksum, ObjectType::File, repo.mode());
let name = name.to_owned();
let checksum = *checksum;
ostrya_rt::unblock(move || {
if remove_existing {
remove_dir_entry(dir.as_fd(), &name)?;
}
let errno = |e: &std::io::Error| e.raw_os_error().map(Errno::from_raw_os_error);
match repo_fs::link(&objects, &loose, dir.as_fd(), &name, false) {
Ok(Published::Created) => {
let st = rustix::fs::statat(dir.as_fd(), &name, AtFlags::SYMLINK_NOFOLLOW)?;
Ok(Some((st.st_dev, st.st_ino)))
}
Ok(Published::Existed) => Err(collision(&name)),
Err(FsError::Io(e)) if errno(&e) == Some(Errno::XDEV) => Ok(None),
Err(FsError::Io(e)) if errno(&e) == Some(Errno::NOENT) => Err(Error::ObjectNotFound {
checksum,
ty: ObjectType::File,
}),
Err(e) => {
Err(object_path_error(e, &loose).into_object_error(&checksum, ObjectType::File))
}
}
})
.await
}
async fn copy_object(
repo: &Repo,
obj: &FileObject,
payload: Option<Payload>,
temp: &OwnedFd,
policy: Policy,
) -> Result<()> {
if policy.repo_mode != RepoMode::Archive {
let objects = repo.objects().clone();
let checksum = *obj.checksum();
let loose = loose_path(&checksum, ObjectType::File, policy.repo_mode);
let dst = std::fs::File::from(temp.as_fd().try_clone_to_owned()?);
return ostrya_rt::unblock(move || {
let src = match payload {
Some((file, _)) => file,
None => {
objects
.open_regular(&loose)
.map_err(|e| e.into_object_error(&checksum, ObjectType::File))?
.file
}
};
repo_fs::clone_or_copy(&src, &dst)?;
Ok(())
})
.await;
}
let reader = match payload {
Some(payload) => obj.reader_over(Some(payload)),
None => obj.reader().await?,
};
let mut writer = RtFile::from(temp.as_fd().try_clone_to_owned()?);
crate::write::copy_stream(reader, &mut writer).await?;
crate::write::flush(&mut writer).await?;
Ok(())
}
struct FinishCopy {
dir: Arc<OwnedFd>,
name: String,
temp: OwnedFd,
kind: TempKind,
effective: CheckoutMode,
uid: u32,
gid: u32,
mode: u32,
xattrs: Xattrs,
enable_fsync: bool,
remove_existing: bool,
}
fn finish_copy_blocking(mut plan: FinishCopy) -> Result<(u64, u64)> {
prepare_copy_blocking(&plan)?;
match &mut plan.kind {
TempKind::Anonymous => {
let proc = format!("/proc/self/fd/{}", plan.temp.as_raw_fd());
match rustix::fs::linkat(
CWD,
proc.as_str(),
plan.dir.as_fd(),
&plan.name,
AtFlags::SYMLINK_FOLLOW,
) {
Ok(()) => {}
Err(Errno::EXIST) => return Err(collision(&plan.name)),
Err(e) => return Err(e.into()),
}
}
TempKind::Named(tmp) => {
let result = if !plan.remove_existing {
match rustix::fs::renameat_with(
plan.dir.as_fd(),
tmp.name(),
plan.dir.as_fd(),
&plan.name,
RenameFlags::NOREPLACE,
) {
Err(Errno::INVAL | Errno::NOSYS) => rustix::fs::renameat(
plan.dir.as_fd(),
tmp.name(),
plan.dir.as_fd(),
&plan.name,
),
other => other,
}
} else {
rustix::fs::renameat(plan.dir.as_fd(), tmp.name(), plan.dir.as_fd(), &plan.name)
};
if let Err(e) = result {
return Err(if e == Errno::EXIST {
collision(&plan.name)
} else {
e.into()
});
}
tmp.disarm();
}
}
let st = rustix::fs::statat(plan.dir.as_fd(), &plan.name, AtFlags::SYMLINK_NOFOLLOW)?;
Ok((st.st_dev, st.st_ino))
}
fn prepare_copy_blocking(plan: &FinishCopy) -> Result<()> {
apply_regular_metadata(
plan.temp.as_fd(),
plan.effective,
plan.uid,
plan.gid,
plan.mode,
&plan.xattrs,
)?;
if plan.enable_fsync {
rustix::fs::fsync(plan.temp.as_fd())?;
}
if plan.remove_existing {
remove_dir_entry(plan.dir.as_fd(), &plan.name)?;
}
Ok(())
}
fn apply_regular_metadata(
fd: BorrowedFd<'_>,
effective: CheckoutMode,
uid: u32,
gid: u32,
mode: u32,
xattrs: &Xattrs,
) -> Result<()> {
match effective {
CheckoutMode::None => {
rustix::fs::fchown(fd, Some(Uid::from_raw(uid)), Some(Gid::from_raw(gid)))?;
for (name, value) in xattrs.iter() {
crate::write::set_inode_xattr(fd, name, value)?;
}
rustix::fs::fchmod(fd, Mode::from_raw_mode(mode & PERM_MASK))?;
}
CheckoutMode::User => {
rustix::fs::fchmod(fd, Mode::from_raw_mode(mode & USER_PERM_MASK))?;
}
}
Ok(())
}
fn apply_dir_metadata(
fd: BorrowedFd<'_>,
effective: CheckoutMode,
bareuseronly_dirs: bool,
dm: &DirMeta,
) -> Result<()> {
if effective == CheckoutMode::None {
for (name, value) in dm.xattrs.iter() {
crate::write::set_inode_xattr(fd, name, value)?;
}
rustix::fs::fchown(fd, Some(Uid::from_raw(dm.uid)), Some(Gid::from_raw(dm.gid)))?;
}
let mask = if bareuseronly_dirs {
BAREUSERONLY_DIR_MASK
} else {
PERM_MASK
};
rustix::fs::fchmod(fd, Mode::from_raw_mode(dm.mode & mask))?;
Ok(())
}
struct RecreateSymlink {
dir: OwnedFd,
name: String,
target: String,
effective: CheckoutMode,
uid: u32,
gid: u32,
xattrs: Xattrs,
remove_existing: bool,
}
fn recreate_symlink_blocking(plan: RecreateSymlink) -> Result<()> {
if plan.remove_existing {
remove_dir_entry(plan.dir.as_fd(), &plan.name)?;
}
match rustix::fs::symlinkat(plan.target.as_str(), plan.dir.as_fd(), &plan.name) {
Ok(()) => {}
Err(Errno::EXIST) => return Err(collision(&plan.name)),
Err(e) => return Err(e.into()),
}
if plan.effective == CheckoutMode::None {
rustix::fs::chownat(
plan.dir.as_fd(),
plan.name.as_str(),
Some(Uid::from_raw(plan.uid)),
Some(Gid::from_raw(plan.gid)),
AtFlags::SYMLINK_NOFOLLOW,
)?;
for (name, value) in plan.xattrs.iter() {
crate::write::set_link_xattr(plan.dir.as_fd(), &plan.name, name, value)?;
}
}
Ok(())
}
fn remove_dir_entry(dir: BorrowedFd<'_>, name: &str) -> Result<()> {
match entry_is_dir(dir, name)? {
None => Ok(()),
Some(false) => unlink_entry(dir, name, false),
Some(true) => remove_subtree(dir, name),
}
}
fn entry_is_dir(dir: BorrowedFd<'_>, name: &str) -> Result<Option<bool>> {
match rustix::fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW) {
Ok(st) => Ok(Some(
FileType::from_raw_mode(st.st_mode) == FileType::Directory,
)),
Err(Errno::NOENT) => Ok(None),
Err(e) => Err(e.into()),
}
}
fn unlink_entry(dir: BorrowedFd<'_>, name: &str, is_dir: bool) -> Result<()> {
let flags = if is_dir {
AtFlags::REMOVEDIR
} else {
AtFlags::empty()
};
match rustix::fs::unlinkat(dir, name, flags) {
Ok(()) | Err(Errno::NOENT) => Ok(()),
Err(e) => Err(e.into()),
}
}
fn remove_subtree(dir: BorrowedFd<'_>, name: &str) -> Result<()> {
let mut level = match open_dir(dir, name) {
Ok(fd) => fd,
Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(e) => return Err(e),
};
let mut levels = vec![(name.to_owned(), read_level(level.as_fd())?)];
while let Some((_, entries)) = levels.last_mut() {
match entries.pop() {
Some((child, false)) => unlink_entry(level.as_fd(), &child, false)?,
Some((child, true)) => {
let child_fd = match open_dir(level.as_fd(), &child) {
Ok(fd) => fd,
Err(Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => continue,
Err(e) => return Err(e),
};
let child_entries = read_level(child_fd.as_fd())?;
level = child_fd;
levels.push((child, child_entries));
}
None => {
let (cleared, _) = levels.pop().expect("a level is in hand within the loop");
if levels.is_empty() {
drop(level);
return unlink_entry(dir, &cleared, true);
}
level = open_dir(level.as_fd(), "..")?;
unlink_entry(level.as_fd(), &cleared, true)?;
}
}
}
Ok(())
}
fn clear_dir(dir: BorrowedFd<'_>) -> Result<()> {
for (name, is_dir) in read_level(dir)? {
if is_dir {
remove_subtree(dir, &name)?;
} else {
unlink_entry(dir, &name, false)?;
}
}
Ok(())
}
fn read_level(level: BorrowedFd<'_>) -> Result<Vec<(String, bool)>> {
let mut entries = Vec::new();
for entry in Dir::read_from(level)? {
let entry = entry?;
let name = entry.file_name();
if name == c"." || name == c".." {
continue;
}
let name = name
.to_str()
.map_err(|_| Error::InvalidFormat("directory entry name is not valid UTF-8".into()))?
.to_owned();
let is_dir = match entry.file_type() {
FileType::Directory => true,
FileType::Unknown => match entry_is_dir(level, &name)? {
Some(is_dir) => is_dir,
None => continue,
},
_ => false,
};
entries.push((name, is_dir));
}
Ok(entries)
}
async fn fsync_dir(dir: OwnedFd) -> Result<()> {
ostrya_rt::unblock(move || rustix::fs::fsync(dir.as_fd()).map_err(Error::from)).await
}
fn collision(name: &str) -> Error {
Error::Checkout(format!("{name}: destination entry already exists"))
}
#[derive(Debug, Clone, Copy)]
struct Policy {
repo_mode: RepoMode,
requested: CheckoutMode,
effective: CheckoutMode,
force_copy: bool,
require_hardlinks: bool,
bareuseronly_dirs: bool,
overwrite: OverwriteMode,
enable_fsync: bool,
process_whiteouts: bool,
process_passthrough_whiteouts: bool,
}
impl Policy {
fn new(repo_mode: RepoMode, opts: &CheckoutOptions) -> Policy {
let effective = if repo_mode == RepoMode::BareUserOnly {
CheckoutMode::User
} else {
opts.mode
};
Policy {
repo_mode,
requested: opts.mode,
effective,
force_copy: opts.force_copy,
require_hardlinks: opts.require_hardlinks,
bareuseronly_dirs: opts.bareuseronly_dirs,
overwrite: opts.overwrite,
enable_fsync: opts.enable_fsync,
process_whiteouts: opts.process_whiteouts,
process_passthrough_whiteouts: opts.process_passthrough_whiteouts,
}
}
}
fn hardlink_regular(policy: Policy) -> bool {
if policy.force_copy {
return false;
}
matches!(
(policy.repo_mode, policy.requested),
(RepoMode::Bare, CheckoutMode::None)
| (RepoMode::BareUser, CheckoutMode::User)
| (RepoMode::BareUserOnly, _)
)
}
fn hardlink_symlink(policy: Policy) -> bool {
!policy.force_copy
&& policy.repo_mode == RepoMode::Bare
&& policy.requested == CheckoutMode::None
}
fn hardlink_regular_object(policy: Policy, obj: &FileObject) -> bool {
hardlink_regular(policy) && !matches!(obj.kind, FileKind::Regular { size: 0 })
}
fn require_hardlinks_refuses(policy: Policy, obj: &FileObject) -> bool {
if !policy.require_hardlinks {
return false;
}
match obj.kind {
FileKind::Regular { size } => size != 0 && require_hardlinks_refuses_regular(policy),
FileKind::Symlink { .. } => require_hardlinks_refuses_symlink(policy),
}
}
fn require_hardlinks_refuses_regular(policy: Policy) -> bool {
!hardlink_regular(policy)
}
fn require_hardlinks_refuses_symlink(policy: Policy) -> bool {
matches!(
(policy.repo_mode, policy.requested),
(RepoMode::Archive, _) | (RepoMode::Bare, CheckoutMode::User)
)
}
fn check_hardlink_device(repo: &Repo, policy: Policy, dest: BorrowedFd<'_>) -> Result<()> {
if !policy.require_hardlinks {
return Ok(());
}
let src = repo_fs::stat_fd(repo.objects_fd())?.dev;
let dst = rustix::fs::fstat(dest)?.st_dev;
if src == dst {
return Ok(());
}
Err(Error::HardlinkAcrossDevices { src, dst })
}
fn hardlink_across_devices(repo: &Repo, dest: BorrowedFd<'_>) -> Result<()> {
let src = repo_fs::stat_fd(repo.objects_fd())?.dev;
let dst = rustix::fs::fstat(dest)?.st_dev;
Err(Error::HardlinkAcrossDevices { src, dst })
}
fn widens_type_conflict(policy: Policy) -> bool {
policy.process_whiteouts && policy.overwrite == OverwriteMode::UnionFiles
}
const _: fn() = || {
fn assert_send<T: Send>() {}
assert_send::<CheckoutOptions>();
};
#[cfg(test)]
mod tests {
use super::*;
use crate::write::NamedTemp;
fn policy(repo_mode: RepoMode, mode: CheckoutMode, force_copy: bool) -> Policy {
Policy::new(
repo_mode,
&CheckoutOptions {
mode,
force_copy,
..CheckoutOptions::default()
},
)
}
fn require_policy(repo_mode: RepoMode, mode: CheckoutMode) -> Policy {
Policy::new(
repo_mode,
&CheckoutOptions {
mode,
require_hardlinks: true,
..CheckoutOptions::default()
},
)
}
#[test]
fn hardlink_regular_matrix() {
use CheckoutMode::{None, User};
use RepoMode::{Archive, Bare, BareUser, BareUserOnly, BareUserPrivate, BareUserShared};
assert!(hardlink_regular(policy(Bare, None, false)));
assert!(!hardlink_regular(policy(Bare, User, false)));
assert!(!hardlink_regular(policy(BareUser, None, false)));
assert!(hardlink_regular(policy(BareUser, User, false)));
assert!(hardlink_regular(policy(BareUserOnly, None, false)));
assert!(hardlink_regular(policy(BareUserOnly, User, false)));
assert!(!hardlink_regular(policy(BareUserShared, None, false)));
assert!(!hardlink_regular(policy(BareUserShared, User, false)));
assert!(!hardlink_regular(policy(BareUserPrivate, None, false)));
assert!(!hardlink_regular(policy(BareUserPrivate, User, false)));
assert!(!hardlink_regular(policy(Archive, None, false)));
assert!(!hardlink_regular(policy(Archive, User, false)));
assert!(!hardlink_regular(policy(Bare, None, true)));
assert!(!hardlink_regular(policy(BareUserOnly, None, true)));
}
#[test]
fn hardlink_symlink_matrix() {
use CheckoutMode::{None, User};
use RepoMode::{Archive, Bare, BareUser, BareUserOnly, BareUserPrivate};
assert!(hardlink_symlink(policy(Bare, None, false)));
assert!(!hardlink_symlink(policy(Bare, User, false)));
assert!(!hardlink_symlink(policy(Bare, None, true)));
assert!(!hardlink_symlink(policy(BareUser, None, false)));
assert!(!hardlink_symlink(policy(BareUserOnly, None, false)));
assert!(!hardlink_symlink(policy(BareUserPrivate, None, false)));
assert!(!hardlink_symlink(policy(BareUserPrivate, User, false)));
assert!(!hardlink_symlink(policy(Archive, None, false)));
}
#[test]
fn require_hardlinks_regular_matrix() {
use CheckoutMode::{None, User};
use RepoMode::{
Archive, Bare, BareSplitXattrs, BareUser, BareUserOnly, BareUserPrivate, BareUserShared,
};
assert!(!require_hardlinks_refuses_regular(require_policy(
Bare, None
)));
assert!(require_hardlinks_refuses_regular(require_policy(
Bare, User
)));
assert!(require_hardlinks_refuses_regular(require_policy(
BareUser, None
)));
assert!(!require_hardlinks_refuses_regular(require_policy(
BareUser, User
)));
assert!(!require_hardlinks_refuses_regular(require_policy(
BareUserOnly,
None
)));
assert!(!require_hardlinks_refuses_regular(require_policy(
BareUserOnly,
User
)));
assert!(require_hardlinks_refuses_regular(require_policy(
BareUserShared,
None
)));
assert!(require_hardlinks_refuses_regular(require_policy(
BareUserShared,
User
)));
assert!(require_hardlinks_refuses_regular(require_policy(
BareUserPrivate,
None
)));
assert!(require_hardlinks_refuses_regular(require_policy(
BareUserPrivate,
User
)));
assert!(require_hardlinks_refuses_regular(require_policy(
Archive, None
)));
assert!(require_hardlinks_refuses_regular(require_policy(
Archive, User
)));
assert!(require_hardlinks_refuses_regular(require_policy(
BareSplitXattrs,
None
)));
assert!(require_hardlinks_refuses_regular(require_policy(
BareSplitXattrs,
User
)));
}
#[test]
fn require_hardlinks_symlink_matrix() {
use CheckoutMode::{None, User};
use RepoMode::{
Archive, Bare, BareSplitXattrs, BareUser, BareUserOnly, BareUserPrivate, BareUserShared,
};
assert!(require_hardlinks_refuses_symlink(require_policy(
Archive, None
)));
assert!(require_hardlinks_refuses_symlink(require_policy(
Archive, User
)));
assert!(!require_hardlinks_refuses_symlink(require_policy(
Bare, None
)));
assert!(require_hardlinks_refuses_symlink(require_policy(
Bare, User
)));
assert!(!require_hardlinks_refuses_symlink(require_policy(
BareUser, None
)));
assert!(!require_hardlinks_refuses_symlink(require_policy(
BareUser, User
)));
assert!(!require_hardlinks_refuses_symlink(require_policy(
BareUserOnly,
None
)));
assert!(!require_hardlinks_refuses_symlink(require_policy(
BareUserOnly,
User
)));
assert!(!require_hardlinks_refuses_symlink(require_policy(
BareUserShared,
None
)));
assert!(!require_hardlinks_refuses_symlink(require_policy(
BareUserShared,
User
)));
assert!(!require_hardlinks_refuses_symlink(require_policy(
BareUserPrivate,
None
)));
assert!(!require_hardlinks_refuses_symlink(require_policy(
BareUserPrivate,
User
)));
assert!(!require_hardlinks_refuses_symlink(require_policy(
BareSplitXattrs,
None
)));
assert!(!require_hardlinks_refuses_symlink(require_policy(
BareSplitXattrs,
User
)));
}
#[test]
fn bare_user_only_forces_user_semantics() {
assert_eq!(
policy(RepoMode::BareUserOnly, CheckoutMode::None, false).effective,
CheckoutMode::User
);
assert_eq!(
policy(RepoMode::Bare, CheckoutMode::None, false).effective,
CheckoutMode::None
);
}
struct Scratch(PathBuf);
impl Scratch {
fn new(tag: &str) -> Scratch {
static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("ostrya-{tag}-{}-{n}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
Scratch(dir)
}
fn path(&self) -> &Path {
&self.0
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn named_none_plan(scratch: &Scratch) -> FinishCopy {
use std::io::Write as _;
let dir_fd = Arc::new(OwnedFd::from(std::fs::File::open(scratch.path()).unwrap()));
let tmp_name = ".ostrya-test-tmp".to_owned();
let mut tmp = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(scratch.path().join(&tmp_name))
.unwrap();
tmp.write_all(b"NEW").unwrap();
FinishCopy {
dir: Arc::clone(&dir_fd),
name: "dest".to_owned(),
temp: tmp.into(),
kind: TempKind::Named(NamedTemp::adopt(dir_fd, tmp_name)),
effective: CheckoutMode::User,
uid: 0,
gid: 0,
mode: 0o644,
xattrs: Xattrs::empty(),
enable_fsync: false,
remove_existing: false,
}
}
#[test]
fn named_temp_none_rejects_a_racing_collision() {
let scratch = Scratch::new("co-named-collide");
std::fs::write(scratch.path().join("dest"), b"OLD").unwrap();
let err = finish_copy_blocking(named_none_plan(&scratch));
assert!(
matches!(err, Err(Error::Checkout(_))),
"a colliding destination is a checkout error, got {err:?}"
);
assert_eq!(
std::fs::read(scratch.path().join("dest")).unwrap(),
b"OLD",
"the existing entry is not overwritten"
);
}
#[test]
fn named_temp_none_places_when_absent() {
let scratch = Scratch::new("co-named-fresh");
finish_copy_blocking(named_none_plan(&scratch)).unwrap();
assert_eq!(std::fs::read(scratch.path().join("dest")).unwrap(), b"NEW");
}
#[test]
fn named_temp_removed_when_finish_plan_drops_unrun() {
let scratch = Scratch::new("co-named-drop");
let plan = named_none_plan(&scratch);
assert!(
scratch.path().join(".ostrya-test-tmp").exists(),
"the named temp file exists"
);
drop(plan);
assert!(
!scratch.path().join(".ostrya-test-tmp").exists(),
"the drop removes the named temp file"
);
}
#[test]
fn named_temp_removed_when_metadata_apply_fails() {
use std::os::unix::fs::MetadataExt as _;
let scratch = Scratch::new("co-named-meta-fail");
let mut plan = named_none_plan(&scratch);
let meta = std::fs::metadata(scratch.path().join(".ostrya-test-tmp")).unwrap();
plan.effective = CheckoutMode::None;
plan.uid = meta.uid();
plan.gid = meta.gid();
let mut name = format!("user.{}", "x".repeat(256)).into_bytes();
name.push(0);
plan.xattrs = Xattrs::new([(name, b"v".to_vec())]).unwrap();
let err = finish_copy_blocking(plan);
assert!(
matches!(&err, Err(Error::Io(e)) if e.raw_os_error() == Some(Errno::RANGE.raw_os_error())),
"the xattr apply fails with ERANGE, got {err:?}"
);
assert!(
!scratch.path().join(".ostrya-test-tmp").exists(),
"the named temp file is removed"
);
assert!(
!scratch.path().join("dest").exists(),
"no destination is written"
);
}
struct ForceNamedTemp;
impl ForceNamedTemp {
fn new() -> ForceNamedTemp {
crate::write::FORCE_NAMED_TEMP.set(true);
ForceNamedTemp
}
}
impl Drop for ForceNamedTemp {
fn drop(&mut self) {
crate::write::FORCE_NAMED_TEMP.set(false);
}
}
const BIG: usize = 8 << 20;
async fn archive_repo_with_file(scratch: &Scratch) -> (Repo, Checksum) {
let repo = Repo::create(
&scratch.path().join("repo"),
crate::repo::CreateOptions::new(RepoMode::Archive),
)
.await
.unwrap();
let txn = repo.transaction().await.unwrap();
let meta = FileMeta {
uid: 0,
gid: 0,
mode: 0o100644,
xattrs: Xattrs::empty(),
};
let payload: Vec<u8> = (0..BIG).map(|i| (i % 251) as u8).collect();
let checksum = txn
.write_regfile_inline(None, &meta, &payload)
.await
.unwrap();
txn.commit().await.unwrap();
(repo, checksum)
}
fn temp_names(dir: &Path) -> Vec<String> {
std::fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap().file_name().into_string().unwrap())
.filter(|n| n.starts_with(".ostrya-tmp-"))
.collect()
}
#[test]
fn place_regular_removes_named_temp_when_copy_fails() {
let scratch = Scratch::new("co-named-copy-fail");
let dest = scratch.path().join("dest");
std::fs::create_dir(&dest).unwrap();
let _force = ForceNamedTemp::new();
ostrya_rt::block_on(async {
let (repo, checksum) = archive_repo_with_file(&scratch).await;
let (obj, payload) = repo.open_file(&checksum).await.unwrap();
let object = scratch.path().join("repo/objects").join(loose_path(
&checksum,
ObjectType::File,
RepoMode::Archive,
));
std::fs::OpenOptions::new()
.write(true)
.open(&object)
.unwrap()
.set_len(obj.stored_size() / 2)
.unwrap();
let mut opts = CheckoutOptions::new(CheckoutMode::User);
let policy = Policy::new(RepoMode::Archive, &opts);
let dir_fd = std::fs::File::open(&dest).unwrap();
let entry = Entry { obj: &obj, payload };
let result =
place_regular(&repo, &mut opts, policy, dir_fd.as_fd(), "file", entry).await;
assert!(
matches!(result, Err(Error::Io(_))),
"the copy of a truncated object fails, got {result:?}"
);
});
assert!(
temp_names(&dest).is_empty(),
"the failed copy removes the named temp file"
);
assert!(!dest.join("file").exists(), "no destination is written");
}
#[test]
fn place_regular_removes_named_temp_when_dropped_during_copy() {
let scratch = Scratch::new("co-named-copy-drop");
let dest = scratch.path().join("dest");
std::fs::create_dir(&dest).unwrap();
let _force = ForceNamedTemp::new();
ostrya_rt::block_on(async {
let (repo, checksum) = archive_repo_with_file(&scratch).await;
let (obj, payload) = repo.open_file(&checksum).await.unwrap();
let mut opts = CheckoutOptions::new(CheckoutMode::User);
let policy = Policy::new(RepoMode::Archive, &opts);
let dir_fd = std::fs::File::open(&dest).unwrap();
let entry = Entry { obj: &obj, payload };
let mut fut = Box::pin(place_regular(
&repo,
&mut opts,
policy,
dir_fd.as_fd(),
"file",
entry,
));
let temp = loop {
let poll =
std::future::poll_fn(|cx| std::task::Poll::Ready(fut.as_mut().poll(cx))).await;
assert!(
poll.is_pending(),
"the copy ended before the test saw its temp file, got {poll:?}"
);
if let [name] = temp_names(&dest).as_slice() {
break dest.join(name);
}
};
let len = std::fs::metadata(&temp).unwrap().len();
assert!(
len < BIG as u64,
"the copy is in progress, but the temp file holds {len} bytes"
);
assert!(
!dest.join("file").exists(),
"the copy has not put the file in place"
);
drop(fut);
});
assert!(
temp_names(&dest).is_empty(),
"the drop removes the named temp file"
);
}
}