Skip to main content

buildl_core/watch/
react.rs

1//! What one batch of changed paths starts.
2//!
3//! Responsibilities: [`kept`], which holds the paths of a batch that are changes, and [`react`],
4//! which sorts a batch into a build, a check of the build files, or nothing.
5//!
6//! Non-responsibilities: what kind of event named a path. A path created, written, renamed or
7//! removed is the same change here.
8
9use crate::ports::IgnoreRules;
10use crate::types::{
11    ChangeBatch, ChangedPath, Directory, EntryKind, Reaction, Reference, WatchLayout,
12};
13
14/// Whether `path` is `dir` or lies below it.
15///
16/// The workspace root holds every path. A shared prefix is not containment: `out` does not hold
17/// `outer/x`.
18fn under(path: &ChangedPath, dir: &Directory) -> bool {
19    dir.is_root() || under_text(path.as_str(), dir.as_str())
20}
21
22/// Whether `path` is the directory `dir` or starts with it followed by `/`.
23fn under_text(path: &str, dir: &str) -> bool {
24    path.strip_prefix(dir)
25        .is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))
26}
27
28/// The paths of `batch` that are changes to the workspace, or `None` when none is.
29///
30/// Paths under the output directory, the state directory or `.git` are not changes: the build
31/// itself writes the first two, and none of the three holds a source. Nor is a path that `rules`
32/// reports ignored, asked as [`EntryKind::Unknown`] because a changed path may be gone. Without
33/// `rules`, nothing is dropped for being ignored, and a path whose question fails is kept.
34#[must_use]
35pub(super) fn kept<I: IgnoreRules>(
36    batch: &ChangeBatch,
37    layout: &WatchLayout,
38    rules: Option<&I>,
39) -> Option<ChangeBatch> {
40    ChangeBatch::new(
41        batch
42            .iter()
43            .filter(|path| {
44                !(under(path, &layout.out)
45                    || under(path, &layout.state)
46                    || under_text(path.as_str(), ".git")
47                    || is_ignored(rules, path))
48            })
49            .cloned()
50            .collect(),
51    )
52}
53
54/// Whether `rules` report `path` ignored. No rules, or a failing question, report nothing.
55fn is_ignored<I: IgnoreRules>(rules: Option<&I>, path: &ChangedPath) -> bool {
56    rules.is_some_and(|rules| {
57        matches!(
58            rules.ignored(path.as_str(), EntryKind::Unknown),
59            Ok(Some(_))
60        )
61    })
62}
63
64/// What `batch` starts, given what the last build and the last open of the workspace read.
65///
66/// Only the paths left after the drop count: those under the output directory, the state
67/// directory or `.git`, and those `rules` report ignored, are dropped. A batch with none left is
68/// [`Reaction::Ignore`]. Otherwise it is [`Reaction::Build`] when the last cycle left no graph,
69/// when a path kept is an input of the last build, or when it is one of the files that decide the
70/// workspace's settings; any other batch is [`Reaction::Check`], for the build files may now
71/// declare a different graph.
72#[must_use]
73pub fn react<I: IgnoreRules>(
74    batch: &ChangeBatch,
75    reference: &Reference,
76    rules: Option<&I>,
77) -> Reaction {
78    let layout = &reference.layout;
79    let Some(kept) = kept(batch, layout, rules) else {
80        return Reaction::Ignore;
81    };
82    let Some(built) = &reference.built else {
83        return Reaction::Build;
84    };
85    let starts_build = kept.iter().any(|path| {
86        layout.config.contains(path)
87            || built
88                .inputs
89                .iter()
90                .any(|input| input.as_str() == path.as_str())
91    });
92    if starts_build {
93        Reaction::Build
94    } else {
95        Reaction::Check
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    #![expect(
102        clippy::unwrap_used,
103        reason = "tests unwrap known-valid fixtures; a panic is the intended failure signal"
104    )]
105
106    use std::collections::BTreeMap;
107    use std::sync::Mutex;
108
109    use super::{kept, react, under};
110    use crate::error::{Error, Result};
111    use crate::ports::IgnoreRules;
112    use crate::types::{
113        Built, ChangeBatch, ChangedPath, Directory, EntryKind, Ignoring, Reaction, Reference,
114        SourcePath, TargetGraph, WatchLayout,
115    };
116
117    /// Rules ignoring the paths in `ignored`, or failing every question when `fails` is set, and
118    /// remembering the kind of each question.
119    #[derive(Default)]
120    struct Rules {
121        ignored: Vec<&'static str>,
122        fails: bool,
123        kinds: Mutex<Vec<EntryKind>>,
124    }
125
126    impl Rules {
127        fn ignoring(ignored: &[&'static str]) -> Self {
128            Self {
129                ignored: ignored.to_vec(),
130                ..Self::default()
131            }
132        }
133
134        fn failing() -> Self {
135            Self {
136                fails: true,
137                ..Self::default()
138            }
139        }
140
141        fn kinds(&self) -> Vec<EntryKind> {
142            self.kinds.lock().unwrap().clone()
143        }
144    }
145
146    impl IgnoreRules for Rules {
147        fn ignored(&self, path: &str, kind: EntryKind) -> Result<Option<Ignoring>> {
148            self.kinds.lock().unwrap().push(kind);
149            if self.fails {
150                return Err(Error::IgnoreFile {
151                    file: ".buildlignore".to_owned(),
152                    line: Some(1),
153                    reason: "unreadable".to_owned(),
154                });
155            }
156            Ok(self
157                .ignored
158                .contains(&path)
159                .then(|| Ignoring::new(".buildlignore", path)))
160        }
161    }
162
163    fn path(raw: &str) -> ChangedPath {
164        ChangedPath::parse(raw).unwrap()
165    }
166
167    fn batch(raws: &[&str]) -> ChangeBatch {
168        ChangeBatch::new(raws.iter().map(|raw| path(raw)).collect()).unwrap()
169    }
170
171    fn reference(out: &str, inputs: &[&str], built: bool) -> Reference {
172        Reference {
173            layout: WatchLayout {
174                out: Directory::parse(out).unwrap(),
175                state: Directory::parse(".buildl").unwrap(),
176                config: ["buildl.toml", "buildl.lock", "plugins/go/extension.toml"]
177                    .iter()
178                    .map(|raw| path(raw))
179                    .collect(),
180            },
181            built: built.then(|| Built {
182                graph: TargetGraph::new(Vec::new(), Vec::new(), BTreeMap::new(), BTreeMap::new()),
183                inputs: inputs
184                    .iter()
185                    .map(|raw| SourcePath::parse(*raw).unwrap())
186                    .collect(),
187            }),
188        }
189    }
190
191    #[test]
192    fn under_holds_for_the_directory_and_below_it_only() {
193        let out = Directory::parse("out").unwrap();
194        assert!(under(&path("out/x.o"), &out));
195        assert!(under(&path("out"), &out));
196        assert!(!under(&path("outer/x"), &out));
197        assert!(under(
198            &path("anything/at/all"),
199            &Directory::parse("").unwrap()
200        ));
201    }
202
203    #[test]
204    fn kept_holds_the_paths_outside_the_ignored_directories() {
205        let reference = reference("out", &[], true);
206        let changes = batch(&[
207            "out/x.o",
208            ".buildl/log.jsonl",
209            ".git/index",
210            "b.txt",
211            "a.txt",
212        ]);
213        assert_eq!(
214            kept(&changes, &reference.layout, None::<&Rules>),
215            Some(batch(&["a.txt", "b.txt"]))
216        );
217    }
218
219    #[test]
220    fn kept_is_none_when_every_path_is_dropped() {
221        let reference = reference("out", &[], true);
222        let changes = batch(&["out/x.o", ".buildl/log.jsonl", ".git/index"]);
223        assert_eq!(kept(&changes, &reference.layout, None::<&Rules>), None);
224    }
225
226    #[test]
227    fn only_ignored_directories_is_ignore() {
228        let reference = reference("out", &[], true);
229        let changes = batch(&["out/x.o", ".buildl/log.jsonl", ".git/index"]);
230        assert_eq!(
231            react(&changes, &reference, None::<&Rules>),
232            Reaction::Ignore
233        );
234    }
235
236    #[test]
237    fn a_changed_out_directory_moves_the_drop() {
238        let reference = reference("build", &[], true);
239        assert_eq!(
240            react(&batch(&["build/x.o"]), &reference, None::<&Rules>),
241            Reaction::Ignore
242        );
243        assert_eq!(
244            react(&batch(&["out/x.o"]), &reference, None::<&Rules>),
245            Reaction::Check
246        );
247    }
248
249    #[test]
250    fn no_graph_builds() {
251        let reference = reference("out", &[], false);
252        assert_eq!(
253            react(&batch(&["README.md"]), &reference, None::<&Rules>),
254            Reaction::Build
255        );
256    }
257
258    #[test]
259    fn an_input_builds() {
260        let reference = reference("out", &["lib/words/a.txt"], true);
261        assert_eq!(
262            react(&batch(&["lib/words/a.txt"]), &reference, None::<&Rules>),
263            Reaction::Build
264        );
265    }
266
267    #[test]
268    fn a_config_file_builds() {
269        let reference = reference("out", &[], true);
270        for raw in ["buildl.toml", "buildl.lock", "plugins/go/extension.toml"] {
271            assert_eq!(
272                react(&batch(&[raw]), &reference, None::<&Rules>),
273                Reaction::Build,
274                "{raw}"
275            );
276        }
277    }
278
279    #[test]
280    fn anything_else_checks() {
281        let reference = reference("out", &["lib/words/a.txt"], true);
282        for raw in ["README.md", ".#a.c"] {
283            assert_eq!(
284                react(&batch(&[raw]), &reference, None::<&Rules>),
285                Reaction::Check,
286                "{raw}"
287            );
288        }
289    }
290
291    #[test]
292    fn an_input_beside_ignored_paths_still_builds() {
293        let reference = reference("out", &["lib/words/a.txt"], true);
294        let changes = batch(&["out/x.o", "lib/words/a.txt"]);
295        assert_eq!(react(&changes, &reference, None::<&Rules>), Reaction::Build);
296    }
297
298    #[test]
299    fn an_ignored_path_is_dropped() {
300        let reference = reference("out", &[], true);
301        let rules = Rules::ignoring(&["notes/a.md"]);
302        let changes = batch(&["notes/a.md", "src/a.c"]);
303        assert_eq!(
304            kept(&changes, &reference.layout, Some(&rules)),
305            Some(batch(&["src/a.c"]))
306        );
307    }
308
309    #[test]
310    fn a_batch_of_only_ignored_paths_is_no_change() {
311        let reference = reference("out", &[], true);
312        let rules = Rules::ignoring(&["notes/a.md"]);
313        let changes = batch(&["notes/a.md"]);
314        assert_eq!(kept(&changes, &reference.layout, Some(&rules)), None);
315        assert_eq!(react(&changes, &reference, Some(&rules)), Reaction::Ignore);
316    }
317
318    #[test]
319    fn without_rules_nothing_is_dropped_by_rules() {
320        let reference = reference("out", &[], true);
321        let changes = batch(&["notes/a.md"]);
322        assert_eq!(
323            kept(&changes, &reference.layout, None::<&Rules>),
324            Some(batch(&["notes/a.md"]))
325        );
326    }
327
328    #[test]
329    fn a_rule_error_keeps_the_path() {
330        let reference = reference("out", &[], true);
331        let rules = Rules::failing();
332        let changes = batch(&["notes/a.md"]);
333        assert_eq!(
334            kept(&changes, &reference.layout, Some(&rules)),
335            Some(batch(&["notes/a.md"]))
336        );
337    }
338
339    #[test]
340    fn paths_are_asked_as_unknown() {
341        let reference = reference("out", &[], true);
342        let rules = Rules::ignoring(&["notes/a.md"]);
343        let changes = batch(&["notes/a.md", "src/a.c"]);
344        let _ = kept(&changes, &reference.layout, Some(&rules));
345        assert_eq!(rules.kinds(), [EntryKind::Unknown, EntryKind::Unknown]);
346    }
347
348    #[test]
349    fn the_built_in_drops_are_not_asked_about() {
350        let reference = reference("out", &[], true);
351        let rules = Rules::ignoring(&[]);
352        let changes = batch(&["out/x.o", ".git/index", "src/a.c"]);
353        let _ = kept(&changes, &reference.layout, Some(&rules));
354        assert_eq!(rules.kinds(), [EntryKind::Unknown]);
355    }
356}