feat(args): args_handler

This commit is contained in:
william.valenduc 2026-01-12 18:42:02 +00:00 committed by Matteo Flebus
parent 8b75d73d56
commit 7b74671042
2 changed files with 105 additions and 0 deletions

64
src/utils/args/args.c Normal file
View file

@ -0,0 +1,64 @@
#include "./args.h"
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
int args_handler(int argc, char **argv, struct args_options *options)
{
options->type = INPUT_UNDEFINED;
options->input_source = NULL;
options->pretty_print = false;
options->verbose = false;
for (int i = 1; i < argc; i++)
{
if (strcmp(argv[i], "--pretty-print") == 0)
{
options->pretty_print = true;
}
else if (strcmp(argv[i], "--verbose") == 0)
{
options->verbose = true;
}
else if (strcmp(argv[i], "-c") == 0 && i + 1 < argc)
{
if (options->type != INPUT_UNDEFINED)
return 1; // Error: multiple input types specified
options->type = INPUT_CMD;
options->input_source = argv[i + 1];
i++;
}
else if (argv[i][0] == '-')
{
return 1; // Error: unknown option
}
else
{
if (options->type != INPUT_UNDEFINED)
return 1; // Error: multiple input types specified
options->type = INPUT_FILE;
options->input_source = argv[i];
}
}
if (options->type == INPUT_UNDEFINED)
options->type = INPUT_STDIN;
return 0;
}
void args_print(struct args_options *options)
{
printf("Input type: %s\n",
options->type == INPUT_CMD ? "COMMAND"
: options->type == INPUT_FILE ? "FILE"
: options->type == INPUT_STDIN ? "STDIN"
: "UNDEFINED");
printf("Input source: %s\n",
options->input_source ? options->input_source : "NULL");
printf("Pretty print: %s\n", options->pretty_print ? "true" : "false");
printf("Verbose: %s\n", options->verbose ? "true" : "false");
}

41
src/utils/args/args.h Normal file
View file

@ -0,0 +1,41 @@
#ifndef ARGS_H
#define ARGS_H
#include <stdbool.h>
enum input_type
{
INPUT_UNDEFINED,
INPUT_FILE,
INPUT_CMD,
INPUT_STDIN
};
struct args_options
{
/** Source of the input, filename or command string depending on type, NULL
* if INPUT_STDIN */
const char *input_source;
/** Type of the input source */
enum input_type type;
/** Enable or disable pretty printing of outputs */
bool pretty_print;
/** Enable or disable verbose mode */
bool verbose;
};
/**
* Handles command-line arguments and populates the args_options structure.
* @param argc The argument count.
* @param argv The argument vector.
* @param options Pointer to args_options structure to be populated.
* @return 0 on success, non-zero on failure.
*/
int args_handler(int argc, char **argv, struct args_options *options);
/** Prints the parsed arguments for debugging purposes.
* @param options Pointer to args_options structure containing parsed options.
*/
void args_print(struct args_options *options);
#endif /* ARGS_H */