Generate Julia code that provide functions to run CLI programs.
The specification to generate this code is similar to what Fig uses, but in JSON format. So for popular CLIs, a starting point can be the spec found in the Fig autocomplete repo. Remember to convert from js
to json
format.
generate(
specfile::AbstractString,
outputfile::AbstractString;
kwargs...
)
Generate a Julia module for a CLI based on a specification file. Refer to Generated Code Structure for more details of the code generated.
Arguments:
specfile
: path to the specification fileoutputfile
: path to the output file
Keyword arguments:
custom_include
: a string to include at the top of the generated moduleignore_base_command
: iftrue
, do not generate the base command. The base command must be made available by the caller, either by including it incustom_include
or by defining it in the module before callinggenerate
.
Code is generated into a module named CLI
. The module name is fixed, the intent being for it to be wrapped within another module or package.
The primary command line options are generated as methods within the module, with names same as the option name. The optional parameters are keyword arguments. And the methods accept other arguments to be passed to the command.
An example that generates a CLI for grep
is included:
grep
specsgrep
generated codegrep
example use of generated code
A more complex spec is that of Open Policy Agent:
opa
specsopa
generated code
Example:
function grep(
ctx::CommandLine,
_args...;
help::Union{Nothing,Bool} = false,
extended_regexp::Union{Nothing,Bool} = false,
...,
file::Union{Nothing,AbstractString} = nothing,
)
Each method accepts an instance of CommandLine
as the first argument that holds the execution context. It has the following members:
exec
: a no argument function that provides the base command to execute in a juliado
block.cmdopts
: keyword arguments that should be used to further customize theCmd
creationpipelineopts
: keyword arguments that should be used to further customize thepipeline
creation
CommandLine
is generated by default, and is termed as the "base command". It can be overridden during code generation by passing the optional ignore_base_command
and custom_include
keyword arguments. See "Code generation".
Create a CommandLine
and invoke methods. Example:
julia> include("grep.jl");
julia> ctx = CLI.CommandLine();
julia> CLI.grep(ctx, "CLI", "grep.jl"; ignore_case=true, count=true);
4
julia> CLI.grep(ctx, "the", "grep.jl"; ignore_case=true, count=true);
40