20 fprintf(stderr,
"%s\n", msg);
30 printf(
"%s\n", self->version);
42 printf(
" Usage: %s %s\n", self->name, self->usage);
44 printf(
" Options:\n");
48 for (i = 0; i <
self->option_count; ++i) {
50 printf(
" %s, %-25s %s\n"
69 self->version = version;
70 self->option_count =
self->argc = 0;
71 self->usage =
"[options]";
85 for (i = 0; i <
self->option_count; ++i) {
92 for (i = 0;
self->nargv[i]; ++i) {
110 size_t len = strlen(str);
113 for (i = 0; i < len; ++i) {
114 if (buffer ||
'[' == str[i] ||
'<' == str[i]) {
116 arg[argpos++] = str[i];
118 if (
' ' == str[i])
continue;
119 flag[flagpos++] = str[i];
124 flag[flagpos] =
'\0';
136 int alloc = *argc + 1;
137 char **nargv = malloc(alloc *
sizeof(
char *));
140 for (i = 0; argv[i]; ++i) {
141 const char *arg = argv[i];
142 size_t len = strlen(arg);
145 if (len > 2 &&
'-' == arg[0] && !strchr(arg + 1,
'-')) {
147 nargv = realloc(nargv, alloc *
sizeof(
char *));
149 for (j = 1; j < len; ++j) {
150 nargv[size] = malloc(3);
151 sprintf(nargv[size],
"-%c", arg[j]);
158 nargv[size] = malloc(len + 1);
159 strcpy(nargv[size], arg);
176 error(
"Maximum option definitions exceeded");
178 int n =
self->option_count++;
181 option->
small = small;
185 option->
argname = malloc(strlen(large) + 1);
187 option->
large = malloc(strlen(large) + 1);
205 for (i = 1; i < argc; ++i) {
206 const char *arg = argv[i];
207 for (j = 0; j <
self->option_count; ++j) {
211 if (!strcmp(arg, option->
small) || !strcmp(arg, option->
large)) {
217 if (!arg ||
'-' == arg[0]) {
218 fprintf(stderr,
"%s %s argument required\n", option->
large, option->
argname);
227 if (argv[i + 1] &&
'-' != argv[i + 1][0]) {
228 self->arg = argv[++i];
239 if (
'-' == arg[0] &&
'-' == arg[1] && 0 == arg[2]) {
245 if (
'-' == arg[0] && !literal) {
246 fprintf(stderr,
"unrecognized flag %s\n", arg);
251 int n =
self->argc++;
254 error(
"Maximum number of arguments exceeded");
256 self->argv[n] = (
char *) arg;
269 self->argv[
self->argc] = NULL;
static char ** normalize_args(int *argc, char **argv)
void command_help(command_t *self)
static void command_version(command_t *self)
void command_free(command_t *self)
static void error(char *msg)
void(* command_callback_t)(struct command *self)
static void parse_argname(const char *str, char *flag, char *arg)
#define COMMANDER_MAX_ARGS
void command_init(command_t *self, const char *name, const char *version)
void command_option(command_t *self, const char *small, const char *large, const char *desc, command_callback_t cb)
const char * large_with_arg
void command_parse(command_t *self, int argc, char **argv)
#define COMMANDER_MAX_OPTIONS
static void command_parse_args(command_t *self, int argc, char **argv)