(* 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 true 32 + 10 # Display 42 and a message about color * cmd.byte settings # Display all the settings * *) (* Verbosity *) let verb = ref 0;; let color = ref false;; (* A set of common flags *) let shared_params = let open Command.Param in return (fun v c rc -> verb := v; color := c; rc) <*> 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" ;; (* Two sub commands *) (* Display the sum of the arguments *) let sum = ( "sum" , Command.basic ~summary:"" Command.Spec.( empty +> shared_params +> anon ("first_number" %: int) +> anon ("second_number" %: int) ) (fun rc a b () -> (* XXX Strange arguments passed here *) (* We would like to get the numbers passed in arguments ("first * number" * and "second number" below) *) a + b |> printf "%i\n"; (* Some code to use common arguments *) if !color then printf "Colored\n" else print_endline rc) ) ;; (* Print some settings and a number passed to the program *) let settings = ( "settings" , Command.basic ~summary:"Display settings" Command.Spec.( empty +> shared_params +> anon (maybe ("a number" %: int)) ) (fun rc n () -> printf "n: %i\n" (Option.value ~default:0 n); printf "\nSettings\n"; printf "Rc: %s\n" rc; printf "Color: %b\n" !color) ) ;; let () = let open Command in run begin group ~summary:"A program to test" [ sum ; settings ] end ;;