use std::borrow::Cow;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::path::{Component, Path, PathBuf};
use crate::output::{io_cause, safe_inline, safe_path, WriteTarget};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Durability {
Fsync,
RenameOnly,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Parents {
Create,
Existing,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct DirIdentity {
#[cfg(unix)]
dev: u64,
#[cfg(unix)]
ino: u64,
created: Option<std::time::SystemTime>,
}
impl DirIdentity {
pub(crate) fn of(path: &Path) -> Option<Self> {
let meta = std::fs::metadata(path).ok().filter(|meta| meta.is_dir())?;
Some(Self::of_metadata(&meta))
}
fn of_metadata(meta: &std::fs::Metadata) -> Self {
#[cfg(unix)]
use std::os::unix::fs::MetadataExt as _;
Self {
#[cfg(unix)]
dev: meta.dev(),
#[cfg(unix)]
ino: meta.ino(),
created: meta.created().ok(),
}
}
}
pub(crate) fn atomic_write_file(
target: &WriteTarget,
content: &str,
durability: Durability,
parents: Parents,
) -> std::result::Result<(), mds::MdsError> {
write_below_anchor(target, content, durability, parents, Commit::Replace(None))
.map_err(|failure| worded(target, failure))?
.synced(target)
.map(drop)
}
pub(crate) fn write_compiled(
target: &WriteTarget,
content: &str,
inputs: &Inputs,
) -> std::result::Result<(), mds::MdsError> {
write_compiled_in(target, content, inputs).map(drop)
}
fn write_compiled_in(
target: &WriteTarget,
content: &str,
inputs: &Inputs,
) -> std::result::Result<imp::Dir, mds::MdsError> {
write_below_anchor(
target,
content,
Durability::RenameOnly,
Parents::Create,
Commit::Output {
inputs,
module: declares_a_module(content),
},
)
.map_err(|failure| worded(target, failure))?
.synced(target)
}
pub(crate) fn write_compiled_and_look(
target: &WriteTarget,
content: &str,
inputs: &Inputs,
beside: &WriteTarget,
) -> std::result::Result<Beside, mds::MdsError> {
let dir = write_compiled_in(target, content, inputs)?;
Ok(match (Below::of(target), Below::of(beside)) {
(Ok(written), Ok(beside))
if written.anchor == beside.anchor && written.dirs == beside.dirs =>
{
imp::look(&dir, beside.name)
}
_ => Beside::Something,
})
}
#[must_use]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Beside {
Nothing,
Something,
}
#[derive(Debug, Clone, Default)]
pub(crate) struct Inputs {
files: Vec<PathBuf>,
found: Option<Found>,
}
#[derive(Debug, Clone)]
struct Found {
from: PathBuf,
find: fn(&Path) -> Option<PathBuf>,
}
impl Inputs {
pub(crate) fn new(files: impl IntoIterator<Item = PathBuf>) -> Self {
Self {
files: files.into_iter().collect(),
found: None,
}
}
#[must_use = "the search is part of the inputs only in the value returned"]
pub(crate) fn and_found_from(self, from: &Path, find: fn(&Path) -> Option<PathBuf>) -> Self {
Self {
found: Some(Found {
from: from.to_path_buf(),
find,
}),
..self
}
}
fn paths(&self) -> impl Iterator<Item = Cow<'_, Path>> {
let named = self.files.iter().map(|file| Cow::Borrowed(file.as_path()));
let found = self
.found
.iter()
.filter_map(|found| (found.find)(&found.from))
.map(Cow::Owned);
named.chain(found)
}
}
pub(crate) fn create_new(
target: &WriteTarget,
content: &str,
durability: Durability,
parents: Parents,
) -> std::result::Result<(), NotCreated> {
match write_below_anchor(target, content, durability, parents, Commit::New) {
Ok(landed) => landed.synced(target).map(drop).map_err(NotCreated::Failed),
Err(Failure::Exists) => Err(NotCreated::Exists),
Err(failure) => Err(NotCreated::Failed(worded(target, failure))),
}
}
#[derive(Debug)]
pub(crate) enum NotCreated {
Exists,
Failed(mds::MdsError),
}
pub(crate) fn write_over_own(
target: &WriteTarget,
own: Option<&str>,
content: &str,
durability: Durability,
parents: Parents,
) -> std::result::Result<(), NotCreated> {
let held = match own {
Some(own) => own_file(target, own),
None => Ok(None),
};
let written = match held {
Ok(Some(held)) => {
pause_before_replace();
imp::replace_held(held, content.as_bytes(), durability)
}
Ok(None) => write_below_anchor(target, content, durability, parents, Commit::New),
Err(failure) => Err(failure),
};
match written {
Ok(landed) => landed.synced(target).map(drop).map_err(NotCreated::Failed),
Err(
Failure::Exists | Failure::Changed | Failure::LinkAtTarget | Failure::NotARegularFile,
) => Err(NotCreated::Exists),
Err(failure) => Err(NotCreated::Failed(worded(target, failure))),
}
}
fn own_file(target: &WriteTarget, own: &str) -> std::result::Result<Option<imp::Held>, Failure> {
let below = Below::of(target)?;
match imp::read_stamped(&below, target.checked_anchor(), own.as_bytes()) {
Ok(held) => Ok(Some(held)),
Err(Failure::Changed | Failure::LinkAtTarget | Failure::NotARegularFile) => Ok(None),
Err(Failure::Io(e)) if imp::nothing_below(&e) => Ok(None),
Err(failure) => Err(failure),
}
}
fn write_below_anchor(
target: &WriteTarget,
content: &str,
durability: Durability,
parents: Parents,
commit: Commit<'_>,
) -> std::result::Result<Landed, Failure> {
let below = Below::of(target)?;
let anchor = target.checked_anchor();
imp::write(
&below,
anchor,
content.as_bytes(),
durability,
parents,
commit,
)
}
struct Landed {
dir: imp::Dir,
not_synced: Option<std::io::Error>,
}
impl Landed {
fn synced(self, target: &WriteTarget) -> std::result::Result<imp::Dir, mds::MdsError> {
match self.not_synced {
None => Ok(self.dir),
Some(cause) => Err(not_synced(target, &cause)),
}
}
}
#[derive(Debug, Clone, Copy)]
enum Commit<'i> {
Replace(Option<&'i imp::Stamp>),
Output { inputs: &'i Inputs, module: bool },
New,
}
pub(crate) struct ReadForRewrite {
target: WriteTarget,
held: imp::Held,
}
pub(crate) fn read_stamped(
target: &WriteTarget,
read: &str,
) -> std::result::Result<ReadForRewrite, mds::MdsError> {
let below = Below::of(target).map_err(|e| io_error(&target.shown, io_cause(&e)))?;
let held = imp::read_stamped(&below, target.checked_anchor(), read.as_bytes())
.map_err(|f| worded(target, f))?;
Ok(ReadForRewrite {
target: target.clone(),
held,
})
}
pub(crate) fn replace_if_unchanged(
read: ReadForRewrite,
content: &str,
durability: Durability,
) -> std::result::Result<Rewritten, mds::MdsError> {
pause_before_replace();
let ReadForRewrite { target, held } = read;
let landed =
imp::replace_held(held, content.as_bytes(), durability).map_err(|f| worded(&target, f))?;
Ok(match landed.not_synced {
None => Rewritten::Done,
Some(cause) => Rewritten::NotSynced(not_synced(&target, &cause)),
})
}
#[must_use]
#[derive(Debug)]
pub(crate) enum Rewritten {
Done,
NotSynced(mds::MdsError),
}
pub(crate) fn replace_owing_sync(
read: ReadForRewrite,
content: &str,
) -> std::result::Result<Renamed, mds::MdsError> {
pause_before_replace();
let ReadForRewrite { target, held } = read;
let dir = imp::rename_held(held, content.as_bytes()).map_err(|f| worded(&target, f))?;
Ok(Renamed { target, dir })
}
#[must_use]
pub(crate) struct Renamed {
target: WriteTarget,
dir: imp::Dir,
}
pub(crate) struct DirectorySyncs<T> {
directory_of: Vec<usize>,
last: Vec<usize>,
owed: Vec<Option<Owed<T>>>,
}
struct Owed<T> {
dir: imp::Dir,
files: Vec<(WriteTarget, T)>,
}
impl<T> DirectorySyncs<T> {
pub(crate) fn new<'p>(files: impl IntoIterator<Item = &'p Path>) -> Self {
let files = files.into_iter();
let mut directories: HashMap<&Path, usize> = HashMap::new();
let mut directory_of = Vec::with_capacity(files.size_hint().0);
let mut last: Vec<usize> = Vec::new();
for (place, file) in files.enumerate() {
let parent = file.parent().unwrap_or(Path::new(""));
let directory = *directories.entry(parent).or_insert_with(|| {
last.push(place);
last.len() - 1
});
if let Some(at) = last.get_mut(directory) {
*at = place;
}
directory_of.push(directory);
}
let owed = std::iter::repeat_with(|| None).take(last.len()).collect();
Self {
directory_of,
last,
owed,
}
}
pub(crate) fn landed(&mut self, place: usize, renamed: Renamed, item: T) -> Option<Flushed<T>> {
let Renamed { target, dir } = renamed;
let owed = self
.directory_of
.get(place)
.and_then(|&directory| self.owed.get_mut(directory));
let Some(owed) = owed else {
return Some(flush(Owed {
dir,
files: vec![(target, item)],
}));
};
if let Some(batch) = owed
.as_mut()
.filter(|batch| imp::same_directory(&batch.dir, &dir))
{
batch.files.push((target, item));
return None;
}
owed.replace(Owed {
dir,
files: vec![(target, item)],
})
.map(flush)
}
pub(crate) fn past(&mut self, place: usize) -> Option<Flushed<T>> {
let &directory = self.directory_of.get(place)?;
if self.last.get(directory) != Some(&place) {
return None;
}
self.owed.get_mut(directory)?.take().map(flush)
}
}
fn flush<T>(owed: Owed<T>) -> Flushed<T> {
let Owed { dir, files } = owed;
let failure = imp::sync_owed(&dir).err();
drop(dir);
Flushed {
files: files.into_iter(),
failure,
}
}
pub(crate) struct Flushed<T> {
files: std::vec::IntoIter<(WriteTarget, T)>,
failure: Option<std::io::Error>,
}
impl<T> Iterator for Flushed<T> {
type Item = Synced<T>;
fn next(&mut self) -> Option<Synced<T>> {
let (target, item) = self.files.next()?;
Some(match &self.failure {
None => Synced::Durable(item),
Some(cause) => Synced::NotSynced(item, not_synced(&target, cause)),
})
}
}
#[must_use]
#[derive(Debug)]
pub(crate) enum Synced<T> {
Durable(T),
NotSynced(T, mds::MdsError),
}
pub(crate) fn remove_proven(
target: &WriteTarget,
proof: impl FnOnce(&mut std::fs::File) -> std::io::Result<bool>,
) -> std::result::Result<Removal, NotRemoved> {
let below = Below::of(target).map_err(|e| NotRemoved::Failed(safe_inline(io_cause(&e))))?;
imp::remove(&below, target.checked_anchor(), proof).map_err(|f| not_removed(target, f))
}
#[must_use]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Removal {
Removed,
Missing,
Kept,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum NotRemoved {
NotAFile,
Link,
Unreadable(String),
Failed(String),
}
impl NotRemoved {
pub(crate) fn out_dir_moved() -> Self {
Self::Failed(OUT_DIR_MOVED.to_owned())
}
pub(crate) fn cause(&self) -> &str {
match self {
Self::NotAFile => NOT_A_REGULAR_FILE,
Self::Link => SYMLINK_REMOVAL_REFUSAL,
Self::Unreadable(cause) | Self::Failed(cause) => cause,
}
}
}
fn not_removed(target: &WriteTarget, failure: Failure) -> NotRemoved {
let cause = |e: &std::io::Error| safe_inline(io_cause(e));
match failure {
Failure::NotARegularFile => NotRemoved::NotAFile,
Failure::Unreadable(e) => NotRemoved::Unreadable(cause(&e)),
Failure::AnchorMoved => NotRemoved::out_dir_moved(),
Failure::Changed => NotRemoved::Failed(CHANGED_WHILE_CHECKED.to_owned()),
Failure::LinkBelowAnchor { depth } => NotRemoved::Failed(format!(
"{FOLLOW_REFUSAL} at {}",
safe_path(&shown_directory(target, depth))
)),
Failure::LinkAtTarget => NotRemoved::Link,
Failure::Exists => NotRemoved::Failed(cause(&std::io::ErrorKind::AlreadyExists.into())),
Failure::Module => NotRemoved::Failed(MODULE_REFUSAL.to_owned()),
Failure::Input => NotRemoved::Failed(INPUT_REFUSAL.to_owned()),
Failure::UnreadMarkdown(e) | Failure::Io(e) => NotRemoved::Failed(cause(&e)),
}
}
fn worded(target: &WriteTarget, failure: Failure) -> mds::MdsError {
match failure {
Failure::AnchorMoved => out_dir_moved(target),
Failure::Changed => io_error(&target.shown, CHANGED_SINCE_READ.to_owned()),
Failure::Exists => io_error(
&target.shown,
io_cause(&std::io::ErrorKind::AlreadyExists.into()),
),
Failure::LinkBelowAnchor { depth } => io_error(
&target.shown,
format!(
"{FOLLOW_REFUSAL} at {}",
safe_path(&shown_directory(target, depth))
),
),
Failure::LinkAtTarget => io_error(&target.shown, SYMLINK_REFUSAL.to_owned()),
Failure::Module => io_error(
&target.shown,
format!("{MODULE_REFUSAL} ({MODULE_WAY_OUT})"),
),
Failure::Input => io_error(&target.shown, INPUT_REFUSAL.to_owned()),
Failure::UnreadMarkdown(e) => mds::MdsError::Io {
message: format!(
"cannot write {}: {MODULE_UNKNOWN}: {}",
safe_path(&target.shown),
safe_inline(io_cause(&e))
),
},
Failure::NotARegularFile => io_error(&target.shown, NOT_A_REGULAR_FILE.to_owned()),
Failure::Unreadable(e) | Failure::Io(e) => io_error(&target.shown, io_cause(&e)),
}
}
pub(crate) const ALREADY_EXISTS: &str = "already exists (use --force to overwrite)";
const SYMLINK_REFUSAL: &str = "refusing to replace a symlink";
const SYMLINK_REMOVAL_REFUSAL: &str = "refusing to remove a symlink";
const MODULE_REFUSAL: &str = "refusing to replace an MDS module";
const MODULE_WAY_OUT: &str =
"an output that declares type: mds is a generated module, and is rebuilt from its source";
const INPUT_REFUSAL: &str = "refusing to replace a file this run reads";
const MODULE_UNKNOWN: &str = "cannot tell whether it is an MDS module";
const CHANGED_SINCE_READ: &str = "changed since it was read; not written";
const CHANGED_WHILE_CHECKED: &str = "changed while it was checked";
const NOT_A_REGULAR_FILE: &str = "not a regular file";
const FOLLOW_REFUSAL: &str = "refusing to follow a symlink";
const OUT_DIR_MOVED: &str = "the output directory now resolves to a different directory; \
restart mds watch to follow it";
pub(crate) fn out_dir_moved(target: &WriteTarget) -> mds::MdsError {
io_error(&target.shown, OUT_DIR_MOVED.to_owned())
}
fn io_error(shown: &Path, cause: String) -> mds::MdsError {
mds::MdsError::Io {
message: format!("cannot write {}: {}", safe_path(shown), safe_inline(cause)),
}
}
const NOT_SYNCED: &str = "written, but its directory could not be synced";
fn not_synced(target: &WriteTarget, e: &std::io::Error) -> mds::MdsError {
mds::MdsError::Io {
message: format!(
"{} {NOT_SYNCED}: {}",
safe_path(&target.shown),
safe_inline(io_cause(e))
),
}
}
fn shown_directory(target: &WriteTarget, depth: usize) -> PathBuf {
let components: Vec<Component<'_>> = target.shown.components().collect();
match components.len().checked_sub(target.below_anchor()) {
Some(above) if above + depth < components.len() => {
components[..=above + depth].iter().collect()
}
_ => target.shown.clone(),
}
}
#[derive(Debug)]
enum Failure {
AnchorMoved,
Changed,
Exists,
LinkBelowAnchor { depth: usize },
LinkAtTarget,
Module,
Input,
UnreadMarkdown(std::io::Error),
NotARegularFile,
Unreadable(std::io::Error),
Io(std::io::Error),
}
impl From<std::io::Error> for Failure {
fn from(e: std::io::Error) -> Self {
Self::Io(e)
}
}
#[cfg(unix)]
impl From<rustix::io::Errno> for Failure {
fn from(e: rustix::io::Errno) -> Self {
Self::Io(e.into())
}
}
#[derive(Debug, PartialEq, Eq)]
struct Below<'a> {
anchor: PathBuf,
dirs: Vec<&'a OsStr>,
name: &'a OsStr,
}
impl<'a> Below<'a> {
fn of(target: &'a WriteTarget) -> std::io::Result<Self> {
if ends_as_a_directory(&target.path) {
return Err(std::io::ErrorKind::IsADirectory.into());
}
let components: Vec<Component<'a>> = target.path.components().collect();
let below = target.below_anchor();
let above = components
.len()
.checked_sub(below)
.filter(|_| below > 0)
.ok_or_else(|| std::io::Error::from(std::io::ErrorKind::InvalidInput))?;
let (anchor, under) = components.split_at(above);
let Some((last, dirs)) = under.split_last() else {
return Err(std::io::ErrorKind::InvalidInput.into());
};
let Component::Normal(name) = *last else {
return Err(std::io::ErrorKind::IsADirectory.into());
};
if cfg!(windows) && names_a_stream(name) {
return Err(std::io::ErrorKind::InvalidFilename.into());
}
let dirs = dirs
.iter()
.map(|component| match component {
Component::Normal(dir) => Ok(*dir),
_ => Err(std::io::Error::from(std::io::ErrorKind::InvalidInput)),
})
.collect::<std::io::Result<Vec<&'a OsStr>>>()?;
let anchor = if anchor.is_empty() {
PathBuf::from(".")
} else {
anchor.iter().collect()
};
Ok(Self { anchor, dirs, name })
}
}
fn names_a_stream(name: &OsStr) -> bool {
name.as_encoded_bytes().contains(&b':')
}
fn ends_as_a_directory(path: &Path) -> bool {
let separator = |byte: &u8| std::path::is_separator(char::from(*byte));
match path.as_os_str().as_encoded_bytes() {
[.., last] if separator(last) => true,
[.., before, b'.'] => separator(before),
_ => false,
}
}
fn names_markdown(name: &OsStr) -> bool {
Path::new(name)
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("md"))
}
fn names_source(name: &OsStr) -> bool {
Path::new(name)
.extension()
.is_some_and(|ext| ext.eq_ignore_ascii_case("mds"))
}
#[cfg(any(windows, test))]
fn as_windows_opens<T: Copy + Into<u32>>(name: &[T]) -> &[T] {
match name
.iter()
.rposition(|&unit| !matches!(unit.into(), 0x2E | 0x20))
{
Some(last) => &name[..=last],
None => name,
}
}
fn is_mds_module(file: &mut std::fs::File) -> std::io::Result<bool> {
const FENCE: &[u8] = b"---\r\n";
const CLOSE: &[u8] = b"\n---";
const ONE_READ: u64 = 8 * 1024;
let fence = u64::try_from(FENCE.len()).unwrap_or(u64::MAX);
let mut head = mds::read_at_most(file, fence, 0)?;
let after_fence = if head.starts_with(b"---\n") {
FENCE.len() - 1
} else if head.starts_with(FENCE) {
FENCE.len()
} else {
return Ok(false);
};
let mut from = after_fence;
for _ in 0..=mds::MAX_FILE_SIZE / ONE_READ {
if let Some(at) = head[from..]
.windows(CLOSE.len())
.position(|bytes| bytes == CLOSE)
{
head.truncate(from + at + CLOSE.len());
break;
}
let held = u64::try_from(head.len()).unwrap_or(u64::MAX);
let more = mds::read_at_most(
file,
ONE_READ.min(mds::MAX_FILE_SIZE.saturating_sub(held)),
0,
)?;
if more.is_empty() {
break;
}
from = head.len().saturating_sub(CLOSE.len() - 1).max(after_fence);
head.extend(more);
}
Ok(declares_a_module(&String::from_utf8_lossy(&head)))
}
fn declares_a_module(text: &str) -> bool {
const MARKDOWN_KEY: &str = "module.md";
let key = mds::ModuleRef::keyed(MARKDOWN_KEY).typed(MARKDOWN_KEY);
mds::check_module_type(key, text).is_ok()
}
const TEMP_PREFIX: &str = ".mds-tmp-";
const TEMP_SUFFIX: &str = ".tmp";
#[cfg(unix)]
use unix as imp;
#[cfg(windows)]
use windows as imp;
#[cfg(unix)]
mod unix {
use std::ffi::{OsStr, OsString};
use std::fs::File;
use std::io::Write as _;
use std::os::fd::{AsFd as _, BorrowedFd, OwnedFd};
use std::path::Path;
use rustix::fs::{self, AtFlags, FileType, Mode, OFlags, CWD};
use rustix::io::Errno;
use super::{
Below, Beside, Commit, DirIdentity, Durability, Failure, Inputs, Landed, Parents, Removal,
TEMP_PREFIX, TEMP_SUFFIX,
};
#[cfg(any(target_os = "linux", target_os = "android"))]
const SEARCH: OFlags = OFlags::PATH;
#[cfg(not(any(target_os = "linux", target_os = "android")))]
const SEARCH: OFlags = OFlags::RDONLY;
const ANCHOR: OFlags = SEARCH.union(OFlags::DIRECTORY).union(OFlags::CLOEXEC);
const BELOW: OFlags = SEARCH
.union(OFlags::DIRECTORY)
.union(OFlags::NOFOLLOW)
.union(OFlags::CLOEXEC);
const TO_SYNC: OFlags = OFlags::RDONLY
.union(OFlags::DIRECTORY)
.union(OFlags::CLOEXEC);
const TEMP: OFlags = OFlags::WRONLY
.union(OFlags::CREATE)
.union(OFlags::EXCL)
.union(OFlags::NOFOLLOW)
.union(OFlags::CLOEXEC);
const IN_PLACE: OFlags = OFlags::WRONLY
.union(OFlags::CREATE)
.union(OFlags::EXCL)
.union(OFlags::NOFOLLOW)
.union(OFlags::CLOEXEC);
const READ: OFlags = OFlags::RDONLY
.union(OFlags::NOFOLLOW)
.union(OFlags::NONBLOCK)
.union(OFlags::CLOEXEC);
const NEW_FILE: Mode = Mode::from_raw_mode(0o666);
const OWNER_ONLY: Mode = Mode::RUSR.union(Mode::WUSR);
const PERMISSION_BITS: fs::RawMode = 0o777;
const NEW_DIR: Mode = Mode::from_raw_mode(0o777);
pub(super) const MAX_TEMP_ATTEMPTS: usize = 16;
pub(super) type Dir = OwnedFd;
pub(super) fn write(
below: &Below<'_>,
anchor: Option<DirIdentity>,
content: &[u8],
durability: Durability,
parents: Parents,
commit: Commit<'_>,
) -> Result<Landed, Failure> {
let dir = walk(below, anchor, parents)?;
replace(dir, below.name, content, durability, commit)
}
pub(super) fn look(dir: &Dir, name: &OsStr) -> Beside {
match fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW) {
Err(Errno::NOENT) => Beside::Nothing,
_ => Beside::Something,
}
}
fn walk(
below: &Below<'_>,
anchor: Option<DirIdentity>,
parents: Parents,
) -> Result<OwnedFd, Failure> {
let mut dir = match anchor {
Some(checked) => match open_anchor(&below.anchor, Parents::Existing) {
Ok(dir) => opened_as_checked(dir, checked)?,
Err(Failure::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => {
return Err(Failure::AnchorMoved)
}
Err(failure) => return Err(failure),
},
None => open_anchor(&below.anchor, parents)?,
};
for (depth, name) in below.dirs.iter().enumerate() {
let next = open_below(dir.as_fd(), name, parents)
.map_err(|errno| below_failure(dir.as_fd(), name, depth, errno))?;
dir = next;
}
Ok(dir)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct Stamp {
device: i128,
inode: i128,
size: i128,
modified: (i128, i128),
changed: (i128, i128),
}
impl Stamp {
fn of(stat: &fs::Stat) -> Self {
Self {
device: i128::from(stat.st_dev),
inode: i128::from(stat.st_ino),
size: i128::from(stat.st_size),
modified: (i128::from(stat.st_mtime), i128::from(stat.st_mtime_nsec)),
changed: (i128::from(stat.st_ctime), i128::from(stat.st_ctime_nsec)),
}
}
fn holds(&self, dir: BorrowedFd<'_>, name: &OsStr) -> bool {
fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW)
.is_ok_and(|stat| Self::of(&stat) == *self)
}
}
pub(super) struct Held {
dir: OwnedFd,
name: OsString,
stamp: Stamp,
}
pub(super) fn read_stamped(
below: &Below<'_>,
anchor: Option<DirIdentity>,
read: &[u8],
) -> Result<Held, Failure> {
let dir = walk(below, anchor, Parents::Existing)?;
let mut file = match open_to_read(dir.as_fd(), below.name) {
Ok(file) => file,
Err(Errno::LOOP) => return Err(Failure::LinkAtTarget),
Err(Errno::NOENT) => return Err(Failure::Changed),
Err(_) if is_no_regular_file(dir.as_fd(), below.name) => return Err(Failure::Changed),
Err(e) => return Err(e.into()),
};
let stat = fs::fstat(&file)?;
if FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile {
return Err(Failure::Changed);
}
let expected = u64::try_from(read.len()).unwrap_or(u64::MAX);
if mds::read_at_most(&mut file, expected.saturating_add(1), expected)? != read {
return Err(Failure::Changed);
}
Ok(Held {
dir,
name: below.name.to_owned(),
stamp: Stamp::of(&stat),
})
}
pub(super) fn replace_held(
held: Held,
content: &[u8],
durability: Durability,
) -> Result<Landed, Failure> {
let commit = Commit::Replace(Some(&held.stamp));
replace(held.dir, &held.name, content, durability, commit)
}
pub(super) fn rename_held(held: Held, content: &[u8]) -> Result<Dir, Failure> {
let commit = Commit::Replace(Some(&held.stamp));
put(held.dir, &held.name, content, Durability::Fsync, commit)
}
pub(super) fn sync_owed(dir: &Dir) -> std::io::Result<()> {
sync_directory(dir.as_fd())
}
pub(super) fn same_directory(a: &Dir, b: &Dir) -> bool {
match (fs::fstat(a), fs::fstat(b)) {
(Ok(a), Ok(b)) => a.st_dev == b.st_dev && a.st_ino == b.st_ino,
_ => false,
}
}
pub(super) fn remove(
below: &Below<'_>,
anchor: Option<DirIdentity>,
proof: impl FnOnce(&mut File) -> std::io::Result<bool>,
) -> Result<Removal, Failure> {
let dir = match walk(below, anchor, Parents::Existing) {
Ok(dir) => dir,
Err(Failure::Io(e)) if nothing_below(&e) => return Ok(Removal::Missing),
Err(failure) => return Err(failure),
};
let name = below.name;
match fs::statat(&dir, name, AtFlags::SYMLINK_NOFOLLOW) {
Ok(stat) => match FileType::from_raw_mode(stat.st_mode) {
FileType::RegularFile => {}
FileType::Symlink => return Err(Failure::LinkAtTarget),
_ => return Err(Failure::NotARegularFile),
},
Err(Errno::NOENT | Errno::NAMETOOLONG) => return Ok(Removal::Missing),
Err(e) => return Err(Failure::Unreadable(e.into())),
}
let mut file = match open_to_read(dir.as_fd(), name) {
Ok(file) => file,
Err(Errno::LOOP) => return Err(Failure::LinkAtTarget),
Err(Errno::NOENT) => return Ok(Removal::Missing),
Err(e) => return Err(Failure::Unreadable(e.into())),
};
let opened = fs::fstat(&file).map_err(|e| Failure::Unreadable(e.into()))?;
if FileType::from_raw_mode(opened.st_mode) != FileType::RegularFile {
return Err(Failure::NotARegularFile);
}
let stamp = Stamp::of(&opened);
if !proof(&mut file).map_err(Failure::Unreadable)? {
return Ok(Removal::Kept);
}
drop(file);
match fs::statat(&dir, name, AtFlags::SYMLINK_NOFOLLOW) {
Ok(now) if Stamp::of(&now) == stamp => {}
Ok(_) => return Err(Failure::Changed),
Err(Errno::NOENT) => return Ok(Removal::Missing),
Err(e) => return Err(e.into()),
}
match fs::unlinkat(&dir, name, AtFlags::empty()) {
Ok(()) => Ok(Removal::Removed),
Err(Errno::NOENT) => Ok(Removal::Missing),
Err(e) => Err(e.into()),
}
}
pub(super) fn nothing_below(e: &std::io::Error) -> bool {
matches!(Errno::from_io_error(e), Some(Errno::NOENT | Errno::NOTDIR))
}
fn open_to_read(dir: BorrowedFd<'_>, name: &OsStr) -> Result<File, Errno> {
fs::openat(dir, name, READ, Mode::empty()).map(File::from)
}
fn open_anchor(anchor: &Path, parents: Parents) -> Result<OwnedFd, Failure> {
let open = || {
search_or_read(ANCHOR, SEARCH, |flags| {
fs::openat(CWD, anchor, flags, Mode::empty())
})
};
match open() {
Err(Errno::NOENT) if parents == Parents::Create => {
std::fs::create_dir_all(anchor).map_err(|e| {
if e.kind() == std::io::ErrorKind::AlreadyExists {
Errno::NOENT.into()
} else {
e
}
})?;
Ok(open()?)
}
opened => Ok(opened?),
}
}
pub(super) fn search_or_read<T>(
flags: OFlags,
search: OFlags,
open: impl Fn(OFlags) -> Result<T, Errno>,
) -> Result<T, Errno> {
match open(flags) {
Err(Errno::INVAL) if !search.is_empty() && flags.contains(search) => {
open(flags.difference(search))
}
opened => opened,
}
}
fn opened_as_checked(dir: OwnedFd, checked: DirIdentity) -> Result<OwnedFd, Failure> {
let dir = File::from(dir);
if DirIdentity::of_metadata(&dir.metadata()?) == checked {
Ok(OwnedFd::from(dir))
} else {
Err(Failure::AnchorMoved)
}
}
pub(super) fn below_failure(
dir: BorrowedFd<'_>,
name: &OsStr,
depth: usize,
errno: Errno,
) -> Failure {
if errno == Errno::LOOP || is_symlink(dir, name) {
Failure::LinkBelowAnchor { depth }
} else {
Failure::from(errno)
}
}
fn open_below(dir: BorrowedFd<'_>, name: &OsStr, parents: Parents) -> Result<OwnedFd, Errno> {
let open = || {
search_or_read(BELOW, SEARCH, |flags| {
fs::openat(dir, name, flags, Mode::empty())
})
};
match open() {
Err(Errno::NOENT) if parents == Parents::Create => {
match fs::mkdirat(dir, name, NEW_DIR) {
Ok(()) | Err(Errno::EXIST) => {}
Err(e) => return Err(e),
}
open()
}
opened => opened,
}
}
fn is_symlink(dir: BorrowedFd<'_>, name: &OsStr) -> bool {
fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW)
.is_ok_and(|stat| FileType::from_raw_mode(stat.st_mode) == FileType::Symlink)
}
fn is_no_regular_file(dir: BorrowedFd<'_>, name: &OsStr) -> bool {
fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW)
.is_ok_and(|stat| FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile)
}
fn replace(
dir: OwnedFd,
name: &OsStr,
content: &[u8],
durability: Durability,
commit: Commit<'_>,
) -> Result<Landed, Failure> {
let dir = put(dir, name, content, durability, commit)?;
let not_synced = match durability {
Durability::Fsync => sync_directory(dir.as_fd()).err(),
Durability::RenameOnly => None,
};
Ok(Landed { dir, not_synced })
}
fn put(
dir: OwnedFd,
name: &OsStr,
content: &[u8],
durability: Durability,
commit: Commit<'_>,
) -> Result<OwnedFd, Failure> {
let replaced = match fs::statat(&dir, name, AtFlags::SYMLINK_NOFOLLOW) {
Ok(stat) => match (FileType::from_raw_mode(stat.st_mode), commit) {
(FileType::Symlink, _) => return Err(Failure::LinkAtTarget),
(_, Commit::New) => return Err(Failure::Exists),
(FileType::RegularFile, _) => Some(stat),
(FileType::Directory, _) => None,
_ => return Err(Failure::NotARegularFile),
},
Err(Errno::NOENT) => None,
Err(e) => return Err(e.into()),
};
let (mut temp, file) = match &replaced {
Some(replaced) => create_replacement(dir.as_fd(), replaced)?,
None => create_temp(dir.as_fd(), NEW_FILE, temp_names())?,
};
fill(file, content, durability)?;
match commit {
Commit::Replace(_) | Commit::Output { .. } => {
ready_to_replace(dir.as_fd(), name, commit)?;
fs::renameat(dir.as_fd(), &temp.name, dir.as_fd(), name)?;
temp.renamed = true;
drop(temp);
}
Commit::New => {
super::pause_before_replace();
commit_new(temp, name, content, durability, &NO_CLOBBER)?;
}
}
Ok(dir)
}
fn create_replacement<'d>(
dir: BorrowedFd<'d>,
replaced: &fs::Stat,
) -> Result<(Temp<'d>, File), Failure> {
let (temp, file) = create_temp(dir, OWNER_ONLY, temp_names())?;
let same_owner = fs::fstat(&file)?.st_uid == replaced.st_uid;
match kept_mode(replaced.st_mode, same_owner) {
Some(mode) => {
fs::fchmod(&file, mode)?;
Ok((temp, file))
}
None => {
drop((temp, file));
Ok(create_temp(dir, NEW_FILE, temp_names())?)
}
}
}
pub(super) fn kept_mode(st_mode: fs::RawMode, same_owner: bool) -> Option<Mode> {
same_owner.then(|| Mode::from_raw_mode(st_mode & PERMISSION_BITS))
}
fn ready_to_replace(
dir: BorrowedFd<'_>,
name: &OsStr,
commit: Commit<'_>,
) -> Result<(), Failure> {
match commit {
Commit::Replace(Some(stamp)) if !stamp.holds(dir, name) => Err(Failure::Changed),
Commit::Output { inputs, module } => never_over_an_input(dir, name, inputs, module),
_ => Ok(()),
}
}
fn never_over_an_input(
dir: BorrowedFd<'_>,
name: &OsStr,
inputs: &Inputs,
module: bool,
) -> Result<(), Failure> {
let stat = match fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW) {
Ok(stat) if FileType::from_raw_mode(stat.st_mode) == FileType::RegularFile => stat,
Ok(_) | Err(Errno::NOENT) => return Ok(()),
Err(e) => return Err(e.into()),
};
if !module && is_a_module(dir, name)? {
return Err(Failure::Module);
}
if is_an_input(inputs, &stat) {
return Err(Failure::Input);
}
Ok(())
}
fn is_an_input(inputs: &Inputs, stat: &fs::Stat) -> bool {
inputs.paths().any(|file| {
fs::stat(&*file)
.is_ok_and(|input| input.st_dev == stat.st_dev && input.st_ino == stat.st_ino)
})
}
fn is_a_module(dir: BorrowedFd<'_>, name: &OsStr) -> Result<bool, Failure> {
if super::names_source(name) {
return Ok(true);
}
if !super::names_markdown(name) {
return Ok(false);
}
let judge = || -> std::io::Result<bool> {
let mut file = match open_to_read(dir, name) {
Ok(file) => file,
Err(Errno::NOENT | Errno::LOOP) => return Ok(false),
Err(e) => return Err(e.into()),
};
let opened = fs::fstat(&file)?;
if FileType::from_raw_mode(opened.st_mode) != FileType::RegularFile {
return Ok(false);
}
super::is_mds_module(&mut file)
};
judge().map_err(Failure::UnreadMarkdown)
}
fn fill(mut file: File, content: &[u8], durability: Durability) -> std::io::Result<()> {
file.write_all(content)?;
if durability == Durability::Fsync {
sync_file(&file)?;
}
Ok(())
}
fn sync_file(file: &File) -> std::io::Result<()> {
full_or_plain(
|| file.sync_all(),
|| fs::fsync(file).map_err(std::io::Error::from),
)
}
pub(super) fn full_or_plain(
full: impl FnOnce() -> std::io::Result<()>,
plain: impl FnOnce() -> std::io::Result<()>,
) -> std::io::Result<()> {
match full() {
Err(e) if refused(&e) => plain(),
synced => synced,
}
}
pub(super) type Step<'s> = &'s dyn Fn(BorrowedFd<'_>, &OsStr, &OsStr) -> Result<(), Errno>;
pub(super) type Fill<'s> = &'s dyn Fn(File, &[u8], Durability) -> std::io::Result<()>;
pub(super) struct NewSteps<'s> {
pub(super) rename: Step<'s>,
pub(super) link: Step<'s>,
pub(super) fill: Fill<'s>,
}
pub(super) const NO_CLOBBER: NewSteps<'static> = NewSteps {
rename: &rename_noreplace,
link: &link_new,
fill: &fill,
};
pub(super) fn commit_new(
mut temp: Temp<'_>,
name: &OsStr,
content: &[u8],
durability: Durability,
steps: &NewSteps<'_>,
) -> Result<(), Failure> {
let dir = temp.dir;
match (steps.rename)(dir, &temp.name, name) {
Ok(()) => {
temp.renamed = true;
Ok(())
}
Err(errno) if no_such_rename(errno) => match (steps.link)(dir, &temp.name, name) {
Ok(()) => Ok(()),
Err(errno) if no_hard_links(errno) => {
write_in_place(dir, name, content, durability, steps.fill)
}
Err(errno) => Err(refused_if_there(errno)),
},
Err(errno) => Err(refused_if_there(errno)),
}
}
#[cfg(any(
target_os = "linux",
target_os = "android",
target_os = "macos",
target_os = "ios",
target_os = "tvos",
target_os = "visionos",
target_os = "watchos"
))]
fn rename_noreplace(dir: BorrowedFd<'_>, from: &OsStr, to: &OsStr) -> Result<(), Errno> {
fs::renameat_with(dir, from, dir, to, fs::RenameFlags::NOREPLACE)
}
#[cfg(not(any(
target_os = "linux",
target_os = "android",
target_os = "macos",
target_os = "ios",
target_os = "tvos",
target_os = "visionos",
target_os = "watchos"
)))]
fn rename_noreplace(_: BorrowedFd<'_>, _: &OsStr, _: &OsStr) -> Result<(), Errno> {
Err(Errno::NOSYS)
}
fn link_new(dir: BorrowedFd<'_>, from: &OsStr, to: &OsStr) -> Result<(), Errno> {
fs::linkat(dir, from, dir, to, AtFlags::empty())
}
fn write_in_place(
dir: BorrowedFd<'_>,
name: &OsStr,
content: &[u8],
durability: Durability,
fill: Fill<'_>,
) -> Result<(), Failure> {
let file = File::from(fs::openat(dir, name, IN_PLACE, NEW_FILE).map_err(refused_if_there)?);
let created = fs::fstat(&file).ok();
fill(file, content, durability).map_err(|e| {
if let Some(created) = &created {
remove_if_still(dir, name, created);
}
Failure::from(e)
})
}
fn remove_if_still(dir: BorrowedFd<'_>, name: &OsStr, created: &fs::Stat) {
let still = fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW)
.is_ok_and(|now| now.st_dev == created.st_dev && now.st_ino == created.st_ino);
if still {
let _ = fs::unlinkat(dir, name, AtFlags::empty());
}
}
fn no_such_rename(errno: Errno) -> bool {
[Errno::INVAL, Errno::NOSYS, Errno::NOTSUP, Errno::OPNOTSUPP].contains(&errno)
}
fn no_hard_links(errno: Errno) -> bool {
[
Errno::PERM,
Errno::NOSYS,
Errno::NOTSUP,
Errno::OPNOTSUPP,
Errno::MLINK,
]
.contains(&errno)
}
fn refused_if_there(errno: Errno) -> Failure {
if errno == Errno::EXIST {
Failure::Exists
} else {
Failure::from(errno)
}
}
pub(super) struct Temp<'d> {
dir: BorrowedFd<'d>,
pub(super) name: OsString,
renamed: bool,
}
impl Drop for Temp<'_> {
fn drop(&mut self) {
if !self.renamed {
let _ = fs::unlinkat(self.dir, &self.name, AtFlags::empty());
}
}
}
pub(super) fn create_temp<'d>(
dir: BorrowedFd<'d>,
mode: Mode,
names: impl IntoIterator<Item = OsString>,
) -> Result<(Temp<'d>, File), Errno> {
for name in names.into_iter().take(MAX_TEMP_ATTEMPTS) {
match fs::openat(dir, &name, TEMP, mode) {
Ok(fd) => {
let temp = Temp {
dir,
name,
renamed: false,
};
return Ok((temp, File::from(fd)));
}
Err(Errno::EXIST) => {}
Err(e) => return Err(e),
}
}
Err(Errno::EXIST)
}
fn temp_names() -> impl Iterator<Item = OsString> {
use std::hash::{BuildHasher as _, Hasher as _};
(0..MAX_TEMP_ATTEMPTS).map(|attempt| {
let mut hasher = std::collections::hash_map::RandomState::new().build_hasher();
hasher.write_usize(attempt);
OsString::from(format!(
"{TEMP_PREFIX}{:016x}{TEMP_SUFFIX}",
hasher.finish()
))
})
}
fn sync_directory(dir: BorrowedFd<'_>) -> std::io::Result<()> {
#[cfg(test)]
super::sync_probe::directory_sync()?;
let readable = File::from(fs::openat(dir, ".", TO_SYNC, Mode::empty())?);
settle_directory_sync(
|| readable.sync_all(),
|| fs::fsync(&readable).map_err(std::io::Error::from),
)
}
pub(super) fn settle_directory_sync(
full: impl FnOnce() -> std::io::Result<()>,
plain: impl FnOnce() -> std::io::Result<()>,
) -> std::io::Result<()> {
match full_or_plain(full, plain) {
Err(e) if refused(&e) => Ok(()),
synced => synced,
}
}
fn refused(e: &std::io::Error) -> bool {
Errno::from_io_error(e).is_some_and(refused_sync)
}
fn refused_sync(errno: Errno) -> bool {
errno == Errno::NOTSUP || errno == Errno::OPNOTSUPP || errno == Errno::INVAL
}
}
#[cfg(windows)]
mod windows {
use std::ffi::{OsStr, OsString};
use std::io::Write as _;
use std::os::windows::ffi::{OsStrExt as _, OsStringExt as _};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use super::{
Below, Beside, Commit, DirIdentity, Durability, Failure, Inputs, Landed, Parents, Removal,
TEMP_PREFIX, TEMP_SUFFIX,
};
const PATH_NOT_FOUND: i32 = 3;
pub(super) type Dir = PathBuf;
pub(super) fn write(
below: &Below<'_>,
anchor: Option<DirIdentity>,
content: &[u8],
durability: Durability,
parents: Parents,
commit: Commit<'_>,
) -> Result<Landed, Failure> {
let dir = walk(below, anchor, parents)?;
let target = dir.join(below.name);
match (std::fs::symlink_metadata(&target), commit) {
(Ok(meta), _) if meta.file_type().is_symlink() => return Err(Failure::LinkAtTarget),
(Ok(_), Commit::New) => return Err(Failure::Exists),
(Err(e), _) if e.kind() != std::io::ErrorKind::NotFound => return Err(e.into()),
_ => {}
}
replace(&dir, &target, content, durability, commit)?;
Ok(Landed {
dir,
not_synced: None,
})
}
pub(super) fn look(dir: &Dir, name: &OsStr) -> Beside {
match std::fs::symlink_metadata(dir.join(name)) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Beside::Nothing,
_ => Beside::Something,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct Stamp {
size: u64,
modified: Option<SystemTime>,
created: Option<SystemTime>,
}
impl Stamp {
fn of(meta: &std::fs::Metadata) -> Self {
Self {
size: meta.len(),
modified: meta.modified().ok(),
created: meta.created().ok(),
}
}
fn holds(&self, file: &Path) -> bool {
std::fs::symlink_metadata(file)
.is_ok_and(|meta| meta.is_file() && Self::of(&meta) == *self)
}
}
pub(super) struct Held {
dir: PathBuf,
file: PathBuf,
stamp: Stamp,
}
pub(super) fn read_stamped(
below: &Below<'_>,
anchor: Option<DirIdentity>,
read: &[u8],
) -> Result<Held, Failure> {
let dir = walk(below, anchor, Parents::Existing)?;
let target = dir.join(below.name);
match std::fs::symlink_metadata(&target) {
Ok(meta) if meta.file_type().is_symlink() => return Err(Failure::LinkAtTarget),
Ok(meta) if !meta.is_file() => return Err(Failure::Changed),
Ok(_) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Err(Failure::Changed),
Err(e) => return Err(e.into()),
}
let mut opened = std::fs::File::open(&target)?;
let meta = opened.metadata()?;
if !meta.is_file() {
return Err(Failure::Changed);
}
let expected = u64::try_from(read.len()).unwrap_or(u64::MAX);
if mds::read_at_most(&mut opened, expected.saturating_add(1), expected)? != read {
return Err(Failure::Changed);
}
Ok(Held {
dir,
file: target,
stamp: Stamp::of(&meta),
})
}
pub(super) fn replace_held(
held: Held,
content: &[u8],
durability: Durability,
) -> Result<Landed, Failure> {
let commit = Commit::Replace(Some(&held.stamp));
replace(&held.dir, &held.file, content, durability, commit)?;
Ok(Landed {
dir: held.dir,
not_synced: None,
})
}
pub(super) fn rename_held(held: Held, content: &[u8]) -> Result<Dir, Failure> {
let commit = Commit::Replace(Some(&held.stamp));
replace(&held.dir, &held.file, content, Durability::Fsync, commit)?;
Ok(held.dir)
}
pub(super) fn sync_owed(_dir: &Dir) -> std::io::Result<()> {
Ok(())
}
pub(super) fn same_directory(a: &Dir, b: &Dir) -> bool {
a == b
}
pub(super) fn remove(
below: &Below<'_>,
anchor: Option<DirIdentity>,
proof: impl FnOnce(&mut std::fs::File) -> std::io::Result<bool>,
) -> Result<Removal, Failure> {
let dir = match walk(below, anchor, Parents::Existing) {
Ok(dir) => dir,
Err(Failure::Io(e)) if nothing_below(&e) => return Ok(Removal::Missing),
Err(failure) => return Err(failure),
};
let target = dir.join(below.name);
match std::fs::symlink_metadata(&target) {
Ok(meta) if meta.file_type().is_symlink() => return Err(Failure::LinkAtTarget),
Ok(meta) if !meta.is_file() => return Err(Failure::NotARegularFile),
Ok(_) => {}
Err(e) if no_such_name(&e) => return Ok(Removal::Missing),
Err(e) => return Err(Failure::Unreadable(e)),
}
let mut file = match std::fs::File::open(&target) {
Ok(file) => file,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Removal::Missing),
Err(e) => return Err(Failure::Unreadable(e)),
};
let stamp = Stamp::of(&file.metadata().map_err(Failure::Unreadable)?);
if !proof(&mut file).map_err(Failure::Unreadable)? {
return Ok(Removal::Kept);
}
drop(file);
match std::fs::symlink_metadata(&target) {
Ok(now) if now.is_file() && Stamp::of(&now) == stamp => {}
Ok(_) => return Err(Failure::Changed),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Removal::Missing),
Err(e) => return Err(e.into()),
}
match std::fs::remove_file(&target) {
Ok(()) => Ok(Removal::Removed),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Removal::Missing),
Err(e) => Err(e.into()),
}
}
pub(super) fn nothing_below(e: &std::io::Error) -> bool {
matches!(
e.kind(),
std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
) || e.raw_os_error() == Some(PATH_NOT_FOUND)
}
fn no_such_name(e: &std::io::Error) -> bool {
matches!(
e.kind(),
std::io::ErrorKind::NotFound | std::io::ErrorKind::InvalidFilename
)
}
fn replace(
dir: &Path,
target: &Path,
content: &[u8],
durability: Durability,
commit: Commit<'_>,
) -> Result<(), Failure> {
let mut temp = tempfile::Builder::new()
.prefix(TEMP_PREFIX)
.suffix(TEMP_SUFFIX)
.make_in(dir, |path| {
std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
})?;
temp.as_file_mut().write_all(content)?;
if durability == Durability::Fsync {
temp.as_file().sync_all()?;
}
match commit {
Commit::Replace(_) | Commit::Output { .. } => {
ready_to_replace(target, commit)?;
std::fs::rename(temp.path(), target)?;
temp.disable_cleanup(true);
}
Commit::New => {
super::pause_before_replace();
temp.persist_noclobber(target).map_err(|e| {
if e.error.kind() == std::io::ErrorKind::AlreadyExists {
Failure::Exists
} else {
Failure::from(e.error)
}
})?;
}
}
Ok(())
}
fn ready_to_replace(target: &Path, commit: Commit<'_>) -> Result<(), Failure> {
match commit {
Commit::Replace(Some(stamp)) if !stamp.holds(target) => Err(Failure::Changed),
Commit::Output { inputs, module } => never_over_an_input(target, inputs, module),
_ => Ok(()),
}
}
fn never_over_an_input(target: &Path, inputs: &Inputs, module: bool) -> Result<(), Failure> {
match std::fs::symlink_metadata(target) {
Ok(meta) if meta.is_file() => {}
Ok(_) => return Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(e) => return Err(e.into()),
}
if !module && is_a_module(target)? {
return Err(Failure::Module);
}
if is_an_input(inputs, target)? {
return Err(Failure::Input);
}
Ok(())
}
fn is_an_input(inputs: &Inputs, target: &Path) -> Result<bool, Failure> {
let target = match std::fs::canonicalize(target) {
Ok(target) => target,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(e) => return Err(e.into()),
};
Ok(inputs
.paths()
.any(|file| std::fs::canonicalize(file).is_ok_and(|file| file == target)))
}
fn opened_name(target: &Path) -> Option<OsString> {
let name: Vec<u16> = target.file_name()?.encode_wide().collect();
Some(OsString::from_wide(super::as_windows_opens(&name)))
}
fn is_a_module(target: &Path) -> Result<bool, Failure> {
let Some(name) = opened_name(target) else {
return Ok(false);
};
if super::names_source(&name) {
return Ok(true);
}
if !super::names_markdown(&name) {
return Ok(false);
}
let judge = || -> std::io::Result<bool> {
let mut file = match std::fs::File::open(target) {
Ok(file) => file,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(e) => return Err(e),
};
super::is_mds_module(&mut file)
};
judge().map_err(Failure::UnreadMarkdown)
}
fn walk(
below: &Below<'_>,
anchor: Option<DirIdentity>,
parents: Parents,
) -> Result<PathBuf, Failure> {
if parents == Parents::Create && anchor.is_none() {
std::fs::create_dir_all(&below.anchor).map_err(|e| {
let leads_nowhere = || {
std::fs::metadata(&below.anchor)
.is_err_and(|m| m.kind() == std::io::ErrorKind::NotFound)
};
if e.kind() == std::io::ErrorKind::AlreadyExists && leads_nowhere() {
std::io::Error::from_raw_os_error(PATH_NOT_FOUND)
} else {
e
}
})?;
}
if anchor.is_some_and(|checked| DirIdentity::of(&below.anchor) != Some(checked)) {
return Err(Failure::AnchorMoved);
}
let mut dir = below.anchor.clone();
for (depth, name) in below.dirs.iter().enumerate() {
dir.push(name);
if !directory_below(&dir, parents)? {
return Err(Failure::LinkBelowAnchor { depth });
}
}
Ok(dir)
}
fn directory_below(dir: &Path, parents: Parents) -> std::io::Result<bool> {
let meta = match std::fs::symlink_metadata(dir) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound && parents == Parents::Create => {
match std::fs::create_dir(dir) {
Err(e) if e.kind() != std::io::ErrorKind::AlreadyExists => return Err(e),
_ => std::fs::symlink_metadata(dir)?,
}
}
looked => looked?,
};
if meta.file_type().is_symlink() {
return Ok(false);
}
if !meta.is_dir() {
return Err(std::io::ErrorKind::NotADirectory.into());
}
Ok(true)
}
}
#[cfg(debug_assertions)]
mod pause_trigger {
use std::path::PathBuf;
use std::time::Duration;
use super::{atomic_write_file, Durability, Parents};
use crate::output::WriteTarget;
const VARIABLE: &str = "MDS_TEST_PAUSE_BEFORE_REPLACE";
const POLL: Duration = Duration::from_millis(5);
const MAX_POLLS: u32 = 2_000;
pub(crate) fn pause_before_replace() {
let Some(go) = std::env::var_os(VARIABLE).map(PathBuf::from) else {
return;
};
let mut paused = go.clone().into_os_string();
paused.push(".paused");
let _ = atomic_write_file(
&WriteTarget::as_typed(PathBuf::from(paused)),
"",
Durability::RenameOnly,
Parents::Existing,
);
for _ in 0..MAX_POLLS {
if go.exists() {
return;
}
std::thread::sleep(POLL);
}
}
}
#[cfg(debug_assertions)]
pub(crate) use pause_trigger::pause_before_replace;
#[cfg(not(debug_assertions))]
pub(crate) fn pause_before_replace() {}
#[cfg(all(test, unix))]
pub(crate) mod sync_probe {
use std::cell::Cell;
thread_local! {
static STARTED: Cell<usize> = const { Cell::new(0) };
static FAILING: Cell<Option<i32>> = const { Cell::new(None) };
}
pub(crate) fn directory_syncs() -> usize {
STARTED.with(Cell::get)
}
pub(crate) fn failing_with(errno: i32) -> Failing {
FAILING.with(|failing| failing.set(Some(errno)));
Failing
}
#[must_use]
pub(crate) struct Failing;
impl Drop for Failing {
fn drop(&mut self) {
FAILING.with(|failing| failing.set(None));
}
}
pub(super) fn directory_sync() -> std::io::Result<()> {
STARTED.with(|started| started.set(started.get() + 1));
match FAILING.with(Cell::get) {
Some(errno) => Err(std::io::Error::from_raw_os_error(errno)),
None => Ok(()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const MODULE_REFUSED: &str = "refusing to replace an MDS module (an output that declares \
type: mds is a generated module, and is rebuilt from its source)";
fn write_as_typed(
path: &Path,
content: &str,
durability: Durability,
) -> std::result::Result<(), mds::MdsError> {
atomic_write_file(
&WriteTarget::as_typed(path.to_path_buf()),
content,
durability,
Parents::Existing,
)
}
fn temp_residue(dir: &Path) -> Vec<String> {
std::fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.filter(|n| n.starts_with(TEMP_PREFIX))
.collect()
}
fn entries(dir: &Path) -> Vec<String> {
let mut names: Vec<String> = std::fs::read_dir(dir)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.collect();
names.sort();
names
}
fn make_symlink(target: &Path, link: &Path) -> bool {
#[cfg(unix)]
let result = std::os::unix::fs::symlink(target, link);
#[cfg(windows)]
let result = if target.is_dir() {
std::os::windows::fs::symlink_dir(target, link)
} else {
std::os::windows::fs::symlink_file(target, link)
};
match result {
Ok(()) => true,
Err(err) => {
#[cfg(windows)]
{
const ERROR_PRIVILEGE_NOT_HELD: i32 = 1314;
if err.raw_os_error() == Some(ERROR_PRIVILEGE_NOT_HELD)
&& std::env::var_os("CI").is_none()
{
crate::output::ewriteln!(
"skipping: symlink creation needs Developer Mode or an elevated process on Windows"
);
return false;
}
}
panic!(
"failed to create symlink {} -> {}: {err}",
target.display(),
link.display()
);
}
}
}
#[cfg(unix)]
fn os_text(errno: rustix::io::Errno) -> String {
std::io::Error::from(errno).to_string()
}
#[test]
fn a_target_splits_at_its_anchor_and_below_it_is_names_only() {
let target = WriteTarget::below(Path::new("out"), Path::new("o"), Path::new("a/b/x.md"));
assert_eq!(
Below::of(&target).unwrap(),
Below {
anchor: PathBuf::from("out"),
dirs: vec![OsStr::new("a"), OsStr::new("b")],
name: OsStr::new("x.md"),
}
);
let bare = WriteTarget::as_typed(PathBuf::from("x.md"));
assert_eq!(
Below::of(&bare).unwrap(),
Below {
anchor: PathBuf::from("."),
dirs: vec![],
name: OsStr::new("x.md"),
}
);
for typed in [".", "out/..", "/"] {
let target = WriteTarget::as_typed(PathBuf::from(typed));
let kind = Below::of(&target).map(|_| ()).unwrap_err().kind();
assert_eq!(
kind,
std::io::ErrorKind::IsADirectory,
"{typed:?} names a directory"
);
}
let climbing =
WriteTarget::below(Path::new("out"), Path::new("out"), Path::new("a/../x.md"));
assert_eq!(
Below::of(&climbing).map(|_| ()).unwrap_err().kind(),
std::io::ErrorKind::InvalidInput,
"a `..` below the anchor is refused"
);
}
#[test]
fn a_target_ending_in_a_separator_names_a_directory() {
let sep = std::path::MAIN_SEPARATOR_STR;
for typed in [
"out/".to_owned(),
"out/.".to_owned(),
"out/./".to_owned(),
"sub/out/".to_owned(),
format!("out{sep}"),
format!("out{sep}."),
] {
let target = WriteTarget::as_typed(PathBuf::from(&typed));
let kind = Below::of(&target).map(|_| ()).unwrap_err().kind();
assert_eq!(
kind,
std::io::ErrorKind::IsADirectory,
"{typed:?} names a directory"
);
}
for (typed, name) in [("out", "out"), ("sub/out", "out"), ("out.", "out.")] {
let target = WriteTarget::as_typed(PathBuf::from(typed));
assert_eq!(
Below::of(&target).unwrap().name,
OsStr::new(name),
"{typed:?}"
);
}
}
#[test]
fn a_name_in_stream_syntax_is_refused_on_windows_alone() {
assert!(names_a_stream(OsStr::new("lib.mds::$DATA")));
assert!(names_a_stream(OsStr::new("lib.md:x")));
assert!(!names_a_stream(OsStr::new("lib.md")));
for name in ["lib.mds::$DATA", "lib.md:x"] {
let target = WriteTarget::below(Path::new("out"), Path::new("o"), Path::new(name));
let split = Below::of(&target).map(|below| below.name.to_owned());
if cfg!(windows) {
assert_eq!(
split.map_err(|e| e.kind()),
Err(std::io::ErrorKind::InvalidFilename),
"{name}"
);
} else {
assert_eq!(split.unwrap(), OsStr::new(name));
}
}
let plain = WriteTarget::below(Path::new("out"), Path::new("o"), Path::new("lib.md"));
assert_eq!(Below::of(&plain).unwrap().name, OsStr::new("lib.md"));
}
#[cfg(unix)]
#[test]
fn a_name_with_a_colon_is_written_on_unix() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("a:b.md");
write_as_typed(&file, "written", Durability::RenameOnly).unwrap();
assert_eq!(std::fs::read_to_string(&file).unwrap(), "written");
}
#[test]
fn a_refused_directory_is_named_as_shown_down_to_the_link() {
let target = WriteTarget::below(
Path::new("/canonical/out"),
Path::new("out"),
Path::new("a/b/x.md"),
);
assert_eq!(shown_directory(&target, 0), Path::new("out").join("a"));
assert_eq!(
shown_directory(&target, 1),
Path::new("out").join("a").join("b")
);
}
#[cfg(unix)]
#[test]
fn a_symlink_planted_below_the_anchor_is_refused() {
let dir = tempfile::tempdir().unwrap();
let anchor = dir.path().join("anchor");
let victim = dir.path().join("victim");
std::fs::create_dir_all(anchor.join("a")).unwrap();
std::fs::create_dir(&victim).unwrap();
std::os::unix::fs::symlink(&victim, anchor.join("a").join("b")).unwrap();
let target = WriteTarget::below(&anchor, Path::new("out"), Path::new("a/b/x.md"));
for parents in [Parents::Create, Parents::Existing] {
let err = atomic_write_file(&target, "X", Durability::Fsync, parents)
.expect_err("a symlink below the anchor is refused")
.to_string();
assert_eq!(
err,
"cannot write out/a/b/x.md: refusing to follow a symlink at out/a/b"
);
}
assert_eq!(entries(&victim), Vec::<String>::new());
assert!(std::fs::symlink_metadata(anchor.join("a/b"))
.unwrap()
.file_type()
.is_symlink());
std::fs::remove_file(anchor.join("a/b")).unwrap();
atomic_write_file(&target, "X", Durability::Fsync, Parents::Create).unwrap();
assert_eq!(
std::fs::read_to_string(anchor.join("a/b/x.md")).unwrap(),
"X"
);
std::fs::remove_dir_all(anchor.join("a/b")).unwrap();
std::os::unix::fs::symlink(&victim, anchor.join("a").join("b")).unwrap();
std::fs::write(anchor.join("a/b/by-hand"), "x").unwrap();
assert_eq!(entries(&victim), vec!["by-hand".to_owned()]);
}
#[cfg(unix)]
#[test]
fn a_failed_open_below_the_anchor_is_refused_when_it_met_a_symlink() {
use std::os::fd::AsFd as _;
use rustix::io::Errno;
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("real")).unwrap();
std::os::unix::fs::symlink("real", dir.path().join("link")).unwrap();
let fd = rustix::fs::open(
dir.path(),
rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::DIRECTORY,
rustix::fs::Mode::empty(),
)
.unwrap();
let failure =
|name: &str, errno| super::unix::below_failure(fd.as_fd(), OsStr::new(name), 3, errno);
assert!(
matches!(
failure("real", Errno::LOOP),
Failure::LinkBelowAnchor { depth: 3 }
),
"ELOOP is a symlink, though a directory is there now"
);
assert!(
matches!(
failure("link", Errno::NOTDIR),
Failure::LinkBelowAnchor { depth: 3 }
),
"a symlink there now is refused, whatever the open said"
);
for errno in [Errno::NOTDIR, Errno::ACCESS] {
assert!(
matches!(failure("real", errno), Failure::Io(_)),
"{errno:?} of a directory is the write's own failure"
);
}
}
#[cfg(unix)]
#[test]
fn a_directory_that_cannot_be_listed_takes_a_write_on_linux_alone() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let drop_box = dir.path().join("box");
std::fs::create_dir(&drop_box).unwrap();
let mode =
|mode| std::fs::set_permissions(&drop_box, std::fs::Permissions::from_mode(mode));
mode(0o333).unwrap();
if std::fs::read_dir(&drop_box).is_ok() {
mode(0o755).unwrap();
crate::output::ewriteln!("running as root; mode 0o333 does not stop a listing");
return;
}
let as_anchor = WriteTarget::as_typed(drop_box.join("anchor.md"));
let below = WriteTarget::below(dir.path(), Path::new("out"), Path::new("box/below.md"));
let written = [&as_anchor, &below].map(|target| {
atomic_write_file(target, "X", Durability::RenameOnly, Parents::Existing)
.map_err(|e| e.to_string())
});
let landed =
["anchor.md", "below.md"].map(|name| std::fs::read_to_string(drop_box.join(name)).ok());
mode(0o755).unwrap();
if cfg!(any(target_os = "linux", target_os = "android")) {
assert_eq!(written, [Ok(()), Ok(())]);
assert_eq!(landed, [Some("X".to_owned()), Some("X".to_owned())]);
assert_eq!(entries(&drop_box), ["anchor.md", "below.md"]);
} else {
let denied = "Permission denied (os error 13)";
let [anchor_err, below_err] = written.map(|w| w.expect_err("a drop box is refused"));
assert!(
anchor_err.starts_with("cannot write ") && anchor_err.ends_with(denied),
"{anchor_err}"
);
assert_eq!(
below_err,
format!("cannot write out/box/below.md: {denied}")
);
assert_eq!(landed, [None, None]);
assert_eq!(entries(&drop_box), Vec::<String>::new());
}
}
#[cfg(unix)]
#[test]
fn a_search_only_open_that_is_refused_is_made_again_to_read() {
use std::cell::RefCell;
use rustix::fs::OFlags;
use rustix::io::Errno;
let search = OFlags::NONBLOCK;
let flags = OFlags::DIRECTORY | search;
let opens = |refusal: Errno, search: OFlags| {
let asked = RefCell::new(Vec::new());
let opened = super::unix::search_or_read(flags, search, |with: OFlags| {
asked.borrow_mut().push(with);
if with.contains(OFlags::NONBLOCK) {
Err(refusal)
} else {
Ok(())
}
});
(opened, asked.into_inner())
};
assert_eq!(
opens(Errno::INVAL, search),
(Ok(()), vec![flags, OFlags::DIRECTORY]),
"refused: opened again to read"
);
assert_eq!(
opens(Errno::ACCESS, search),
(Err(Errno::ACCESS), vec![flags]),
"any other failure is the open's"
);
assert_eq!(
opens(Errno::INVAL, OFlags::empty()),
(Err(Errno::INVAL), vec![flags]),
"no search flag of its own: nothing to open again without"
);
}
#[cfg(unix)]
#[test]
fn a_rewrite_whose_directory_cannot_be_synced_is_written_and_said_so() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("src");
std::fs::create_dir(&src).unwrap();
let file = src.join("a.mds");
let target = WriteTarget::below(dir.path(), Path::new("out"), Path::new("src/a.mds"));
let mode = |mode| std::fs::set_permissions(&src, std::fs::Permissions::from_mode(mode));
let rewrite_unlistable = |durability| {
std::fs::write(&file, "OLD").unwrap();
let read = read_stamped(&target, "OLD").unwrap();
mode(0o333).unwrap();
let rewritten = replace_if_unchanged(read, "NEW", durability).map(|r| match r {
Rewritten::Done => None,
Rewritten::NotSynced(e) => Some(e.to_string()),
});
let landed = std::fs::read_to_string(&file).unwrap();
let listable = std::fs::read_dir(&src).is_ok();
mode(0o755).unwrap();
(rewritten.map_err(|e| e.to_string()), landed, listable)
};
let (fsync, landed, listable) = rewrite_unlistable(Durability::Fsync);
if listable {
crate::output::ewriteln!("running as root; mode 0o333 does not stop a listing");
return;
}
assert_eq!(
fsync,
Ok(Some(
"out/src/a.mds written, but its directory could not be synced: Permission \
denied (os error 13)"
.to_owned()
))
);
assert_eq!(landed, "NEW", "the rewrite landed");
assert_eq!(
rewrite_unlistable(Durability::RenameOnly),
(Ok(None), "NEW".to_owned(), false),
"control: the rename-only tier syncs no directory"
);
std::fs::write(&file, "OLD").unwrap();
let read = read_stamped(&target, "OLD").unwrap();
assert!(
matches!(
replace_if_unchanged(read, "NEW", Durability::Fsync),
Ok(Rewritten::Done)
),
"control: a directory left alone is synced"
);
assert_eq!(std::fs::read_to_string(&file).unwrap(), "NEW");
assert_eq!(entries(&src), ["a.mds"]);
}
#[cfg(unix)]
fn owing(root: &Path, file: &str) -> Renamed {
std::fs::write(root.join(file), "OLD").unwrap();
let target = WriteTarget::below(root, Path::new("d"), Path::new(file));
replace_owing_sync(read_stamped(&target, "OLD").unwrap(), "NEW").unwrap()
}
#[cfg(unix)]
fn shown(flushed: Option<Flushed<&str>>) -> Vec<String> {
flushed
.into_iter()
.flatten()
.map(|synced| match synced {
Synced::Durable(file) => format!("synced {file}"),
Synced::NotSynced(file, e) => format!("{file}: {e}"),
})
.collect()
}
#[cfg(unix)]
#[test]
fn owed_syncs_are_made_once_for_each_directory_after_its_last_file() {
use sync_probe::{directory_syncs, failing_with};
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::create_dir(root.join("sub")).unwrap();
let files = ["a.mds", "sub/x.mds", "b.mds", "c.mds"];
let run = || {
let mut syncs = DirectorySyncs::new(files.iter().map(Path::new));
let before = directory_syncs();
let mut at = Vec::new();
for (place, &file) in files.iter().enumerate() {
let mut back = shown(syncs.landed(place, owing(root, file), file));
back.extend(shown(syncs.past(place)));
if !back.is_empty() {
at.push((place, back));
}
}
for file in files {
assert_eq!(std::fs::read_to_string(root.join(file)).unwrap(), "NEW");
}
(at, directory_syncs() - before)
};
let synced = |file: &str| format!("synced {file}");
assert_eq!(
run(),
(
vec![
(1, vec![synced("sub/x.mds")]),
(3, ["a.mds", "b.mds", "c.mds"].map(synced).to_vec()),
],
2
)
);
let failing = failing_with(5);
let cause = std::io::Error::from_raw_os_error(5);
let not_synced = |file: &str| {
format!("{file}: d/{file} written, but its directory could not be synced: {cause}")
};
assert_eq!(
run(),
(
vec![
(1, vec![not_synced("sub/x.mds")]),
(3, ["a.mds", "b.mds", "c.mds"].map(not_synced).to_vec()),
],
2
),
"a failed sync comes back for each rewrite owed there, once"
);
drop(failing);
}
#[cfg(unix)]
#[test]
fn a_rewrite_into_a_directory_swapped_in_syncs_the_one_before_it_first() {
use sync_probe::directory_syncs;
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
std::fs::create_dir(root.join("s")).unwrap();
let files = ["s/a.mds", "s/b.mds"];
let run = |swap: bool| {
let mut syncs = DirectorySyncs::new(files.iter().map(Path::new));
let before = directory_syncs();
assert!(shown(syncs.landed(0, owing(root, files[0]), files[0])).is_empty());
assert!(
shown(syncs.past(0)).is_empty(),
"s/a.mds is not s's last file"
);
if swap {
std::fs::rename(root.join("s"), root.join("s-old")).unwrap();
std::fs::create_dir(root.join("s")).unwrap();
}
let landed = shown(syncs.landed(1, owing(root, files[1]), files[1]));
let past = shown(syncs.past(1));
(landed, past, directory_syncs() - before)
};
assert_eq!(
run(false),
(
Vec::new(),
vec!["synced s/a.mds".to_string(), "synced s/b.mds".to_string()],
1
),
"control: one directory"
);
assert_eq!(
run(true),
(
vec!["synced s/a.mds".to_string()],
vec!["synced s/b.mds".to_string()],
2
)
);
assert_eq!(
std::fs::read_to_string(root.join("s-old/a.mds")).unwrap(),
"NEW"
);
}
#[cfg(unix)]
#[test]
fn a_rewrite_at_a_place_the_run_did_not_name_is_synced_at_once() {
use sync_probe::directory_syncs;
let dir = tempfile::tempdir().unwrap();
let mut syncs = DirectorySyncs::new([Path::new("a.mds")]);
let before = directory_syncs();
assert_eq!(
shown(syncs.landed(1, owing(dir.path(), "x.mds"), "x.mds")),
["synced x.mds"]
);
assert_eq!(directory_syncs() - before, 1);
assert!(shown(syncs.past(0)).is_empty(), "nothing is owed for a.mds");
}
#[cfg(unix)]
#[test]
fn a_file_sync_the_filesystem_refuses_falls_back_to_a_plain_one() {
use rustix::io::Errno;
let fail = |errno: Errno| -> std::io::Result<()> { Err(errno.into()) };
let sync = |full: std::io::Result<()>, plain: Option<std::io::Result<()>>| {
let mut fell_back = false;
let synced = super::unix::full_or_plain(
|| full,
|| {
fell_back = true;
plain.expect("no fallback after this sync")
},
);
(synced.map_err(|e| Errno::from_io_error(&e)), fell_back)
};
assert_eq!(sync(Ok(()), None), (Ok(()), false), "synced");
for refusal in [Errno::NOTSUP, Errno::OPNOTSUPP, Errno::INVAL] {
assert_eq!(
sync(fail(refusal), Some(Ok(()))),
(Ok(()), true),
"{refusal:?}, then a plain sync"
);
assert_eq!(
sync(fail(refusal), Some(fail(Errno::INVAL))),
(Err(Some(Errno::INVAL)), true),
"{refusal:?}, then a plain sync refused too: the write's error"
);
assert_eq!(
sync(fail(refusal), Some(fail(Errno::IO))),
(Err(Some(Errno::IO)), true),
"{refusal:?}, then a plain sync that fails: the write's error"
);
}
assert_eq!(
sync(fail(Errno::IO), None),
(Err(Some(Errno::IO)), false),
"a failed sync is the write's error, with no fallback"
);
}
#[cfg(unix)]
#[test]
fn a_directory_sync_the_filesystem_refuses_twice_does_not_fail_the_write() {
use rustix::io::Errno;
let fail = |errno: Errno| -> std::io::Result<()> { Err(errno.into()) };
let settle = |full: std::io::Result<()>, plain: Option<std::io::Result<()>>| {
let mut fell_back = false;
let settled = super::unix::settle_directory_sync(
|| full,
|| {
fell_back = true;
plain.expect("no fallback after this sync")
},
);
(settled.map_err(|e| Errno::from_io_error(&e)), fell_back)
};
assert_eq!(settle(Ok(()), None), (Ok(()), false), "synced");
for refusal in [Errno::NOTSUP, Errno::OPNOTSUPP, Errno::INVAL] {
assert_eq!(
settle(fail(refusal), Some(Ok(()))),
(Ok(()), true),
"{refusal:?}, then a plain sync"
);
assert_eq!(
settle(fail(refusal), Some(fail(Errno::INVAL))),
(Ok(()), true),
"{refusal:?}, then a plain sync refused too: no directory sync to be had"
);
assert_eq!(
settle(fail(refusal), Some(fail(Errno::IO))),
(Err(Some(Errno::IO)), true),
"{refusal:?}, then a plain sync that fails: the sync's error"
);
}
assert_eq!(
settle(fail(Errno::IO), None),
(Err(Some(Errno::IO)), false),
"a failed sync is the sync's error, with no fallback"
);
}
#[test]
fn a_symlinked_anchor_is_followed() {
let dir = tempfile::tempdir().unwrap();
let real = dir.path().join("real");
std::fs::create_dir(&real).unwrap();
let link = dir.path().join("link");
if !make_symlink(&real, &link) {
return;
}
let target = WriteTarget::below(&link, Path::new("link"), Path::new("sub/x.md"));
atomic_write_file(&target, "X", Durability::RenameOnly, Parents::Create).unwrap();
assert_eq!(
std::fs::read_to_string(real.join("sub").join("x.md")).unwrap(),
"X"
);
}
#[cfg(unix)]
#[test]
fn a_write_whose_anchor_is_not_the_directory_checked_is_refused() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out");
let other = dir.path().join("other");
for made in [&out, &other] {
std::fs::create_dir(made).unwrap();
}
let identity = |of: &Path| DirIdentity::of(of).expect("a directory");
let target = WriteTarget::below(&out, Path::new("o"), Path::new("sub/x.md"));
let swapped = target.below_checked_anchor(&out, 0, identity(&other));
let err = atomic_write_file(&swapped, "X", Durability::RenameOnly, Parents::Create)
.expect_err("the anchor opened is not the directory checked")
.to_string();
assert_eq!(
err,
format!("cannot write {}: {OUT_DIR_MOVED}", safe_path(&target.shown))
);
assert_eq!(
entries(&out),
Vec::<String>::new(),
"nothing is written or created below it"
);
let checked = target.below_checked_anchor(&out, 0, identity(&out));
atomic_write_file(&checked, "X", Durability::RenameOnly, Parents::Create).unwrap();
assert_eq!(
std::fs::read_to_string(out.join("sub").join("x.md")).unwrap(),
"X"
);
}
#[cfg(unix)]
#[test]
fn a_missing_out_dir_is_made_below_the_directory_checked_above_it() {
let dir = tempfile::tempdir().unwrap();
let base = dir.path().join("base");
let other = dir.path().join("other");
let victim = dir.path().join("victim");
for made in [&base, &other, &victim] {
std::fs::create_dir(made).unwrap();
}
let identity = |of: &Path| DirIdentity::of(of).expect("a directory");
let out = base.join("out");
let target = WriteTarget::below(&out, Path::new("o"), Path::new("x.md"));
let write = |anchor: &Path| {
let checked = target.below_checked_anchor(&out, 1, identity(anchor));
atomic_write_file(&checked, "X", Durability::RenameOnly, Parents::Create)
};
let err = write(&other)
.expect_err("not the directory checked")
.to_string();
assert_eq!(
err,
format!("cannot write {}: {OUT_DIR_MOVED}", safe_path(&target.shown))
);
assert!(!out.exists(), "nothing is created");
std::os::unix::fs::symlink(&victim, &out).unwrap();
let err = write(&base)
.expect_err("a link where the out-dir goes")
.to_string();
assert_eq!(err, format!("cannot write o/x.md: {FOLLOW_REFUSAL} at o"));
assert_eq!(
entries(&victim),
Vec::<String>::new(),
"nothing lands there"
);
std::fs::remove_file(&out).unwrap();
write(&base).unwrap();
assert_eq!(std::fs::read_to_string(out.join("x.md")).unwrap(), "X");
}
#[test]
fn a_checked_anchor_that_is_gone_is_not_made_again() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out");
std::fs::create_dir(&out).unwrap();
let identity = DirIdentity::of(&out).expect("a directory");
std::fs::remove_dir(&out).unwrap();
let target = WriteTarget::below(&out, Path::new("o"), Path::new("x.md"));
let checked = target.below_checked_anchor(&out, 0, identity);
let err = atomic_write_file(&checked, "X", Durability::RenameOnly, Parents::Create)
.expect_err("the anchor checked is gone")
.to_string();
assert_eq!(
err,
format!("cannot write {}: {OUT_DIR_MOVED}", safe_path(&target.shown))
);
assert!(!out.exists(), "nothing is made by path");
atomic_write_file(&target, "X", Durability::RenameOnly, Parents::Create).unwrap();
assert_eq!(std::fs::read_to_string(out.join("x.md")).unwrap(), "X");
}
#[cfg(unix)]
#[test]
fn a_swap_loop_below_the_anchor_lands_nothing_in_the_link_s_target() {
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
const HOLD: Duration = Duration::from_micros(200);
let dir = tempfile::tempdir().unwrap();
let anchor = dir.path().join("anchor");
let victim = dir.path().join("victim");
std::fs::create_dir_all(anchor.join("sub")).unwrap();
std::fs::create_dir(&victim).unwrap();
let target = WriteTarget::below(&anchor, Path::new("out"), Path::new("sub/x.md"));
let stop = Arc::new(AtomicBool::new(false));
let swapper = {
let stop = Arc::clone(&stop);
let (anchor, victim) = (anchor.clone(), victim.clone());
std::thread::spawn(move || {
let sub = anchor.join("sub");
for i in 0..100_000u32 {
if stop.load(Ordering::Relaxed) {
break;
}
let _ = std::fs::rename(&sub, anchor.join(format!("away-{i}")));
let _ = std::os::unix::fs::symlink(&victim, &sub);
std::thread::sleep(HOLD);
if std::fs::remove_file(&sub).is_err() {
let _ = std::fs::rename(&sub, anchor.join(format!("away-{i}-b")));
}
let _ = std::fs::create_dir(&sub);
std::thread::sleep(HOLD);
}
})
};
let started = Instant::now();
let (mut written, mut refused) = (0u32, 0u32);
for _ in 0..2_000 {
if started.elapsed() > Duration::from_secs(10) {
break;
}
match atomic_write_file(&target, "X", Durability::RenameOnly, Parents::Create) {
Ok(()) => written += 1,
Err(e) if e.to_string().contains(FOLLOW_REFUSAL) => refused += 1,
Err(_) => {}
}
}
stop.store(true, Ordering::Relaxed);
swapper.join().unwrap();
assert_eq!(
entries(&victim),
Vec::<String>::new(),
"nothing landed in the link's target ({written} written, {refused} refused)"
);
assert!(
written > 0 && refused > 0,
"the loop met both states: {written} written, {refused} refused"
);
let _ = std::fs::remove_file(anchor.join("sub"));
let _ = std::fs::remove_dir_all(anchor.join("sub"));
std::os::unix::fs::symlink(&victim, anchor.join("sub")).unwrap();
std::fs::write(anchor.join("sub/by-hand"), "x").unwrap();
assert_eq!(entries(&victim), vec!["by-hand".to_owned()]);
}
#[test]
fn only_an_output_creates_its_directories() {
let dir = tempfile::tempdir().unwrap();
let anchor = dir.path().join("new").join("anchor");
let target = WriteTarget::below(&anchor, Path::new("out"), Path::new("a/b/x.md"));
let err = atomic_write_file(&target, "X", Durability::RenameOnly, Parents::Existing)
.expect_err("nothing is created for a rewrite")
.to_string();
let named = format!("cannot write {}: ", safe_path(&target.shown));
assert!(err.starts_with(&named), "{err}");
assert!(!dir.path().join("new").exists(), "nothing was created");
atomic_write_file(&target, "X", Durability::RenameOnly, Parents::Create).unwrap();
assert_eq!(
std::fs::read_to_string(anchor.join("a").join("b").join("x.md")).unwrap(),
"X"
);
}
#[test]
fn a_dangling_symlink_anchor_is_reported_as_missing() {
let dir = tempfile::tempdir().unwrap();
let link = dir.path().join("link");
let nowhere = dir.path().join("nowhere");
std::fs::create_dir(&nowhere).unwrap();
if !make_symlink(&nowhere, &link) {
return;
}
std::fs::remove_dir(&nowhere).unwrap();
let target = WriteTarget::below(&link, Path::new("o"), Path::new("x.md"));
let err = atomic_write_file(&target, "X", Durability::RenameOnly, Parents::Create)
.expect_err("a dangling anchor cannot be written below")
.to_string();
#[cfg(unix)]
let missing = os_text(rustix::io::Errno::NOENT);
#[cfg(windows)]
let missing = std::io::Error::from_raw_os_error(3).to_string();
assert_eq!(
err,
format!("cannot write {}: {missing}", safe_path(&target.shown))
);
assert!(
!nowhere.exists(),
"nothing was created where the link points"
);
std::fs::create_dir(&nowhere).unwrap();
atomic_write_file(&target, "X", Durability::RenameOnly, Parents::Create).unwrap();
assert_eq!(std::fs::read_to_string(nowhere.join("x.md")).unwrap(), "X");
}
#[test]
fn a_rewrite_replaces_only_the_file_as_it_was_read() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("a.mds");
let target = WriteTarget::new(file.clone(), PathBuf::from("a.mds"));
let changed = format!(
"cannot write {}: changed since it was read; not written",
safe_path(&target.shown)
);
let refused = |read: &str| {
read_stamped(&target, read)
.map(|_| ())
.expect_err("not the file as read")
.to_string()
};
std::fs::write(&file, "one").unwrap();
assert_eq!(refused("two"), changed, "other bytes");
assert_eq!(refused("on"), changed, "more bytes than were read");
let read = read_stamped(&target, "one").unwrap();
std::fs::write(&file, "edited").unwrap();
let err = replace_if_unchanged(read, "ONE", Durability::Fsync)
.expect_err("edited after the read")
.to_string();
assert_eq!(err, changed);
assert_eq!(std::fs::read_to_string(&file).unwrap(), "edited");
assert_eq!(temp_residue(dir.path()), Vec::<String>::new());
let read = read_stamped(&target, "edited").unwrap();
assert!(matches!(
replace_if_unchanged(read, "EDITED", Durability::Fsync),
Ok(Rewritten::Done)
));
assert_eq!(std::fs::read_to_string(&file).unwrap(), "EDITED");
std::fs::remove_file(&file).unwrap();
assert_eq!(refused("EDITED"), changed, "gone");
if make_symlink(&dir.path().join("elsewhere"), &file) {
assert_eq!(
refused("EDITED"),
format!(
"cannot write {}: {SYMLINK_REFUSAL}",
safe_path(&target.shown)
),
"a symlink in its place"
);
}
}
#[test]
fn a_new_file_is_never_put_where_a_file_is() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("a.mds");
let target = WriteTarget::new(file.clone(), PathBuf::from("a.mds"));
let new = |content: &str| {
create_new(&target, content, Durability::RenameOnly, Parents::Existing).map_err(
|not_created| match not_created {
NotCreated::Exists => "exists".to_owned(),
NotCreated::Failed(e) => e.to_string(),
},
)
};
new("first").unwrap();
assert_eq!(std::fs::read_to_string(&file).unwrap(), "first");
assert_eq!(new("second"), Err("exists".to_owned()));
assert_eq!(std::fs::read_to_string(&file).unwrap(), "first");
assert_eq!(temp_residue(dir.path()), Vec::<String>::new());
atomic_write_file(
&target,
"replaced",
Durability::RenameOnly,
Parents::Existing,
)
.unwrap();
assert_eq!(std::fs::read_to_string(&file).unwrap(), "replaced");
std::fs::remove_file(&file).unwrap();
let elsewhere = dir.path().join("elsewhere");
if make_symlink(&elsewhere, &file) {
assert_eq!(
new("third"),
Err(format!(
"cannot write {}: {SYMLINK_REFUSAL}",
safe_path(&target.shown)
))
);
assert!(!elsewhere.exists(), "nothing is written through the link");
}
}
fn over_own(target: &WriteTarget, own: Option<&str>, content: &str) -> Result<(), String> {
write_over_own(
target,
own,
content,
Durability::RenameOnly,
Parents::Existing,
)
.map_err(|not_written| match not_written {
NotCreated::Exists => "kept".to_owned(),
NotCreated::Failed(e) => e.to_string(),
})
}
#[test]
fn a_write_over_its_own_file_replaces_no_other() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("a.md");
let target = WriteTarget::new(file.clone(), PathBuf::from("a.md"));
let text = || std::fs::read_to_string(&file).unwrap();
let kept = Err("kept".to_owned());
assert_eq!(over_own(&target, None, "first"), Ok(()), "nothing there");
assert_eq!(text(), "first");
assert_eq!(over_own(&target, None, "second"), kept, "not the caller's");
assert_eq!(text(), "first");
assert_eq!(
over_own(&target, Some("first"), "second"),
Ok(()),
"the caller's own, unchanged"
);
assert_eq!(text(), "second");
assert_eq!(
over_own(&target, Some("first"), "third"),
kept,
"changed since the caller wrote it"
);
assert_eq!(
over_own(&target, Some("secon"), "third"),
kept,
"more bytes"
);
assert_eq!(text(), "second");
assert_eq!(temp_residue(dir.path()), Vec::<String>::new());
std::fs::remove_file(&file).unwrap();
assert_eq!(over_own(&target, Some("second"), "third"), Ok(()), "gone");
assert_eq!(text(), "third");
std::fs::remove_file(&file).unwrap();
std::fs::create_dir(&file).unwrap();
assert_eq!(
over_own(&target, Some("third"), "fourth"),
kept,
"a directory"
);
assert!(file.is_dir(), "the directory is left");
std::fs::remove_dir(&file).unwrap();
let elsewhere = dir.path().join("elsewhere");
std::fs::write(&elsewhere, "third").unwrap();
if make_symlink(&elsewhere, &file) {
for own in [Some("third"), None] {
assert_eq!(over_own(&target, own, "fourth"), kept, "a symlink, {own:?}");
}
assert_eq!(
std::fs::read_to_string(&elsewhere).unwrap(),
"third",
"nothing is written through the link"
);
assert!(std::fs::symlink_metadata(&file)
.unwrap()
.file_type()
.is_symlink());
}
assert_eq!(temp_residue(dir.path()), Vec::<String>::new());
}
#[cfg(unix)]
#[test]
fn a_write_over_its_own_file_keeps_a_fifo() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("a.md");
let made = std::process::Command::new("mkfifo")
.arg(&file)
.status()
.expect("mkfifo runs");
assert!(made.success(), "mkfifo a.md");
let target = WriteTarget::new(file.clone(), PathBuf::from("a.md"));
for own in [Some("first"), None] {
assert_eq!(
over_own(&target, own, "second"),
Err("kept".to_owned()),
"{own:?}"
);
}
assert_eq!(
entries(dir.path()),
["a.md"],
"the FIFO is left, and no temporary file"
);
}
#[cfg(unix)]
#[test]
fn a_write_over_its_own_file_keeps_a_socket() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("a.md");
let _socket = std::os::unix::net::UnixListener::bind(&file).unwrap();
let target = WriteTarget::new(file.clone(), PathBuf::from("a.md"));
for own in [Some("first"), None] {
assert_eq!(
over_own(&target, own, "second"),
Err("kept".to_owned()),
"{own:?}"
);
}
assert_eq!(
entries(dir.path()),
["a.md"],
"the socket is left, and no temporary file"
);
}
#[cfg(unix)]
#[test]
fn a_write_over_its_own_file_reports_a_file_it_cannot_read() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("a.md");
let target = WriteTarget::new(file.clone(), PathBuf::from("a.md"));
let set_mode = |mode: u32| {
std::fs::set_permissions(&file, std::fs::Permissions::from_mode(mode)).unwrap();
};
std::fs::write(&file, "first").unwrap();
set_mode(0o200);
let Err(denied) = std::fs::File::open(&file) else {
crate::output::ewriteln!("running as root; mode 0o200 does not stop a read");
return;
};
let failed = over_own(&target, Some("first"), "second");
set_mode(0o644);
assert_eq!(
failed,
Err(format!(
"cannot write {}: {}",
safe_path(&target.shown),
io_cause(&denied)
))
);
assert_eq!(std::fs::read_to_string(&file).unwrap(), "first", "left");
assert_eq!(temp_residue(dir.path()), Vec::<String>::new());
assert_eq!(over_own(&target, Some("first"), "second"), Ok(()));
assert_eq!(std::fs::read_to_string(&file).unwrap(), "second");
}
#[test]
fn a_write_over_its_own_file_in_a_directory_gone_since_makes_it_again() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("sub").join("a.md");
let target = WriteTarget::below(dir.path(), Path::new("o"), Path::new("sub/a.md"));
let written = |own: Option<&str>| {
write_over_own(
&target,
own,
"second",
Durability::RenameOnly,
Parents::Create,
)
.map_err(|not_written| match not_written {
NotCreated::Exists => "kept".to_owned(),
NotCreated::Failed(e) => e.to_string(),
})
};
assert_eq!(written(None), Ok(()), "control: made where nothing is");
std::fs::remove_dir_all(dir.path().join("sub")).unwrap();
assert_eq!(written(Some("second")), Ok(()));
assert_eq!(std::fs::read_to_string(&file).unwrap(), "second");
}
#[test]
fn an_output_is_never_written_over_an_mds_module() {
let dir = tempfile::tempdir().unwrap();
let shown = |name: &str| PathBuf::from("out").join(name);
let write = |name: &str| {
write_compiled(
&WriteTarget::new(dir.path().join(name), shown(name)),
"X",
&Inputs::default(),
)
.map_err(|e| e.to_string())
};
let text = |name: &str| std::fs::read_to_string(dir.path().join(name)).unwrap();
for (name, module) in [
("m.md", "---\ntype: mds\n---\nM\n"),
("q.md", "---\ntype: \"mds\"\n---\nQ\n"),
("crlf.md", "---\r\ntype: 'mds'\r\n---\r\nC\r\n"),
("UP.MD", "---\ntype: mds\n---\nU\n"),
("mixed.Md", "---\ntype: mds\n---\nX\n"),
("source.mds", "---\ntype: mds\n---\nS\n"),
("plain.mds", "Hello\n"),
("UP.MDS", ""),
] {
std::fs::write(dir.path().join(name), module).unwrap();
assert_eq!(
write(name),
Err(format!(
"cannot write {}: {MODULE_REFUSED}",
shown(name).display()
)),
"{name}"
);
assert_eq!(text(name), module, "{name} is left as it is");
}
assert_eq!(
temp_residue(dir.path()),
Vec::<String>::new(),
"no temporary file"
);
for (name, other) in [
("plain.md", Some("plain\n")),
("other.md", Some("---\ntype: other\n---\nO\n")),
("nested.md", Some("---\nconfig:\n type: mds\n---\nN\n")),
("notes.txt", Some("---\ntype: mds\n---\nT\n")),
("new.md", None),
("new.mds", None),
] {
if let Some(other) = other {
std::fs::write(dir.path().join(name), other).unwrap();
}
assert_eq!(write(name), Ok(()), "control: {name} is written");
assert_eq!(text(name), "X", "control: {name}");
}
}
#[test]
fn a_module_is_replaced_only_by_output_that_is_itself_a_module() {
const GENERATED: &str = "---\ntype: mds\n---\nGenerated\n";
let dir = tempfile::tempdir().unwrap();
let path = |name: &str| dir.path().join(name);
let write = |name: &str, content: &str, inputs: &Inputs| {
write_compiled(
&WriteTarget::new(path(name), PathBuf::from(name)),
content,
inputs,
)
.map_err(|e| e.to_string())
};
let text = |name: &str| std::fs::read_to_string(path(name)).unwrap();
let module = "---\ntype: mds\n---\nM\n";
std::fs::write(path("m.md"), module).unwrap();
assert_eq!(
write("m.md", "plain\n", &Inputs::default()),
Err(format!("cannot write m.md: {MODULE_REFUSED}")),
"control: an output that is no module"
);
assert_eq!(
write(
"m.md",
"---\nconfig:\n type: mds\n---\nN\n",
&Inputs::default()
),
Err(format!("cannot write m.md: {MODULE_REFUSED}")),
"control: type: mds below another key is no module"
);
assert_eq!(text("m.md"), module, "left as it is");
assert_eq!(write("m.md", GENERATED, &Inputs::default()), Ok(()));
assert_eq!(text("m.md"), GENERATED, "a module replaces a module");
std::fs::write(path("lib.mds"), "Hello\n").unwrap();
assert_eq!(
write("lib.mds", "plain\n", &Inputs::default()),
Err(format!("cannot write lib.mds: {MODULE_REFUSED}")),
"control: an output that is no module, over a .mds file"
);
assert_eq!(write("lib.mds", GENERATED, &Inputs::default()), Ok(()));
assert_eq!(text("lib.mds"), GENERATED, "a module replaces a .mds file");
let crlf = "---\r\ntype: 'mds'\r\n---\r\nAgain\r\n";
assert_eq!(write("m.md", crlf, &Inputs::default()), Ok(()));
assert_eq!(text("m.md"), crlf, "and its own output again");
assert_eq!(
write("m.md", GENERATED, &Inputs::new([path("m.md")])),
Err(format!("cannot write m.md: {INPUT_REFUSAL}")),
"never over a file the run reads"
);
assert_eq!(text("m.md"), crlf, "the input is left as it is");
assert_eq!(
temp_residue(dir.path()),
Vec::<String>::new(),
"no temporary file"
);
}
#[cfg(unix)]
#[test]
fn a_module_is_judged_in_the_directory_the_write_opened() {
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
const HOLD: Duration = Duration::from_micros(200);
const MODULE: &str = "---\ntype: mds\n---\nM\n";
let dir = tempfile::tempdir().unwrap();
let (with_module, plain) = (dir.path().join("with-module"), dir.path().join("plain"));
std::fs::create_dir(&with_module).unwrap();
std::fs::create_dir(&plain).unwrap();
std::fs::write(with_module.join("a.md"), MODULE).unwrap();
std::fs::write(plain.join("a.md"), "plain\n").unwrap();
let cur = dir.path().join("cur");
std::os::unix::fs::symlink(&with_module, &cur).unwrap();
let target = WriteTarget::below(&cur, Path::new("cur"), Path::new("a.md"));
let stop = Arc::new(AtomicBool::new(false));
let swapper = {
let stop = Arc::clone(&stop);
let (base, with_module, plain) =
(dir.path().to_path_buf(), with_module.clone(), plain.clone());
std::thread::spawn(move || {
for i in 0..100_000u32 {
if stop.load(Ordering::Relaxed) {
break;
}
let next = if i % 2 == 0 { &plain } else { &with_module };
let link = base.join(format!("link-{i}"));
let _ = std::os::unix::fs::symlink(next, &link);
let _ = std::fs::rename(&link, base.join("cur"));
std::thread::sleep(HOLD);
}
})
};
let started = Instant::now();
let (mut written, mut refused) = (0u32, 0u32);
for _ in 0..2_000 {
if started.elapsed() > Duration::from_secs(10) {
break;
}
match write_compiled(&target, "X", &Inputs::default()) {
Ok(()) => written += 1,
Err(e) if e.to_string().contains(MODULE_REFUSAL) => refused += 1,
Err(_) => {}
}
}
stop.store(true, Ordering::Relaxed);
swapper.join().unwrap();
assert_eq!(
std::fs::read_to_string(with_module.join("a.md")).unwrap(),
MODULE,
"the module is never replaced ({written} written, {refused} refused)"
);
assert!(
written > 0 && refused > 0,
"the loop met both directories: {written} written, {refused} refused"
);
}
#[test]
fn an_output_is_never_written_over_a_file_the_run_reads() {
let dir = tempfile::tempdir().unwrap();
let (vars, other) = (dir.path().join("vars.json"), dir.path().join("other.json"));
std::fs::write(&vars, "{}\n").unwrap();
std::fs::write(&other, "{}\n").unwrap();
let inputs = Inputs::new([vars.clone()]);
let write = |path: &Path, inputs: &Inputs| {
write_compiled(
&WriteTarget::new(path.to_path_buf(), PathBuf::from("out/x.json")),
"X",
inputs,
)
.map_err(|e| e.to_string())
};
assert_eq!(
write(&vars, &inputs),
Err(format!(
"cannot write {}: {INPUT_REFUSAL}",
Path::new("out/x.json").display()
))
);
assert_eq!(
std::fs::read_to_string(&vars).unwrap(),
"{}\n",
"left as it is"
);
assert_eq!(
temp_residue(dir.path()),
Vec::<String>::new(),
"no temporary file"
);
assert_eq!(
write(&other, &inputs),
Ok(()),
"control: no input is written"
);
assert_eq!(
write(&vars, &Inputs::default()),
Ok(()),
"control: no inputs"
);
assert_eq!(std::fs::read_to_string(&vars).unwrap(), "X");
}
#[test]
fn an_input_found_from_a_path_is_searched_for_only_when_a_file_is_at_the_target() {
use std::sync::atomic::{AtomicUsize, Ordering};
static SEARCHES: AtomicUsize = AtomicUsize::new(0);
fn beside(from: &Path) -> Option<PathBuf> {
SEARCHES.fetch_add(1, Ordering::SeqCst);
Some(from.with_file_name("mds.json"))
}
let dir = tempfile::tempdir().unwrap();
let path = |name: &str| dir.path().join(name);
let inputs = Inputs::default().and_found_from(&path("page.mds"), beside);
let write = |name: &str| {
write_compiled(
&WriteTarget::new(path(name), PathBuf::from(name)),
"X",
&inputs,
)
.map_err(|e| e.to_string())
};
let searches = || SEARCHES.load(Ordering::SeqCst);
assert_eq!(write("page.md"), Ok(()));
assert_eq!(searches(), 0, "a new file is written without the search");
assert_eq!(
write("page.md"),
Ok(()),
"control: no input is written over"
);
assert_eq!(
searches(),
1,
"control: a file at the target is searched for"
);
std::fs::write(path("mds.json"), "{}\n").unwrap();
assert_eq!(
write("mds.json"),
Err(format!("cannot write mds.json: {INPUT_REFUSAL}"))
);
assert_eq!(searches(), 2);
assert_eq!(
std::fs::read_to_string(path("mds.json")).unwrap(),
"{}\n",
"left as it is"
);
}
#[test]
fn a_compiled_output_s_write_looks_at_the_file_beside_it() {
let dir = tempfile::tempdir().unwrap();
let path = |name: &str| dir.path().join(name);
let target = WriteTarget::new(path("a.md"), PathBuf::from("a.md"));
let look = |beside: &WriteTarget| {
write_compiled_and_look(&target, "X", &Inputs::default(), beside)
.map_err(|e| e.to_string())
};
let named = |name: &str| target.sibling(|file| file.with_file_name(name));
assert_eq!(look(&named("a.json")), Ok(Beside::Nothing), "nothing there");
std::fs::write(path("a.json"), "[]\n").unwrap();
assert_eq!(look(&named("a.json")), Ok(Beside::Something), "a file");
assert_eq!(
std::fs::read_to_string(path("a.json")).unwrap(),
"[]\n",
"left as it is"
);
std::fs::create_dir(path("d.json")).unwrap();
assert_eq!(look(&named("d.json")), Ok(Beside::Something), "a directory");
#[cfg(unix)]
{
std::os::unix::fs::symlink(path("gone"), path("l.json")).unwrap();
assert_eq!(
look(&named("l.json")),
Ok(Beside::Something),
"a dangling symlink"
);
}
std::fs::create_dir(path("sub")).unwrap();
std::fs::write(path("sub").join("e.json"), "[]\n").unwrap();
let elsewhere = WriteTarget::new(path("sub").join("e.json"), PathBuf::from("e.json"));
assert_eq!(
look(&elsewhere),
Ok(Beside::Something),
"another directory is not looked at"
);
assert_eq!(std::fs::read_to_string(path("a.md")).unwrap(), "X");
}
#[cfg(unix)]
#[test]
fn an_input_is_the_file_its_path_leads_to_now() {
let dir = tempfile::tempdir().unwrap();
let path = |name: &str| dir.path().join(name);
std::fs::write(path("vars.json"), "{}\n").unwrap();
std::fs::hard_link(path("vars.json"), path("linked.json")).unwrap();
std::os::unix::fs::symlink(path("vars.json"), path("via.json")).unwrap();
std::fs::write(path("copy.json"), "{}\n").unwrap();
let write = |name: &str, inputs: &Inputs| {
write_compiled(
&WriteTarget::new(path(name), PathBuf::from(name)),
"X",
inputs,
)
.map_err(|e| e.to_string())
};
let refused = |name: &str| Err(format!("cannot write {name}: {INPUT_REFUSAL}"));
assert_eq!(
write("linked.json", &Inputs::new([path("vars.json")])),
refused("linked.json")
);
assert_eq!(
write("vars.json", &Inputs::new([path("via.json")])),
refused("vars.json")
);
assert_eq!(std::fs::read_to_string(path("vars.json")).unwrap(), "{}\n");
assert_eq!(
write("copy.json", &Inputs::new([path("vars.json")])),
Ok(()),
"control: a copy is another file"
);
}
#[cfg(unix)]
#[test]
fn an_output_is_never_written_over_a_markdown_file_it_cannot_read() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let path = |name: &str| dir.path().join(name);
let shown = |name: &str| PathBuf::from("out").join(name);
let write = |name: &str| {
write_compiled(
&WriteTarget::new(path(name), shown(name)),
"X",
&Inputs::default(),
)
.map_err(|e| e.to_string())
};
let set_mode = |name: &str, mode: u32| {
std::fs::set_permissions(path(name), std::fs::Permissions::from_mode(mode)).unwrap();
};
std::fs::write(path("locked.md"), "notes\n").unwrap();
std::fs::write(path("locked.json"), "{}\n").unwrap();
set_mode("locked.md", 0o000);
set_mode("locked.json", 0o000);
let Err(denied) = std::fs::File::open(path("locked.md")) else {
crate::output::ewriteln!("running as root; mode 0o000 does not stop a read");
return;
};
let refused = write("locked.md");
set_mode("locked.md", 0o644);
assert_eq!(
refused,
Err(format!(
"cannot write {}: {MODULE_UNKNOWN}: {}",
shown("locked.md").display(),
io_cause(&denied)
))
);
assert_eq!(
std::fs::read_to_string(path("locked.md")).unwrap(),
"notes\n",
"left as it is"
);
assert_eq!(
temp_residue(dir.path()),
Vec::<String>::new(),
"no temporary file"
);
assert_eq!(
write("locked.md"),
Ok(()),
"control: readable, it is written"
);
assert_eq!(std::fs::read_to_string(path("locked.md")).unwrap(), "X");
assert_eq!(
write("locked.json"),
Ok(()),
"control: a .json file is never opened"
);
set_mode("locked.json", 0o644);
assert_eq!(std::fs::read_to_string(path("locked.json")).unwrap(), "X");
std::fs::write(path("locked.mds"), "Hello\n").unwrap();
set_mode("locked.mds", 0o000);
let refused = write("locked.mds");
set_mode("locked.mds", 0o644);
assert_eq!(
refused,
Err(format!(
"cannot write {}: {MODULE_REFUSED}",
shown("locked.mds").display()
)),
"a .mds file is never read to tell"
);
assert_eq!(
std::fs::read_to_string(path("locked.mds")).unwrap(),
"Hello\n"
);
}
#[test]
fn a_name_is_judged_without_the_dots_and_spaces_windows_drops() {
let trimmed = |name: &str| as_windows_opens(name.as_bytes()).to_vec();
for (name, opens) in [
("lib.md.", "lib.md"),
("lib.md ", "lib.md"),
("lib.md. .", "lib.md"),
("lib.mds...", "lib.mds"),
("lib.md", "lib.md"),
("a. b.md", "a. b.md"),
("...", "..."),
(". ", ". "),
("", ""),
] {
assert_eq!(trimmed(name), opens.as_bytes(), "{name:?}");
}
let wide: Vec<u16> = "lib.md .".encode_utf16().collect();
let expected: Vec<u16> = "lib.md".encode_utf16().collect();
assert_eq!(as_windows_opens(&wide), expected.as_slice(), "UTF-16");
}
#[test]
fn the_module_check_reads_no_further_than_the_frontmatter() {
use std::io::Seek as _;
const ONE_READ: usize = 8 * 1024;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("out.md");
let check = |text: &str| -> (bool, usize) {
std::fs::write(&path, text).unwrap();
let mut file = std::fs::File::open(&path).unwrap();
let module = is_mds_module(&mut file).unwrap();
let read = usize::try_from(file.stream_position().unwrap()).unwrap();
(module, read)
};
let body = "b\n".repeat(512 * 1024);
let straddle = format!("---\ntype: mds\n{}", "a".repeat(8181));
for (label, frontmatter, module) in [
("no type", "---\ntitle: t\n---\n".to_owned(), false),
("a module", "---\ntype: mds\n---\n".to_owned(), true),
("CRLF", "---\r\ntype: mds\r\n---\r\n".to_owned(), true),
("across two reads", format!("{straddle}\n---\n"), true),
(
"longer than one read",
format!("---\n{}type: mds\n---\n", "k: v\n".repeat(5000)),
true,
),
] {
let (judged, read) = check(&format!("{frontmatter}{body}"));
assert_eq!(judged, module, "{label}");
assert!(
read <= frontmatter.len() + ONE_READ,
"{label}: read {read} bytes of a {}-byte frontmatter",
frontmatter.len()
);
}
let cap = usize::try_from(mds::MAX_FILE_SIZE).unwrap();
let (judged, read) = check(&format!("---\ntype: mds\n{}", "u".repeat(cap + 1024)));
assert!(!judged, "a fence that never closes is no module");
assert!(read <= cap, "read {read} bytes, past the cap");
let (judged, read) = check(&format!("plain\n{body}"));
assert!(!judged, "control");
assert!(read <= 5, "control: read {read} bytes");
}
#[cfg(windows)]
#[test]
fn on_windows_a_name_ending_in_dots_or_spaces_is_judged_as_the_file_it_opens() {
let dir = tempfile::tempdir().unwrap();
let path = |name: &str| dir.path().join(name);
let write = |name: &str| {
write_compiled(
&WriteTarget::new(path(name), PathBuf::from(name)),
"X",
&Inputs::default(),
)
.map_err(|e| e.to_string())
};
let module = "---\ntype: mds\n---\nM\n";
std::fs::write(path("m.md"), module).unwrap();
std::fs::write(path("lib.mds"), "Hello\n").unwrap();
std::fs::write(path("plain.md"), "notes\n").unwrap();
for name in ["m.md.", "m.md ", "lib.mds."] {
assert_eq!(
write(name),
Err(format!("cannot write {name}: {MODULE_REFUSED}")),
"{name:?}"
);
}
assert_eq!(std::fs::read_to_string(path("m.md")).unwrap(), module);
assert_eq!(std::fs::read_to_string(path("lib.mds")).unwrap(), "Hello\n");
assert_eq!(write("plain.md."), Ok(()), "control");
assert_eq!(std::fs::read_to_string(path("plain.md")).unwrap(), "X");
}
#[cfg(windows)]
#[test]
fn on_windows_a_file_another_program_holds_open_is_still_replaced() {
use std::io::Write as _;
const ERROR_ACCESS_DENIED: i32 = 5;
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("out.md");
std::fs::write(&file, "old\n").unwrap();
let held = std::fs::File::open(&file).unwrap();
let mut control = tempfile::NamedTempFile::new_in(dir.path()).unwrap();
control.write_all(b"control\n").unwrap();
let refused = control
.persist(&file)
.expect_err("control: persist over a file held open must fail");
assert_eq!(
refused.error.raw_os_error(),
Some(ERROR_ACCESS_DENIED),
"control: {}",
refused.error
);
drop(refused);
assert_eq!(std::fs::read_to_string(&file).unwrap(), "old\n", "control");
let target = WriteTarget::new(file.clone(), PathBuf::from("out.md"));
assert_eq!(
write_compiled(&target, "output\n", &Inputs::default()).map_err(|e| e.to_string()),
Ok(()),
"an output"
);
assert_eq!(std::fs::read_to_string(&file).unwrap(), "output\n");
let held_again = std::fs::File::open(&file).unwrap();
let read = read_stamped(&target, "output\n").unwrap();
assert!(
matches!(
replace_if_unchanged(read, "rewrite\n", Durability::Fsync),
Ok(Rewritten::Done)
),
"a rewrite"
);
assert_eq!(std::fs::read_to_string(&file).unwrap(), "rewrite\n");
assert_eq!(temp_residue(dir.path()), Vec::<String>::new());
drop((held, held_again));
}
#[cfg(unix)]
#[test]
fn each_step_of_a_new_file_s_commit_never_replaces_a_file() {
use std::cell::RefCell;
use std::ffi::OsString;
use std::io::Write as _;
use std::os::fd::{AsFd as _, BorrowedFd};
use rustix::fs::{Mode, OFlags};
use rustix::io::Errno;
use super::unix::{commit_new, create_temp, NewSteps, NO_CLOBBER};
#[derive(Debug, PartialEq, Eq)]
struct Outcome {
result: Result<(), String>,
steps: Vec<&'static str>,
file: Option<String>,
names: Vec<String>,
}
let commit = |rename: Option<Errno>, link: Option<Errno>, taken: bool| {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("a.mds");
if taken {
std::fs::write(&file, "there").unwrap();
}
let fd = rustix::fs::open(
dir.path(),
OFlags::RDONLY | OFlags::DIRECTORY,
Mode::empty(),
)
.unwrap();
let taken_steps = RefCell::new(Vec::new());
let forced_rename = |d: BorrowedFd<'_>, from: &OsStr, to: &OsStr| {
taken_steps.borrow_mut().push("rename");
rename.map_or_else(|| (NO_CLOBBER.rename)(d, from, to), Err)
};
let forced_link = |d: BorrowedFd<'_>, from: &OsStr, to: &OsStr| {
taken_steps.borrow_mut().push("link");
link.map_or_else(|| (NO_CLOBBER.link)(d, from, to), Err)
};
let steps = NewSteps {
rename: &forced_rename,
link: &forced_link,
fill: NO_CLOBBER.fill,
};
let temp_name = OsString::from(format!("{TEMP_PREFIX}step{TEMP_SUFFIX}"));
let (temp, mut written) =
create_temp(fd.as_fd(), Mode::from_raw_mode(0o644), [temp_name]).unwrap();
written.write_all(b"new").unwrap();
drop(written);
let result = commit_new(
temp,
OsStr::new("a.mds"),
b"new",
Durability::RenameOnly,
&steps,
)
.map_err(|failure| match failure {
Failure::Exists => "exists".to_owned(),
Failure::Io(e) => format!("{:?}", Errno::from_io_error(&e)),
other => format!("{other:?}"),
});
Outcome {
result,
steps: taken_steps.into_inner(),
file: std::fs::read_to_string(&file).ok(),
names: entries(dir.path()),
}
};
let landed = |steps: &[&'static str]| Outcome {
result: Ok(()),
steps: steps.to_vec(),
file: Some("new".to_owned()),
names: vec!["a.mds".to_owned()],
};
let refused = |steps: &[&'static str]| Outcome {
result: Err("exists".to_owned()),
steps: steps.to_vec(),
file: Some("there".to_owned()),
names: vec!["a.mds".to_owned()],
};
assert_eq!(commit(None, None, false), landed(&["rename"]), "renamed");
assert_eq!(
commit(None, None, true),
refused(&["rename"]),
"rename refused"
);
for no_rename in [Errno::INVAL, Errno::NOSYS, Errno::NOTSUP, Errno::OPNOTSUPP] {
let both = ["rename", "link"];
assert_eq!(
commit(Some(no_rename), None, false),
landed(&both),
"{no_rename:?}: linked"
);
assert_eq!(
commit(Some(no_rename), None, true),
refused(&both),
"{no_rename:?}: link refused"
);
}
for no_link in [
Errno::PERM,
Errno::NOSYS,
Errno::NOTSUP,
Errno::OPNOTSUPP,
Errno::MLINK,
] {
let both = ["rename", "link"];
assert_eq!(
commit(Some(Errno::INVAL), Some(no_link), false),
landed(&both),
"{no_link:?}: written in place"
);
assert_eq!(
commit(Some(Errno::INVAL), Some(no_link), true),
refused(&both),
"{no_link:?}: written in place refused"
);
}
let failed = |steps: &[&'static str]| Outcome {
result: Err(format!("{:?}", Some(Errno::IO))),
steps: steps.to_vec(),
file: None,
names: Vec::new(),
};
assert_eq!(
commit(Some(Errno::IO), None, false),
failed(&["rename"]),
"a failed rename is no reason to link"
);
assert_eq!(
commit(Some(Errno::INVAL), Some(Errno::IO), false),
failed(&["rename", "link"]),
"a failed link is no reason to write in place"
);
}
#[cfg(unix)]
#[test]
fn a_new_file_written_in_place_that_fails_part_way_is_removed_again() {
use std::ffi::OsString;
use std::fs::File;
use std::io::Write as _;
use std::os::fd::{AsFd as _, BorrowedFd};
use rustix::fs::{Mode, OFlags};
use rustix::io::Errno;
use super::unix::{commit_new, create_temp, Fill, NewSteps, NO_CLOBBER};
const CONTENT: &[u8] = b"new content";
let in_place = |dir: &Path, fill: Fill<'_>| {
let fd =
rustix::fs::open(dir, OFlags::RDONLY | OFlags::DIRECTORY, Mode::empty()).unwrap();
let no_rename = |_: BorrowedFd<'_>, _: &OsStr, _: &OsStr| Err(Errno::INVAL);
let no_link = |_: BorrowedFd<'_>, _: &OsStr, _: &OsStr| Err(Errno::PERM);
let steps = NewSteps {
rename: &no_rename,
link: &no_link,
fill,
};
let temp_name = OsString::from(format!("{TEMP_PREFIX}step{TEMP_SUFFIX}"));
let (temp, mut written) =
create_temp(fd.as_fd(), Mode::from_raw_mode(0o644), [temp_name]).unwrap();
written.write_all(CONTENT).unwrap();
drop(written);
let result = commit_new(
temp,
OsStr::new("a.mds"),
CONTENT,
Durability::RenameOnly,
&steps,
)
.map_err(|failure| match failure {
Failure::Io(e) => format!("{:?}", Errno::from_io_error(&e)),
other => format!("{other:?}"),
});
let left: Vec<(String, String)> = entries(dir)
.into_iter()
.map(|name| {
let text = std::fs::read_to_string(dir.join(&name)).unwrap();
(name, text)
})
.collect();
(result, left)
};
let no_space = format!("{:?}", Some(Errno::NOSPC));
let dir = tempfile::tempdir().unwrap();
assert_eq!(
in_place(dir.path(), NO_CLOBBER.fill),
(Ok(()), vec![("a.mds".to_owned(), "new content".to_owned())]),
"control: written whole"
);
let dir = tempfile::tempdir().unwrap();
let part_way = |mut file: File, content: &[u8], _: Durability| {
file.write_all(&content[..3])?;
Err(Errno::NOSPC.into())
};
assert_eq!(
in_place(dir.path(), &part_way),
(Err(no_space.clone()), Vec::new()),
"removed again"
);
let dir = tempfile::tempdir().unwrap();
let theirs = dir.path().join("theirs");
let replaced_meanwhile = |mut file: File, content: &[u8], _: Durability| {
file.write_all(&content[..3])?;
std::fs::write(&theirs, "theirs")?;
std::fs::rename(&theirs, dir.path().join("a.mds"))?;
Err(Errno::NOSPC.into())
};
assert_eq!(
in_place(dir.path(), &replaced_meanwhile),
(
Err(no_space),
vec![("a.mds".to_owned(), "theirs".to_owned())]
),
"a file put at the name since is left"
);
}
fn to_remove(anchor: &Path, rel: &str) -> WriteTarget {
WriteTarget::below(anchor, Path::new("o"), Path::new(rel))
}
#[test]
fn a_file_its_proof_does_not_accept_is_kept() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("x.json");
std::fs::write(&file, "stale").unwrap();
let target = to_remove(dir.path(), "x.json");
let mut read = String::new();
let kept = remove_proven(&target, |opened| {
std::io::Read::read_to_string(opened, &mut read)?;
Ok(false)
});
assert_eq!(kept, Ok(Removal::Kept));
assert_eq!(read, "stale", "the proof reads the file to be removed");
assert_eq!(
std::fs::read_to_string(&file).unwrap(),
"stale",
"it is kept"
);
let unreadable = remove_proven(&target, |_| Err(std::io::ErrorKind::InvalidData.into()));
assert!(
matches!(unreadable, Err(NotRemoved::Unreadable(_))),
"{unreadable:?}"
);
assert!(file.exists(), "a file its proof cannot read is kept");
assert_eq!(remove_proven(&target, |_| Ok(true)), Ok(Removal::Removed));
assert!(!file.exists(), "control: the file proven is removed");
}
#[test]
fn a_file_that_is_not_there_is_nothing_to_remove() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("file"), "x").unwrap();
for rel in ["gone.json", "gone/x.json", "file/x.json"] {
let removal = remove_proven(&to_remove(dir.path(), rel), |_| {
panic!("{rel}: there is no file to prove")
});
assert_eq!(removal, Ok(Removal::Missing), "{rel}");
}
std::fs::write(dir.path().join("here.json"), "x").unwrap();
let mut asked = false;
let removal = remove_proven(&to_remove(dir.path(), "here.json"), |_| {
asked = true;
Ok(false)
});
assert_eq!(removal, Ok(Removal::Kept));
assert!(asked, "control: the proof is asked of a file that is there");
}
#[test]
fn a_name_too_long_for_the_file_system_is_nothing_to_remove() {
let dir = tempfile::tempdir().unwrap();
let too_long = format!("{}.json", "x".repeat(300));
let removal = remove_proven(&to_remove(dir.path(), &too_long), |_| {
panic!("there is no file to prove")
});
assert_eq!(removal, Ok(Removal::Missing));
let longest = format!("{}.json", "y".repeat(250));
std::fs::write(dir.path().join(&longest), "x").unwrap();
assert_eq!(
remove_proven(&to_remove(dir.path(), &longest), |_| Ok(true)),
Ok(Removal::Removed),
"control"
);
}
#[cfg(unix)]
#[test]
fn a_directory_name_too_long_on_the_way_is_an_error() {
let dir = tempfile::tempdir().unwrap();
let rel = format!("{}/x.json", "d".repeat(300));
let removal = remove_proven(&to_remove(dir.path(), &rel), |_| {
panic!("there is no file to prove")
});
assert_eq!(
removal,
Err(NotRemoved::Failed(os_text(rustix::io::Errno::NAMETOOLONG)))
);
}
#[test]
fn a_removal_through_a_symlink_or_of_one_is_refused() {
let dir = tempfile::tempdir().unwrap();
let anchor = dir.path().join("out");
let real = anchor.join("real");
let victim = dir.path().join("victim");
std::fs::create_dir_all(&real).unwrap();
std::fs::create_dir(&victim).unwrap();
std::fs::write(victim.join("x.json"), "victim").unwrap();
let linked = make_symlink(&victim, &anchor.join("sub"))
&& make_symlink(&victim.join("x.json"), &real.join("live.json"))
&& make_symlink(&dir.path().join("nowhere"), &real.join("gone.json"));
let links: &[&str] = if linked {
&["gone.json", "live.json"]
} else {
&[]
};
if linked {
assert_eq!(
remove_proven(&to_remove(&anchor, "sub/x.json"), |_| Ok(true)),
Err(NotRemoved::Failed(format!(
"{FOLLOW_REFUSAL} at {}",
Path::new("o").join("sub").display()
)))
);
for link in ["real/live.json", "real/gone.json"] {
let removal = remove_proven(&to_remove(&anchor, link), |_| Ok(true));
assert_eq!(removal, Err(NotRemoved::Link), "{link}");
assert_eq!(
removal.unwrap_err().cause(),
SYMLINK_REMOVAL_REFUSAL,
"{link}"
);
}
assert_eq!(
std::fs::read_to_string(victim.join("x.json")).unwrap(),
"victim",
"nothing is removed through a symlink"
);
assert_eq!(entries(&real), links, "no symlink is removed");
}
std::fs::write(real.join("x.json"), "stale").unwrap();
assert_eq!(
remove_proven(&to_remove(&anchor, "real/x.json"), |_| Ok(true)),
Ok(Removal::Removed)
);
assert_eq!(entries(&real), links, "control: the file is removed");
}
#[cfg(unix)]
#[test]
fn anything_but_a_regular_file_is_left() {
let dir = tempfile::tempdir().unwrap();
let made = std::process::Command::new("mkfifo")
.arg(dir.path().join("x.json"))
.status()
.expect("mkfifo runs");
assert!(made.success(), "mkfifo x.json");
std::fs::create_dir(dir.path().join("x.md")).unwrap();
for name in ["x.json", "x.md"] {
let removal = remove_proven(&to_remove(dir.path(), name), |_| {
panic!("{name}: not a file to prove")
});
assert_eq!(removal, Err(NotRemoved::NotAFile), "{name}");
}
assert_eq!(entries(dir.path()), ["x.json", "x.md"], "both are left");
std::fs::write(dir.path().join("x.txt"), "stale").unwrap();
assert_eq!(
remove_proven(&to_remove(dir.path(), "x.txt"), |_| Ok(true)),
Ok(Removal::Removed)
);
assert_eq!(
entries(dir.path()),
["x.json", "x.md"],
"control: the file is removed"
);
}
#[test]
fn a_file_put_in_the_place_of_the_one_proven_is_not_removed() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("x.json");
let other = dir.path().join("other.json");
std::fs::write(&file, "proven").unwrap();
std::fs::write(&other, "put there").unwrap();
let target = to_remove(dir.path(), "x.json");
let swapped = remove_proven(&target, |_| {
std::fs::rename(&other, &file).expect("put another file at the name");
Ok(true)
});
assert_eq!(
swapped,
Err(NotRemoved::Failed(CHANGED_WHILE_CHECKED.to_owned()))
);
assert_eq!(
std::fs::read_to_string(&file).unwrap(),
"put there",
"the file put there is left"
);
assert_eq!(remove_proven(&target, |_| Ok(true)), Ok(Removal::Removed));
assert!(!file.exists(), "control: the file proven is removed");
}
#[test]
fn an_edit_made_in_place_after_the_proof_read_it_is_not_removed() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("x.json");
let target = to_remove(dir.path(), "x.json");
let read_then = |edit: Option<&'static str>| {
let path = path.clone();
move |file: &mut std::fs::File| {
let mut read = String::new();
std::io::Read::read_to_string(file, &mut read)?;
if let Some(edit) = edit {
std::fs::write(&path, edit)?;
}
Ok(read == "mds bytes")
}
};
std::fs::write(&path, "mds bytes").unwrap();
let edited = remove_proven(&target, read_then(Some("the user's edit, longer")));
assert_eq!(
std::fs::read_to_string(&path).ok().as_deref(),
Some("the user's edit, longer"),
"the edit is left"
);
assert_eq!(
edited,
Err(NotRemoved::Failed(CHANGED_WHILE_CHECKED.to_owned()))
);
std::fs::write(&path, "mds bytes").unwrap();
assert_eq!(
remove_proven(&target, read_then(None)),
Ok(Removal::Removed)
);
assert!(!path.exists(), "control: the file proven is removed");
}
#[cfg(unix)]
#[test]
fn a_removal_whose_anchor_is_not_the_directory_checked_is_refused() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out");
let other = dir.path().join("other");
std::fs::create_dir_all(out.join("sub")).unwrap();
std::fs::create_dir(&other).unwrap();
let file = out.join("sub/x.json");
std::fs::write(&file, "stale").unwrap();
let identity = |of: &Path| DirIdentity::of(of).expect("a directory");
let target = to_remove(&out, "sub/x.json");
let swapped = target.below_checked_anchor(&out, 0, identity(&other));
assert_eq!(
remove_proven(&swapped, |_| Ok(true)),
Err(NotRemoved::out_dir_moved())
);
assert!(file.exists(), "nothing is removed below it");
let checked = target.below_checked_anchor(&out, 0, identity(&out));
assert_eq!(remove_proven(&checked, |_| Ok(true)), Ok(Removal::Removed));
assert!(!file.exists(), "control: the file is removed");
}
#[cfg(unix)]
#[test]
fn temporary_names_are_tried_a_bounded_number_of_times() {
use std::os::fd::AsFd as _;
use super::unix::{create_temp, MAX_TEMP_ATTEMPTS};
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join(".taken"), "T").unwrap();
let fd = rustix::fs::open(
dir.path(),
rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::DIRECTORY,
rustix::fs::Mode::empty(),
)
.unwrap();
let tried = std::cell::Cell::new(0usize);
let taken = std::iter::repeat_with(|| {
tried.set(tried.get() + 1);
std::ffi::OsString::from(".taken")
});
let result = create_temp(fd.as_fd(), rustix::fs::Mode::RUSR, taken);
assert_eq!(result.map(|_| ()).unwrap_err(), rustix::io::Errno::EXIST);
assert_eq!(tried.get(), MAX_TEMP_ATTEMPTS);
assert_eq!(
std::fs::read_to_string(dir.path().join(".taken")).unwrap(),
"T"
);
let free = [std::ffi::OsString::from(".free")];
let (temp, _file) = create_temp(fd.as_fd(), rustix::fs::Mode::RUSR, free).unwrap();
assert_eq!(temp.name, ".free");
drop(temp);
assert!(
!dir.path().join(".free").exists(),
"dropped, the file is unlinked"
);
}
#[cfg(unix)]
#[test]
fn an_error_writing_names_the_file_as_shown_and_no_path_of_its_own() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let sub = dir.path().join("sub");
std::fs::create_dir(&sub).unwrap();
let target = WriteTarget::new(sub.join("locked.mds"), Path::new("out").join("locked.mds"));
std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o555)).unwrap();
let probe = std::fs::write(sub.join("probe"), "");
let result = atomic_write_file(&target, "NEW", Durability::Fsync, Parents::Existing);
std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o755)).unwrap();
if probe.is_ok() {
crate::output::ewriteln!(
"running as root; a read-only directory does not stop the write"
);
return;
}
let err = result
.expect_err("a read-only directory must fail the write")
.to_string();
assert_eq!(
err,
format!(
"cannot write out/locked.mds: {}",
os_text(rustix::io::Errno::ACCESS)
)
);
let tmp = dir.path().display().to_string();
assert!(!err.contains(&tmp), "no path of the write's own: {err}");
assert!(!err.contains(TEMP_PREFIX), "no temporary file: {err}");
}
#[test]
fn atomic_write_file_creates_missing_target() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("fresh.md");
assert!(!target.exists(), "precondition: target must be absent");
write_as_typed(&target, "CREATED", Durability::Fsync)
.expect("writing an absent target must succeed");
assert_eq!(std::fs::read_to_string(&target).unwrap(), "CREATED");
let residue = temp_residue(dir.path());
assert!(
residue.is_empty(),
"no .mds-tmp- residue may survive a successful write; got {residue:?}"
);
}
#[test]
fn atomic_write_file_rename_only_matches_fsync_contract() {
let dir = tempfile::tempdir().unwrap();
let quick = dir.path().join("quick.md");
let synced = dir.path().join("synced.md");
write_as_typed(&quick, "DERIVED", Durability::RenameOnly).unwrap();
write_as_typed(&synced, "DERIVED", Durability::Fsync).unwrap();
assert_eq!(std::fs::read_to_string(&quick).unwrap(), "DERIVED");
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt as _;
assert_eq!(
std::fs::metadata(&quick).unwrap().permissions().mode() & 0o777,
std::fs::metadata(&synced).unwrap().permissions().mode() & 0o777,
"RenameOnly must not change the mode a fresh artifact is created with"
);
}
write_as_typed(&quick, "REBUILT", Durability::RenameOnly).unwrap();
assert_eq!(std::fs::read_to_string(&quick).unwrap(), "REBUILT");
write_as_typed(&synced, "RESYNCED", Durability::Fsync).unwrap();
assert_eq!(std::fs::read_to_string(&synced).unwrap(), "RESYNCED");
{
let real = dir.path().join("real.md");
std::fs::write(&real, "REAL").unwrap();
let link = dir.path().join("link.md");
if !make_symlink(&real, &link) {
return;
}
let err = write_as_typed(&link, "NEW", Durability::RenameOnly)
.expect_err("RenameOnly must still refuse a symlink target");
assert!(
err.to_string().contains("symlink"),
"the refusal must say why; got: {err}"
);
assert_eq!(std::fs::read_to_string(&real).unwrap(), "REAL");
}
let residue = temp_residue(dir.path());
assert!(
residue.is_empty(),
"RenameOnly must leave no .mds-tmp- residue; got {residue:?}"
);
}
#[cfg(unix)]
#[test]
fn atomic_write_file_new_file_mode_matches_std_fs_write() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out.md");
let ctl = dir.path().join("ctl.md");
write_as_typed(&out, "X", Durability::Fsync).unwrap();
std::fs::write(&ctl, "X").unwrap();
let mode_out = std::fs::metadata(&out).unwrap().permissions().mode() & 0o777;
let mode_ctl = std::fs::metadata(&ctl).unwrap().permissions().mode() & 0o777;
assert_eq!(
mode_out, mode_ctl,
"new-file mode must match std::fs::write; got 0{mode_out:o} vs control 0{mode_ctl:o}"
);
}
#[cfg(unix)]
#[test]
fn atomic_write_file_existing_mode_preserved() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
for kept in [0o600, 0o640] {
let target = dir.path().join(format!("src-{kept:o}.mds"));
std::fs::write(&target, "OLD").unwrap();
std::fs::set_permissions(&target, std::fs::Permissions::from_mode(kept)).unwrap();
write_as_typed(&target, "NEW", Durability::Fsync).unwrap();
let mode = std::fs::metadata(&target).unwrap().permissions().mode() & 0o7777;
assert_eq!(mode, kept, "existing mode must be preserved; got 0{mode:o}");
assert_eq!(std::fs::read_to_string(&target).unwrap(), "NEW");
}
}
#[cfg(unix)]
#[test]
fn a_replaced_file_lends_only_its_permission_bits() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
for special in [0o4755, 0o2755, 0o1755] {
let target = dir.path().join(format!("tool-{special:o}.md"));
let mode = || std::fs::metadata(&target).unwrap().permissions().mode() & 0o7777;
std::fs::write(&target, "OLD").unwrap();
std::fs::set_permissions(&target, std::fs::Permissions::from_mode(special)).unwrap();
assert_eq!(mode(), special, "the file replaced holds the bit");
write_as_typed(&target, "NEW", Durability::RenameOnly).unwrap();
assert_eq!(std::fs::read_to_string(&target).unwrap(), "NEW");
assert_eq!(mode(), 0o755, "0{special:o} replaced: got 0{:o}", mode());
}
}
#[cfg(unix)]
#[test]
fn only_a_file_its_writer_owns_lends_its_mode() {
use rustix::fs::RawMode;
use super::unix::kept_mode;
const REGULAR: RawMode = 0o100_000;
let kept = |st_mode: RawMode, same_owner: bool| {
kept_mode(st_mode, same_owner).map(|mode| mode.bits())
};
assert_eq!(kept(REGULAR | 0o640, true), Some(0o640));
assert_eq!(kept(REGULAR | 0o7755, true), Some(0o755));
assert_eq!(kept(REGULAR | 0o666, false), None);
assert_eq!(kept(REGULAR | 0o4755, false), None);
assert_eq!(kept(REGULAR | 0o600, false), None);
}
#[cfg(unix)]
#[test]
fn a_file_another_user_owns_lends_its_replacement_no_mode() {
use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
let dir = tempfile::tempdir().unwrap();
if std::fs::metadata(dir.path()).unwrap().uid() != 0 {
crate::output::ewriteln!("not running as root; cannot give a file to another user");
return;
}
let target = dir.path().join("shared.md");
let fresh = dir.path().join("fresh.md");
std::fs::write(&target, "OLD").unwrap();
std::os::unix::fs::chown(&target, Some(65_534), None).unwrap();
std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o777)).unwrap();
let mode = |path: &Path| std::fs::metadata(path).unwrap().permissions().mode() & 0o7777;
assert_eq!(std::fs::metadata(&target).unwrap().uid(), 65_534);
assert_eq!(mode(&target), 0o777);
write_as_typed(&target, "NEW", Durability::RenameOnly).unwrap();
std::fs::write(&fresh, "NEW").unwrap();
assert_eq!(std::fs::read_to_string(&target).unwrap(), "NEW");
assert_eq!(mode(&target), mode(&fresh), "got 0{:o}", mode(&target));
assert_eq!(temp_residue(dir.path()), Vec::<String>::new());
}
#[test]
fn atomic_write_file_refuses_live_symlink_target() {
let dir = tempfile::tempdir().unwrap();
let real = dir.path().join("real.md");
let link = dir.path().join("link.md");
std::fs::write(&real, "REAL").unwrap();
if !make_symlink(&real, &link) {
return;
}
let err = write_as_typed(&link, "NEW", Durability::Fsync)
.expect_err("writing through a symlink must be refused");
assert!(
matches!(err, mds::MdsError::Io { .. }),
"a refused write is mds::io, exit 2 (#157); got {err:?}"
);
let err = err.to_string();
assert!(
err.ends_with(&format!(": {SYMLINK_REFUSAL}")),
"expected a symlink refusal; got {err}"
);
assert_eq!(
std::fs::read_to_string(&real).unwrap(),
"REAL",
"the symlink's target must not be written through"
);
assert!(
std::fs::symlink_metadata(&link)
.unwrap()
.file_type()
.is_symlink(),
"the symlink itself must survive the refusal"
);
write_as_typed(&real, "NEW", Durability::Fsync)
.expect("writing the real file must succeed");
assert_eq!(std::fs::read_to_string(&real).unwrap(), "NEW");
}
#[test]
fn atomic_write_file_refuses_dangling_symlink_target() {
let dir = tempfile::tempdir().unwrap();
let missing = dir.path().join("missing.md");
let link = dir.path().join("link.md");
if !make_symlink(&missing, &link) {
return;
}
let err = write_as_typed(&link, "NEW", Durability::Fsync)
.expect_err("writing through a dangling symlink must be refused")
.to_string();
assert!(
err.ends_with(&format!(": {SYMLINK_REFUSAL}")),
"expected a symlink refusal; got {err}"
);
assert!(
!missing.exists(),
"the dangling link's target must not be created"
);
assert!(
std::fs::symlink_metadata(&link)
.unwrap()
.file_type()
.is_symlink(),
"the symlink itself must survive the refusal"
);
}
#[cfg(unix)]
#[test]
fn atomic_write_file_failure_preserves_original_and_leaves_no_temp() {
use std::os::unix::fs::MetadataExt as _;
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let sub = dir.path().join("sub");
std::fs::create_dir(&sub).unwrap();
let target = sub.join("locked.mds");
std::fs::write(&target, "OLD").unwrap();
let before = std::fs::metadata(&target).unwrap();
let (ino, mtime) = (before.ino(), before.modified().unwrap());
std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o555)).unwrap();
let result = write_as_typed(&target, "NEW", Durability::Fsync);
std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o755)).unwrap();
let err = result
.expect_err("a read-only parent directory must fail the write")
.to_string();
assert!(
err.contains("locked.mds"),
"error must name the target; got {err}"
);
assert_eq!(std::fs::read_to_string(&target).unwrap(), "OLD");
let after = std::fs::metadata(&target).unwrap();
assert_eq!(
after.ino(),
ino,
"a failed write must not replace the inode"
);
assert_eq!(
after.modified().unwrap(),
mtime,
"a failed write must not touch the mtime"
);
let residue = temp_residue(&sub);
assert!(
residue.is_empty(),
"failed write left temp residue: {residue:?}"
);
write_as_typed(&target, "NEW", Durability::Fsync)
.expect("write must succeed once the dir is writable");
assert_eq!(std::fs::read_to_string(&target).unwrap(), "NEW");
assert_ne!(
std::fs::metadata(&target).unwrap().ino(),
ino,
"replace-by-rename must produce a new inode"
);
}
#[test]
fn atomic_write_file_directory_target_refused_without_residue() {
let dir = tempfile::tempdir().unwrap();
let target = dir.path().join("adir");
std::fs::create_dir(&target).unwrap();
let shown = Path::new("out").join("adir");
let err = atomic_write_file(
&WriteTarget::new(target.clone(), shown.clone()),
"X",
Durability::Fsync,
Parents::Existing,
)
.expect_err("a directory target must not be written")
.to_string();
let named = format!("cannot write {}: ", safe_path(&shown));
assert!(
err.starts_with(&named),
"error must name the target as shown; got {err}"
);
let tmp = dir.path().display().to_string();
assert!(!err.contains(&tmp), "no path of the write's own: {err}");
assert!(!err.contains(TEMP_PREFIX), "no temporary file: {err}");
assert!(target.is_dir(), "the directory must survive the refusal");
let residue = temp_residue(dir.path());
assert!(
residue.is_empty(),
"refused write left temp residue: {residue:?}"
);
}
#[cfg(unix)]
#[test]
fn atomic_write_file_unreadable_parent_is_hard_error() {
use std::os::unix::fs::PermissionsExt as _;
let dir = tempfile::tempdir().unwrap();
let p = dir.path().join("nosearch");
std::fs::create_dir(&p).unwrap();
let probe = p.join("probe");
std::fs::write(&probe, "").unwrap();
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o000)).unwrap();
if std::fs::metadata(&probe).is_ok() {
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
crate::output::ewriteln!("running as root; cannot exercise EACCES");
return;
}
let target = WriteTarget::new(p.join("x.md"), PathBuf::from("x.md"));
let result = atomic_write_file(&target, "X", Durability::Fsync, Parents::Existing);
std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
let err = result
.expect_err("an unopenable directory must be a hard error")
.to_string();
assert_eq!(
err,
format!("cannot write x.md: {}", os_text(rustix::io::Errno::ACCESS))
);
assert!(!p.join("x.md").exists());
}
}