Skip to main content

gdtest_analysis/
deps.rs

1//! Test impact analysis: which test files a change can affect.
2//!
3//! Which file uses which comes from [`gdsyntax::project`], which reads it
4//! from the source. A test file is affected by a change when it reaches a
5//! changed file through those links. What the source cannot tell is handled
6//! cautiously:
7//!
8//! - a script that loads a computed path (`load(path)`) may load any file, so
9//!   the tests that reach it always run; with a known folder
10//!   (`load("res://items/" + id)`), it depends on every file of that folder;
11//! - `project.godot`, the autoloads and the test runner's own files change
12//!   what every test runs with, so a change to one of them affects every test.
13//!
14//! What the tests did when they last ran adds to that, as Vitest learns a
15//! test's dynamic imports by running it: the worker reports the scenes and
16//! scripts of the nodes each test added to the tree, and [`record_uses`]
17//! keeps them per test file. A test file uses what it was seen to use, and
18//! once seen, a computed `load()` it reaches no longer makes it run on every
19//! change.
20
21use std::collections::{BTreeSet, HashMap, HashSet};
22use std::path::Path;
23
24pub use gdsyntax::project::{DepGraph, FileDeps, in_folder, parse_script, parse_text_resource};
25
26/// Which test files a change affects.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum Impact {
29    /// Every test: `reason` says why.
30    All { reason: String },
31    /// These test files, and no other.
32    Files(BTreeSet<String>),
33}
34
35/// The project's dependency graph, with what the tests were seen using.
36#[derive(Debug, Default)]
37pub struct Graph {
38    /// Which file uses which, from the source and from what the tests were
39    /// seen using.
40    pub project: gdsyntax::project::Graph,
41    /// Files whose change affects every test, with the reason.
42    global: HashMap<String, String>,
43    /// Folders whose files affect every test (the test runner's addon).
44    global_folders: Vec<(String, String)>,
45    /// Test files seen running, with what they used: see [`record_uses`].
46    seen: HashSet<String>,
47}
48
49/// Where gdtest keeps what each test file used when it last ran.
50pub fn uses_path(project_abs: &Path) -> std::path::PathBuf {
51    project_abs.join(".godot").join("gdtest").join("uses.json")
52}
53
54/// What each test file was seen to use: test file → res:// paths.
55pub fn read_uses(project_abs: &Path) -> HashMap<String, BTreeSet<String>> {
56    std::fs::read_to_string(uses_path(project_abs))
57        .ok()
58        .and_then(|text| serde_json::from_str(&text).ok())
59        .unwrap_or_default()
60}
61
62/// Adds what the test files of a run used to what was seen before. Kept
63/// across runs, so a test that loads different scenes on different runs
64/// depends on all of them.
65pub fn record_uses(
66    project_abs: &Path,
67    uses: &HashMap<String, BTreeSet<String>>,
68) -> anyhow::Result<()> {
69    let mut all = read_uses(project_abs);
70    for (file, paths) in uses {
71        all.entry(file.clone())
72            .or_default()
73            .extend(paths.iter().cloned());
74    }
75    let path = uses_path(project_abs);
76    if let Some(parent) = path.parent() {
77        std::fs::create_dir_all(parent)?;
78    }
79    let sorted: std::collections::BTreeMap<_, _> = all.into_iter().collect();
80    std::fs::write(&path, serde_json::to_string_pretty(&sorted)?)?;
81    Ok(())
82}
83
84impl Graph {
85    /// Reads the project's scripts, scenes and resources, and what its tests
86    /// were seen using.
87    pub fn build(project_abs: &Path) -> Graph {
88        let mut graph = Graph {
89            project: gdsyntax::project::Graph::build(project_abs),
90            ..Graph::default()
91        };
92        for (test, paths) in read_uses(project_abs) {
93            for path in paths {
94                graph.project.add_use(&test, &path);
95            }
96            graph.seen.insert(test);
97        }
98        graph.global.insert(
99            "res://project.godot".to_string(),
100            "project.godot changed".to_string(),
101        );
102        for config in ["res://gdtest.toml", "res://.gdtest.toml"] {
103            graph
104                .global
105                .insert(config.to_string(), format!("{} changed", &config[6..]));
106        }
107        graph.global_folders.push((
108            "res://addons/gdtest/".to_string(),
109            "the gdtest addon changed".to_string(),
110        ));
111        for (name, path) in graph.project.autoloads().clone() {
112            graph
113                .global
114                .insert(path, format!("the autoload {name} changed"));
115        }
116        graph
117    }
118
119    /// The test files among `tests` that a change to `changed` (res://
120    /// paths) affects.
121    pub fn impact(&self, changed: &[String], tests: &[String]) -> Impact {
122        for file in changed {
123            if let Some(reason) = self.global.get(file) {
124                return Impact::All {
125                    reason: reason.clone(),
126                };
127            }
128            for (folder, reason) in &self.global_folders {
129                if file.starts_with(folder.as_str()) {
130                    return Impact::All {
131                        reason: reason.clone(),
132                    };
133                }
134            }
135        }
136
137        // The changed files, and the files that load from their folders.
138        let start = self.project.with_folder_loaders(changed);
139        let reached = self.project.users_of(&start);
140
141        let mut affected = BTreeSet::new();
142        for test in tests {
143            if start.contains(test) || reached.contains(test) || self.loads_unknown(test) {
144                affected.insert(test.clone());
145            }
146        }
147        Impact::Files(affected)
148    }
149
150    /// Whether `file`, or a file it uses, loads a path the source does not
151    /// tell: then any change may affect it.
152    pub fn loads_unknown(&self, file: &str) -> bool {
153        // What it loads was seen when it ran.
154        if !self.project.has_unknown_loads() || self.seen.contains(file) {
155            return false;
156        }
157        let mut seen: HashSet<&str> = HashSet::new();
158        let mut stack = vec![file];
159        while let Some(current) = stack.pop() {
160            if !seen.insert(current) {
161                continue;
162            }
163            // The test runner loads whatever it runs; a change to it
164            // already affects every test.
165            if self.in_global_folder(current) {
166                continue;
167            }
168            if self.project.loads_unknown(current) {
169                return true;
170            }
171            if let Some(uses) = self.project.forward.get(current) {
172                stack.extend(uses.iter().map(String::as_str));
173            }
174        }
175        false
176    }
177
178    /// The files that load paths the source does not tell, among the files
179    /// `tests` reach.
180    pub fn unknown_loaders(&self, tests: &[String]) -> BTreeSet<String> {
181        let mut found = BTreeSet::new();
182        let mut seen: HashSet<&str> = HashSet::new();
183        let mut stack: Vec<&str> = tests.iter().map(String::as_str).collect();
184        while let Some(current) = stack.pop() {
185            if !seen.insert(current) || self.in_global_folder(current) {
186                continue;
187            }
188            if self.project.loads_unknown(current) {
189                found.insert(current.to_string());
190            }
191            if let Some(uses) = self.project.forward.get(current) {
192                stack.extend(uses.iter().map(String::as_str));
193            }
194        }
195        found
196    }
197
198    fn in_global_folder(&self, file: &str) -> bool {
199        self.global_folders
200            .iter()
201            .any(|(folder, _)| file.starts_with(folder.as_str()))
202    }
203}
204
205/// The `res://` paths a script names in `extends`, `preload` and `load`.
206/// Kept for callers of the first version; [`parse_script`] reads more.
207pub fn parse_file_deps(source: &[u8]) -> Vec<String> {
208    let Ok(text) = std::str::from_utf8(source) else {
209        return Vec::new();
210    };
211    parse_script(text, "res://")
212        .paths
213        .into_iter()
214        .filter(|p| p.starts_with("res://"))
215        .collect()
216}
217
218/// Forward and reverse graphs of the project. See [`Graph::build`].
219pub fn build_dep_graph(project_abs: &Path) -> (DepGraph, DepGraph) {
220    let graph = Graph::build(project_abs);
221    (graph.project.forward, graph.project.reverse)
222}
223
224/// Every file that uses one of `changed`, directly or not, without the
225/// changed files themselves.
226pub fn affected_files(changed: &HashSet<String>, reverse: &DepGraph) -> HashSet<String> {
227    let mut reached: HashSet<String> = HashSet::new();
228    let mut frontier: Vec<&String> = changed.iter().collect();
229    while let Some(file) = frontier.pop() {
230        for user in reverse.get(file).into_iter().flatten() {
231            if reached.insert(user.clone()) {
232                frontier.push(user);
233            }
234        }
235    }
236    reached.retain(|f| !changed.contains(f));
237    reached
238}
239
240#[cfg(test)]
241mod tests {
242    use super::*;
243
244    fn project(files: &[(&str, &str)]) -> tempfile_dir::Dir {
245        let dir = tempfile_dir::Dir::new();
246        for (path, text) in files {
247            let full = dir.path().join(path);
248            std::fs::create_dir_all(full.parent().unwrap()).unwrap();
249            std::fs::write(full, text).unwrap();
250        }
251        dir
252    }
253
254    fn files(impact: Impact) -> Vec<String> {
255        match impact {
256            Impact::Files(files) => files.into_iter().collect(),
257            Impact::All { reason } => panic!("expected some files, got all: {reason}"),
258        }
259    }
260
261    fn s(paths: &[&str]) -> Vec<String> {
262        paths.iter().map(|p| p.to_string()).collect()
263    }
264
265    #[test]
266    fn parses_preload_and_extends() {
267        let src = br#"extends "res://src/base.gd"
268const Util = preload("res://src/util.gd")
269var x = load("res://data/config.gd")
270"#;
271        let deps = parse_file_deps(src);
272        assert!(deps.contains(&"res://src/base.gd".to_string()), "extends");
273        assert!(deps.contains(&"res://src/util.gd".to_string()), "preload");
274        assert!(deps.contains(&"res://data/config.gd".to_string()), "load");
275    }
276
277    #[test]
278    fn skips_comments_and_non_res() {
279        let src = br#"# preload("res://commented.gd")
280load("user://settings.cfg")
281preload("res://valid.gd")
282"#;
283        let deps = parse_file_deps(src);
284        assert_eq!(deps, vec!["res://valid.gd".to_string()]);
285    }
286
287    #[test]
288    fn affected_files_transitive() {
289        let mut reverse: DepGraph = HashMap::new();
290        reverse.insert("res://a.gd".to_string(), ["res://b.gd".to_string()].into());
291        reverse.insert("res://b.gd".to_string(), ["res://c.gd".to_string()].into());
292
293        let changed: HashSet<String> = ["res://a.gd".to_string()].into();
294        let affected = affected_files(&changed, &reverse);
295        assert!(affected.contains("res://b.gd"), "direct dependent");
296        assert!(affected.contains("res://c.gd"), "transitive dependent");
297        assert!(
298            !affected.contains("res://a.gd"),
299            "changed file itself not in affected"
300        );
301    }
302
303    #[test]
304    fn follows_class_names_scenes_and_uids() {
305        let dir = project(&[
306            ("project.godot", "[application]\n"),
307            ("src/gold.gd", "class_name Gold\nvar amount := 0\n"),
308            ("src/shop.gd", "class_name Shop\nvar gold := Gold.new()\n"),
309            ("src/enemy.gd", "extends Node\n"),
310            ("src/enemy.gd.uid", "uid://enemy123\n"),
311            (
312                "scenes/enemy.tscn",
313                "[gd_scene format=3 uid=\"uid://scene1\"]\n\n[ext_resource type=\"Script\" uid=\"uid://enemy123\" id=\"1\"]\n",
314            ),
315            ("src/unrelated.gd", "class_name Unrelated\n"),
316            (
317                "test/test_shop.gd",
318                "extends GdtTest\nfunc test_buy():\n    Shop.new()\n",
319            ),
320            (
321                "test/test_enemy.gd",
322                "extends GdtTest\nconst S = preload(\"uid://scene1\")\nfunc test_spawn():\n    pass\n",
323            ),
324        ]);
325        let graph = Graph::build(dir.path());
326        let tests = s(&["res://test/test_shop.gd", "res://test/test_enemy.gd"]);
327
328        let gold = graph.impact(&s(&["res://src/gold.gd"]), &tests);
329        assert_eq!(files(gold), s(&["res://test/test_shop.gd"]));
330
331        let enemy = graph.impact(&s(&["res://src/enemy.gd"]), &tests);
332        assert_eq!(files(enemy), s(&["res://test/test_enemy.gd"]));
333
334        let unrelated = graph.impact(&s(&["res://src/unrelated.gd"]), &tests);
335        assert!(files(unrelated).is_empty());
336
337        let itself = graph.impact(&s(&["res://test/test_shop.gd"]), &tests);
338        assert_eq!(files(itself), s(&["res://test/test_shop.gd"]));
339    }
340
341    #[test]
342    fn project_settings_and_autoloads_affect_every_test() {
343        let dir = project(&[
344            (
345                "project.godot",
346                "[application]\n\n[autoload]\n\nClock=\"*res://core/clock.gd\"\n",
347            ),
348            ("core/clock.gd", "extends Node\nvar time := 0\n"),
349            ("src/timer.gd", "func now():\n    return Clock.time\n"),
350            ("test/test_a.gd", "extends GdtTest\n"),
351        ]);
352        let graph = Graph::build(dir.path());
353        let tests = s(&["res://test/test_a.gd"]);
354        assert!(matches!(
355            graph.impact(&s(&["res://project.godot"]), &tests),
356            Impact::All { .. }
357        ));
358        assert!(matches!(
359            graph.impact(&s(&["res://core/clock.gd"]), &tests),
360            Impact::All { .. }
361        ));
362        // A script that uses the autoload by name depends on it.
363        assert!(graph.project.forward["res://src/timer.gd"].contains("res://core/clock.gd"));
364    }
365
366    #[test]
367    fn unknown_and_folder_loads() {
368        let dir = project(&[
369            ("project.godot", ""),
370            (
371                "items/sword.tres",
372                "[gd_resource type=\"Resource\" format=3]\n",
373            ),
374            (
375                "src/items.gd",
376                "class_name Items\nfunc get(id):\n    return load(\"res://items/\" + id)\n",
377            ),
378            (
379                "src/loader.gd",
380                "class_name Loader\nfunc get(path):\n    return load(path)\n",
381            ),
382            ("src/other.gd", "class_name Other\n"),
383            (
384                "test/test_items.gd",
385                "extends GdtTest\nfunc test_a():\n    Items.new()\n",
386            ),
387            (
388                "test/test_loader.gd",
389                "extends GdtTest\nfunc test_b():\n    Loader.new()\n",
390            ),
391            ("test/test_plain.gd", "extends GdtTest\n"),
392        ]);
393        let graph = Graph::build(dir.path());
394        let tests = s(&[
395            "res://test/test_items.gd",
396            "res://test/test_loader.gd",
397            "res://test/test_plain.gd",
398        ]);
399        // A file in the folder Items loads from affects its tests; the
400        // tests of a script that loads unknown paths run on any change.
401        let sword = graph.impact(&s(&["res://items/sword.tres"]), &tests);
402        assert_eq!(
403            files(sword),
404            s(&["res://test/test_items.gd", "res://test/test_loader.gd"])
405        );
406        let other = graph.impact(&s(&["res://src/other.gd"]), &tests);
407        assert_eq!(files(other), s(&["res://test/test_loader.gd"]));
408    }
409
410    #[test]
411    fn a_directive_says_where_computed_loads_come_from() {
412        let dir = project(&[
413            ("project.godot", ""),
414            (
415                "actors/minion.tscn",
416                "[gd_scene format=3]\n\n[ext_resource type=\"Script\" path=\"res://combat/hit.gd\" id=\"1\"]\n",
417            ),
418            ("combat/hit.gd", "extends Node\n"),
419            ("ui/menu.gd", "class_name Menu\n"),
420            (
421                "net/restore.gd",
422                "class_name Restore\n# gdtest: loads res://actors/\nfunc f(path):\n    return load(path)\n",
423            ),
424            (
425                "test/test_restore.gd",
426                "extends GdtTest\nfunc test_a():\n    Restore.new()\n",
427            ),
428        ]);
429        let graph = Graph::build(dir.path());
430        let tests = s(&["res://test/test_restore.gd"]);
431        // Through the scene it may load, it uses that scene's script.
432        let hit = graph.impact(&s(&["res://combat/hit.gd"]), &tests);
433        assert_eq!(files(hit), tests);
434        let menu = graph.impact(&s(&["res://ui/menu.gd"]), &tests);
435        assert!(files(menu).is_empty());
436        assert!(in_folder("res://actors/a/b.tscn", "res://actors/*.tscn"));
437        assert!(!in_folder("res://actors/a/b.gd", "res://actors/*.tscn"));
438    }
439
440    #[test]
441    fn what_a_test_was_seen_using_counts() {
442        let dir = project(&[
443            ("project.godot", ""),
444            (
445                "actors/minion.tscn",
446                "[gd_scene format=3]\n\n[ext_resource type=\"Script\" path=\"res://actors/minion.gd\" id=\"1\"]\n",
447            ),
448            ("actors/minion.gd", "extends Node\n"),
449            ("actors/tower.gd", "extends Node\n"),
450            (
451                "net/restore.gd",
452                "class_name Restore\nfunc f(path):\n    return load(path)\n",
453            ),
454            (
455                "test/test_restore.gd",
456                "extends GdtTest\nfunc test_a():\n    Restore.new()\n",
457            ),
458        ]);
459        let tests = s(&["res://test/test_restore.gd"]);
460        // Never run: it may load anything, so any change runs it.
461        let graph = Graph::build(dir.path());
462        assert_eq!(
463            files(graph.impact(&s(&["res://actors/tower.gd"]), &tests)),
464            tests
465        );
466
467        let seen: HashMap<String, BTreeSet<String>> = [(
468            "res://test/test_restore.gd".to_string(),
469            ["res://actors/minion.tscn".to_string()].into(),
470        )]
471        .into();
472        record_uses(dir.path(), &seen).unwrap();
473        let graph = Graph::build(dir.path());
474        // Seen loading the minion scene: the scene and its script affect it.
475        assert_eq!(
476            files(graph.impact(&s(&["res://actors/minion.gd"]), &tests)),
477            tests
478        );
479        assert_eq!(
480            files(graph.impact(&s(&["res://actors/minion.tscn"]), &tests)),
481            tests
482        );
483        assert!(files(graph.impact(&s(&["res://actors/tower.gd"]), &tests)).is_empty());
484        // Its own source still counts.
485        assert_eq!(
486            files(graph.impact(&s(&["res://net/restore.gd"]), &tests)),
487            tests
488        );
489    }
490
491    #[test]
492    fn the_gdtest_addon_affects_every_test() {
493        let dir = project(&[
494            ("project.godot", ""),
495            ("test/test_a.gd", "extends GdtTest\n"),
496        ]);
497        let graph = Graph::build(dir.path());
498        assert!(matches!(
499            graph.impact(
500                &s(&["res://addons/gdtest/gdt.gd"]),
501                &s(&["res://test/test_a.gd"])
502            ),
503            Impact::All { .. }
504        ));
505    }
506
507    /// A temporary folder, removed when dropped. The crate has no tempfile
508    /// dependency, and the tests need little.
509    mod tempfile_dir {
510        use std::path::{Path, PathBuf};
511        use std::sync::atomic::{AtomicUsize, Ordering};
512
513        static NEXT: AtomicUsize = AtomicUsize::new(0);
514
515        pub struct Dir(PathBuf);
516
517        impl Dir {
518            pub fn new() -> Dir {
519                let n = NEXT.fetch_add(1, Ordering::SeqCst);
520                let path =
521                    std::env::temp_dir().join(format!("gdtest-deps-{}-{}", std::process::id(), n));
522                let _ = std::fs::remove_dir_all(&path);
523                std::fs::create_dir_all(&path).unwrap();
524                Dir(path)
525            }
526
527            pub fn path(&self) -> &Path {
528                &self.0
529            }
530        }
531
532        impl Drop for Dir {
533            fn drop(&mut self) {
534                let _ = std::fs::remove_dir_all(&self.0);
535            }
536        }
537    }
538}