Something went wrong. Try again.
How a command-line program ends
Something went wrong. Try again.
1.5 kB · 38 lines
OCaml
at main
123456789101112131415161718192021222324252627282930313233343536373839(* A group whose root carries an option cmdliner cannot see: a group dispatches on the first token after the program name, so [dispatch -C somewhere say hello] would reach [Cmd.eval] with [-C] where the verb belongs. The option is stripped here and what remains is handed to [Cli_exit.run] as the command line. *)
open Cmdliner
let strip_directory argv = let rec scan directory kept = function | "-C" :: value :: rest -> scan (Some value) kept rest | word :: _ as rest when not (String.starts_with ~prefix:"-" word) -> (directory, List.rev_append kept rest) | word :: rest -> scan directory (word :: kept) rest | [] -> (directory, List.rev kept) in match Array.to_list argv with | [] -> (None, argv) | program :: rest -> let directory, rest = scan None [] rest in (directory, Array.of_list (program :: rest))
let say directory word = Fmt.pr "%s %s@." (Option.value directory ~default:"here") word
let say_cmd directory = let word = let doc = "The word to say." in Arg.(required & pos 0 (some string) None & info [] ~docv:"WORD" ~doc) in let info = Cmd.info "say" ~doc:"Say a word, and where it was said." in Cmd.v info Term.(const (say directory) $ word)
let () = let directory, argv = strip_directory Sys.argv in let doc = "A group whose root takes an option, spelt as $(b,git -C) is." in let info = Cmd.info "dispatch" ~doc in Cli_exit.run ~argv (Cmd.group info [ say_cmd directory ])