Skip to main content

bynk_testkit/
lib.rs

1//! Content-ownership track (#1086) slice 3: the cross-crate replacement for
2//! `diagnose_project(&root, &HashMap::new())` and bare
3//! `CompileOptions::single`/`::split`'s reliance on `bynk-emit`'s disk
4//! fallback (`design/tracks/content-ownership.md` §3.3, §4).
5//!
6//! Every helper here walks a project exactly the way production code already
7//! does — `bynk_ide::discover_files` for `diagnose_project*`-style callers,
8//! the same `bynk_driver::project::Roots` a `CompileOptions` will itself
9//! compile for `compile_options_*` — and reads every file into a complete
10//! sources map, instead of reimplementing the walk. There is no second
11//! resolution to drift from the first: a test built on these helpers cannot
12//! silently miss a file because this crate's notion of "the project's files"
13//! diverged from the compiler's own.
14//!
15//! Dev-only: invisible to `fs_below_driver`'s probe
16//! (`design/greenfield-status.md`), which is scoped to the crates below the
17//! driver (`bynk-emit`, `bynk-ide`, `bynk-fmt`) — not to dev-only crates like
18//! this one, which is why this file's own real `std::fs` reads (`read_all`,
19//! the `bynk.toml` read below) never register, not because the probe walks
20//! only production code.
21
22// The README's `rust` examples are compiled (and, unless marked `no_run`, run)
23// as doctests, so they cannot rot (#1645). `cfg(doctest)` keeps this item out of
24// every build and out of the docs.rs front page, which the `//!` docs above own.
25#[cfg(doctest)]
26#[doc = include_str!("../README.md")]
27struct ReadmeDoctests;
28
29use std::collections::HashMap;
30use std::path::PathBuf;
31
32/// Keyed by the literal discovered path, **not** canonicalised —
33/// `bynk-driver`'s own `sources_for_roots`/`read_bynk_tree` (the proven,
34/// production `CompileOptions.sources` populator, #1077/#1081) key theirs
35/// the same way. `CompileOptions.sources`'s own doc says filesystem
36/// discovery is skipped entirely once `sources` is `Some`, so whatever shape
37/// a file's identity/consistency checks expect has to come from these keys
38/// directly — canonicalising here (found the hard way: it broke
39/// `bynk.project.inconsistent_commons_name`'s path-shape check against a
40/// real multi-root example) would hand the compiler a different path shape
41/// than `discover_bynk_files`'s own walk produces.
42fn read_all(paths: Vec<PathBuf>) -> HashMap<PathBuf, String> {
43    paths
44        .into_iter()
45        .filter_map(|p| {
46            let content = std::fs::read_to_string(&p).ok()?;
47            Some((p, content))
48        })
49        .collect()
50}
51
52/// A complete `(path, content)` map for `roots`, resolved and enumerated the
53/// same way `bynk_ide::diagnose_project_with`'s own callers already do — the
54/// direct replacement for `diagnose_project(&root, &HashMap::new())`'s
55/// reliance on `bynk-emit`'s disk fallback filling in what the (empty)
56/// overlay doesn't cover.
57///
58/// Content-ownership track (#1086) slice 5 correction: for
59/// [`bynk_ide::AnalysisRoots::Project`], also reads `roots`'s own
60/// `bynk.toml` and includes it in the returned map — `bynk_ide::discover_files`
61/// needs it to resolve a non-conventional `[paths] include`/`exclude`, and a
62/// caller re-lowering `roots` against this map (e.g. a subsequent
63/// `diagnose_project_with`) needs it too. `bynk-ide` can no longer fall back
64/// to a disk read for a miss itself (R2.3), so this crate — a dev-only test
65/// seam, not gated by R2.3 at all — is where that real read belongs.
66pub fn read_project_sources(roots: &bynk_ide::AnalysisRoots) -> HashMap<PathBuf, String> {
67    let overlay = manifest_overlay(roots);
68    let mut sources = read_all(bynk_ide::discover_files(roots, &overlay));
69    sources.extend(overlay);
70    sources
71}
72
73/// `bynk.toml`'s real on-disk content for [`bynk_ide::AnalysisRoots::Project`],
74/// as a one-entry map — empty for `SingleTree` (no manifest consulted) or an
75/// unreadable/absent manifest, both already-handled "no manifest" cases.
76fn manifest_overlay(roots: &bynk_ide::AnalysisRoots) -> HashMap<PathBuf, String> {
77    let bynk_ide::AnalysisRoots::Project(root) = roots else {
78        return HashMap::new();
79    };
80    let toml_path = root.join("bynk.toml");
81    match std::fs::read_to_string(&toml_path) {
82        Ok(text) => HashMap::from([(toml_path, text)]),
83        Err(_) => HashMap::new(),
84    }
85}
86
87/// `CompileOptions::single(root)`, with every source pre-read — the direct
88/// replacement for its reliance on `bynk-emit`'s disk fallback.
89pub fn compile_options_single(root: impl Into<PathBuf>) -> bynk_driver::project::CompileOptions {
90    let root = root.into();
91    let sources = read_project_sources(&bynk_ide::AnalysisRoots::SingleTree(root.clone()));
92    let assets = list_assets(&root);
93    let embeds = list_embeds(&root);
94    let fixtures = list_fixtures(&root);
95    let migrations = list_migrations(&root);
96    bynk_driver::project::CompileOptions::single(root)
97        .sources(sources)
98        .asset_files(assets)
99        .embed_files(embeds)
100        .fixture_files(fixtures)
101        .migration_files(migrations)
102}
103
104/// `CompileOptions::split(project_root, paths)`, with every source pre-read.
105/// Discovers exactly the files `CompileOptions::split` itself would compile —
106/// built from the same `paths` this call also hands to `split`, not
107/// re-derived from `bynk.toml` through a second read, so the two can never
108/// disagree.
109pub fn compile_options_split(
110    project_root: impl Into<PathBuf>,
111    paths: bynk_driver::project::ProjectPaths,
112) -> bynk_driver::project::CompileOptions {
113    let project_root = project_root.into();
114    let roots = bynk_driver::project::Roots::Split {
115        project_root: project_root.clone(),
116        paths: paths.clone(),
117    };
118    let sources = read_all(bynk_driver::project::discover_project_files(&roots));
119    let assets = list_assets(&project_root);
120    let embeds = list_embeds(&project_root);
121    let fixtures = list_fixtures(&project_root);
122    let migrations = list_migrations(&project_root);
123    bynk_driver::project::CompileOptions::split(project_root, paths)
124        .sources(sources)
125        .asset_files(assets)
126        .embed_files(embeds)
127        .fixture_files(fixtures)
128        .migration_files(migrations)
129}
130
131/// #1883, slice 1b: the project's `assets/` folder, as the driver lists it
132/// for a real build — so a fixture's `assets/` reaches the compiler.
133fn list_assets(project_root: &std::path::Path) -> bynk_driver::project::assets::AssetFolder {
134    bynk_driver::project::assets::AssetFolder::on_disk(project_root)
135        .unwrap_or_else(|e| panic!("list `{}/assets`: {e}", project_root.display()))
136}
137
138/// P4b (#2608): the project's `migrations/` folder, listed the same way.
139fn list_migrations(project_root: &std::path::Path) -> bynk_driver::project::assets::AssetFolder {
140    bynk_driver::project::assets::AssetFolder::migrations_on_disk(project_root)
141        .unwrap_or_else(|e| panic!("list `{}/migrations`: {e}", project_root.display()))
142}
143
144/// #2387, slice 2: the project's `embeds/` folder, listed the same way.
145/// #2841: the project's `fixtures/` folder, as the driver lists it.
146fn list_fixtures(project_root: &std::path::Path) -> bynk_driver::project::assets::FixtureFolder {
147    bynk_driver::project::assets::AssetFolder::fixtures_on_disk(project_root)
148        .unwrap_or_else(|e| panic!("list `{}/fixtures`: {e}", project_root.display()))
149}
150
151fn list_embeds(project_root: &std::path::Path) -> bynk_driver::project::assets::EmbedFolder {
152    bynk_driver::project::assets::AssetFolder::embeds_on_disk(project_root)
153        .unwrap_or_else(|e| panic!("list `{}/embeds`: {e}", project_root.display()))
154}
155
156/// Stage the whole runtime (`__bynk_runtime/*.ts`) under `dir`, for a test that
157/// compiles emitted code by hand beside a runtime (ADR 0615: a project's own
158/// output carries only the modules it reaches).
159pub fn write_runtime_modules(dir: &std::path::Path) -> std::io::Result<()> {
160    for (path, source) in bynk_emit::emitter::emit_all_runtime_modules() {
161        let target = dir.join(path);
162        if let Some(parent) = target.parent() {
163            std::fs::create_dir_all(parent)?;
164        }
165        std::fs::write(target, source)?;
166    }
167    Ok(())
168}