clap-sort
A Rust library and CLI tool to validate that clap Subcommand enums are sorted alphabetically by their CLI names.
Overview
When using clap's derive API, it's a good practice to keep subcommands sorted alphabetically for easier maintenance. This crate helps enforce that convention by parsing Rust source files and checking that all enums with #[derive(Subcommand)] have their variants sorted.
Features
- Validates that clap
Subcommandenum variants are sorted alphabetically - Respects custom
#[command(name = "...")]attributes - Handles kebab-case conversion from snake_case variant names
- Ignores non-Subcommand enums
- Can be used as a library or CLI tool
Installation
As a library
Add to your Cargo.toml:
[]
= { = "path/to/clap-sort" }
As a CLI tool
Build and install:
Usage
Library
use ;
use Path;
// Validate a source string
let source = r#"
use clap::Subcommand;
#[derive(Subcommand)]
enum Commands {
Add,
Delete,
List,
}
"#;
assert!;
// Validate a file
let path = new;
match validate_file_path
CLI
# Check a single file
# Check multiple files
# Example output for unsorted file:
# ✗ src/commands.rs: Found 1 error(s)
# Enum 'Commands' has unsorted subcommands.
# Actual order: ["list", "add", "delete"]
# Expected order: ["add", "delete", "list"]
How It Works
The library uses syn to parse Rust source files and find all enums with #[derive(Subcommand)]. For each variant, it:
- Checks for
#[command(name = "...")]or#[clap(name = "...")]attributes - If no custom name, converts the variant identifier to kebab-case (e.g.,
AddUser→add-user) - Compares the actual order with the alphabetically sorted order
- Reports any mismatches
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
Use Cases
- CI/CD: Add to your pipeline to enforce sorted subcommands
- Pre-commit hooks: Validate files before committing
- Development: Quickly check if your commands are properly sorted
- Code review: Automatically verify PR changes maintain sort order
License
MIT or Apache-2.0 (your choice)