Repository navigation
Practices Studies Clap
clap is the de facto standard command-line argument parser for Rust. The root package describes itself in extras/clap/Cargo.toml as "A simple to use, efficient, and full-featured Command Line Argument Parser". Its crate-level documentation in extras/clap/src/lib.rs states the project's engineering values directly, and they read like a maintenance policy rather than marketing:
//! - Resilient maintainership, including
//! - Willing to break compatibility rather than batching up breaking changes in large releases
//! - Leverage feature flags to keep to one active branch
//! - Being under [WG-CLI](https://github.com/rust-cli/team/) to increase the bus factor
//! - We follow semver and will wait about 6-9 months between major breaking changes
//! - We will support the last two minor Rust releases (MSRV, currently 1.74)
Industry adopts it because it delivers a polished end-user CLI experience (help text, suggestions, colored output, completions) out of the box, and because it exposes both a runtime builder API and a #[derive] API over the same core.
Measured scale from the clone:
- 8 packages: the root
clapfacade plus 7 workspace members listed inextras/clap/Cargo.toml(clap_bench,clap_builder,clap_derive,clap_lex,clap_complete,clap_complete_nushell,clap_mangen). - 330
.rsfiles totaling 84,223 lines of Rust. - Per-area line counts:
clap_builder28,998;tests30,959;clap_complete9,470;clap_derive4,517;examples2,648;clap_mangen1,842;clap_bench1,601;src1,676;clap_lex1,269;clap_complete_nushell1,243. The integration test tree is larger than the core implementation crate, which says a lot about the testing culture. - Version at the clone:
clap 4.6.6, MSRV1.85, edition2024.
extras/clap/
|-- Cargo.toml root "clap" facade crate + [workspace] tables
|-- Cargo.lock committed, freshness-checked in CI
|-- CHANGELOG.md Keep a Changelog format, machine-updated
|-- CONTRIBUTING.md goals, compat policy, commit hygiene
|-- CITATION.cff citation metadata, validated in CI
|-- Makefile feature-matrix commands shared by devs and CI
|-- deny.toml cargo-deny bans/licenses/sources config
|-- .clippy.toml clippy knobs: test allowances, disallowed-methods
|-- committed.toml conventional-commit lint config
|-- typos.toml spell-check exceptions
|-- release.toml cargo-release workspace config
|-- .pre-commit-config.yaml pre-commit hooks (yaml/json/toml checks, typos, committed)
|-- .cargo/config.toml resolver behavior for incompatible rust versions
|-- .github/
| |-- workflows/ ci, audit, bench-baseline, committed, post-release,
| | pre-commit, rust-next, spelling, template + release-notes.py
| |-- ISSUE_TEMPLATE/ bug_report.yml, feature_request.yml, config.yml
| |-- PULL_REQUEST_TEMPLATE.md
| |-- renovate.json5 dependency-update policy incl. custom regex managers
| `-- settings.yml repo settings as code (probot settings app)
|-- src/ thin facade: lib.rs re-exports + doc-only modules
| |-- bin/stdio-fixture.rs fixture binary for output snapshot tests
| |-- _tutorial.rs, _faq.rs, _features.rs, _concepts.rs
| |-- _cookbook/ and _derive/ rustdoc-only documentation modules
|-- clap_builder/ the actual implementation (builder API, parser, output)
|-- clap_derive/ proc-macro crate (Parser/Args/Subcommand/ValueEnum)
|-- clap_lex/ minimal OsStr-level lexer, reusable standalone
|-- clap_complete/ shell completion generation (static + dynamic engine)
|-- clap_complete_nushell/ nushell completion backend
|-- clap_mangen/ man page (roff) generation
|-- clap_bench/ divan benchmarks, publish = false
|-- examples/ paired .rs + .md trycmd transcripts, tutorials
`-- tests/ integration tests for the public surface
Why this split works: the root clap crate is a facade over clap_builder and clap_derive (see [dependencies] in extras/clap/Cargo.toml), so the proc-macro crate can be compiled in parallel with the builder and users who skip derive never pay for syn. clap_lex isolates the genuinely tricky, unsafe-bearing OsStr handling into a tiny auditable crate. Completion and man-page generation live in separate crates with their own versions so they can release independently.
extras/clap/Cargo.toml uses [workspace.package] inheritance for everything that must stay uniform:
[workspace.package]
repository = "https://github.com/clap-rs/clap"
license = "MIT OR Apache-2.0"
edition = "2024"
rust-version = "1.85" # MSRV
include = [
"build.rs",
"src/**/*",
"Cargo.toml",
"LICENSE*",
"README.md",
"examples/**/*"
]Every member manifest then carries repository.workspace = true, license.workspace = true, edition.workspace = true, rust-version.workspace = true, include.workspace = true (for example extras/clap/clap_builder/Cargo.toml). The include list keeps published tarballs lean. The # MSRV comment is not decoration: it is a grep anchor. extras/clap/CONTRIBUTING.md documents "Updating MSRV: Search for MSRV" and Renovate keys off similar comment tags.
Other notable manifest practices:
- Lockstep internal versions are pinned exactly:
clap_builder = { path = "./clap_builder", version = "=4.6.6", default-features = false }inextras/clap/Cargo.toml, so facade and implementation can never drift. - Feature flags are organized into labeled tiers in
extras/clap/Cargo.toml:default(std, color, help, usage, error-context, suggestions), "Optional" (deprecated, derive, cargo, wrap_help, env, unicode, string), and "In-work features" all prefixedunstable-(unstable-v5,unstable-ext,unstable-markdown). Facade features forward with the?syntax:deprecated = ["clap_builder/deprecated", "clap_derive?/deprecated"]. - Optional dependencies are namespaced via
dep::color = ["dep:anstream"]inextras/clap/clap_builder/Cargo.toml, so features never leak implicit dependency features. -
[lints] workspace = trueappears in every member (for exampleextras/clap/clap_lex/Cargo.toml), pulling from the shared[workspace.lints.*]tables. - Profiles in
extras/clap/Cargo.toml:panic = "abort"in both dev and release (a parser library needs no unwinding),codegen-units = 1pluslto = truein release and bench, and[profile.test] opt-level = 1to keep the huge test suite fast. -
[lib] bench = falsein every crate socargo benchonly runs the real[[bench]]targets inextras/clap/clap_bench/Cargo.toml, each withharness = falsefor divan. - Dozens of
[[example]]blocks inextras/clap/Cargo.tomleach declarerequired-featuresanddoc-scrape-examples = true, so examples build only with the features they need and get scraped into docs.rs. - docs.rs config:
[package.metadata.docs.rs] features = ["unstable-doc"]andrustdoc-args = ["--generate-link-to-definition"]. -
extras/clap/clap_bench/Cargo.tomlsetspublish = false,version = "0.0.0"and[package.metadata.release] release = false: the benchmark crate can never leak to crates.io. -
extras/clap/.cargo/config.tomlsets[resolver] incompatible-rust-versions = "fallback"so dependency resolution respects the MSRV.
There is no rustfmt.toml or .rustfmt.toml anywhere in the repository, and no .editorconfig. That absence is itself the policy: default rustfmt, zero configuration to argue about. Enforcement happens in CI, in the rustfmt job of extras/clap/.github/workflows/ci.yml:
rustfmt:
name: rustfmt
...
- name: Install Rust
uses: dtolnay/rust-toolchain@stable
with:
toolchain: "1.97" # STABLE
components: rustfmt
...
- name: Check formatting
run: cargo fmt --checkThe toolchain is pinned to a specific stable (1.97) rather than floating stable, so a rustfmt release cannot break every open PR overnight; the # STABLE comment is a Renovate anchor that gets bumped automatically (see section 6).
Non-Rust files are handled by pre-commit hooks in extras/clap/.pre-commit-config.yaml: check-yaml, check-json, check-toml, check-merge-conflict, check-case-conflict, detect-private-key, plus typos and committed. The config excludes generated content:
exclude: |
(?x)^(
tests/.*|
CHANGELOG.md
)$These same hooks run in CI via extras/clap/.github/workflows/pre-commit.yml using the j178/prek-action runner with a pinned prek-version: '0.2.27'.
Clippy policy lives in three places, each doing a distinct job.
First, [workspace.lints.rust] and [workspace.lints.clippy] in extras/clap/Cargo.toml define the lint wall once for all 8 crates. The philosophy is a curated warn-list, not a blanket pedantic: about 50 individually chosen clippy lints set to warn (str_to_string, dbg_macro, todo, mem_forget, uninlined_format_args, verbose_file_reads, ...), with explicit allows that carry their reasoning inline:
let_and_return = "allow" # sometimes good to name what you are returning
...
# Fix later:
multiple_bound_locations = "allow"
assigning_clones = "allow"
blocks_in_conditions = "allow"The # Fix later: block is a visible debt ledger inside the lint table itself. On the rustc side, rust_2018_idioms is enabled as a group at priority = -1 with targeted members (unreachable_pub = "warn", unused_qualifications = "warn") layered on top.
Second, extras/clap/.clippy.toml configures lint behavior, including a project-specific style ruleset via disallowed-methods, each with a human reason:
allow-print-in-tests = true
allow-expect-in-tests = true
allow-unwrap-in-tests = true
allow-dbg-in-tests = true
disallowed-methods = [
{ path = "std::option::Option::map_or", reason = "prefer `map(..).unwrap_or(..)` for legibility" },
...
{ path = "std::iter::Iterator::for_each", reason = "prefer `for` for side-effects" },
]This is how you get custom "house style" lints without writing a compiler plugin: disallowed-methods turns taste into machine-checked policy, and the allow-*-in-tests keys stop test code from fighting production-strictness.
Third, crate-level attributes set non-negotiables per crate. Every crate opens with the same wall, for example extras/clap/clap_builder/src/lib.rs:
#![forbid(unsafe_code)]
#![warn(missing_docs)]
#![warn(clippy::print_stderr)]
#![warn(clippy::print_stdout)]print_stdout/print_stderr matter for a library that must never write to the user's terminal except through its own Colorizer.
Enforcement escalates warnings to errors only in CI: the clippy-% target in extras/clap/Makefile runs cargo clippy ... --all-targets -- -D warnings -A deprecated, and the clippy CI job runs it four times across feature configurations (ultra-minimal, minimal, full, release). Spelling is a separate lint layer (extras/clap/typos.toml plus extras/clap/.github/workflows/spelling.yml), and commit messages are linted with committed against style="conventional" in extras/clap/committed.toml.
All CI logic is intentionally split between thin YAML and a Makefile that both humans and CI call. extras/clap/Makefile opens with the rationale:
# CI Steps
#
# Considerations
# - Easy to debug: show the command being run
# - Leverage CI features: Only run individual steps so we can use features like reporting elapsed time per stepIt defines named feature bundles (minimal, default, wasm, full, next, debug, release) and pattern rules (check-%, build-%, test-%, clippy-%) that expand them, so make test-full means the same thing on a laptop and in a runner.
extras/clap/.github/workflows/ci.yml is the main pipeline:
- Top-level
permissions: contents: read, per-job overrides (permissions: contents: noneon the gate job),concurrencywithcancel-in-progress: true, and envRUST_BACKTRACE: 1,CARGO_TERM_COLOR: always. - A single aggregation gate job named
cithatneeds:every other job and fails if any dependency failed, was cancelled, or skipped:
ci:
permissions:
contents: none
name: CI
needs: [test, shell-integration, shell-integration-nu, check, ui, minimal-versions, lockfile, docs, rustfmt, clippy, cffconvert]
runs-on: ubuntu-latest
if: "always()"
steps:
- name: Failed
run: exit 1
if: "contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') || contains(needs.*.result, 'skipped')"Branch protection then only needs to require one check ("CI"), as documented in the commented ruleset at the bottom of extras/clap/.github/settings.yml.
-
testmatrix: 6 builds coveringlinux/windows/macatfullfeatures plusminimal,defaultandnextfeature sets on Linux; every leg also runs benches in test mode and dynamic-completion tests. -
checkmatrix covers the MSRV toolchain (1.85),wasm32-unknown-unknown,wasm32-wasip2, adebug-feature build, and areleasebuild. -
minimal-versionsjob downgrades the lockfile withcargo +nightly generate-lockfile -Z minimal-versionsand then compiles on stable--locked, proving the declared version floors are honest. -
lockfilejob runscargo update --workspace --lockedto fail ifCargo.lockis stale. -
docsbuilds withRUSTDOCFLAGS: -D warningsthroughmake doc, which passes--all-features --no-deps --document-private-items. - Caching is
Swatinem/rust-cache@v2everywhere, with cache size deliberately reduced viaenv: CARGO_PROFILE_DEV_DEBUG: line-tables-onlyand a comment saying so. - Actions are pinned to major tags (
actions/checkout@v7,dtolnay/rust-toolchain@stable), not SHAs; toolchains are pinned to explicit versions with# MSRVand# STABLEcomments.
Supporting workflows:
-
extras/clap/.github/workflows/audit.yml:actions-rs/audit-checkplusEmbarkStudios/cargo-deny-action@v2(checkingbans licenses sources), triggered only onCargo.toml/Cargo.lockpaths, withcontinue-on-error: trueon the audit job and the comment "Prevent sudden announcement of a new advisory from failing ci". -
extras/clap/.github/workflows/rust-next.yml: a monthly cron ('3 3 3 * *') that runs the whole matrix on beta and nightly, plus a "Check latest dependencies" job that runscargo updatefirst. Toolchain and dependency breakage is detected on a schedule instead of blocking PRs. -
extras/clap/.github/workflows/bench-baseline.yml: on every push to master, builds thegit-deriveexample withCARGO_PROFILE_RELEASE_STRIP: trueand reports its file size to Bencher (bencherdev/bencher@main,--file-size target/release/examples/git-derive). Binary size is a tracked benchmark, not folklore. -
extras/clap/.github/workflows/committed.ymlandspelling.yml: conventional-commit and typos gates on every PR. -
extras/clap/.github/workflows/template.yml: a monthly cron that merges from a shared template repository (TEMPLATE_URL: "https://github.com/epage/_rust.git"), pushes a branch, opens a PR withgh pr create, and enables automerge. Repository boilerplate stays converged across the maintainer's projects automatically. -
extras/clap/.github/settings.ymlkeeps repository settings in code (probot settings app):allow_rebase_merge: false,allow_auto_merge: true,delete_branch_on_merge: true,squash_merge_commit_title: "PR_TITLE". -
extras/clap/.github/renovate.json5encodes a deliberate dependency policy: compatible updates for normal dependencies are disabled ("Keep version reqs low"), dev-dependency patches automerge, and custom regex managers keep theSTABLERust pin synchronized acrossMakefile,ci.yml,rust-next.yml,.clippy.toml, andtests/derive_ui.rswith automerge enabled.
Tests live almost entirely as integration tests against the public API. extras/clap/tests/builder/ has 46 files exercising the builder API and extras/clap/tests/derive/ covers the derive API; both are wired up with a single line thanks to automod, as in extras/clap/tests/builder/main.rs:
#![allow(clippy::self_named_module_files)] // false positive
#![cfg(feature = "help")]
#![cfg(feature = "usage")]
automod::dir!("tests/builder");Adding a test file requires no registration, and the whole directory compiles as one test binary (fast linking) while staying organized by topic (env.rs, groups.rs, subcommands.rs, ...).
Distinct testing layers:
- End-to-end CLI transcripts with trycmd:
extras/clap/tests/ui.rscompiles the examples and replays TOML cases fromextras/clap/tests/ui/*.toml. A case likeextras/clap/tests/ui/help_flag_stdout.tomlpinsbin.name,args,status.code, fullstdoutandstderragainst the fixture binaryextras/clap/src/bin/stdio-fixture.rs. Additionally, every example has a paired markdown transcript (extras/clap/examples/git.mdshows$ git ...sessions with expected output) that trycmd verifies, so the documentation is executable. - Compile-fail UI tests with trybuild:
extras/clap/tests/derive_ui.rsrunst.compile_fail("tests/derive_ui/*.rs")against checked-in.stderrfiles, pinned to one toolchain with#[rustversion::attr(not(stable(1.97)), ignore)] // STABLEso rustc diagnostic changes cannot break unrelated PRs, and gated behind theunstable-derive-ui-testsfeature. - Snapshot testing with snapbox, including rendered-terminal SVG snapshots: the root dev-dependencies in
extras/clap/Cargo.tomlincludesnapbox = { version = "1.2.0", features = ["term-svg"] }, andextras/clap/tests/derive/snapshots/holds files likeheaders.term.svg, capturing styled help output including ANSI colors as reviewable SVG images. - Real-shell completion tests in PTYs:
extras/clap/clap_complete/tests/testsuite/bash.rsusescompletest_pty::BashRuntimeBuilderto type into an actual bash and assert the completions; theshell-integrationCI job installselvish fish zshvia apt before running them, andextras/clap/clap_complete/tests/snapshots/pins generated scripts per shell (basic.bash,basic.zsh,basic.fish,basic.ps1,basic.elvish). - Benchmarks:
extras/clap/clap_bench/benches/contains divan benchmarks modeled on real CLIs (ripgrep.rs,rustup.rs), allharness = false, and CI compiles them on every PR viamake test-... ARGS='--workspace --benches'. - Feature-matrix testing: the Makefile bundles ensure the crate is tested with no default features, default, full, and next (v5-preview) feature sets, catching feature-gate compile breakage that single-configuration CI misses.
There is no thiserror or anyhow anywhere in the dependency tree; error handling is fully hand-rolled and user-facing. The central type in extras/clap/clap_builder/src/error/mod.rs is generic over a formatting strategy and keeps its payload boxed so Result<T, Error> stays one pointer wide:
pub struct Error<F: ErrorFormatter = DefaultFormatter> {
inner: Box<ErrorInner>,
phantom: std::marker::PhantomData<F>,
}DefaultFormatter is itself a conditional alias: RichFormatter when the error-context feature is on, KindFormatter otherwise (same file). ErrorKind in extras/clap/clap_builder/src/error/kind.rs is a #[non_exhaustive] enum where every variant carries a runnable doctest demonstrating how to trigger it. Exit codes are explicit constants in extras/clap/clap_builder/src/util/mod.rs (SUCCESS_CODE: i32 = 0, USAGE_CODE: i32 = 2, matching Unix convention for usage errors), and Error::exit() returns !.
The panic policy is written down in extras/clap/CONTRIBUTING.md: "panic! on developer error, exit gracefully on end-user error". It is implemented, not just stated: extras/clap/clap_builder/src/builder/debug_asserts.rs is a 63-assertion validation pass over the built Command (duplicate flags, version settings, index collisions) that runs only in debug builds, and panicking accessors in extras/clap/clap_builder/src/parser/matches/arg_matches.rs are annotated #[cfg_attr(debug_assertions, track_caller)] so the panic points at the caller's line, with panic messages that teach ("arg {id}'s ArgAction should be Count which should provide a default"). Internal invariant failures route through a single INTERNAL_ERROR_MSG in extras/clap/clap_builder/src/lib.rs that asks the user to file a bug.
API design discipline visible in the code:
- Builder setters take
impl IntoResettable<T>(for examplepub fn long(mut self, l: impl IntoResettable<Str>) -> Selfinextras/clap/clap_builder/src/builder/arg.rs), giving ergonomic conversions plus the ability to passNoneto reset. - 141
#[must_use]annotations inclap_builder/srcalone, so dropping a builder result warns. - Newtypes carry semantics:
Str,OsStr,StyledStr,Id,ValueRangeinextras/clap/clap_builder/src/builder/. - Visibility is tight: internals live in
pub(crate)modules (mkeymap,output,utilinextras/clap/clap_builder/src/lib.rs),unreachable_pub = "warn"is on workspace-wide, and macro plumbing that must bepubis#[doc(hidden)](32 occurrences inclap_builder/src).
-
Autoref specialization on stable. The
value_parser!macro inextras/clap/clap_builder/src/builder/value_parser.rspicks the best available parser for a type at compile time without specialization, by exploiting method resolution over reference depth:macro_rules! value_parser { ($name:ty) => {{ use $crate::builder::impl_prelude::*; let auto = $crate::builder::_infer_ValueParser_for::<$name>::new(); (&&&&&&auto).value_parser() }}; }
Six traits are implemented for
&&&&&&_infer_ValueParser_for<P>down to_infer_ValueParser_for<P>(same file,impl_prelude), rankingValueParserFactoryaboveValueEnumaboveFrom<OsString>and so on. Deref coercion selects the highest-priority impl that applies. -
Sealed traits. Both the specialization traits (
_impls_ValueParserFactorySealedand friends inextras/clap/clap_builder/src/builder/value_parser.rs) and theOsStrextension trait inextras/clap/clap_lex/src/ext.rsare sealed:mod private { pub trait Sealed {} impl Sealed for std::ffi::OsStr {} }
Public traits stay extensible only where extension is intended (
TypedValueParseris open;OsStrExtis closed). -
Quarantined unsafe with audited boundaries. Five of six crates declare
#. The onlyunsafelives inextras/clap/clap_lex/src/ext.rsfor zero-copyOsStrsplitting, each site carrying a SAFETY argument:bytes.strip_prefix(prefix.as_bytes()).map(|s| { // SAFETY: // - This came from `as_encoded_bytes` // - Since `prefix` is `&str`, any split will be along UTF-8 boundary unsafe { OsStr::from_encoded_bytes_unchecked(s) } })
The workspace also sets
unsafe_op_in_unsafe_fn = "warn"inextras/clap/Cargo.toml. -
Binary-size-aware string newtype.
Strinextras/clap/clap_builder/src/builder/str.rsstores&'static strby default and only gains aString-backed variant when thestringfeature is on (#[cfg(feature = "string")] impl From<String> for Str). Users who define their CLI with literals never link allocation paths for names. -
Type erasure with debug-only diagnostics.
AnyValueinextras/clap/clap_builder/src/util/any_value.rswrapsArc<dyn Any + Send + Sync>for parsed values of arbitrary type, and itsAnyValueIdkeepstype_name: &'static stronly under#[cfg(debug_assertions)]so release builds pay nothing for readable type mismatch errors.downcast_intousesArc::try_unwrap(...).unwrap_or_else(|arc| (*arc).clone())to avoid cloning when it holds the last reference. -
Data-structure choice by workload.
extras/clap/clap_builder/src/util/flat_map.rsimplements aVec-backed map ("This preserves insertion order") withBorrow-based lookup generics mirroring the std API. For the small maps a CLI definition produces, linear scan beats hashing, and insertion order is exactly help-display order. -
Resettable<T>to fix a real type-inference gap.extras/clap/clap_builder/src/builder/resettable.rsdocuments precisely why it exists: "you can't have a function argument that isimpl Into<Option<T>>whereTisimpl Into<S>acceptNoneas its type is ambiguous". The workaround is a two-variant enum plusFrom<T>andFrom<Option<T>>impls, keepingarg.short(None)compiling. -
Zero-cost debug tracing.
extras/clap/clap_builder/src/macros.rsdefinesdebug!twice: a styled-stderr writer when thedebugfeature is on, andmacro_rules! debug { ($($arg:tt)*) => {}; }otherwise. Hundreds of trace points cost nothing in normal builds, andextras/clap/CONTRIBUTING.mddocumentscargo test --features debugas the debugging workflow. -
Early-return macros instead of
?.extras/clap/clap_builder/src/macros.rsdefinesok!andsome!thatmatchandreturndirectly. Unlike?,ok!performs noFrom::fromconversion on the error, keeping error paths monomorphic and cheap inside the parser hot loop (used pervasively, for example inextras/clap/clap_builder/src/util/flat_map.rs). -
Iterator-driven algorithms with measured exceptions.
did_you_meaninextras/clap/clap_builder/src/parser/features/suggestions.rsmaintains a sorted candidate list viabinary_search_by(...).unwrap_or_else(|e| e)insertion and ends with aninto_iter().map(...).collect()pipeline; it also documents an upstream bug decision inline: "GH #4660: usingjarobecausejaro_winklerimplementation instrsim-rsis wrong". -
Feature-gated graceful degradation without cfg soup.
extras/clap/clap_builder/src/output/textwrap/mod.rsis a deliberate micro-fork ("Pull in only what we need rather than relying on the compiler to remove what we don't need") that exposes onewrap()signature with two bodies: real wrapping underwrap_help, identity otherwise. Callers never see the feature flag. The same file-header pattern inextras/clap/clap_builder/src/error/mod.rsuses module-level#![cfg_attr(not(feature = "error-context"), allow(dead_code))]instead of sprinkling per-item cfgs. -
Docs as compiled code.
extras/clap/src/lib.rsembeds runnable material with#![doc = include_str!("../examples/demo.rs")]and even doctests the README:
#[doc = include_str!("../README.md")]
#[cfg(doctest)]
pub struct ReadmeDoctests;A guard for unsupported configurations uses the language rather than build scripts: #[cfg(not(feature = "std"))] compile_error!("stdfeature is currently required to buildclap"); in the same file.
The most distinctive practice: the entire book lives inside the crate as rustdoc modules. extras/clap/src/lib.rs declares pub mod _tutorial;, _cookbook, _derive, _faq, _features, _concepts, all behind #[cfg(feature = "unstable-doc")], and docs.rs builds with that feature via [package.metadata.docs.rs] in extras/clap/Cargo.toml. Tutorials interleave prose with #![doc = include_str!("../examples/tutorial_builder/01_quick.rs")] (see extras/clap/src/_tutorial.rs), so every tutorial snippet is a compiled example, and every example's console output is a trycmd-verified .md transcript. extras/clap/examples/README.md states the framework explicitly: the docs are organized by the four documentation types (tutorials, how-to guides, reference, explanation).
extras/clap/CONTRIBUTING.md is unusually operational: it defines compatibility expectations per release type (major "6-9 months", minor "2 months", patch "one for every user-facing, user-contributed PR (i.e. release early, release often)"), a version support table (v4 active, v3 maintenance, v2 deprecated), deprecation mechanics (#[cfg_attr(feature = "deprecated", deprecated(...))] behind an opt-in feature flag), and commit-history guidance including "Add tests in a commit before their feature or fix, showing the current behavior". It even documents code layout philosophy: "the pub items serve as a table-of-contents".
Issue intake is structured: extras/clap/.github/ISSUE_TEMPLATE/bug_report.yml is a form requiring exact versions ("PLEASE DO NOT PUT "latest" HERE"), a minimal reproduction, and pre-search checkboxes; config.yml routes questions to Discussions. extras/clap/.github/PULL_REQUEST_TEMPLATE.md asks only two things: what issue this closes ("a maintainer-approved Issue is required for non-trivial changes") and notes to reviewers. missing_docs is warn at crate level, and the docs CI job turns rustdoc warnings into failures including for private items.
Releases are driven by cargo-release with the entire mechanical burden encoded in manifests:
-
extras/clap/release.tomlsetsdependent-version = "fix",allow-branch = ["master", "v*-master"](so patch releases can happen from old major branches), andownersfor crates.io team access. -
[package.metadata.release]inextras/clap/Cargo.tomlsetsshared-version = true,tag-name = "v{{version}}", andpre-release-replacementsthat rewriteCHANGELOG.md(stampingUnreleasedandReleaseDate, regenerating the compare links fromandmarkers), updateCITATION.cff, and even fix the changelog link insidesrc/lib.rs. Each subcrate carries its own replacement set (seeextras/clap/clap_lex/Cargo.toml), anddependent-version = "upgrade"inextras/clap/clap_builder/Cargo.tomlkeeps the facade's pinned dependency in lockstep. -
extras/clap/CHANGELOG.mdfollows Keep a Changelog with semver, contains a pre-written "5.0.0 - TBD" section flagged "available throughunstable-v5feature flag", and shows patch cadence in action (4.6.4, 4.6.5, 4.6.6 within weeks). - On tag push,
extras/clap/.github/workflows/post-release.ymlextracts the matching changelog section withextras/clap/.github/workflows/release-notes.pyand creates the GitHub release from it. One changelog, two outputs, no drift.
clap is a library, so "distribution" means crates.io plus enabling downstream binaries to distribute well: extras/clap/clap_complete generates completions for bash, zsh, fish, PowerShell and elvish (snapshots in extras/clap/clap_complete/tests/snapshots/), extras/clap/clap_complete_nushell covers nushell, and extras/clap/clap_mangen renders man pages via the roff crate. Versioning strategy is notable: breaking changes for v5 are developed on master behind unstable-v5 (see the feature graph in extras/clap/Cargo.toml), keeping one active branch instead of a long-lived diverging v5 branch.
quinjet already has a stricter clippy wall than clap, plus rustfmt, cargo-deny, taplo, typos, coverage, miri and mutants. What clap still adds:
- Adopt trycmd markdown transcripts for every subcommand. Add dev-dependency
trycmd(clap usestrycmd = { version = "1.2.0", default-features = false, features = ["color-auto", "diff", "examples"] }inextras/clap/Cargo.toml), createtests/ui/*.tomlcases pinningargs,status.code,stdout,stderras inextras/clap/tests/ui/help_flag_stdout.toml, and write.mdtranscripts per subcommand so docs and end-to-end tests are the same artifact. Since every quinjet operation is a CLI subcommand, this covers the whole command surface. - Snapshot styled output as terminal SVGs. Add
snapboxwithfeatures = ["term-svg"](rootextras/clap/Cargo.toml) and commit.term.svgsnapshots likeextras/clap/tests/derive/snapshots/headers.term.svg; for a ratatui app this pins help screens and error rendering including color, reviewable in a browser. - Use
automod::dir!for integration test trees.extras/clap/tests/builder/main.rsshows one test binary spanning 46 topic files with zero mod declarations; quinjet gets fast link times and per-topic files for free with theautomodcrate. - Add a minimal-versions CI job:
cargo +nightly generate-lockfile -Z minimal-versionsthencargo +stable check --workspace --all-features --locked, exactly as in theminimal-versionsjob ofextras/clap/.github/workflows/ci.yml, to prove declared dependency floors are real. - Add a lockfile-freshness job:
cargo update --workspace --locked(thelockfilejob inextras/clap/.github/workflows/ci.yml). - Use the aggregation-gate pattern: one job named
ciwithneeds: [...],if: always(), failing oncontains(needs.*.result, 'failure') || ... 'skipped'(top ofextras/clap/.github/workflows/ci.yml), so branch protection requires exactly one check and matrix changes never desync required-check names. - Pin the lint/format toolchain to a named stable with a
# STABLEcomment and let Renovate bump it via a custom regex manager (extras/clap/.github/renovate.json5matchesSTABLE.*?(?<currentValue>\d+...)acrossMakefileand workflow files, withautomerge: true). - Move a scheduled
rust-next.ymloff the PR path: monthly cron testing beta and nightly plus acargo update"latest dependencies" leg (extras/clap/.github/workflows/rust-next.yml), so toolchain and ecosystem breakage is discovered without blocking merges. quinjet's miri/mutants Makefile targets belong on such a cron too. - Track binary size as a benchmark: build with
CARGO_PROFILE_RELEASE_STRIP: trueand report--file-sizeof the release binary viabencherdev/bencheron every push to main (extras/clap/.github/workflows/bench-baseline.yml). For a TUI that people install, size regressions become visible per commit. - Encode house style as
disallowed-methodsin.clippy.tomlwith areasonper entry, and useallow-unwrap-in-tests = true/allow-expect-in-tests = true(extras/clap/.clippy.toml) instead of blanket test attributes; quinjet's restriction wall covers categories, this covers specific APIs the project has decided against. - Enforce conventional commits mechanically:
committed.tomlwithstyle="conventional"plus thecrate-ci/committedaction onpull_requestwithfetch-depth: 0(extras/clap/committed.ymlworkflow), feeding straight into changelog discipline. - Automate the changelog-to-release pipeline: adopt
cargo-releasewithpre-release-replacementsrewritingCHANGELOG.md/markers ([package.metadata.release]inextras/clap/Cargo.toml), and a tag-triggered workflow that extracts the section into the GitHub release body (extras/clap/.github/workflows/post-release.yml+release-notes.py). - Harden workflows: top-level
permissions: contents: read, per-job elevation only where needed, andconcurrencygroups withcancel-in-progress: trueon every workflow (all files underextras/clap/.github/workflows/). - Set
panic = "abort"in dev and release profiles pluscodegen-units = 1,lto = truein release (extras/clap/Cargo.toml[profile.*]), andopt-level = 1for the test profile if the suite grows; also[lib] bench = falseif benches are added, socargo benchtargets stay explicit. - Add a
debugcargo feature with a no-opdebug!macro twin (extras/clap/clap_builder/src/macros.rs): free-when-off tracing is more useful in a TUI, where stderr printing breaks the screen, than ad hoc logging. - Ship completions and man pages from the existing clap definition:
clap_complete(andclap_mangenwith theroffbackend,extras/clap/clap_mangen/Cargo.toml) can generate them in a build script or a hidden subcommand; clap's own PTY test approach withcompletest-pty(extras/clap/clap_complete/tests/testsuite/bash.rs) shows how to verify them against real shells. - Keep exit codes as named constants with usage errors distinct from failures:
SUCCESS_CODE = 0,USAGE_CODE = 2inextras/clap/clap_builder/src/util/mod.rs; quinjet subcommands should distinguish "bad invocation" (2) from "operation failed" (1) the same way. - Turn rustdoc into a gate: a docs CI job with
RUSTDOCFLAGS: -D warningsrunningcargo doc --all-features --no-deps --document-private-items(docsjob inextras/clap/.github/workflows/ci.ymlplus thedoctarget inextras/clap/Makefile).
Generated from docs/, edit the docs in the repo, not the wiki.
CLI reference
Pull Request
- View
- Commits
- Files
- Diff
- Conversation
- Checks
- Logs
- Open
- Merge
- Admin Merge
- Auto Merge
- Disable Auto Merge
- Dequeue
- Ready
- Draft
- Review
- Reviews
- Comment
- Edit Last Comment
- Delete Last Comment
- Edit
- Update Branch
- Lock
- Unlock
- Subscribe
- Unsubscribe
- Allow Maintainer Edits
- Disallow Maintainer Edits
- Revert
- Close
- Reopen
Guides
Optimization
Rust practices