CodeSampleX

Exemple

clap 4.6.7: clap::Error

Échantillon vérifié pour cargo clap 4.6.7: clap::Error. Le contrat s'est exécuté sur rust 1 · linux alpine/x64 · docker et a réussi.

sha256:8c2306d7d51e8dfc1cdc72eb0f34c91f48d332777ec8128fc1692290d5633a86

Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré. Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes. MIT-0

Preuves d'exécution

L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.

Base de preuve
Contrat signé réussi
Reçus de vérification
1
Clés de signature qui l’ont compilé
1
Environnement déclaré linux x64 cargo

Environnements des exécutions de vérification

Environnement Contrat Étapes Exécution
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-10-22

Cas

HOW
Objectif
verify clap::Error in pkg:cargo/clap@4.6.7
Paquets
Symboles
  • clap::Error
Créé
2026-10-22T15:55:43Z

Contrat

  1. clap::Error::raw(ErrorKind::ValueValidation, msg) constructs an Error with kind() == ErrorKind::ValueValidation, use_stderr() == true, and exit_code() == 2
  2. Command::try_get_matches_from returns Err(clap::Error) with ErrorKind::UnknownArgument and InvalidArg context when given an unrecognized flag
  3. Command::try_get_matches_from returns Err(clap::Error) with ErrorKind::ValueValidation when a typed argument fails value_parser validation
  4. Command::try_get_matches_from returns Err(clap::Error) with ErrorKind::DisplayHelp, use_stderr() == false, and exit_code() == 0 on --help
  5. Command::error(ErrorKind::ArgumentConflict, msg) produces a formatted clap::Error whose render() output includes the message

Fichiers

  • Cargo.lock
  • Cargo.toml
  • PROMPT.md
  • csx.json
  • spec.json
  • src/lib.rs
  • test/contract.rs

Télécharger l’artefact source (tar.gz)

Code source

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 = "clap"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946"
dependencies = [
 "clap_builder",
]

[[package]]
name = "clap-error-sample"
version = "0.1.0"
dependencies = [
 "clap",
]

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

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

[[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 = "clap-error-sample"
version = "0.1.0"
edition = "2021"
publish = false

[[bin]]
name = "clap-error-sample"
path = "test/contract.rs"

[dependencies]
clap = "=4.6.7"
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify clap::Error in pkg:cargo/clap@4.6.7
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/clap@4.6.7
Demonstrate these symbols/APIs:
  - clap::Error

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:93e938ef9273b61bbe718c048a9656e0e3a97cadd03b5d235b2205b0fbb7b8fe","contract":["clap::Error::raw(ErrorKind::ValueValidation, msg) constructs an Error with kind() == ErrorKind::ValueValidation, use_stderr() == true, and exit_code() == 2","Command::try_get_matches_from returns Err(clap::Error) with ErrorKind::UnknownArgument and InvalidArg context when given an unrecognized flag","Command::try_get_matches_from returns Err(clap::Error) with ErrorKind::ValueValidation when a typed argument fails value_parser validation","Command::try_get_matches_from returns Err(clap::Error) with ErrorKind::DisplayHelp, use_stderr() == false, and exit_code() == 0 on --help","Command::error(ErrorKind::ArgumentConflict, msg) produces a formatted clap::Error whose render() output includes the message"],"goal":"verify clap::Error in pkg:cargo/clap@4.6.7","kind":"HOW","packages":["pkg:cargo/clap@4.6.7"],"schemaVersion":1,"symbols":["clap::Error"]},"contractCommand":["cargo","run","--offline"],"environment":{"arch":"x64","ecosystem":"cargo","os":"linux","packageManager":"cargo","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/clap@4.6.7"],"schemaVersion":1,"subject":"pkg:cargo/clap@4.6.7","symbols":["clap::Error"],"verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify clap::Error in pkg:cargo/clap@4.6.7",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/clap@4.6.7"
  ],
  "symbols": [
    "clap::Error"
  ]
}
src/lib.rs
use clap::error::{ContextKind, ContextValue, ErrorKind};
use clap::{Arg, Command, Error};

pub fn build_command() -> Command {
    Command::new("tool")
        .version("1.0.0")
        .arg(
            Arg::new("port")
                .long("port")
                .required(true)
                .value_parser(clap::value_parser!(u16)),
        )
}

pub fn create_raw_error(kind: ErrorKind, message: &str) -> Error {
    Error::raw(kind, message)
}

pub fn parse_args(args: &[&str]) -> Result<u16, Error> {
    let cmd = build_command();
    let matches = cmd.try_get_matches_from(args)?;
    let port = *matches.get_one::<u16>("port").expect("required arg");
    Ok(port)
}

pub fn attach_command_error(kind: ErrorKind, message: &str) -> Error {
    let mut cmd = build_command();
    cmd.error(kind, message)
}

pub fn extract_invalid_arg(err: &Error) -> Option<String> {
    match err.get(ContextKind::InvalidArg) {
        Some(ContextValue::String(s)) => Some(s.clone()),
        _ => None,
    }
}
test/contract.rs
use clap::error::ErrorKind;
use clap::Error;
use clap_error_sample::{
    attach_command_error, create_raw_error, extract_invalid_arg, parse_args,
};

fn main() {
    // 1. Direct construction with clap::Error::raw
    let raw_err: Error = create_raw_error(ErrorKind::ValueValidation, "invalid port range\n");
    assert_eq!(raw_err.kind(), ErrorKind::ValueValidation);
    assert!(raw_err.use_stderr());
    assert_eq!(raw_err.exit_code(), 2);
    assert!(raw_err.to_string().contains("invalid port range"));

    // 2. Parsing unknown argument produces clap::Error with ErrorKind::UnknownArgument
    let unknown_err = parse_args(&["tool", "--unknown"]).expect_err("should fail on unknown flag");
    assert_eq!(unknown_err.kind(), ErrorKind::UnknownArgument);
    assert!(unknown_err.use_stderr());
    assert_eq!(unknown_err.exit_code(), 2);
    assert_eq!(
        extract_invalid_arg(&unknown_err).as_deref(),
        Some("--unknown")
    );

    // 3. Parsing invalid value produces clap::Error with ErrorKind::ValueValidation
    let val_err =
        parse_args(&["tool", "--port", "not-a-number"]).expect_err("should fail on non-u16");
    assert_eq!(val_err.kind(), ErrorKind::ValueValidation);
    assert!(val_err.use_stderr());
    assert_eq!(val_err.exit_code(), 2);

    // 4. Help request produces clap::Error with ErrorKind::DisplayHelp (stdout, exit code 0)
    let help_err = parse_args(&["tool", "--help"]).expect_err("help exits via clap::Error");
    assert_eq!(help_err.kind(), ErrorKind::DisplayHelp);
    assert!(!help_err.use_stderr());
    assert_eq!(help_err.exit_code(), 0);

    // 5. Creating a command-formatted error via Command::error
    let cmd_err = attach_command_error(ErrorKind::ArgumentConflict, "conflicting options");
    assert_eq!(cmd_err.kind(), ErrorKind::ArgumentConflict);
    assert!(cmd_err.render().to_string().contains("conflicting options"));
}

Seeder d'origine

anonyme