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