111 lines
2.4 KiB
C
111 lines
2.4 KiB
C
#include "args.h"
|
|
#include "error.h"
|
|
#include "convert.h"
|
|
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
|
|
#ifndef MAJOR
|
|
#define MAJOR 0
|
|
#endif
|
|
|
|
#ifndef MINOR
|
|
#define MINOR 0
|
|
#endif
|
|
|
|
#ifndef PATCH
|
|
#define PATCH 0
|
|
#endif
|
|
|
|
void check_arg (char* arg) {
|
|
if (arg == NULL) {
|
|
error("expected another argument after option");
|
|
}
|
|
}
|
|
|
|
void global_help(void (*help)(void)) {
|
|
printf("LazySphere v%d.%d.%d multi-call binary.\n\n", MAJOR, MINOR, PATCH);
|
|
help();
|
|
exit(EXIT_SUCCESS);
|
|
}
|
|
|
|
void parse_help(int argc, char** argv, void (*help)(void)) {
|
|
int i;
|
|
|
|
if (argc < 1) return;
|
|
|
|
for (i = 0; i < argc; i++) {
|
|
if (!prefix("-", argv[i]) || streql("-", argv[i])) break;
|
|
if (help != NULL && streql("--help", argv[i])) global_help(help);
|
|
}
|
|
}
|
|
|
|
int parse_args(int argc, char** argv, void (*help)(void), int (*short_arg)(char, char*), int (*long_arg)(char*, char*)) {
|
|
int start, i, current;
|
|
char* next_arg;
|
|
|
|
if (argc < 1) return 0;
|
|
|
|
start = 0;
|
|
for (i = 0; i < argc; i++) {
|
|
|
|
if (!prefix("-", argv[i]) || streql("-", argv[i])) break;
|
|
if (help != NULL && streql("--help", argv[i])) global_help(help);
|
|
|
|
if (i + 1 == argc) {
|
|
next_arg = NULL;
|
|
} else {
|
|
next_arg = argv[i+1];
|
|
}
|
|
|
|
current = i;
|
|
|
|
if (prefix("--", argv[i])) {
|
|
int r;
|
|
|
|
if (long_arg == NULL) {
|
|
goto exit;
|
|
}
|
|
|
|
r = long_arg(argv[current], next_arg);
|
|
|
|
if (r == ARG_USED) {
|
|
i++;
|
|
start++;
|
|
} else if (r == ARG_IGNORE) {
|
|
goto exit;
|
|
} else if (r == ARG_INVALID) {
|
|
error("invalid argument %s", argv[current]);
|
|
|
|
}
|
|
} else {
|
|
size_t j;
|
|
int r;
|
|
|
|
if (short_arg == NULL) {
|
|
goto exit;
|
|
}
|
|
|
|
for (j = 1; j < strlen(argv[current]); j++) {
|
|
|
|
r = short_arg(argv[current][j], next_arg);
|
|
|
|
if (r == ARG_USED) {
|
|
i++;
|
|
start++;
|
|
} else if (r == ARG_IGNORE) {
|
|
goto exit;
|
|
} else if (r == ARG_INVALID) {
|
|
error("invalid argument -%c", argv[current][j]);
|
|
}
|
|
}
|
|
}
|
|
|
|
start++;
|
|
}
|
|
|
|
exit:
|
|
|
|
return start;
|
|
}
|