Banjo API 1.1.0-alpha
Low-level C99 game development API
Loading...
Searching...
No Matches
Argument Parsing

Data Structures

struct  bj_cli_argument
struct  bj_cli

Typedefs

typedef bj_bool(* bj_cli_action_fn) (const struct bj_cli *parser, const struct bj_cli_argument *arg, const char *value, void *dest, struct bj_error **error)

Functions

bj_bool bj_parse_cli (struct bj_cli *parser, int argc, char *argv[], struct bj_error **error)
bj_bool bj_validate_cli (const struct bj_cli *parser, struct bj_error **error)
void bj_print_cli_help (const struct bj_cli *parser)
size_t bj_get_cli_help_string (const struct bj_cli *parser, char *buffer, size_t buffer_size)
bj_bool bj_store_cli_cstring (const struct bj_cli *parser, const struct bj_cli_argument *arg, const char *value, void *dest, struct bj_error **error)
bj_bool bj_store_cli_double (const struct bj_cli *parser, const struct bj_cli_argument *arg, const char *value, void *dest, struct bj_error **error)
bj_bool bj_store_cli_int (const struct bj_cli *parser, const struct bj_cli_argument *arg, const char *value, void *dest, struct bj_error **error)
bj_bool bj_store_cli_uint (const struct bj_cli *parser, const struct bj_cli_argument *arg, const char *value, void *dest, struct bj_error **error)
bj_bool bj_store_cli_bool (const struct bj_cli *parser, const struct bj_cli_argument *arg, const char *value, void *dest, struct bj_error **error)
bj_bool bj_print_cli_help_action (const struct bj_cli *parser, const struct bj_cli_argument *arg, const char *value, void *dest, struct bj_error **error)

Detailed Description

Parse argc/argv into named options and positional values.

Every C program that runs from a shell starts with int main(int argc, char* argv[]). Banjo's CLI subsystem helps you turn that pair into something useful: the user runs myprog --port 8080 -v input.txt, and you get a structured view (port = 8080, verbose = true, input file = "input.txt") without having to walk argv by hand or write a parser.

You describe your program's accepted arguments (one bj_cli_argument per option or positional), pass them and argc/argv to bj_parse_cli, and you're done. --help is generated for you from the descriptions.

What it understands

  • Short options (one dash, one letter): -f, -v, -o.
  • Long options (two dashes, a word): --file, --verbose, --output.
  • Values attached to options: -finput.txt and -f input.txt both work; --file=input.txt and --file input.txt both work.
  • Type conversion done for you: declare an option as int / unsigned / double / bool / string, and the parser converts the value and stores it where you tell it to.
  • Flag options that don't take a value, just set an int to 1.
  • Chained short options: -abc is -a -b -c, the GNU convention.
  • Positional arguments: anything without a leading dash, an empty argument included, and anything after --, either required or optional.
  • Auto-generated --help: bj_print_cli_help_action prints a usage summary built from your argument descriptions.

Properties

  • Zero heap allocation in the success path. The parser writes parsed values straight into the storage locations you pointed it at; nothing is malloc'd.
  • Small implementation: it's a finite-state machine, small enough to embed in tools where binary size matters.

Data Structure Documentation

◆ bj_cli_argument

struct bj_cli_argument

Descriptor for a single command line argument.

Defines how an argument is parsed and stored by bj_parse_cli.

Most arguments will set .dest and either .name (long option) or .shortname (short option).

int verbose = 0;
struct bj_cli parser = {
.arguments_len = 1,
.arguments = (struct bj_cli_argument[]) {
{.shortname = 'v', .name = "verbose", .help = "verbose mode", .dest = &verbose},
},
};
struct bj_error* error = NULL;
bj_parse_cli(&parser, argc, argv, &error);
if (verbose) {
bj_info("Verbose Mode");
}
bj_bool bj_parse_cli(struct bj_cli *parser, int argc, char *argv[], struct bj_error **error)
Parse command-line arguments according to parser configuration.
Parser context and argument list descriptor.
Definition cli.h:185
Descriptor for a single command line argument.
Definition cli.h:159
struct bj_error bj_error
Definition api.h:348
#define bj_info(...)
Log a message using the BJ_LOG_INFO level.
Definition log.h:141
Named arguments

Named arguments have .name (e.g., --file) or .shortname (e.g., -f). They can appear anywhere in the command line, and multiple times, the last value replacing the earlier ones. They are always optional: a named argument with .required set fails validation.

If the argument expects a value, .action and .dest must be set. The .action callback validates, converts, and stores the value.

Flags

Flags are named arguments with no value expected. To create a flag, set .dest but leave .action as 0.

The integer pointed by .dest is set to 1 when the flag is present, and left untouched otherwise. A flag takes no value: --verbose=1 fails.

Positional arguments

Positional arguments have no .name or .shortname. They are identified by their order relative to other positional arguments.

They can be declared anywhere in the argument list, mixed with named args, but a required one cannot follow an optional one. On the command line, a token that starts with a dash is an option, and any other one, an empty one included, a positional value. A -- token ends the options: every token after it is a positional value, even one starting with a dash. A -- that an option takes as its value is that value.

Example:

struct bj_cli parser = {
.arguments_len = 4,
.arguments = (struct bj_cli_argument[]) {
{.shortname = 'f', .name = "format", .help = "output format",
.dest = &format, .action = bj_store_cli_cstring},
{.help = "input file", .dest = &input, .action = bj_store_cli_cstring},
{.shortname = 'v', .name = "verbose", .help = "verbose mode", .dest = &verbose},
{.help = "output file", .dest = &output, .action = bj_store_cli_cstring},
},
};
bj_bool bj_store_cli_cstring(const struct bj_cli *parser, const struct bj_cli_argument *arg, const char *value, void *dest, struct bj_error **error)
Store string argument value.
Examples
banjo-info.c, and cli.c.

Definition at line 159 of file cli.h.

Collaboration diagram for bj_cli_argument:
Data Fields
bj_cli_action_fn action Callback to parse/store argument value.

If 0, the argument is a flag that sets the int at .dest to 1.

void * dest Pointer to store parsed value.

If 0, the program exits with status 0 once the argument is found and its action has run (e.g., --help).

const char * help Help message shown in usage output.

Can be 0 if no help needed.

const char * metavar Placeholder for argument value in help output, printed in capitals.

If 0, the long name, the short name or VALUE is used. Must be 0 for flag arguments, which take no value.

const char * name Long option name (e.g., "file" for --file).

Can be 0 if positional or only shortname used.

int required Set to 1 if positional argument is mandatory.
char shortname Short option name (e.g., 'o' for -o).

Can be 0 if positional or only long name used.

◆ bj_cli

struct bj_cli

Parser context and argument list descriptor.

Contains global parser settings, program info, and list of argument descriptors.

Examples
banjo-info.c, and cli.c.

Definition at line 185 of file cli.h.

Collaboration diagram for bj_cli:
Data Fields
struct bj_cli_argument * arguments Pointer to array of argument descriptors.
size_t arguments_len Number of arguments in the parser.
const char * description Description text displayed before argument list.
const char * epilog Text displayed after argument list.
const char * prog Program name; if 0, bj_parse_cli sets it to argv[0].

Typedef Documentation

◆ bj_cli_action_fn

typedef bj_bool(* bj_cli_action_fn) (const struct bj_cli *parser, const struct bj_cli_argument *arg, const char *value, void *dest, struct bj_error **error)

Callback function prototype for argument value processing.

Set in each bj_cli_argument to parse, validate and store the argument's string value extracted from argv.

Predefined callbacks include:

Parameters
parserPointer to the bj_cli instance
argPointer to the argument descriptor
valueArgument string value from argv
destPointer to storage location
errorError output location (may be NULL to ignore errors)
Returns
BJ_TRUE on success, BJ_FALSE on error

Definition at line 81 of file cli.h.

Function Documentation

◆ bj_get_cli_help_string()

size_t bj_get_cli_help_string ( const struct bj_cli * parser,
char * buffer,
size_t buffer_size )

Get help message as a string for custom output.

Generates formatted help text into the provided buffer.

This function can be called with buffer set to NULL and buffer_size set to 0, in which case it returns the required buffer size without writing anything.

Parameters
parserPointer to the argument parser configuration, or NULL, which gives 0 and writes nothing.
bufferBuffer to write help text to, or NULL, which only measures the text, whatever buffer_size.
buffer_sizeSize of buffer in bytes.

When the configuration is invalid, the text is the message of bj_validate_cli instead.

Returns
The length of the whole help text, excluding the null terminator, like snprintf: when it is buffer_size or more, the text in buffer was truncated, and is still null-terminated.
See also
bj_print_cli_help

◆ bj_parse_cli()

bj_bool bj_parse_cli ( struct bj_cli * parser,
int argc,
char * argv[],
struct bj_error ** error )

Parse command-line arguments according to parser configuration.

Parses the provided argument vector (argv) according to the argument descriptors in parser, storing results in the destinations specified by each argument.

This function validates the parser configuration, processes all arguments, and reports any errors through the error system.

Parameters
parserPointer to the argument parser configuration, or NULL, which fails.
argcArgument count (typically from main).
argvArgument vector (typically from main). NULL fails unless argc is 0 or less.
errorError output location (may be NULL to ignore errors).
Returns
BJ_TRUE on success, BJ_FALSE if parsing failed or configuration invalid. A NULL parser or argv that fails leaves error alone.
Error Codes
  • BJ_ERROR_INVALID_DATA: Parser configuration error (duplicate names, etc.)
  • BJ_ERROR_INVALID_DOMAIN: Invalid argument value provided
  • BJ_ERROR: General parsing error (missing required args, unknown options, etc.)
Zero-Heap Design
This function does not allocate heap memory during normal operation. Memory allocation only occurs if an error is reported (for error object).
See also
bj_validate_cli, bj_print_cli_help
Todo
This function does not yet enforce UTF-8 on the strings of argv or the text of parser. Per ADR 0008, it will.
Examples
banjo-info.c, and cli.c.

Referenced by main().

◆ bj_print_cli_help()

void bj_print_cli_help ( const struct bj_cli * parser)

Print the help message to standard output.

Prints the text bj_get_cli_help_string generates: the usage line, the program description, the arguments with their help and the epilog.

Parameters
parserPointer to the argument parser configuration, or NULL, which prints nothing.
See also
bj_get_cli_help_string
Examples
banjo-info.c, and cli.c.

Referenced by main().

◆ bj_print_cli_help_action()

bj_bool bj_print_cli_help_action ( const struct bj_cli * parser,
const struct bj_cli_argument * arg,
const char * value,
void * dest,
struct bj_error ** error )

Print help argument action.

Prints the help with bj_print_cli_help. Use this as the .action of a --help argument without .dest, so that bj_parse_cli exits with status 0 after it.

Parameters
parserParser instance, or NULL, which prints nothing.
argArgument descriptor, unused, which may be NULL.
valueArgument string, unused, usually NULL.
destDestination: with 0, the program exits after printing the help; otherwise the argument takes a value, which the action ignores, and parsing goes on.
errorError output location, unused, which may be NULL.
Returns
BJ_TRUE always.
Examples
banjo-info.c, and cli.c.

Referenced by main().

◆ bj_store_cli_bool()

bj_bool bj_store_cli_bool ( const struct bj_cli * parser,
const struct bj_cli_argument * arg,
const char * value,
void * dest,
struct bj_error ** error )

Store boolean argument value.

Accepts true, 1, yes and on for 1, and false, 0, no and off for 0, in any case.

Parameters
parserParser instance, unused, which may be NULL.
argArgument descriptor, unused, which may be NULL.
valueString representation of bool value, or NULL, a missing value, which fails with BJ_ERROR_INVALID_DOMAIN.
destDestination pointer (int*).
errorError output location (may be NULL to ignore errors).
Returns
BJ_TRUE on success, BJ_FALSE on error. A NULL dest stores nothing, fails and leaves error alone.
Error Codes
  • BJ_ERROR_INVALID_DOMAIN: Invalid boolean value
Todo
This function does not yet enforce UTF-8 on value. Per ADR 0008, it will.
Examples
cli.c.

Referenced by main().

◆ bj_store_cli_cstring()

bj_bool bj_store_cli_cstring ( const struct bj_cli * parser,
const struct bj_cli_argument * arg,
const char * value,
void * dest,
struct bj_error ** error )

Store string argument value.

Stores value as a null-terminated string pointer. The pointer is stored directly (no copy is made).

Parameters
parserParser instance, unused, which may be NULL.
argArgument descriptor, unused, which may be NULL.
valueC-string value, or NULL, a missing value, which fails with BJ_ERROR_INVALID_DOMAIN.
destDestination pointer (const char**).
errorError output location (may be NULL to ignore errors).
Returns
BJ_TRUE on success, BJ_FALSE on error. A NULL dest stores nothing, fails and leaves error alone.
Todo
This function does not yet enforce UTF-8 on value. Per ADR 0008, it will.
Examples
cli.c.

Referenced by main().

◆ bj_store_cli_double()

bj_bool bj_store_cli_double ( const struct bj_cli * parser,
const struct bj_cli_argument * arg,
const char * value,
void * dest,
struct bj_error ** error )

Store double argument value.

Parses and stores a double floating point value.

Parameters
parserParser instance, unused, which may be NULL.
argArgument descriptor, unused, which may be NULL.
valueString representation of float value, or NULL, a missing value, which fails with BJ_ERROR_INVALID_DOMAIN.
destDestination pointer (double*).
errorError output location (may be NULL to ignore errors).
Returns
BJ_TRUE on success, BJ_FALSE on error. A NULL dest stores nothing, fails and leaves error alone.
Error Codes
  • BJ_ERROR_INVALID_DOMAIN: Invalid value, or one that overflows a double
Todo
This function does not yet enforce UTF-8 on value. Per ADR 0008, it will.
Examples
cli.c.

Referenced by main().

◆ bj_store_cli_int()

bj_bool bj_store_cli_int ( const struct bj_cli * parser,
const struct bj_cli_argument * arg,
const char * value,
void * dest,
struct bj_error ** error )

Store int argument value.

Parses and stores a signed integer value, in decimal, in hexadecimal with a 0x prefix or in octal with a leading 0.

Parameters
parserParser instance, unused, which may be NULL.
argArgument descriptor, unused, which may be NULL.
valueString representation of int value, or NULL, a missing value, which fails with BJ_ERROR_INVALID_DOMAIN.
destDestination pointer (int*).
errorError output location (may be NULL to ignore errors).
Returns
BJ_TRUE on success, BJ_FALSE on error. A NULL dest stores nothing, fails and leaves error alone.
Error Codes
  • BJ_ERROR_INVALID_DOMAIN: Invalid or out-of-range value
Todo
This function does not yet enforce UTF-8 on value. Per ADR 0008, it will.
Examples
cli.c.

Referenced by main().

◆ bj_store_cli_uint()

bj_bool bj_store_cli_uint ( const struct bj_cli * parser,
const struct bj_cli_argument * arg,
const char * value,
void * dest,
struct bj_error ** error )

Store unsigned int argument value.

Parses and stores an unsigned integer value, in decimal, in hexadecimal with a 0x prefix or in octal with a leading 0.

Parameters
parserParser instance, unused, which may be NULL.
argArgument descriptor, unused, which may be NULL.
valueString representation of unsigned int value, or NULL, a missing value, which fails with BJ_ERROR_INVALID_DOMAIN.
destDestination pointer (unsigned int*).
errorError output location (may be NULL to ignore errors).
Returns
BJ_TRUE on success, BJ_FALSE on error. A NULL dest stores nothing, fails and leaves error alone.
Error Codes
  • BJ_ERROR_INVALID_DOMAIN: Invalid, negative or out-of-range value
Todo
This function does not yet enforce UTF-8 on value. Per ADR 0008, it will.

◆ bj_validate_cli()

bj_bool bj_validate_cli ( const struct bj_cli * parser,
struct bj_error ** error )

Check for configuration errors in the parser.

Ensures no conflicts or inconsistencies in argument definitions. Reports configuration errors such as:

  • Duplicate argument names or shortnames
  • Invalid characters in names
  • Conflicting dest pointers
  • Invalid metavar usage
Parameters
parserPointer to the argument parser configuration, or NULL, which fails and leaves error alone.
errorError output location (may be NULL to ignore errors).
Returns
BJ_TRUE if configuration is valid, BJ_FALSE if errors found.
Error Codes
  • BJ_ERROR_INVALID_DATA: Parser configuration has errors