Sélectionner une révision Git
cmd.c 1,89 Kio
#define _POSIX_C_SOURCE 200809L
#include <lektor/cmd.h>
#include <common/common.h>
#include <sys/types.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
const char *executable_name = NULL;
extern const char *man_executable_path;
noreturn void
help__(void)
{
if (!executable_name)
exit(EXIT_FAILURE);
const char *const args[] = { man_executable_path, executable_name, NULL };
execv(args[0], (char *const *) args);
exit(EXIT_FAILURE);
}
noreturn void
lkt_cmd_parse(struct lkt_cmd_opt *opts, int argc, const char **argv)
{
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 || ! strcasecmp(argv[0], "help") ||
! strcasecmp(argv[0], "--help") || ! strcasecmp(argv[0], "-help"))
goto help;
/* Find the command */
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);
}
LOG_ERROR_SCT("COMMAND", "Command '%s' could not be found", argv[0]);
exit(EXIT_FAILURE);
help:
help__();
not_exclusive:
LOG_ERROR_SCT("COMMAND", "Failed to determine option, '%s' not exclusive", argv[0]);
exit(EXIT_FAILURE);
}