The purpose of Argparse is to facilitate the process of parsing command-line arguments passed to a program. Command-line arguments are a way for users to provide input to a program when it is run from the command-line, and are a common way to configure the behavior of command-line applications.
Some of the features of Argparse:
- Support for different types of arguments, such as options, flags, key-value pairs, and positional arguments.
- Automatic generation of help and usage messages.
- Automatic error handling, such as handling missing or invalid arguments.
By using an Argparse, developers can make their command-line applications more user-friendly, easier to use, and more robust.
For now it is a single page module, which you can directly copy from here and paste in your project. But if you want to properly install it in your project with the pom.xml
file (that includes the dependency tree), then you should look at the Releases and download one of the zip files from there.
-
ArgparseOptionType
This
enum
includes the type of options that can be given over the command-line if using Argparse as your main parsing program.This
enum
includes the following types of options:ARGPARSE_OPT_GROUP
ARGPARSE_OPT_BOOLEAN
ARGPARSE_OPT_BIT
ARGPARSE_OPT_INTEGER
ARGPARSE_OPT_FLOAT
ARGPARSE_OPT_STRING
-
ArgparseOption
This class creates a parser option.
It has the following attributes attached to its instance:
prefix
- Flag prefix.shortName
- Flag short name.longName
- Flag long name.value
- Flag value.defaultValue
- Flag default value.help
- Flag help text.optionType
- Type of the flag.
-
Argparse
Creates the parser instance for your command-line application.
-
Argparse(String[] sysargs, String progname, String usage, String description, String epilog);
The
Argparse
constructor initializes theArgparse
object with the provided arguments. The constructor takes in thesysargs
,progname
,usage
,description
, andepilog
arguments.If the
progname
argument isnull
or empty, it retrieves the program name from the first element of thesysargs
array. If the program name has an extension, it removes the extension from the name.The
usage
,description
, andepilog
arguments are assigned to the corresponding instance variables of theArgparse
object.The constructor shifts the
sysargs
array by one position to remove the program name from the array, and assigns it to thesysargs
instance variable of theArgparse
object.The constructor initializes three maps:
optionsMap
,shortToLongOptionsMap
, andlongToShortOptionsMap
. TheoptionsMap
maps an integer key to anArgparseOption
object. TheshortToLongOptionsMap
maps short option strings to their corresponding long option strings. ThelongToShortOptionsMap
maps long option strings to their corresponding short option strings. -
public void addArgument(final ArgparseOption argparseOption) throws InvalidAttributeValueException;
This function,
addArgument
, is used to add an argument to theoptionsMap
, which is a hash map that maps a hash code generated from the short or long name of the argument to the argument itself. The function first checks if the argument's short name or long name is provided, and throws anInvalidAttributeValueException
if both are empty. The argument is then added to theoptionsMap
with its hash code as the key. If the argument has a short name, the short-to-long name mapping is added toshortToLongOptionsMap
. If the argument has a long name, the long-to-short name mapping is added tolongToShortOptionsMap
. This function helps build the argument parser by allowing the user to add arguments and their associated short and long names. -
public void parse();
The
parse()
function is responsible for parsing the command line arguments provided to the program. It first checks if any arguments have been provided and if so, it iterates through them. If an argument contains an equal sign, it splits the argument into the argument name and value, and then looks for the corresponding option in theoptionsMap
. If it finds a match, it assigns the value to the option's value attribute. If the argument does not contain an equal sign, it checks if the option is aboolean
type. If it is, it assigns the value "true" to the option's value attribute, otherwise it errors out. If the argument is not recognized, it also errors out. The function locks the current group argument if it exists before setting the value. -
public String getArgumentValue(String argument);
This is a method that returns the value of a given argument if present in the
optionsMap
hash map. If the argument is not present, it returnsnull
. The method checks if the argument is present in thelongToShortOptionsMap
andshortToLongOptionsMap
hash maps and retrieves the value of the corresponding option from theoptionsMap
. If the retrieved value is null, it returns the default value for the option. -
public static void printMessage(final ArgparseOption argparseOption);
This method prints out a formatted string of an
ArgparseOption
object, which can be used for debugging purposes. -
public static void printMessage(final String message);
This method is a simple wrapper around the
System.out.print()
method to make it easier to print messages to the console. It takes a string as input and prints it to the console. There are no overloads for integer orfloat
values, soString.format()
can be used to passstrings
withinteger
orfloat
values. -
public void printUsage();
This function prints the usage string of the program along with the description and epilog, if provided during initialization of the parser. It also uses
Argparse.colorEncodedString
to add color to the printed output. -
public void exit();
The
exit()
method exits the program and releases the resources acquired by thelogger
. It calls theSystem.exit(0)
method to terminate the program with a successful status code. -
public void exit(final int status, final String message);
This method overloads the
exit()
method and takes two parameters: aninteger
status and aString
message. It prints the message to the console if it is not null or empty, then exits the program with the specified status code. -
public void error(final String message);
This method prints an error message, followed by the usage string, and then exits the program with an error code of
2
. The error message indicates that there was an error in the usage of a shell built-in command. The error message is passed as an argument to the method.
-
import Argparse;
import javax.management.InvalidAttributeValueException;
class Main {
public void main(String[] args) {
Argparse parser = new Argparse(
args,
null, /** Program name is automatically deduced. */
"Usage: progname --foo\n" +
"\n" +
" --foo=<STRING>\n" +
" Just a flag argument like any other flag argument.",
"This is the program description and the program parses the value for flag 'foo'.",
"This is the epilog (set the footer here).");
try {
parser.addArgument(
new Argparse.ArgparseOption(
"f",
"foo",
Argparse.ArgparseOptionType.ARGPARSE_OPT_STRING,
null,
"bar",
"Help text for foo."));
} catch (InvalidAttributeValueException exc) {
System.err.println(exc.toString());
}
parser.parse();
final String fooValue = parser.getArgumentValue("foo");
...
}
}