ktstr/
kernel_path.rs

1// Shared kernel directory resolution.
2//
3// This file lives in two places: `src/kernel_path.rs` (the canonical
4// source in the parent ktstr crate, included into its `build.rs` via
5// `include!("src/kernel_path.rs")` and exposed to its lib via
6// `pub mod kernel_path`) and `ktstr-macros/src/kernel_path.rs` (the
7// bundled mirror, declared `mod kernel_path` in the macros crate's
8// `src/lib.rs` and verified byte-identical to the canonical by
9// `ktstr-macros/build.rs`'s drift check). The `include!` in the
10// parent's build.rs is deliberate — build.rs runs before the crate
11// compiles, so it cannot `use ktstr::...`. Duplicating the resolution
12// logic across the three consumers (parent build.rs, parent lib,
13// macros crate) would drift between build-time BTF discovery
14// (vmlinux.h generation), run-time kernel selection, and the macros
15// crate's parse-time KernelId construction.
16//
17// Constraints that every edit to this file must satisfy — breaking
18// any of them surfaces as either a cryptic build-script error or a
19// runtime/build-time behaviour mismatch:
20//
21// 1. **No non-std imports.** build.rs has its own dependency graph
22//    (`libbpf-cargo`, `tempfile`, etc.). A `use foo::bar` here would
23//    compile inside lib.rs (via the `pub mod` path) but fail inside
24//    build.rs because build.rs hasn't declared `foo` as a build-dep.
25// 2. **No `pub(crate)` items.** `pub(crate)` is meaningless inside
26//    an `include!`'d fragment — build.rs isn't a crate, so the item
27//    resolves at crate-root visibility there. Use `pub` for items
28//    build.rs needs, `fn` (private) for items lib.rs alone uses.
29// 3. **`#[cfg(test)]` blocks may use non-std test helpers freely.**
30//    Cargo does not set `cfg(test)` when compiling build scripts, so
31//    `#[cfg(test)]` items inside this file are simply elided from the
32//    build.rs view of the fragment — `tempfile`, `proptest`, etc. are
33//    safe to import inside `#[cfg(test)] mod tests { ... }`. The
34//    std-only rule (#1 above) applies to non-`cfg(test)` items only.
35// 4. **All functions are pure.** Callers supply inputs and handle
36//    caching — no global state, no `std::env::set_var`, no FS
37//    writes outside the caller-provided paths. Pure is what makes
38//    the double-consumer (build + runtime) safe.
39// 5. **Bundled into ktstr-macros.** Everything before the first
40//    `#[cfg(test)]` is mirrored verbatim between
41//    `src/kernel_path.rs` (the canonical source) and
42//    `ktstr-macros/src/kernel_path.rs` (the bundled mirror);
43//    `ktstr-macros/build.rs` panics on any drift. Edits to
44//    non-test items must update both copies in lock-step. The
45//    `#[cfg(test)]` portion lives in `src/kernel_path.rs` only.
46
47/// Human-readable enumeration of every form `KernelId::parse` accepts.
48/// The macro-time rejection in `declare_scheduler!(kernels = […])`
49/// cites this const verbatim. The runtime cache-lookup bails in
50/// `ktstr` / `cargo-ktstr` cite the `KTSTR_KERNEL_HINT` const, a manual
51/// mirror of this same wording — const composition cannot `concat!` a
52/// `const &str`, only literals — so keep the two in sync when either
53/// changes.
54pub const KERNEL_ID_GRAMMAR: &str = "exact version (`6.14`), inclusive range (`6.14..7.0` or \
55     `6.14..=7.0`), git source (`git+URL#tag=NAME`, `git+URL#branch=NAME`, or \
56     `git+URL#sha=<40-hex>`), absolute or `~`-prefixed path, local kernel package \
57     (`*.rpm`, `*.deb`, or `*.pkg.tar.zst`), distro kernel (`fedora`/`fedora-44`/`f44`, \
58     `ubuntu`/`ubuntu-24.04`, `amazonlinux`/`amazonlinux-2023`/`al2023`, \
59     `steamos`/`steamos-3.8`, `gke`/`gke-129`), or cache key";
60
61/// Kernel identifier: filesystem path, version string, cache key,
62/// stable-release range, or git source.
63///
64/// Parsing heuristic (see [`KernelId::parse`]):
65/// - Starts with `git+`: [`KernelId::Git`] (form `git+URL#tag=NAME` /
66///   `git+URL#branch=NAME` / `git+URL#sha=<40-hex>`)
67/// - Ends with `.rpm`, `.deb`, or `.pkg.tar.zst`: [`KernelId::Package`]
68/// - Contains `/` (without a `git+` prefix) or starts with `.` or `~`:
69///   [`KernelId::Path`]
70/// - Contains `..` between two version-shaped tokens:
71///   [`KernelId::Range`] (inclusive on both endpoints)
72/// - Matches `MAJOR.MINOR[.PATCH][-rcN]`: [`KernelId::Version`]
73/// - A distro name (`fedora` / `ubuntu` / `amazonlinux` /
74///   `steamos` / `gke`, an explicit-release `NAME-REL`, or shorthand `f44` /
75///   `al2023`): [`KernelId::Distro`]
76/// - Otherwise: [`KernelId::CacheKey`]
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub enum KernelId {
79    /// Filesystem path to kernel source/build directory.
80    Path(std::path::PathBuf),
81    /// Kernel version string (e.g. "6.14.2", "6.15-rc3").
82    Version(String),
83    /// Cache key (e.g. "6.14.2-tarball-x86_64-kc...").
84    CacheKey(String),
85    /// Inclusive range of stable kernel versions, expanded against
86    /// kernel.org's release index at resolve time. `start` and `end`
87    /// are both [`KernelId::Version`]-shaped strings (e.g. "6.10",
88    /// "6.13"); the resolver fans this out to every release in
89    /// [start, end] inclusive on both endpoints regardless of whether
90    /// the parser saw `..` or `..=`. A version present in the range
91    /// but missing from the upstream index is a hard error before any
92    /// boot — partial expansions are not silently dropped. The
93    /// `syntax_inclusive` flag preserves the original separator for
94    /// round-trip [`std::fmt::Display`] and operator-facing error
95    /// messages; it does not change resolution semantics.
96    Range {
97        /// Inclusive lower bound, version-shaped.
98        start: String,
99        /// Inclusive upper bound, version-shaped.
100        end: String,
101        /// `true` when the parser saw `..=` (or the construction site
102        /// asked for it); `false` for the `..` form. Both are
103        /// resolved as inclusive ranges; the flag exists so
104        /// [`std::fmt::Display`] and the inverted-range error
105        /// message round-trip the operator's typed form.
106        syntax_inclusive: bool,
107    },
108    /// Git source: acquire the source at `git_ref` per `ref_kind`
109    /// (tag / branch / sha), chosen explicitly by the operator's
110    /// `#tag=` / `#branch=` / `#sha=` fragment — no DWIM. Stored
111    /// verbatim by `KernelId::parse` with no remote contact. At
112    /// cache-resolution time `resolve_git_kernel` obtains the peeled
113    /// commit from the exact gix fetch's single prepared ref-map, probes
114    /// the content-addressed cache, and receives the pack only for the
115    /// elected builder.
116    ///
117    /// Acquisition is routed by host (see `resolve_git_kernel` /
118    /// `crate::fetch`):
119    /// - `Tag` and `Branch` use one uniform, kind-directed, depth-one
120    ///   in-process gix fetch on every host. Annotated tags peel to the
121    ///   commit while their selected tag object is retained.
122    /// - An explicit immutable GitHub `Sha` uses its codeload snapshot.
123    ///   `Sha` is unsupported off GitHub because the remote generally
124    ///   does not allow fetching an unadvertised bare commit.
125    Git {
126        /// Remote URL. Branches/tags are fetched verbatim through gix;
127        /// an explicit GitHub SHA uses codeload.
128        url: String,
129        /// The ref value after `kind=` (verbatim, no `refs/` prefix) for
130        /// `Tag` / `Branch` / `Sha`; the whole unrecognized fragment for
131        /// `Unknown`. For `ref_kind == Sha` this is the 40-hex commit id.
132        git_ref: String,
133        /// Which git namespace `git_ref` names, from the explicit
134        /// `#tag=` / `#branch=` / `#sha=` selector. `Unknown` marks a
135        /// bare `#REF` or unrecognized selector that `validate` rejects.
136        ref_kind: GitRefKind,
137    },
138    /// Local kernel package: an `.rpm`, `.deb`, or pacman
139    /// `.pkg.tar.zst` file on disk, to be unpacked for its prebuilt
140    /// kernel image and modules. Classified by [`KernelId::parse`] on
141    /// the case-sensitive `.rpm` / `.deb` / `.pkg.tar.zst` suffix
142    /// ahead of the path check, so `./foo.rpm`, `/abs/foo.deb`, and a
143    /// bare `foo.rpm` all land here rather than as
144    /// [`KernelId::Path`]. The `path` is `~`-expanded identically to
145    /// the Path variant.
146    Package {
147        /// Path to the `.rpm` / `.deb` / `.pkg.tar.zst` file.
148        path: std::path::PathBuf,
149    },
150    /// Distro-provided prebuilt kernel: download a specific build for a
151    /// named distribution and (optional) release. A bare distro name
152    /// (`fedora`) leaves `release` `None` — the resolver picks the
153    /// distro's default; an explicit release (`fedora-44`, `f44`,
154    /// `ubuntu-24.04`, `amazonlinux-2023`, `al2023`,
155    /// `steamos-3.8`, `gke-129`) pins one. The
156    /// release string's grammar is distro-specific and enforced by
157    /// [`KernelId::validate`], not `parse`: a distro name with a
158    /// malformed release parses to this variant and is rejected at
159    /// validate time (mirroring the git arm's parse/validate split),
160    /// never silently demoted to [`KernelId::CacheKey`].
161    Distro {
162        /// Which distribution.
163        kind: DistroKind,
164        /// Release identifier (e.g. "44", "24.04", "2023"), or `None`
165        /// for the distro's default.
166        release: Option<String>,
167    },
168}
169
170/// Which distribution a [`KernelId::Distro`] names.
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172pub enum DistroKind {
173    /// Fedora (`fedora`, `fedora-44`, or shorthand `f44`).
174    Fedora,
175    /// Ubuntu (`ubuntu`, `ubuntu-24.04`).
176    Ubuntu,
177    /// Amazon Linux (`amazonlinux`, `amazonlinux-2023`, or shorthand
178    /// `al2023`).
179    AmazonLinux,
180    /// SteamOS (`steamos`, or a pinned channel `steamos-3.8`).
181    /// x86_64 only — Valve publishes no other architecture.
182    SteamOs,
183    /// Google Kubernetes Engine COS node image (`gke`, or a constrained
184    /// COS milestone such as `gke-129`). Bare `gke` tracks the newest
185    /// GKE-promoted image; the milestone form tracks the newest promoted
186    /// revision within that milestone. x86_64 only today.
187    Gke,
188}
189
190/// Which git ref namespace a [`KernelId::Git`]'s `git_ref` names,
191/// chosen explicitly by the operator via the `#tag=` / `#branch=` /
192/// `#sha=` fragment — never DWIM-inferred.
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194pub enum GitRefKind {
195    /// `#tag=v6.14` → an annotated or lightweight tag (`refs/tags/`).
196    Tag,
197    /// `#branch=for-next` → a branch head (`refs/heads/`).
198    Branch,
199    /// `#sha=<40-hex>` → a raw commit id.
200    Sha,
201    /// A bare `#REF` fragment (no `kind=`) or an unrecognized selector;
202    /// carried so [`KernelId::validate`] can emit an actionable error.
203    /// Never resolved.
204    Unknown,
205}
206
207impl KernelId {
208    /// Parse a string into a kernel identifier.
209    ///
210    /// Recognizes (in order):
211    /// - `git+`-prefixed → [`KernelId::Git`]. ANY `git+…` string is a
212    ///   Git source (the `git+` prefix takes precedence over the range
213    ///   and `/`-contains tests below), so a typo such as a missing
214    ///   `#fragment` never silently becomes a `Path`. The fragment
215    ///   selects the ref kind: `#tag=NAME` / `#branch=NAME` /
216    ///   `#sha=<40-hex>`; a missing/empty fragment or unrecognized
217    ///   selector yields `GitRefKind::Unknown`, and an empty URL an
218    ///   empty `url` — both of which [`KernelId::validate`] rejects
219    ///   with an actionable error rather than the resolver later
220    ///   reporting a confusing "path not found".
221    /// - `.rpm`/`.deb`/`.pkg.tar.zst`-suffixed → [`KernelId::Package`].
222    ///   Checked ahead of the path test so `./foo.rpm`, `/abs/foo.deb`,
223    ///   and a bare `foo.rpm` all classify as a package rather than a
224    ///   path.
225    /// - `START..=END` or `START..END` where both endpoints are
226    ///   version-shaped → [`KernelId::Range`]. The endpoints are
227    ///   ALWAYS inclusive — both `..` and `..=` spellings produce a
228    ///   closed range, regardless of Rust's exclusive-`..` /
229    ///   inclusive-`..=` distinction. Both forms are accepted so test
230    ///   authors and CLI users can write whichever feels natural.
231    /// - `/`-containing or `.`/`~`-prefixed → [`KernelId::Path`].
232    /// - Version-shaped → [`KernelId::Version`].
233    /// - A distro name (`fedora` / `ubuntu` / `amazonlinux` /
234    ///   `steamos`, an explicit-release `NAME-REL`, or
235    ///   shorthand `f44` / `al2023`) →
236    ///   [`KernelId::Distro`]. The release grammar is checked by
237    ///   `validate`, not here — a malformed release still classifies as
238    ///   `Distro` (not `CacheKey`) so `validate` can reject it.
239    /// - Anything else → [`KernelId::CacheKey`].
240    pub fn parse(s: &str) -> Self {
241        if let Some(rest) = s.strip_prefix("git+") {
242            // ANY `git+…` string is a Git source — split off the
243            // `#fragment` (a missing one leaves an empty fragment) and
244            // NEVER fall through to Path/CacheKey, so a typo such as
245            // `git+URL` (no fragment) surfaces the actionable
246            // git-grammar error from `validate` rather than a confusing
247            // "path not found". `parse` returns `Self`, not `Result`, so
248            // all structural rejection (Unknown kind, empty url/ref, bad
249            // sha) is deferred to `validate`.
250            let (url, frag) = match rest.rsplit_once('#') {
251                Some((url, frag)) => (url, frag),
252                None => (rest, ""),
253            };
254            // Explicit ref-kind grammar: `#tag=NAME` / `#branch=NAME` /
255            // `#sha=<40-hex>`. A bare `#REF` (no `kind=`), an empty
256            // fragment, or an unrecognized selector parses as `Unknown`.
257            let (ref_kind, git_ref) = match frag.split_once('=') {
258                Some(("tag", v)) => (GitRefKind::Tag, v.to_string()),
259                Some(("branch", v)) => (GitRefKind::Branch, v.to_string()),
260                Some(("sha", v)) => (GitRefKind::Sha, v.to_string()),
261                _ => (GitRefKind::Unknown, frag.to_string()),
262            };
263            return KernelId::Git {
264                url: url.to_string(),
265                git_ref,
266                ref_kind,
267            };
268        }
269        // Case-sensitive suffix, checked before the path arm so a
270        // package spec with directory separators (`/abs/foo.deb`) or a
271        // `.`-prefix (`./foo.rpm`) still classifies as a package.
272        // Classification requires a non-empty file stem before the
273        // extension: a bare `.deb` / `.rpm` / `.pkg.tar.zst` (or a
274        // path ending in such a component) is a HIDDEN-FILE name, not
275        // a package spec — it falls through to the Path arm via its
276        // `.` prefix or `/` content, preserving the dot-prefix → Path
277        // contract the property tests pin.
278        let base = s.rsplit('/').next().unwrap_or(s);
279        if [".rpm", ".deb", ".pkg.tar.zst"]
280            .iter()
281            .any(|ext| base.ends_with(ext) && base.len() > ext.len())
282        {
283            return KernelId::Package {
284                path: expand_tilde(s),
285            };
286        }
287        if let Some((start, end)) = s.split_once("..=")
288            && _is_version_string(start)
289            && _is_version_string(end)
290        {
291            return KernelId::Range {
292                start: start.to_string(),
293                end: end.to_string(),
294                syntax_inclusive: true,
295            };
296        }
297        if let Some((start, end)) = s.split_once("..")
298            && _is_version_string(start)
299            && _is_version_string(end)
300        {
301            return KernelId::Range {
302                start: start.to_string(),
303                end: end.to_string(),
304                syntax_inclusive: false,
305            };
306        }
307        if s.contains('/') || s.starts_with('.') || s.starts_with('~') {
308            return KernelId::Path(expand_tilde(s));
309        }
310        if _is_version_string(s) {
311            return KernelId::Version(s.to_string());
312        }
313        if let Some(distro) = parse_distro(s) {
314            return distro;
315        }
316        KernelId::CacheKey(s.to_string())
317    }
318
319    /// Parse a comma-separated list of kernel specs into a vector of
320    /// identifiers. Empty entries are silently skipped (so trailing
321    /// commas or repeated separators are forgiving). Each non-empty
322    /// segment is fed through [`KernelId::parse`] verbatim — so
323    /// `parse_list("6.10,git+URL#branch=main,/srv/linux")` returns three
324    /// distinct variants. Deduplication is the resolver's
325    /// responsibility (after canonicalization to a cache key); this
326    /// function preserves order and duplicates as written.
327    pub fn parse_list(s: &str) -> Vec<KernelId> {
328        s.split(',')
329            .map(str::trim)
330            .filter(|seg| !seg.is_empty())
331            .map(KernelId::parse)
332            .collect()
333    }
334
335    /// Validate a parsed `KernelId` for resolve-time legality. Returns
336    /// `Err(message)` when the identifier carries a structural problem
337    /// the parser couldn't catch on its own — currently:
338    ///
339    /// - [`KernelId::Range`] with `start > end` after numeric
340    ///   component-wise comparison. The parser cannot reject this at
341    ///   parse time because both endpoints are valid version strings
342    ///   in isolation; the inversion only surfaces when the two are
343    ///   compared.
344    /// - [`KernelId::Git`] with an `Unknown` ref kind, an empty
345    ///   url/ref, or a `#sha=` that isn't a full 40-hex id.
346    /// - [`KernelId::Distro`] whose explicit release does not match the
347    ///   distro's grammar (Fedora `\d{2,3}`, Ubuntu `YY.MM`, Amazon
348    ///   Linux `\d{4}`, SteamOS
349    ///   `\d{1,2}.\d{1,2}`). As with git, the parser defers the
350    ///   release
351    ///   check here so a malformed release classifies as `Distro`
352    ///   rather than silently becoming a `CacheKey`.
353    ///
354    /// The remaining variants (Path, Version, CacheKey, Package) always
355    /// return `Ok(())` — this is a hook for per-variant invariants, not
356    /// a general-purpose validator.
357    /// Use `Result<(), String>` rather than `anyhow::Result` because
358    /// this file is included from `build.rs` (see file header rule
359    /// #1, no non-std imports outside `cfg(test)`).
360    ///
361    /// Comparison semantics: each endpoint decomposes to a
362    /// `(major, minor, patch, rc)` tuple where missing patch maps to
363    /// `0` and missing `-rc` maps to `u64::MAX` so a release
364    /// (`6.10`) sorts strictly above any pre-release (`6.10-rc3`) of
365    /// the same major.minor.patch. Inverted ranges include
366    /// `7.0..6.99`, `6.10..6.5`, `6.10..6.10-rc3` (release > rc), and
367    /// `6.10-rc3..6.10-rc1`. Equal endpoints (`6.10..6.10`) pass
368    /// validation as a single-element range.
369    pub fn validate(&self) -> Result<(), String> {
370        match self {
371            KernelId::Range {
372                start,
373                end,
374                syntax_inclusive,
375            } => {
376                let start_key = decompose_version_for_compare(start).ok_or_else(|| {
377                    format!(
378                        "kernel range start `{start}` is not a parseable version. \
379                         Expected `MAJOR.MINOR[.PATCH][-rc<num>]` (e.g. \"6.10\", \
380                         \"6.14.2\", \"6.15-rc3\"). Range examples: `6.10..6.15`, \
381                         `6.10-rc1..=6.10`.",
382                    )
383                })?;
384                // END is series-inclusive: a 2-component `MAJOR.MINOR`
385                // END names the whole series (see `range_end_key`), so
386                // the inversion check must use the SAME widened bound the
387                // expansion does — otherwise a valid same-series range
388                // like `6.14.5..6.14` (= 6.14.5 .. end of the 6.14
389                // series) is falsely rejected as inverted.
390                let end_key = range_end_key(end).ok_or_else(|| {
391                    format!(
392                        "kernel range end `{end}` is not a parseable version. \
393                         Expected `MAJOR.MINOR[.PATCH][-rc<num>]` (e.g. \"6.10\", \
394                         \"6.14.2\", \"6.15-rc3\"). Range examples: `6.10..6.15`, \
395                         `6.10-rc1..=6.10`.",
396                    )
397                })?;
398                if start_key > end_key {
399                    let sep = if *syntax_inclusive { "..=" } else { ".." };
400                    return Err(format!(
401                        "inverted kernel range `{start}{sep}{end}`: start version is greater \
402                         than end version. Swap the endpoints (`{end}{sep}{start}`) or use \
403                         a single version (no range) to test just one release.",
404                    ));
405                }
406                Ok(())
407            }
408            KernelId::Git {
409                url,
410                git_ref,
411                ref_kind,
412            } => {
413                if url.is_empty() {
414                    return Err(format!(
415                        "git source `git+#{git_ref}`: empty URL — write \
416                         `git+<url>#tag=<name>` (or `#branch=` / `#sha=`)."
417                    ));
418                }
419                if *ref_kind == GitRefKind::Unknown {
420                    return Err(format!(
421                        "git source `git+{url}#{git_ref}`: the ref kind must be \
422                         explicit — write `#tag=<name>`, `#branch=<name>`, or \
423                         `#sha=<40-hex>` (a bare `#REF` is no longer accepted).",
424                    ));
425                }
426                if git_ref.is_empty() {
427                    return Err(format!(
428                        "git source `git+{url}#...`: empty ref value — write \
429                         `#tag=<name>`, `#branch=<name>`, or `#sha=<40-hex>`.",
430                    ));
431                }
432                if *ref_kind == GitRefKind::Sha
433                    && (git_ref.len() != 40 || !git_ref.bytes().all(|b| b.is_ascii_hexdigit()))
434                {
435                    return Err(format!(
436                        "git source `git+{url}#sha={git_ref}`: a sha must be the full \
437                         40-hex commit id (abbreviated shas can't be fetched); use \
438                         `#tag=` or `#branch=` for a name.",
439                    ));
440                }
441                Ok(())
442            }
443            KernelId::Distro { kind, release } => {
444                let Some(rel) = release.as_deref() else {
445                    return Ok(());
446                };
447                let all_digits = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit());
448                let (ok, expected) = match kind {
449                    // 2–3 digits: `44` today, `100`+ future-proofed.
450                    DistroKind::Fedora => (
451                        (2..=3).contains(&rel.len()) && all_digits(rel),
452                        "a 2- or 3-digit release number (e.g. `fedora-44` or `f44`)",
453                    ),
454                    // `YY.MM`, e.g. `24.04`.
455                    DistroKind::Ubuntu => (
456                        matches!(rel.split_once('.'), Some((y, m))
457                            if y.len() == 2 && m.len() == 2 && all_digits(y) && all_digits(m)),
458                        "a `YY.MM` release (e.g. `ubuntu-24.04`)",
459                    ),
460                    // 4-digit year, e.g. `2023`.
461                    DistroKind::AmazonLinux => (
462                        rel.len() == 4 && all_digits(rel),
463                        "a 4-digit year release (e.g. `amazonlinux-2023` or `al2023`)",
464                    ),
465                    // `MAJOR.MINOR` channel version, e.g. `3.8`.
466                    DistroKind::SteamOs => (
467                        matches!(rel.split_once('.'), Some((maj, min))
468                            if (1..=2).contains(&maj.len()) && (1..=2).contains(&min.len())
469                                && all_digits(maj) && all_digits(min)),
470                        "a `MAJOR.MINOR` channel version (e.g. `steamos-3.8`)",
471                    ),
472                    // COS milestone, e.g. `129`.
473                    DistroKind::Gke => (
474                        (2..=3).contains(&rel.len()) && all_digits(rel),
475                        "a 2- or 3-digit COS milestone (e.g. `gke-129`)",
476                    ),
477                };
478                if ok {
479                    Ok(())
480                } else {
481                    Err(format!(
482                        "distro kernel `{self}`: `{rel}` is not a valid \
483                         {kind} release — expected {expected}.",
484                        kind = kind.as_str(),
485                    ))
486                }
487            }
488            KernelId::Path(_)
489            | KernelId::Version(_)
490            | KernelId::CacheKey(_)
491            | KernelId::Package { .. } => Ok(()),
492        }
493    }
494}
495
496impl std::fmt::Display for KernelId {
497    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
498        match self {
499            KernelId::Path(p) => write!(f, "{}", p.display()),
500            KernelId::Version(v) => write!(f, "{v}"),
501            KernelId::CacheKey(k) => write!(f, "{k}"),
502            KernelId::Range {
503                start,
504                end,
505                syntax_inclusive,
506            } => {
507                let sep = if *syntax_inclusive { "..=" } else { ".." };
508                write!(f, "{start}{sep}{end}")
509            }
510            KernelId::Git {
511                url,
512                git_ref,
513                ref_kind,
514            } => match ref_kind {
515                GitRefKind::Tag => write!(f, "git+{url}#tag={git_ref}"),
516                GitRefKind::Branch => write!(f, "git+{url}#branch={git_ref}"),
517                GitRefKind::Sha => write!(f, "git+{url}#sha={git_ref}"),
518                // Round-trip a rejected bare fragment verbatim so
519                // `parse(Display(x)) == x` still holds for the Unknown case.
520                GitRefKind::Unknown => write!(f, "git+{url}#{git_ref}"),
521            },
522            KernelId::Package { path } => write!(f, "{}", path.display()),
523            KernelId::Distro { kind, release } => {
524                let name = kind.as_str();
525                match release {
526                    // Shorthand inputs (`f44`, `al2023`) render in long
527                    // form; `parse(Display(x))` still yields an equal id
528                    // (both spellings parse to the same variant).
529                    Some(rel) => write!(f, "{name}-{rel}"),
530                    None => write!(f, "{name}"),
531                }
532            }
533        }
534    }
535}
536
537impl DistroKind {
538    /// The canonical long-form distro name.
539    fn as_str(self) -> &'static str {
540        match self {
541            DistroKind::Fedora => "fedora",
542            DistroKind::Ubuntu => "ubuntu",
543            DistroKind::AmazonLinux => "amazonlinux",
544            DistroKind::SteamOs => "steamos",
545            DistroKind::Gke => "gke",
546        }
547    }
548}
549
550/// Classify a distro kernel spec, or `None` so the caller falls
551/// through to [`KernelId::CacheKey`].
552///
553/// Recognizes the long form — an exact distro name (`fedora`, release
554/// `None`) or `NAME-REL` (`fedora-44`) — and the shorthands `f<rel>`
555/// (Fedora) and `al<rel>` (Amazon Linux), where `<rel>` is a run of
556/// digits. A bare `al<digits>` (`al2023`, or a malformed `al9`) is
557/// Amazon Linux; a non-digit remainder (`alma9`, whose `al`-stripped
558/// tail `ma9` is not all digits) is not a distro spec and stays a
559/// cache key.
560/// The release portion is carried verbatim; its per-distro
561/// digit grammar is enforced by [`KernelId::validate`], not here — so a
562/// name with a malformed release (`fedora-abc`, `f4`) classifies as
563/// `Distro` and surfaces an actionable validation error rather than a
564/// silent cache-key miss (mirroring the git arm's parse/validate
565/// split). A shorthand whose remainder is not all digits (`foo`,
566/// `alpha`) is not a distro spec and stays a cache key.
567fn parse_distro(s: &str) -> Option<KernelId> {
568    for (name, kind) in [
569        ("fedora", DistroKind::Fedora),
570        ("ubuntu", DistroKind::Ubuntu),
571        ("amazonlinux", DistroKind::AmazonLinux),
572        ("steamos", DistroKind::SteamOs),
573        ("gke", DistroKind::Gke),
574    ] {
575        if s == name {
576            return Some(KernelId::Distro {
577                kind,
578                release: None,
579            });
580        }
581        if let Some(rel) = s.strip_prefix(name).and_then(|r| r.strip_prefix('-')) {
582            return Some(KernelId::Distro {
583                kind,
584                release: Some(rel.to_string()),
585            });
586        }
587    }
588    for (prefix, kind) in [("f", DistroKind::Fedora), ("al", DistroKind::AmazonLinux)] {
589        if let Some(rel) = s.strip_prefix(prefix)
590            && !rel.is_empty()
591            && rel.bytes().all(|b| b.is_ascii_digit())
592        {
593            return Some(KernelId::Distro {
594                kind,
595                release: Some(rel.to_string()),
596            });
597        }
598    }
599    None
600}
601
602/// Check if a string matches a kernel version pattern.
603///
604/// Matches: `6` (bare major prefix), `6.14`, `6.14.2`, `6.15-rc3`,
605/// `6.14.2-rc1`. Does not match: `v6.14` (git tag prefix), `6.`
606/// (trailing dot), `6.14.2-tarball-x86_64-kc...` (cache key with
607/// extra segments).
608fn _is_version_string(s: &str) -> bool {
609    let (version_part, rc_part) = match s.split_once("-rc") {
610        Some((v, rc)) => (v, Some(rc)),
611        None => (s, None),
612    };
613
614    // The part after -rc must be a non-empty digit string.
615    if let Some(rc) = rc_part
616        && (rc.is_empty() || !rc.bytes().all(|b| b.is_ascii_digit()))
617    {
618        return false;
619    }
620
621    let mut parts = version_part.split('.');
622
623    // Major: required, non-empty digits.
624    match parts.next() {
625        Some(p) if !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) => {}
626        _ => return false,
627    }
628    // Minor: OPTIONAL — a bare MAJOR (`6`) is a valid version prefix
629    // that resolves to the highest patch across all minors (see
630    // `crate::fetch::fetch_version_for_prefix`). If present it must be
631    // non-empty digits; `6.` (trailing dot) is rejected as an empty
632    // component.
633    match parts.next() {
634        None => {}
635        Some(p) if !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()) => {}
636        _ => return false,
637    }
638    // Patch: optional, non-empty digits.
639    if let Some(patch) = parts.next()
640        && (patch.is_empty() || !patch.bytes().all(|b| b.is_ascii_digit()))
641    {
642        return false;
643    }
644    // No more segments allowed (rejects `1.2.3.4`).
645    parts.next().is_none()
646}
647
648/// Decompose a version-shaped string into a `(major, minor, patch,
649/// rc)` tuple suitable for `Ord` comparison. Returns `None` when the
650/// input doesn't match the kernel-version grammar — same predicate as
651/// [`_is_version_string`] but extracting numeric components rather
652/// than just yes/no.
653///
654/// Comparison semantics:
655/// - Missing patch defaults to `0` so `6.10` and `6.10.0` compare
656///   equal.
657/// - Missing `-rcN` defaults to `u64::MAX` so a release
658///   (`6.10`, `6.10.5`) sorts strictly above any pre-release
659///   (`6.10-rc3`, `6.10.5-rc1`) of the same `major.minor.patch`. A
660///   future major/minor/patch bump still dominates because the tuple
661///   is compared in declaration order — the rc-as-MAX trick only
662///   resolves ties on the leading three components.
663///
664/// Used by [`KernelId::validate`] to detect inverted ranges
665/// (`6.16..6.12`, `6.10..6.10-rc3`, `7.0..6.99`), and by
666/// the `cli` module's range-expansion helper to filter and sort
667/// kernel.org release rows that fall inside a `start..end` interval.
668pub(crate) fn decompose_version_for_compare(s: &str) -> Option<(u64, u64, u64, u64)> {
669    let (version_part, rc_part) = match s.split_once("-rc") {
670        Some((v, rc)) => (v, Some(rc)),
671        None => (s, None),
672    };
673    // rc must be a non-empty digit string when present.
674    let rc: u64 = match rc_part {
675        Some(rc) if rc.is_empty() || !rc.bytes().all(|b| b.is_ascii_digit()) => return None,
676        Some(rc) => rc.parse().ok()?,
677        None => u64::MAX,
678    };
679    let mut parts = version_part.split('.');
680    let major: u64 = parts.next()?.parse().ok()?;
681    // Minor optional: a bare MAJOR (`6`) decomposes to `(major, 0, 0,
682    // ..)` so it behaves as a series-floor prefix, consistent with
683    // `_is_version_string` accepting a bare major.
684    let minor: u64 = match parts.next() {
685        None => 0,
686        Some("") => return None,
687        Some(m) => m.parse().ok()?,
688    };
689    let patch: u64 = match parts.next() {
690        Some("") => return None,
691        Some(p) => p.parse().ok()?,
692        None => 0,
693    };
694    // Reject `1.2.3.4` and similar — only major.minor[.patch] is grammar.
695    if parts.next().is_some() {
696        return None;
697    }
698    Some((major, minor, patch, rc))
699}
700
701/// The upper-bound comparison key for a range's END endpoint,
702/// series-inclusive: a 2-component `MAJOR.MINOR` (or bare-major) END
703/// with no `-rc` names the WHOLE series, so its patch and rc slots are
704/// widened to `u64::MAX`. [`decompose_version_for_compare`] alone maps a
705/// missing patch to 0, which as an inclusive upper bound would exclude
706/// every `6.14.N` (N >= 1) from an END of `6.14`. An explicit-patch END
707/// (`6.14.2`) or an `-rc` END keeps its exact key. Shared by
708/// [`KernelId::validate`]'s inversion check and the `cli` module's
709/// range expansion (`range_bounds`) so the two agree on where a range
710/// ends. START needs no such widening — its `.0` is the series floor.
711pub(crate) fn range_end_key(end: &str) -> Option<(u64, u64, u64, u64)> {
712    let key = decompose_version_for_compare(end)?;
713    // Same predicate as `crate::fetch::is_major_minor_prefix`, inlined
714    // because this file forbids non-std imports (file-header rule #1):
715    // a 2-component (or bare-major) endpoint with no `-rc` is a whole
716    // series and widens to its ceiling.
717    if end.matches('.').count() < 2 && !end.contains("-rc") {
718        Some((key.0, key.1, u64::MAX, u64::MAX))
719    } else {
720        Some(key)
721    }
722}
723
724/// Expand a leading `~` or `~/...` in `s` against `$HOME` and
725/// return the resulting [`std::path::PathBuf`]. Any other shape (no leading
726/// `~`, `~user/...` for a different user, `$HOME` unset or empty)
727/// passes through verbatim — the caller's downstream `is_dir()`
728/// surfaces a regular "no such directory" error instead of being
729/// silently rewritten.
730///
731/// Cases handled:
732/// - `"~"` → `$HOME`
733/// - `"~/"` → `$HOME` (same as bare `"~"`; the empty suffix
734///   after `~/` yields no trailing separator)
735/// - `"~/linux"` → `$HOME/linux`
736/// - `"~user/..."` → unchanged (std has no `getpwnam`; a
737///   different-user expansion would require shelling out, which
738///   the file's "no non-std imports outside cfg(test)" rule
739///   forbids; the operator who wants a peer's home dir can spell
740///   it absolutely)
741/// - any input not starting with `~` → unchanged
742/// - `~`-prefix with `$HOME` unset / empty → unchanged (the
743///   downstream `is_dir()` failure is the clearest error path
744///   we can produce without a logging dep)
745///
746/// Pure with respect to filesystem writes; reads `$HOME` once. Env
747/// reads are consistent with the existing
748/// [`kernel_release_from_procfs`] pattern (FS read at resolve time)
749/// and explicitly outside the file-header `std::env::set_var` ban.
750///
751/// Called from [`KernelId::parse`]'s Path arm so the Path variant
752/// stores an absolute (or filesystem-resolvable) path. Without this,
753/// `KernelId::parse("~/linux")` stores the literal `"~/linux"`,
754/// which `is_dir()` rejects unconditionally — there is no shell to
755/// perform the standard tilde expansion on the operator's behalf at
756/// CLI invocation time.
757fn expand_tilde(s: &str) -> std::path::PathBuf {
758    // Bare `~` and `~/...` are the only shapes we expand. Anything
759    // else falls through verbatim.
760    if s != "~" && !s.starts_with("~/") {
761        return std::path::PathBuf::from(s);
762    }
763    // `$HOME` empty or unset is treated identically to "no
764    // expansion possible" — the caller's `is_dir()` check will
765    // surface the missing-path error normally. We do NOT panic
766    // here because `KernelId::parse` is `pub` and on a hot CLI
767    // path; failing to expand a single arg is not a fatal
768    // condition for the whole CLI.
769    let home = match std::env::var("HOME") {
770        Ok(h) if !h.is_empty() => h,
771        _ => return std::path::PathBuf::from(s),
772    };
773    if s == "~" {
774        return std::path::PathBuf::from(home);
775    }
776    // s starts with "~/", so the suffix we want to splice on is
777    // the slice starting AFTER the `/` separator. Joining `home`
778    // with `&s[1..]` would land an absolute path inside `home`
779    // (PathBuf::push of an absolute path RESETS the buffer to that
780    // absolute path), so we strip the leading `/` first. Doubled
781    // separators in the rest portion (`~//foo` → `s[2..] = "/foo"`)
782    // would also reset the buffer; loop the strip so any run of
783    // leading `/`s is consumed before the push.
784    let mut rest = &s[2..]; // skip "~/"
785    while let Some(stripped) = rest.strip_prefix('/') {
786        rest = stripped;
787    }
788    let mut p = std::path::PathBuf::from(home);
789    if !rest.is_empty() {
790        p.push(rest);
791    }
792    p
793}
794
795/// Read the running kernel release from `/proc/sys/kernel/osrelease`.
796///
797/// Returns `None` if the procfs entry is unreadable, empty, or missing.
798/// Callers that need the release string for `/lib/modules/{release}/…`
799/// fallbacks use this rather than shelling out to `uname -r`: the
800/// procfs entry exposes the raw utsname release (served by
801/// `proc_do_uts_string` in linux/kernel/utsname_sysctl.c), the same
802/// field uname(2) reads — modulo the UNAME26 personality shim
803/// `override_release` applies on the uname(2) path only — and only
804/// costs a small read.
805fn kernel_release_from_procfs() -> Option<String> {
806    std::fs::read_to_string("/proc/sys/kernel/osrelease")
807        .ok()
808        .map(|s| s.trim().to_string())
809        .filter(|s| !s.is_empty())
810}
811
812/// Resolve a kernel source/build directory.
813///
814/// `kernel_dir`: value of `KTSTR_KERNEL` env var (if set).
815///
816/// Search order:
817/// 1. `kernel_dir` parameter (from env var)
818/// 2. `./linux` (workspace-local build tree)
819/// 3. `../linux` (sibling directory)
820/// 4. `/lib/modules/{release}/build` (installed kernel headers)
821///
822/// Returns the directory path if a kernel tree is found.
823#[allow(dead_code)]
824pub fn resolve_kernel(kernel_dir: Option<&str>) -> Option<std::path::PathBuf> {
825    // 1. Explicit directory.
826    if let Some(dir) = kernel_dir {
827        let p = std::path::PathBuf::from(dir);
828        if p.is_dir() {
829            return Some(p);
830        }
831    }
832
833    // 2-3. Local build trees.
834    for rel in &["./linux", "../linux"] {
835        let p = std::path::PathBuf::from(rel);
836        if p.is_dir() && has_kernel_artifacts(&p) {
837            return Some(p);
838        }
839    }
840
841    // 4. Installed kernel build dir — use the running release from
842    // procfs to locate `/lib/modules/{release}/build`.
843    if let Some(rel) = kernel_release_from_procfs() {
844        let p = std::path::PathBuf::from(format!("/lib/modules/{rel}/build"));
845        if p.is_dir() {
846            return Some(p);
847        }
848    }
849
850    None
851}
852
853/// Derive the kernel directory (holding `vmlinux` and related build
854/// artifacts) from a kernel image path.
855///
856/// Recognizes two layouts:
857///
858/// - **Build tree**: `<root>/arch/x86/boot/bzImage` (or
859///   `arch/arm64/boot/Image`) → `<root>`. Suffix match on the
860///   canonical path.
861/// - **Cache entry**: `<cache_dir>/bzImage` (or `Image`) with a
862///   sibling `vmlinux` → `<cache_dir>`. Lets probe source-location
863///   resolution walk a cached kernel's stripped ELF.
864///
865/// Returns `None` when neither layout matches or the input path
866/// doesn't canonicalize.
867///
868/// Cache entries carry stripped vmlinux (no DWARF) — `strip_vmlinux_debug`
869/// drops `.debug_*` on every cache entry regardless of source type.
870/// file:line resolution works only for build-tree paths where the
871/// unstripped vmlinux is still present, or when the caller layers
872/// `cache::prefer_source_tree_for_dwarf` on top to re-route
873/// `cache::KernelSource::Local` entries at their original source tree.
874#[allow(dead_code)]
875pub fn derive_kernel_dir(image: &std::path::Path) -> Option<std::path::PathBuf> {
876    let canon = std::fs::canonicalize(image).ok()?;
877
878    #[cfg(target_arch = "x86_64")]
879    let build_suffix = "/arch/x86/boot/bzImage";
880    #[cfg(target_arch = "aarch64")]
881    let build_suffix = "/arch/arm64/boot/Image";
882
883    if let Some(canon_str) = canon.to_str()
884        && let Some(root) = canon_str.strip_suffix(build_suffix)
885    {
886        return Some(std::path::PathBuf::from(root));
887    }
888
889    let parent = canon.parent()?;
890    // is_file (not exists) matches cache::prefer_source_tree_for_dwarf's
891    // sibling probe, so a `vmlinux` directory or symlink-to-directory
892    // cannot satisfy either check.
893    if parent.join("vmlinux").is_file() {
894        return Some(parent.to_path_buf());
895    }
896
897    None
898}
899
900/// Find a bootable kernel image within a directory.
901///
902/// Checks the arch-specific build tree path first (`arch/x86/boot/bzImage`
903/// or `arch/arm64/boot/Image`), then falls back to the directory root
904/// (for cache entries that store the boot image directly).
905#[allow(dead_code)]
906pub fn find_image_in_dir(dir: &std::path::Path) -> Option<std::path::PathBuf> {
907    // Build tree layout: arch-specific subdirectory.
908    #[cfg(target_arch = "x86_64")]
909    {
910        let p = dir.join("arch/x86/boot/bzImage");
911        if p.exists() {
912            return Some(p);
913        }
914    }
915    #[cfg(target_arch = "aarch64")]
916    {
917        let p = dir.join("arch/arm64/boot/Image");
918        if p.exists() {
919            return Some(p);
920        }
921    }
922    // Cache entry layout: boot image at directory root.
923    #[cfg(target_arch = "x86_64")]
924    {
925        let p = dir.join("bzImage");
926        if p.exists() {
927            return Some(p);
928        }
929    }
930    #[cfg(target_arch = "aarch64")]
931    {
932        let p = dir.join("Image");
933        if p.exists() {
934            return Some(p);
935        }
936    }
937    None
938}
939
940/// Find a bootable kernel image on the host.
941///
942/// `kernel_dir`: explicit kernel directory (e.g. from `KTSTR_KERNEL`).
943/// When set, only that directory is searched — no fallback to local
944/// build trees or host paths.
945///
946/// `release`: kernel release string (e.g. from `uname -r`). When
947/// `None`, falls back to reading `/proc/sys/kernel/osrelease` — the
948/// same value the kernel exposes via the `uname(2)` syscall, without
949/// the shell-out cost.
950///
951/// Without `kernel_dir`, searches local build trees (`./linux`,
952/// `../linux`), `/lib/modules/{release}/build`, then host paths
953/// (`/lib/modules/{release}/vmlinuz`, `/boot/vmlinuz-{release}`,
954/// `/boot/vmlinuz`).
955#[allow(dead_code)]
956pub fn find_image(kernel_dir: Option<&str>, release: Option<&str>) -> Option<std::path::PathBuf> {
957    // When kernel_dir is explicit, only check that directory.
958    if let Some(dir_str) = kernel_dir {
959        let dir = std::path::PathBuf::from(dir_str);
960        if !dir.is_dir() {
961            return None;
962        }
963        return find_image_in_dir(&dir);
964    }
965
966    // No explicit dir: search local build trees via resolve_kernel.
967    if let Some(dir) = resolve_kernel(None)
968        && let Some(img) = find_image_in_dir(&dir)
969    {
970        return Some(img);
971    }
972
973    // Host fallback paths. When `release` is not supplied, pull the
974    // running kernel release from procfs via
975    // [`kernel_release_from_procfs`].
976    let owned_release;
977    let rel = match release {
978        Some(r) => Some(r),
979        None => {
980            owned_release = kernel_release_from_procfs();
981            owned_release.as_deref()
982        }
983    };
984
985    if let Some(rel) = rel {
986        let p = std::path::PathBuf::from(format!("/lib/modules/{rel}/vmlinuz"));
987        if std::fs::File::open(&p).is_ok() {
988            return Some(p);
989        }
990        let p = std::path::PathBuf::from(format!("/boot/vmlinuz-{rel}"));
991        if std::fs::File::open(&p).is_ok() {
992            return Some(p);
993        }
994    }
995
996    let p = std::path::PathBuf::from("/boot/vmlinuz");
997    if std::fs::File::open(&p).is_ok() {
998        return Some(p);
999    }
1000
1001    None
1002}
1003
1004/// Resolve the BTF source file for vmlinux.h generation.
1005///
1006/// `kernel_dir`: explicit kernel directory (e.g. from `KTSTR_KERNEL`).
1007///
1008/// Prefers `{resolved_dir}/vmlinux`, then `/sys/kernel/btf/vmlinux`.
1009#[allow(dead_code)]
1010pub fn resolve_btf(kernel_dir: Option<&str>) -> Option<std::path::PathBuf> {
1011    if let Some(dir) = resolve_kernel(kernel_dir) {
1012        let vmlinux = dir.join("vmlinux");
1013        if vmlinux.exists() {
1014            return Some(vmlinux);
1015        }
1016    }
1017    let sysfs = std::path::Path::new("/sys/kernel/btf/vmlinux");
1018    if sysfs.exists() {
1019        return Some(sysfs.to_path_buf());
1020    }
1021    None
1022}
1023
1024/// Check if a directory contains kernel build artifacts.
1025///
1026/// Checks both build tree layout (arch subdirectories) and cache
1027/// entry layout (boot image at directory root).
1028fn has_kernel_artifacts(dir: &std::path::Path) -> bool {
1029    if dir.join("vmlinux").exists() {
1030        return true;
1031    }
1032    #[cfg(target_arch = "x86_64")]
1033    if dir.join("arch/x86/boot/bzImage").exists() || dir.join("bzImage").exists() {
1034        return true;
1035    }
1036    #[cfg(target_arch = "aarch64")]
1037    if dir.join("arch/arm64/boot/Image").exists() || dir.join("Image").exists() {
1038        return true;
1039    }
1040    false
1041}
1042#[cfg(test)]
1043mod tests {
1044    use super::*;
1045    use std::path::PathBuf;
1046    use tempfile::TempDir;
1047
1048    // -- resolve_kernel --
1049
1050    #[test]
1051    fn kernel_path_resolve_explicit_dir_exists() {
1052        let tmp = TempDir::new().unwrap();
1053        let result = resolve_kernel(Some(tmp.path().to_str().unwrap()));
1054        assert_eq!(result, Some(tmp.path().to_path_buf()));
1055    }
1056
1057    #[test]
1058    fn kernel_path_resolve_explicit_dir_not_exists() {
1059        let result = resolve_kernel(Some("/nonexistent/kernel/dir/that/does/not/exist"));
1060        // The explicit dir doesn't exist, so resolve_kernel skips it.
1061        // It may still find a kernel via fallback paths (./linux, ../linux,
1062        // /lib/modules). The key invariant: the nonexistent path must never
1063        // be returned.
1064        assert_ne!(
1065            result,
1066            Some(PathBuf::from("/nonexistent/kernel/dir/that/does/not/exist"))
1067        );
1068    }
1069
1070    #[test]
1071    fn kernel_path_resolve_none_falls_through() {
1072        // With None, resolve_kernel skips the explicit branch and tries
1073        // ./linux, ../linux, then /lib/modules. The result depends on
1074        // the host, but the function must not panic.
1075        let _ = resolve_kernel(None);
1076    }
1077
1078    #[test]
1079    fn kernel_path_resolve_none_returns_osrelease_build_dir_when_present() {
1080        // resolve_kernel(None) reads `/proc/sys/kernel/osrelease` and
1081        // checks `/lib/modules/{rel}/build` as its last fallback. The
1082        // earlier branches (`./linux`, `../linux`) cannot be controlled
1083        // from a parallel-safe unit test (`set_current_dir` is process-
1084        // wide), so this test is strong only when those local trees are
1085        // absent. When `/lib/modules/{rel}/build` is absent on the host
1086        // (typical CI without installed kernel headers), skip via early
1087        // return — the panic-free contract is already covered by
1088        // `kernel_path_resolve_none_falls_through`.
1089        let release = std::fs::read_to_string("/proc/sys/kernel/osrelease")
1090            .expect("host /proc/sys/kernel/osrelease must be readable for this test")
1091            .trim()
1092            .to_string();
1093        let expected = std::path::PathBuf::from(format!("/lib/modules/{release}/build"));
1094        if !expected.is_dir() {
1095            return;
1096        }
1097
1098        let resolved = resolve_kernel(None).unwrap_or_else(|| {
1099            panic!(
1100                "resolve_kernel(None) must return Some when {} exists",
1101                expected.display(),
1102            )
1103        });
1104        assert!(
1105            resolved.is_dir(),
1106            "resolved path must be a directory, got {}",
1107            resolved.display(),
1108        );
1109        // Strong pin only when no earlier branch (`./linux`, `../linux`)
1110        // shadowed the osrelease path. When an earlier branch matched,
1111        // the panic-free + valid-dir contract above is what we get.
1112        let local_shadowed = std::path::PathBuf::from("./linux").is_dir()
1113            || std::path::PathBuf::from("../linux").is_dir();
1114        if !local_shadowed {
1115            assert_eq!(
1116                resolved, expected,
1117                "with no local trees, resolve_kernel(None) must return the osrelease build dir",
1118            );
1119        }
1120    }
1121
1122    #[test]
1123    fn kernel_path_resolve_empty_string() {
1124        // Empty string creates a PathBuf("") which is_dir() returns false,
1125        // so it falls through to search paths.
1126        let result = resolve_kernel(Some(""));
1127        // "" is not a directory, so it must not be returned as the explicit path.
1128        assert_ne!(result, Some(PathBuf::from("")));
1129    }
1130
1131    // -- has_kernel_artifacts --
1132
1133    #[test]
1134    fn kernel_path_has_artifacts_vmlinux() {
1135        let tmp = TempDir::new().unwrap();
1136        std::fs::write(tmp.path().join("vmlinux"), b"fake").unwrap();
1137        assert!(has_kernel_artifacts(tmp.path()));
1138    }
1139
1140    #[cfg(target_arch = "x86_64")]
1141    #[test]
1142    fn kernel_path_has_artifacts_bzimage() {
1143        let tmp = TempDir::new().unwrap();
1144        let boot = tmp.path().join("arch/x86/boot");
1145        std::fs::create_dir_all(&boot).unwrap();
1146        std::fs::write(boot.join("bzImage"), b"fake").unwrap();
1147        assert!(has_kernel_artifacts(tmp.path()));
1148    }
1149
1150    #[cfg(target_arch = "aarch64")]
1151    #[test]
1152    fn kernel_path_has_artifacts_image() {
1153        // aarch64 build tree layout: arch/arm64/boot/Image.
1154        let tmp = TempDir::new().unwrap();
1155        let boot = tmp.path().join("arch/arm64/boot");
1156        std::fs::create_dir_all(&boot).unwrap();
1157        std::fs::write(boot.join("Image"), b"fake").unwrap();
1158        assert!(has_kernel_artifacts(tmp.path()));
1159    }
1160
1161    #[test]
1162    fn kernel_path_has_artifacts_empty_dir() {
1163        let tmp = TempDir::new().unwrap();
1164        assert!(!has_kernel_artifacts(tmp.path()));
1165    }
1166
1167    // -- find_image_in_dir --
1168
1169    #[cfg(target_arch = "x86_64")]
1170    #[test]
1171    fn kernel_path_find_image_in_dir_bzimage() {
1172        let tmp = TempDir::new().unwrap();
1173        let boot = tmp.path().join("arch/x86/boot");
1174        std::fs::create_dir_all(&boot).unwrap();
1175        std::fs::write(boot.join("bzImage"), b"fake").unwrap();
1176        let result = find_image_in_dir(tmp.path());
1177        assert_eq!(result, Some(boot.join("bzImage")));
1178    }
1179
1180    #[cfg(target_arch = "aarch64")]
1181    #[test]
1182    fn kernel_path_find_image_in_dir_image() {
1183        // aarch64 build tree layout: find_image_in_dir returns
1184        // arch/arm64/boot/Image.
1185        let tmp = TempDir::new().unwrap();
1186        let boot = tmp.path().join("arch/arm64/boot");
1187        std::fs::create_dir_all(&boot).unwrap();
1188        std::fs::write(boot.join("Image"), b"fake").unwrap();
1189        let result = find_image_in_dir(tmp.path());
1190        assert_eq!(result, Some(boot.join("Image")));
1191    }
1192
1193    #[test]
1194    fn kernel_path_find_image_in_dir_empty() {
1195        let tmp = TempDir::new().unwrap();
1196        assert!(find_image_in_dir(tmp.path()).is_none());
1197    }
1198
1199    #[cfg(target_arch = "x86_64")]
1200    #[test]
1201    fn kernel_path_find_image_in_dir_cache_layout() {
1202        // Cache entries store bzImage at directory root (no arch/ subdir).
1203        let tmp = TempDir::new().unwrap();
1204        std::fs::write(tmp.path().join("bzImage"), b"fake").unwrap();
1205        let result = find_image_in_dir(tmp.path());
1206        assert_eq!(result, Some(tmp.path().join("bzImage")));
1207    }
1208
1209    #[cfg(target_arch = "aarch64")]
1210    #[test]
1211    fn kernel_path_find_image_in_dir_cache_layout_image() {
1212        // Cache entries store Image at directory root on aarch64.
1213        let tmp = TempDir::new().unwrap();
1214        std::fs::write(tmp.path().join("Image"), b"fake").unwrap();
1215        let result = find_image_in_dir(tmp.path());
1216        assert_eq!(result, Some(tmp.path().join("Image")));
1217    }
1218
1219    #[cfg(target_arch = "x86_64")]
1220    #[test]
1221    fn kernel_path_find_image_in_dir_prefers_build_tree() {
1222        // When both arch/ and root-level bzImage exist, prefer arch/.
1223        let tmp = TempDir::new().unwrap();
1224        let boot = tmp.path().join("arch/x86/boot");
1225        std::fs::create_dir_all(&boot).unwrap();
1226        std::fs::write(boot.join("bzImage"), b"build-tree").unwrap();
1227        std::fs::write(tmp.path().join("bzImage"), b"root-level").unwrap();
1228        let result = find_image_in_dir(tmp.path());
1229        assert_eq!(result, Some(boot.join("bzImage")));
1230    }
1231
1232    #[cfg(target_arch = "aarch64")]
1233    #[test]
1234    fn kernel_path_find_image_in_dir_prefers_build_tree_image() {
1235        // When both arch/arm64/boot/Image and root-level Image exist,
1236        // prefer the build-tree path. Pins the same precedence on
1237        // aarch64 as the x86_64 sibling — the build-tree branch in
1238        // `find_image_in_dir` runs before the cache-entry branch on
1239        // either arch.
1240        let tmp = TempDir::new().unwrap();
1241        let boot = tmp.path().join("arch/arm64/boot");
1242        std::fs::create_dir_all(&boot).unwrap();
1243        std::fs::write(boot.join("Image"), b"build-tree").unwrap();
1244        std::fs::write(tmp.path().join("Image"), b"root-level").unwrap();
1245        let result = find_image_in_dir(tmp.path());
1246        assert_eq!(result, Some(boot.join("Image")));
1247    }
1248
1249    #[cfg(target_arch = "x86_64")]
1250    #[test]
1251    fn kernel_path_has_artifacts_root_bzimage() {
1252        // Cache entry layout: bzImage at directory root.
1253        let tmp = TempDir::new().unwrap();
1254        std::fs::write(tmp.path().join("bzImage"), b"fake").unwrap();
1255        assert!(has_kernel_artifacts(tmp.path()));
1256    }
1257
1258    #[cfg(target_arch = "aarch64")]
1259    #[test]
1260    fn kernel_path_has_artifacts_root_image() {
1261        // Cache entry layout on aarch64: Image at directory root.
1262        let tmp = TempDir::new().unwrap();
1263        std::fs::write(tmp.path().join("Image"), b"fake").unwrap();
1264        assert!(has_kernel_artifacts(tmp.path()));
1265    }
1266
1267    // -- derive_kernel_dir --
1268
1269    #[cfg(target_arch = "x86_64")]
1270    #[test]
1271    fn derive_kernel_dir_build_tree_x86() {
1272        let tmp = TempDir::new().unwrap();
1273        let boot = tmp.path().join("arch/x86/boot");
1274        std::fs::create_dir_all(&boot).unwrap();
1275        let image = boot.join("bzImage");
1276        std::fs::write(&image, b"fake").unwrap();
1277
1278        let canon_root = std::fs::canonicalize(tmp.path()).unwrap();
1279        assert_eq!(derive_kernel_dir(&image), Some(canon_root));
1280    }
1281
1282    #[cfg(target_arch = "aarch64")]
1283    #[test]
1284    fn derive_kernel_dir_build_tree_aarch64() {
1285        let tmp = TempDir::new().unwrap();
1286        let boot = tmp.path().join("arch/arm64/boot");
1287        std::fs::create_dir_all(&boot).unwrap();
1288        let image = boot.join("Image");
1289        std::fs::write(&image, b"fake").unwrap();
1290
1291        let canon_root = std::fs::canonicalize(tmp.path()).unwrap();
1292        assert_eq!(derive_kernel_dir(&image), Some(canon_root));
1293    }
1294
1295    #[cfg(target_arch = "x86_64")]
1296    #[test]
1297    fn derive_kernel_dir_cache_entry_x86_with_vmlinux() {
1298        let tmp = TempDir::new().unwrap();
1299        let image = tmp.path().join("bzImage");
1300        std::fs::write(&image, b"fake").unwrap();
1301        std::fs::write(tmp.path().join("vmlinux"), b"fake-elf").unwrap();
1302
1303        let canon = std::fs::canonicalize(tmp.path()).unwrap();
1304        assert_eq!(derive_kernel_dir(&image), Some(canon));
1305    }
1306
1307    #[cfg(target_arch = "aarch64")]
1308    #[test]
1309    fn derive_kernel_dir_cache_entry_aarch64_with_vmlinux() {
1310        let tmp = TempDir::new().unwrap();
1311        let image = tmp.path().join("Image");
1312        std::fs::write(&image, b"fake").unwrap();
1313        std::fs::write(tmp.path().join("vmlinux"), b"fake-elf").unwrap();
1314
1315        let canon = std::fs::canonicalize(tmp.path()).unwrap();
1316        assert_eq!(derive_kernel_dir(&image), Some(canon));
1317    }
1318
1319    #[cfg(target_arch = "x86_64")]
1320    #[test]
1321    fn derive_kernel_dir_cache_entry_without_vmlinux() {
1322        // bzImage at root with no vmlinux sibling — neither layout
1323        // applies, return None.
1324        let tmp = TempDir::new().unwrap();
1325        let image = tmp.path().join("bzImage");
1326        std::fs::write(&image, b"fake").unwrap();
1327        assert_eq!(derive_kernel_dir(&image), None);
1328    }
1329
1330    #[cfg(target_arch = "aarch64")]
1331    #[test]
1332    fn derive_kernel_dir_cache_entry_without_vmlinux_aarch64() {
1333        // Image at root with no vmlinux sibling — neither the build-
1334        // tree suffix nor the cache-entry vmlinux probe applies,
1335        // return None. Mirror of the x86_64 sibling so a future
1336        // refactor that loosened the predicate on either arch trips
1337        // a test rather than silently mapping arbitrary
1338        // `Image`-named files to their parent directories.
1339        let tmp = TempDir::new().unwrap();
1340        let image = tmp.path().join("Image");
1341        std::fs::write(&image, b"fake").unwrap();
1342        assert_eq!(derive_kernel_dir(&image), None);
1343    }
1344
1345    #[test]
1346    fn derive_kernel_dir_nonexistent_path() {
1347        // canonicalize fails on a nonexistent path.
1348        let p = std::path::Path::new("/nonexistent/kernel/bzImage");
1349        assert_eq!(derive_kernel_dir(p), None);
1350    }
1351
1352    #[cfg(target_arch = "x86_64")]
1353    #[test]
1354    fn derive_kernel_dir_arbitrary_image_no_vmlinux_sibling() {
1355        // A file named bzImage but in a dir without a vmlinux sibling
1356        // and not under arch/x86/boot — no match.
1357        let tmp = TempDir::new().unwrap();
1358        let sub = tmp.path().join("somewhere/else");
1359        std::fs::create_dir_all(&sub).unwrap();
1360        let image = sub.join("bzImage");
1361        std::fs::write(&image, b"fake").unwrap();
1362        assert_eq!(derive_kernel_dir(&image), None);
1363    }
1364
1365    #[cfg(target_arch = "aarch64")]
1366    #[test]
1367    fn derive_kernel_dir_arbitrary_image_no_vmlinux_sibling_aarch64() {
1368        // A file named Image but neither under arch/arm64/boot nor
1369        // alongside a vmlinux sibling — no match. Mirror of the
1370        // x86_64 sibling.
1371        let tmp = TempDir::new().unwrap();
1372        let sub = tmp.path().join("somewhere/else");
1373        std::fs::create_dir_all(&sub).unwrap();
1374        let image = sub.join("Image");
1375        std::fs::write(&image, b"fake").unwrap();
1376        assert_eq!(derive_kernel_dir(&image), None);
1377    }
1378
1379    // -- resolve_btf --
1380
1381    #[test]
1382    fn kernel_path_resolve_btf_with_vmlinux_in_dir() {
1383        let tmp = TempDir::new().unwrap();
1384        std::fs::write(tmp.path().join("vmlinux"), b"fake").unwrap();
1385        let result = resolve_btf(Some(tmp.path().to_str().unwrap()));
1386        assert_eq!(result, Some(tmp.path().join("vmlinux")));
1387    }
1388
1389    #[test]
1390    fn kernel_path_resolve_btf_dir_without_vmlinux() {
1391        let tmp = TempDir::new().unwrap();
1392        // No vmlinux in dir; falls through to /sys/kernel/btf/vmlinux check.
1393        let result = resolve_btf(Some(tmp.path().to_str().unwrap()));
1394        // Result depends on host: either /sys/kernel/btf/vmlinux exists or None.
1395        if let Some(ref p) = result {
1396            assert!(p.exists());
1397        }
1398    }
1399
1400    #[test]
1401    fn kernel_path_resolve_btf_nonexistent_dir() {
1402        let result = resolve_btf(Some("/nonexistent/btf/dir/xyz"));
1403        // Dir doesn't exist so resolve_kernel returns None; falls to sysfs.
1404        if let Some(ref p) = result {
1405            assert!(p.exists());
1406        }
1407    }
1408
1409    // -- find_image --
1410
1411    #[cfg(target_arch = "x86_64")]
1412    #[test]
1413    fn kernel_path_find_image_explicit_dir_with_bzimage() {
1414        let tmp = TempDir::new().unwrap();
1415        let boot = tmp.path().join("arch/x86/boot");
1416        std::fs::create_dir_all(&boot).unwrap();
1417        std::fs::write(boot.join("bzImage"), b"fake").unwrap();
1418        let result = find_image(Some(tmp.path().to_str().unwrap()), None);
1419        assert_eq!(result, Some(boot.join("bzImage")));
1420    }
1421
1422    #[cfg(target_arch = "aarch64")]
1423    #[test]
1424    fn kernel_path_find_image_explicit_dir_with_image() {
1425        // `find_image(Some(dir), _)` must short-circuit to the
1426        // directory-local search and return the build-tree
1427        // arch/arm64/boot/Image without falling through to host
1428        // fallback paths. Mirror of the x86_64 sibling.
1429        let tmp = TempDir::new().unwrap();
1430        let boot = tmp.path().join("arch/arm64/boot");
1431        std::fs::create_dir_all(&boot).unwrap();
1432        std::fs::write(boot.join("Image"), b"fake").unwrap();
1433        let result = find_image(Some(tmp.path().to_str().unwrap()), None);
1434        assert_eq!(result, Some(boot.join("Image")));
1435    }
1436
1437    #[test]
1438    fn kernel_path_find_image_nonexistent_dir() {
1439        // Nonexistent explicit dir: `!dir.is_dir()` in the explicit-dir
1440        // branch hits `return None` (find_image ~line 592) with no
1441        // fallthrough to resolve_kernel / host fallback paths. The
1442        // return value None — not merely "did not panic" — is the
1443        // documented short-circuit contract, so pin it. A regression
1444        // that fell through to local/host search instead of
1445        // short-circuiting would be caught here.
1446        assert_eq!(
1447            find_image(Some("/nonexistent/image/dir/xyz"), None),
1448            None,
1449            "nonexistent explicit dir must short-circuit to None with no fallthrough",
1450        );
1451    }
1452
1453    #[test]
1454    fn kernel_path_find_image_release_none_matches_osrelease() {
1455        // The `/proc/sys/kernel/osrelease` path is hardcoded in
1456        // find_image and cannot be mocked, so the fallback can only
1457        // be verified by equivalence: read osrelease the way the
1458        // function does, then assert that find_image(None, None)
1459        // equals find_image(None, Some(<that value>)). Identical
1460        // post-`rel` logic in both calls means equal outputs prove
1461        // the None branch derived `rel` from osrelease (or both
1462        // short-circuited via resolve_kernel(None), which is also
1463        // a contract — no panic, no divergence).
1464        let host_release = std::fs::read_to_string("/proc/sys/kernel/osrelease")
1465            .expect("host /proc/sys/kernel/osrelease must be readable for this test")
1466            .trim()
1467            .to_string();
1468        assert!(
1469            !host_release.is_empty(),
1470            "/proc/sys/kernel/osrelease must be non-empty for this test",
1471        );
1472
1473        let derived = find_image(None, None);
1474        let explicit = find_image(None, Some(&host_release));
1475        assert_eq!(
1476            derived, explicit,
1477            "find_image(None, None) must equal find_image(None, Some(osrelease)); fallback diverged",
1478        );
1479    }
1480
1481    // -- KernelId parsing --
1482
1483    #[test]
1484    fn kernel_id_parse_path_with_slash() {
1485        assert_eq!(
1486            KernelId::parse("../linux"),
1487            KernelId::Path(PathBuf::from("../linux"))
1488        );
1489        assert_eq!(
1490            KernelId::parse("/boot/vmlinuz"),
1491            KernelId::Path(PathBuf::from("/boot/vmlinuz"))
1492        );
1493    }
1494
1495    #[test]
1496    fn kernel_id_parse_path_dot_prefix() {
1497        assert_eq!(
1498            KernelId::parse("./linux"),
1499            KernelId::Path(PathBuf::from("./linux"))
1500        );
1501        assert_eq!(KernelId::parse("."), KernelId::Path(PathBuf::from(".")));
1502    }
1503
1504    /// `~`-prefixed paths are expanded against `$HOME` at parse
1505    /// time so a downstream `is_dir()` sees the resolved path
1506    /// rather than the literal `~/...` (which the libc / Rust
1507    /// path APIs do not interpret — only shells do). Pins the
1508    /// expansion against an explicit `HOME` value so the test is
1509    /// independent of the running operator's environment.
1510    ///
1511    /// Uses the env-mutation `lock_env` helper to serialise the
1512    /// `HOME` write against any sibling test that reads
1513    /// `$HOME` — see `crate::test_support::test_helpers::lock_env`
1514    /// for the locking rationale. `EnvVarGuard::set` restores the
1515    /// prior value when the guard drops so the test does not leak
1516    /// the override into peers.
1517    #[test]
1518    fn kernel_id_parse_path_tilde_prefix_expands() {
1519        let _lock = crate::test_support::test_helpers::lock_env();
1520        let _home_guard =
1521            crate::test_support::test_helpers::EnvVarGuard::set("HOME", "/home/fixture-user");
1522        assert_eq!(
1523            KernelId::parse("~/linux"),
1524            KernelId::Path(PathBuf::from("/home/fixture-user/linux")),
1525        );
1526    }
1527
1528    /// Bare `~` (no slash) expands to `$HOME` exactly. Pins the
1529    /// degenerate single-character case so a future regression
1530    /// that special-cased "must contain `/` after `~`" lands
1531    /// here instead of silently leaving the literal `~`.
1532    #[test]
1533    fn kernel_id_parse_path_bare_tilde_expands() {
1534        let _lock = crate::test_support::test_helpers::lock_env();
1535        let _home_guard =
1536            crate::test_support::test_helpers::EnvVarGuard::set("HOME", "/home/fixture-user");
1537        assert_eq!(
1538            KernelId::parse("~"),
1539            KernelId::Path(PathBuf::from("/home/fixture-user")),
1540        );
1541    }
1542
1543    /// `$HOME` unset → no expansion possible. The literal `~/...`
1544    /// passes through verbatim. Downstream `is_dir()` will reject
1545    /// it normally, surfacing the missing-directory error rather
1546    /// than panicking inside the parser.
1547    #[test]
1548    fn kernel_id_parse_path_tilde_with_home_unset_passes_through() {
1549        let _lock = crate::test_support::test_helpers::lock_env();
1550        let _home_guard = crate::test_support::test_helpers::EnvVarGuard::remove("HOME");
1551        assert_eq!(
1552            KernelId::parse("~/linux"),
1553            KernelId::Path(PathBuf::from("~/linux")),
1554        );
1555    }
1556
1557    /// `~user/...` (different user) is NOT expanded because std
1558    /// has no `getpwnam`. Operator who wants a peer's home dir
1559    /// can spell it absolutely. Pin the no-op behavior so a
1560    /// future "shell out to getpwnam" addition has to update
1561    /// this test deliberately.
1562    #[test]
1563    fn kernel_id_parse_path_tilde_user_passes_through() {
1564        let _lock = crate::test_support::test_helpers::lock_env();
1565        let _home_guard =
1566            crate::test_support::test_helpers::EnvVarGuard::set("HOME", "/home/fixture-user");
1567        assert_eq!(
1568            KernelId::parse("~peer/linux"),
1569            KernelId::Path(PathBuf::from("~peer/linux")),
1570        );
1571    }
1572
1573    #[test]
1574    fn kernel_id_parse_version_stable() {
1575        assert_eq!(
1576            KernelId::parse("6.14.2"),
1577            KernelId::Version("6.14.2".to_string())
1578        );
1579        assert_eq!(
1580            KernelId::parse("6.14"),
1581            KernelId::Version("6.14".to_string())
1582        );
1583    }
1584
1585    #[test]
1586    fn kernel_id_parse_version_rc() {
1587        assert_eq!(
1588            KernelId::parse("6.15-rc3"),
1589            KernelId::Version("6.15-rc3".to_string())
1590        );
1591    }
1592
1593    #[test]
1594    fn kernel_id_parse_version_patch_rc() {
1595        assert_eq!(
1596            KernelId::parse("6.14.2-rc1"),
1597            KernelId::Version("6.14.2-rc1".to_string())
1598        );
1599    }
1600
1601    #[test]
1602    fn kernel_id_parse_cache_key() {
1603        assert_eq!(
1604            KernelId::parse("6.14.2-tarball-x86_64"),
1605            KernelId::CacheKey("6.14.2-tarball-x86_64".to_string())
1606        );
1607        assert_eq!(
1608            KernelId::parse("local-deadbeef-x86_64"),
1609            KernelId::CacheKey("local-deadbeef-x86_64".to_string())
1610        );
1611    }
1612
1613    #[test]
1614    fn kernel_id_parse_v_prefix_not_version() {
1615        // "v6.14" starts with 'v', not a digit -- cache key.
1616        assert_eq!(
1617            KernelId::parse("v6.14"),
1618            KernelId::CacheKey("v6.14".to_string())
1619        );
1620    }
1621
1622    #[test]
1623    fn kernel_id_parse_bare_major_is_version() {
1624        // "6" is a bare-major version prefix (resolves to the highest
1625        // 6.x.y patch via fetch_version_for_prefix), NOT a cache key.
1626        assert_eq!(KernelId::parse("6"), KernelId::Version("6".to_string()));
1627    }
1628
1629    #[test]
1630    fn kernel_id_display() {
1631        assert_eq!(
1632            KernelId::Version("6.14.2".to_string()).to_string(),
1633            "6.14.2"
1634        );
1635        assert_eq!(
1636            KernelId::Path(PathBuf::from("../linux")).to_string(),
1637            "../linux"
1638        );
1639        assert_eq!(
1640            KernelId::CacheKey("my-key".to_string()).to_string(),
1641            "my-key"
1642        );
1643        assert_eq!(
1644            KernelId::Range {
1645                start: "6.10".to_string(),
1646                end: "6.13".to_string(),
1647                syntax_inclusive: false,
1648            }
1649            .to_string(),
1650            "6.10..6.13",
1651        );
1652        assert_eq!(
1653            KernelId::Range {
1654                start: "6.10".to_string(),
1655                end: "6.13".to_string(),
1656                syntax_inclusive: true,
1657            }
1658            .to_string(),
1659            "6.10..=6.13",
1660        );
1661        assert_eq!(
1662            KernelId::Git {
1663                url: "https://example.com/r.git".to_string(),
1664                git_ref: "for-next".to_string(),
1665                ref_kind: GitRefKind::Branch,
1666            }
1667            .to_string(),
1668            "git+https://example.com/r.git#branch=for-next",
1669        );
1670        assert_eq!(
1671            KernelId::Git {
1672                url: "https://example.com/r.git".to_string(),
1673                git_ref: "v6.14".to_string(),
1674                ref_kind: GitRefKind::Tag,
1675            }
1676            .to_string(),
1677            "git+https://example.com/r.git#tag=v6.14",
1678        );
1679        assert_eq!(
1680            KernelId::Git {
1681                url: "https://example.com/r.git".to_string(),
1682                git_ref: "abc123".to_string(),
1683                ref_kind: GitRefKind::Sha,
1684            }
1685            .to_string(),
1686            "git+https://example.com/r.git#sha=abc123",
1687        );
1688        // Unknown (a bare `#REF`) round-trips verbatim so
1689        // parse(Display(x)) == x still holds for the reject case.
1690        assert_eq!(
1691            KernelId::Git {
1692                url: "https://example.com/r.git".to_string(),
1693                git_ref: "main".to_string(),
1694                ref_kind: GitRefKind::Unknown,
1695            }
1696            .to_string(),
1697            "git+https://example.com/r.git#main",
1698        );
1699    }
1700
1701    // -- KernelId::parse — Range arm --
1702
1703    #[test]
1704    fn kernel_id_parse_range_versions() {
1705        assert_eq!(
1706            KernelId::parse("6.10..6.15"),
1707            KernelId::Range {
1708                start: "6.10".to_string(),
1709                end: "6.15".to_string(),
1710                syntax_inclusive: false,
1711            },
1712        );
1713    }
1714
1715    /// `..=` (inclusive Rust syntax) and `..` both produce a Range
1716    /// with the SAME endpoints (and the same closed-range resolution
1717    /// semantics — both endpoints inclusive); they differ only in
1718    /// the `syntax_inclusive` flag, which round-trips through
1719    /// [`std::fmt::Display`] and the inverted-range error message
1720    /// so the operator-typed form is preserved verbatim. The `..=`
1721    /// arm is checked first in `parse`, so even though `..=` contains
1722    /// `..` as a substring the version-shaped split lands on `6.10`
1723    /// / `6.15`, not on `6.10` / `=6.15`.
1724    #[test]
1725    fn kernel_id_parse_range_inclusive_eq_syntax() {
1726        assert_eq!(
1727            KernelId::parse("6.10..=6.15"),
1728            KernelId::Range {
1729                start: "6.10".to_string(),
1730                end: "6.15".to_string(),
1731                syntax_inclusive: true,
1732            },
1733        );
1734    }
1735
1736    #[test]
1737    fn kernel_id_parse_range_patch_versions() {
1738        assert_eq!(
1739            KernelId::parse("6.10.5..6.10.10"),
1740            KernelId::Range {
1741                start: "6.10.5".to_string(),
1742                end: "6.10.10".to_string(),
1743                syntax_inclusive: false,
1744            },
1745        );
1746    }
1747
1748    #[test]
1749    fn kernel_id_parse_range_rc() {
1750        assert_eq!(
1751            KernelId::parse("6.10..6.10-rc3"),
1752            KernelId::Range {
1753                start: "6.10".to_string(),
1754                end: "6.10-rc3".to_string(),
1755                syntax_inclusive: false,
1756            },
1757        );
1758    }
1759
1760    /// Both endpoints non-version: not a Range. The `/`-contains
1761    /// test fails too, so this falls to the version-shaped check
1762    /// (also fails on the `..`) and lands as CacheKey.
1763    #[test]
1764    fn kernel_id_parse_range_non_version_falls_through() {
1765        assert_eq!(
1766            KernelId::parse("foo..bar"),
1767            KernelId::CacheKey("foo..bar".to_string()),
1768        );
1769    }
1770
1771    /// One endpoint version-shaped, the other not: the Range arm
1772    /// requires BOTH endpoints to pass `_is_version_string`, so
1773    /// `6.10..foo` falls through to CacheKey.
1774    #[test]
1775    fn kernel_id_parse_range_one_non_version() {
1776        assert_eq!(
1777            KernelId::parse("6.10..foo"),
1778            KernelId::CacheKey("6.10..foo".to_string()),
1779        );
1780    }
1781
1782    /// Trailing `..` with no second endpoint: `_is_version_string("")`
1783    /// is false, so the Range arm doesn't fire. Falls to CacheKey
1784    /// (the version-shaped check also fails because the trailing `..`
1785    /// means a parts-iter sees an empty patch component).
1786    #[test]
1787    fn kernel_id_parse_range_empty_endpoint() {
1788        assert_eq!(
1789            KernelId::parse("6.10.."),
1790            KernelId::CacheKey("6.10..".to_string()),
1791        );
1792    }
1793
1794    // -- KernelId::parse — Git arm (explicit #tag= / #branch= / #sha=) --
1795
1796    #[test]
1797    fn kernel_id_parse_git_branch() {
1798        assert_eq!(
1799            KernelId::parse("git+https://example.com/r.git#branch=main"),
1800            KernelId::Git {
1801                url: "https://example.com/r.git".to_string(),
1802                git_ref: "main".to_string(),
1803                ref_kind: GitRefKind::Branch,
1804            },
1805        );
1806    }
1807
1808    #[test]
1809    fn kernel_id_parse_git_tag() {
1810        assert_eq!(
1811            KernelId::parse("git+https://example.com/r.git#tag=v6.14"),
1812            KernelId::Git {
1813                url: "https://example.com/r.git".to_string(),
1814                git_ref: "v6.14".to_string(),
1815                ref_kind: GitRefKind::Tag,
1816            },
1817        );
1818    }
1819
1820    #[test]
1821    fn kernel_id_parse_git_sha() {
1822        let sha = "0123456789abcdef0123456789abcdef01234567";
1823        assert_eq!(
1824            KernelId::parse(&format!("git+https://example.com/r.git#sha={sha}")),
1825            KernelId::Git {
1826                url: "https://example.com/r.git".to_string(),
1827                git_ref: sha.to_string(),
1828                ref_kind: GitRefKind::Sha,
1829            },
1830        );
1831    }
1832
1833    /// A bare `#REF` (no `kind=`) parses to `GitRefKind::Unknown` so
1834    /// `validate` — not `parse` — surfaces the actionable error; `parse`
1835    /// returns `Self`, never `Result`. An unrecognized `#foo=` selector
1836    /// lands the same way (the whole fragment is kept as the ref).
1837    #[test]
1838    fn kernel_id_parse_git_bare_ref_is_unknown() {
1839        assert_eq!(
1840            KernelId::parse("git+https://example.com/r.git#main"),
1841            KernelId::Git {
1842                url: "https://example.com/r.git".to_string(),
1843                git_ref: "main".to_string(),
1844                ref_kind: GitRefKind::Unknown,
1845            },
1846        );
1847        assert_eq!(
1848            KernelId::parse("git+https://example.com/r.git#foo=bar"),
1849            KernelId::Git {
1850                url: "https://example.com/r.git".to_string(),
1851                git_ref: "foo=bar".to_string(),
1852                ref_kind: GitRefKind::Unknown,
1853            },
1854        );
1855    }
1856
1857    /// The Git arm splits the URL/fragment on the LAST `#` (so a `#`
1858    /// inside the URL survives), then the fragment on the FIRST `=`
1859    /// into kind/value — `git+https://x#frag#branch=main` parses as
1860    /// url=`https://x#frag`, branch=`main`. A regression to
1861    /// `split_once('#')` would flip the URL/ref.
1862    #[test]
1863    fn kernel_id_parse_git_multi_hash_url() {
1864        assert_eq!(
1865            KernelId::parse("git+https://x#frag#branch=main"),
1866            KernelId::Git {
1867                url: "https://x#frag".to_string(),
1868                git_ref: "main".to_string(),
1869                ref_kind: GitRefKind::Branch,
1870            },
1871        );
1872    }
1873
1874    /// Empty fragment after the `#` (`git+URL#`): the Git arm now
1875    /// claims ANY `git+…` string, so this parses to a Git with an empty
1876    /// `git_ref` and `GitRefKind::Unknown` rather than falling through
1877    /// to Path. That routes the typo into `validate`, which surfaces the
1878    /// actionable "ref kind must be explicit" error instead of a
1879    /// confusing filesystem "path not found".
1880    #[test]
1881    fn kernel_id_parse_git_empty_ref_is_git_unknown() {
1882        let id = KernelId::parse("git+https://example.com/r.git#");
1883        assert_eq!(
1884            id,
1885            KernelId::Git {
1886                url: "https://example.com/r.git".to_string(),
1887                git_ref: String::new(),
1888                ref_kind: GitRefKind::Unknown,
1889            },
1890        );
1891        assert!(
1892            id.validate().is_err(),
1893            "an empty/kind-less git fragment must be rejected by validate",
1894        );
1895    }
1896
1897    /// Empty URL before the `#`: the Git arm claims it (git+ takes
1898    /// precedence), producing a Git with an empty `url`. A valid `#tag=`
1899    /// selector isolates the empty-URL `validate` check (a kind-less
1900    /// fragment would also trip the Unknown check), pinning that the
1901    /// empty URL — not a silent CacheKey miss — is what gets rejected.
1902    #[test]
1903    fn kernel_id_parse_git_empty_url_is_rejected() {
1904        let id = KernelId::parse("git+#tag=x");
1905        assert_eq!(
1906            id,
1907            KernelId::Git {
1908                url: String::new(),
1909                git_ref: "x".to_string(),
1910                ref_kind: GitRefKind::Tag,
1911            },
1912        );
1913        let err = id
1914            .validate()
1915            .expect_err("an empty git URL must be rejected by validate");
1916        assert!(
1917            err.contains("empty URL"),
1918            "empty-URL git spec must surface the empty-URL diagnostic, got: {err}",
1919        );
1920    }
1921
1922    /// `git+` prefix takes precedence over the `/`-contains Path
1923    /// test. A user pointing at a local clone via `git+/local/repo#v1`
1924    /// should get a Git, not a Path. This pins the parse-arm
1925    /// ordering — flipping the Path check above the Git check would
1926    /// land here as KernelId::Path("git+/local/repo#v1").
1927    #[test]
1928    fn kernel_id_parse_git_beats_path() {
1929        assert_eq!(
1930            KernelId::parse("git+/local/repo#tag=v1"),
1931            KernelId::Git {
1932                url: "/local/repo".to_string(),
1933                git_ref: "v1".to_string(),
1934                ref_kind: GitRefKind::Tag,
1935            },
1936        );
1937    }
1938
1939    // -- KernelId::parse — Package arm (`.rpm` / `.deb` / `.pkg.tar.zst`) --
1940
1941    /// A bare package filename (no separators) classifies as Package,
1942    /// NOT a CacheKey — the suffix check runs before the version and
1943    /// cache-key fallbacks.
1944    #[test]
1945    fn kernel_id_parse_package_bare_filename() {
1946        assert_eq!(
1947            KernelId::parse("linux-6.14.rpm"),
1948            KernelId::Package {
1949                path: PathBuf::from("linux-6.14.rpm"),
1950            },
1951        );
1952        assert_eq!(
1953            KernelId::parse("linux-image.deb"),
1954            KernelId::Package {
1955                path: PathBuf::from("linux-image.deb"),
1956            },
1957        );
1958        assert_eq!(
1959            KernelId::parse("linux-neptune-618-x86_64.pkg.tar.zst"),
1960            KernelId::Package {
1961                path: PathBuf::from("linux-neptune-618-x86_64.pkg.tar.zst"),
1962            },
1963        );
1964    }
1965
1966    /// `./foo.rpm` and `/abs/foo.deb` classify as Package, NOT Path —
1967    /// the `.rpm` / `.deb` suffix check runs ahead of the
1968    /// `/`-contains / `.`-prefix path test.
1969    #[test]
1970    fn kernel_id_parse_package_beats_path() {
1971        assert_eq!(
1972            KernelId::parse("./foo.rpm"),
1973            KernelId::Package {
1974                path: PathBuf::from("./foo.rpm"),
1975            },
1976        );
1977        assert_eq!(
1978            KernelId::parse("/abs/dir/foo.deb"),
1979            KernelId::Package {
1980                path: PathBuf::from("/abs/dir/foo.deb"),
1981            },
1982        );
1983        assert_eq!(
1984            KernelId::parse("./local.pkg.tar.zst"),
1985            KernelId::Package {
1986                path: PathBuf::from("./local.pkg.tar.zst"),
1987            },
1988        );
1989    }
1990
1991    /// A bare extension with no stem is a HIDDEN-FILE name, not a
1992    /// package spec: `.deb` / `.rpm` / `.pkg.tar.zst` classify as
1993    /// Path via the dot-prefix arm, and a path whose last component
1994    /// is such a name classifies as Path via the `/` arm. Regression:
1995    /// the suffix check used to run without a stem requirement, so
1996    /// proptest's `\.[a-z]{1,10}` generator (which pins dot-prefix →
1997    /// Path) failed the moment it drew `.deb`.
1998    #[test]
1999    fn kernel_id_parse_bare_extension_is_path_not_package() {
2000        assert_eq!(
2001            KernelId::parse(".deb"),
2002            KernelId::Path(PathBuf::from(".deb"))
2003        );
2004        assert_eq!(
2005            KernelId::parse(".rpm"),
2006            KernelId::Path(PathBuf::from(".rpm"))
2007        );
2008        assert_eq!(
2009            KernelId::parse(".pkg.tar.zst"),
2010            KernelId::Path(PathBuf::from(".pkg.tar.zst")),
2011        );
2012        assert_eq!(
2013            KernelId::parse("/abs/dir/.deb"),
2014            KernelId::Path(PathBuf::from("/abs/dir/.deb")),
2015        );
2016    }
2017
2018    /// The suffix is case-sensitive lowercase — `.RPM` is not a
2019    /// package; `FOO.RPM` (no separators) falls through to CacheKey.
2020    #[test]
2021    fn kernel_id_parse_package_case_sensitive() {
2022        assert_eq!(
2023            KernelId::parse("FOO.RPM"),
2024            KernelId::CacheKey("FOO.RPM".to_string()),
2025        );
2026    }
2027
2028    /// `git+…` takes precedence over the package suffix — a git URL
2029    /// that happens to end in `.rpm` is still a Git source.
2030    #[test]
2031    fn kernel_id_parse_git_beats_package() {
2032        assert!(matches!(
2033            KernelId::parse("git+https://example.com/r.git#tag=v1.rpm"),
2034            KernelId::Git { .. },
2035        ));
2036    }
2037
2038    /// A `~`-prefixed package path is expanded against `$HOME` at parse
2039    /// time, exactly like the Path arm.
2040    #[test]
2041    fn kernel_id_parse_package_tilde_expands() {
2042        let _lock = crate::test_support::test_helpers::lock_env();
2043        let _home_guard =
2044            crate::test_support::test_helpers::EnvVarGuard::set("HOME", "/home/fixture-user");
2045        assert_eq!(
2046            KernelId::parse("~/pkgs/foo.rpm"),
2047            KernelId::Package {
2048                path: PathBuf::from("/home/fixture-user/pkgs/foo.rpm"),
2049            },
2050        );
2051    }
2052
2053    /// Package always validates — resolve-time legality is the
2054    /// integration step's concern, not the parser's.
2055    #[test]
2056    fn kernel_id_validate_package_ok() {
2057        assert!(
2058            KernelId::parse("linux.rpm").validate().is_ok(),
2059            "package spec must validate",
2060        );
2061    }
2062
2063    // -- KernelId::parse — Distro arm --
2064
2065    #[test]
2066    fn kernel_id_parse_distro_bare_names() {
2067        for (spec, kind) in [
2068            ("fedora", DistroKind::Fedora),
2069            ("ubuntu", DistroKind::Ubuntu),
2070            ("amazonlinux", DistroKind::AmazonLinux),
2071            ("steamos", DistroKind::SteamOs),
2072            ("gke", DistroKind::Gke),
2073        ] {
2074            assert_eq!(
2075                KernelId::parse(spec),
2076                KernelId::Distro {
2077                    kind,
2078                    release: None,
2079                },
2080                "bare distro name {spec:?}",
2081            );
2082        }
2083    }
2084
2085    #[test]
2086    fn kernel_id_parse_distro_explicit_release() {
2087        assert_eq!(
2088            KernelId::parse("fedora-44"),
2089            KernelId::Distro {
2090                kind: DistroKind::Fedora,
2091                release: Some("44".to_string()),
2092            },
2093        );
2094        assert_eq!(
2095            KernelId::parse("ubuntu-24.04"),
2096            KernelId::Distro {
2097                kind: DistroKind::Ubuntu,
2098                release: Some("24.04".to_string()),
2099            },
2100        );
2101        assert_eq!(
2102            KernelId::parse("amazonlinux-2023"),
2103            KernelId::Distro {
2104                kind: DistroKind::AmazonLinux,
2105                release: Some("2023".to_string()),
2106            },
2107        );
2108        assert_eq!(
2109            KernelId::parse("steamos-3.8"),
2110            KernelId::Distro {
2111                kind: DistroKind::SteamOs,
2112                release: Some("3.8".to_string()),
2113            },
2114        );
2115        assert_eq!(
2116            KernelId::parse("gke-129"),
2117            KernelId::Distro {
2118                kind: DistroKind::Gke,
2119                release: Some("129".to_string()),
2120            },
2121        );
2122    }
2123
2124    /// `f44` and `al2023` shorthands map to the same variants their
2125    /// long forms produce.
2126    #[test]
2127    fn kernel_id_parse_distro_shorthand() {
2128        assert_eq!(
2129            KernelId::parse("f44"),
2130            KernelId::Distro {
2131                kind: DistroKind::Fedora,
2132                release: Some("44".to_string()),
2133            },
2134        );
2135        assert_eq!(
2136            KernelId::parse("al2023"),
2137            KernelId::Distro {
2138                kind: DistroKind::AmazonLinux,
2139                release: Some("2023".to_string()),
2140            },
2141        );
2142    }
2143
2144    /// `al<digits>` is Amazon Linux — `al9` parses as Amazon Linux
2145    /// release `9` and is then REJECTED by validate (not a 4-digit
2146    /// year). AlmaLinux is not supported (RHEL-family kernels disable
2147    /// CONFIG_VIRTIO_MMIO, which ktstr's console needs), so its former
2148    /// `alma<digits>` shorthand is now an ordinary cache key: `al`
2149    /// strips to `ma9`, which is not all digits, so the distro arm
2150    /// declines and the token falls through to `CacheKey`.
2151    #[test]
2152    fn kernel_id_parse_distro_shorthand_al_amazon_and_alma_is_cache_key() {
2153        assert_eq!(
2154            KernelId::parse("al9"),
2155            KernelId::Distro {
2156                kind: DistroKind::AmazonLinux,
2157                release: Some("9".to_string()),
2158            },
2159        );
2160        let err = KernelId::parse("al9")
2161            .validate()
2162            .expect_err("al9 must fail amazonlinux release validation");
2163        assert!(
2164            err.contains("amazonlinux") && err.contains("4-digit"),
2165            "al9 rejection must steer to the amazonlinux grammar: {err}",
2166        );
2167        // Former AlmaLinux spellings fall back to CacheKey like any
2168        // unknown token — parse never demotes them to a distro spec.
2169        for spec in ["alma", "alma9", "alma10", "almalinux", "almalinux-10"] {
2170            assert_eq!(
2171                KernelId::parse(spec),
2172                KernelId::CacheKey(spec.to_string()),
2173                "{spec:?} must classify as a cache key, not a distro",
2174            );
2175        }
2176    }
2177
2178    /// A shorthand-shaped prefix whose remainder is not all digits is
2179    /// NOT a distro — `foo` / `alpha` stay CacheKey, and a bare `f`
2180    /// (empty remainder) too.
2181    #[test]
2182    fn kernel_id_parse_distro_shorthand_non_digits_are_cache_keys() {
2183        assert_eq!(
2184            KernelId::parse("foo"),
2185            KernelId::CacheKey("foo".to_string()),
2186        );
2187        assert_eq!(
2188            KernelId::parse("alpha"),
2189            KernelId::CacheKey("alpha".to_string()),
2190        );
2191        assert_eq!(KernelId::parse("f"), KernelId::CacheKey("f".to_string()));
2192    }
2193
2194    /// A real cache-key shape must still classify as CacheKey, not get
2195    /// captured by the distro arm.
2196    #[test]
2197    fn kernel_id_parse_distro_does_not_shadow_cache_keys() {
2198        assert_eq!(
2199            KernelId::parse("6.14-tarball-x86_64-kc12345678"),
2200            KernelId::CacheKey("6.14-tarball-x86_64-kc12345678".to_string()),
2201        );
2202    }
2203
2204    /// A distro name with a malformed release classifies as Distro (so
2205    /// `validate` can reject it) rather than silently becoming a
2206    /// CacheKey — mirrors the git parse/validate split.
2207    #[test]
2208    fn kernel_id_parse_distro_malformed_release_is_distro_not_cache_key() {
2209        assert_eq!(
2210            KernelId::parse("fedora-abc"),
2211            KernelId::Distro {
2212                kind: DistroKind::Fedora,
2213                release: Some("abc".to_string()),
2214            },
2215        );
2216        assert_eq!(
2217            KernelId::parse("ubuntu-24"),
2218            KernelId::Distro {
2219                kind: DistroKind::Ubuntu,
2220                release: Some("24".to_string()),
2221            },
2222        );
2223    }
2224
2225    #[test]
2226    fn kernel_id_validate_distro_accepts_valid_releases() {
2227        for spec in [
2228            "fedora",
2229            "fedora-44",
2230            "f44",
2231            "fedora-100",
2232            "ubuntu",
2233            "ubuntu-24.04",
2234            "amazonlinux",
2235            "amazonlinux-2023",
2236            "al2023",
2237            "steamos",
2238            "steamos-3.7",
2239            "steamos-3.8",
2240            "gke",
2241            "gke-129",
2242        ] {
2243            assert!(
2244                KernelId::parse(spec).validate().is_ok(),
2245                "distro spec {spec:?} must validate",
2246            );
2247        }
2248    }
2249
2250    #[test]
2251    fn kernel_id_validate_distro_rejects_malformed_releases() {
2252        // Fedora: 1 digit too short, 4 digits too long, non-digits.
2253        for spec in ["fedora-4", "f4", "fedora-4444", "fedora-abc"] {
2254            let err = KernelId::parse(spec)
2255                .validate()
2256                .expect_err("fedora spec must be rejected");
2257            assert!(
2258                err.contains("not a valid") && err.contains("fedora"),
2259                "fedora reject for {spec:?} must name the distro: {err}",
2260            );
2261        }
2262        // Ubuntu: bare year, wrong shape.
2263        for spec in ["ubuntu-24", "ubuntu-2404", "ubuntu-24.4"] {
2264            assert!(
2265                KernelId::parse(spec).validate().is_err(),
2266                "ubuntu spec {spec:?} must be rejected",
2267            );
2268        }
2269        // Amazon Linux: not 4 digits.
2270        for spec in ["amazonlinux-23", "al23", "amazonlinux-abcd"] {
2271            assert!(
2272                KernelId::parse(spec).validate().is_err(),
2273                "amazonlinux spec {spec:?} must be rejected",
2274            );
2275        }
2276        // SteamOS: bare major, no dot, non-digits.
2277        for spec in ["steamos-3", "steamos-38", "steamos-3.x", "steamos-3.8.1"] {
2278            let err = KernelId::parse(spec)
2279                .validate()
2280                .expect_err("steamos spec must be rejected");
2281            assert!(
2282                err.contains("steamos") && err.contains("MAJOR.MINOR"),
2283                "steamos reject for {spec:?} must cite the grammar: {err}",
2284            );
2285        }
2286        // GKE: milestone only, 2-3 decimal digits.
2287        for spec in ["gke-1", "gke-129.1", "gke-1234", "gke-latest"] {
2288            let err = KernelId::parse(spec)
2289                .validate()
2290                .expect_err("gke spec must be rejected");
2291            assert!(
2292                err.contains("gke") && err.contains("milestone"),
2293                "gke reject for {spec:?} must cite the grammar: {err}",
2294            );
2295        }
2296    }
2297
2298    /// Distro Display renders the canonical long form; shorthand and
2299    /// long-form inputs round-trip semantically (Display then re-parse
2300    /// yields an equal id).
2301    #[test]
2302    fn kernel_id_distro_display_and_round_trip() {
2303        assert_eq!(
2304            KernelId::Distro {
2305                kind: DistroKind::Fedora,
2306                release: None,
2307            }
2308            .to_string(),
2309            "fedora",
2310        );
2311        assert_eq!(
2312            KernelId::parse("f44").to_string(),
2313            "fedora-44",
2314            "shorthand renders in long form",
2315        );
2316        for spec in [
2317            "fedora",
2318            "fedora-44",
2319            "f44",
2320            "ubuntu-24.04",
2321            "al2023",
2322            "steamos",
2323            "steamos-3.8",
2324            "gke",
2325            "gke-129",
2326        ] {
2327            let id = KernelId::parse(spec);
2328            assert_eq!(
2329                KernelId::parse(&id.to_string()),
2330                id,
2331                "distro spec {spec:?} must round-trip through Display",
2332            );
2333        }
2334    }
2335
2336    // -- KernelId::parse_list --
2337
2338    #[test]
2339    fn kernel_id_parse_list_basic() {
2340        let list = KernelId::parse_list("6.10,6.13");
2341        assert_eq!(
2342            list,
2343            vec![
2344                KernelId::Version("6.10".to_string()),
2345                KernelId::Version("6.13".to_string()),
2346            ],
2347        );
2348    }
2349
2350    #[test]
2351    fn kernel_id_parse_list_mixed() {
2352        let list = KernelId::parse_list("6.10,git+url#branch=main,/srv/linux");
2353        assert_eq!(list.len(), 3, "expected 3 entries, got {list:?}");
2354        assert!(matches!(list[0], KernelId::Version(ref v) if v == "6.10"));
2355        assert!(matches!(
2356            list[1],
2357            KernelId::Git { ref url, ref git_ref, ref_kind: GitRefKind::Branch }
2358                if url == "url" && git_ref == "main"
2359        ));
2360        assert!(matches!(list[2], KernelId::Path(ref p) if p == &PathBuf::from("/srv/linux")));
2361    }
2362
2363    #[test]
2364    fn kernel_id_parse_list_empty() {
2365        assert_eq!(KernelId::parse_list(""), Vec::<KernelId>::new());
2366    }
2367
2368    /// Trailing / leading / repeated commas are forgiving — empty
2369    /// segments are silently dropped so `,6.10,,` yields just one
2370    /// entry. Spec says: defer dedup to the resolver but do not
2371    /// inject empty Cache-key entries from an operator typo.
2372    #[test]
2373    fn kernel_id_parse_list_trailing_comma() {
2374        assert_eq!(
2375            KernelId::parse_list(",6.10,,"),
2376            vec![KernelId::Version("6.10".to_string())],
2377        );
2378    }
2379
2380    /// Whitespace around comma-separated entries gets trimmed before
2381    /// `parse` runs so `"6.10 , 6.13"` produces clean Version variants
2382    /// rather than CacheKey entries with embedded spaces.
2383    #[test]
2384    fn kernel_id_parse_list_whitespace() {
2385        assert_eq!(
2386            KernelId::parse_list("6.10 , 6.13"),
2387            vec![
2388                KernelId::Version("6.10".to_string()),
2389                KernelId::Version("6.13".to_string()),
2390            ],
2391        );
2392    }
2393
2394    /// A single-entry list with no commas falls through `split(',')`
2395    /// as one segment and produces the same Variant `parse` would
2396    /// have produced directly. Pins the parse_list/parse equivalence
2397    /// for the trivial case so a future regression that special-cased
2398    /// "must contain comma" lands here.
2399    #[test]
2400    fn kernel_id_parse_list_single() {
2401        assert_eq!(
2402            KernelId::parse_list("6.10"),
2403            vec![KernelId::Version("6.10".to_string())],
2404        );
2405    }
2406
2407    /// Duplicate entries are PRESERVED at parse time — `parse_list`
2408    /// is a pure splitter, and dedup is the resolver's job (after
2409    /// canonicalization to a cache key, since `6.10` and `v6.10` and
2410    /// a tag pointing at the same sha all collapse). Pin the count
2411    /// AND the index of each occurrence so a future regression that
2412    /// added an early dedup at parse time (which would silently
2413    /// collapse `6.10,6.10` to one entry and lose the operator's
2414    /// "run twice" intent if they later added that semantic) lands
2415    /// here.
2416    #[test]
2417    fn kernel_id_parse_list_preserves_dups() {
2418        let list = KernelId::parse_list("6.10,6.10,6.13");
2419        assert_eq!(list.len(), 3, "expected 3 entries, got {list:?}");
2420        assert_eq!(list[0], KernelId::Version("6.10".to_string()));
2421        assert_eq!(list[1], KernelId::Version("6.10".to_string()));
2422        assert_eq!(list[2], KernelId::Version("6.13".to_string()));
2423    }
2424
2425    // -- KernelId::validate — inverted-range rejection --
2426
2427    /// Forward range `6.10..6.13` validates fine — the most common
2428    /// happy-path case, here as a baseline for the failure tests
2429    /// below.
2430    #[test]
2431    fn kernel_id_validate_range_forward_ok() {
2432        let id = KernelId::parse("6.10..6.13");
2433        assert!(id.validate().is_ok(), "forward range must validate: {id:?}");
2434    }
2435
2436    /// Equal endpoints `6.10..6.10` validate fine — degenerate
2437    /// single-element range, not inverted.
2438    #[test]
2439    fn kernel_id_validate_range_equal_endpoints_ok() {
2440        let id = KernelId::parse("6.10..6.10");
2441        assert!(
2442            id.validate().is_ok(),
2443            "equal endpoints must validate: {id:?}"
2444        );
2445    }
2446
2447    /// `6.16..6.12` — same major, minor decreases. Reject. The error
2448    /// message must name both endpoints AND suggest the swapped
2449    /// spelling so the operator can fix the typo without re-reading
2450    /// the help.
2451    #[test]
2452    fn kernel_id_validate_range_inverted_minor() {
2453        let id = KernelId::parse("6.16..6.12");
2454        let err = id.validate().unwrap_err();
2455        assert!(
2456            err.contains("inverted kernel range"),
2457            "error must say 'inverted kernel range', got: {err}",
2458        );
2459        assert!(
2460            err.contains("6.16..6.12"),
2461            "error must cite the spec, got: {err}"
2462        );
2463        assert!(
2464            err.contains("6.12..6.16"),
2465            "error must suggest the swapped form, got: {err}",
2466        );
2467        // Load-bearing negative: the operator typed `..`, so the error
2468        // must NOT silently substitute `..=`. Pins the
2469        // `syntax_inclusive: false` branch of validate's separator
2470        // selection — a regression that always emitted `..=`
2471        // (regardless of the typed form) would still pass the
2472        // positive substring checks above, but trips this assertion.
2473        assert!(
2474            !err.contains("..="),
2475            "operator typed `..`, error must not silently switch to `..=`: {err}",
2476        );
2477    }
2478
2479    /// Mirror of `kernel_id_validate_range_inverted_minor` for the
2480    /// `..=` typed form. Pins the `syntax_inclusive: true` branch of
2481    /// validate's separator selection — the inverted-range error must
2482    /// preserve the operator's `..=` separator in both the as-typed
2483    /// citation and the swap suggestion, and must NOT silently
2484    /// substitute `..` (load-bearing negative). A regression that
2485    /// flipped the ternary in only one direction (Display correct,
2486    /// validate wrong, or vice versa) trips one of the four
2487    /// assertions.
2488    #[test]
2489    fn kernel_id_validate_range_inverted_minor_inclusive_eq_syntax() {
2490        let id = KernelId::parse("6.16..=6.12");
2491        let err = id.validate().unwrap_err();
2492        assert!(
2493            err.contains("inverted kernel range"),
2494            "error must say 'inverted kernel range', got: {err}",
2495        );
2496        assert!(
2497            err.contains("6.16..=6.12"),
2498            "error must cite the spec verbatim (typed `..=`), got: {err}",
2499        );
2500        assert!(
2501            err.contains("6.12..=6.16"),
2502            "error must suggest the swapped form preserving `..=`, got: {err}",
2503        );
2504        // Load-bearing negative: operator typed `..=`, so the error
2505        // must NOT contain a bare `..` separator between version-shaped
2506        // tokens. The "bare `..` between digits" pattern only appears
2507        // when the separator is wrong; `..=` substrings always have
2508        // the trailing `=`, so checking for any `..` not followed by
2509        // `=` catches the bug. Use a substring check on both renderings
2510        // we expect to be inclusive.
2511        assert!(
2512            !err.contains("6.16..6.12"),
2513            "operator typed `..=`, error must not switch the cited spec to `..`: {err}",
2514        );
2515        assert!(
2516            !err.contains("6.12..6.16"),
2517            "operator typed `..=`, error must not switch the swap suggestion to `..`: {err}",
2518        );
2519    }
2520
2521    /// Direct (non-parse) construction with `syntax_inclusive: true`
2522    /// still produces a `..=`-embedded error. Catches the gap where a
2523    /// caller bypasses [`KernelId::parse`] — e.g. config-file
2524    /// deserialization or a future builder API — and sets the flag
2525    /// directly. Validates that the flag drives the error format
2526    /// regardless of construction path.
2527    #[test]
2528    fn kernel_id_validate_range_inverted_inclusive_direct_construction() {
2529        let id = KernelId::Range {
2530            start: "6.16".to_string(),
2531            end: "6.12".to_string(),
2532            syntax_inclusive: true,
2533        };
2534        let err = id.validate().unwrap_err();
2535        assert!(
2536            err.contains("6.16..=6.12"),
2537            "direct-construction Range with syntax_inclusive=true must emit `..=` cite in error, got: {err}",
2538        );
2539        assert!(
2540            err.contains("6.12..=6.16"),
2541            "direct-construction Range with syntax_inclusive=true must emit `..=` swap in error, got: {err}",
2542        );
2543    }
2544
2545    /// End-to-end round-trip: parse → Display round-trips the typed
2546    /// form verbatim, AND validate's error message embeds the typed
2547    /// form in both the as-typed cite and the swap suggestion.
2548    /// Parameterized over both separator spellings so a regression
2549    /// that broke ONE direction trips here. Integration test for the
2550    /// `syntax_inclusive` contract across parse + Display + validate.
2551    #[test]
2552    fn kernel_id_display_inverted_range_round_trips_syntax_through_validate() {
2553        for (input, sep) in [("6.16..6.12", ".."), ("6.16..=6.12", "..=")] {
2554            let id = KernelId::parse(input);
2555            assert_eq!(
2556                id.to_string(),
2557                input,
2558                "Display must round-trip input verbatim for {input:?}",
2559            );
2560            let err = id.validate().unwrap_err();
2561            let cite = format!("6.16{sep}6.12");
2562            let suggest = format!("6.12{sep}6.16");
2563            assert!(
2564                err.contains(&cite),
2565                "validate error must cite `{cite}` for input {input:?}, got: {err}",
2566            );
2567            assert!(
2568                err.contains(&suggest),
2569                "validate error must suggest swap `{suggest}` for input {input:?}, got: {err}",
2570            );
2571        }
2572    }
2573
2574    /// `7.0..6.99` — major decreases. Reject.
2575    #[test]
2576    fn kernel_id_validate_range_inverted_major() {
2577        let id = KernelId::parse("7.0..6.99");
2578        assert!(id.validate().is_err(), "inverted major must reject: {id:?}");
2579    }
2580
2581    /// `6.10.5..6.10.3` — same major.minor, patch decreases. Reject.
2582    #[test]
2583    fn kernel_id_validate_range_inverted_patch() {
2584        let id = KernelId::parse("6.10.5..6.10.3");
2585        assert!(id.validate().is_err(), "inverted patch must reject: {id:?}");
2586    }
2587
2588    /// `6.10..6.10-rc3` — release > rc per the rc-as-MAX rule, so
2589    /// pre-release on the upper end is inverted. Reject. Catches the
2590    /// common operator mistake of "I want 6.10 latest stable up
2591    /// through the rc series" written in reverse order.
2592    #[test]
2593    fn kernel_id_validate_range_inverted_rc_below_release() {
2594        let id = KernelId::parse("6.10..6.10-rc3");
2595        assert!(
2596            id.validate().is_err(),
2597            "release > rc — `6.10..6.10-rc3` must reject: {id:?}",
2598        );
2599    }
2600
2601    /// `6.10-rc3..6.10` — pre-release < release. Forward direction;
2602    /// validate passes. The companion to `inverted_rc_below_release`.
2603    #[test]
2604    fn kernel_id_validate_range_rc_below_release_forward_ok() {
2605        let id = KernelId::parse("6.10-rc3..6.10");
2606        assert!(
2607            id.validate().is_ok(),
2608            "rc < release — `6.10-rc3..6.10` must validate: {id:?}",
2609        );
2610    }
2611
2612    /// `6.14.5..6.14` — an explicit-patch START into a 2-component END
2613    /// that names the WHOLE 6.14 series. `range_end_key` widens the END
2614    /// to the series ceiling (6,14,MAX,MAX), so this is the valid range
2615    /// "6.14.5 through the end of the 6.14 series", NOT an inversion.
2616    /// Regression pin: before END-series-inclusivity, validate used the
2617    /// un-widened end (6,14,0,MAX) and falsely rejected this while the
2618    /// expansion accepted it — the two disagreed; now they must agree.
2619    #[test]
2620    fn kernel_id_validate_range_explicit_start_patch_into_series_end_ok() {
2621        let id = KernelId::parse("6.14.5..6.14");
2622        assert!(
2623            id.validate().is_ok(),
2624            "explicit-patch start into a series END must validate: {id:?}",
2625        );
2626    }
2627
2628    /// `6.15..6.14` — a higher START minor than the END series must
2629    /// still reject even with the END widened to (6,14,MAX,MAX): the
2630    /// widening must not mask a real inversion.
2631    #[test]
2632    fn kernel_id_validate_range_series_end_still_rejects_higher_start() {
2633        let id = KernelId::parse("6.15..6.14");
2634        assert!(
2635            id.validate().is_err(),
2636            "higher start minor must still reject as inverted: {id:?}",
2637        );
2638    }
2639
2640    /// `6.10-rc3..6.10-rc1` — same major.minor.patch but rc decreases.
2641    /// Reject. Pre-release ordering must follow numeric rcN order.
2642    #[test]
2643    fn kernel_id_validate_range_inverted_rc_to_rc() {
2644        let id = KernelId::parse("6.10-rc3..6.10-rc1");
2645        assert!(id.validate().is_err(), "rc3..rc1 must reject: {id:?}");
2646    }
2647
2648    /// `6.10..6.10.5` — `6.10` decomposes to (6,10,0,MAX), `6.10.5`
2649    /// to (6,10,5,MAX). Forward direction. Validates.
2650    #[test]
2651    fn kernel_id_validate_range_missing_patch_treated_as_zero() {
2652        let id = KernelId::parse("6.10..6.10.5");
2653        assert!(
2654            id.validate().is_ok(),
2655            "missing patch defaults to 0, so `6.10..6.10.5` is forward: {id:?}",
2656        );
2657    }
2658
2659    /// All non-Range variants validate trivially — Path, Version,
2660    /// CacheKey, Git all return Ok. Pins the "validate is currently
2661    /// only meaningful for Range" contract: a future field with its
2662    /// own resolve-time invariant should add an arm here, not slip
2663    /// through silently.
2664    #[test]
2665    fn kernel_id_validate_non_range_variants_ok() {
2666        assert!(KernelId::Version("6.14.2".to_string()).validate().is_ok());
2667        assert!(KernelId::CacheKey("my-key".to_string()).validate().is_ok());
2668        assert!(KernelId::Path(PathBuf::from("../linux")).validate().is_ok(),);
2669        assert!(
2670            KernelId::Git {
2671                url: "https://example.com/r.git".to_string(),
2672                git_ref: "main".to_string(),
2673                ref_kind: GitRefKind::Branch,
2674            }
2675            .validate()
2676            .is_ok(),
2677        );
2678    }
2679
2680    /// The explicit git ref grammar rejects, at `validate`, a bare
2681    /// `#REF` (Unknown kind), an empty ref value, and a `#sha=` that
2682    /// is not a full 40-hex commit id. `parse` returns the variant;
2683    /// `validate` is the error channel (there is no `KernelId::Invalid`).
2684    #[test]
2685    fn kernel_id_validate_git_rejects_malformed_ref() {
2686        // Bare `#main` → Unknown → rejected with the "use #tag=/…" hint.
2687        let bare = KernelId::parse("git+https://example.com/r.git#main");
2688        let err = bare.validate().expect_err("bare #REF must be rejected");
2689        assert!(
2690            err.contains("#tag=") && err.contains("#branch=") && err.contains("#sha="),
2691            "error must name the accepted grammar: {err}"
2692        );
2693        // Empty value after a valid kind.
2694        assert!(
2695            KernelId::parse("git+https://example.com/r.git#tag=")
2696                .validate()
2697                .is_err(),
2698            "empty #tag= must be rejected"
2699        );
2700        // `#sha=` that is not 40 hex.
2701        assert!(
2702            KernelId::parse("git+https://example.com/r.git#sha=abc123")
2703                .validate()
2704                .is_err(),
2705            "short (non-40-hex) #sha= must be rejected"
2706        );
2707        let full = "0123456789abcdef0123456789abcdef01234567";
2708        assert!(
2709            KernelId::parse(&format!("git+https://example.com/r.git#sha={full}"))
2710                .validate()
2711                .is_ok(),
2712            "a full 40-hex #sha= must validate"
2713        );
2714    }
2715
2716    /// Direct construction with an unparseable `start` endpoint
2717    /// (callers that build `KernelId::Range` outside `KernelId::parse`
2718    /// can put any string in either slot — the Display round-trip
2719    /// gives them the spelling back, but `validate()` is the safety
2720    /// net for resolve-time legality). Asserts the error names the
2721    /// "not a parseable version" condition so a downstream tool can
2722    /// distinguish this from the inverted-range message above.
2723    #[test]
2724    fn kernel_id_validate_range_unparseable_start() {
2725        let id = KernelId::Range {
2726            start: "garbage".to_string(),
2727            end: "6.10".to_string(),
2728            syntax_inclusive: false,
2729        };
2730        let err = id.validate().unwrap_err();
2731        assert!(
2732            err.contains("not a parseable version"),
2733            "error must say 'not a parseable version', got: {err}",
2734        );
2735        assert!(
2736            err.contains("garbage"),
2737            "error must cite the bad endpoint, got: {err}"
2738        );
2739    }
2740
2741    /// Companion to `unparseable_start` for the `end` slot.
2742    #[test]
2743    fn kernel_id_validate_range_unparseable_end() {
2744        let id = KernelId::Range {
2745            start: "6.10".to_string(),
2746            end: "garbage".to_string(),
2747            syntax_inclusive: false,
2748        };
2749        let err = id.validate().unwrap_err();
2750        assert!(
2751            err.contains("not a parseable version"),
2752            "error must say 'not a parseable version', got: {err}",
2753        );
2754        assert!(
2755            err.contains("garbage"),
2756            "error must cite the bad endpoint, got: {err}"
2757        );
2758    }
2759
2760    // -- _is_version_string --
2761
2762    #[test]
2763    fn kernel_id_is_version_string_valid() {
2764        assert!(_is_version_string("6"), "bare major is a version prefix");
2765        assert!(_is_version_string("6.14"));
2766        assert!(_is_version_string("6.14.2"));
2767        assert!(_is_version_string("6.15-rc3"));
2768        assert!(_is_version_string("6.14.0-rc1"));
2769        assert!(_is_version_string("5.0"));
2770        assert!(_is_version_string("5.0.0"));
2771        assert!(_is_version_string("5.4.0"));
2772    }
2773
2774    #[test]
2775    fn kernel_id_is_version_string_invalid() {
2776        // Bare major `6` is now VALID (optional minor), but a non-digit
2777        // minor must still reject — pins the optional-minor boundary.
2778        assert!(!_is_version_string("6.x"));
2779        assert!(!_is_version_string("v6.14"));
2780        assert!(!_is_version_string(""));
2781        assert!(!_is_version_string("6.14.2-tarball-x86_64"));
2782        assert!(!_is_version_string("6.14.2.3"));
2783        assert!(!_is_version_string("6.14-rc"));
2784        assert!(!_is_version_string("6.14-rcX"));
2785        // rc_part contains non-digits after splitting on "-rc".
2786        assert!(!_is_version_string("6.14-rc3-tarball-x86_64"));
2787        assert!(!_is_version_string("abc"));
2788        assert!(!_is_version_string(".14"));
2789        assert!(!_is_version_string("6."));
2790        assert!(!_is_version_string("linux"));
2791        assert!(!_is_version_string(".6"));
2792    }
2793
2794    // -- proptest --
2795
2796    use proptest::prop_assert;
2797
2798    proptest::proptest! {
2799        /// Arbitrary input must parse into a `KernelId` variant whose
2800        /// payload round-trips to the original string where a
2801        /// round-trip is defined (Path / Version / CacheKey). Bumped
2802        /// the input range from 30 to 120 characters to exercise long
2803        /// paths and pathological multi-dot strings.
2804        ///
2805        /// Path payload round-trip is conditional on the leading
2806        /// `~`-expansion path: a `~`- or `~/...`-prefixed input
2807        /// that resolves against `$HOME` lands in `Path` with the
2808        /// expanded form, NOT the literal `~`-prefix the input
2809        /// carried. The proptest detects that case and asserts the
2810        /// expanded equivalence instead of the literal one. Other
2811        /// `~`-prefix shapes (`~user/...`, or any prefix when
2812        /// `$HOME` is empty/unset) pass through verbatim and the
2813        /// strict round-trip assertion still holds — see
2814        /// [`super::expand_tilde`] for the case table.
2815        #[test]
2816        fn prop_kernel_id_parse_never_panics(s in "\\PC{0,120}") {
2817            // Hold the env lock for each proptest iteration so a
2818            // parallel test that mutates `HOME` cannot race the
2819            // two `expand_tilde` reads (one inside `parse`, one
2820            // for the expected value below) and produce a
2821            // false-positive payload-drift failure on a
2822            // `~`-prefixed input.
2823            let _env_lock = crate::test_support::test_helpers::lock_env();
2824            match KernelId::parse(&s) {
2825                KernelId::Path(p) => {
2826                    let expected = expand_tilde(&s);
2827                    prop_assert!(
2828                        p == expected,
2829                        "Path payload drift for {s:?}: got {p:?}, expected {expected:?}",
2830                    );
2831                }
2832                KernelId::Version(v) => prop_assert!(v == s, "Version payload drift for {s:?}"),
2833                KernelId::CacheKey(k) => prop_assert!(k == s, "CacheKey payload drift for {s:?}"),
2834                KernelId::Range { start, end, syntax_inclusive } => {
2835                    // Range is constructed only when both endpoints
2836                    // are version-shaped, so the payload round-trips
2837                    // through the `start..end` (or `start..=end`)
2838                    // rendering. Display emits the same separator
2839                    // the parser consumed, tracked via
2840                    // `syntax_inclusive`.
2841                    let sep = if syntax_inclusive { "..=" } else { ".." };
2842                    prop_assert!(
2843                        format!("{start}{sep}{end}") == s,
2844                        "Range payload drift for {s:?}",
2845                    );
2846                }
2847                KernelId::Git { .. } => {
2848                    // Any `git+…` string parses to a Git value. A STRING
2849                    // round-trip cannot hold for every input: `git+URL`
2850                    // and `git+URL#` both parse to the same value
2851                    // (`Unknown` kind, empty ref), and `Display` always
2852                    // renders a `#`, so `git+URL` != Display(parse("git+URL")).
2853                    // Assert the SEMANTIC round-trip instead — Display
2854                    // then re-parse yields an equal id — which holds for
2855                    // every kind including the `#`-free / empty-fragment
2856                    // spellings.
2857                    let id = KernelId::parse(&s);
2858                    let reparsed = KernelId::parse(&id.to_string());
2859                    prop_assert!(
2860                        reparsed == id,
2861                        "Git semantic round-trip drift for {s:?}: \
2862                         {id:?} -> {:?} -> {reparsed:?}",
2863                        id.to_string(),
2864                    );
2865                }
2866                KernelId::Package { path } => {
2867                    // Package mirrors Path: the payload is the
2868                    // `~`-expanded input, so it round-trips against
2869                    // `expand_tilde` exactly like the Path arm.
2870                    let expected = expand_tilde(&s);
2871                    prop_assert!(
2872                        path == expected,
2873                        "Package payload drift for {s:?}: got {path:?}, expected {expected:?}",
2874                    );
2875                }
2876                KernelId::Distro { .. } => {
2877                    // Shorthand spellings (`f44`, `al2023`) render in
2878                    // long form, so a STRING round-trip need not hold;
2879                    // assert the SEMANTIC round-trip (Display then
2880                    // re-parse yields an equal id) as the Git arm does.
2881                    let id = KernelId::parse(&s);
2882                    let reparsed = KernelId::parse(&id.to_string());
2883                    prop_assert!(
2884                        reparsed == id,
2885                        "Distro semantic round-trip drift for {s:?}: \
2886                         {id:?} -> {:?} -> {reparsed:?}",
2887                        id.to_string(),
2888                    );
2889                }
2890            }
2891        }
2892
2893        #[test]
2894        fn prop_kernel_id_path_on_slash(
2895            prefix in "[a-z]{1,5}",
2896            suffix in "[a-z]{1,5}",
2897        ) {
2898            let s = format!("{prefix}/{suffix}");
2899            assert!(matches!(KernelId::parse(&s), KernelId::Path(_)));
2900        }
2901
2902        #[test]
2903        fn prop_kernel_id_path_on_dot_prefix(s in "\\.[a-z]{1,10}") {
2904            assert!(matches!(KernelId::parse(&s), KernelId::Path(_)));
2905        }
2906
2907        #[test]
2908        fn prop_kernel_id_version_roundtrip(
2909            major in 1u32..20,
2910            minor in 0u32..50,
2911            patch in 0u32..100,
2912        ) {
2913            let v = format!("{major}.{minor}.{patch}");
2914            assert_eq!(KernelId::parse(&v), KernelId::Version(v.clone()));
2915        }
2916
2917        #[test]
2918        fn prop_kernel_id_version_rc(major in 1u32..20, minor in 0u32..50, rc in 1u32..10) {
2919            let v = format!("{major}.{minor}-rc{rc}");
2920            assert_eq!(KernelId::parse(&v), KernelId::Version(v.clone()));
2921        }
2922    }
2923}