use std::cell::OnceCell;
use std::collections::{BTreeSet, HashMap, HashSet};
use std::ops::ControlFlow;
use std::panic::AssertUnwindSafe;
use std::path::{Path, PathBuf};
use std::sync::mpsc;
use std::time::{Duration, Instant};
use miette::Result;
use notify::{Event, RecommendedWatcher, RecursiveMode, Watcher};
use mds::MdsError;
use crate::build::{
admit_output, auto_detect_mds_file, build_runtime_vars, compile_inputs,
compile_native_to_content, resolve_dir_as_created, resolve_output_path_for_kind, source_inputs,
write_output, CompileOutput, EntryPaths, OutputKind, ProjectConfig, RuntimeVarArgs,
RuntimeVars,
};
use crate::output::{
collect_mds_files, eprint_error, eprint_warning, is_partial, is_within_default_excluded_dir,
notify_cause, output_path_for, resolve_output_base, safe_inline, safe_path, stdout_failure,
write_stdout, OutputBase, Panicked, RootPaths, StdoutOutcome, WriteTarget,
};
use crate::write::{
remove_proven, write_over_own, DirIdentity, Durability, Inputs, NotCreated, NotRemoved,
Parents, Removal,
};
pub(crate) struct WatchArgs {
pub(crate) input: Option<PathBuf>,
pub(crate) output: Option<std::ffi::OsString>,
pub(crate) out_dir: Option<PathBuf>,
pub(crate) vars: Option<PathBuf>,
pub(crate) set_vars: Vec<(String, String)>,
pub(crate) set_string_vars: Vec<(String, String)>,
pub(crate) clear: bool,
pub(crate) debounce: u64,
pub(crate) quiet: bool,
pub(crate) poll_interval: u64,
}
enum Msg {
Fs(notify::Result<Event>),
Interrupt,
}
pub(crate) fn dirs_to_watch(
entry: &Path,
deps: &[PathBuf],
vars_file: Option<&Path>,
) -> BTreeSet<PathBuf> {
let mut dirs = BTreeSet::new();
let push_parent = |path: &Path, set: &mut BTreeSet<PathBuf>| {
set.insert(mds::effective_parent(path).to_path_buf());
};
push_parent(entry, &mut dirs);
for dep in deps {
push_parent(dep, &mut dirs);
}
if let Some(vf) = vars_file {
push_parent(vf, &mut dirs);
}
dirs
}
pub(crate) fn files_of_interest(
entry: &Path,
deps: &[PathBuf],
vars_file: Option<&Path>,
) -> HashSet<PathBuf> {
let mut set = HashSet::new();
set.insert(entry.to_path_buf());
for dep in deps {
set.insert(dep.clone());
}
if let Some(vf) = vars_file {
set.insert(vf.to_path_buf());
}
set
}
pub(crate) fn is_content_event(kind: ¬ify::EventKind) -> bool {
!matches!(kind, notify::EventKind::Access(_))
}
pub(crate) fn event_is_relevant(event: &Event, watched: &HashSet<PathBuf>) -> bool {
for path in &event.paths {
if watched.contains(path) {
return true;
}
if let Ok(canonical) = path.canonicalize() {
if watched.contains(&canonical) {
return true;
}
let dir = canonical.parent();
if watched
.iter()
.filter(|w| w.parent() == dir)
.any(|w| w.canonicalize().is_ok_and(|now| now == canonical))
{
return true;
}
}
let name = path.file_name();
let parent = path.parent();
if let (Some(n), Some(p)) = (name, parent) {
if watched
.iter()
.any(|w| w.file_name() == Some(n) && w.parent() == Some(p))
{
return true;
}
if let Ok(cp) = p.canonicalize() {
if watched
.iter()
.any(|w| w.file_name() == Some(n) && w.parent() == Some(cp.as_path()))
{
return true;
}
}
}
}
false
}
pub(crate) fn graph_key(p: &Path) -> PathBuf {
if let Ok(c) = p.canonicalize() {
return c;
}
let parent = mds::effective_parent(p);
if let Ok(cp) = parent.canonicalize() {
if let Some(name) = p.file_name() {
return cp.join(name);
}
}
p.to_path_buf()
}
pub(crate) fn graph_keys<P: AsRef<Path>>(paths: &[P]) -> Vec<PathBuf> {
paths.iter().map(|p| graph_key(p.as_ref())).collect()
}
pub(crate) fn affected_sources(
forward_deps: &HashMap<PathBuf, Vec<PathBuf>>,
seeds: &BTreeSet<PathBuf>,
) -> Vec<PathBuf> {
let mut importers: HashMap<&PathBuf, Vec<&PathBuf>> = HashMap::new();
for (src, deps) in forward_deps {
for dep in deps {
importers.entry(dep).or_default().push(src);
}
}
let mut visited: HashSet<&PathBuf> = HashSet::new();
let mut result: Vec<PathBuf> = Vec::new();
let mut stack: Vec<&PathBuf> = Vec::new();
for seed in seeds {
if visited.insert(seed) {
result.push(seed.clone());
stack.push(seed);
}
}
while let Some(node) = stack.pop() {
if let Some(imps) = importers.get(node) {
for imp in imps {
if visited.insert(imp) {
result.push((*imp).clone());
stack.push(imp);
}
}
}
}
result
}
pub(crate) type FileStamp = (Option<std::time::SystemTime>, Option<u64>);
pub(crate) type StampMap = HashMap<PathBuf, FileStamp>;
pub(crate) fn snapshot_state(paths: &HashSet<PathBuf>) -> StampMap {
let mut map = HashMap::new();
for p in paths {
match std::fs::metadata(p) {
Ok(m) => {
let mtime = m.modified().ok();
let size = Some(m.len());
map.insert(p.clone(), (mtime, size));
}
Err(_) => {
map.insert(p.clone(), (None, None));
}
}
}
map
}
pub(crate) fn baseline_path(path: &Path, snapshot: &mut StampMap) {
snapshot
.entry(path.to_path_buf())
.or_insert_with(|| match std::fs::metadata(path) {
Ok(m) => (m.modified().ok(), Some(m.len())),
Err(_) => (None, None),
});
}
pub(crate) fn path_state_differs(path: &Path, prev: &StampMap) -> bool {
let current = match std::fs::metadata(path) {
Ok(m) => (m.modified().ok(), Some(m.len())),
Err(_) => (None, None),
};
!matches!(prev.get(path), Some(old) if *old == current)
}
pub(crate) fn state_differs(paths: &HashSet<PathBuf>, prev: &StampMap) -> bool {
paths.iter().any(|p| path_state_differs(p, prev))
}
pub(crate) fn external_recovery_decision(
prev_missing: &BTreeSet<PathBuf>,
statuses: &[(PathBuf, bool, bool)],
) -> (bool, BTreeSet<PathBuf>) {
let mut now_missing = BTreeSet::new();
let mut recovery = false;
for (dir, exists, rearm_ok) in statuses {
if *exists {
if !*rearm_ok {
recovery = true;
} else if prev_missing.contains(dir) {
recovery = true;
}
} else {
now_missing.insert(dir.clone());
}
}
(recovery, now_missing)
}
pub(crate) fn canonicalize_vars_path(vars: Option<PathBuf>) -> Result<Option<PathBuf>, MdsError> {
if let Some(p) = &vars {
crate::output::reject_forbidden_output_path("path", p.as_os_str())?;
}
match vars {
Some(p) if p.exists() => mds::NativeFs::check_symlink(&p)
.map(Some)
.map_err(|e| crate::build::vars_file_error(&p, e)),
other => Ok(other),
}
}
fn end_rebuild_clear(hold: &EmptyHold) {
if hold.deadline().is_none() {
crate::output::cancel_clear();
}
}
pub(crate) fn resync_watches(
watcher: &mut RecommendedWatcher,
current_dirs: &BTreeSet<PathBuf>,
new_dirs: &BTreeSet<PathBuf>,
root: RootPaths<'_>,
vars: Option<RootPaths<'_>>,
) -> BTreeSet<PathBuf> {
let mut result = current_dirs.clone();
for dir in current_dirs.difference(new_dirs) {
let _ = watcher.unwatch(dir);
result.remove(dir);
}
for dir in new_dirs.difference(current_dirs) {
if let Err(e) = watcher.watch(dir, RecursiveMode::NonRecursive) {
eprint_warning(&format!(
"warning: failed to watch {}: {}",
safe_path(&shown_watched_dir(dir, root, vars)),
safe_inline(notify_cause(&e))
));
} else {
result.insert(dir.clone());
}
}
result
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum StopReason {
Interrupted,
StdoutClosed,
}
fn stop_watching(quiet: bool, why: StopReason) {
if quiet {
return;
}
match why {
StopReason::Interrupted => crate::output::ewriteln!("Stopped watching."),
StopReason::StdoutClosed => crate::output::ewriteln!("Stopped watching (stdout closed)."),
}
}
#[cfg(feature = "startup-race-probe")]
fn startup_race_probe() {
std::thread::sleep(Duration::from_millis(200));
}
#[cfg(not(feature = "startup-race-probe"))]
fn startup_race_probe() {}
#[cfg(debug_assertions)]
mod ready_trigger {
use std::path::{Path, PathBuf};
const READY_MARKER_ENV: &str = "MDS_TEST_READY";
const READY_MARKER: &str = "MDS_WATCH_READY";
pub(super) fn emit_ready_marker() {
let Some(raw) = std::env::var_os(READY_MARKER_ENV) else {
return;
};
let path = PathBuf::from(raw);
if !path.is_absolute() {
return;
}
let mut tmp = path.clone().into_os_string();
tmp.push(".tmp");
let tmp = PathBuf::from(tmp);
if create_ready_marker(&tmp).is_ok() {
let _ = std::fs::rename(&tmp, &path);
}
}
fn create_ready_marker(tmp: &Path) -> std::io::Result<()> {
use std::io::Write as _;
let create = || {
std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(tmp)
};
let mut file = match create() {
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
std::fs::remove_file(tmp)?;
create()?
}
created => created?,
};
file.write_all(READY_MARKER.as_bytes())
}
}
#[cfg(debug_assertions)]
use ready_trigger::emit_ready_marker;
#[cfg(not(debug_assertions))]
fn emit_ready_marker() {}
const EMPTY_HOLD_DEADLINE: Duration = Duration::from_secs(1);
fn went_empty(before: Option<&FileStamp>, now: &FileStamp) -> bool {
matches!((before.and_then(|stamp| stamp.1), now.1), (Some(had), Some(0)) if had > 0)
}
fn stamp_now(path: &Path) -> FileStamp {
match std::fs::metadata(path) {
Ok(m) => (m.modified().ok(), Some(m.len())),
Err(_) => (None, None),
}
}
#[cfg(test)]
fn any_went_empty<'a>(paths: impl IntoIterator<Item = &'a PathBuf>, baseline: &StampMap) -> bool {
paths
.into_iter()
.any(|path| went_empty(baseline.get(path), &stamp_now(path)))
}
fn emptied_paths<'a>(
paths: impl IntoIterator<Item = &'a PathBuf>,
baseline: &StampMap,
) -> BTreeSet<PathBuf> {
paths
.into_iter()
.filter(|path| went_empty(baseline.get(*path), &stamp_now(path)))
.cloned()
.collect()
}
fn look_at<'a>(paths: impl IntoIterator<Item = &'a PathBuf>) -> StampMap {
let mut look = StampMap::new();
for path in paths {
if !look.contains_key(path) {
look.insert(path.clone(), stamp_now(path));
}
}
look
}
fn emptied_in<'a>(look: &'a StampMap, baseline: &'a StampMap) -> impl Iterator<Item = &'a PathBuf> {
look.iter()
.filter(move |(path, now)| went_empty(baseline.get(*path), now))
.map(|(path, _)| path)
}
fn baseline_over<'a>(
mut taken: StampMap,
domain: impl IntoIterator<Item = &'a PathBuf>,
) -> StampMap {
let mut baseline = StampMap::with_capacity(taken.len());
for path in domain {
if baseline.contains_key(path) {
continue;
}
let (path, stamp) = taken
.remove_entry(path)
.unwrap_or_else(|| (path.clone(), stamp_now(path)));
baseline.insert(path, stamp);
}
baseline
}
fn not_before(now: Instant, due: Option<Instant>) -> Instant {
due.map_or(now, |due| now.max(due))
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
enum EmptyHold {
#[default]
Off,
Until(Instant),
Expired,
}
#[must_use]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HoldVerdict {
Compile,
Hold,
}
impl EmptyHold {
fn on_rebuild(&mut self, emptied: bool, now: Instant) -> HoldVerdict {
match (*self, emptied) {
(_, false) => {
*self = Self::Off;
HoldVerdict::Compile
}
(Self::Off | Self::Expired, true) => {
*self = Self::Until(now + EMPTY_HOLD_DEADLINE);
HoldVerdict::Hold
}
(Self::Until(until), true) if now < until => HoldVerdict::Hold,
(Self::Until(_), true) => {
*self = Self::Expired;
HoldVerdict::Compile
}
}
}
fn on_late_empty(&mut self, now: Instant) -> HoldVerdict {
match *self {
Self::Expired => HoldVerdict::Compile,
Self::Off | Self::Until(_) => self.on_rebuild(true, now),
}
}
fn deadline(&self) -> Option<Instant> {
match *self {
Self::Off | Self::Expired => None,
Self::Until(until) => Some(until),
}
}
}
#[must_use]
fn held_after_look<'a>(
hold: &mut EmptyHold,
read: impl IntoIterator<Item = &'a PathBuf>,
baseline: &StampMap,
) -> Option<BTreeSet<PathBuf>> {
let emptied = emptied_paths(read, baseline);
if emptied.is_empty() {
return None;
}
(hold.on_late_empty(Instant::now()) == HoldVerdict::Hold).then_some(emptied)
}
#[derive(Debug, Clone, Copy)]
enum TickSchedule {
Off,
Every { interval: Duration, next: Instant },
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TickPoll {
Never,
Due,
Wait(Duration),
}
impl TickSchedule {
fn start(interval: Option<Duration>, now: Instant) -> Self {
match interval {
None => Self::Off,
Some(interval) => Self::Every {
interval,
next: now + interval,
},
}
}
fn poll(&mut self, now: Instant) -> TickPoll {
let Self::Every { next, .. } = *self else {
return TickPoll::Never;
};
if now >= next {
self.rearm(now);
TickPoll::Due
} else {
TickPoll::Wait(next - now)
}
}
fn rearm(&mut self, now: Instant) {
if let Self::Every { interval, next } = self {
*next = now + *interval;
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WakePoll {
HoldDue,
TickDue,
Wait { wait: Duration, hold: bool },
Never,
}
fn poll_wake(schedule: &mut TickSchedule, hold: Option<Instant>, now: Instant) -> WakePoll {
if hold.is_some_and(|until| now >= until) {
return WakePoll::HoldDue;
}
let until_hold = hold.map(|until| until - now);
match (schedule.poll(now), until_hold) {
(TickPoll::Due, _) => WakePoll::TickDue,
(TickPoll::Never, None) => WakePoll::Never,
(TickPoll::Never, Some(wait)) => WakePoll::Wait { wait, hold: true },
(TickPoll::Wait(tick), Some(wait)) if wait <= tick => WakePoll::Wait { wait, hold: true },
(TickPoll::Wait(wait), _) => WakePoll::Wait { wait, hold: false },
}
}
enum Wake {
Message(Msg),
Tick,
HoldDue,
}
struct TickClock {
schedule: TickSchedule,
}
impl TickClock {
fn new(interval: Option<Duration>) -> Self {
Self {
schedule: TickSchedule::start(interval, Instant::now()),
}
}
fn recv_next(
&mut self,
rx: &mpsc::Receiver<Msg>,
hold: Option<Instant>,
) -> std::result::Result<Wake, mpsc::RecvError> {
match poll_wake(&mut self.schedule, hold, Instant::now()) {
WakePoll::HoldDue => Ok(Wake::HoldDue),
WakePoll::TickDue => Ok(Wake::Tick),
WakePoll::Never => rx.recv().map(Wake::Message),
WakePoll::Wait { wait, hold } => match rx.recv_timeout(wait) {
Ok(msg) => Ok(Wake::Message(msg)),
Err(mpsc::RecvTimeoutError::Timeout) if hold => Ok(Wake::HoldDue),
Err(mpsc::RecvTimeoutError::Timeout) => {
self.schedule.rearm(Instant::now());
Ok(Wake::Tick)
}
Err(mpsc::RecvTimeoutError::Disconnected) => Err(mpsc::RecvError),
},
}
}
}
const MAX_DEBOUNCE_MS: u64 = 60_000;
const DEBOUNCE_CAP_FACTOR: u32 = 10;
const DEBOUNCE_CAP_FLOOR: Duration = Duration::from_millis(1_000);
const MAX_DEBOUNCE_MESSAGES: usize = 10_000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DebounceEnd {
Disabled,
Closed(WindowEnd),
Interrupted,
Disconnected,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WindowEnd {
Quiet,
Cap,
MessageLimit,
}
struct DebounceOutcome {
paths: BTreeSet<PathBuf>,
rescan: bool,
end: DebounceEnd,
}
impl DebounceOutcome {
fn interrupted(&self) -> bool {
self.end == DebounceEnd::Interrupted
}
}
fn clamp_debounce(debounce_ms: u64) -> Option<Duration> {
if debounce_ms == 0 {
None
} else {
Some(Duration::from_millis(debounce_ms.min(MAX_DEBOUNCE_MS)))
}
}
fn debounce_cap(window: Duration) -> Duration {
(window * DEBOUNCE_CAP_FACTOR).max(DEBOUNCE_CAP_FLOOR)
}
struct DebounceWindow {
window: Duration,
cap_end: Instant,
deadline: Instant,
messages: usize,
paths: BTreeSet<PathBuf>,
rescan: bool,
}
impl DebounceWindow {
fn open(window: Duration, start: Instant) -> Self {
Self {
window,
cap_end: start + debounce_cap(window),
deadline: start + window,
messages: 0,
paths: BTreeSet::new(),
rescan: false,
}
}
fn on_event(&mut self, event: notify::Event, now: Instant) {
self.messages += 1;
if !is_content_event(&event.kind) {
return;
}
self.rescan |= event.need_rescan();
self.paths.extend(event.paths);
self.on_content(now);
}
fn on_watch_error(&mut self) {
self.messages += 1;
}
fn on_content(&mut self, now: Instant) {
self.deadline = (now + self.window).min(self.cap_end);
}
fn deadline(&self) -> Instant {
self.deadline
}
fn classify(&self, now: Instant) -> Option<WindowEnd> {
assert!(
self.deadline <= self.cap_end,
"debounce deadline escaped its cap: a file written to continuously would \
postpone its own rebuild (and the idle-tick backstop behind it) for as \
long as the writing lasts"
);
if self.messages >= MAX_DEBOUNCE_MESSAGES {
Some(WindowEnd::MessageLimit)
} else if now < self.deadline {
None
} else if self.deadline == self.cap_end {
Some(WindowEnd::Cap)
} else {
Some(WindowEnd::Quiet)
}
}
}
fn drain_debounce(rx: &mpsc::Receiver<Msg>, debounce_ms: u64) -> DebounceOutcome {
let Some(window) = clamp_debounce(debounce_ms) else {
return DebounceOutcome {
paths: BTreeSet::new(),
rescan: false,
end: DebounceEnd::Disabled,
};
};
let mut open = DebounceWindow::open(window, Instant::now());
let end = loop {
let now = Instant::now();
if let Some(closed) = open.classify(now) {
break DebounceEnd::Closed(closed);
}
match rx.recv_timeout(open.deadline() - now) {
Ok(Msg::Fs(Ok(event))) => open.on_event(event, Instant::now()),
Ok(Msg::Fs(Err(e))) => {
open.on_watch_error();
eprint_warning(&format!(
"warning: watch error during debounce: {}",
safe_inline(notify_cause(&e))
));
}
Ok(Msg::Interrupt) => break DebounceEnd::Interrupted,
Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Disconnected) => break DebounceEnd::Disconnected,
}
};
DebounceOutcome {
paths: open.paths,
rescan: open.rescan,
end,
}
}
fn clamp_poll_interval(poll_interval: u64) -> Option<Duration> {
if poll_interval == 0 {
None
} else {
Some(Duration::from_millis(poll_interval.max(50)))
}
}
struct WorkingDir {
canonical: Option<PathBuf>,
}
impl WorkingDir {
fn record() -> Self {
WorkingDir {
canonical: std::env::current_dir()
.and_then(|dir| dir.canonicalize())
.ok(),
}
}
fn restore_if_recreated(&self) {
let Some(recorded) = &self.canonical else {
return;
};
if std::env::current_dir().is_ok() {
return;
}
if recorded.canonicalize().is_ok_and(|now| now == *recorded) {
let _ = std::env::set_current_dir(recorded);
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OutDirNow {
Unchanged,
New,
Elsewhere,
}
struct OutDirAnchor {
typed: PathBuf,
resolved: PathBuf,
out_dir: PathBuf,
identity: Option<DirIdentity>,
checked: Option<CheckedAnchor>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct CheckedAnchor {
missing: usize,
identity: DirIdentity,
}
impl CheckedAnchor {
fn find(dir: &Path) -> Option<Self> {
dir.ancestors().enumerate().find_map(|(missing, at)| {
DirIdentity::of(at).map(|identity| Self { missing, identity })
})
}
}
impl OutDirAnchor {
fn record(out_dir: Option<&Path>, config: Option<&ProjectConfig>) -> Option<Self> {
let (typed, below) = match (out_dir, config) {
(Some(typed), _) => (typed.to_path_buf(), None),
(None, Some(project)) => (
project.shown_dir.clone(),
Some(project.config.build.output_dir.as_deref()?),
),
(None, None) => return None,
};
let resolved = resolve_dir_as_created(&typed)?;
let out_dir = below.map_or_else(|| resolved.clone(), |below| resolved.join(below));
let identity = DirIdentity::of(&out_dir);
Some(Self {
typed,
resolved,
out_dir,
identity,
checked: None,
})
}
fn check(&mut self) -> OutDirNow {
self.checked = CheckedAnchor::find(&self.resolved);
if self.checked.is_none()
|| resolve_dir_as_created(&self.typed).as_ref() != Some(&self.resolved)
{
self.checked = None;
return OutDirNow::Elsewhere;
}
let now = DirIdentity::of(&self.out_dir);
if now.is_some() && now == self.identity {
OutDirNow::Unchanged
} else {
self.identity = now;
OutDirNow::New
}
}
fn written(&mut self) {
if self.identity.is_none() {
self.identity = DirIdentity::of(&self.out_dir);
}
}
}
fn check_out_dir<K, V>(
anchor: Option<&mut OutDirAnchor>,
last_written: &mut HashMap<K, V>,
) -> OutDirNow {
let now = anchor.map_or(OutDirNow::Unchanged, OutDirAnchor::check);
if now == OutDirNow::New {
last_written.clear();
}
now
}
fn below_checked_out_dir(anchor: Option<&OutDirAnchor>, target: &WriteTarget) -> WriteTarget {
match anchor.and_then(|anchor| Some((anchor, anchor.checked?))) {
Some((anchor, CheckedAnchor { missing, identity })) => {
target.below_checked_anchor(&anchor.resolved, missing, identity)
}
None => target.clone(),
}
}
#[derive(Clone, Copy)]
enum Retirement {
SourceDeleted,
KindChanged,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct WrittenOutput {
source: PathBuf,
content: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Record<'a> {
Unwritten,
OtherSource,
Own(&'a str),
}
impl<'a> Record<'a> {
fn of_entry(written: Option<&'a String>) -> Self {
written.map_or(Self::Unwritten, |content| Self::Own(content))
}
}
#[must_use]
fn retire_output(
out: &WriteTarget,
anchor: Option<&OutDirAnchor>,
now: OutDirNow,
record: Record<'_>,
why: Retirement,
quiet: bool,
) -> bool {
if let Err(e) = std::fs::symlink_metadata(&out.path) {
if matches!(
e.kind(),
std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
) {
return true;
}
}
let written = match record {
Record::Own(written) => written,
Record::Unwritten => {
if !quiet {
crate::output::ewriteln!(
"Kept {}: not written by this session",
safe_path(&out.shown)
);
}
return false;
}
Record::OtherSource => {
if !quiet {
crate::output::ewriteln!(
"Kept {}: not written by this source",
safe_path(&out.shown)
);
}
return false;
}
};
let removal = match now {
OutDirNow::Elsewhere => Err(NotRemoved::out_dir_moved()),
OutDirNow::Unchanged | OutDirNow::New => {
remove_proven(&below_checked_out_dir(anchor, out), |file| {
holds_exactly(file, written)
})
}
};
match removal {
Ok(Removal::Removed) => {
if let (Retirement::SourceDeleted, false) = (why, quiet) {
crate::output::ewriteln!("Removed {} (source deleted)", safe_path(&out.shown));
}
true
}
Ok(Removal::Kept) => {
if !quiet {
crate::output::ewriteln!(
"Kept {}: changed since it was written",
safe_path(&out.shown)
);
}
false
}
Ok(Removal::Missing) => true,
Err(not_removed) => {
match why {
Retirement::SourceDeleted => eprint_warning(&format!(
"warning: could not remove {}: {}",
safe_path(&out.shown),
safe_inline(not_removed.cause())
)),
Retirement::KindChanged => eprint_warning(&format!(
"warning: could not remove stale output {}: {}",
safe_path(&out.shown),
safe_inline(not_removed.cause())
)),
}
false
}
}
}
fn write_after_change_of_kind(
out: &WriteTarget,
record: Record<'_>,
content: &str,
told: bool,
quiet: bool,
) -> std::result::Result<bool, MdsError> {
let own = match record {
Record::Own(written) => Some(written),
Record::Unwritten | Record::OtherSource => None,
};
match write_over_own(out, own, content, Durability::RenameOnly, Parents::Create) {
Ok(()) => Ok(true),
Err(NotCreated::Exists) => {
if !told && !quiet {
match record {
Record::Own(_) => crate::output::ewriteln!(
"Kept {}: changed since it was written; not overwritten",
safe_path(&out.shown)
),
Record::OtherSource => crate::output::ewriteln!(
"Kept {}: not written by this source; not overwritten",
safe_path(&out.shown)
),
Record::Unwritten => crate::output::ewriteln!(
"Kept {}: not written by this session; not overwritten",
safe_path(&out.shown)
),
}
}
Ok(false)
}
Err(NotCreated::Failed(e)) => Err(e),
}
}
fn holds_exactly(file: &mut std::fs::File, written: &str) -> std::io::Result<bool> {
let len = written.len() as u64;
Ok(mds::read_at_most(file, len.saturating_add(1), len)? == written.as_bytes())
}
#[derive(Clone, Copy)]
enum Watched {
Entry,
Root,
Source,
}
impl Watched {
fn moved(self, typed: &Path) -> MdsError {
let (watched, different) = match self {
Watched::Entry => ("entry", "file"),
Watched::Root => ("directory", "directory"),
Watched::Source => ("file", "file"),
};
MdsError::Io {
message: format!(
"watched {watched} now resolves to a different {different}: \"{}\"; \
restart mds watch to follow it",
mds::escape_path_for_message(&typed.to_string_lossy())
),
}
}
}
struct WatchedPath {
typed: PathBuf,
canonical: PathBuf,
what: Watched,
}
impl WatchedPath {
fn paths(&self) -> EntryPaths<'_> {
EntryPaths {
typed: &self.typed,
canonical: &self.canonical,
}
}
fn ensure_unmoved(&self) -> Result<(), MdsError> {
let moved = match self.what {
Watched::Root => {
let now = self.typed.canonicalize().map_err(|e| {
let shown =
mds::escape_path_for_message(&self.typed.to_string_lossy()).into_owned();
if e.kind() == std::io::ErrorKind::NotFound {
MdsError::FileNotFound {
path: shown,
span: None,
src: None,
}
} else {
MdsError::Io {
message: format!(
"cannot resolve path {shown}: {}",
safe_inline(crate::output::io_cause(&e))
),
}
}
})?;
now != self.canonical
}
Watched::Entry | Watched::Source => {
mds::NativeFs::check_symlink(&self.typed)?.parent() != self.canonical.parent()
}
};
if moved {
Err(self.what.moved(&self.typed))
} else {
Ok(())
}
}
fn compile(
&self,
runtime_vars: Option<HashMap<String, mds::Value>>,
quiet: bool,
) -> std::result::Result<CompileOutput, CompileFailure> {
self.ensure_unmoved().map_err(miette::Error::from)?;
compile_caught(&self.typed, &self.canonical, runtime_vars, quiet)
}
fn root_paths(&self) -> RootPaths<'_> {
RootPaths {
typed: &self.typed,
walked: &self.canonical,
}
}
fn dir_paths(&self) -> RootPaths<'_> {
RootPaths {
typed: mds::effective_parent(&self.typed),
walked: mds::effective_parent(&self.canonical),
}
}
fn walked(&self, src: &Path) -> PathBuf {
self.root_paths().shown_below(src)
}
fn compile_source(
&self,
src: &Path,
runtime_vars: Option<HashMap<String, mds::Value>>,
quiet: bool,
) -> std::result::Result<CompileOutput, CompileFailure> {
if !src.starts_with(&self.canonical) {
return compile_caught(src, src, runtime_vars, quiet);
}
self.ensure_unmoved().map_err(miette::Error::from)?;
WatchedPath {
typed: self.walked(src),
canonical: src.to_path_buf(),
what: Watched::Source,
}
.compile(runtime_vars, quiet)
}
}
#[derive(Debug)]
enum CompileFailure {
Error(miette::Report),
Panicked,
}
impl CompileFailure {
fn into_report(self) -> Option<miette::Report> {
match self {
Self::Error(e) => Some(e),
Self::Panicked => None,
}
}
}
impl From<miette::Report> for CompileFailure {
fn from(e: miette::Report) -> Self {
Self::Error(e)
}
}
fn compile_caught(
path: &Path,
canonical: &Path,
runtime_vars: Option<HashMap<String, mds::Value>>,
quiet: bool,
) -> std::result::Result<CompileOutput, CompileFailure> {
let fs = mds::NativeFs::new()
.with_entry_pin(mds::EntryPin::parent_dir(mds::effective_parent(canonical)));
pause_before_compile();
let compiled = crate::output::catch_compile(
path,
AssertUnwindSafe(|| {
compile_native_to_content(
fs,
path,
runtime_vars,
quiet,
mds::CompileOptions::default(),
)
}),
);
compiled
.map_err(|Panicked| CompileFailure::Panicked)?
.map_err(CompileFailure::from)
}
pub(crate) fn run_watch(args: WatchArgs) -> Result<()> {
let WatchArgs {
input,
output,
out_dir,
vars,
set_vars,
set_string_vars,
clear,
debounce,
quiet,
poll_interval,
} = args;
let output =
crate::build::reject_forbidden_output_flags(output.as_deref(), out_dir.as_deref())?;
if input.as_deref() == Some(Path::new("-")) {
return Err(miette::miette!(
"watch does not support stdin ('-'); use 'mds build -' instead"
));
}
let resolved_input = match input {
None => auto_detect_mds_file("watch")?,
Some(p) => p,
};
let is_dir = resolved_input.is_dir();
if is_dir && output.is_some() {
return Err(miette::miette!(
"watch directory mode does not support -o/--output; \
use --out-dir to specify an output directory"
));
}
let tick_opt: Option<Duration> = clamp_poll_interval(poll_interval);
let session_args = SessionArgs {
out_dir,
vars,
set_vars,
set_string_vars,
clear,
debounce_ms: debounce,
quiet,
tick: tick_opt,
};
if is_dir {
let canonical = crate::input::resolve_directory_argument(&resolved_input)
.map_err(miette::Error::from)?;
run_watch_dir(
WatchedPath {
typed: resolved_input,
canonical,
what: Watched::Root,
},
session_args,
)
} else {
let canonical =
mds::NativeFs::check_symlink(&resolved_input).map_err(miette::Error::from)?;
run_watch_file(
WatchedPath {
typed: resolved_input,
canonical,
what: Watched::Entry,
},
output,
session_args,
)
}
}
struct SessionArgs {
out_dir: Option<PathBuf>,
vars: Option<PathBuf>,
set_vars: Vec<(String, String)>,
set_string_vars: Vec<(String, String)>,
clear: bool,
debounce_ms: u64,
quiet: bool,
tick: Option<Duration>,
}
mod live {
use std::ops::ControlFlow;
use std::sync::mpsc;
use std::time::{Duration, Instant};
use super::{emit_ready_marker, stop_watching, Msg, StopReason, TickClock, Wake};
pub(super) trait Session {
fn is_quiet(&self) -> bool;
fn hold_deadline(&self) -> Option<Instant>;
fn on_tick(&mut self) -> ControlFlow<StopReason>;
fn on_hold_due(&mut self) -> ControlFlow<StopReason>;
fn on_message(&mut self, msg: Msg, rx: &mpsc::Receiver<Msg>) -> ControlFlow<StopReason>;
}
pub(super) fn run_session(
tx: mpsc::Sender<Msg>,
rx: mpsc::Receiver<Msg>,
tick: Option<Duration>,
mut session: impl Session,
) {
go_live(&tx);
let why = watch_loop(&rx, tick, &mut session);
stop_watching(session.is_quiet(), why);
}
fn go_live(tx: &mpsc::Sender<Msg>) {
let tx_ctrlc = tx.clone();
let _ = ctrlc::set_handler(move || {
crate::output::panic_in_handler("ctrlc");
let _ = tx_ctrlc.send(Msg::Interrupt);
});
crate::output::note_watch_session_live();
emit_ready_marker();
}
fn watch_loop(
rx: &mpsc::Receiver<Msg>,
tick: Option<Duration>,
session: &mut impl Session,
) -> StopReason {
let mut clock = TickClock::new(tick);
loop {
let next = match clock.recv_next(rx, session.hold_deadline()) {
Err(mpsc::RecvError) => break StopReason::Interrupted,
Ok(Wake::Tick) => session.on_tick(),
Ok(Wake::HoldDue) => session.on_hold_due(),
Ok(Wake::Message(msg)) => session.on_message(msg, rx),
};
if let ControlFlow::Break(why) = next {
break why;
}
}
}
}
type WrittenEntry = (Option<WriteTarget>, Vec<PathBuf>, String);
enum CompileWriteOutcome {
Written(WrittenEntry),
CompileFailed(Option<miette::Report>),
WriteFailed {
deps: Vec<PathBuf>,
failure: Option<miette::Report>,
},
StdoutClosed,
}
#[derive(Debug)]
#[must_use]
enum OutputWrite {
Written,
Failed(Option<miette::Report>),
StdoutClosed,
}
impl OutputWrite {
fn from_stdout(outcome: StdoutOutcome) -> Self {
match outcome {
StdoutOutcome::Written => Self::Written,
StdoutOutcome::Closed => Self::StdoutClosed,
StdoutOutcome::Failed(e) => Self::Failed(Some(miette::Report::new(stdout_failure(&e)))),
StdoutOutcome::FailedAgain => Self::Failed(None),
}
}
}
fn written_path(output: &Option<WriteTarget>) -> Option<&Path> {
output.as_ref().map(|target| target.path.as_path())
}
fn shown_output(output: &Option<WriteTarget>) -> &Path {
output
.as_ref()
.map_or(Path::new("<stdout>"), |target| target.shown.as_path())
}
fn empties_output(before: Option<&str>, after: &str) -> bool {
after.is_empty() && before.is_some_and(|before| !before.is_empty())
}
fn announce_emptied_output(shown: &Path, emptied: bool, quiet: bool) {
if emptied && !quiet {
crate::output::ewriteln!("Wrote an empty output: {}", safe_path(shown));
}
}
fn write_session_output(
output_path: Option<&WriteTarget>,
content: &str,
inputs: &Inputs,
quiet: bool,
announce: bool,
) -> OutputWrite {
match output_path {
Some(target) => match write_output(Some(target), content, inputs, quiet, announce) {
Ok(()) => OutputWrite::Written,
Err(e) => OutputWrite::Failed(Some(e)),
},
None => OutputWrite::from_stdout(write_stdout(content.as_bytes())),
}
}
#[derive(Debug, Clone, Copy)]
struct ChangeOfKind<'a> {
record: Record<'a>,
told: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Rewritten {
Written,
Kept,
}
fn write_rebuilt(
target: &WriteTarget,
anchor: Option<&OutDirAnchor>,
now: OutDirNow,
change_of_kind: Option<ChangeOfKind<'_>>,
content: &str,
inputs: impl FnOnce() -> Inputs,
quiet: bool,
) -> std::result::Result<Rewritten, miette::Report> {
if now == OutDirNow::Elsewhere {
return Err(miette::Report::new(crate::write::out_dir_moved(target)));
}
let below = below_checked_out_dir(anchor, target);
match change_of_kind {
Some(ChangeOfKind { record, told }) => {
write_after_change_of_kind(&below, record, content, told, quiet)
.map(|written| {
if written {
Rewritten::Written
} else {
Rewritten::Kept
}
})
.map_err(miette::Report::new)
}
None => write_output(Some(&below), content, &inputs(), quiet, false)
.map(|()| Rewritten::Written),
}
}
fn announce_recompiled(shown: &Path, dep_count: usize, since: Instant, emptied: bool, quiet: bool) {
if !quiet {
let elapsed = since.elapsed().as_millis();
crate::output::ewriteln!(
"Recompiled {} ({} deps) in {}ms",
safe_path(shown),
dep_count,
elapsed
);
}
announce_emptied_output(shown, emptied, quiet);
}
fn compile_and_write(
entry: &WatchedPath,
output: &Option<String>,
out_dir: &Option<PathBuf>,
config: &Option<ProjectConfig>,
reads: &[PathBuf],
runtime_vars: Option<HashMap<String, mds::Value>>,
quiet: bool,
) -> Result<CompileWriteOutcome> {
let compiled = match entry.compile(runtime_vars, quiet) {
Ok(compiled) => compiled,
Err(failure) => return Ok(CompileWriteOutcome::CompileFailed(failure.into_report())),
};
let output_path =
resolve_output_path_for_kind(Some(entry.paths()), output, out_dir, config, compiled.kind)?;
admit_output(
written_path(&output_path),
entry.paths(),
output,
compiled.kind,
quiet,
)
.map_err(miette::Error::from)?;
let inputs = compile_inputs(Some(&entry.canonical), &compiled.dependencies, reads);
Ok(
match write_session_output(
output_path.as_ref(),
&compiled.content,
&inputs,
quiet,
true,
) {
OutputWrite::Written => CompileWriteOutcome::Written((
output_path,
graph_keys(&compiled.dependencies),
compiled.content,
)),
OutputWrite::Failed(failure) => CompileWriteOutcome::WriteFailed {
deps: graph_keys(&compiled.dependencies),
failure,
},
OutputWrite::StdoutClosed => CompileWriteOutcome::StdoutClosed,
},
)
}
struct FileCompileCtx {
entry: WatchedPath,
working_dir: WorkingDir,
vars_path: Option<PathBuf>,
vars_path_typed: Option<PathBuf>,
reads: Vec<PathBuf>,
static_set_vars: Vec<(String, String)>,
static_set_string_vars: Vec<(String, String)>,
quiet: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum OutputKey {
Stdout,
File(PathBuf),
}
impl OutputKey {
fn of(output: Option<&WriteTarget>) -> Self {
match output {
Some(target) => Self::File(target.path.clone()),
None => Self::Stdout,
}
}
}
#[derive(Debug, PartialEq, Eq)]
enum OutputRoute {
Named(Option<WriteTarget>),
ByKind {
markdown: Option<WriteTarget>,
messages: Option<WriteTarget>,
},
}
impl OutputRoute {
fn of(&self, kind: OutputKind) -> &Option<WriteTarget> {
match self {
Self::Named(route) => route,
Self::ByKind { markdown, messages } => match kind {
OutputKind::Markdown => markdown,
OutputKind::Messages => messages,
},
}
}
fn other_than(&self, kind: OutputKind) -> Option<&WriteTarget> {
match self {
Self::Named(_) => None,
Self::ByKind { markdown, messages } => match kind {
OutputKind::Markdown => messages.as_ref(),
OutputKind::Messages => markdown.as_ref(),
},
}
}
}
struct FileWatchState {
watched_dirs: BTreeSet<PathBuf>,
armed_dirs: BTreeSet<PathBuf>,
foi: HashSet<PathBuf>,
last_mtimes: StampMap,
hold: EmptyHold,
last_written: HashMap<OutputKey, String>,
written_to: Option<OutputKey>,
kept: Option<String>,
output: OutputRoute,
out_dir: Option<OutDirAnchor>,
entry_was_missing: bool,
first_tick: bool,
missing_watched_dirs: BTreeSet<PathBuf>,
}
impl FileWatchState {
fn rebaseline(&mut self) {
let taken = std::mem::take(&mut self.last_mtimes);
self.last_mtimes = baseline_over(taken, &self.foi);
}
}
enum FileEventAction {
Skip,
Stop,
Rebuild,
}
fn liveness_probe_file(
ctx: &FileCompileCtx,
watcher: &mut RecommendedWatcher,
state: &mut FileWatchState,
) -> bool {
let desired_dirs: BTreeSet<PathBuf> =
dirs_to_watch(&ctx.entry.canonical, &[], ctx.vars_path.as_deref())
.union(&state.watched_dirs)
.cloned()
.collect();
let dir_statuses: Vec<(PathBuf, bool, bool)> = desired_dirs
.iter()
.map(|d| {
let exists = d.exists();
let needs_arm = !state.armed_dirs.contains(d) || state.missing_watched_dirs.contains(d);
let rearm_ok = if exists && needs_arm {
let ok = watcher.watch(d, RecursiveMode::NonRecursive).is_ok();
if ok {
state.armed_dirs.insert(d.clone());
}
ok
} else {
exists
};
(d.clone(), exists, rearm_ok)
})
.collect();
for (d, exists, _) in &dir_statuses {
if !exists {
state.armed_dirs.remove(d);
}
}
let (dirs_recovery, now_missing_dirs) =
external_recovery_decision(&state.missing_watched_dirs, &dir_statuses);
state.missing_watched_dirs = now_missing_dirs;
let entry_now_exists = ctx.entry.canonical.exists();
let recovery =
state.first_tick || dirs_recovery || (state.entry_was_missing && entry_now_exists);
state.first_tick = false;
state.entry_was_missing = !entry_now_exists;
let changed = state_differs(&state.foi, &state.last_mtimes);
recovery || changed
}
fn handle_fs_event_file(
msg: Msg,
foi: &HashSet<PathBuf>,
rx: &mpsc::Receiver<Msg>,
debounce_ms: u64,
clear: bool,
) -> FileEventAction {
let interrupted = match msg {
Msg::Interrupt => true,
Msg::Fs(Err(e)) => {
eprint_warning(&format!(
"warning: watch error: {}",
safe_inline(notify_cause(&e))
));
return FileEventAction::Skip;
}
Msg::Fs(Ok(ref event)) => {
if !is_content_event(&event.kind) {
return FileEventAction::Skip;
}
if !event_is_relevant(event, foi) {
return FileEventAction::Skip; }
false
}
};
if interrupted {
return FileEventAction::Stop;
}
if drain_debounce(rx, debounce_ms).interrupted() {
return FileEventAction::Stop;
}
if clear {
crate::output::ask_clear();
}
FileEventAction::Rebuild
}
fn rebuild_file(
ctx: &FileCompileCtx,
watcher: &mut RecommendedWatcher,
state: &mut FileWatchState,
due: Option<Instant>,
) -> ControlFlow<StopReason> {
let flow = run_file_rebuild(ctx, watcher, state, due);
end_rebuild_clear(&state.hold);
flow
}
fn run_file_rebuild(
ctx: &FileCompileCtx,
watcher: &mut RecommendedWatcher,
state: &mut FileWatchState,
due: Option<Instant>,
) -> ControlFlow<StopReason> {
ctx.working_dir.restore_if_recreated();
let look = snapshot_state(&state.foi);
let emptied = emptied_in(&look, &state.last_mtimes).next().is_some();
let verdict = state
.hold
.on_rebuild(emptied, not_before(Instant::now(), due));
debug_assert!(
due.is_none() || verdict == HoldVerdict::Compile,
"a held rebuild's deadline ends its hold"
);
if verdict == HoldVerdict::Hold {
settle(SettleInto::File(state), None, Settle::Defer);
return ControlFlow::Continue(());
}
state.last_mtimes.extend(look);
pause_after_look();
let kept_before = state.kept.take();
let loaded = load_and_compile(ctx);
let read = match &loaded {
Ok(done) => &done.foi,
Err(_) => &state.foi,
};
if held_after_look(&mut state.hold, read, &state.last_mtimes).is_some() {
state.kept = kept_before;
settle(SettleInto::File(state), None, Settle::Defer);
return ControlFlow::Continue(());
}
let FileCompiled {
resolved,
started: t0,
compiled,
deps,
foi,
} = match loaded {
Ok(done) => done,
Err((failure, how)) => {
settle(SettleInto::File(state), failure, how);
return ControlFlow::Continue(());
}
};
let entry = &ctx.entry;
let new_dirs = dirs_to_watch(&entry.canonical, &deps, ctx.vars_path.as_deref());
state.watched_dirs = resync_watches(
watcher,
&state.watched_dirs,
&new_dirs,
entry.dir_paths(),
vars_dir_paths(ctx.vars_path.as_deref(), ctx.vars_path_typed.as_deref()),
);
state.armed_dirs = state.watched_dirs.clone();
state.foi = foi;
pause_after_read();
state.rebaseline();
let output_path = state.output.of(compiled.kind).clone();
if let Err(refused) = admit_output(
written_path(&output_path),
entry.paths(),
&None,
compiled.kind,
ctx.quiet,
) {
settle(
SettleInto::File(state),
Some(miette::Report::from(refused)),
Settle::MarkErrored(&entry.canonical),
);
return ControlFlow::Continue(());
}
let output_key = OutputKey::of(output_path.as_ref());
let out_dir = check_out_dir(state.out_dir.as_mut(), &mut state.last_written);
let kind_changed = state
.written_to
.as_ref()
.is_some_and(|key| *key != output_key);
let content_changed = kind_changed
|| state
.last_written
.get(&output_key)
.is_none_or(|prev| *prev != compiled.content);
if !content_changed {
return ControlFlow::Continue(());
}
let warn_duplicates = || crate::build::emit_duplicate_vars_file_warnings(&resolved, ctx.quiet);
let told = kept_before.as_ref() == Some(&compiled.content);
let written = match output_path.as_ref() {
Some(target) => match write_rebuilt(
target,
state.out_dir.as_ref(),
out_dir,
kind_changed.then(|| ChangeOfKind {
record: Record::of_entry(state.last_written.get(&output_key)),
told,
}),
&compiled.content,
|| {
compile_inputs(
Some(&ctx.entry.canonical),
&compiled.dependencies,
&ctx.reads,
)
},
ctx.quiet,
) {
Ok(Rewritten::Written) => OutputWrite::Written,
Ok(Rewritten::Kept) => {
if !told {
warn_duplicates();
}
state.kept = Some(compiled.content);
return ControlFlow::Continue(());
}
Err(e) => OutputWrite::Failed(Some(e)),
},
None => OutputWrite::from_stdout(write_stdout(compiled.content.as_bytes())),
};
match written {
OutputWrite::Written => {
warn_duplicates();
announce_recompiled(
shown_output(&output_path),
deps.len(),
t0,
empties_output(
state.last_written.get(&output_key).map(String::as_str),
&compiled.content,
),
ctx.quiet,
);
state
.last_written
.insert(output_key.clone(), compiled.content);
state.written_to = Some(output_key);
if let Some(anchor) = &mut state.out_dir {
anchor.written();
}
if let Some(stale) = state
.output
.other_than(compiled.kind)
.filter(|_| kind_changed)
.cloned()
{
let stale_key = OutputKey::of(Some(&stale));
let gone = retire_output(
&stale,
state.out_dir.as_ref(),
out_dir,
Record::of_entry(state.last_written.get(&stale_key)),
Retirement::KindChanged,
ctx.quiet,
);
if gone {
state.last_written.remove(&stale_key);
}
}
}
OutputWrite::Failed(Some(e)) => {
warn_duplicates();
settle(
SettleInto::File(state),
Some(e),
Settle::MarkErrored(&ctx.entry.canonical),
);
}
OutputWrite::Failed(None) => {}
OutputWrite::StdoutClosed => return ControlFlow::Break(StopReason::StdoutClosed),
}
ControlFlow::Continue(())
}
struct FileCompiled {
resolved: RuntimeVars,
started: Instant,
compiled: CompileOutput,
deps: Vec<PathBuf>,
foi: HashSet<PathBuf>,
}
fn load_and_compile(
ctx: &FileCompileCtx,
) -> std::result::Result<FileCompiled, (Option<miette::Report>, Settle<'_>)> {
let mut resolved = build_runtime_vars(RuntimeVarArgs {
vars: ctx.vars_path_typed.clone(),
set_vars: ctx.static_set_vars.clone(),
set_string_vars: ctx.static_set_string_vars.clone(),
})
.map_err(|e| (Some(e), Settle::Rebaseline))?;
let runtime_vars = resolved.vars.take();
let started = Instant::now();
let entry = &ctx.entry;
let compiled = entry
.compile(runtime_vars, ctx.quiet)
.map_err(|failure| (failure.into_report(), Settle::MarkErrored(&entry.canonical)))?;
let deps = graph_keys(&compiled.dependencies);
let foi = files_of_interest(&entry.canonical, &deps, ctx.vars_path.as_deref());
Ok(FileCompiled {
resolved,
started,
compiled,
deps,
foi,
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Settle<'a> {
Rebaseline,
MarkErrored(&'a Path),
Defer,
}
enum SettleInto<'a> {
File(&'a mut FileWatchState),
Dir(&'a mut DirWatchState),
}
fn settle(into: SettleInto<'_>, failure: Option<miette::Report>, how: Settle<'_>) {
settle_reporting(into, failure, how, eprint_error);
}
fn settle_reporting(
into: SettleInto<'_>,
failure: Option<miette::Report>,
how: Settle<'_>,
report: impl FnOnce(miette::Report),
) {
if let Some(e) = failure {
report(e);
}
match (into, how) {
(SettleInto::File(state), Settle::Rebaseline | Settle::MarkErrored(_)) => {
state.rebaseline();
}
(SettleInto::Dir(state), Settle::Rebaseline) => {
state.rebaseline();
}
(SettleInto::Dir(state), Settle::MarkErrored(src)) => {
state.record_error(src);
}
(SettleInto::File(_) | SettleInto::Dir(_), Settle::Defer) => {}
}
}
enum StartupInto<'a> {
File,
Dir(&'a mut DirWatchState),
}
fn settle_startup_error(into: StartupInto<'_>, failure: Option<miette::Report>, src: &Path) {
settle_startup_error_reporting(into, failure, src, eprint_error);
}
fn settle_startup_error_reporting(
into: StartupInto<'_>,
failure: Option<miette::Report>,
src: &Path,
report: impl FnOnce(miette::Report),
) {
if let Some(e) = failure {
report(e);
}
if let StartupInto::Dir(state) = into {
state.record_error(src);
}
}
fn shown_watched_dir(dir: &Path, root: RootPaths<'_>, vars: Option<RootPaths<'_>>) -> PathBuf {
match vars {
Some(vars) if dir == vars.walked && dir != root.walked => vars.typed.to_path_buf(),
_ => root.typed_below(dir).unwrap_or_else(|| dir.to_path_buf()),
}
}
fn vars_dir_paths<'a>(
canonical: Option<&'a Path>,
typed: Option<&'a Path>,
) -> Option<RootPaths<'a>> {
canonical.zip(typed).map(|(canonical, typed)| RootPaths {
typed: mds::effective_parent(typed),
walked: mds::effective_parent(canonical),
})
}
fn extra_vars_dir<'a>(
vars_dir_extra: Option<&'a Path>,
vars_path_typed: Option<&'a Path>,
) -> Option<RootPaths<'a>> {
vars_dir_extra
.zip(vars_path_typed)
.map(|(walked, typed)| RootPaths {
typed: mds::effective_parent(typed),
walked,
})
}
fn run_watch_file(entry: WatchedPath, output: Option<String>, args: SessionArgs) -> Result<()> {
let quiet = args.quiet;
let armed = file_startup::arm_pre_read(entry, output, args)?;
let compiled = match file_startup::startup_compile(armed)? {
ControlFlow::Continue(compiled) => compiled,
ControlFlow::Break((why, _armed)) => {
stop_watching(quiet, why);
return Ok(());
}
};
file_startup::arm_deps_and_seed(compiled)?.go_live();
Ok(())
}
mod file_startup {
use std::collections::{BTreeSet, HashMap};
use std::ops::ControlFlow;
use std::path::PathBuf;
use std::sync::mpsc;
use std::time::{Duration, Instant};
use miette::Result;
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use crate::build::{
admit_output, build_runtime_vars, emit_duplicate_var_warnings, load_config,
resolve_output_path_for_kind, run_reads, OutputKind, ProjectConfig, RuntimeVarArgs,
};
use crate::output::{notify_cause, safe_inline, safe_path, WriteTarget};
use super::{
baseline_path, canonicalize_vars_path, compile_and_write, dirs_to_watch, files_of_interest,
handle_fs_event_file, live, liveness_probe_file, rebuild_file, settle_startup_error,
shown_watched_dir, snapshot_state, startup_race_probe, vars_dir_paths, written_path,
CompileWriteOutcome, EmptyHold, FileCompileCtx, FileEventAction, FileWatchState, Msg,
OutDirAnchor, OutputKey, OutputRoute, SessionArgs, StampMap, StartupInto, StopReason,
WatchedPath, WorkingDir,
};
pub(super) struct Armed {
entry: WatchedPath,
output: Option<String>,
out_dir: Option<PathBuf>,
working_dir: WorkingDir,
vars_path: Option<PathBuf>,
vars_path_typed: Option<PathBuf>,
static_set_vars: Vec<(String, String)>,
static_set_string_vars: Vec<(String, String)>,
quiet: bool,
clear: bool,
debounce_ms: u64,
tick: Option<Duration>,
tx: mpsc::Sender<Msg>,
rx: mpsc::Receiver<Msg>,
watcher: RecommendedWatcher,
watched_dirs: BTreeSet<PathBuf>,
pre_mtimes: StampMap,
entry_was_missing: bool,
}
pub(super) struct Compiled {
armed: Armed,
config: Option<ProjectConfig>,
reads: Vec<PathBuf>,
output_route: OutputRoute,
initial_written: Option<(Option<WriteTarget>, String)>,
initial_deps: Vec<PathBuf>,
}
pub(super) struct Seeded {
tx: mpsc::Sender<Msg>,
rx: mpsc::Receiver<Msg>,
tick: Option<Duration>,
session: FileSession,
}
struct FileSession {
ctx: FileCompileCtx,
watcher: RecommendedWatcher,
state: FileWatchState,
debounce_ms: u64,
clear: bool,
}
pub(super) fn arm_pre_read(
entry: WatchedPath,
output: Option<String>,
args: SessionArgs,
) -> Result<Armed> {
let SessionArgs {
out_dir,
vars,
set_vars: static_set_vars,
set_string_vars: static_set_string_vars,
clear,
debounce_ms,
quiet,
tick,
} = args;
let working_dir = WorkingDir::record();
let vars_path_typed = vars.clone();
let vars_path = canonicalize_vars_path(vars).map_err(miette::Error::from)?;
if !quiet {
crate::output::ewriteln!("Watching {}", safe_path(&entry.typed));
}
let (tx, rx) = mpsc::channel::<Msg>();
let tx_fs = tx.clone();
let mut watcher = RecommendedWatcher::new(
move |res| {
crate::output::panic_in_handler("notify");
let _ = tx_fs.send(Msg::Fs(res));
},
notify::Config::default(),
)
.map_err(|e| {
miette::miette!(
"failed to initialize file watcher: {}",
safe_inline(notify_cause(&e))
)
})?;
let mut watched_dirs: BTreeSet<PathBuf> = BTreeSet::new();
for dir in dirs_to_watch(&entry.canonical, &[], vars_path.as_deref()) {
if dir.exists() && watcher.watch(&dir, RecursiveMode::NonRecursive).is_ok() {
watched_dirs.insert(dir);
}
}
let pre_mtimes = snapshot_state(&files_of_interest(
&entry.canonical,
&[],
vars_path.as_deref(),
));
let entry_was_missing = !entry.canonical.exists();
Ok(Armed {
entry,
output,
out_dir,
working_dir,
vars_path,
vars_path_typed,
static_set_vars,
static_set_string_vars,
quiet,
clear,
debounce_ms,
tick,
tx,
rx,
watcher,
watched_dirs,
pre_mtimes,
entry_was_missing,
})
}
pub(super) fn startup_compile(
armed: Armed,
) -> Result<ControlFlow<(StopReason, Armed), Compiled>> {
let Armed {
entry,
output,
out_dir,
vars_path,
vars_path_typed,
static_set_vars,
static_set_string_vars,
quiet,
..
} = &armed;
let quiet = *quiet;
let resolved = build_runtime_vars(RuntimeVarArgs {
vars: vars_path_typed.clone(),
set_vars: static_set_vars.clone(),
set_string_vars: static_set_string_vars.clone(),
})?;
emit_duplicate_var_warnings(&resolved, quiet);
let runtime_vars = resolved.vars;
let config = load_config(&entry.typed)?;
let reads = run_reads(vars_path.as_deref(), config.as_ref());
let startup =
compile_and_write(entry, output, out_dir, &config, &reads, runtime_vars, quiet)?;
let route_of = |kind| {
resolve_output_path_for_kind(Some(entry.paths()), output, out_dir, &config, kind)
};
let (initial_written, initial_deps) = match startup {
CompileWriteOutcome::Written((output_path, deps, content)) => {
(Some((output_path, content)), deps)
}
CompileWriteOutcome::StdoutClosed => {
return Ok(ControlFlow::Break((StopReason::StdoutClosed, armed)));
}
CompileWriteOutcome::WriteFailed { deps, failure } => {
settle_startup_error(StartupInto::File, failure, &entry.canonical);
(None, deps)
}
CompileWriteOutcome::CompileFailed(e) => {
settle_startup_error(StartupInto::File, e, &entry.canonical);
if output.is_some() {
let _ = admit_output(
written_path(&route_of(OutputKind::Markdown)?),
entry.paths(),
output,
OutputKind::Markdown,
quiet,
);
}
(None, vec![])
}
};
let output_route = if output.is_some() {
OutputRoute::Named(route_of(OutputKind::Markdown)?)
} else {
OutputRoute::ByKind {
markdown: route_of(OutputKind::Markdown)?,
messages: route_of(OutputKind::Messages)?,
}
};
Ok(ControlFlow::Continue(Compiled {
armed,
config,
reads,
output_route,
initial_written,
initial_deps,
}))
}
pub(super) fn arm_deps_and_seed(compiled: Compiled) -> Result<Seeded> {
let Compiled {
armed,
config,
reads,
output_route,
initial_written,
initial_deps,
} = compiled;
let Armed {
entry,
output,
out_dir,
working_dir,
vars_path,
vars_path_typed,
static_set_vars,
static_set_string_vars,
quiet,
clear,
debounce_ms,
tick,
tx,
rx,
mut watcher,
mut watched_dirs,
mut pre_mtimes,
entry_was_missing,
} = armed;
for dep in &initial_deps {
baseline_path(dep, &mut pre_mtimes);
}
startup_race_probe();
let init_dirs = dirs_to_watch(&entry.canonical, &initial_deps, vars_path.as_deref());
let unarmed: Vec<PathBuf> = init_dirs.difference(&watched_dirs).cloned().collect();
for dir in unarmed {
match watcher.watch(&dir, RecursiveMode::NonRecursive) {
Ok(()) => {
watched_dirs.insert(dir);
}
Err(e) => {
let vars = vars_dir_paths(vars_path.as_deref(), vars_path_typed.as_deref());
return Err(miette::miette!(
"failed to watch directory {}: {}\n\
hint: on Linux you may need to increase fs.inotify.max_user_watches",
safe_path(&shown_watched_dir(&dir, entry.dir_paths(), vars)),
safe_inline(notify_cause(&e))
));
}
}
}
let mut last_written: HashMap<OutputKey, String> = HashMap::new();
let written_to = initial_written.map(|(written, content)| {
let key = OutputKey::of(written.as_ref());
last_written.insert(key.clone(), content);
key
});
let foi = files_of_interest(&entry.canonical, &initial_deps, vars_path.as_deref());
let missing_watched_dirs: BTreeSet<PathBuf> = {
let desired = dirs_to_watch(&entry.canonical, &[], vars_path.as_deref())
.union(&watched_dirs)
.cloned()
.collect::<BTreeSet<_>>();
desired.into_iter().filter(|d| !d.exists()).collect()
};
let mut last_mtimes = snapshot_state(&foi);
let entry_pre = pre_mtimes.get(&entry.canonical).copied();
last_mtimes.extend(pre_mtimes);
debug_assert_eq!(
last_mtimes.get(&entry.canonical).copied(),
entry_pre,
"baseline merge inverted: the entry's pre-compile (mtime, size) must survive \
the merge with the post-compile snapshot, or an edit made during startup can \
never register as a difference"
);
let state = FileWatchState {
armed_dirs: watched_dirs.clone(),
watched_dirs,
foi,
last_mtimes,
hold: EmptyHold::Off,
last_written,
written_to,
kept: None,
output: output_route,
out_dir: if output.is_some() {
None
} else {
OutDirAnchor::record(out_dir.as_deref(), config.as_ref())
},
entry_was_missing,
first_tick: true,
missing_watched_dirs,
};
let ctx = FileCompileCtx {
entry,
working_dir,
vars_path,
vars_path_typed,
reads,
static_set_vars,
static_set_string_vars,
quiet,
};
Ok(Seeded {
tx,
rx,
tick,
session: FileSession {
ctx,
watcher,
state,
debounce_ms,
clear,
},
})
}
impl Seeded {
pub(super) fn go_live(self) {
let Seeded {
tx,
rx,
tick,
session,
} = self;
live::run_session(tx, rx, tick, session);
}
}
impl live::Session for FileSession {
fn is_quiet(&self) -> bool {
self.ctx.quiet
}
fn hold_deadline(&self) -> Option<Instant> {
self.state.hold.deadline()
}
fn on_tick(&mut self) -> ControlFlow<StopReason> {
if liveness_probe_file(&self.ctx, &mut self.watcher, &mut self.state) {
rebuild_file(&self.ctx, &mut self.watcher, &mut self.state, None)
} else {
ControlFlow::Continue(())
}
}
fn on_hold_due(&mut self) -> ControlFlow<StopReason> {
let due = self.state.hold.deadline();
rebuild_file(&self.ctx, &mut self.watcher, &mut self.state, due)
}
fn on_message(&mut self, msg: Msg, rx: &mpsc::Receiver<Msg>) -> ControlFlow<StopReason> {
let action =
handle_fs_event_file(msg, &self.state.foi, rx, self.debounce_ms, self.clear);
match action {
FileEventAction::Skip => ControlFlow::Continue(()),
FileEventAction::Stop => ControlFlow::Break(StopReason::Interrupted),
FileEventAction::Rebuild => {
rebuild_file(&self.ctx, &mut self.watcher, &mut self.state, None)
}
}
}
}
}
const MAX_COLLECT_DEPTH: usize = 64;
struct DirWatchState {
forward_deps: HashMap<PathBuf, Vec<PathBuf>>,
errored: HashSet<PathBuf>,
known_files: BTreeSet<PathBuf>,
last_written: HashMap<PathBuf, WrittenOutput>,
outputs: HashMap<PathBuf, WriteTarget>,
kept: HashMap<PathBuf, String>,
out_dir: Option<OutDirAnchor>,
reads: Vec<PathBuf>,
external_dep_dirs: BTreeSet<PathBuf>,
vars_file: Option<PathBuf>,
last_mtimes: StampMap,
hold: EmptyHold,
held: HeldBatch,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct Batch {
paths: BTreeSet<PathBuf>,
vars_changed: bool,
}
#[derive(Debug, Default, PartialEq, Eq)]
struct HeldBatch {
paths: BTreeSet<PathBuf>,
sources: BTreeSet<PathBuf>,
read_empty: BTreeSet<PathBuf>,
vars_changed: bool,
}
impl HeldBatch {
fn hold(&mut self, batch: &Batch, root: &Path) {
for path in &batch.paths {
if names_a_source(root, path) {
self.sources.insert(path.clone());
}
self.paths.insert(path.clone());
}
self.vars_changed |= batch.vars_changed;
}
fn carry(&mut self, batch: &Batch, root: &Path) {
self.hold(batch, root);
}
fn hold_read_empty(&mut self, source: &Path, emptied: BTreeSet<PathBuf>, root: &Path) {
let batch = Batch {
paths: BTreeSet::from([source.to_path_buf()]),
vars_changed: false,
};
self.hold(&batch, root);
self.read_empty.extend(emptied);
}
fn release(&mut self, batch: Batch) -> Batch {
let held = std::mem::take(self);
let mut paths = held.paths;
paths.extend(batch.paths);
Batch {
paths,
vars_changed: batch.vars_changed || held.vars_changed,
}
}
}
fn join_emptied(mut batch: Batch, emptied: &BTreeSet<PathBuf>, vars_file: Option<&Path>) -> Batch {
let (vars, paths): (Vec<&PathBuf>, Vec<&PathBuf>) = emptied
.iter()
.partition(|path| Some(path.as_path()) == vars_file);
batch.paths.extend(paths.into_iter().cloned());
batch.vars_changed |= !vars.is_empty();
batch
}
impl DirWatchState {
fn record_success(
&mut self,
src: &Path,
dep_paths: Vec<PathBuf>,
root: &Path,
out: Option<&WriteTarget>,
content: Option<String>,
) {
for dep in &dep_paths {
if let Some(parent) = dep.parent() {
if !parent.starts_with(root) {
self.external_dep_dirs.insert(parent.to_path_buf());
}
}
}
self.forward_deps.insert(src.to_path_buf(), dep_paths);
self.errored.remove(src);
self.known_files.insert(src.to_path_buf());
if let (Some(out), Some(content)) = (out, content) {
self.wrote(src, out, content);
}
}
fn wrote(&mut self, src: &Path, out: &WriteTarget, content: String) {
let written = WrittenOutput {
source: src.to_path_buf(),
content,
};
self.last_written.insert(out.path.clone(), written);
self.outputs.insert(src.to_path_buf(), out.clone());
}
fn record(&self, path: &Path, src: &Path) -> Record<'_> {
match self.last_written.get(path) {
None => Record::Unwritten,
Some(written) if written.source == src => Record::Own(&written.content),
Some(_) => Record::OtherSource,
}
}
fn retire(
&mut self,
src: &Path,
out: &WriteTarget,
now: OutDirNow,
why: Retirement,
quiet: bool,
) {
let record = self.record(&out.path, src);
let own = matches!(record, Record::Own(_));
if retire_output(out, self.out_dir.as_ref(), now, record, why, quiet) && own {
self.last_written.remove(&out.path);
}
}
fn record_error(&mut self, src: &Path) {
self.errored.insert(src.to_path_buf());
self.forward_deps.entry(src.to_path_buf()).or_default();
}
fn dep_dirs_outside(&self, root: &Path) -> BTreeSet<PathBuf> {
self.forward_deps
.values()
.flatten()
.filter_map(|dep| dep.parent())
.filter(|parent| !parent.starts_with(root))
.map(Path::to_path_buf)
.collect()
}
fn tracked_paths(&self) -> impl Iterator<Item = &PathBuf> {
self.known_files
.iter()
.chain(self.forward_deps.values().flatten())
}
#[cfg(test)]
fn tracked_set(&self) -> HashSet<PathBuf> {
self.tracked_paths().cloned().collect()
}
fn watched_set(&self) -> HashSet<PathBuf> {
self.watched_paths().cloned().collect()
}
fn watched_paths(&self) -> impl Iterator<Item = &PathBuf> {
self.tracked_paths().chain(self.vars_file.iter())
}
fn baselined_paths(&self) -> impl Iterator<Item = &PathBuf> {
self.watched_paths()
.chain(&self.held.sources)
.chain(&self.held.read_empty)
}
fn hold_after_vars_load_failed(&mut self, batch: &Batch, root: &Path) -> bool {
let watched = self.watched_set();
let Some(emptied) = held_after_look(&mut self.hold, &watched, &self.last_mtimes) else {
return false;
};
let batch = join_emptied(batch.clone(), &emptied, self.vars_file.as_deref());
self.held.hold(&batch, root);
true
}
fn hold_back(
&mut self,
src: &Path,
kept_before: Option<String>,
read_empty: BTreeSet<PathBuf>,
root: &Path,
) {
let source = src.to_path_buf();
if let Some(kept) = kept_before {
self.kept.insert(source.clone(), kept);
}
self.held.hold_read_empty(&source, read_empty, root);
}
fn rebaseline(&mut self) {
let taken = std::mem::take(&mut self.last_mtimes);
self.last_mtimes = baseline_over(taken, self.baselined_paths());
}
fn forget_graph(&mut self, src: &Path) {
self.forward_deps.remove(src);
self.errored.remove(src);
self.known_files.remove(src);
}
fn forget(&mut self, src: &Path) {
if let Some(out) = self.outputs.remove(src) {
for kind in [OutputKind::Markdown, OutputKind::Messages] {
let path = out.path.with_extension(kind.extension());
if self
.last_written
.get(&path)
.is_some_and(|written| written.source == src)
{
self.last_written.remove(&path);
}
}
}
self.kept.remove(src);
self.forget_graph(src);
}
fn retire_deleted(
&mut self,
src: &Path,
watch_root: &WatchedPath,
output_base: &OutputBase,
quiet: bool,
) {
if src.exists() {
return;
}
let known = self.known_files.contains(src) || self.errored.contains(src);
let out = match self.outputs.get(src) {
Some(out) => Some(out.clone()),
None if known
&& classify(&watch_root.canonical, src, &self.external_dep_dirs)
== Node::Source =>
{
Some(output_path_for(
src,
watch_root.root_paths(),
output_base,
OutputKind::Markdown.extension(),
))
}
None => None,
};
if let Some(out) = out {
let now = check_out_dir(self.out_dir.as_mut(), &mut self.last_written);
for kind in [OutputKind::Markdown, OutputKind::Messages] {
let candidate = out.sibling(|path| path.with_extension(kind.extension()));
self.retire(src, &candidate, now, Retirement::SourceDeleted, quiet);
}
}
self.forget(src);
}
}
struct LivenessState {
first_tick: bool,
root_was_missing: bool,
root_armed: bool,
missing_external_dirs: BTreeSet<PathBuf>,
armed_dirs: BTreeSet<PathBuf>,
failing_dirs: BTreeSet<PathBuf>,
}
struct BatchVars<'a> {
map: &'a Option<HashMap<String, mds::Value>>,
unreported: Option<&'a RuntimeVars>,
}
impl<'a> BatchVars<'a> {
fn of(resolved: &'a RuntimeVars) -> Self {
Self {
map: &resolved.vars,
unreported: Some(resolved),
}
}
#[cfg(test)]
fn map_only(map: &'a Option<HashMap<String, mds::Value>>) -> Self {
Self {
map,
unreported: None,
}
}
fn shown(&mut self, quiet: bool) {
if let Some(resolved) = self.unreported.take() {
crate::build::emit_duplicate_vars_file_warnings(resolved, quiet);
}
}
}
struct BatchCtx<'a> {
watch_root: &'a WatchedPath,
output_base: &'a OutputBase,
vars: BatchVars<'a>,
quiet: bool,
}
fn compile_one_source(src: &Path, ctx: &mut BatchCtx<'_>, state: &mut DirWatchState) {
let BatchCtx {
watch_root,
output_base,
quiet,
..
} = *ctx;
let root = watch_root.canonical.as_path();
let t0 = Instant::now();
let kept_before = state.kept.remove(src);
pause_after_batch_split();
let compiled = match watch_root.compile_source(src, ctx.vars.map.clone(), quiet) {
Ok(compiled) => compiled,
Err(CompileFailure::Error(_)) if matches!(src.try_exists(), Ok(false)) => {
state.retire_deleted(src, watch_root, output_base, quiet);
return;
}
Err(failure) => {
let source = src.to_path_buf();
let reads = std::iter::once(&source)
.chain(state.forward_deps.get(src).into_iter().flatten())
.chain(state.vars_file.as_ref());
if held_after_look(&mut state.hold, reads, &state.last_mtimes).is_some() {
state.hold_back(src, kept_before, BTreeSet::new(), root);
return;
}
settle(
SettleInto::Dir(state),
failure.into_report(),
Settle::MarkErrored(src),
);
return;
}
};
let dep_paths = graph_keys(&compiled.dependencies);
if is_partial(src) {
state.record_success(src, dep_paths, root, None, None);
return;
}
let ext = compiled.kind.extension();
let out = output_path_for(src, watch_root.root_paths(), output_base, ext);
let out_dir = check_out_dir(state.out_dir.as_mut(), &mut state.last_written);
let previous = state
.outputs
.get(src)
.filter(|last| last.path != out.path)
.cloned();
let content_changed =
previous.is_some() || state.record(&out.path, src) != Record::Own(&compiled.content);
let emptied = match state.record(&out.path, src) {
Record::Own(before) => empties_output(Some(before), &compiled.content),
Record::Unwritten | Record::OtherSource => false,
};
if !content_changed {
state.record_success(src, dep_paths, root, None, None);
return;
}
let source = src.to_path_buf();
let reads = std::iter::once(&source)
.chain(&dep_paths)
.chain(state.vars_file.as_ref());
if let Some(read_empty) = held_after_look(&mut state.hold, reads, &state.last_mtimes) {
state.hold_back(src, kept_before, read_empty, root);
return;
}
let told = kept_before.as_ref() == Some(&compiled.content);
let written = write_rebuilt(
&out,
state.out_dir.as_ref(),
out_dir,
previous.is_some().then(|| ChangeOfKind {
record: state.record(&out.path, src),
told,
}),
&compiled.content,
|| source_inputs(src, &compiled.dependencies, &state.reads),
quiet,
);
match written {
Ok(Rewritten::Kept) => {
if !told {
ctx.vars.shown(quiet);
}
state.kept.insert(src.to_path_buf(), compiled.content);
state.record_success(src, dep_paths, root, None, None);
return;
}
Err(e) => {
state.record_success(src, dep_paths, root, None, None);
ctx.vars.shown(quiet);
settle(SettleInto::Dir(state), Some(e), Settle::MarkErrored(src));
return;
}
Ok(Rewritten::Written) => {}
}
ctx.vars.shown(quiet);
if let Some(anchor) = &mut state.out_dir {
anchor.written();
}
announce_recompiled(&out.shown, compiled.dependencies.len(), t0, emptied, quiet);
if let Some(previous) = &previous {
state.retire(src, previous, out_dir, Retirement::KindChanged, quiet);
}
state.record_success(src, dep_paths, root, Some(&out), Some(compiled.content));
}
struct DirWatchCtx {
root: WatchedPath,
working_dir: WorkingDir,
vars_path: Option<PathBuf>,
vars_path_typed: Option<PathBuf>,
static_set_vars: Vec<(String, String)>,
static_set_string_vars: Vec<(String, String)>,
output_base: OutputBase,
exclude_prefix: Option<PathBuf>,
vars_dir_extra: Option<PathBuf>,
clear: bool,
debounce_ms: u64,
quiet: bool,
}
#[derive(Debug)]
enum DirArm {
Held,
Armed,
Failed(notify::Error),
FailedAgain,
}
fn arm_dir(
dir: &Path,
armed: &mut BTreeSet<PathBuf>,
failing: &mut BTreeSet<PathBuf>,
watch: impl FnOnce(&Path) -> notify::Result<()>,
) -> DirArm {
if armed.contains(dir) {
return DirArm::Held;
}
match watch(dir) {
Ok(()) => {
armed.insert(dir.to_path_buf());
failing.remove(dir);
DirArm::Armed
}
Err(e) if failing.insert(dir.to_path_buf()) => DirArm::Failed(e),
Err(_) => DirArm::FailedAgain,
}
}
fn arm_external_dep_dirs<'a>(
dirs: impl IntoIterator<Item = &'a PathBuf>,
armed: &mut BTreeSet<PathBuf>,
failing: &mut BTreeSet<PathBuf>,
mut watch: impl FnMut(&Path) -> notify::Result<()>,
root: RootPaths<'_>,
vars: Option<RootPaths<'_>>,
) {
for dir in dirs {
match arm_dir(dir, armed, failing, &mut watch) {
DirArm::Failed(e) => eprint_warning(&format!(
"warning: failed to watch external dep dir {}: {}",
safe_path(&shown_watched_dir(dir, root, vars)),
safe_inline(notify_cause(&e))
)),
DirArm::Held | DirArm::Armed | DirArm::FailedAgain => {}
}
}
}
fn unwatch_unimported_dirs(
ctx: &DirWatchCtx,
watcher: &mut dyn Watcher,
liveness: &mut LivenessState,
imported: &BTreeSet<PathBuf>,
) {
let unimported: Vec<PathBuf> = liveness
.armed_dirs
.iter()
.filter(|dir| !imported.contains(*dir) && ctx.vars_dir_extra.as_ref() != Some(*dir))
.cloned()
.collect();
for dir in &unimported {
let _ = watcher.unwatch(dir);
liveness.armed_dirs.remove(dir);
}
liveness.failing_dirs.retain(|dir| imported.contains(dir));
}
fn arm_external_dirs_after_rebuild(
ctx: &DirWatchCtx,
watcher: &mut dyn Watcher,
liveness: &mut LivenessState,
state: &DirWatchState,
) {
unwatch_unimported_dirs(ctx, watcher, liveness, &state.external_dep_dirs);
let unarmed: Vec<&PathBuf> = state
.external_dep_dirs
.iter()
.filter(|dir| !liveness.armed_dirs.contains(*dir) && dir.exists())
.collect();
arm_external_dep_dirs(
unarmed,
&mut liveness.armed_dirs,
&mut liveness.failing_dirs,
|dir| watcher.watch(dir, RecursiveMode::NonRecursive),
ctx.root.root_paths(),
extra_vars_dir(
ctx.vars_dir_extra.as_deref(),
ctx.vars_path_typed.as_deref(),
),
);
}
fn liveness_probe_dir(
ctx: &DirWatchCtx,
watcher: &mut dyn Watcher,
liveness: &mut LivenessState,
state: &mut DirWatchState,
) {
let root_now_exists = ctx.root.canonical.exists();
let need_root_rearm = (liveness.root_was_missing && root_now_exists) || !liveness.root_armed;
let root_ok = if root_now_exists && need_root_rearm {
let ok = watcher
.watch(&ctx.root.canonical, RecursiveMode::Recursive)
.is_ok();
liveness.root_armed = ok;
ok
} else if root_now_exists {
true
} else {
liveness.root_armed = false;
false
};
unwatch_unimported_dirs(ctx, watcher, liveness, &state.external_dep_dirs);
liveness
.missing_external_dirs
.retain(|d| state.external_dep_dirs.contains(d));
let ext_statuses: Vec<(PathBuf, bool, bool)> = state
.external_dep_dirs
.iter()
.map(|ext_dir| {
let exists = ext_dir.exists();
let already_armed = liveness.armed_dirs.contains(ext_dir);
let rearm_ok = if exists {
if already_armed {
true
} else {
let ok = watcher.watch(ext_dir, RecursiveMode::NonRecursive).is_ok();
if ok {
liveness.armed_dirs.insert(ext_dir.clone());
liveness.failing_dirs.remove(ext_dir);
}
ok
}
} else {
liveness.armed_dirs.remove(ext_dir);
false
};
(ext_dir.clone(), exists, rearm_ok)
})
.collect();
let (external_recovery, now_missing_external) =
external_recovery_decision(&liveness.missing_external_dirs, &ext_statuses);
if let Some(vd) = ctx.vars_dir_extra.as_deref() {
if !vd.exists() {
liveness.armed_dirs.remove(vd);
} else if !liveness.armed_dirs.contains(vd)
&& watcher.watch(vd, RecursiveMode::NonRecursive).is_ok()
{
liveness.armed_dirs.insert(vd.to_path_buf());
}
}
let recovery = liveness.first_tick
|| (root_now_exists && !root_ok)
|| external_recovery
|| (liveness.root_was_missing && root_now_exists);
liveness.first_tick = false;
liveness.root_was_missing = !root_now_exists;
liveness.missing_external_dirs = now_missing_external;
let found = scan_directory(ctx, state, recovery);
if !found.paths.is_empty() || found.vars_changed {
rebuild_dir_batch(ctx, &found.paths, found.vars_changed, state, None);
arm_external_dirs_after_rebuild(ctx, watcher, liveness, state);
}
}
fn scan_directory(ctx: &DirWatchCtx, state: &mut DirWatchState, walk: bool) -> Batch {
let watched = state.watched_set();
let mut paths: BTreeSet<PathBuf> = watched
.iter()
.filter(|p| path_state_differs(p, &state.last_mtimes))
.cloned()
.collect();
let vars_changed = state
.vars_file
.as_ref()
.is_some_and(|vars| paths.remove(vars));
if walk {
let current: BTreeSet<PathBuf> = collect_mds_files(
&ctx.root.canonical,
MAX_COLLECT_DEPTH,
ctx.exclude_prefix.as_deref(),
)
.into_iter()
.map(|p| graph_key(&p))
.collect();
paths.extend(current.difference(&state.known_files).cloned());
paths.extend(state.known_files.difference(¤t).cloned());
state.known_files = current;
}
Batch {
paths,
vars_changed,
}
}
fn rebuild_dir_batch(
ctx: &DirWatchCtx,
batch: &BTreeSet<PathBuf>,
vars_changed: bool,
state: &mut DirWatchState,
due: Option<Instant>,
) {
let batch = Batch {
paths: batch.clone(),
vars_changed,
};
run_dir_batch(ctx, batch, state, due);
end_rebuild_clear(&state.hold);
}
fn run_dir_batch(ctx: &DirWatchCtx, batch: Batch, state: &mut DirWatchState, due: Option<Instant>) {
ctx.working_dir.restore_if_recreated();
let root = ctx.root.canonical.as_path();
let errored_sources = state
.errored
.iter()
.filter(|path| names_a_source(root, path));
let look = look_at(
state
.baselined_paths()
.chain(&batch.paths)
.chain(errored_sources),
);
let emptied: BTreeSet<PathBuf> = emptied_in(&look, &state.last_mtimes).cloned().collect();
let verdict = state
.hold
.on_rebuild(!emptied.is_empty(), not_before(Instant::now(), due));
debug_assert!(
due.is_none() || verdict == HoldVerdict::Compile,
"a held rebuild's deadline ends its hold"
);
let batch = join_emptied(batch, &emptied, state.vars_file.as_deref());
if verdict == HoldVerdict::Hold {
state.held.hold(&batch, root);
settle(SettleInto::Dir(state), None, Settle::Defer);
return;
}
state.last_mtimes.extend(look);
let batch = state.held.release(batch);
pause_after_look();
let resolved = match build_runtime_vars(RuntimeVarArgs {
vars: ctx.vars_path_typed.clone(),
set_vars: ctx.static_set_vars.clone(),
set_string_vars: ctx.static_set_string_vars.clone(),
}) {
Ok(v) => v,
Err(e) => {
if state.hold_after_vars_load_failed(&batch, root) {
settle(SettleInto::Dir(state), None, Settle::Defer);
return;
}
state.held.carry(&batch, root);
settle(SettleInto::Dir(state), Some(e), Settle::Rebaseline);
return;
}
};
process_dir_batch(
&batch.paths,
batch.vars_changed,
&mut BatchCtx {
watch_root: &ctx.root,
output_base: &ctx.output_base,
vars: BatchVars::of(&resolved),
quiet: ctx.quiet,
},
state,
);
}
enum DirEventOutcome {
Skip,
Stop,
Done,
}
fn handle_fs_event_dir(
msg: Msg,
ctx: &DirWatchCtx,
rx: &mpsc::Receiver<Msg>,
state: &mut DirWatchState,
) -> DirEventOutcome {
let mut changed: BTreeSet<PathBuf> = BTreeSet::new();
let mut rescan = false;
let interrupted = match msg {
Msg::Interrupt => true,
Msg::Fs(Err(e)) => {
eprint_warning(&format!(
"warning: watch error: {}",
safe_inline(notify_cause(&e))
));
return DirEventOutcome::Skip;
}
Msg::Fs(Ok(event)) => {
if is_content_event(&event.kind) {
rescan = event.need_rescan();
for p in event.paths {
changed.insert(p);
}
}
false
}
};
if interrupted {
return DirEventOutcome::Stop;
}
let drained = drain_debounce(rx, ctx.debounce_ms);
if drained.interrupted() {
return DirEventOutcome::Stop;
}
changed.extend(drained.paths);
rescan |= drained.rescan;
let mut vars_changed = ctx
.vars_path
.as_deref()
.map(|vf| changed.contains(vf))
.unwrap_or(false);
if let OutputBase::Dir {
canonical: ref od, ..
} = ctx.output_base
{
changed.retain(|p| !p.starts_with(od));
}
changed.retain(|p| !is_within_default_excluded_dir(&ctx.root.canonical, p));
let dependencies: OnceCell<HashSet<&PathBuf>> = OnceCell::new();
let mut mds_changed: BTreeSet<PathBuf> = changed
.iter()
.filter_map(|p| {
let key = graph_key(p);
let admitted = (has_mds_extension(p)
&& classify(&ctx.root.canonical, p, &state.external_dep_dirs) != Node::Unrelated)
|| dependencies
.get_or_init(|| state.forward_deps.values().flatten().collect())
.contains(&key);
admitted.then_some(key)
})
.collect();
if rescan {
let found = scan_directory(ctx, state, true);
mds_changed.extend(found.paths);
vars_changed |= found.vars_changed;
}
if mds_changed.is_empty() && !vars_changed {
return DirEventOutcome::Skip; }
if ctx.clear {
crate::output::ask_clear();
}
rebuild_dir_batch(ctx, &mds_changed, vars_changed, state, None);
DirEventOutcome::Done
}
fn run_watch_dir(root: WatchedPath, args: SessionArgs) -> Result<()> {
let armed = dir_startup::arm_pre_read(root, args)?;
let compiled = dir_startup::startup_compile(armed)?;
dir_startup::arm_deps_and_seed(compiled).go_live();
Ok(())
}
mod dir_startup {
use std::collections::{BTreeSet, HashMap, HashSet};
use std::ops::ControlFlow;
use std::path::PathBuf;
use std::sync::mpsc;
use std::time::{Duration, Instant};
use miette::Result;
use notify::{RecommendedWatcher, RecursiveMode, Watcher};
use crate::build::{
build_runtime_vars, emit_duplicate_var_warnings, load_config, run_reads, source_inputs,
write_output, ProjectConfig, RuntimeVarArgs,
};
use crate::output::{
collect_mds_files, eprint_warning, is_partial, notify_cause, output_path_for, safe_inline,
safe_path, OutputBase,
};
use super::{
arm_external_dep_dirs, arm_external_dirs_after_rebuild, baseline_path,
canonicalize_vars_path, extra_vars_dir, graph_key, graph_keys, handle_fs_event_dir, live,
liveness_probe_dir, rebuild_dir_batch, resolve_output_base, settle_startup_error,
shown_watched_dir, snapshot_state, startup_race_probe, DirEventOutcome, DirWatchCtx,
DirWatchState, EmptyHold, FileStamp, HeldBatch, LivenessState, Msg, OutDirAnchor,
SessionArgs, StampMap, StartupInto, StopReason, WatchedPath, WorkingDir, MAX_COLLECT_DEPTH,
};
pub(super) struct Armed {
root: WatchedPath,
out_dir: Option<PathBuf>,
working_dir: WorkingDir,
config: Option<ProjectConfig>,
vars_path: Option<PathBuf>,
vars_path_typed: Option<PathBuf>,
static_set_vars: Vec<(String, String)>,
static_set_string_vars: Vec<(String, String)>,
output_base: OutputBase,
exclude_prefix: Option<PathBuf>,
vars_dir_extra: Option<PathBuf>,
armed_dirs: BTreeSet<PathBuf>,
quiet: bool,
clear: bool,
debounce_ms: u64,
tick: Option<Duration>,
tx: mpsc::Sender<Msg>,
rx: mpsc::Receiver<Msg>,
watcher: RecommendedWatcher,
}
pub(super) struct Compiled {
armed: Armed,
state: DirWatchState,
pre_mtimes: StampMap,
}
pub(super) struct Seeded {
tx: mpsc::Sender<Msg>,
rx: mpsc::Receiver<Msg>,
tick: Option<Duration>,
session: DirSession,
}
struct DirSession {
ctx: DirWatchCtx,
watcher: RecommendedWatcher,
state: DirWatchState,
liveness: LivenessState,
}
pub(super) fn arm_pre_read(watch_root: WatchedPath, args: SessionArgs) -> Result<Armed> {
let SessionArgs {
out_dir,
vars,
set_vars,
set_string_vars,
clear,
debounce_ms,
quiet,
tick,
} = args;
let working_dir = WorkingDir::record();
let root = watch_root.canonical.as_path();
let config = load_config(&watch_root.typed)?;
let vars_path_typed = vars.clone();
let vars_path = canonicalize_vars_path(vars).map_err(miette::Error::from)?;
let static_set_vars = set_vars;
let static_set_string_vars = set_string_vars;
let output_base = resolve_output_base(out_dir.as_ref(), &config)?;
let exclude_prefix: Option<PathBuf> = match &output_base {
OutputBase::Dir { canonical: d, .. } if d.starts_with(root) => Some(d.clone()),
_ => None,
};
if !quiet {
crate::output::ewriteln!("Watching directory {}", safe_path(&watch_root.typed));
}
let vars_dir_extra: Option<PathBuf> = vars_path.as_deref().and_then(|vf| {
let parent = vf.parent()?;
if !parent.starts_with(root) {
Some(parent.to_path_buf())
} else {
None
}
});
let vars_dir = extra_vars_dir(vars_dir_extra.as_deref(), vars_path_typed.as_deref());
let (tx, rx) = mpsc::channel::<Msg>();
let tx_fs = tx.clone();
let mut watcher = RecommendedWatcher::new(
move |res| {
crate::output::panic_in_handler("notify");
let _ = tx_fs.send(Msg::Fs(res));
},
notify::Config::default(),
)
.map_err(|e| {
miette::miette!(
"failed to initialize file watcher: {}",
safe_inline(notify_cause(&e))
)
})?;
watcher.watch(root, RecursiveMode::Recursive).map_err(|e| {
miette::miette!(
"failed to watch directory {}: {}\n\
hint: on Linux you may need to increase fs.inotify.max_user_watches",
safe_path(&shown_watched_dir(root, watch_root.root_paths(), vars_dir)),
safe_inline(notify_cause(&e))
)
})?;
let mut armed_dirs = BTreeSet::new();
if let Some(ref vd) = vars_dir_extra {
match watcher.watch(vd, RecursiveMode::NonRecursive) {
Ok(()) => {
armed_dirs.insert(vd.clone());
}
Err(e) => eprint_warning(&format!(
"warning: failed to watch vars directory {}: {}",
safe_path(&shown_watched_dir(vd, watch_root.root_paths(), vars_dir)),
safe_inline(notify_cause(&e))
)),
}
}
Ok(Armed {
root: watch_root,
out_dir,
working_dir,
config,
vars_path,
vars_path_typed,
static_set_vars,
static_set_string_vars,
output_base,
exclude_prefix,
vars_dir_extra,
armed_dirs,
quiet,
clear,
debounce_ms,
tick,
tx,
rx,
watcher,
})
}
pub(super) fn startup_compile(armed: Armed) -> Result<Compiled> {
let Armed {
root: watch_root,
out_dir,
config,
vars_path,
vars_path_typed,
static_set_vars,
static_set_string_vars,
output_base,
exclude_prefix,
..
} = &armed;
let root = watch_root.canonical.as_path();
let quiet = armed.quiet;
let all_files = collect_mds_files(root, MAX_COLLECT_DEPTH, exclude_prefix.as_deref());
let mut pre_mtimes = snapshot_state(
&all_files
.iter()
.map(|p| graph_key(p))
.chain(vars_path.iter().cloned())
.collect::<HashSet<_>>(),
);
let resolved = build_runtime_vars(RuntimeVarArgs {
vars: vars_path_typed.clone(),
set_vars: static_set_vars.clone(),
set_string_vars: static_set_string_vars.clone(),
})?;
emit_duplicate_var_warnings(&resolved, quiet);
let runtime_vars = resolved.vars;
let mut state = DirWatchState {
forward_deps: HashMap::new(),
errored: HashSet::new(),
known_files: BTreeSet::new(),
last_written: HashMap::new(),
outputs: HashMap::new(),
kept: HashMap::new(),
out_dir: None,
reads: run_reads(vars_path.as_deref(), config.as_ref()),
external_dep_dirs: BTreeSet::new(),
vars_file: vars_path.clone(),
last_mtimes: HashMap::new(),
hold: EmptyHold::Off,
held: HeldBatch::default(),
};
for source in &all_files {
let key = graph_key(source);
match watch_root.compile_source(source, runtime_vars.clone(), quiet) {
Ok(compiled) => {
let dep_paths = graph_keys(&compiled.dependencies);
for dep in &dep_paths {
if let Some(parent) = dep.parent() {
if !parent.starts_with(root) {
state.external_dep_dirs.insert(parent.to_path_buf());
}
}
}
for dep in &dep_paths {
baseline_path(dep, &mut pre_mtimes);
}
state.forward_deps.insert(key.clone(), dep_paths);
state.known_files.insert(key.clone());
if !is_partial(source) {
let ext = compiled.kind.extension();
let out = output_path_for(&key, watch_root.root_paths(), output_base, ext);
let inputs = source_inputs(&key, &compiled.dependencies, &state.reads);
if let Err(e) =
write_output(Some(&out), &compiled.content, &inputs, quiet, true)
{
settle_startup_error(StartupInto::Dir(&mut state), Some(e), &key);
} else {
state.wrote(&key, &out, compiled.content);
}
}
}
Err(failure) => {
settle_startup_error(StartupInto::Dir(&mut state), failure.into_report(), &key);
state.known_files.insert(key);
}
}
}
state.out_dir = OutDirAnchor::record(out_dir.as_deref(), config.as_ref());
Ok(Compiled {
armed,
state,
pre_mtimes,
})
}
pub(super) fn arm_deps_and_seed(compiled: Compiled) -> Seeded {
let Compiled {
armed,
mut state,
pre_mtimes,
} = compiled;
let Armed {
root: watch_root,
out_dir: _,
working_dir,
config: _,
vars_path,
vars_path_typed,
static_set_vars,
static_set_string_vars,
output_base,
exclude_prefix,
vars_dir_extra,
mut armed_dirs,
quiet,
clear,
debounce_ms,
tick,
tx,
rx,
mut watcher,
} = armed;
let root = watch_root.canonical.as_path();
startup_race_probe();
let mut failing_dirs = BTreeSet::new();
arm_external_dep_dirs(
&state.external_dep_dirs,
&mut armed_dirs,
&mut failing_dirs,
|dir| watcher.watch(dir, RecursiveMode::NonRecursive),
watch_root.root_paths(),
extra_vars_dir(vars_dir_extra.as_deref(), vars_path_typed.as_deref()),
);
let mut last_mtimes = snapshot_state(&state.watched_set());
let witness: Option<(PathBuf, FileStamp)> =
pre_mtimes.keys().min().map(|p| (p.clone(), pre_mtimes[p]));
last_mtimes.extend(pre_mtimes);
if let Some((path, pre)) = witness {
debug_assert_eq!(
last_mtimes.get(&path).copied(),
Some(pre),
"baseline merge inverted: a pre-compile (mtime, size) must survive the merge \
with the post-compile snapshot, or an edit made during startup can never \
register as a difference on the idle tick"
);
}
state.last_mtimes = last_mtimes;
let liveness = LivenessState {
first_tick: true,
root_was_missing: !root.exists(),
root_armed: root.exists(),
missing_external_dirs: state
.external_dep_dirs
.iter()
.filter(|d| !d.exists())
.cloned()
.collect(),
armed_dirs,
failing_dirs,
};
let ctx = DirWatchCtx {
root: watch_root,
working_dir,
vars_path,
vars_path_typed,
static_set_vars,
static_set_string_vars,
output_base,
exclude_prefix,
vars_dir_extra,
clear,
debounce_ms,
quiet,
};
Seeded {
tx,
rx,
tick,
session: DirSession {
ctx,
watcher,
state,
liveness,
},
}
}
impl Seeded {
pub(super) fn go_live(self) {
let Seeded {
tx,
rx,
tick,
session,
} = self;
live::run_session(tx, rx, tick, session);
}
}
impl live::Session for DirSession {
fn is_quiet(&self) -> bool {
self.ctx.quiet
}
fn hold_deadline(&self) -> Option<Instant> {
self.state.hold.deadline()
}
fn on_tick(&mut self) -> ControlFlow<StopReason> {
liveness_probe_dir(
&self.ctx,
&mut self.watcher,
&mut self.liveness,
&mut self.state,
);
ControlFlow::Continue(())
}
fn on_hold_due(&mut self) -> ControlFlow<StopReason> {
let due = self.state.hold.deadline();
rebuild_dir_batch(&self.ctx, &BTreeSet::new(), false, &mut self.state, due);
arm_external_dirs_after_rebuild(
&self.ctx,
&mut self.watcher,
&mut self.liveness,
&self.state,
);
ControlFlow::Continue(())
}
fn on_message(&mut self, msg: Msg, rx: &mpsc::Receiver<Msg>) -> ControlFlow<StopReason> {
match handle_fs_event_dir(msg, &self.ctx, rx, &mut self.state) {
DirEventOutcome::Skip => ControlFlow::Continue(()),
DirEventOutcome::Done => {
arm_external_dirs_after_rebuild(
&self.ctx,
&mut self.watcher,
&mut self.liveness,
&self.state,
);
ControlFlow::Continue(())
}
DirEventOutcome::Stop => ControlFlow::Break(StopReason::Interrupted),
}
}
}
}
fn process_dir_batch(
changed: &BTreeSet<PathBuf>,
vars_changed: bool,
ctx: &mut BatchCtx<'_>,
state: &mut DirWatchState,
) {
if vars_changed {
process_dir_batch_vars_changed(changed, ctx, state);
} else {
process_dir_batch_incremental(changed, ctx, state);
}
state.rebaseline();
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Node {
Source,
Partial,
InRootModule,
ExternalDep,
ExcludedDep,
Unrelated,
}
impl Node {
fn is_source(self) -> bool {
matches!(self, Node::Source | Node::Partial)
}
}
fn has_mds_extension(path: &Path) -> bool {
path.extension().is_some_and(|ext| ext == "mds")
}
fn classify(root: &Path, path: &Path, external_dirs: &BTreeSet<PathBuf>) -> Node {
if path.starts_with(root) {
if is_within_default_excluded_dir(root, path) {
Node::ExcludedDep
} else if !has_mds_extension(path) {
Node::InRootModule
} else if is_partial(path) {
Node::Partial
} else {
Node::Source
}
} else if external_dirs
.iter()
.any(|dir| path.parent() == Some(dir.as_path()))
{
Node::ExternalDep
} else {
Node::Unrelated
}
}
fn names_a_source(root: &Path, path: &Path) -> bool {
classify(root, path, &BTreeSet::new()).is_source()
}
fn process_dir_batch_vars_changed(
changed: &BTreeSet<PathBuf>,
ctx: &mut BatchCtx<'_>,
state: &mut DirWatchState,
) {
let BatchCtx {
watch_root,
output_base,
quiet,
..
} = *ctx;
let root = watch_root.canonical.as_path();
let all_sources: BTreeSet<PathBuf> = state
.known_files
.iter()
.chain(
state
.errored
.iter()
.chain(changed)
.filter(|path| names_a_source(root, path)),
)
.cloned()
.collect();
for del_src in all_sources.iter().filter(|p| !p.exists()) {
state.retire_deleted(del_src, watch_root, output_base, quiet);
}
let mut previous = std::mem::take(&mut state.forward_deps);
state.errored.clear();
for src in &all_sources {
if !src.exists() {
state.retire_deleted(src, watch_root, output_base, quiet);
continue;
}
if let Some(deps) = previous.remove(src) {
state.forward_deps.insert(src.clone(), deps);
}
compile_one_source(src, ctx, state);
}
state.external_dep_dirs = state.dep_dirs_outside(root);
let (present, gone): (BTreeSet<PathBuf>, BTreeSet<PathBuf>) =
all_sources.into_iter().partition(|p| p.exists());
for src in &gone {
state.retire_deleted(src, watch_root, output_base, quiet);
}
state.known_files = present;
}
fn refresh_dependency(src: &Path, ctx: &BatchCtx<'_>, state: &mut DirWatchState) {
match ctx
.watch_root
.compile_source(src, ctx.vars.map.clone(), true)
{
Ok(compiled) => {
state
.forward_deps
.insert(src.to_path_buf(), graph_keys(&compiled.dependencies));
state.errored.remove(src);
}
Err(failure) => {
settle(
SettleInto::Dir(state),
failure.into_report(),
Settle::MarkErrored(src),
);
}
}
}
fn process_dir_batch_incremental(
changed: &BTreeSet<PathBuf>,
ctx: &mut BatchCtx<'_>,
state: &mut DirWatchState,
) {
let BatchCtx {
watch_root,
output_base,
quiet,
..
} = *ctx;
let root = watch_root.canonical.as_path();
let (existing, deleted): (BTreeSet<PathBuf>, BTreeSet<PathBuf>) =
changed.iter().cloned().partition(|p| p.exists());
let has_real_change = !existing.is_empty() || !deleted.is_empty();
let mut seeds: BTreeSet<PathBuf> = existing.union(&deleted).cloned().collect();
if has_real_change {
seeds.extend(state.errored.iter().cloned());
}
if seeds.is_empty() {
return;
}
let affected = affected_sources(&state.forward_deps, &seeds);
pause_after_batch_split();
for src in &affected {
let node = classify(root, src, &state.external_dep_dirs);
if node == Node::Unrelated {
continue;
}
if !src.exists() {
if !deleted.contains(src) {
if node == Node::ExternalDep {
state.forget(src);
} else {
state.retire_deleted(src, watch_root, output_base, quiet);
}
}
continue;
}
match node {
Node::Source | Node::Partial => compile_one_source(src, ctx, state),
Node::ExternalDep | Node::ExcludedDep if has_mds_extension(src) => {
refresh_dependency(src, ctx, state)
}
Node::InRootModule | Node::ExternalDep | Node::ExcludedDep | Node::Unrelated => {}
}
}
for del_src in &deleted {
state.retire_deleted(del_src, watch_root, output_base, quiet);
}
state.external_dep_dirs = state.dep_dirs_outside(root);
}
#[cfg(debug_assertions)]
mod batch_pause_trigger {
use std::path::PathBuf;
use std::time::Duration;
use crate::output::WriteTarget;
use crate::write::{atomic_write_file, Durability, Parents};
const VARIABLE: &str = "MDS_TEST_PAUSE_AFTER_BATCH_SPLIT";
pub(super) const LOOK_VARIABLE: &str = "MDS_TEST_PAUSE_AFTER_LOOK";
const READ_VARIABLE: &str = "MDS_TEST_PAUSE_AFTER_READ";
const COMPILE_VARIABLE: &str = "MDS_TEST_PAUSE_BEFORE_WATCH_COMPILE";
const POLL: Duration = Duration::from_millis(5);
const MAX_POLLS: u32 = 2_000;
pub(super) fn pause_after_batch_split() {
pause_on(VARIABLE);
}
pub(super) fn pause_after_look() {
pause_on(LOOK_VARIABLE);
}
pub(super) fn pause_after_read() {
pause_on(READ_VARIABLE);
}
pub(super) fn pause_before_compile() {
pause_on(COMPILE_VARIABLE);
}
fn pause_on(variable: &str) {
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)]
use batch_pause_trigger::{
pause_after_batch_split, pause_after_look, pause_after_read, pause_before_compile,
};
#[cfg(not(debug_assertions))]
fn pause_after_batch_split() {}
#[cfg(not(debug_assertions))]
fn pause_after_look() {}
#[cfg(not(debug_assertions))]
fn pause_after_read() {}
#[cfg(not(debug_assertions))]
fn pause_before_compile() {}
#[cfg(test)]
mod tests {
use super::*;
use crate::output::child_process;
use std::path::PathBuf;
#[test]
fn canonicalize_vars_path_refuses_a_forbidden_char_before_existence() {
let dir = tempfile::tempdir().unwrap();
for ch in ['\t', '\x1b', '\n', '\u{202E}'] {
let hostile = dir.path().join(format!("v{ch}q")).join("x.json");
let err = canonicalize_vars_path(Some(hostile.clone()))
.expect_err("a hostile --vars path is refused");
let s = err.serialize();
assert_eq!(s.code, "mds::io", "U+{:04X}", u32::from(ch));
assert!(
s.message.starts_with(&format!(
"path contains forbidden character U+{:04X}: \"",
u32::from(ch)
)),
"got: {}",
s.message
);
assert!(!s.message.contains(ch), "raw char: {:?}", s.message);
}
let clean = dir.path().join("missing.json");
assert_eq!(
canonicalize_vars_path(Some(clean.clone())).unwrap(),
Some(clean),
"control: a clean missing --vars path is kept"
);
}
#[test]
fn dirs_to_watch_deduplicates_parents() {
let entry = PathBuf::from("/project/src/entry.mds");
let deps = vec![
PathBuf::from("/project/src/a.mds"),
PathBuf::from("/project/src/b.mds"), PathBuf::from("/project/lib/c.mds"), ];
let vars = PathBuf::from("/project/vars.json");
let dirs = dirs_to_watch(&entry, &deps, Some(&vars));
assert!(dirs.contains(&PathBuf::from("/project/src")));
assert!(dirs.contains(&PathBuf::from("/project/lib")));
assert!(dirs.contains(&PathBuf::from("/project")));
assert_eq!(dirs.len(), 3, "should deduplicate identical parent dirs");
}
#[test]
fn files_of_interest_contains_all() {
let entry = PathBuf::from("/a/entry.mds");
let deps = vec![PathBuf::from("/a/dep1.mds"), PathBuf::from("/b/dep2.mds")];
let vars = PathBuf::from("/c/vars.json");
let foi = files_of_interest(&entry, &deps, Some(&vars));
assert!(foi.contains(&PathBuf::from("/a/entry.mds")));
assert!(foi.contains(&PathBuf::from("/a/dep1.mds")));
assert!(foi.contains(&PathBuf::from("/b/dep2.mds")));
assert!(foi.contains(&PathBuf::from("/c/vars.json")));
assert_eq!(foi.len(), 4);
}
#[cfg(unix)]
#[test]
fn distinct_non_utf8_paths_stay_distinct_graph_and_output_keys() {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let dir = tempfile::tempdir().unwrap();
let a = dir.path().join(OsStr::from_bytes(b"\xff.mds"));
let b = dir.path().join(OsStr::from_bytes(b"\xfe.mds"));
assert_ne!(a, b);
assert_eq!(a.display().to_string(), b.display().to_string());
let keys = graph_keys(&[a.clone(), b.clone()]);
assert_eq!(keys.len(), 2);
assert_ne!(keys[0], keys[1], "two dependencies, two graph keys");
assert_eq!(keys[0].file_name(), a.file_name(), "a key keeps its bytes");
let key = |p: &Path| OutputKey::of(Some(&WriteTarget::as_typed(p.with_extension("md"))));
assert_ne!(key(&a), key(&b), "two outputs, two dedup keys");
assert_ne!(key(&a), OutputKey::Stdout);
assert_eq!(OutputKey::of(None), OutputKey::Stdout);
}
#[test]
fn a_compile_s_dependencies_are_keyed_as_notify_reports_them() {
let dir = tempfile::TempDir::new().unwrap();
std::fs::write(
dir.path().join("main.mds"),
"@import \"./lib.mds\" as lib\n{{lib.hi()}}\n",
)
.unwrap();
std::fs::write(dir.path().join("lib.mds"), "@define hi():\nHi\n@end\n").unwrap();
let main = dir.path().join("main.mds");
let compiled = compile_caught(&main, &main.canonicalize().unwrap(), None, true).unwrap();
let reported = mds::compile_with_deps(&main, None).unwrap().dependencies;
assert_eq!(
compiled.dependencies, reported,
"the compiler's list, passed on as it is"
);
assert_eq!(
graph_keys(&compiled.dependencies),
[graph_key(&dir.path().join("lib.mds"))],
"the dependency is keyed by the watch graph key of the imported file"
);
#[cfg(windows)]
{
assert!(graph_keys(&reported)[0]
.to_string_lossy()
.starts_with(r"\\?\"));
assert!(!reported[0].starts_with(r"\\?\"));
}
}
#[test]
fn a_watched_directory_is_named_as_the_user_typed_it() {
use std::ffi::OsStr;
let entry = WatchedPath {
typed: PathBuf::from("page.mds"),
canonical: PathBuf::from("/project/page.mds"),
what: Watched::Entry,
};
let vars = vars_dir_paths(
Some(Path::new("/elsewhere/v.json")),
Some(Path::new("../v.json")),
);
let shown = |dir: &str| shown_watched_dir(Path::new(dir), entry.dir_paths(), vars);
assert_eq!(shown("/project").as_os_str(), OsStr::new("."));
assert_eq!(shown("/elsewhere").as_os_str(), OsStr::new(".."));
assert_eq!(shown("/project/lib"), Path::new("./lib"));
assert_eq!(shown("/project/lib/deep"), Path::new("./lib/deep"));
assert_eq!(shown("/lib"), Path::new("/lib"));
assert_eq!(shown("/elsewhere/sub"), Path::new("/elsewhere/sub"));
assert_eq!(
shown_watched_dir(Path::new("/elsewhere"), entry.dir_paths(), None),
Path::new("/elsewhere")
);
let beside = vars_dir_paths(
Some(Path::new("/project/v.json")),
Some(Path::new("../project/v.json")),
);
assert_eq!(
shown_watched_dir(Path::new("/project"), entry.dir_paths(), beside).as_os_str(),
OsStr::new(".")
);
let root = WatchedPath {
typed: PathBuf::from("src"),
canonical: PathBuf::from("/project/src"),
what: Watched::Root,
};
let vars = Some(RootPaths {
typed: Path::new("cfg"),
walked: Path::new("cfg"),
});
let shown = |dir: &str| shown_watched_dir(Path::new(dir), root.root_paths(), vars);
assert_eq!(shown("/project/src").as_os_str(), OsStr::new("src"));
assert_eq!(shown("/project/src/sub"), Path::new("src/sub"));
assert_eq!(shown("cfg").as_os_str(), OsStr::new("cfg"));
assert_eq!(shown("/project/shared"), Path::new("/project/shared"));
}
#[test]
fn an_external_dep_dir_is_armed_only_once_its_watch_succeeds() {
let scratch = tempfile::tempdir().unwrap();
let (ok, refused) = (scratch.path().join("ok"), scratch.path().join("refused"));
std::fs::create_dir(&ok).unwrap();
std::fs::create_dir(&refused).unwrap();
let dirs = BTreeSet::from([ok.clone(), refused.clone()]);
let root = RootPaths {
typed: Path::new("src"),
walked: Path::new("/project/src"),
};
let (mut armed, mut failing) = (BTreeSet::new(), BTreeSet::new());
let mut watched = Vec::new();
let first = |dir: &Path| {
watched.push(dir.to_path_buf());
if dir == refused {
Err(notify::Error::generic("refused"))
} else {
Ok(())
}
};
arm_external_dep_dirs(&dirs, &mut armed, &mut failing, first, root, None);
assert!(ok.is_dir() && refused.is_dir());
assert_eq!(watched, [ok.clone(), refused.clone()]);
assert_eq!(
armed,
BTreeSet::from([ok.clone()]),
"only the directory whose watch succeeded is armed"
);
let mut again = Vec::new();
let second = |dir: &Path| {
again.push(dir.to_path_buf());
Ok(())
};
arm_external_dep_dirs(&dirs, &mut armed, &mut failing, second, root, None);
assert_eq!(
again,
[refused],
"the refused directory is tried again, the armed one is not"
);
assert_eq!(armed, dirs);
}
#[test]
fn is_content_event_filters_access_passes_others() {
use notify::event::{AccessKind, AccessMode, CreateKind, ModifyKind, RemoveKind};
assert!(!is_content_event(¬ify::EventKind::Access(
AccessKind::Read
)));
assert!(!is_content_event(¬ify::EventKind::Access(
AccessKind::Open(AccessMode::Read)
)));
assert!(!is_content_event(¬ify::EventKind::Access(
AccessKind::Close(AccessMode::Read)
)));
assert!(!is_content_event(¬ify::EventKind::Access(
AccessKind::Close(AccessMode::Write)
)));
assert!(!is_content_event(¬ify::EventKind::Access(
AccessKind::Any
)));
assert!(!is_content_event(¬ify::EventKind::Access(
AccessKind::Other
)));
assert!(is_content_event(¬ify::EventKind::Modify(
ModifyKind::Any
)));
assert!(is_content_event(¬ify::EventKind::Modify(
ModifyKind::Data(notify::event::DataChange::Any)
)));
assert!(is_content_event(¬ify::EventKind::Create(
CreateKind::File
)));
assert!(is_content_event(¬ify::EventKind::Remove(
RemoveKind::File
)));
assert!(is_content_event(¬ify::EventKind::Any));
assert!(is_content_event(¬ify::EventKind::Other));
}
#[test]
fn event_is_relevant_matches_and_rejects() {
let watched_path = PathBuf::from("/project/src/entry.mds");
let sibling = PathBuf::from("/project/src/other.mds");
let mut watched = HashSet::new();
watched.insert(watched_path.clone());
let relevant_event = notify::Event {
kind: notify::EventKind::Modify(notify::event::ModifyKind::Any),
paths: vec![watched_path.clone()],
attrs: Default::default(),
};
let irrelevant_event = notify::Event {
kind: notify::EventKind::Modify(notify::event::ModifyKind::Any),
paths: vec![sibling],
attrs: Default::default(),
};
assert!(event_is_relevant(&relevant_event, &watched));
assert!(!event_is_relevant(&irrelevant_event, &watched));
}
#[test]
fn event_is_relevant_matches_a_case_only_rename_of_a_watched_file() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().canonicalize().unwrap();
let watched_path = root.join("Main.mds");
std::fs::write(&watched_path, "watched").unwrap();
let case_insensitive = root.join("MAIN.mds").exists();
let other_case = root.join("main.mds");
let unrelated = root.join("other.mds");
let output = root.join("Main.md");
std::fs::write(&unrelated, "unrelated").unwrap();
std::fs::write(&output, "output").unwrap();
let watched = HashSet::from([watched_path.clone()]);
let event = |p: &Path| notify::Event {
kind: notify::EventKind::Modify(notify::event::ModifyKind::Any),
paths: vec![p.to_path_buf()],
attrs: Default::default(),
};
if case_insensitive {
std::fs::rename(&watched_path, &other_case).unwrap();
let names: Vec<String> = std::fs::read_dir(&root)
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
.collect();
assert!(
names.iter().any(|n| n == "main.mds") && !names.iter().any(|n| n == "Main.mds"),
"arm: case-insensitive volume. The rename must change the stored name, or \
the event below names the old spelling and never reaches the case-only \
path: {names:?}"
);
assert!(
event_is_relevant(&event(&other_case), &watched),
"arm: case-insensitive volume. An event for the new spelling must match the \
watched old spelling"
);
} else {
std::fs::write(&other_case, "another file").unwrap();
assert_eq!(
std::fs::read_to_string(&watched_path).unwrap(),
"watched",
"arm: case-sensitive volume. Main.mds and main.mds must be two files on this \
volume"
);
assert!(
!event_is_relevant(&event(&other_case), &watched),
"arm: case-sensitive volume. An event for another file whose name differs \
only in case must not match"
);
assert!(
event_is_relevant(&event(&watched_path), &watched),
"arm: case-sensitive volume. An event for the watched file must match"
);
}
let arm = if case_insensitive {
"case-insensitive"
} else {
"case-sensitive"
};
assert!(
!event_is_relevant(&event(&unrelated), &watched),
"arm: {arm} volume. An event for an unrelated file must not match"
);
assert!(
!event_is_relevant(&event(&output), &watched),
"arm: {arm} volume. An event for the output beside the watched file must not match"
);
}
#[test]
fn collect_mds_files_recurses_and_depth_bounded() {
let dir = tempfile::tempdir().unwrap();
let sub = dir.path().join("sub");
std::fs::create_dir(&sub).unwrap();
let deep = sub.join("deep");
std::fs::create_dir(&deep).unwrap();
std::fs::write(dir.path().join("a.mds"), "Hello!").unwrap();
std::fs::write(sub.join("b.mds"), "World!").unwrap();
std::fs::write(deep.join("c.mds"), "Deep!").unwrap();
std::fs::write(dir.path().join("ignore.txt"), "not mds").unwrap();
let all = collect_mds_files(dir.path(), 64, None);
let names: Vec<_> = all
.iter()
.filter_map(|p| p.file_name().and_then(|n| n.to_str()))
.collect();
assert!(names.contains(&"a.mds"), "should find top-level a.mds");
assert!(names.contains(&"b.mds"), "should find sub/b.mds");
assert!(names.contains(&"c.mds"), "should find deep/c.mds");
assert!(!names.contains(&"ignore.txt"), "should skip non-.mds files");
let top_only = collect_mds_files(dir.path(), 0, None);
assert_eq!(top_only.len(), 1, "depth=0 should return only root files");
}
#[test]
fn collect_mds_files_excludes_prefix() {
let dir = tempfile::tempdir().unwrap();
let out = dir.path().join("out");
std::fs::create_dir(&out).unwrap();
std::fs::write(dir.path().join("a.mds"), "A").unwrap();
std::fs::write(out.join("b.mds"), "B (should be excluded)").unwrap();
let files = collect_mds_files(dir.path(), 64, Some(&out));
let names: Vec<_> = files
.iter()
.filter_map(|p| p.file_name().and_then(|n| n.to_str()))
.collect();
assert!(names.contains(&"a.mds"), "a.mds should be included");
assert!(
!names.contains(&"b.mds"),
"b.mds inside out/ should be excluded"
);
}
fn dir_base(d: impl Into<PathBuf>) -> OutputBase {
let d = d.into();
OutputBase::Dir {
canonical: d.clone(),
shown: d,
below_anchor: 0,
}
}
fn project_config(output_dir: &str) -> Option<ProjectConfig> {
use crate::build::{BuildConfig, MdsConfig};
Some(ProjectConfig {
config: MdsConfig {
build: BuildConfig {
output_dir: Some(output_dir.to_string()),
..Default::default()
},
..Default::default()
},
dir: PathBuf::from("/project"),
shown_dir: PathBuf::from("."),
})
}
#[test]
fn output_path_for_mirrors_subtree() {
let root = PathBuf::from("/root");
let source = PathBuf::from("/root/a/b/foo.mds");
let base = dir_base("/out");
let result = output_path_for(&source, RootPaths::as_typed(&root), &base, "md");
assert_eq!(result.path, PathBuf::from("/out/a/b/foo.md"));
}
#[test]
fn output_path_for_no_stem_collision() {
let root = PathBuf::from("/root");
let a = PathBuf::from("/root/a/x.mds");
let b = PathBuf::from("/root/b/x.mds");
let base = dir_base("/out");
assert_ne!(
output_path_for(&a, RootPaths::as_typed(&root), &base, "md"),
output_path_for(&b, RootPaths::as_typed(&root), &base, "md"),
"two files with the same stem in different subdirs must not collide"
);
assert_eq!(
output_path_for(&a, RootPaths::as_typed(&root), &base, "md").path,
PathBuf::from("/out/a/x.md")
);
assert_eq!(
output_path_for(&b, RootPaths::as_typed(&root), &base, "md").path,
PathBuf::from("/out/b/x.md")
);
}
#[test]
fn output_path_for_next_to_source() {
let root = PathBuf::from("/root");
let source = PathBuf::from("/root/a/b/foo.mds");
let result = output_path_for(
&source,
RootPaths::as_typed(&root),
&OutputBase::NextToSource,
"md",
);
assert_eq!(result.path, PathBuf::from("/root/a/b/foo.md"));
}
#[test]
fn output_path_for_compound_extension() {
let root = PathBuf::from("/root");
let source = PathBuf::from("/root/foo.bar.mds");
let base = dir_base("/out");
let result = output_path_for(&source, RootPaths::as_typed(&root), &base, "md");
assert_eq!(result.path, PathBuf::from("/out/foo.bar.md"));
}
#[test]
fn output_path_for_source_outside_root_stays_contained() {
let root = PathBuf::from("/root");
let source = PathBuf::from("/elsewhere/a/b/foo.mds");
let base = dir_base("/out");
let result = output_path_for(&source, RootPaths::as_typed(&root), &base, "md");
assert!(
result.path.starts_with("/out"),
"output must stay inside out-dir even when source is outside root; got {result:?}"
);
assert_eq!(result.path, PathBuf::from("/out/foo.md"));
}
#[test]
fn resolve_output_base_outdir_wins() {
let tmp = tempfile::tempdir().unwrap();
let d = tmp.path().join("out");
let result = resolve_output_base(Some(&d), &project_config("dist")).unwrap();
assert!(
matches!(result, OutputBase::Dir { ref canonical, ref shown, below_anchor: 0 }
if canonical == &d && shown == &d),
"expected Dir({d:?}), got {result:?}"
);
}
#[test]
fn resolve_output_base_config_used_when_no_outdir() {
let result = resolve_output_base(None, &project_config("dist")).unwrap();
assert!(
matches!(result, OutputBase::Dir { ref canonical, .. }
if canonical == &PathBuf::from("/project/dist")),
"expected Dir(/project/dist), got {result:?}"
);
}
#[test]
fn resolve_output_base_rejects_dotdot() {
let result = resolve_output_base(None, &project_config("../bad"));
assert!(
result.is_err(),
"resolve_output_base must reject output_dir with '..' components"
);
}
#[test]
fn resolve_output_base_default_next_to_source() {
let result = resolve_output_base(None, &None).unwrap();
assert!(matches!(result, OutputBase::NextToSource));
}
#[test]
fn is_partial_detects_underscore_prefix() {
assert!(is_partial(Path::new("/some/dir/_partial.mds")));
assert!(!is_partial(Path::new("/some/dir/normal.mds")));
assert!(!is_partial(Path::new("/some/dir/a_b.mds")));
}
#[test]
fn affected_sources_chain() {
let a = PathBuf::from("/root/a.mds");
let b = PathBuf::from("/root/b.mds");
let c = PathBuf::from("/root/c.mds");
let mut forward_deps = HashMap::new();
forward_deps.insert(a.clone(), vec![b.clone()]);
forward_deps.insert(b.clone(), vec![c.clone()]);
forward_deps.insert(c.clone(), vec![]);
let mut seeds = BTreeSet::new();
seeds.insert(c.clone());
let affected = affected_sources(&forward_deps, &seeds);
let affected_set: HashSet<PathBuf> = affected.into_iter().collect();
assert!(affected_set.contains(&a), "A should be affected");
assert!(affected_set.contains(&b), "B should be affected");
assert!(affected_set.contains(&c), "C (seed) should be in result");
}
#[test]
fn affected_sources_shared_partial() {
let partial = PathBuf::from("/root/_p.mds");
let a = PathBuf::from("/root/a.mds");
let b = PathBuf::from("/root/b.mds");
let mut forward_deps = HashMap::new();
forward_deps.insert(a.clone(), vec![partial.clone()]);
forward_deps.insert(b.clone(), vec![partial.clone()]);
forward_deps.insert(partial.clone(), vec![]);
let mut seeds = BTreeSet::new();
seeds.insert(partial.clone());
let affected = affected_sources(&forward_deps, &seeds);
let affected_set: HashSet<PathBuf> = affected.into_iter().collect();
assert!(affected_set.contains(&a));
assert!(affected_set.contains(&b));
assert!(affected_set.contains(&partial));
}
#[test]
fn affected_sources_cycle_terminates() {
let a = PathBuf::from("/root/a.mds");
let b = PathBuf::from("/root/b.mds");
let mut forward_deps = HashMap::new();
forward_deps.insert(a.clone(), vec![b.clone()]);
forward_deps.insert(b.clone(), vec![a.clone()]);
let mut seeds = BTreeSet::new();
seeds.insert(a.clone());
let affected = affected_sources(&forward_deps, &seeds);
let affected_set: HashSet<PathBuf> = affected.into_iter().collect();
assert!(affected_set.contains(&a));
assert!(affected_set.contains(&b));
}
#[test]
fn affected_sources_seed_not_in_graph() {
let forward_deps: HashMap<PathBuf, Vec<PathBuf>> = HashMap::new();
let lone = PathBuf::from("/root/lone.mds");
let mut seeds = BTreeSet::new();
seeds.insert(lone.clone());
let affected = affected_sources(&forward_deps, &seeds);
assert_eq!(affected, vec![lone]);
}
#[test]
fn affected_sources_dual_role_visited_once() {
let a = PathBuf::from("/root/a.mds");
let b = PathBuf::from("/root/b.mds");
let c = PathBuf::from("/root/c.mds");
let mut forward_deps = HashMap::new();
forward_deps.insert(a.clone(), vec![b.clone()]);
forward_deps.insert(b.clone(), vec![c.clone()]);
forward_deps.insert(c.clone(), vec![]);
let mut seeds = BTreeSet::new();
seeds.insert(c.clone());
let affected = affected_sources(&forward_deps, &seeds);
let b_count = affected.iter().filter(|p| *p == &b).count();
assert_eq!(b_count, 1, "dual-role node B should appear exactly once");
}
#[test]
fn external_recovery_missing_stays_missing_no_recovery() {
let gone = PathBuf::from("/elsewhere/shared");
let prev_missing: BTreeSet<PathBuf> = std::iter::once(gone.clone()).collect();
let statuses = vec![(gone.clone(), false, false)];
let (recovery, now_missing) = external_recovery_decision(&prev_missing, &statuses);
assert!(
!recovery,
"a permanently-missing external dir must NOT trigger a reconcile"
);
assert!(
now_missing.contains(&gone),
"still-missing dir stays tracked"
);
}
#[test]
fn external_recovery_reappear_triggers_recovery() {
let dir = PathBuf::from("/elsewhere/shared");
let prev_missing: BTreeSet<PathBuf> = std::iter::once(dir.clone()).collect();
let statuses = vec![(dir.clone(), true, true)];
let (recovery, now_missing) = external_recovery_decision(&prev_missing, &statuses);
assert!(
recovery,
"a reappeared external dir must trigger a reconcile"
);
assert!(
now_missing.is_empty(),
"reappeared dir no longer tracked as missing"
);
}
#[test]
fn external_recovery_rearm_failure_triggers_recovery() {
let dir = PathBuf::from("/elsewhere/shared");
let prev_missing = BTreeSet::new();
let statuses = vec![(dir.clone(), true, false)];
let (recovery, now_missing) = external_recovery_decision(&prev_missing, &statuses);
assert!(
recovery,
"a failed re-arm of an existing dir must trigger a reconcile"
);
assert!(now_missing.is_empty());
}
#[test]
fn external_recovery_stable_no_recovery() {
let a = PathBuf::from("/ext/a");
let b = PathBuf::from("/ext/b");
let prev_missing = BTreeSet::new();
let statuses = vec![(a, true, true), (b, true, true)];
let (recovery, now_missing) = external_recovery_decision(&prev_missing, &statuses);
assert!(
!recovery,
"stable existing external dirs must not trigger a reconcile"
);
assert!(now_missing.is_empty());
}
#[test]
fn snapshot_and_diff_detect_change() {
let dir = tempfile::tempdir().unwrap();
let f = dir.path().join("test.mds");
std::fs::write(&f, "v1").unwrap();
let paths: HashSet<PathBuf> = std::iter::once(f.clone()).collect();
let snap = snapshot_state(&paths);
assert!(!state_differs(&paths, &snap));
std::fs::write(&f, "v2 — longer").unwrap();
assert!(state_differs(&paths, &snap), "should detect content change");
}
#[test]
fn snapshot_and_diff_detect_same_size_mtime_change() {
let dir = tempfile::tempdir().unwrap();
let f = dir.path().join("test.mds");
std::fs::write(&f, "v1").unwrap();
let paths: HashSet<PathBuf> = std::iter::once(f.clone()).collect();
let snap = snapshot_state(&paths);
let (t0, size0) = snap[&f];
let t0 = t0.expect("mtime must be readable on the test filesystem");
std::fs::write(&f, "v2").unwrap();
let set_mtime = |t: std::time::SystemTime| {
std::fs::OpenOptions::new()
.write(true)
.open(&f)
.unwrap()
.set_modified(t)
.unwrap();
};
assert_eq!(
std::fs::metadata(&f).unwrap().len(),
size0.unwrap(),
"precondition: the rewrite keeps the size, so only mtime can differ"
);
set_mtime(t0);
assert!(
!state_differs(&paths, &snap),
"control: same size and same mtime must compare equal"
);
set_mtime(t0 + Duration::from_secs(2));
assert!(
state_differs(&paths, &snap),
"should detect an mtime-only change"
);
}
#[test]
fn snapshot_detects_disappearing_file() {
let dir = tempfile::tempdir().unwrap();
let f = dir.path().join("gone.mds");
std::fs::write(&f, "initial").unwrap();
let paths: HashSet<PathBuf> = std::iter::once(f.clone()).collect();
let snap = snapshot_state(&paths);
std::fs::remove_file(&f).unwrap();
assert!(
state_differs(&paths, &snap),
"should detect deleted file as changed"
);
}
#[test]
fn clamp_poll_interval_zero_disables_probe() {
assert_eq!(
clamp_poll_interval(0),
None,
"poll_interval=0 must disable the liveness probe (blocking recv)"
);
}
#[test]
fn clamp_poll_interval_one_clamped_to_50ms() {
assert_eq!(
clamp_poll_interval(1),
Some(Duration::from_millis(50)),
"poll_interval=1 must be clamped to the 50ms floor"
);
}
#[test]
fn clamp_poll_interval_exactly_50_unchanged() {
assert_eq!(
clamp_poll_interval(50),
Some(Duration::from_millis(50)),
"poll_interval=50 (at the floor) must pass through unchanged"
);
}
#[test]
fn clamp_poll_interval_above_floor_unchanged() {
assert_eq!(
clamp_poll_interval(1000),
Some(Duration::from_millis(1000)),
"poll_interval=1000 (above floor) must pass through unchanged"
);
}
#[test]
fn clamp_poll_interval_75ms_unchanged() {
assert_eq!(
clamp_poll_interval(75),
Some(Duration::from_millis(75)),
"poll_interval=75 (above floor) must pass through unchanged"
);
}
fn ms(n: u64) -> Duration {
Duration::from_millis(n)
}
fn within_5s<T: Send + 'static>(what: &str, driver: impl FnOnce() -> T + Send + 'static) -> T {
let (done_tx, done_rx) = mpsc::channel();
std::thread::spawn(move || {
let _ = done_tx.send(driver());
});
done_rx
.recv_timeout(Duration::from_secs(5))
.unwrap_or_else(|e| panic!("{what} did not return within 5s ({e:?})"))
}
fn ticks_under_saturation(
interval: Duration,
per_message: Duration,
until: Duration,
) -> Vec<Duration> {
let t0 = Instant::now();
let mut schedule = TickSchedule::start(Some(interval), t0);
let mut now = t0;
let mut ticks = Vec::new();
for _ in 0..10_000 {
if now >= t0 + until {
return ticks;
}
match schedule.poll(now) {
TickPoll::Due => ticks.push(now - t0),
TickPoll::Wait(_) | TickPoll::Never => now += per_message,
}
}
panic!("the replay did not reach {until:?} within 10 000 steps; ticks so far: {ticks:?}");
}
#[test]
fn tick_schedule_comes_due_one_interval_after_it_starts() {
let t0 = Instant::now();
let mut schedule = TickSchedule::start(Some(ms(50)), t0);
assert_eq!(schedule.poll(t0), TickPoll::Wait(ms(50)));
assert_eq!(schedule.poll(t0 + ms(49)), TickPoll::Wait(ms(1)));
assert_eq!(
schedule.poll(t0 + ms(50)),
TickPoll::Due,
"an idle channel must produce a tick one interval in"
);
assert_eq!(
schedule.poll(t0 + ms(50)),
TickPoll::Wait(ms(50)),
"a due tick re-arms one interval after it fired"
);
schedule.rearm(t0 + ms(100));
assert_eq!(schedule.poll(t0 + ms(100)), TickPoll::Wait(ms(50)));
assert_eq!(schedule.poll(t0 + ms(150)), TickPoll::Due);
}
#[test]
fn tick_schedule_is_due_first_under_saturation() {
assert_eq!(
ticks_under_saturation(ms(50), ms(5), ms(210)),
[ms(50), ms(100), ms(150), ms(200)],
"a saturated channel must not postpone a tick past its deadline"
);
assert_eq!(
ticks_under_saturation(ms(50), ms(7), ms(230)),
[ms(56), ms(112), ms(168), ms(224)],
"a tick is due at the first poll at or after its deadline, under saturation too"
);
}
#[test]
fn tick_schedule_rearms_from_the_tick_it_observed() {
let t0 = Instant::now();
let interval = ms(50);
let mut schedule = TickSchedule::start(Some(interval), t0);
assert_eq!(schedule.poll(t0 + ms(50)), TickPoll::Due, "first tick");
assert_eq!(
schedule.poll(t0 + ms(170)),
TickPoll::Due,
"an overdue tick must fire immediately, not wait another interval"
);
assert_eq!(
schedule.poll(t0 + ms(170)),
TickPoll::Wait(interval),
"the tick following an overdue one must wait a full interval, not fire a \
catch-up burst"
);
assert_eq!(schedule.poll(t0 + ms(219)), TickPoll::Wait(ms(1)));
assert_eq!(schedule.poll(t0 + ms(220)), TickPoll::Due);
}
#[test]
fn tick_schedule_without_interval_never_comes_due() {
let t0 = Instant::now();
let mut off = TickSchedule::start(None, t0);
let mut on = TickSchedule::start(Some(ms(50)), t0);
for later in [Duration::ZERO, ms(50), Duration::from_secs(3_600)] {
assert_eq!(off.poll(t0 + later), TickPoll::Never, "at {later:?}");
}
assert_eq!(
on.poll(t0 + ms(50)),
TickPoll::Due,
"positive control: with an interval the same instant is due"
);
}
#[test]
fn tick_clock_without_interval_never_ticks() {
let (tx, rx) = mpsc::channel::<Msg>();
let mut clock = TickClock::new(None);
tx.send(Msg::Interrupt).expect("send failed");
assert!(
matches!(
clock.recv_next(&rx, None),
Ok(Wake::Message(Msg::Interrupt))
),
"with no poll interval the clock must deliver the message, never a tick"
);
drop(tx);
assert!(
matches!(clock.recv_next(&rx, None), Err(mpsc::RecvError)),
"a closed channel must report Disconnected rather than tick forever"
);
}
#[test]
fn tick_clock_serves_a_due_tick_before_a_waiting_message() {
let (tx, rx) = mpsc::channel::<Msg>();
tx.send(Msg::Interrupt).expect("send failed");
let mut clock = TickClock {
schedule: TickSchedule::Every {
interval: Duration::from_secs(3_600),
next: Instant::now(),
},
};
assert!(
matches!(clock.recv_next(&rx, None), Ok(Wake::Tick)),
"a due tick must be served before the message waiting in the channel"
);
assert!(
matches!(
clock.recv_next(&rx, None),
Ok(Wake::Message(Msg::Interrupt))
),
"positive control: the waiting message is delivered next, not lost"
);
drop(tx);
}
#[test]
fn tick_clock_rearms_when_its_wait_runs_out() {
let interval = ms(50);
let (tx, rx) = mpsc::channel::<Msg>();
let t1 = Instant::now();
let (wake, clock, _rx) = within_5s("an idle tick", move || {
let mut clock = TickClock::new(Some(interval));
(clock.recv_next(&rx, None), clock, rx)
});
assert!(
matches!(wake, Ok(Wake::Tick)),
"an idle channel's wait runs out at the tick"
);
let TickSchedule::Every { next, .. } = clock.schedule else {
panic!("a clock started with an interval keeps it");
};
assert!(
next >= t1 + interval * 2,
"the next tick must come due one interval after the wait ran out, not at the \
deadline that has just passed: due {:?} after the clock started, expected at \
least {:?}",
next - t1,
interval * 2
);
drop(tx);
}
#[test]
fn went_empty_is_a_file_with_bytes_found_with_none() {
let stamp = |size: Option<u64>| -> FileStamp { (Some(std::time::UNIX_EPOCH), size) };
assert!(
went_empty(Some(&stamp(Some(5))), &stamp(Some(0))),
"bytes, then none"
);
assert!(
!went_empty(Some(&stamp(Some(0))), &stamp(Some(0))),
"a file empty from the start, or compiled since it was emptied"
);
assert!(
!went_empty(None, &stamp(Some(0))),
"a file the baseline never saw"
);
assert!(
!went_empty(Some(&stamp(None)), &stamp(Some(0))),
"a file the baseline saw missing"
);
assert!(
!went_empty(Some(&stamp(Some(5))), &stamp(None)),
"a file that is gone"
);
assert!(
!went_empty(Some(&stamp(Some(5))), &stamp(Some(3))),
"a file that still has bytes"
);
}
#[test]
fn empty_hold_deadline_is_fixed_at_the_first_empty_observation() {
let t0 = Instant::now();
let mut hold = EmptyHold::default();
assert_eq!(
hold.deadline(),
None,
"nothing is held before a file is emptied"
);
assert_eq!(hold.on_rebuild(true, t0), HoldVerdict::Hold);
assert_eq!(hold.deadline(), Some(t0 + EMPTY_HOLD_DEADLINE));
for k in 1..10u64 {
let now = t0 + ms(100 * k);
assert_eq!(hold.on_rebuild(true, now), HoldVerdict::Hold, "at {now:?}");
assert_eq!(
hold.deadline(),
Some(t0 + EMPTY_HOLD_DEADLINE),
"a rebuild {}ms in must not move the deadline",
100 * k
);
}
let just_before = t0 + EMPTY_HOLD_DEADLINE - Duration::from_nanos(1);
assert_eq!(hold.on_rebuild(true, just_before), HoldVerdict::Hold);
assert_eq!(
hold.on_rebuild(true, t0 + EMPTY_HOLD_DEADLINE),
HoldVerdict::Compile,
"at the deadline the files are compiled as they are"
);
assert_eq!(
hold.deadline(),
None,
"the rebuild at the deadline ends the hold"
);
}
#[test]
fn empty_hold_compiles_an_endless_stream_at_its_first_deadline() {
for (every, compiled_at) in [
(ms(2), ms(1_000)),
(ms(100), ms(1_000)),
(ms(999), ms(1_998)),
] {
let t0 = Instant::now();
let mut hold = EmptyHold::default();
let compiled = (0u32..)
.take(10_000)
.map(|k| t0 + every * k)
.find(|&now| hold.on_rebuild(true, now) == HoldVerdict::Compile);
assert_eq!(
compiled.map(|at| at - t0),
Some(compiled_at),
"a stream of rebuilds every {every:?} must compile at its first deadline"
);
}
}
#[test]
fn empty_hold_ends_when_no_watched_file_is_emptied() {
let t0 = Instant::now();
let mut hold = EmptyHold::default();
assert_eq!(
hold.on_rebuild(false, t0),
HoldVerdict::Compile,
"nothing emptied, nothing held"
);
assert_eq!(hold.deadline(), None);
assert_eq!(hold.on_rebuild(true, t0 + ms(10)), HoldVerdict::Hold);
assert_eq!(
hold.on_rebuild(false, t0 + ms(500)),
HoldVerdict::Compile,
"written: compiled at once, not at the deadline"
);
assert_eq!(hold.deadline(), None, "the write ends the hold");
assert_eq!(hold.on_rebuild(true, t0 + ms(600)), HoldVerdict::Hold);
assert_eq!(
hold.deadline(),
Some(t0 + ms(600) + EMPTY_HOLD_DEADLINE),
"a new truncation sets its own deadline"
);
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Woke {
Hold,
Tick,
}
fn wakes_under_saturation(
interval: Option<Duration>,
hold: Duration,
per_message: Duration,
until: Duration,
) -> Vec<(Duration, Woke)> {
let t0 = Instant::now();
let mut schedule = TickSchedule::start(interval, t0);
let mut held = Some(t0 + hold);
let mut now = t0;
let mut wakes = Vec::new();
for _ in 0..10_000 {
if now >= t0 + until {
return wakes;
}
match poll_wake(&mut schedule, held, now) {
WakePoll::HoldDue => {
wakes.push((now - t0, Woke::Hold));
held = None;
}
WakePoll::TickDue => wakes.push((now - t0, Woke::Tick)),
WakePoll::Wait { .. } | WakePoll::Never => now += per_message,
}
}
panic!("the replay did not reach {until:?} within 10 000 steps; wakes so far: {wakes:?}");
}
#[test]
fn wake_schedule_serves_a_held_rebuild_first_under_saturation() {
use Woke::{Hold, Tick};
assert_eq!(
wakes_under_saturation(Some(ms(50)), ms(120), ms(5), ms(210)),
[
(ms(50), Tick),
(ms(100), Tick),
(ms(120), Hold),
(ms(150), Tick),
(ms(200), Tick)
],
"a saturated channel must postpone neither the tick nor the held rebuild"
);
assert_eq!(
wakes_under_saturation(Some(ms(50)), ms(100), ms(5), ms(160)),
[
(ms(50), Tick),
(ms(100), Hold),
(ms(100), Tick),
(ms(150), Tick)
],
"a held rebuild due with a tick runs first, the tick straight after it"
);
assert_eq!(
wakes_under_saturation(None, ms(1_000), ms(7), ms(2_000)),
[(ms(1_001), Hold)],
"with no tick the held rebuild still runs at the first poll at or after its \
deadline"
);
}
#[test]
fn wake_schedule_waits_for_the_earlier_deadline() {
let t0 = Instant::now();
let held = Some(t0 + ms(1_000));
let mut off = TickSchedule::start(None, t0);
assert_eq!(
poll_wake(&mut off, held, t0),
WakePoll::Wait {
wait: ms(1_000),
hold: true
},
"--poll-interval 0 must still wait for the held rebuild"
);
assert_eq!(
poll_wake(&mut off, held, t0 + ms(999)),
WakePoll::Wait {
wait: ms(1),
hold: true
}
);
assert_eq!(poll_wake(&mut off, held, t0 + ms(1_000)), WakePoll::HoldDue);
assert_eq!(
poll_wake(&mut off, None, t0 + ms(1_000)),
WakePoll::Never,
"positive control: nothing held and no tick — a message, however long it takes"
);
let mut every = TickSchedule::start(Some(ms(50)), t0);
assert_eq!(
poll_wake(&mut every, Some(t0 + ms(30)), t0),
WakePoll::Wait {
wait: ms(30),
hold: true
},
"the held rebuild's deadline comes first"
);
assert_eq!(
poll_wake(&mut every, Some(t0 + ms(80)), t0),
WakePoll::Wait {
wait: ms(50),
hold: false
},
"the tick comes first"
);
assert_eq!(
poll_wake(&mut every, Some(t0 + ms(50)), t0),
WakePoll::Wait {
wait: ms(50),
hold: true
},
"a tie waits for the held rebuild, which is served first"
);
assert_eq!(
poll_wake(&mut every, None, t0),
WakePoll::Wait {
wait: ms(50),
hold: false
}
);
}
#[test]
fn held_batches_are_rebuilt_with_the_batch_that_ends_the_hold() {
let paths =
|names: &[&str]| -> BTreeSet<PathBuf> { names.iter().map(PathBuf::from).collect() };
let root = Path::new("/w");
let batch = |names: &[&str], vars_changed: bool| Batch {
paths: paths(names),
vars_changed,
};
let mut held = HeldBatch::default();
held.hold(&batch(&["/w/b.mds", "/x/unread.mds"], false), root);
held.hold(&batch(&["/w/a.mds", "/w/b.mds"], true), root);
assert_eq!(held.sources, paths(&["/w/a.mds", "/w/b.mds"]));
assert_eq!(
held.release(batch(&["/w/a.mds", "/w/c.mds"], false)),
batch(&["/w/a.mds", "/w/b.mds", "/w/c.mds", "/x/unread.mds"], true)
);
assert_eq!(held, HeldBatch::default(), "nothing stays held");
assert_eq!(
held.release(batch(&["/w/c.mds"], false)),
batch(&["/w/c.mds"], false),
"positive control: with nothing held, a batch is its own"
);
}
#[test]
fn a_file_a_held_compile_read_empty_is_in_the_baseline_until_the_hold_ends() {
let (_root_dir, root) = canonical_tempdir();
let mut state = empty_dir_state();
let page = root.join("page.mds");
let dependency = PathBuf::from("/outside/_y.mds");
let in_domain = |state: &DirWatchState| state.baselined_paths().any(|p| *p == dependency);
assert!(
!in_domain(&state),
"control: the session tracks no such file"
);
state
.held
.hold_read_empty(&page, BTreeSet::from([dependency.clone()]), &root);
assert!(
state.held.paths.contains(&page) && state.held.sources.contains(&page),
"the source is held; {:?}",
state.held
);
assert!(in_domain(&state), "the file is in the baseline's domain");
assert_eq!(
state.held.release(Batch {
paths: BTreeSet::new(),
vars_changed: false
}),
Batch {
paths: BTreeSet::from([page]),
vars_changed: false
},
"the batch that ends the hold rebuilds the source"
);
assert!(
!in_domain(&state),
"the file leaves the domain with the hold"
);
assert_eq!(state.held, HeldBatch::default(), "nothing stays held");
}
#[test]
fn empties_output_is_an_output_with_bytes_written_with_none() {
assert!(empties_output(Some("Page\n"), ""), "bytes, then none");
assert!(!empties_output(Some(""), ""), "an output already empty");
assert!(
!empties_output(None, ""),
"an output the session never wrote there"
);
assert!(
!empties_output(Some("Page\n"), "Other\n"),
"an output still with bytes"
);
}
fn content_event(path: &str) -> notify::Event {
notify::Event {
kind: notify::EventKind::Modify(notify::event::ModifyKind::Any),
paths: vec![PathBuf::from(path)],
attrs: Default::default(),
}
}
fn read_event(path: &str) -> notify::Event {
notify::Event {
kind: notify::EventKind::Access(notify::event::AccessKind::Read),
paths: vec![PathBuf::from(path)],
attrs: Default::default(),
}
}
fn modify_event(path: &str) -> Msg {
Msg::Fs(Ok(content_event(path)))
}
const REPLAY_STEPS: usize = 2 * MAX_DEBOUNCE_MESSAGES;
fn replay(
window: Duration,
start: Instant,
events: impl IntoIterator<Item = (Instant, notify::Event)>,
) -> (Instant, WindowEnd, DebounceWindow) {
let mut open = DebounceWindow::open(window, start);
let mut events = events.into_iter().peekable();
let mut now = start;
for _ in 0..REPLAY_STEPS {
if let Some(end) = open.classify(now) {
return (now, end, open);
}
let deadline = open.deadline();
match events.next_if(|(at, _)| *at < deadline) {
Some((at, event)) => {
now = now.max(at);
open.on_event(event, now);
}
None => now = deadline,
}
}
panic!("the window was still open after {REPLAY_STEPS} steps");
}
#[test]
fn a_debounce_window_keeps_that_an_event_said_events_were_lost() {
let t0 = Instant::now();
let rescan =
notify::Event::new(notify::EventKind::Other).set_flag(notify::event::Flag::Rescan);
let (_, _, closed) = replay(ms(100), t0, [(t0 + ms(10), rescan)]);
assert!(closed.rescan, "the window says events were lost");
let (_, _, closed) = replay(ms(100), t0, [(t0 + ms(10), content_event("/w/a.mds"))]);
assert!(
!closed.rescan,
"control: a window of ordinary events does not"
);
}
#[test]
fn debounce_window_quiet_end_is_one_window_after_the_last_content_event() {
let t0 = Instant::now();
let (closed_at, end, _) = replay(ms(100), t0, std::iter::empty());
assert_eq!(
(closed_at, end),
(t0 + ms(100), WindowEnd::Quiet),
"with no further event the window closes one window after it opened"
);
let burst = (0..40u32).map(|i| (t0 + ms(5) * i, content_event(&format!("/w/f{i}.mds"))));
let (closed_at, end, closed) = replay(ms(100), t0, burst);
assert_eq!(
end,
WindowEnd::Quiet,
"a 195ms burst under a 100ms window must end quiet, not capped"
);
assert_eq!(
closed_at,
t0 + ms(295),
"the window closes one window after the burst's last event (195ms)"
);
assert_eq!(
closed.classify(t0 + ms(294)),
None,
"one millisecond earlier the window is still open"
);
assert_eq!(
closed.paths.len(),
40,
"every path in the burst must be collected into the one window; got {:?}",
closed.paths
);
}
#[test]
fn debounce_window_cap_ends_an_endless_stream_exactly_at_start_plus_cap() {
let streams = [
(ms(50), ms(2), ms(1_000)),
(ms(10), ms(9), ms(1_000)),
(ms(250), ms(100), ms(2_500)),
(ms(1_000), ms(999), ms(10_000)),
];
for (window, every, cap) in streams {
let t0 = Instant::now();
let endless = (1u32..).map(|i| (t0 + every * i, content_event("/w/hot.mds")));
let (closed_at, end, closed) = replay(window, t0, endless);
assert_eq!(
end,
WindowEnd::Cap,
"a {window:?} window under an event every {every:?} must end at the cap"
);
assert_eq!(
closed_at,
t0 + cap,
"a {window:?} window must close exactly at its cap, max(10 x window, 1s)"
);
assert_eq!(closed.paths.len(), 1, "every event names the same path");
}
}
#[test]
fn debounce_zero_is_disabled_and_leaves_the_channel_untouched() {
let (tx, rx) = mpsc::channel::<Msg>();
tx.send(modify_event("/w/a.mds")).expect("send failed");
let outcome = drain_debounce(&rx, 0);
assert_eq!(outcome.end, DebounceEnd::Disabled);
assert!(
outcome.paths.is_empty(),
"a disabled window must collect nothing"
);
assert!(
matches!(rx.try_recv(), Ok(Msg::Fs(Ok(_)))),
"the queued event must still be in the channel: with coalescing off the \
loop delivers it as its own batch"
);
}
#[test]
fn debounce_interrupt_returns_immediately() {
let (tx, rx) = mpsc::channel::<Msg>();
tx.send(modify_event("/w/a.mds")).expect("send failed");
tx.send(Msg::Interrupt).expect("send failed");
let outcome = drain_debounce(&rx, 5_000);
drop(tx);
assert_eq!(outcome.end, DebounceEnd::Interrupted);
assert!(
outcome.interrupted(),
"interrupted() must agree with the end reason"
);
assert_eq!(
outcome.paths.len(),
1,
"positive control: the window was open and draining when Ctrl+C arrived"
);
}
#[test]
fn debounce_window_reads_count_but_neither_extend_nor_collect() {
let t0 = Instant::now();
let reads = std::iter::once((t0, content_event("/w/a.mds")))
.chain((1..=60u32).map(|i| (t0 + ms(5) * i, read_event("/w/a.mds"))));
let (closed_at, end, closed) = replay(ms(100), t0, reads);
assert_eq!(
(closed_at, end),
(t0 + ms(100), WindowEnd::Quiet),
"300ms of reads must not extend a 100ms window"
);
assert_eq!(
closed.paths.len(),
1,
"only the one content event contributes a path; got {:?}",
closed.paths
);
assert_eq!(
closed.messages, 20,
"the content event and the 19 reads drained before the deadline all count"
);
let writes = (0..=60u32).map(|i| (t0 + ms(5) * i, content_event(&format!("/w/f{i}.mds"))));
let (closed_at, end, closed) = replay(ms(100), t0, writes);
assert_eq!((closed_at, end), (t0 + ms(400), WindowEnd::Quiet));
assert_eq!(closed.paths.len(), 61);
}
#[test]
fn debounce_window_closes_at_the_message_limit() {
let t0 = Instant::now();
let mut open = DebounceWindow::open(ms(100), t0);
for _ in 2..MAX_DEBOUNCE_MESSAGES {
open.on_event(content_event("/w/same.mds"), t0);
}
open.on_event(read_event("/w/same.mds"), t0);
assert_eq!(
open.classify(t0),
None,
"one message short of the limit, the window is still open"
);
open.on_watch_error();
assert_eq!(
open.classify(t0),
Some(WindowEnd::MessageLimit),
"contents, reads and watch errors all count toward the limit"
);
let queued = (0..12_000u32).map(|_| (t0, content_event("/w/same.mds")));
let (closed_at, end, closed) = replay(ms(100), t0, queued);
assert_eq!(
(closed_at, end),
(t0, WindowEnd::MessageLimit),
"12 000 queued events must hit the message bound, not the quiet period"
);
assert_eq!(closed.messages, MAX_DEBOUNCE_MESSAGES);
assert_eq!(
closed.paths.len(),
1,
"all 12 000 events name the same path; got {:?}",
closed.paths
);
}
#[test]
fn debounce_driver_stops_at_the_message_limit_with_the_rest_still_queued() {
let (tx, rx) = mpsc::channel::<Msg>();
for _ in 2..MAX_DEBOUNCE_MESSAGES {
tx.send(modify_event("/w/same.mds")).expect("send failed");
}
tx.send(Msg::Fs(Ok(read_event("/w/read.mds"))))
.expect("send failed");
let watch_error = notify::Error::generic("a planted watch error");
tx.send(Msg::Fs(Err(watch_error))).expect("send failed");
for _ in 0..2_000 {
tx.send(modify_event("/w/later.mds")).expect("send failed");
}
drop(tx);
let outcome = drain_debounce(&rx, 60_000);
assert_eq!(
outcome.end,
DebounceEnd::Closed(WindowEnd::MessageLimit),
"{} queued messages must end the window at the message limit",
MAX_DEBOUNCE_MESSAGES + 2_000
);
assert_eq!(
outcome.paths,
BTreeSet::from([PathBuf::from("/w/same.mds")]),
"only the content events drained before the limit contribute a path"
);
let left: Vec<Msg> = rx.try_iter().collect();
assert_eq!(
left.len(),
2_000,
"the content events, the read and the watch error all count toward the \
limit, and every message after it stays queued"
);
assert!(
left.iter().all(|msg| matches!(
msg,
Msg::Fs(Ok(event)) if event.paths == [PathBuf::from("/w/later.mds")]
)),
"positive control: the messages still queued are the flood after the limit"
);
}
#[test]
fn debounce_disconnected_ends_the_window_immediately() {
let (tx, rx) = mpsc::channel::<Msg>();
tx.send(modify_event("/w/a.mds")).expect("send failed");
drop(tx);
let outcome = drain_debounce(&rx, 5_000);
assert_eq!(
outcome.end,
DebounceEnd::Disconnected,
"a 5s window that waited itself out would end Quiet, not Disconnected"
);
assert_eq!(
outcome.paths.len(),
1,
"messages queued before the disconnect must still be collected; got {:?}",
outcome.paths
);
}
#[test]
fn debounce_and_tick_drivers_run_on_the_real_clock() {
let (tx, rx) = mpsc::channel::<Msg>();
tx.send(modify_event("/w/a.mds")).expect("send failed");
let t0 = Instant::now();
let (outcome, rx) = within_5s("drain_debounce", move || (drain_debounce(&rx, 20), rx));
assert!(
t0.elapsed() >= ms(20),
"a 20ms window must wait at least 20ms; got {:?}",
t0.elapsed()
);
assert!(
matches!(
outcome.end,
DebounceEnd::Closed(WindowEnd::Quiet | WindowEnd::Cap)
),
"the window must close on its own; got {:?}",
outcome.end
);
assert_eq!(outcome.paths.len(), 1, "the queued event is drained");
let t1 = Instant::now();
let (wake, rx) = within_5s("an idle tick", move || {
(TickClock::new(Some(ms(50))).recv_next(&rx, None), rx)
});
assert!(
matches!(wake, Ok(Wake::Tick)),
"an idle channel must produce a tick"
);
assert!(
t1.elapsed() >= ms(50),
"the tick must not come due before its interval; got {:?}",
t1.elapsed()
);
let t2 = Instant::now();
let (wake, _rx) = within_5s("a held rebuild's deadline", move || {
(TickClock::new(None).recv_next(&rx, Some(t2 + ms(30))), rx)
});
assert!(
matches!(wake, Ok(Wake::HoldDue)),
"a held rebuild's deadline must wake an idle loop with no tick"
);
assert!(
t2.elapsed() >= ms(30),
"the held rebuild must not run before its deadline; got {:?}",
t2.elapsed()
);
drop(tx);
}
#[test]
fn clamp_debounce_contract() {
assert_eq!(
clamp_debounce(0),
None,
"0 disables coalescing; it does not mean a 0ms window"
);
assert_eq!(clamp_debounce(100), Some(Duration::from_millis(100)));
assert_eq!(
clamp_debounce(u64::MAX),
Some(Duration::from_secs(60)),
"an unclamped u64::MAX window does not overflow on a monotonic clock — it \
lands ~585 million years out, so the watcher silently never rebuilds"
);
}
#[test]
fn debounce_cap_contract() {
assert_eq!(
debounce_cap(Duration::from_millis(10)),
Duration::from_secs(1),
"the floor binds for small windows"
);
assert_eq!(
debounce_cap(Duration::from_millis(250)),
Duration::from_millis(2_500)
);
assert_eq!(
debounce_cap(Duration::from_millis(1_000)),
Duration::from_secs(10)
);
}
#[test]
fn tracked_set_includes_cross_root_dependencies() {
let root = PathBuf::from("/w/root");
let importer = root.join("importer.mds");
let external = PathBuf::from("/w/shared/_x.mds");
let mut state = DirWatchState {
forward_deps: HashMap::new(),
errored: HashSet::new(),
known_files: BTreeSet::new(),
last_written: HashMap::new(),
outputs: HashMap::new(),
kept: HashMap::new(),
out_dir: None,
reads: Vec::new(),
external_dep_dirs: BTreeSet::new(),
vars_file: None,
last_mtimes: HashMap::new(),
hold: EmptyHold::Off,
held: HeldBatch::default(),
};
state.known_files.insert(importer.clone());
state
.forward_deps
.insert(importer.clone(), vec![external.clone()]);
let tracked = state.tracked_set();
assert!(
tracked.contains(&importer),
"in-root source must be tracked"
);
assert!(
tracked.contains(&external),
"a cross-root dependency must be tracked; it is exactly the path no \
collect_mds_files(root) walk can report"
);
}
#[test]
fn record_error_preserves_last_known_deps() {
let root = PathBuf::from("/w/root");
let importer = root.join("importer.mds");
let external = PathBuf::from("/w/shared/_x.mds");
let mut state = DirWatchState {
forward_deps: HashMap::new(),
errored: HashSet::new(),
known_files: BTreeSet::new(),
last_written: HashMap::new(),
outputs: HashMap::new(),
kept: HashMap::new(),
out_dir: None,
reads: Vec::new(),
external_dep_dirs: BTreeSet::new(),
vars_file: None,
last_mtimes: HashMap::new(),
hold: EmptyHold::Off,
held: HeldBatch::default(),
};
state.record_success(&importer, vec![external.clone()], &root, None, None);
assert!(state.external_dep_dirs.contains(Path::new("/w/shared")));
state.record_error(&importer);
assert!(state.errored.contains(&importer), "error must be recorded");
assert_eq!(
state.forward_deps.get(&importer),
Some(&vec![external.clone()]),
"a failed compile must keep the last known dep set, or the external dep \
dir is pruned and its events are filtered out from then on"
);
assert!(
state.tracked_set().contains(&external),
"the backstop must still cover a dependency whose importer is broken — \
that is precisely when it needs to notice the dependency being fixed"
);
}
#[test]
fn ghost_external_dep_prune_keeps_in_root_last_written() {
let root_dir = tempfile::tempdir().unwrap();
let out_dir = tempfile::tempdir().unwrap();
let shared_dir = tempfile::tempdir().unwrap();
let root = root_dir.path().to_path_buf();
let out = out_dir.path().to_path_buf();
let other = root.join("other.mds");
std::fs::write(&other, "Hello.\n").unwrap();
let victim = root.join("x.mds");
std::fs::write(&victim, "Victim.\n").unwrap();
let victim_out = out.join("x.md");
let ghost = shared_dir.path().join("x.mds");
assert!(!ghost.exists(), "the ghost dep must not exist on disk");
let mut state = DirWatchState {
forward_deps: HashMap::new(),
errored: HashSet::new(),
known_files: BTreeSet::new(),
last_written: HashMap::new(),
outputs: HashMap::new(),
kept: HashMap::new(),
out_dir: None,
reads: Vec::new(),
external_dep_dirs: BTreeSet::new(),
vars_file: None,
last_mtimes: HashMap::new(),
hold: EmptyHold::Off,
held: HeldBatch::default(),
};
state.known_files.insert(victim.clone());
state.last_written.insert(
victim_out.clone(),
WrittenOutput {
source: victim.clone(),
content: "Victim.\n".to_string(),
},
);
state.errored.insert(ghost.clone());
state
.external_dep_dirs
.insert(shared_dir.path().to_path_buf());
let changed: BTreeSet<PathBuf> = std::iter::once(other).collect();
process_dir_batch_incremental(
&changed,
&mut BatchCtx {
watch_root: &WatchedPath {
typed: root.clone(),
canonical: root,
what: Watched::Root,
},
output_base: &dir_base(out.clone()),
vars: BatchVars::map_only(&None),
quiet: true,
},
&mut state,
);
assert!(
!state.errored.contains(&ghost),
"control: the ghost prune must actually have run — without it the assertion \
below would pass on a batch that never reached the branch"
);
assert!(
state.last_written.contains_key(&victim_out),
"#217: forgetting a ghost external dep must not drop an in-root source's \
last_written entry; keys: {:?}",
state.last_written.keys().collect::<Vec<_>>()
);
}
#[test]
fn a_vars_changed_batch_compiles_the_sources_created_in_it() {
let root_dir = tempfile::tempdir().unwrap();
let out_dir = tempfile::tempdir().unwrap();
let elsewhere = tempfile::tempdir().unwrap();
let canonical = |dir: &tempfile::TempDir| std::fs::canonicalize(dir.path()).unwrap();
let (root, out) = (canonical(&root_dir), canonical(&out_dir));
let known = root.join("known.mds");
let created = root.join("created.mds");
let not_a_source = root.join("notes.md");
let excluded = root.join("node_modules").join("dep.mds");
let outside = canonical(&elsewhere).join("outside.mds");
std::fs::create_dir(root.join("node_modules")).unwrap();
for (path, text) in [
(&known, "Known.\n"),
(&created, "Created.\n"),
(¬_a_source, "---\ntype: mds\nname: notes\n---\nNotes.\n"),
(&excluded, "Excluded.\n"),
(&outside, "Outside.\n"),
] {
std::fs::write(path, text).unwrap();
}
let mut state = empty_dir_state();
state.known_files.insert(known.clone());
let changed: BTreeSet<PathBuf> = [&created, ¬_a_source, &excluded, &outside]
.into_iter()
.cloned()
.collect();
process_dir_batch(
&changed,
true,
&mut BatchCtx {
watch_root: &WatchedPath {
typed: root.clone(),
canonical: root.clone(),
what: Watched::Root,
},
output_base: &dir_base(out.clone()),
vars: BatchVars::map_only(&None),
quiet: true,
},
&mut state,
);
let read = |rel: &Path| std::fs::read_to_string(out.join(rel)).ok();
assert!(
read(Path::new("known.md")).is_some_and(|text| text.contains("Known.")),
"positive control: a known source is recompiled; out/known.md: {:?}",
read(Path::new("known.md"))
);
assert!(
read(Path::new("created.md")).is_some_and(|text| text.contains("Created.")),
"a source created in the batch is compiled with it; out/created.md: {:?}",
read(Path::new("created.md"))
);
assert!(
state.known_files.contains(&created) && state.last_mtimes.contains_key(&created),
"and is known and in the baseline, so a later edit or the idle tick finds it; \
known: {:?}",
state.known_files
);
for rel in [
PathBuf::from("notes.md"),
Path::new("node_modules").join("dep.md"),
PathBuf::from("outside.md"),
] {
assert_eq!(
read(&rel),
None,
"{}: a path that is no source below the root is not compiled as one",
rel.display()
);
}
for path in [¬_a_source, &excluded, &outside] {
assert!(
!state.known_files.contains(path) && !state.errored.contains(path),
"{}: neither known nor errored; known: {:?}, errored: {:?}",
path.display(),
state.known_files,
state.errored
);
}
}
#[test]
fn watch_root_walked_keeps_the_typed_prefix() {
let root = WatchedPath {
typed: PathBuf::from("src"),
canonical: PathBuf::from("/abs/project/src"),
what: Watched::Root,
};
assert_eq!(
root.walked(Path::new("/abs/project/src/sub/a.mds")),
Path::new("src").join("sub").join("a.mds")
);
assert_eq!(
root.walked(Path::new("/abs/shared/b.mds")),
Path::new("/abs/shared/b.mds"),
"an out-of-root dependency has no walked form"
);
}
#[test]
fn record_error_on_unknown_source_inserts_empty_deps() {
let mut state = DirWatchState {
forward_deps: HashMap::new(),
errored: HashSet::new(),
known_files: BTreeSet::new(),
last_written: HashMap::new(),
outputs: HashMap::new(),
kept: HashMap::new(),
out_dir: None,
reads: Vec::new(),
external_dep_dirs: BTreeSet::new(),
vars_file: None,
last_mtimes: HashMap::new(),
hold: EmptyHold::Off,
held: HeldBatch::default(),
};
let src = PathBuf::from("/w/root/broken.mds");
state.record_error(&src);
assert_eq!(state.forward_deps.get(&src), Some(&vec![]));
}
#[test]
fn baseline_path_keeps_existing_entry() {
let dir = tempfile::tempdir().unwrap();
let f = dir.path().join("a.mds");
std::fs::write(&f, "one").unwrap();
let mut snap = HashMap::new();
baseline_path(&f, &mut snap);
let first = snap.get(&f).copied();
std::fs::write(&f, "a much longer second revision").unwrap();
baseline_path(&f, &mut snap);
assert_eq!(
snap.get(&f).copied(),
first,
"baseline_path must not overwrite an existing entry: only the older pair \
predates the read whose output was published"
);
assert!(
path_state_differs(&f, &snap),
"the retained older baseline must therefore report the file as changed"
);
}
#[test]
fn path_state_differs_reports_unknown_path() {
let dir = tempfile::tempdir().unwrap();
let f = dir.path().join("a.mds");
std::fs::write(&f, "one").unwrap();
let snap = HashMap::new();
assert!(
path_state_differs(&f, &snap),
"a path the baseline has never seen cannot be claimed as accounted for"
);
}
#[test]
fn output_path_for_no_create() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().to_path_buf();
let new_subdir = dir.path().join("new_out");
assert!(!new_subdir.exists(), "precondition: subdir does not exist");
let source = root.join("template.mds");
let base = dir_base(new_subdir.clone());
let result = output_path_for(&source, RootPaths::as_typed(&root), &base, "md");
assert_eq!(result.path, new_subdir.join("template.md"));
assert!(
!new_subdir.exists(),
"output_path_for must not create directories"
);
}
#[test]
fn compile_and_write_returns_deps_for_importing_template() {
let dir = tempfile::tempdir().unwrap();
let helper = dir.path().join("helper.mds");
std::fs::write(
&helper,
"@define greet(name):\nHello {name}!\n@end\n\n@export greet\n",
)
.unwrap();
let entry = dir.path().join("entry.mds");
std::fs::write(
&entry,
"@import \"./helper.mds\" as h\n\n{h.greet(\"World\")}\n",
)
.unwrap();
let out = dir.path().join("entry.md");
let out_str = out.display().to_string();
let watched = WatchedPath {
canonical: mds::NativeFs::check_symlink(&entry).unwrap(),
typed: entry,
what: Watched::Entry,
};
let (_written_path, deps, _content) =
match compile_and_write(&watched, &Some(out_str), &None, &None, &[], None, true)
.unwrap()
{
CompileWriteOutcome::Written(result) => result,
CompileWriteOutcome::CompileFailed(e) => panic!("the compile failed: {e:?}"),
CompileWriteOutcome::WriteFailed { failure, .. } => {
panic!("the write failed: {failure:?}")
}
CompileWriteOutcome::StdoutClosed => {
panic!("compile_and_write writes a file here, never stdout")
}
};
assert!(out.exists(), "output file should be created");
assert!(
!deps.is_empty(),
"compile_and_write should return the imported helper as a dep"
);
let dep_names: Vec<_> = deps
.iter()
.filter_map(|d| {
PathBuf::from(d)
.file_name()
.and_then(|n| n.to_str())
.map(str::to_owned)
})
.collect();
assert!(
dep_names.iter().any(|n| n == "helper.mds"),
"deps should contain helper.mds, got: {dep_names:?}"
);
}
#[test]
fn compile_and_write_tells_a_failed_write_from_a_failed_compile() {
let dir = tempfile::tempdir().unwrap();
std::fs::write(
dir.path().join("part.mds"),
"@define who():\nWorld\n@end\n\n@export who\n",
)
.unwrap();
let entry = dir.path().join("chat.mds");
std::fs::write(
&entry,
"@import \"./part.mds\" as p\n@message user:\nHello {{p.who()}}\n@end\n",
)
.unwrap();
std::fs::create_dir(dir.path().join("chat.json")).unwrap();
let watched = WatchedPath {
canonical: mds::NativeFs::check_symlink(&entry).unwrap(),
typed: entry.clone(),
what: Watched::Entry,
};
let name = |path: &Path| path.file_name().and_then(|n| n.to_str()).map(str::to_owned);
match compile_and_write(&watched, &None, &None, &None, &[], None, true).unwrap() {
CompileWriteOutcome::WriteFailed { deps, failure } => {
let dep_names: Vec<_> = deps.iter().filter_map(|d| name(d)).collect();
assert!(
dep_names.iter().any(|n| n == "part.mds"),
"the dependencies the compile reported: {dep_names:?}"
);
let failure = failure.expect("a failed write is reported").to_string();
assert!(
failure.contains("chat.json"),
"the failure names the output: {failure}"
);
}
CompileWriteOutcome::CompileFailed(e) => panic!("the compile failed: {e:?}"),
CompileWriteOutcome::Written(_) => panic!("a directory is never written over"),
CompileWriteOutcome::StdoutClosed => panic!("the output is a file, never stdout"),
}
assert!(
!dir.path().join("chat.md").exists(),
"nothing is written on the Markdown route"
);
std::fs::write(&entry, "Hello {{name\n").unwrap();
assert!(
matches!(
compile_and_write(&watched, &None, &None, &None, &[], None, true).unwrap(),
CompileWriteOutcome::CompileFailed(Some(_))
),
"a failed compile is reported as one"
);
}
#[test]
fn output_route_is_each_kinds_own_unless_one_is_named() {
let target = |name: &str| Some(WriteTarget::as_typed(PathBuf::from(name)));
let (md, json, named) = (target("chat.md"), target("chat.json"), target("out.md"));
let by_kind = OutputRoute::ByKind {
markdown: md.clone(),
messages: json.clone(),
};
assert_eq!(by_kind.of(OutputKind::Messages), &json);
assert_eq!(by_kind.of(OutputKind::Markdown), &md);
assert_eq!(by_kind.other_than(OutputKind::Messages), md.as_ref());
assert_eq!(by_kind.other_than(OutputKind::Markdown), json.as_ref());
let route = OutputRoute::Named(named.clone());
for kind in [OutputKind::Markdown, OutputKind::Messages] {
assert_eq!(route.of(kind), &named, "-o is the route of every kind");
assert_eq!(route.other_than(kind), None, "-o leaves nothing behind");
}
}
#[test]
fn watched_entry_refuses_a_typed_path_that_leads_elsewhere() {
let dir = tempfile::TempDir::new().unwrap();
for name in ["a", "b"] {
std::fs::create_dir(dir.path().join(name)).unwrap();
std::fs::write(
dir.path().join(name).join("page.mds"),
format!("Hi {name}\n"),
)
.unwrap();
}
let typed = dir.path().join("a").join("page.mds");
let compile = |canonical: &Path| {
WatchedPath {
typed: typed.clone(),
canonical: canonical.to_path_buf(),
what: Watched::Entry,
}
.compile(None, true)
.map(|compiled| compiled.content)
.map_err(|failure| {
failure
.into_report()
.map_or_else(|| "a panic".to_string(), |e| e.to_string())
})
};
let here = mds::NativeFs::check_symlink(&typed).unwrap();
assert_eq!(compile(&here), Ok("Hi a\n".to_string()), "control");
let elsewhere =
mds::NativeFs::check_symlink(&dir.path().join("b").join("page.mds")).unwrap();
let refused = compile(&elsewhere).unwrap_err();
assert_eq!(
refused,
format!(
"watched entry now resolves to a different file: \"{}\"; \
restart mds watch to follow it",
typed.display()
)
);
assert!(
!refused.contains(&*elsewhere.to_string_lossy()),
"{refused}"
);
std::fs::remove_file(&typed).unwrap();
let missing = compile(&here).unwrap_err();
assert_eq!(
missing,
format!("file not found: {}", typed.display()),
"the check refuses a missing entry with the lookup's own error and typed path"
);
}
#[test]
fn watched_root_and_source_share_the_entry_rule() {
let dir = tempfile::TempDir::new().unwrap();
for name in ["a", "b"] {
std::fs::create_dir(dir.path().join(name)).unwrap();
std::fs::write(dir.path().join(name).join("page.mds"), "Hi\n").unwrap();
}
let canonical = |p: PathBuf| p.canonicalize().unwrap();
let check = |typed: PathBuf, canonical: PathBuf, what: Watched| {
WatchedPath {
typed,
canonical,
what,
}
.ensure_unmoved()
.map_err(|e| e.to_string())
};
let moved = |kind: &str, now: &str, typed: &Path| {
Err(format!(
"watched {kind} now resolves to a different {now}: \"{}\"; \
restart mds watch to follow it",
typed.display()
))
};
let root = dir.path().join("a");
let source = root.join("page.mds");
let root_b = canonical(dir.path().join("b"));
let source_b = canonical(dir.path().join("b").join("page.mds"));
let mut mismatches = Vec::new();
let rows = [
(
"root, unmoved",
check(root.clone(), canonical(root.clone()), Watched::Root),
Ok(()),
),
(
"root, moved",
check(root.clone(), root_b.clone(), Watched::Root),
moved("directory", "directory", &root),
),
(
"source, unmoved",
check(source.clone(), canonical(source.clone()), Watched::Source),
Ok(()),
),
(
"source, moved",
check(source.clone(), source_b.clone(), Watched::Source),
moved("file", "file", &source),
),
(
"root, gone",
check(dir.path().join("gone"), root_b, Watched::Root),
Err(format!(
"file not found: {}",
dir.path().join("gone").display()
)),
),
(
"source, gone",
check(root.join("gone.mds"), source_b, Watched::Source),
Err(format!(
"file not found: {}",
root.join("gone.mds").display()
)),
),
];
for (label, got, want) in rows {
if got != want {
mismatches.push(format!("{label}: got {got:?}, want {want:?}"));
}
}
assert!(mismatches.is_empty(), "{mismatches:#?}");
}
#[test]
fn watched_paths_return_the_lookup_error_before_a_compile() {
let dir = tempfile::TempDir::new().unwrap();
let file = dir.path().join("page.mds");
std::fs::write(&file, "Hi\n").unwrap();
let canonical = file.canonicalize().unwrap();
let blocked = file.join("blocked.mds");
for what in [Watched::Root, Watched::Entry, Watched::Source] {
let path = WatchedPath {
typed: blocked.clone(),
canonical: canonical.clone(),
what,
};
let expected = match what {
Watched::Root => {
let cause = blocked.canonicalize().unwrap_err();
let shown =
mds::escape_path_for_message(&blocked.to_string_lossy()).into_owned();
if cause.kind() == std::io::ErrorKind::NotFound {
MdsError::FileNotFound {
path: shown,
span: None,
src: None,
}
} else {
MdsError::Io {
message: format!(
"cannot resolve path {shown}: {}",
crate::output::safe_inline(crate::output::io_cause(&cause))
),
}
}
}
Watched::Entry | Watched::Source => {
mds::NativeFs::check_symlink(&blocked).unwrap_err()
}
};
assert_eq!(
path.ensure_unmoved().map_err(|error| error.to_string()),
Err(expected.to_string()),
"the lookup error must not become a moved error"
);
let control = WatchedPath {
typed: file.clone(),
canonical: canonical.clone(),
what,
};
assert!(control.ensure_unmoved().is_ok());
}
}
#[test]
fn a_session_reads_each_stdout_outcome_for_itself() {
assert!(matches!(
OutputWrite::from_stdout(StdoutOutcome::Written),
OutputWrite::Written
));
assert!(matches!(
OutputWrite::from_stdout(StdoutOutcome::Closed),
OutputWrite::StdoutClosed
));
assert!(matches!(
OutputWrite::from_stdout(StdoutOutcome::FailedAgain),
OutputWrite::Failed(None)
));
let failed = std::io::Error::new(std::io::ErrorKind::StorageFull, "no space left");
match OutputWrite::from_stdout(StdoutOutcome::Failed(failed)) {
OutputWrite::Failed(Some(report)) => {
assert_eq!(
report.to_string(),
format!(
"cannot write to stdout: {}",
std::io::ErrorKind::StorageFull
),
"the error's kind, not the text it carries (#390)"
);
assert_eq!(
report.code().map(|c| c.to_string()).as_deref(),
Some("mds::io")
);
}
other => panic!("want Failed(Some(mds::io)); got {other:?}"),
}
}
fn empty_dir_state() -> DirWatchState {
DirWatchState {
forward_deps: HashMap::new(),
errored: HashSet::new(),
known_files: BTreeSet::new(),
last_written: HashMap::new(),
outputs: HashMap::new(),
kept: HashMap::new(),
out_dir: None,
reads: Vec::new(),
external_dep_dirs: BTreeSet::new(),
vars_file: None,
last_mtimes: HashMap::new(),
hold: EmptyHold::Off,
held: HeldBatch::default(),
}
}
fn file_state(foi: HashSet<PathBuf>) -> FileWatchState {
FileWatchState {
watched_dirs: BTreeSet::new(),
armed_dirs: BTreeSet::new(),
foi,
last_mtimes: HashMap::new(),
hold: EmptyHold::Off,
last_written: HashMap::new(),
written_to: None,
kept: None,
output: OutputRoute::Named(None),
out_dir: None,
entry_was_missing: false,
first_tick: false,
missing_watched_dirs: BTreeSet::new(),
}
}
fn source_and_dependency() -> (tempfile::TempDir, PathBuf, PathBuf) {
let dir = tempfile::tempdir().unwrap();
let src = dir.path().join("page.mds");
let dep = dir.path().join("_dep.mds");
std::fs::write(&src, "Page.\n").unwrap();
std::fs::write(&dep, "Dep.\n").unwrap();
(dir, src, dep)
}
#[test]
fn settle_rebaseline_takes_the_baseline_again_in_a_rebuild_only() {
let (dir, src, dep) = source_and_dependency();
let foi: HashSet<PathBuf> = [src.clone(), dep.clone()].into_iter().collect();
let mut file = file_state(foi.clone());
settle(SettleInto::File(&mut file), None, Settle::Rebaseline);
assert_eq!(file.last_mtimes, snapshot_state(&foi));
assert!(
file.last_mtimes
.get(&src)
.is_some_and(|stamp| stamp.0.is_some()),
"the baseline holds the source as it is on disk: {:?}",
file.last_mtimes
);
let vars = dir.path().join("vars.json");
std::fs::write(&vars, r#"{"v": 1}"#).unwrap();
let mut rebuild = empty_dir_state();
rebuild.known_files.insert(src.clone());
rebuild.forward_deps.insert(src.clone(), vec![dep.clone()]);
rebuild.vars_file = Some(vars.clone());
settle(SettleInto::Dir(&mut rebuild), None, Settle::Rebaseline);
assert_eq!(rebuild.last_mtimes, snapshot_state(&rebuild.watched_set()));
assert!(
rebuild.last_mtimes.contains_key(&dep) && rebuild.last_mtimes.contains_key(&vars),
"the dependency and the vars file are in the baseline: {:?}",
rebuild.last_mtimes
);
assert!(
!rebuild.tracked_set().contains(&vars),
"the vars file is outside the tracked set: no source and no dependency"
);
assert!(rebuild.errored.is_empty(), "nothing is marked errored");
}
#[test]
fn settle_defer_leaves_the_baseline_and_records_nothing() {
let (_dir, src, dep) = source_and_dependency();
let foi: HashSet<PathBuf> = [src.clone(), dep.clone()].into_iter().collect();
let before = snapshot_state(&foi);
std::fs::write(&dep, "").unwrap();
let report = |e: miette::Report| panic!("a deferral reports nothing; got {e:?}");
let mut file = file_state(foi.clone());
file.last_mtimes = before.clone();
settle_reporting(SettleInto::File(&mut file), None, Settle::Defer, report);
assert_eq!(file.last_mtimes, before, "the baseline is left as it was");
assert!(
any_went_empty(&file.foi, &file.last_mtimes),
"the next rebuild finds the dependency emptied again"
);
file.last_mtimes.extend(snapshot_state(&foi));
settle(SettleInto::File(&mut file), None, Settle::Rebaseline);
assert!(
!any_went_empty(&file.foi, &file.last_mtimes),
"positive control: a rebaseline after a look that saw it empty takes it in"
);
let mut rebuild = empty_dir_state();
rebuild.known_files.insert(src.clone());
rebuild.forward_deps.insert(src.clone(), vec![dep.clone()]);
rebuild.last_mtimes = before.clone();
settle_reporting(SettleInto::Dir(&mut rebuild), None, Settle::Defer, report);
assert_eq!(
rebuild.last_mtimes, before,
"the baseline is left as it was"
);
assert!(rebuild.errored.is_empty(), "nothing is marked errored");
assert!(
any_went_empty(&rebuild.watched_set(), &rebuild.last_mtimes),
"the next batch finds the dependency emptied again"
);
rebuild
.last_mtimes
.extend(snapshot_state(&rebuild.watched_set()));
settle(SettleInto::Dir(&mut rebuild), None, Settle::Rebaseline);
assert!(
!any_went_empty(&rebuild.watched_set(), &rebuild.last_mtimes),
"positive control: a rebaseline after a look that saw it empty takes it in"
);
}
#[test]
fn settle_rebaseline_keeps_the_stamps_the_look_took() {
let (dir, src, dep) = source_and_dependency();
let gone = dir.path().join("gone.mds");
let mut look = snapshot_state(&HashSet::from([dep.clone()]));
look.insert(gone.clone(), (None, Some(4)));
std::fs::write(&dep, "").unwrap();
let kept = |baseline: &StampMap, what: &str| {
assert_eq!(
baseline.get(&dep),
look.get(&dep),
"{what}: the look's stamp, not the emptied file's"
);
assert!(
baseline.contains_key(&src),
"{what}: positive control: a file no look stamped is stamped; {baseline:?}"
);
assert!(
!baseline.contains_key(&gone),
"{what}: a file the mode no longer watches is dropped; {baseline:?}"
);
};
let foi: HashSet<PathBuf> = [src.clone(), dep.clone()].into_iter().collect();
for (how, what) in [
(Settle::Rebaseline, "file mode, a rebaseline"),
(Settle::MarkErrored(&src), "file mode, a failed compile"),
] {
let mut file = file_state(foi.clone());
file.last_mtimes = look.clone();
settle(SettleInto::File(&mut file), None, how);
kept(&file.last_mtimes, what);
assert!(
any_went_empty(&file.foi, &file.last_mtimes),
"{what}: the next rebuild finds the dependency emptied"
);
}
let vars = dir.path().join("vars.json");
std::fs::write(&vars, r#"{"v": 1}"#).unwrap();
let mut rebuild = empty_dir_state();
rebuild.known_files.insert(src.clone());
rebuild.forward_deps.insert(src.clone(), vec![dep.clone()]);
rebuild.vars_file = Some(vars.clone());
rebuild.last_mtimes = look.clone();
settle(SettleInto::Dir(&mut rebuild), None, Settle::Rebaseline);
kept(&rebuild.last_mtimes, "directory mode, a rebaseline");
assert!(
rebuild.last_mtimes.contains_key(&vars),
"the vars file is stamped: {:?}",
rebuild.last_mtimes
);
assert!(
any_went_empty(&rebuild.watched_set(), &rebuild.last_mtimes),
"the next batch finds the dependency emptied"
);
}
fn canonical_tempdir() -> (tempfile::TempDir, PathBuf) {
let dir = tempfile::tempdir().unwrap();
let path = std::fs::canonicalize(dir.path()).unwrap();
(dir, path)
}
fn dir_ctx(root: &Path, out: &Path) -> DirWatchCtx {
DirWatchCtx {
root: WatchedPath {
typed: root.to_path_buf(),
canonical: root.to_path_buf(),
what: Watched::Root,
},
working_dir: WorkingDir { canonical: None },
vars_path: None,
vars_path_typed: None,
static_set_vars: Vec::new(),
static_set_string_vars: Vec::new(),
output_base: dir_base(out.to_path_buf()),
exclude_prefix: None,
vars_dir_extra: None,
clear: false,
debounce_ms: 0,
quiet: true,
}
}
#[test]
fn a_file_found_emptied_without_its_event_is_rebuilt_when_the_hold_ends() {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let (a, x) = (root.join("a.mds"), root.join("x.mds"));
std::fs::write(&a, "A one\n").unwrap();
std::fs::write(&x, "X one\n").unwrap();
let ctx = dir_ctx(&root, &out);
let mut state = empty_dir_state();
state.known_files.extend([a.clone(), x.clone()]);
state.last_mtimes = snapshot_state(&state.watched_set());
std::fs::write(&x, "").unwrap();
rebuild_dir_batch(&ctx, &BTreeSet::from([a.clone()]), false, &mut state, None);
assert!(
state.hold.deadline().is_some(),
"control: the batch is held while x is empty"
);
std::fs::write(&x, "X two\n").unwrap();
rebuild_dir_batch(&ctx, &BTreeSet::new(), false, &mut state, None);
let read = |name: &str| std::fs::read_to_string(out.join(name)).ok();
assert!(
read("a.md").is_some_and(|text| text.contains("A one")),
"positive control: the held batch is rebuilt; out/a.md: {:?}",
read("a.md")
);
assert!(
read("x.md").is_some_and(|text| text.contains("X two")),
"the file found emptied is rebuilt with it; out/x.md: {:?}",
read("x.md")
);
}
#[test]
fn a_batch_the_vars_file_could_not_be_read_for_is_rebuilt_with_the_next() {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let (_vars_dir, vars_dir) = canonical_tempdir();
let vars = vars_dir.join("vars.json");
let known = root.join("known.mds");
let gone = root.join("gone.mds");
let created = root.join("created.mds");
std::fs::write(&known, "Known {{v}}\n").unwrap();
std::fs::write(&gone, "Gone {{v}}\n").unwrap();
std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
let ctx = DirWatchCtx {
vars_path: Some(vars.clone()),
vars_path_typed: Some(vars.clone()),
..dir_ctx(&root, &out)
};
let mut state = empty_dir_state();
state.vars_file = Some(vars.clone());
state.known_files.extend([known.clone(), gone.clone()]);
rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);
let read = |name: &str| std::fs::read_to_string(out.join(name)).ok();
assert!(
read("gone.md").is_some_and(|text| text.contains("Gone one")),
"control: the session wrote out/gone.md; {:?}",
read("gone.md")
);
std::fs::write(&vars, r#"{"v": "#).unwrap();
rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);
std::fs::write(&created, "Created {{v}}\n").unwrap();
std::fs::remove_file(&gone).unwrap();
let batch = BTreeSet::from([created.clone(), gone.clone()]);
rebuild_dir_batch(&ctx, &batch, false, &mut state, None);
assert_eq!(
read("created.md"),
None,
"control: nothing is compiled while the vars file cannot be read"
);
std::fs::write(&vars, r#"{"v": "two"}"#).unwrap();
rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);
assert!(
read("known.md").is_some_and(|text| text.contains("Known two")),
"positive control: the vars fix recompiles the known source; out/known.md: {:?}",
read("known.md")
);
assert!(
read("created.md").is_some_and(|text| text.contains("Created two")),
"the source created while the vars file was broken is compiled; \
out/created.md: {:?}",
read("created.md")
);
assert!(
state.known_files.contains(&created) && !state.known_files.contains(&gone),
"the created source is known, the deleted one not; known: {:?}",
state.known_files
);
assert_eq!(
read("gone.md"),
None,
"the source deleted while the vars file was broken is retired"
);
assert_eq!(state.held, HeldBatch::default(), "nothing stays held");
}
#[test]
fn a_vars_change_kept_for_the_next_batch_recompiles_every_known_source() {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let (_vars_dir, vars_dir) = canonical_tempdir();
let vars = vars_dir.join("vars.json");
let (a, b) = (root.join("a.mds"), root.join("b.mds"));
std::fs::write(&a, "A {{v}}\n").unwrap();
std::fs::write(&b, "B {{v}}\n").unwrap();
std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
let ctx = DirWatchCtx {
vars_path: Some(vars.clone()),
vars_path_typed: Some(vars.clone()),
..dir_ctx(&root, &out)
};
let mut state = empty_dir_state();
state.vars_file = Some(vars.clone());
state.known_files.extend([a.clone(), b.clone()]);
rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);
let read = |name: &str| std::fs::read_to_string(out.join(name)).ok();
assert!(
read("b.md").is_some_and(|text| text.contains("B one")),
"control: out/b.md is compiled against the first vars; {:?}",
read("b.md")
);
std::fs::write(&vars, r#"{"v": "#).unwrap();
rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);
std::fs::write(&vars, r#"{"v": "two"}"#).unwrap();
std::fs::write(&a, "A again {{v}}\n").unwrap();
rebuild_dir_batch(&ctx, &BTreeSet::from([a.clone()]), false, &mut state, None);
assert!(
read("a.md").is_some_and(|text| text.contains("A again two")),
"positive control: the edited source is compiled; out/a.md: {:?}",
read("a.md")
);
assert!(
read("b.md").is_some_and(|text| text.contains("B two")),
"the vars change kept from the batch that could not read it recompiles the \
other known source; out/b.md: {:?}",
read("b.md")
);
}
#[test]
fn a_vars_changed_batch_recompiles_the_sources_whose_last_compile_failed() {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let (_vars_dir, vars_dir) = canonical_tempdir();
let (_elsewhere_dir, elsewhere) = canonical_tempdir();
let vars = vars_dir.join("vars.json");
let known = root.join("known.mds");
let created = root.join("created.mds");
let failing = root.join("failing.mds");
let excluded = root.join("node_modules").join("dep.mds");
let outside = elsewhere.join("outside.mds");
std::fs::create_dir(root.join("node_modules")).unwrap();
std::fs::write(&known, "Known {{v}}\n").unwrap();
std::fs::write(&excluded, "Excluded {{x}}\n").unwrap();
std::fs::write(&outside, "Outside {{x}}\n").unwrap();
std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
let ctx = DirWatchCtx {
vars_path: Some(vars.clone()),
vars_path_typed: Some(vars.clone()),
..dir_ctx(&root, &out)
};
let mut state = empty_dir_state();
state.vars_file = Some(vars.clone());
state.known_files.insert(known.clone());
rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);
let read = |rel: &Path| std::fs::read_to_string(out.join(rel)).ok();
assert!(
read(Path::new("known.md")).is_some_and(|text| text.contains("Known one")),
"control: out/known.md is compiled against the first vars; {:?}",
read(Path::new("known.md"))
);
std::fs::write(&created, "Created {{x}}\n").unwrap();
std::fs::write(&failing, "Failing {{missing}}\n").unwrap();
let batch = BTreeSet::from([created.clone(), failing.clone()]);
rebuild_dir_batch(&ctx, &batch, false, &mut state, None);
assert!(
read(Path::new("created.md")).is_none()
&& state.errored.contains(&created)
&& !state.known_files.contains(&created),
"control: the created source's compile failed, and it is errored, not known; \
errored: {:?}, known: {:?}",
state.errored,
state.known_files
);
state.errored.extend([excluded.clone(), outside.clone()]);
std::fs::write(&vars, r#"{"v": "two", "x": "World"}"#).unwrap();
rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);
assert!(
read(Path::new("known.md")).is_some_and(|text| text.contains("Known two")),
"positive control: the vars change recompiles the known source; \
out/known.md: {:?}",
read(Path::new("known.md"))
);
assert!(
read(Path::new("created.md")).is_some_and(|text| text.contains("Created World")),
"the source whose last compile failed is recompiled; out/created.md: {:?}",
read(Path::new("created.md"))
);
assert!(
state.known_files.contains(&created) && !state.errored.contains(&created),
"and is known, no longer errored; known: {:?}, errored: {:?}",
state.known_files,
state.errored
);
assert!(
read(Path::new("failing.md")).is_none() && state.errored.contains(&failing),
"a source still failing stays errored; errored: {:?}",
state.errored
);
for rel in [
Path::new("node_modules").join("dep.md"),
PathBuf::from("outside.md"),
] {
assert_eq!(
read(&rel),
None,
"{}: an errored path that is no source below the root is not compiled as one",
rel.display()
);
}
for path in [&excluded, &outside] {
assert!(
!state.known_files.contains(path) && !state.errored.contains(path),
"{}: neither known nor errored; known: {:?}, errored: {:?}",
path.display(),
state.known_files,
state.errored
);
}
}
fn idle_liveness() -> LivenessState {
LivenessState {
first_tick: false,
root_was_missing: false,
root_armed: true,
missing_external_dirs: BTreeSet::new(),
armed_dirs: BTreeSet::new(),
failing_dirs: BTreeSet::new(),
}
}
#[derive(Debug, PartialEq, Eq)]
enum WatchCall {
Watch(PathBuf),
Unwatch(PathBuf),
}
#[derive(Default)]
struct RecordingWatcher {
calls: Vec<WatchCall>,
}
impl Watcher for RecordingWatcher {
fn new<F: notify::EventHandler>(_: F, _: notify::Config) -> notify::Result<Self> {
Ok(Self::default())
}
fn watch(&mut self, path: &Path, _: RecursiveMode) -> notify::Result<()> {
self.calls.push(WatchCall::Watch(path.to_path_buf()));
Ok(())
}
fn unwatch(&mut self, path: &Path) -> notify::Result<()> {
self.calls.push(WatchCall::Unwatch(path.to_path_buf()));
Ok(())
}
fn kind() -> notify::WatcherKind {
notify::WatcherKind::NullWatcher
}
}
fn dir_ctx_with_vars(root: &Path, out: &Path, vars: &Path) -> (DirWatchCtx, DirWatchState) {
let ctx = DirWatchCtx {
vars_path: Some(vars.to_path_buf()),
vars_path_typed: Some(vars.to_path_buf()),
vars_dir_extra: vars.parent().map(Path::to_path_buf),
..dir_ctx(root, out)
};
let mut state = empty_dir_state();
state.vars_file = Some(vars.to_path_buf());
state.last_mtimes = snapshot_state(&state.watched_set());
(ctx, state)
}
#[test]
fn a_tick_watches_a_directory_only_when_the_watcher_does_not_hold_it() {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let (_vars_parent, vars_parent) = canonical_tempdir();
let (_ext_dir, ext) = canonical_tempdir();
let vars_dir = vars_parent.join("cfg");
let vars = vars_dir.join("vars.json");
std::fs::create_dir(&vars_dir).unwrap();
std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
let (ctx, mut state) = dir_ctx_with_vars(&root, &out, &vars);
state.external_dep_dirs.insert(ext.clone());
let mut liveness = LivenessState {
first_tick: true,
..idle_liveness()
};
let mut watcher = RecordingWatcher::default();
for _ in 0..6 {
liveness_probe_dir(&ctx, &mut watcher, &mut liveness, &mut state);
}
assert_eq!(
watcher.calls,
[
WatchCall::Watch(ext.clone()),
WatchCall::Watch(vars_dir.clone())
],
"six ticks watch each directory the watcher did not hold once — the positive \
control — and nothing else"
);
}
#[test]
fn a_vars_directory_back_from_vanishing_is_watched_once_more() {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let (_vars_parent, vars_parent) = canonical_tempdir();
let vars_dir = vars_parent.join("cfg");
let vars = vars_dir.join("vars.json");
std::fs::create_dir(&vars_dir).unwrap();
std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
let (ctx, mut state) = dir_ctx_with_vars(&root, &out, &vars);
let mut liveness = LivenessState {
armed_dirs: BTreeSet::from([vars_dir.clone()]),
..idle_liveness()
};
let mut watcher = RecordingWatcher::default();
liveness_probe_dir(&ctx, &mut watcher, &mut liveness, &mut state);
assert_eq!(
watcher.calls,
[],
"control: the held directory is not watched"
);
std::fs::remove_dir_all(&vars_dir).unwrap();
liveness_probe_dir(&ctx, &mut watcher, &mut liveness, &mut state);
assert_eq!(watcher.calls, [], "a directory that is gone is not watched");
std::fs::create_dir(&vars_dir).unwrap();
std::fs::write(&vars, r#"{"v": "two"}"#).unwrap();
for _ in 0..3 {
liveness_probe_dir(&ctx, &mut watcher, &mut liveness, &mut state);
}
assert_eq!(
watcher.calls,
[WatchCall::Watch(vars_dir.clone())],
"the directory back is watched once, by the first tick that finds it"
);
}
#[test]
fn a_vars_directory_a_dependency_shares_stays_watched_once_the_import_goes() {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let (_shared_dir, shared) = canonical_tempdir();
let (_other_dir, other) = canonical_tempdir();
let vars = shared.join("vars.json");
std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
let (ctx, mut state) = dir_ctx_with_vars(&root, &out, &vars);
state
.external_dep_dirs
.extend([shared.clone(), other.clone()]);
let mut liveness = LivenessState {
armed_dirs: BTreeSet::from([shared.clone(), other.clone()]),
..idle_liveness()
};
let mut watcher = RecordingWatcher::default();
liveness_probe_dir(&ctx, &mut watcher, &mut liveness, &mut state);
assert_eq!(
watcher.calls,
[],
"every directory is held: nothing is watched"
);
state.external_dep_dirs.clear();
for _ in 0..3 {
liveness_probe_dir(&ctx, &mut watcher, &mut liveness, &mut state);
}
assert_eq!(
watcher.calls,
[WatchCall::Unwatch(other.clone())],
"the directory nothing needs is unwatched — the positive control — and the vars \
file's is left as it is"
);
assert_eq!(liveness.armed_dirs, BTreeSet::from([shared]));
}
#[test]
fn a_rebuild_unwatches_a_directory_no_source_imports_any_more() {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let (_vars_dir, vars_dir) = canonical_tempdir();
let (_kept_dir, kept) = canonical_tempdir();
let (_gone_dir, gone) = canonical_tempdir();
let vars = vars_dir.join("vars.json");
std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
let (ctx, mut state) = dir_ctx_with_vars(&root, &out, &vars);
state.external_dep_dirs.insert(kept.clone());
let mut liveness = LivenessState {
armed_dirs: BTreeSet::from([vars_dir.clone(), kept.clone(), gone.clone()]),
..idle_liveness()
};
let mut watcher = RecordingWatcher::default();
arm_external_dirs_after_rebuild(&ctx, &mut watcher, &mut liveness, &state);
assert_eq!(
watcher.calls,
[WatchCall::Unwatch(gone.clone())],
"the directory no source imports is unwatched — the positive control — and \
nothing else is unwatched or watched"
);
assert_eq!(liveness.armed_dirs, BTreeSet::from([vars_dir, kept]));
}
struct CrossRootPage {
dirs: (tempfile::TempDir, tempfile::TempDir),
base: PathBuf,
out: PathBuf,
page: PathBuf,
module: PathBuf,
shared: PathBuf,
vars: PathBuf,
ctx: DirWatchCtx,
state: DirWatchState,
}
fn cross_root_page() -> CrossRootPage {
let (base_dir, base) = canonical_tempdir();
let (out_dir, out) = canonical_tempdir();
let (root, shared) = (base.join("root"), base.join("shared"));
std::fs::create_dir(&root).unwrap();
std::fs::create_dir(&shared).unwrap();
std::fs::write(base.join(".mdsroot"), "").unwrap();
let (page, module) = (root.join("page.mds"), shared.join("_x.mds"));
std::fs::write(
&page,
"@import \"../shared/_x.mds\" as x\n{{x.greet()}} {{v}}\n",
)
.unwrap();
std::fs::write(&module, "@define greet():\nX\n@end\n\n@export greet\n").unwrap();
let vars = base.join("vars.json");
std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
let (ctx, mut state) = dir_ctx_with_vars(&root, &out, &vars);
state.known_files.insert(page.clone());
rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);
assert!(
state.tracked_set().contains(&module) && state.external_dep_dirs.contains(&shared),
"control: the first batch tracks the dependency outside the root; out/page.md: {:?}",
std::fs::read_to_string(out.join("page.md")).ok()
);
CrossRootPage {
dirs: (base_dir, out_dir),
base,
out,
page,
module,
shared,
vars,
ctx,
state,
}
}
#[test]
fn a_batch_forgets_a_directory_no_source_imports_any_more() {
for vars_changed in [false, true] {
let CrossRootPage {
dirs: _dirs,
base,
out,
page,
module,
shared,
vars,
ctx,
mut state,
} = cross_root_page();
std::fs::write(&page, "Page {{v}}\n").unwrap();
if vars_changed {
std::fs::write(&vars, r#"{"v": "two"}"#).unwrap();
}
let batch = BTreeSet::from([page.clone()]);
rebuild_dir_batch(&ctx, &batch, vars_changed, &mut state, None);
let written = std::fs::read_to_string(out.join("page.md")).ok();
assert!(
written
.as_deref()
.is_some_and(|text| text.starts_with("Page ")),
"vars changed: {vars_changed}: control: the source compiled without the \
import; out/page.md: {written:?}"
);
assert!(
!state.tracked_set().contains(&module)
&& !state.external_dep_dirs.contains(&shared),
"vars changed: {vars_changed}: the directory no source imports from is \
forgotten; known: {:?}",
state.external_dep_dirs
);
let mut liveness = LivenessState {
armed_dirs: BTreeSet::from([base.clone(), shared.clone()]),
..idle_liveness()
};
let mut watcher = RecordingWatcher::default();
arm_external_dirs_after_rebuild(&ctx, &mut watcher, &mut liveness, &state);
assert_eq!(
watcher.calls,
[WatchCall::Unwatch(shared)],
"vars changed: {vars_changed}: the rebuild unwatches it, and leaves the vars \
file's directory watched"
);
}
}
#[test]
fn a_vars_change_keeps_the_dependencies_of_a_source_that_failed_or_was_held() {
let cases = [
("a failed compile", r#"{"w": "two"}"#, false, false),
(
"a compile held on its source",
r#"{"v": "two"}"#,
true,
false,
),
(
"a compile failed on its dependency",
r#"{"v": "two"}"#,
false,
true,
),
];
for (label, vars_text, empties_source, empties_dependency) in cases {
let (_gone_dir, gone) = canonical_tempdir();
let CrossRootPage {
dirs: _dirs,
base,
out: _,
page,
module,
shared,
vars,
ctx,
mut state,
} = cross_root_page();
std::fs::write(&vars, vars_text).unwrap();
if empties_source {
std::fs::write(&page, "").unwrap();
}
if empties_dependency {
std::fs::write(&module, "").unwrap();
}
let runtime_vars = build_runtime_vars(RuntimeVarArgs {
vars: Some(vars.clone()),
set_vars: Vec::new(),
set_string_vars: Vec::new(),
})
.unwrap()
.vars;
process_dir_batch(
&BTreeSet::new(),
true,
&mut BatchCtx {
watch_root: &ctx.root,
output_base: &ctx.output_base,
vars: BatchVars::map_only(&runtime_vars),
quiet: true,
},
&mut state,
);
let (held, errored) = (
state.held.paths.contains(&page),
state.errored.contains(&page),
);
if empties_source || empties_dependency {
assert!(
held && !errored,
"{label}: the source is held, not reported; held: {:?}, errored: {:?}",
state.held,
state.errored
);
} else {
assert!(
errored && !held,
"{label}: control: the compile failed; errored: {:?}",
state.errored
);
}
assert!(
state.tracked_set().contains(&module),
"{label}: the dependency outside the root is still tracked; tracked: {:?}",
state.tracked_set()
);
assert!(
state.external_dep_dirs.contains(&shared),
"{label}: its directory is still known; {:?}",
state.external_dep_dirs
);
let mut liveness = LivenessState {
armed_dirs: BTreeSet::from([base.clone(), shared.clone(), gone.clone()]),
..idle_liveness()
};
let mut watcher = RecordingWatcher::default();
arm_external_dirs_after_rebuild(&ctx, &mut watcher, &mut liveness, &state);
assert_eq!(
watcher.calls,
[WatchCall::Unwatch(gone.clone())],
"{label}: the directory nothing imports is unwatched — the positive control — \
and the dependency's stays watched"
);
}
}
#[test]
fn a_retired_output_that_is_not_there_is_gone_with_its_record() {
let (_dir, root) = canonical_tempdir();
let src = root.join("page.mds");
std::fs::write(root.join("file"), "a file, no directory\n").unwrap();
for (label, out) in [
("a missing name", root.join("page.md")),
("a file on its way", root.join("file").join("page.md")),
] {
let target = WriteTarget::as_typed(out.clone());
assert!(
retire_output(
&target,
None,
OutDirNow::Unchanged,
Record::Unwritten,
Retirement::SourceDeleted,
true,
),
"{label}: with no record, the output is gone — not kept, with a notice"
);
let mut state = empty_dir_state();
state.wrote(&src, &target, "Page.\n".to_owned());
state.retire(
&src,
&target,
OutDirNow::Unchanged,
Retirement::SourceDeleted,
true,
);
assert_eq!(
state.record(&out, &src),
Record::Unwritten,
"{label}: the output is gone, and its record with it"
);
}
}
#[cfg(unix)]
#[test]
fn a_retired_output_that_cannot_be_looked_at_keeps_its_record() {
use std::os::unix::fs::PermissionsExt as _;
let (_dir, root) = canonical_tempdir();
let (src, sub) = (root.join("page.mds"), root.join("sub"));
std::fs::create_dir(&sub).unwrap();
let out = sub.join("page.md");
std::fs::write(&out, "Page.\n").unwrap();
let target = WriteTarget::as_typed(out.clone());
let mut state = empty_dir_state();
state.wrote(&src, &target, "Page.\n".to_owned());
std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o000)).unwrap();
if std::fs::symlink_metadata(&out).is_ok() {
std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o755)).unwrap();
crate::output::ewriteln!("running as root; mode 0o000 does not stop a look");
return;
}
state.retire(
&src,
&target,
OutDirNow::Unchanged,
Retirement::SourceDeleted,
true,
);
let kept = state.record(&out, &src) == Record::Own("Page.\n");
std::fs::set_permissions(&sub, std::fs::Permissions::from_mode(0o755)).unwrap();
assert!(
kept,
"an output that cannot be looked at keeps the session's record of it"
);
assert_eq!(
std::fs::read_to_string(&out).ok().as_deref(),
Some("Page.\n"),
"and is left as it is"
);
state.retire(
&src,
&target,
OutDirNow::Unchanged,
Retirement::SourceDeleted,
true,
);
assert!(
!out.exists() && state.record(&out, &src) == Record::Unwritten,
"positive control: the directory searchable again, the output is removed and \
its record goes"
);
}
#[test]
fn a_file_event_s_rebuild_asks_for_the_clear_only_under_clear() {
const NAME: &str =
"watch::tests::a_file_event_s_rebuild_asks_for_the_clear_only_under_clear";
if child_process::is_child(NAME) {
let (_dir, root) = canonical_tempdir();
let (entry, other) = (root.join("page.mds"), root.join("other.txt"));
let foi: HashSet<PathBuf> = std::iter::once(entry.clone()).collect();
let (_tx, rx) = mpsc::channel::<Msg>();
for clear in [false, true] {
crate::output::cancel_clear();
let skipped = handle_fs_event_file(
modify_event(other.to_str().unwrap()),
&foi,
&rx,
0,
clear,
);
assert!(
matches!(skipped, FileEventAction::Skip) && !child_process::clear_is_asked(),
"--clear: {clear}: control: an event that rebuilds nothing asks for nothing"
);
let action = handle_fs_event_file(
modify_event(entry.to_str().unwrap()),
&foi,
&rx,
0,
clear,
);
assert!(
matches!(action, FileEventAction::Rebuild),
"--clear: {clear}: control: the event rebuilds"
);
assert_eq!(
child_process::clear_is_asked(),
clear,
"--clear: {clear}: the event's rebuild asks for the clear"
);
}
return;
}
let _ = stderr_of_a_child_on_a_terminal(NAME);
}
const CLEAR: &str = "\x1b[2J\x1b[3J\x1b[H";
fn stderr_of_a_child_on_a_terminal(name: &str) -> String {
let child = child_process::run_on_a_terminal(name);
let report = String::from_utf8_lossy(&child.stdout).into_owned();
let printed = String::from_utf8_lossy(&child.stderr).into_owned();
assert!(
report.contains("running 1 test"),
"control: the child ran the test; stdout:\n{report}"
);
assert!(
child.status.success(),
"the child's test passes; stdout:\n{report}\nstderr:\n{printed}"
);
printed
}
fn page_with_a_warning(root: &Path, name: &str) -> PathBuf {
std::fs::write(
root.join("_fns.mds"),
"@define greet(who):\nHello {{who}}!\n@end\n\n@export greet\n",
)
.unwrap();
let page = root.join(name);
std::fs::write(
&page,
"@import \"./_fns.mds\" as fns\nBefore\n@include fns\nAfter\n",
)
.unwrap();
page
}
fn idle_watcher() -> RecommendedWatcher {
RecommendedWatcher::new(|_: notify::Result<Event>| {}, notify::Config::default()).unwrap()
}
fn file_state_writing(entry: &Path, out: Option<&Path>) -> FileWatchState {
let mut state = file_state(std::iter::once(entry.to_path_buf()).collect());
state.output = OutputRoute::Named(out.map(|out| WriteTarget::as_typed(out.to_path_buf())));
state.last_mtimes = snapshot_state(&state.foi);
state
}
#[test]
fn a_file_rebuild_prints_its_compile_warning_after_the_clear() {
const NAME: &str =
"watch::tests::a_file_rebuild_prints_its_compile_warning_after_the_clear";
if child_process::is_child(NAME) {
let (_dir, root) = canonical_tempdir();
let entry = page_with_a_warning(&root, "page.mds");
let ctx = FileCompileCtx {
quiet: false,
..file_ctx(&entry)
};
let mut state = file_state_writing(&entry, Some(&root.join("page.md")));
crate::output::ask_clear();
let _ = rebuild_file(&ctx, &mut idle_watcher(), &mut state, None);
return;
}
let printed = stderr_of_a_child_on_a_terminal(NAME);
assert!(
printed.starts_with(CLEAR),
"the clear is the first thing the rebuild prints:\n{printed:?}"
);
assert_eq!(printed.matches(CLEAR).count(), 1, "made once:\n{printed:?}");
let (warning, recompiled) = (printed.find("warning:"), printed.find("Recompiled"));
assert!(
warning.is_some() && warning < recompiled,
"control: the warning is printed, before the Recompiled line:\n{printed:?}"
);
}
#[test]
fn a_held_file_rebuild_leaves_the_clear_to_the_rebuild_that_ends_the_hold() {
const NAME: &str =
"watch::tests::a_held_file_rebuild_leaves_the_clear_to_the_rebuild_that_ends_the_hold";
if child_process::is_child(NAME) {
let (_dir, root) = canonical_tempdir();
let (entry, module, out) = (
root.join("page.mds"),
root.join("_inc.mds"),
root.join("page.md"),
);
let mut watcher = idle_watcher();
let ctx = FileCompileCtx {
quiet: false,
..file_ctx(&entry)
};
for held_by in ["its look", "its compile"] {
std::fs::write(
&entry,
"@import \"./_inc.mds\" as inc\nPage.\n@include inc\n",
)
.unwrap();
std::fs::write(&module, "Inc.\n").unwrap();
let mut state = file_state_writing(&entry, Some(&out));
if held_by == "its look" {
std::fs::write(&entry, "").unwrap();
} else {
std::fs::write(&module, "").unwrap();
state.last_mtimes.insert(module.clone(), (None, Some(5)));
}
crate::output::ask_clear();
let _ = rebuild_file(&ctx, &mut watcher, &mut state, None);
assert!(
state.hold.deadline().is_some(),
"{held_by}: control: the rebuild is held"
);
assert_eq!(
child_process::clear_is_asked(),
held_by == "its look",
"{held_by}: a rebuild held before it prints leaves the clear asked for"
);
let due = if held_by == "its look" {
state.hold.deadline()
} else {
std::fs::write(&module, "Inc.\n").unwrap();
None
};
let _ = rebuild_file(&ctx, &mut watcher, &mut state, due);
assert_eq!(
state.hold.deadline(),
None,
"{held_by}: control: the hold ends"
);
assert!(
!child_process::clear_is_asked(),
"{held_by}: the rebuild that ends the hold made the clear"
);
}
return;
}
let printed = stderr_of_a_child_on_a_terminal(NAME);
let shown: Vec<&str> = printed.split(CLEAR).collect();
assert!(
shown.len() == 3
&& shown[0].is_empty()
&& shown[1].starts_with("Recompiled")
&& shown[2].starts_with("warning:")
&& shown[2].contains("Recompiled"),
"held by its look: one clear before the line of the rebuild that ends the hold, \
none before the held rebuild; held by its compile: one clear before the \
compile's own warning, none before the line of the rebuild that ends the \
hold; stderr:\n{printed:?}"
);
}
#[test]
fn a_file_rebuild_that_prints_nothing_leaves_no_clear_behind() {
const NAME: &str =
"watch::tests::a_file_rebuild_that_prints_nothing_leaves_no_clear_behind";
if child_process::is_child(NAME) {
let (_dir, root) = canonical_tempdir();
let (entry, out) = (root.join("page.mds"), root.join("page.md"));
std::fs::write(&entry, "Page.\n").unwrap();
let ctx = FileCompileCtx {
quiet: false,
..file_ctx(&entry)
};
let mut state = file_state_writing(&entry, Some(&out));
let mut watcher = idle_watcher();
crate::output::ask_clear();
let _ = rebuild_file(&ctx, &mut watcher, &mut state, None);
assert!(
!child_process::clear_is_asked(),
"control: the first rebuild printed"
);
crate::output::ask_clear();
let _ = rebuild_file(&ctx, &mut watcher, &mut state, None);
assert!(
!child_process::clear_is_asked(),
"a rebuild that printed nothing leaves no clear behind"
);
eprint_warning("a later line");
return;
}
let printed = stderr_of_a_child_on_a_terminal(NAME);
assert_eq!(printed.matches(CLEAR).count(), 1, "one clear:\n{printed:?}");
assert!(
printed.starts_with(CLEAR) && printed.ends_with("a later line\n"),
"only the first rebuild's line is preceded by it:\n{printed:?}"
);
}
#[test]
fn a_stdout_rebuild_clears_before_its_output() {
const NAME: &str = "watch::tests::a_stdout_rebuild_clears_before_its_output";
if child_process::is_child(NAME) {
let (_dir, root) = canonical_tempdir();
let entry = root.join("page.mds");
std::fs::write(&entry, "Page body.\n").unwrap();
let mut state = file_state_writing(&entry, None);
crate::output::ask_clear();
let _ = rebuild_file(&file_ctx(&entry), &mut idle_watcher(), &mut state, None);
return;
}
let child = child_process::run_on_a_terminal(NAME);
let (report, printed) = (
String::from_utf8_lossy(&child.stdout),
String::from_utf8_lossy(&child.stderr),
);
assert!(
report.contains("running 1 test") && child.status.success(),
"control: the child ran the test and it passed; stdout:\n{report}\nstderr:\n{printed}"
);
assert!(
report.contains("Page body."),
"control: the compiled output reached stdout:\n{report}"
);
assert_eq!(printed, CLEAR, "the clear, and nothing else, on stderr");
}
#[test]
fn a_rebuild_that_reports_a_failure_makes_the_clear_first() {
const NAME: &str = "watch::tests::a_rebuild_that_reports_a_failure_makes_the_clear_first";
if child_process::is_child(NAME) {
let (_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let (entry, vars) = (root.join("page.mds"), root.join("vars.json"));
let mut watcher = idle_watcher();
for failure in ["the --vars file", "the compile"] {
std::fs::write(&entry, "Page {{v}}\n").unwrap();
let vars_text = if failure == "the --vars file" {
r#"{"v": "#
} else {
r#"{"w": "one"}"#
};
std::fs::write(&vars, vars_text).unwrap();
let ctx = FileCompileCtx {
vars_path: Some(vars.clone()),
vars_path_typed: Some(vars.clone()),
quiet: false,
..file_ctx(&entry)
};
let mut state = file_state([entry.clone(), vars.clone()].into_iter().collect());
state.last_mtimes = snapshot_state(&state.foi);
crate::output::ask_clear();
let _ = rebuild_file(&ctx, &mut watcher, &mut state, None);
assert!(
state.hold.deadline().is_none(),
"file mode, {failure}: control: nothing is held"
);
assert!(
!child_process::clear_is_asked(),
"file mode, {failure}: the rebuild that reports it made the clear"
);
}
std::fs::write(&vars, r#"{"v": "#).unwrap();
let (ctx, mut state) = dir_ctx_with_vars(&root, &out, &vars);
let ctx = DirWatchCtx {
quiet: false,
..ctx
};
state.known_files.insert(entry.clone());
crate::output::ask_clear();
rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);
assert!(
state.hold.deadline().is_none() && state.held.vars_changed,
"directory mode: control: the batch is kept for the next, not held"
);
assert!(
!child_process::clear_is_asked(),
"directory mode, the --vars file: the batch that reports it made the clear"
);
return;
}
let printed = stderr_of_a_child_on_a_terminal(NAME);
let shown: Vec<&str> = printed.split(CLEAR).collect();
assert!(
shown.len() == 4 && shown[0].is_empty() && shown[1..].iter().all(|r| !r.is_empty()),
"each of the three failures is reported after a clear of its own:\n{printed:?}"
);
}
fn dir_session_of_two_sources(
clear: bool,
) -> (
(tempfile::TempDir, tempfile::TempDir),
PathBuf,
DirWatchCtx,
DirWatchState,
) {
let (root_dir, root) = canonical_tempdir();
let (out_dir, out) = canonical_tempdir();
std::fs::write(root.join("a.mds"), "A one\n").unwrap();
std::fs::write(root.join("x.mds"), "X one\n").unwrap();
let ctx = DirWatchCtx {
clear,
quiet: false,
..dir_ctx(&root, &out)
};
let mut state = empty_dir_state();
state
.known_files
.extend([root.join("a.mds"), root.join("x.mds")]);
state.last_mtimes = snapshot_state(&state.watched_set());
((root_dir, out_dir), root, ctx, state)
}
#[test]
fn a_directory_batch_prints_its_compile_warning_after_the_clear() {
const NAME: &str =
"watch::tests::a_directory_batch_prints_its_compile_warning_after_the_clear";
if child_process::is_child(NAME) {
let (_dirs, root, ctx, mut state) = dir_session_of_two_sources(true);
let a = page_with_a_warning(&root, "a.mds");
let (_tx, rx) = mpsc::channel::<Msg>();
let outcome =
handle_fs_event_dir(modify_event(a.to_str().unwrap()), &ctx, &rx, &mut state);
assert!(
matches!(outcome, DirEventOutcome::Done),
"control: it rebuilds"
);
return;
}
let printed = stderr_of_a_child_on_a_terminal(NAME);
assert!(
printed.starts_with(CLEAR),
"the clear is the first thing the batch prints:\n{printed:?}"
);
assert_eq!(printed.matches(CLEAR).count(), 1, "made once:\n{printed:?}");
let (warning, recompiled) = (printed.find("warning:"), printed.find("Recompiled"));
assert!(
warning.is_some() && warning < recompiled,
"control: the warning is printed, before the Recompiled line:\n{printed:?}"
);
}
#[test]
fn a_held_directory_batch_leaves_the_clear_to_the_batch_that_ends_the_hold() {
const NAME: &str =
"watch::tests::a_held_directory_batch_leaves_the_clear_to_the_batch_that_ends_the_hold";
if child_process::is_child(NAME) {
let (_dirs, root, ctx, mut state) = dir_session_of_two_sources(true);
let (a, x) = (root.join("a.mds"), root.join("x.mds"));
std::fs::write(&x, "").unwrap();
let (_tx, rx) = mpsc::channel::<Msg>();
let outcome =
handle_fs_event_dir(modify_event(a.to_str().unwrap()), &ctx, &rx, &mut state);
assert!(
matches!(outcome, DirEventOutcome::Done) && state.hold.deadline().is_some(),
"control: the event's batch is held"
);
assert!(
child_process::clear_is_asked(),
"the held batch printed nothing and leaves the clear its event asked for"
);
std::fs::write(&x, "X two\n").unwrap();
rebuild_dir_batch(&ctx, &BTreeSet::new(), false, &mut state, None);
assert_eq!(state.hold.deadline(), None, "control: the hold ends");
assert!(
!child_process::clear_is_asked(),
"the batch that ends the hold made the clear"
);
return;
}
let printed = stderr_of_a_child_on_a_terminal(NAME);
assert!(
printed.starts_with(CLEAR) && printed.matches(CLEAR).count() == 1,
"one clear, before the first line of the batch that ends the hold:\n{printed:?}"
);
assert!(
printed.contains("Recompiled"),
"control: that batch printed:\n{printed:?}"
);
}
#[test]
fn a_directory_batch_that_prints_nothing_leaves_no_clear_behind() {
const NAME: &str =
"watch::tests::a_directory_batch_that_prints_nothing_leaves_no_clear_behind";
if child_process::is_child(NAME) {
let (_dirs, root, ctx, mut state) = dir_session_of_two_sources(true);
let a = root.join("a.mds");
let batch = BTreeSet::from([a]);
crate::output::ask_clear();
rebuild_dir_batch(&ctx, &batch, false, &mut state, None);
assert!(
!child_process::clear_is_asked(),
"control: the first batch printed"
);
crate::output::ask_clear();
rebuild_dir_batch(&ctx, &batch, false, &mut state, None);
assert!(
!child_process::clear_is_asked(),
"a batch that printed nothing leaves no clear behind"
);
eprint_warning("a later line");
return;
}
let printed = stderr_of_a_child_on_a_terminal(NAME);
assert_eq!(printed.matches(CLEAR).count(), 1, "one clear:\n{printed:?}");
assert!(
printed.starts_with(CLEAR) && printed.ends_with("a later line\n"),
"only the first batch's line is preceded by it:\n{printed:?}"
);
}
#[test]
fn a_directory_event_asks_for_the_clear_only_under_clear() {
const NAME: &str = "watch::tests::a_directory_event_asks_for_the_clear_only_under_clear";
if child_process::is_child(NAME) {
let (_dirs, root, _ctx, _state) = dir_session_of_two_sources(false);
let (a, other) = (root.join("a.mds"), root.join("other.txt"));
for clear in [false, true] {
let (_out_dir, out) = canonical_tempdir();
let ctx = DirWatchCtx {
clear,
quiet: false,
..dir_ctx(&root, &out)
};
let mut state = empty_dir_state();
state.known_files.insert(a.clone());
let (_tx, rx) = mpsc::channel::<Msg>();
let skipped = handle_fs_event_dir(
modify_event(other.to_str().unwrap()),
&ctx,
&rx,
&mut state,
);
assert!(
matches!(skipped, DirEventOutcome::Skip) && !child_process::clear_is_asked(),
"--clear: {clear}: control: an event that rebuilds nothing asks for nothing"
);
let done =
handle_fs_event_dir(modify_event(a.to_str().unwrap()), &ctx, &rx, &mut state);
assert!(
matches!(done, DirEventOutcome::Done),
"--clear: {clear}: control: the event rebuilds"
);
}
return;
}
let printed = stderr_of_a_child_on_a_terminal(NAME);
let shown: Vec<&str> = printed.split(CLEAR).collect();
assert!(
shown.len() == 2
&& shown[0].starts_with("Recompiled")
&& shown[1].starts_with("Recompiled"),
"without --clear the line comes alone; with it, after one clear:\n{printed:?}"
);
}
fn refuse(_: &Path) -> notify::Result<()> {
Err(notify::Error::generic("refused"))
}
#[test]
fn a_directory_whose_watch_keeps_failing_is_reported_once_until_a_watch_succeeds() {
let dir = Path::new("/elsewhere/lib");
let (mut armed, mut failing) = (BTreeSet::new(), BTreeSet::new());
let outcomes: Vec<DirArm> = (0..3)
.map(|_| arm_dir(dir, &mut armed, &mut failing, refuse))
.collect();
assert!(
matches!(
outcomes.as_slice(),
[DirArm::Failed(_), DirArm::FailedAgain, DirArm::FailedAgain]
),
"the first failure is reported, the two after it are not: {outcomes:?}"
);
let armed_now = arm_dir(dir, &mut armed, &mut failing, |_| Ok(()));
assert!(
matches!(armed_now, DirArm::Armed),
"control: a watch that succeeds: {armed_now:?}"
);
let mut asked = false;
let held = arm_dir(dir, &mut armed, &mut failing, |_| {
asked = true;
Ok(())
});
assert!(
matches!(held, DirArm::Held) && !asked,
"a directory held is not watched: {held:?}"
);
armed.remove(dir);
let again = arm_dir(dir, &mut armed, &mut failing, refuse);
assert!(
matches!(again, DirArm::Failed(_)),
"a failure after a watch that succeeded is reported again: {again:?}"
);
}
#[test]
fn a_directory_imported_again_reports_its_failed_watch_again() {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let ctx = dir_ctx(&root, &out);
let dir = Path::new("/elsewhere/lib");
let imported = BTreeSet::from([dir.to_path_buf()]);
let mut liveness = idle_liveness();
let mut watcher = RecordingWatcher::default();
let arm = |liveness: &mut LivenessState| {
arm_dir(
dir,
&mut liveness.armed_dirs,
&mut liveness.failing_dirs,
refuse,
)
};
let first = arm(&mut liveness);
unwatch_unimported_dirs(&ctx, &mut watcher, &mut liveness, &imported);
let still = arm(&mut liveness);
assert!(
matches!((&first, &still), (DirArm::Failed(_), DirArm::FailedAgain)),
"control: while it is imported, only the first failure is reported: \
{first:?}, {still:?}"
);
unwatch_unimported_dirs(&ctx, &mut watcher, &mut liveness, &BTreeSet::new());
let back = arm(&mut liveness);
assert!(
matches!(back, DirArm::Failed(_)),
"the directory imported again reports its failed watch again: {back:?}"
);
}
#[test]
fn a_tick_that_arms_a_failing_directory_ends_its_run_of_failures() {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let (_ext_dir, ext) = canonical_tempdir();
let ctx = dir_ctx(&root, &out);
let mut state = empty_dir_state();
state.external_dep_dirs.insert(ext.clone());
let mut liveness = idle_liveness();
let first = arm_dir(
&ext,
&mut liveness.armed_dirs,
&mut liveness.failing_dirs,
refuse,
);
assert!(
matches!(first, DirArm::Failed(_)),
"control: a rebuild's watch failed: {first:?}"
);
let mut watcher = RecordingWatcher::default();
liveness_probe_dir(&ctx, &mut watcher, &mut liveness, &mut state);
assert_eq!(
watcher.calls,
[WatchCall::Watch(ext.clone())],
"control: the tick watches it, and the watch succeeds"
);
liveness.armed_dirs.remove(&ext);
let again = arm_dir(
&ext,
&mut liveness.armed_dirs,
&mut liveness.failing_dirs,
refuse,
);
assert!(
matches!(again, DirArm::Failed(_)),
"a failure after the tick's watch succeeded is reported: {again:?}"
);
}
#[test]
fn an_idle_tick_rebuilds_with_a_vars_edit_whose_event_was_lost() {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let (_vars_dir, vars_dir) = canonical_tempdir();
let vars = vars_dir.join("vars.json");
let a = root.join("a.mds");
std::fs::write(&a, "A {{v}}\n").unwrap();
std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
let (ctx, mut state) = dir_ctx_with_vars(&root, &out, &vars);
state.known_files.insert(a.clone());
rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);
let read = || std::fs::read_to_string(out.join("a.md")).ok();
assert!(
read().is_some_and(|text| text.contains("A one")),
"control: the source is compiled with the vars file; out/a.md: {:?}",
read()
);
std::fs::write(&vars, r#"{"v": "two, longer"}"#).unwrap();
let mut watcher = RecordingWatcher::default();
liveness_probe_dir(&ctx, &mut watcher, &mut idle_liveness(), &mut state);
assert!(
read().is_some_and(|text| text.contains("A two, longer")),
"the tick rebuilds with the vars file as it now reads; out/a.md: {:?}",
read()
);
}
#[test]
fn a_vars_file_s_event_rebuilds_where_other_paths_events_are_dropped() {
for place in [".config", "node_modules", "the out-dir"] {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let (vars_dir, inside_root) = match place {
"the out-dir" => (out.clone(), false),
hidden => (root.join(hidden), true),
};
std::fs::create_dir_all(&vars_dir).unwrap();
let vars = vars_dir.join("vars.json");
let a = root.join("a.mds");
std::fs::write(&a, "A {{v}}\n").unwrap();
std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
let (ctx, mut state) = dir_ctx_with_vars(&root, &out, &vars);
let ctx = DirWatchCtx {
vars_dir_extra: (!inside_root).then(|| vars_dir.clone()),
..ctx
};
state.known_files.insert(a.clone());
rebuild_dir_batch(&ctx, &BTreeSet::new(), true, &mut state, None);
let read = || std::fs::read_to_string(out.join("a.md")).ok();
assert!(
read().is_some_and(|text| text.contains("A one")),
"{place}: control: the source is compiled; out/a.md: {:?}",
read()
);
let (_tx, rx) = mpsc::channel::<Msg>();
let beside = vars_dir.join("beside.mds");
std::fs::write(&beside, "Beside.\n").unwrap();
let outcome = handle_fs_event_dir(
modify_event(beside.to_str().unwrap()),
&ctx,
&rx,
&mut state,
);
assert!(
matches!(outcome, DirEventOutcome::Skip),
"{place}: positive control: a source's event there is dropped"
);
std::fs::write(&vars, r#"{"v": "two"}"#).unwrap();
let outcome =
handle_fs_event_dir(modify_event(vars.to_str().unwrap()), &ctx, &rx, &mut state);
assert!(
matches!(outcome, DirEventOutcome::Done),
"{place}: the vars file's event rebuilds"
);
assert!(
read().is_some_and(|text| text.contains("A two")),
"{place}: with the vars file as it now reads; out/a.md: {:?}",
read()
);
}
}
#[test]
fn an_idle_tick_rebuilds_the_importers_of_a_changed_module_never_the_module() {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let notes = root.join("notes");
std::fs::create_dir(¬es).unwrap();
let (a, b) = (root.join("a.mds"), root.join("b.mds"));
let (inc, lib) = (notes.join("inc.md"), notes.join("lib.md"));
std::fs::write(&a, "@import \"./notes/inc.md\" as inc\nA.\n@include inc\n").unwrap();
std::fs::write(&b, "@import \"./notes/lib.md\" as lib\nB {{lib.hi()}}\n").unwrap();
std::fs::write(&inc, "---\ntype: mds\n---\nIncluded one\n").unwrap();
std::fs::write(&lib, "---\ntype: mds\n---\n@define hi():\nLib one\n@end\n").unwrap();
let ctx = dir_ctx(&root, &out);
let mut state = empty_dir_state();
state.known_files.extend([a.clone(), b.clone()]);
let sources = BTreeSet::from([a.clone(), b.clone()]);
rebuild_dir_batch(&ctx, &sources, false, &mut state, None);
let read = |rel: &Path| std::fs::read_to_string(out.join(rel)).ok();
let tracked = state.tracked_set();
assert!(
read(Path::new("a.md")).is_some_and(|text| text.contains("Included one"))
&& read(Path::new("b.md")).is_some_and(|text| text.contains("B Lib one"))
&& tracked.contains(&inc)
&& tracked.contains(&lib),
"control: both importers are compiled and both modules are tracked, so the \
tick's content check looks at them; out/a.md: {:?}, out/b.md: {:?}, \
tracked: {tracked:?}",
read(Path::new("a.md")),
read(Path::new("b.md"))
);
std::fs::write(&inc, "---\ntype: mds\n---\nIncluded two, longer\n").unwrap();
std::fs::write(
&lib,
"---\ntype: mds\n---\n@define hi():\nLib two, longer\n@end\n",
)
.unwrap();
let mut watcher =
RecommendedWatcher::new(|_: notify::Result<Event>| {}, notify::Config::default())
.unwrap();
liveness_probe_dir(&ctx, &mut watcher, &mut idle_liveness(), &mut state);
assert!(
read(Path::new("a.md")).is_some_and(|text| text.contains("Included two, longer")),
"positive control: the tick rebuilds the module's importer; out/a.md: {:?}",
read(Path::new("a.md"))
);
assert!(
read(Path::new("b.md")).is_some_and(|text| text.contains("B Lib two, longer")),
"positive control: the tick rebuilds the importer of the module whose function \
it calls; out/b.md: {:?}",
read(Path::new("b.md"))
);
for module in [&inc, &lib] {
let rel = module.strip_prefix(&root).unwrap();
assert_eq!(
read(rel),
None,
"{}: a module that is no source is never compiled as one",
rel.display()
);
assert!(
!state.known_files.contains(module) && !state.errored.contains(module),
"{}: neither known nor errored; known: {:?}, errored: {:?}",
rel.display(),
state.known_files,
state.errored
);
}
}
#[test]
fn an_idle_tick_refuses_a_plain_md_dependency_only_through_its_importer() {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let notes = root.join("notes");
std::fs::create_dir(¬es).unwrap();
let a = root.join("a.mds");
let inc = notes.join("inc.md");
std::fs::write(&a, "@import \"./notes/inc.md\" as inc\nA.\n@include inc\n").unwrap();
std::fs::write(&inc, "---\ntype: mds\n---\nIncluded one\n").unwrap();
let ctx = dir_ctx(&root, &out);
let mut state = empty_dir_state();
state.known_files.insert(a.clone());
rebuild_dir_batch(&ctx, &BTreeSet::from([a.clone()]), false, &mut state, None);
assert!(
state.tracked_set().contains(&inc) && state.errored.is_empty(),
"control: the importer compiled and the module is tracked; errored: {:?}",
state.errored
);
std::fs::write(&inc, "Plain text now, with no frontmatter at all\n").unwrap();
let mut watcher =
RecommendedWatcher::new(|_: notify::Result<Event>| {}, notify::Config::default())
.unwrap();
liveness_probe_dir(&ctx, &mut watcher, &mut idle_liveness(), &mut state);
assert!(
state.errored.contains(&a),
"positive control: the tick rebuilds the importer, whose import is refused; \
errored: {:?}",
state.errored
);
assert!(
!state.errored.contains(&inc) && !state.known_files.contains(&inc),
"the plain `.md` is no source, so it is never compiled as one; errored: {:?}, \
known: {:?}",
state.errored,
state.known_files
);
}
#[test]
fn an_event_for_an_md_file_rebuilds_only_when_a_source_imports_it() {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let (a, inc, readme) = (
root.join("a.mds"),
root.join("inc.md"),
root.join("README.md"),
);
std::fs::write(&a, "@import \"./inc.md\" as inc\nA.\n@include inc\n").unwrap();
std::fs::write(&inc, "---\ntype: mds\n---\nIncluded one\n").unwrap();
std::fs::write(&readme, "Notes\n").unwrap();
let ctx = dir_ctx(&root, &out);
let mut state = empty_dir_state();
state.known_files.insert(a.clone());
rebuild_dir_batch(&ctx, &BTreeSet::from([a.clone()]), false, &mut state, None);
let (_tx, rx) = mpsc::channel::<Msg>();
let outcome = handle_fs_event_dir(
modify_event(readme.to_str().unwrap()),
&ctx,
&rx,
&mut state,
);
assert!(
matches!(outcome, DirEventOutcome::Skip),
"a file no source imports names no rebuild"
);
std::fs::write(&inc, "---\ntype: mds\n---\nIncluded two\n").unwrap();
let outcome =
handle_fs_event_dir(modify_event(inc.to_str().unwrap()), &ctx, &rx, &mut state);
assert!(
matches!(outcome, DirEventOutcome::Done),
"positive control: a module a source imports names one"
);
let read = |name: &str| std::fs::read_to_string(out.join(name)).ok();
assert!(
read("a.md").is_some_and(|text| text.contains("Included two")),
"its importer is rebuilt; out/a.md: {:?}",
read("a.md")
);
assert_eq!(
read("inc.md"),
None,
"the module is never compiled as a source"
);
}
fn rescan_event() -> Msg {
Msg::Fs(Ok(
notify::Event::new(notify::EventKind::Other).set_flag(notify::event::Flag::Rescan)
))
}
#[test]
fn a_rescan_event_finds_what_the_lost_events_would_have_said() {
let unflagged = || Msg::Fs(Ok(notify::Event::new(notify::EventKind::Other)));
for (debounce_ms, place) in [(0, "the event itself"), (20, "an event of the window")] {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let (_vars_dir, vars_dir) = canonical_tempdir();
let vars = vars_dir.join("vars.json");
let (a, created) = (root.join("a.mds"), root.join("created.mds"));
std::fs::write(&a, "A {{v}}\n").unwrap();
std::fs::write(&vars, r#"{"v": "one"}"#).unwrap();
let (ctx, mut state) = dir_ctx_with_vars(&root, &out, &vars);
let ctx = DirWatchCtx { debounce_ms, ..ctx };
state.known_files.insert(a.clone());
rebuild_dir_batch(&ctx, &BTreeSet::from([a.clone()]), false, &mut state, None);
let read = |name: &str| std::fs::read_to_string(out.join(name)).ok();
assert!(
read("a.md").is_some_and(|text| text.contains("A one")),
"{place}: control: the source is compiled; out/a.md: {:?}",
read("a.md")
);
std::fs::write(&created, "Created {{v}}\n").unwrap();
std::fs::write(&vars, r#"{"v": "two, longer"}"#).unwrap();
let (tx, rx) = mpsc::channel::<Msg>();
if debounce_ms > 0 {
tx.send(unflagged()).unwrap();
}
let outcome = handle_fs_event_dir(unflagged(), &ctx, &rx, &mut state);
assert!(
matches!(outcome, DirEventOutcome::Skip) && read("created.md").is_none(),
"{place}: control: events that name no path and say nothing of lost events \
rebuild nothing; out/created.md: {:?}",
read("created.md")
);
let first = if debounce_ms > 0 {
tx.send(rescan_event()).unwrap();
unflagged()
} else {
rescan_event()
};
let outcome = handle_fs_event_dir(first, &ctx, &rx, &mut state);
assert!(
matches!(outcome, DirEventOutcome::Done),
"{place}: the rescan event rebuilds"
);
assert!(
read("created.md").is_some_and(|text| text.contains("Created two, longer")),
"{place}: the source created meanwhile is compiled; out/created.md: {:?}",
read("created.md")
);
assert!(
read("a.md").is_some_and(|text| text.contains("A two, longer")),
"{place}: the vars edit made meanwhile is rebuilt with; out/a.md: {:?}",
read("a.md")
);
assert!(
state.known_files.contains(&created),
"{place}: the source created meanwhile is known: {:?}",
state.known_files
);
}
}
#[test]
fn a_file_rebuild_whose_compile_read_a_file_emptied_since_its_look_is_held() {
let (_dir, root) = canonical_tempdir();
let entry = root.join("page.mds");
let module = root.join("_inc.mds");
let out = root.join("page.md");
std::fs::write(
&entry,
"@import \"./_inc.mds\" as inc\nPage.\n@include inc\n",
)
.unwrap();
std::fs::write(&module, "").unwrap();
let ctx = FileCompileCtx {
entry: WatchedPath {
typed: entry.clone(),
canonical: entry.clone(),
what: Watched::Entry,
},
working_dir: WorkingDir { canonical: None },
vars_path: None,
vars_path_typed: None,
reads: Vec::new(),
static_set_vars: Vec::new(),
static_set_string_vars: Vec::new(),
quiet: true,
};
let mut watcher =
RecommendedWatcher::new(|_: notify::Result<Event>| {}, notify::Config::default())
.unwrap();
for (seen, held) in [(Some(9), true), (Some(0), false)] {
let _ = std::fs::remove_file(&out);
let mut state = file_state(std::iter::once(entry.clone()).collect());
state.output = OutputRoute::Named(Some(WriteTarget::as_typed(out.clone())));
state.last_mtimes = snapshot_state(&state.foi);
state.last_mtimes.insert(module.clone(), (None, seen));
let before = state.last_mtimes.clone();
let _ = rebuild_file(&ctx, &mut watcher, &mut state, None);
let written = std::fs::read_to_string(&out).ok();
if held {
assert_eq!(
written, None,
"a compile that read a file emptied since the look is held, not published"
);
assert!(state.hold.deadline().is_some(), "a hold of its own is set");
assert_eq!(state.last_mtimes, before, "the baseline is left as it was");
} else {
assert!(
written
.as_deref()
.is_some_and(|text| text.contains("Page.")),
"positive control: a file the baseline saw empty is no file emptied; \
page.md: {written:?}"
);
assert_eq!(state.hold.deadline(), None, "nothing is held");
}
}
}
fn file_ctx(entry: &Path) -> FileCompileCtx {
FileCompileCtx {
entry: WatchedPath {
typed: entry.to_path_buf(),
canonical: entry.to_path_buf(),
what: Watched::Entry,
},
working_dir: WorkingDir { canonical: None },
vars_path: None,
vars_path_typed: None,
reads: Vec::new(),
static_set_vars: Vec::new(),
static_set_string_vars: Vec::new(),
quiet: true,
}
}
#[test]
fn a_rebuild_takes_its_look_s_stamps_as_its_baseline() {
let stale: FileStamp = (None, Some(99));
let (_dir, root) = canonical_tempdir();
let entry = root.join("page.mds");
let out = root.join("page.md");
std::fs::write(&entry, "Page.\n").unwrap();
let mut watcher =
RecommendedWatcher::new(|_: notify::Result<Event>| {}, notify::Config::default())
.unwrap();
let mut state = file_state(std::iter::once(entry.clone()).collect());
state.output = OutputRoute::Named(Some(WriteTarget::as_typed(out.clone())));
state.last_mtimes.insert(entry.clone(), stale);
let _ = rebuild_file(&file_ctx(&entry), &mut watcher, &mut state, None);
assert!(
std::fs::read_to_string(&out).is_ok_and(|text| text.contains("Page.")),
"control: the rebuild ran"
);
assert_eq!(
state.last_mtimes.get(&entry),
Some(&stamp_now(&entry)),
"file mode: the look's stamp, not the one the baseline held"
);
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let (ctx, mut state) = two_compiled_sources(&root, &out);
let a = root.join("a.mds");
state.last_mtimes.insert(a.clone(), stale);
rebuild_dir_batch(&ctx, &BTreeSet::from([a.clone()]), false, &mut state, None);
assert_eq!(
state.last_mtimes.get(&a),
Some(&stamp_now(&a)),
"directory mode: the look's stamp, not the one the baseline held"
);
}
#[test]
fn a_directory_source_whose_compile_read_a_file_emptied_since_the_look_is_held() {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let (page, module) = (root.join("page.mds"), root.join("_inc.mds"));
std::fs::write(
&page,
"@import \"./_inc.mds\" as inc\nPage.\n@include inc\n",
)
.unwrap();
std::fs::write(&module, "").unwrap();
let ctx = dir_ctx(&root, &out);
let mut state = empty_dir_state();
state.last_mtimes.insert(module.clone(), (None, Some(9)));
rebuild_dir_batch(
&ctx,
&BTreeSet::from([page.clone()]),
false,
&mut state,
None,
);
assert_eq!(
std::fs::read_to_string(out.join("page.md")).ok(),
None,
"a compile that read a file emptied since the look is held, not published"
);
assert!(state.hold.deadline().is_some(), "a hold of its own is set");
assert!(state.held.paths.contains(&page), "{:?}", state.held);
std::fs::write(&module, "Inc.\n").unwrap();
std::fs::write(&page, "Page two\n").unwrap();
rebuild_dir_batch(&ctx, &BTreeSet::new(), false, &mut state, None);
assert!(
std::fs::read_to_string(out.join("page.md"))
.is_ok_and(|text| text.contains("Page two")),
"the batch that ends the hold rebuilds the source held"
);
assert_eq!(state.hold.deadline(), None, "the hold has ended");
}
#[test]
fn a_new_source_held_and_emptied_before_the_hold_ends_is_held_again() {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let (page, module) = (root.join("page.mds"), root.join("_inc.mds"));
std::fs::write(
&page,
"@import \"./_inc.mds\" as inc\nPage.\n@include inc\n",
)
.unwrap();
std::fs::write(&module, "").unwrap();
let ctx = dir_ctx(&root, &out);
let mut state = empty_dir_state();
state.last_mtimes.insert(module.clone(), (None, Some(9)));
let read = || std::fs::read_to_string(out.join("page.md")).ok();
rebuild_dir_batch(
&ctx,
&BTreeSet::from([page.clone()]),
false,
&mut state,
None,
);
let deadline = state.hold.deadline();
assert!(
deadline.is_some() && state.held.paths.contains(&page),
"control: page's compile is held; {:?}",
state.held
);
std::fs::write(&module, "Inc.\n").unwrap();
std::fs::write(&page, "").unwrap();
rebuild_dir_batch(&ctx, &BTreeSet::new(), false, &mut state, None);
assert_eq!(
read(),
None,
"a held source emptied before the hold ends is held, not published empty"
);
assert_eq!(
state.hold.deadline(),
deadline,
"it is held again at the same deadline"
);
std::fs::write(&page, "Page two\n").unwrap();
rebuild_dir_batch(&ctx, &BTreeSet::new(), false, &mut state, None);
assert!(
read().is_some_and(|text| text.contains("Page two")),
"positive control: the batch that finds it written publishes it; \
out/page.md: {:?}",
read()
);
assert_eq!(state.hold.deadline(), None, "the hold has ended");
}
#[test]
fn a_file_nothing_reads_named_by_a_batch_its_vars_file_failed_holds_nothing_when_emptied() {
for (label, read_by_the_run) in [("a new source", true), ("a file nothing reads", false)] {
let CrossRootPage {
dirs: _dirs,
base: _,
out,
page: _,
module: _,
shared,
vars,
ctx,
mut state,
} = cross_root_page();
let named = if read_by_the_run {
ctx.root.canonical.join("n.mds")
} else {
shared.join("unread.mds")
};
let batch = BTreeSet::from([named.clone()]);
std::fs::write(&named, "Named\n").unwrap();
std::fs::write(&vars, "{").unwrap();
rebuild_dir_batch(&ctx, &batch, false, &mut state, None);
assert!(
state.held.paths.contains(&named) && state.hold.deadline().is_none(),
"{label}: control: the batch the vars file could not be read for keeps what it \
named, and holds nothing; {:?}",
state.held
);
std::fs::write(&named, "").unwrap();
std::fs::write(&vars, r#"{"v": "two"}"#).unwrap();
rebuild_dir_batch(&ctx, &batch, true, &mut state, None);
let page_md = std::fs::read_to_string(out.join("page.md")).ok();
if read_by_the_run {
assert!(
state.hold.deadline().is_some()
&& page_md.as_deref().is_some_and(|text| !text.contains("two")),
"{label}: positive control: emptied, it holds the batch; out/page.md: \
{page_md:?}"
);
} else {
assert_eq!(
state.hold.deadline(),
None,
"{label}: emptied, it holds nothing"
);
assert!(
page_md.as_deref().is_some_and(|text| text.contains("two")),
"{label}: the batch compiles at once; out/page.md: {page_md:?}"
);
}
}
}
#[cfg(debug_assertions)]
#[test]
fn a_dependency_outside_the_root_a_batch_names_is_held_when_truncated_after_the_look() {
const NAME: &str = "watch::tests::\
a_dependency_outside_the_root_a_batch_names_is_held_when_truncated_after_the_look";
if child_process::is_child(NAME) {
let CrossRootPage {
dirs: _dirs,
out,
page,
shared,
ctx,
mut state,
..
} = cross_root_page();
let output = out.join("page.md");
let before = std::fs::read_to_string(&output).unwrap();
let dependency = shared.join("_y.mds");
std::fs::write(&page, "@import \"../shared/_y.mds\" as y\n@include y\n").unwrap();
std::fs::write(&dependency, "Y one\n").unwrap();
let batch = BTreeSet::from([page.clone(), dependency.clone()]);
let (_gate_dir, gate) = canonical_tempdir();
let (go, paused) = (gate.join("go"), gate.join("go.paused"));
std::env::set_var(batch_pause_trigger::LOOK_VARIABLE, &go);
let truncating = std::thread::spawn({
let (dependency, go) = (dependency.clone(), go.clone());
move || {
let stopped = (0..2_000).any(|_| {
std::thread::sleep(Duration::from_millis(5));
paused.exists()
});
std::fs::File::create(&dependency).unwrap();
std::fs::write(&go, "").unwrap();
stopped
}
});
rebuild_dir_batch(&ctx, &batch, false, &mut state, None);
assert!(
truncating.join().unwrap(),
"control: the batch stopped after its look"
);
assert_eq!(
std::fs::read_to_string(&output).unwrap(),
before,
"a dependency truncated after the batch's look: the empty read is not written"
);
assert!(
state.held.paths.contains(&page) && state.hold.deadline().is_some(),
"the source is held for the batch that ends the hold; {:?}",
state.held
);
std::fs::write(&dependency, "Y two\n").unwrap();
rebuild_dir_batch(&ctx, &BTreeSet::from([dependency]), false, &mut state, None);
assert_eq!(
std::fs::read_to_string(&output).unwrap(),
"Y two\n",
"positive control: the batch after the write publishes it"
);
assert!(
state.held.paths.is_empty(),
"the hold has ended; {:?}",
state.held
);
return;
}
let child = child_process::run(NAME);
let report = String::from_utf8_lossy(&child.stdout).into_owned();
let printed = String::from_utf8_lossy(&child.stderr).into_owned();
assert!(
report.contains("running 1 test"),
"control: the child ran the test; stdout:\n{report}"
);
assert!(
child.status.success(),
"the child's test passes; stdout:\n{report}\nstderr:\n{printed}"
);
}
#[test]
fn empty_hold_holds_a_late_finding_unless_the_deadline_ended_it() {
let t0 = Instant::now();
let mut hold = EmptyHold::default();
assert_eq!(hold.on_rebuild(false, t0), HoldVerdict::Compile);
assert_eq!(
hold.on_late_empty(t0 + ms(1)),
HoldVerdict::Hold,
"found after a look that found nothing"
);
let deadline = t0 + ms(1) + EMPTY_HOLD_DEADLINE;
assert_eq!(hold.deadline(), Some(deadline));
assert_eq!(hold.on_late_empty(t0 + ms(100)), HoldVerdict::Hold);
assert_eq!(
hold.deadline(),
Some(deadline),
"a later finding must not move the deadline"
);
assert_eq!(hold.on_rebuild(true, deadline), HoldVerdict::Compile);
assert_eq!(
hold.on_late_empty(deadline + ms(1)),
HoldVerdict::Compile,
"a rebuild the deadline runs compiles the files as they are"
);
assert_eq!(hold.deadline(), None, "and leaves nothing held");
assert_eq!(hold.on_rebuild(true, deadline + ms(10)), HoldVerdict::Hold);
assert_eq!(
hold.deadline(),
Some(deadline + ms(10) + EMPTY_HOLD_DEADLINE)
);
assert_eq!(
hold.on_rebuild(false, deadline + ms(20)),
HoldVerdict::Compile
);
assert_eq!(hold.deadline(), None);
}
#[test]
fn a_deadline_rebuild_ends_its_hold_whatever_the_clock_reads() {
let deadline = Instant::now() + EMPTY_HOLD_DEADLINE;
let behind = deadline - ms(5);
assert_eq!(not_before(behind, None), behind);
assert_eq!(not_before(behind, Some(deadline)), deadline);
assert_eq!(
not_before(deadline + ms(5), Some(deadline)),
deadline + ms(5)
);
let mut held = EmptyHold::Until(deadline);
assert_eq!(
held.on_rebuild(true, behind),
HoldVerdict::Hold,
"control: a rebuild at the clock's earlier reading is held again"
);
assert_eq!(
held.on_rebuild(true, not_before(behind, Some(deadline))),
HoldVerdict::Compile,
"the deadline's rebuild ends the hold"
);
assert_eq!(held.deadline(), None);
}
#[test]
fn files_found_emptied_join_the_batch() {
let path = |name: &str| PathBuf::from("/w").join(name);
let batch = |vars_changed: bool| Batch {
paths: BTreeSet::from([path("a.mds")]),
vars_changed,
};
let vars = path("vars.json");
let emptied: BTreeSet<PathBuf> = BTreeSet::from([path("x.mds"), vars.clone()]);
assert_eq!(
join_emptied(batch(false), &emptied, Some(&vars)),
Batch {
paths: BTreeSet::from([path("a.mds"), path("x.mds")]),
vars_changed: true
},
"the vars file is a change to it, not a path of the batch"
);
assert_eq!(
join_emptied(batch(false), &BTreeSet::from([path("x.mds")]), Some(&vars)),
Batch {
paths: BTreeSet::from([path("a.mds"), path("x.mds")]),
vars_changed: false
}
);
assert_eq!(
join_emptied(batch(true), &BTreeSet::new(), Some(&vars)),
batch(true),
"nothing emptied: the batch as it came"
);
}
fn state_with_a_vars_file(root: &Path) -> (DirWatchState, [PathBuf; 3]) {
let paths = ["page.mds", "_dep.mds", "vars.json"].map(|name| root.join(name));
for path in &paths {
std::fs::write(path, "bytes\n").unwrap();
}
let [page, dep, vars] = &paths;
let mut state = empty_dir_state();
state.known_files.insert(page.clone());
state.forward_deps.insert(page.clone(), vec![dep.clone()]);
state.vars_file = Some(vars.clone());
state.last_mtimes = snapshot_state(&state.watched_set());
(state, paths)
}
#[test]
fn a_batch_whose_vars_load_failed_on_an_emptied_dependency_is_held_with_it() {
let (_dir, root) = canonical_tempdir();
let (mut state, [page, dep, _vars]) = state_with_a_vars_file(&root);
let batch = Batch {
paths: BTreeSet::from([page.clone()]),
vars_changed: false,
};
std::fs::write(&dep, "").unwrap();
assert!(
state.hold_after_vars_load_failed(&batch, &root),
"the batch is held"
);
assert_eq!(
state.held.paths,
BTreeSet::from([page, dep]),
"the batch and the file found emptied"
);
assert!(!state.held.vars_changed, "no change to the vars file");
assert!(
state.hold.deadline().is_some(),
"the hold runs towards its deadline"
);
}
#[test]
fn a_batch_whose_vars_load_failed_on_an_emptied_vars_file_is_held_as_a_change_to_it() {
let (_dir, root) = canonical_tempdir();
let (mut state, [page, _dep, vars]) = state_with_a_vars_file(&root);
let batch = Batch {
paths: BTreeSet::from([page.clone()]),
vars_changed: false,
};
std::fs::write(&vars, "").unwrap();
assert!(
state.hold_after_vars_load_failed(&batch, &root),
"the batch is held"
);
assert!(state.held.vars_changed, "a change to the vars file");
assert_eq!(
state.held.paths,
BTreeSet::from([page]),
"the vars file is no path of the batch"
);
}
#[test]
fn a_batch_whose_vars_load_failed_is_held_only_for_a_file_emptied_before_the_deadline() {
let (_dir, root) = canonical_tempdir();
let (mut state, [page, dep, _vars]) = state_with_a_vars_file(&root);
let batch = Batch {
paths: BTreeSet::from([page]),
vars_changed: false,
};
assert!(
!state.hold_after_vars_load_failed(&batch, &root),
"no file went empty"
);
assert_eq!(state.held, HeldBatch::default(), "nothing is held");
assert_eq!(state.hold, EmptyHold::Off, "and no hold runs");
std::fs::write(&dep, "").unwrap();
state.hold = EmptyHold::Expired;
assert!(
!state.hold_after_vars_load_failed(&batch, &root),
"the deadline ended the hold in this rebuild"
);
assert_eq!(state.held, HeldBatch::default(), "nothing is held");
state.hold = EmptyHold::Off;
assert!(
state.hold_after_vars_load_failed(&batch, &root),
"positive control: the same file, with the deadline still ahead, holds the batch"
);
}
#[test]
fn a_baseline_keeps_the_stamps_taken_and_stamps_only_the_rest() {
let (_dir, root) = canonical_tempdir();
let [emptied, edited, was_empty, new, gone] =
["emptied", "edited", "was_empty", "new", "gone"].map(|name| root.join(name));
for (path, text) in [
(&emptied, ""),
(&edited, "edited since\n"),
(&was_empty, ""),
(&new, "new\n"),
] {
std::fs::write(path, text).unwrap();
}
let taken: StampMap = [
(emptied.clone(), (None, Some(5))),
(edited.clone(), (None, Some(3))),
(was_empty.clone(), (None, Some(0))),
(gone.clone(), (None, Some(1))),
]
.into_iter()
.collect();
let domain = [
emptied.clone(),
edited.clone(),
was_empty.clone(),
new.clone(),
edited.clone(),
];
let baseline = baseline_over(taken.clone(), &domain);
for path in [&emptied, &edited, &was_empty] {
assert_eq!(baseline.get(path), taken.get(path), "{}", path.display());
}
assert_eq!(
baseline.get(&new),
Some(&stamp_now(&new)),
"a file none was taken for is stamped now"
);
assert!(!baseline.contains_key(&gone), "{baseline:?}");
assert_eq!(baseline.len(), 4, "{baseline:?}");
}
fn two_compiled_sources(root: &Path, out: &Path) -> (DirWatchCtx, DirWatchState) {
std::fs::write(root.join("a.mds"), "A one\n").unwrap();
std::fs::write(root.join("b.mds"), "B one\n").unwrap();
let ctx = dir_ctx(root, out);
let mut state = empty_dir_state();
let both = BTreeSet::from([root.join("a.mds"), root.join("b.mds")]);
rebuild_dir_batch(&ctx, &both, false, &mut state, None);
(ctx, state)
}
#[test]
fn a_batch_keeps_a_file_emptied_since_its_look_found_emptied() {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let (ctx, mut state) = two_compiled_sources(&root, &out);
let (a, b) = (root.join("a.mds"), root.join("b.mds"));
let read = |name: &str| std::fs::read_to_string(out.join(name)).ok();
assert!(
read("a.md").is_some_and(|text| text.contains("A one")),
"control: a is compiled; out/a.md: {:?}",
read("a.md")
);
std::fs::write(&b, "B two\n").unwrap();
std::fs::write(&a, "").unwrap();
process_dir_batch(
&BTreeSet::from([b.clone()]),
false,
&mut BatchCtx {
watch_root: &ctx.root,
output_base: &ctx.output_base,
vars: BatchVars::map_only(&None),
quiet: true,
},
&mut state,
);
assert!(
read("b.md").is_some_and(|text| text.contains("B two")),
"positive control: the batch rebuilds b; out/b.md: {:?}",
read("b.md")
);
rebuild_dir_batch(&ctx, &BTreeSet::from([a.clone()]), false, &mut state, None);
assert!(
read("a.md").is_some_and(|text| text.contains("A one")),
"a file emptied while a batch ran is held, not published empty; out/a.md: {:?}",
read("a.md")
);
assert!(state.hold.deadline().is_some(), "{:?}", state.hold);
}
#[test]
fn a_batch_s_baseline_is_its_look_s_stamps() {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let (ctx, mut state) = two_compiled_sources(&root, &out);
let b = root.join("b.mds");
let look = state.last_mtimes.clone();
std::fs::write(&b, "B two, saved after the look\n").unwrap();
process_dir_batch(
&BTreeSet::from([b.clone()]),
false,
&mut BatchCtx {
watch_root: &ctx.root,
output_base: &ctx.output_base,
vars: BatchVars::map_only(&None),
quiet: true,
},
&mut state,
);
let read = std::fs::read_to_string(out.join("b.md")).ok();
assert!(
read.as_deref()
.is_some_and(|text| text.contains("B two, saved after the look")),
"control: the batch compiled what it read; out/b.md: {read:?}"
);
assert_eq!(
state.last_mtimes, look,
"the baseline is the look's stamps, b's included"
);
assert!(
path_state_differs(&b, &state.last_mtimes),
"so the next look finds b changed"
);
}
#[test]
fn a_deadline_batch_takes_a_file_it_compiled_empty_into_the_baseline() {
let (_root_dir, root) = canonical_tempdir();
let (_out_dir, out) = canonical_tempdir();
let (ctx, mut state) = two_compiled_sources(&root, &out);
let (a, b) = (root.join("a.mds"), root.join("b.mds"));
let read = |name: &str| std::fs::read_to_string(out.join(name)).ok();
std::fs::write(&a, "").unwrap();
rebuild_dir_batch(&ctx, &BTreeSet::from([a.clone()]), false, &mut state, None);
let deadline = state.hold.deadline().expect("control: the batch is held");
rebuild_dir_batch(&ctx, &BTreeSet::new(), false, &mut state, Some(deadline));
assert_eq!(
read("a.md").as_deref(),
Some(""),
"control: the deadline compiles a as it is"
);
std::fs::write(&b, "B two\n").unwrap();
rebuild_dir_batch(&ctx, &BTreeSet::from([b.clone()]), false, &mut state, None);
assert!(
read("b.md").is_some_and(|text| text.contains("B two")),
"a batch after the deadline is not held for a file left empty; out/b.md: {:?}",
read("b.md")
);
assert_eq!(state.hold.deadline(), None, "{:?}", state.hold);
}
#[test]
fn emptied_paths_are_those_found_with_none_after_bytes() {
let (_dir, root) = canonical_tempdir();
let [emptied, kept, unseen] = ["emptied", "kept", "unseen"].map(|name| root.join(name));
std::fs::write(&emptied, "bytes").unwrap();
std::fs::write(&kept, "bytes").unwrap();
let paths: HashSet<PathBuf> = [emptied.clone(), kept.clone()].into_iter().collect();
let baseline = snapshot_state(&paths);
std::fs::write(&emptied, "").unwrap();
std::fs::write(&unseen, "").unwrap();
let all = [emptied.clone(), kept, unseen];
assert_eq!(emptied_paths(&all, &baseline), BTreeSet::from([emptied]));
}
#[test]
fn settle_mark_errored_records_the_source_in_directory_mode() {
let (_dir, src, dep) = source_and_dependency();
let mut rebuild = empty_dir_state();
rebuild.known_files.insert(src.clone());
rebuild.forward_deps.insert(src.clone(), vec![dep.clone()]);
settle(
SettleInto::Dir(&mut rebuild),
None,
Settle::MarkErrored(&src),
);
assert!(rebuild.errored.contains(&src), "{:?}", rebuild.errored);
assert_eq!(rebuild.forward_deps.get(&src), Some(&vec![dep.clone()]));
assert!(rebuild.last_mtimes.is_empty(), "{:?}", rebuild.last_mtimes);
let foi: HashSet<PathBuf> = [src.clone(), dep.clone()].into_iter().collect();
let mut file = file_state(foi.clone());
settle(SettleInto::File(&mut file), None, Settle::MarkErrored(&src));
assert_eq!(file.last_mtimes, snapshot_state(&foi));
assert!(
file.last_mtimes.contains_key(&src),
"{:?}",
file.last_mtimes
);
}
#[test]
fn settle_startup_error_records_the_source_in_directory_mode() {
let (_dir, src, _dep) = source_and_dependency();
let mut startup = empty_dir_state();
settle_startup_error(StartupInto::Dir(&mut startup), None, &src);
assert!(startup.errored.contains(&src), "{:?}", startup.errored);
assert_eq!(startup.forward_deps.get(&src), Some(&vec![]));
assert!(startup.last_mtimes.is_empty(), "{:?}", startup.last_mtimes);
}
#[test]
fn a_panicked_compile_settles_as_an_error_does_and_is_not_reported() {
let (_dir, src, dep) = source_and_dependency();
let foi: HashSet<PathBuf> = [src.clone(), dep.clone()].into_iter().collect();
let failures = || {
[
(
"an error",
CompileFailure::from(miette::miette!("broken")),
1,
),
("a panic", CompileFailure::Panicked, 0),
]
};
for (what, failure, reports) in failures() {
let mut reported = Vec::new();
let mut state = empty_dir_state();
state.forward_deps.insert(src.clone(), vec![dep.clone()]);
settle_reporting(
SettleInto::Dir(&mut state),
failure.into_report(),
Settle::MarkErrored(&src),
|e| reported.push(e.to_string()),
);
assert!(state.errored.contains(&src), "{what}: marked errored");
assert_eq!(
state.forward_deps.get(&src),
Some(&vec![dep.clone()]),
"{what}"
);
assert_eq!(reported.len(), reports, "{what}: reported {reported:?}");
}
for (what, failure, reports) in failures() {
let mut reported = Vec::new();
let mut state = file_state(foi.clone());
settle_reporting(
SettleInto::File(&mut state),
failure.into_report(),
Settle::MarkErrored(&src),
|e| reported.push(e.to_string()),
);
assert_eq!(
state.last_mtimes,
snapshot_state(&foi),
"{what}: rebaselined"
);
assert_eq!(reported.len(), reports, "{what}: reported {reported:?}");
}
let mut reported = Vec::new();
settle_startup_error_reporting(
StartupInto::File,
CompileFailure::from(miette::miette!("broken")).into_report(),
&src,
|e| reported.push(e.to_string()),
);
assert_eq!(reported, ["broken"]);
}
#[test]
fn an_out_dir_deleted_or_replaced_at_its_path_is_new_once() {
let base = tempfile::tempdir().unwrap();
let out = base.path().join("out");
std::fs::create_dir(&out).unwrap();
let mut anchor = OutDirAnchor::record(Some(&out), None).expect("an out-dir");
assert_eq!(
anchor.check(),
OutDirNow::Unchanged,
"the directory recorded"
);
std::fs::remove_dir(&out).unwrap();
assert_eq!(anchor.check(), OutDirNow::New, "deleted");
assert_eq!(anchor.check(), OutDirNow::New, "still none");
std::fs::create_dir(&out).unwrap();
anchor.written();
assert_eq!(
anchor.check(),
OutDirNow::Unchanged,
"the directory the write made"
);
if cfg!(unix) {
std::fs::rename(&out, base.path().join("out.old")).unwrap();
std::fs::create_dir(&out).unwrap();
assert_eq!(
anchor.check(),
OutDirNow::New,
"another directory in its place"
);
assert_eq!(
anchor.check(),
OutDirNow::Unchanged,
"then the one compared"
);
}
}
#[cfg(unix)]
#[test]
fn an_out_dir_the_typed_path_leads_away_from_is_elsewhere() {
use std::os::unix::fs::symlink;
let base = tempfile::tempdir().unwrap();
for name in ["a", "b"] {
std::fs::create_dir(base.path().join(name)).unwrap();
}
let link = base.path().join("link");
symlink("a", &link).unwrap();
let mut anchor = OutDirAnchor::record(Some(&link), None).expect("an out-dir");
let mut below = OutDirAnchor::record(Some(&link.join("out")), None).expect("an out-dir");
assert_eq!(anchor.check(), OutDirNow::Unchanged);
assert_eq!(below.check(), OutDirNow::New, "none yet");
let retarget = |to: &str| {
std::fs::remove_file(&link).unwrap();
symlink(to, &link).unwrap();
};
retarget("b");
assert_eq!(
anchor.check(),
OutDirNow::Elsewhere,
"a directory that is there"
);
assert_eq!(anchor.checked, None, "a refused write is anchored nowhere");
assert_eq!(
below.check(),
OutDirNow::Elsewhere,
"one a write would create"
);
retarget("nowhere");
assert_eq!(
anchor.check(),
OutDirNow::Elsewhere,
"a link that leads nowhere"
);
retarget("a");
assert_eq!(anchor.check(), OutDirNow::Unchanged, "led back");
assert_eq!(below.check(), OutDirNow::New, "led back, still none");
}
#[test]
fn a_build_output_dir_is_checked_below_the_directory_of_mds_json() {
use crate::build::{BuildConfig, MdsConfig};
let base = tempfile::tempdir().unwrap();
let dir = base.path().canonicalize().unwrap();
let config = |output_dir: Option<&str>| ProjectConfig {
config: MdsConfig {
build: BuildConfig {
output_dir: output_dir.map(str::to_owned),
..Default::default()
},
..Default::default()
},
dir: dir.clone(),
shown_dir: base.path().to_path_buf(),
};
let dist = config(Some("dist"));
std::fs::create_dir(dir.join("dist")).unwrap();
let mut anchor = OutDirAnchor::record(None, Some(&dist)).expect("an out-dir");
assert_eq!(
(&anchor.typed, &anchor.out_dir),
(&base.path().to_path_buf(), &dir.join("dist"))
);
assert_eq!(anchor.check(), OutDirNow::Unchanged);
std::fs::remove_dir(dir.join("dist")).unwrap();
assert_eq!(anchor.check(), OutDirNow::New, "deleted below it");
let flag = base.path().join("flag");
let chosen = OutDirAnchor::record(Some(&flag), Some(&dist)).expect("an out-dir");
assert_eq!(chosen.out_dir, dir.join("flag"), "--out-dir first");
assert!(OutDirAnchor::record(None, Some(&config(None))).is_none());
assert!(OutDirAnchor::record(None, None).is_none());
let config_dir = Some(CheckedAnchor {
missing: 0,
identity: DirIdentity::of(&dir).expect("a directory"),
});
assert_eq!(anchor.checked, config_dir);
std::fs::create_dir(dir.join("dist")).unwrap();
anchor.check();
assert_eq!(anchor.checked, config_dir);
}
#[test]
fn a_check_finds_the_directory_the_next_write_is_anchored_at() {
let base = tempfile::tempdir().unwrap();
let root = base.path().canonicalize().unwrap();
let out = root.join("out");
std::fs::create_dir(&out).unwrap();
let mut anchor = OutDirAnchor::record(Some(&out), None).expect("an out-dir");
assert_eq!(anchor.checked, None, "nothing found before a check");
let target = WriteTarget::new(out.join("a.md"), PathBuf::from("o/a.md"));
let written = |anchor: &OutDirAnchor| {
let checked = below_checked_out_dir(Some(anchor), &target);
(
checked.path.clone(),
checked.shown.clone(),
checked.below_anchor(),
checked.checked_anchor(),
)
};
assert_eq!(anchor.check(), OutDirNow::Unchanged);
assert_eq!(
written(&anchor),
(
out.join("a.md"),
PathBuf::from("o/a.md"),
1,
DirIdentity::of(&out)
),
"the out-dir"
);
std::fs::remove_dir(&out).unwrap();
assert_eq!(anchor.check(), OutDirNow::New);
assert_eq!(
written(&anchor),
(
out.join("a.md"),
PathBuf::from("o/a.md"),
2,
DirIdentity::of(&root)
),
"deleted: the directory above it, the out-dir below it"
);
assert_eq!(below_checked_out_dir(None, &target), target, "no out-dir");
}
}