matt/src/args.c

92 lines
1.9 KiB
C
Raw Normal View History

2024-07-16 17:37:46 +00:00
#include <libmp/all.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include "args.h"
#include "util.h"
2024-07-16 17:38:58 +00:00
void args_add(args_t *args, char *name) {
if (NULL == args->list)
args->list = malloc(sizeof(arg_t) * (args->count + 1));
2024-07-16 17:37:46 +00:00
else
2024-07-16 17:38:58 +00:00
args->list = realloc(args->list, sizeof(arg_t) * (args->count + 1));
2024-07-16 17:37:46 +00:00
2024-07-16 17:38:58 +00:00
args->list[args->count].name = name;
2024-07-16 17:37:46 +00:00
args->list[args->count++].value = NULL;
}
2024-07-16 17:38:58 +00:00
void args_add_value(args_t *args, char *value) {
if (NULL != args->list && args->list[args->count - 1].value == NULL) {
args->list[args->count - 1].value = value;
2024-07-16 17:37:46 +00:00
return;
}
2024-07-16 17:38:58 +00:00
if (NULL == args->list)
args->list = malloc(sizeof(arg_t) * (args->count + 1));
2024-07-16 17:37:46 +00:00
else
2024-07-16 17:38:58 +00:00
args->list = realloc(args->list, sizeof(arg_t) * (args->count + 1));
2024-07-16 17:37:46 +00:00
2024-07-16 17:38:58 +00:00
args->list[args->count].name = NULL;
2024-07-16 17:37:46 +00:00
args->list[args->count++].value = value;
}
2024-07-16 17:38:58 +00:00
args_t *args_parse(int argc, char *argv[]) {
2024-07-16 17:37:46 +00:00
args_t *args = malloc(sizeof(args_t));
bzero(args, sizeof(args_t));
2024-07-16 17:38:58 +00:00
if (argc <= 1)
2024-07-16 17:37:46 +00:00
return args;
2024-07-16 17:38:58 +00:00
for (int i = 1; i < argc; i++) {
if (startswith(argv[i], "--"))
args_add(args, argv[i] + 2);
2024-07-16 17:37:46 +00:00
else
args_add_value(args, argv[i]);
}
return args;
}
2024-07-16 17:38:58 +00:00
void args_free(args_t *args) {
2024-07-16 17:37:46 +00:00
free(args->list);
free(args);
}
2024-07-16 17:38:58 +00:00
char *args_get_string(args_t *args, char *name) {
for (int i = 0; i < args->count; i++) {
if (NULL == args->list[i].name)
2024-07-16 17:37:46 +00:00
continue;
2024-07-16 17:38:58 +00:00
if (eq(args->list[i].name, name))
2024-07-16 17:37:46 +00:00
return args->list[i].value;
}
return NULL;
}
2024-07-16 17:38:58 +00:00
bool args_get_bool(args_t *args, char *name) {
for (int i = 0; i < args->count; i++) {
if (NULL == args->list[i].name)
2024-07-16 17:37:46 +00:00
continue;
2024-07-16 17:38:58 +00:00
if (eq(args->list[i].name, name))
2024-07-16 17:37:46 +00:00
return true;
}
return false;
}
2024-07-16 17:38:58 +00:00
int args_get_int(args_t *args, char *name) {
for (int i = 0; i < args->count; i++) {
if (NULL == args->list[i].name)
2024-07-16 17:37:46 +00:00
continue;
2024-07-16 17:38:58 +00:00
if (eq(args->list[i].name, name))
2024-07-16 17:37:46 +00:00
return atoi(args->list[i].value);
}
return -1;
}