1use std::collections::HashMap;
10use std::fs;
11use std::path::{Path, PathBuf};
12use std::process::ExitCode;
13
14use bynk_fmt::{FormatOptions, IndentStyle, format_source};
15use project::{CompileOptions, ProjectPathsError, try_read_project_paths_with};
16use render::LabelHome;
17
18pub mod colour;
19pub mod compile_cmd;
20pub mod contracts_lock;
21pub mod coverage;
22pub mod dev_run;
23pub mod discovery;
24pub mod doc_examples;
25pub mod eval;
26pub mod fix;
27pub mod mutate;
28pub mod npm_install;
29pub mod output;
30pub mod probe;
31pub mod progress;
32pub mod project;
33pub mod remote;
34pub mod render;
35pub mod schema_lock;
36pub mod smoke;
37pub mod snapshots;
38pub mod source_overlay;
39pub mod strip;
40pub mod test_filter;
41pub mod test_json;
42pub mod test_runner;
43pub mod test_stream;
44pub mod tools;
45pub mod tsc_report;
46
47pub use compile_cmd::{
48 BuildArgs, CliPlatform, CliProfile, CliTarget, CompileArgs, EmitFormat, profile_contracts,
49 project_contracts, refuse_release_contracts, refuse_undeployable_project, run_build,
50 run_compile,
51};
52pub use output::{write_document, write_modules, write_modules_for_node, write_output};
53
54pub fn project_options(input: &Path) -> Result<CompileOptions, discovery::DiscoveryError> {
70 if input.join("bynk.toml").exists() || input.join("src").is_dir() {
71 let overlay = manifest_overlay(input);
72 let paths = try_read_project_paths_with(input, &overlay)
73 .unwrap_or_else(|_| project::ProjectPaths::conventional(input));
74 let workers = project::try_read_workers_config_with(input, &overlay).unwrap_or_default();
76 Ok(options_for_split(input, paths)?
77 .compatibility_flags(workers.compatibility_flags)
78 .workers_dev(workers.workers_dev)
79 .asset_files(discovery::list_asset_folder(input)?)
80 .embed_files(discovery::list_embed_folder(input)?)
81 .fixture_files(discovery::list_fixture_folder(input)?)
82 .migration_files(discovery::list_migration_folder(input)?))
83 } else {
84 let sources = discovery::read_bynk_tree_single(input)?;
85 Ok(CompileOptions::single(input.to_path_buf())
86 .sources(sources)
87 .asset_files(discovery::list_asset_folder(input)?)
88 .embed_files(discovery::list_embed_folder(input)?)
89 .fixture_files(discovery::list_fixture_folder(input)?)
90 .migration_files(discovery::list_migration_folder(input)?))
91 }
92}
93
94pub fn try_project_options(input: &Path) -> Result<CompileOptions, ProjectOptionsError> {
104 let asset_files = discovery::list_asset_folder(input)?;
108 let embed_files = discovery::list_embed_folder(input)?;
110 let fixture_files = discovery::list_fixture_folder(input)?;
112 let migration_files = discovery::list_migration_folder(input)?;
114 let contracts_lock = contracts_lock::read(input).map_err(|e| {
119 ProjectOptionsError::ContractsLock(format!(
120 "could not read {}: {e}",
121 contracts_lock::lock_path(input).display()
122 ))
123 })?;
124 Ok(match project_sources(input, Projects::Separate)? {
125 (Some(paths), sources) => {
126 let workers = project::try_read_workers_config_with(input, &manifest_overlay(input))?;
127 CompileOptions::split(input.to_path_buf(), paths)
128 .sources(sources)
129 .compatibility_flags(workers.compatibility_flags)
130 .workers_dev(workers.workers_dev)
131 .asset_files(asset_files)
132 .embed_files(embed_files)
133 .fixture_files(fixture_files)
134 .migration_files(migration_files.clone())
135 .contracts_lock(contracts_lock)
136 }
137 (None, sources) => CompileOptions::single(input.to_path_buf())
138 .sources(sources)
139 .asset_files(asset_files)
140 .embed_files(embed_files)
141 .fixture_files(fixture_files)
142 .migration_files(migration_files)
143 .contracts_lock(contracts_lock),
144 })
145}
146
147pub fn project_source_files(input: &Path) -> Result<Vec<PathBuf>, ProjectOptionsError> {
152 let (_, sources) = project_sources(input, Projects::Separate)?;
153 let mut files: Vec<PathBuf> = sources.into_keys().collect();
154 files.sort();
155 Ok(files)
156}
157
158fn fmt_source_files(input: &Path) -> Result<Vec<PathBuf>, ProjectOptionsError> {
163 let (_, sources) = project_sources(input, Projects::AsOneTree)?;
164 let mut files: Vec<PathBuf> = sources.into_keys().collect();
165 files.sort();
166 Ok(files)
167}
168
169#[derive(Clone, Copy, PartialEq, Eq)]
172enum Projects {
173 Separate,
177 AsOneTree,
179}
180
181fn project_sources(
187 input: &Path,
188 projects: Projects,
189) -> Result<(Option<project::ProjectPaths>, HashMap<PathBuf, String>), ProjectOptionsError> {
190 if input.join("bynk.toml").exists() || input.join("src").is_dir() {
191 let overlay = manifest_overlay(input);
192 project::check_manifest(input, &overlay)?;
195 if project::is_workspace_root(input) {
198 return Err(ProjectPathsError::WorkspaceRoot.into());
199 }
200 let paths = try_read_project_paths_with(input, &overlay)?;
201 let sources = split_sources(input, &paths, projects)?;
202 if projects == Projects::Separate {
203 note_skipped_projects(
204 input,
205 &project::Roots::Split {
206 project_root: input.to_path_buf(),
207 paths: paths.clone(),
208 },
209 );
210 }
211 Ok((Some(paths), sources))
212 } else if projects == Projects::AsOneTree {
213 Ok((None, discovery::read_bynk_tree_across_projects(input)?))
214 } else {
215 let nested = bynk_project::nested_projects(input, &[]);
220 if !nested.is_empty() && !has_manifest_above(input) {
221 return Err(ProjectOptionsError::NestedProjects {
222 root: input.to_path_buf(),
223 projects: nested,
224 });
225 }
226 let sources = discovery::read_bynk_tree_single(input)?;
227 note_skipped_nested_projects(input, &nested);
228 Ok((None, sources))
229 }
230}
231
232fn has_manifest_above(dir: &Path) -> bool {
235 let Ok(abs) = dir.canonicalize() else {
236 return false;
237 };
238 abs.ancestors()
239 .skip(1)
240 .any(|a| a.join("bynk.toml").is_file())
241}
242
243fn note_skipped_nested_projects(root: &Path, nested: &[PathBuf]) {
246 static SAID: std::sync::Mutex<Option<std::collections::HashSet<PathBuf>>> =
247 std::sync::Mutex::new(None);
248 for project in nested {
249 if !bynk_project::holds_bynk_source(project) {
250 continue;
251 }
252 let first = SAID
253 .lock()
254 .unwrap_or_else(|e| e.into_inner())
255 .get_or_insert_with(Default::default)
256 .insert(project.clone());
257 if first {
258 crate::emsg!(
259 "bynk: note: skipped `{}`: it has its own bynk.toml, so it is a separate project; run the command inside it",
260 shown(project.strip_prefix(root).map_or(project.as_path(), |p| p))
261 );
262 }
263 }
264}
265
266fn note_skipped_projects(root: &Path, roots: &project::Roots) {
269 let excludes = roots.excludes();
270 let mut nested: Vec<PathBuf> = Vec::new();
271 for (tree, _) in roots.trees() {
272 nested.extend(bynk_project::nested_projects(&tree, &excludes));
273 }
274 nested.sort();
275 nested.dedup();
276 note_skipped_nested_projects(root, &nested);
277}
278
279fn manifest_overlay(input: &Path) -> HashMap<PathBuf, String> {
293 let toml_path = input.join("bynk.toml");
294 match fs::read_to_string(&toml_path) {
295 Ok(text) => HashMap::from([(toml_path, text)]),
296 Err(_) => HashMap::new(),
297 }
298}
299
300fn options_for_split(
304 input: &Path,
305 paths: project::ProjectPaths,
306) -> Result<CompileOptions, discovery::DiscoveryError> {
307 let sources = split_sources(input, &paths, Projects::Separate)?;
308 Ok(CompileOptions::split(input.to_path_buf(), paths).sources(sources))
309}
310
311fn split_sources(
318 input: &Path,
319 paths: &project::ProjectPaths,
320 projects: Projects,
321) -> Result<HashMap<PathBuf, String>, discovery::DiscoveryError> {
322 let roots = project::Roots::Split {
323 project_root: input.to_path_buf(),
324 paths: paths.clone(),
325 };
326 match projects {
327 Projects::Separate => discovery::sources_for_roots(&roots),
328 Projects::AsOneTree => discovery::sources_for_roots_across_projects(&roots),
329 }
330}
331
332#[derive(Debug)]
337pub enum ProjectOptionsError {
338 Paths(ProjectPathsError),
339 Discovery(discovery::DiscoveryError),
340 ContractsLock(String),
342 NestedProjects {
345 root: PathBuf,
346 projects: Vec<PathBuf>,
347 },
348}
349
350impl std::fmt::Display for ProjectOptionsError {
351 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
352 match self {
353 Self::Paths(e) => write!(f, "{e}"),
354 Self::Discovery(e) => write!(f, "{e}"),
355 Self::ContractsLock(e) => write!(f, "{e}"),
356 Self::NestedProjects { root, projects } => {
357 write!(f, "{}", nested_projects_message(root, projects, true))
358 }
359 }
360 }
361}
362
363impl ProjectOptionsError {
364 pub fn render(&self, each_applies: bool) -> String {
369 match self {
370 Self::NestedProjects { root, projects } => {
371 nested_projects_message(root, projects, each_applies)
372 }
373 other => other.to_string(),
374 }
375 }
376}
377
378fn nested_projects_message(root: &Path, projects: &[PathBuf], each_applies: bool) -> String {
380 const SHOWN: usize = 5;
381 let names: Vec<String> = projects
382 .iter()
383 .take(SHOWN)
384 .map(|p| format!("`{}`", shown(p.strip_prefix(root).unwrap_or(p))))
385 .collect();
386 let more = projects.len().saturating_sub(SHOWN);
387 format!(
388 "`{}` is not a project (no `bynk.toml` here or above) but holds {} that have their own: {}{}.\n\
389 Run the command inside one of them, {}or add a `bynk.toml` here with\n\
390 \n [workspace]\n members = [\"*\"]\n\n\
391 to {}",
392 dir_label(root),
393 if projects.len() == 1 {
394 "a project".to_string()
395 } else {
396 format!("{} projects", projects.len())
397 },
398 names.join(", "),
399 if more > 0 {
400 format!(" and {more} more")
401 } else {
402 String::new()
403 },
404 if each_applies {
405 "pass `--each` to run it over each, "
406 } else {
407 ""
408 },
409 if each_applies {
410 "keep that choice in the repository"
411 } else {
412 "run it over each"
413 },
414 )
415}
416
417fn dir_label(dir: &Path) -> String {
419 match shown(dir) {
420 s if s.is_empty() => ".".to_string(),
421 s => s,
422 }
423}
424
425impl std::error::Error for ProjectOptionsError {
426 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
427 match self {
428 Self::Paths(_) | Self::ContractsLock(_) | Self::NestedProjects { .. } => None,
431 Self::Discovery(e) => Some(e),
432 }
433 }
434}
435
436impl From<ProjectPathsError> for ProjectOptionsError {
437 fn from(e: ProjectPathsError) -> Self {
438 Self::Paths(e)
439 }
440}
441
442impl From<discovery::DiscoveryError> for ProjectOptionsError {
443 fn from(e: discovery::DiscoveryError) -> Self {
444 Self::Discovery(e)
445 }
446}
447
448pub fn print_project_failure(failure: &project::ProjectFailure) {
457 for ae in failure.errors.iter().filter(|ae| !is_hint(ae)) {
458 match attributed_snapshot(ae, &failure.snapshots, &failure.display_root) {
459 Some((label, text)) => {
460 print_attributed(ae, &label, text, &failure.snapshots, &failure.display_root);
461 }
462 None => {
463 eprintln!("[{}] {}", ae.error.category, ae.error.message);
464 for note in &ae.error.notes {
465 crate::emsg!(" note: {note}");
466 }
467 for (_, label) in &ae.error.labels {
470 eprintln!(" label: {label}");
471 }
472 }
473 }
474 }
475}
476
477fn is_hint(ae: &project::AttributedError) -> bool {
480 bynk_syntax::Severity::for_error(&ae.error) == bynk_syntax::Severity::Hint
481}
482
483pub fn print_project_warnings(
489 warnings: &[project::AttributedError],
490 snapshots: &[(PathBuf, String)],
491 display_root: &Path,
492) {
493 for w in warnings.iter().filter(|w| !is_hint(w)) {
494 match attributed_snapshot(w, snapshots, display_root) {
495 Some((label, text)) => print_attributed(w, &label, text, snapshots, display_root),
496 None => {
497 let where_ = w
498 .source_path
499 .as_deref()
500 .map(|p| format!("{}: ", p.to_string_lossy().replace('\\', "/")))
501 .unwrap_or_default();
502 eprintln!("{where_}warning[{}]: {}", w.error.category, w.error.message);
503 for note in &w.error.notes {
504 crate::emsg!(" note: {note}");
505 }
506 for (_, label) in &w.error.labels {
507 eprintln!(" label: {label}");
508 }
509 }
510 }
511 }
512}
513
514pub fn print_project_warnings_short(
521 warnings: &[project::AttributedError],
522 snapshots: &[(PathBuf, String)],
523 display_root: &Path,
524) {
525 for w in warnings.iter().filter(|w| !is_hint(w)) {
526 match attributed_snapshot(w, snapshots, display_root) {
527 Some((label, text)) => {
528 eprintln!("{}", crate::render::short_line(&label, text, &w.error))
529 }
530 None => eprintln!(
535 "{}[{}]: {}",
536 crate::render::severity_word(&w.error),
537 w.error.category,
538 w.error.message
539 ),
540 }
541 }
542}
543
544fn attributed_snapshot<'a>(
553 ae: &project::AttributedError,
554 snapshots: &'a [(PathBuf, String)],
555 display_root: &Path,
556) -> Option<(String, &'a str)> {
557 let path = ae.source_path.as_deref()?;
558 let text = snapshots
559 .iter()
560 .find(|(p, _)| p.as_path() == path)
561 .map(|(_, t)| t.as_str())?;
562 Some((display_path(display_root, path), text))
563}
564
565fn print_attributed(
574 ae: &project::AttributedError,
575 label: &str,
576 text: &str,
577 snapshots: &[(PathBuf, String)],
578 display_root: &Path,
579) {
580 let others: Vec<Option<(String, &str)>> = (0..ae.error.labels.len())
581 .map(|i| match ae.label_file(i) {
582 project::LabelFile::Other(path) => snapshots
583 .iter()
584 .find(|(p, _)| p == path)
585 .map(|(_, t)| (display_path(display_root, path), t.as_str())),
586 project::LabelFile::FirstParty {
587 identity_path,
588 source,
589 } => Some(((*identity_path).to_string(), *source)),
590 _ => None,
591 })
592 .collect();
593 let homes: Vec<LabelHome<'_>> = others
594 .iter()
595 .enumerate()
596 .map(|(i, other)| match (ae.label_file(i), other) {
597 (project::LabelFile::Primary, _) => LabelHome::Primary,
598 (_, Some((filename, source))) => LabelHome::File { filename, source },
599 (_, None) => LabelHome::Unavailable,
600 })
601 .collect();
602 crate::render::print_error_in(&ae.error, text, label, &homes, crate::colour::stderr());
603}
604
605pub fn display_path(display_root: &Path, identity: &Path) -> String {
621 use std::path::Component;
622 let joined: PathBuf = display_root
623 .join(identity)
624 .components()
625 .filter(|c| !matches!(c, Component::CurDir))
626 .collect();
627 let shown = if joined.is_absolute() {
628 let cwd = std::env::current_dir().ok();
629 let canonical_cwd = cwd.as_ref().and_then(|c| c.canonicalize().ok());
630 cwd.iter()
631 .chain(canonical_cwd.iter())
632 .find_map(|base| joined.strip_prefix(base).ok().map(Path::to_path_buf))
633 .unwrap_or(joined)
634 } else {
635 joined
636 };
637 let text = shown.to_string_lossy().replace('\\', "/");
638 if let Some(unc) = text.strip_prefix("//?/UNC/") {
640 format!("//{unc}")
641 } else if let Some(rest) = text.strip_prefix("//?/") {
642 rest.to_string()
643 } else {
644 text
645 }
646}
647
648fn shown(path: &Path) -> String {
653 display_path(Path::new(""), path)
654}
655
656pub fn print_project_failure_short(failure: &project::ProjectFailure) {
660 for ae in failure.errors.iter().filter(|ae| !is_hint(ae)) {
663 eprintln!("{}", failure_short_line(failure, ae));
664 }
665}
666
667pub fn project_failure_short_lines(failure: &project::ProjectFailure) -> Vec<String> {
681 failure
682 .errors
683 .iter()
684 .map(|ae| failure_short_line(failure, ae))
685 .collect()
686}
687
688fn failure_short_line(failure: &project::ProjectFailure, ae: &project::AttributedError) -> String {
690 match attributed_snapshot(ae, &failure.snapshots, &failure.display_root) {
691 Some((label, text)) => crate::render::short_line(&label, text, &ae.error),
692 None => format!(
693 "{}[{}]: {}",
694 crate::render::severity_word(&ae.error),
695 ae.error.category,
696 ae.error.message
697 ),
698 }
699}
700
701pub fn print_project_check(check: &project::ProjectCheck) {
709 for ae in check.errors.iter().filter(|ae| !is_hint(ae)) {
710 match attributed_snapshot(ae, &check.snapshots, &check.display_root) {
711 Some((label, text)) => {
712 print_attributed(ae, &label, text, &check.snapshots, &check.display_root);
713 }
714 None => {
715 eprintln!(
716 "{}[{}]: {}",
717 crate::render::severity_word(&ae.error),
718 ae.error.category,
719 ae.error.message
720 );
721 for note in &ae.error.notes {
722 crate::emsg!(" note: {note}");
723 }
724 for (_, label) in &ae.error.labels {
725 eprintln!(" label: {label}");
726 }
727 }
728 }
729 }
730}
731
732pub fn project_check_short_lines(check: &project::ProjectCheck) -> Vec<String> {
735 check
736 .errors
737 .iter()
738 .filter(|ae| !is_hint(ae))
739 .map(
740 |ae| match attributed_snapshot(ae, &check.snapshots, &check.display_root) {
741 Some((label, text)) => crate::render::short_line(&label, text, &ae.error),
742 None => format!(
743 "{}[{}]: {}",
744 crate::render::severity_word(&ae.error),
745 ae.error.category,
746 ae.error.message
747 ),
748 },
749 )
750 .collect()
751}
752
753pub fn print_project_check_short(check: &project::ProjectCheck) {
755 for line in project_check_short_lines(check) {
756 eprintln!("{line}");
757 }
758}
759
760#[derive(clap::ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
764pub enum IndentKind {
765 Tab,
768 Spaces,
770}
771
772#[derive(clap::Args, Debug)]
784pub struct FmtArgs {
785 pub inputs: Vec<PathBuf>,
790 #[arg(long)]
793 pub check: bool,
794 #[arg(long, value_enum)]
797 pub indent: Option<IndentKind>,
798 #[arg(long, value_name = "N", value_parser = clap::value_parser!(u8).range(0..=64))]
802 pub indent_width: Option<u8>,
803 #[arg(long, value_name = "COLUMNS", value_parser = clap::value_parser!(u32).range(1..))]
808 pub max_line_width: Option<u32>,
809 #[arg(long, overrides_with = "no_trailing_comma")]
813 pub trailing_comma: bool,
814 #[arg(long, overrides_with = "trailing_comma")]
818 pub no_trailing_comma: bool,
819 #[arg(long)]
823 pub no_config: bool,
824}
825
826impl FmtArgs {
827 pub fn apply_to(&self, base: FormatOptions) -> Result<FormatOptions, String> {
831 let base_width = match base.indent {
835 IndentStyle::Spaces(n) => Some(n),
836 IndentStyle::Tab => None,
837 };
838 let kind = self.indent.unwrap_or(match base.indent {
839 IndentStyle::Tab => IndentKind::Tab,
840 IndentStyle::Spaces(_) => IndentKind::Spaces,
841 });
842 let indent = match (kind, self.indent_width) {
843 (IndentKind::Tab, None) => IndentStyle::Tab,
844 (IndentKind::Tab, Some(_)) => {
849 return Err(
850 "`--indent-width` applies only to spaces indentation, and this run resolves \
851 to tabs (pass `--indent spaces`, or set `[fmt] indent` in bynk.toml)"
852 .to_string(),
853 );
854 }
855 (IndentKind::Spaces, width) => IndentStyle::Spaces(width.or(base_width).unwrap_or(2)),
858 };
859 Ok(FormatOptions {
860 indent,
861 max_line_width: self.max_line_width.unwrap_or(base.max_line_width),
862 trailing_comma: if self.no_trailing_comma {
865 false
866 } else if self.trailing_comma {
867 true
868 } else {
869 base.trailing_comma
870 },
871 })
872 }
873}
874
875enum FmtOptionsError {
877 Manifest(PathBuf, bynk_fmt::ConfigError),
879 ManifestTables(PathBuf, project::ProjectPathsError),
882 Args(String),
884}
885
886impl std::fmt::Display for FmtOptionsError {
887 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
888 match self {
889 Self::Manifest(path, e) => write!(f, "{}: {e}", path.display()),
892 Self::ManifestTables(path, e) => write!(f, "{}: {e}", path.display()),
893 Self::Args(e) => write!(f, "{e}"),
894 }
895 }
896}
897
898struct ManifestCache {
904 disabled: bool,
906 by_dir: std::collections::HashMap<PathBuf, FormatOptions>,
907}
908
909impl ManifestCache {
910 fn new(disabled: bool) -> Self {
911 Self {
912 disabled,
913 by_dir: std::collections::HashMap::new(),
914 }
915 }
916
917 fn options_for(&mut self, input: &Path) -> Result<FormatOptions, FmtOptionsError> {
919 if self.disabled {
920 return Ok(FormatOptions::default());
921 }
922 let start: PathBuf = if input.as_os_str() == "-" {
925 PathBuf::from(".")
926 } else {
927 match input.parent() {
928 Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
930 _ => PathBuf::from("."),
931 }
932 };
933 let start = std::env::current_dir()
945 .map(|cwd| cwd.join(&start))
946 .unwrap_or(start);
947 if let Some(hit) = self.by_dir.get(&start) {
948 return Ok(*hit);
949 }
950 let opts = match bynk_fmt::find_manifest(&start) {
951 None => FormatOptions::default(),
952 Some(manifest) => {
953 let text = std::fs::read_to_string(&manifest).map_err(|e| {
954 FmtOptionsError::Manifest(
955 manifest.clone(),
956 bynk_fmt::ConfigError::Read(e.to_string()),
957 )
958 })?;
959 let config = bynk_fmt::FmtConfig::from_manifest_str(&text)
962 .map_err(|e| FmtOptionsError::Manifest(manifest.clone(), e))?;
963 let options = config.apply(FormatOptions::default());
964 let root = manifest.parent().unwrap_or(Path::new("."));
967 project::check_manifest(root, &HashMap::from([(root.join("bynk.toml"), text)]))
968 .map_err(|e| FmtOptionsError::ManifestTables(manifest, e))?;
969 options
970 }
971 };
972 self.by_dir.insert(start, opts);
973 Ok(opts)
974 }
975}
976
977pub fn run_fmt(prog: &str, args: &FmtArgs) -> ExitCode {
982 let check = args.check;
983 if args.inputs.is_empty() {
984 crate::emsg!(
985 "{prog} fmt: error: no input files (pass file or directory paths, or `-` for stdin)"
986 );
987 return ExitCode::FAILURE;
988 }
989 let inputs = match expand_fmt_inputs(&args.inputs) {
990 Ok(inputs) => inputs,
991 Err(e) => {
992 crate::emsg!("{prog} fmt: error: {e}");
993 return ExitCode::FAILURE;
994 }
995 };
996 let inputs = &inputs;
997 let mut manifests = ManifestCache::new(args.no_config);
1004 let mut resolved: Vec<FormatOptions> = Vec::with_capacity(inputs.len());
1005 for input in inputs {
1006 match manifests
1007 .options_for(input)
1008 .and_then(|base| args.apply_to(base).map_err(FmtOptionsError::Args))
1009 {
1010 Ok(opts) => resolved.push(opts),
1011 Err(e) => {
1012 crate::emsg!("{prog} fmt: error: {e}");
1013 return ExitCode::FAILURE;
1014 }
1015 }
1016 }
1017
1018 let mut had_diff = false;
1019 let mut had_error = false;
1020 for (input, opts) in inputs.iter().zip(resolved) {
1021 if input.as_os_str() == "-" {
1022 use std::io::Read;
1023 let mut source = String::new();
1024 if let Err(e) = std::io::stdin().read_to_string(&mut source) {
1025 crate::emsg!("{prog} fmt: error: read from stdin: {e}");
1026 return ExitCode::FAILURE;
1027 }
1028 let source = bynk_fmt::normalize_line_endings(&source);
1030 match format_source(&source, &opts) {
1031 Ok(formatted) => {
1032 if check {
1033 if formatted != source {
1039 crate::emsg!("{prog} fmt: error: <stdin> is not canonically formatted");
1040 had_diff = true;
1041 }
1042 } else {
1043 print!("{formatted}");
1044 }
1045 }
1046 Err(e) => {
1047 crate::render::print_errors(
1048 &e.errors,
1049 &source,
1050 "<stdin>",
1051 crate::colour::stderr(),
1052 );
1053 return ExitCode::FAILURE;
1054 }
1055 }
1056 continue;
1057 }
1058 let raw = match std::fs::read_to_string(input) {
1059 Ok(s) => s,
1060 Err(e) => {
1061 crate::emsg!("{prog} fmt: error: read `{}`: {e}", shown(input));
1062 had_error = true;
1063 continue;
1064 }
1065 };
1066 let source = bynk_fmt::normalize_line_endings(&raw);
1071 let filename = shown(input);
1072 match format_source(&source, &opts) {
1073 Ok(formatted) => {
1074 if check {
1075 if formatted != source {
1076 crate::emsg!(
1077 "{prog} fmt: error: {} is not canonically formatted",
1078 filename
1079 );
1080 had_diff = true;
1081 }
1082 } else if formatted != source
1083 && let Err(e) = atomic_write(input, &formatted)
1084 {
1085 crate::emsg!("{prog} fmt: error: write `{}`: {e}", filename);
1086 had_error = true;
1087 }
1088 }
1089 Err(e) => {
1090 crate::render::print_errors(&e.errors, &source, &filename, crate::colour::stderr());
1091 had_error = true;
1092 }
1093 }
1094 }
1095 if had_error || (check && had_diff) {
1096 ExitCode::FAILURE
1097 } else {
1098 ExitCode::SUCCESS
1099 }
1100}
1101
1102fn expand_fmt_inputs(inputs: &[PathBuf]) -> Result<Vec<PathBuf>, String> {
1113 let mut out = Vec::new();
1114 let mut seen = std::collections::HashSet::new();
1115 for input in inputs {
1116 if input.as_os_str() != "-"
1119 && let Some(workspace) = workspace_at(input)
1120 {
1121 let workspace = workspace.map_err(|e| format!("`{}`: {e}", input.display()))?;
1122 for member in &workspace.members {
1123 let member = member_dir(input, member);
1124 let files =
1125 fmt_source_files(&member).map_err(|e| format!("`{}`: {e}", shown(&member)))?;
1126 for file in files {
1127 let key = std::fs::canonicalize(&file).unwrap_or_else(|_| file.clone());
1128 if seen.insert(key) {
1129 out.push(file);
1130 }
1131 }
1132 }
1133 continue;
1134 }
1135 let files = if input.as_os_str() != "-" && input.is_dir() {
1136 let files =
1137 fmt_source_files(input).map_err(|e| format!("`{}`: {e}", input.display()))?;
1138 if files.is_empty() {
1139 return Err(format!("no `.bynk` files under `{}`", input.display()));
1140 }
1141 files
1142 } else {
1143 vec![input.clone()]
1144 };
1145 for file in files {
1146 let key = std::fs::canonicalize(&file).unwrap_or_else(|_| file.clone());
1147 if seen.insert(key) {
1148 out.push(file);
1149 }
1150 }
1151 }
1152 Ok(out)
1153}
1154
1155fn atomic_write(path: &Path, contents: &str) -> std::io::Result<()> {
1177 use std::io::Write as _;
1178 use std::sync::atomic::{AtomicU64, Ordering};
1179
1180 static COUNTER: AtomicU64 = AtomicU64::new(0);
1181
1182 let dir = path.parent().filter(|p| !p.as_os_str().is_empty());
1183 let file_name = path
1184 .file_name()
1185 .map(|n| n.to_string_lossy().into_owned())
1186 .unwrap_or_default();
1187
1188 let (mut file, tmp) = loop {
1191 let n = COUNTER.fetch_add(1, Ordering::Relaxed);
1192 let tmp_name = format!(".{file_name}.bynk-fmt.{}.{n}.tmp", std::process::id());
1193 let tmp = match dir {
1194 Some(d) => d.join(tmp_name),
1195 None => PathBuf::from(tmp_name),
1196 };
1197 match std::fs::OpenOptions::new()
1198 .write(true)
1199 .create_new(true)
1200 .open(&tmp)
1201 {
1202 Ok(f) => break (f, tmp),
1203 Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
1204 Err(e) => return Err(e),
1205 }
1206 };
1207
1208 let write_result = (|| {
1214 if let Ok(meta) = std::fs::metadata(path) {
1217 let _ = file.set_permissions(meta.permissions());
1218 }
1219 file.write_all(contents.as_bytes())?;
1220 file.sync_all()
1221 })();
1222 if let Err(e) = write_result {
1223 let _ = std::fs::remove_file(&tmp);
1224 return Err(e);
1225 }
1226 if let Err(e) = std::fs::rename(&tmp, path) {
1227 let _ = std::fs::remove_file(&tmp);
1228 return Err(e);
1229 }
1230 Ok(())
1231}
1232
1233pub fn run_check(
1249 prog: &str,
1250 input: &Path,
1251 short: bool,
1252 fix: Option<&[String]>,
1253 each: bool,
1254) -> ExitCode {
1255 let scope = match fix.map(fix::Scope::codes).transpose() {
1256 Ok(scope) => scope,
1257 Err(message) => {
1258 crate::emsg!("{prog}: error: --fix: {message}");
1259 return ExitCode::FAILURE;
1260 }
1261 };
1262 let workspace = match workspace_at_each(input, each) {
1268 Ok(w) => w,
1269 Err(message) => {
1270 crate::emsg!("{prog}: error: {message}");
1271 return ExitCode::FAILURE;
1272 }
1273 };
1274 if let Some(workspace) = workspace {
1275 let workspace = match workspace {
1276 Ok(w) => w,
1277 Err(e) => {
1278 crate::emsg!("{prog}: error: {}: {e}", shown(&input.join("bynk.toml")));
1279 return ExitCode::FAILURE;
1280 }
1281 };
1282 let members: Vec<PathBuf> = workspace
1283 .members
1284 .iter()
1285 .map(|m| member_dir(input, m))
1286 .collect();
1287 let mut failed = false;
1290 if let Some(scope) = &scope {
1291 let named: Vec<(&Path, String)> = members
1292 .iter()
1293 .map(|m| (m.as_path(), format!("{prog}: {}", shown(m))))
1294 .collect();
1295 failed |= !fix::fix_all(prog, scope, &named);
1296 }
1297 for member in &members {
1298 if !short {
1299 eprintln!("{}", member_header(member));
1300 }
1301 failed |= !check_one(prog, member, short, Some(member));
1302 }
1303 return if failed {
1304 ExitCode::FAILURE
1305 } else {
1306 ExitCode::SUCCESS
1307 };
1308 }
1309 let fixed = scope
1310 .as_ref()
1311 .is_none_or(|scope| fix::fix_all(prog, scope, &[(input, prog.to_string())]));
1312 if check_one(prog, input, short, None) && fixed {
1313 ExitCode::SUCCESS
1314 } else {
1315 ExitCode::FAILURE
1316 }
1317}
1318
1319pub fn workspace_at(input: &Path) -> Option<Result<project::Workspace, ProjectPathsError>> {
1322 (input.is_dir() && project::is_workspace_root(input)).then(|| project::load_workspace(input))
1323}
1324
1325pub fn workspace_at_each(
1337 input: &Path,
1338 each: bool,
1339) -> Result<Option<Result<project::Workspace, ProjectPathsError>>, String> {
1340 if !each || project::is_workspace_root(input) {
1341 return Ok(workspace_at(input));
1342 }
1343 let name = dir_label(input);
1344 if !input.is_dir() {
1345 return Err(format!(
1346 "`--each` takes a directory of projects, not `{name}`"
1347 ));
1348 }
1349 if input.join("bynk.toml").exists() || input.join("src").is_dir() {
1350 return Err(format!(
1351 "`--each` applies to a directory of projects, but `{name}` is a project: run the command without it"
1352 ));
1353 }
1354 if has_manifest_above(input) {
1355 return Err(format!(
1356 "`--each` applies to a directory of projects, but `{name}` is inside a project (a `bynk.toml` is above it): run the command without it"
1357 ));
1358 }
1359 match bynk_project::implicit_workspace(input) {
1360 Ok(implicit) => {
1361 for dir in &implicit.skipped {
1362 note_skipped_manifestless(input, dir);
1363 }
1364 Ok(Some(Ok(implicit.workspace)))
1365 }
1366 Err(bynk_project::ImplicitWorkspaceError::RootSources) => Err(format!(
1367 "`{name}` holds `.bynk` files of its own, which no project under it would read: move them into a project, or drop `--each`"
1368 )),
1369 Err(bynk_project::ImplicitWorkspaceError::NoProjects { deeper }) => {
1370 if deeper.is_empty() {
1371 Err(format!(
1372 "`{name}` holds no project: no subdirectory of it has a `bynk.toml`"
1373 ))
1374 } else {
1375 let shown_deeper: Vec<String> = deeper
1376 .iter()
1377 .take(5)
1378 .map(|p| format!("`{}`", shown(p.strip_prefix(input).unwrap_or(p))))
1379 .collect();
1380 let more = deeper.len().saturating_sub(5);
1381 Err(format!(
1382 "`{name}` holds no project directly inside it, but {} further down: {}{}.\n\
1383 `--each` runs the projects directly inside a directory: pass the directory that holds them",
1384 if deeper.len() == 1 {
1385 "one".to_string()
1386 } else {
1387 format!("{}", deeper.len())
1388 },
1389 shown_deeper.join(", "),
1390 if more > 0 {
1391 format!(" and {more} more")
1392 } else {
1393 String::new()
1394 }
1395 ))
1396 }
1397 }
1398 }
1399}
1400
1401fn note_skipped_manifestless(root: &Path, dir: &Path) {
1404 static SAID: std::sync::Mutex<Option<std::collections::HashSet<PathBuf>>> =
1405 std::sync::Mutex::new(None);
1406 let key = root.join(dir);
1407 let first = SAID
1408 .lock()
1409 .unwrap_or_else(|e| e.into_inner())
1410 .get_or_insert_with(Default::default)
1411 .insert(key);
1412 if first {
1413 crate::emsg!(
1414 "bynk: note: skipped `{}`: it has no bynk.toml, so it is not a project",
1415 shown(dir)
1416 );
1417 }
1418}
1419
1420pub fn member_dir(root: &Path, member: &Path) -> PathBuf {
1424 root.join(member)
1425 .components()
1426 .filter(|c| !matches!(c, std::path::Component::CurDir))
1427 .collect()
1428}
1429
1430pub fn member_header(member: &Path) -> String {
1434 format!("── {} ──", shown(member))
1435}
1436
1437fn check_one(prog: &str, input: &Path, short: bool, member: Option<&Path>) -> bool {
1441 let prog = match member {
1442 Some(m) => format!("{prog}: {}", shown(m)),
1443 None => prog.to_string(),
1444 };
1445 let prog = prog.as_str();
1446 if input.is_dir() {
1447 let options = match try_project_options(input) {
1448 Ok(o) => o,
1449 Err(e) => {
1450 crate::emsg!("{prog}: error: {e}");
1451 return false;
1452 }
1453 };
1454 let options = match schema_lock::read_only(input) {
1459 Ok(lock) => options.schema_registry(lock),
1460 Err(e) => {
1461 crate::emsg!("{prog}: error: {e}");
1462 return false;
1463 }
1464 };
1465 let check = project::check_project(&options);
1466 let has_errors = check.has_errors();
1467 if short {
1468 print_project_check_short(&check);
1469 } else {
1470 print_project_check(&check);
1471 }
1472 !has_errors
1473 } else {
1474 let source = match std::fs::read_to_string(input) {
1475 Ok(s) => s,
1476 Err(e) => {
1477 crate::emsg!("{prog}: error: could not read `{}`: {e}", shown(input));
1478 return false;
1479 }
1480 };
1481 let filename = shown(input);
1482 match bynk_emit::check_with_warnings(&source, &filename) {
1483 Ok(warnings) => {
1484 let warnings = crate::render::without_hints(&warnings);
1485 if !warnings.is_empty() {
1486 if short {
1487 crate::render::print_errors_short(&warnings, &source, &filename);
1488 } else {
1489 crate::render::print_errors(
1490 &warnings,
1491 &source,
1492 &filename,
1493 crate::colour::stderr(),
1494 );
1495 }
1496 }
1497 true
1498 }
1499 Err(errors) => {
1500 if short {
1501 crate::render::print_errors_short(&errors, &source, &filename);
1502 } else {
1503 crate::render::print_errors(
1504 &errors,
1505 &source,
1506 &filename,
1507 crate::colour::stderr(),
1508 );
1509 }
1510 false
1511 }
1512 }
1513 }
1514}
1515
1516#[cfg(test)]
1517mod tests {
1518 use super::*;
1519 use clap::Parser;
1520
1521 #[derive(clap::Parser, Debug)]
1524 struct Harness {
1525 #[command(flatten)]
1526 args: FmtArgs,
1527 }
1528
1529 fn parse(argv: &[&str]) -> FmtArgs {
1530 let mut full = vec!["fmt"];
1531 full.extend_from_slice(argv);
1532 Harness::parse_from(full).args
1533 }
1534
1535 fn resolve(argv: &[&str]) -> Result<FormatOptions, String> {
1537 parse(argv).apply_to(FormatOptions::default())
1538 }
1539
1540 fn manifest(toml: &str) -> FormatOptions {
1542 bynk_fmt::FmtConfig::from_manifest_str(toml)
1543 .expect("manifest parses")
1544 .apply(FormatOptions::default())
1545 }
1546
1547 #[test]
1548 fn no_flags_is_the_canonical_style() {
1549 let opts = resolve(&["a.bynk"]).expect("valid");
1550 assert_eq!(opts, FormatOptions::default());
1551 }
1552
1553 #[test]
1554 fn spaces_without_a_width_falls_back_to_two() {
1555 let opts = resolve(&["--indent", "spaces", "a.bynk"]).expect("valid");
1558 assert_eq!(opts.indent, IndentStyle::Spaces(2));
1559 }
1560
1561 #[test]
1562 fn spaces_takes_the_given_width() {
1563 let opts =
1564 resolve(&["--indent", "spaces", "--indent-width", "4", "a.bynk"]).expect("valid");
1565 assert_eq!(opts.indent, IndentStyle::Spaces(4));
1566 }
1567
1568 #[test]
1569 fn a_width_with_tabs_is_an_error_not_a_silent_no_op() {
1570 let err = resolve(&["--indent", "tab", "--indent-width", "4", "a.bynk"])
1571 .expect_err("a meaningless width must be reported");
1572 assert!(err.contains("--indent-width"), "{err}");
1573 assert!(err.contains("spaces"), "{err}");
1574 }
1575
1576 #[test]
1577 fn the_trailing_comma_pair_is_last_one_wins() {
1578 assert!(
1581 resolve(&["--no-trailing-comma", "--trailing-comma", "a.bynk"])
1582 .expect("valid")
1583 .trailing_comma
1584 );
1585 assert!(
1586 !resolve(&["--trailing-comma", "--no-trailing-comma", "a.bynk"])
1587 .expect("valid")
1588 .trailing_comma
1589 );
1590 }
1591
1592 #[test]
1593 fn max_line_width_is_taken_verbatim_and_zero_is_refused() {
1594 assert_eq!(
1595 resolve(&["--max-line-width", "60", "a.bynk"])
1596 .expect("valid")
1597 .max_line_width,
1598 60
1599 );
1600 assert!(
1603 Harness::try_parse_from(["fmt", "--max-line-width", "0", "a.bynk"]).is_err(),
1604 "`--max-line-width 0` must not parse"
1605 );
1606 }
1607
1608 #[test]
1611 fn an_unflagged_run_takes_the_manifest_whole() {
1612 let base = manifest(
1613 "[fmt]\nindent = \"spaces\"\nindent_width = 4\nmax_line_width = 120\ntrailing_comma = false\n",
1614 );
1615 let opts = parse(&["a.bynk"]).apply_to(base).expect("valid");
1616 assert_eq!(opts.indent, IndentStyle::Spaces(4));
1617 assert_eq!(opts.max_line_width, 120);
1618 assert!(!opts.trailing_comma);
1619 }
1620
1621 #[test]
1622 fn a_flag_beats_the_manifest_field_it_names_and_no_other() {
1623 let base = manifest("[fmt]\nindent = \"spaces\"\nindent_width = 4\nmax_line_width = 120\n");
1624 let opts = parse(&["--max-line-width", "80", "a.bynk"])
1625 .apply_to(base)
1626 .expect("valid");
1627 assert_eq!(opts.max_line_width, 80, "the flag wins where it speaks");
1628 assert_eq!(
1629 opts.indent,
1630 IndentStyle::Spaces(4),
1631 "and stays silent everywhere else"
1632 );
1633 }
1634
1635 #[test]
1636 fn an_absent_flag_does_not_reset_the_manifest_to_the_default() {
1637 let base = manifest("[fmt]\nmax_line_width = 120\n");
1641 assert_eq!(
1642 parse(&["a.bynk"])
1643 .apply_to(base)
1644 .expect("valid")
1645 .max_line_width,
1646 120
1647 );
1648 }
1649
1650 #[test]
1651 fn indent_spaces_alone_keeps_the_manifest_width() {
1652 let base = manifest("[fmt]\nindent = \"spaces\"\nindent_width = 4\n");
1653 let opts = parse(&["--indent", "spaces", "a.bynk"])
1654 .apply_to(base)
1655 .expect("valid");
1656 assert_eq!(opts.indent, IndentStyle::Spaces(4), "not reset to 2");
1657 }
1658
1659 #[test]
1660 fn indent_width_alone_applies_to_a_manifest_that_chose_spaces() {
1661 let base = manifest("[fmt]\nindent = \"spaces\"\n");
1662 let opts = parse(&["--indent-width", "8", "a.bynk"])
1663 .apply_to(base)
1664 .expect("valid");
1665 assert_eq!(opts.indent, IndentStyle::Spaces(8));
1666 }
1667
1668 #[test]
1669 fn indent_width_alone_is_refused_when_the_run_resolves_to_tabs() {
1670 let err = parse(&["--indent-width", "8", "a.bynk"])
1674 .apply_to(manifest("[fmt]\nindent = \"tab\"\n"))
1675 .expect_err("refused");
1676 assert!(err.contains("resolves"), "{err}");
1677 }
1678
1679 #[test]
1680 fn an_explicit_tab_flag_overrides_a_manifest_choosing_spaces() {
1681 let base = manifest("[fmt]\nindent = \"spaces\"\nindent_width = 4\n");
1682 let opts = parse(&["--indent", "tab", "a.bynk"])
1683 .apply_to(base)
1684 .expect("valid");
1685 assert_eq!(opts.indent, IndentStyle::Tab);
1686 }
1687
1688 #[test]
1689 fn trailing_comma_flag_overrides_a_manifest_that_turned_it_off() {
1690 let base = manifest("[fmt]\ntrailing_comma = false\n");
1691 assert!(
1692 parse(&["--trailing-comma", "a.bynk"])
1693 .apply_to(base)
1694 .expect("valid")
1695 .trailing_comma
1696 );
1697 assert!(
1699 !parse(&["a.bynk"])
1700 .apply_to(base)
1701 .expect("valid")
1702 .trailing_comma
1703 );
1704 }
1705
1706 #[test]
1707 fn no_config_is_parsed_and_defaults_are_used_in_its_presence() {
1708 let args = parse(&["--no-config", "a.bynk"]);
1711 assert!(args.no_config);
1712 assert_eq!(
1713 args.apply_to(FormatOptions::default()).expect("valid"),
1714 FormatOptions::default()
1715 );
1716 }
1717
1718 struct Scratch(PathBuf);
1721 impl Drop for Scratch {
1722 fn drop(&mut self) {
1723 let _ = fs::remove_dir_all(&self.0);
1724 }
1725 }
1726
1727 fn scratch_dir(tag: &str) -> Scratch {
1728 let dir = std::env::temp_dir().join(format!(
1729 "bynk_1077_{tag}_{}_{:?}",
1730 std::process::id(),
1731 std::thread::current().id()
1732 ));
1733 let _ = fs::remove_dir_all(&dir);
1734 fs::create_dir_all(&dir).unwrap();
1735 Scratch(dir)
1736 }
1737
1738 #[test]
1748 fn manifest_overlay_keys_and_reads_a_real_bynk_toml() {
1749 let dir = scratch_dir("manifest_overlay");
1750 let toml = "[paths]\ninclude = [\"lib\"]\n";
1751 fs::write(dir.0.join("bynk.toml"), toml).unwrap();
1752
1753 let overlay = manifest_overlay(&dir.0);
1754
1755 assert_eq!(
1756 overlay.get(&dir.0.join("bynk.toml")).map(String::as_str),
1757 Some(toml)
1758 );
1759 }
1760
1761 #[test]
1762 fn manifest_overlay_is_empty_with_no_bynk_toml() {
1763 let dir = scratch_dir("manifest_overlay_missing");
1764 assert!(manifest_overlay(&dir.0).is_empty());
1765 }
1766
1767 #[test]
1775 fn try_project_options_surfaces_an_unknown_paths_key() {
1776 let dir = scratch_dir("try_project_options_unknown_key");
1777 fs::write(dir.0.join("bynk.toml"), "[paths]\ninculde = [\"src\"]\n").unwrap();
1778 fs::create_dir_all(dir.0.join("src")).unwrap();
1779 fs::write(dir.0.join("src/thing.bynk"), "context thing\n").unwrap();
1780
1781 let err = match try_project_options(&dir.0) {
1782 Err(e) => e,
1783 Ok(_) => panic!("an unrecognised [paths] key must be reported, not silently ignored"),
1784 };
1785 assert!(
1786 matches!(
1787 &err,
1788 ProjectOptionsError::Paths(ProjectPathsError::UnknownKey(k)) if k == "inculde"
1789 ),
1790 "expected Paths(UnknownKey(\"inculde\")), got: {err:?}"
1791 );
1792 }
1793
1794 #[test]
1797 fn try_project_options_surfaces_an_unknown_table() {
1798 let dir = scratch_dir("try_project_options_unknown_table");
1799 fs::write(
1800 dir.0.join("bynk.toml"),
1801 "[paths]\ninclude = [\"src\"]\n\n[pahts]\nexclude = []\n",
1802 )
1803 .unwrap();
1804 fs::create_dir_all(dir.0.join("src")).unwrap();
1805 fs::write(dir.0.join("src/thing.bynk"), "context thing\n").unwrap();
1806
1807 let err = match try_project_options(&dir.0) {
1808 Err(e) => e,
1809 Ok(_) => panic!("an unknown table must be reported, not silently ignored"),
1810 };
1811 assert!(
1812 matches!(
1813 &err,
1814 ProjectOptionsError::Paths(ProjectPathsError::UnknownTable(t)) if t == "pahts"
1815 ),
1816 "expected Paths(UnknownTable(\"pahts\")), got: {err:?}"
1817 );
1818 assert!(err.to_string().contains("did you mean `[paths]`?"), "{err}");
1819 }
1820
1821 fn workers_project(name: &str, manifest: &str) -> Scratch {
1823 let dir = scratch_dir(name);
1824 fs::write(dir.0.join("bynk.toml"), manifest).unwrap();
1825 fs::create_dir_all(dir.0.join("src")).unwrap();
1826 fs::write(
1827 dir.0.join("src/greet.bynk"),
1828 "context greet\n\nservice hello {\n on call(name: String) -> Effect[Result[String, ()]] by Caller {\n Ok(name)\n }\n}\n",
1829 )
1830 .unwrap();
1831 dir
1832 }
1833
1834 fn greet_wrangler(options: CompileOptions) -> (String, Vec<&'static str>) {
1837 let out = project::compile_project(&options.target(project::BuildTarget::Workers))
1838 .unwrap_or_else(|f| {
1839 let msgs: Vec<&str> = f.errors.iter().map(|e| e.error.message.as_str()).collect();
1840 panic!("builds: {msgs:?}")
1841 });
1842 let text = out.artefacts.docs[Path::new("workers/greet/wrangler.toml")].text();
1843 (
1844 text,
1845 out.warnings.iter().map(|w| w.error.category).collect(),
1846 )
1847 }
1848
1849 #[test]
1853 fn manifest_compatibility_flags_reach_wrangler_toml() {
1854 let dir = workers_project(
1855 "compat_flags_1890",
1856 "[workers]\ncompatibility_flags = [\"nodejs_compat\", \"global_fetch_strictly_public\"]\n",
1857 );
1858 let want = "compatibility_flags = [\"global_fetch_strictly_public\", \"nodejs_compat\"]\n";
1859 for options in [
1860 try_project_options(&dir.0).expect("reads"),
1861 project_options(&dir.0).expect("reads"),
1862 ] {
1863 let (text, warnings) = greet_wrangler(options);
1864 assert!(text.contains(want), "{text}");
1865 assert_eq!(
1866 warnings,
1867 ["bynk.project.duplicate_compatibility_flag"],
1868 "the repeated default is reported"
1869 );
1870 }
1871 }
1872
1873 #[test]
1876 fn manifest_workers_dev_reaches_wrangler_toml() {
1877 let dir = workers_project("workers_dev_off", "[workers]\nworkers_dev = false\n");
1878 for options in [
1879 try_project_options(&dir.0).expect("reads"),
1880 project_options(&dir.0).expect("reads"),
1881 ] {
1882 let (text, _) = greet_wrangler(options);
1883 assert!(text.contains("workers_dev = false\n"), "{text}");
1884 }
1885 let dir = workers_project("workers_dev_unset", "[workers]\ncompatibility_flags = []\n");
1886 let (text, _) = greet_wrangler(try_project_options(&dir.0).expect("reads"));
1887 assert!(!text.contains("workers_dev"), "{text}");
1888 let dir = workers_project("workers_dev_bad", "[workers]\nworkers_dev = \"no\"\n");
1889 assert!(matches!(
1890 try_project_options(&dir.0),
1891 Err(ProjectOptionsError::Paths(
1892 ProjectPathsError::NotABool { .. }
1893 ))
1894 ));
1895 }
1896
1897 #[test]
1899 fn a_worker_gets_the_default_compatibility_flag_without_a_workers_table() {
1900 let dir = workers_project("compat_flags_default_1890", "[project]\nname = \"p\"\n");
1901 let (text, warnings) = greet_wrangler(try_project_options(&dir.0).expect("reads"));
1902 assert!(
1903 text.contains("compatibility_flags = [\"global_fetch_strictly_public\"]\n"),
1904 "{text}"
1905 );
1906 assert!(warnings.is_empty(), "{warnings:?}");
1907 }
1908
1909 #[test]
1911 fn try_project_options_refuses_a_non_string_compatibility_flag() {
1912 let dir = workers_project(
1913 "compat_flags_bad_1890",
1914 "[workers]\ncompatibility_flags = [\"nodejs_compat\", 2]\n",
1915 );
1916 match try_project_options(&dir.0) {
1917 Err(ProjectOptionsError::Paths(ProjectPathsError::NotAStringList { .. })) => {}
1918 Err(e) => panic!("wrong error: {e:?}"),
1919 Ok(_) => panic!("a non-string flag must be refused"),
1920 }
1921 }
1922}
1923
1924#[cfg(test)]
1925mod display_path_tests {
1926 use super::display_path;
1927 use std::path::Path;
1928
1929 #[test]
1930 fn a_relative_root_is_joined_as_typed() {
1931 assert_eq!(
1932 display_path(Path::new("test/fixtures/x"), Path::new("src/a.bynk")),
1933 "test/fixtures/x/src/a.bynk"
1934 );
1935 }
1936
1937 #[test]
1939 fn a_dot_root_adds_no_prefix() {
1940 assert_eq!(
1941 display_path(Path::new("."), Path::new("src/a.bynk")),
1942 "src/a.bynk"
1943 );
1944 assert_eq!(
1945 display_path(Path::new(""), Path::new("./src/a.bynk")),
1946 "src/a.bynk"
1947 );
1948 }
1949
1950 #[test]
1952 fn an_absolute_root_inside_the_cwd_is_shown_relative() {
1953 let cwd = std::env::current_dir().unwrap();
1954 assert_eq!(
1955 display_path(&cwd.join("proj"), Path::new("src/a.bynk")),
1956 "proj/src/a.bynk"
1957 );
1958 let canonical = cwd.canonicalize().unwrap();
1960 assert_eq!(
1961 display_path(&canonical.join("proj"), Path::new("src/a.bynk")),
1962 "proj/src/a.bynk"
1963 );
1964 }
1965
1966 #[test]
1968 fn an_absolute_root_outside_the_cwd_is_shown_absolute() {
1969 let cwd = std::env::current_dir().unwrap();
1970 let outside = cwd.parent().unwrap().join("bynk-display-path-elsewhere");
1971 let shown = display_path(&outside, Path::new("src/a.bynk"));
1972 assert!(
1973 shown.ends_with("bynk-display-path-elsewhere/src/a.bynk"),
1974 "{shown}"
1975 );
1976 assert!(
1977 !shown.contains('\\') && !shown.starts_with("//?/"),
1978 "{shown}"
1979 );
1980 }
1981
1982 #[cfg(windows)]
1984 #[test]
1985 fn a_verbatim_root_outside_the_cwd_loses_its_prefix() {
1986 assert_eq!(
1987 display_path(Path::new(r"\\?\C:\elsewhere"), Path::new("src/a.bynk")),
1988 "C:/elsewhere/src/a.bynk"
1989 );
1990 }
1991}