Package org.refcodes.cli
Getting started:
Consider you have a tool called "foo-bar" to be invoked with the below allowed argument combinations (syntax):
foo-bar [{ -a | -d }] -f <file>
"foo-bar" can be invoked either with an optional "-a" or with an optional "-d" switch, but not both of them at the same time, and a file "-f <file>" must be provided, else the passed arguments are rejected as not being valid.
Valid arguments would be:
- foo-bar -f someFile
- foo-bar -d -f anyFile
- foo-bar -f otherFile -a
- foo-bar -a -f otherFile
- foo-bar -f someFile -b
- foo-bar -a someFile -f
- foo-bar -a -d -f anyFile
- foo-bar -a -x -f otherFile
Construct your parser:
First build your syntax usingFlag
es , Option
s and
ArgsSyntax
s. You actually build the syntax tree for
your command line tool's supported arguments:
Option<String> theFile = new StringOption( "-f", "--file", "file", "A file" );
Flag theAdd = new Flag( "-a", null, "Add the specified file" );
Flag theDelete = new Flag( "-d", null, "Delete the specified file" );
ArgsSyntax theXor = new XorCondition( theAdd, theDelete );
Syntaxable theOptional = new AnyCondition( theXor );
ArgsSyntax theAnd = new AndCondition( theOptional, theFile );
ArgsParser theArgsParser = new ArgsParserImpl( theAnd );
theArgsParser.printUsage();
// theArgsParser.printHelp();
Using syntactic sugar
The [`TinyRestfulServer`](https://bitbucket.org/refcodes/funcodes-tinyrestful/raw /master/src/main/java/club/funcodes/tinyrestful/TinyRestfulServer.java) demo application uses `syntactic sugar` for setting up the command line arguments parser:
import static org.refcodes.cli.CliSugar.*;
...
public static void main( String args[] ) {
Option<Integer> theWidth = intOption( "-w", "--width", "width", "Sets the console width" );
Option<Integer> thePort = intOption( "-p", "--port", "port", "Sets the port for the server" );
Option<Integer> theMaxConns = intOption( "-c", "--connections", "connections", "Sets the number of max. connections" );
Option<String> theUsername = stringOption( "-u", "--user", "username", "The username for HTTP Basic-Authentication" );
Option<String> theSecret = stringOption( "-s", "--secret", "secret", "The password for HTTP Basic-Authentication" );
Flag theHelp = helpSwitch( "Shows this help" );
ArgsSyntax theRootCondition = xor(
and(
thePort, optional( theMaxConns ), optional( and( theUsername, theSecret ) ), optional( theWidth )
),
theHelp
);
ArgsParser theArgsParser = new ArgsParserImpl( theRootCondition );
theArgsParser.withSyntaxNotation( SyntaxNotation.REFCODES );
theArgsParser.withName( "TinyRestful" ).withTitle( "TINYRESTFUL" ).withCopyrightNote( "Copyright (c) by FUNCODES.CLUB, Munich, Germany." ).withLicenseNote( "Licensed under GNU General Public License, v3.0 and Apache License, v2.0" );
theArgsParser.withBannerFont( new FontImpl( FontFamily.DIALOG, FontStyle.BOLD, 14 ) ).withBannerFontPalette( AsciiColorPalette.MAX_LEVEL_GRAY.getPalette() );
theArgsParser.setDescription( "Tiny evil RESTful server. TinyRestfulServer makes heavy use of the REFCODES.ORG artifacts found together with the FUNCODES.CLUB sources at http://bitbucket.org/refcodes." );
List<? extends Operand<?>> theResult = theArgsParser.evalArgs( args );
...
}
...
Most obvious is the missing new
statement for instantiating the
parts of your command line parser as this is done by the statically imported
methods. ### Under the hood As seen above, you pass your root
ArgsSyntax
to the ArgsParser
which then already can print out your command line tool's usage string:
Test (invoke) your parser:
In real live you would pass your main-method's args[] array to the parser. Now just for a test-run, pass aString
array to your parser and let it parse it:
String[] args = new String[] {
"-f", "someFile", "-d"
};
List<? extends Operand<?>> theResult = theArgsParser.evalArgs( args );
File theConfigFile = new File( theFile.getValue() );
Now the leaves of your syntax tree are filled with the argument's values
according to the syntax you have been setting up: Your
StringOption
instance aliased "theFile" now contains
the value "someFile".
The "theResult" contains the parsed arguments for you to use in your business logic.
In case of argument rejection, a sub-type of the
ArgsMismatchException
is being thrown; actually one
of the exceptions UnknownArgsException
,
AmbiguousArgsException
,
SuperfluousArgsException
or
ParseArgsException
is being thrown, according to the
cause of the rejection. So you can either catch the
ArgsMismatchException
or, if you need more details
on the cause, the other sub-exceptions.
Syntaxable
:
Syntaxable
defines the
methods at least required when building a command line arguments syntax tree
for traversing the syntax tree; either for parsing command line arguments or
for constructing the command line arguments syntax.
By providing various implementations of the Syntaxable
's subclasses
such as Operand
, Option
or ArgsSyntax
, a command line
arguments syntax tree can be constructed. This syntax tree can be use to
create a human readable (verbose) command line arguments syntax and to parse
an array of command line arguments for determining the Operand
s', the
Flag
es' or the Option
s' values.
Operand
:
An Operand
represents a
value parsed from command line arguments. An Operand
has a state
which changes with each invocation of the
ArgsParser.evalArgs(String[])
method.
It is recommended to put your Operand
instance(s) at the end of your
top ArgsSyntax
to enforce it to be the last Syntaxable
(s) when
parsing the command line arguments - this makes sure that any Option
s
pick their option arguments so that the Operand
(s) will correctly be
left over for parsing command line argument(s); the Operand
will not
pick by mistake an Option
argument.
Option
:
An Option
represents a
command line option with the according option's value. An Option
can
be seen as a key/value(s) pair defined in the command line arguments parsed
via the ArgsParser.evalArgs(String[])
method.
An Option
has a state which changes with each invocation of the
ArgsParser.evalArgs(String[])
method.
Flag
:
A Flag
is an Option
with a Boolean
state. Usually switches are just set or omitted in the
command line arguments with no value provided; former representing a
true
status and latter representing a false
status.
Operation
:
The Operation
is an
argument representing a function or a method and is either provided or not
provided as of Operation.isEnabled()
. It must neither be prefixed
with "-" nor with "--" in contrast to the Option
or the Flag
type.
ArgsSyntax
:
The ArgsSyntax
interface
represents a node in the command line arguments syntax tree; simply extending
the Syntaxable
interface and adding the functionality of providing
access to the added Operand
s (leafs). In future extensions, a
ArgsSyntax
might provide access to the child Syntaxable
elements contained in a ArgsSyntax
instance. As of the current
findings, access to the children of the ArgsSyntax
node is not
required and would make the interface unnecessarily complicated.
See also:
-
Interface Summary Interface Description ArgsAccessor Provides an accessor for a command line arguments (short "args") array.ArgsAccessor.ArgsMutator Provides a mutator for a args property.ArgsAccessor.ArgsProperty Provides a args property.ArgsParser TheArgsParser
provides means for parsing command line arguments and constructing a command line utility's help output.ArgsParserAccessor Provides an accessor for aArgsParser
property.ArgsParserAccessor.ArgsParserBuilder<B extends ArgsParserAccessor.ArgsParserBuilder<B>> Provides a builder method for aArgsParser
property returning the builder for applying multiple build operations.ArgsParserAccessor.ArgsParserMutator Provides a mutator for aArgsParser
property.ArgsParserAccessor.ArgsParserProperty Provides aArgsParser
property.ArgsParserMixin<B extends ArgsParserMixin<B>> This mixin provides builder additions (as of the builder pattern for chained configuring method calls) for parsing command line arguments.ArgsSyntax TheArgsSyntax
interface represents a node (and therewith the syntax for the arguments) in the command line arguments syntax tree; simply extending theSyntaxable
interface and adding the functionality of providing access to the addedOperand
s (leafs).Condition Interface indicating that theArgsSyntax
semantically represents a condition.Operand<T> AnOperand
represents a value parsed from command line arguments.Option<T> AnOption
represents a command line option with the according option's value.RootConditionAccessor Provides an accessor for a root condition property.RootConditionAccessor.RootConditionBuilder<B extends RootConditionAccessor.RootConditionBuilder<B>> Provides a builder method for a root condition property returning the builder for applying multiple build operations.RootConditionAccessor.RootConditionMutator Provides a mutator for a root condition property.RootConditionAccessor.RootConditionProperty Provides a root condition property.Syntaxable ASyntaxable
defines the methods at least required when building a command line arguments syntax tree for traversing the syntax tree; either for parsing command line arguments or for constructing the command line arguments syntax.SyntaxUsage TheSyntaxUsage
interface defines those methods required to create a human readable usageString
from the implementing instance. -
Class Summary Class Description AbstractCondition TheAbstractCondition
is an abstract implementation of theArgsSyntax
interface providing the boiler plate when implementing theArgsSyntax
interface as done by theAbstractCondition
's sub-classes.AbstractOperand<T> TheAbstractOperand
is an abstract implementation of anOperand
providing the boiler plate when implementing theOperand
interface.AbstractOption<T> TheAbstractOption
is an abstract implementation of anOption
providing the boiler plate when implementing theOption
interface.AllCondition TheAllCondition
enforces that the encapsulatedSyntaxable
consumes all arguments passed via invoking itsSyntaxable.parseArgs(String[])
, else aSuperfluousArgsException
is thrown.AndCondition AnAndCondition
contains (represents) a list ofArgsSyntax
(Syntaxable
) instances (nested by theAndCondition
) of which all are to be parsed successfully as of invoking theSyntaxable.parseArgs(String[], String[])
methods.AnyCondition Any of the nestedArgsSyntax
conditions may match for theAnyCondition
to match, e.g. all of the nested conditions are optional.ArgsParserImpl A straightforward implementation of theArgsParser
interface.ArrayOperand<T> Creates an array representation facade for the encapsulatedOperand
.ArrayOption<T> Creates an array representation facade for the encapsulatedOption
.CasesCondition TheCasesCondition
is anXorCondition
making sure that all possible cases inside theXorCondition
must(!)CharOption CliSugar Declarative syntactic sugar which may be statically imported in order to allow declarative definitions for the command lineFlag
,ArgsSyntax
,Option
andOperand
elements.CliUtility This utility class provides method useful for the refcodes-cli artifact and whose implementation has been motivated by the implementation of the refcodes-cli artifact.ConfigOption TheConfigOption
represents anOption
holding a value specifying a configuration file or identifying a configuration in general.DaemonFlag A predefined daemonFlag
: A predefinedFlag
gives itsDaemonFlag.SHORT_OPTION
, itsDaemonFlag.LONG_OPTION
as well as itsDaemonFlag.ALIAS
an according semantics regarded by other subsystems.DebugFlag A predefined debugFlag
: A predefinedFlag
gives itsDebugFlag.SHORT_OPTION
, itsDebugFlag.LONG_OPTION
as well as itsDebugFlag.ALIAS
an according semantics regarded by other subsystems.DoubleOption EnumOption<T extends Enum<T>> The Class EnumOption.ExampleUsage An example usage item describing a usage scenario.FileOption Flag TheFlag
class implements theOption
interface for representing either atrue
or afalse
state: When a flag is provided to your command line arguments, then it is considered to betrue
, when it is omitted, then it is considered to befalse
as ofFlag.isEnabled()
.FloatOption ForceFlag A predefined forceFlag
: A predefinedFlag
gives itsForceFlag.SHORT_OPTION
, itsForceFlag.LONG_OPTION
as well as itsForceFlag.ALIAS
an according semantics regarded by other subsystems.HelpFlag A predefined helpFlag
: A predefinedFlag
gives itsHelpFlag.SHORT_OPTION
, itsHelpFlag.LONG_OPTION
as well as itsHelpFlag.ALIAS
an according semantics regarded by other subsystems.InitFlag A predefined initFlag
: A predefinedFlag
gives itsInitFlag.SHORT_OPTION
, itsInitFlag.LONG_OPTION
as well as itsInitFlag.ALIAS
an according semantics regarded by other subsystems.IntOption LongOption NoneOperand TheNoneOperand
represents an empty set of arguments, e.g. no command line argument is being passed.Operation TheOperation
is an argument representing a function or a method ("command") and is either provided or not provided as ofOperation.isEnabled()
.OptionCondition OrCondition AnOrCondition
represents a list ofArgsSyntax
(Syntaxable
) instances of which at least one must be parsed successfully when theSyntaxable
s'Syntaxable.parseArgs(String[], String[])
methods are invoked.QuietFlag A predefined "be quiet"Flag
: A predefinedFlag
gives itsQuietFlag.SHORT_OPTION
, itsQuietFlag.LONG_OPTION
as well as itsQuietFlag.ALIAS
an according semantics regarded by other subsystems.StringOperand StringOption SysInfoFlag A predefined system informationFlag
: A predefinedFlag
gives itsSysInfoFlag.SHORT_OPTION
, itsSysInfoFlag.LONG_OPTION
as well as itsSysInfoFlag.ALIAS
an according semantics regarded by other subsystems..VerboseFlag A predefined verboseFlag
: A predefinedFlag
gives itsVerboseFlag.SHORT_OPTION
, itsVerboseFlag.LONG_OPTION
as well as itsVerboseFlag.ALIAS
an according semantics regarded by other subsystems.XorCondition AnXorCondition
represents a list ofArgsSyntax
(Syntaxable
) instances of which only one is allowed to be parsed successfully when theSyntaxable.parseArgs(String[], String[])
methods are invoked. -
Enum Summary Enum Description ExitCode Some default exit codes defined for CLI applications.SyntaxNotation TheSyntaxNotation
is used by a theSyntaxable.toSyntax(SyntaxNotation, String, String)
method to determine which notation to be used for the generated syntax. -
Exception Summary Exception Description AmbiguousArgsException Thrown in case at least one command line argument is ambiguous regarding expected args vs. provided args.ArgsMismatchException Thrown in case a command line arguments mismatch regarding provided and expected args.CliException Base exception for the console artifact.CliException.ConsoleArgsException This abstract exception is the base exception for all command line argument related exceptions.CliException.ConsoleCliException The Class ConsoleCliException.ParseArgsException Thrown in case the provided command line arguments do not respect the required syntax or cannot be converted to the required type.SuperfluousArgsException Thrown in case there were arguments found not being used (superfluous arguments).UnknownArgsException Thrown in case not one command line argument matched regarding the provided args vs. the expected args.