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