registry.c (1737B)
1 #include "registry.h" 2 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <string.h> 6 7 struct cli_command *cli_commands = NULL; 8 char *command_list = NULL; 9 10 // Command list {{{ 11 // 12 // The rendered command table, refreshed on every registration 13 // commands register from constructors, so the list is final before main runs 14 // the format is what the global usage has always printed 15 16 static void command_list_render(void) { 17 struct cli_command *command; 18 char *text; 19 size_t len = sizeof("commands:\n"); 20 size_t at = 0; 21 22 for (command = cli_commands; command; command = command->next) { 23 len += (size_t)snprintf(NULL, 0, " %-12s %s\n", command->display, command->description); 24 } 25 text = malloc(len); 26 if (!text) return; 27 at += (size_t)snprintf(text + at, len - at, "commands:\n"); 28 for (command = cli_commands; command; command = command->next) { 29 at += (size_t)snprintf(text + at, len - at, " %-12s %s\n", command->display, command->description); 30 } 31 free(command_list); 32 command_list = text; 33 } 34 // }}} 35 36 // Registry {{{ 37 // 38 // Commands prepend themselves on load 39 // names is a NULL terminated alias list, argv[0] is the command name 40 41 void cli_command_register(struct cli_command *command) { 42 if (!command) return; 43 command->next = cli_commands; 44 cli_commands = command; 45 command_list_render(); 46 } 47 48 struct cli_command *cli_command_find(const char *name) { 49 struct cli_command *command; 50 if (!name) return NULL; 51 for (command = cli_commands; command; command = command->next) { 52 for (const char *const *alias = command->names; alias && *alias; alias++) { 53 if (!strcmp(*alias, name)) { 54 return command; 55 } 56 } 57 } 58 return NULL; 59 } 60 // }}}