From 50759fb279b38c5db7cacf88206188b827f564b2 Mon Sep 17 00:00:00 2001 From: Harry Jeffery Date: Fri, 14 Apr 2017 16:44:07 +0100 Subject: Let's not have imv_commands use hidden globals --- src/commands.c | 55 +++++++++++++++++++++++++++++++------------------------ 1 file changed, 31 insertions(+), 24 deletions(-) (limited to 'src/commands.c') diff --git a/src/commands.c b/src/commands.c index f9a4ff3..a3a59b1 100644 --- a/src/commands.c +++ b/src/commands.c @@ -18,58 +18,65 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. #include "commands.h" #include "list.h" -struct imv_command { - const char* command; +struct command { + char* command; void (*handler)(struct imv_list *args); - const char* alias; + char* alias; }; -struct imv_list *g_commands = NULL; +struct imv_commands *imv_commands_create(void) +{ + struct imv_commands *cmds = malloc(sizeof(struct imv_commands)); + cmds->command_list = imv_list_create(); + return cmds; +} -void imv_command_register(const char *command, void (*handler)()) +void imv_commands_free(struct imv_commands *cmds) { - if(!g_commands) { - g_commands = imv_list_create(); + for(size_t i = 0; i < cmds->command_list->len; ++i) { + struct command *cmd = cmds->command_list->items[i]; + free(cmd->command); + if(cmd->alias) { + free(cmd->alias); + } + free(cmd); } + imv_list_free(cmds->command_list); + free(cmds); +} - struct imv_command *cmd = malloc(sizeof(struct imv_command)); +void imv_command_register(struct imv_commands *cmds, const char *command, void (*handler)()) +{ + struct command *cmd = malloc(sizeof(struct command)); cmd->command = strdup(command); cmd->handler = handler; cmd->alias = NULL; - imv_list_append(g_commands, cmd); + imv_list_append(cmds->command_list, cmd); } -void imv_command_alias(const char *command, const char *alias) +void imv_command_alias(struct imv_commands *cmds, const char *command, const char *alias) { - if(!g_commands) { - g_commands = imv_list_create(); - } - - struct imv_command *cmd = malloc(sizeof(struct imv_command)); + struct command *cmd = malloc(sizeof(struct command)); cmd->command = strdup(command); cmd->handler = NULL; cmd->alias = strdup(alias); - imv_list_append(g_commands, cmd); + imv_list_append(cmds->command_list, cmd); } -int imv_command_exec(const char *command) +int imv_command_exec(struct imv_commands *cmds, const char *command) { - if(!g_commands) { - return 1; - } - struct imv_list *args = imv_split_string(command, ' '); int ret = 1; if(args->len > 0) { - for(size_t i = 0; i < g_commands->len; ++i) { - struct imv_command *cmd = g_commands->items[i]; + for(size_t i = 0; i < cmds->command_list->len; ++i) { + struct command *cmd = cmds->command_list->items[i]; if(!strcmp(cmd->command, args->items[0])) { if(cmd->handler) { cmd->handler(args); ret = 0; } else if(cmd->alias) { - ret = imv_command_exec(cmd->alias); + ret = imv_command_exec(cmds, cmd->alias); } break; } -- cgit v1.2.3