From f10d685722662c6c071f1272939812131dbba227 Mon Sep 17 00:00:00 2001 From: Joshua Seaton Date: Wed, 7 Aug 2024 22:08:34 -0700 Subject: [PATCH] [console] List commands alphabetically by name in normal mode This change updates the `help` console command to list the available commands alphabetically, but only when we're not panicking. This makes `help`'s helping more helpful. --- lib/console/console.c | 28 +++++++++++++++++++++++++++- 1 file changed, 27 insertions(+), 1 deletion(-) diff --git a/lib/console/console.c b/lib/console/console.c index c92676341..ebed3053a 100644 --- a/lib/console/console.c +++ b/lib/console/console.c @@ -785,10 +785,33 @@ console_cmd_func console_get_command_handler(const char *commandstr) { return NULL; } +// Compare alphabetically by name. +static int compare_cmds(const void *cmd1, const void *cmd2) { + return strcmp(((const console_cmd_block *)cmd1)->name, + ((const console_cmd_block *)cmd2)->name); +} + static int cmd_help_impl(uint8_t availability_mask) { printf("command list by block:\n"); - for (const console_cmd_block *block = &__start_commands; block != &__stop_commands; block++) { + // If we're not panicking and are free to allocate memory, sort the commands + // alphabetically before printing. + const console_cmd_block *start = &__start_commands; + const console_cmd_block *end = &__stop_commands; + console_cmd_block *sorted = NULL; + if ((availability_mask & CMD_AVAIL_PANIC) == 0) { + size_t num_cmds = end - start; + size_t size_bytes = num_cmds * sizeof(console_cmd_block); + sorted = (console_cmd_block *) malloc(size_bytes); + if (sorted) { + memcpy(sorted, start, size_bytes); + qsort(sorted, num_cmds, sizeof(console_cmd_block), compare_cmds); + start = sorted; + end = sorted + num_cmds; + } + } + + for (const console_cmd_block *block = start; block != end; block++) { const console_cmd *curr_cmd = block->list; printf(" [%s]\n", block->name); for (size_t i = 0; i < block->count; i++) { @@ -801,6 +824,9 @@ static int cmd_help_impl(uint8_t availability_mask) { } } + if (sorted) { + free(sorted); + } return 0; }