123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074(** Purely functional command line parsing.
Here is a simple example:
{[
let () =
let open Command.Let_syntax in
Command.basic
~summary:"cook eggs"
(let%map_open num_eggs =
flag "num-eggs" (required int) ~doc:"COUNT cook this many eggs"
and style =
flag "style" (required (Arg_type.create Egg_style.of_string))
~doc:"OVER-EASY|SUNNY-SIDE-UP style of eggs"
and recipient =
anon ("recipient" %: string)
in
fun () ->
(* TODO: implement egg-cooking in ocaml *)
failwith "no eggs today")
|> Command.run
]}
{b Note}: {{!Core.Command.Param}[Command.Param]} has replaced
{{!Core.Command.Spec}[Command.Spec] (DEPRECATED)} and should be used in all new
code. *)open!Baseopen!Importtypeenv=[`Replaceof(string*string)list|`Extendof(string*string)list|`Overrideof(string*stringoption)list|`Replace_rawofstringlist]moduletypeVersion_util=sigmoduleTime:sigtypet[@@derivingsexp_of]endvalversion_list:stringlistvalreprint_build_info:(Time.t->Sexp.t)->stringend(** [For_unix] is the subset of Core's interface that [Command] needs, in particular to
implement the [shape] and [run] functions. [Core.Private.Command] is a functor
taking a module matching [For_unix] and is applied in Core to construct
[Core.Command]. We use a functor in this way so that [Command]'s internal data
types can remain hidden. *)moduletypeFor_unix=sigtypeenv_varmoduleVersion_util:Version_utilmodulePid:sigtypetvalto_int:t->intendmoduleSignal:sigtypetendmoduleThread:sigtypetvalcreate:on_uncaught_exn:[`Kill_whole_process|`Print_to_stderr]->('a->unit)->'a->tvaljoin:t->unitendmoduleUnix:sigmoduleFile_descr:sigtypetendvalgetpid:unit->Pid.tvalclose:?restart:bool->File_descr.t->unitvalin_channel_of_descr:File_descr.t->In_channel.tvalputenv:key:env_var->data:string->unitvalunsetenv:env_var->unitvalunsafe_getenv:env_var->stringoptiontypeenv:=[`Replaceof(env_var*string)list|`Extendof(env_var*string)list|`Overrideof(env_var*stringoption)list|`Replace_rawofstringlist]valexec:prog:string->argv:stringlist->?use_path:bool->?env:env->unit->Nothing.tmoduleProcess_info:sigtypet={pid:Pid.t;stdin:File_descr.t;stdout:File_descr.t;stderr:File_descr.t}endvalcreate_process_env:?working_dir:string->?prog_search_path:stringlist->?argv0:string->prog:string->args:stringlist->env:env->unit->Process_info.tvalwait:Pid.t->unitendendmoduletypeEnumerable_sexpable=sigtypet[@@derivingenumerate,sexp_of]endmoduletypeEnumerable_stringable=sigtypet[@@derivingenumerate]valto_string:t->stringendmoduletypeCommand=sigmoduletypeEnumerable_sexpable=Enumerable_sexpablemoduletypeEnumerable_stringable=Enumerable_stringable(** Specifications for command-line auto-completion. *)moduleAuto_complete:sig(** In addition to the argument prefix, an auto-completion spec has access to any
previously parsed arguments in the form of a heterogeneous map into which those
arguments may register themselves by providing a [Univ_map.Multi.Key] using the
[~key] argument to [Arg_type.create]. *)typet=Univ_map.t->part:string->stringlistmoduleFor_escape:sig(** For the [escape] flag, it's more useful if the auto-completion spec has access
to all past arguments after the flag, hence the [part:string list] argument. *)typet=Univ_map.t->part:stringlist->stringlistendend(** Argument types. *)moduleArg_type:sig(** The type of a command line argument. *)type'at(** An argument type includes information about how to parse values of that type from
the command line, and (optionally) how to autocomplete partial arguments of that
type via bash's programmable tab-completion.
If the [of_string] function raises an exception, command line parsing will be
aborted and the exception propagated up to top-level and printed along with
command-line help. *)valcreate:?complete:Auto_complete.t->?key:'aUniv_map.Multi.Key.t->(string->'a)->'at(** Apply the parse function to the given string the same way it would apply to an
argument, catching any exceptions thrown. *)valparse:'at->string->'aOr_error.t(** Transforms the result of a [t] using [f]. *)valmap:?key:'bUniv_map.Multi.Key.t->'at->f:('a->'b)->'bt(** Defers construction of the arg type until it is needed. *)valof_lazy:?key:'aUniv_map.Multi.Key.t->'atLazy.t->'at(** An auto-completing [Arg_type] over a finite set of values. *)valof_map:?accept_unique_prefixes:bool(** Defaults to [true]. Automatically parses a prefix of a valid key if it's
unambiguous. *)->?case_sensitive:bool(** Defaults to [true]. If [false], map keys must all be distinct when lowercased.*)->?list_values_in_help:bool(** Defaults to [true]. If you set it to false the accepted values won't be listed
in the command help. *)->?auto_complete:Auto_complete.t(** Defaults to bash completion on the string prefix. This allows users to specify
arbitrary auto-completion for [t]. *)->?key:'aUniv_map.Multi.Key.t->'aMap.M(String).t->'at(** Convenience wrapper for [of_map]. Raises on duplicate keys. *)valof_alist_exn:?accept_unique_prefixes:bool->?case_sensitive:bool(** Defaults to [true]. If [false], map keys must all be distinct when lowercased.*)->?list_values_in_help:bool(** default: true *)->?auto_complete:Auto_complete.t->?key:'aUniv_map.Multi.Key.t->(string*'a)list->'at(** Convenience wrapper for [of_alist_exn] to use with [ppx_enumerate] using
[to_string]. Raises on duplicate [to_string]ed values. *)valenumerated:?accept_unique_prefixes:bool->?case_sensitive:bool(** Defaults to [true]. If [false], map keys must all be distinct when lowercased.*)->?list_values_in_help:bool(** default: true *)->?auto_complete:Auto_complete.t->?key:'aUniv_map.Multi.Key.t->(moduleEnumerable_stringablewithtypet='a)->'at(** Convenience wrapper for [of_alist_exn] to use with [ppx_enumerate] using
[sexp_of_t] to turn the value into a string. Raises on duplicate [to_string]ed
values. *)valenumerated_sexpable:?accept_unique_prefixes:bool->?case_sensitive:bool(** Defaults to [true]. If [false], map keys must all be distinct when lowercased.*)->?list_values_in_help:bool(** default: true *)->?auto_complete:Auto_complete.t->?key:'aUniv_map.Multi.Key.t->(moduleEnumerable_sexpablewithtypet='a)->'at(** [comma_separated t] accepts comma-separated lists of arguments parsed by [t].
If [strip_whitespace = true], whitespace is stripped from each comma-separated
string before it is parsed by [t].
If [allow_empty = true] then the empty string (or just whitespace, if
[strip_whitespace = true]) results in an empty list, and if [allow_empty = false]
then the empty string will fail to parse. (Note that there is currently no way for
[comma_separated] to produce a list whose only element is the empty string.)
If [unique_values = true] no autocompletion will be offered for arguments already
supplied in the fragment to complete. *)valcomma_separated:?allow_empty:bool(** default: [false] *)->?key:'alistUniv_map.Multi.Key.t->?strip_whitespace:bool(** default: [false] *)->?unique_values:bool(** default: [false] *)->'at->'alistt(** Values to include in other namespaces. *)moduleExport:sigvalstring:stringt(** Beware that an anonymous argument of type [int] cannot be specified as negative,
as it is ambiguous whether -1 is a negative number or a flag. (The same applies
to [float], [time_span], etc.) You can use the special built-in "-anon" flag to
force a string starting with a hyphen to be interpreted as an anonymous argument
rather than as a flag, or you can just make it a parameter to a flag to avoid the
issue. *)valint:inttvalchar:chartvalfloat:floattvalbool:booltvalsexp:Sexp.ttvalsexp_conv:?complete:Auto_complete.t->(Sexp.t->'a)->'atendvalauto_complete:_t->Auto_complete.tend(** Command-line flag specifications. *)moduleFlag:sigtype'at(** Required flags must be passed exactly once. *)valrequired:'aArg_type.t->'at(** Optional flags may be passed at most once. *)valoptional:'aArg_type.t->'aoptiont(** [optional_with_default] flags may be passed at most once, and default to a given
value. *)valoptional_with_default:'a->'aArg_type.t->'at(** [listed] flags may be passed zero or more times. *)vallisted:'aArg_type.t->'alistt(** [one_or_more_as_pair] flags must be passed one or more times. *)valone_or_more_as_pair:'aArg_type.t->('a*'alist)t(** Like [one_or_more_as_pair], but returns the flag values as a list. *)valone_or_more_as_list:'aArg_type.t->'alistt(** [no_arg] flags may be passed at most once. The boolean returned is true iff the
flag is passed on the command line. *)valno_arg:boolt(** [no_arg_register ~key ~value] is like [no_arg], but associates [value] with [key]
in the autocomplete environment. *)valno_arg_register:key:'aUniv_map.With_default.Key.t->value:'a->boolt(** [no_arg_some value] is like [no_arg], but will return [Some value] if the flag is
passed on the command line, and return [None] otherwise. *)valno_arg_some:'a->'aoptiont(** [no_arg_required value] is like [no_arg], but the argument is required.
This is useful in combination with [choose_one_non_optional]. *)valno_arg_required:'a->'at(** [no_arg_abort ~exit] is like [no_arg], but aborts command-line parsing by calling
[exit]. This flag type is useful for "help"-style flags that just print something
and exit. *)valno_arg_abort:exit:(unit->Nothing.t)->unitt(** [escape] flags may be passed at most once. They cause the command line parser to
abort and pass through all remaining command line arguments as the value of the
flag.
A standard choice of flag name to use with [escape] is ["--"]. *)valescape:stringlistoptiontvalescape_with_autocomplete:complete:Auto_complete.For_escape.t->stringlistoptiont(** [map_flag flag ~f] transforms the parsed result of [flag] by applying [f]. *)valmap_flag:'at->f:('a->'b)->'btend(** Anonymous command-line argument specification. *)moduleAnons:sig(** A specification of some number of anonymous arguments. *)type+'at(** [(name %: typ)] specifies a required anonymous argument of type [typ].
The [name] must not be surrounded by whitespace; if it is, an exn will be raised.
If the [name] is surrounded by a special character pair (<>, \{\}, \[\] or (),)
[name] will remain as-is, otherwise, [name] will be uppercased.
In the situation where [name] is only prefixed or only suffixed by one of the
special character pairs, or different pairs are used (e.g., "<ARG\]"), an exn will
be raised.
The (possibly transformed) [name] is mentioned in the generated help for the
command. *)val(%:):string->'aArg_type.t->'at(** [sequence anons] specifies a sequence of anonymous arguments. An exception will be
raised if [anons] matches anything other than a fixed number of anonymous arguments.
*)valsequence:'at->'alistt(** [non_empty_sequence_as_pair anons] and [non_empty_sequence_as_list anons] are like
[sequence anons] except that an exception will be raised if there is not at least
one anonymous argument given. *)valnon_empty_sequence_as_pair:'at->('a*'alist)tvalnon_empty_sequence_as_list:'at->'alistt(** [(maybe anons)] indicates that some anonymous arguments are optional. *)valmaybe:'at->'aoptiont(** [(maybe_with_default default anons)] indicates an optional anonymous argument with a
default value. *)valmaybe_with_default:'a->'at->'at(** [t2], [t3], and [t4] each concatenate multiple anonymous argument specs into a
single one. The purpose of these combinators is to allow for optional sequences of
anonymous arguments. Consider a command with usage:
{v
main.exe FOO [BAR BAZ]
v}
where the second and third anonymous arguments must either both be there or both not
be there. This can be expressed as:
{[
t2 ("FOO" %: foo) (maybe (t2 ("BAR" %: bar) ("BAZ" %: baz)))]
]}
Sequences of 5 or more anonymous arguments can be built up using
nested tuples:
{[
maybe (t3 a b (t3 c d e))
]}
*)valt2:'at->'bt->('a*'b)tvalt3:'at->'bt->'ct->('a*'b*'c)tvalt4:'at->'bt->'ct->'dt->('a*'b*'c*'d)t(** [map_anons anons ~f] transforms the parsed result of [anons] by applying [f]. *)valmap_anons:'at->f:('a->'b)->'btend(** Command-line parameter specification.
This module replaces {{!Core.Command.Spec}[Command.Spec]}, and should be used
in all new code. Its types and compositional rules are much easier to
understand. *)moduleParam:sigmoduletypeS=sigtype+'at(** [Command.Param] is intended to be used with the [[%map_open]] syntax defined in
[ppx_let], like so:
{[
let command =
Command.basic ~summary:"..."
(let%map_open count = anon ("COUNT" %: int)
and port = flag "port" (optional int) ~doc:"N listen on this port"
and person = person_param
in
(* ... Command-line validation code, if any, goes here ... *)
fun () ->
(* The body of the command *)
do_stuff count port person)
]}
One can also use [[%map_open]] to define composite command line parameters, like
[person_param] in the previous snippet:
{[
type person = { name : string; age : int }
let person_param : person Command.Param.t =
(let%map_open name =
flag "name" (required string) ~doc:"X name of the person"
and age = flag "age" (required int) ~doc:"N how many years old"
in
{name; age})
]}
The right-hand sides of [[%map_open]] definitions have [Command.Param] in scope.
See example/command/main.ml for more examples.
*)includeApplicative.Swithtype'at:='at(** {2 Various internal values} *)(** The help text for the command. *)valhelp:stringLazy.tt(** The subcommand path of the command. *)valpath:stringlistt(** The arguments passed to the command. *)valargs:stringlistt(** [flag name spec ~doc] specifies a command that, among other things, takes a flag
named [name] on its command line. [doc] indicates the meaning of the flag.
All flags must have a dash at the beginning of the name. If [name] is not
prefixed by "-", it will be normalized to ["-" ^ name].
Unless [full_flag_required] is used, one doesn't have to pass [name] exactly on
the command line, but only an unambiguous prefix of [name] (i.e., a prefix which
is not a prefix of any other flag's name).
NOTE: the [doc] for a flag which takes an argument should be of the form
[arg_name ^ " " ^ description] where [arg_name] describes the argument and
[description] describes the meaning of the flag.
NOTE: flag names (including aliases) containing underscores will be rejected.
Use dashes instead.
NOTE: "-" by itself is an invalid flag name and will be rejected.
*)valflag:?aliases:stringlist->?full_flag_required:unit->string->'aFlag.t->doc:string->'at(** [flag_optional_with_default_doc name arg_type sexp_of_default ~default ~doc] is
a shortcut for [flag], where:
+ The [Flag.t] is [optional_with_default default arg_type]
+ The [doc] is passed through with an explanation of what the default value
appended. *)valflag_optional_with_default_doc:?aliases:stringlist->?full_flag_required:unit->string->'aArg_type.t->('a->Sexp.t)->default:'a->doc:string->'at(** [anon spec] specifies a command that, among other things, takes the anonymous
arguments specified by [spec]. *)valanon:'aAnons.t->'at(** [escape_anon ~final_anon] parses [anon] and then stops parsing. Remaining
command line arguments are collected in the [string list], even if they start
with dashes.
See [escape] for the flag version of this behavior.
The final anon is required to indicate when to stop parsing. *)valescape_anon:final_anon:'aAnons.t->('a*stringlist)tmoduleIf_nothing_chosen:sigtype(_,_)t=|Default_to:'a->('a,'a)t|Raise:('a,'a)t|Return_none:('a,'aoption)tend(** [choose_one clauses ~if_nothing_chosen] expresses a sum type. It raises if more
than one of [clauses] is [Some _]. When [if_nothing_chosen = Raise], it also
raises if none of [clauses] is [Some _]. *)valchoose_one:'aoptiontlist->if_nothing_chosen:('a,'b)If_nothing_chosen.t->'bt(** [choose_one_non_optional clauses ~if_nothing_chosen] expresses a sum type.
It raises if more than one of the [clauses] has any flags given on the
command-line, and returns the value parsed from the clause that's given.
When [if_nothing_chosen = Raise], it also raises if none of the [clauses] are
given. *)valchoose_one_non_optional:'atlist->if_nothing_chosen:('a,'b)If_nothing_chosen.t->'bt(** [and_arg_names t] returns both the value of [t] and the names of the arguments
that went into [t]. Useful for errors that reference multiple params. *)valand_arg_names:'at->('a*stringlist)t(** Like [and_arg_names], but asserts that there is exactly one name. *)valand_arg_name:'at->('a*string)tvalarg_names:'at->stringlistendincludeS(** @inline *)(** If [None] is returned, then the param acts as a required flag that was omitted.
This is intended to be used with [choose_one_non_optional]. *)valoptional_to_required:'aoptiont->'at(** Values included for convenience so you can specify all command line parameters
inside a single local open of [Param]. *)moduleArg_type:moduletypeofArg_typewithtype'at='aArg_type.tincludemoduletypeofArg_type.ExportincludemoduletypeofFlagwithtype'at:='aFlag.tincludemoduletypeofAnonswithtype'at:='aAnons.t(** [parse t cmdline] will attempt to parse [t] out of [cmdline]. Beware there is
nothing stopping effectful operations in [t] from being performed. *)valparse:'at->stringlist->'aOr_error.tendmoduleLet_syntax:sig(** Substituted below. *)type'atvalreturn:'a->'atincludeApplicative.Applicative_infixwithtype'at:='atmoduleLet_syntax:sig(** Substituted below. *)type'atvalreturn:'a->'atvalmap:'at->f:('a->'b)->'btvalboth:'at->'bt->('a*'b)tmoduleOpen_on_rhs=Paramendwithtype'at:='aParam.tendwithtype'at:='aParam.t(** The old interface for command-line specifications -- {b Do Not Use}.
This interface should not be used. See the {{!Core.Command.Param}[Param]}
module for the new way to do things. *)moduleSpec:sig(** {2 Command parameters} *)(** Specification of an individual parameter to the command's main function. *)type'aparam='aParam.t[@@deprecated"[since 2019-03] use [Command.Param.t] instead"]includeParam.Swithtype'at:='aParam.t(** Superceded by [return], preserved for backwards compatibility. *)valconst:'a->'aParam.t[@@deprecated"[since 2018-10] use [Command.Param.return] instead of [Command.Spec.const]"](** Superceded by [both], preserved for backwards compatibility. *)valpair:'aParam.t->'bParam.t->('a*'b)Param.t[@@deprecated"[since 2018-10] use [Command.Param.both] instead of [Command.Spec.pair]"](** {2 Command specifications} *)(** Composable command-line specifications. *)type(-'main_in,+'main_out)t(** Ultimately one forms a basic command by combining a spec of type [('main, unit ->
unit) t] with a main function of type ['main]; see the [basic] function below.
Combinators in this library incrementally build up the type of main according to
what command-line parameters it expects, so the resulting type of [main] is
something like:
[arg1 -> ... -> argN -> unit -> unit]
It may help to think of [('a, 'b) t] as a function space ['a -> 'b] embellished with
information about:
{ul {- how to parse the command line}
{- what the command does and how to call it}
{- how to autocomplete a partial command line}}
One can view a value of type [('main_in, 'main_out) t] as a function that transforms
a main function from type ['main_in] to ['main_out], typically by supplying some
arguments. E.g., a value of type [Spec.t] might have type:
{[
(arg1 -> ... -> argN -> 'r, 'r) Spec.t
]}
Such a value can transform a main function of type [arg1 -> ... -> argN -> 'r] by
supplying it argument values of type [arg1], ..., [argn], leaving a main function
whose type is ['r]. In the end, [Command.basic] takes a completed spec where
['r = unit -> unit], and hence whose type looks like:
{[
(arg1 -> ... -> argN -> unit -> unit, unit -> unit) Spec.t
]}
A value of this type can fully apply a main function of type [arg1 -> ... -> argN ->
unit -> unit] to all its arguments.
The final unit argument allows the implementation to distinguish between the phases
of (1) parsing the command line and (2) running the body of the command. Exceptions
raised in phase (1) lead to a help message being displayed alongside the exception.
Exceptions raised in phase (2) are displayed without any command line help.
The view of [('main_in, main_out) Spec.t] as a function from ['main_in] to
['main_out] is directly reflected by the [step] function, whose type is:
{[
val step : ('m1 -> 'm2) -> ('m1, 'm2) t
]}
*)(** [spec1 ++ spec2 ++ ... ++ specN] composes [spec1] through [specN].
For example, if [spec_a] and [spec_b] have types:
{[
spec_a: (a1 -> ... -> aN -> 'ra, 'ra) Spec.t;
spec_b: (b1 -> ... -> bM -> 'rb, 'rb) Spec.t
]}
then [spec_a ++ spec_b] has the following type:
{[
(a1 -> ... -> aN -> b1 -> ... -> bM -> 'rb, 'rb) Spec.t
]}
So, [spec_a ++ spec_b] transforms a main function by first supplying [spec_a]'s
arguments of type [a1], ..., [aN], and then supplying [spec_b]'s arguments of type
[b1], ..., [bm].
One can understand [++] as function composition by thinking of the type of specs
as concrete function types, representing the transformation of a main function:
{[
spec_a: \/ra. (a1 -> ... -> aN -> 'ra) -> 'ra;
spec_b: \/rb. (b1 -> ... -> bM -> 'rb) -> 'rb
]}
Under this interpretation, the composition of [spec_a] and [spec_b] has type:
{[
spec_a ++ spec_b : \/rc. (a1 -> ... -> aN -> b1 -> ... -> bM -> 'rc) -> 'rc
]}
And the implementation is just function composition:
{[
sa ++ sb = fun main -> sb (sa main)
]}
*)(** The empty command-line spec. *)valempty:('m,'m)t(** Command-line spec composition. *)val(++):('m1,'m2)t->('m2,'m3)t->('m1,'m3)t(** Adds a rightmost parameter onto the type of main. *)val(+>):('m1,'a->'m2)t->'aParam.t->('m1,'m2)t(** Adds a leftmost parameter onto the type of main.
This function should only be used as a workaround in situations where the order of
composition is at odds with the order of anonymous arguments because you're
factoring out some common spec. *)val(+<):('m1,'m2)t->'aParam.t->('a->'m1,'m2)t(** Combinator for patching up how parameters are obtained or presented.
Here are a couple examples of some of its many uses:
{ul
{li {i introducing labeled arguments}
{v step (fun m v -> m ~foo:v)
+> flag "-foo" no_arg : (foo:bool -> 'm, 'm) t v}}
{li {i prompting for missing values}
{v step (fun m user -> match user with
| Some user -> m user
| None -> print_string "enter username: "; m (read_line ()))
+> flag "-user" (optional string) ~doc:"USER to frobnicate"
: (string -> 'm, 'm) t v}}
}
A use of [step] might look something like:
{[
step (fun main -> let ... in main x1 ... xN) : (arg1 -> ... -> argN -> 'r, 'r) t
]}
Thus, [step] allows one to write arbitrary code to decide how to transform a main
function. As a simple example:
{[
step (fun main -> main 13.) : (float -> 'r, 'r) t
]}
This spec is identical to [const 13.]; it transforms a main function by supplying
it with a single float argument, [13.]. As another example:
{[
step (fun m v -> m ~foo:v) : (foo:'foo -> 'r, 'foo -> 'r) t
]}
This spec transforms a main function that requires a labeled argument into
a main function that requires the argument unlabeled, making it easily composable
with other spec combinators.
*)valstep:('m1->'m2)->('m1,'m2)t(** Combinator for defining a class of commands with common behavior.
Here are two examples of command classes defined using [wrap]:
{ul
{li {i print top-level exceptions to stderr}
{v wrap (fun ~run ~main ->
Exn.handle_uncaught ~exit:true (fun () -> run main)
) : ('m, unit) t -> ('m, unit) t
v}}
{li {i iterate over lines from stdin}
{v wrap (fun ~run ~main ->
In_channel.iter_lines stdin ~f:(fun line -> run (main line))
) : ('m, unit) t -> (string -> 'm, unit) t
v}}
}
*)valwrap:(run:('m1->'r1)->main:'m2->'r2)->('m1,'r1)t->('m2,'r2)tmoduleArg_type:moduletypeofArg_typewithtype'at='aArg_type.tincludemoduletypeofArg_type.Export(** A flag specification. *)type'aflag='aFlag.tincludemoduletypeofFlagwithtype'at:='aflag(** [flags_of_args_exn args] creates a spec from [Caml.Arg.t]s, for compatibility with
OCaml's base libraries. Fails if it encounters an arg that cannot be converted.
NOTE: There is a difference in side effect ordering between [Caml.Arg] and
[Command]. In the [Arg] module, flag handling functions embedded in [Caml.Arg.t]
values will be run in the order that flags are passed on the command line. In the
[Command] module, using [flags_of_args_exn flags], they are evaluated in the order
that the [Caml.Arg.t] values appear in [args]. *)valflags_of_args_exn:(Stdlib.Arg.key*Stdlib.Arg.spec*Stdlib.Arg.doc)list->('a,'a)t[@@deprecated"[since 2018-10] switch to Command.Param"](** A specification of some number of anonymous arguments. *)type'aanons='aAnons.tincludemoduletypeofAnonswithtype'at:='aanons(** Conversions to and from new-style [Param] command line specifications. *)valto_param:('a,'r)t->'a->'rParam.tvalof_param:'rParam.t->('r->'m,'m)tend(** Commands which can be combined into a hierarchy of subcommands. *)typettype('main,'result)basic_spec_command=summary:string->?readme:(unit->string)->('main,unit->'result)Spec.t->'main->t(** [basic_spec ~summary ?readme spec main] is a basic command that executes a function
[main] which is passed parameters parsed from the command line according to [spec].
[summary] is to contain a short one-line description of its behavior. [readme] is to
contain any longer description of its behavior that will go on that command's help
screen. *)valbasic_spec:('main,unit)basic_spec_commandtype'resultbasic_command=summary:string->?readme:(unit->string)->(unit->'result)Param.t->t(** Same general behavior as [basic_spec], but takes a command line specification built up
using [Params] instead of [Spec]. *)valbasic:unitbasic_command(** [basic_or_error] is like [basic], except that the main function it expects may
return an error, in which case it prints out the error message and shuts down with
exit code 1. *)valbasic_or_error:unitOr_error.tbasic_command(** [group ~summary subcommand_alist] is a compound command with named subcommands, as
found in [subcommand_alist]. [summary] is to contain a short one-line description of
the command group. [readme] is to contain any longer description of its behavior that
will go on that command's help screen.
NOTE: subcommand names containing underscores will be rejected; use dashes instead.
[body] is called when no additional arguments are passed -- in particular, when no
subcommand is passed. Its [path] argument is the subcommand path by which the group
command was reached. *)valgroup:summary:string->?readme:(unit->string)->?preserve_subcommand_order:unit->?body:(path:stringlist->unit)->(string*t)list->t(** [lazy_group] is the same as [group], except that the list of subcommands may be
generated lazily. *)vallazy_group:summary:string->?readme:(unit->string)->?preserve_subcommand_order:unit->?body:(path:stringlist->unit)->(string*t)listLazy.t->t(** [exec ~summary ~path_to_exe] runs [exec] on the executable at [path_to_exe]. If
[path_to_exe] is [`Absolute path] then [path] is executed without any further
qualification. If it is [`Relative_to_me path] then [Filename.dirname
Sys.executable_name ^ "/" ^ path] is executed instead. All of the usual caveats about
[Sys.executable_name] apply: specifically, it may only return an absolute path in
Linux. On other operating systems it will return [Sys.argv.(0)]. If it is
[`Relative_to_argv0 path] then [Sys.argv.(0) ^ "/" ^ path] is executed.
The [child_subcommand] argument allows referencing a subcommand one or more levels
below the top-level of the child executable. It should {e not} be used to pass flags
or anonymous arguments to the child.
Care has been taken to support nesting multiple executables built with Command. In
particular, recursive help and autocompletion should work as expected.
NOTE: Non-Command executables can be used with this function but will still be
executed when [help -recursive] is called or autocompletion is attempted (despite the
fact that neither will be particularly helpful in this case). This means that if you
have a shell script called "reboot-everything.sh" that takes no arguments and reboots
everything no matter how it is called, you shouldn't use it with [exec].
Additionally, no loop detection is attempted, so if you nest an executable within
itself, [help -recursive] and autocompletion will hang forever (although actually
running the subcommand will work). *)valexec:summary:string->?readme:(unit->string)->?child_subcommand:stringlist->?env:env->path_to_exe:[`Absoluteofstring|`Relative_to_argv0ofstring|`Relative_to_meofstring]->unit->t(** [of_lazy thunk] constructs a lazy command that is forced only when necessary to run it
or extract its shape. *)valof_lazy:tLazy.t->t(** Extracts the summary string for a command. *)valsummary:t->stringmoduleShape=Shape(** call this instead of [Core.exit] if in command-related code that you want to run in
tests. For example, in the body of [Command.Param.no_arg_abort] *)valexit:int->_moduleFor_telemetry:sig(** Returns the command and the list of subcommands. Arguments to the [Command.t] are
not included.
If a subcommand was specified as a unique prefix [normalized_path] will contain
the full subcommand name.
If the entry point to the program was not through [Command] returns [None].
*)valnormalized_path:unit->stringlistoption(** Returns the full list of arguments that were parsed by [Command].
If a flag name was specified as a unique prefix [normalized_args] will contain the
full flag name.
If the entry point to the program was not through [Command] returns [None].
*)valnormalized_args:unit->stringlistoptionend(** [Deprecated] should be used only by [Deprecated_command]. At some point
it will go away. *)moduleDeprecated:sigmoduleSpec:sigvalno_arg:hook:(unit->unit)->boolSpec.flagvalescape:hook:(stringlist->unit)->stringlistoptionSpec.flagvalad_hoc:usage_arg:string->stringlistSpec.anonsendvalsummary:t->stringvalhelp_recursive:cmd:string->with_flags:bool->expand_dots:bool->t->string->(string*string)listvalget_flag_names:t->stringlistend(** Deprecated values that moved from [Core.Command] to [Command_unix]. *)valrun:[`Use_Command_unix][@@deprecated"[since 2021-03] Use [Command_unix]"]modulePath:sigend[@@deprecated"[since 2021-03] Use [Command_unix]"]valshape:[`Use_Command_unix][@@deprecated"[since 2021-03] Use [Command_unix]"](**/**)(*_ See the Jane Street Style Guide for an explanation of [Private] submodules:
https://opensource.janestreet.com/standards/#private-submodules *)modulePrivate:sigvalabs_path:dir:string->string->stringvalword_wrap:string->int->stringlistmoduleAnons:sigvalnormalize:string->stringendmodulePath:sigtypetvalempty:tvalcreate:path_to_exe:string->tvalappend:t->subcommand:string->tvalparts:t->stringlistvalreplace_first:t->from:string->to_:string->tvalto_string:t->stringvalto_string_dots:t->stringendmoduleCmdline:sigtypet[@@derivingcompare]valof_list:stringlist->tvalextend:t->extend:(stringlist->stringlist)->path:Path.t->tendmoduleSpec:sigvalflags_of_args_exn:(string*Stdlib.Arg.spec*string)list->('a,'a)Spec.tvalto_string_for_choose_one:_Param.t->stringendmoduleFor_unix(M:For_unixwithtypeenv_var:=string):sigvalshape:t->Shape.tvalhelp_for_shape:Shape.t->Path.t->expand_dots:bool->flags:bool->recursive:bool->stringvalrun:?add_validate_parsing_flag:bool(** When [add_validate_parsing_flag] is true a new flag `-validate-parsing` is
added to all subcommands. When this flag is passed the command will exit
immediately if parsing is succesfull and return 0. This flag does not take any
steps to stop side effects from occurring. *)->?verbose_on_parse_error:bool->?version:string->?build_info:string->?argv:stringlist->?extend:(stringlist->stringlist)->?when_parsing_succeeds:(unit->unit)->?complete_subcommands:(path:stringlist->part:string->stringlistlist->stringlistoption)(** [complete_subcommands ~path ~part options] allows users to provide a custom
tab completion handler to an invocation of [run]. By default, completion is
performed via standard bash completion.
One may use this to, e.g. use a fuzzy finder for completion.
Imagine a command whose structure is "subcommand1 subcommand2",
[path] represents the subcommand invocations interpreted thusfar in being
matched.
[part] is the portion of the auto-completion that is being matched upon.
If a user attempts to complete "exe subcommand1 s<TAB>", they will get
["subcommand1"] in [path] and "s" in [part].
[options] are the valid subcommand invocations to present to the user.
[complete_subcommands] should return the selection made, if any. *)->t->unitvaldeprecated_run:t->cmd:string->args:stringlist->is_help:bool->is_help_rec:bool->is_help_rec_flags:bool->is_expand_dots:bool->unitendendend