Types

YAArguParser.AbstractArgumentParserType
abstract type AbstractArgumentParser

The supertype for argument parser types. Base functions hasproperty, getproperty, setproperty!, and propertynames have overloaded methods for AbstractArgumentParser, providing a flattened view onto nested structs. See also initparser.

Type AbstractArgumentParser is public, but not exported.

Examples

julia> @kwdef mutable struct MyAP <: AbstractArgumentParser
       ap::ArgumentParser=ArgumentParser()
       foo::Bool=false
       end
MyAP

julia> x = MyAP(ap=ArgumentParser(; color="magenta"); foo=true);

julia> x.foo
true

julia> x.ap.color
"magenta"

julia> x.color
"magenta"
source
YAArguParser.ArgFormsType
ArgForms

Command-line arguments, short and long forms.

Fields

  • short::String
  • long::String

Type ArgForms is exported.

source
YAArguParser.ArgumentParserType
ArgumentParser <: AbstractArgumentParser

Command-line argument parser with numkey-value stores and attributes.

Fields

stores

  • kv_store::OrderedDict{UInt16,ArgumentValues} = OrderedDict(): numkey => value
  • arg_store::OrderedDict{String,UInt16} = OrderedDict(): numkey-value store: arg => numkey
  • lng::UInt16 = 0: counter of stored args

attributes

  • description::String = "": description
  • usage::String = "": The script name passed to Julia from the command line.
  • usage::String = "": usage/help message
  • examples::Vector{String} = String[]: usage examples
  • add_help::Bool = false: flag to automatically generate a help message
  • color::String = "default": output color - for color table, see help to colorprint function.

Type ArgumentParser is exported

source
YAArguParser.ArgumentValuesType
ArgumentValues

Command-line argument values.

Fields

  • const args::ArgForms
  • value::Any
  • const type::Type = Any
  • const positional::Bool = false
  • const description::String = ""
  • const validator::Union{AbstractValidator, Nothing} = nothing

Type ArgumentValues is exported.

source
YAArguParser.InteractiveArgumentParserType
InteractiveArgumentParser <: AbstractArgumentParser

Extension of ArgumentParser for interactive use.

Fields

  • ap::ArgumentParser = ArgumentParser()
  • throw_on_exception = false: cause to immediately throw on exception if true, vs. processing error downstream if false (interactive use)
  • introduction::String = "": explanation or introduction to be shown before prompt on a separate line
  • prompt::String = "> "

Type InteractiveArgumentParser is exported.

source
YAArguParser.RealValidatorType
RealValidator{T} <: AbstractValidator

Numbers validator type. If no include criteria specified, anything not excluded considered OK. The intervals are evaluated as closed a ≤ x ≤ b.

Fields

  • excl_vals::Vector{T} = T[]: list of values to exclude
  • excl_ivls::Vector{Tuple{T, T}} = Tuple{T, T}[]: list of intervals to exclude
  • incl_vals::Vector{T} = T[]: list of accepted values
  • incl_ivls::Vector{Tuple{T, T}} = Tuple{T, T}[]: list of accepted intervals

Type RealValidator is exported.

Examples

julia> validate(1, RealValidator{Int}(;excl_vals=[1, 2], excl_ivls=[(10, 15), (20, 25)], incl_vals=[3, 4, 11], incl_ivls=[(100, 1000)]))
(ok = false, v = nothing)

julia> validate(150, RealValidator{Int}(;incl_ivls=[(100, 200)]))
(ok = true, v = 150)

julia> validate(50, RealValidator{Int}(;excl_ivls=[(100, 200)]))
(ok = true, v = 50)
source
YAArguParser.StrValidatorType
StrValidator <: AbstractValidator

String validator type.

Fields

  • upper_case::Bool = false: If true, input and pattern converted to uppercase, except for regex comparison
  • starts_with::Bool = false: If true, validate if one of the words in the patterns starts with input. Returns the whole matching word.
  • patterns::Vector{Union{AbstractString, Regex}}

Type StrValidator is exported.

Examples

julia> validate("foo", StrValidator(; upper_case=true, patterns=["foo", "bar"]))
(ok = true, v = "FOO")

julia> validate("foo", StrValidator(; patterns=[r"^fo[aoe]$"]))
(ok = true, v = "foo")

julia> validate("ye", StrValidator(; upper_case=true, starts_with=true, patterns=["yes", "no"]))
(ok = true, v = "YES")
source

Functions

Exported functions

YAArguParser.add_argument!Function
add_argument!(parser::AbstractArgumentParser, arg_short::String="", arg_long::String=""; kwargs...) → Nothing

Arguments

  • parser::AbstractArgumentParser: AbstractArgumentParser object instance.
  • arg_short::String="": short argument flag.
  • arg_long::String="": long argument flag.

Keywords

  • type::Type=nothing: type, the argument value to be parsed/converted into.
  • default::Any=nothing
  • positional::Bool=false
  • description::String=nothing
  • validator::Union{AbstractValidator, Nothing}=nothing

Throws

  • Throws immediately in case of error, e.g. if a key already present.

Function add_argument! is exported

source
YAArguParser.add_example!Function
add_example!(parser::AbstractArgumentParser, example::AbstractString) → Nothing

Function add_example! is exported.

source
YAArguParser.args_pairsFunction
args_pairs(parser::AbstractArgumentParser; excl::Union{Nothing, Vector{String}}=nothing) → ::Vector{Pair{Symbol, Any}}

Return vector of pairs argname => argvalue for all arguments except listed in excl. If argument has both short and long forms, the long one is used. Returned value can be e.g. passed as kwargs... to a function processing the parsed data, converted to a Dict or NamedTuple.

Function args_pairs is exported.

source
YAArguParser.colorprintFunction
colorprint(text, color::Union{AbstractString, Symbol}="default", newline=true; background=false, 
    bright=false, bold=false, italic=false, underline=false, blink=false) → nothing
colorprint(text, parser::AbstractArgumentParser, newline=true; kwargs...) → nothing

Print colored/styled text into stdout, provided the terminal supports it. Available colors are "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", and "default". If second arg is an AbstractArgumentParser, uses color as defined within, if any, otherwise uses "default".

Function colorprint is exported.

source
Base.haskeyFunction
haskey(parser::AbstractArgumentParser, key::AbstractString) → 
haskey(parser::AbstractArgumentParser, key::Integer) →
source
YAArguParser.helpFunction
help(parser::AbstractArgumentParser; color::Union{AbstractString, Nothing}) → nothing

Print usage/help message. Function help is exported.

source
YAArguParser.parse_args!Function
parse_args!(parser::AbstractArgumentParser; cli_args=nothing) →  ::Union{Nothing, Exception}

Parses arguments, validates them and stores the updated values in the parser.

Keywords

  • cli_args::Union{Vector{AbstractString}, Nothing}=nothing: if the cli_args not provided, parses the command line arguments ARGS. Otherwise accepts equivalent Vector of Strings, e.g. ["--foo", "FOO", "-i", "1"]

Throws

  • Exception: depending on the value of parser.interactive, in case of non-valid args vector, the function will either throw imediately, or return e <: Exception to be processed downstream.

Function parse_args! is exported.

source

Public functions

YAArguParser.generate_usage!Function
generate_usage!(parser::AbstractArgumentParser) → Nothing

Usage/help message generator. Function generate_usage! is public, not exported.

Example of generated text

Usage: main.jl –input <PATH> [–verbose] [–problem] [–help]

A Julia script with command-line arguments.

Options: -i, –input <PATH> Path to the input file. -v, –verbose Enable verbose message output. -p, –problem Print the problem statement. -h, –help Print this help message.

Examples: $ julia main.jl –input dir/file.txt –verbose $ julia main.jl –help

source
YAArguParser.get_valueFunction
get_value(parser, arg) → value::Any

Get argument value from parser.

Arguments

  • parser::AbstractArgumentParser: AbstractArgumentParser object instance.
  • arg::AbstractString="": argument name, e.g. "-f", "--foo".

Throws

  • Exception: depending on the value of throw_on_exception(parser), if the argument not found, the function will either throw imediately, or return e <: Exception to be processed downstream.

Function get_value is public, not exported.

source
YAArguParser.getcolorFunction
getcolor(parser::AbstractArgumentParser, color=nothing)  → color::String

Returns color in case second arg is defined, otherwise the color defined in parser, or "default".

Function getcolor is public, not exported.

source
YAArguParser.parse_argFunction
parse_arg(t::Type, val_str::Union{AbstractString, Bool}, ::Union{Nothing, AbstractValidator}) → (; ok, v=parsed_value, msg=nothing)

Tries to parse val_str to type t. For your custom types or custom parsing, provide your own methods.

Function parse_arg is public, but not exported.

source
YAArguParser.set_value!Function
set_value!(parser::AbstractArgumentParser, numkey::Integer, value::Any) → ::Union{Nothing, Exception}
set_value!(parser::AbstractArgumentParser, argname::AbstractString, value::Any) → ::Union{Nothing, Exception}

Set/update value of argument, validating it, as specified by numkey or argname, in parser.

Throws

  • Exception: depending on the value of throw_on_exception , if the argument not found, the function will either throw imediately, or return e <: Exception to be processed downstream.

Function set_value! is public, not exported.

source
Base.shell_splitFunction
shell_split(s::AbstractString) → String[]

Split a string into a vector of args.

shell_split is in internal function of Base, accessible as a public function of YAArguParser e.g. by using YAArguParser: shell_split.

Examples

julia> shell_split("--foo 3 -b bar")
4-element Vector{String}:
 "--foo"
 "3"
 "-b"
 "bar"
source
YAArguParser.validateFunction
validate(v::Any, ::Nothing) → (;ok=true, v)
validate(v::Missing, ::Any) → (;ok=true, v)
validate(v::Any, vl::AbstractValidator) → (;ok::Bool, v)

Validate input v against validator vl, and returns named tuple with validation result ok and (possibly canonicalized) input value v on success, or nothing on validation failure. If nothing is supplied instead of Validator, validation skipped. The same, if the value v to be validated is nothing. For examples and specific information see documentation for the corresponding Validator, e.g. StrValidator or RealValidator.

Function validate is exported.

source

Internal functions

YAArguParser._errorMethod
_error(throw_on_exception, msg::AbstractString; excp=ArgumentError) → ::Exception

Depending on value of throw_on_exception, throw immediately, or return Exception to be processed downstream.

Function _error is internal.

source
YAArguParser.arg2strkeyMethod
arg2strkey(arg::AbstractString) → ::SubString

Argument to argument-store string key conversion by removing hypenation from prefix.

Function arg2strkey is internal.

source
YAArguParser.args2vecMethod
args2vec(args::ArgForms) → ::Vector{String}

Extract struct members to vector of length 1 or 2.

Function args2vec is internal.

source
YAArguParser.check_missing_inputMethod
check_missing_input(parser::AbstractArgumentParser) → Union{Nothing, Exception}

Checks if all required arguments were supplied. Required is an argument without a default value.

Throws

  • Exception: depending on the value of throw_on_exception(parser), if an argument is missing, the function will either throw imediately, or return e <: Exception to be processed downstream.

Function check_missing_input is internal.

source
YAArguParser.hyphenateMethod
hyphenate(argname::AbstractString) → ::String

Prepend hyphenation back onto argument after stripping it for the argument-store numkey.

Function hyphenate is internal.

source
YAArguParser.initparserFunction
initparser(AP::::Type{AbstractArgumentParser}, strict=true; kwargs...) →  ::AbstractArgumentParser

Initializes a parser. First a parser of AP type with default values is created, then it's properties set to the values provided by kwargs. With strict flag set, checks if every kwarg corresponds to an AP property, otherwise ignore those without correspondence.

initparser is a syntactic sugar to "normal" struct initialization, making use of the flattened view onto nested structs , as provided by overloading of property functions for AbstractArgumentParser.

Throws

  • ErrorException: if supplied with kwargs having no corresponding AP .

Function initparser is exported.

Examples

julia> initparser(InteractiveArgumentParser; description="blablabla", color="magenta", add_help=true, throw_on_exception=true)
InteractiveArgumentParser(ArgumentParser(OrderedCollections.OrderedDict{UInt16, ArgumentValues}(), OrderedCollections.OrderedDict{String, UInt16}(), 0x0000, "blablabla", "", "", String[], true, "magenta"), true, "", "> ")
source
YAArguParser.sort_argsMethod
sort_args(parser::AbstractArgumentParser) → (;pos_args, keyed_args, all_args)

Function sort_args is internal.

source
YAArguParser.update_val!Method
update_val!(parser::AbstractArgumentParser, numkey::Integer, val_str::AbstractString) → ::Union{Nothing, Exception}

See also set_value!. Function update_val! is internal.

source
YAArguParser.warn_and_returnMethod
warn_and_return(v) → (; ok=false, v=nothing)

Prints a warning message and returns a tuple signalling invalid input. Used by the methods of validate function.

Function validate is public, not exported.

source

Constants

Index