Skip to main content

bynk_driver/
probe.rs

1//! The shared detection probe: **presence + version + provenance**.
2//!
3//! This generalises `bynkc`'s old `tool_exists` (which shelled the POSIX
4//! `which` and conceded it was Unix-only). Detection is backed by the `which`
5//! crate, which handles `PATHEXT`/`where` on Windows, so a *user-facing*
6//! environment check tells the truth on every platform (v0.46 portability
7//! decision).
8//!
9//! Lookups go through a [`Toolbox`] so the capability/exit matrix and the
10//! output goldens can run against a deterministic fake instead of the host.
11
12use std::ffi::OsStr;
13use std::path::{Path, PathBuf};
14use std::process::Command;
15
16use crate::npm_install::PackageManager;
17
18/// A parsed tool version. Missing components default to zero, so `"v18"` parses
19/// as `18.0.0` and compares sensibly against a major-version floor.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub struct Version {
22    pub major: u32,
23    pub minor: u32,
24    pub patch: u32,
25}
26
27impl Version {
28    /// Extract the first dotted-decimal run from arbitrary `--version` output
29    /// (e.g. `"v18.17.0"`, `"Version 5.4.2"`, `"⛅️ wrangler 3.90.0"`).
30    pub fn parse(s: &str) -> Option<Version> {
31        let b = s.as_bytes();
32        let mut i = 0;
33        while i < b.len() && !b[i].is_ascii_digit() {
34            i += 1;
35        }
36        if i >= b.len() {
37            return None;
38        }
39        let mut nums = [0u32; 3];
40        let mut slot = 0;
41        while i < b.len() && slot < 3 {
42            let start = i;
43            while i < b.len() && b[i].is_ascii_digit() {
44                i += 1;
45            }
46            nums[slot] = s[start..i].parse().ok()?;
47            slot += 1;
48            if i < b.len() && b[i] == b'.' {
49                i += 1;
50            } else {
51                break;
52            }
53        }
54        Some(Version {
55            major: nums[0],
56            minor: nums[1],
57            patch: nums[2],
58        })
59    }
60}
61
62impl std::fmt::Display for Version {
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
65    }
66}
67
68/// Where a tool was found — the **provenance** half of a probe. The distinction
69/// between [`Provenance::Path`]/[`Provenance::ProjectLocal`] (installed) and
70/// [`Provenance::Runner`] (fetchable on demand) is the whole point: `npx --yes`
71/// (or `pnpm dlx`, `bunx`) will *download* a package at first use, so it must never read as a green
72/// "ok".
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub enum Provenance {
75    /// On the global `PATH`, at this resolved path.
76    Path(PathBuf),
77    /// In a project-local `node_modules/.bin` (preferred over `PATH`).
78    ProjectLocal(PathBuf),
79    /// Not installed, but **provisionable** through the package manager's
80    /// runner (`npx --yes`, `pnpm dlx`, `bunx`) — a deferred download, not a
81    /// present tool. Holds the manager whose runner it is.
82    Runner(PackageManager),
83    /// Not found, and not provisionable.
84    Missing,
85}
86
87impl Provenance {
88    /// The stable token used in `--format json`/`short` and the human table.
89    pub fn token(&self) -> &'static str {
90        match self {
91            Provenance::Path(_) => "path",
92            Provenance::ProjectLocal(_) => "project-local",
93            Provenance::Runner(PackageManager::Pnpm) => "pnpm-dlx",
94            Provenance::Runner(PackageManager::Bun) => "bunx",
95            // Yarn classic has no runner of its own and never reaches here.
96            Provenance::Runner(PackageManager::Npm | PackageManager::Yarn) => "npx",
97            Provenance::Missing => "missing",
98        }
99    }
100
101    /// The runner that would fetch the tool (`npx`, `pnpm dlx`, `bunx`), for
102    /// provisionable tools.
103    pub fn runner_label(&self) -> Option<&'static str> {
104        match self {
105            Provenance::Runner(m) => m.runner_label().or(Some("npx")),
106            _ => None,
107        }
108    }
109
110    /// The resolved path, if the tool is actually installed.
111    pub fn path(&self) -> Option<&Path> {
112        match self {
113            Provenance::Path(p) | Provenance::ProjectLocal(p) => Some(p),
114            _ => None,
115        }
116    }
117}
118
119/// One detection result: a tool, its version (if installed and it reports one),
120/// and where it came from.
121#[derive(Debug, Clone)]
122pub struct Probe {
123    pub tool: String,
124    pub version: Option<Version>,
125    pub provenance: Provenance,
126}
127
128impl Probe {
129    /// Installed on disk (`PATH` or project-local) — not merely provisionable.
130    pub fn is_present(&self) -> bool {
131        matches!(
132            self.provenance,
133            Provenance::Path(_) | Provenance::ProjectLocal(_)
134        )
135    }
136
137    /// Absent but fetchable on demand through a runner (`npx`, `pnpm dlx`, `bunx`).
138    pub fn is_provisionable(&self) -> bool {
139        matches!(self.provenance, Provenance::Runner(_))
140    }
141
142    /// Neither installed nor provisionable.
143    pub fn is_missing(&self) -> bool {
144        matches!(self.provenance, Provenance::Missing)
145    }
146}
147
148/// How a detection should look: where to search, and whether a runner's
149/// fetch-on-demand counts as a (provisionable) fallback. `node` itself is never
150/// `allow_npx` — you cannot `npx` a runtime. `manager` is the package manager
151/// whose runner is tried first (`None`: npm, so `npx`).
152#[derive(Debug, Clone, Copy, Default)]
153pub struct DetectOpts<'a> {
154    pub project_root: Option<&'a Path>,
155    pub allow_npx: bool,
156    pub manager: Option<PackageManager>,
157}
158
159/// Abstraction over the host so detection is testable. The real implementation
160/// is [`SystemToolbox`]; tests supply a deterministic fake.
161pub trait Toolbox {
162    /// Resolve `tool` on the global `PATH` (with `PATHEXT` semantics).
163    fn on_path(&self, tool: &str) -> Option<PathBuf>;
164    /// Resolve `tool` inside a specific directory (a `node_modules/.bin`).
165    fn in_dir(&self, dir: &Path, tool: &str) -> Option<PathBuf>;
166    /// Run `<path> --version` and parse the first version it prints.
167    fn version(&self, path: &Path) -> Option<Version>;
168    /// Is `npx` itself available to provision packages on demand?
169    fn npx_available(&self) -> bool;
170    /// #3477: does the Docker CLI at `path` reach a running daemon (`docker
171    /// info` succeeds)? Building a container image needs one. The default says
172    /// yes, so a fake that does not model Docker is not made to fail.
173    fn docker_daemon_running(&self, _path: &Path) -> bool {
174        true
175    }
176}
177
178/// Detect a single tool: project-local first (it wins over a global install),
179/// then `PATH`, then — only if `allow_npx` — a runner-provisionable fallback,
180/// else missing.
181pub fn detect(tb: &dyn Toolbox, tool: &str, opts: DetectOpts<'_>) -> Probe {
182    if let Some(root) = opts.project_root {
183        let bin = root.join("node_modules").join(".bin");
184        if let Some(p) = tb.in_dir(&bin, tool) {
185            let version = tb.version(&p);
186            return Probe {
187                tool: tool.to_string(),
188                version,
189                provenance: Provenance::ProjectLocal(p),
190            };
191        }
192    }
193    if let Some(p) = tb.on_path(tool) {
194        let version = tb.version(&p);
195        return Probe {
196            tool: tool.to_string(),
197            version,
198            provenance: Provenance::Path(p),
199        };
200    }
201    if opts.allow_npx
202        && let Some(runner) = opts.manager.unwrap_or(PackageManager::Npm).runner(tb)
203    {
204        return Probe {
205            tool: tool.to_string(),
206            version: None,
207            provenance: Provenance::Runner(runner),
208        };
209    }
210    Probe {
211        tool: tool.to_string(),
212        version: None,
213        provenance: Provenance::Missing,
214    }
215}
216
217/// Detect `tool` for the project at `project_root`: project-local first, then
218/// `PATH`, then the runner of the package manager detected for the project.
219/// Returns that manager too, since hints follow it.
220pub fn detect_in_project(
221    tb: &dyn Toolbox,
222    tool: &str,
223    project_root: &Path,
224) -> (PackageManager, Probe) {
225    let manager = crate::npm_install::manager_in(project_root, tb);
226    let opts = DetectOpts {
227        project_root: Some(project_root),
228        allow_npx: true,
229        manager: Some(manager),
230    };
231    (manager, detect(tb, tool, opts))
232}
233
234/// #1758: the program to spawn for `tool`: the path `which` resolves on
235/// `PATH`, or the bare name when it resolves nothing. Spawn tools through this
236/// rather than `Command::new("<name>")`. On Windows, `Command` looks up a bare
237/// name with `.exe` only, so an npm shim (`npx.cmd`, `tsc.cmd`) that detection
238/// finds through `PATHEXT` is never started. An explicit path to a `.cmd` is
239/// spawned correctly, with its arguments escaped.
240///
241/// Resolved through [`SystemToolbox::on_path`], the same lookup detection uses,
242/// so the spawned program is the one a probe of `tool` reports.
243pub fn program_path(tool: &str) -> PathBuf {
244    SystemToolbox
245        .on_path(tool)
246        .unwrap_or_else(|| PathBuf::from(tool))
247}
248
249/// The real host: `which`-crate lookups and a `--version` shell-out.
250#[derive(Debug, Default, Clone, Copy)]
251pub struct SystemToolbox;
252
253impl Toolbox for SystemToolbox {
254    fn on_path(&self, tool: &str) -> Option<PathBuf> {
255        which::which(tool).ok()
256    }
257
258    fn in_dir(&self, dir: &Path, tool: &str) -> Option<PathBuf> {
259        // `which_in` applies the same PATHEXT/extension resolution inside the
260        // given directory, so a Windows `tsc.cmd`/`tsc.exe` resolves too.
261        which::which_in(tool, Some(dir.as_os_str()), dir).ok()
262    }
263
264    fn version(&self, path: &Path) -> Option<Version> {
265        let out = Command::new(path).arg("--version").output().ok()?;
266        let stdout = String::from_utf8_lossy(&out.stdout);
267        let parsed = Version::parse(&stdout);
268        if parsed.is_some() {
269            return parsed;
270        }
271        // Some tools print their version banner to stderr.
272        Version::parse(&String::from_utf8_lossy(&out.stderr))
273    }
274
275    fn npx_available(&self) -> bool {
276        which::which(OsStr::new("npx")).is_ok()
277    }
278
279    fn docker_daemon_running(&self, path: &Path) -> bool {
280        // A wedged Docker Desktop or an unreachable `DOCKER_HOST` can leave
281        // `docker info` waiting for a long time; past the bound it counts as
282        // no daemon running.
283        let Ok(mut child) = Command::new(path)
284            .arg("info")
285            .stdin(std::process::Stdio::null())
286            .stdout(std::process::Stdio::null())
287            .stderr(std::process::Stdio::null())
288            .spawn()
289        else {
290            return false;
291        };
292        let deadline = std::time::Instant::now() + DOCKER_INFO_TIMEOUT;
293        loop {
294            match child.try_wait() {
295                Ok(Some(status)) => return status.success(),
296                Ok(None) if std::time::Instant::now() < deadline => {
297                    std::thread::sleep(std::time::Duration::from_millis(50));
298                }
299                _ => {
300                    let _ = child.kill();
301                    let _ = child.wait();
302                    return false;
303                }
304            }
305        }
306    }
307}
308
309/// How long `docker info` may take before the daemon counts as not running.
310const DOCKER_INFO_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315
316    #[test]
317    fn parses_common_version_banners() {
318        assert_eq!(
319            Version::parse("v18.17.0"),
320            Some(Version {
321                major: 18,
322                minor: 17,
323                patch: 0
324            })
325        );
326        assert_eq!(
327            Version::parse("Version 5.4.2"),
328            Some(Version {
329                major: 5,
330                minor: 4,
331                patch: 2
332            })
333        );
334        assert_eq!(
335            Version::parse("⛅️ wrangler 3.90.0"),
336            Some(Version {
337                major: 3,
338                minor: 90,
339                patch: 0
340            })
341        );
342        assert_eq!(
343            Version::parse("v20"),
344            Some(Version {
345                major: 20,
346                minor: 0,
347                patch: 0
348            })
349        );
350        assert_eq!(Version::parse("no digits here"), None);
351    }
352}