Skip to content

Instantly share code, notes, and snippets.

@Stebalien
Created July 7, 2013 03:35
Show Gist options
  • Save Stebalien/5942170 to your computer and use it in GitHub Desktop.
Save Stebalien/5942170 to your computer and use it in GitHub Desktop.
#include <stdbool.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>
#include <stdio.h>
/* commands/restore.h */
struct cmd_restore_instance {
char *history_file;
char *tree_file;
} typedef cmd_restore_instance_t;
/* commands/restore.c */
bool cmd_restore_parse(cmd_restore_instance_t *inst, int argv, char **argc, char *msg) {
char opt;
while ((opt = getopt(argv, argc, "H:T:")) != -1) {
switch (opt) {
case 'H':
inst->history_file = optarg;
break;
case 'T':
inst->tree_file = optarg;
break;
default:
// Error message
return false;
}
}
return true;
}
bool cmd_restore_execute(cmd_restore_instance_t *inst, char *msg) {
if (inst->history_file != NULL)
printf("history: %s\n", inst->history_file);
if (inst->tree_file != NULL)
printf("tree: %s\n", inst->tree_file);
return true;
}
/* commands.h */
typedef bool (*cmd_parse_t)(void *, int, char **, char *);
typedef bool (*cmd_execute_t)(void *, char *);
struct command {
char *name;
size_t instance_size;
cmd_parse_t parse;
cmd_execute_t execute;
} typedef command_t;
// Add the commands here:
command_t commands[] = {
{
.name = "restore",
.instance_size = sizeof(cmd_restore_instance_t),
.parse = (cmd_parse_t) cmd_restore_parse,
.execute = (cmd_execute_t) cmd_restore_execute
}
};
/* commands.c */
void *cmd_instantiate(command_t *cmd) {
return calloc(1, cmd->instance_size);
}
int cmd_count = sizeof(commands)/sizeof(command_t);
command_t *cmd_lookup(char *name) {
for (int i = 0; i < cmd_count; i++) {
if (strcmp(name, commands[i].name) == 0) {
return &commands[i];
}
}
return NULL;
}
/* Simple command handling test logic */
int main(int argv, char **argc) {
command_t *cmd = cmd_lookup(argc[1]);
if (cmd == NULL) {
fprintf(stderr, "Unknown Command: %s\n", argc[1]);
return 1;
}
void *instance = cmd_instantiate(cmd);
char resp[BUFSIZ];
optind = 2;
if (cmd->parse(instance, argv, argc, resp)) {
return (int)cmd->execute(instance, resp);
} else {
return 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment