Comonicon.ComoniconModule

All 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.CommandExceptionType
CommandException <: Exception

Abstract type for command exceptions. All command exceptions should contain an exitcode field.

Comonicon.cmd_errorFunction
cmd_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_exitFunction
cmd_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_nameMethod
default_name(x::String)

Return the lowercase of a given package name. It will ignore the suffix if it ends with ".jl".

Comonicon.get_versionMethod
get_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_kwargsMethod
parse_kwargs(fn::JLFunction) -> flags, options

Parse the keyword arguments of function expression fn into intermediate Julia CLI objects JLFlag and JLOption.

Comonicon.set_cmd!Function
set_cmd!(cmds::Dict, cmd)

register cmd in the command registry cmds, which usually is a constant CASTED_COMMANDS under given module.

Comonicon.@castMacro
@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.@lazyloadMacro
@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.

Warning

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.@mainMacro
@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.ApplicationType
Application

Application build configurations.

Keywords

  • path: application build path, default is "build".
  • incremental: set to true to build incrementally, default is true.
  • filter_stdlibs: set to true to filter out unused stdlibs, default is false.
  • cpu_target: cpu target to build, default is PackageCompiler.default_app_cpu_target().
  • precompile: precompile configurations, see Precompile, default is Precompile().
  • c_driver_program: driver program.
Comonicon.Configs.CommandType
Command

Configs for Command execution.

Keywords

  • color: whether print with color in help page, default is true.
  • static: whether genrate help info at compile time, the format won't be adaptive to displaysize anymore, if true, default is true.
  • width: if static=true, width is used to set the static size of expected terminal.
  • dash: whether parse -- seperator, default is true.
  • plugin: parse <main CLI name>-<plugin> for CLI plugin, default is false.
Comonicon.Configs.ComoniconType
Comonicon

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 also Install.
  • sysimg: system image build options, see also SysImg.
  • download: download options, see also Download.
  • application: application build options, see also Application.
Comonicon.Configs.DownloadType
Download

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.
Note

Currently this only supports github, and this is considered experimental.

Comonicon.Configs.InstallType
Install

Installation configurations.

Keywords

  • path: installation path.
  • completion: set to true to install shell auto-completion scripts.
  • quiet: print logs or not, default is false.
  • 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 is 2.
  • nthreads: julia compiler option for CLIs if not built as standalone application, default is 1.
Comonicon.Configs.PrecompileType
Precompile

Precompilation files for PackageCompiler.

Keywords

  • execution_file: precompile execution file.
  • statements_file: precompile statements file.
Comonicon.Configs.SysImgType
SysImg

System image build configurations.

Keywords

  • path: system image path to generate into, default is "deps/lib".
  • incremental: set to true to build incrementally, default is true.
  • filter_stdlibs: set to true to filter out unused stdlibs, default is false.
  • cpu_target: cpu target to build, default is PackageCompiler.default_app_cpu_target().
  • precompile: precompile configurations, see Precompile, default is Precompile().
Comonicon.Configs.find_comonicon_tomlFunction
find_comonicon_toml(path::String, files=["Comonicon.toml", "JuliaComonicon.toml"])

Find Comonicon.toml or JuliaComonicon.toml in given path.

Comonicon.Configs.read_optionsMethod
read_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 or Comonicon.toml.
  • a path to a Comonicon CLI build configuration file named either JuliaComonicon.toml or Comonicon.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.Arg.ArgTypeType
abstract 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.DirNameType
struct DirName <: ArgType
DirName(content)

A DirName object denotes a directory name as CLI input.

Comonicon.Arg.FileNameType
struct FileName <: ArgType
FileName(content)

A FileName object denotes a file name as CLI input.

Comonicon.Arg.PathType
struct Path <: ArgType
Path(content)

A Path object denotes a path as CLI input.

Comonicon.Arg.PrefixType
struct Prefix{name} <: ArgType
Prefix{name}(content)

Denotes strings with prefix name as CLI input, e.g data-xxx

Comonicon.Arg.SuffixType
struct Suffix{name} <: ArgType
Suffix{name}(content)

Denotes strings with suffix name as CLI input, e.g xxxxx.jl.

Comonicon.Arg.UserNameType
struct UserName <: ArgType
UserName(content)

A UserName object denotes a Linux/MacOS user name as CLI input.

Comonicon.Arg.@Prefix_strMacro
macro Prefix_str
Prefix"<name>"

Syntax sugar for creating a prefix type, e.g Predix"data" is the same as Prefix{:data}.

Comonicon.Arg.@Suffix_strMacro
macro 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_envFunction
create_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.AST.ArgumentType
struct Argument <: ComoniconExpr

type for positional argument of a command.

Fields

  • name::String: name of the argument.
  • type: type of the argument, default Any.
  • vararg::Bool: if the argument is a variant argument, default false.
  • require::Bool: if the argument is required, default true.
  • default::Maybe{String}: the default value of this argument if argument is not required (optional), default nothing.
  • description::Description: the description of this argument, default Description().
  • line::Maybe{LineNumberNode}: the line number of this argument, default is nothing.

Constructors

Argument(fields_above...)
Argument(;fields_above...)
Comonicon.AST.ColorType
mutable struct Color

Color configuration.

Fields

  • name::Symbol: command name color.
  • args::Symbol: command args color.
  • dash::Symbol: command flag/option color.
Comonicon.AST.DescriptionType
struct 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.EntryType
struct 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.FlagType
struct 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 as sym but will replace _ with -.
  • short::Bool: if this flag support short flag syntax e.g -f, default is false.
  • description::Description: description of this flag, default is Description().
  • line::Maybe{LineNumberNode}: the line number of this flag object in original Julia program.

Constructors

Flag(fields_above...)
Flag(;fields_above...)
Comonicon.AST.LeafCommandType
struct 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, see Argument, default is Argument[].
  • nrequire::Int: number of required arguments, default is the number of require==true arugments in args.
  • vararg::Maybe{Argument}: variant argument, default is nothing.
  • flags::OrderedDict{String, Flag}: map between flag name and flag object, see Flag, default is the empty collection.
  • options::OrderedDict{String, Option}: map between option name and option object, see Option, default is the empty collection.
  • description::Description: description of the leaf command, default is Description().
  • line::Maybe{LineNumberNode}: line number of the leaf command in original Julia program.

Constructors

LeafCommand(fields_above...)
LeafCommand(;fields_above...)
Comonicon.AST.NodeCommandType
struct 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 a name=>command dict, the command should be either NodeCommand or LeafCommand.
  • description::Description: description of this node command, default is Description().
  • line::Maybe{LineNumberNode}: line number of the node command in its original Julia program, default is nothing.

Constructors

NodeCommand(fields_above...)
NodeCommand(;fields_above...)
Comonicon.AST.OptionType
struct 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 as sym but will replace _ with -.
  • hint::Maybe{String}: hint message of this option, default is nothing.
  • require::Bool: if this option is required, default is false.
  • type: type of the option value, default is Any.
  • short::Bool: if the option support short option syntax (-o<value> syntax), default is false.
  • description::Description: description of this option, default is Description().
  • line::Maybe{LineNumberNode}: line number of this option in Julia scripts.
Comonicon.AST.TerminalType
mutable struct Terminal

Configurations for terminal printing.

Fields

  • width::Int: width of the terminal.
  • left::Int: left column max width.
  • right::Int: right column max width.
  • color:Color: color configurations, see Color.
  • indent::Indent: indent configuration, see Indent.
  • brief::Bool: print the brief intro or not.
Comonicon.AST.print_cmdFunction
print_cmd([io::IO], cmd, [terminal::Terminal])

Print the command object in terminal.

Arguments

  • io::IO: an IO object, default is stdout.
  • cmd: a command object, can be Entry, NodeCommand, LeafCommand.
  • terminal::Terminal: a Terminal object, contains the printing and terminal configuration. See also Terminal.
Comonicon.AST.splittextMethod
splittext(s)

Split the text in string s into an array, but keep all the separators attached to the preceding word.

Note

this is copied from Luxor/text.jl

Comonicon.Tools.promptMethod
prompt(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 return true, default is false.
  • require: require user to input the answer explicitly. This will repeat 3 times to ask user to input the answer then throw an CommandError.
Comonicon.Tools.promptMethod
prompt(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 is stdin.

Keyword Arguments

  • yes: skip the prompt and always return true, default is false.
  • require: require user to input the answer explicitly. This will repeat 3 times to ask user to input the answer then throw an CommandError.