Skip to main content

bynk_driver/
lib.rs

1//! bynk-driver — the front-end of the `bynk` CLI (#521).
2//!
3//! Both binaries expose `fmt` and `check` with identical semantics; before
4//! this crate each re-implemented the command bodies (and the project-failure
5//! flattening layer, and the project-rooting rule) as by-hand copies pinned
6//! only by comments and a skip-able parity test. The single implementation
7//! lives here, parameterised by the program name that prefixes messages.
8
9use std::collections::HashMap;
10use std::fs;
11use std::path::{Path, PathBuf};
12use std::process::ExitCode;
13
14use bynk_fmt::{FormatOptions, IndentStyle, format_source};
15use project::{CompileOptions, ProjectPathsError, try_read_project_paths_with};
16use render::LabelHome;
17
18pub mod colour;
19pub mod compile_cmd;
20pub mod contracts_lock;
21pub mod coverage;
22pub mod dev_run;
23pub mod discovery;
24pub mod doc_examples;
25pub mod eval;
26pub mod fix;
27pub mod mutate;
28pub mod npm_install;
29pub mod output;
30pub mod probe;
31pub mod progress;
32pub mod project;
33pub mod remote;
34pub mod render;
35pub mod schema_lock;
36pub mod smoke;
37pub mod snapshots;
38pub mod source_overlay;
39pub mod strip;
40pub mod test_filter;
41pub mod test_json;
42pub mod test_runner;
43pub mod test_stream;
44pub mod tools;
45pub mod tsc_report;
46
47pub use compile_cmd::{
48    BuildArgs, CliPlatform, CliProfile, CliTarget, CompileArgs, EmitFormat, profile_contracts,
49    project_contracts, refuse_release_contracts, refuse_undeployable_project, run_build,
50    run_compile,
51};
52pub use output::{write_document, write_modules, write_modules_for_node, write_output};
53
54/// Root a directory project the way every project command should (#46): a
55/// `bynk.toml` or a `src/` subdir selects **project** mode, whose flat
56/// `[paths] include`/`exclude` layout (v0.113, DECISION S) defaults to the
57/// conventional roots that exist (`src`, `tests`) or the project root itself;
58/// otherwise the legacy **single-tree** where `<dir>` is itself the root.
59/// `check`, `compile`, `test`, and `dev` all route through this so the
60/// conventional layout works the same from any of them.
61///
62/// #1077 (R2.3/T0.7 residue): reads and populates `.sources(...)` itself —
63/// `bynk-emit` no longer discovers or reads project files on disk, so this is
64/// now the one real place that walk happens for the live CLI path.
65///
66/// #1081 review: returns `Result` because that walk is real I/O against a
67/// user-controlled `bynk.toml` (a missing `include` root, an unreadable
68/// directory) — [`discovery::DiscoveryError`], not a panic.
69pub fn project_options(input: &Path) -> Result<CompileOptions, discovery::DiscoveryError> {
70    if input.join("bynk.toml").exists() || input.join("src").is_dir() {
71        let overlay = manifest_overlay(input);
72        let paths = try_read_project_paths_with(input, &overlay)
73            .unwrap_or_else(|_| project::ProjectPaths::conventional(input));
74        // #1890: degrades like `[paths]` above; `try_project_options` refuses.
75        let workers = project::try_read_workers_config_with(input, &overlay).unwrap_or_default();
76        Ok(options_for_split(input, paths)?
77            .compatibility_flags(workers.compatibility_flags)
78            .workers_dev(workers.workers_dev)
79            .asset_files(discovery::list_asset_folder(input)?)
80            .embed_files(discovery::list_embed_folder(input)?)
81            .fixture_files(discovery::list_fixture_folder(input)?)
82            .migration_files(discovery::list_migration_folder(input)?))
83    } else {
84        let sources = discovery::read_bynk_tree_single(input)?;
85        Ok(CompileOptions::single(input.to_path_buf())
86            .sources(sources)
87            .asset_files(discovery::list_asset_folder(input)?)
88            .embed_files(discovery::list_embed_folder(input)?)
89            .fixture_files(discovery::list_fixture_folder(input)?)
90            .migration_files(discovery::list_migration_folder(input)?))
91    }
92}
93
94/// [`project_options`], but a malformed `bynk.toml` is an error rather than a
95/// silent fall-back to the conventional layout — the one input a user
96/// hand-edits that the compiler otherwise reads without checking, after which
97/// a cascade of `bynk.uses.unknown_target` errors points at units that
98/// plainly exist on disk.
99///
100/// #1890: project mode also reads `[workers] compatibility_flags` into the
101/// options, so every CLI build (`bynk compile`, `bynk dev`/`deploy`, which
102/// all come through here) writes the project's flags into `wrangler.toml`.
103pub fn try_project_options(input: &Path) -> Result<CompileOptions, ProjectOptionsError> {
104    // #1883, slice 1b: the `assets/` folder is listed once here, beside the
105    // sources; the build reads only the declared files through it, so
106    // `bynk-emit` never touches the disk.
107    let asset_files = discovery::list_asset_folder(input)?;
108    // #2387, slice 2: the `embeds/` folder, listed the same way.
109    let embed_files = discovery::list_embed_folder(input)?;
110    // #2841: the `fixtures/` folder, listed the same way.
111    let fixture_files = discovery::list_fixture_folder(input)?;
112    // P4b (#2608): the `migrations/` folder, listed the same way.
113    let migration_files = discovery::list_migration_folder(input)?;
114    // #2554: the older contracts each callee still accepts. Read here, with
115    // the manifest, so every CLI build (`bynk compile`, `bynk dev`/`deploy`)
116    // honours the lock without its own plumbing. An unreadable file is an
117    // error, as for the schema lock: absent is the only "accepts nothing".
118    let contracts_lock = contracts_lock::read(input).map_err(|e| {
119        ProjectOptionsError::ContractsLock(format!(
120            "could not read {}: {e}",
121            contracts_lock::lock_path(input).display()
122        ))
123    })?;
124    Ok(match project_sources(input, Projects::Separate)? {
125        (Some(paths), sources) => {
126            let workers = project::try_read_workers_config_with(input, &manifest_overlay(input))?;
127            CompileOptions::split(input.to_path_buf(), paths)
128                .sources(sources)
129                .compatibility_flags(workers.compatibility_flags)
130                .workers_dev(workers.workers_dev)
131                .asset_files(asset_files)
132                .embed_files(embed_files)
133                .fixture_files(fixture_files)
134                .migration_files(migration_files.clone())
135                .contracts_lock(contracts_lock)
136        }
137        (None, sources) => CompileOptions::single(input.to_path_buf())
138            .sources(sources)
139            .asset_files(asset_files)
140            .embed_files(embed_files)
141            .fixture_files(fixture_files)
142            .migration_files(migration_files)
143            .contracts_lock(contracts_lock),
144    })
145}
146
147/// The `.bynk` files [`try_project_options`] reads for the directory `input`,
148/// sorted: what `check`, `test` and `compile` see. #1753: `fmt` expands a
149/// directory argument through this, so `fmt --check <dir>` and
150/// `check <dir>` cover the same files.
151pub fn project_source_files(input: &Path) -> Result<Vec<PathBuf>, ProjectOptionsError> {
152    let (_, sources) = project_sources(input, Projects::Separate)?;
153    let mut files: Vec<PathBuf> = sources.into_keys().collect();
154    files.sort();
155    Ok(files)
156}
157
158/// [`project_source_files`] for `fmt`: a directory of projects with no manifest
159/// of its own is formatted as one tree (#3242). Formatting reads no fixtures or
160/// migrations and takes each file's `[fmt]` settings from its own project, so
161/// walking through a project boundary is harmless, unlike compiling across it.
162fn fmt_source_files(input: &Path) -> Result<Vec<PathBuf>, ProjectOptionsError> {
163    let (_, sources) = project_sources(input, Projects::AsOneTree)?;
164    let mut files: Vec<PathBuf> = sources.into_keys().collect();
165    files.sort();
166    Ok(files)
167}
168
169/// #3242: how [`project_sources`] treats a directory with no manifest of its own
170/// that holds other projects.
171#[derive(Clone, Copy, PartialEq, Eq)]
172enum Projects {
173    /// What compiling needs: a nested `bynk.toml` marks another project, so it
174    /// is not walked, and a directory that is no project and holds several is
175    /// refused ([`ProjectOptionsError::NestedProjects`]).
176    Separate,
177    /// What formatting can do: one tree, nested projects and all.
178    AsOneTree,
179}
180
181/// [`try_project_options`]' rooting and walk, shared with
182/// [`project_source_files`] so the two can't disagree on which files a
183/// directory holds. A `bynk.toml` or a `src/` subdir selects project mode,
184/// returning its `[paths]` layout alongside the sources; otherwise `input` is
185/// a single tree and the layout is `None`.
186fn project_sources(
187    input: &Path,
188    projects: Projects,
189) -> Result<(Option<project::ProjectPaths>, HashMap<PathBuf, String>), ProjectOptionsError> {
190    if input.join("bynk.toml").exists() || input.join("src").is_dir() {
191        let overlay = manifest_overlay(input);
192        // #1665: an unknown table is refused here, on the CLIs' path, before
193        // `[paths]` is read. (The language server reads `[paths]` alone.)
194        project::check_manifest(input, &overlay)?;
195        // #2207 (decision C): a workspace root is not a project. Walking it as
196        // one would read every member's sources as a single tree.
197        if project::is_workspace_root(input) {
198            return Err(ProjectPathsError::WorkspaceRoot.into());
199        }
200        let paths = try_read_project_paths_with(input, &overlay)?;
201        let sources = split_sources(input, &paths, projects)?;
202        if projects == Projects::Separate {
203            note_skipped_projects(
204                input,
205                &project::Roots::Split {
206                    project_root: input.to_path_buf(),
207                    paths: paths.clone(),
208                },
209            );
210        }
211        Ok((Some(paths), sources))
212    } else if projects == Projects::AsOneTree {
213        Ok((None, discovery::read_bynk_tree_across_projects(input)?))
214    } else {
215        // #3242: no manifest here. If none is above either, this directory is
216        // not a project, and a tree of projects would compile as one program
217        // against the wrong roots (fixtures, migrations, `[paths]`, `[check]`).
218        // Say so rather than produce errors that don't name the cause.
219        let nested = bynk_project::nested_projects(input, &[]);
220        if !nested.is_empty() && !has_manifest_above(input) {
221            return Err(ProjectOptionsError::NestedProjects {
222                root: input.to_path_buf(),
223                projects: nested,
224            });
225        }
226        let sources = discovery::read_bynk_tree_single(input)?;
227        note_skipped_nested_projects(input, &nested);
228        Ok((None, sources))
229    }
230}
231
232/// Whether a `bynk.toml` sits above `dir` (not in it): `dir` is then inside a
233/// project, even if it has no manifest of its own.
234fn has_manifest_above(dir: &Path) -> bool {
235    let Ok(abs) = dir.canonicalize() else {
236        return false;
237    };
238    abs.ancestors()
239        .skip(1)
240        .any(|a| a.join("bynk.toml").is_file())
241}
242
243/// #3242: the one-line note for a nested project discovery stepped over, once
244/// per project per process, so a command that reads a tree twice says it once.
245fn note_skipped_nested_projects(root: &Path, nested: &[PathBuf]) {
246    static SAID: std::sync::Mutex<Option<std::collections::HashSet<PathBuf>>> =
247        std::sync::Mutex::new(None);
248    for project in nested {
249        if !bynk_project::holds_bynk_source(project) {
250            continue;
251        }
252        let first = SAID
253            .lock()
254            .unwrap_or_else(|e| e.into_inner())
255            .get_or_insert_with(Default::default)
256            .insert(project.clone());
257        if first {
258            crate::emsg!(
259                "bynk: note: skipped `{}`: it has its own bynk.toml, so it is a separate project; run the command inside it",
260                shown(project.strip_prefix(root).map_or(project.as_path(), |p| p))
261            );
262        }
263    }
264}
265
266/// [`note_skipped_nested_projects`] for a manifest-backed project: the projects
267/// nested under any of its `include` trees.
268fn note_skipped_projects(root: &Path, roots: &project::Roots) {
269    let excludes = roots.excludes();
270    let mut nested: Vec<PathBuf> = Vec::new();
271    for (tree, _) in roots.trees() {
272        nested.extend(bynk_project::nested_projects(&tree, &excludes));
273    }
274    nested.sort();
275    nested.dedup();
276    note_skipped_nested_projects(root, &nested);
277}
278
279/// `bynk.toml`'s own content, keyed exactly as [`try_read_project_paths_with`]
280/// looks it up (`project_root.join("bynk.toml")`, unmodified — the literal-path
281/// branch of `discovery::read_source`'s overlay lookup, so this never needs to
282/// match a canonicalised key).
283///
284/// #1077 review: without this, both entry points above read `bynk.toml`
285/// through `bynk-emit`'s own disk-fallback (`read_source`'s `fs::read_to_string`
286/// on an overlay miss) — the one on-disk read #1081 left the CLI path still
287/// implicitly depending on `bynk-emit` for, despite that PR's claim of a fully
288/// fallback-free CLI path. A missing/unreadable `bynk.toml` yields an empty
289/// overlay, which `try_read_project_paths_with` already treats as "no
290/// manifest" (falls back to the conventional layout) — the same degrade
291/// `try_read_project_paths` itself provides.
292fn manifest_overlay(input: &Path) -> HashMap<PathBuf, String> {
293    let toml_path = input.join("bynk.toml");
294    match fs::read_to_string(&toml_path) {
295        Ok(text) => HashMap::from([(toml_path, text)]),
296        Err(_) => HashMap::new(),
297    }
298}
299
300/// The split-layout half of `project_options`: walk the project's sources
301/// ([`split_sources`]) and hand them to `CompileOptions::split` alongside the
302/// layout.
303fn options_for_split(
304    input: &Path,
305    paths: project::ProjectPaths,
306) -> Result<CompileOptions, discovery::DiscoveryError> {
307    let sources = split_sources(input, &paths, Projects::Separate)?;
308    Ok(CompileOptions::split(input.to_path_buf(), paths).sources(sources))
309}
310
311/// The sources of a project rooted at `input` with layout `paths`: build the
312/// one `Roots` value the project resolves to and walk exactly that (via
313/// [`discovery::sources_for_roots`] — #1081 review, so the CLI's walk can't
314/// drift from what `Roots::trees`/`Roots::excludes` themselves say). The one
315/// copy of the split-layout walk, shared by [`project_options`] and
316/// [`try_project_options`]/[`project_source_files`] (#1755 review).
317fn split_sources(
318    input: &Path,
319    paths: &project::ProjectPaths,
320    projects: Projects,
321) -> Result<HashMap<PathBuf, String>, discovery::DiscoveryError> {
322    let roots = project::Roots::Split {
323        project_root: input.to_path_buf(),
324        paths: paths.clone(),
325    };
326    match projects {
327        Projects::Separate => discovery::sources_for_roots(&roots),
328        Projects::AsOneTree => discovery::sources_for_roots_across_projects(&roots),
329    }
330}
331
332/// Why [`try_project_options`] could not produce a usable [`CompileOptions`]:
333/// either the manifest itself is unreadable ([`ProjectPathsError`]), or a
334/// well-formed manifest names a project tree that can't be walked
335/// ([`discovery::DiscoveryError`]) — #1081 review.
336#[derive(Debug)]
337pub enum ProjectOptionsError {
338    Paths(ProjectPathsError),
339    Discovery(discovery::DiscoveryError),
340    /// #2554: `bynk.contracts.lock` exists but could not be read.
341    ContractsLock(String),
342    /// #3242: the directory has no `bynk.toml`, nor does any above it, but
343    /// projects with their own manifests are nested below.
344    NestedProjects {
345        root: PathBuf,
346        projects: Vec<PathBuf>,
347    },
348}
349
350impl std::fmt::Display for ProjectOptionsError {
351    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
352        match self {
353            Self::Paths(e) => write!(f, "{e}"),
354            Self::Discovery(e) => write!(f, "{e}"),
355            Self::ContractsLock(e) => write!(f, "{e}"),
356            Self::NestedProjects { root, projects } => {
357                write!(f, "{}", nested_projects_message(root, projects, true))
358            }
359        }
360    }
361}
362
363impl ProjectOptionsError {
364    /// The message, for a command that cannot take `--each` (#3274): the
365    /// refusal of a directory of projects then advises only running inside one
366    /// or adding a root manifest. Every other error reads as [`std::fmt::Display`] does,
367    /// and so does a directory of projects for `check` and `test`, which can.
368    pub fn render(&self, each_applies: bool) -> String {
369        match self {
370            Self::NestedProjects { root, projects } => {
371                nested_projects_message(root, projects, each_applies)
372            }
373            other => other.to_string(),
374        }
375    }
376}
377
378/// #3242/#3274: the refusal of a directory that is not a project but holds some.
379fn nested_projects_message(root: &Path, projects: &[PathBuf], each_applies: bool) -> String {
380    const SHOWN: usize = 5;
381    let names: Vec<String> = projects
382        .iter()
383        .take(SHOWN)
384        .map(|p| format!("`{}`", shown(p.strip_prefix(root).unwrap_or(p))))
385        .collect();
386    let more = projects.len().saturating_sub(SHOWN);
387    format!(
388        "`{}` is not a project (no `bynk.toml` here or above) but holds {} that have their own: {}{}.\n\
389         Run the command inside one of them, {}or add a `bynk.toml` here with\n\
390         \n    [workspace]\n    members = [\"*\"]\n\n\
391         to {}",
392        dir_label(root),
393        if projects.len() == 1 {
394            "a project".to_string()
395        } else {
396            format!("{} projects", projects.len())
397        },
398        names.join(", "),
399        if more > 0 {
400            format!(" and {more} more")
401        } else {
402            String::new()
403        },
404        if each_applies {
405            "pass `--each` to run it over each, "
406        } else {
407            ""
408        },
409        if each_applies {
410            "keep that choice in the repository"
411        } else {
412            "run it over each"
413        },
414    )
415}
416
417/// A directory as a message names it: `.` rather than an empty string.
418fn dir_label(dir: &Path) -> String {
419    match shown(dir) {
420        s if s.is_empty() => ".".to_string(),
421        s => s,
422    }
423}
424
425impl std::error::Error for ProjectOptionsError {
426    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
427        match self {
428            // `ProjectPathsError` doesn't itself implement `Error` (no
429            // further cause to chain to — it's already a leaf).
430            Self::Paths(_) | Self::ContractsLock(_) | Self::NestedProjects { .. } => None,
431            Self::Discovery(e) => Some(e),
432        }
433    }
434}
435
436impl From<ProjectPathsError> for ProjectOptionsError {
437    fn from(e: ProjectPathsError) -> Self {
438        Self::Paths(e)
439    }
440}
441
442impl From<discovery::DiscoveryError> for ProjectOptionsError {
443    fn from(e: discovery::DiscoveryError) -> Self {
444        Self::Discovery(e)
445    }
446}
447
448/// Render a project build failure with per-file ariadne context, exactly as
449/// single-file mode had rich rendering. Unattributed (project-level) errors
450/// keep the plain form.
451///
452/// This is the **flattening layer** (ADR 0100): it attributes each
453/// `AttributedError` to its file snapshot and delegates the actual rendering to
454/// [`crate::render::print_errors`]. The `ProjectFailure → CompileError` flattening
455/// stays here, above the `render` module, so there is no `render → emit` edge.
456pub fn print_project_failure(failure: &project::ProjectFailure) {
457    for ae in failure.errors.iter().filter(|ae| !is_hint(ae)) {
458        match attributed_snapshot(ae, &failure.snapshots, &failure.display_root) {
459            Some((label, text)) => {
460                print_attributed(ae, &label, text, &failure.snapshots, &failure.display_root);
461            }
462            None => {
463                eprintln!("[{}] {}", ae.error.category, ae.error.message);
464                for note in &ae.error.notes {
465                    crate::emsg!("  note: {note}");
466                }
467                // Finding #47: a label's text still surfaces even with no
468                // file to underline it against.
469                for (_, label) in &ae.error.labels {
470                    eprintln!("  label: {label}");
471                }
472            }
473        }
474    }
475}
476
477/// #2838: a hint is for the editor and machine-readable surfaces; the terminal
478/// reports (`check`, `build`) leave it out.
479fn is_hint(ae: &project::AttributedError) -> bool {
480    bynk_syntax::Severity::for_error(&ae.error) == bynk_syntax::Severity::Hint
481}
482
483/// v0.89 (ADR 0117): print a successful build's non-failing warnings, with
484/// real per-file ariadne context now that a successful build's `snapshots`
485/// (mirroring `ProjectFailure::snapshots`) make that possible. A warning whose
486/// source isn't attributable (or doesn't fit the snapshot) falls back to the
487/// plain `warning[<category>]: <message>` form.
488pub fn print_project_warnings(
489    warnings: &[project::AttributedError],
490    snapshots: &[(PathBuf, String)],
491    display_root: &Path,
492) {
493    for w in warnings.iter().filter(|w| !is_hint(w)) {
494        match attributed_snapshot(w, snapshots, display_root) {
495            Some((label, text)) => print_attributed(w, &label, text, snapshots, display_root),
496            None => {
497                let where_ = w
498                    .source_path
499                    .as_deref()
500                    .map(|p| format!("{}: ", p.to_string_lossy().replace('\\', "/")))
501                    .unwrap_or_default();
502                eprintln!("{where_}warning[{}]: {}", w.error.category, w.error.message);
503                for note in &w.error.notes {
504                    crate::emsg!("  note: {note}");
505                }
506                for (_, label) in &w.error.labels {
507                    eprintln!("  label: {label}");
508                }
509            }
510        }
511    }
512}
513
514/// [`print_project_warnings`]'s `--format short` analogue: one
515/// `path:line:col: warning[category]: message` line per warning, falling
516/// back to `warning[category]: message` when unattributed. Strictly one
517/// line per warning throughout (like [`crate::render::render_errors_short`],
518/// this mirrors the VS Code problem-matcher's contract), so — unlike
519/// [`print_project_warnings`] — finding #47 doesn't reach this one.
520pub fn print_project_warnings_short(
521    warnings: &[project::AttributedError],
522    snapshots: &[(PathBuf, String)],
523    display_root: &Path,
524) {
525    for w in warnings.iter().filter(|w| !is_hint(w)) {
526        match attributed_snapshot(w, snapshots, display_root) {
527            Some((label, text)) => {
528                eprintln!("{}", crate::render::short_line(&label, text, &w.error))
529            }
530            // Every entry in `warnings` is warning-severity by construction
531            // (ADR 0117's own split), so `severity_word` here is always
532            // "warning" — read off the shared helper (finding #48) rather
533            // than hardcoding the string a second time.
534            None => eprintln!(
535                "{}[{}]: {}",
536                crate::render::severity_word(&w.error),
537                w.error.category,
538                w.error.message
539            ),
540        }
541    }
542}
543
544/// The `(label, source text)` an `AttributedError`'s `source_path` resolves
545/// to in `snapshots`, if any — the one attribution lookup every renderer in
546/// this file shares (finding #48; previously `print_project_failure` and
547/// [`project_failure_short_lines`] each hand-rolled their own copy).
548///
549/// #1772: the label is the file's path as typed from the working directory
550/// ([`display_path`]), not its identity path. `snapshots` stay keyed by
551/// identity.
552fn attributed_snapshot<'a>(
553    ae: &project::AttributedError,
554    snapshots: &'a [(PathBuf, String)],
555    display_root: &Path,
556) -> Option<(String, &'a str)> {
557    let path = ae.source_path.as_deref()?;
558    let text = snapshots
559        .iter()
560        .find(|(p, _)| p.as_path() == path)
561        .map(|(_, t)| t.as_str())?;
562    Some((display_path(display_root, path), text))
563}
564
565/// Render `ae` with ariadne against its own file's `text` (shown as `label`),
566/// each secondary label against the file it lies in: a "previously declared
567/// here" in a sibling file of a multi-file unit is drawn in a snippet of that
568/// file, from `snapshots`, not at the same offsets in this one. A label into a
569/// first-party unit (#1956) is drawn against that unit's own source, named by
570/// its bare identity path (`bynk.bynk`) — it is not under the project root, so
571/// [`display_path`] would name a file that doesn't exist. A label whose file
572/// has no text becomes a note.
573fn print_attributed(
574    ae: &project::AttributedError,
575    label: &str,
576    text: &str,
577    snapshots: &[(PathBuf, String)],
578    display_root: &Path,
579) {
580    let others: Vec<Option<(String, &str)>> = (0..ae.error.labels.len())
581        .map(|i| match ae.label_file(i) {
582            project::LabelFile::Other(path) => snapshots
583                .iter()
584                .find(|(p, _)| p == path)
585                .map(|(_, t)| (display_path(display_root, path), t.as_str())),
586            project::LabelFile::FirstParty {
587                identity_path,
588                source,
589            } => Some(((*identity_path).to_string(), *source)),
590            _ => None,
591        })
592        .collect();
593    let homes: Vec<LabelHome<'_>> = others
594        .iter()
595        .enumerate()
596        .map(|(i, other)| match (ae.label_file(i), other) {
597            (project::LabelFile::Primary, _) => LabelHome::Primary,
598            (_, Some((filename, source))) => LabelHome::File { filename, source },
599            (_, None) => LabelHome::Unavailable,
600        })
601        .collect();
602    crate::render::print_error_in(&ae.error, text, label, &homes, crate::colour::stderr());
603}
604
605/// #1772: the path a diagnostic names, as a user would type it from the
606/// working directory: the build's root as the caller spelled it, joined with
607/// the file's identity path (relative to that root). A relative root is
608/// already relative to the working directory; an absolute one (`bynk dev`
609/// resolves the project root) is shown relative to the working directory when
610/// it lies inside it. This matches the path `fmt` reports for the same file,
611/// so a problem matcher resolving against the working directory finds it.
612/// Separators print as `/` on every platform.
613///
614/// #1774 review: a `.` component is dropped (`bynk check`'s default input is
615/// `.`, and `Roots::trees` already keeps `./` out of identity paths for the
616/// same reason), and an absolute path is compared against the cwd both as
617/// given and canonicalised, since a canonical root on Windows is a verbatim
618/// `\\?\C:\…` path that a plain cwd never prefixes. One that still isn't
619/// under the cwd is shown absolute, without a verbatim prefix.
620pub fn display_path(display_root: &Path, identity: &Path) -> String {
621    use std::path::Component;
622    let joined: PathBuf = display_root
623        .join(identity)
624        .components()
625        .filter(|c| !matches!(c, Component::CurDir))
626        .collect();
627    let shown = if joined.is_absolute() {
628        let cwd = std::env::current_dir().ok();
629        let canonical_cwd = cwd.as_ref().and_then(|c| c.canonicalize().ok());
630        cwd.iter()
631            .chain(canonical_cwd.iter())
632            .find_map(|base| joined.strip_prefix(base).ok().map(Path::to_path_buf))
633            .unwrap_or(joined)
634    } else {
635        joined
636    };
637    let text = shown.to_string_lossy().replace('\\', "/");
638    // A verbatim prefix (`//?/C:/…`, `//?/UNC/server/…`) is Windows-internal.
639    if let Some(unc) = text.strip_prefix("//?/UNC/") {
640        format!("//{unc}")
641    } else if let Some(rest) = text.strip_prefix("//?/") {
642        rest.to_string()
643    } else {
644        text
645    }
646}
647
648/// #1774: a path the user named directly (a `fmt` input, a single-file
649/// `check`), shown by the same rule as [`display_path`], so `fmt` and `check`
650/// print one file identically on every platform. On Windows a directory's
651/// expansion joined `\` onto a `/`-typed input, giving mixed separators.
652fn shown(path: &Path) -> String {
653    display_path(Path::new(""), path)
654}
655
656/// The project-failure analogue of [`crate::render::print_errors_short`]: each
657/// attributed error is positioned against its file's snapshot; an unattributed
658/// (project-level) error falls back to `<severity>[<category>]: <message>`.
659pub fn print_project_failure_short(failure: &project::ProjectFailure) {
660    // #2838: the lines keep hints for the machine consumers that re-parse them
661    // (the `test --format json` document); the terminal drops them.
662    for ae in failure.errors.iter().filter(|ae| !is_hint(ae)) {
663        eprintln!("{}", failure_short_line(failure, ae));
664    }
665}
666
667/// The string form of [`print_project_failure_short`]: one `path:line:col:
668/// severity[category]: message` line per attributed error (an unattributed
669/// project-level error falls back to `severity[category]: message`). Backs both
670/// the printer above and the `bynk test --format json` compile-error document,
671/// whose `diagnostics` the VS Code `bynk` problem-matcher re-parses — each
672/// `Vec` entry is exactly one line by that contract, so unlike the other
673/// renderers in this file this one deliberately does *not* grow note/label
674/// continuation lines (finding #47): doing so would break a machine consumer
675/// that re-parses every entry as a single diagnostic line.
676///
677/// The flattening layer (ADR 0100): it delegates the per-error formatting to
678/// [`crate::render::short_line`] / [`crate::render::severity_word`], and the
679/// attribution lookup to the crate-private `attributed_snapshot` (finding #48).
680pub fn project_failure_short_lines(failure: &project::ProjectFailure) -> Vec<String> {
681    failure
682        .errors
683        .iter()
684        .map(|ae| failure_short_line(failure, ae))
685        .collect()
686}
687
688/// One error of `failure` as its single `--format short` line.
689fn failure_short_line(failure: &project::ProjectFailure, ae: &project::AttributedError) -> String {
690    match attributed_snapshot(ae, &failure.snapshots, &failure.display_root) {
691        Some((label, text)) => crate::render::short_line(&label, text, &ae.error),
692        None => format!(
693            "{}[{}]: {}",
694            crate::render::severity_word(&ae.error),
695            ae.error.category,
696            ae.error.message
697        ),
698    }
699}
700
701/// Render every diagnostic from a [`project::ProjectCheck`] (finding #64) with
702/// the same per-file ariadne context [`print_project_failure`] gives its own,
703/// errors-only list. Unlike that renderer, a `ProjectCheck`'s list can
704/// legitimately mix both severities — the unattributed fallback line names its
705/// actual severity ([`crate::render::severity_word`]) rather than
706/// `print_project_failure`'s bare `[category]: message` (silently correct only
707/// because that list is errors-only by construction).
708pub fn print_project_check(check: &project::ProjectCheck) {
709    for ae in check.errors.iter().filter(|ae| !is_hint(ae)) {
710        match attributed_snapshot(ae, &check.snapshots, &check.display_root) {
711            Some((label, text)) => {
712                print_attributed(ae, &label, text, &check.snapshots, &check.display_root);
713            }
714            None => {
715                eprintln!(
716                    "{}[{}]: {}",
717                    crate::render::severity_word(&ae.error),
718                    ae.error.category,
719                    ae.error.message
720                );
721                for note in &ae.error.notes {
722                    crate::emsg!("  note: {note}");
723                }
724                for (_, label) in &ae.error.labels {
725                    eprintln!("  label: {label}");
726                }
727            }
728        }
729    }
730}
731
732/// [`print_project_check`]'s `--format short` analogue, mirroring
733/// [`project_failure_short_lines`].
734pub fn project_check_short_lines(check: &project::ProjectCheck) -> Vec<String> {
735    check
736        .errors
737        .iter()
738        .filter(|ae| !is_hint(ae))
739        .map(
740            |ae| match attributed_snapshot(ae, &check.snapshots, &check.display_root) {
741                Some((label, text)) => crate::render::short_line(&label, text, &ae.error),
742                None => format!(
743                    "{}[{}]: {}",
744                    crate::render::severity_word(&ae.error),
745                    ae.error.category,
746                    ae.error.message
747                ),
748            },
749        )
750        .collect()
751}
752
753/// [`print_project_check`] via [`project_check_short_lines`].
754pub fn print_project_check_short(check: &project::ProjectCheck) {
755    for line in project_check_short_lines(check) {
756        eprintln!("{line}");
757    }
758}
759
760/// How `--indent` spells the two [`IndentStyle`] variants. The words match the
761/// `[fmt] indent` key in `bynk.toml`, which the language server already reads,
762/// so a project states the same choice the same way in either place.
763#[derive(clap::ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
764pub enum IndentKind {
765    /// One tab per nesting level. The default — a reader sets their own tab
766    /// width in the editor, which space indentation takes away from them.
767    Tab,
768    /// `--indent-width` spaces per nesting level.
769    Spaces,
770}
771
772/// The `fmt` subcommand's arguments, flattened by
773/// `bynk::cli` so the two spell one contract rather than two copies of it (the
774/// [`test_runner::TestArgs`] pattern, findings #40/#72). Field docs here are
775/// the CLI help text for both commands' flags.
776///
777/// Every style field is an `Option`, and deliberately carries no clap
778/// `default_value` (#972). The three sources are layered — spec default, then
779/// the project's `bynk.toml` `[fmt]`, then the flag — and a clap default would
780/// make "the user asked for 100" indistinguishable from "the user said
781/// nothing", so a manifest's `max_line_width = 120` would be overwritten by a
782/// flag nobody passed. `None` means *defer to the layer below*.
783#[derive(clap::Args, Debug)]
784pub struct FmtArgs {
785    /// Files or directories to format. A directory formats the `.bynk` files
786    /// `check` would read in it: a project root's `[paths] include` trees minus
787    /// `exclude`, a workspace root's members, or any other directory walked
788    /// recursively. Use `-` for stdin → stdout.
789    pub inputs: Vec<PathBuf>,
790    /// Check formatting without writing changes. Exits non-zero if any
791    /// file is not already canonical.
792    #[arg(long)]
793    pub check: bool,
794    /// Indent with tabs or spaces. Defaults to the project's `[fmt] indent`,
795    /// or tabs.
796    #[arg(long, value_enum)]
797    pub indent: Option<IndentKind>,
798    /// Spaces per nesting level, with spaces indentation. Defaults to the
799    /// project's `[fmt] indent_width`, or 2. Rejected when the effective
800    /// indentation is tabs, where it would have no effect.
801    #[arg(long, value_name = "N", value_parser = clap::value_parser!(u8).range(0..=64))]
802    pub indent_width: Option<u8>,
803    /// Soft target line width in columns. A construct wider than this wraps
804    /// across lines where the grammar allows; one with no break point in it
805    /// (a long string literal) is left long. Defaults to the project's
806    /// `[fmt] max_line_width`, or 100.
807    #[arg(long, value_name = "COLUMNS", value_parser = clap::value_parser!(u32).range(1..))]
808    pub max_line_width: Option<u32>,
809    /// Emit a trailing comma in multi-line records, sums, list literals and
810    /// `exports` clauses. Overrides a project's `trailing_comma = false`, and
811    /// overrides an earlier `--no-trailing-comma`.
812    #[arg(long, overrides_with = "no_trailing_comma")]
813    pub trailing_comma: bool,
814    /// Omit the trailing comma in multi-line records, sums, list literals and
815    /// `exports` clauses. (Parameter and argument lists never carry one — the
816    /// grammar rejects it — regardless of this flag.)
817    #[arg(long, overrides_with = "trailing_comma")]
818    pub no_trailing_comma: bool,
819    /// Ignore the project's `bynk.toml` `[fmt]` section and format to the
820    /// canonical style, plus whatever flags this run passes. For a script that
821    /// wants one fixed rendering whatever project it is pointed at.
822    #[arg(long)]
823    pub no_config: bool,
824}
825
826impl FmtArgs {
827    /// Layer these arguments over `base` — the manifest-resolved options for
828    /// the file about to be formatted — or report why they describe nothing
829    /// usable. A field the run did not state leaves `base` untouched.
830    pub fn apply_to(&self, base: FormatOptions) -> Result<FormatOptions, String> {
831        // The width already in `base` (from `[fmt] indent_width`, or the spec
832        // default), so `--indent spaces` alone over a manifest's `indent_width
833        // = 4` lands on four spaces rather than resetting to two.
834        let base_width = match base.indent {
835            IndentStyle::Spaces(n) => Some(n),
836            IndentStyle::Tab => None,
837        };
838        let kind = self.indent.unwrap_or(match base.indent {
839            IndentStyle::Tab => IndentKind::Tab,
840            IndentStyle::Spaces(_) => IndentKind::Spaces,
841        });
842        let indent = match (kind, self.indent_width) {
843            (IndentKind::Tab, None) => IndentStyle::Tab,
844            // A width alongside tab indentation is silently meaningless, which
845            // is exactly the kind of ignored flag that costs an hour to
846            // notice. Say so instead — naming the *effective* indentation,
847            // since it may have come from the manifest rather than this run.
848            (IndentKind::Tab, Some(_)) => {
849                return Err(
850                    "`--indent-width` applies only to spaces indentation, and this run resolves \
851                     to tabs (pass `--indent spaces`, or set `[fmt] indent` in bynk.toml)"
852                        .to_string(),
853                );
854            }
855            // 2 matches the `bynk.toml` `[fmt] indent_width` fallback, so the
856            // CLI and the editor agree from the same words.
857            (IndentKind::Spaces, width) => IndentStyle::Spaces(width.or(base_width).unwrap_or(2)),
858        };
859        Ok(FormatOptions {
860            indent,
861            max_line_width: self.max_line_width.unwrap_or(base.max_line_width),
862            // Neither flag set defers to `base`; clap's `overrides_with` pair
863            // makes the last one given win.
864            trailing_comma: if self.no_trailing_comma {
865                false
866            } else if self.trailing_comma {
867                true
868            } else {
869                base.trailing_comma
870            },
871        })
872    }
873}
874
875/// Why a run could not settle on the options to format an input with.
876enum FmtOptionsError {
877    /// The project's `bynk.toml` `[fmt]` section is unusable.
878    Manifest(PathBuf, bynk_fmt::ConfigError),
879    /// #1665: the project's `bynk.toml` has a table (or a `[project]`/`[lsp]`
880    /// key) it doesn't define.
881    ManifestTables(PathBuf, project::ProjectPathsError),
882    /// The flags this run passed contradict each other or the manifest.
883    Args(String),
884}
885
886impl std::fmt::Display for FmtOptionsError {
887    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
888        match self {
889            // Named, because the manifest governing a file is not necessarily
890            // the one in the working directory.
891            Self::Manifest(path, e) => write!(f, "{}: {e}", path.display()),
892            Self::ManifestTables(path, e) => write!(f, "{}: {e}", path.display()),
893            Self::Args(e) => write!(f, "{e}"),
894        }
895    }
896}
897
898/// Per-directory memo of the `[fmt]` section governing an input.
899///
900/// A run typically formats many files under one project (`fmt src/*.bynk`), so
901/// the upward walk for `bynk.toml` and its parse happen once per starting
902/// directory rather than once per file.
903struct ManifestCache {
904    /// `--no-config`: skip discovery entirely and hand back the spec defaults.
905    disabled: bool,
906    by_dir: std::collections::HashMap<PathBuf, FormatOptions>,
907}
908
909impl ManifestCache {
910    fn new(disabled: bool) -> Self {
911        Self {
912            disabled,
913            by_dir: std::collections::HashMap::new(),
914        }
915    }
916
917    /// The options `input` inherits from its project, before this run's flags.
918    fn options_for(&mut self, input: &Path) -> Result<FormatOptions, FmtOptionsError> {
919        if self.disabled {
920            return Ok(FormatOptions::default());
921        }
922        // Stdin carries no path to search from; the working directory is the
923        // only project context a pipe has.
924        let start: PathBuf = if input.as_os_str() == "-" {
925            PathBuf::from(".")
926        } else {
927            match input.parent() {
928                // A bare `x.bynk` has an empty parent, which is the cwd.
929                Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
930                _ => PathBuf::from("."),
931            }
932        };
933        // Absolutise before walking. A relative start has no ancestors to walk
934        // *through*: `Path::new("src").parent()` is `""` and `""`'s parent is
935        // `None`, so the search stops at the working directory and never
936        // reaches the project root above it. Run from `src/`, `fmt calc.bynk`
937        // therefore missed the very manifest `fmt src/calc.bynk` from the root
938        // found — silently formatting to the canonical style, and (under
939        // `--check`) gating CI on a style the editor never produces. Joining
940        // onto the cwd also collapses `src` and `/abs/src` to one cache key.
941        //
942        // `current_dir()` rather than `std::path::absolute`: same result here,
943        // and it does not raise the crate's MSRV.
944        let start = std::env::current_dir()
945            .map(|cwd| cwd.join(&start))
946            .unwrap_or(start);
947        if let Some(hit) = self.by_dir.get(&start) {
948            return Ok(*hit);
949        }
950        let opts = match bynk_fmt::find_manifest(&start) {
951            None => FormatOptions::default(),
952            Some(manifest) => {
953                let text = std::fs::read_to_string(&manifest).map_err(|e| {
954                    FmtOptionsError::Manifest(
955                        manifest.clone(),
956                        bynk_fmt::ConfigError::Read(e.to_string()),
957                    )
958                })?;
959                // `[fmt]` first: its reader owns the detailed TOML parse error
960                // and its own keys. #1665: then the manifest's table set.
961                let config = bynk_fmt::FmtConfig::from_manifest_str(&text)
962                    .map_err(|e| FmtOptionsError::Manifest(manifest.clone(), e))?;
963                let options = config.apply(FormatOptions::default());
964                // #2207: path-aware, so a workspace member's own
965                // `[registries]` or `[workspace]` is refused here as in `check`.
966                let root = manifest.parent().unwrap_or(Path::new("."));
967                project::check_manifest(root, &HashMap::from([(root.join("bynk.toml"), text)]))
968                    .map_err(|e| FmtOptionsError::ManifestTables(manifest, e))?;
969                options
970            }
971        };
972        self.by_dir.insert(start, opts);
973        Ok(opts)
974    }
975}
976
977/// The `fmt` command body run by `bynk fmt`: each input is
978/// formatted and rewritten only when it changes; `--check` reports
979/// non-canonical files without writing; `-` reads stdin and writes the
980/// formatted result to stdout. `prog` prefixes messages (`bynk fmt: …`).
981pub fn run_fmt(prog: &str, args: &FmtArgs) -> ExitCode {
982    let check = args.check;
983    if args.inputs.is_empty() {
984        crate::emsg!(
985            "{prog} fmt: error: no input files (pass file or directory paths, or `-` for stdin)"
986        );
987        return ExitCode::FAILURE;
988    }
989    let inputs = match expand_fmt_inputs(&args.inputs) {
990        Ok(inputs) => inputs,
991        Err(e) => {
992            crate::emsg!("{prog} fmt: error: {e}");
993            return ExitCode::FAILURE;
994        }
995    };
996    let inputs = &inputs;
997    // Resolve *every* input's options before formatting any of them. Options
998    // are per-input — `[fmt]` belongs to the project the file sits in, so a
999    // path outside the current project obeys that project's style — but a
1000    // manifest error found on the third input must not land after the first two
1001    // have already been rewritten. Configuration is a whole-run precondition:
1002    // it fails before a byte is written, or not at all.
1003    let mut manifests = ManifestCache::new(args.no_config);
1004    let mut resolved: Vec<FormatOptions> = Vec::with_capacity(inputs.len());
1005    for input in inputs {
1006        match manifests
1007            .options_for(input)
1008            .and_then(|base| args.apply_to(base).map_err(FmtOptionsError::Args))
1009        {
1010            Ok(opts) => resolved.push(opts),
1011            Err(e) => {
1012                crate::emsg!("{prog} fmt: error: {e}");
1013                return ExitCode::FAILURE;
1014            }
1015        }
1016    }
1017
1018    let mut had_diff = false;
1019    let mut had_error = false;
1020    for (input, opts) in inputs.iter().zip(resolved) {
1021        if input.as_os_str() == "-" {
1022            use std::io::Read;
1023            let mut source = String::new();
1024            if let Err(e) = std::io::stdin().read_to_string(&mut source) {
1025                crate::emsg!("{prog} fmt: error: read from stdin: {e}");
1026                return ExitCode::FAILURE;
1027            }
1028            // #1763: compared, and errors rendered, modulo line endings.
1029            let source = bynk_fmt::normalize_line_endings(&source);
1030            match format_source(&source, &opts) {
1031                Ok(formatted) => {
1032                    if check {
1033                        // `--check` on stdin must not print the formatted text
1034                        // (it would pollute a CI log) and must report a diff the
1035                        // same way the file path does — a `generator | bynk fmt
1036                        // --check -` gate is otherwise dead, passing green on
1037                        // non-canonical input.
1038                        if formatted != source {
1039                            crate::emsg!("{prog} fmt: error: <stdin> is not canonically formatted");
1040                            had_diff = true;
1041                        }
1042                    } else {
1043                        print!("{formatted}");
1044                    }
1045                }
1046                Err(e) => {
1047                    crate::render::print_errors(
1048                        &e.errors,
1049                        &source,
1050                        "<stdin>",
1051                        crate::colour::stderr(),
1052                    );
1053                    return ExitCode::FAILURE;
1054                }
1055            }
1056            continue;
1057        }
1058        let raw = match std::fs::read_to_string(input) {
1059            Ok(s) => s,
1060            Err(e) => {
1061                crate::emsg!("{prog} fmt: error: read `{}`: {e}", shown(input));
1062                had_error = true;
1063                continue;
1064            }
1065        };
1066        // #1763: line endings are not a formatting difference. A CRLF copy of a
1067        // canonical file passes `--check` and isn't rewritten; a file that does
1068        // need formatting is written in the LF canonical form. Errors render
1069        // against the normalised text, whose spans they carry.
1070        let source = bynk_fmt::normalize_line_endings(&raw);
1071        let filename = shown(input);
1072        match format_source(&source, &opts) {
1073            Ok(formatted) => {
1074                if check {
1075                    if formatted != source {
1076                        crate::emsg!(
1077                            "{prog} fmt: error: {} is not canonically formatted",
1078                            filename
1079                        );
1080                        had_diff = true;
1081                    }
1082                } else if formatted != source
1083                    && let Err(e) = atomic_write(input, &formatted)
1084                {
1085                    crate::emsg!("{prog} fmt: error: write `{}`: {e}", filename);
1086                    had_error = true;
1087                }
1088            }
1089            Err(e) => {
1090                crate::render::print_errors(&e.errors, &source, &filename, crate::colour::stderr());
1091                had_error = true;
1092            }
1093        }
1094    }
1095    if had_error || (check && had_diff) {
1096        ExitCode::FAILURE
1097    } else {
1098        ExitCode::SUCCESS
1099    }
1100}
1101
1102/// #1753: expand `fmt`'s arguments to the files it formats. A directory
1103/// becomes the `.bynk` files [`project_source_files`] finds in it, which is what
1104/// `check` and `test` read for the same argument: a project root's `[paths]`
1105/// `include` trees minus `exclude`, or a plain directory walked recursively,
1106/// hidden directories skipped either way. A file or `-` passes through. A file
1107/// named more than once, directly or through a directory, is formatted once.
1108///
1109/// A directory with no `.bynk` files is an error rather than an empty run, so
1110/// a mistyped path cannot pass `--check`. Expansion happens before any file is
1111/// read, so its errors, like a manifest error, land before anything is written.
1112fn expand_fmt_inputs(inputs: &[PathBuf]) -> Result<Vec<PathBuf>, String> {
1113    let mut out = Vec::new();
1114    let mut seen = std::collections::HashSet::new();
1115    for input in inputs {
1116        // #2207 (decision C): a workspace root formats every member's files,
1117        // named from the root as the command was given it.
1118        if input.as_os_str() != "-"
1119            && let Some(workspace) = workspace_at(input)
1120        {
1121            let workspace = workspace.map_err(|e| format!("`{}`: {e}", input.display()))?;
1122            for member in &workspace.members {
1123                let member = member_dir(input, member);
1124                let files =
1125                    fmt_source_files(&member).map_err(|e| format!("`{}`: {e}", shown(&member)))?;
1126                for file in files {
1127                    let key = std::fs::canonicalize(&file).unwrap_or_else(|_| file.clone());
1128                    if seen.insert(key) {
1129                        out.push(file);
1130                    }
1131                }
1132            }
1133            continue;
1134        }
1135        let files = if input.as_os_str() != "-" && input.is_dir() {
1136            let files =
1137                fmt_source_files(input).map_err(|e| format!("`{}`: {e}", input.display()))?;
1138            if files.is_empty() {
1139                return Err(format!("no `.bynk` files under `{}`", input.display()));
1140            }
1141            files
1142        } else {
1143            vec![input.clone()]
1144        };
1145        for file in files {
1146            let key = std::fs::canonicalize(&file).unwrap_or_else(|_| file.clone());
1147            if seen.insert(key) {
1148                out.push(file);
1149            }
1150        }
1151    }
1152    Ok(out)
1153}
1154
1155/// Write `contents` to `path` atomically: the bytes land in a sibling temp
1156/// file that is then `rename`d over `path`. A plain `std::fs::write` truncates
1157/// the destination *before* writing, so an ENOSPC, a signal, or a crash
1158/// mid-write leaves the file truncated or empty — and for `fmt`, whose only
1159/// copy of the original is the in-memory `source`, that original is then gone.
1160/// The rename is atomic on POSIX and Windows, so a reader sees either the whole
1161/// old file or the whole new one, never a half-written mix.
1162///
1163/// The temp file is a sibling (same directory) so the rename stays within one
1164/// filesystem — a cross-device rename would fail with `EXDEV`. Its name carries
1165/// the PID and a per-process counter so concurrent `fmt` runs, or two files in
1166/// one run, never collide, and it is opened with `create_new` (`O_EXCL`): a
1167/// pre-existing path — a stale temp from an earlier crashed run, or a symlink a
1168/// local actor pre-planted to redirect the formatted bytes — is refused rather
1169/// than opened, and we bump the counter and retry. On any failure the temp file
1170/// is removed so a botched write leaves no litter beside the untouched original.
1171///
1172/// The `rename` swaps in a fresh inode, so if `path` was a symlink or a
1173/// hardlink the formatted file replaces the link rather than being written
1174/// through it (the old `std::fs::write` wrote through). Uncommon for source
1175/// files, and the atomicity is worth it.
1176fn atomic_write(path: &Path, contents: &str) -> std::io::Result<()> {
1177    use std::io::Write as _;
1178    use std::sync::atomic::{AtomicU64, Ordering};
1179
1180    static COUNTER: AtomicU64 = AtomicU64::new(0);
1181
1182    let dir = path.parent().filter(|p| !p.as_os_str().is_empty());
1183    let file_name = path
1184        .file_name()
1185        .map(|n| n.to_string_lossy().into_owned())
1186        .unwrap_or_default();
1187
1188    // Open a fresh sibling temp file exclusively, bumping the counter past any
1189    // name that is already taken (stale temp or planted symlink).
1190    let (mut file, tmp) = loop {
1191        let n = COUNTER.fetch_add(1, Ordering::Relaxed);
1192        let tmp_name = format!(".{file_name}.bynk-fmt.{}.{n}.tmp", std::process::id());
1193        let tmp = match dir {
1194            Some(d) => d.join(tmp_name),
1195            None => PathBuf::from(tmp_name),
1196        };
1197        match std::fs::OpenOptions::new()
1198            .write(true)
1199            .create_new(true)
1200            .open(&tmp)
1201        {
1202            Ok(f) => break (f, tmp),
1203            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
1204            Err(e) => return Err(e),
1205        }
1206    };
1207
1208    // Scope the write so the handle is flushed and closed before the rename.
1209    // The rename replaces the destination inode, so carry the original file's
1210    // permissions onto the temp file first — otherwise a formatted file would
1211    // silently pick up the process umask's default mode (e.g. an executable or
1212    // group-restricted source would lose its bits).
1213    let write_result = (|| {
1214        // Best-effort: a filesystem that cannot honour the mode must not fail
1215        // the whole write.
1216        if let Ok(meta) = std::fs::metadata(path) {
1217            let _ = file.set_permissions(meta.permissions());
1218        }
1219        file.write_all(contents.as_bytes())?;
1220        file.sync_all()
1221    })();
1222    if let Err(e) = write_result {
1223        let _ = std::fs::remove_file(&tmp);
1224        return Err(e);
1225    }
1226    if let Err(e) = std::fs::rename(&tmp, path) {
1227        let _ = std::fs::remove_file(&tmp);
1228        return Err(e);
1229    }
1230    Ok(())
1231}
1232
1233/// The `check` command body run by `bynk check`: a
1234/// directory routes through [`project::check_project`] (finding #64 —
1235/// non-bailing, so a structural error anywhere does not hide diagnostics
1236/// elsewhere the way `compile_project`'s bail-fast `Mode::Build` would), a
1237/// single file through [`bynk_emit::check_with_warnings`]. `short` selects
1238/// the one-line `--format short` rendering. `prog` prefixes messages
1239/// (`bynk: …`).
1240///
1241/// #2642: `fix` first applies the machine-applicable suggestions ([`fix`]) to
1242/// the input, or to each workspace member in turn, then reports what remains
1243/// as an ordinary check does. A refused or failed fix fails the run.
1244///
1245/// #3537: `fix` is `None` for no fixing, `Some(&[])` for `--fix` (every
1246/// diagnostic `check` shows) and `Some(codes)` for `--fix=<code>,…`, which
1247/// takes only those codes' fixes. An unknown code is refused before any work.
1248pub fn run_check(
1249    prog: &str,
1250    input: &Path,
1251    short: bool,
1252    fix: Option<&[String]>,
1253    each: bool,
1254) -> ExitCode {
1255    let scope = match fix.map(fix::Scope::codes).transpose() {
1256        Ok(scope) => scope,
1257        Err(message) => {
1258            crate::emsg!("{prog}: error: --fix: {message}");
1259            return ExitCode::FAILURE;
1260        }
1261    };
1262    // #2207 (decision C): at a workspace root, check every member in order.
1263    // Every member runs, and the run fails if any does. `rich` heads each
1264    // member's report with its path; `short` adds no headers, and its paths
1265    // are already relative to where the command ran.
1266    // #3274: `each` makes a manifest-less directory of projects the same.
1267    let workspace = match workspace_at_each(input, each) {
1268        Ok(w) => w,
1269        Err(message) => {
1270            crate::emsg!("{prog}: error: {message}");
1271            return ExitCode::FAILURE;
1272        }
1273    };
1274    if let Some(workspace) = workspace {
1275        let workspace = match workspace {
1276            Ok(w) => w,
1277            Err(e) => {
1278                crate::emsg!("{prog}: error: {}: {e}", shown(&input.join("bynk.toml")));
1279                return ExitCode::FAILURE;
1280            }
1281        };
1282        let members: Vec<PathBuf> = workspace
1283            .members
1284            .iter()
1285            .map(|m| member_dir(input, m))
1286            .collect();
1287        // #2642: plan every member before writing any, so a refusal in one
1288        // leaves the whole workspace untouched.
1289        let mut failed = false;
1290        if let Some(scope) = &scope {
1291            let named: Vec<(&Path, String)> = members
1292                .iter()
1293                .map(|m| (m.as_path(), format!("{prog}: {}", shown(m))))
1294                .collect();
1295            failed |= !fix::fix_all(prog, scope, &named);
1296        }
1297        for member in &members {
1298            if !short {
1299                eprintln!("{}", member_header(member));
1300            }
1301            failed |= !check_one(prog, member, short, Some(member));
1302        }
1303        return if failed {
1304            ExitCode::FAILURE
1305        } else {
1306            ExitCode::SUCCESS
1307        };
1308    }
1309    let fixed = scope
1310        .as_ref()
1311        .is_none_or(|scope| fix::fix_all(prog, scope, &[(input, prog.to_string())]));
1312    if check_one(prog, input, short, None) && fixed {
1313        ExitCode::SUCCESS
1314    } else {
1315        ExitCode::FAILURE
1316    }
1317}
1318
1319/// #2207: if `input` is a workspace root (a directory whose `bynk.toml` holds
1320/// `[workspace]`), the workspace it loads to, or why it doesn't.
1321pub fn workspace_at(input: &Path) -> Option<Result<project::Workspace, ProjectPathsError>> {
1322    (input.is_dir() && project::is_workspace_root(input)).then(|| project::load_workspace(input))
1323}
1324
1325/// #3274: [`workspace_at`], or, with `each`, the workspace `--each` stands for:
1326///
1327/// - a real workspace root is itself (the flag changes nothing there);
1328/// - a manifest-less directory with no `bynk.toml` above it is the implicit
1329///   workspace of its immediate-subdirectory projects, with a note for each
1330///   manifest-less subdirectory holding `.bynk` files;
1331/// - anything else (a file, a project, a directory inside a project, a
1332///   directory with no project directly below it, or one with `.bynk` files of
1333///   its own) is refused with a message, so the flag never quietly does nothing.
1334///
1335/// The `Err` is the message, without a command prefix.
1336pub fn workspace_at_each(
1337    input: &Path,
1338    each: bool,
1339) -> Result<Option<Result<project::Workspace, ProjectPathsError>>, String> {
1340    if !each || project::is_workspace_root(input) {
1341        return Ok(workspace_at(input));
1342    }
1343    let name = dir_label(input);
1344    if !input.is_dir() {
1345        return Err(format!(
1346            "`--each` takes a directory of projects, not `{name}`"
1347        ));
1348    }
1349    if input.join("bynk.toml").exists() || input.join("src").is_dir() {
1350        return Err(format!(
1351            "`--each` applies to a directory of projects, but `{name}` is a project: run the command without it"
1352        ));
1353    }
1354    if has_manifest_above(input) {
1355        return Err(format!(
1356            "`--each` applies to a directory of projects, but `{name}` is inside a project (a `bynk.toml` is above it): run the command without it"
1357        ));
1358    }
1359    match bynk_project::implicit_workspace(input) {
1360        Ok(implicit) => {
1361            for dir in &implicit.skipped {
1362                note_skipped_manifestless(input, dir);
1363            }
1364            Ok(Some(Ok(implicit.workspace)))
1365        }
1366        Err(bynk_project::ImplicitWorkspaceError::RootSources) => Err(format!(
1367            "`{name}` holds `.bynk` files of its own, which no project under it would read: move them into a project, or drop `--each`"
1368        )),
1369        Err(bynk_project::ImplicitWorkspaceError::NoProjects { deeper }) => {
1370            if deeper.is_empty() {
1371                Err(format!(
1372                    "`{name}` holds no project: no subdirectory of it has a `bynk.toml`"
1373                ))
1374            } else {
1375                let shown_deeper: Vec<String> = deeper
1376                    .iter()
1377                    .take(5)
1378                    .map(|p| format!("`{}`", shown(p.strip_prefix(input).unwrap_or(p))))
1379                    .collect();
1380                let more = deeper.len().saturating_sub(5);
1381                Err(format!(
1382                    "`{name}` holds no project directly inside it, but {} further down: {}{}.\n\
1383                     `--each` runs the projects directly inside a directory: pass the directory that holds them",
1384                    if deeper.len() == 1 {
1385                        "one".to_string()
1386                    } else {
1387                        format!("{}", deeper.len())
1388                    },
1389                    shown_deeper.join(", "),
1390                    if more > 0 {
1391                        format!(" and {more} more")
1392                    } else {
1393                        String::new()
1394                    }
1395                ))
1396            }
1397        }
1398    }
1399}
1400
1401/// #3274: the one-line note for a subdirectory `--each` set aside because it
1402/// holds `.bynk` files but no `bynk.toml`, once per directory per process.
1403fn note_skipped_manifestless(root: &Path, dir: &Path) {
1404    static SAID: std::sync::Mutex<Option<std::collections::HashSet<PathBuf>>> =
1405        std::sync::Mutex::new(None);
1406    let key = root.join(dir);
1407    let first = SAID
1408        .lock()
1409        .unwrap_or_else(|e| e.into_inner())
1410        .get_or_insert_with(Default::default)
1411        .insert(key);
1412    if first {
1413        crate::emsg!(
1414            "bynk: note: skipped `{}`: it has no bynk.toml, so it is not a project",
1415            shown(dir)
1416        );
1417    }
1418}
1419
1420/// #2207: a member's directory as the command names it: `root` (as the user
1421/// typed it) joined with the member's relative path, without `.` components,
1422/// so a run at `.` names `packages/money`, not `./packages/money`.
1423pub fn member_dir(root: &Path, member: &Path) -> PathBuf {
1424    root.join(member)
1425        .components()
1426        .filter(|c| !matches!(c, std::path::Component::CurDir))
1427        .collect()
1428}
1429
1430/// #2207 (decision C): the line that heads one member's report in a
1431/// workspace run, `── packages/money ──`, its path as typed from the working
1432/// directory.
1433pub fn member_header(member: &Path) -> String {
1434    format!("── {} ──", shown(member))
1435}
1436
1437/// [`run_check`] over one project or file; `true` when it passes. `member`
1438/// names the workspace member being checked, so a project-level error says
1439/// which one it is.
1440fn check_one(prog: &str, input: &Path, short: bool, member: Option<&Path>) -> bool {
1441    let prog = match member {
1442        Some(m) => format!("{prog}: {}", shown(m)),
1443        None => prog.to_string(),
1444    };
1445    let prog = prog.as_str();
1446    if input.is_dir() {
1447        let options = match try_project_options(input) {
1448            Ok(o) => o,
1449            Err(e) => {
1450                crate::emsg!("{prog}: error: {e}");
1451                return false;
1452            }
1453        };
1454        // #2078: reconcile events against the committed `bynk.schema.lock`,
1455        // read-only, so a non-additive change fails `check` as it fails a
1456        // build. Nothing is written: an additive change is left for a build
1457        // to record.
1458        let options = match schema_lock::read_only(input) {
1459            Ok(lock) => options.schema_registry(lock),
1460            Err(e) => {
1461                crate::emsg!("{prog}: error: {e}");
1462                return false;
1463            }
1464        };
1465        let check = project::check_project(&options);
1466        let has_errors = check.has_errors();
1467        if short {
1468            print_project_check_short(&check);
1469        } else {
1470            print_project_check(&check);
1471        }
1472        !has_errors
1473    } else {
1474        let source = match std::fs::read_to_string(input) {
1475            Ok(s) => s,
1476            Err(e) => {
1477                crate::emsg!("{prog}: error: could not read `{}`: {e}", shown(input));
1478                return false;
1479            }
1480        };
1481        let filename = shown(input);
1482        match bynk_emit::check_with_warnings(&source, &filename) {
1483            Ok(warnings) => {
1484                let warnings = crate::render::without_hints(&warnings);
1485                if !warnings.is_empty() {
1486                    if short {
1487                        crate::render::print_errors_short(&warnings, &source, &filename);
1488                    } else {
1489                        crate::render::print_errors(
1490                            &warnings,
1491                            &source,
1492                            &filename,
1493                            crate::colour::stderr(),
1494                        );
1495                    }
1496                }
1497                true
1498            }
1499            Err(errors) => {
1500                if short {
1501                    crate::render::print_errors_short(&errors, &source, &filename);
1502                } else {
1503                    crate::render::print_errors(
1504                        &errors,
1505                        &source,
1506                        &filename,
1507                        crate::colour::stderr(),
1508                    );
1509                }
1510                false
1511            }
1512        }
1513    }
1514}
1515
1516#[cfg(test)]
1517mod tests {
1518    use super::*;
1519    use clap::Parser;
1520
1521    /// A minimal parser around [`FmtArgs`], so these assert what the real CLIs
1522    /// parse rather than what a hand-built struct claims.
1523    #[derive(clap::Parser, Debug)]
1524    struct Harness {
1525        #[command(flatten)]
1526        args: FmtArgs,
1527    }
1528
1529    fn parse(argv: &[&str]) -> FmtArgs {
1530        let mut full = vec!["fmt"];
1531        full.extend_from_slice(argv);
1532        Harness::parse_from(full).args
1533    }
1534
1535    /// The options a run resolves with no manifest in play.
1536    fn resolve(argv: &[&str]) -> Result<FormatOptions, String> {
1537        parse(argv).apply_to(FormatOptions::default())
1538    }
1539
1540    /// A stand-in for what `bynk.toml` `[fmt]` resolved to.
1541    fn manifest(toml: &str) -> FormatOptions {
1542        bynk_fmt::FmtConfig::from_manifest_str(toml)
1543            .expect("manifest parses")
1544            .apply(FormatOptions::default())
1545    }
1546
1547    #[test]
1548    fn no_flags_is_the_canonical_style() {
1549        let opts = resolve(&["a.bynk"]).expect("valid");
1550        assert_eq!(opts, FormatOptions::default());
1551    }
1552
1553    #[test]
1554    fn spaces_without_a_width_falls_back_to_two() {
1555        // The same fallback `bynk.toml`'s `[fmt] indent_width` uses, so the CLI
1556        // and the language server land on the same style from the same words.
1557        let opts = resolve(&["--indent", "spaces", "a.bynk"]).expect("valid");
1558        assert_eq!(opts.indent, IndentStyle::Spaces(2));
1559    }
1560
1561    #[test]
1562    fn spaces_takes_the_given_width() {
1563        let opts =
1564            resolve(&["--indent", "spaces", "--indent-width", "4", "a.bynk"]).expect("valid");
1565        assert_eq!(opts.indent, IndentStyle::Spaces(4));
1566    }
1567
1568    #[test]
1569    fn a_width_with_tabs_is_an_error_not_a_silent_no_op() {
1570        let err = resolve(&["--indent", "tab", "--indent-width", "4", "a.bynk"])
1571            .expect_err("a meaningless width must be reported");
1572        assert!(err.contains("--indent-width"), "{err}");
1573        assert!(err.contains("spaces"), "{err}");
1574    }
1575
1576    #[test]
1577    fn the_trailing_comma_pair_is_last_one_wins() {
1578        // `overrides_with` in both directions: a script may append either flag
1579        // to a shared argument list and have it win rather than conflict-error.
1580        assert!(
1581            resolve(&["--no-trailing-comma", "--trailing-comma", "a.bynk"])
1582                .expect("valid")
1583                .trailing_comma
1584        );
1585        assert!(
1586            !resolve(&["--trailing-comma", "--no-trailing-comma", "a.bynk"])
1587                .expect("valid")
1588                .trailing_comma
1589        );
1590    }
1591
1592    #[test]
1593    fn max_line_width_is_taken_verbatim_and_zero_is_refused() {
1594        assert_eq!(
1595            resolve(&["--max-line-width", "60", "a.bynk"])
1596                .expect("valid")
1597                .max_line_width,
1598            60
1599        );
1600        // A zero-column budget is a nonsense input; clap rejects it at parse
1601        // time rather than the formatter wrapping every construct maximally.
1602        assert!(
1603            Harness::try_parse_from(["fmt", "--max-line-width", "0", "a.bynk"]).is_err(),
1604            "`--max-line-width 0` must not parse"
1605        );
1606    }
1607
1608    // -- #972: the `bynk.toml` `[fmt]` layer beneath the flags --
1609
1610    #[test]
1611    fn an_unflagged_run_takes_the_manifest_whole() {
1612        let base = manifest(
1613            "[fmt]\nindent = \"spaces\"\nindent_width = 4\nmax_line_width = 120\ntrailing_comma = false\n",
1614        );
1615        let opts = parse(&["a.bynk"]).apply_to(base).expect("valid");
1616        assert_eq!(opts.indent, IndentStyle::Spaces(4));
1617        assert_eq!(opts.max_line_width, 120);
1618        assert!(!opts.trailing_comma);
1619    }
1620
1621    #[test]
1622    fn a_flag_beats_the_manifest_field_it_names_and_no_other() {
1623        let base = manifest("[fmt]\nindent = \"spaces\"\nindent_width = 4\nmax_line_width = 120\n");
1624        let opts = parse(&["--max-line-width", "80", "a.bynk"])
1625            .apply_to(base)
1626            .expect("valid");
1627        assert_eq!(opts.max_line_width, 80, "the flag wins where it speaks");
1628        assert_eq!(
1629            opts.indent,
1630            IndentStyle::Spaces(4),
1631            "and stays silent everywhere else"
1632        );
1633    }
1634
1635    #[test]
1636    fn an_absent_flag_does_not_reset_the_manifest_to_the_default() {
1637        // The regression a clap `default_value` would have caused: "the user
1638        // said 100" is indistinguishable from "the user said nothing", so a
1639        // project's 120 would be overwritten by a flag nobody passed.
1640        let base = manifest("[fmt]\nmax_line_width = 120\n");
1641        assert_eq!(
1642            parse(&["a.bynk"])
1643                .apply_to(base)
1644                .expect("valid")
1645                .max_line_width,
1646            120
1647        );
1648    }
1649
1650    #[test]
1651    fn indent_spaces_alone_keeps_the_manifest_width() {
1652        let base = manifest("[fmt]\nindent = \"spaces\"\nindent_width = 4\n");
1653        let opts = parse(&["--indent", "spaces", "a.bynk"])
1654            .apply_to(base)
1655            .expect("valid");
1656        assert_eq!(opts.indent, IndentStyle::Spaces(4), "not reset to 2");
1657    }
1658
1659    #[test]
1660    fn indent_width_alone_applies_to_a_manifest_that_chose_spaces() {
1661        let base = manifest("[fmt]\nindent = \"spaces\"\n");
1662        let opts = parse(&["--indent-width", "8", "a.bynk"])
1663            .apply_to(base)
1664            .expect("valid");
1665        assert_eq!(opts.indent, IndentStyle::Spaces(8));
1666    }
1667
1668    #[test]
1669    fn indent_width_alone_is_refused_when_the_run_resolves_to_tabs() {
1670        // No `--indent`, and a manifest that says tabs (or none at all): the
1671        // width has nothing to apply to, and the message says so rather than
1672        // the flag vanishing.
1673        let err = parse(&["--indent-width", "8", "a.bynk"])
1674            .apply_to(manifest("[fmt]\nindent = \"tab\"\n"))
1675            .expect_err("refused");
1676        assert!(err.contains("resolves"), "{err}");
1677    }
1678
1679    #[test]
1680    fn an_explicit_tab_flag_overrides_a_manifest_choosing_spaces() {
1681        let base = manifest("[fmt]\nindent = \"spaces\"\nindent_width = 4\n");
1682        let opts = parse(&["--indent", "tab", "a.bynk"])
1683            .apply_to(base)
1684            .expect("valid");
1685        assert_eq!(opts.indent, IndentStyle::Tab);
1686    }
1687
1688    #[test]
1689    fn trailing_comma_flag_overrides_a_manifest_that_turned_it_off() {
1690        let base = manifest("[fmt]\ntrailing_comma = false\n");
1691        assert!(
1692            parse(&["--trailing-comma", "a.bynk"])
1693                .apply_to(base)
1694                .expect("valid")
1695                .trailing_comma
1696        );
1697        // …and an unflagged run still honours the manifest.
1698        assert!(
1699            !parse(&["a.bynk"])
1700                .apply_to(base)
1701                .expect("valid")
1702                .trailing_comma
1703        );
1704    }
1705
1706    #[test]
1707    fn no_config_is_parsed_and_defaults_are_used_in_its_presence() {
1708        // `--no-config` is honoured by the manifest *lookup* (ManifestCache),
1709        // so here it is enough that it parses and leaves the flag layer alone.
1710        let args = parse(&["--no-config", "a.bynk"]);
1711        assert!(args.no_config);
1712        assert_eq!(
1713            args.apply_to(FormatOptions::default()).expect("valid"),
1714            FormatOptions::default()
1715        );
1716    }
1717
1718    /// A throwaway on-disk directory, removed on drop (including on panic) —
1719    /// mirrors `bynk-driver/tests/project_diagnostics.rs`'s own `Scratch`.
1720    struct Scratch(PathBuf);
1721    impl Drop for Scratch {
1722        fn drop(&mut self) {
1723            let _ = fs::remove_dir_all(&self.0);
1724        }
1725    }
1726
1727    fn scratch_dir(tag: &str) -> Scratch {
1728        let dir = std::env::temp_dir().join(format!(
1729            "bynk_1077_{tag}_{}_{:?}",
1730            std::process::id(),
1731            std::thread::current().id()
1732        ));
1733        let _ = fs::remove_dir_all(&dir);
1734        fs::create_dir_all(&dir).unwrap();
1735        Scratch(dir)
1736    }
1737
1738    /// #1077 review: `manifest_overlay` keys its entry exactly as
1739    /// `try_read_project_paths_with` looks it up — `root.join("bynk.toml")`,
1740    /// literal, no canonicalisation — and reads `bynk.toml`'s real content.
1741    /// This is what stops that lookup from falling through to `bynk-emit`'s
1742    /// own disk fallback; a mismatched key would silently degrade to the
1743    /// conventional layout instead of surfacing as a test failure here, so
1744    /// this asserts the map entry directly rather than only the end-to-end
1745    /// behaviour (which the integration test in `project_diagnostics.rs`
1746    /// covers).
1747    #[test]
1748    fn manifest_overlay_keys_and_reads_a_real_bynk_toml() {
1749        let dir = scratch_dir("manifest_overlay");
1750        let toml = "[paths]\ninclude = [\"lib\"]\n";
1751        fs::write(dir.0.join("bynk.toml"), toml).unwrap();
1752
1753        let overlay = manifest_overlay(&dir.0);
1754
1755        assert_eq!(
1756            overlay.get(&dir.0.join("bynk.toml")).map(String::as_str),
1757            Some(toml)
1758        );
1759    }
1760
1761    #[test]
1762    fn manifest_overlay_is_empty_with_no_bynk_toml() {
1763        let dir = scratch_dir("manifest_overlay_missing");
1764        assert!(manifest_overlay(&dir.0).is_empty());
1765    }
1766
1767    /// Review of #1084: `ProjectOptionsError::Paths` had no test anywhere in
1768    /// the repo, despite being the one arm where an overlay/disk divergence
1769    /// in the manifest read would actually be observable — everywhere else,
1770    /// `read_source`'s still-present disk fallback quietly reproduces the
1771    /// same result either way. This also re-pins that `?`'s automatic
1772    /// `From<ProjectPathsError>` conversion (not an explicit `map_err`) still
1773    /// reaches the caller correctly.
1774    #[test]
1775    fn try_project_options_surfaces_an_unknown_paths_key() {
1776        let dir = scratch_dir("try_project_options_unknown_key");
1777        fs::write(dir.0.join("bynk.toml"), "[paths]\ninculde = [\"src\"]\n").unwrap();
1778        fs::create_dir_all(dir.0.join("src")).unwrap();
1779        fs::write(dir.0.join("src/thing.bynk"), "context thing\n").unwrap();
1780
1781        let err = match try_project_options(&dir.0) {
1782            Err(e) => e,
1783            Ok(_) => panic!("an unrecognised [paths] key must be reported, not silently ignored"),
1784        };
1785        assert!(
1786            matches!(
1787                &err,
1788                ProjectOptionsError::Paths(ProjectPathsError::UnknownKey(k)) if k == "inculde"
1789            ),
1790            "expected Paths(UnknownKey(\"inculde\")), got: {err:?}"
1791        );
1792    }
1793
1794    /// #1665: an unknown table reaches the caller from the same strict path,
1795    /// even with a valid `[paths]`. Before, `[pahts]` built cleanly.
1796    #[test]
1797    fn try_project_options_surfaces_an_unknown_table() {
1798        let dir = scratch_dir("try_project_options_unknown_table");
1799        fs::write(
1800            dir.0.join("bynk.toml"),
1801            "[paths]\ninclude = [\"src\"]\n\n[pahts]\nexclude = []\n",
1802        )
1803        .unwrap();
1804        fs::create_dir_all(dir.0.join("src")).unwrap();
1805        fs::write(dir.0.join("src/thing.bynk"), "context thing\n").unwrap();
1806
1807        let err = match try_project_options(&dir.0) {
1808            Err(e) => e,
1809            Ok(_) => panic!("an unknown table must be reported, not silently ignored"),
1810        };
1811        assert!(
1812            matches!(
1813                &err,
1814                ProjectOptionsError::Paths(ProjectPathsError::UnknownTable(t)) if t == "pahts"
1815            ),
1816            "expected Paths(UnknownTable(\"pahts\")), got: {err:?}"
1817        );
1818        assert!(err.to_string().contains("did you mean `[paths]`?"), "{err}");
1819    }
1820
1821    /// A one-context project with `bynk.toml` `manifest`, for the #1890 tests.
1822    fn workers_project(name: &str, manifest: &str) -> Scratch {
1823        let dir = scratch_dir(name);
1824        fs::write(dir.0.join("bynk.toml"), manifest).unwrap();
1825        fs::create_dir_all(dir.0.join("src")).unwrap();
1826        fs::write(
1827            dir.0.join("src/greet.bynk"),
1828            "context greet\n\nservice hello {\n  on call(name: String) -> Effect[Result[String, ()]] by Caller {\n    Ok(name)\n  }\n}\n",
1829        )
1830        .unwrap();
1831        dir
1832    }
1833
1834    /// The `wrangler.toml` a Workers build of `options` writes for `greet`,
1835    /// and the build's warnings' codes.
1836    fn greet_wrangler(options: CompileOptions) -> (String, Vec<&'static str>) {
1837        let out = project::compile_project(&options.target(project::BuildTarget::Workers))
1838            .unwrap_or_else(|f| {
1839                let msgs: Vec<&str> = f.errors.iter().map(|e| e.error.message.as_str()).collect();
1840                panic!("builds: {msgs:?}")
1841            });
1842        let text = out.artefacts.docs[Path::new("workers/greet/wrangler.toml")].text();
1843        (
1844            text,
1845            out.warnings.iter().map(|w| w.error.category).collect(),
1846        )
1847    }
1848
1849    /// #1890: `[workers] compatibility_flags` reaches every emitted
1850    /// `wrangler.toml`, after the default, from both option builders. A flag
1851    /// already on by default is dropped with a warning.
1852    #[test]
1853    fn manifest_compatibility_flags_reach_wrangler_toml() {
1854        let dir = workers_project(
1855            "compat_flags_1890",
1856            "[workers]\ncompatibility_flags = [\"nodejs_compat\", \"global_fetch_strictly_public\"]\n",
1857        );
1858        let want = "compatibility_flags = [\"global_fetch_strictly_public\", \"nodejs_compat\"]\n";
1859        for options in [
1860            try_project_options(&dir.0).expect("reads"),
1861            project_options(&dir.0).expect("reads"),
1862        ] {
1863            let (text, warnings) = greet_wrangler(options);
1864            assert!(text.contains(want), "{text}");
1865            assert_eq!(
1866                warnings,
1867                ["bynk.project.duplicate_compatibility_flag"],
1868                "the repeated default is reported"
1869            );
1870        }
1871    }
1872
1873    /// `[workers] workers_dev` is written into every `wrangler.toml` when set,
1874    /// and left out when it isn't; a non-boolean is refused.
1875    #[test]
1876    fn manifest_workers_dev_reaches_wrangler_toml() {
1877        let dir = workers_project("workers_dev_off", "[workers]\nworkers_dev = false\n");
1878        for options in [
1879            try_project_options(&dir.0).expect("reads"),
1880            project_options(&dir.0).expect("reads"),
1881        ] {
1882            let (text, _) = greet_wrangler(options);
1883            assert!(text.contains("workers_dev = false\n"), "{text}");
1884        }
1885        let dir = workers_project("workers_dev_unset", "[workers]\ncompatibility_flags = []\n");
1886        let (text, _) = greet_wrangler(try_project_options(&dir.0).expect("reads"));
1887        assert!(!text.contains("workers_dev"), "{text}");
1888        let dir = workers_project("workers_dev_bad", "[workers]\nworkers_dev = \"no\"\n");
1889        assert!(matches!(
1890            try_project_options(&dir.0),
1891            Err(ProjectOptionsError::Paths(
1892                ProjectPathsError::NotABool { .. }
1893            ))
1894        ));
1895    }
1896
1897    /// #1890: with no `[workers]` table, a Worker still gets the default flag.
1898    #[test]
1899    fn a_worker_gets_the_default_compatibility_flag_without_a_workers_table() {
1900        let dir = workers_project("compat_flags_default_1890", "[project]\nname = \"p\"\n");
1901        let (text, warnings) = greet_wrangler(try_project_options(&dir.0).expect("reads"));
1902        assert!(
1903            text.contains("compatibility_flags = [\"global_fetch_strictly_public\"]\n"),
1904            "{text}"
1905        );
1906        assert!(warnings.is_empty(), "{warnings:?}");
1907    }
1908
1909    /// #1890: a non-string flag is refused on the CLIs' strict path.
1910    #[test]
1911    fn try_project_options_refuses_a_non_string_compatibility_flag() {
1912        let dir = workers_project(
1913            "compat_flags_bad_1890",
1914            "[workers]\ncompatibility_flags = [\"nodejs_compat\", 2]\n",
1915        );
1916        match try_project_options(&dir.0) {
1917            Err(ProjectOptionsError::Paths(ProjectPathsError::NotAStringList { .. })) => {}
1918            Err(e) => panic!("wrong error: {e:?}"),
1919            Ok(_) => panic!("a non-string flag must be refused"),
1920        }
1921    }
1922}
1923
1924#[cfg(test)]
1925mod display_path_tests {
1926    use super::display_path;
1927    use std::path::Path;
1928
1929    #[test]
1930    fn a_relative_root_is_joined_as_typed() {
1931        assert_eq!(
1932            display_path(Path::new("test/fixtures/x"), Path::new("src/a.bynk")),
1933            "test/fixtures/x/src/a.bynk"
1934        );
1935    }
1936
1937    /// `bynk check` defaults its input to `.`; that adds no `./`.
1938    #[test]
1939    fn a_dot_root_adds_no_prefix() {
1940        assert_eq!(
1941            display_path(Path::new("."), Path::new("src/a.bynk")),
1942            "src/a.bynk"
1943        );
1944        assert_eq!(
1945            display_path(Path::new(""), Path::new("./src/a.bynk")),
1946            "src/a.bynk"
1947        );
1948    }
1949
1950    /// `bynk dev` hands an absolute root; inside the cwd it shows relative.
1951    #[test]
1952    fn an_absolute_root_inside_the_cwd_is_shown_relative() {
1953        let cwd = std::env::current_dir().unwrap();
1954        assert_eq!(
1955            display_path(&cwd.join("proj"), Path::new("src/a.bynk")),
1956            "proj/src/a.bynk"
1957        );
1958        // A canonicalised root (on Windows, a verbatim `\\?\` path) too.
1959        let canonical = cwd.canonicalize().unwrap();
1960        assert_eq!(
1961            display_path(&canonical.join("proj"), Path::new("src/a.bynk")),
1962            "proj/src/a.bynk"
1963        );
1964    }
1965
1966    /// Outside the cwd, the path stays absolute, with `/` separators.
1967    #[test]
1968    fn an_absolute_root_outside_the_cwd_is_shown_absolute() {
1969        let cwd = std::env::current_dir().unwrap();
1970        let outside = cwd.parent().unwrap().join("bynk-display-path-elsewhere");
1971        let shown = display_path(&outside, Path::new("src/a.bynk"));
1972        assert!(
1973            shown.ends_with("bynk-display-path-elsewhere/src/a.bynk"),
1974            "{shown}"
1975        );
1976        assert!(
1977            !shown.contains('\\') && !shown.starts_with("//?/"),
1978            "{shown}"
1979        );
1980    }
1981
1982    /// On Windows, a verbatim root outside the cwd loses its `\\?\` prefix.
1983    #[cfg(windows)]
1984    #[test]
1985    fn a_verbatim_root_outside_the_cwd_loses_its_prefix() {
1986        assert_eq!(
1987            display_path(Path::new(r"\\?\C:\elsewhere"), Path::new("src/a.bynk")),
1988            "C:/elsewhere/src/a.bynk"
1989        );
1990    }
1991}