Skip to main content

release_kit/
probes.rs

1//! The environment probe catalog.
2//!
3//! One catalog, read by every caller that needs to know whether this host
4//! is ready: `rk doctor` runs it whole, and a mutating command guards the
5//! subset it depends on at entry, so the per-command guards and the
6//! doctor cannot drift apart. Each probe answers with a status, a
7//! message, and — on failure — the remediation printed verbatim wherever
8//! the probe is consulted.
9
10use std::process::Command;
11
12use serde::Serialize;
13
14use crate::detect::Forge;
15use crate::skills::record::{RECORD_PATH, Record};
16use crate::skills::{AGENTS_ROOT, CLAUDE_ROOT, Digest};
17
18/// How a failure weighs at the doctor level.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
20#[serde(rename_all = "kebab-case")]
21pub enum ProbeClass {
22    /// No mutating command can work without this.
23    Hard,
24    /// Needed only by some commands or some forges.
25    Soft,
26}
27
28/// What a probe found.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
30#[serde(rename_all = "kebab-case")]
31pub enum ProbeStatus {
32    /// The probe passed.
33    Ok,
34    /// The probe failed; the remediation says what fixes it.
35    Failed,
36}
37
38/// One probe's answer.
39#[derive(Debug, Serialize)]
40pub struct ProbeResult {
41    /// The probe's stable name.
42    pub id: &'static str,
43    /// How the failure weighs.
44    pub class: ProbeClass,
45    /// What was found.
46    pub status: ProbeStatus,
47    /// What was found, one line.
48    pub message: String,
49    /// The exact fix, when the probe failed.
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub remediation: Option<String>,
52}
53
54impl ProbeResult {
55    fn ok(id: &'static str, class: ProbeClass, message: impl Into<String>) -> Self {
56        Self {
57            id,
58            class,
59            status: ProbeStatus::Ok,
60            message: message.into(),
61            remediation: None,
62        }
63    }
64
65    fn failed(
66        id: &'static str,
67        class: ProbeClass,
68        message: impl Into<String>,
69        remediation: impl Into<String>,
70    ) -> Self {
71        Self {
72            id,
73            class,
74            status: ProbeStatus::Failed,
75            message: message.into(),
76            remediation: Some(remediation.into()),
77        }
78    }
79}
80
81/// The probes judging the skill installation itself, in catalog order.
82///
83/// Declared here rather than derived by running the catalog: the shared plan
84/// gate's pre-flight phase must name each of these, and the test holding it to
85/// that must not have to spawn a forge CLI or write into the operator's home
86/// to learn what they are.
87pub const SKILL_PROBES: [&str; 1] = ["skill-shadow"];
88
89/// Every executable a Hard probe requires, paired with the nixpkgs package
90/// whose `bin/` supplies it in the installed package's wrapper.
91///
92/// `nix/package.nix` mirrors this list by hand — Nix cannot read this
93/// registry, and generating one list from the other is more machinery than
94/// two entries earn — so the mirror test in `tests/cli.rs` holds the two
95/// lists to agreement and a divergence fails by name instead of shipping.
96pub const HARD_RUNTIME_TOOLS: [(&str, &str); 2] = [("git", "git"), ("sh", "bash")];
97
98/// One owner for the git binary every production launcher spawns.
99///
100/// `RK_GIT_BIN` substitutes it — the same contract every soft tool's
101/// override states, and what lets an operator's own git win over the one
102/// the installed package's wrapper supplies.
103#[must_use]
104pub fn git_bin() -> std::ffi::OsString {
105    crate::requirements::Tool::Git.program()
106}
107
108/// One owner for the nix binary every devshell launch spawns: the lock
109/// refresh, the system probe, and the build. `RK_NIX_BIN` substitutes it.
110#[must_use]
111pub fn nix_bin() -> std::ffi::OsString {
112    crate::requirements::Tool::Nix.program()
113}
114
115/// One owner for the direnv binary, which nothing here spawns but the
116/// doctor probes: it is what loads a consumer's devshell on entry.
117/// `RK_DIRENV_BIN` substitutes it.
118#[must_use]
119pub fn direnv_bin() -> std::ffi::OsString {
120    std::env::var_os("RK_DIRENV_BIN")
121        .filter(|value| !value.is_empty())
122        .unwrap_or_else(|| "direnv".into())
123}
124
125/// Nix answers; `rk self-depend sync` updates and builds the pinned devshell
126/// with it. Soft, and deliberately outside the wrapper: wrapping nix
127/// would put it inside the package's own closure on every host.
128#[must_use]
129pub fn nix() -> ProbeResult {
130    tool(
131        "nix",
132        "RK_NIX_BIN",
133        "nix",
134        "Nix; rk self-depend sync updates and builds the pinned devshell with it",
135        &["--version"],
136    )
137}
138
139/// direnv answers; it loads the devshell on directory entry.
140#[must_use]
141pub fn direnv() -> ProbeResult {
142    tool(
143        "direnv",
144        "RK_DIRENV_BIN",
145        "direnv",
146        "direnv; it loads the devshell on directory entry",
147        &["version"],
148    )
149}
150
151/// One owner for the POSIX shell every setup step spawns through.
152///
153/// `RK_SH_BIN` substitutes it, which is also what keeps tests hermetic on
154/// a host whose `sh` is not the one under test.
155#[must_use]
156pub fn sh_bin() -> std::ffi::OsString {
157    crate::requirements::Tool::Sh.program()
158}
159
160/// One owner for the git-cliff binary the release engine spawns.
161///
162/// `RK_GIT_CLIFF_BIN` substitutes it, the same contract `RK_GIT_BIN`
163/// states. The engine compares the binary's version with the
164/// `versions.toml` pin before it trusts any output.
165#[must_use]
166pub fn git_cliff_bin() -> std::ffi::OsString {
167    crate::requirements::Tool::GitCliff.program()
168}
169
170/// One owner for the uv binary the python driver adapter spawns.
171///
172/// `RK_UV_BIN` substitutes it. The engine runs the uv the job installed,
173/// and uv enforces the target's own `required-version`.
174#[must_use]
175pub fn uv_bin() -> std::ffi::OsString {
176    crate::requirements::Tool::Uv.program()
177}
178
179/// Run the whole catalog, in its stable order.
180#[must_use]
181pub fn run_all() -> Vec<ProbeResult> {
182    let mut probes = vec![
183        shell(),
184        git(),
185        state_root(),
186        skill_shadow(),
187        git_remote(),
188        pin_freshness(),
189        forge_cli(
190            "gh-auth",
191            "RK_GH_BIN",
192            "gh",
193            "the GitHub CLI",
194            "gh auth login",
195            // `gh auth status` fails when any stored account is broken,
196            // even while the active one works; `--active` judges only the
197            // credential this tool would use, and the gh floor is the
198            // release that added it.
199            &[&["auth", "status", "--active"]],
200        ),
201        forge_cli(
202            "glab-auth",
203            "RK_GLAB_BIN",
204            "glab",
205            "the GitLab CLI",
206            "glab auth login",
207            &[&["auth", "status"]],
208        ),
209        forge_cli_floor(Forge::Github),
210        forge_cli_floor(Forge::Gitlab),
211        registry(),
212        nix(),
213        direnv(),
214        tool(
215            "cosign",
216            "RK_COSIGN_BIN",
217            "cosign",
218            "cosign; the release verify step checks a GitLab provenance bundle with it",
219            &["version"],
220        ),
221        tool(
222            "pypi-attestations",
223            "RK_PYPI_ATTESTATIONS_BIN",
224            "pypi-attestations",
225            "pypi-attestations; the release verify step checks a PyPI distribution's attestations with it",
226            &["--help"],
227        ),
228    ];
229    probes.extend(hook_probes());
230    probes
231}
232
233/// The hooks of the repository at the current directory, a report for a
234/// project that uses rk: whether the `pre-merge-commit` hook that
235/// `rk integrate` asks git to run is installed, and whether each hook
236/// manager that wrote an installed hook answers. A hook no known manager
237/// wrote is the project's own. Nothing outside a repository, and nothing
238/// here changes what a verb runs.
239fn hook_probes() -> Vec<ProbeResult> {
240    let Ok(cwd) = std::env::current_dir() else {
241        return Vec::new();
242    };
243    let Some(installed) = crate::hooks::installed(&cwd) else {
244        return Vec::new();
245    };
246    let names = |filter: &dyn Fn(crate::hooks::Writer) -> bool| -> Vec<&'static str> {
247        installed
248            .iter()
249            .filter(|hook| filter(hook.writer))
250            .map(|hook| hook.event)
251            .collect()
252    };
253    let mut probes = vec![if installed
254        .iter()
255        .any(|hook| hook.event == "pre-merge-commit")
256    {
257        ProbeResult::ok(
258            "pre-merge-commit-hook",
259            ProbeClass::Soft,
260            "a pre-merge-commit hook is installed, the gate rk integrate asks git to run",
261        )
262    } else {
263        ProbeResult::failed(
264            "pre-merge-commit-hook",
265            ProbeClass::Soft,
266            "no pre-merge-commit hook is installed, so rk integrate has no gate to run in this clone",
267            "install it with the project's hook manager, for example prek install --hook-type pre-merge-commit",
268        )
269    }];
270    for (id, writer) in [
271        ("prek", crate::hooks::Writer::Prek),
272        ("pre-commit", crate::hooks::Writer::PreCommit),
273    ] {
274        let hooks = names(&|found| found == writer);
275        if hooks.is_empty() {
276            continue;
277        }
278        let answers = Command::new(id)
279            .arg("--version")
280            .output()
281            .is_ok_and(|out| out.status.success());
282        let wrote = hooks.join(", ");
283        probes.push(if answers {
284            ProbeResult::ok(id, ProbeClass::Soft, format!("{id} runs; it wrote the {wrote} hooks"))
285        } else {
286            ProbeResult::failed(
287                id,
288                ProbeClass::Soft,
289                format!("{id} does not run, and the {wrote} hooks call it"),
290                format!("install {id} on the host, or reinstall the hooks with the project's hook manager"),
291            )
292        });
293    }
294    let configured = names(&|found| found == crate::hooks::Writer::Configured);
295    if !configured.is_empty() {
296        let mut events = configured.clone();
297        events.dedup();
298        probes.push(ProbeResult::ok(
299            "configured-hooks",
300            ProbeClass::Soft,
301            format!(
302                "git's configuration defines {} hooks for {}",
303                configured.len(),
304                events.join(", ")
305            ),
306        ));
307    }
308    let own = names(&|found| found == crate::hooks::Writer::Own);
309    if !own.is_empty() {
310        probes.push(ProbeResult::ok(
311            "own-hooks",
312            ProbeClass::Soft,
313            format!(
314                "the {} hooks are the project's own, written by no known hook manager",
315                own.join(", ")
316            ),
317        ));
318    }
319    probes
320}
321
322/// A helper binary answers its version call. `env_override` names the
323/// substitute, which is also what keeps tests hermetic; presence is the
324/// whole question, because the tools here take no configuration.
325fn tool(
326    id: &'static str,
327    env_override: &str,
328    default_bin: &str,
329    label: &str,
330    args: &[&str],
331) -> ProbeResult {
332    let bin = std::env::var(env_override)
333        .ok()
334        .filter(|value| !value.is_empty())
335        .unwrap_or_else(|| default_bin.to_owned());
336    match Command::new(&bin).args(args).output() {
337        Ok(out) if out.status.success() => {
338            ProbeResult::ok(id, ProbeClass::Soft, format!("{default_bin} runs"))
339        }
340        Ok(_) => ProbeResult::failed(
341            id,
342            ProbeClass::Soft,
343            format!("{default_bin} does not answer {}", args.join(" ")),
344            format!("repair {label}"),
345        ),
346        Err(_) => ProbeResult::failed(
347            id,
348            ProbeClass::Soft,
349            format!("{default_bin} is not on PATH"),
350            format!("install {label}"),
351        ),
352    }
353}
354
355/// The crates.io index answers, so `rk versions --check` and
356/// `rk self-depend sync` can compare a pin against the registry. Soft: a
357/// host that cannot reach it is a constraint on the two verbs that fetch,
358/// never a broken install, and every offline verb runs without it.
359fn registry() -> ProbeResult {
360    let id = "registry";
361    let answered = crate::http::send(
362        &crate::http::Request::get(
363            "https://index.crates.io/config.json",
364            std::time::Duration::from_secs(5),
365        )
366        .following(),
367    )
368    .is_ok_and(|answer| answer.ok());
369    if answered {
370        ProbeResult::ok(id, ProbeClass::Soft, "the crates.io index answers")
371    } else {
372        ProbeResult::failed(
373            id,
374            ProbeClass::Soft,
375            "the crates.io index does not answer",
376            "reach the network before rk versions --check or rk self-depend sync; every offline verb runs without it",
377        )
378    }
379}
380
381/// A POSIX shell runs; every setup step spawns through it.
382fn shell() -> ProbeResult {
383    let id = "sh";
384    match Command::new(sh_bin()).args(["-c", "exit 0"]).status() {
385        Ok(status) if status.success() => ProbeResult::ok(id, ProbeClass::Hard, "sh runs"),
386        Ok(status) => ProbeResult::failed(
387            id,
388            ProbeClass::Hard,
389            format!("sh exited {status}"),
390            "repair the POSIX shell on PATH",
391        ),
392        Err(source) => ProbeResult::failed(
393            id,
394            ProbeClass::Hard,
395            format!("sh does not spawn: {source}"),
396            "install a POSIX shell on PATH",
397        ),
398    }
399}
400
401/// Version control answers; every branch, worktree, landing, and setup
402/// verb launches it.
403fn git() -> ProbeResult {
404    let id = "git";
405    match Command::new(git_bin()).arg("--version").output() {
406        Ok(out) if out.status.success() => ProbeResult::ok(id, ProbeClass::Hard, "git runs"),
407        Ok(_) => ProbeResult::failed(
408            id,
409            ProbeClass::Hard,
410            "git does not answer --version",
411            "repair the git on PATH, or point RK_GIT_BIN at a working one",
412        ),
413        Err(_) => ProbeResult::failed(id, ProbeClass::Hard, "git is not on PATH", "install git"),
414    }
415}
416
417/// The XDG state root accepts writes; the log and every run journal live
418/// under it.
419fn state_root() -> ProbeResult {
420    let id = "state-root";
421    let Some(root) = crate::applog::state_root() else {
422        return ProbeResult::failed(
423            id,
424            ProbeClass::Hard,
425            "neither XDG_STATE_HOME nor HOME is set",
426            "export HOME, or XDG_STATE_HOME",
427        );
428    };
429    let display = root.display().to_string();
430    let probe = root.join(format!(".probe-{}", std::process::id()));
431    let written = std::fs::create_dir_all(&root).and_then(|()| std::fs::write(&probe, b"probe"));
432    let _ = std::fs::remove_file(&probe);
433    match written {
434        Ok(()) => ProbeResult::ok(id, ProbeClass::Hard, format!("{display} is writable")),
435        Err(source) => ProbeResult::failed(
436            id,
437            ProbeClass::Hard,
438            format!("{display} is not writable: {source}"),
439            format!("make {display} writable"),
440        ),
441    }
442}
443
444/// No user-scope copy of an embedded skill shadows the project's landed
445/// one.
446///
447/// Claude Code resolves a name collision as "personal over project", and
448/// Codex lists both copies, so a `SKILL.md` an earlier release installed
449/// under the home wins over the skills every landing now carries. A folder
450/// without `SKILL.md`, such as one that keeps the operator's notes after
451/// an uninstall, passes. The probe creates nothing.
452///
453/// SATISFIES distribution:the-doctor-names-a-shadowing-user-copy
454fn skill_shadow() -> ProbeResult {
455    let id = SKILL_PROBES[0];
456    let Ok(home) = crate::skills::home() else {
457        return ProbeResult::failed(
458            id,
459            ProbeClass::Soft,
460            "neither HOME nor USERPROFILE is set, so no user-scope skill root resolves",
461            "export HOME",
462        );
463    };
464    let Ok(skills) = crate::skills::all() else {
465        return ProbeResult::failed(
466            id,
467            ProbeClass::Soft,
468            "this binary's embedded skills do not read",
469            "reinstall rk; the sources it was built from are defective",
470        );
471    };
472    let record = Record::load(&home.join(RECORD_PATH));
473    let mut vouched = Vec::new();
474    let mut edited = Vec::new();
475    for root in [CLAUDE_ROOT, AGENTS_ROOT] {
476        for skill in &skills {
477            let manual = home.join(root).join(&skill.name).join("SKILL.md");
478            if std::fs::symlink_metadata(&manual).is_err() {
479                continue;
480            }
481            let ours = std::fs::read(&manual)
482                .is_ok_and(|bytes| record.wrote(&manual, &Digest::of(&bytes)));
483            if ours {
484                vouched.push(manual);
485            } else {
486                edited.push(manual);
487            }
488        }
489    }
490    if let Some(first) = edited.first() {
491        return ProbeResult::failed(
492            id,
493            ProbeClass::Soft,
494            format!(
495                "{} user-scope SKILL.md file(s) shadow the project's landed skills, and the uninstall kept them as your edits, the first at {first}",
496                edited.len()
497            ),
498            format!(
499                "read {first} and each other kept copy, keep what you need elsewhere, and remove them by hand"
500            ),
501        );
502    }
503    if let Some(first) = vouched.first() {
504        return ProbeResult::failed(
505            id,
506            ProbeClass::Soft,
507            format!(
508                "{} user-scope SKILL.md file(s) that an earlier release installed shadow the project's landed skills, the first at {first}",
509                vouched.len()
510            ),
511            "rk skill uninstall --apply",
512        );
513    }
514    ProbeResult::ok(
515        id,
516        ProbeClass::Soft,
517        format!("no user-scope copy of an rk skill under {home} shadows a project's landed one"),
518    )
519}
520
521/// Whether the rk pin of the working directory is behind the latest
522/// release that its check cache records. It reads the cache and never
523/// the network. A directory with no pin or no cache passes.
524///
525/// SATISFIES packaging:the-unattended-caller-never-fails-the-shell
526fn pin_freshness() -> ProbeResult {
527    use crate::self_depend::{self, advice};
528    let id = "pin-freshness";
529    let Ok(observed) = self_depend::observe(camino::Utf8Path::new(".")) else {
530        return ProbeResult::ok(
531            id,
532            ProbeClass::Soft,
533            "the working directory does not read as a project",
534        );
535    };
536    let Some(pin) = observed
537        .wired
538        .and_then(|wired| observed.entry(wired))
539        .and_then(|entry| entry.read.version())
540        .map(|version| version.trim_start_matches('v').to_owned())
541    else {
542        return ProbeResult::ok(id, ProbeClass::Soft, "the working directory pins no rk");
543    };
544    let key = observed.key();
545    if let Some(warning) = advice::pending_from_cache(&key, &pin) {
546        return ProbeResult::failed(
547            id,
548            ProbeClass::Soft,
549            format!("this project pins rk {pin}, and a newer release is out"),
550            warning,
551        );
552    }
553    let message = advice::cached_latest(&key).map_or_else(
554        || format!("this project pins rk {pin}; no release check is cached yet"),
555        |latest| {
556            format!(
557                "this project pins rk {pin}, and the latest known release is {}",
558                latest.trim_start_matches('v')
559            )
560        },
561    );
562    ProbeResult::ok(id, ProbeClass::Soft, message)
563}
564
565/// The working directory's `origin` remote parses to a host, which is
566/// what forge and slug detection read.
567fn git_remote() -> ProbeResult {
568    let id = "git-remote";
569    let out = Command::new(git_bin())
570        .args(["remote", "get-url", "origin"])
571        .output();
572    let url = match out {
573        Ok(out) if out.status.success() => String::from_utf8_lossy(&out.stdout).trim().to_owned(),
574        _ => {
575            return ProbeResult::failed(
576                id,
577                ProbeClass::Soft,
578                "the working directory has no origin remote",
579                "pass --repo <owner/name> where a command needs the slug",
580            );
581        }
582    };
583    // The raw remote never reaches the message: a malformed URL can carry
584    // userinfo — `https://user:token@…` — and a probe result lands in
585    // captured output and CI logs, where a credential must never appear.
586    remote_host(&url).map_or_else(
587        || {
588            ProbeResult::failed(
589                id,
590                ProbeClass::Soft,
591                "the origin remote does not parse to a host",
592                "pass --repo <owner/name> where a command needs the slug",
593            )
594        },
595        |host| ProbeResult::ok(id, ProbeClass::Soft, format!("origin resolves to {host}")),
596    )
597}
598
599/// The host in a git remote URL, for the `scp`-like and URL forms.
600fn remote_host(url: &str) -> Option<String> {
601    if let Some(rest) = url.split_once("://").map(|(_, rest)| rest) {
602        let authority = rest.split('/').next()?;
603        let host = authority
604            .rsplit_once('@')
605            .map_or(authority, |(_, host)| host);
606        let host = host.split(':').next()?;
607        return (!host.is_empty()).then(|| host.to_owned());
608    }
609    let (authority, path) = url.split_once(':')?;
610    let host = authority
611        .rsplit_once('@')
612        .map_or(authority, |(_, host)| host);
613    (!host.is_empty() && !path.is_empty()).then(|| host.to_owned())
614}
615
616/// A forge CLI is present and authenticated. `env_override` names the
617/// variable that substitutes the binary, which is also what keeps tests
618/// hermetic. `attempts` is tried in order and the first success wins, so
619/// a probe can prefer a sharper flag and still work where the CLI
620/// predates it.
621fn forge_cli(
622    id: &'static str,
623    env_override: &str,
624    default_bin: &str,
625    label: &str,
626    login: &str,
627    attempts: &[&[&str]],
628) -> ProbeResult {
629    let bin = std::env::var(env_override)
630        .ok()
631        .filter(|value| !value.is_empty())
632        .unwrap_or_else(|| default_bin.to_owned());
633    let mut spawned = false;
634    for args in attempts {
635        match Command::new(&bin).args(*args).output() {
636            Ok(out) if out.status.success() => {
637                return ProbeResult::ok(
638                    id,
639                    ProbeClass::Soft,
640                    format!("{default_bin} is authenticated"),
641                );
642            }
643            Ok(_) => spawned = true,
644            Err(_) => {}
645        }
646    }
647    if spawned {
648        ProbeResult::failed(
649            id,
650            ProbeClass::Soft,
651            format!("{default_bin} is not authenticated"),
652            format!("run {login}"),
653        )
654    } else {
655        ProbeResult::failed(
656            id,
657            ProbeClass::Soft,
658            format!("{default_bin} is not on PATH"),
659            format!("install {label}"),
660        )
661    }
662}
663
664/// One owner for a forge CLI's binary name, honoring the override that
665/// keeps the tests hermetic.
666#[must_use]
667pub fn forge_bin(forge: Forge) -> String {
668    crate::requirements::Tool::ForgeCli(forge)
669        .program()
670        .to_string_lossy()
671        .into_owned()
672}
673
674/// The version probe's stable name.
675const fn version_probe_id(forge: Forge) -> &'static str {
676    match forge {
677        Forge::Github => "gh-version",
678        Forge::Gitlab => "glab-version",
679    }
680}
681
682/// The first `<major>.<minor>.<patch>` run in a version line.
683///
684/// `gh version 2.19.0 (2022-10-25)` and `glab 1.114.0 (4d7c6cd)` both
685/// resolve. Nothing else in the crate parses a version string.
686#[must_use]
687pub fn parse_cli_version(text: &str) -> Option<(u32, u32, u32)> {
688    let bytes = text.as_bytes();
689    let mut start = 0;
690    while start < bytes.len() {
691        if !bytes[start].is_ascii_digit() {
692            start += 1;
693            continue;
694        }
695        let mut end = start;
696        while end < bytes.len() && (bytes[end].is_ascii_digit() || bytes[end] == b'.') {
697            end += 1;
698        }
699        let run = &text[start..end];
700        let mut parts = run.split('.');
701        let parsed = (|| {
702            let major = parts.next()?.parse().ok()?;
703            let minor = parts.next()?.parse().ok()?;
704            let patch = parts.next()?.parse().ok()?;
705            Some((major, minor, patch))
706        })();
707        if let Some(version) = parsed {
708            return Some(version);
709        }
710        start = end.max(start + 1);
711    }
712    None
713}
714
715/// Run `<bin> --version` and parse it. A spawn failure, a non-zero exit,
716/// or output carrying no version run all answer `None`, because none of
717/// them proves a version this binary can trust.
718#[must_use]
719pub fn forge_cli_version(bin: &str) -> Option<(u32, u32, u32)> {
720    let out = Command::new(bin).arg("--version").output().ok()?;
721    if !out.status.success() {
722        return None;
723    }
724    parse_cli_version(&String::from_utf8_lossy(&out.stdout))
725}
726
727/// A forge CLI is present and at or above the floor this binary calls.
728///
729/// Soft: a host that never starts work from an issue does not need it.
730fn forge_cli_floor(forge: Forge) -> ProbeResult {
731    let id = version_probe_id(forge);
732    let bin = forge_bin(forge);
733    let name = forge.cli();
734    let floor = forge.cli_floor();
735    match forge_cli_version(&bin) {
736        Some(found) if found >= floor => ProbeResult::ok(
737            id,
738            ProbeClass::Soft,
739            format!("{name} {} is at or above {}", show(found), show(floor)),
740        ),
741        Some(found) => ProbeResult::failed(
742            id,
743            ProbeClass::Soft,
744            format!(
745                "{name} {} is below the {} rk calls",
746                show(found),
747                show(floor)
748            ),
749            forge.cli_upgrade(),
750        ),
751        None => ProbeResult::failed(
752            id,
753            ProbeClass::Soft,
754            format!("{name} does not answer --version with a version"),
755            format!("install {name}"),
756        ),
757    }
758}
759
760/// `<major>.<minor>.<patch>` for a message.
761fn show((major, minor, patch): (u32, u32, u32)) -> String {
762    format!("{major}.{minor}.{patch}")
763}
764
765#[cfg(test)]
766mod tests {
767    use super::{parse_cli_version, remote_host};
768
769    /// Both forge CLIs print their version in a different shape, and a
770    /// line carrying no version resolves to nothing rather than to a
771    /// guess.
772    #[test]
773    fn a_version_line_parses_from_both_forge_clis() {
774        assert_eq!(
775            parse_cli_version("gh version 2.19.0 (2022-10-25)"),
776            Some((2, 19, 0))
777        );
778        assert_eq!(
779            parse_cli_version("glab 1.114.0 (4d7c6cd)\n"),
780            Some((1, 114, 0))
781        );
782        assert_eq!(parse_cli_version("gh version 2.99.0"), Some((2, 99, 0)));
783        assert_eq!(parse_cli_version("no version here"), None);
784        assert_eq!(parse_cli_version("gh version 2.19"), None);
785    }
786
787    /// The floor comparison orders by component, so no string comparison
788    /// survives it.
789    #[test]
790    fn a_floor_comparison_orders_by_component() {
791        assert!((2, 100, 0) > (2, 99, 0));
792        assert!((2, 9, 0) < (2, 19, 0));
793        assert!((2, 19, 0) >= (2, 19, 0));
794    }
795
796    #[test]
797    fn a_remote_host_parses_from_both_url_forms() {
798        assert_eq!(
799            remote_host("https://github.com/owner/name.git").as_deref(),
800            Some("github.com")
801        );
802        assert_eq!(
803            remote_host("git@gitlab.com:group/sub/name.git").as_deref(),
804            Some("gitlab.com")
805        );
806        assert_eq!(
807            remote_host("ssh://git@github.com:22/owner/name.git").as_deref(),
808            Some("github.com")
809        );
810        assert_eq!(remote_host("not a url"), None);
811    }
812}