c-md/srcs/cli/cli.c
2026-01-12 12:16:52 +01:00

112 lines
2 KiB
C

#include <stddef.h>
#include <getopt.h>
#include <string.h>
#include "cli.h"
typedef void (*t_handler)(t_args *, const char *);
typedef struct s_opt
{
int8_t short_opt;
t_handler handler;
} t_opt;
static void handle_help(t_args *args, const char *value);
static void handle_ext(t_args *args, const char *value);
static void handle_input(t_args *args, const char *value);
static void handle_output(t_args *args, const char *value);
static void handle_map(t_args *args, const char *value);
static t_handler find_handler(int8_t opt);
static void init_args(t_args *args);
static const t_opt g_opts[] = {
{'h', handle_help},
{'e', handle_ext},
{'i', handle_input},
{'o', handle_output},
{'m', handle_map},
{0, NULL}
};
static struct option g_long_opts[] = {
{"help", no_argument, NULL, 'h'},
{"ext", required_argument, NULL, 'e'},
{"input", required_argument, NULL, 'i'},
{"output", required_argument, NULL, 'o'},
{"map", required_argument, NULL, 'm'},
{NULL, 0, NULL, 0}
};
int8_t
cli_parse(t_args *args, int32_t argc, char **argv)
{
int32_t opt;
t_handler handler;
init_args(args);
while (-1 != (opt = getopt_long(argc, argv, "he:i:o:m:", g_long_opts, NULL)))
{
handler = find_handler((int8_t)opt);
if (NULL == handler)
return (-1);
handler(args, optarg);
}
return (0);
}
static void
init_args(t_args *args)
{
args->ext = NULL;
args->input = NULL;
args->output = NULL;
args->map_path = NULL;
args->show_help = 0;
}
static t_handler
find_handler(int8_t opt)
{
size_t i;
i = 0;
while (0 != g_opts[i].short_opt)
{
if (opt == g_opts[i].short_opt)
return (g_opts[i].handler);
i++;
}
return (NULL);
}
static void
handle_help(t_args *args, const char *value)
{
(void)value;
args->show_help = 1;
}
static void
handle_ext(t_args *args, const char *value)
{
args->ext = value;
}
static void
handle_input(t_args *args, const char *value)
{
args->input = value;
}
static void
handle_output(t_args *args, const char *value)
{
args->output = value;
}
static void
handle_map(t_args *args, const char *value)
{
args->map_path = value;
}