Skip to main content

gdtest_analysis/
deps.rs

1//! Test impact analysis: which test files a change can affect.
2//!
3//! The graph links every file of the project to the files it uses, as far as
4//! they can be read from the source:
5//!
6//! - in a script: `extends`, `preload`/`load` and any other `"res://…"` or
7//!   `"uid://…"` string, the `class_name` of another script used by name, and
8//!   an autoload used by name;
9//! - in a scene or text resource (`.tscn`, `.tres`): its `ext_resource`s.
10//!
11//! A test file is affected by a change when it reaches a changed file through
12//! these links. What the source cannot tell is handled cautiously:
13//!
14//! - a script that loads a computed path (`load(path)`) may load any file, so
15//!   the tests that reach it always run; with a known folder
16//!   (`load("res://items/" + id)`), it depends on every file of that folder;
17//! - `project.godot`, the autoloads and the test runner's own files change
18//!   what every test runs with, so a change to one of them affects every test.
19//!
20//! What the tests did when they last ran adds to that, as Vitest learns a
21//! test's dynamic imports by running it: the worker reports the scenes and
22//! scripts of the nodes each test added to the tree, and [`record_uses`]
23//! keeps them per test file. A test file uses what it was seen to use, and
24//! once seen, a computed `load()` it reaches no longer makes it run on every
25//! change.
26
27use std::collections::{BTreeSet, HashMap, HashSet};
28use std::path::Path;
29
30use gdsyntax::SyntaxKind;
31use walkdir::WalkDir;
32
33/// Maps res:// path → set of res:// paths.
34pub type DepGraph = HashMap<String, HashSet<String>>;
35
36/// What one file uses, read from its source.
37#[derive(Debug, Default, Clone, PartialEq, Eq)]
38pub struct FileDeps {
39    /// `res://` paths, and `uid://` ids still to resolve.
40    pub paths: BTreeSet<String>,
41    /// Names that may be a `class_name` or an autoload.
42    pub names: BTreeSet<String>,
43    /// Folders it loads computed paths from: `res://items/`.
44    pub folders: BTreeSet<String>,
45    /// It loads a path the source does not tell.
46    pub loads_unknown: bool,
47    /// The `class_name` it declares.
48    pub class_name: Option<String>,
49}
50
51/// Which test files a change affects.
52#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum Impact {
54    /// Every test: `reason` says why.
55    All { reason: String },
56    /// These test files, and no other.
57    Files(BTreeSet<String>),
58}
59
60/// The project's dependency graph.
61#[derive(Debug, Default)]
62pub struct Graph {
63    /// `forward[a]`: the files `a` uses.
64    pub forward: DepGraph,
65    /// `reverse[b]`: the files that use `b`.
66    pub reverse: DepGraph,
67    /// file → folders it loads computed paths from.
68    folders: HashMap<String, BTreeSet<String>>,
69    /// Files that load paths the source does not tell.
70    unknown: HashSet<String>,
71    /// Files whose change affects every test, with the reason.
72    global: HashMap<String, String>,
73    /// Folders whose files affect every test (the test runner's addon).
74    global_folders: Vec<(String, String)>,
75    /// Test files seen running, with what they used: see [`record_uses`].
76    seen: HashSet<String>,
77}
78
79/// Where gdtest keeps what each test file used when it last ran.
80pub fn uses_path(project_abs: &Path) -> std::path::PathBuf {
81    project_abs.join(".godot").join("gdtest").join("uses.json")
82}
83
84/// What each test file was seen to use: test file → res:// paths.
85pub fn read_uses(project_abs: &Path) -> HashMap<String, BTreeSet<String>> {
86    std::fs::read_to_string(uses_path(project_abs))
87        .ok()
88        .and_then(|text| serde_json::from_str(&text).ok())
89        .unwrap_or_default()
90}
91
92/// Adds what the test files of a run used to what was seen before. Kept
93/// across runs, so a test that loads different scenes on different runs
94/// depends on all of them.
95pub fn record_uses(
96    project_abs: &Path,
97    uses: &HashMap<String, BTreeSet<String>>,
98) -> anyhow::Result<()> {
99    let mut all = read_uses(project_abs);
100    for (file, paths) in uses {
101        all.entry(file.clone())
102            .or_default()
103            .extend(paths.iter().cloned());
104    }
105    let path = uses_path(project_abs);
106    if let Some(parent) = path.parent() {
107        std::fs::create_dir_all(parent)?;
108    }
109    let sorted: std::collections::BTreeMap<_, _> = all.into_iter().collect();
110    std::fs::write(&path, serde_json::to_string_pretty(&sorted)?)?;
111    Ok(())
112}
113
114impl Graph {
115    /// Reads the project's scripts, scenes and resources.
116    pub fn build(project_abs: &Path) -> Graph {
117        let mut sources: HashMap<String, FileDeps> = HashMap::new();
118        let mut uids: HashMap<String, String> = HashMap::new();
119
120        let walker = WalkDir::new(project_abs)
121            .follow_links(false)
122            .into_iter()
123            .filter_entry(|e| e.depth() == 0 || !e.file_name().to_string_lossy().starts_with('.'));
124        for entry in walker.flatten() {
125            if !entry.file_type().is_file() {
126                continue;
127            }
128            let path = entry.path();
129            let Ok(rel) = path.strip_prefix(project_abs) else {
130                continue;
131            };
132            let res = format!("res://{}", rel.to_string_lossy().replace('\\', "/"));
133            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
134            match ext {
135                "gd" => {
136                    if let Ok(text) = std::fs::read_to_string(path) {
137                        sources.insert(res.clone(), parse_script(&text, &res));
138                    }
139                }
140                "tscn" | "tres" => {
141                    if let Ok(text) = std::fs::read_to_string(path) {
142                        if let Some(uid) = header_uid(&text) {
143                            uids.insert(uid, res.clone());
144                        }
145                        sources.insert(res.clone(), parse_text_resource(&text));
146                    }
147                }
148                // `a.gd.uid` holds the uid of `a.gd`.
149                "uid" => {
150                    if let Ok(text) = std::fs::read_to_string(path) {
151                        let uid = text.trim();
152                        if uid.starts_with("uid://") {
153                            uids.insert(uid.to_string(), res.trim_end_matches(".uid").to_string());
154                        }
155                    }
156                }
157                // `icon.png.import` holds the uid of `icon.png`.
158                "import" => {
159                    if let Ok(text) = std::fs::read_to_string(path)
160                        && let Some(uid) = header_uid(&text)
161                    {
162                        uids.insert(uid, res.trim_end_matches(".import").to_string());
163                    }
164                }
165                _ => {}
166            }
167        }
168
169        let mut graph = Graph::default();
170        for (test, paths) in read_uses(project_abs) {
171            graph.seen.insert(test.clone());
172            for path in paths {
173                if path != test {
174                    graph
175                        .reverse
176                        .entry(path.clone())
177                        .or_default()
178                        .insert(test.clone());
179                    graph.forward.entry(test.clone()).or_default().insert(path);
180                }
181            }
182        }
183        let autoloads = read_autoloads(project_abs);
184        graph.global.insert(
185            "res://project.godot".to_string(),
186            "project.godot changed".to_string(),
187        );
188        for config in ["res://gdtest.toml", "res://.gdtest.toml"] {
189            graph
190                .global
191                .insert(config.to_string(), format!("{} changed", &config[6..]));
192        }
193        graph.global_folders.push((
194            "res://addons/gdtest/".to_string(),
195            "the gdtest addon changed".to_string(),
196        ));
197        for (name, path) in &autoloads {
198            graph
199                .global
200                .insert(path.clone(), format!("the autoload {name} changed"));
201        }
202
203        let classes: HashMap<&str, &str> = sources
204            .iter()
205            .filter_map(|(file, deps)| deps.class_name.as_deref().map(|c| (c, file.as_str())))
206            .collect();
207
208        for (file, deps) in &sources {
209            let mut uses: HashSet<String> = HashSet::new();
210            for path in &deps.paths {
211                if let Some(target) = uids.get(path) {
212                    uses.insert(target.clone());
213                } else if path.starts_with("res://") {
214                    uses.insert(path.clone());
215                }
216            }
217            // A folder it loads from: it may load any file there.
218            for folder in &deps.folders {
219                uses.extend(sources.keys().filter(|f| in_folder(f, folder)).cloned());
220            }
221            for name in &deps.names {
222                if let Some(target) = classes.get(name.as_str()) {
223                    uses.insert((*target).to_string());
224                }
225                if let Some(target) = autoloads.get(name) {
226                    uses.insert(target.clone());
227                }
228            }
229            uses.remove(file);
230            for used in &uses {
231                graph
232                    .reverse
233                    .entry(used.clone())
234                    .or_default()
235                    .insert(file.clone());
236            }
237            graph.forward.entry(file.clone()).or_default().extend(uses);
238            if !deps.folders.is_empty() {
239                graph.folders.insert(file.clone(), deps.folders.clone());
240            }
241            if deps.loads_unknown {
242                graph.unknown.insert(file.clone());
243            }
244        }
245        graph
246    }
247
248    /// The test files among `tests` that a change to `changed` (res://
249    /// paths) affects.
250    pub fn impact(&self, changed: &[String], tests: &[String]) -> Impact {
251        for file in changed {
252            if let Some(reason) = self.global.get(file) {
253                return Impact::All {
254                    reason: reason.clone(),
255                };
256            }
257            for (folder, reason) in &self.global_folders {
258                if file.starts_with(folder.as_str()) {
259                    return Impact::All {
260                        reason: reason.clone(),
261                    };
262                }
263            }
264        }
265
266        // The changed files, and the files that load from their folders.
267        let mut start: HashSet<String> = changed.iter().cloned().collect();
268        for (file, folders) in &self.folders {
269            if changed
270                .iter()
271                .any(|c| folders.iter().any(|f| in_folder(c, f)))
272            {
273                start.insert(file.clone());
274            }
275        }
276        let reached = dependents(&start, &self.reverse);
277
278        let mut affected = BTreeSet::new();
279        for test in tests {
280            if start.contains(test) || reached.contains(test) || self.loads_unknown(test) {
281                affected.insert(test.clone());
282            }
283        }
284        Impact::Files(affected)
285    }
286
287    /// Whether `file`, or a file it uses, loads a path the source does not
288    /// tell: then any change may affect it.
289    pub fn loads_unknown(&self, file: &str) -> bool {
290        // What it loads was seen when it ran.
291        if self.unknown.is_empty() || self.seen.contains(file) {
292            return false;
293        }
294        let mut seen: HashSet<&str> = HashSet::new();
295        let mut stack = vec![file];
296        while let Some(current) = stack.pop() {
297            if !seen.insert(current) {
298                continue;
299            }
300            // The test runner loads whatever it runs; a change to it
301            // already affects every test.
302            if self
303                .global_folders
304                .iter()
305                .any(|(folder, _)| current.starts_with(folder.as_str()))
306            {
307                continue;
308            }
309            if self.unknown.contains(current) {
310                return true;
311            }
312            if let Some(uses) = self.forward.get(current) {
313                stack.extend(uses.iter().map(String::as_str));
314            }
315        }
316        false
317    }
318
319    /// The files that load paths the source does not tell, among the files
320    /// `tests` reach.
321    pub fn unknown_loaders(&self, tests: &[String]) -> BTreeSet<String> {
322        let mut found = BTreeSet::new();
323        let mut seen: HashSet<&str> = HashSet::new();
324        let mut stack: Vec<&str> = tests.iter().map(String::as_str).collect();
325        while let Some(current) = stack.pop() {
326            if !seen.insert(current)
327                || self
328                    .global_folders
329                    .iter()
330                    .any(|(folder, _)| current.starts_with(folder.as_str()))
331            {
332                continue;
333            }
334            if self.unknown.contains(current) {
335                found.insert(current.to_string());
336            }
337            if let Some(uses) = self.forward.get(current) {
338                stack.extend(uses.iter().map(String::as_str));
339            }
340        }
341        found
342    }
343}
344
345/// Whether `file` is in `folder`: `res://actors/`, or `res://actors/*.tscn`
346/// for the scenes of that folder and the folders in it.
347fn in_folder(file: &str, folder: &str) -> bool {
348    match folder.rsplit_once("/*") {
349        Some((dir, suffix)) => file.starts_with(dir) && file.ends_with(suffix),
350        None => file.starts_with(folder),
351    }
352}
353
354/// Every file that uses one of `start`, directly or through other files.
355fn dependents(start: &HashSet<String>, reverse: &DepGraph) -> HashSet<String> {
356    let mut reached: HashSet<String> = HashSet::new();
357    let mut frontier: Vec<&String> = start.iter().collect();
358    while let Some(file) = frontier.pop() {
359        if let Some(users) = reverse.get(file) {
360            for user in users {
361                if reached.insert(user.clone()) {
362                    frontier.push(user);
363                }
364            }
365        }
366    }
367    reached
368}
369
370/// Functions whose first argument is a resource to load. Like Vitest, which
371/// follows imports and not `fs.readFile`, files opened with FileAccess or
372/// DirAccess are not followed, unless a `"res://…"` string names them: they
373/// are mostly saves, replays and logs, read and written while running.
374const LOADERS: &[&str] = &["load", "load_threaded_request", "change_scene_to_file"];
375
376/// `# gdtest: loads res://actors/`: a script that loads computed paths says
377/// where from, so that it depends on that folder instead of on everything.
378/// `res://actors/*.tscn` narrows it to the scenes of that folder.
379const LOADS_DIRECTIVE: &str = "gdtest: loads ";
380
381/// Reads what a script uses.
382pub fn parse_script(text: &str, res: &str) -> FileDeps {
383    let lexed = gdsyntax::lexer::tokenize(text);
384    let mut tokens: Vec<(SyntaxKind, &str)> = Vec::new();
385    let mut declared_folders: BTreeSet<String> = BTreeSet::new();
386    let mut offset = 0usize;
387    for token in &lexed.tokens {
388        let end = offset + token.len as usize;
389        let token_text = &text[offset..end];
390        if !token.kind.is_trivia() {
391            tokens.push((token.kind, token_text));
392        } else if token.kind == SyntaxKind::COMMENT
393            && let Some(at) = token_text.find(LOADS_DIRECTIVE)
394        {
395            for folder in token_text[at + LOADS_DIRECTIVE.len()..].split([' ', ',']) {
396                if folder.starts_with("res://") {
397                    declared_folders.insert(folder.to_string());
398                }
399            }
400        }
401        offset = end;
402    }
403
404    let dir = res.rsplit_once('/').map(|(d, _)| d).unwrap_or("res:/");
405    let constants = literal_names(&tokens);
406    let mut deps = FileDeps::default();
407    for (i, &(kind, token_text)) in tokens.iter().enumerate() {
408        match kind {
409            SyntaxKind::STRING => {
410                if let Some(value) = gdsyntax::literal::string_value(token_text)
411                    && (value.starts_with("res://") || value.starts_with("uid://"))
412                {
413                    deps.paths.insert(value);
414                }
415            }
416            SyntaxKind::IDENTIFIER => {
417                deps.names.insert(token_text.to_string());
418            }
419            SyntaxKind::CLASS_NAME_KW => {
420                if let Some(&(SyntaxKind::IDENTIFIER, name)) = tokens.get(i + 1) {
421                    deps.class_name = Some(name.to_string());
422                }
423            }
424            _ => {}
425        }
426        // A call that loads a path: `preload(...)`, `load(...)`,
427        // `ResourceLoader.load(...)`, `FileAccess.open(...)`.
428        let is_loader = match kind {
429            SyntaxKind::PRELOAD_KW => true,
430            SyntaxKind::IDENTIFIER => LOADERS.contains(&token_text) && is_loader_call(&tokens, i),
431            _ => false,
432        };
433        if is_loader && matches!(tokens.get(i + 1), Some((SyntaxKind::PARENTHESIS_OPEN, _))) {
434            read_load_argument(&tokens, i + 2, dir, &constants, &mut deps);
435        }
436    }
437    if !declared_folders.is_empty() {
438        deps.loads_unknown = false;
439        deps.folders.extend(declared_folders);
440    }
441    // `extends "a.gd"` is relative to the script.
442    for (i, &(kind, _)) in tokens.iter().enumerate() {
443        if kind == SyntaxKind::EXTENDS_KW
444            && let Some(&(SyntaxKind::STRING, text)) = tokens.get(i + 1)
445            && let Some(value) = gdsyntax::literal::string_value(text)
446            && !value.contains("://")
447        {
448            deps.paths.insert(join_relative(dir, &value));
449        }
450    }
451    deps
452}
453
454/// Whether the loader name at `i` is a call this analysis follows: `load`
455/// on its own or on ResourceLoader, `open` on FileAccess or DirAccess, and
456/// the other names on anything. `config.load(path)` is not one: it reads a
457/// ConfigFile, usually from `user://`.
458fn is_loader_call(tokens: &[(SyntaxKind, &str)], i: usize) -> bool {
459    let name = tokens[i].1;
460    let receiver = if i >= 2 && tokens[i - 1].0 == SyntaxKind::PERIOD {
461        Some(tokens[i - 2].1)
462    } else {
463        None
464    };
465    match name {
466        "load" | "load_threaded_request" => matches!(receiver, None | Some("ResourceLoader")),
467        _ => true,
468    }
469}
470
471/// Names given a string literal once, and never assigned again:
472/// `const PATH := "res://a.json"`, `var path = "user://save"`.
473fn literal_names(tokens: &[(SyntaxKind, &str)]) -> HashMap<String, String> {
474    let mut values: HashMap<String, String> = HashMap::new();
475    let mut assigned: HashMap<&str, usize> = HashMap::new();
476    for (i, &(kind, text)) in tokens.iter().enumerate() {
477        let assigns = matches!(tokens.get(i + 1).map(|t| t.1), Some("=") | Some("+="));
478        let declared =
479            i > 0 && matches!(tokens[i - 1].0, SyntaxKind::CONST_KW | SyntaxKind::VAR_KW);
480        if kind == SyntaxKind::IDENTIFIER && assigns && !declared {
481            *assigned.entry(text).or_default() += 1;
482        }
483        let declares = matches!(kind, SyntaxKind::CONST_KW | SyntaxKind::VAR_KW);
484        if !declares {
485            continue;
486        }
487        let Some(&(SyntaxKind::IDENTIFIER, name)) = tokens.get(i + 1) else {
488            continue;
489        };
490        // `const A = "..."`, `const A := "..."`, `const A: String = "..."`.
491        let mut at = i + 2;
492        if tokens.get(at).map(|t| t.1) == Some(":") {
493            at += 1;
494            if tokens.get(at).map(|t| t.1) != Some("=") {
495                at += 1;
496            }
497        }
498        if tokens.get(at).map(|t| t.1) != Some("=") {
499            continue;
500        }
501        if let Some(&(SyntaxKind::STRING, literal)) = tokens.get(at + 1)
502            && matches!(
503                tokens.get(at + 2).map(|t| t.0),
504                Some(SyntaxKind::NEWLINE) | None
505            )
506            && let Some(value) = gdsyntax::literal::string_value(literal)
507        {
508            values.insert(name.to_string(), value);
509        }
510    }
511    // A name assigned again later may hold anything.
512    values.retain(|name, _| !assigned.contains_key(name.as_str()));
513    values
514}
515
516/// Reads the path a loader call gets, from the token at `at`.
517fn read_load_argument(
518    tokens: &[(SyntaxKind, &str)],
519    at: usize,
520    dir: &str,
521    constants: &HashMap<String, String>,
522    deps: &mut FileDeps,
523) {
524    let Some(&(kind, text)) = tokens.get(at) else {
525        return;
526    };
527    let next = tokens.get(at + 1).map(|t| t.0);
528    // `FileAccess.open(path, FileAccess.WRITE)` writes: it reads nothing.
529    if next == Some(SyntaxKind::COMMA) && matches!(tokens.get(at + 4).map(|t| t.1), Some("WRITE")) {
530        return;
531    }
532    let literal = match kind {
533        SyntaxKind::STRING => gdsyntax::literal::string_value(text),
534        SyntaxKind::IDENTIFIER => constants.get(text).cloned(),
535        _ => None,
536    };
537    if let Some(value) = literal {
538        if value.starts_with("user://") {
539            return;
540        }
541        let path = if value.contains("://") {
542            value
543        } else {
544            join_relative(dir, &value)
545        };
546        match next {
547            Some(SyntaxKind::PARENTHESIS_CLOSE) | Some(SyntaxKind::COMMA) => {
548                deps.paths.insert(path);
549            }
550            // `"res://items/" + id` or `"res://items/%s.tres" % id`.
551            _ if path.starts_with("res://") => {
552                let folder = match path.rfind('/') {
553                    Some(slash) if slash >= "res://".len() => &path[..=slash],
554                    _ => "res://",
555                };
556                deps.folders.insert(folder.to_string());
557            }
558            _ => deps.loads_unknown = true,
559        }
560        return;
561    }
562    deps.loads_unknown = true;
563}
564
565/// `res://a/b` and `../c.gd` give `res://a/c.gd`.
566fn join_relative(dir: &str, relative: &str) -> String {
567    let mut parts: Vec<&str> = dir.trim_start_matches("res://").split('/').collect();
568    parts.retain(|p| !p.is_empty());
569    for part in relative.split('/') {
570        match part {
571            "" | "." => {}
572            ".." => {
573                parts.pop();
574            }
575            _ => parts.push(part),
576        }
577    }
578    format!("res://{}", parts.join("/"))
579}
580
581/// Reads what a scene or text resource uses: its `ext_resource`s.
582pub fn parse_text_resource(text: &str) -> FileDeps {
583    let mut deps = FileDeps::default();
584    for line in text.lines() {
585        let line = line.trim_start();
586        if !line.starts_with("[ext_resource") {
587            continue;
588        }
589        if let Some(path) = attribute(line, "path") {
590            deps.paths.insert(path.to_string());
591        } else if let Some(uid) = attribute(line, "uid") {
592            deps.paths.insert(uid.to_string());
593        }
594    }
595    deps
596}
597
598/// The `uid="uid://…"` of a file's first `[…]` header line.
599fn header_uid(text: &str) -> Option<String> {
600    let header = text.lines().find(|l| l.trim_start().starts_with('['))?;
601    attribute(header, "uid")
602        .filter(|u| u.starts_with("uid://"))
603        .map(str::to_string)
604        .or_else(|| {
605            // An `.import` file has its uid on a line of its own.
606            text.lines()
607                .find_map(|l| l.trim().strip_prefix("uid=\""))
608                .and_then(|rest| rest.split('"').next())
609                .filter(|u| u.starts_with("uid://"))
610                .map(str::to_string)
611        })
612}
613
614/// The value of `name="…"` in a header line.
615fn attribute<'a>(line: &'a str, name: &str) -> Option<&'a str> {
616    let key = format!(" {name}=\"");
617    let start = line.find(&key)? + key.len();
618    let end = line[start..].find('"')? + start;
619    Some(&line[start..end])
620}
621
622/// The project's autoloads: name → res:// path.
623fn read_autoloads(project_abs: &Path) -> HashMap<String, String> {
624    let mut autoloads = HashMap::new();
625    let Ok(text) = std::fs::read_to_string(project_abs.join("project.godot")) else {
626        return autoloads;
627    };
628    let mut in_section = false;
629    for line in text.lines() {
630        let line = line.trim();
631        if line.starts_with('[') {
632            in_section = line == "[autoload]";
633            continue;
634        }
635        if !in_section {
636            continue;
637        }
638        if let Some((name, value)) = line.split_once('=') {
639            let path = value.trim().trim_matches('"').trim_start_matches('*');
640            if path.starts_with("res://") {
641                autoloads.insert(name.trim().to_string(), path.to_string());
642            }
643        }
644    }
645    autoloads
646}
647
648/// The `res://` paths a script names in `extends`, `preload` and `load`.
649/// Kept for callers of the first version; [`parse_script`] reads more.
650pub fn parse_file_deps(source: &[u8]) -> Vec<String> {
651    let Ok(text) = std::str::from_utf8(source) else {
652        return Vec::new();
653    };
654    parse_script(text, "res://")
655        .paths
656        .into_iter()
657        .filter(|p| p.starts_with("res://"))
658        .collect()
659}
660
661/// Forward and reverse graphs of the project. See [`Graph::build`].
662pub fn build_dep_graph(project_abs: &Path) -> (DepGraph, DepGraph) {
663    let graph = Graph::build(project_abs);
664    (graph.forward, graph.reverse)
665}
666
667/// Every file that uses one of `changed`, directly or not, without the
668/// changed files themselves.
669pub fn affected_files(changed: &HashSet<String>, reverse: &DepGraph) -> HashSet<String> {
670    let mut reached = dependents(changed, reverse);
671    reached.retain(|f| !changed.contains(f));
672    reached
673}
674
675#[cfg(test)]
676mod tests {
677    use super::*;
678
679    fn project(files: &[(&str, &str)]) -> tempfile_dir::Dir {
680        let dir = tempfile_dir::Dir::new();
681        for (path, text) in files {
682            let full = dir.path().join(path);
683            std::fs::create_dir_all(full.parent().unwrap()).unwrap();
684            std::fs::write(full, text).unwrap();
685        }
686        dir
687    }
688
689    fn files(impact: Impact) -> Vec<String> {
690        match impact {
691            Impact::Files(files) => files.into_iter().collect(),
692            Impact::All { reason } => panic!("expected some files, got all: {reason}"),
693        }
694    }
695
696    fn s(paths: &[&str]) -> Vec<String> {
697        paths.iter().map(|p| p.to_string()).collect()
698    }
699
700    #[test]
701    fn parses_preload_and_extends() {
702        let src = br#"extends "res://src/base.gd"
703const Util = preload("res://src/util.gd")
704var x = load("res://data/config.gd")
705"#;
706        let deps = parse_file_deps(src);
707        assert!(deps.contains(&"res://src/base.gd".to_string()), "extends");
708        assert!(deps.contains(&"res://src/util.gd".to_string()), "preload");
709        assert!(deps.contains(&"res://data/config.gd".to_string()), "load");
710    }
711
712    #[test]
713    fn skips_comments_and_non_res() {
714        let src = br#"# preload("res://commented.gd")
715load("user://settings.cfg")
716preload("res://valid.gd")
717"#;
718        let deps = parse_file_deps(src);
719        assert_eq!(deps, vec!["res://valid.gd".to_string()]);
720    }
721
722    #[test]
723    fn affected_files_transitive() {
724        let mut reverse: DepGraph = HashMap::new();
725        reverse.insert("res://a.gd".to_string(), ["res://b.gd".to_string()].into());
726        reverse.insert("res://b.gd".to_string(), ["res://c.gd".to_string()].into());
727
728        let changed: HashSet<String> = ["res://a.gd".to_string()].into();
729        let affected = affected_files(&changed, &reverse);
730        assert!(affected.contains("res://b.gd"), "direct dependent");
731        assert!(affected.contains("res://c.gd"), "transitive dependent");
732        assert!(
733            !affected.contains("res://a.gd"),
734            "changed file itself not in affected"
735        );
736    }
737
738    #[test]
739    fn reads_names_strings_and_loads() {
740        let deps = parse_script(
741            r#"class_name Player extends Actor
742const Sword = preload("weapons/sword.gd")
743var data = FileAccess.open("res://data/stats.json", FileAccess.READ)
744var save = FileAccess.open(save_path, FileAccess.READ)  # a save: not followed
745var cfg = ConfigFile.new()
746func _ready():
747    cfg.load(some_path)  # a ConfigFile: not followed
748    var item = load("res://items/%s.tres" % id)
749    var scene = "res://levels/one.tscn"
750    var any = load(path)
751"#,
752            "res://actors/player.gd",
753        );
754        assert_eq!(deps.class_name.as_deref(), Some("Player"));
755        assert!(deps.names.contains("Actor"));
756        assert!(deps.paths.contains("res://actors/weapons/sword.gd"));
757        assert!(deps.paths.contains("res://data/stats.json"));
758        assert!(deps.paths.contains("res://levels/one.tscn"));
759        assert!(deps.folders.contains("res://items/"));
760        assert!(deps.loads_unknown);
761    }
762
763    #[test]
764    fn constants_and_writes() {
765        let deps = parse_script(
766            "const DOC := \"res://docs/gate.tscn\"\nvar out = \"user://x.tres\"\nfunc f():\n    load(DOC)\n    load(out)\n",
767            "res://f.gd",
768        );
769        assert!(deps.paths.contains("res://docs/gate.tscn"));
770        assert!(!deps.loads_unknown);
771        let reassigned = parse_script(
772            "var p := \"res://a.tres\"\nfunc f():\n    p = other()\n    load(p)\n",
773            "res://f.gd",
774        );
775        assert!(reassigned.loads_unknown);
776    }
777
778    #[test]
779    fn a_literal_load_is_not_unknown() {
780        let deps = parse_script(
781            "func f():\n    var a = load(\"res://a.gd\")\n    var c = ConfigFile.new()\n    c.load(p)\n",
782            "res://f.gd",
783        );
784        assert!(!deps.loads_unknown);
785    }
786
787    #[test]
788    fn follows_class_names_scenes_and_uids() {
789        let dir = project(&[
790            ("project.godot", "[application]\n"),
791            ("src/gold.gd", "class_name Gold\nvar amount := 0\n"),
792            ("src/shop.gd", "class_name Shop\nvar gold := Gold.new()\n"),
793            ("src/enemy.gd", "extends Node\n"),
794            ("src/enemy.gd.uid", "uid://enemy123\n"),
795            (
796                "scenes/enemy.tscn",
797                "[gd_scene format=3 uid=\"uid://scene1\"]\n\n[ext_resource type=\"Script\" uid=\"uid://enemy123\" id=\"1\"]\n",
798            ),
799            ("src/unrelated.gd", "class_name Unrelated\n"),
800            (
801                "test/test_shop.gd",
802                "extends GdtTest\nfunc test_buy():\n    Shop.new()\n",
803            ),
804            (
805                "test/test_enemy.gd",
806                "extends GdtTest\nconst S = preload(\"uid://scene1\")\nfunc test_spawn():\n    pass\n",
807            ),
808        ]);
809        let graph = Graph::build(dir.path());
810        let tests = s(&["res://test/test_shop.gd", "res://test/test_enemy.gd"]);
811
812        let gold = graph.impact(&s(&["res://src/gold.gd"]), &tests);
813        assert_eq!(files(gold), s(&["res://test/test_shop.gd"]));
814
815        let enemy = graph.impact(&s(&["res://src/enemy.gd"]), &tests);
816        assert_eq!(files(enemy), s(&["res://test/test_enemy.gd"]));
817
818        let unrelated = graph.impact(&s(&["res://src/unrelated.gd"]), &tests);
819        assert!(files(unrelated).is_empty());
820
821        let itself = graph.impact(&s(&["res://test/test_shop.gd"]), &tests);
822        assert_eq!(files(itself), s(&["res://test/test_shop.gd"]));
823    }
824
825    #[test]
826    fn project_settings_and_autoloads_affect_every_test() {
827        let dir = project(&[
828            (
829                "project.godot",
830                "[application]\n\n[autoload]\n\nClock=\"*res://core/clock.gd\"\n",
831            ),
832            ("core/clock.gd", "extends Node\nvar time := 0\n"),
833            ("src/timer.gd", "func now():\n    return Clock.time\n"),
834            ("test/test_a.gd", "extends GdtTest\n"),
835        ]);
836        let graph = Graph::build(dir.path());
837        let tests = s(&["res://test/test_a.gd"]);
838        assert!(matches!(
839            graph.impact(&s(&["res://project.godot"]), &tests),
840            Impact::All { .. }
841        ));
842        assert!(matches!(
843            graph.impact(&s(&["res://core/clock.gd"]), &tests),
844            Impact::All { .. }
845        ));
846        // A script that uses the autoload by name depends on it.
847        assert!(graph.forward["res://src/timer.gd"].contains("res://core/clock.gd"));
848    }
849
850    #[test]
851    fn unknown_and_folder_loads() {
852        let dir = project(&[
853            ("project.godot", ""),
854            (
855                "items/sword.tres",
856                "[gd_resource type=\"Resource\" format=3]\n",
857            ),
858            (
859                "src/items.gd",
860                "class_name Items\nfunc get(id):\n    return load(\"res://items/\" + id)\n",
861            ),
862            (
863                "src/loader.gd",
864                "class_name Loader\nfunc get(path):\n    return load(path)\n",
865            ),
866            ("src/other.gd", "class_name Other\n"),
867            (
868                "test/test_items.gd",
869                "extends GdtTest\nfunc test_a():\n    Items.new()\n",
870            ),
871            (
872                "test/test_loader.gd",
873                "extends GdtTest\nfunc test_b():\n    Loader.new()\n",
874            ),
875            ("test/test_plain.gd", "extends GdtTest\n"),
876        ]);
877        let graph = Graph::build(dir.path());
878        let tests = s(&[
879            "res://test/test_items.gd",
880            "res://test/test_loader.gd",
881            "res://test/test_plain.gd",
882        ]);
883        // A file in the folder Items loads from affects its tests; the
884        // tests of a script that loads unknown paths run on any change.
885        let sword = graph.impact(&s(&["res://items/sword.tres"]), &tests);
886        assert_eq!(
887            files(sword),
888            s(&["res://test/test_items.gd", "res://test/test_loader.gd"])
889        );
890        let other = graph.impact(&s(&["res://src/other.gd"]), &tests);
891        assert_eq!(files(other), s(&["res://test/test_loader.gd"]));
892    }
893
894    #[test]
895    fn a_directive_says_where_computed_loads_come_from() {
896        let dir = project(&[
897            ("project.godot", ""),
898            (
899                "actors/minion.tscn",
900                "[gd_scene format=3]\n\n[ext_resource type=\"Script\" path=\"res://combat/hit.gd\" id=\"1\"]\n",
901            ),
902            ("combat/hit.gd", "extends Node\n"),
903            ("ui/menu.gd", "class_name Menu\n"),
904            (
905                "net/restore.gd",
906                "class_name Restore\n# gdtest: loads res://actors/\nfunc f(path):\n    return load(path)\n",
907            ),
908            (
909                "test/test_restore.gd",
910                "extends GdtTest\nfunc test_a():\n    Restore.new()\n",
911            ),
912        ]);
913        let graph = Graph::build(dir.path());
914        let tests = s(&["res://test/test_restore.gd"]);
915        // Through the scene it may load, it uses that scene's script.
916        let hit = graph.impact(&s(&["res://combat/hit.gd"]), &tests);
917        assert_eq!(files(hit), tests);
918        let menu = graph.impact(&s(&["res://ui/menu.gd"]), &tests);
919        assert!(files(menu).is_empty());
920        assert!(in_folder("res://actors/a/b.tscn", "res://actors/*.tscn"));
921        assert!(!in_folder("res://actors/a/b.gd", "res://actors/*.tscn"));
922    }
923
924    #[test]
925    fn what_a_test_was_seen_using_counts() {
926        let dir = project(&[
927            ("project.godot", ""),
928            (
929                "actors/minion.tscn",
930                "[gd_scene format=3]\n\n[ext_resource type=\"Script\" path=\"res://actors/minion.gd\" id=\"1\"]\n",
931            ),
932            ("actors/minion.gd", "extends Node\n"),
933            ("actors/tower.gd", "extends Node\n"),
934            (
935                "net/restore.gd",
936                "class_name Restore\nfunc f(path):\n    return load(path)\n",
937            ),
938            (
939                "test/test_restore.gd",
940                "extends GdtTest\nfunc test_a():\n    Restore.new()\n",
941            ),
942        ]);
943        let tests = s(&["res://test/test_restore.gd"]);
944        // Never run: it may load anything, so any change runs it.
945        let graph = Graph::build(dir.path());
946        assert_eq!(
947            files(graph.impact(&s(&["res://actors/tower.gd"]), &tests)),
948            tests
949        );
950
951        let seen: HashMap<String, BTreeSet<String>> = [(
952            "res://test/test_restore.gd".to_string(),
953            ["res://actors/minion.tscn".to_string()].into(),
954        )]
955        .into();
956        record_uses(dir.path(), &seen).unwrap();
957        let graph = Graph::build(dir.path());
958        // Seen loading the minion scene: the scene and its script affect it.
959        assert_eq!(
960            files(graph.impact(&s(&["res://actors/minion.gd"]), &tests)),
961            tests
962        );
963        assert_eq!(
964            files(graph.impact(&s(&["res://actors/minion.tscn"]), &tests)),
965            tests
966        );
967        assert!(files(graph.impact(&s(&["res://actors/tower.gd"]), &tests)).is_empty());
968        // Its own source still counts.
969        assert_eq!(
970            files(graph.impact(&s(&["res://net/restore.gd"]), &tests)),
971            tests
972        );
973    }
974
975    #[test]
976    fn the_gdtest_addon_affects_every_test() {
977        let dir = project(&[
978            ("project.godot", ""),
979            ("test/test_a.gd", "extends GdtTest\n"),
980        ]);
981        let graph = Graph::build(dir.path());
982        assert!(matches!(
983            graph.impact(
984                &s(&["res://addons/gdtest/gdt.gd"]),
985                &s(&["res://test/test_a.gd"])
986            ),
987            Impact::All { .. }
988        ));
989    }
990
991    /// A temporary folder, removed when dropped. The crate has no tempfile
992    /// dependency, and the tests need little.
993    mod tempfile_dir {
994        use std::path::{Path, PathBuf};
995        use std::sync::atomic::{AtomicUsize, Ordering};
996
997        static NEXT: AtomicUsize = AtomicUsize::new(0);
998
999        pub struct Dir(PathBuf);
1000
1001        impl Dir {
1002            pub fn new() -> Dir {
1003                let n = NEXT.fetch_add(1, Ordering::SeqCst);
1004                let path =
1005                    std::env::temp_dir().join(format!("gdtest-deps-{}-{}", std::process::id(), n));
1006                let _ = std::fs::remove_dir_all(&path);
1007                std::fs::create_dir_all(&path).unwrap();
1008                Dir(path)
1009            }
1010
1011            pub fn path(&self) -> &Path {
1012                &self.0
1013            }
1014        }
1015
1016        impl Drop for Dir {
1017            fn drop(&mut self) {
1018                let _ = std::fs::remove_dir_all(&self.0);
1019            }
1020        }
1021    }
1022}