I’ve already wrote something about OptParse last month. Today I discovered how to create a new option (that is not a string, int or bool) and validate it within the arg parser.
So suppose we want to write an application that can output both txt
and html and we want the user to specify the format with command line
option. One way would be to use a StdOpt.str_option
- eventually
with a default option - and to retrive it in application code with
OptParse.Opt.get
.
However this is not satisfactory as we are mixing the application code
with command line parsing. A better way is to create a new type of
option with Opt.value_option
.
This is the concept :
type out_t = Txt | Html
module Options = struct
open OptParse
exception Format
let out_option ?default ?(metavar = "<txt|html>") () =
let corce = function
|"txt" -> Txt
|"html" -> Html
| _ -> raise Format
in
let error _ s = Printf.sprintf "%s format not supported" s in
Opt.value_option metavar default corce error
let output = out_option ~default:Txt ()
let description = "This is an example"
let options = OptParser.make ~description:description ()
open OptParser
add options ~short_name:'o' ~long_name:"out" ~help:"Output type" output;
end
Note that the function Opt.value_option
get a default value, a
metavar - that is the sting associated with the option in the help (
-o<txt|html>, --out=<txt|html> Output type
), a corce
function, that is, a function that transforms a string in the desired
type, and an error function that is used by the parser to give a
meaningful error is the option is not correctly validated.
For example :
$./test.native -oooo
usage: test.native [options]
test.native: option '-o': ooo format not supported
Now when we use this new option in the application code with
OptParse.Opt.get
and we can be certain that it was correctly validated.