Comonicon.Comonicon
— ModuleAll the terminals are under my command. Comonicon
is a CLI (Command Line Interface) generator that features light-weight dependency (optional to have zero dependency), fast start-up time and easy to use. See the website for more info.
Comonicon.CommandError
— Typestruct CommandError <: CommandException
Exception type for general CLI compatible errors thrown by cmd_error
.
Comonicon.CommandException
— TypeCommandException <: Exception
Abstract type for command exceptions. All command exceptions should contain an exitcode
field.
Comonicon.CommandExit
— Typestruct CommandExit <: CommandException
Exception type for cmd_exit
.
Comonicon.cmd_error
— Functioncmd_error(msg::String, code::Int = 1)
Throw a CommandError
with message msg
and return code code
. This is preferred as exception handle when writing a CLI compatible Julia program.
When the program is running in normal Julia execution the error will print as normal Julia exception with stacktrace.
When the progrm is running from a CLI entry, the exception is printed as standard CLI exceptions with exit code (default is 1
). Then the corresponding help message is printed.
Comonicon.cmd_exit
— Functioncmd_exit(code::Int = 0)
Exit the CLI program with code
. This method is preferred over exit
to make sure the program won't exit directly without handling the exception.
Comonicon.default_name
— Methoddefault_name(x::String)
Return the lowercase of a given package name. It will ignore the suffix if it ends with ".jl".
Comonicon.get_version
— Methodget_version(m::Module)
Get the version of a given module. It will try to find the version of Project.toml
if the given module is a project module. If fails, it returns v"0.0.0"
.
Comonicon.parse_kwargs
— Methodparse_kwargs(fn::JLFunction) -> flags, options
Parse the keyword arguments of function expression fn
into intermediate Julia CLI objects JLFlag
and JLOption
.
Comonicon.rm_format
— Functionrm_format(md)
Remove Markdown DOM and flatten to strings.
Comonicon.set_cmd!
— Functionset_cmd!(cmds::Dict, cmd)
register cmd
in the command registry cmds
, which usually is a constant CASTED_COMMANDS
under given module.
Comonicon.write_cmd
— Methodwrite_cmd(filename, cmd::Entry)
Write a command to filename
.
Comonicon.@cast
— Macro@cast <function definition>
@cast <module definition>
Denote a Julia expression is a command. If the expression is a function definition, it will be parsed as a leaf command, if the expression is a module definition or module name, it will be parsed as a node command. This macro must be used with @main
to create a multi-command CLI.
Quick Example
# in a script or module
"""
sum two numbers.
# Args
- `x`: first number
- `y`: second number
# Options
- `-p, --precision=<type>`: precision of the calculation.
# Flags
- `-f, --fastmath`: enable fastmath.
"""
@cast function sum(x, y; precision::String="float32", fastmath::Bool=false)
# implementation
return
end
"product two numbers"
@cast function prod(x, y)
return
end
@main
Comonicon.@lazyload
— Macro@lazyload expr @cast <valid castable expr>
Evaluate expr
if command f
is called. This is useful for reducing the latency of scripts that has subcmds depend on plotting, serialization etc.
Please see @cast
for valid expression specifications.
This macro only works at top-level command and thus can only be used in Main
and only works in scripts. Using this macro in any other module or a project module will not work.
Comonicon.@main
— Macro@main
@main <function definition>
Main entry of the CLI application.
Quick Example
# in a script or module
"""
sum two numbers.
# Args
- `x`: first number
- `y`: second number
# Options
- `-p, --precision=<type>`: precision of the calculation.
# Flags
- `-f, --fastmath`: enable fastmath.
"""
@main function sum(x, y; precision::String="float32", fastmath::Bool=false)
# implementation
return
end
CLI Definitions and Julia Syntax Mapping
positional arguments normal inputs, these are mapped as Julia function arguments, e.g
sum 1 2
sum
is the command, and 1
, 2
are positional arguments.
options arguments with syntax --<name>=<value>
or --<name> <value>
, these are mapped as Julia keyword arguments, e.g
sum --precision=float32 1 2
--precision
is the option of command sum
and has value float32
.
short options arguments with syntax -<letter>=<value>
or -<letter><value>
or --<letter> <value>
, the letter is usually the first character of a normal option, e.g
sum -pfloat32 1 2
-p
is the same as --precision
, but in short hand, this is enabled by writing corresponding docstring (see the next section on docstring syntax).
flags like options, but without any value, e.g --<name>
, this is mapped to a special type of keyword argument that is of type Bool
and has default value false
, e.g
sum --fastmath
short flags flags with syntax -<letter>
, the letter should be the first character of the corresponding normal flag, e.g
sum -f
Doc String Syntax
Each different kind of inputs must have a different level-1 section (markdown syntax #<section name>
).
The docstring must have section name:
#Args
or#Arguments
to declare the documentation of positional arguments.#Options
to declare the documentation of options.#Flags
to declare the documentation of flags.
Examples
The simplest usage is creating the following commands
"""
an example command
# Args
- `x`: first argument
- `y`: second argument
- `z`: last argument
# Flags
- `-f, --flag`: a flag, optionally can be a short flag.
# Options
- `-o, --option=<int>`: an option, optionally can be short option.
"""
@cast function mycommand(x, y, z; flag::Bool=false, option::Int=2)
# some implementation
return
end
@cast function myothercommand(xs...)
# another command with variatic arguments
return
end
"""
My main command.
"""
@main # declare the entry
this can be used in command line as mycommand 1 2 3 --flag
, you can also just type -h
to check the detailed help info.
The command line documentation will be generated automatically from your Julia docstring.
If you have deeper hierachy of commands, you can also put @cast
on a Julia module.
using Comonicon
@cast module NodeCommand
using Comonicon
@cast module NodeSubCommand
using Comonicon
@cast bar(x) = println("bar $x")
end
@cast foo(x) = println("foo $x")
@main
end
NodeCommand.command_main()
Comonicon.Configs.Application
— TypeApplication
Application build configurations.
Keywords
path
: application build path, default is "build".incremental
: set totrue
to build incrementally, default istrue
.filter_stdlibs
: set totrue
to filter out unused stdlibs, default isfalse
.cpu_target
: cpu target to build, default isPackageCompiler.default_app_cpu_target()
.precompile
: precompile configurations, seePrecompile
, default isPrecompile()
.c_driver_program
: driver program.
Comonicon.Configs.Command
— TypeCommand
Configs for Command execution.
Keywords
color
: whether print with color in help page, default istrue
.static
: whether genrate help info at compile time, the format won't be adaptive to displaysize anymore, iftrue
, default istrue
.width
: ifstatic=true
,width
is used to set the static size of expected terminal.dash
: whether parse--
seperator, default istrue
.plugin
: parse<main CLI name>-<plugin>
for CLI plugin, default isfalse
.
Comonicon.Configs.Comonicon
— TypeComonicon
Build configurations for Comonicon. One can set this option via Comonicon.toml
under the root path of a Julia project directory and read in using read_configs
.
Keywords
name
: required, the name of CLI file to install.command
: configs for command parsing.install
: installation options, see alsoInstall
.sysimg
: system image build options, see alsoSysImg
.download
: download options, see alsoDownload
.application
: application build options, see alsoApplication
.
Comonicon.Configs.Download
— TypeDownload
Download information.
Keywords
host
: where are the tarballs hosted, default is "github.com"user
: required, user name on the host.repo
: required, repo name on the host.
Currently this only supports github, and this is considered experimental.
Comonicon.Configs.Install
— TypeInstall
Installation configurations.
Keywords
path
: installation path.completion
: set totrue
to install shell auto-completion scripts.quiet
: print logs or not, default isfalse
.compile
: julia compiler option for CLIs if not built as standalone application, default is "min".optimize
: julia compiler option for CLIs if not built as standalone application, default is2
.nthreads
: julia compiler option for CLIs if not built as standalone application, default is1
.
Comonicon.Configs.Precompile
— TypePrecompile
Precompilation files for PackageCompiler
.
Keywords
execution_file
: precompile execution file.statements_file
: precompile statements file.
Comonicon.Configs.SysImg
— TypeSysImg
System image build configurations.
Keywords
path
: system image path to generate into, default is "deps/lib".incremental
: set totrue
to build incrementally, default istrue
.filter_stdlibs
: set totrue
to filter out unused stdlibs, default isfalse
.cpu_target
: cpu target to build, default isPackageCompiler.default_app_cpu_target()
.precompile
: precompile configurations, seePrecompile
, default isPrecompile()
.
Comonicon.Configs.find_comonicon_toml
— Functionfind_comonicon_toml(path::String, files=["Comonicon.toml", "JuliaComonicon.toml"])
Find Comonicon.toml
or JuliaComonicon.toml
in given path.
Comonicon.Configs.read_options
— Methodread_options(comonicon; kwargs...)
Read in Comonicon build options. The argument comonicon
can be:
- a module of a Comonicon CLI project.
- a path to a Comonicon CLI project that contains either
JuliaComonicon.toml
orComonicon.toml
. - a path to a Comonicon CLI build configuration file named either
JuliaComonicon.toml
orComonicon.toml
.
In some cases, you might want to change the configuration written in the TOML file temporarily, e.g for writing build tests etc. In this case, you can modify the configuration using corresponding keyword arguments.
keyword arguments of Application
and SysImg
are the same, thus keys like filter_stdlibs
are considered ambiguous in read_options
, but you can specifiy them by specifiy the specific Application
or SysImg
object, e.g
read_options(MyCLI; sysimg=SysImg(filter_stdlibs=false))
See also Comonicon
, Install
, SysImg
, Application
, Download
, Precompile
.
Comonicon.Configs.read_toml
— Methodread_toml(mod::Module)
Read Comonicon.toml
or JuliaComonicon.toml
in given module's project path.
Comonicon.Configs.read_toml
— Methodread_toml(path::String)
Read Comonicon.toml
or JuliaComonicon.toml
in given path.
Comonicon.Arg.ArgType
— Typeabstract type ArgType
Abstract type for special CLI arguments. These types are useful for generating shell autocompletions and argument checks. All the ArgType
should implement a corresponding Base.tryparse
method, otherwise it will fallback to passing the raw string as the content
field.
Comonicon.Arg.DirName
— Typestruct DirName <: ArgType
DirName(content)
A DirName
object denotes a directory name as CLI input.
Comonicon.Arg.FileName
— Typestruct FileName <: ArgType
FileName(content)
A FileName
object denotes a file name as CLI input.
Comonicon.Arg.Path
— Typestruct Path <: ArgType
Path(content)
A Path
object denotes a path as CLI input.
Comonicon.Arg.Prefix
— Typestruct Prefix{name} <: ArgType
Prefix{name}(content)
Denotes strings with prefix name
as CLI input, e.g data-xxx
Comonicon.Arg.Suffix
— Typestruct Suffix{name} <: ArgType
Suffix{name}(content)
Denotes strings with suffix name
as CLI input, e.g xxxxx.jl
.
Comonicon.Arg.UserName
— Typestruct UserName <: ArgType
UserName(content)
A UserName
object denotes a Linux/MacOS user name as CLI input.
Comonicon.Arg.@Prefix_str
— Macromacro Prefix_str
Prefix"<name>"
Syntax sugar for creating a prefix type, e.g Predix"data"
is the same as Prefix{:data}
.
Comonicon.Arg.@Suffix_str
— Macromacro Suffix_str
Suffix"<name>"
Syntax sugar for creating a suffix type, e.g Suffix"data"
is the same as Suffix{:data}
.
Comonicon.Builder.create_command_env
— Functioncreate_command_env(m::Module, envpath::String=mktempdir(); test_deps=true)
Create an environment to execute the CLI command.
Arguments
m
: the CLI module.envpath
: the generated environment path.
Keyword Arguments
test_deps
: include test deps or not.
Comonicon.Builder.osname
— Methodosname()
Return the name of OS, will be used in building tarball.
Comonicon.AST.Argument
— Typestruct Argument <: ComoniconExpr
type for positional argument of a command.
Fields
name::String
: name of the argument.type
: type of the argument, defaultAny
.vararg::Bool
: if the argument is a variant argument, defaultfalse
.require::Bool
: if the argument is required, defaulttrue
.default::Maybe{String}
: the default value of this argument if argument is not required (optional), defaultnothing
.description::Description
: the description of this argument, defaultDescription()
.line::Maybe{LineNumberNode}
: the line number of this argument, default isnothing
.
Constructors
Argument(fields_above...)
Argument(;fields_above...)
Comonicon.AST.Color
— Typemutable struct Color
Color configuration.
Fields
name::Symbol
: command name color.args::Symbol
: command args color.dash::Symbol
: command flag/option color.
Comonicon.AST.ComoniconExpr
— Typeabstract type ComoniconExpr end
Abstract type for Comonicon CLI expression.
Comonicon.AST.Description
— Typestruct Description <: ComoniconExpr
type for description of a command object.
Fields
brief::String
: brief introduction of the command, will be printed as the first sentence of the whole description as well as brief intro in upper level help info.content::String
: long introduction of the command.
Constructors
Description(;brief="", content="")
Description(brief)
Comonicon.AST.Entry
— Typestruct Entry <: ComoniconExpr
Top-level entry of the CLI.
Fields
root::Union{NodeCommand,LeafCommand}
: the entry command.version::Maybe{VersionNumber}
: version number of the command.line::Maybe{LineNumberNode}
: line number of the original Julia program.
Constructors
Entry(fields_above...)
Entry(;fields_above...)
Comonicon.AST.Flag
— Typestruct Flag <: ComoniconExpr
Type for flag in CLI, e.g --flag
or -f
.
Fields
sym
: the symbol in Julia programs.name::String
: name of the flag, default is the same assym
but will replace_
with-
.short::Bool
: if this flag support short flag syntax e.g-f
, default isfalse
.description::Description
: description of this flag, default isDescription()
.line::Maybe{LineNumberNode}
: the line number of this flag object in original Julia program.
Constructors
Flag(fields_above...)
Flag(;fields_above...)
Comonicon.AST.LeafCommand
— Typestruct LeafCommand <: ComoniconExpr
Type for a leaf command in CLI. A leaf command is the command that actually execute the program e.g
main-cmd node-cmd leaf-cmd 1 2 3
Fields
fn
: a Julia callable that executes the command.name::String
: name of the command.args::Vector{Argument}
: list of CLI arguments, seeArgument
, default isArgument[]
.nrequire::Int
: number of required arguments, default is the number ofrequire==true
arugments inargs
.vararg::Maybe{Argument}
: variant argument, default isnothing
.flags::OrderedDict{String, Flag}
: map between flag name and flag object, seeFlag
, default is the empty collection.options::OrderedDict{String, Option}
: map between option name and option object, seeOption
, default is the empty collection.description::Description
: description of the leaf command, default isDescription()
.line::Maybe{LineNumberNode}
: line number of the leaf command in original Julia program.
Constructors
LeafCommand(fields_above...)
LeafCommand(;fields_above...)
Comonicon.AST.NodeCommand
— Typestruct NodeCommand <: ComoniconExpr
Type for node command in a CLI, these command are only used to dispatch the actual command in CLI, and must have sub-command, e.g
main-cmd node-cmd leaf-cmd 1 2 3
Fields
name::String
: name of the command.subcmds::Dict{String, Any}
: sub-commands of the node command, this is aname=>command
dict, the command should be eitherNodeCommand
orLeafCommand
.description::Description
: description of this node command, default isDescription()
.line::Maybe{LineNumberNode}
: line number of the node command in its original Julia program, default isnothing
.
Constructors
NodeCommand(fields_above...)
NodeCommand(;fields_above...)
Comonicon.AST.Option
— Typestruct Option <: ComoniconExpr
type for options, e.g --option=<value>
or -o<value>
.
Fields
sym::Symbol
: symbol of the option in Julia program.name::String
: name of the option in shell, by default this is the same assym
but will replace_
with-
.hint::Maybe{String}
: hint message of this option, default isnothing
.require::Bool
: if this option is required, default isfalse
.type
: type of the option value, default isAny
.short::Bool
: if the option support short option syntax (-o<value>
syntax), default isfalse
.description::Description
: description of this option, default isDescription()
.line::Maybe{LineNumberNode}
: line number of this option in Julia scripts.
Comonicon.AST.Terminal
— Typemutable struct Terminal
Configurations for terminal printing.
Fields
Comonicon.AST.print_cmd
— Functionprint_cmd([io::IO], cmd, [terminal::Terminal])
Print the command object in terminal.
Arguments
io::IO
: an IO object, default isstdout
.cmd
: a command object, can beEntry
,NodeCommand
,LeafCommand
.terminal::Terminal
: aTerminal
object, contains the printing and terminal configuration. See alsoTerminal
.
Comonicon.AST.splitlines
— Functionsplitlines(s, width = 80)
Split a given string into lines of width 80
characters.
Comonicon.AST.splittext
— Methodsplittext(s)
Split the text in string s
into an array, but keep all the separators attached to the preceding word.
this is copied from Luxor/text.jl
Comonicon.JuliaExpr.emit
— Functionemit(cmd::Entry[, ptr::Int=1])
Emit Expr
from a Entry
.
Comonicon.JuliaExpr.emit_dash_body
— Functionemit dash parsing code (contains --
).
Comonicon.JuliaExpr.emit_norm_body
— Functionemit the normal parsing code (do not contain dash --
)
Comonicon.Tools.prompt
— Methodprompt(msg::AbstractString[, yes::Bool=false])
Prompt with message to ask user Yes or No.
Arguments
msg
: the message to show in prompt.
Keyword Arguments
yes
: skip the prompt and always returntrue
, default isfalse
.require
: require user to input the answer explicitly. This will repeat 3 times to ask user to input the answer then throw anCommandError
.
Comonicon.Tools.prompt
— Methodprompt(f, [io=stdin,] yes::Bool=false)
Prompt with custom printing to ask user Yes or No.
Arguments
f
: a function with no arguments, which prints the prompt message.io
: user input stream, default isstdin
.
Keyword Arguments
yes
: skip the prompt and always returntrue
, default isfalse
.require
: require user to input the answer explicitly. This will repeat 3 times to ask user to input the answer then throw anCommandError
.