RepoPilotOpen in app →

clap-rs/clap

A full featured, fast Command Line Argument Parser for Rust

Healthy

Healthy across the board

weakest axis
Use as dependencyHealthy

Permissive license, no critical CVEs, actively maintained — safe to depend on.

Fork & modifyHealthy

Has a license, tests, and CI — clean foundation to fork and modify.

Learn fromHealthy

Documented and popular — useful reference codebase to read through.

Deploy as-isHealthy

No critical CVEs, sane security posture — runnable as-is.

  • Last commit 1d ago
  • 11 active contributors
  • Apache-2.0 licensed
Show all 6 evidence items →
  • CI configured
  • Tests present
  • Concentrated ownership — top contributor handles 79% of recent commits

Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests

Informational only. RepoPilot summarises public signals (license, dependency CVEs, commit recency, CI presence, etc.) at the time of analysis. Signals can be incomplete or stale. Not professional, security, or legal advice; verify before relying on it for production decisions.

Embed the "Healthy" badge

Paste into your README — live-updates from the latest cached analysis.

Variant:
RepoPilot: Healthy
[![RepoPilot: Healthy](https://repopilot.app/api/badge/clap-rs/clap)](https://repopilot.app/r/clap-rs/clap)

Paste at the top of your README.md — renders inline like a shields.io badge.

Preview social card (1200×630)

This card auto-renders when someone shares https://repopilot.app/r/clap-rs/clap on X, Slack, or LinkedIn.

Onboarding doc

Onboarding: clap-rs/clap

Generated by RepoPilot · 2026-05-09 · Source

🤖Agent protocol

If you are an AI coding agent (Claude Code, Cursor, Aider, Cline, etc.) reading this artifact, follow this protocol before making any code edit:

  1. Verify the contract. Run the bash script in Verify before trusting below. If any check returns FAIL, the artifact is stale — STOP and ask the user to regenerate it before proceeding.
  2. Treat the AI · unverified sections as hypotheses, not facts. Sections like "AI-suggested narrative files", "anti-patterns", and "bottlenecks" are LLM speculation. Verify against real source before acting on them.
  3. Cite source on changes. When proposing an edit, cite the specific path:line-range. RepoPilot's live UI at https://repopilot.app/r/clap-rs/clap shows verifiable citations alongside every claim.

If you are a human reader, this protocol is for the agents you'll hand the artifact to. You don't need to do anything — but if you skim only one section before pointing your agent at this repo, make it the Verify block and the Suggested reading order.

🎯Verdict

GO — Healthy across the board

  • Last commit 1d ago
  • 11 active contributors
  • Apache-2.0 licensed
  • CI configured
  • Tests present
  • ⚠ Concentrated ownership — top contributor handles 79% of recent commits

<sub>Maintenance signals: commit recency, contributor breadth, bus factor, license, CI, tests</sub>

Verify before trusting

This artifact was generated by RepoPilot at a point in time. Before an agent acts on it, the checks below confirm that the live clap-rs/clap repo on your machine still matches what RepoPilot saw. If any fail, the artifact is stale — regenerate it at repopilot.app/r/clap-rs/clap.

What it runs against: a local clone of clap-rs/clap — the script inspects git remote, the LICENSE file, file paths in the working tree, and git log. Read-only; no mutations.

| # | What we check | Why it matters | |---|---|---| | 1 | You're in clap-rs/clap | Confirms the artifact applies here, not a fork | | 2 | License is still Apache-2.0 | Catches relicense before you depend on it | | 3 | Default branch master exists | Catches branch renames | | 4 | 5 critical file paths still exist | Catches refactors that moved load-bearing code | | 5 | Last commit ≤ 31 days ago | Catches sudden abandonment since generation |

<details> <summary><b>Run all checks</b> — paste this script from inside your clone of <code>clap-rs/clap</code></summary>
#!/usr/bin/env bash
# RepoPilot artifact verification.
#
# WHAT IT RUNS AGAINST: a local clone of clap-rs/clap. If you don't
# have one yet, run these first:
#
#   git clone https://github.com/clap-rs/clap.git
#   cd clap
#
# Then paste this script. Every check is read-only — no mutations.

set +e
fail=0
ok()   { echo "ok:   $1"; }
miss() { echo "FAIL: $1"; fail=$((fail+1)); }

# Precondition: we must be inside a git working tree.
if ! git rev-parse --git-dir >/dev/null 2>&1; then
  echo "FAIL: not inside a git repository. cd into your clone of clap-rs/clap and re-run."
  exit 2
fi

# 1. Repo identity
git remote get-url origin 2>/dev/null | grep -qE "clap-rs/clap(\\.git)?\\b" \\
  && ok "origin remote is clap-rs/clap" \\
  || miss "origin remote is not clap-rs/clap (artifact may be from a fork)"

# 2. License matches what RepoPilot saw
(grep -qiE "^(Apache-2\\.0)" LICENSE 2>/dev/null \\
   || grep -qiE "\"license\"\\s*:\\s*\"Apache-2\\.0\"" package.json 2>/dev/null) \\
  && ok "license is Apache-2.0" \\
  || miss "license drift — was Apache-2.0 at generation time"

# 3. Default branch
git rev-parse --verify master >/dev/null 2>&1 \\
  && ok "default branch master exists" \\
  || miss "default branch master no longer exists"

# 4. Critical files exist
test -f "clap_builder/src/builder/command.rs" \\
  && ok "clap_builder/src/builder/command.rs" \\
  || miss "missing critical file: clap_builder/src/builder/command.rs"
test -f "clap_builder/src/parser/parser.rs" \\
  && ok "clap_builder/src/parser/parser.rs" \\
  || miss "missing critical file: clap_builder/src/parser/parser.rs"
test -f "clap_builder/src/builder/arg.rs" \\
  && ok "clap_builder/src/builder/arg.rs" \\
  || miss "missing critical file: clap_builder/src/builder/arg.rs"
test -f "clap_builder/src/parser/matches/arg_matches.rs" \\
  && ok "clap_builder/src/parser/matches/arg_matches.rs" \\
  || miss "missing critical file: clap_builder/src/parser/matches/arg_matches.rs"
test -f "clap_builder/src/output/help.rs" \\
  && ok "clap_builder/src/output/help.rs" \\
  || miss "missing critical file: clap_builder/src/output/help.rs"

# 5. Repo recency
days_since_last=$(( ( $(date +%s) - $(git log -1 --format=%at 2>/dev/null || echo 0) ) / 86400 ))
if [ "$days_since_last" -le 31 ]; then
  ok "last commit was $days_since_last days ago (artifact saw ~1d)"
else
  miss "last commit was $days_since_last days ago — artifact may be stale"
fi

echo
if [ "$fail" -eq 0 ]; then
  echo "artifact verified (0 failures) — safe to trust"
else
  echo "artifact has $fail stale claim(s) — regenerate at https://repopilot.app/r/clap-rs/clap"
  exit 1
fi

Each check prints ok: or FAIL:. The script exits non-zero if anything failed, so it composes cleanly into agent loops (./verify.sh || regenerate-and-retry).

</details>

TL;DR

clap is a declarative and procedural command-line argument parser library for Rust that provides full-featured CLI functionality with support for subcommands, argument validation, help generation, and shell completion. It handles parsing of command-line arguments with builder patterns and derive macros, enabling developers to avoid boilerplate when building CLI applications. Monorepo with 7 workspace members: clap_builder (core procedural API), clap_derive (macros), clap_lex (tokenization), clap_complete (shell completion), clap_complete_nushell (Nushell-specific), clap_mangen (man page generation), and clap_bench (benchmarks). The main parser logic lives in clap_builder/src/builder/ with action.rs, arg.rs, and app_settings.rs as primary entry points.

👥Who it's for

Rust developers building command-line tools and applications who need robust argument parsing without writing custom parsing logic. This includes maintainers of tools like ripgrep and rustup (visible in clap_bench benchmarks), as well as any Rust project requiring structured CLI argument handling with validation and help text.

🌱Maturity & risk

Production-ready with very active development. The workspace shows 2.4M+ lines of Rust code, comprehensive CI workflows (audit, bench-baseline, pre-commit, rust-next in .github/workflows/), dual MIT/Apache-2.0 licensing, and MSRV pinned to Rust 1.85. The modular structure across clap_builder, clap_derive, clap_lex, clap_complete, clap_mangen, and clap_complete_nushell suggests extensive real-world usage and active feature expansion.

Low risk for a mature library. The workspace-based structure with clear separation of concerns (builder, derive, lexer, completion, man page generation) suggests good maintainability. However, being a foundational CLI library, breaking changes in releases require careful version management. The MSRV constraint at 1.85 is reasonable. No obvious single-maintainer risk is evident from the codebase organization.

Active areas of work

Active development across multiple dimensions: shell completion support (distinct clap_complete and clap_complete_nushell packages suggest recent Nushell support), man page generation (clap_mangen), benchmarking infrastructure (ripgrep, rustup, complex scenarios in clap_bench/benches/), and CI coverage with specialized workflows for audits, rust-next compatibility, and pre-commit hooks.

🚀Get running

Clone and build with Cargo: git clone https://github.com/clap-rs/clap && cd clap && cargo build. Run tests with cargo test (workspace supports running all tests across members). Run benchmarks with cargo bench -p clap_bench to verify performance on complex (ripgrep.rs), simple, and empty arg parsers.

Daily commands: This is a library, not an application. To use: add clap = { version = "4", features = ["derive"] } to your Cargo.toml, or cargo add clap. To develop clap itself: cargo build builds all workspace members, cargo test runs tests, cargo bench -p clap_bench runs benchmarks against complex, simple, and existing CLI tools (ripgrep, rustup).

🗺️Map of the codebase

  • clap_builder/src/builder/command.rs — Core Command abstraction that represents a CLI application; all argument parsing flows originate here.
  • clap_builder/src/parser/parser.rs — The argument parsing engine that tokenizes and matches user input against defined commands and arguments.
  • clap_builder/src/builder/arg.rs — Defines the Arg struct that represents individual command-line arguments; essential for understanding argument configuration.
  • clap_builder/src/parser/matches/arg_matches.rs — ArgMatches struct that holds parsed results; the primary interface for accessing parsed values.
  • clap_builder/src/output/help.rs — Help text generation and formatting; critical for CLI UX and public API behavior.
  • clap_builder/src/builder/value_parser.rs — Value parsing and type conversion framework; handles the critical task of transforming strings to typed values.
  • clap_builder/Cargo.toml — Main library package configuration; defines features and dependencies for the core parser.

🛠️How to make changes

Add a new Argument to a Command

  1. Define the argument using the Arg builder in your Command::new() chain (clap_builder/src/builder/arg.rs)
  2. Configure parsing behavior via Arg methods: .short(), .long(), .value_parser(), .required(true), etc. (clap_builder/src/builder/arg.rs)
  3. Add the argument to your command with .arg(arg) (clap_builder/src/builder/command.rs)
  4. Retrieve the parsed value in your main logic via ArgMatches::get_one() or .try_get_one() (clap_builder/src/parser/matches/arg_matches.rs)

Implement a Custom Value Parser

  1. Implement the ValueParserFactory trait or use the enum-style ValueParser builder (clap_builder/src/builder/value_parser.rs)
  2. Define parse logic to convert String → Result<T, Error> (clap_builder/src/builder/value_parser.rs)
  3. Attach via Arg::value_parser(your_parser) (clap_builder/src/builder/arg.rs)
  4. Optionally provide possible_values() for help text suggestions (clap_builder/src/builder/possible_value.rs)

Add a Subcommand Group

  1. Create a new Command via Command::new() for each subcommand (clap_builder/src/builder/command.rs)
  2. Add arguments and configuration to each subcommand (clap_builder/src/builder/arg.rs)
  3. Attach subcommands to the parent Command via .subcommand() (clap_builder/src/builder/command.rs)
  4. In parsing, use ArgMatches::subcommand() to dispatch to handler (clap_builder/src/parser/matches/arg_matches.rs)

Customize Error Messages and Help Output

  1. Override default help via Command::override_help() or help_template() (clap_builder/src/builder/command.rs)
  2. Use StyledStr for colored/formatted help text (clap_builder/src/builder/styled_str.rs)
  3. Catch Error and call .print() or format manually for custom rendering (clap_builder/src/error/mod.rs)
  4. Override Error::format() behavior or re-context errors via .with_cmd() (clap_builder/src/error/context.rs)

🔧Why these technologies

  • Rust type system & generics — Enables zero-cost abstractions, compile-time type safety for value parsers, and eliminating runtime type tags via monomorphization.
  • Builder pattern (fluent API) — Provides an ergonomic, readable declarative syntax for CLI definition while keeping the underlying structs simple.
  • Derive macros (clap_derive) — Reduces boilerplate by auto-generating Builder code from struct definitions; makes simple CLIs declarative.
  • Value type erasure (AnyValue) — Allows heterogeneous argument types (String, i32, PathBuf, custom enums) to be stored in a single collection without runtime overhead.

⚖️Trade-offs already made

  • Separate clap_builder, clap_derive, and clap_complete crates

    • Why: Allows users to depend only on the core parser if they don't need derives or shell completions; keeps build times lean.
    • Consequence: Requires coordination across multiple crates and separate versioning; more complex workspace management.
  • Eager parsing with upfront validation

    • Why: Catches all errors before user code runs, enabling fail-fast semantics and clear error messages.
    • Consequence: Cannot stream arguments or lazily parse; all args must be resolved before program logic begins.
  • Stateful ArgMatches rather than returning values directly

    • Why: Supports querying values multiple times, checking value sources, and maintaining compatibility with subcommand dispatch.
    • Consequence: Slightly higher memory overhead per parse; users must call .get_one() rather than using move semantics.
  • No async argument parsing

    • Why: undefined
    • Consequence: undefined

🪤Traps & gotchas

No required environment variables or external services detected. Key considerations: (1) MSRV is pinned to Rust 1.85 in workspace.package — code using newer syntax will break older users. (2) Feature flags are critical: 'derive' is optional but widely used; 'cargo' feature required for some completion behaviors. (3) clap_lex and clap_builder have no_std support but many features require std. (4) Builder API is fluent but chainable — misunderstanding action precedence can cause subtle parsing bugs. (5) Shell completion generation requires explicit shell type specification (Bash, Zsh, Fish, Elvish, Nushell) — incomplete specs yield broken completions.

🏗️Architecture

💡Concepts to learn

  • Builder Pattern for Fluent API — Core design pattern in clap_builder allowing chainable method calls (e.g., arg.long("flag").help("...").action(Action::SetTrue)) — essential for understanding procedural API design
  • Procedural Macros (derive macros) — clap_derive uses syn/quote to generate parsing code at compile-time from #[derive(Parser)] attributes, enabling declarative DSL alternative to builder pattern
  • Action Dispatch and Value Handling — The Action enum (Store, StoreValue, SetTrue, Append, etc.) is clap's core abstraction for controlling how each argument type accumulates values — misunderstanding actions causes incorrect parsing
  • Argument Precedence and Conflict Resolution — clap uses ArgGroup and mutual exclusivity rules to prevent conflicting flags; understanding precedence (last-one-wins vs. error) is critical for validation logic in app_settings.rs
  • Lexical Tokenization (clap_lex) — Raw CLI strings are tokenized by clap_lex before parsing (handles --, quoting, short flag clustering) — understanding token boundaries prevents off-by-one parsing bugs
  • Shell Completion Scripts (Shell Integration) — clap_complete generates dynamic completions for Bash/Zsh/Fish/Elvish/Nushell by introspecting the parser definition; requires understanding shell-specific completion protocols (bash compgen vs zsh _arguments syntax)
  • no_std and Feature-Gating — clap_builder supports no_std environments when std is disabled, requiring careful abstraction of allocator and I/O dependencies — critical for embedded CLI use cases
  • rust-lang/rustup — Major real-world consumer of clap visible in clap_bench/benches/rustup.rs benchmarks; rustup's CLI is a canonical clap showcase
  • BurntSushi/ripgrep — High-performance CLI tool benchmarked in clap_bench/benches/ripgrep.rs; used to validate parser performance at scale
  • clap-rs/clap-complete-nushell — Specialized completion generator for Nushell, spun out as separate workspace member for focused development on emerging shell support
  • structopt-rs/structopt — Predecessor derive-macro crate that inspired clap_derive; knowledge of structopt patterns helps understand clap's macro philosophy
  • TeXitoi/structopt — Original structopt repository; clap's derive interface evolved from structopt design principles

🪄PR ideas

To work on one of these in Claude Code or Cursor, paste: Implement the "<title>" PR idea from CLAUDE.md, working through the checklist as the task list.

Add comprehensive integration tests for clap_complete shell completion across all shell backends

The clap_complete and clap_complete_nushell crates generate shell completions for bash, zsh, fish, and PowerShell, but there's no dedicated integration test suite validating the actual completion output for edge cases. This would catch regressions in completion generation and ensure consistency across all supported shells.

  • [ ] Create clap_complete/tests/integration/ directory with separate test files for each shell (bash.rs, zsh.rs, fish.rs, powershell.rs, nushell.rs)
  • [ ] Write tests that validate: subcommand completion, flag completion, value completion, argument hints, and argument predicates for each shell
  • [ ] Add test fixtures in clap_complete/tests/fixtures/ with sample CLI definitions (matching clap_bench examples like ripgrep, rustup)
  • [ ] Reference clap_builder/src/builder/value_hint.rs to test all ValueHint variants across shell backends
  • [ ] Integrate tests into .github/workflows/ci.yml if not already running integration tests for completion crates

Add benchmark suite for error formatting and help text generation with --help

The clap_builder/src/error/format.rs handles error and help formatting, which is critical for CLI responsiveness. Currently clap_bench has empty.rs, simple.rs, complex.rs but no focused benchmarks for help/error rendering. This helps prevent performance regressions in user-facing output generation.

  • [ ] Create clap_bench/benches/help_render.rs with benchmarks measuring: help text generation time, error message formatting time, styled output rendering
  • [ ] Create clap_bench/benches/error_format.rs benchmarking various error scenarios (unknown args, missing required values, validation errors) with large command definitions
  • [ ] Reference clap_builder/src/error/format.rs and clap_builder/src/builder/styled_str.rs to test styling overhead
  • [ ] Ensure benchmarks test both plain and colored output paths to catch color formatting performance issues
  • [ ] Add baseline comparisons in .github/workflows/bench-baseline.yml

Add missing unit tests for ArgPredicate variants and edge cases in value validation

The clap_builder/src/builder/arg_predicate.rs file exists but likely lacks comprehensive test coverage for all predicate types and their interactions. Value parsing and predicate validation are core to clap's correctness; thorough unit tests would catch regressions early.

  • [ ] Review clap_builder/src/builder/arg_predicate.rs to identify all predicate types (Equals, IsPresent, custom predicates, etc.)
  • [ ] Create clap_builder/src/builder/tests/arg_predicate_tests.rs with unit tests covering: each predicate variant, predicate combinations, interaction with value_parser.rs, and edge cases (empty values, special characters, unicode)
  • [ ] Add tests validating predicate behavior with different Action types (Set, Append, SetTrue, etc.) from clap_builder/src/builder/action.rs
  • [ ] Include tests for predicates used in arg_group.rs to ensure group requirements work correctly with complex predicates
  • [ ] Reference existing tests in clap_builder/src/builder/tests.rs to match the testing style and patterns

🌿Good first issues

  • Add comprehensive integration tests for clap_complete_nushell in tests/ (currently underrepresented vs Bash/Zsh/Fish coverage in clap_complete/tests/). Test dynamic completion with custom completion providers and verify parity with other shells.
  • Document the Action enum variants (Store, StoreValue, SetTrue, Append, etc.) with practical examples in clap_builder/src/builder/action.rs showing when to use each. Many contributors misuse actions due to unclear semantics.
  • Add benchmarks for derive macro overhead in clap_bench: compare parsing speed of equivalent procedural vs. declarative parsers to quantify macro expansion cost, visible in simple.rs and complex.rs but missing macro-specific variants.

Top contributors

Click to expand

📝Recent commits

Click to expand
  • d142d8f — Merge pull request #6360 from epage/string (epage)
  • ba89563 — style: Prefer explicit string operations (epage)
  • bea966e — Merge pull request #6359 from epage/man (epage)
  • b811986 — chore(man):Remove unused required-features (epage)
  • 0010bf2 — Merge pull request #6358 from clap-rs/renovate/crate-ci-typos-1.x (epage)
  • bab9b24 — chore(deps): Update compatible (dev) (#6357) (renovate[bot])
  • 4dd18e5 — chore(deps): Update pre-commit hook crate-ci/typos to v1.46.0 (renovate[bot])
  • 7e0bcca — chore: Release (epage)
  • 0f09905 — docs: Update changelog (epage)
  • 9706951 — Merge pull request #6353 from truffle-dev/feat-completer-arg-index (epage)

🔒Security observations

The clap repository demonstrates good security practices with dual licensing, comprehensive linting configurations, and a clear code organization structure. However, there are concerns: (1) the use of edition '2024' which is not a stable Rust edition, (2) inability to fully assess dependency security due to truncated Cargo.toml, and (3) lack of explicit unsafe code controls. No hardcoded secrets, injection risks, or infrastructure misconfigurations were detected in the provided file structure. The project maintains active CI/CD workflows including an audit workflow, which is positive. Recommend running 'cargo audit' regularly and clarifying the edition configuration.

  • Medium · Edition 2024 Not Yet Stable — Cargo.toml - [workspace.package] edition field. The workspace is configured with edition = '2024', which is not yet an official Rust edition. This could indicate either a configuration error or use of unstable/experimental Rust features. Standard editions are 2015, 2018, and 2021. Fix: Update to a stable Rust edition (2021 recommended). Verify this is intentional if using nightly Rust features.
  • Low · Incomplete Cargo.toml Configuration — Cargo.toml - [workspace.lints.clippy] section. The provided Cargo.toml snippet is truncated (ends mid-clippy configuration), making it impossible to fully analyze dependency versions for known vulnerabilities. The clippy lints configuration is incomplete. Fix: Review complete Cargo.toml file. Run 'cargo audit' to check for known vulnerabilities in all dependencies, and ensure all dependencies are pinned to secure versions.
  • Low · Missing Security-Focused Lints — Cargo.toml - [workspace.lints] sections. While the Cargo.toml enables many good lints, there is no explicit configuration for security-critical lints like 'unsafe_code' warnings or enforcement of 'forbid(unsafe_code)' where possible in a command-line argument parser. Fix: Add stricter lint configurations: consider 'unsafe_op_in_unsafe_fn = "forbid"' and audit all unsafe code blocks in clap_builder for necessity and correctness.

LLM-derived; treat as a starting point, not a security audit.


Generated by RepoPilot. Verdict based on maintenance signals — see the live page for receipts. Re-run on a new commit to refresh.

Healthy signals · clap-rs/clap — RepoPilot