Skip to main content

bynk_driver/
discovery.rs

1//! Walking a directory tree for `.bynk` files and reading them — the driver's
2//! side of `CompileOptions.sources` (#1077, R2.3/T0.7 residue).
3//!
4//! The real CLI entry points (`project_options`/`try_project_options` below)
5//! now walk and read every file up front, via this module, and hand the
6//! result to `CompileOptions::sources`.
7//!
8//! #1077 review: this module's own original doc claimed the CLI path was
9//! already fully independent of `bynk-emit`'s disk reads — false as written.
10//! `project_options`/`try_project_options` still read `bynk.toml` itself via
11//! `read_project_paths`/`try_read_project_paths`, which reach
12//! `discovery::read_source`'s overlay-miss fallback (`fs::read_to_string`)
13//! with an always-empty overlay — one real disk read inside `bynk-emit` on
14//! every real CLI invocation, unnoticed because `fs_below_driver` scans
15//! `bynk-emit`'s own text, not who calls into it. Both entry points now read
16//! `bynk.toml` themselves (`manifest_overlay`) and hand it to
17//! `try_read_project_paths_with`'s overlay instead, so that read genuinely
18//! moves above `bynk-emit` **when `bynk.toml` exists**. A conventional
19//! project with no manifest at all still reaches `try_read_project_paths_with`
20//! with an empty overlay, which still tries (and fails to find) `bynk.toml`
21//! via `read_source`'s own `fs::read_to_string` before falling back to
22//! `ProjectPaths::conventional` — a real, if harmless (the read fails and is
23//! discarded), disk touch still inside `bynk-emit` for that case.
24//!
25//! `bynk-emit`'s own on-disk discovery (`project::discover_bynk_files`) and
26//! `read_source`'s overlay-miss fallback are **not** removed, and can't be
27//! yet: `analyse_project_with` (the LSP's own analysis path — deleted at
28//! #1541; the equivalent hardcoding now lives in
29//! `bynk_check::analysis::analyse_project`) hardcodes `discovered: None` and
30//! passes an overlay that deliberately covers only open editor buffers — it
31//! depends on that exact fallback to see every other project file, including its own
32//! `bynk.toml` read (`AnalysisRoots::lower`, `bynk-ide/src/lib.rs`, has the
33//! same gap this module just closed for the CLI, unclosed). `#1079`'s issue
34//! text scopes only `bynk-ide`'s `completion.rs`/`symbols.rs` — it does not
35//! mention `analyse_project_with` or the `diagnose_project(&root,
36//! &HashMap::new())` pattern that is `bynk-ide`'s (and `bynk`'s test suite's)
37//! dominant way of exercising this whole analysis path (100+ call sites
38//! spanning `bynk-ide`'s own inline test modules, `bynk-lsp/tests`, and
39//! `bynk-tests/tests`) — every one depends on `read_source`'s fallback today.
40//! Closing `discovery.rs` for good needs all of that migrated first, which is
41//! bigger than either #1077 or #1079's issue text currently describes; #1077
42//! stays open pending that combined, design-reviewed effort. `fs_below_driver`
43//! does not move for `bynk-emit` from this module alone.
44
45use std::collections::HashMap;
46use std::path::{Path, PathBuf};
47
48use crate::project::Roots;
49
50/// An I/O failure while walking a project tree for `.bynk` files, or reading
51/// one found there.
52///
53/// #1081 review: `read_bynk_tree` used to `panic!` on any such failure, on the
54/// premise that every caller was a test fixture. That stopped being true the
55/// moment `project_options`/`try_project_options` (below) became its
56/// production callers — a `bynk.toml` with an `include` root that does not
57/// exist yet (or any other unreadable directory) is a normal, recoverable
58/// input on the live CLI path, not a broken fixture, and `try_project_options`
59/// already has a `Result` error channel for exactly this kind of thing.
60#[derive(Debug)]
61pub struct DiscoveryError {
62    path: PathBuf,
63    source: std::io::Error,
64}
65
66impl std::fmt::Display for DiscoveryError {
67    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
68        write!(
69            f,
70            "could not read project files under `{}`: {}",
71            self.path.display(),
72            self.source
73        )
74    }
75}
76
77impl std::error::Error for DiscoveryError {
78    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
79        Some(&self.source)
80    }
81}
82
83/// #1883, slice 1b: the project's `assets/` folder, listed
84/// ([`crate::project::assets::AssetFolder::on_disk`]) for
85/// `CompileOptions::asset_files`. No file's bytes are read here: the build
86/// reads only the files a declaration names. A missing folder is empty; an
87/// unlistable one is a [`DiscoveryError`] naming the folder.
88pub fn list_asset_folder(
89    project_root: &Path,
90) -> Result<crate::project::assets::AssetFolder, DiscoveryError> {
91    crate::project::assets::AssetFolder::on_disk(project_root).map_err(|source| DiscoveryError {
92        path: project_root.join(crate::project::assets::PROJECT_ASSETS_DIR),
93        source,
94    })
95}
96
97/// #2387, slice 2: the project's `embeds/` folder, listed as
98/// [`list_asset_folder`] lists `assets/`, for `CompileOptions::embed_files`.
99pub fn list_embed_folder(
100    project_root: &Path,
101) -> Result<crate::project::assets::EmbedFolder, DiscoveryError> {
102    crate::project::assets::AssetFolder::embeds_on_disk(project_root).map_err(|source| {
103        DiscoveryError {
104            path: project_root.join(crate::project::assets::PROJECT_EMBEDS_DIR),
105            source,
106        }
107    })
108}
109
110/// #2841: the project's `fixtures/` folder, listed as [`list_asset_folder`]
111/// lists `assets/`, for `CompileOptions::fixture_files`.
112pub fn list_fixture_folder(
113    project_root: &Path,
114) -> Result<crate::project::assets::FixtureFolder, DiscoveryError> {
115    crate::project::assets::AssetFolder::fixtures_on_disk(project_root).map_err(|source| {
116        DiscoveryError {
117            path: project_root.join(crate::project::assets::PROJECT_FIXTURES_DIR),
118            source,
119        }
120    })
121}
122
123/// P4b (#2608): the project's `migrations/` folder, listed as
124/// [`list_asset_folder`] lists `assets/`, for `CompileOptions::migration_files`.
125pub fn list_migration_folder(
126    project_root: &Path,
127) -> Result<crate::project::assets::AssetFolder, DiscoveryError> {
128    crate::project::assets::AssetFolder::migrations_on_disk(project_root).map_err(|source| {
129        DiscoveryError {
130            path: project_root.join(crate::project::assets::PROJECT_MIGRATIONS_DIR),
131            source,
132        }
133    })
134}
135
136/// Walk `root` for every `.bynk` file (skipping `excludes` and hidden
137/// directories, mirroring `bynk-emit`'s former `discover_bynk_files` exactly)
138/// and read each one's content. Keys are the same literal (non-canonicalised)
139/// path shape a plain recursive walk produces — `CompileOptions.sources`'s own
140/// contract, and what `read_source`'s overlay lookup tries first.
141///
142/// #3242: a subdirectory holding its own `bynk.toml` is another project and is
143/// not entered, as `bynk_project::discover_bynk_files` does. Use
144/// [`read_bynk_tree_across_projects`] to walk through such a directory.
145pub fn read_bynk_tree(
146    root: &Path,
147    excludes: &[PathBuf],
148) -> Result<HashMap<PathBuf, String>, DiscoveryError> {
149    walk_bynk_tree(root, excludes, true)
150}
151
152/// [`read_bynk_tree`] without stopping at nested projects, for `bynk fmt`: it
153/// formats each file by its own project's `[fmt]` settings, so a directory of
154/// projects is a fine thing to format as one tree.
155pub fn read_bynk_tree_across_projects(
156    root: &Path,
157) -> Result<HashMap<PathBuf, String>, DiscoveryError> {
158    walk_bynk_tree(root, &[], false)
159}
160
161fn walk_bynk_tree(
162    root: &Path,
163    excludes: &[PathBuf],
164    respect_projects: bool,
165) -> Result<HashMap<PathBuf, String>, DiscoveryError> {
166    let mut out = HashMap::new();
167    let is_excluded = |dir: &Path| {
168        excludes.iter().any(|ex| dir == ex || dir.starts_with(ex))
169            || dir
170                .file_name()
171                .and_then(|n| n.to_str())
172                .is_some_and(|n| n.starts_with('.') && n != ".")
173    };
174    let to_err = |path: &Path, source: std::io::Error| DiscoveryError {
175        path: path.to_path_buf(),
176        source,
177    };
178    let mut stack = vec![root.to_path_buf()];
179    while let Some(dir) = stack.pop() {
180        let rd = std::fs::read_dir(&dir).map_err(|e| to_err(&dir, e))?;
181        for entry in rd {
182            let entry = entry.map_err(|e| to_err(&dir, e))?;
183            let p = entry.path();
184            if p.is_dir() {
185                if !(is_excluded(&p) || respect_projects && bynk_project::is_project_boundary(&p)) {
186                    stack.push(p);
187                }
188            } else if p.extension().and_then(|e| e.to_str()) == Some("bynk") {
189                let text = std::fs::read_to_string(&p).map_err(|e| to_err(&p, e))?;
190                out.insert(p, text);
191            }
192        }
193    }
194    Ok(out)
195}
196
197/// [`read_bynk_tree`] with no excludes — the common case for a single-root
198/// project (`CompileOptions::single`, whose own `Roots::excludes()` is always
199/// empty) and for test fixtures, which rarely declare an `exclude` list.
200pub fn read_bynk_tree_single(root: &Path) -> Result<HashMap<PathBuf, String>, DiscoveryError> {
201    read_bynk_tree(root, &[])
202}
203
204/// [`read_bynk_tree`] merged across every one of a split project's `include`
205/// roots, matching `Roots::trees`' shape — the primary root's `paths.exclude`
206/// (plus the tool's own `out`/`node_modules` caches) applies to all of them.
207///
208/// R3.9 (#1113): walks every tree `Roots::trees` resolves to, not a hardcoded
209/// primary/secondary pair. `trees[0]` is mandatory (a missing directory is a
210/// real [`DiscoveryError`], same as any other unreadable directory); every
211/// later tree is optional — a conventional `src`-only project simply has no
212/// `tests/` at all — so only its absence is tolerated. Tried via
213/// `read_bynk_tree` itself (a `fs::read_dir`) and its `NotFound` caught for
214/// an optional tree, rather than a `root.exists()` pre-check, which would
215/// cost a redundant `stat()` per optional tree for the same answer.
216///
217/// Only a `NotFound` reported *for the root itself* is tolerated — matched by
218/// `e.path == *root`, true only for the walk's very first `fs::read_dir`
219/// call. A `NotFound` for anything deeper (a dangling symlink, a
220/// subdirectory removed mid-walk) means the tree exists and had real files;
221/// swallowing that would silently discard everything `read_bynk_tree` had
222/// already collected for it, with no diagnostic — a review-caught defect in
223/// an earlier cut of this fix, which matched on the error's `io::ErrorKind`
224/// alone regardless of which path it named.
225pub fn read_bynk_tree_split(
226    trees: &[PathBuf],
227    excludes: &[PathBuf],
228) -> Result<HashMap<PathBuf, String>, DiscoveryError> {
229    read_bynk_tree_split_with(trees, excludes, true)
230}
231
232/// [`read_bynk_tree_split`], with `respect_projects` choosing whether a nested
233/// project (#3242) is skipped (`true`) or walked through (`false`, for `fmt`).
234fn read_bynk_tree_split_with(
235    trees: &[PathBuf],
236    excludes: &[PathBuf],
237    respect_projects: bool,
238) -> Result<HashMap<PathBuf, String>, DiscoveryError> {
239    let mut out = HashMap::new();
240    for (i, root) in trees.iter().enumerate() {
241        match walk_bynk_tree(root, excludes, respect_projects) {
242            Ok(files) => out.extend(files),
243            Err(e)
244                if i > 0 && &e.path == root && e.source.kind() == std::io::ErrorKind::NotFound => {}
245            Err(e) => return Err(e),
246        }
247    }
248    Ok(out)
249}
250
251/// The complete `CompileOptions.sources` map for a project rooted at `roots`.
252///
253/// #1081 review: this used to re-implement `Roots::resolve`/`Roots::excludes`
254/// verbatim (down to the hardcoded `out`/`node_modules` cache list) because
255/// those were private to `bynk-emit`. Now that they're `pub` (moved to
256/// `bynk-project`, #1113), this calls them directly — one definition of
257/// "which files are in this project", shared by the CLI's own walk and
258/// `compile_project`'s in-memory partitioning, so the two can no longer drift.
259pub fn sources_for_roots(roots: &Roots) -> Result<HashMap<PathBuf, String>, DiscoveryError> {
260    sources_for_roots_with(roots, true)
261}
262
263/// [`sources_for_roots`] for `bynk fmt`, which formats through a nested project
264/// as it always has (#3242): each file takes its own project's `[fmt]` settings.
265pub fn sources_for_roots_across_projects(
266    roots: &Roots,
267) -> Result<HashMap<PathBuf, String>, DiscoveryError> {
268    sources_for_roots_with(roots, false)
269}
270
271fn sources_for_roots_with(
272    roots: &Roots,
273    respect_projects: bool,
274) -> Result<HashMap<PathBuf, String>, DiscoveryError> {
275    let mut trees: Vec<PathBuf> = roots.trees().into_iter().map(|(root, _)| root).collect();
276    // #2223: and each path dependency's trees, computed as `compile_project`
277    // computes them, so its partitioning finds every dependency file a home.
278    if let Roots::Split { project_root, .. } = roots {
279        trees.extend(
280            crate::project::dependency_trees(project_root, &HashMap::new())
281                .into_iter()
282                .map(|(root, _)| root),
283        );
284    }
285    read_bynk_tree_split_with(&trees, &roots.excludes(), respect_projects)
286}
287
288#[cfg(test)]
289mod tests {
290    use super::*;
291    use crate::project::{ProjectPaths, try_read_project_paths};
292    use std::fs;
293
294    /// A throwaway on-disk directory tree, removed on drop (including on
295    /// panic) — mirrors `bynk-driver/tests/project_diagnostics.rs`'s own
296    /// `Scratch` helper.
297    struct Scratch(PathBuf);
298    impl Drop for Scratch {
299        fn drop(&mut self) {
300            let _ = fs::remove_dir_all(&self.0);
301        }
302    }
303
304    fn scratch(tag: &str, files: &[(&str, &str)]) -> Scratch {
305        let dir = std::env::temp_dir().join(format!(
306            "bynk_driver_discovery_{tag}_{}_{:?}",
307            std::process::id(),
308            std::thread::current().id()
309        ));
310        let _ = fs::remove_dir_all(&dir);
311        for (rel, body) in files {
312            let p = dir.join(rel);
313            fs::create_dir_all(p.parent().unwrap()).unwrap();
314            fs::write(&p, body).unwrap();
315        }
316        Scratch(dir)
317    }
318
319    #[test]
320    fn walks_nested_files_and_skips_hidden_directories() {
321        let root = scratch(
322            "hidden",
323            &[
324                ("a.bynk", "context a\n"),
325                ("nested/b.bynk", "context b\n"),
326                (".git/c.bynk", "context c\n"),
327            ],
328        );
329        let found = read_bynk_tree(&root.0, &[]).expect("a real tree must not error");
330        assert_eq!(
331            found.len(),
332            2,
333            "found: {:?}",
334            found.keys().collect::<Vec<_>>()
335        );
336        assert!(found.contains_key(&root.0.join("a.bynk")));
337        assert!(found.contains_key(&root.0.join("nested/b.bynk")));
338    }
339
340    #[test]
341    fn excludes_skip_the_named_subtree() {
342        let root = scratch(
343            "excludes",
344            &[("a.bynk", "context a\n"), ("out/b.bynk", "context b\n")],
345        );
346        let found = read_bynk_tree(&root.0, &[root.0.join("out")]).expect("must not error");
347        assert_eq!(found.len(), 1);
348        assert!(found.contains_key(&root.0.join("a.bynk")));
349    }
350
351    #[test]
352    fn an_empty_tree_is_not_an_error() {
353        let root = scratch("empty", &[(".keep", "")]);
354        let found = read_bynk_tree(&root.0, &[]).expect("an empty tree is a valid, empty result");
355        assert!(found.is_empty());
356    }
357
358    #[test]
359    fn a_missing_root_is_a_discovery_error_not_a_panic() {
360        let missing = std::env::temp_dir().join(format!(
361            "bynk_driver_discovery_missing_{}_{:?}",
362            std::process::id(),
363            std::thread::current().id()
364        ));
365        let _ = fs::remove_dir_all(&missing);
366        let err = read_bynk_tree(&missing, &[]).expect_err("a nonexistent root must not panic");
367        assert!(err.to_string().contains(&missing.display().to_string()));
368    }
369
370    #[test]
371    fn split_secondary_root_is_optional_but_primary_is_not() {
372        // `tests/` need not exist for a `src`-only project.
373        let root = scratch("split_no_secondary", &[("src/a.bynk", "context a\n")]);
374        let found = read_bynk_tree_split(&[root.0.join("src"), root.0.join("tests")], &[])
375            .expect("a missing secondary root is tolerated");
376        assert_eq!(found.len(), 1);
377
378        // A missing *primary* root is a real error, matching the review's
379        // "missing include root panics instead of erroring" finding.
380        let missing_primary = root.0.join("does-not-exist");
381        read_bynk_tree_split(&[missing_primary, root.0.join("tests")], &[])
382            .expect_err("a missing primary root must error, not panic");
383    }
384
385    /// Regression (code review of the #1114 fix itself): an earlier cut of
386    /// the optional-tree `NotFound` tolerance matched on `io::ErrorKind`
387    /// alone, regardless of *which path* the error named — so a `NotFound`
388    /// anywhere inside an *existing* optional tree's walk (a dangling
389    /// symlink, a subdirectory removed mid-walk) was silently treated the
390    /// same as the tree itself being absent, discarding every real file
391    /// `read_bynk_tree` had already collected for it with no diagnostic.
392    /// Only a `NotFound` for the root itself should be tolerated.
393    #[cfg(unix)]
394    #[test]
395    fn a_dangling_symlink_deep_in_an_optional_tree_is_a_real_error_not_a_silent_drop() {
396        let root = scratch(
397            "split_dangling_symlink",
398            &[("src/a.bynk", "context a\n"), ("tests/b.bynk", "suite a\n")],
399        );
400        // The tree itself (`tests/`) exists and has a real `.bynk` file
401        // already collected by the time the walk reaches this dangling
402        // entry — `NotFound` here must not look like "no such optional
403        // tree."
404        std::os::unix::fs::symlink(
405            root.0.join("tests/does-not-exist.bynk"),
406            root.0.join("tests/dangling.bynk"),
407        )
408        .expect("symlink creation must succeed on unix");
409        let err = read_bynk_tree_split(&[root.0.join("src"), root.0.join("tests")], &[])
410            .expect_err("a NotFound deep in an existing optional tree's walk must still error");
411        assert!(
412            err.to_string().contains("dangling.bynk"),
413            "the error must name the file that actually failed: {err}"
414        );
415    }
416
417    /// R3.9 (#1113): three or more `include` roots are all merged — not just
418    /// the first two — exercised through `sources_for_roots` the way
419    /// `project_options` calls it — the file set a real `bynk.toml` project
420    /// resolves to.
421    #[test]
422    fn sources_for_roots_merges_three_or_more_include_roots() {
423        let root = scratch(
424            "many_includes",
425            &[
426                (
427                    "bynk.toml",
428                    "[project]\nname = \"x\"\n\n[paths]\ninclude = [\"src\", \"tests\", \"examples\"]\n",
429                ),
430                ("src/a.bynk", "context a\n"),
431                ("tests/a.bynk", "suite a\n"),
432                ("examples/e.bynk", "context e\n"),
433            ],
434        );
435        let paths: ProjectPaths =
436            try_read_project_paths(&root.0).expect("well-formed fixture manifest");
437        let roots = Roots::Split {
438            project_root: root.0.clone(),
439            paths,
440        };
441        let found = sources_for_roots(&roots).expect("a well-formed project must not error");
442        assert_eq!(
443            found.len(),
444            3,
445            "found: {:?}",
446            found.keys().collect::<Vec<_>>()
447        );
448        assert!(found.contains_key(&root.0.join("src/a.bynk")));
449        assert!(found.contains_key(&root.0.join("tests/a.bynk")));
450        assert!(found.contains_key(&root.0.join("examples/e.bynk")));
451    }
452
453    /// The `include.len()` == 0/1/2 branches, exercised through
454    /// `sources_for_roots` the way `project_options` calls it — the file set
455    /// a real `bynk.toml` project resolves to.
456    #[test]
457    fn sources_for_roots_matches_a_conventional_split_project() {
458        let root = scratch(
459            "conventional",
460            &[
461                ("bynk.toml", "[project]\nname = \"x\"\n"),
462                ("src/a.bynk", "context a\n"),
463                ("tests/a.bynk", "suite a\n"),
464            ],
465        );
466        let paths: ProjectPaths =
467            try_read_project_paths(&root.0).expect("well-formed fixture manifest");
468        let roots = Roots::Split {
469            project_root: root.0.clone(),
470            paths,
471        };
472        let found = sources_for_roots(&roots).expect("a well-formed project must not error");
473        assert_eq!(found.len(), 2);
474        assert!(found.contains_key(&root.0.join("src/a.bynk")));
475        assert!(found.contains_key(&root.0.join("tests/a.bynk")));
476    }
477
478    #[test]
479    fn sources_for_roots_on_a_flat_include_root_excludes_its_own_caches() {
480        // `include = ["."]` (`ProjectPaths::conventional`'s flat fallback):
481        // one root, and `node_modules`/`out` must still be swept out of it.
482        let root = scratch(
483            "flat",
484            &[
485                ("bynk.toml", "[project]\nname = \"x\"\n"),
486                ("a.bynk", "context a\n"),
487                ("node_modules/dep.bynk", "context dep\n"),
488                ("out/built.bynk", "context built\n"),
489            ],
490        );
491        let paths = ProjectPaths {
492            include: vec![PathBuf::from(".")],
493            exclude: Vec::new(),
494        };
495        let roots = Roots::Split {
496            project_root: root.0.clone(),
497            paths,
498        };
499        let found = sources_for_roots(&roots).expect("must not error");
500        assert_eq!(
501            found.len(),
502            1,
503            "found: {:?}",
504            found.keys().collect::<Vec<_>>()
505        );
506        assert!(found.contains_key(&root.0.join("a.bynk")));
507    }
508}