Types
Exported types
YAArguParser.ArgForms — TypeArgFormsCommand-line arguments, short and long forms.
Fields
short::Stringlong::String
Type ArgForms is exported.
YAArguParser.ArgumentParser — TypeArgumentParser <: AbstractArgumentParserCommand-line argument parser with numkey-value stores and attributes.
Fields
stores
kv_store::OrderedDict{UInt16,ArgumentValues} = OrderedDict():numkey => valuearg_store::OrderedDict{String,UInt16} = OrderedDict(): numkey-value store:arg => numkeylng::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 tocolorprintfunction.
Type ArgumentParser is exported
YAArguParser.ArgumentValues — TypeArgumentValuesCommand-line argument values.
Fields
const args::ArgFormscli_val::Union{String, Bool, Nothing} = nothing: the "raw" value as received from the command linevalue::Any: the processed and validated valueconst type::Type = Anyconst positional::Bool = falseconst description::String = ""const validator::Union{<:AbstractValidator, Nothing} = nothing
Type ArgumentValues is exported.
YAArguParser.InteractiveArgumentParser — TypeInteractiveArgumentParser <: AbstractArgumentParserExtension 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} <: AbstractValidatorNumbers 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 <: AbstractValidatorString 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 thepatternsstarts 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")Public types
YAArguParser.AbstractArgumentParser — Typeabstract type AbstractArgumentParserThe 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 — TypeAbstractValidatorThe supertype for validators. Type AbstractValidator is public, but not exported.
Functions
Exported functions
YAArguParser.add_argument! — Functionadd_argument!(parser::AbstractArgumentParser, arg_short::String="", arg_long::String=""; kwargs...) → NothingArguments
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=nothingpositional::Bool=falsedescription::String=nothingvalidator::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! — Methodadd_example!(parser::AbstractArgumentParser, example::AbstractString) → NothingFunction add_example! is exported.
YAArguParser.args_pairs — Methodargs_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...) → nothingPrint 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.
YAArguParser.help — Methodhelp(parser::AbstractArgumentParser; color::Union{AbstractString, Nothing}) → nothingPrint usage/help message. Function help is exported.
YAArguParser.initparser — Functioninitparser(AP::::Type{AbstractArgumentParser}, strict=true; kwargs...) → ::AbstractArgumentParserInitializes 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.parse_args! — Methodparse_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_argsnot provided, parses the command line argumentsARGS. Otherwise accepts equivalentVectorofStrings, 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 <: Exceptionto be processed downstream.
Function parse_args! is exported.
Public functions
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.generate_usage! — Methodgenerate_usage!(parser::AbstractArgumentParser) → NothingUsage/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 — Methodget_value(parser, arg) → value::AnyGet 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 <: Exceptionto be processed downstream.
Function get_value is public, not exported.
YAArguParser.getcolor — Functiongetcolor(parser::AbstractArgumentParser, color=nothing) → color::StringReturns color in case second arg is defined, otherwise the color defined in parser, or "default".
Function getcolor is public, not exported.
YAArguParser.parse_arg — Methodparse_arg(av::ArgumentValues) → (; ok, v=parsed_value, msg=nothing)
parse_arg(t::Type, av::ArgumentValues)
parse_arg(t::Type, val::Union{AbstractString, Bool}, ::Union{Nothing, AbstractValidator})Tries to parse cli_val to type t. For your custom types or custom parsing, provide your own methods. Returns a NamedTuple as above.
Function parse_arg is public, but not exported.
YAArguParser.set_value! — Methodset_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 (which is specified by numkey or argname), validating it, in parser.
Throws
Exception: depending on the value ofthrow_on_exception, if the argument not found, the function will either throw imediately, or returne <: Exceptionto be processed downstream.
Function set_value! is public, not exported.
YAArguParser.validate — Methodvalidate(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.
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.
ParseDatesExt.parse_datetime — Methodparse_datetime(av::ArgumentValues, validator::AbstractValidator)Parses v to DateTime, Date, or Time, depending on v. Works for many common formats of date and time representation.
This function is public, not exported, and can be specialized on validator, if desired.
YAArguParser.parse_arg — Methodparse_arg(t::Type{DateTime}, av::ArgumentValues) → (; ok, v::Union{DateTime, Date, Time}=parsed_value, msg=nothing)Parses v to DateTime, Date, or Time, depending on v. Works for many common formats of date and time representation.
Examples
julia> parse_arg(DateTime, "2024-12-31", nothing)
(ok = true, v = Date("2024-12-31"), msg = nothing)
julia> parse_arg(DateTime, "17:18:19", nothing)
(ok = true, v = Time(17, 18, 19), msg = nothing)
julia> parse_arg(DateTime, "31.12.2024 17:18", nothing)
(ok = true, v = DateTime("2024-12-31T17:18:00"), msg = nothing)YAArguParser.specify_datetime_fmts — Methodspecify_datetime_fmts(::Nothing)Provides the lists of date & time formats to be accepted and rejected. For
This function is public, not exported, and is intended to be specialized on validator, if desired.
Internal functions
Base.haskey — Methodhaskey(parser::AbstractArgumentParser, key::AbstractString) →
haskey(parser::AbstractArgumentParser, key::Integer) →YAArguParser._error — Method_error(throw_on_exception, msg::AbstractString; excp=ArgumentError) → ::ExceptionDepending on value of throw_on_exception, throw immediately, or return Exception to be processed downstream.
Function _error is internal.
YAArguParser.arg2strkey — Methodarg2strkey(arg::AbstractString) → ::SubStringArgument 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 <: Exceptionto be processed downstream.
Function check_missing_input is internal.
YAArguParser.hyphenate — Methodhyphenate(argname::AbstractString) → ::StringPrepend hyphenation back onto argument after stripping it for the argument-store numkey.
Function hyphenate is internal.
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, cli_val::Union{AbstractString, Bool}) → ::Union{Nothing, Exception}See also set_value!. Function update_val! is internal.
Index
YAArguParser.AbstractArgumentParserYAArguParser.AbstractValidatorYAArguParser.ArgFormsYAArguParser.ArgumentParserYAArguParser.ArgumentValuesYAArguParser.InteractiveArgumentParserYAArguParser.RealValidatorYAArguParser.StrValidatorBase.haskeyBase.shell_splitParseDatesExt.parse_datetimeYAArguParser._errorYAArguParser.add_argument!YAArguParser.add_example!YAArguParser.arg2strkeyYAArguParser.args2vecYAArguParser.args_pairsYAArguParser.argument_usageYAArguParser.check_missing_inputYAArguParser.colorprintYAArguParser.generate_usage!YAArguParser.get_valueYAArguParser.getcolorYAArguParser.helpYAArguParser.hyphenateYAArguParser.initparserYAArguParser.parse_argYAArguParser.parse_argYAArguParser.parse_args!YAArguParser.set_value!YAArguParser.sort_argsYAArguParser.specify_datetime_fmtsYAArguParser.update_val!YAArguParser.validateYAArguParser.warn_and_return