Sélectionner une révision Git
cmd.c 2,01 Kio
#define _POSIX_C_SOURCE 200809L
#include <lektor/cmd.h>
#include <lektor/macro.h>
#include <sys/types.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
noreturn void
lkt_cmd_parse(struct lkt_cmd_opt *opts, int argc, const char **argv, void (*help)(void))
{
int count = 0, is_ok, offset = 0;
struct lkt_cmd_opt *it = opts;
lkt_cmd_callback call[2] = { NULL, NULL };
if (argc == 0 || *argv == NULL)
goto no_args;
while (it && it->name) {
is_ok = (! strncasecmp(argv[0], it->name, strlen(argv[0])));
call[is_ok] = it->call;
count += is_ok;
it = opts + (++offset);
}
/* Now search for a unique match */
if (count > 1)
goto not_exclusive;
if (!call[1] || count == 0)
goto not_found;
struct lkt_cmd_args arguments = {
.argc = argc - 1,
.argv = (const char **) & (argv[1]),
};
/* This call should exit. */
call[1](&arguments);
exit(EXIT_FAILURE);
not_found:
/* The default function */
if (!it->name && it->call) {
struct lkt_cmd_args arguments = {
.argc = argc,
.argv = (const char **) argv,
};
it->call(&arguments);
}
fprintf(stderr, "Command '%s' could not be found\n", argv[0]);
exit(EXIT_FAILURE);
no_args:
help();
not_exclusive:
fprintf(stderr, "Failed to determine which option to choose, '%s' is not exclusive\n", argv[0]);
exit(EXIT_FAILURE);
}
void
lkt_cmd_help(struct lkt_cmd_opt *opts, const char *name)
{
struct lkt_cmd_opt *it = opts;
int offset = 0, max_len = 1;
/* Get the maximan argument len */
while (it && it->name) {
int len = strlen(it->name);
max_len = MAX(max_len, len);
it = opts + (++offset);
}
/* Print the options */
it = opts;
offset = 0;
printf("COMMAND %s:\n", name);
while (it && it->name) {
printf("\t%*s %s\n", max_len, it->name, it->help);
it = opts + (++offset);
}
}