Skip to content

Commit

Permalink
[console] List commands alphabetically by name in normal mode
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
joshuaseaton authored and travisg committed Aug 10, 2024
1 parent 3579bf2 commit f10d685
Showing 1 changed file with 27 additions and 1 deletion.
28 changes: 27 additions & 1 deletion lib/console/console.c
Original file line number Diff line number Diff line change
Expand Up @@ -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++) {
Expand All @@ -801,6 +824,9 @@ static int cmd_help_impl(uint8_t availability_mask) {
}
}

if (sorted) {
free(sorted);
}
return 0;
}

Expand Down

0 comments on commit f10d685

Please sign in to comment.