Parsing non-standard command line grammar? (flag=value instead of --flag value)

Hi all, I am new to the ocaml eco system. I want to build a CLI that deviates a bit from the common POSIX / GNU standards. The grammar is summarized as follows:

cmd subcommand [named arguments] [positional arguments] [named arguments]

Important deviations:

  • named arguments may not have the -- prefix, and follow the syntax flag=value or flag = 'value with spaces' instead of --flag value.
  • some of the flags may be defined at runtime. An example of how this may work: cmd subcommand --extra-fields='fieldA' fieldA=someValue or a --config argument could be provided where these fields are defined. A field must not be used prior to its definition.

From the looks of it, the popular cmdliner does not support this. Are there any alternatives to just… Parsing sys argv by hand with a ton of if-statements and pattern matches?

Should I be using parsers like Angstrom?

You should be able to use the imperative command line parser clap for your second requirement (defining flags at runtime).

I can’t think of a clean way in any framework to support your first requirement. I guess you could preprocess the command line array and prepend a double dash (--) to any argument that contains an equals (=). Perhaps someone else knows a better way.

Note that cmdliner also allows this (a feature I use extensively in b0) . You can always create terms dynamically and evaluate them with whatever list of strings you want and the eval function you find suitable among the (embarrasing, but historically explainable) menagerie of evaluation functions.

Indeed, this has been the principal migration path for people wanting to move from non-standard - long options to standard -- ones. E.g. the js_of_ocaml project.

1 Like