1use std::path::{Path, PathBuf};
22
23use crate::probe::{SystemToolbox, Toolbox};
24
25pub const PACKAGE_MANAGER_ENV: &str = "BYNK_PACKAGE_MANAGER";
27
28pub const NO_INSTALL_ENV: &str = "BYNK_NO_INSTALL";
30
31pub fn no_install_from_env() -> bool {
34 std::env::var(NO_INSTALL_ENV).is_ok_and(|v| {
35 let v = v.trim().to_ascii_lowercase();
36 !matches!(v.as_str(), "" | "0" | "false" | "no" | "off")
37 })
38}
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum PackageManager {
43 Npm,
44 Pnpm,
45 Bun,
46 Yarn,
48}
49
50impl PackageManager {
51 pub const ALL: [PackageManager; 4] = [Self::Npm, Self::Pnpm, Self::Bun, Self::Yarn];
53
54 pub fn name(self) -> &'static str {
56 match self {
57 Self::Npm => "npm",
58 Self::Pnpm => "pnpm",
59 Self::Bun => "bun",
60 Self::Yarn => "yarn",
61 }
62 }
63
64 pub fn parse(name: &str) -> Option<Self> {
66 Self::ALL.into_iter().find(|m| m.name() == name.trim())
67 }
68
69 pub fn install_args(self) -> &'static [&'static str] {
71 match self {
72 Self::Npm => &["install", "--no-audit", "--no-fund", "--ignore-scripts"],
73 Self::Pnpm => &["install", "--ignore-scripts", "--ignore-workspace"],
76 Self::Bun => &["install", "--ignore-scripts"],
77 Self::Yarn => &["install", "--ignore-scripts", "--non-interactive"],
78 }
79 }
80
81 pub fn command_line(self) -> String {
83 format!("{} {}", self.name(), self.install_args().join(" "))
84 }
85}
86
87impl PackageManager {
88 pub fn runner_program(self) -> Option<&'static str> {
91 match self {
92 Self::Npm => Some("npx"),
93 Self::Pnpm => Some("pnpm"),
94 Self::Bun => Some("bunx"),
95 Self::Yarn => None,
96 }
97 }
98
99 pub fn runner_label(self) -> Option<&'static str> {
102 match self {
103 Self::Npm => Some("npx"),
104 Self::Pnpm => Some("pnpm dlx"),
105 Self::Bun => Some("bunx"),
106 Self::Yarn => None,
107 }
108 }
109
110 pub fn runner_args(self, package: &str, bin: &str) -> Vec<String> {
116 let own = |parts: &[&str]| parts.iter().map(|p| (*p).to_string()).collect::<Vec<_>>();
117 match self {
118 Self::Npm => own(&["--yes", "-p", package, bin]),
119 Self::Pnpm => own(&["dlx", "--package", package, bin]),
120 Self::Bun => own(&["--package", package, bin]),
121 Self::Yarn => Vec::new(),
122 }
123 }
124
125 pub fn global_install(self, package: &str) -> String {
127 match self {
128 Self::Npm => format!("npm install -g {package}"),
129 Self::Pnpm => format!("pnpm add -g {package}"),
130 Self::Bun => format!("bun add -g {package}"),
131 Self::Yarn => format!("yarn global add {package}"),
132 }
133 }
134
135 pub fn dev_install(self, package: &str) -> String {
137 match self {
138 Self::Npm => format!("npm install --save-dev {package}"),
139 Self::Pnpm => format!("pnpm add -D {package}"),
140 Self::Bun => format!("bun add -d {package}"),
141 Self::Yarn => format!("yarn add -D {package}"),
142 }
143 }
144
145 pub fn runner(self, tb: &dyn Toolbox) -> Option<PackageManager> {
149 let found = |m: PackageManager| match m {
150 PackageManager::Npm => tb.npx_available(),
151 other => other
152 .runner_program()
153 .is_some_and(|program| tb.on_path(program).is_some()),
154 };
155 [self, PackageManager::Npm]
156 .into_iter()
157 .find(|m| m.runner_program().is_some() && found(*m))
158 }
159}
160
161pub fn tool_manager(
165 project: &dyn Project,
166 setting: Option<&str>,
167 tb: &dyn Toolbox,
168) -> PackageManager {
169 detect(project, setting, tb)
170 .map(|d| d.manager)
171 .unwrap_or(PackageManager::Npm)
172}
173
174pub fn manager_in(project_root: &Path, tb: &dyn Toolbox) -> PackageManager {
178 tool_manager(
179 &RealProject(project_root),
180 configured_manager(project_root).as_deref(),
181 tb,
182 )
183}
184
185pub fn system_tool_manager(project_root: &Path) -> PackageManager {
187 manager_in(project_root, &SystemToolbox)
188}
189
190#[derive(Debug, Clone, PartialEq, Eq)]
192pub enum Rule {
193 Env,
195 Setting,
197 PackageJson,
199 Lockfile(&'static str),
201 UserAgent,
203 Path,
205}
206
207impl Rule {
208 pub fn describe(&self) -> String {
210 match self {
211 Rule::Env => format!("`{PACKAGE_MANAGER_ENV}` is set"),
212 Rule::Setting => "`bynk.toml` sets `[build] package_manager`".to_string(),
213 Rule::PackageJson => "`package.json` names it in `packageManager`".to_string(),
214 Rule::Lockfile(file) => format!("`{file}` is at the project root"),
215 Rule::UserAgent => "bynk was started by it (`npm_config_user_agent`)".to_string(),
216 Rule::Path => "the first of npm, pnpm and bun on PATH".to_string(),
217 }
218 }
219}
220
221#[derive(Debug, Clone, PartialEq, Eq)]
223pub struct Detection {
224 pub manager: PackageManager,
225 pub rule: Rule,
226}
227
228#[derive(Debug, Clone, PartialEq, Eq)]
230pub enum DetectError {
231 UnknownManager { source: &'static str, value: String },
233 NoneAvailable,
235}
236
237impl std::fmt::Display for DetectError {
238 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
239 match self {
240 DetectError::UnknownManager { source, value } => write!(
241 f,
242 "{source} names the package manager `{value}`, which bynk cannot install with (npm, pnpm, bun or yarn)"
243 ),
244 DetectError::NoneAvailable => f.write_str(
245 "none of npm, pnpm or bun is on PATH to install the generated project's npm packages; install Node.js (which ships npm), or set `[build] package_manager`",
246 ),
247 }
248 }
249}
250
251pub trait Project {
253 fn read(&self, name: &str) -> Option<String>;
255 fn exists(&self, name: &str) -> bool;
257 fn env(&self, key: &str) -> Option<String>;
259}
260
261pub struct RealProject<'a>(pub &'a Path);
263
264impl Project for RealProject<'_> {
265 fn read(&self, name: &str) -> Option<String> {
266 std::fs::read_to_string(self.0.join(name)).ok()
267 }
268
269 fn exists(&self, name: &str) -> bool {
270 self.0.join(name).is_file()
271 }
272
273 fn env(&self, key: &str) -> Option<String> {
274 std::env::var(key).ok().filter(|v| !v.trim().is_empty())
275 }
276}
277
278const LOCKFILES: [(&str, PackageManager); 5] = [
280 ("pnpm-lock.yaml", PackageManager::Pnpm),
281 ("bun.lock", PackageManager::Bun),
282 ("bun.lockb", PackageManager::Bun),
283 ("yarn.lock", PackageManager::Yarn),
284 ("package-lock.json", PackageManager::Npm),
285];
286
287const PATH_ORDER: [PackageManager; 3] = [
289 PackageManager::Npm,
290 PackageManager::Pnpm,
291 PackageManager::Bun,
292];
293
294pub fn detect(
307 project: &dyn Project,
308 setting: Option<&str>,
309 tb: &dyn Toolbox,
310) -> Result<Detection, DetectError> {
311 if let Some(found) = explicit(project, setting)? {
312 return Ok(found);
313 }
314 if let Some(found) = from_package_json(project)
315 .or_else(|| from_lockfile(project))
316 .or_else(|| from_user_agent(project))
317 {
318 return Ok(found);
319 }
320 PATH_ORDER
321 .into_iter()
322 .find(|m| tb.on_path(m.name()).is_some())
323 .map(|manager| Detection {
324 manager,
325 rule: Rule::Path,
326 })
327 .ok_or(DetectError::NoneAvailable)
328}
329
330fn explicit(
331 project: &dyn Project,
332 setting: Option<&str>,
333) -> Result<Option<Detection>, DetectError> {
334 let candidates = [
335 (
336 Rule::Env,
337 "`BYNK_PACKAGE_MANAGER`",
338 project.env(PACKAGE_MANAGER_ENV),
339 ),
340 (
341 Rule::Setting,
342 "`bynk.toml`'s `[build] package_manager`",
343 setting.map(str::to_string),
344 ),
345 ];
346 for (rule, source, value) in candidates {
347 let Some(value) = value else { continue };
348 let manager = PackageManager::parse(&value).ok_or(DetectError::UnknownManager {
349 source,
350 value: value.clone(),
351 })?;
352 return Ok(Some(Detection { manager, rule }));
353 }
354 Ok(None)
355}
356
357fn from_package_json(project: &dyn Project) -> Option<Detection> {
358 let text = project.read("package.json")?;
359 let doc: serde_json::Value = serde_json::from_str(&text).ok()?;
360 let field = doc.get("packageManager")?.as_str()?;
361 let manager = PackageManager::parse(field.split('@').next()?)?;
362 Some(Detection {
363 manager,
364 rule: Rule::PackageJson,
365 })
366}
367
368fn from_lockfile(project: &dyn Project) -> Option<Detection> {
369 LOCKFILES
370 .into_iter()
371 .find(|(file, _)| project.exists(file))
372 .map(|(file, manager)| Detection {
373 manager,
374 rule: Rule::Lockfile(file),
375 })
376}
377
378fn from_user_agent(project: &dyn Project) -> Option<Detection> {
379 let agent = project.env("npm_config_user_agent")?;
380 let tool = agent.split(['/', ' ']).next()?;
382 let manager = PackageManager::parse(tool)?;
383 Some(Detection {
384 manager,
385 rule: Rule::UserAgent,
386 })
387}
388
389pub fn missing_npm_dependencies(build_dir: &Path) -> Vec<String> {
393 missing_npm_dependencies_in(build_dir, build_dir)
394}
395
396fn missing_npm_dependencies_in(build_dir: &Path, modules_root: &Path) -> Vec<String> {
401 let Ok(text) = std::fs::read_to_string(build_dir.join("package.json")) else {
402 return Vec::new();
403 };
404 let Ok(manifest) = serde_json::from_str::<serde_json::Value>(&text) else {
405 return Vec::new();
406 };
407 let mut missing: Vec<String> = manifest["dependencies"]
408 .as_object()
409 .into_iter()
410 .flatten()
411 .map(|(name, _)| name.clone())
412 .filter(|name| {
413 !modules_root
414 .join("node_modules")
415 .join(name)
416 .join("package.json")
417 .is_file()
418 })
419 .collect();
420 missing.sort();
421 missing
422}
423
424#[derive(Debug, Clone, Copy, PartialEq, Eq)]
426pub enum Mode {
427 Install,
429 NoInstall,
431 DryRun,
433}
434
435impl Mode {
436 pub fn of(dry_run: bool, no_install: bool) -> Mode {
439 if dry_run {
440 Mode::DryRun
441 } else if no_install {
442 Mode::NoInstall
443 } else {
444 Mode::Install
445 }
446 }
447}
448
449#[derive(Debug, Clone, PartialEq, Eq)]
451pub enum Outcome {
452 Present,
454 Installed(Detection),
456 WouldInstall(Vec<String>, Result<Detection, DetectError>),
460}
461
462#[derive(Debug, Clone, PartialEq, Eq)]
464pub enum InstallError {
465 Detect(DetectError),
466 Declined {
468 missing: Vec<String>,
469 command: Option<String>,
471 dir: PathBuf,
472 },
473 ToolMissing {
475 detection: Detection,
476 },
477 YarnBerry {
479 version: String,
480 },
481 Failed {
483 command: String,
484 dir: PathBuf,
485 detail: String,
486 },
487}
488
489impl std::fmt::Display for InstallError {
490 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
491 match self {
492 InstallError::Detect(e) => write!(f, "{e}"),
493 InstallError::Declined {
494 missing,
495 command,
496 dir,
497 } => {
498 let run = command.as_ref().map_or_else(
499 || "Install them with your package manager".to_string(),
500 |c| format!("Run `{c}`"),
501 );
502 write!(
503 f,
504 "the build needs npm packages that are not installed: {}. {run} in `{}`, then try again",
505 missing.join(", "),
506 dir.display()
507 )
508 }
509 InstallError::ToolMissing { detection } => write!(
510 f,
511 "`{}` is not on PATH to install the generated project's npm packages ({}); install it, or choose another with `[build] package_manager` or `{PACKAGE_MANAGER_ENV}`",
512 detection.manager.name(),
513 detection.rule.describe()
514 ),
515 InstallError::YarnBerry { version } => write!(
516 f,
517 "yarn {version} is Yarn Berry, which bynk does not install with (its Plug'n'Play layout leaves no `node_modules`); use Yarn classic, or choose npm, pnpm or bun with `[build] package_manager` or `{PACKAGE_MANAGER_ENV}`"
518 ),
519 InstallError::Failed {
520 command,
521 dir,
522 detail,
523 } => write!(
524 f,
525 "`{command}` failed in `{}`:\n{}",
526 dir.display(),
527 detail.trim_end()
528 ),
529 }
530 }
531}
532
533impl std::error::Error for InstallError {}
534
535pub trait Runner {
537 fn run(&self, program: &Path, args: &[&str], dir: &Path) -> Result<(bool, String), String>;
540}
541
542pub struct SystemRunner;
544
545impl Runner for SystemRunner {
546 fn run(&self, program: &Path, args: &[&str], dir: &Path) -> Result<(bool, String), String> {
547 crate::tools::run_to_completion(program, args, dir)
548 }
549}
550
551pub struct Install<'a> {
554 pub project: &'a dyn Project,
555 pub setting: Option<&'a str>,
557 pub toolbox: &'a dyn Toolbox,
558 pub runner: &'a dyn Runner,
559}
560
561pub fn ensure_installed(
564 install: &Install<'_>,
565 build_dir: &Path,
566 mode: Mode,
567) -> Result<Outcome, InstallError> {
568 ensure_installed_in(install, build_dir, build_dir, mode)
569}
570
571fn ensure_installed_in(
574 install: &Install<'_>,
575 build_dir: &Path,
576 modules_root: &Path,
577 mode: Mode,
578) -> Result<Outcome, InstallError> {
579 let missing = missing_npm_dependencies_in(build_dir, modules_root);
580 if missing.is_empty() {
581 return Ok(Outcome::Present);
582 }
583 let detection = detect(install.project, install.setting, install.toolbox);
584 match (mode, detection) {
585 (Mode::DryRun, detection) => Ok(Outcome::WouldInstall(missing, detection)),
588 (Mode::NoInstall, detection) => Err(InstallError::Declined {
589 command: detection.ok().map(|d| d.manager.command_line()),
590 missing,
591 dir: build_dir.to_path_buf(),
592 }),
593 (Mode::Install, Err(e)) => Err(InstallError::Detect(e)),
594 (Mode::Install, Ok(detection)) => run_install(install, build_dir, detection),
595 }
596}
597
598fn run_install(
599 install: &Install<'_>,
600 build_dir: &Path,
601 detection: Detection,
602) -> Result<Outcome, InstallError> {
603 let manager = detection.manager;
604 let Some(program) = install.toolbox.on_path(manager.name()) else {
605 return Err(InstallError::ToolMissing { detection });
606 };
607 if manager == PackageManager::Yarn {
608 check_yarn_classic(install.runner, &program, build_dir)?;
609 }
610 let failed = |detail: String| InstallError::Failed {
611 command: manager.command_line(),
612 dir: build_dir.to_path_buf(),
613 detail,
614 };
615 match install
616 .runner
617 .run(&program, manager.install_args(), build_dir)
618 {
619 Ok((true, _)) => Ok(Outcome::Installed(detection)),
620 Ok((false, output)) => Err(failed(output)),
621 Err(e) => Err(failed(e)),
622 }
623}
624
625fn check_yarn_classic(runner: &dyn Runner, yarn: &Path, dir: &Path) -> Result<(), InstallError> {
628 let Ok((true, text)) = runner.run(yarn, &["--version"], dir) else {
629 return Ok(());
630 };
631 let version = text.trim().to_string();
632 match version
633 .split('.')
634 .next()
635 .and_then(|major| major.parse::<u32>().ok())
636 {
637 Some(major) if major >= 2 => Err(InstallError::YarnBerry { version }),
638 _ => Ok(()),
639 }
640}
641
642pub fn announce(detection: &Detection, build_dir: &Path) -> String {
645 format!(
646 "bynk: installing npm packages with {} in `{}`",
647 detection.manager.name(),
648 build_dir.display()
649 )
650}
651
652pub fn dry_run_message(
654 missing: &[String],
655 detection: &Result<Detection, DetectError>,
656 build_dir: &Path,
657) -> String {
658 let how = match detection {
659 Ok(found) => format!(
660 "A real run would install them with `{}` in `{}` ({})",
661 found.manager.command_line(),
662 build_dir.display(),
663 found.rule.describe()
664 ),
665 Err(e) => format!("A real run could not install them: {e}"),
666 };
667 format!(
668 "bynk: the build needs npm packages that are not installed: {}. {how}",
669 missing.join(", ")
670 )
671}
672
673pub fn install_for_project(
677 project_root: &Path,
678 build_dir: &Path,
679 setting: Option<&str>,
680 mode: Mode,
681) -> Result<(), String> {
682 install_for_project_shown_as(project_root, build_dir, build_dir, setting, mode)
683}
684
685pub fn install_for_project_shown_as(
689 project_root: &Path,
690 build_dir: &Path,
691 shown_dir: &Path,
692 setting: Option<&str>,
693 mode: Mode,
694) -> Result<(), String> {
695 let project = RealProject(project_root);
696 let toolbox = SystemToolbox;
697 let install = Install {
698 project: &project,
699 setting,
700 toolbox: &toolbox,
701 runner: &SystemRunner,
702 };
703 if mode == Mode::Install
705 && !missing_npm_dependencies(build_dir).is_empty()
706 && let Ok(found) = detect(&project, setting, &toolbox)
707 {
708 crate::colour::eprintln(&announce(&found, build_dir));
709 }
710 let modules_root = if mode == Mode::DryRun {
713 shown_dir
714 } else {
715 build_dir
716 };
717 match ensure_installed_in(&install, build_dir, modules_root, mode).map_err(|e| e.to_string())? {
718 Outcome::WouldInstall(missing, found) => {
719 crate::colour::eprintln(&dry_run_message(&missing, &found, shown_dir));
720 Ok(())
721 }
722 Outcome::Present | Outcome::Installed(_) => Ok(()),
723 }
724}
725
726pub fn configured_manager(project_root: &Path) -> Option<String> {
729 bynk_project::try_read_build_config(project_root)
730 .ok()
731 .and_then(|c| c.package_manager)
732}
733
734#[cfg(test)]
735mod tests {
736 use super::*;
737 use crate::probe::Version;
738 use std::cell::RefCell;
739 use std::collections::{BTreeMap, BTreeSet};
740 use std::process::Command;
741
742 #[derive(Default)]
743 struct Fake {
744 files: BTreeMap<&'static str, String>,
745 env: BTreeMap<&'static str, &'static str>,
746 path: BTreeSet<&'static str>,
747 }
748
749 impl Project for Fake {
750 fn read(&self, name: &str) -> Option<String> {
751 self.files.get(name).cloned()
752 }
753 fn exists(&self, name: &str) -> bool {
754 self.files.contains_key(name)
755 }
756 fn env(&self, key: &str) -> Option<String> {
757 self.env.get(key).map(|v| v.to_string())
758 }
759 }
760
761 impl Toolbox for Fake {
762 fn on_path(&self, tool: &str) -> Option<PathBuf> {
763 self.path
764 .contains(tool)
765 .then(|| PathBuf::from(format!("/bin/{tool}")))
766 }
767 fn in_dir(&self, _: &Path, _: &str) -> Option<PathBuf> {
768 None
769 }
770 fn version(&self, _: &Path) -> Option<Version> {
771 None
772 }
773 fn npx_available(&self) -> bool {
774 false
775 }
776 }
777
778 fn pick(fake: &Fake, setting: Option<&str>) -> Result<Detection, DetectError> {
779 detect(fake, setting, fake)
780 }
781
782 fn chose(fake: &Fake, setting: Option<&str>) -> (PackageManager, Rule) {
783 let d = pick(fake, setting).unwrap();
784 (d.manager, d.rule)
785 }
786
787 #[test]
788 fn the_environment_overrides_the_setting() {
789 let mut f = Fake::default();
790 f.env.insert(PACKAGE_MANAGER_ENV, "bun");
791 assert_eq!(chose(&f, Some("pnpm")), (PackageManager::Bun, Rule::Env));
792 }
793
794 #[test]
795 fn the_setting_beats_package_json_and_lockfiles() {
796 let mut f = Fake::default();
797 f.files
798 .insert("package.json", r#"{"packageManager":"[email protected]"}"#.into());
799 f.files.insert("yarn.lock", String::new());
800 assert_eq!(chose(&f, Some("bun")), (PackageManager::Bun, Rule::Setting));
801 }
802
803 #[test]
804 fn an_unknown_explicit_setting_is_an_error_naming_where_it_came_from() {
805 let f = Fake::default();
806 let e = pick(&f, Some("deno")).unwrap_err();
807 assert!(
808 e.to_string().contains("`bynk.toml`") && e.to_string().contains("`deno`"),
809 "{e}"
810 );
811 let mut f = Fake::default();
812 f.env.insert(PACKAGE_MANAGER_ENV, "nope");
813 assert!(
814 pick(&f, None)
815 .unwrap_err()
816 .to_string()
817 .contains("BYNK_PACKAGE_MANAGER")
818 );
819 }
820
821 #[test]
822 fn package_json_names_the_manager_before_any_version() {
823 for (field, want) in [
824 ("[email protected]+sha512.abc", PackageManager::Pnpm),
825 ("[email protected]", PackageManager::Yarn),
826 ("[email protected]", PackageManager::Bun),
827 ("[email protected]", PackageManager::Npm),
828 ] {
829 let mut f = Fake::default();
830 f.files
831 .insert("package.json", format!(r#"{{"packageManager":"{field}"}}"#));
832 f.files.insert("package-lock.json", String::new());
833 assert_eq!(chose(&f, None), (want, Rule::PackageJson), "{field}");
834 }
835 }
836
837 #[test]
838 fn an_unknown_or_absent_package_manager_field_falls_through() {
839 let mut f = Fake::default();
840 f.files
841 .insert("package.json", r#"{"packageManager":"deno@2"}"#.into());
842 f.files.insert("pnpm-lock.yaml", String::new());
843 assert_eq!(
844 chose(&f, None),
845 (PackageManager::Pnpm, Rule::Lockfile("pnpm-lock.yaml"))
846 );
847 let mut f = Fake::default();
848 f.files.insert("package.json", "{ not json".into());
849 f.files.insert("yarn.lock", String::new());
850 assert_eq!(
851 chose(&f, None),
852 (PackageManager::Yarn, Rule::Lockfile("yarn.lock"))
853 );
854 }
855
856 #[test]
857 fn each_lockfile_names_its_manager() {
858 for (file, want) in [
859 ("pnpm-lock.yaml", PackageManager::Pnpm),
860 ("bun.lock", PackageManager::Bun),
861 ("bun.lockb", PackageManager::Bun),
862 ("yarn.lock", PackageManager::Yarn),
863 ("package-lock.json", PackageManager::Npm),
864 ] {
865 let mut f = Fake::default();
866 f.files.insert(file, String::new());
867 assert_eq!(chose(&f, None), (want, Rule::Lockfile(file)), "{file}");
868 }
869 }
870
871 #[test]
872 fn a_lockfile_beats_the_user_agent_and_the_user_agent_beats_path() {
873 let mut f = Fake::default();
874 f.files.insert("yarn.lock", String::new());
875 f.env
876 .insert("npm_config_user_agent", "pnpm/9.0.0 npm/? node/v22");
877 assert_eq!(chose(&f, None).0, PackageManager::Yarn);
878
879 let mut f = Fake::default();
880 f.env
881 .insert("npm_config_user_agent", "pnpm/9.0.0 npm/? node/v22");
882 f.path.insert("npm");
883 assert_eq!(chose(&f, None), (PackageManager::Pnpm, Rule::UserAgent));
884 for (agent, want) in [
885 ("bun/1.1.0 npm/? node/v22", PackageManager::Bun),
886 ("yarn/1.22.0 npm/? node/v22", PackageManager::Yarn),
887 ("npm/10.0.0 node/v22 linux x64", PackageManager::Npm),
888 ] {
889 let mut f = Fake::default();
890 f.env.insert("npm_config_user_agent", agent);
891 assert_eq!(chose(&f, None), (want, Rule::UserAgent), "{agent}");
892 }
893 }
894
895 #[test]
896 fn an_unrecognised_user_agent_falls_through_to_path() {
897 let mut f = Fake::default();
898 f.env.insert("npm_config_user_agent", "deno/2.0");
899 f.path.insert("bun");
900 assert_eq!(chose(&f, None), (PackageManager::Bun, Rule::Path));
901 }
902
903 #[test]
904 fn path_prefers_npm_then_pnpm_then_bun() {
905 let mut f = Fake::default();
906 f.path.extend(["bun", "pnpm", "npm"]);
907 assert_eq!(chose(&f, None), (PackageManager::Npm, Rule::Path));
908 f.path.remove("npm");
909 assert_eq!(chose(&f, None).0, PackageManager::Pnpm);
910 f.path.remove("pnpm");
911 assert_eq!(chose(&f, None).0, PackageManager::Bun);
912 f.path.remove("bun");
913 assert_eq!(pick(&f, None), Err(DetectError::NoneAvailable));
914 }
915
916 #[test]
917 fn each_tools_arguments_turn_lifecycle_scripts_off() {
918 assert_eq!(
919 PackageManager::Npm.install_args(),
920 ["install", "--no-audit", "--no-fund", "--ignore-scripts"]
921 );
922 assert_eq!(
923 PackageManager::Pnpm.install_args(),
924 ["install", "--ignore-scripts", "--ignore-workspace"]
925 );
926 assert_eq!(
927 PackageManager::Bun.install_args(),
928 ["install", "--ignore-scripts"]
929 );
930 assert_eq!(
931 PackageManager::Yarn.install_args(),
932 ["install", "--ignore-scripts", "--non-interactive"]
933 );
934 for m in PackageManager::ALL {
935 assert!(m.install_args().contains(&"--ignore-scripts"), "{m:?}");
936 }
937 }
938
939 #[derive(Default)]
942 struct Spy {
943 calls: RefCell<Vec<(PathBuf, Vec<String>, PathBuf)>>,
944 yarn_version: &'static str,
945 fail: bool,
946 }
947
948 impl Runner for Spy {
949 fn run(&self, program: &Path, args: &[&str], dir: &Path) -> Result<(bool, String), String> {
950 if args == ["--version"] {
951 return Ok((true, self.yarn_version.to_string()));
952 }
953 self.calls.borrow_mut().push((
954 program.to_path_buf(),
955 args.iter().map(|a| a.to_string()).collect(),
956 dir.to_path_buf(),
957 ));
958 if self.fail {
959 Ok((false, "ERR network unreachable\n".to_string()))
960 } else {
961 Ok((true, String::new()))
962 }
963 }
964 }
965
966 fn build_dir(name: &str, listed: &[&str], installed: &[&str]) -> PathBuf {
967 let d =
968 std::env::temp_dir().join(format!("bynk-npm-install-{name}-{}", std::process::id()));
969 let _ = std::fs::remove_dir_all(&d);
970 std::fs::create_dir_all(&d).unwrap();
971 let deps: Vec<String> = listed
972 .iter()
973 .map(|n| format!("\"{n}\": \"1.0.0\""))
974 .collect();
975 std::fs::write(
976 d.join("package.json"),
977 format!("{{\"dependencies\": {{{}}}}}", deps.join(", ")),
978 )
979 .unwrap();
980 for n in installed {
981 let p = d.join("node_modules").join(n);
982 std::fs::create_dir_all(&p).unwrap();
983 std::fs::write(p.join("package.json"), "{}").unwrap();
984 }
985 d
986 }
987
988 fn with_pnpm() -> Fake {
989 let mut f = Fake::default();
990 f.files.insert("pnpm-lock.yaml", String::new());
991 f.path.insert("pnpm");
992 f
993 }
994
995 fn run_mode(fake: &Fake, spy: &Spy, dir: &Path, mode: Mode) -> Result<Outcome, InstallError> {
996 let install = Install {
997 project: fake,
998 setting: None,
999 toolbox: fake,
1000 runner: spy,
1001 };
1002 ensure_installed(&install, dir, mode)
1003 }
1004
1005 #[test]
1006 fn a_missing_package_runs_the_detected_tool_in_the_build_directory() {
1007 let d = build_dir("run", &["postal-mime"], &[]);
1008 let spy = Spy::default();
1009 let got = run_mode(&with_pnpm(), &spy, &d, Mode::Install).unwrap();
1010 assert!(matches!(got, Outcome::Installed(ref det) if det.manager == PackageManager::Pnpm));
1011 let calls = spy.calls.borrow();
1012 assert_eq!(calls.len(), 1);
1013 assert_eq!(calls[0].0, PathBuf::from("/bin/pnpm"));
1014 assert_eq!(
1015 calls[0].1,
1016 ["install", "--ignore-scripts", "--ignore-workspace"]
1017 );
1018 assert_eq!(calls[0].2, d);
1019 }
1020
1021 #[test]
1022 fn a_warm_directory_runs_nothing_and_needs_no_tool() {
1023 let d = build_dir("warm", &["postal-mime", "jose"], &["postal-mime", "jose"]);
1024 let spy = Spy::default();
1025 let got = run_mode(&Fake::default(), &spy, &d, Mode::Install).unwrap();
1027 assert_eq!(got, Outcome::Present);
1028 assert!(spy.calls.borrow().is_empty());
1029 let none = build_dir("none", &[], &[]);
1030 assert_eq!(
1031 run_mode(&Fake::default(), &spy, &none, Mode::Install).unwrap(),
1032 Outcome::Present
1033 );
1034 }
1035
1036 #[test]
1037 fn a_partly_installed_directory_installs_again() {
1038 let d = build_dir("partial", &["postal-mime", "jose"], &["jose"]);
1039 let spy = Spy::default();
1040 run_mode(&with_pnpm(), &spy, &d, Mode::Install).unwrap();
1041 assert_eq!(spy.calls.borrow().len(), 1);
1042 }
1043
1044 #[test]
1045 fn no_install_stops_naming_the_detected_command_and_directory() {
1046 let d = build_dir("declined", &["postal-mime"], &[]);
1047 let spy = Spy::default();
1048 let e = run_mode(&with_pnpm(), &spy, &d, Mode::NoInstall).unwrap_err();
1049 let text = e.to_string();
1050 assert!(
1051 text.contains("postal-mime")
1052 && text.contains("Run `pnpm install --ignore-scripts --ignore-workspace`")
1053 && text.contains(&d.display().to_string())
1054 && !text.contains("`npm install"),
1055 "{text}"
1056 );
1057 assert!(spy.calls.borrow().is_empty());
1058 }
1059
1060 #[test]
1061 fn a_dry_run_reports_what_it_would_install_and_runs_nothing() {
1062 let d = build_dir("dry", &["postal-mime"], &[]);
1063 let spy = Spy::default();
1064 let got = run_mode(&with_pnpm(), &spy, &d, Mode::DryRun).unwrap();
1065 let Outcome::WouldInstall(missing, det) = got else {
1066 panic!("{got:?}")
1067 };
1068 assert_eq!(missing, ["postal-mime"]);
1069 assert_eq!(det.as_ref().unwrap().manager, PackageManager::Pnpm);
1070 let msg = dry_run_message(&missing, &det, &d);
1071 assert!(
1072 msg.contains("pnpm install") && msg.contains("pnpm-lock.yaml"),
1073 "{msg}"
1074 );
1075 assert!(spy.calls.borrow().is_empty());
1076 assert_eq!(Mode::of(true, true), Mode::DryRun);
1078 assert_eq!(Mode::of(false, true), Mode::NoInstall);
1079 assert_eq!(Mode::of(false, false), Mode::Install);
1080 }
1081
1082 #[test]
1083 fn a_dry_run_and_no_install_still_name_the_packages_when_no_tool_is_found() {
1084 let d = build_dir("no-tool", &["postal-mime"], &[]);
1085 let spy = Spy::default();
1086 let got = run_mode(&Fake::default(), &spy, &d, Mode::DryRun).unwrap();
1088 let Outcome::WouldInstall(missing, det) = got else {
1089 panic!("{got:?}")
1090 };
1091 assert_eq!(det, Err(DetectError::NoneAvailable));
1092 let msg = dry_run_message(&missing, &det, &d);
1093 assert!(
1094 msg.contains("postal-mime") && msg.contains("could not install"),
1095 "{msg}"
1096 );
1097 let text = run_mode(&Fake::default(), &spy, &d, Mode::NoInstall)
1098 .unwrap_err()
1099 .to_string();
1100 assert!(
1101 text.contains("postal-mime")
1102 && text.contains("Install them with your package manager")
1103 && text.contains(&d.display().to_string()),
1104 "{text}"
1105 );
1106 let install = Install {
1108 project: &Fake::default(),
1109 setting: Some("deno"),
1110 toolbox: &Fake::default(),
1111 runner: &spy,
1112 };
1113 assert!(ensure_installed(&install, &d, Mode::DryRun).is_ok());
1114 assert!(matches!(
1115 ensure_installed(&install, &d, Mode::Install),
1116 Err(InstallError::Detect(_))
1117 ));
1118 assert!(spy.calls.borrow().is_empty());
1119 }
1120
1121 #[test]
1122 fn a_failed_install_names_the_command_the_directory_and_the_tools_error() {
1123 let d = build_dir("failed", &["postal-mime"], &[]);
1124 let spy = Spy {
1125 fail: true,
1126 ..Spy::default()
1127 };
1128 let text = run_mode(&with_pnpm(), &spy, &d, Mode::Install)
1129 .unwrap_err()
1130 .to_string();
1131 assert!(
1132 text.contains("pnpm install")
1133 && text.contains(&d.display().to_string())
1134 && text.contains("network unreachable"),
1135 "{text}"
1136 );
1137 }
1138
1139 #[test]
1140 fn a_chosen_tool_that_is_not_installed_says_why_it_was_chosen() {
1141 let d = build_dir("toolless", &["postal-mime"], &[]);
1142 let mut f = Fake::default();
1143 f.files.insert("bun.lock", String::new());
1144 let text = run_mode(&f, &Spy::default(), &d, Mode::Install)
1145 .unwrap_err()
1146 .to_string();
1147 assert!(
1148 text.contains("`bun`") && text.contains("bun.lock"),
1149 "{text}"
1150 );
1151 }
1152
1153 #[test]
1154 fn the_npm_fallback_installs_with_npm_when_nothing_else_points_anywhere() {
1155 let d = build_dir("npm", &["postal-mime"], &[]);
1156 let mut f = Fake::default();
1157 f.path.insert("npm");
1158 let spy = Spy::default();
1159 run_mode(&f, &spy, &d, Mode::Install).unwrap();
1160 assert_eq!(
1161 spy.calls.borrow()[0].1,
1162 ["install", "--no-audit", "--no-fund", "--ignore-scripts"]
1163 );
1164 }
1165
1166 #[test]
1167 fn yarn_classic_installs_and_berry_is_refused() {
1168 let mut f = Fake::default();
1169 f.files.insert("yarn.lock", String::new());
1170 f.path.insert("yarn");
1171 let d = build_dir("yarn", &["postal-mime"], &[]);
1172 let classic = Spy {
1173 yarn_version: "1.22.22\n",
1174 ..Spy::default()
1175 };
1176 run_mode(&f, &classic, &d, Mode::Install).unwrap();
1177 assert_eq!(classic.calls.borrow().len(), 1);
1178 let berry = Spy {
1179 yarn_version: "4.5.0\n",
1180 ..Spy::default()
1181 };
1182 let e = run_mode(&f, &berry, &d, Mode::Install).unwrap_err();
1183 assert!(matches!(e, InstallError::YarnBerry { .. }), "{e}");
1184 assert!(berry.calls.borrow().is_empty());
1185 assert!(e.to_string().contains("Berry"));
1186 }
1187
1188 fn real_install(tool: &str) {
1193 let Ok(path) = which::which(tool) else {
1194 eprintln!("skipping: `{tool}` is not installed");
1195 return;
1196 };
1197 let up = std::env::temp_dir().join(format!("bynk-npm-real-{tool}-{}", std::process::id()));
1198 let _ = std::fs::remove_dir_all(&up);
1199 std::fs::create_dir_all(&up).unwrap();
1202 std::fs::write(
1203 up.join("pnpm-workspace.yaml"),
1204 "packages:\n - 'elsewhere'\n",
1205 )
1206 .unwrap();
1207 let dir = up.join(".bynk").join("deploy");
1208 std::fs::create_dir_all(&dir).unwrap();
1209 std::fs::write(
1210 dir.join("package.json"),
1211 r#"{"type":"module","dependencies":{"postal-mime":"4.1.4"}}"#,
1212 )
1213 .unwrap();
1214 let mut fake = Fake::default();
1215 fake.path.insert(match tool {
1216 "npm" => "npm",
1217 "pnpm" => "pnpm",
1218 "bun" => "bun",
1219 _ => "yarn",
1220 });
1221 struct At(PathBuf);
1224 impl Runner for At {
1225 fn run(&self, _: &Path, args: &[&str], dir: &Path) -> Result<(bool, String), String> {
1226 SystemRunner.run(&self.0, args, dir)
1227 }
1228 }
1229 let runner = At(path);
1230 let install = Install {
1231 project: &fake,
1232 setting: Some(tool),
1233 toolbox: &fake,
1234 runner: &runner,
1235 };
1236 let first = ensure_installed(&install, &dir, Mode::Install);
1237 assert!(
1238 matches!(first, Ok(Outcome::Installed(_))),
1239 "{tool}: {first:?}"
1240 );
1241 assert!(
1242 dir.join("node_modules/postal-mime/package.json").is_file(),
1243 "{tool}: installed into the generated directory"
1244 );
1245 assert!(
1246 !up.join("node_modules").exists(),
1247 "{tool}: nothing was installed at the workspace root"
1248 );
1249 assert_eq!(
1251 ensure_installed(&install, &dir, Mode::Install),
1252 Ok(Outcome::Present),
1253 "{tool}"
1254 );
1255 let _ = std::fs::remove_dir_all(&up);
1256 }
1257
1258 #[test]
1259 fn npm_installs_for_real() {
1260 real_install("npm");
1261 }
1262
1263 #[test]
1264 fn pnpm_installs_for_real_beside_a_workspace_file() {
1265 real_install("pnpm");
1266 }
1267
1268 #[test]
1269 fn bun_installs_for_real() {
1270 real_install("bun");
1271 }
1272
1273 #[test]
1274 fn yarn_classic_installs_for_real() {
1275 let classic = which::which("yarn").ok().is_some_and(|y| {
1276 Command::new(y)
1277 .arg("--version")
1278 .output()
1279 .is_ok_and(|o| String::from_utf8_lossy(&o.stdout).starts_with("1."))
1280 });
1281 if classic {
1282 real_install("yarn");
1283 } else {
1284 eprintln!("skipping: Yarn classic is not installed");
1285 }
1286 }
1287
1288 struct Tools {
1290 path: &'static [&'static str],
1291 npx: bool,
1292 }
1293
1294 impl Toolbox for Tools {
1295 fn on_path(&self, tool: &str) -> Option<PathBuf> {
1296 self.path
1297 .contains(&tool)
1298 .then(|| PathBuf::from(format!("/bin/{tool}")))
1299 }
1300 fn in_dir(&self, _: &Path, _: &str) -> Option<PathBuf> {
1301 None
1302 }
1303 fn version(&self, _: &Path) -> Option<Version> {
1304 None
1305 }
1306 fn npx_available(&self) -> bool {
1307 self.npx
1308 }
1309 }
1310
1311 #[test]
1312 fn each_manager_runs_a_pinned_package_binary_its_own_way() {
1313 let typescript = crate::tools::pins::typescript_spec();
1314 let args = |m: PackageManager| m.runner_args(&typescript, "tsc");
1315 assert_eq!(
1316 args(PackageManager::Npm),
1317 ["--yes", "-p", typescript.as_str(), "tsc"]
1318 );
1319 assert_eq!(
1320 args(PackageManager::Pnpm),
1321 ["dlx", "--package", typescript.as_str(), "tsc"]
1322 );
1323 assert_eq!(
1324 args(PackageManager::Bun),
1325 ["--package", typescript.as_str(), "tsc"]
1326 );
1327 assert!(args(PackageManager::Yarn).is_empty());
1328 let programs = PackageManager::ALL.map(PackageManager::runner_program);
1329 assert_eq!(programs, [Some("npx"), Some("pnpm"), Some("bunx"), None]);
1330 let labels = PackageManager::ALL.map(PackageManager::runner_label);
1331 assert_eq!(labels, [Some("npx"), Some("pnpm dlx"), Some("bunx"), None]);
1332 }
1333
1334 #[test]
1335 fn each_manager_has_its_own_install_commands() {
1336 let global = PackageManager::ALL.map(|m| m.global_install("wrangler@4"));
1337 assert_eq!(
1338 global,
1339 [
1340 "npm install -g wrangler@4",
1341 "pnpm add -g wrangler@4",
1342 "bun add -g wrangler@4",
1343 "yarn global add wrangler@4"
1344 ]
1345 );
1346 let dev = PackageManager::ALL.map(|m| m.dev_install("wrangler@4"));
1347 assert_eq!(
1348 dev,
1349 [
1350 "npm install --save-dev wrangler@4",
1351 "pnpm add -D wrangler@4",
1352 "bun add -d wrangler@4",
1353 "yarn add -D wrangler@4"
1354 ]
1355 );
1356 }
1357
1358 #[test]
1359 fn the_runner_is_the_managers_own_else_npx_else_none() {
1360 let all = Tools {
1361 path: &["pnpm", "bunx"],
1362 npx: true,
1363 };
1364 assert_eq!(
1365 PackageManager::Pnpm.runner(&all),
1366 Some(PackageManager::Pnpm)
1367 );
1368 assert_eq!(PackageManager::Bun.runner(&all), Some(PackageManager::Bun));
1369 assert_eq!(PackageManager::Npm.runner(&all), Some(PackageManager::Npm));
1370 assert_eq!(PackageManager::Yarn.runner(&all), Some(PackageManager::Npm));
1372 let none = Tools {
1374 path: &["yarn"],
1375 npx: false,
1376 };
1377 assert_eq!(PackageManager::Yarn.runner(&none), None);
1378 let npx_only = Tools {
1380 path: &[],
1381 npx: true,
1382 };
1383 assert_eq!(
1384 PackageManager::Pnpm.runner(&npx_only),
1385 Some(PackageManager::Npm)
1386 );
1387 assert_eq!(PackageManager::Bun.runner(&none), None);
1388 }
1389
1390 #[test]
1391 fn tool_manager_reuses_detection_and_defaults_to_npm() {
1392 let pnpm = Fake {
1393 files: BTreeMap::from([("pnpm-lock.yaml", String::new())]),
1394 ..Fake::default()
1395 };
1396 assert_eq!(tool_manager(&pnpm, None, &pnpm), PackageManager::Pnpm);
1397 let empty = Fake::default();
1399 assert_eq!(tool_manager(&empty, None, &empty), PackageManager::Npm);
1400 assert_eq!(
1401 tool_manager(&empty, Some("nope"), &empty),
1402 PackageManager::Npm
1403 );
1404 }
1405
1406 #[test]
1410 fn real_runners_run_a_pinned_tsc() {
1411 if std::env::var_os("BYNK_REAL_RUNNERS").is_none() {
1412 eprintln!("skipping: set BYNK_REAL_RUNNERS=1 to download and run each tool");
1413 return;
1414 }
1415 for manager in [
1416 PackageManager::Pnpm,
1417 PackageManager::Bun,
1418 PackageManager::Npm,
1419 ] {
1420 let program = manager.runner_program().expect("a runner");
1421 let Ok(path) = which::which(program) else {
1422 eprintln!("skipping {}: not installed", manager.name());
1423 continue;
1424 };
1425 let out = Command::new(path)
1426 .args(manager.runner_args(&crate::tools::pins::typescript_spec(), "tsc"))
1427 .arg("--version")
1428 .output()
1429 .expect("runs");
1430 let text = String::from_utf8_lossy(&out.stdout);
1431 let version = format!("Version {}.", bynk_emit::TYPESCRIPT_MAJOR_TESTED);
1432 assert!(
1433 out.status.success() && text.contains(&version),
1434 "{}: {text}",
1435 manager.name()
1436 );
1437 }
1438 }
1439}