use std::io::Read;
use std::panic::Location;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
#[allow(dead_code)]
pub fn fixture(name: &str) -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fixtures")
.join(name)
}
#[allow(dead_code)]
pub fn mds_bin() -> std::process::Command {
let mut cmd = std::process::Command::new(env!("CARGO_BIN_EXE_mds"));
cmd.env("NO_COLOR", "1");
cmd
}
#[allow(dead_code)]
pub fn closed_pipe() -> std::io::PipeWriter {
let (reader, writer) = std::io::pipe().expect("create a pipe");
drop(reader);
writer
}
#[allow(dead_code)]
pub fn make_symlink(target: &Path, link: &Path) -> bool {
#[cfg(unix)]
let result = std::os::unix::fs::symlink(target, link);
#[cfg(windows)]
let result = {
let resolved = link
.parent()
.map_or_else(|| target.to_path_buf(), |dir| dir.join(target));
if resolved.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()
{
eprintln!(
"skipping: symlink creation needs Developer Mode or an elevated process on Windows"
);
return false;
}
}
panic!(
"failed to create symlink {} -> {}: {err}",
target.display(),
link.display()
);
}
}
}
#[allow(dead_code)]
pub fn remove_symlink(link: &Path) {
#[cfg(windows)]
{
use std::os::windows::fs::FileTypeExt as _;
let linked = std::fs::symlink_metadata(link)
.unwrap_or_else(|e| panic!("look at the link {}: {e}", link.display()));
if linked.file_type().is_symlink_dir() {
std::fs::remove_dir(link)
.unwrap_or_else(|e| panic!("remove the link {}: {e}", link.display()));
return;
}
}
std::fs::remove_file(link)
.unwrap_or_else(|e| panic!("remove the link {}: {e}", link.display()));
}
#[allow(dead_code)]
pub const MAX_FRONTMATTER_SIZE: usize = 1 << 20;
#[allow(dead_code)]
pub fn wrap(yaml: &str) -> String {
format!("---\n{yaml}---\nHi\n")
}
#[allow(dead_code)]
pub fn fm_of_size(bytes: usize) -> String {
const PREFIX: &str = "k: ZZSENTINELZZ";
assert!(bytes > PREFIX.len() + 1, "requested size too small");
let pad = bytes - PREFIX.len() - 1;
let out = format!("{PREFIX}{}\n", "x".repeat(pad));
assert_eq!(
out.len(),
bytes,
"fm_of_size must produce EXACTLY `bytes` bytes"
);
out
}
#[allow(dead_code)]
pub fn alias_bomb(n: usize, m: usize) -> String {
let xs = vec!["x"; n].join(", ");
let refs = vec!["*a"; m].join(", ");
format!("a: &a [{xs}]\nb: [{refs}]\n")
}
#[allow(dead_code)]
pub fn nested_flow_seq(d: usize) -> String {
format!("k: {}x{}\n", "[".repeat(d), "]".repeat(d))
}
#[allow(dead_code)]
pub const DUP_VARS_FILE_WARNING_FMT: &str =
"warning: key '{key}' is set more than once in vars file {path}; the last value wins";
#[allow(dead_code)]
pub const DUP_VARS_FILE_OMITTED_FMT: &str =
"warning: {n} more duplicate keys in vars file {path} are not listed";
#[allow(dead_code)]
pub fn dup_vars_file_warning(key: &str, path: &Path) -> String {
DUP_VARS_FILE_WARNING_FMT
.replace("{key}", key)
.replace("{path}", &path.display().to_string())
}
#[allow(dead_code)]
pub fn dup_vars_file_omitted(n: usize, path: &Path) -> String {
DUP_VARS_FILE_OMITTED_FMT
.replace("{n}", &n.to_string())
.replace("{path}", &path.display().to_string())
}
#[allow(dead_code)]
pub fn count_occurrences(haystack: &str, needle: &str) -> usize {
let mut count = 0;
let mut start = 0;
while let Some(pos) = haystack[start..].find(needle) {
count += 1;
start += pos + needle.len();
}
count
}
static WRITE_ATOMIC_SEQ: AtomicU64 = AtomicU64::new(0);
#[allow(dead_code)]
pub fn write_atomic(path: &Path, contents: impl AsRef<[u8]>) {
let dir = path
.parent()
.unwrap_or_else(|| panic!("write_atomic: path has no parent: {}", path.display()));
let name = path
.file_name()
.unwrap_or_else(|| panic!("write_atomic: path has no file name: {}", path.display()));
let seq = WRITE_ATOMIC_SEQ.fetch_add(1, Ordering::Relaxed);
let tmp = dir.join(format!(
".{}.tmp-{}-{}",
name.to_string_lossy(),
std::process::id(),
seq
));
debug_assert_ne!(
tmp.extension().and_then(|e| e.to_str()),
Some("mds"),
"write_atomic temp name must never end in .mds; it would be collected as a source"
);
if let Err(e) = std::fs::write(&tmp, contents.as_ref()) {
panic!(
"write_atomic: cannot write temp file {}: {e}",
tmp.display()
);
}
if let Err(e) = std::fs::rename(&tmp, path) {
let _ = std::fs::remove_file(&tmp);
panic!(
"write_atomic: cannot rename {} -> {}: {e}",
tmp.display(),
path.display()
);
}
}
const READY_MARKER: &str = "MDS_WATCH_READY";
const READY_POLL: Duration = Duration::from_millis(2);
const READY_TIMEOUT: Duration = Duration::from_secs(10);
#[allow(dead_code)]
pub struct ChildGuard(pub Child);
impl Drop for ChildGuard {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
#[allow(dead_code)]
impl ChildGuard {
pub fn id(&self) -> u32 {
self.0.id()
}
#[track_caller]
pub fn wait_status(&mut self) -> std::process::ExitStatus {
self.0.wait().expect("wait failed")
}
pub fn kill_and_wait(&mut self) -> std::process::ExitStatus {
let _ = self.0.kill();
self.0.wait().expect("wait failed")
}
}
const WALK_POLL: Duration = Duration::from_millis(5);
const WALK_MAX_POLLS: u32 = READY_TIMEOUT.as_millis().div_ceil(WALK_POLL.as_millis()) as u32;
#[test]
fn after_walk_wait_covers_the_readiness_timeout() {
assert!(WALK_POLL * WALK_MAX_POLLS >= READY_TIMEOUT);
}
#[allow(dead_code)]
pub fn run_after_walk(cmd: &mut Command, change: impl FnOnce()) -> std::process::Output {
let gate = tempfile::tempdir().unwrap();
let go = gate.path().join("go");
let paused = gate.path().join("go.paused");
let mut child = ChildGuard(
cmd.env("MDS_TEST_PAUSE_AFTER_WALK", &go)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap(),
);
let stdout = tap_reader(child.0.stdout.take().unwrap());
let stderr = tap_reader(child.0.stderr.take().unwrap());
for _ in 0..WALK_MAX_POLLS {
if paused.exists() {
break;
}
assert!(child.0.try_wait().unwrap().is_none(), "{}", stderr.text());
std::thread::sleep(WALK_POLL);
}
assert!(paused.exists(), "the walk must pause: {}", stderr.text());
change();
std::fs::write(go, "").unwrap();
for _ in 0..WALK_MAX_POLLS {
if let Some(status) = child.0.try_wait().unwrap() {
return std::process::Output {
status,
stdout: stdout.finish(&mut child),
stderr: stderr.finish(&mut child),
};
}
std::thread::sleep(WALK_POLL);
}
panic!("the directory command did not exit: {}", stderr.text());
}
#[allow(dead_code)]
#[derive(Clone)]
pub struct PipeTap {
buf: Arc<Mutex<Vec<u8>>>,
drain: Arc<Mutex<Option<std::thread::JoinHandle<()>>>>,
}
#[allow(dead_code)]
pub type StderrTap = PipeTap;
#[allow(dead_code)]
pub type StdoutTap = PipeTap;
#[allow(dead_code)]
impl PipeTap {
pub fn bytes(&self) -> Vec<u8> {
self.buf.lock().expect("pipe tap poisoned").clone()
}
pub fn text(&self) -> String {
String::from_utf8_lossy(&self.bytes()).into_owned()
}
#[must_use]
pub fn finish(self, child: &mut ChildGuard) -> Vec<u8> {
child.kill_and_wait();
{
let mut slot = self.drain.lock().expect("pipe tap drain slot poisoned");
if let Some(handle) = slot.take() {
handle.join().expect("pipe drain thread panicked");
}
}
self.bytes()
}
#[must_use]
pub fn finish_text(self, child: &mut ChildGuard) -> String {
String::from_utf8_lossy(&self.finish(child)).into_owned()
}
}
#[allow(dead_code)]
pub fn tap_reader<R: Read + Send + 'static>(reader: R) -> PipeTap {
let buf = Arc::new(Mutex::new(Vec::<u8>::new()));
let sink = buf.clone();
let handle = std::thread::spawn(move || {
let mut reader = reader;
let mut chunk = [0u8; 512];
loop {
match reader.read(&mut chunk) {
Ok(0) | Err(_) => break,
Ok(n) => sink
.lock()
.expect("pipe tap poisoned")
.extend_from_slice(&chunk[..n]),
}
}
});
PipeTap {
buf,
drain: Arc::new(Mutex::new(Some(handle))),
}
}
const TAP_POLL: Duration = Duration::from_millis(20);
#[allow(dead_code)]
pub fn poll_tap_until(
tap: &PipeTap,
timeout: Duration,
done: impl Fn(&str) -> bool,
) -> Result<String, String> {
let deadline = Instant::now() + timeout;
loop {
let text = tap.text();
if done(&text) {
return Ok(text);
}
if Instant::now() >= deadline {
return Err(text);
}
std::thread::sleep(TAP_POLL);
}
}
#[track_caller]
#[allow(dead_code)]
pub fn wait_for_tap(tap: &PipeTap, needle: &str, timeout: Duration) -> String {
match poll_tap_until(tap, timeout, |text| text.contains(needle)) {
Ok(text) => text,
Err(seen) => panic!(
"wait_for_tap at {}: {needle:?} did not appear within {timeout:?}; \
the tap held:\n{seen}",
Location::caller()
),
}
}
#[track_caller]
#[allow(dead_code)]
pub fn wait_for_tap_count(tap: &PipeTap, needle: &str, n: usize, timeout: Duration) -> String {
match poll_tap_until(tap, timeout, |text| count_occurrences(text, needle) >= n) {
Ok(text) => text,
Err(seen) => panic!(
"wait_for_tap_count at {}: expected at least {n} occurrences of {needle:?} \
within {timeout:?}; saw {}; the tap held:\n{seen}",
Location::caller(),
count_occurrences(&seen, needle)
),
}
}
#[allow(dead_code)]
pub const ORDER_MARKER_SOURCE: &str = "Order marker {{__order_marker__}}\n";
#[allow(dead_code)]
pub const ORDER_MARKER_LINE: &str = "undefined variable '__order_marker__'";
#[allow(dead_code)]
#[derive(Debug, Default)]
pub struct WriteCadence {
writes: Vec<(Instant, Instant)>,
}
#[allow(dead_code)]
impl WriteCadence {
pub fn with_capacity(writes: usize) -> Self {
Self {
writes: Vec::with_capacity(writes),
}
}
pub fn of(writes: Vec<(Instant, Instant)>) -> Self {
for (i, &(began, completed)) in writes.iter().enumerate() {
assert!(began <= completed, "write {i} completes before it begins");
if let Some(&(_, previous)) = i.checked_sub(1).and_then(|p| writes.get(p)) {
assert!(
previous <= began,
"write {i} begins before the write before it completed"
);
}
}
Self { writes }
}
pub fn time<T>(&mut self, write: impl FnOnce() -> T) -> T {
let began = Instant::now();
let done = write();
self.writes.push((began, Instant::now()));
done
}
pub fn writes(&self) -> usize {
self.writes.len()
}
pub fn first(&self, n: usize) -> Self {
Self {
writes: self.writes.iter().take(n).copied().collect(),
}
}
pub fn span(&self) -> Duration {
match (self.writes.first(), self.writes.last()) {
(Some(&(began, _)), Some(&(_, completed))) => completed.duration_since(began),
_ => Duration::ZERO,
}
}
pub fn gaps(&self) -> Vec<Duration> {
self.writes
.windows(2)
.map(|pair| pair[1].1.duration_since(pair[0].0))
.collect()
}
pub fn pauses(&self, at_least: Duration) -> usize {
self.gaps()
.into_iter()
.filter(|&gap| gap >= at_least)
.count()
}
}
impl std::fmt::Display for WriteCadence {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut gaps = self.gaps();
gaps.sort_unstable();
let rank = |per_mille: usize| -> Duration {
gaps.get(gaps.len().saturating_sub(1) * per_mille / 1000)
.copied()
.unwrap_or_default()
};
write!(
f,
"{} writes over {:?}; gaps: max {:?}, median {:?}, p99 {:?}",
self.writes.len(),
self.span(),
rank(1000),
rank(500),
rank(990)
)
}
}
#[allow(dead_code)]
pub fn most_debounce_windows(cadence: &WriteCadence, window: Duration, cap: Duration) -> usize {
assert!(
!window.is_zero() && cap >= window,
"a debounce cap is at least its nonzero window"
);
let reach = cadence.span() + window + window / 2;
let cap_closes = usize::try_from(reach.as_nanos() / cap.as_nanos()).unwrap_or(usize::MAX);
cap_closes
.saturating_add(cadence.pauses(window / 2))
.saturating_add(1)
}
#[allow(dead_code)]
pub const RUN_FLAG_LOG_ENV: &str = "MDS_TEST_FLAG_LOG";
#[allow(dead_code)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunFlag {
Conclusive,
Inconclusive,
}
impl std::fmt::Display for RunFlag {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
RunFlag::Conclusive => "conclusive",
RunFlag::Inconclusive => "inconclusive",
})
}
}
#[allow(dead_code)]
pub fn run_flag_line(test: &str, flag: RunFlag, details: &str) -> String {
assert!(
!test.contains(['\n', '\r']) && !details.contains(['\n', '\r']),
"a run flag is one line"
);
format!("{test}: {flag}: {details}")
}
#[allow(dead_code)]
pub fn append_line(path: &Path, line: &str) -> std::io::Result<()> {
use std::io::Write as _;
let mut file = std::fs::OpenOptions::new()
.append(true)
.create(true)
.open(path)?;
file.write_all(format!("{line}\n").as_bytes())
}
#[allow(dead_code)]
pub fn record_run_flag(test: &str, flag: RunFlag, details: &str) {
let line = run_flag_line(test, flag, details);
eprintln!("{line}");
if let Some(path) = std::env::var_os(RUN_FLAG_LOG_ENV) {
let path = PathBuf::from(path);
if let Err(e) = append_line(&path, &line) {
panic!(
"{RUN_FLAG_LOG_ENV}={}: cannot record the run's flag: {e}",
path.display()
);
}
} else if flag == RunFlag::Inconclusive {
if let Some(summary) = std::env::var_os("GITHUB_STEP_SUMMARY") {
let _ = append_line(Path::new(&summary), &format!(":information_source: {line}"));
}
}
}
#[allow(dead_code)]
pub fn spawn_watch_unsynchronized(cmd: &mut Command) -> (Child, StderrTap, Option<StdoutTap>) {
let mut child = cmd
.stderr(Stdio::piped())
.spawn()
.expect("failed to spawn mds watch");
let tap = tap_reader(child.stderr.take().expect("stderr must be piped"));
let stdout_tap = child.stdout.take().map(tap_reader);
(child, tap, stdout_tap)
}
#[allow(dead_code)]
pub fn spawn_watch_ready(cmd: &mut Command) -> (Child, StderrTap, Option<StdoutTap>) {
let ready = ReadyFile::new();
let (mut child, tap, stdout_tap) =
spawn_watch_unsynchronized(cmd.env("MDS_TEST_READY", ready.path()));
ready.wait(&mut child, || tap.text());
(child, tap, stdout_tap)
}
#[allow(dead_code)]
pub fn spawn_watch_ready_stderr_untapped(cmd: &mut Command) -> (Child, Option<StdoutTap>) {
let ready = ReadyFile::new();
let mut child = cmd
.env("MDS_TEST_READY", ready.path())
.spawn()
.expect("failed to spawn mds watch");
let stdout_tap = child.stdout.take().map(tap_reader);
ready.wait(&mut child, || "(stderr is not tapped)".to_string());
(child, stdout_tap)
}
#[allow(dead_code)]
pub fn spawn_watch_ready_at(
cmd: &mut Command,
marker: &Path,
) -> (Child, StderrTap, Option<StdoutTap>) {
assert!(
marker.is_absolute(),
"MDS_TEST_READY must be absolute; mds watch ignores relative values"
);
let (mut child, tap, stdout_tap) =
spawn_watch_unsynchronized(cmd.env("MDS_TEST_READY", marker));
wait_for_ready(marker, &mut child, || tap.text());
(child, tap, stdout_tap)
}
struct ReadyFile {
_dir: tempfile::TempDir,
path: PathBuf,
}
impl ReadyFile {
fn new() -> Self {
let dir = tempfile::tempdir().expect("failed to create readiness tempdir");
let path = dir.path().join("watch-ready");
assert!(
path.is_absolute(),
"MDS_TEST_READY must be absolute; mds watch ignores relative values"
);
Self { _dir: dir, path }
}
fn path(&self) -> &Path {
&self.path
}
fn wait(&self, child: &mut Child, stderr: impl Fn() -> String) {
wait_for_ready(&self.path, child, stderr);
}
}
fn wait_for_ready(marker: &Path, child: &mut Child, stderr: impl Fn() -> String) {
let deadline = std::time::Instant::now() + READY_TIMEOUT;
loop {
if std::fs::read(marker).is_ok_and(|b| b == READY_MARKER.as_bytes()) {
return;
}
if let Ok(Some(status)) = child.try_wait() {
let seen = stderr();
panic!(
"mds watch exited with {status:?} before signalling readiness; \
stderr was:\n{seen}"
);
}
if std::time::Instant::now() >= deadline {
let seen = stderr();
let _ = child.kill();
let _ = child.wait();
panic!(
"mds watch did not signal readiness within {READY_TIMEOUT:?}; \
stderr so far was:\n{seen}"
);
}
std::thread::sleep(READY_POLL);
}
}
#[cfg(unix)]
#[allow(dead_code)]
pub fn limit_file_growth(cmd: &mut Command, limit: libc::rlim_t) {
use std::os::unix::process::CommandExt as _;
unsafe {
cmd.pre_exec(move || {
if libc::signal(libc::SIGXFSZ, libc::SIG_IGN) == libc::SIG_ERR {
return Err(std::io::Error::last_os_error());
}
let growth = libc::rlimit {
rlim_cur: limit,
rlim_max: limit,
};
if libc::setrlimit(libc::RLIMIT_FSIZE, &growth) != 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
}
#[cfg(unix)]
#[allow(dead_code)]
pub fn full_file(path: &Path, len: usize) -> std::fs::File {
use std::io::{Seek as _, SeekFrom};
std::fs::write(path, vec![b'#'; len]).expect("fill the stream file");
let mut file = std::fs::OpenOptions::new()
.write(true)
.open(path)
.expect("open the stream file");
file.seek(SeekFrom::End(0))
.expect("move to the end of the stream file");
file
}
#[cfg(unix)]
#[allow(dead_code)]
pub fn default_sigint(cmd: &mut Command) {
use std::os::unix::process::CommandExt as _;
unsafe {
cmd.pre_exec(|| {
if libc::signal(libc::SIGINT, libc::SIG_DFL) == libc::SIG_ERR {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
}
#[allow(dead_code)]
pub fn assert_no_control_chars(s: &str, label: &str) {
for (byte_offset, ch) in s.char_indices() {
let code = ch as u32;
let is_c0 = code < 0x20 && code != 0x09 && code != 0x0a;
let is_del = code == 0x7f;
let is_c1 = (0x80..=0x9f).contains(&code);
let is_format_hazard = matches!(ch,
'\u{061C}'
| '\u{200E}' | '\u{200F}'
| '\u{2028}' | '\u{2029}'
| '\u{202A}'..='\u{202E}'
| '\u{2066}'..='\u{2069}'
| '\u{FEFF}'
);
assert!(
!is_c0 && !is_del && !is_c1 && !is_format_hazard,
"{label}: raw hostile char U+{code:04X} at byte offset {byte_offset}; \
full string: {s:?}"
);
}
}