ktstr/cli/
kernel_cmd.rs

1//! `kernel` subcommand definition and help-text constants.
2//!
3//! Holds the `KernelCommand` enum (shared by `ktstr` and
4//! `cargo-ktstr`), the `--help` text constants for kernel-related
5//! flags (`--kernel`, `--cpu-cap`, `--extra-kconfig`, `--disk`),
6//! and the legend / footer helpers that flow through `kernel list`'s
7//! tag-emission gates.
8
9use std::path::{Path, PathBuf};
10
11use clap::Subcommand;
12
13/// Shared `kernel` subcommand tree used by both `ktstr` and
14/// `cargo ktstr`. The two binaries embed this as
15/// `ktstr kernel <subcmd>` / `cargo ktstr kernel <subcmd>` and
16/// dispatch identically; defining the variants once means a new
17/// `kernel` subcommand (or a flag change) lands in both surfaces by
18/// construction.
19#[derive(Subcommand, Debug)]
20pub enum KernelCommand {
21    /// List cached kernel images, or preview a range expansion
22    /// without downloading or building.
23    ///
24    /// Default mode (no `--kernel`): walks the local cache and
25    /// reports every cached kernel image. `--kernel START..END`
26    /// switches to PREVIEW mode: fetches kernel.org's
27    /// `releases.json`, expands the inclusive range against the
28    /// `stable` / `longterm` releases, and prints the resulting
29    /// version list. Preview mode performs no downloads or builds
30    /// and ignores the local cache — operators can use it to
31    /// answer "what does `--kernel 6.12..6.16` actually cover?"
32    /// before paying the network or cache-store cost of a real
33    /// resolve.
34    #[command(long_about = KERNEL_LIST_LONG_ABOUT)]
35    List {
36        /// Output in JSON format for CI scripting.
37        #[arg(long)]
38        json: bool,
39        /// Range to PREVIEW. When supplied, switches the subcommand
40        /// from "list cached kernels" to "fetch releases.json and
41        /// print the versions a `START..END` range expands to."
42        /// Format: `MAJOR.MINOR[.PATCH][-rcN]..MAJOR.MINOR[.PATCH][-rcN]`,
43        /// matching [`crate::kernel_path::KernelId::Range`].
44        /// Example: `--kernel 6.12..6.14` → every stable/longterm
45        /// release in `[6.12, 6.14]` inclusive. A non-range
46        /// `--kernel` (a single version, path, or git source) is
47        /// rejected — preview mode expands ranges only; to inspect a
48        /// cached single kernel run `kernel list` without `--kernel`.
49        ///
50        /// In preview mode the subcommand performs no cache
51        /// reads or kernel.org tarball downloads — only the
52        /// single `releases.json` fetch that
53        /// [`crate::cli::expand_kernel_range`] already runs for
54        /// real range resolves. `--json` (when also supplied)
55        /// emits a JSON object with the literal range string and
56        /// the expanded version array; without `--json` the
57        /// versions are written one per line to stdout for shell
58        /// pipelines.
59        #[arg(long)]
60        kernel: Option<String>,
61        /// See [`INCLUDE_EOL_HELP`]. Only affects a `--kernel`
62        /// range preview; ignored in the default cache-listing mode
63        /// (which reads no releases.json and enumerates no series).
64        #[arg(long, help = INCLUDE_EOL_HELP)]
65        include_eol: bool,
66    },
67    /// Download, build, and cache a kernel image.
68    Build {
69        /// Kernel to build (the unified `--kernel` grammar). Omitted,
70        /// builds the latest stable release. See [`KERNEL_HELP_BUILD`]
71        /// for the accepted shapes.
72        #[arg(long, help = KERNEL_HELP_BUILD)]
73        kernel: Option<String>,
74        /// Rebuild even if a cached image exists.
75        #[arg(long)]
76        force: bool,
77        /// Run `make mrproper` before configuring. Only meaningful for
78        /// a `--kernel <path>` source tree: version / range / git
79        /// sources build from a fresh tarball or clone, so this flag
80        /// prints a notice and is ignored for them.
81        #[arg(long)]
82        clean: bool,
83        #[arg(long, help = CPU_CAP_HELP)]
84        cpu_cap: Option<usize>,
85        /// Path to an additional kconfig fragment merged on top of
86        /// the baked-in `ktstr.kconfig`.
87        ///
88        /// # Format
89        ///
90        /// One declaration per line, same shapes the kernel itself
91        /// uses:
92        ///
93        /// ```text
94        /// # comment lines start with `#` and a space
95        /// CONFIG_FOO=y                  # boolean enable
96        /// CONFIG_FOO=m                  # build as module
97        /// CONFIG_FOO=n                  # disable (equivalent to is-not-set)
98        /// CONFIG_BAR="some value"       # string
99        /// CONFIG_BAR=42                 # integer / hex
100        /// # CONFIG_FOO is not set       # explicit disable directive
101        /// ```
102        ///
103        /// The baked-in fragment lives at `ktstr.kconfig` in the
104        /// ktstr repository root. See [`EMBEDDED_KCONFIG`] for the
105        /// const that loads it at compile time.
106        ///
107        /// # Conflict resolution
108        ///
109        /// User values win on conflict — kbuild's `.config` parser
110        /// (`scripts/kconfig/confdata.c::conf_read_simple`) emits
111        /// "override: reassigning to symbol X" and keeps the
112        /// last-occurring assignment, so appending the user fragment
113        /// AFTER the baked-in fragment makes user values take
114        /// precedence. Non-conflicting user lines combine with the
115        /// baked-in set verbatim.
116        ///
117        /// Override warnings: `kernel build` emits one
118        /// `tracing::warn!` per user line that overrides a baked-in
119        /// symbol (format: "--extra-kconfig overrides baked-in
120        /// CONFIG_FOO (was =y, now =n)"). The build proceeds; the
121        /// warning lets the operator see they are shadowing a
122        /// baked-in setting before make olddefconfig runs.
123        ///
124        /// # Dependency resolution
125        ///
126        /// `make olddefconfig` runs after the merge to resolve any
127        /// added symbols' dependencies. Options whose deps are not
128        /// met land as `# CONFIG_X is not set` in the final
129        /// `.config`; those silent drops surface as `tracing::warn!`
130        /// lines (not errors) so the operator sees the diagnostic
131        /// without the build failing.
132        ///
133        /// # Critical-symbol protection
134        ///
135        /// After build, [`super::validate_kernel_config`] rejects entries
136        /// that disabled symbols required by ktstr (CONFIG_BPF_SYSCALL,
137        /// CONFIG_DEBUG_INFO_BTF, CONFIG_FTRACE,
138        /// CONFIG_SCHED_CLASS_EXT, etc.). The error names
139        /// `--extra-kconfig` as the likely cause when extras were
140        /// supplied. So a fragment with
141        /// `# CONFIG_BPF is not set` will fail
142        /// `validate_kernel_config` post-build with an actionable
143        /// message — the override warning fires pre-build and the
144        /// validation error fires post-build, giving the operator
145        /// two chances to catch a fatal override.
146        ///
147        /// # Caching
148        ///
149        /// The cache key suffix grows from `kc{baked}` to
150        /// `kc{baked}-xkc{extra}` when extras are present (see
151        /// [`crate::cache_key_suffix_with_extra`]). Two builds
152        /// with distinct extra-kconfig content land at distinct
153        /// cache entries (different content = cache miss; same
154        /// content = cache hit on re-run). Builds with NO
155        /// `--extra-kconfig` keep using the bare `kc{baked}` suffix,
156        /// so existing cached kernels are not orphaned. An
157        /// `--extra-kconfig`-built kernel is only addressable by a
158        /// matching `--extra-kconfig` invocation or by an explicit
159        /// `--kernel <path>` / `KTSTR_KERNEL` path — `cargo ktstr test
160        /// --kernel 6.14.2` (which doesn't take `--extra-kconfig`)
161        /// will not surface the extra-built artifact.
162        ///
163        /// `kernel list` tags entries built with extras as
164        /// `(extra kconfig)` so an operator can spot which cached
165        /// kernels carry user modifications.
166        #[arg(long = "extra-kconfig", value_name = "PATH", help = EXTRA_KCONFIG_HELP)]
167        extra_kconfig: Option<PathBuf>,
168        /// Skip SHA-256 verification of downloaded stable tarballs.
169        /// Useful when cdn.kernel.org updates a tarball in-place (new
170        /// point release reusing the same URL) and the
171        /// sha256sums.asc manifest is stale or mismatched. Only affects
172        /// a version / range `--kernel` (the tarball download): no
173        /// effect on a `--kernel <path>` source tree (no download), a
174        /// `--kernel git+…` source (no manifest), or RC tarballs
175        /// (git.kernel.org dynamically generates RC archives and
176        /// publishes no upstream manifest, so RC downloads always run
177        /// unverified regardless of this flag). Bypassing verification
178        /// is security-sensitive: a single `--skip-sha256: bypassing
179        /// checksum verification` warning fires per affected download
180        /// so the lost guarantee is visible alongside the
181        /// verification-success line that would otherwise appear.
182        #[arg(long)]
183        skip_sha256: bool,
184        /// See [`INCLUDE_EOL_HELP`]. Only affects a `--kernel START..END`
185        /// range (e.g. `kernel build --kernel 6.11..6.14`); ignored for
186        /// a single version, path, or git source, none of which expand
187        /// a range.
188        #[arg(long, help = INCLUDE_EOL_HELP)]
189        include_eol: bool,
190    },
191    /// Remove cached kernel images.
192    Clean {
193        /// Keep the N most recent VALID cached kernels. When absent,
194        /// removes every valid entry. Corrupt entries are always
195        /// candidates for removal regardless of this value — they
196        /// waste disk space and serve no build — so a corrupt entry
197        /// never consumes a keep slot.
198        #[arg(long)]
199        keep: Option<usize>,
200        /// Skip the y/N confirmation prompt before deleting. Always
201        /// required in non-interactive contexts: without `--force`
202        /// the command bails on a non-tty stdin rather than hang
203        /// waiting for input. In an interactive shell, omit
204        /// `--force` to be prompted.
205        #[arg(long)]
206        force: bool,
207        /// Remove only corrupt cache entries (metadata missing or
208        /// unparseable, image file absent). Valid entries are left
209        /// untouched regardless of `--force`. Useful for clearing
210        /// broken entries after an interrupted build without
211        /// risking the curated set of good kernels. Mutually
212        /// exclusive with `--keep`: `--corrupt-only` never touches
213        /// valid entries, so a keep budget would silently be
214        /// ignored; rejecting at parse time surfaces the
215        /// misunderstanding instead.
216        #[arg(long, conflicts_with = "keep")]
217        corrupt_only: bool,
218    },
219}
220
221/// Help text for `--kernel` in contexts that reject raw image files:
222/// `cargo ktstr test`, `cargo ktstr coverage`, `cargo ktstr llvm-cov`,
223/// and `ktstr shell`. Matches
224/// `KernelResolvePolicy { accept_raw_image: false, .. }`.
225///
226/// Raw images are rejected here because these commands depend on a
227/// matching `vmlinux` and the cached kconfig fragment alongside the
228/// image (test/coverage need BTF, `ktstr shell` reuses the cache
229/// entry for kconfig discovery). A bare `bzImage`/`Image` passed
230/// directly carries neither, so silently accepting it would produce
231/// hard-to-diagnose mid-run failures.
232/// `cargo ktstr shell` accepts raw images because its flow does not
233/// need that companion metadata; see [`KERNEL_HELP_RAW_OK`].
234pub const KERNEL_HELP_NO_RAW: &str = "Kernel identifier — one of: \
235     (1) an exact version (`6.14.2`, `6.15-rc3`), a major.minor prefix \
236     (`6.14`, latest patch in the series), or a bare major (`6`, latest \
237     `6.x`); \
238     (2) an inclusive version range (`6.12..6.14` or `6.12..=6.14`); \
239     (3) a git source (`git+URL#tag=NAME`, `git+URL#branch=NAME`, or \
240     `git+URL#sha=<40-hex>`); \
241     (4) a source directory path (`./linux`, `~/linux`, or an absolute path); \
242     (5) a local kernel package (`*.rpm` / `*.deb` / `*.pkg.tar.zst`, one \
243     file per `--kernel`); \
244     (6) a prebuilt distro kernel — `fedora` / `fedora-44` / `f44`, \
245     `ubuntu` / `ubuntu-24.04` (resolves to the latest LTS HWE kernel), \
246     `amazonlinux` / `amazonlinux-2023` / `al2023`, \
247     `steamos` / `steamos-3.8`, or `gke` / `gke-129` \
248     (official GKE COS kernel; x86_64 only; bare `gke` picks the newest \
249     image in Google's current GKE release notes, while `gke-129` tracks \
250     the newest promoted revision within COS milestone 129); or \
251     (7) a cache key (see `kernel list`). Raw \
252     image files are rejected. Source directories auto-build (can be slow \
253     on a fresh tree); versions auto-download from kernel.org on cache \
254     miss; distro kernels download official kernel + debuginfo/source artifacts \
255     (cached like a built kernel). Ubuntu splits its \
256     image and modules across two debs, so a modular Ubuntu image needs the \
257     `ubuntu` distro form (which downloads both) rather than a single local \
258     `.deb`. The flag is REPEATABLE on `test`, `coverage`, and `llvm-cov` \
259     — passing multiple `--kernel` flags fans the gauntlet across every \
260     resolved kernel; each (test × scenario × topology × kernel) \
261     tuple becomes a distinct nextest test case so nextest's parallelism, \
262     retries, and `-E` filtering work natively. Ranges expand to every \
263     `stable` and `longterm` release inside `[START, END]` inclusive \
264     (mainline / linux-next dropped). Git branch and tag sources use \
265     the same exact-ref, depth-one in-process gix fetch on every host; \
266     only an explicit immutable GitHub SHA uses codeload. Same-content \
267     concurrent callers share one fetch and build. In contrast, `ktstr shell` accepts a single \
268     kernel only — pass exactly one `--kernel`.";
269
270/// Help text for `--kernel` in contexts that accept raw image files:
271/// `cargo ktstr shell`. Matches
272/// `KernelResolvePolicy { accept_raw_image: true, .. }`. See
273/// [`KERNEL_HELP_NO_RAW`] for the converse and the rationale for
274/// the asymmetry.
275pub const KERNEL_HELP_RAW_OK: &str = "Kernel identifier — one of: \
276     (1) a source directory path (`./linux`, `~/linux`, or an absolute path); \
277     (2) a raw image file (`bzImage` / `Image`); \
278     (3) an exact version (`6.14.2`, `6.15-rc3`), a major.minor prefix \
279     (`6.14`, latest patch), or a bare major (`6`); \
280     (4) a local kernel package (`*.rpm` / `*.deb` / `*.pkg.tar.zst`, one \
281     file per `--kernel`); \
282     (5) a prebuilt distro kernel — `fedora` / `fedora-44` / `f44`, \
283     `ubuntu` / `ubuntu-24.04` (resolves to the latest LTS HWE kernel), \
284     `amazonlinux` / `amazonlinux-2023` / `al2023`, \
285     `steamos` / `steamos-3.8`, or `gke` / `gke-129`; or \
286     (6) a cache key (see `kernel list`). Source directories auto-build \
287     (can be slow on a fresh tree); versions auto-download from kernel.org \
288     on cache miss; distro kernels download official kernel + debuginfo/source \
289     artifacts (cached like a built kernel). When \
290     absent, resolves via cache then filesystem, falling back to downloading \
291     the latest stable kernel. Version ranges (`START..END`) and git sources \
292     (`git+URL#tag=NAME`) are not supported here — pass a single kernel.";
293
294/// Help text for `--kernel` on `kernel build` (`ktstr` and
295/// `cargo ktstr`). Unlike [`KERNEL_HELP_NO_RAW`], this surface builds a
296/// kernel rather than resolving one for a test run: it is NOT repeatable
297/// (one kernel or one range per invocation), and a cache key is rejected
298/// (a cache key names an already-built entry, so there is nothing to
299/// build). A source-directory path auto-builds; a version / range
300/// auto-downloads; a git source is fetched and built. Omitting `--kernel`
301/// builds the latest stable release.
302pub const KERNEL_HELP_BUILD: &str = "Kernel to build (or, for a prebuilt \
303     spec, acquire into the cache) — one of: \
304     (1) a version (`6.14.2`, `6.15-rc3`), a `MAJOR.MINOR` prefix (`6.14`, \
305     latest patch in that series), or a bare `MAJOR` prefix (`6`, latest \
306     `6.x`); \
307     (2) an inclusive version range (`6.11..6.14` or `6.11..=6.14` — builds \
308     every stable/longterm release in the range); \
309     (3) a source directory path (`./linux`, `~/linux`, or an absolute path; \
310     a bare relative name like `linux` is read as a cache key, so prefix a \
311     relative source dir with `./`); \
312     (4) a git source (`git+URL#tag=NAME`, `git+URL#branch=NAME`, or \
313     `git+URL#sha=<40-hex>`); \
314     (5) a local kernel package (`*.rpm` / `*.deb` / `*.pkg.tar.zst`, one \
315     file per `--kernel`); \
316     or (6) a prebuilt distro kernel — `fedora` / `fedora-44` / `f44`, \
317     `ubuntu` / `ubuntu-24.04` (resolves to the latest LTS HWE kernel), \
318     `amazonlinux` / `amazonlinux-2023` / `al2023`, \
319     `steamos` / `steamos-3.8`, or `gke` / `gke-129` (x86_64 only). Omitted, the latest \
320     stable release is built. For a local package or distro spec, `build` \
321     downloads/unpacks the prebuilt kernel into the cache rather than \
322     compiling. A cache key (an already-built entry from `kernel list`) is \
323     rejected — it names a built kernel, so there is nothing to build. Build \
324     (or acquire) one kernel per invocation (or one range).";
325
326/// Help text for the `--include-eol` flag, shared by every command
327/// that expands a `START..END` kernel range (`cargo ktstr test`,
328/// `coverage`, `llvm-cov`, `verifier`, `kernel list`, and
329/// `kernel build` when the `--kernel` value is a range). One const so
330/// the wording stays identical across every surface the flag appears on.
331///
332/// Describes what the code DOES: [`crate::cli::expand_kernel_range`]
333/// draws only from kernel.org's `releases.json` by default (active
334/// `stable`/`longterm` series); under this flag it unions in the
335/// `vX.Y.Z` tags of the gregkh linux-stable mirror
336/// (`crate::fetch::cached_stable_tags`) and takes the latest patch
337/// per `(major, minor)` series across both sources, so a series that
338/// has aged out of `releases.json` still contributes its highest
339/// point release. If the mirror tag list cannot be fetched, expansion
340/// proceeds with a warning against the active-release set alone.
341pub const INCLUDE_EOL_HELP: &str = "Include end-of-life stable series when \
342     expanding a `START..END` kernel range. Default range resolution draws \
343     only from kernel.org's active releases (releases.json), which omits \
344     series no longer maintained; with this flag the range additionally \
345     covers every `vX.Y.Z` tag in the gregkh linux-stable mirror, so an EOL \
346     series inside [START, END] still contributes its highest point release. \
347     Has no effect on a single version, path, cache key, or git source — \
348     only range expansion consults the EOL set. When the mirror tag list \
349     cannot be fetched, expansion proceeds with a warning against the \
350     active-release set alone.";
351
352/// Help text for the `--cpu-cap N` flag. Shared across `ktstr kernel build`,
353/// `cargo ktstr kernel build`, and `ktstr shell` so the operator-facing
354/// wording is identical regardless of entry point.
355///
356/// This flag is the resource-budget contract: the operator promises
357/// (and the framework enforces) that the build or no-perf-mode shell
358/// VM will stay within N CPUs' worth of reservation and the NUMA
359/// nodes hosting them. Setting `--cpu-cap N` flips several internal
360/// defaults on this run: the LLC discovery walks whole LLCs in
361/// consolidation- and NUMA-aware order until the CPU budget is met;
362/// make's `-jN` parallelism matches the plan's CPU count so gcc
363/// can't fan out beyond the budget; a cgroup v2 sandbox binds make +
364/// gcc's cpuset to the plan's CPUs and `cpuset.mems` to the plan's
365/// NUMA nodes, so any degradation is fatal under the flag rather
366/// than a silent warning.
367pub const CPU_CAP_HELP: &str = "Reserve exactly N host CPUs for the build or \
368     no-perf-mode shell. Integer ≥ 1; must be ≤ the calling process's \
369     sched_getaffinity cpuset size (the allowed CPU count, NOT the \
370     host's total online CPUs — under a cgroup-restricted runner the \
371     allowed set is typically smaller). When absent, 30% of the \
372     allowed CPUs are reserved (minimum 1). The planner walks whole \
373     LLCs in consolidation- and NUMA-aware order, filtered to the \
374     allowed cpuset, partial-taking the last LLC so `plan.cpus.len() \
375     == N` exactly. The flock set may cover more LLCs than strictly \
376     required (flock coordination is per-LLC even when the last LLC \
377     is only partially used for the CPU budget). Run `ktstr locks \
378     --watch 1s` to observe NUMA placement live. Under --cpu-cap, \
379     make's `-jN` parallelism matches the reserved CPU count and the \
380     kernel build runs inside a cgroup v2 sandbox that pins gcc/ld \
381     to the reserved CPUs + NUMA nodes; if the sandbox cannot be \
382     installed (missing cgroup v2, missing cpuset controller, \
383     permission denied), the build aborts rather than running \
384     without enforcement. Mutually exclusive with \
385     KTSTR_BYPASS_LLC_LOCKS=1. On `ktstr shell`, requires \
386     --no-perf-mode (perf-mode already holds every LLC exclusively). \
387     Also settable via KTSTR_CPU_CAP env var (CLI flag wins when both \
388     are present).";
389
390/// Short clap-help for `--extra-kconfig`. Mirrors the [`CPU_CAP_HELP`]
391/// pattern: terse first sentence on the clap surface, full rustdoc
392/// on the [`KernelCommand::Build`] variant for `--help` long-about.
393///
394/// The full rustdoc covers: accepted line shapes, kbuild last-wins
395/// rule, `make olddefconfig` dependency resolution, post-build
396/// `validate_kernel_config` interaction, two-segment cache key,
397/// override warnings, and the unaddressable-from-other-flags
398/// rationale.
399pub const EXTRA_KCONFIG_HELP: &str = "Additional kconfig fragment merged on top of \
400     the baked-in `ktstr.kconfig`. Same line shapes the kernel uses: \
401     `CONFIG_FOO=y`, `CONFIG_FOO=m`, `CONFIG_FOO=\"value\"`, and \
402     `# CONFIG_FOO is not set`. User values win on conflict; \
403     `make olddefconfig` resolves dependencies. Each unique fragment \
404     produces a distinct cache slot via the `kc{baked}-xkc{extra}` \
405     key suffix. After build, `validate_kernel_config` rejects \
406     entries that disabled critical baked-in symbols \
407     (CONFIG_SCHED_CLASS_EXT, CONFIG_DEBUG_INFO_BTF, CONFIG_BPF_SYSCALL, \
408     CONFIG_FTRACE, CONFIG_KPROBE_EVENTS, CONFIG_BPF_EVENTS). \
409     The baked-in fragment lives at `ktstr.kconfig` in the ktstr \
410     repository root.";
411
412/// Literal text of the `(EOL)` tag explanation. Lives inside a macro
413/// (instead of a `pub const`) so that downstream `concat!` callers
414/// — specifically [`KERNEL_LIST_LONG_ABOUT`] — can embed the bytes at
415/// compile time without duplicating the string. `concat!` requires
416/// each argument to be a string literal at expansion, and a macro
417/// call that expands to a literal satisfies that requirement while
418/// a `&'static str` reference does not. Expansion order: the inner
419/// macro is expanded first, `concat!` then sees a literal.
420macro_rules! eol_explanation_literal {
421    () => {
422        "(EOL) marks entries whose major.minor series is absent from \
423         kernel.org's current active releases. Suppressed when the \
424         active-release list cannot be fetched."
425    };
426}
427
428/// Explanation of the `(EOL)` tag, shared between the text-output
429/// legend printed after `kernel list` and the `kernel list --help`
430/// long description (via [`KERNEL_LIST_LONG_ABOUT`], which embeds this
431/// exact byte sequence at its head through the shared
432/// `eol_explanation_literal!` macro). One literal → one source of
433/// truth, so a wording drift cannot put the two surfaces out of
434/// sync. `pub` matches the visibility of the sibling
435/// `KERNEL_HELP_*` constants so downstream consumers (e.g.
436/// documentation generators) can reference the exact text the CLI
437/// prints.
438pub const EOL_EXPLANATION: &str = eol_explanation_literal!();
439
440/// `long_about` for `kernel list --help`. Embeds [`EOL_EXPLANATION`]
441/// verbatim (via `eol_explanation_literal!`) so the tag legend
442/// cannot drift between the post-table output and the help copy,
443/// then appends a plain-text rendering of the `--json` output
444/// schema so scripted consumers can discover the contract from the
445/// terminal without running `cargo doc`. The schema wording
446/// mirrors the Rust-doc schema on [fn@super::kernel_list]; keeping both
447/// surfaces terse makes a drift obvious on review. A plain-text
448/// (not JSON/markdown) rendering is used because clap applies no
449/// JSON/markdown formatting pass, so the schema reads as plain
450/// text. Clap does apply terminal-width wrapping, so the embedded
451/// EOL sentence re-flows to the width of the host terminal; the
452/// schema block's explicit `\n` line breaks survive wrapping and
453/// preserve the column-aligned field table.
454pub const KERNEL_LIST_LONG_ABOUT: &str = concat!(
455    eol_explanation_literal!(),
456    "\n\n",
457    "--json emits one JSON object with three top-level fields:\n",
458    "\n",
459    "  current_ktstr_kconfig_hash   hex digest of the kconfig fragment the\n",
460    "                               running binary was built with, for\n",
461    "                               stale-entry detection.\n",
462    "  active_prefixes_fetch_error  null on success; error string on\n",
463    "                               active-series fetch failure. When\n",
464    "                               non-null, every entry's `eol` is false\n",
465    "                               regardless of actual support status —\n",
466    "                               check this field before trusting `eol`.\n",
467    "  entries                      array of per-entry objects. Each\n",
468    "                               element is either a VALID entry (full\n",
469    "                               field set) or a CORRUPT entry\n",
470    "                               (`key`, `path`, `error`,\n",
471    "                               `error_kind`). `error` is the\n",
472    "                               human-readable reason; `error_kind`\n",
473    "                               the machine-readable classifier.\n",
474    "                               Detect\n",
475    "                               corruption by the presence of `error`.\n",
476    "\n",
477    "Valid entry fields: key, path, version (nullable), source, arch,\n",
478    "built_at, ktstr_kconfig_hash (nullable), extra_kconfig_hash\n",
479    "(nullable), kconfig_status, eol, config_hash (nullable),\n",
480    "image_name, image_path, has_vmlinux, vmlinux_stripped.\n",
481    "\n",
482    "  path             absolute path to the cache entry DIRECTORY.\n",
483    "  image_path       absolute path to the boot image file INSIDE\n",
484    "                   that directory. `path` points at the dir, not\n",
485    "                   the image — scripts that want the kernel\n",
486    "                   artifact to pass to qemu/vm-loaders should\n",
487    "                   read `image_path`, not join `path` with a\n",
488    "                   hardcoded filename.\n",
489    "  kconfig_status   one of \"matches\", \"stale\", \"untracked\"\n",
490    "                   (Display form of cache::KconfigStatus).\n",
491    "  source           internally-tagged on \"type\":\n",
492    "                     {\"type\": \"tarball\"}\n",
493    "                     {\"type\": \"git\",   \"git_hash\": ?, \"ref\": ?}\n",
494    "                     {\"type\": \"local\", \"source_tree_path\": ?,\n",
495    "                                       \"git_hash\": ?}\n",
496    "                   Dispatch on \"type\" before reading variant\n",
497    "                   fields.\n",
498    "  eol              true iff the entry's major.minor series is absent\n",
499    "                   from the active-prefix list. Meaningful only when\n",
500    "                   active_prefixes_fetch_error is null. Also false\n",
501    "                   whenever version is null (the missing-version\n",
502    "                   short-circuit in `entry_is_eol`).\n",
503    "  has_vmlinux      true iff the uncompressed vmlinux is cached\n",
504    "                   alongside the compressed image (required for\n",
505    "                   DWARF-driven probes).\n",
506    "  vmlinux_stripped true iff the cached vmlinux came from a\n",
507    "                   successful strip pass. false marks the\n",
508    "                   raw-fallback path — a larger on-disk payload\n",
509    "                   indicating the strip pipeline errored on this\n",
510    "                   kernel; the entry is still usable but the\n",
511    "                   fallback is a signal to investigate. Meaningful\n",
512    "                   only when has_vmlinux is true (false otherwise).\n",
513    "  config_hash      CRC32 of the final merged .config; distinct\n",
514    "                   from ktstr_kconfig_hash which covers only the\n",
515    "                   ktstr fragment.\n",
516    "  extra_kconfig_hash\n",
517    "                   CRC32 of the user `--extra-kconfig` fragment\n",
518    "                   (raw bytes, no canonicalization), or null when\n",
519    "                   the entry was built without --extra-kconfig.\n",
520    "                   The cache key suffix grows from `kc{baked}` to\n",
521    "                   `kc{baked}-xkc{extra}` when extras are present,\n",
522    "                   and this field stores the `xkc` segment so\n",
523    "                   `kernel list` is self-describing for entries\n",
524    "                   that carry user modifications.\n",
525    "\n",
526    "When --kernel is a range, the subcommand SWITCHES to range-preview\n",
527    "mode and emits a structurally different JSON shape — the cache\n",
528    "is not walked at all, only kernel.org's releases.json is fetched\n",
529    "to expand the inclusive range. The --json output is one object\n",
530    "with four top-level fields:\n",
531    "\n",
532    "  range     literal range string supplied to --kernel\n",
533    "            (e.g. \"6.12..6.14\").\n",
534    "  start     parsed start endpoint\n",
535    "            (MAJOR.MINOR[.PATCH][-rcN]).\n",
536    "  end       parsed end endpoint, same shape as start.\n",
537    "  versions  array of resolved version strings inside\n",
538    "            [start, end] inclusive, ascending by\n",
539    "            (major, minor, patch, rc) tuple. Stable and\n",
540    "            longterm releases only — mainline / linux-next\n",
541    "            are excluded by the moniker filter.\n",
542    "\n",
543    "Range-mode output never carries cache metadata\n",
544    "(no current_ktstr_kconfig_hash, no entries) — to inspect cached\n",
545    "kernels for one of the resolved versions, run `kernel list`\n",
546    "without --kernel. Consumers should dispatch on the presence of\n",
547    "the `range` key (range mode) versus `entries` key (list mode)\n",
548    "to branch the parse."
549);
550
551/// Emitted by `kernel build` when a local source tree has
552/// uncommitted index/worktree changes. Caching would key the built
553/// artifact on a git hash that does not describe the actual tree,
554/// so the build completes but the result is not archived. The
555/// hint names the two remediation paths (commit or stash) so an
556/// operator re-running the build after cleaning the tree benefits
557/// from the cache. Extracted from the call site so a wording drift
558/// between what's printed and what's documented elsewhere is
559/// impossible by construction; pinned by
560/// `dirty_tree_cache_skip_hint_shape` below.
561pub const DIRTY_TREE_CACHE_SKIP_HINT: &str = "skipping cache — working tree has uncommitted changes; \
562     commit or stash to enable caching";
563
564/// Hint shown in place of [`DIRTY_TREE_CACHE_SKIP_HINT`] when the
565/// source tree is not a git repository at all. `commit` / `stash`
566/// are not actionable remediations in that case — the operator's
567/// only path to caching is to put the source under git (or use a
568/// kernel-source fetch mode that produces a git-tracked tree).
569/// Pinned by `non_git_tree_cache_skip_hint_shape` below so a
570/// wording drift is caught in unit tests.
571pub const NON_GIT_TREE_CACHE_SKIP_HINT: &str = "skipping cache — source tree is not a git repository so dirty \
572     state cannot be detected; put the source under git, or replace the \
573     `--kernel <path>` source with one of the content-keyed fetch modes \
574     that does not need dirty-state detection — `kernel build --kernel \
575     <version>` (downloads the tarball from kernel.org) or `kernel build \
576     --kernel git+URL#branch=NAME` (shallow-clones the given ref) — to \
577     enable caching";
578
579/// Decide whether to emit the `(EOL)` legend under the `kernel list`
580/// table. Returns `Some(EOL_EXPLANATION)` iff at least one rendered
581/// row carried the tag, else `None`. Splitting the conditional out
582/// of `kernel_list` lets both branches be pinned in unit tests
583/// without capturing stderr.
584pub(crate) fn eol_legend_if_any(any_eol: bool) -> Option<&'static str> {
585    if any_eol { Some(EOL_EXPLANATION) } else { None }
586}
587
588/// Explanation of the `(untracked kconfig)` tag. Consumer-facing
589/// wording mirrors `EOL_EXPLANATION`'s "one-const, one-surface"
590/// pattern so a doc-drift between the tag word and the legend
591/// cannot silently slip. Mirrors [`STALE_KCONFIG_EXPLANATION`] so
592/// the kconfig tag pair shares one shape.
593///
594/// The `(corrupt)` tag is deliberately not in this legend family —
595/// its remediation is operational, not informational. See
596/// `format_corrupt_footer` for the full rationale.
597pub const UNTRACKED_KCONFIG_EXPLANATION: &str = "(untracked kconfig) marks entries with no recorded ktstr.kconfig hash \
598     (pre-dates kconfig hash tracking). Rebuild with: kernel build --force --kernel VERSION \
599     (add --extra-kconfig PATH if the original entry was built with a user fragment).";
600
601/// Decide whether to emit the `(untracked kconfig)` legend under the
602/// `kernel list` table. Parallels [`eol_legend_if_any`] so both
603/// branches are unit-testable without stderr capture.
604pub(crate) fn untracked_legend_if_any(any_untracked: bool) -> Option<&'static str> {
605    if any_untracked {
606        Some(UNTRACKED_KCONFIG_EXPLANATION)
607    } else {
608        None
609    }
610}
611
612/// Explanation of the `(stale kconfig)` tag. Mirrors
613/// [`UNTRACKED_KCONFIG_EXPLANATION`] so the kconfig tag pair
614/// shares one shape — every kconfig-status legend in the
615/// informational trio (EOL / UNTRACKED / STALE) is now a const
616/// surfaced via a `*_legend_if_any` helper. Verbatim wording
617/// preserved from the prior inline `eprintln!` in `kernel_list`
618/// so existing operators see no behavioural change.
619pub const STALE_KCONFIG_EXPLANATION: &str = "warning: entries marked (stale kconfig) were built against a different ktstr.kconfig. \
620     Rebuild with: kernel build --force --kernel <entry version> \
621     (add --extra-kconfig PATH if the entry also carries the (extra kconfig) tag).";
622
623/// Decide whether to emit the `(stale kconfig)` legend under the
624/// `kernel list` table. Mirrors [`eol_legend_if_any`] and
625/// [`untracked_legend_if_any`] so all three informational legends
626/// share one shape (boolean in, `Option<&'static str>` out) and
627/// every branch is unit-testable without stderr capture.
628pub(crate) fn stale_legend_if_any(any_stale: bool) -> Option<&'static str> {
629    if any_stale {
630        Some(STALE_KCONFIG_EXPLANATION)
631    } else {
632        None
633    }
634}
635
636/// Footer emitted by `kernel_list` when at least one entry is
637/// corrupt. Pure function of the cache-root path so tests pin the
638/// exact same string the production path prints — not a hand-copied
639/// duplicate. Extracted alongside [`eol_legend_if_any`] so the
640/// three actionable elements (the `(corrupt)` tag label, the
641/// `kernel clean` variants, and the cache-root path) are enforced
642/// by one source of truth.
643///
644/// Scope-safe wording: callers inspecting the footer in isolation
645/// must not be able to misread `kernel clean --force` as surgical.
646/// The text explicitly spells out "ALL cached entries" and
647/// surfaces `--corrupt-only --force` (the surgical form that leaves
648/// valid entries intact) ahead of the broader `--force` and
649/// `--keep N --force` escalation paths, so an operator with valid
650/// alongside corrupt entries reaches for the safe option first
651/// rather than blowing them all away in a single command.
652///
653/// Design decision: `(corrupt)` is deliberately NOT promoted to a
654/// one-line tag-explanation const in the [`EOL_EXPLANATION`] /
655/// [`UNTRACKED_KCONFIG_EXPLANATION`] / [`STALE_KCONFIG_EXPLANATION`]
656/// legend family. Two constraints drive the decision:
657///
658/// 1. **Runtime cache-root path.** The remediation must surface
659///    the actual cache-root directory so operators know where to
660///    inspect, and a `&'static str` cannot interpolate a runtime
661///    value. [`UNTRACKED_KCONFIG_EXPLANATION`] fits on one line
662///    precisely because its remediation (`kernel build --force
663///    VERSION`) is a literal string with no runtime context;
664///    corrupt's is not, and splitting definition from remediation
665///    is only a fallback — not a solution — since the runtime
666///    path still has to land somewhere adjacent to the tag.
667///
668/// 2. **Duplication avoidance.** The footer's first sentence
669///    already IS the legend — it names the tag, states the
670///    unusable meaning, and enumerates the three corruption modes
671///    (missing metadata, malformed metadata, missing image). A
672///    separate `CORRUPT_EXPLANATION` const would duplicate that
673///    content at two surfaces (const + footer), create drift risk
674///    as either wording is edited, and pay for nothing: a reader
675///    who sees `(corrupt)` in a row and scrolls to the footer
676///    already hits the definition in the first line. Test
677///    `corrupt_footer_is_self_documenting` pins that invariant.
678///
679/// Consistency note: the informational trio (EOL / UNTRACKED /
680/// STALE) all share the const + `*_legend_if_any` shape;
681/// `(corrupt)` is the sole tag whose remediation requires runtime
682/// state (the cache-root path), which is why it stays in the
683/// footer family rather than joining the informational trio.
684///
685/// Command ordering inside the footer: `--corrupt-only --force`
686/// is listed FIRST because it is the zero-risk surgical option
687/// for the common case (a cache with both valid and corrupt
688/// entries — leaves valid alone). The broader `--force` (removes
689/// ALL) and `--keep N --force` (preserves N newest) variants
690/// follow as escalation paths for operators who want to expand
691/// scope beyond corrupt entries alone.
692pub(crate) fn format_corrupt_footer(cache_root: &Path) -> String {
693    format!(
694        "warning: entries marked (corrupt) cannot be used — cached metadata is \
695         missing, malformed, or references a missing image. Inspect the entry \
696         directory under {} to remove it manually, or run \
697         `kernel clean --corrupt-only --force` which removes ONLY corrupt \
698         entries and leaves valid ones intact. For broader cleanup, \
699         `kernel clean --force` removes ALL cached entries (valid and corrupt \
700         alike); `kernel clean --keep N --force` preserves the N newest \
701         cached entries while removing the rest.",
702        cache_root.display(),
703    )
704}
705
706/// Decide whether to emit the corrupt-entry footer under the
707/// `kernel list` table. Mirrors [`eol_legend_if_any`] and
708/// [`untracked_legend_if_any`] so the three "tag → footer" gates
709/// share one shape (count in, `Option<String>` out) and every
710/// branch is unit-testable without stderr capture. The
711/// unconditional emission-only-when-tag-rendered invariant is the
712/// signal that keeps the normal no-corrupt case noise-free; a
713/// regression that unconditionally emitted the footer would show
714/// up as a red test on the `corrupt_count == 0` branch here.
715///
716/// Prepends a `"N corrupt entr{y|ies}. Run `cargo ktstr kernel
717/// clean --corrupt-only` to remove.\n"` summary line before the
718/// full [`format_corrupt_footer`] body so an operator sees the
719/// count and the short remediation FIRST, with the multi-option
720/// escalation detail following. The pluralized form ("entry" vs
721/// "entries") matches the count, making the line read naturally
722/// at both the 1-entry and N>1-entry boundaries.
723pub(crate) fn corrupt_footer_if_any(corrupt_count: usize, cache_root: &Path) -> Option<String> {
724    if corrupt_count == 0 {
725        return None;
726    }
727    let noun = if corrupt_count == 1 {
728        "entry"
729    } else {
730        "entries"
731    };
732    let summary = format!(
733        "{corrupt_count} corrupt {noun}. \
734         Run `cargo ktstr kernel clean --corrupt-only` to remove.",
735    );
736    let detail = format_corrupt_footer(cache_root);
737    Some(format!("{summary}\n{detail}"))
738}
739
740/// ktstr.kconfig embedded at compile time.
741pub const EMBEDDED_KCONFIG: &str = crate::EMBEDDED_KCONFIG;
742
743/// Compute CRC32 of the embedded ktstr.kconfig fragment.
744pub fn embedded_kconfig_hash() -> String {
745    crate::kconfig_hash()
746}
747
748#[cfg(test)]
749mod tests {
750    use super::*;
751
752    /// `eol_legend_if_any` is the sole gate on whether the text
753    /// output under `kernel list` emits the `(EOL)` legend.
754    #[test]
755    fn eol_legend_if_any_branches() {
756        assert_eq!(eol_legend_if_any(true), Some(EOL_EXPLANATION));
757        assert_eq!(eol_legend_if_any(false), None);
758    }
759
760    /// `untracked_legend_if_any` mirrors `eol_legend_if_any`.
761    #[test]
762    fn untracked_legend_if_any_branches() {
763        assert_eq!(
764            untracked_legend_if_any(true),
765            Some(UNTRACKED_KCONFIG_EXPLANATION),
766        );
767        assert_eq!(untracked_legend_if_any(false), None);
768    }
769
770    /// `stale_legend_if_any` completes the kconfig legend pair.
771    #[test]
772    fn stale_legend_if_any_branches() {
773        assert_eq!(stale_legend_if_any(true), Some(STALE_KCONFIG_EXPLANATION));
774        assert_eq!(stale_legend_if_any(false), None);
775    }
776
777    /// `STALE_KCONFIG_EXPLANATION` shape pin.
778    #[test]
779    fn stale_kconfig_explanation_shape() {
780        assert!(STALE_KCONFIG_EXPLANATION.starts_with("warning"));
781        assert!(STALE_KCONFIG_EXPLANATION.contains("(stale kconfig)"));
782        assert!(STALE_KCONFIG_EXPLANATION.contains("different ktstr.kconfig"));
783        assert!(
784            STALE_KCONFIG_EXPLANATION.contains("kernel build --force --kernel <entry version>")
785        );
786    }
787
788    /// `corrupt_footer_if_any` branches.
789    #[test]
790    fn corrupt_footer_if_any_branches() {
791        let root = std::path::Path::new("/tmp/ktstr-cache-test-root");
792        assert_eq!(corrupt_footer_if_any(0, root), None);
793        let one = corrupt_footer_if_any(1, root).expect("positive count must yield Some(footer)");
794        assert!(one.contains("1 corrupt entry."));
795        assert!(one.contains("cargo ktstr kernel clean --corrupt-only"));
796        assert!(one.contains(&format_corrupt_footer(root)));
797        let many = corrupt_footer_if_any(3, root).expect("positive count must yield Some(footer)");
798        assert!(many.contains("3 corrupt entries."));
799    }
800
801    /// Pin design decision: `(corrupt)` first sentence IS the
802    /// legend; the footer carries it AND the operational
803    /// remediation block.
804    #[test]
805    fn corrupt_footer_is_self_documenting() {
806        let root = std::path::Path::new("/tmp/ktstr-cache-test-root");
807        let footer = format_corrupt_footer(root);
808        let first_sentence = footer
809            .split_once(". ")
810            .map(|(head, _)| head)
811            .expect("footer must terminate legend sentence with period-space");
812        assert!(first_sentence.contains("(corrupt)"));
813        assert!(first_sentence.contains("cannot be used"));
814        for reason_token in ["metadata is missing", "malformed", "missing image"] {
815            assert!(
816                first_sentence.contains(reason_token),
817                "legend sentence must enumerate corruption modes; \
818                 expected `{reason_token}`, got: {first_sentence:?}",
819            );
820        }
821        assert!(footer.contains(&root.display().to_string()));
822        assert!(footer.contains("kernel clean --corrupt-only --force"));
823        assert!(footer.contains("kernel clean --force"));
824        assert!(footer.contains("kernel clean --keep N --force"));
825        assert!(footer.contains("ALL cached entries"));
826        let pos_corrupt_only = footer
827            .find("kernel clean --corrupt-only --force")
828            .expect("--corrupt-only must appear");
829        let pos_force = footer
830            .find("kernel clean --force")
831            .expect("--force must appear");
832        let pos_keep = footer
833            .find("kernel clean --keep N --force")
834            .expect("--keep must appear");
835        assert!(pos_corrupt_only < pos_force);
836        assert!(pos_force < pos_keep);
837    }
838
839    /// `DIRTY_TREE_CACHE_SKIP_HINT` shape pin.
840    #[test]
841    fn dirty_tree_cache_skip_hint_shape() {
842        assert!(DIRTY_TREE_CACHE_SKIP_HINT.contains("skipping cache"));
843        assert!(DIRTY_TREE_CACHE_SKIP_HINT.contains("uncommitted changes"));
844        assert!(
845            DIRTY_TREE_CACHE_SKIP_HINT.contains("commit")
846                && DIRTY_TREE_CACHE_SKIP_HINT.contains("stash")
847        );
848    }
849
850    /// `NON_GIT_TREE_CACHE_SKIP_HINT` shape pin.
851    #[test]
852    fn non_git_tree_cache_skip_hint_shape() {
853        assert!(NON_GIT_TREE_CACHE_SKIP_HINT.starts_with("skipping cache"));
854        assert!(NON_GIT_TREE_CACHE_SKIP_HINT.contains("not a git repository"));
855        assert!(NON_GIT_TREE_CACHE_SKIP_HINT.contains("put the source under git"));
856        assert!(NON_GIT_TREE_CACHE_SKIP_HINT.contains("kernel build --kernel <version>"));
857        assert!(NON_GIT_TREE_CACHE_SKIP_HINT.contains("kernel build --kernel git+URL#branch=NAME"));
858        assert!(!NON_GIT_TREE_CACHE_SKIP_HINT.contains("stash"));
859        assert!(!NON_GIT_TREE_CACHE_SKIP_HINT.contains("commit"));
860    }
861
862    /// `untracked_legend_names_the_tag_word` — legend mentions tag.
863    #[test]
864    fn untracked_legend_names_the_tag_word() {
865        assert!(UNTRACKED_KCONFIG_EXPLANATION.contains("(untracked kconfig)"));
866    }
867
868    /// kernel_clean rejects `--keep` together with `--corrupt-only`.
869    #[test]
870    fn kernel_clean_rejects_corrupt_only_with_keep() {
871        use clap::Parser as _;
872        #[derive(clap::Parser, Debug)]
873        struct TestCli {
874            #[command(subcommand)]
875            cmd: KernelCommand,
876        }
877        let err = TestCli::try_parse_from(["prog", "clean", "--keep", "2", "--corrupt-only"])
878            .expect_err("--keep together with --corrupt-only must fail parsing");
879        let msg = err.to_string();
880        assert!(
881            msg.to_ascii_lowercase().contains("cannot be used with")
882                || msg.to_ascii_lowercase().contains("conflict"),
883            "clap error must surface the conflict between --keep and --corrupt-only, got: {msg}",
884        );
885    }
886
887    #[test]
888    fn kernel_clean_accepts_corrupt_only_alone() {
889        use clap::Parser as _;
890        #[derive(clap::Parser, Debug)]
891        struct TestCli {
892            #[command(subcommand)]
893            cmd: KernelCommand,
894        }
895        let parsed = TestCli::try_parse_from(["prog", "clean", "--corrupt-only"])
896            .expect("--corrupt-only without --keep must parse cleanly");
897        match parsed.cmd {
898            KernelCommand::Clean {
899                keep,
900                force,
901                corrupt_only,
902            } => {
903                assert_eq!(keep, None);
904                assert!(!force);
905                assert!(corrupt_only);
906            }
907            other => panic!("expected KernelCommand::Clean, got {other:?}"),
908        }
909    }
910
911    /// `kernel build --cpu-cap N` parses to `Build { cpu_cap: Some(N) }`.
912    #[test]
913    fn kernel_build_parses_cpu_cap_without_extra_flags() {
914        use clap::Parser as _;
915        #[derive(clap::Parser, Debug)]
916        struct TestCli {
917            #[command(subcommand)]
918            cmd: KernelCommand,
919        }
920        let parsed =
921            TestCli::try_parse_from(["prog", "build", "--kernel", "6.14.2", "--cpu-cap", "4"])
922                .expect("kernel build --cpu-cap N must parse");
923        match parsed.cmd {
924            KernelCommand::Build {
925                cpu_cap, kernel, ..
926            } => {
927                assert_eq!(cpu_cap, Some(4));
928                assert_eq!(kernel.as_deref(), Some("6.14.2"));
929            }
930            other => panic!("expected KernelCommand::Build, got {other:?}"),
931        }
932    }
933
934    /// `kernel build` without `--cpu-cap` parses with cpu_cap: None.
935    #[test]
936    fn kernel_build_without_cpu_cap_defaults_to_none() {
937        use clap::Parser as _;
938        #[derive(clap::Parser, Debug)]
939        struct TestCli {
940            #[command(subcommand)]
941            cmd: KernelCommand,
942        }
943        let parsed = TestCli::try_parse_from(["prog", "build", "--kernel", "6.14.2"])
944            .expect("kernel build without --cpu-cap must parse");
945        match parsed.cmd {
946            KernelCommand::Build { cpu_cap, .. } => {
947                assert_eq!(cpu_cap, None, "no --cpu-cap must produce None, not Some(0)");
948            }
949            other => panic!("expected KernelCommand::Build, got {other:?}"),
950        }
951    }
952
953    /// Bare `kernel build` (no `--kernel`) parses to `Build { kernel:
954    /// None }` — the latest-stable default. Pins the None default at the
955    /// parse layer so the dispatch's `None => latest stable` arm stays
956    /// reachable.
957    #[test]
958    fn kernel_build_without_kernel_defaults_to_none() {
959        use clap::Parser as _;
960        #[derive(clap::Parser, Debug)]
961        struct TestCli {
962            #[command(subcommand)]
963            cmd: KernelCommand,
964        }
965        let parsed =
966            TestCli::try_parse_from(["prog", "build"]).expect("bare kernel build must parse");
967        match parsed.cmd {
968            KernelCommand::Build { kernel, .. } => {
969                assert_eq!(
970                    kernel, None,
971                    "no --kernel must produce None (the latest-stable default)"
972                );
973            }
974            other => panic!("expected KernelCommand::Build, got {other:?}"),
975        }
976    }
977
978    /// `kernel build --cpu-cap 0` passes clap (validation runs at runtime).
979    #[test]
980    fn kernel_build_cpu_cap_zero_passes_clap() {
981        use clap::Parser as _;
982        #[derive(clap::Parser, Debug)]
983        struct TestCli {
984            #[command(subcommand)]
985            cmd: KernelCommand,
986        }
987        let parsed =
988            TestCli::try_parse_from(["prog", "build", "--kernel", "6.14.2", "--cpu-cap", "0"])
989                .expect("clap-level parse must accept 0; runtime validation rejects");
990        match parsed.cmd {
991            KernelCommand::Build { cpu_cap, .. } => {
992                assert_eq!(cpu_cap, Some(0));
993            }
994            other => panic!("expected KernelCommand::Build, got {other:?}"),
995        }
996    }
997
998    /// `kernel build --skip-sha256` parses to
999    /// `Build { skip_sha256: true, .. }`. Pins the bypass flag's
1000    /// wire path: a regression that dropped the field would surface
1001    /// as a parse rejection.
1002    #[test]
1003    fn kernel_build_parses_skip_sha256() {
1004        use clap::Parser as _;
1005        #[derive(clap::Parser, Debug)]
1006        struct TestCli {
1007            #[command(subcommand)]
1008            cmd: KernelCommand,
1009        }
1010        let parsed =
1011            TestCli::try_parse_from(["prog", "build", "--kernel", "6.14.2", "--skip-sha256"])
1012                .expect("kernel build --skip-sha256 must parse");
1013        match parsed.cmd {
1014            KernelCommand::Build { skip_sha256, .. } => {
1015                assert!(
1016                    skip_sha256,
1017                    "--skip-sha256 must round-trip as true so the \
1018                     downstream download path bypasses sha256sums.asc"
1019                );
1020            }
1021            other => panic!("expected KernelCommand::Build, got {other:?}"),
1022        }
1023    }
1024
1025    /// `kernel build` without `--skip-sha256` parses with the safe
1026    /// default `skip_sha256: false`. Pins the no-flag path so a
1027    /// regression that flipped the default to true (silently
1028    /// disabling checksum verification on every download) surfaces
1029    /// as a test failure.
1030    #[test]
1031    fn kernel_build_without_skip_sha256_defaults_to_false() {
1032        use clap::Parser as _;
1033        #[derive(clap::Parser, Debug)]
1034        struct TestCli {
1035            #[command(subcommand)]
1036            cmd: KernelCommand,
1037        }
1038        let parsed = TestCli::try_parse_from(["prog", "build", "--kernel", "6.14.2"])
1039            .expect("kernel build without --skip-sha256 must parse");
1040        match parsed.cmd {
1041            KernelCommand::Build { skip_sha256, .. } => {
1042                assert!(
1043                    !skip_sha256,
1044                    "no --skip-sha256 must produce false (verification \
1045                     enabled by default); got skip_sha256={skip_sha256}"
1046                );
1047            }
1048            other => panic!("expected KernelCommand::Build, got {other:?}"),
1049        }
1050    }
1051
1052    /// `KERNEL_LIST_LONG_ABOUT` drives `kernel list --help` and must
1053    /// expose the `--json` output contract so scripted consumers can
1054    /// discover the schema from the terminal alone. Pins:
1055    /// 1. the `(EOL)` legend text appears verbatim at the head;
1056    /// 2. every top-level wrapper field appears;
1057    /// 3. every valid-entry field appears;
1058    /// 4. each `Option<T>` field carries a `(nullable)` tag;
1059    /// 5. each `KernelSource` variant tag and `kconfig_status`
1060    ///    enum value is documented.
1061    #[test]
1062    fn kernel_list_long_about_exposes_json_schema() {
1063        assert!(
1064            KERNEL_LIST_LONG_ABOUT.starts_with(EOL_EXPLANATION),
1065            "KERNEL_LIST_LONG_ABOUT must embed EOL_EXPLANATION verbatim at its \
1066             head so the --help and post-table legend share one source of \
1067             truth; got: {KERNEL_LIST_LONG_ABOUT:?}",
1068        );
1069
1070        for wrapper_field in [
1071            "current_ktstr_kconfig_hash",
1072            "active_prefixes_fetch_error",
1073            "entries",
1074        ] {
1075            assert!(
1076                KERNEL_LIST_LONG_ABOUT.contains(wrapper_field),
1077                "KERNEL_LIST_LONG_ABOUT must mention top-level wrapper field \
1078                 `{wrapper_field}` so scripted consumers discover the \
1079                 schema without `cargo doc`",
1080            );
1081        }
1082
1083        for valid_entry_field in [
1084            "key",
1085            "path",
1086            "version",
1087            "source",
1088            "arch",
1089            "built_at",
1090            "ktstr_kconfig_hash",
1091            "kconfig_status",
1092            "eol",
1093            "config_hash",
1094            "image_name",
1095            "image_path",
1096            "has_vmlinux",
1097            "vmlinux_stripped",
1098            "git_hash",
1099            "\"ref\"",
1100            "source_tree_path",
1101        ] {
1102            assert!(
1103                KERNEL_LIST_LONG_ABOUT.contains(valid_entry_field),
1104                "KERNEL_LIST_LONG_ABOUT must mention valid-entry JSON \
1105                 field `{valid_entry_field}`",
1106            );
1107        }
1108
1109        assert!(
1110            KERNEL_LIST_LONG_ABOUT.contains("error"),
1111            "KERNEL_LIST_LONG_ABOUT must mention corrupt-entry JSON \
1112             field `error` so consumers know the corrupt-entry shape",
1113        );
1114
1115        for nullable_field in ["version", "ktstr_kconfig_hash", "config_hash"] {
1116            let marker = format!("{nullable_field} (nullable)");
1117            assert!(
1118                KERNEL_LIST_LONG_ABOUT.contains(&marker),
1119                "KERNEL_LIST_LONG_ABOUT must mark `{nullable_field}` \
1120                 as `(nullable)` (expected substring `{marker}`)",
1121            );
1122        }
1123
1124        for source_variant_tag in ["\"tarball\"", "\"git\"", "\"local\""] {
1125            assert!(
1126                KERNEL_LIST_LONG_ABOUT.contains(source_variant_tag),
1127                "KERNEL_LIST_LONG_ABOUT must list source variant tag \
1128                 `{source_variant_tag}`",
1129            );
1130        }
1131
1132        for status_variant in ["\"matches\"", "\"stale\"", "\"untracked\""] {
1133            assert!(
1134                KERNEL_LIST_LONG_ABOUT.contains(status_variant),
1135                "KERNEL_LIST_LONG_ABOUT must list kconfig_status variant \
1136                 `{status_variant}`",
1137            );
1138        }
1139    }
1140
1141    /// Pin that the `#[command(long_about = KERNEL_LIST_LONG_ABOUT)]`
1142    /// attribute on `KernelCommand::List` is wired through clap.
1143    #[test]
1144    fn kernel_list_long_about_wired_via_clap() {
1145        use clap::CommandFactory as _;
1146        #[derive(clap::Parser, Debug)]
1147        struct TestCli {
1148            #[command(subcommand)]
1149            cmd: KernelCommand,
1150        }
1151        let cmd = TestCli::command();
1152        let list = cmd
1153            .find_subcommand("list")
1154            .expect("clap must register a `list` subcommand on KernelCommand");
1155        let long_about = list
1156            .get_long_about()
1157            .expect("`list` subcommand must have a long_about set")
1158            .to_string();
1159        assert_eq!(long_about, KERNEL_LIST_LONG_ABOUT);
1160    }
1161
1162    /// `kernel build --help` must surface the `--skip-sha256` flag
1163    /// with documentation covering the no-op semantics on
1164    /// `--kernel <path>` / git+ / RC tarballs and the
1165    /// security-sensitive bypass-warning contract. Without these
1166    /// hints an operator setting the flag would have no way to
1167    /// know whether their fetch actually bypassed verification.
1168    #[test]
1169    fn kernel_build_help_documents_skip_sha256_no_op_semantics() {
1170        use clap::CommandFactory as _;
1171        #[derive(clap::Parser, Debug)]
1172        struct TestCli {
1173            #[command(subcommand)]
1174            cmd: KernelCommand,
1175        }
1176        let cmd = TestCli::command();
1177        let build = cmd
1178            .find_subcommand("build")
1179            .expect("clap must register a `build` subcommand on KernelCommand");
1180        // Locate the --skip-sha256 arg and read its long help.
1181        let arg = build
1182            .get_arguments()
1183            .find(|a| a.get_long() == Some("skip-sha256"))
1184            .expect("kernel build must register --skip-sha256 with clap");
1185        let help = arg
1186            .get_long_help()
1187            .or_else(|| arg.get_help())
1188            .map(|s| s.to_string())
1189            .expect("--skip-sha256 must carry help text");
1190        // Pins the user-facing semantics so a future doc rewrite
1191        // cannot drop the no-op clauses or the warning contract.
1192        assert!(
1193            help.contains("--kernel <path>"),
1194            "--skip-sha256 help must call out the --kernel <path> no-op so \
1195             operators don't expect bypass on local-source builds: {help}"
1196        );
1197        assert!(
1198            help.contains("git+"),
1199            "--skip-sha256 help must call out the git-source no-op so \
1200             operators don't expect bypass on git-source builds: {help}"
1201        );
1202        assert!(
1203            help.contains("RC"),
1204            "--skip-sha256 help must call out the RC-tarball no-op \
1205             (RC archives have no upstream manifest, so the flag is \
1206             a no-op there): {help}"
1207        );
1208        assert!(
1209            help.contains("warning"),
1210            "--skip-sha256 help must mention the bypass warning so \
1211             ops know the lost guarantee surfaces in the same channel \
1212             as verification-success lines: {help}"
1213        );
1214    }
1215}