Skip to main content

rust_anything/
doctor.rs

1//! `doctor`: check the toolchains, the agent setup and the MCP server on this machine, and say
2//! the command that fixes each problem.
3//!
4//! Language runtimes are optional: each matters only for the languages being ported. Cargo, the
5//! MCP server and the setup of every agent found on the machine are required.
6
7use std::io::{BufRead, BufReader, Write};
8use std::path::{Path, PathBuf};
9use std::process::{Command, Stdio};
10use std::sync::mpsc;
11use std::time::{Duration, Instant};
12
13use serde::Serialize;
14use serde_json::{Value, json};
15
16use crate::setup::{self, Agent, NAME, SKILL_FILES};
17use crate::walk::Canonical;
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
20#[serde(rename_all = "lowercase")]
21pub enum Status {
22    Ok,
23    Missing,
24    Outdated,
25    /// Something named rust-anything is there, but it is not ours.
26    Foreign,
27}
28
29impl Status {
30    fn label(self) -> &'static str {
31        match self {
32            Status::Ok => "ok",
33            Status::Missing => "missing",
34            Status::Outdated => "outdated",
35            Status::Foreign => "foreign",
36        }
37    }
38}
39
40#[derive(Debug, Serialize)]
41pub struct Check {
42    pub name: String,
43    pub status: Status,
44    /// A problem here makes `doctor` exit 1; optional checks only matter for some languages.
45    pub required: bool,
46    pub detail: String,
47    pub fix: Option<String>,
48}
49
50#[derive(Debug, Serialize)]
51pub struct Report {
52    pub checks: Vec<Check>,
53}
54
55impl Report {
56    /// Whether every required check passed.
57    pub fn ok(&self) -> bool {
58        self.checks
59            .iter()
60            .all(|c| !c.required || c.status == Status::Ok)
61    }
62}
63
64/// A version as `major.minor.patch`.
65#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
66pub struct Version(pub u32, pub u32, pub u32);
67
68impl std::fmt::Display for Version {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        write!(f, "{}.{}.{}", self.0, self.1, self.2)
71    }
72}
73
74/// The first `N[.N[.N]]` in a version banner (`v24.1.0`, `go version go1.22.3 ...`,
75/// `openjdk version "21.0.2"`, `ruby 2.6.10p210`).
76pub fn parse_version(text: &str) -> Option<Version> {
77    let start = text.find(|c: char| c.is_ascii_digit())?;
78    let mut parts = text[start..]
79        .split(|c: char| !c.is_ascii_digit() && c != '.')
80        .next()?
81        .split('.')
82        .map(|p| p.parse::<u32>().ok());
83    let major = parts.next()??;
84    let minor = parts.next().flatten().unwrap_or(0);
85    let patch = parts.next().flatten().unwrap_or(0);
86    Some(Version(major, minor, patch))
87}
88
89/// Java's version, reading the old `1.8.0` scheme as 8.
90pub fn parse_java_version(text: &str) -> Option<Version> {
91    parse_version(text).map(|v| match v {
92        Version(1, minor, patch) => Version(minor, patch, 0),
93        v => v,
94    })
95}
96
97/// A runtime's status from whether it ran, its version and the oldest version that works.
98pub fn grade(ran: bool, version: Option<Version>, minimum: Option<Version>) -> Status {
99    match (ran, version, minimum) {
100        (false, _, _) => Status::Missing,
101        (true, Some(v), Some(min)) if v < min => Status::Outdated,
102        _ => Status::Ok,
103    }
104}
105
106/// The state of something `setup` installs: an MCP entry or the skill.
107#[derive(Clone, Copy, Debug, PartialEq, Eq)]
108pub enum Install {
109    Missing,
110    Current,
111    Outdated,
112    Foreign,
113}
114
115impl From<Install> for Status {
116    fn from(i: Install) -> Status {
117        match i {
118            Install::Missing => Status::Missing,
119            Install::Current => Status::Ok,
120            Install::Outdated => Status::Outdated,
121            Install::Foreign => Status::Foreign,
122        }
123    }
124}
125
126/// An agent's `rust-anything` MCP server entry, as read from its settings.
127#[derive(Debug, Default)]
128pub struct Entry {
129    pub command: Option<String>,
130    pub args: Vec<String>,
131    pub url: bool,
132    /// OpenCode keeps a configured server out of the way with `disabled`; never set elsewhere.
133    pub disabled: bool,
134}
135
136/// Ours and current when it runs `<exe> mcp`; outdated when it runs `mcp` on another binary.
137pub fn entry_state(entry: Option<&Entry>, exe: &Path) -> Install {
138    let Some(entry) = entry else {
139        return Install::Missing;
140    };
141    let Some(command) = entry.command.as_deref() else {
142        return Install::Foreign;
143    };
144    if entry.url {
145        return Install::Foreign;
146    }
147    let npx = match entry.args.as_slice() {
148        [y, package, mcp] if y == "-y" && mcp == "mcp" && command == "npx" => Some(package),
149        [c, n, y, package, mcp]
150            if c == "/c" && n == "npx" && y == "-y" && mcp == "mcp" && command == "cmd" =>
151        {
152            Some(package)
153        }
154        _ => None,
155    };
156    if let Some(package) = npx {
157        if package != NAME && !package.starts_with(&format!("{NAME}@")) {
158            return Install::Foreign;
159        }
160        let wanted = crate::setup::launcher(exe);
161        return if !entry.disabled && wanted.command == command && wanted.args == entry.args {
162            Install::Current
163        } else {
164            Install::Outdated
165        };
166    }
167    if entry.args != ["mcp"] {
168        return Install::Foreign;
169    }
170    if entry.disabled {
171        return Install::Outdated;
172    }
173    let path = Path::new(command);
174    if path == exe || path.canonical().is_ok_and(|p| p == exe) {
175        Install::Current
176    } else {
177        Install::Outdated
178    }
179}
180
181/// The installed skill files, in `SKILL_FILES` order, against the embedded copies.
182pub fn skill_state(installed: &[Option<String>]) -> Install {
183    let Some(main) = installed.first().and_then(Option::as_deref) else {
184        return if installed.iter().all(Option::is_none) {
185            Install::Missing
186        } else {
187            Install::Outdated
188        };
189    };
190    if installed
191        .iter()
192        .zip(SKILL_FILES)
193        .all(|(have, (_, want))| have.as_deref() == Some(*want))
194    {
195        Install::Current
196    } else if main
197        .lines()
198        .take_while(|l| !l.is_empty())
199        .any(|l| l.trim() == format!("name: {NAME}"))
200    {
201        Install::Outdated
202    } else {
203        Install::Foreign
204    }
205}
206
207pub fn run() -> Report {
208    let exe = std::env::current_exe()
209        .and_then(|p| p.canonical())
210        .unwrap_or_else(|_| PathBuf::from(NAME));
211    let mut checks: Vec<Check> = std::thread::scope(|s| {
212        let probes: Vec<_> = RUNTIMES.iter().map(|r| s.spawn(|| runtime(r))).collect();
213        let wasm = s.spawn(wasm_target);
214        let ndk = s.spawn(android_ndk);
215        let android_targets = s.spawn(android_targets);
216        let adb = s.spawn(android_adb);
217        let mcp = s.spawn(|| mcp_self_test(&exe));
218        let mut checks: Vec<Check> = probes
219            .into_iter()
220            .map(|p| p.join().expect("a runtime probe panicked"))
221            .collect();
222        checks.push(wasm.join().expect("the wasm probe panicked"));
223        checks.push(ndk.join().expect("the NDK probe panicked"));
224        checks.push(
225            android_targets
226                .join()
227                .expect("the Android targets probe panicked"),
228        );
229        checks.push(adb.join().expect("the adb probe panicked"));
230        checks.push(mcp.join().expect("the MCP self-test panicked"));
231        checks
232    });
233    checks.extend(agents(&exe));
234    Report { checks }
235}
236
237/// The command `doctor` gives on this platform to install or update a runtime, by its name.
238pub(crate) fn install_command(name: &str) -> Option<String> {
239    let r = RUNTIMES.iter().find(|r| r.name == name)?;
240    runtime_fix(r, Status::Outdated, Platform::HERE)
241}
242
243/// The command `doctor` gives on this platform when a runtime is missing, matched by its name or
244/// executable (`program`).
245pub(crate) fn missing_command(program: &str) -> Option<String> {
246    let lookup = program.strip_suffix(".exe").unwrap_or(program);
247    let r = RUNTIMES.iter().find(|r| {
248        r.program == program
249            || r.program == lookup
250            || r.name == lookup
251            || (lookup == "python" && r.name == "python3")
252    })?;
253    runtime_fix(r, Status::Missing, Platform::HERE)
254}
255
256/// The oldest version of a runtime that `doctor` accepts, by its name.
257pub(crate) fn minimum(name: &str) -> Option<Version> {
258    RUNTIMES.iter().find(|r| r.name == name)?.minimum
259}
260
261struct Runtime {
262    name: &'static str,
263    program: &'static str,
264    args: &'static [&'static str],
265    minimum: Option<Version>,
266    required: bool,
267    java: bool,
268    /// Fix commands: macOS, Windows, elsewhere.
269    fix: [&'static str; 3],
270}
271
272/// The C++ Build Tools, which Rust links with on Windows. Without `--add`, winget installs them
273/// with no workload: no compiler, linker or Windows SDK. The workload's recommended tools build for
274/// x64 and x86, so a build for Windows on ARM (npm has no binary for it) adds the ARM64 tools.
275const BUILD_TOOLS: &str = if cfg!(all(windows, target_arch = "aarch64")) {
276    BUILD_TOOLS_ARM64
277} else {
278    BUILD_TOOLS_X64
279};
280const BUILD_TOOLS_X64: &str = "winget install Microsoft.VisualStudio.2022.BuildTools --override \"--wait --passive --norestart --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended\"";
281const BUILD_TOOLS_ARM64: &str = "winget install Microsoft.VisualStudio.2022.BuildTools --override \"--wait --passive --norestart --add Microsoft.VisualStudio.Workload.VCTools --includeRecommended --add Microsoft.VisualStudio.Component.VC.Tools.ARM64\"";
282/// winget adds nothing to Build Tools that are already installed: an upgrade cannot add a workload.
283const BUILD_TOOLS_INSTALLED: &str = "(Build Tools already installed: add \"Desktop development with C++\" in Visual Studio Installer)";
284
285const RUNTIMES: &[Runtime] = &[
286    Runtime {
287        name: "cargo",
288        program: "cargo",
289        args: &["--version"],
290        minimum: Some(Version(1, 97, 0)),
291        required: true,
292        java: false,
293        fix: [
294            "rustup update stable",
295            "rustup update stable",
296            "rustup update stable",
297        ],
298    },
299    Runtime {
300        name: "node",
301        program: "node",
302        args: &["--version"],
303        minimum: Some(Version(22, 6, 0)),
304        required: false,
305        java: false,
306        fix: [
307            "brew install node@24",
308            "winget install OpenJS.NodeJS",
309            "fnm install 24 && fnm default 24",
310        ],
311    },
312    Runtime {
313        name: "python3",
314        program: if cfg!(windows) { "python" } else { "python3" },
315        args: &["--version"],
316        minimum: Some(Version(3, 9, 0)),
317        required: false,
318        java: false,
319        fix: [
320            "brew install python@3.13",
321            "winget install Python.Python.3.13",
322            "sudo apt install python3",
323        ],
324    },
325    Runtime {
326        name: "cc",
327        program: "cc",
328        args: &["--version"],
329        minimum: None,
330        required: false,
331        java: false,
332        fix: [
333            "xcode-select --install",
334            BUILD_TOOLS,
335            "sudo apt install build-essential",
336        ],
337    },
338    Runtime {
339        name: "go",
340        program: "go",
341        args: &["version"],
342        minimum: Some(Version(1, 22, 0)),
343        required: false,
344        java: false,
345        fix: [
346            "brew install go",
347            "winget install GoLang.Go",
348            "install Go 1.22+ from https://go.dev/dl",
349        ],
350    },
351    Runtime {
352        name: "ruby",
353        program: "ruby",
354        args: &["--version"],
355        minimum: Some(Version(3, 0, 0)),
356        required: false,
357        java: false,
358        fix: [
359            "brew install ruby && export PATH=\"$(brew --prefix ruby)/bin:$PATH\"",
360            "winget install RubyInstallerTeam.RubyWithDevKit.3.4",
361            "sudo apt install ruby-full",
362        ],
363    },
364    Runtime {
365        name: "java",
366        program: "java",
367        args: &["-version"],
368        minimum: Some(Version(17, 0, 0)),
369        required: false,
370        java: true,
371        fix: [
372            "brew install openjdk@21",
373            "winget install EclipseAdoptium.Temurin.21.JDK",
374            "sudo apt install openjdk-21-jdk",
375        ],
376    },
377    Runtime {
378        name: "javac",
379        program: "javac",
380        args: &["-version"],
381        minimum: Some(Version(17, 0, 0)),
382        required: false,
383        java: true,
384        fix: [
385            "brew install openjdk@21",
386            "winget install EclipseAdoptium.Temurin.21.JDK",
387            "sudo apt install openjdk-21-jdk",
388        ],
389    },
390    Runtime {
391        name: "kotlinc",
392        program: "kotlinc",
393        args: &["-version"],
394        minimum: None,
395        required: false,
396        java: false,
397        fix: [
398            "brew install kotlin",
399            "winget install JetBrains.Kotlin",
400            "sdk install kotlin",
401        ],
402    },
403    Runtime {
404        name: "php",
405        program: "php",
406        args: &["--version"],
407        minimum: Some(Version(8, 0, 0)),
408        required: false,
409        java: false,
410        fix: [
411            "brew install php",
412            "winget install PHP.PHP.8.4",
413            "sudo apt install php-cli",
414        ],
415    },
416    Runtime {
417        name: "dotnet",
418        program: "dotnet",
419        args: &["--version"],
420        minimum: None,
421        required: false,
422        java: false,
423        fix: [
424            "brew install --cask dotnet-sdk",
425            "winget install Microsoft.DotNet.SDK.8",
426            "install the .NET SDK from https://dotnet.microsoft.com/download",
427        ],
428    },
429    Runtime {
430        name: "pwsh",
431        program: "pwsh",
432        args: &["-NoProfile", "-NonInteractive", "-Version"],
433        minimum: Some(Version(7, 4, 0)),
434        required: false,
435        java: false,
436        fix: [
437            "brew install powershell",
438            "winget install Microsoft.PowerShell",
439            "install PowerShell 7.4+ from https://aka.ms/install-powershell",
440        ],
441    },
442    Runtime {
443        name: "wasm-bindgen",
444        program: "wasm-bindgen",
445        args: &["--version"],
446        minimum: None,
447        required: false,
448        java: false,
449        fix: [
450            "cargo install wasm-bindgen-cli --version <the crate's wasm-bindgen version> --locked",
451            "cargo install wasm-bindgen-cli --version <the crate's wasm-bindgen version> --locked",
452            "cargo install wasm-bindgen-cli --version <the crate's wasm-bindgen version> --locked",
453        ],
454    },
455];
456
457/// Where a fix runs: [`Runtime::fix`] has one command for each, in this order.
458#[derive(Clone, Copy, Debug, PartialEq, Eq)]
459enum Platform {
460    MacOs,
461    Windows,
462    Other,
463}
464
465impl Platform {
466    const HERE: Platform = if cfg!(target_os = "macos") {
467        Platform::MacOs
468    } else if cfg!(windows) {
469        Platform::Windows
470    } else {
471        Platform::Other
472    };
473
474    fn pick(self, fix: &[&'static str; 3]) -> &'static str {
475        fix[self as usize]
476    }
477}
478
479/// The commands that install or update `r` on `platform`, one per line, to run in order; `None`
480/// when it is fine.
481fn runtime_fix(r: &Runtime, status: Status, platform: Platform) -> Option<String> {
482    let fix = match (status, r.name) {
483        (Status::Ok, _) => return None,
484        (Status::Outdated, "cargo") => "rustup update stable".to_string(),
485        // rustup's script needs a Unix shell. winget runs `rustup-init -y`, which skips the Build
486        // Tools with a warning, so they come first, on a line of their own: `cmd` does not split
487        // commands at `;`.
488        (Status::Missing, "cargo") if platform == Platform::Windows => {
489            format!("{BUILD_TOOLS}\nwinget install Rustlang.Rustup")
490        }
491        (Status::Missing, "cargo") => {
492            "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh".to_string()
493        }
494        _ => platform.pick(&r.fix).to_string(),
495    };
496    Some(if fix.starts_with(BUILD_TOOLS) {
497        format!("{fix}\n{BUILD_TOOLS_INSTALLED}")
498    } else {
499        fix
500    })
501}
502
503/// The program's banner (stdout, else stderr), or `None` when it did not run.
504fn probe(program: &str, args: &[&str]) -> Option<String> {
505    let out =
506        crate::process::output(Command::new(program).args(args), crate::process::QUICK).ok()?;
507    if !out.success() {
508        return None;
509    }
510    let text = out.stdout_text();
511    let text = if text.trim().is_empty() {
512        out.stderr_text()
513    } else {
514        text
515    };
516    Some(text.lines().next().unwrap_or_default().trim().to_string())
517}
518
519fn which(program: &str) -> Option<PathBuf> {
520    std::env::split_paths(&std::env::var_os("PATH")?)
521        .map(|dir| dir.join(program))
522        .find(|p| p.is_file())
523}
524
525/// Whether `php -m` lists the `FFI` extension.
526pub fn php_has_ffi(modules: &str) -> bool {
527    modules
528        .lines()
529        .any(|l| l.trim().eq_ignore_ascii_case("ffi"))
530}
531
532fn php_modules(program: &str) -> Option<String> {
533    let out =
534        crate::process::output(Command::new(program).arg("-m"), crate::process::QUICK).ok()?;
535    out.success().then(|| out.stdout_text())
536}
537
538fn php_ffi_fix(platform: Platform) -> &'static str {
539    match platform {
540        Platform::MacOs => {
541            "brew install php  (or enable `extension=ffi` in the `php.ini` shown by `php --ini`)"
542        }
543        Platform::Windows => {
544            "enable `extension=ffi` (and `extension_dir=\"ext\"`) in the `php.ini` shown by `php --ini`"
545        }
546        Platform::Other => {
547            "enable `extension=ffi` in the `php.ini` shown by `php --ini` (or install `php-ffi`)"
548        }
549    }
550}
551
552fn runtime(r: &Runtime) -> Check {
553    let banner = probe(r.program, r.args);
554    let version = banner.as_deref().and_then(if r.java {
555        parse_java_version
556    } else {
557        parse_version
558    });
559    let modules = (r.name == "php" && grade(banner.is_some(), version, r.minimum) == Status::Ok)
560        .then(|| php_modules(r.program))
561        .flatten();
562    runtime_check(r, banner.as_deref(), modules.as_deref(), Platform::HERE)
563}
564
565fn runtime_check(
566    r: &Runtime,
567    banner: Option<&str>,
568    php_modules: Option<&str>,
569    platform: Platform,
570) -> Check {
571    let version = banner.and_then(if r.java {
572        parse_java_version
573    } else {
574        parse_version
575    });
576    let mut status = grade(banner.is_some(), version, r.minimum);
577    let mut detail = match (banner, r.minimum) {
578        (None, _) => format!("`{}` not found or did not run", r.program),
579        (Some(b), Some(min)) if status == Status::Outdated => {
580            format!("{b}; rust-anything needs {}.{}+", min.0, min.1)
581        }
582        (Some(b), _) => b.to_string(),
583    };
584    if r.name == "node" && status == Status::Ok && version.is_some_and(|v| v.0 < 24) {
585        detail.push_str("; works, but `profile` through `npx` or `npm run` may need Node 24");
586    }
587    if r.name == "ruby" && status == Status::Outdated {
588        detail.push_str("; magnus/rb-sys extensions do not build on Ruby 2");
589        if platform == Platform::MacOs && which("ruby").is_some_and(|p| p.starts_with("/usr/bin")) {
590            detail.push_str(" (this is macOS's system Ruby)");
591        }
592    }
593    let mut fix = runtime_fix(r, status, platform);
594    if r.name == "php" && status == Status::Ok {
595        match php_modules {
596            Some(m) if php_has_ffi(m) => detail.push_str(" (FFI loaded)"),
597            Some(_) => {
598                status = Status::Missing;
599                detail.push_str("; FFI extension not loaded");
600                fix = Some(php_ffi_fix(platform).to_string());
601            }
602            None => {
603                status = Status::Missing;
604                detail.push_str("; could not check the FFI extension (`php -m` failed)");
605                fix = Some(php_ffi_fix(platform).to_string());
606            }
607        }
608    }
609    Check {
610        name: r.name.to_string(),
611        status,
612        required: r.required,
613        detail,
614        fix,
615    }
616}
617
618fn wasm_target() -> Check {
619    const TARGET: &str = "wasm32-unknown-unknown";
620    let installed = crate::process::output(
621        Command::new("rustup").args(["target", "list", "--installed"]),
622        crate::process::QUICK,
623    )
624    .ok()
625    .filter(|o| o.success())
626    .map(|o| o.stdout_text());
627    let (status, detail) = match installed {
628        None => (Status::Missing, "`rustup` not found or did not run".into()),
629        Some(list) if list.lines().any(|l| l.trim() == TARGET) => {
630            (Status::Ok, format!("{TARGET} installed"))
631        }
632        Some(_) => (Status::Missing, format!("{TARGET} not installed")),
633    };
634    Check {
635        name: TARGET.into(),
636        status,
637        required: false,
638        detail,
639        fix: (status != Status::Ok).then(|| format!("rustup target add {TARGET}")),
640    }
641}
642
643/// The Android NDK `build --profile android` links with.
644fn android_ndk() -> Check {
645    let (status, detail) = match crate::android::ndk_root(None) {
646        Ok(path) => (Status::Ok, path.display().to_string()),
647        Err(e) => (Status::Missing, format!("{e:#}")),
648    };
649    Check {
650        name: "Android NDK".into(),
651        status,
652        required: false,
653        detail,
654        fix: (status != Status::Ok).then(|| {
655            "sdkmanager \"ndk;28.0.13004108\"  (or set ANDROID_NDK_HOME to an installed NDK)"
656                .to_string()
657        }),
658    }
659}
660
661/// `adb`, which `record`/`diff --profile android` use to reach a device.
662fn android_adb() -> Check {
663    let probe = probe("adb", &["version"]);
664    let (status, detail) = match probe.as_deref() {
665        Some(banner) => (
666            Status::Ok,
667            banner.lines().next().unwrap_or(banner).to_string(),
668        ),
669        None => (
670            Status::Missing,
671            "`adb` not found or did not run; recording and diffing on a device needs it".into(),
672        ),
673    };
674    Check {
675        name: "Android adb".into(),
676        status,
677        required: false,
678        detail,
679        fix: (status != Status::Ok).then(|| {
680            // The package alone is not enough: its folder has to be on PATH, or the next probe
681            // still cannot find `adb`.
682            "sdkmanager \"platform-tools\"  (or install Android Studio's SDK tools), then put its \
683             platform-tools folder on PATH"
684                .to_string()
685        }),
686    }
687}
688
689/// The Rust targets `build --profile android` needs.
690fn android_targets() -> Check {
691    let wanted: Vec<&str> = crate::android::DEFAULT_ABIS
692        .iter()
693        .map(|a| a.triple())
694        .collect();
695    let installed = crate::process::output(
696        Command::new("rustup").args(["target", "list", "--installed"]),
697        crate::process::QUICK,
698    )
699    .ok()
700    .filter(|o| o.success())
701    .map(|o| o.stdout_text());
702    let (status, detail, fix) = match installed {
703        None => (
704            Status::Missing,
705            "`rustup` not found or did not run".into(),
706            "install Rust with rustup (https://rustup.rs) to add Android targets".to_string(),
707        ),
708        Some(list) => {
709            let missing: Vec<&str> = wanted
710                .iter()
711                .copied()
712                .filter(|t| !list.lines().any(|l| l.trim() == *t))
713                .collect();
714            if missing.is_empty() {
715                (
716                    Status::Ok,
717                    format!("{} installed", wanted.join(", ")),
718                    String::new(),
719                )
720            } else {
721                (
722                    Status::Missing,
723                    format!("not installed: {}", missing.join(", ")),
724                    format!("rustup target add {}", missing.join(" ")),
725                )
726            }
727        }
728    };
729    Check {
730        name: "Android Rust targets".into(),
731        status,
732        required: false,
733        detail,
734        fix: (status != Status::Ok).then_some(fix),
735    }
736}
737
738/// Starts `<exe> mcp`, asks for `initialize` and `tools/list`, and expects both answers in 10 s.
739fn mcp_self_test(exe: &Path) -> Check {
740    let (status, detail) = match talk_to_mcp(exe, Duration::from_secs(10)) {
741        Ok(tools) => (
742            Status::Ok,
743            format!("`{} mcp` answered with {tools} tools", exe.display()),
744        ),
745        Err(e) => (Status::Missing, format!("`{} mcp`: {e}", exe.display())),
746    };
747    Check {
748        name: "mcp server".into(),
749        status,
750        required: true,
751        detail,
752        fix: (status != Status::Ok).then(|| {
753            format!(
754                "run `{} mcp` by hand and look at what it prints; reinstall with `cargo install rust-anything`",
755                quoted(exe)
756            )
757        }),
758    }
759}
760
761fn talk_to_mcp(exe: &Path, limit: Duration) -> Result<usize, String> {
762    let mut child = Command::new(exe)
763        .arg("mcp")
764        .stdin(Stdio::piped())
765        .stdout(Stdio::piped())
766        .stderr(Stdio::null())
767        .spawn()
768        .map_err(|e| format!("could not start: {e}"))?;
769    let requests = [
770        json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "rust-anything-doctor", "version": env!("CARGO_PKG_VERSION")}}}),
771        json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
772        json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}),
773    ];
774    if let Some(mut stdin) = child.stdin.take() {
775        for r in &requests {
776            let _ = writeln!(stdin, "{r}");
777        }
778    }
779    let (tx, rx) = mpsc::channel();
780    if let Some(stdout) = child.stdout.take() {
781        std::thread::spawn(move || {
782            for line in BufReader::new(stdout).lines() {
783                let Ok(line) = line else { break };
784                if tx.send(line).is_err() {
785                    break;
786                }
787            }
788        });
789    }
790    let deadline = Instant::now() + limit;
791    let mut init = None;
792    let mut list = None;
793    let outcome = loop {
794        if let (Some(_), Some(_)) = (&init, &list) {
795            break Ok(());
796        }
797        let left = deadline.saturating_duration_since(Instant::now());
798        match rx.recv_timeout(left) {
799            Ok(line) => {
800                let Ok(reply) = serde_json::from_str::<Value>(&line) else {
801                    break Err(format!("printed a line that is not JSON: {line}"));
802                };
803                match reply["id"].as_i64() {
804                    Some(1) => init = Some(reply),
805                    Some(2) => list = Some(reply),
806                    _ => {}
807                }
808            }
809            Err(mpsc::RecvTimeoutError::Timeout) => {
810                break Err(format!("no answer within {}s", limit.as_secs()));
811            }
812            Err(mpsc::RecvTimeoutError::Disconnected) => {
813                break Err("exited before answering".to_string());
814            }
815        }
816    };
817    let _ = child.kill();
818    let _ = child.wait();
819    outcome?;
820    let init = init.unwrap_or_default();
821    let list = list.unwrap_or_default();
822    if !init["result"]["protocolVersion"].is_string() {
823        return Err(format!("`initialize` gave no protocol version: {init}"));
824    }
825    match list["result"]["tools"].as_array() {
826        Some(tools) if !tools.is_empty() => Ok(tools.len()),
827        _ => Err(format!("`tools/list` listed no tools: {list}")),
828    }
829}
830
831fn quoted(path: &Path) -> String {
832    let text = path.display().to_string();
833    if text.contains(' ') {
834        format!("\"{text}\"")
835    } else {
836        text
837    }
838}
839
840fn slug(agent: Agent) -> &'static str {
841    match agent {
842        Agent::Claude => "claude",
843        Agent::Codex => "codex",
844        Agent::Cursor => "cursor",
845        Agent::Gemini => "gemini",
846        Agent::OpenCode => "opencode",
847    }
848}
849
850fn agents(exe: &Path) -> Vec<Check> {
851    let home = match setup::home() {
852        Ok(h) => h,
853        Err(e) => {
854            return vec![Check {
855                name: "agents".into(),
856                status: Status::Missing,
857                required: false,
858                detail: format!("{e:#}"),
859                fix: Some("set HOME".into()),
860            }];
861        }
862    };
863    let found: Vec<Agent> = Agent::ALL
864        .into_iter()
865        .filter(|a| a.present(&home))
866        .collect();
867    if found.is_empty() {
868        return vec![Check {
869            name: "agents".into(),
870            status: Status::Missing,
871            required: false,
872            detail: "no coding agent found (Claude Code, Codex, Cursor, Gemini CLI, OpenCode); the CLI works without one".into(),
873            fix: Some(format!("{} setup --agent claude", quoted(exe))),
874        }];
875    }
876    let setup_fix = |agent: Agent| format!("{} setup --agent {}", quoted(exe), slug(agent));
877    let mut checks = Vec::new();
878    for agent in found {
879        let config = agent.config(&home);
880        let (state, detail) = match read_entry(agent, &config) {
881            Err(e) => (Install::Foreign, e),
882            Ok(entry) => {
883                let state = entry_state(entry.as_ref(), exe);
884                let detail = match (state, &entry) {
885                    (Install::Missing, _) => format!("no `{NAME}` server in {}", config.display()),
886                    (_, Some(Entry { disabled: true, .. })) => {
887                        format!("`{NAME}` in {} is disabled", config.display())
888                    }
889                    (
890                        _,
891                        Some(Entry {
892                            command: Some(c), ..
893                        }),
894                    ) => {
895                        format!("{} runs `{c}`", config.display())
896                    }
897                    _ => format!(
898                        "`{NAME}` in {} is not `{} mcp`",
899                        config.display(),
900                        exe.display()
901                    ),
902                };
903                (state, detail)
904            }
905        };
906        checks.push(Check {
907            name: format!("{} mcp", agent.name()),
908            status: state.into(),
909            required: true,
910            detail,
911            fix: match state {
912                Install::Current => None,
913                Install::Missing | Install::Outdated => Some(setup_fix(agent)),
914                Install::Foreign => Some(format!(
915                    "fix or remove the `{NAME}` entry in {}, then run `{}`",
916                    config.display(),
917                    setup_fix(agent)
918                )),
919            },
920        });
921        if let Some(dir) = agent.skill_dir(&home) {
922            let installed: Vec<Option<String>> = SKILL_FILES
923                .iter()
924                .map(|(name, _)| std::fs::read_to_string(dir.join(name)).ok())
925                .collect();
926            let state = skill_state(&installed);
927            let skill_md = dir.join("SKILL.md");
928            checks.push(Check {
929                name: format!("{} skill", agent.name()),
930                status: state.into(),
931                required: true,
932                detail: match state {
933                    Install::Missing => format!("{} not installed", skill_md.display()),
934                    Install::Current => format!("{} matches this version", skill_md.display()),
935                    Install::Outdated => {
936                        format!("{} is from another version", skill_md.display())
937                    }
938                    Install::Foreign => {
939                        format!("{} is not rust-anything's skill", skill_md.display())
940                    }
941                },
942                fix: match state {
943                    Install::Current => None,
944                    Install::Missing | Install::Outdated => Some(setup_fix(agent)),
945                    Install::Foreign => Some(format!(
946                        "move {} aside, then run `{}`",
947                        dir.display(),
948                        setup_fix(agent)
949                    )),
950                },
951            });
952        }
953    }
954    checks
955}
956
957/// The agent's `rust-anything` entry; `Err` when the settings file cannot be read as settings.
958fn read_entry(agent: Agent, path: &Path) -> Result<Option<Entry>, String> {
959    let text = match std::fs::read_to_string(path) {
960        Ok(t) => t,
961        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
962        Err(e) => return Err(format!("reading {}: {e}", path.display())),
963    };
964    if text.trim().is_empty() {
965        return Ok(None);
966    }
967    if agent == Agent::Codex {
968        let doc: toml_edit::DocumentMut = text
969            .parse()
970            .map_err(|_| format!("{} is not valid TOML", path.display()))?;
971        let Some(server) = doc
972            .get("mcp_servers")
973            .and_then(|s| s.get(NAME))
974            .and_then(toml_edit::Item::as_table_like)
975        else {
976            return Ok(None);
977        };
978        return Ok(Some(Entry {
979            command: server
980                .get("command")
981                .and_then(|c| c.as_str())
982                .map(String::from),
983            args: server
984                .get("args")
985                .and_then(|a| a.as_array())
986                .map(|a| {
987                    a.iter()
988                        .filter_map(|v| v.as_str().map(String::from))
989                        .collect()
990                })
991                .unwrap_or_default(),
992            url: server.get("url").is_some(),
993            disabled: false,
994        }));
995    }
996    if agent == Agent::OpenCode {
997        let doc: Value = serde_json::from_str(&text)
998            .map_err(|_| format!("{} is not valid JSON", path.display()))?;
999        // Current OpenCode keeps servers under `mcp.servers`; older files list them in `mcp`.
1000        let mcp = &doc["mcp"];
1001        let servers = if mcp.get("servers").is_some() {
1002            &mcp["servers"]
1003        } else {
1004            mcp
1005        };
1006        let Some(server) = servers.get(NAME) else {
1007            return Ok(None);
1008        };
1009        // OpenCode's local server takes the whole argv in `command`.
1010        let mut argv = server["command"]
1011            .as_array()
1012            .map(|a| a.iter().filter_map(|v| v.as_str().map(String::from)));
1013        return Ok(Some(Entry {
1014            command: argv.as_mut().and_then(|a| a.next()),
1015            args: argv.into_iter().flatten().collect(),
1016            url: server.get("url").is_some(),
1017            disabled: server["disabled"].as_bool() == Some(true),
1018        }));
1019    }
1020    let doc: Value =
1021        serde_json::from_str(&text).map_err(|_| format!("{} is not valid JSON", path.display()))?;
1022    let Some(server) = doc["mcpServers"].get(NAME) else {
1023        return Ok(None);
1024    };
1025    Ok(Some(Entry {
1026        command: server["command"].as_str().map(String::from),
1027        args: server["args"]
1028            .as_array()
1029            .map(|a| {
1030                a.iter()
1031                    .filter_map(|v| v.as_str().map(String::from))
1032                    .collect()
1033            })
1034            .unwrap_or_default(),
1035        url: server.get("url").is_some(),
1036        disabled: false,
1037    }))
1038}
1039
1040/// The report for people: one line per check, the fix under each problem.
1041pub fn text(r: &Report) -> String {
1042    let mut out = String::new();
1043    let width = r.checks.iter().map(|c| c.name.len()).max().unwrap_or(0);
1044    for c in &r.checks {
1045        let optional = if c.required || c.status == Status::Ok {
1046            ""
1047        } else {
1048            " (optional)"
1049        };
1050        out.push_str(&format!(
1051            "{:<9} {:<width$}  {}{optional}\n",
1052            c.status.label(),
1053            c.name,
1054            c.detail
1055        ));
1056        if let Some(fix) = &c.fix {
1057            // Further lines of a fix line up under the first.
1058            for (i, line) in fix.lines().enumerate() {
1059                let label = if i == 0 { "fix:" } else { "" };
1060                out.push_str(&format!("{:<9} {:<width$}  {label:<4} {line}\n", "", ""));
1061            }
1062        }
1063    }
1064    out.push_str(if r.ok() {
1065        "\nEverything required is in place. Language runtimes and wasm are optional: each matters only for the languages you port.\n"
1066    } else {
1067        "\nSomething required is missing: cargo, the MCP server, or the setup of an agent found here. Run the fix commands above.\n"
1068    });
1069    out
1070}
1071
1072#[cfg(test)]
1073mod tests {
1074    use super::*;
1075
1076    #[test]
1077    fn install_command_is_doctor_fix_for_a_runtime() {
1078        let ruby = RUNTIMES.iter().find(|r| r.name == "ruby").unwrap();
1079        assert_eq!(
1080            install_command("ruby"),
1081            runtime_fix(ruby, Status::Outdated, Platform::HERE)
1082        );
1083        assert!(install_command("cobol").is_none());
1084        assert_eq!(minimum("ruby"), ruby.minimum);
1085        assert!(minimum("cobol").is_none());
1086
1087        let cargo = RUNTIMES.iter().find(|r| r.name == "cargo").unwrap();
1088        assert_eq!(
1089            missing_command("cargo"),
1090            runtime_fix(cargo, Status::Missing, Platform::HERE)
1091        );
1092        assert_ne!(
1093            missing_command("cargo").as_deref(),
1094            Some("rustup update stable")
1095        );
1096        assert!(missing_command("cobol").is_none());
1097    }
1098
1099    #[test]
1100    fn versions_are_read_from_every_banner() {
1101        let cases = [
1102            ("v24.1.0", Version(24, 1, 0)),
1103            ("Python 3.12.1", Version(3, 12, 1)),
1104            ("go version go1.22.3 darwin/arm64", Version(1, 22, 3)),
1105            (
1106                "ruby 2.6.10p210 (2022-04-12 revision 67958) [universal.arm64e-darwin26]",
1107                Version(2, 6, 10),
1108            ),
1109            ("openjdk version \"21.0.8\" 2025-07-15", Version(21, 0, 8)),
1110            ("javac 17", Version(17, 0, 0)),
1111            ("PHP 8.3.4 (cli) (built: Mar 12 2024)", Version(8, 3, 4)),
1112            ("PowerShell 7.7.0", Version(7, 7, 0)),
1113            ("cargo 1.97.0 (abcdef 2026-01-01)", Version(1, 97, 0)),
1114            ("8.0.100", Version(8, 0, 100)),
1115        ];
1116        for (text, want) in cases {
1117            assert_eq!(parse_version(text), Some(want), "{text}");
1118        }
1119        assert_eq!(parse_version("no digits"), None);
1120        assert_eq!(
1121            parse_java_version("java version \"1.8.0_281\""),
1122            Some(Version(8, 0, 0))
1123        );
1124        assert_eq!(
1125            parse_java_version("openjdk version \"17.0.2\""),
1126            Some(Version(17, 0, 2))
1127        );
1128    }
1129
1130    #[test]
1131    fn runtimes_are_graded_against_their_minimum() {
1132        let min = Some(Version(3, 0, 0));
1133        assert_eq!(grade(false, None, min), Status::Missing);
1134        assert_eq!(grade(true, Some(Version(2, 6, 10)), min), Status::Outdated);
1135        assert_eq!(grade(true, Some(Version(3, 0, 0)), min), Status::Ok);
1136        assert_eq!(grade(true, Some(Version(3, 4, 1)), min), Status::Ok);
1137        assert_eq!(grade(true, None, min), Status::Ok);
1138        assert_eq!(grade(true, Some(Version(1, 0, 0)), None), Status::Ok);
1139        assert!(Version(22, 6, 0) > Version(22, 5, 9));
1140    }
1141
1142    #[test]
1143    fn install_states_map_to_statuses() {
1144        assert_eq!(Status::from(Install::Missing), Status::Missing);
1145        assert_eq!(Status::from(Install::Current), Status::Ok);
1146        assert_eq!(Status::from(Install::Outdated), Status::Outdated);
1147        assert_eq!(Status::from(Install::Foreign), Status::Foreign);
1148        assert_eq!(
1149            serde_json::to_value(Status::Outdated).unwrap(),
1150            json!("outdated")
1151        );
1152    }
1153
1154    #[test]
1155    fn mcp_entries_are_ours_only_when_they_run_this_binary() {
1156        let exe = Path::new("/opt/bin/rust-anything");
1157        let entry = |command: &str, args: &[&str], url: bool| Entry {
1158            command: Some(command.into()),
1159            args: args.iter().map(|a| a.to_string()).collect(),
1160            url,
1161            disabled: false,
1162        };
1163        assert_eq!(entry_state(None, exe), Install::Missing);
1164        assert_eq!(
1165            entry_state(Some(&entry("/opt/bin/rust-anything", &["mcp"], false)), exe),
1166            Install::Current
1167        );
1168        assert_eq!(
1169            entry_state(Some(&entry("/old/rust-anything", &["mcp"], false)), exe),
1170            Install::Outdated
1171        );
1172        assert_eq!(
1173            entry_state(
1174                Some(&entry("/opt/bin/rust-anything", &["serve"], false)),
1175                exe
1176            ),
1177            Install::Foreign
1178        );
1179        assert_eq!(
1180            entry_state(Some(&entry("/opt/bin/rust-anything", &["mcp"], true)), exe),
1181            Install::Foreign
1182        );
1183        assert_eq!(entry_state(Some(&Entry::default()), exe), Install::Foreign);
1184        // A server OpenCode keeps disabled is not current.
1185        let mut disabled = entry("/opt/bin/rust-anything", &["mcp"], false);
1186        disabled.disabled = true;
1187        assert_eq!(entry_state(Some(&disabled), exe), Install::Outdated);
1188    }
1189
1190    #[cfg(not(windows))]
1191    #[test]
1192    fn an_npx_entry_is_current_for_a_copy_run_by_npx() {
1193        let exe = Path::new(
1194            "/home/u/.npm/_npx/0a1b2c/node_modules/rust-anything/binaries/linux-x64/rust-anything",
1195        );
1196        let entry = |args: &[&str]| Entry {
1197            command: Some("npx".into()),
1198            args: args.iter().map(|a| a.to_string()).collect(),
1199            url: false,
1200            disabled: false,
1201        };
1202        let package = format!("{NAME}@{}", env!("CARGO_PKG_VERSION"));
1203        assert_eq!(
1204            entry_state(Some(&entry(&["-y", &package, "mcp"])), exe),
1205            Install::Current
1206        );
1207        assert_eq!(
1208            entry_state(Some(&entry(&["-y", "rust-anything@0.0.1", "mcp"])), exe),
1209            Install::Outdated
1210        );
1211        assert_eq!(
1212            entry_state(
1213                Some(&entry(&["-y", &package, "mcp"])),
1214                Path::new("/opt/bin/rust-anything")
1215            ),
1216            Install::Outdated
1217        );
1218        assert_eq!(
1219            entry_state(Some(&entry(&["-y", "other-package", "mcp"])), exe),
1220            Install::Foreign
1221        );
1222    }
1223
1224    #[test]
1225    fn opencode_entries_come_from_mcp_servers() {
1226        let home = std::env::temp_dir().join(format!(
1227            "rust-anything-doctor-opencode-{}",
1228            std::process::id()
1229        ));
1230        let _ = std::fs::remove_dir_all(&home);
1231        std::fs::create_dir_all(home.join(".config/opencode")).unwrap();
1232        let config = home.join(".config/opencode/opencode.json");
1233        std::fs::write(
1234            &config,
1235            r#"{"mcp":{"servers":{"rust-anything":{"type":"local","command":["/opt/bin/rust-anything","mcp"]}}}}"#,
1236        )
1237        .unwrap();
1238        let exe = Path::new("/opt/bin/rust-anything");
1239        let entry = read_entry(Agent::OpenCode, &config).unwrap();
1240        assert_eq!(entry_state(entry.as_ref(), exe), Install::Current);
1241        assert_eq!(
1242            entry_state(entry.as_ref(), Path::new("/elsewhere/rust-anything")),
1243            Install::Outdated
1244        );
1245        std::fs::write(
1246            &config,
1247            r#"{"mcp":{"servers":{"rust-anything":{"type":"local","command":["/opt/bin/rust-anything","mcp"],"disabled":true}}}}"#,
1248        )
1249        .unwrap();
1250        let entry = read_entry(Agent::OpenCode, &config).unwrap();
1251        assert_eq!(entry_state(entry.as_ref(), exe), Install::Outdated);
1252        // Older files list servers in `mcp` itself.
1253        std::fs::write(
1254            &config,
1255            r#"{"mcp":{"rust-anything":{"type":"local","command":["/opt/bin/rust-anything","mcp"]}}}"#,
1256        )
1257        .unwrap();
1258        let entry = read_entry(Agent::OpenCode, &config).unwrap();
1259        assert_eq!(entry_state(entry.as_ref(), exe), Install::Current);
1260        std::fs::remove_dir_all(&home).unwrap();
1261    }
1262
1263    #[test]
1264    fn skills_are_current_outdated_or_foreign() {
1265        let ours: Vec<Option<String>> = SKILL_FILES
1266            .iter()
1267            .map(|(_, t)| Some(t.to_string()))
1268            .collect();
1269        assert_eq!(skill_state(&ours), Install::Current);
1270        assert_eq!(
1271            skill_state(&vec![None; SKILL_FILES.len()]),
1272            Install::Missing
1273        );
1274        let mut old = ours.clone();
1275        old[0] = Some(format!(
1276            "---\nname: {NAME}\ndescription: old\n---\n\n# Old\n"
1277        ));
1278        assert_eq!(skill_state(&old), Install::Outdated);
1279        let mut partial = ours.clone();
1280        partial[1] = None;
1281        assert_eq!(skill_state(&partial), Install::Outdated);
1282        let mut foreign = ours;
1283        foreign[0] = Some("---\nname: something-else\n---\n".into());
1284        assert_eq!(skill_state(&foreign), Install::Foreign);
1285    }
1286
1287    #[test]
1288    fn only_required_problems_fail_the_report() {
1289        let check = |status, required| Check {
1290            name: "x".into(),
1291            status,
1292            required,
1293            detail: String::new(),
1294            fix: None,
1295        };
1296        let optional = Report {
1297            checks: vec![check(Status::Ok, true), check(Status::Missing, false)],
1298        };
1299        assert!(optional.ok());
1300        let required = Report {
1301            checks: vec![check(Status::Outdated, true)],
1302        };
1303        assert!(!required.ok());
1304    }
1305
1306    fn runtime_named(name: &str) -> &'static Runtime {
1307        RUNTIMES.iter().find(|r| r.name == name).unwrap()
1308    }
1309
1310    #[test]
1311    fn fixes_follow_the_platform() {
1312        let cc = runtime_named("cc");
1313        let fix = |platform| runtime_fix(cc, Status::Missing, platform);
1314        assert_eq!(
1315            fix(Platform::MacOs).as_deref(),
1316            Some("xcode-select --install")
1317        );
1318        assert_eq!(
1319            fix(Platform::Windows),
1320            Some(format!("{BUILD_TOOLS}\n{BUILD_TOOLS_INSTALLED}"))
1321        );
1322        assert_eq!(
1323            fix(Platform::Other).as_deref(),
1324            Some("sudo apt install build-essential")
1325        );
1326        assert_eq!(runtime_fix(cc, Status::Ok, Platform::Windows), None);
1327    }
1328
1329    #[test]
1330    fn windows_fixes_need_no_unix_shell() {
1331        for r in RUNTIMES {
1332            for status in [Status::Missing, Status::Outdated] {
1333                let fix = runtime_fix(r, status, Platform::Windows).unwrap();
1334                assert!(!fix.contains("| sh"), "{}: {fix}", r.name);
1335            }
1336        }
1337    }
1338
1339    #[test]
1340    fn windows_build_tools_fixes_add_the_cpp_workload() {
1341        for name in ["cargo", "cc"] {
1342            let fix = runtime_fix(runtime_named(name), Status::Missing, Platform::Windows).unwrap();
1343            assert!(
1344                fix.contains("--add Microsoft.VisualStudio.Workload.VCTools"),
1345                "{name}: {fix}"
1346            );
1347        }
1348    }
1349
1350    #[test]
1351    fn windows_cargo_fix_has_one_command_per_line() {
1352        let fix = runtime_fix(runtime_named("cargo"), Status::Missing, Platform::Windows).unwrap();
1353        assert_eq!(
1354            fix.lines().collect::<Vec<_>>(),
1355            [
1356                BUILD_TOOLS,
1357                "winget install Rustlang.Rustup",
1358                BUILD_TOOLS_INSTALLED
1359            ]
1360        );
1361    }
1362
1363    #[test]
1364    fn windows_on_arm_adds_the_arm64_tools() {
1365        let workload = "--add Microsoft.VisualStudio.Workload.VCTools --includeRecommended";
1366        assert!(BUILD_TOOLS_X64.contains(workload));
1367        assert!(!BUILD_TOOLS_X64.contains("ARM64"));
1368        assert!(BUILD_TOOLS_ARM64.contains(workload));
1369        assert!(
1370            BUILD_TOOLS_ARM64.ends_with(" --add Microsoft.VisualStudio.Component.VC.Tools.ARM64\"")
1371        );
1372        assert_eq!(
1373            BUILD_TOOLS == BUILD_TOOLS_ARM64,
1374            cfg!(all(windows, target_arch = "aarch64"))
1375        );
1376    }
1377
1378    #[test]
1379    fn fixes_of_several_lines_line_up() {
1380        let report = Report {
1381            checks: vec![Check {
1382                name: "cargo".into(),
1383                status: Status::Missing,
1384                required: true,
1385                detail: "not found".into(),
1386                fix: Some("first\nsecond".into()),
1387            }],
1388        };
1389        let out = text(&report);
1390        let lines: Vec<_> = out.lines().collect();
1391        assert!(lines[1].trim_start().starts_with("fix: first"), "{out}");
1392        assert_eq!(lines[1].find("first"), lines[2].find("second"), "{out}");
1393    }
1394
1395    #[test]
1396    fn adb_is_a_row_of_its_own_and_never_required() {
1397        // `record`/`diff --profile android` run `adb devices`, so a machine without it should hear
1398        // about it — but a device is optional, like the NDK and the Rust targets next to it.
1399        let check = android_adb();
1400        assert_eq!(check.name, "Android adb");
1401        assert!(!check.required);
1402        if check.status != Status::Ok {
1403            assert!(
1404                check
1405                    .fix
1406                    .as_deref()
1407                    .is_some_and(|f| f.contains("platform-tools")),
1408                "a missing adb names the package that installs it: {:?}",
1409                check.fix
1410            );
1411        }
1412    }
1413
1414    #[test]
1415    fn php_requires_the_ffi_extension_and_stays_optional() {
1416        let php = runtime_named("php");
1417        let banner = Some("PHP 8.3.4 (cli) (built: Mar 12 2024)");
1418        assert!(php_has_ffi("[PHP Modules]\nCore\nFFI\njson\n"));
1419        assert!(php_has_ffi("  ffi \n"));
1420        assert!(!php_has_ffi("[PHP Modules]\nCore\nfileinfo\njson\n"));
1421        assert!(!php_has_ffi(
1422            "PHP Warning: Unable to load dynamic library 'ffi'\n[PHP Modules]\nCore\n"
1423        ));
1424
1425        let loaded = runtime_check(
1426            php,
1427            banner,
1428            Some("[PHP Modules]\nCore\nFFI\n"),
1429            Platform::Other,
1430        );
1431        assert_eq!(loaded.status, Status::Ok);
1432        assert!(!loaded.required);
1433        assert!(loaded.detail.ends_with("(FFI loaded)"), "{}", loaded.detail);
1434        assert_eq!(loaded.fix, None);
1435
1436        for platform in [Platform::MacOs, Platform::Windows, Platform::Other] {
1437            let no_ffi = runtime_check(php, banner, Some("[PHP Modules]\nCore\n"), platform);
1438            assert_eq!(no_ffi.status, Status::Missing);
1439            assert!(!no_ffi.required);
1440            assert!(
1441                no_ffi.detail.contains("FFI extension not loaded"),
1442                "{}",
1443                no_ffi.detail
1444            );
1445            let fix = no_ffi.fix.as_deref().expect("a fix when FFI is missing");
1446            assert!(fix.contains("extension=ffi"), "{platform:?}: {fix}");
1447            assert!(!fix.contains("| sh"), "{platform:?}: {fix}");
1448            assert!(
1449                Report {
1450                    checks: vec![no_ffi]
1451                }
1452                .ok(),
1453                "missing FFI stays optional"
1454            );
1455        }
1456
1457        let probe_failed = runtime_check(php, banner, None, Platform::Other);
1458        assert_eq!(probe_failed.status, Status::Missing);
1459        assert!(probe_failed.detail.contains("`php -m` failed"));
1460        assert!(probe_failed.fix.is_some());
1461
1462        let old = runtime_check(php, Some("PHP 7.4.33 (cli)"), None, Platform::Other);
1463        assert_eq!(old.status, Status::Outdated);
1464        assert!(old.detail.contains("needs 8.0+"));
1465    }
1466    #[test]
1467    fn install_md_names_the_runtime_minimums_doctor_checks() {
1468        // docs/install.md lists the runtimes `record`, `diff` and `bench` run the original in; it
1469        // must not promise an older version than `doctor` accepts, or leave a checked one out.
1470        let doc = include_str!("../docs/install.md")
1471            .split_whitespace()
1472            .collect::<Vec<_>>()
1473            .join(" ");
1474        let named = [
1475            ("node", "Node"),
1476            ("python3", "Python"),
1477            ("go", "Go"),
1478            ("ruby", "Ruby"),
1479            ("javac", "JDK"),
1480            ("php", "PHP"),
1481            ("pwsh", "PowerShell"),
1482        ];
1483        for r in RUNTIMES.iter().filter(|r| r.minimum.is_some()) {
1484            assert!(
1485                matches!(r.name, "cargo" | "java") || named.iter().any(|(n, _)| *n == r.name),
1486                "add {} to this list and to docs/install.md",
1487                r.name
1488            );
1489        }
1490        for (name, label) in named {
1491            let Version(major, minor, _) = minimum(name).unwrap();
1492            let version = if minor == 0 {
1493                major.to_string()
1494            } else {
1495                format!("{major}.{minor}")
1496            };
1497            let text = format!("{label} {version}+");
1498            assert!(
1499                doc.contains(&text),
1500                "docs/install.md should say `{text}`, as doctor does"
1501            );
1502        }
1503        for runtime in ["`kotlinc`", ".NET SDK"] {
1504            assert!(
1505                doc.contains(runtime),
1506                "docs/install.md should name {runtime}"
1507            );
1508        }
1509    }
1510}