Skip to main content

Module clap_shim

Module clap_shim 

Source
Expand description

Bridge between clap-derive command structs and mkit’s sysexits contract.

mkit’s top-level dispatcher in lib.rs hands each subcommand a &[String] of remaining argv and expects a u8 exit code back. When a subcommand opts into clap-derive parsing, it gets two choices about how to handle parse errors:

  1. Map the error kind to the correct sysexit (USAGE for missing args, DATAERR for invalid values, etc.) so shell scripts that do mkit foo … || handle see the right code.
  2. Print the error to stderr in clap’s standard format so users see consistent diagnostics across commands.

This module does both. The typical migrated command looks like:

use crate::clap_shim;
use clap::Parser;

#[derive(Parser, Debug)]
struct Opts {
    #[arg(short, long)]
    verbose: bool,
}

pub fn run(args: &[String]) -> u8 {
    let opts = match clap_shim::parse::<Opts>("mkit my-cmd", args) {
        Ok(o) => o,
        Err(code) => return code,
    };
    // ...real work using `opts`
}

§Exit-code mapping

clap ErrorKindmkit exit code
InvalidValueDATAERR (65)
ValueValidationDATAERR (65)
IoNOINPUT (66)
DisplayHelpOK (0)
DisplayVersionOK (0)
everything else (missing arg, unknown flag, …)USAGE (64)

Help / version requests are NOT treated as errors — clap prints them and we exit 0.

Functions§

map_clap_error_kind
Map a clap::ErrorKind to a mkit sysexit. Kept as a small freestanding function so unit tests can pin the mapping without running clap.
parse
Parse args (everything after argv[1] from the dispatcher) into P. On success, returns the parsed struct. On error, prints clap’s formatted diagnostic to stdout (for help/version) or stderr (for usage / value errors) and returns the matching sysexits code so the caller can return it.
report_clap_error
Write a clap error to the appropriate stream and return the matching sysexits code. Public so commands that hand-roll their own clap::Command (rather than using the derive form) can reuse the mapping.