Skip to content

Commit

Permalink
sort --help subcommands alphabetically
Browse files Browse the repository at this point in the history
  • Loading branch information
mjurbanski-reef committed Apr 30, 2024
1 parent 5a51819 commit 70801ff
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
18 changes: 13 additions & 5 deletions b2/_internal/arg_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ def add_argument(self, action):
def _unique_choice_values(cls, action):
seen = set()
seen_add = seen.add
for value in action.choices.values():
for _, value in sorted(action.choices.items()):
if not (value in seen or seen_add(value)):
yield value

Expand Down Expand Up @@ -150,6 +150,11 @@ def print_help(self, *args, show_all: bool = False, **kwargs):
super().print_help(*args, **kwargs)

def format_usage(self):
"""
Format usage message.
Deduplicate subcommands aliases if they only differ by underscores.
"""
# TODO We don't want to list underscore aliases subcommands in the usage.
# Unfortunately the only way found was to temporarily remove the aliases,
# print the usage and then restore the aliases since the formatting is deep
Expand All @@ -163,10 +168,13 @@ def format_usage(self):
if isinstance(action, argparse._SubParsersAction):
subparsers_action = action
original_choices = action.choices
action.choices = {
key: choice
for key, choice in action.choices.items() if "_" not in key
}
action.choices = {}
choice_values = set()
# sort alphabetically; this also makes `-` come before `_`
for key, choice in sorted(original_choices.items()):
if choice not in choice_values:
action.choices[key] = choice
choice_values.add(choice)
# only one subparser supported
break
usage = super().format_usage()
Expand Down
1 change: 1 addition & 0 deletions changelog.d/+sort_help.doc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Sort subcommands in `--help` alphabetically for better readability.

0 comments on commit 70801ff

Please sign in to comment.