CORDEA blog

Android applications engineer

OCaml で Subcommand をパースする

Arg module のドキュメント読んでもどうすればいいかいまいち分からなかったので
OCaml で Subcommand とそのオプションを Arg module でパースする方法をメモしておきます。

何か間違っているところなどあればコメント、ツイートなど下さい。

実装

parse_dynamic を使用する

let usage = ""

let options = ref []

let hoge_options = [
    ("-hoge",
        Arg.Unit(fun () -> print_endline "hoge option"),
        "");
]

let huge_options = [
    ("-huge",
        Arg.Unit(fun () -> print_endline "huge option"),
        "");
]

let parse arg =
    if !Arg.current = 1 then
        match arg with
        | "hoge" -> options := hoge_options
        | "huge" -> options := huge_options
        | _ -> raise (Arg.Bad "Invalid subcommand")

let () =
    Arg.parse_dynamic options parse usage
;;

確認

$ ocamlbuild demo.native
$ ./demo.native hoge -hoge
hoge option
$ ./demo.native hoge -huge
demo.native: unknown option '-huge'.

  -help  Display this list of options
  --help  Display this list of options
$ ./demo.native huge -huge
huge option
$ ./demo.native huge -hoge
demo.native: unknown option '-hoge'.

  -help  Display this list of options
  --help  Display this list of options
$ ./demo.native demo
demo.native: Invalid subcommand.

  -help  Display this list of options
  --help  Display this list of options

参考