Skip to main content

bynk_driver/tools/
ladder.rs

1//! The runner ladders for `tsc` and `tsx`: the tool itself when it is on PATH,
2//! then the package manager's runner (`npx`, `pnpm dlx`, `bunx`) fetching it.
3//!
4//! `bynk test` and `bynk check --emit` both walk the `tsc` ladder, so it is
5//! written once here. A rung is resolved through detection
6//! ([`crate::probe::detect`]) when the walk reaches it, and spawned at the path
7//! detection found, so a Windows npm shim (`tsc.cmd`) is also the program that
8//! runs (#1758).
9
10use crate::npm_install::PackageManager;
11use crate::probe::{DetectOpts, SystemToolbox, Toolbox};
12use crate::tools::pins;
13use std::path::{Path, PathBuf};
14use std::process::Command;
15
16/// The programs to try, in order, to run `tool` (a binary of `package`, which
17/// may be pinned): the tool itself, then the runner that fetches it on demand
18/// when `manager` (or `npx`, for a manager with no runner) is on PATH. Each is
19/// a program name with its leading arguments.
20pub fn tool_ladder(
21    tool: &str,
22    package: &str,
23    manager: PackageManager,
24    tb: &dyn Toolbox,
25) -> Vec<(String, Vec<String>)> {
26    let mut rungs = vec![(tool.to_string(), Vec::new())];
27    if let Some(runner) = manager.runner(tb)
28        && let Some(program) = runner.runner_program()
29    {
30        rungs.push((program.to_string(), runner.runner_args(package, tool)));
31    }
32    rungs
33}
34
35/// [`tool_ladder`] over the real PATH.
36pub fn system_tool_ladder(
37    tool: &str,
38    package: &str,
39    manager: PackageManager,
40) -> Vec<(String, Vec<String>)> {
41    tool_ladder(tool, package, manager, &SystemToolbox)
42}
43
44/// Where `name` is installed on `PATH`, if it is. #1758: callers spawn this
45/// path, not the bare name, so a Windows npm shim (`tsc.cmd`) that detection
46/// finds is also the program that runs.
47pub(crate) fn resolve_tool(name: &str) -> Option<PathBuf> {
48    crate::probe::detect(&SystemToolbox, name, DetectOpts::default())
49        .provenance
50        .path()
51        .map(Path::to_path_buf)
52}
53
54/// #1758: a runner that was found but would not start. Recorded instead of
55/// silently skipped, so a run with no working runner reports the real cause
56/// rather than advising an install of something already installed.
57pub(crate) fn start_failure(path: &Path, e: &std::io::Error) -> String {
58    format!(
59        "`{}` was found but could not be started: {e}",
60        path.display()
61    )
62}
63
64/// A tool's ladder over the real PATH, for one package manager.
65pub struct Ladder {
66    rungs: Vec<(String, Vec<String>)>,
67}
68
69impl Ladder {
70    /// `tsc`, then the runner fetching [`pins::typescript_spec`].
71    pub fn tsc(manager: PackageManager) -> Self {
72        Ladder {
73            rungs: system_tool_ladder("tsc", &pins::typescript_spec(), manager),
74        }
75    }
76
77    /// `tsx`, then the runner fetching [`pins::TSX_SPEC`].
78    pub fn tsx(manager: PackageManager) -> Self {
79        Ladder {
80            rungs: system_tool_ladder("tsx", pins::TSX_SPEC, manager),
81        }
82    }
83
84    /// Each rung that is on PATH, in order. A rung is resolved only when the
85    /// walk reaches it, so a caller that stops at the first that runs never
86    /// probes the rest.
87    pub fn rungs(&self) -> impl Iterator<Item = Rung> + '_ {
88        self.rungs.iter().filter_map(|(program, prefix)| {
89            resolve_tool(program).map(|path| Rung {
90                path,
91                prefix: prefix.clone(),
92            })
93        })
94    }
95}
96
97/// One resolved rung of a [`Ladder`].
98pub struct Rung {
99    path: PathBuf,
100    prefix: Vec<String>,
101}
102
103impl Rung {
104    /// The rung's command: its resolved program and leading arguments. The
105    /// caller adds its own.
106    pub fn command(&self) -> Command {
107        let mut cmd = Command::new(&self.path);
108        cmd.args(&self.prefix);
109        cmd
110    }
111
112    /// Why this rung, found on PATH, did not start.
113    pub fn start_failure(&self, e: &std::io::Error) -> String {
114        start_failure(&self.path, e)
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121    use crate::probe::Version;
122
123    /// A toolbox with chosen programs on PATH and `npx` present or not.
124    struct Tools {
125        path: &'static [&'static str],
126        npx: bool,
127    }
128
129    impl Toolbox for Tools {
130        fn on_path(&self, tool: &str) -> Option<PathBuf> {
131            self.path
132                .contains(&tool)
133                .then(|| PathBuf::from(format!("/bin/{tool}")))
134        }
135        fn in_dir(&self, _: &Path, _: &str) -> Option<PathBuf> {
136            None
137        }
138        fn version(&self, _: &Path) -> Option<Version> {
139            None
140        }
141        fn npx_available(&self) -> bool {
142            self.npx
143        }
144    }
145
146    #[test]
147    fn the_tool_ladder_is_the_tool_then_the_runner() {
148        let tb = Tools {
149            path: &["pnpm"],
150            npx: true,
151        };
152        let typescript = pins::typescript_spec();
153        let rungs = tool_ladder("tsc", &typescript, PackageManager::Pnpm, &tb);
154        assert_eq!(
155            rungs,
156            [
157                ("tsc".to_string(), vec![]),
158                (
159                    "pnpm".to_string(),
160                    ["dlx", "--package", typescript.as_str(), "tsc"]
161                        .map(String::from)
162                        .to_vec()
163                )
164            ]
165        );
166        // Yarn classic goes through `npx`, as before.
167        let yarn = tool_ladder("tsx", pins::TSX_SPEC, PackageManager::Yarn, &tb);
168        assert_eq!(yarn[1].0, "npx");
169        assert_eq!(yarn[1].1, ["--yes", "-p", "tsx", "tsx"]);
170        // With no runner at all, only the tool itself is tried.
171        let bare = Tools {
172            path: &[],
173            npx: false,
174        };
175        assert_eq!(
176            tool_ladder("tsx", pins::TSX_SPEC, PackageManager::Yarn, &bare).len(),
177            1
178        );
179    }
180
181    #[test]
182    fn each_manager_puts_its_own_runner_on_the_second_rung() {
183        let tb = Tools {
184            path: &["pnpm", "bunx"],
185            npx: true,
186        };
187        let typescript = pins::typescript_spec();
188        let second = |m: PackageManager| tool_ladder("tsc", &typescript, m, &tb)[1].clone();
189        assert_eq!(
190            second(PackageManager::Npm),
191            (
192                "npx".to_string(),
193                ["--yes", "-p", typescript.as_str(), "tsc"]
194                    .map(String::from)
195                    .to_vec()
196            )
197        );
198        assert_eq!(second(PackageManager::Pnpm).0, "pnpm");
199        assert_eq!(
200            second(PackageManager::Bun),
201            (
202                "bunx".to_string(),
203                ["--package", typescript.as_str(), "tsc"]
204                    .map(String::from)
205                    .to_vec()
206            )
207        );
208        assert_eq!(second(PackageManager::Yarn).0, "npx");
209    }
210
211    #[test]
212    fn a_rung_runs_its_path_with_its_prefix() {
213        let rung = Rung {
214            path: PathBuf::from("/bin/npx"),
215            prefix: ["--yes", "-p", "tsx", "tsx"].map(String::from).to_vec(),
216        };
217        let cmd = rung.command();
218        assert_eq!(cmd.get_program(), std::ffi::OsStr::new("/bin/npx"));
219        let args: Vec<_> = cmd.get_args().map(|a| a.to_string_lossy()).collect();
220        assert_eq!(args, ["--yes", "-p", "tsx", "tsx"]);
221        let e = std::io::Error::from(std::io::ErrorKind::PermissionDenied);
222        assert!(
223            rung.start_failure(&e)
224                .starts_with("`/bin/npx` was found but could not be started: "),
225            "{}",
226            rung.start_failure(&e)
227        );
228    }
229}