use crate::error::Error;
use crate::ports::{Changes, Cycles, NothingIgnored, WatchReport};
use crate::types::{Cycle, Reaction, Reference, Trigger, WatchLayout};
use crate::watch::react::{kept, react};
pub fn watch<C: Changes, Y: Cycles + WatchReport>(
changes: &mut C,
cycles: &mut Y,
layout: WatchLayout,
) -> Error {
let mut reference = cycle(
cycles,
Reference {
layout,
built: None,
},
&Trigger::Start,
);
loop {
let batch = match changes.next() {
Ok(batch) => batch,
Err(error) => return error,
};
let Some(batch) = kept(&batch, &reference.layout, cycles.rules()) else {
continue;
};
let build = match react(&batch, &reference, None::<&NothingIgnored>) {
Reaction::Build => true,
Reaction::Ignore => false,
Reaction::Check => cycles.graph().map_or(true, |graph| {
reference
.built
.as_ref()
.is_none_or(|built| built.graph != graph)
}),
};
if build {
reference = cycle(cycles, reference, &Trigger::Changed(batch));
}
}
}
fn cycle<Y: Cycles + WatchReport>(
cycles: &mut Y,
reference: Reference,
trigger: &Trigger,
) -> Reference {
cycles.building(trigger);
let ended = cycles.build();
if let Err(error) = &ended.watched.ended {
cycles.failed(error);
}
let reference = renew(reference, ended);
cycles.waiting();
reference
}
fn renew(reference: Reference, cycle: Cycle) -> Reference {
Reference {
layout: cycle.layout.unwrap_or(reference.layout),
built: cycle.watched.built,
}
}
#[cfg(test)]
mod tests {
#![expect(
clippy::unwrap_used,
reason = "tests unwrap known-valid fixtures; a panic is the intended failure signal"
)]
use std::cell::RefCell;
use std::collections::{BTreeMap, VecDeque};
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use super::watch;
use crate::error::{Error, PortName, Result};
use crate::ports::{Changes, Cycles, IgnoreRules, WatchReport};
use crate::types::{
Built, ChangeBatch, ChangedPath, Cycle, Diagnostic, Directory, EntryKind, Ignoring,
SettingName, SettingValue, TargetGraph, Trigger, WatchLayout, Watched,
};
struct Rules {
held: Vec<&'static str>,
asked: Arc<Mutex<Vec<String>>>,
}
impl Rules {
fn new(held: Vec<&'static str>) -> Self {
Self {
held,
asked: Arc::default(),
}
}
}
impl IgnoreRules for Rules {
fn ignored(&self, path: &str, _kind: EntryKind) -> Result<Option<Ignoring>> {
self.asked.lock().unwrap().push(path.to_owned());
Ok(self
.held
.contains(&path)
.then(|| Ignoring::new(".buildlignore", path)))
}
}
#[derive(Debug, PartialEq)]
enum Call {
Next,
Building(Trigger),
Build,
Graph,
Failed(String),
Waiting,
}
type Log = Rc<RefCell<Vec<Call>>>;
struct Scripted {
log: Log,
batches: VecDeque<ChangeBatch>,
}
impl Changes for Scripted {
fn next(&mut self) -> Result<ChangeBatch> {
self.log.borrow_mut().push(Call::Next);
self.batches.pop_front().ok_or_else(|| Error::Adapter {
port: PortName::Changes,
diagnostic: Diagnostic::new("no more changes"),
})
}
}
struct Fake {
log: Log,
cycles: VecDeque<Cycle>,
graphs: VecDeque<Result<TargetGraph>>,
rules: Option<Rules>,
}
impl Cycles for Fake {
type Ignore = Rules;
fn rules(&self) -> Option<&Rules> {
self.rules.as_ref()
}
fn build(&mut self) -> Cycle {
self.log.borrow_mut().push(Call::Build);
self.cycles.pop_front().unwrap_or_else(|| cycle(None, None))
}
fn graph(&mut self) -> Result<TargetGraph> {
self.log.borrow_mut().push(Call::Graph);
self.graphs.pop_front().unwrap()
}
}
impl WatchReport for Fake {
fn building(&mut self, trigger: &Trigger) {
self.log.borrow_mut().push(Call::Building(trigger.clone()));
}
fn failed(&mut self, error: &Error) {
self.log.borrow_mut().push(Call::Failed(error.to_string()));
}
fn waiting(&mut self) {
self.log.borrow_mut().push(Call::Waiting);
}
}
fn path(raw: &str) -> ChangedPath {
ChangedPath::parse(raw).unwrap()
}
fn batch(raws: &[&str]) -> ChangeBatch {
ChangeBatch::new(raws.iter().map(|raw| path(raw)).collect()).unwrap()
}
fn layout(out: &str) -> WatchLayout {
WatchLayout {
out: Directory::parse(out).unwrap(),
state: Directory::parse(".buildl").unwrap(),
config: std::iter::once(path("buildl.toml")).collect(),
}
}
fn graph(mark: &str) -> TargetGraph {
TargetGraph::new(
Vec::new(),
Vec::new(),
BTreeMap::new(),
BTreeMap::from([(
SettingName::parse("mark").unwrap(),
SettingValue::parse(mark).unwrap(),
)]),
)
}
fn built(mark: &str) -> Built {
Built {
graph: graph(mark),
inputs: std::collections::BTreeSet::new(),
}
}
fn cycle(layout: Option<WatchLayout>, built: Option<Built>) -> Cycle {
Cycle {
layout,
watched: Watched {
built,
ended: Ok(Vec::new()),
},
}
}
fn run(
batches: Vec<ChangeBatch>,
cycles: Vec<Cycle>,
graphs: Vec<Result<TargetGraph>>,
) -> (Error, Vec<Call>) {
run_with(None, batches, cycles, graphs)
}
fn run_with(
rules: Option<Rules>,
batches: Vec<ChangeBatch>,
cycles: Vec<Cycle>,
graphs: Vec<Result<TargetGraph>>,
) -> (Error, Vec<Call>) {
let log = Log::default();
let mut changes = Scripted {
log: Rc::clone(&log),
batches: batches.into(),
};
let mut fake = Fake {
log: Rc::clone(&log),
cycles: cycles.into(),
graphs: graphs.into(),
rules,
};
let error = watch(&mut changes, &mut fake, layout("out"));
let calls = log.take();
(error, calls)
}
#[test]
fn the_first_cycle_runs_before_any_change() {
let (_, calls) = run(Vec::new(), vec![cycle(None, None)], Vec::new());
assert_eq!(
calls,
[
Call::Building(Trigger::Start),
Call::Build,
Call::Waiting,
Call::Next,
]
);
}
#[test]
fn an_ignored_batch_runs_nothing_and_says_nothing() {
let first = cycle(Some(layout("out")), Some(built("a")));
let (_, calls) = run(vec![batch(&["out/x.o"])], vec![first], Vec::new());
assert_eq!(
calls,
[
Call::Building(Trigger::Start),
Call::Build,
Call::Waiting,
Call::Next,
Call::Next,
]
);
}
#[test]
fn a_check_with_an_unchanged_graph_runs_no_build() {
let first = cycle(Some(layout("out")), Some(built("a")));
let (_, calls) = run(
vec![batch(&["README.md"])],
vec![first],
vec![Ok(graph("a"))],
);
assert_eq!(
calls,
[
Call::Building(Trigger::Start),
Call::Build,
Call::Waiting,
Call::Next,
Call::Graph,
Call::Next,
]
);
}
#[test]
fn a_check_with_a_changed_graph_builds() {
let changes = batch(&["README.md"]);
let first = cycle(Some(layout("out")), Some(built("a")));
let second = cycle(Some(layout("out")), Some(built("b")));
let (_, calls) = run(
vec![changes.clone()],
vec![first, second],
vec![Ok(graph("b"))],
);
assert_eq!(
calls,
[
Call::Building(Trigger::Start),
Call::Build,
Call::Waiting,
Call::Next,
Call::Graph,
Call::Building(Trigger::Changed(changes)),
Call::Build,
Call::Waiting,
Call::Next,
]
);
}
#[test]
fn a_check_that_fails_builds() {
let changes = batch(&["README.md"]);
let first = cycle(Some(layout("out")), Some(built("a")));
let failed = Err(Error::Adapter {
port: PortName::Host,
diagnostic: Diagnostic::new("build file did not load"),
});
let (_, calls) = run(
vec![changes.clone()],
vec![first, cycle(None, None)],
vec![failed],
);
assert_eq!(
calls,
[
Call::Building(Trigger::Start),
Call::Build,
Call::Waiting,
Call::Next,
Call::Graph,
Call::Building(Trigger::Changed(changes)),
Call::Build,
Call::Waiting,
Call::Next,
]
);
}
#[test]
fn a_failed_cycle_is_reported_and_watching_goes_on() {
let mut first = cycle(None, None);
first.watched.ended = Err(Error::Adapter {
port: PortName::Host,
diagnostic: Diagnostic::new("boom"),
});
let (_, calls) = run(Vec::new(), vec![first], Vec::new());
assert_eq!(
calls,
[
Call::Building(Trigger::Start),
Call::Build,
Call::Failed("host: boom".to_owned()),
Call::Waiting,
Call::Next,
]
);
}
#[test]
fn after_a_cycle_without_a_graph_any_change_builds() {
let changes = batch(&["README.md"]);
let (_, calls) = run(
vec![changes.clone()],
vec![cycle(Some(layout("out")), None), cycle(None, None)],
Vec::new(),
);
assert_eq!(
calls,
[
Call::Building(Trigger::Start),
Call::Build,
Call::Waiting,
Call::Next,
Call::Building(Trigger::Changed(changes)),
Call::Build,
Call::Waiting,
Call::Next,
]
);
}
#[test]
fn a_cycle_without_a_graph_forgets_the_last_one() {
let changes = batch(&["README.md"]);
let first = cycle(Some(layout("out")), Some(built("a")));
let second = cycle(Some(layout("out")), None);
let (_, calls) = run(
vec![changes.clone(), changes.clone()],
vec![first, second, cycle(None, None)],
vec![Ok(graph("b"))],
);
assert_eq!(
calls,
[
Call::Building(Trigger::Start),
Call::Build,
Call::Waiting,
Call::Next,
Call::Graph,
Call::Building(Trigger::Changed(changes.clone())),
Call::Build,
Call::Waiting,
Call::Next,
Call::Building(Trigger::Changed(changes)),
Call::Build,
Call::Waiting,
Call::Next,
]
);
}
#[test]
fn a_cycle_that_could_not_open_keeps_the_old_layout() {
let first = cycle(None, Some(built("a")));
let (_, calls) = run(vec![batch(&["out/x.o"])], vec![first], Vec::new());
assert_eq!(
calls,
[
Call::Building(Trigger::Start),
Call::Build,
Call::Waiting,
Call::Next,
Call::Next,
]
);
}
#[test]
fn a_cycle_with_a_new_layout_moves_the_drop() {
let first = cycle(Some(layout("build")), Some(built("a")));
let (_, calls) = run(vec![batch(&["build/x.o"])], vec![first], Vec::new());
assert_eq!(
calls,
[
Call::Building(Trigger::Start),
Call::Build,
Call::Waiting,
Call::Next,
Call::Next,
]
);
}
#[test]
fn the_trigger_names_the_batch() {
let changes = batch(&["b.txt", "a.txt"]);
let (_, calls) = run(vec![changes], vec![cycle(None, None)], Vec::new());
let named = calls.iter().find_map(|call| match call {
Call::Building(Trigger::Changed(named)) => Some(named),
_ => None,
});
let named = named.unwrap();
assert_eq!(named.first().as_str(), "a.txt");
assert_eq!(named.len(), 2);
}
#[test]
fn the_trigger_names_only_the_paths_kept() {
let changes = batch(&["out/x.o", ".buildl/log.jsonl", "lib/words/a.txt"]);
let first = cycle(Some(layout("out")), Some(built("a")));
let (_, calls) = run(
vec![changes],
vec![first, cycle(None, None)],
vec![Ok(graph("b"))],
);
assert_eq!(
calls[5],
Call::Building(Trigger::Changed(batch(&["lib/words/a.txt"])))
);
}
#[test]
fn a_changes_error_ends_the_loop_with_that_error() {
let (error, _) = run(Vec::new(), vec![cycle(None, None)], Vec::new());
assert!(matches!(
error,
Error::Adapter {
port: PortName::Changes,
..
}
));
assert_eq!(error.to_string(), "file watcher: no more changes");
}
#[test]
fn the_loop_filters_with_the_last_opened_rules() {
let first = cycle(Some(layout("out")), Some(built("a")));
let second = cycle(Some(layout("out")), Some(built("b")));
let changes = batch(&["src/a.c"]);
let (_, calls) = run_with(
Some(Rules::new(vec!["notes/a.md"])),
vec![batch(&["notes/a.md"]), changes.clone()],
vec![first, second],
vec![Ok(graph("b"))],
);
assert_eq!(
calls,
[
Call::Building(Trigger::Start),
Call::Build,
Call::Waiting,
Call::Next,
Call::Next,
Call::Graph,
Call::Building(Trigger::Changed(changes)),
Call::Build,
Call::Waiting,
Call::Next,
]
);
}
#[test]
fn the_trigger_names_only_the_paths_the_rules_keep() {
let first = cycle(Some(layout("out")), Some(built("a")));
let (_, calls) = run_with(
Some(Rules::new(vec!["notes/a.md"])),
vec![batch(&["notes/a.md", "src/a.c"])],
vec![first, cycle(None, None)],
vec![Ok(graph("b"))],
);
assert_eq!(
calls[5],
Call::Building(Trigger::Changed(batch(&["src/a.c"])))
);
}
#[test]
fn each_changed_path_is_asked_of_the_rules_once() {
let first = cycle(Some(layout("out")), Some(built("a")));
let rules = Rules::new(vec!["notes/a.md"]);
let asked = Arc::clone(&rules.asked);
let _ = run_with(
Some(rules),
vec![batch(&["notes/a.md", "src/a.c"])],
vec![first, cycle(None, None)],
vec![Ok(graph("b"))],
);
assert_eq!(*asked.lock().unwrap(), ["notes/a.md", "src/a.c"]);
}
}