Skip to main content

bynk_driver/
lib.rs

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