(* Build with: * corebuild cmd.byte *) open Core.Std;; (* With this code, we are trying to * Define a common set of arguments to be passed to all sub commands * Handle these common arguments all the same way * Define sub commands in a common, less verbose way *) (* The program compiled could be used this way * cmd.byte sum 32 + 10 # Display 42 * cmd.byte settings # Display all the settings * But we could use common arguments : * cmd.byte sum -c 32 + 10 # Display 42 and a message about color * cmd.byte settings # Display all the settings * *) (* Problems: * Arguments from other commands are not passed to the functions * Several XXX below *) (* Verbosity *) let verb = ref 0;; let color = ref false;; (* A set of common flags *) let common = let open Command.Spec in empty +> flag "-v" (optional_with_default 0 int) ~doc:"n Set verbosity" +> flag "-c" (optional_with_default false bool) ~doc:"bool Set color" +> flag "--rc" (optional_with_default "" string) ~doc:"name Set configuration file" ;; (* Treating common args *) let parse_common ~f = fun verbosity col rc -> verb := verbosity; color := col; f ~rc ;; (* Common way to define subcommands *) let sub ~f ~summary ~args name = let open Command in let def = basic ~summary:"" Spec.(common +> args) (* XXX Couldn't set set summary with the argument ~summary of sub function. Error is This expression has type t -> bytes but an expression was expected of type bytes*) (parse_common ~f) in ( name, def ) ;; (* Two sub commands *) (* Display the sum of the arguments *) let sum = sub ~f:(fun ~rc _ () -> (* XXX Strange arguments passed here *) (* We would like to get the numbers passed in arguments ("first number" * and "second number" below) *) (); (* Some code to use common arguments *) if !color then printf "Colored\n" else print_endline rc) ~args:(Command.Spec.( empty +> anon ("first number" %: int) +> anon ("second number" %: int) )) ~summary:"Sum" "sum" ;; (* Print some settings and a number passed to the program *) let settings = sub ~f:(fun ~rc _ () -> printf "Settings\n"; printf "Rc: %s" rc; printf "Color: %b" !color) ~args:(let open Command.Spec in empty ) ~summary:"Display settings" "settings" ;; let () = let open Command in group ~summary:"A program to test" [ sum ; settings ] |> run ~version:"" ~build_info:"" ~argv:[] ;;