clap-sort
A Rust library to validate that clap Subcommand enums are sorted alphabetically.
Overview
When using clap's derive API, it's a good practice to keep subcommands sorted alphabetically for easier maintenance and better UX. This crate helps enforce that convention by validating the clap Command structure at runtime.
Features
- Validates that clap subcommands are sorted alphabetically
- Works with both builder and derive APIs
- Easy integration via unit tests
- Zero dependencies beyond clap
- Lightweight and fast
Installation
Add to your Cargo.toml:
[]
= "0.1"
Usage
Unit Test Integration (Recommended)
The best way to use clap-sort is to add a unit test to your CLI project:
This approach ensures that:
- Your subcommands stay sorted as part of your normal test suite
- CI/CD will catch any unsorted commands before merge
- Developers get immediate feedback when running
cargo test
Full Example with Derive API
use ;
Non-Panicking Validation
If you prefer Result-based error handling:
use CommandFactory;
How It Works
The library validates the runtime Command structure by:
- Extracting all subcommand names from the clap
Command - Comparing them with their alphabetically sorted order
- Panicking (or returning an error) if they don't match
This approach works with both the builder API and derive API, and validates the actual command structure as clap sees it.
Examples
✅ Correctly sorted
✅ Correctly sorted with custom names
❌ Unsorted
Testing
Run the test suite:
The library includes comprehensive tests covering:
- Sorted enums
- Unsorted enums
- Custom command names
- Non-Subcommand enums (should be ignored)
- Multiple enums in one file
Real-world Example
Here's a complete example showing how unsorted commands are caught:
use ;
When you run cargo test, this will fail with:
thread 'tests::test_sorted' panicked at 'Subcommands are not sorted alphabetically!
Actual order: ["list", "add", "delete"]
Expected order: ["add", "delete", "list"]'
License
MIT or Apache-2.0 (your choice)