CodeSampleX

Exemplo

clap 4.6.6: Assert clap 4 builder API traps: downcast panics on get_flag/get_one type mismatches, get_many vs Vec downcast for Append, num_args(0..=1) requirement for default_missing_value, and argv[0] program name consumption in try_get_matches_from

Amostra verificada para cargo clap 4.6.6: Assert clap 4 builder API traps: downcast panics on get_flag/get_one type mismatches, get_many vs Vec downcast for…

sha256:a58f6f21c612813f9bfb5172344901a8e9bacf1f11dea240f82a210daf63bc14

Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu. Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas. MIT-0

Evidência de execução

O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.

Base da evidência
Contrato assinado aprovado
Recibos de verificação
3
Chaves de assinatura que o compilaram
3
Ambiente declarado rust linux x64 rust rust cargo

Ambientes das execuções de verificação

Ambiente Contrato Etapas Execução
rust 1 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1
2026-08-16
rust 1 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1
2026-08-18
rust 1 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1rust:1-alpine@sha256:a10e64dd139b…
2026-09-08

Caso

HOW
Objetivo
Assert clap 4 builder API traps: downcast panics on get_flag/get_one type mismatches, get_many vs Vec downcast for Append, num_args(0..=1) requirement for default_missing_value, and argv[0] program name consumption in try_get_matches_from
Pacotes
Símbolos
  • clap::Command::try_get_matches_from
  • clap::Arg::default_missing_value
  • clap::Arg::num_args
  • clap::ArgAction::Append
  • clap::ArgAction::Count
  • clap::ArgMatches::get_flag
  • clap::ArgMatches::get_many
  • clap::ArgMatches::get_one
  • clap::ArgMatches::remove_one
Ambiente
rust
Criado
2026-08-16T08:02:26Z

Contrato

  1. assert get_flag returns primitive bool while get_one::<bool> returns Option<&bool> with Some(&false) when an ArgAction::SetTrue flag is omitted
  2. assert calling get_flag on a string option or Count arg panics with a downcast error rather than returning false
  3. assert get_one::<u32> on a value_parser!(u16) argument panics with downcast mismatch instead of coercing
  4. assert get_one::<Vec<String>> on ArgAction::Append panics with downcast error and that get_many::<String> must be used to iterate values
  5. assert default_missing_value without num_args(0..=1) fails with ErrorKind::InvalidValue on bare flags, and that num_args(0..=1) is required for optional-value flags
  6. assert try_get_matches_from consumes the 0-th element as argv[0] binary name, failing required positional arguments if the binary name is omitted
  7. assert remove_one takes ownership returning Option<T> and causes subsequent get_one calls to return None

Arquivos

  • Cargo.lock
  • Cargo.toml
  • NOTES.md
  • csx.json
  • src/lib.rs
  • tests/contract.rs

Baixar o artefato de código-fonte (tar.gz)

Código-fonte

Cargo.lock
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4

[[package]]
name = "anstream"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
dependencies = [
 "anstyle",
 "anstyle-parse",
 "anstyle-query",
 "anstyle-wincon",
 "colorchoice",
 "is_terminal_polyfill",
 "utf8parse",
]

[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"

[[package]]
name = "anstyle-parse"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
dependencies = [
 "utf8parse",
]

[[package]]
name = "anstyle-query"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
 "windows-sys",
]

[[package]]
name = "anstyle-wincon"
version = "3.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
 "anstyle",
 "once_cell_polyfill",
 "windows-sys",
]

[[package]]
name = "cargo-clap-api"
version = "1.0.0"
dependencies = [
 "clap",
]

[[package]]
name = "clap"
version = "4.6.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "473c7e07f409a8d772161724aa8db6a765a2532a70f9667eeb7b49d3d02fbdca"
dependencies = [
 "clap_builder",
]

[[package]]
name = "clap_builder"
version = "4.6.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b48fea5a88e9ae728a2dcbedbfc0e730f7d60da42e1cb049a83c9fb8b789889"
dependencies = [
 "anstream",
 "anstyle",
 "clap_lex",
 "strsim",
]

[[package]]
name = "clap_lex"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"

[[package]]
name = "colorchoice"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"

[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"

[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"

[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"

[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"

[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"

[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
 "windows-link",
]
Cargo.toml
[package]
name = "cargo-clap-api"
version = "1.0.0"
edition = "2021"
license = "MIT-0"

[dependencies]
clap = "4.6.5"
NOTES.md
# Notes on clap Builder API & ArgMatches Contract

## What `search_known_solution` answered
`search_known_solution` returned existing sample `sha256:6e0aceb749a7c19cc2aa7a185f5f9cac427fedb08e50c9afc51b0c69de42d116`, which covers clap 4 derive attribute migrations (`#[command]` vs `#[arg]`), `try_parse_from`, and `ValueEnum`. This sample targets the non-derive builder API and `ArgMatches` downcasting traps instead.

## What a model would have written instead
A model writing clap 4 builder code would typically retrieve repeated options via `matches.get_one::<Vec<String>>("items")`, query flags on string/count arguments with `matches.get_flag(...)`, specify `Arg::default_missing_value(...)` without setting `.num_args(0..=1)`, and pass argument slices without `argv[0]` to `try_get_matches_from`.

## How the wrong version fails
- `matches.get_one::<Vec<String>>("items")` on `ArgAction::Append` and `matches.get_flag` on non-bool args fail loudly at runtime with panic `Mismatch between definition and access (...): Could not downcast to ...`.
- `default_missing_value` without `.num_args(0..=1)` fails loudly on bare flag input with `ErrorKind::InvalidValue` (error: a value is required for '--flag <flag>' but none was supplied).
- Passing args to `try_get_matches_from` without a binary name fails loudly with `ErrorKind::MissingRequiredArgument` (as the first argument is silently consumed as `argv[0]`), or silently treats flags as the binary name.
csx.json
{"case":{"caseId":"case:sha256:f7c81acf1fc9a72ebe2f9255219608d14763d3664247ae49249a7646e0de6ea0","contract":["assert get_flag returns primitive bool while get_one::\u003cbool\u003e returns Option\u003c\u0026bool\u003e with Some(\u0026false) when an ArgAction::SetTrue flag is omitted","assert calling get_flag on a string option or Count arg panics with a downcast error rather than returning false","assert get_one::\u003cu32\u003e on a value_parser!(u16) argument panics with downcast mismatch instead of coercing","assert get_one::\u003cVec\u003cString\u003e\u003e on ArgAction::Append panics with downcast error and that get_many::\u003cString\u003e must be used to iterate values","assert default_missing_value without num_args(0..=1) fails with ErrorKind::InvalidValue on bare flags, and that num_args(0..=1) is required for optional-value flags","assert try_get_matches_from consumes the 0-th element as argv[0] binary name, failing required positional arguments if the binary name is omitted","assert remove_one takes ownership returning Option\u003cT\u003e and causes subsequent get_one calls to return None"],"goal":"Assert clap 4 builder API traps: downcast panics on get_flag/get_one type mismatches, get_many vs Vec downcast for Append, num_args(0..=1) requirement for default_missing_value, and argv[0] program name consumption in try_get_matches_from","kind":"HOW","packages":["pkg:cargo/clap@4.6.6"],"schemaVersion":1,"symbols":["clap::Command::try_get_matches_from","clap::Arg::default_missing_value","clap::Arg::num_args","clap::ArgAction::Append","clap::ArgAction::Count","clap::ArgMatches::get_flag","clap::ArgMatches::get_many","clap::ArgMatches::get_one","clap::ArgMatches::remove_one"]},"contractCommand":["cargo","test","--offline"],"environment":{"arch":"x64","ecosystem":"cargo","executionContext":"rust","language":"rust","os":"linux","packageManager":"cargo","runtime":"rust","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/clap@4.6.6"],"schemaVersion":1,"symbols":["clap::Command::try_get_matches_from","clap::Arg::default_missing_value","clap::Arg::num_args","clap::ArgAction::Append","clap::ArgAction::Count","clap::ArgMatches::get_flag","clap::ArgMatches::get_many","clap::ArgMatches::get_one","clap::ArgMatches::remove_one"],"verifierAdapter":"cargo@1"}
src/lib.rs
//! Contract test demonstrating Clap 4 Builder API and ArgMatches typing traps.

pub fn parse_app_args<I, T>(args: I) -> Result<clap::ArgMatches, clap::Error>
where
    I: IntoIterator<Item = T>,
    T: Into<std::ffi::OsString> + Clone,
{
    clap::Command::new("demo")
        .arg(clap::Arg::new("verbose").short('v').long("verbose").action(clap::ArgAction::SetTrue))
        .arg(clap::Arg::new("count").short('c').action(clap::ArgAction::Count))
        .arg(clap::Arg::new("items").short('i').action(clap::ArgAction::Append))
        .arg(
            clap::Arg::new("log")
                .long("log")
                .num_args(0..=1)
                .default_value("off")
                .default_missing_value("debug"),
        )
        .try_get_matches_from(args)
}
tests/contract.rs
use clap::error::ErrorKind;
use clap::{value_parser, Arg, ArgAction, Command};
use std::panic::AssertUnwindSafe;

#[test]
fn test_boolean_flag_get_flag_and_get_one() {
    let cmd = Command::new("demo")
        .arg(Arg::new("verbose").short('v').long("verbose").action(ArgAction::SetTrue))
        .arg(Arg::new("dry-run").long("dry-run").action(ArgAction::SetTrue));

    let matches = cmd.clone().try_get_matches_from(["demo", "-v"]).unwrap();

    // get_flag returns primitive bool
    assert_eq!(matches.get_flag("verbose"), true);
    assert_eq!(matches.get_flag("dry-run"), false);

    // get_one::<bool> returns Option<&bool> (Some(&true) when present, Some(&false) when absent)
    assert_eq!(matches.get_one::<bool>("verbose"), Some(&true));
    assert_eq!(matches.get_one::<bool>("dry-run"), Some(&false));
}

#[test]
fn test_type_downcast_panics() {
    let cmd = Command::new("demo")
        .arg(Arg::new("name").long("name"))
        .arg(Arg::new("count").short('c').action(ArgAction::Count))
        .arg(Arg::new("port").long("port").value_parser(value_parser!(u16)));

    let matches = cmd
        .try_get_matches_from(["demo", "--name", "alice", "-c", "-c", "--port", "8080"])
        .unwrap();

    // TRAP: get_flag on a string argument panics because String cannot downcast to bool
    let flag_on_string = std::panic::catch_unwind(AssertUnwindSafe(|| {
        matches.get_flag("name");
    }));
    assert!(flag_on_string.is_err(), "get_flag on string option must panic");

    // TRAP: get_flag or get_one::<bool> on Count panics because Count stores u8, not bool
    let flag_on_count = std::panic::catch_unwind(AssertUnwindSafe(|| {
        matches.get_flag("count");
    }));
    assert!(flag_on_count.is_err(), "get_flag on Count must panic");
    assert_eq!(matches.get_count("count"), 2);

    // TRAP: get_one with mismatched integer type (u32 vs u16) panics
    let wrong_int = std::panic::catch_unwind(AssertUnwindSafe(|| {
        matches.get_one::<u32>("port");
    }));
    assert!(wrong_int.is_err(), "get_one::<u32> on u16 value_parser must panic");
    assert_eq!(matches.get_one::<u16>("port"), Some(&8080u16));
}

#[test]
fn test_append_action_get_many_vs_vec_panic() {
    let cmd = Command::new("demo")
        .arg(Arg::new("items").short('i').long("item").action(ArgAction::Append));

    let matches = cmd
        .try_get_matches_from(["demo", "-i", "first", "--item", "second"])
        .unwrap();

    // TRAP: get_one::<Vec<String>> panics because items are stored individually as String
    let vec_downcast = std::panic::catch_unwind(AssertUnwindSafe(|| {
        matches.get_one::<Vec<String>>("items");
    }));
    assert!(vec_downcast.is_err(), "get_one::<Vec<String>> on Append must panic");

    // Correct API: get_many::<String> returns an iterator over &String
    let collected: Vec<&str> = matches
        .get_many::<String>("items")
        .unwrap()
        .map(|s| s.as_str())
        .collect();
    assert_eq!(collected, vec!["first", "second"]);
}

#[test]
fn test_default_missing_value_num_args_requirement() {
    // TRAP: default_missing_value without num_args(0..=1) FAILS when --opt is given without a value
    let broken_cmd = Command::new("demo")
        .arg(Arg::new("opt").long("opt").default_missing_value("fallback"));
    let err = broken_cmd.try_get_matches_from(["demo", "--opt"]).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidValue);

    // Correct pattern: num_args(0..=1) enables default_missing_value for bare flag occurrences
    let correct_cmd = Command::new("demo").arg(
        Arg::new("opt")
            .long("opt")
            .num_args(0..=1)
            .default_value("default")
            .default_missing_value("fallback"),
    );

    // Case 1: Flag omitted -> default_value
    let m_omitted = correct_cmd.clone().try_get_matches_from(["demo"]).unwrap();
    assert_eq!(m_omitted.get_one::<String>("opt").map(|s| s.as_str()), Some("default"));

    // Case 2: Bare flag passed -> default_missing_value
    let m_bare = correct_cmd.clone().try_get_matches_from(["demo", "--opt"]).unwrap();
    assert_eq!(m_bare.get_one::<String>("opt").map(|s| s.as_str()), Some("fallback"));

    // Case 3: Explicit value passed -> provided value
    let m_val = correct_cmd.try_get_matches_from(["demo", "--opt", "custom"]).unwrap();
    assert_eq!(m_val.get_one::<String>("opt").map(|s| s.as_str()), Some("custom"));
}

#[test]
fn test_try_get_matches_from_consumes_argv0() {
    let cmd = Command::new("demo").arg(Arg::new("file").required(true));

    // TRAP: try_get_matches_from treats the first element as binary name ($0).
    // Passing ["file.txt"] causes "file.txt" to be treated as binary name, reporting missing required arg.
    let err = cmd.clone().try_get_matches_from(["file.txt"]).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::MissingRequiredArgument);

    let ok = cmd.try_get_matches_from(["demo", "file.txt"]).unwrap();
    assert_eq!(ok.get_one::<String>("file").map(|s| s.as_str()), Some("file.txt"));
}

#[test]
fn test_remove_one_ownership_and_invalidation() {
    let mut matches = Command::new("demo")
        .arg(Arg::new("token").long("token"))
        .try_get_matches_from(["demo", "--token", "secret123"])
        .unwrap();

    let owned_token: Option<String> = matches.remove_one::<String>("token");
    assert_eq!(owned_token, Some("secret123".to_string()));
    // Once removed, the value is no longer accessible via get_one
    assert_eq!(matches.get_one::<String>("token"), None);
}

Seeder de origem

csx-seed