Types
YAArguParser.AbstractArgumentParser
— Typeabstract 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"
YAArguParser.AbstractValidator
— TypeAbstractValidator
The supertype for validators. Type AbstractValidator
is public, but not exported.
YAArguParser.ArgForms
— TypeArgForms
Command-line arguments, short and long forms.
Fields
short::String
long::String
Type ArgForms
is exported.
YAArguParser.ArgumentParser
— TypeArgumentParser <: 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 = ""
: descriptionusage::String = ""
: The script name passed to Julia from the command line.usage::String = ""
: usage/help messageexamples::Vector{String} = String[]
: usage examplesadd_help::Bool = false
: flag to automatically generate a help messagecolor::String = "default"
: output color - for color table, see help tocolorprint
function.
Type ArgumentParser
is exported
YAArguParser.ArgumentValues
— TypeArgumentValues
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.
YAArguParser.InteractiveArgumentParser
— TypeInteractiveArgumentParser <: AbstractArgumentParser
Extension of ArgumentParser
for interactive use.
Fields
ap::ArgumentParser = ArgumentParser()
throw_on_exception = false
: cause to immediately throw on exception iftrue
, vs. processing error downstream iffalse
(interactive use)introduction::String = ""
: explanation or introduction to be shown before prompt on a separate lineprompt::String = "> "
Type InteractiveArgumentParser
is exported.
YAArguParser.RealValidator
— TypeRealValidator{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 excludeexcl_ivls::Vector{Tuple{T, T}} = Tuple{T, T}[]
: list of intervals to excludeincl_vals::Vector{T} = T[]
: list of accepted valuesincl_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)
YAArguParser.StrValidator
— TypeStrValidator <: AbstractValidator
String validator type.
Fields
upper_case::Bool = false
: Iftrue
, input and pattern converted touppercase
, except for regex comparisonstarts_with::Bool = false
: Iftrue
, validate if one of the words in thepatterns
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")
Functions
Exported functions
YAArguParser.add_argument!
— Functionadd_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
YAArguParser.add_example!
— Functionadd_example!(parser::AbstractArgumentParser, example::AbstractString) → Nothing
Function add_example!
is exported.
YAArguParser.args_pairs
— Functionargs_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.
YAArguParser.colorprint
— Functioncolorprint(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.
Base.haskey
— Functionhaskey(parser::AbstractArgumentParser, key::AbstractString) →
haskey(parser::AbstractArgumentParser, key::Integer) →
YAArguParser.help
— Functionhelp(parser::AbstractArgumentParser; color::Union{AbstractString, Nothing}) → nothing
Print usage/help message. Function help
is exported.
YAArguParser.parse_args!
— Functionparse_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 thecli_args
not provided, parses the command line argumentsARGS
. Otherwise accepts equivalentVector
ofString
s, e.g.["--foo", "FOO", "-i", "1"]
Throws
Exception
: depending on the value ofparser.interactive
, in case of non-valid args vector, the function will either throw imediately, or returne <: Exception
to be processed downstream.
Function parse_args!
is exported.
Public functions
YAArguParser.generate_usage!
— Functiongenerate_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
YAArguParser.get_value
— Functionget_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 ofthrow_on_exception(parser)
, if the argument not found, the function will either throw imediately, or returne <: Exception
to be processed downstream.
Function get_value
is public, not exported.
YAArguParser.getcolor
— Functiongetcolor(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.
YAArguParser.parse_arg
— Functionparse_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.
YAArguParser.set_value!
— Functionset_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 ofthrow_on_exception
, if the argument not found, the function will either throw imediately, or returne <: Exception
to be processed downstream.
Function set_value!
is public, not exported.
Base.shell_split
— Functionshell_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"
YAArguParser.validate
— Functionvalidate(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.
Internal functions
YAArguParser._error
— Method_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.
YAArguParser.arg2strkey
— Methodarg2strkey(arg::AbstractString) → ::SubString
Argument to argument-store string key conversion by removing hypenation from prefix.
Function arg2strkey
is internal.
YAArguParser.args2vec
— Methodargs2vec(args::ArgForms) → ::Vector{String}
Extract struct members to vector of length 1 or 2.
Function args2vec
is internal.
YAArguParser.argument_usage
— Methodargument_usage(v::ArgumentValues) → (; u=args_usage, o=options)
Function argument_usage
is internal.
YAArguParser.check_missing_input
— Methodcheck_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 ofthrow_on_exception(parser)
, if an argument is missing, the function will either throw imediately, or returne <: Exception
to be processed downstream.
Function check_missing_input
is internal.
YAArguParser.hyphenate
— Methodhyphenate(argname::AbstractString) → ::String
Prepend hyphenation back onto argument after stripping it for the argument-store numkey.
Function hyphenate
is internal.
YAArguParser.initparser
— Functioninitparser(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 correspondingAP
.
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, "", "> ")
YAArguParser.sort_args
— Methodsort_args(parser::AbstractArgumentParser) → (;pos_args, keyed_args, all_args)
Function sort_args
is internal.
YAArguParser.update_val!
— Methodupdate_val!(parser::AbstractArgumentParser, numkey::Integer, val_str::AbstractString) → ::Union{Nothing, Exception}
See also set_value!
. Function update_val!
is internal.
YAArguParser.warn_and_return
— Methodwarn_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.
Constants
Index
YAArguParser.AbstractArgumentParser
YAArguParser.AbstractValidator
YAArguParser.ArgForms
YAArguParser.ArgumentParser
YAArguParser.ArgumentValues
YAArguParser.InteractiveArgumentParser
YAArguParser.RealValidator
YAArguParser.StrValidator
Base.haskey
Base.shell_split
YAArguParser._error
YAArguParser.add_argument!
YAArguParser.add_example!
YAArguParser.arg2strkey
YAArguParser.args2vec
YAArguParser.args_pairs
YAArguParser.argument_usage
YAArguParser.check_missing_input
YAArguParser.colorprint
YAArguParser.generate_usage!
YAArguParser.get_value
YAArguParser.getcolor
YAArguParser.help
YAArguParser.hyphenate
YAArguParser.initparser
YAArguParser.parse_arg
YAArguParser.parse_args!
YAArguParser.set_value!
YAArguParser.sort_args
YAArguParser.update_val!
YAArguParser.validate
YAArguParser.warn_and_return