Skip to content

Custom sorting of arguments in help message #6140

@thomas-zahner

Description

@thomas-zahner

Please complete the following tasks

Clap Version

master

Describe your use case

By using next_display_order I've managed to get clap sort arguments alphabetically in the --help message. However, I don't like the sorting behaviour of clap. I would like to sort my arguments by the long argument names first.

Currently my help message looks like:

  -V, --version
          Print version

  -X, --method <METHOD>
          Request method

          [default: get]

But I want --method to be before --version. This aligns with the other programs such as cURL. (see curl --help or man curl)

Sorting is done by the following code in help_template.rs:

fn option_sort_key(arg: &Arg) -> (usize, String) {
    // Formatting key like this to ensure that:
    // 1. Argument has long flags are printed just after short flags.
    // 2. For two args both have short flags like `-c` and `-C`, the
    //    `-C` arg is printed just after the `-c` arg
    // 3. For args without short or long flag, print them at last(sorted
    //    by arg name).
    // Example order: -a, -b, -B, -s, --select-file, --select-folder, -x

    let key = if let Some(x) = arg.get_short() {
        let mut s = x.to_ascii_lowercase().to_string();
        s.push(if x.is_ascii_lowercase() { '0' } else { '1' });
        s
    } else if let Some(x) = arg.get_long() {
        x.to_string()
    } else {
        let mut s = '{'.to_string();
        s.push_str(arg.get_id().as_str());
        s
    };
    (arg.get_display_order(), key)
}

I would like to swap the first if let with the second one for my use case.

Describe the solution you'd like

If possible I would like to simply swap the two if let statements as mentioned above. Would you accept this change? Or do you think this is an unnecessary opinionated breaking change?

Alternatives, if applicable

If you think this would be too opinionated and break the behaviour of too many users, can we make the sorting behaviour configurable, by somehow providing a sorting function to clap? This way option_sort_key would only be used if the user provided none.

Additional Context

This if for lychee-bin where I want to sort the help message for better usability and align the output more closely to cURL's help message. See: lycheeverse/lychee#1858

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-helpArea: documentation, including docs.rs, readme, examples, etc...C-enhancementCategory: Raise on the bar on expectationsS-waiting-on-designStatus: Waiting on user-facing design to be resolved before implementing

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions