cmdline.h¶
The cmdline.h module provides an opinionated set of convenience functions
for parsing the command line. In particular, it assumes the presence of zero or
more flags and at most one action.
A flag is an argument with a leading hyphen (
-). It expects zero or more values. The number of values it accepts is called its arity.An action is a positional argument. It accepts no values.
As an example, the following command has action run and flags --port and
-c, both with arity one:
$ ./server --port 8000 run -c config.lua
Here is a full example to demonstrate usage.
#include <stdlib.h>
#include "makinori.h"
int main(int argc, char const *argv[argc])
{
struct mn_flag flag_help = {
.sflag = mn_str_lit("h"),
.lflag = mn_str_lit("help"),
.arity = 0,
};
struct mn_flag flag_config = {
.sflag = mn_str_lit("c"),
.lflag = mn_str_lit("config"),
.arity = 1,
};
struct mn_cmdline cl = {.flags = {&flag_help, &flag_config}};
auto status = mn_cmdline_parse(argc, argv, &cl);
if (status.error) {
return EXIT_FAILURE;
}
if (flag_help.set) {
// printf help documentation
return EXIT_SUCCESS;
}
if (mn_str_eq(cl.action, mn_str_lit("run"))) {
// run server
} else {
// printf unknown action
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Options¶
-
MN_CMDLINE_MAX_FLAGS¶
Defaults to 16. The maximum number of flags that can be parsed. To update, define before including makinori:
#define MN_CMDLINE_MAX_FLAGS 32 #include "makinori.h"
-
MN_CMDLINE_MAX_ARITY¶
Defaults to 8. The maximum number of values any one flag can have. To update, define before including makinori:
#define MN_CMDLINE_MAX_ARITY 16 #include "makinori.h"
API¶
-
struct mn_flag¶
A representation of a command line flag.
-
unsigned int arity¶
The number of arguments to expect. The argument count is exact; too few or too many and the parser will complain.
-
bool set¶
Whether the flag was set. Mostly useful in the case of a flag with
mn_flag_arityzero.
-
struct mn_str vals[MN_FLAG_ARITY_MAX]¶
The values following the flag. After a call to
mn_cmdline_parse(), vals[0] will contain the first value, vals[1] contains the second value, and so on.
-
unsigned int arity¶
-
struct mn_cmdline¶
The object populated after a successful call to
mn_cmdline_parse().-
struct mn_str action¶
Either an empty string (if no action is specified) or the single positional argument supplied in the command.
-
struct mn_flag *flags¶
A list of flags to search the command line for. If two flags have the same
sflagorlflag, the first in the list takes priority. You must not specify more thanMN_CMDLINE_MAX_FLAGSentries.Call
mn_cmdline_parse()only after this array has been set.
-
struct mn_str action¶
- struct mn_status mn_cmdline_parse(
- int const argc,
- char const *argv[const argc],
- struct mn_cmdline cl[static 1]
Parses the command line.
- Parameters:
argc – The
argcas supplied tomain.argv – The
argvas supplied tomain.cl – A pointer to the
mn_cmdlineto populate.
- Returns: