use std::collections::{BTreeSet, HashMap, HashSet};
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::{
auto_detect_mds_file, build_runtime_vars, compile_and_write, compile_to_content,
emit_duplicate_var_warnings, load_config, resolve_output_path_for_kind, write_output,
OutputKind, RuntimeVarArgs,
};
use crate::output::{
canonicalize_out_dir, collect_mds_files, eprint_error, eprint_warning, is_partial,
is_within_default_excluded_dir, output_base_no_ext, output_path_for, probe_and_remove_stale,
resolve_output_base, safe_inline, safe_path, OutputBase,
};
pub(crate) struct WatchArgs {
pub(crate) input: Option<PathBuf>,
pub(crate) output: Option<String>,
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: &[String],
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(Path::new(dep), &mut dirs);
}
if let Some(vf) = vars_file {
push_parent(vf, &mut dirs);
}
dirs
}
pub(crate) fn files_of_interest(
entry: &Path,
deps: &[String],
vars_file: Option<&Path>,
) -> HashSet<PathBuf> {
let mut set = HashSet::new();
set.insert(entry.to_path_buf());
for dep in deps {
set.insert(PathBuf::from(dep));
}
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 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 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> {
match vars {
Some(p) if p.exists() => {
mds::NativeFs::check_symlink(&p)
.map(Some)
.map_err(|_| MdsError::Io {
message: format!("--vars file must not be a symlink: {}", p.display()),
})
}
other => Ok(other),
}
}
pub(crate) fn clear_terminal() {
use std::io::IsTerminal;
if std::io::stderr().is_terminal() {
eprint!("\x1b[2J\x1b[3J\x1b[H");
}
}
pub(crate) fn resync_watches(
watcher: &mut RecommendedWatcher,
current_dirs: &BTreeSet<PathBuf>,
new_dirs: &BTreeSet<PathBuf>,
) -> 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(dir),
safe_inline(&e)
));
} else {
result.insert(dir.clone());
}
}
result
}
fn stop_watching(quiet: bool) {
if !quiet {
eprintln!("Stopped watching.");
}
}
#[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() {}
const READY_MARKER_ENV: &str = "MDS_TEST_READY";
const READY_MARKER: &str = "MDS_WATCH_READY";
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 std::fs::write(&tmp, READY_MARKER).is_ok() {
let _ = std::fs::rename(&tmp, &path);
}
}
struct TickClock {
interval: Option<Duration>,
next: Instant,
}
impl TickClock {
fn new(interval: Option<Duration>) -> Self {
Self {
interval,
next: Instant::now() + interval.unwrap_or(Duration::ZERO),
}
}
fn recv_next(
&mut self,
rx: &mpsc::Receiver<Msg>,
) -> std::result::Result<Option<Msg>, mpsc::RecvTimeoutError> {
let Some(interval) = self.interval else {
return rx
.recv()
.map(Some)
.map_err(|_| mpsc::RecvTimeoutError::Disconnected);
};
let now = Instant::now();
if now >= self.next {
self.next = now + interval;
return Ok(None);
}
match rx.recv_timeout(self.next - now) {
Ok(msg) => Ok(Some(msg)),
Err(mpsc::RecvTimeoutError::Timeout) => {
self.next = Instant::now() + interval;
Ok(None)
}
Err(e @ mpsc::RecvTimeoutError::Disconnected) => Err(e),
}
}
}
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,
Quiet,
Cap,
MessageLimit,
Interrupted,
Disconnected,
}
struct DebounceOutcome {
paths: BTreeSet<PathBuf>,
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)
}
fn drain_debounce(rx: &mpsc::Receiver<Msg>, debounce_ms: u64) -> DebounceOutcome {
let mut paths = BTreeSet::new();
let Some(window) = clamp_debounce(debounce_ms) else {
return DebounceOutcome {
paths,
end: DebounceEnd::Disabled,
};
};
let start = Instant::now();
let hard_cap = start + debounce_cap(window);
let mut deadline = start + window;
let mut messages: usize = 0;
let end = loop {
assert!(
deadline <= hard_cap,
"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 messages >= MAX_DEBOUNCE_MESSAGES {
break DebounceEnd::MessageLimit;
}
let now = Instant::now();
if now >= deadline {
break if deadline == hard_cap {
DebounceEnd::Cap
} else {
DebounceEnd::Quiet
};
}
match rx.recv_timeout(deadline - now) {
Ok(msg) => {
messages += 1;
match msg {
Msg::Fs(Ok(event)) => {
if !is_content_event(&event.kind) {
continue;
}
for p in event.paths {
paths.insert(p);
}
deadline = (Instant::now() + window).min(hard_cap);
}
Msg::Fs(Err(e)) => {
eprint_warning(&format!(
"warning: watch error during debounce: {}",
safe_inline(&e)
));
}
Msg::Interrupt => break DebounceEnd::Interrupted,
}
}
Err(mpsc::RecvTimeoutError::Timeout) => {}
Err(mpsc::RecvTimeoutError::Disconnected) => break DebounceEnd::Disconnected,
}
};
DebounceOutcome { paths, end }
}
fn clamp_poll_interval(poll_interval: u64) -> Option<Duration> {
if poll_interval == 0 {
None
} else {
Some(Duration::from_millis(poll_interval.max(50)))
}
}
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;
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 canonical_input =
mds::NativeFs::check_symlink(&resolved_input).map_err(miette::Error::from)?;
let tick_opt: Option<Duration> = clamp_poll_interval(poll_interval);
if is_dir {
run_watch_dir(
canonical_input,
out_dir,
vars,
set_vars,
set_string_vars,
clear,
debounce,
quiet,
tick_opt,
)
} else {
run_watch_file(
canonical_input,
output,
out_dir,
vars,
set_vars,
set_string_vars,
clear,
debounce,
quiet,
tick_opt,
)
}
}
struct FileCompileCtx {
entry: PathBuf,
vars_path: Option<PathBuf>,
vars_path_raw: Option<PathBuf>,
static_set_vars: Vec<(String, String)>,
static_set_string_vars: Vec<(String, String)>,
output_arg: Option<String>,
out_dir: Option<PathBuf>,
output_path: Option<PathBuf>,
quiet: bool,
}
struct FileWatchState {
watched_dirs: BTreeSet<PathBuf>,
armed_dirs: BTreeSet<PathBuf>,
foi: HashSet<PathBuf>,
last_mtimes: StampMap,
last_written: HashMap<String, String>,
entry_was_missing: bool,
first_tick: bool,
missing_watched_dirs: BTreeSet<PathBuf>,
}
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, &[], 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.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(&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 {
clear_terminal();
}
FileEventAction::Rebuild
}
fn rebuild_file(
ctx: &FileCompileCtx,
watcher: &mut RecommendedWatcher,
state: &mut FileWatchState,
) {
let mut resolved = match build_runtime_vars(RuntimeVarArgs {
vars: ctx.vars_path_raw.clone(),
set_vars: ctx.static_set_vars.clone(),
set_string_vars: ctx.static_set_string_vars.clone(),
}) {
Ok(v) => v,
Err(e) => {
eprint_error(e);
state.last_mtimes = snapshot_state(&state.foi);
return;
}
};
let runtime_vars = resolved.vars.take();
let t0 = Instant::now();
match compile_to_content(
&ctx.entry,
runtime_vars,
ctx.quiet,
mds::CompileOptions::default(),
) {
Ok(compiled) => {
let output_path = if ctx.output_path.is_some() {
ctx.output_path.clone()
} else {
let config = load_config(&ctx.entry).unwrap_or(None);
resolve_output_path_for_kind(
&Some(ctx.entry.clone()),
&ctx.output_arg,
&ctx.out_dir,
&config,
compiled.kind,
ctx.quiet,
)
.unwrap_or(None)
};
let output_key: String = output_path
.as_deref()
.map(|p| p.display().to_string())
.unwrap_or_else(|| "<stdout>".to_string());
let content_changed = state
.last_written
.get(&output_key)
.is_none_or(|prev| *prev != compiled.content);
if content_changed {
crate::build::emit_duplicate_vars_file_warnings(&resolved, ctx.quiet);
}
let new_dirs =
dirs_to_watch(&ctx.entry, &compiled.dependencies, ctx.vars_path.as_deref());
state.watched_dirs = resync_watches(watcher, &state.watched_dirs, &new_dirs);
state.armed_dirs = state.watched_dirs.clone();
state.foi =
files_of_interest(&ctx.entry, &compiled.dependencies, ctx.vars_path.as_deref());
state.last_mtimes = snapshot_state(&state.foi);
if content_changed {
match write_output(output_path.clone(), &compiled.content, ctx.quiet, false) {
Ok(()) => {
let elapsed = t0.elapsed().as_millis();
let dep_count = compiled.dependencies.len();
let out_display = output_path
.as_deref()
.map(|p| p.display().to_string())
.unwrap_or_else(|| "<stdout>".to_string());
state.last_written.insert(output_key, compiled.content);
if !ctx.quiet {
eprintln!(
"Recompiled {} ({} deps) in {}ms",
safe_inline(&out_display),
dep_count,
elapsed
);
}
}
Err(e) => {
eprint_error(e);
state.last_mtimes = snapshot_state(&state.foi);
}
}
}
}
Err(e) => {
eprint_error(e);
state.last_mtimes = snapshot_state(&state.foi);
}
}
}
#[allow(clippy::too_many_arguments)]
fn run_watch_file(
entry: PathBuf,
output: Option<String>,
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>,
) -> Result<()> {
let vars_path_raw = 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;
if !quiet {
eprintln!("Watching {}", safe_path(&entry));
}
let (tx, rx) = mpsc::channel::<Msg>();
let tx_fs = tx.clone();
let mut watcher = RecommendedWatcher::new(
move |res| {
let _ = tx_fs.send(Msg::Fs(res));
},
notify::Config::default(),
)
.map_err(|e| miette::miette!("failed to initialize file watcher: {e}"))?;
let mut watched_dirs: BTreeSet<PathBuf> = BTreeSet::new();
for dir in dirs_to_watch(&entry, &[], vars_path.as_deref()) {
if dir.exists() && watcher.watch(&dir, RecursiveMode::NonRecursive).is_ok() {
watched_dirs.insert(dir);
}
}
let mut pre_mtimes = snapshot_state(&files_of_interest(&entry, &[], vars_path.as_deref()));
let entry_was_missing = !entry.exists();
let resolved = build_runtime_vars(RuntimeVarArgs {
vars: vars_path_raw.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)?;
let (output_path, initial_deps, initial_content) = match compile_and_write(
&entry,
&output,
&out_dir,
&config,
runtime_vars,
quiet,
mds::CompileOptions::default(),
) {
Ok(result) => result,
Err(e) => {
eprint_error(e);
let fallback_path = resolve_output_path_for_kind(
&Some(entry.clone()),
&output,
&out_dir,
&config,
OutputKind::Markdown,
quiet,
)
.unwrap_or(None);
(fallback_path, vec![], String::new())
}
};
for dep in &initial_deps {
baseline_path(Path::new(dep), &mut pre_mtimes);
}
startup_race_probe();
let output_key: String = output_path
.as_deref()
.map(|p| p.display().to_string())
.unwrap_or_else(|| "<stdout>".to_string());
let init_dirs = dirs_to_watch(&entry, &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) => {
return Err(miette::miette!(
"failed to watch directory {}: {e}\n\
hint: on Linux you may need to increase fs.inotify.max_user_watches",
dir.display()
));
}
}
}
let mut last_written: HashMap<String, String> = HashMap::new();
if !initial_content.is_empty() {
last_written.insert(output_key.clone(), initial_content);
}
let foi = files_of_interest(&entry, &initial_deps, vars_path.as_deref());
let missing_watched_dirs: BTreeSet<PathBuf> = {
let desired = dirs_to_watch(&entry, &[], 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).copied();
last_mtimes.extend(pre_mtimes);
debug_assert_eq!(
last_mtimes.get(&entry).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 mut state = FileWatchState {
armed_dirs: watched_dirs.clone(),
watched_dirs,
foi,
last_mtimes,
last_written,
entry_was_missing,
first_tick: true,
missing_watched_dirs,
};
let ctx = FileCompileCtx {
entry,
vars_path,
vars_path_raw,
static_set_vars,
static_set_string_vars,
output_arg: output,
out_dir,
output_path,
quiet,
};
let tx_ctrlc = tx.clone();
let _ = ctrlc::set_handler(move || {
let _ = tx_ctrlc.send(Msg::Interrupt);
});
emit_ready_marker();
let mut clock = TickClock::new(tick);
loop {
match clock.recv_next(&rx) {
Err(mpsc::RecvTimeoutError::Disconnected) => break,
Ok(None) => {
if liveness_probe_file(&ctx, &mut watcher, &mut state) {
rebuild_file(&ctx, &mut watcher, &mut state);
}
continue;
}
Ok(Some(msg)) => match handle_fs_event_file(msg, &state.foi, &rx, debounce_ms, clear) {
FileEventAction::Skip => continue,
FileEventAction::Stop => {
stop_watching(ctx.quiet);
return Ok(());
}
FileEventAction::Rebuild => rebuild_file(&ctx, &mut watcher, &mut state),
},
Err(mpsc::RecvTimeoutError::Timeout) => {}
}
}
stop_watching(ctx.quiet);
Ok(())
}
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, String>,
external_dep_dirs: BTreeSet<PathBuf>,
last_mtimes: StampMap,
}
impl DirWatchState {
fn record_success(
&mut self,
src: &Path,
dep_paths: Vec<PathBuf>,
root: &Path,
out: Option<&Path>,
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_path), Some(c)) = (out, content) {
self.last_written.insert(out_path.to_path_buf(), c);
}
}
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 tracked_set(&self) -> HashSet<PathBuf> {
let mut tracked: HashSet<PathBuf> = self.known_files.iter().cloned().collect();
for deps in self.forward_deps.values() {
tracked.extend(deps.iter().cloned());
}
tracked
}
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, out: &Path) {
self.last_written.remove(out);
self.forget_graph(src);
}
}
struct LivenessState {
first_tick: bool,
root_was_missing: bool,
root_armed: bool,
missing_external_dirs: BTreeSet<PathBuf>,
armed_external_dirs: BTreeSet<PathBuf>,
}
fn compile_one_source(
src: &Path,
root: &Path,
output_base: &OutputBase,
runtime_vars: &Option<HashMap<String, mds::Value>>,
quiet: bool,
state: &mut DirWatchState,
) -> bool {
let t0 = Instant::now();
match compile_to_content(
src,
runtime_vars.clone(),
quiet,
mds::CompileOptions::default(),
) {
Ok(compiled) => {
let dep_paths: Vec<PathBuf> = compiled.dependencies.iter().map(PathBuf::from).collect();
if is_partial(src) {
state.record_success(src, dep_paths, root, None, None);
return false;
}
let ext = compiled.kind.extension();
let out = output_path_for(src, root, output_base, ext);
let content_changed = state
.last_written
.get(&out)
.is_none_or(|prev| *prev != compiled.content);
if content_changed {
match write_output(Some(out.clone()), &compiled.content, quiet, false) {
Ok(()) => {
let elapsed = t0.elapsed().as_millis();
let dep_count = compiled.dependencies.len();
if !quiet {
eprintln!(
"Recompiled {} ({} deps) in {}ms",
safe_path(&out),
dep_count,
elapsed
);
}
let base_no_ext = output_base_no_ext(src, root, output_base);
let stale_path =
base_no_ext.with_extension(compiled.kind.stale_extension());
let tool_wrote_stale = state.last_written.remove(&stale_path).is_some();
if tool_wrote_stale {
probe_and_remove_stale(&base_no_ext, compiled.kind);
}
state.record_success(
src,
dep_paths,
root,
Some(&out),
Some(compiled.content),
);
true
}
Err(e) => {
eprint_error(e);
state.record_error(src);
false
}
}
} else {
state.record_success(src, dep_paths, root, None, None);
false
}
}
Err(e) => {
eprint_error(e);
state.record_error(src);
false
}
}
}
struct DirStartup {
watcher: RecommendedWatcher,
rx: mpsc::Receiver<Msg>,
state: DirWatchState,
liveness: LivenessState,
ctx: DirWatchCtx,
}
struct DirWatchCtx {
root: PathBuf,
vars_path: Option<PathBuf>,
vars_path_raw: 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,
}
fn liveness_probe_dir(
ctx: &DirWatchCtx,
watcher: &mut RecommendedWatcher,
liveness: &mut LivenessState,
state: &mut DirWatchState,
) {
let root_now_exists = ctx.root.exists();
let need_root_rearm = liveness.first_tick
|| (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, RecursiveMode::Recursive).is_ok();
liveness.root_armed = ok;
ok
} else if root_now_exists {
true
} else {
liveness.root_armed = false;
false
};
let dropped_external: Vec<PathBuf> = liveness
.armed_external_dirs
.iter()
.filter(|d| !state.external_dep_dirs.contains(*d))
.cloned()
.collect();
for d in &dropped_external {
let _ = watcher.unwatch(d);
liveness.armed_external_dirs.remove(d);
}
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_external_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_external_dirs.insert(ext_dir.clone());
}
ok
}
} else {
liveness.armed_external_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(ref vd) = ctx.vars_dir_extra {
if vd.exists() {
let _ = watcher.watch(vd, RecursiveMode::NonRecursive);
}
}
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 tracked = state.tracked_set();
let mut batch: BTreeSet<PathBuf> = tracked
.iter()
.filter(|p| path_state_differs(p, &state.last_mtimes))
.cloned()
.collect();
if recovery {
let current: BTreeSet<PathBuf> =
collect_mds_files(&ctx.root, MAX_COLLECT_DEPTH, ctx.exclude_prefix.as_deref())
.into_iter()
.map(|p| graph_key(&p))
.collect();
batch.extend(current.difference(&state.known_files).cloned());
batch.extend(state.known_files.difference(¤t).cloned());
state.known_files = current;
}
if !batch.is_empty() {
let resolved = match build_runtime_vars(RuntimeVarArgs {
vars: ctx.vars_path_raw.clone(),
set_vars: ctx.static_set_vars.clone(),
set_string_vars: ctx.static_set_string_vars.clone(),
}) {
Ok(v) => v,
Err(e) => {
eprint_error(e);
state.last_mtimes = snapshot_state(&state.tracked_set());
return;
}
};
let any_changed = process_dir_batch(
&batch,
false,
&ctx.root,
&ctx.output_base,
&resolved.vars,
ctx.quiet,
state,
);
if any_changed {
crate::build::emit_duplicate_vars_file_warnings(&resolved, ctx.quiet);
}
}
}
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 interrupted = match msg {
Msg::Interrupt => true,
Msg::Fs(Err(e)) => {
eprint_warning(&format!("warning: watch error: {}", safe_inline(&e)));
return DirEventOutcome::Skip;
}
Msg::Fs(Ok(event)) => {
if is_content_event(&event.kind) {
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);
if let OutputBase::Dir(ref od) = ctx.output_base {
changed.retain(|p| !p.starts_with(od));
}
changed.retain(|p| !is_within_default_excluded_dir(&ctx.root, p));
let vars_changed = ctx
.vars_path
.as_deref()
.map(|vf| changed.contains(vf))
.unwrap_or(false);
let mds_changed: BTreeSet<PathBuf> = changed
.iter()
.filter(|p| {
p.extension().and_then(|e| e.to_str()) == Some("mds")
&& (p.starts_with(&ctx.root)
|| state
.external_dep_dirs
.iter()
.any(|d| p.parent() == Some(d.as_path())))
})
.map(|p| graph_key(p))
.collect();
if mds_changed.is_empty() && !vars_changed {
return DirEventOutcome::Skip; }
if ctx.clear {
clear_terminal();
}
let resolved = match build_runtime_vars(RuntimeVarArgs {
vars: ctx.vars_path_raw.clone(),
set_vars: ctx.static_set_vars.clone(),
set_string_vars: ctx.static_set_string_vars.clone(),
}) {
Ok(v) => v,
Err(e) => {
eprint_error(e);
state.last_mtimes = snapshot_state(&state.tracked_set());
return DirEventOutcome::Done;
}
};
let any_changed = process_dir_batch(
&mds_changed,
vars_changed,
&ctx.root,
&ctx.output_base,
&resolved.vars,
ctx.quiet,
state,
);
if any_changed {
crate::build::emit_duplicate_vars_file_warnings(&resolved, ctx.quiet);
}
DirEventOutcome::Done
}
#[allow(clippy::too_many_arguments)]
fn dir_watch_startup(
root: PathBuf,
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,
) -> Result<DirStartup> {
let config = load_config(&root)?;
let vars_path_raw = 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 abs_out_dir = canonicalize_out_dir(out_dir.as_ref());
let output_base = resolve_output_base(abs_out_dir.as_deref(), &config)?;
let exclude_prefix: Option<PathBuf> = match &output_base {
OutputBase::Dir(d) if d.starts_with(&root) => Some(d.clone()),
_ => None,
};
if !quiet {
eprintln!("Watching directory {}", safe_path(&root));
}
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 (tx, rx) = mpsc::channel::<Msg>();
let tx_fs = tx.clone();
let mut watcher = RecommendedWatcher::new(
move |res| {
let _ = tx_fs.send(Msg::Fs(res));
},
notify::Config::default(),
)
.map_err(|e| miette::miette!("failed to initialize file watcher: {e}"))?;
watcher
.watch(&root, RecursiveMode::Recursive)
.map_err(|e| {
miette::miette!(
"failed to watch directory {}: {e}\n\
hint: on Linux you may need to increase fs.inotify.max_user_watches",
root.display()
)
})?;
if let Some(ref vd) = vars_dir_extra {
if let Err(e) = watcher.watch(vd, RecursiveMode::NonRecursive) {
eprint_warning(&format!(
"warning: failed to watch vars directory {}: {}",
safe_path(vd),
safe_inline(&e)
));
}
}
let all_files = collect_mds_files(&root, MAX_COLLECT_DEPTH, exclude_prefix.as_deref());
let resolved = build_runtime_vars(RuntimeVarArgs {
vars: vars_path_raw.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(),
external_dep_dirs: BTreeSet::new(),
last_mtimes: HashMap::new(),
};
let mut pre_mtimes = snapshot_state(
&all_files
.iter()
.map(|p| graph_key(p))
.collect::<HashSet<_>>(),
);
for source in &all_files {
let key = graph_key(source);
match compile_to_content(
source,
runtime_vars.clone(),
quiet,
mds::CompileOptions::default(),
) {
Ok(compiled) => {
let dep_paths: Vec<PathBuf> =
compiled.dependencies.iter().map(PathBuf::from).collect();
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, &root, &output_base, ext);
if let Err(e) = write_output(Some(out.clone()), &compiled.content, quiet, true)
{
eprint_error(e);
} else {
state.last_written.insert(out, compiled.content);
}
}
}
Err(e) => {
eprint_error(e);
state.forward_deps.insert(key.clone(), vec![]);
state.errored.insert(key.clone());
state.known_files.insert(key);
}
}
}
startup_race_probe();
for ext_dir in &state.external_dep_dirs {
if let Err(e) = watcher.watch(ext_dir, RecursiveMode::NonRecursive) {
eprint_warning(&format!(
"warning: failed to watch external dep dir {}: {}",
safe_path(ext_dir),
safe_inline(&e)
));
}
}
{
let baseline_resolved = build_runtime_vars(RuntimeVarArgs {
vars: vars_path_raw.clone(),
set_vars: static_set_vars.clone(),
set_string_vars: static_set_string_vars.clone(),
})?;
let baseline_vars = baseline_resolved.vars;
for source in &all_files {
let key = graph_key(source);
if is_partial(source) {
continue; }
match compile_to_content(
source,
baseline_vars.clone(),
true,
mds::CompileOptions::default(),
) {
Ok(compiled) => {
let ext = compiled.kind.extension();
let out = output_path_for(&key, &root, &output_base, ext);
if state.last_written.contains_key(&out) {
continue;
}
state.last_written.insert(out, compiled.content);
}
Err(_) => {
}
}
}
}
let mut last_mtimes = snapshot_state(&state.tracked_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 startup_armed_external: BTreeSet<PathBuf> = state
.external_dep_dirs
.iter()
.filter(|d| d.exists())
.cloned()
.collect();
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_external_dirs: startup_armed_external,
};
let ctx = DirWatchCtx {
root,
vars_path,
vars_path_raw,
static_set_vars,
static_set_string_vars,
output_base,
exclude_prefix,
vars_dir_extra,
clear,
debounce_ms,
quiet,
};
let tx_ctrlc = tx.clone();
let _ = ctrlc::set_handler(move || {
let _ = tx_ctrlc.send(Msg::Interrupt);
});
emit_ready_marker();
Ok(DirStartup {
watcher,
rx,
state,
liveness,
ctx,
})
}
#[allow(clippy::too_many_arguments)]
fn run_watch_dir(
root: PathBuf,
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>,
) -> Result<()> {
let DirStartup {
mut watcher,
rx,
mut state,
mut liveness,
ctx,
} = dir_watch_startup(
root,
out_dir,
vars,
set_vars,
set_string_vars,
clear,
debounce_ms,
quiet,
)?;
let mut clock = TickClock::new(tick);
loop {
match clock.recv_next(&rx) {
Err(mpsc::RecvTimeoutError::Disconnected) => break,
Ok(None) => {
liveness_probe_dir(&ctx, &mut watcher, &mut liveness, &mut state);
continue;
}
Ok(Some(msg)) => match handle_fs_event_dir(msg, &ctx, &rx, &mut state) {
DirEventOutcome::Skip | DirEventOutcome::Done => {}
DirEventOutcome::Stop => {
stop_watching(ctx.quiet);
return Ok(());
}
},
Err(mpsc::RecvTimeoutError::Timeout) => {}
}
}
stop_watching(ctx.quiet);
Ok(())
}
fn process_dir_batch(
changed: &BTreeSet<PathBuf>,
vars_changed: bool,
root: &Path,
output_base: &OutputBase,
runtime_vars: &Option<HashMap<String, mds::Value>>,
quiet: bool,
state: &mut DirWatchState,
) -> bool {
let any_changed = if vars_changed {
process_dir_batch_vars_changed(root, output_base, runtime_vars, quiet, state)
} else {
process_dir_batch_incremental(changed, root, output_base, runtime_vars, quiet, state)
};
state.last_mtimes = snapshot_state(&state.tracked_set());
any_changed
}
fn process_dir_batch_vars_changed(
root: &Path,
output_base: &OutputBase,
runtime_vars: &Option<HashMap<String, mds::Value>>,
quiet: bool,
state: &mut DirWatchState,
) -> bool {
let mut any_changed = false;
let all_sources: Vec<PathBuf> = state.known_files.iter().cloned().collect();
let deleted: Vec<&PathBuf> = all_sources.iter().filter(|p| !p.exists()).collect();
for del_src in &deleted {
let base_no_ext = output_base_no_ext(del_src, root, output_base);
for ext in &["md", "json"] {
let out = base_no_ext.with_extension(ext);
if out.exists() {
match std::fs::remove_file(&out) {
Ok(()) => {
if !quiet {
eprintln!("Removed {} (source deleted)", safe_path(&out));
}
}
Err(e) => {
eprint_warning(&format!(
"warning: could not remove {}: {}",
safe_path(&out),
safe_inline(&e)
));
}
}
state.forget(del_src, &out);
}
}
state.forward_deps.remove(*del_src);
state.errored.remove(*del_src);
state.known_files.remove(*del_src);
}
state.forward_deps.clear();
state.errored.clear();
state.external_dep_dirs.clear();
for src in &all_sources {
if src.exists() && compile_one_source(src, root, output_base, runtime_vars, quiet, state) {
any_changed = true;
}
}
state.known_files = all_sources.into_iter().filter(|p| p.exists()).collect();
any_changed
}
fn process_dir_batch_incremental(
changed: &BTreeSet<PathBuf>,
root: &Path,
output_base: &OutputBase,
runtime_vars: &Option<HashMap<String, mds::Value>>,
quiet: bool,
state: &mut DirWatchState,
) -> bool {
let mut any_changed = false;
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 false;
}
let affected = affected_sources(&state.forward_deps, &seeds);
for src in &affected {
let is_in_root = src.starts_with(root);
let is_excluded_in_root = is_in_root && is_within_default_excluded_dir(root, src);
let is_known_external = state
.external_dep_dirs
.iter()
.any(|d| src.parent() == Some(d.as_path()));
if !is_in_root && !is_known_external {
continue;
}
if !src.exists() {
if !deleted.contains(src) {
if is_in_root {
let base_no_ext = output_base_no_ext(src, root, output_base);
for ext in &["md", "json"] {
let out = base_no_ext.with_extension(ext);
state.forget(src, &out);
}
} else {
state.forget_graph(src);
}
}
continue;
}
if !is_in_root || is_excluded_in_root {
match compile_to_content(
src,
runtime_vars.clone(),
true,
mds::CompileOptions::default(),
) {
Ok(compiled) => {
let dep_paths: Vec<PathBuf> =
compiled.dependencies.iter().map(PathBuf::from).collect();
state.forward_deps.insert(src.clone(), dep_paths);
state.errored.remove(src);
}
Err(e) => {
eprint_error(e);
state.errored.insert(src.clone());
}
}
continue;
}
if compile_one_source(src, root, output_base, runtime_vars, quiet, state) {
any_changed = true;
}
}
for del_src in &deleted {
let base_no_ext = output_base_no_ext(del_src, root, output_base);
for ext in &["md", "json"] {
let out = base_no_ext.with_extension(ext);
if out.exists() {
match std::fs::remove_file(&out) {
Ok(()) => {
if !quiet {
eprintln!("Removed {} (source deleted)", safe_path(&out));
}
}
Err(e) => {
eprint_warning(&format!(
"warning: could not remove {}: {}",
safe_path(&out),
safe_inline(&e)
));
}
}
}
state.forget(del_src, &out);
}
state.forward_deps.remove(del_src);
state.errored.remove(del_src);
state.known_files.remove(del_src);
}
let live_ext_dirs: BTreeSet<PathBuf> = state
.forward_deps
.values()
.flatten()
.filter_map(|dep| dep.parent().map(Path::to_path_buf))
.filter(|parent| !parent.starts_with(root))
.collect();
state.external_dep_dirs = live_ext_dirs;
any_changed
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn dirs_to_watch_deduplicates_parents() {
let entry = PathBuf::from("/project/src/entry.mds");
let deps = vec![
"/project/src/a.mds".to_string(),
"/project/src/b.mds".to_string(), "/project/lib/c.mds".to_string(), ];
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!["/a/dep1.mds".to_string(), "/b/dep2.mds".to_string()];
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);
}
#[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 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"
);
}
#[test]
fn output_path_for_mirrors_subtree() {
let root = PathBuf::from("/root");
let source = PathBuf::from("/root/a/b/foo.mds");
let base = OutputBase::Dir(PathBuf::from("/out"));
let result = output_path_for(&source, &root, &base, "md");
assert_eq!(result, 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 = OutputBase::Dir(PathBuf::from("/out"));
assert_ne!(
output_path_for(&a, &root, &base, "md"),
output_path_for(&b, &root, &base, "md"),
"two files with the same stem in different subdirs must not collide"
);
assert_eq!(
output_path_for(&a, &root, &base, "md"),
PathBuf::from("/out/a/x.md")
);
assert_eq!(
output_path_for(&b, &root, &base, "md"),
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, &root, &OutputBase::NextToSource, "md");
assert_eq!(result, 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 = OutputBase::Dir(PathBuf::from("/out"));
let result = output_path_for(&source, &root, &base, "md");
assert_eq!(result, 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 = OutputBase::Dir(PathBuf::from("/out"));
let result = output_path_for(&source, &root, &base, "md");
assert!(
result.starts_with("/out"),
"output must stay inside out-dir even when source is outside root; got {result:?}"
);
assert_eq!(result, PathBuf::from("/out/foo.md"));
}
#[test]
fn resolve_output_base_outdir_wins() {
let d = PathBuf::from("/my/out");
let result = resolve_output_base(Some(&d), &None).unwrap();
assert!(matches!(result, OutputBase::Dir(p) if p == d));
}
#[test]
fn resolve_output_base_config_used_when_no_outdir() {
use crate::build::{BuildConfig, MdsConfig};
let config = Some((
MdsConfig {
build: BuildConfig {
output_dir: Some("dist".to_string()),
..Default::default()
},
..Default::default()
},
PathBuf::from("/project"),
));
let result = resolve_output_base(None, &config).unwrap();
assert!(
matches!(result, OutputBase::Dir(ref p) if p == &PathBuf::from("/project/dist")),
"expected Dir(/project/dist), got {result:?}"
);
}
#[test]
fn resolve_output_base_rejects_dotdot() {
use crate::build::{BuildConfig, MdsConfig};
let config = Some((
MdsConfig {
build: BuildConfig {
output_dir: Some("../bad".to_string()),
..Default::default()
},
..Default::default()
},
PathBuf::from("/project"),
));
let result = resolve_output_base(None, &config);
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").unwrap();
assert!(state_differs(&paths, &snap), "should detect content 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"
);
}
#[test]
fn tick_clock_fires_when_idle() {
let (_tx, rx) = mpsc::channel::<Msg>();
let mut clock = TickClock::new(Some(Duration::from_millis(50)));
assert!(
matches!(clock.recv_next(&rx), Ok(None)),
"an idle channel must produce a tick"
);
}
#[test]
fn tick_clock_fires_under_message_flood() {
let (tx, rx) = mpsc::channel::<Msg>();
let sender = std::thread::spawn(move || {
for _ in 0..50 {
if tx.send(Msg::Interrupt).is_err() {
return;
}
std::thread::sleep(Duration::from_millis(5));
}
});
let mut clock = TickClock::new(Some(Duration::from_millis(50)));
let mut ticks = 0usize;
for _ in 0..200 {
match clock.recv_next(&rx) {
Ok(None) => {
ticks += 1;
break;
}
Ok(Some(_)) => {}
Err(_) => break,
}
}
sender.join().expect("sender thread panicked");
assert!(
ticks > 0,
"the idle tick must fire while messages are arriving 10x faster than the \
poll interval; a starvable tick makes the content backstop unreachable"
);
}
#[test]
fn tick_clock_rate_limits_consecutive_ticks() {
let (_tx, rx) = mpsc::channel::<Msg>();
let interval = Duration::from_millis(50);
let mut clock = TickClock::new(Some(interval));
assert!(matches!(clock.recv_next(&rx), Ok(None)), "first tick");
std::thread::sleep(Duration::from_millis(120));
let t0 = Instant::now();
assert!(matches!(clock.recv_next(&rx), Ok(None)), "overdue tick");
let t1 = Instant::now();
assert!(
matches!(clock.recv_next(&rx), Ok(None)),
"tick after the overdue one"
);
assert!(
t1.duration_since(t0) < Duration::from_millis(20),
"an overdue tick must fire immediately, not wait another interval"
);
assert!(
t1.elapsed() >= Duration::from_millis(40),
"the tick following an overdue one must wait a full interval, not fire a \
catch-up burst; got {:?}",
t1.elapsed()
);
}
#[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), Ok(Some(Msg::Interrupt))),
"with no poll interval the clock must deliver the message, never a tick"
);
drop(tx);
assert!(
matches!(
clock.recv_next(&rx),
Err(mpsc::RecvTimeoutError::Disconnected)
),
"a closed channel must report Disconnected rather than tick forever"
);
}
fn modify_event(path: &str) -> Msg {
Msg::Fs(Ok(notify::Event {
kind: notify::EventKind::Modify(notify::event::ModifyKind::Any),
paths: vec![PathBuf::from(path)],
attrs: Default::default(),
}))
}
fn access_event(path: &str) -> Msg {
Msg::Fs(Ok(notify::Event {
kind: notify::EventKind::Access(notify::event::AccessKind::Read),
paths: vec![PathBuf::from(path)],
attrs: Default::default(),
}))
}
fn drain_bounded(
rx: mpsc::Receiver<Msg>,
debounce_ms: u64,
bound: Duration,
why: &str,
) -> DebounceOutcome {
let (done_tx, done_rx) = mpsc::channel();
std::thread::spawn(move || {
let outcome = drain_debounce(&rx, debounce_ms);
let _ = done_tx.send(outcome);
});
done_rx.recv_timeout(bound).unwrap_or_else(|e| {
panic!("drain_debounce did not return within {bound:?} ({e:?}): {why}")
})
}
#[test]
fn debounce_quiet_period_extends_on_content_events() {
let (tx, rx) = mpsc::channel::<Msg>();
let keepalive = tx.clone();
let sender = std::thread::spawn(move || {
for i in 0..40u32 {
if tx.send(modify_event(&format!("/w/f{i}.mds"))).is_err() {
return;
}
std::thread::sleep(Duration::from_millis(5));
}
});
let t0 = Instant::now();
let outcome = drain_bounded(
rx,
100,
Duration::from_secs(3),
"a burst of content events must not postpone the window forever",
);
let elapsed = t0.elapsed();
drop(keepalive);
sender.join().expect("sender thread panicked");
assert_eq!(
outcome.end,
DebounceEnd::Quiet,
"a 200ms burst under a 100ms window must end quiet, not capped"
);
assert_eq!(
outcome.paths.len(),
40,
"every path in the burst must be collected into the one window; got {:?}",
outcome.paths
);
assert!(
elapsed >= Duration::from_millis(240) && elapsed <= Duration::from_millis(900),
"the window must outlast the burst (>=200ms) and then close one window \
later (~100ms), so ~300ms; got {elapsed:?}"
);
}
#[test]
fn debounce_cap_ends_a_continuous_stream() {
let (tx, rx) = mpsc::channel::<Msg>();
let sender = std::thread::spawn(move || {
for _ in 0..1000u32 {
if tx.send(modify_event("/w/hot.mds")).is_err() {
return;
}
std::thread::sleep(Duration::from_millis(2));
}
});
let t0 = Instant::now();
let outcome = drain_bounded(
rx,
50,
Duration::from_secs(3),
"an unbounded window never returns while writes continue",
);
let elapsed = t0.elapsed();
sender.join().expect("sender thread panicked");
assert_eq!(
outcome.end,
DebounceEnd::Cap,
"a continuous stream must end the window at the cap, not quiet"
);
assert!(
elapsed >= Duration::from_millis(900) && elapsed < Duration::from_millis(1600),
"cap for a 50ms window is max(500ms, 1s) = 1s; got {elapsed:?}"
);
}
#[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 t0 = Instant::now();
let outcome = drain_debounce(&rx, 0);
let elapsed = t0.elapsed();
assert_eq!(outcome.end, DebounceEnd::Disabled);
assert!(
outcome.paths.is_empty(),
"a disabled window must collect nothing"
);
assert!(
elapsed < Duration::from_millis(50),
"a disabled window must return immediately; got {elapsed:?}"
);
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>();
let sender = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(20));
let _ = tx.send(Msg::Interrupt);
});
let t0 = Instant::now();
let outcome = drain_bounded(
rx,
5_000,
Duration::from_secs(2),
"Ctrl+C must not wait out the window",
);
let elapsed = t0.elapsed();
sender.join().expect("sender thread panicked");
assert_eq!(outcome.end, DebounceEnd::Interrupted);
assert!(
outcome.interrupted(),
"interrupted() must agree with the end reason"
);
assert!(
elapsed < Duration::from_millis(500),
"an interrupt must end a 5s window immediately; got {elapsed:?}"
);
}
#[test]
fn debounce_access_events_do_not_extend() {
let (tx, rx) = mpsc::channel::<Msg>();
let keepalive = tx.clone();
let sender = std::thread::spawn(move || {
if tx.send(modify_event("/w/a.mds")).is_err() {
return;
}
for _ in 0..60u32 {
if tx.send(access_event("/w/a.mds")).is_err() {
return;
}
std::thread::sleep(Duration::from_millis(5));
}
});
let t0 = Instant::now();
let outcome = drain_bounded(
rx,
100,
Duration::from_secs(3),
"a stream of reads must not hold the window open",
);
let elapsed = t0.elapsed();
drop(keepalive);
sender.join().expect("sender thread panicked");
assert_eq!(outcome.end, DebounceEnd::Quiet);
assert_eq!(
outcome.paths.len(),
1,
"only the one content event contributes a path; got {:?}",
outcome.paths
);
assert!(
elapsed < Duration::from_millis(250),
"300ms of reads must not extend a 100ms window past ~100ms; got {elapsed:?}"
);
}
#[test]
fn debounce_message_limit_bounds_one_window() {
let (tx, rx) = mpsc::channel::<Msg>();
for _ in 0..12_000u32 {
tx.send(modify_event("/w/same.mds")).expect("send failed");
}
let t0 = Instant::now();
let outcome = drain_bounded(
rx,
100,
Duration::from_secs(5),
"an unbounded message count lets a fast sender own the window",
);
let elapsed = t0.elapsed();
drop(tx);
assert_eq!(
outcome.end,
DebounceEnd::MessageLimit,
"12 000 queued events must hit the message bound, not the quiet period"
);
assert_eq!(
outcome.paths.len(),
1,
"all 12 000 events name the same path; got {:?}",
outcome.paths
);
assert!(
elapsed < Duration::from_secs(2),
"the bound must be reached promptly; got {elapsed:?}"
);
}
#[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 t0 = Instant::now();
let outcome = drain_debounce(&rx, 5_000);
let elapsed = t0.elapsed();
assert_eq!(outcome.end, DebounceEnd::Disconnected);
assert_eq!(
outcome.paths.len(),
1,
"messages queued before the disconnect must still be collected; got {:?}",
outcome.paths
);
assert!(
elapsed < Duration::from_millis(500),
"a disconnect must end a 5s window immediately; got {elapsed:?}"
);
}
#[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(),
external_dep_dirs: BTreeSet::new(),
last_mtimes: HashMap::new(),
};
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(),
external_dep_dirs: BTreeSet::new(),
last_mtimes: HashMap::new(),
};
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(),
external_dep_dirs: BTreeSet::new(),
last_mtimes: HashMap::new(),
};
state.known_files.insert(victim.clone());
state
.last_written
.insert(victim_out.clone(), "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,
&root,
&OutputBase::Dir(out.clone()),
&None,
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 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(),
external_dep_dirs: BTreeSet::new(),
last_mtimes: HashMap::new(),
};
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 = OutputBase::Dir(new_subdir.clone());
let result = output_path_for(&source, &root, &base, "md");
assert_eq!(result, 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 (_written_path, deps, _content) = compile_and_write(
&entry,
&Some(out_str),
&None,
&None,
None,
true,
mds::CompileOptions::default(),
)
.unwrap();
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:?}"
);
}
}