feat(args): args_handler error handling and print_usage

This commit is contained in:
william.valenduc 2026-01-12 19:30:11 +00:00 committed by Matteo Flebus
parent 7b74671042
commit 111f2cf5c2
4 changed files with 183 additions and 6 deletions

View file

@ -1,8 +1,19 @@
// all includes
#include <stdio.h>
#include "utils/args/args.h"
int main(int argc, char **argv)
{
(void)argc;
(void)argv;
struct args_options options;
int r = args_handler(argc, argv, &options);
if (r != 0)
{
print_usage(stderr, argv[0]);
return 2;
}
args_print(&options);
return 0;
}

View file

@ -21,10 +21,19 @@ int args_handler(int argc, char **argv, struct args_options *options)
{
options->verbose = true;
}
else if (strcmp(argv[i], "-c") == 0 && i + 1 < argc)
else if (strcmp(argv[i], "-c") == 0)
{
if (options->type != INPUT_UNDEFINED)
return 1; // Error: multiple input types specified
{
fprintf(stderr, "Multiple input sources specified: %s\n",
argv[i + 1]);
return 1;
}
else if (i + 1 >= argc)
{
fprintf(stderr, "No command provided after -c\n");
return 1;
}
options->type = INPUT_CMD;
options->input_source = argv[i + 1];
@ -32,12 +41,17 @@ int args_handler(int argc, char **argv, struct args_options *options)
}
else if (argv[i][0] == '-')
{
return 1; // Error: unknown option
fprintf(stderr, "Unknown option: %s\n", argv[i]);
return 1;
}
else
{
if (options->type != INPUT_UNDEFINED)
return 1; // Error: multiple input types specified
{
fprintf(stderr, "Multiple input sources specified: %s\n",
argv[i]);
return 1;
}
options->type = INPUT_FILE;
options->input_source = argv[i];
@ -62,3 +76,14 @@ void args_print(struct args_options *options)
printf("Pretty print: %s\n", options->pretty_print ? "true" : "false");
printf("Verbose: %s\n", options->verbose ? "true" : "false");
}
void print_usage(FILE *std, const char *program_name)
{
fprintf(std, "Usage: %s [OPTIONS] [SCRIPT] [ARGUMENTS...]\n", program_name);
fprintf(std, "Options:\n");
fprintf(std, " -c [SCRIPT] Execute the given command string.\n");
fprintf(std, " --pretty-print Enable pretty printing of outputs.\n");
fprintf(std, " --verbose Enable verbose mode.\n");
fprintf(std,
"If no SCRIPT is provided, input is read from standard input.\n");
}

View file

@ -2,6 +2,7 @@
#define ARGS_H
#include <stdbool.h>
#include <stdio.h>
enum input_type
{
@ -38,4 +39,10 @@ int args_handler(int argc, char **argv, struct args_options *options);
*/
void args_print(struct args_options *options);
/** Prints the usage information for the program.
* @param std The output stream to print to (e.g., stdout or stderr).
* @param program_name The name of the program.
*/
void print_usage(FILE *std, const char *program_name);
#endif /* ARGS_H */