diff --git a/README.md b/README.md index ed2b9ca..43374af 100644 --- a/README.md +++ b/README.md @@ -28,21 +28,31 @@ catering to diverse application needs. easier to pass arrays of data. - **Arguments Directly Casted:** Accessing a parameter's argument returns it as the defined type. - **Lightweight:** Using the ArgsParser library is very simply and straight forward as shown in the example below. +- **Build-in Parameter Types:** ArgsParser provides usage ready Parameters for all commonly used types like *String*, + *Double*, *Path* and more +- **Extensible:** Extend the library with custom parameter classes tailored to your application’s needs. + ## Example Code: ```java import ArgsParser.*; +import ArgsParser.ParameterTypes.StrParameter; public class Example { public static void main(String[] args) { ArgsParser parser = new ArgsParser(); - Parameter param1 = parser.addMandatoryStringParameter("parameterFlag", "pf", "description"); - Command command1 = parser.addCommand("commandName", "c", "description of the command"); + // define a String mandatory parameter + StrParameter param1 = parser.addParameter( + new StrParameter("parameterFlag", "pf", "description", true)); + // define a command + Command command1 = parser.addCommand( + new Command("commandName", "c", "description of the command")); + ArgsParser.parse(args); if (command1.isProvided()) { - System.out.println(param1.getArgument()); + System.out.println(param1.getArgument()); } } } @@ -67,35 +77,73 @@ public static void main(String[] args) { ``` ### 2. Define the Parameters or Commands -This parser supports 5 **types**: -- *String, Integer, Double, Boolean, Character* - -#### addParameter methods: -The type of a Parameter is defined with its respective method on the parser object. -For each type there are 5 `addParameter` methods (example for String): -- `addMandatoryStringParameter(String fullFlag, String shortFlag, String description)` -- `addOptionalStringParameter(String fullFlag, String shortFlag, String description)` -- `addDefaultStringParameter(String fullFlag, String shortFlag, String description, String defaultValue)` -- `addStringArrayParameter(String fullFlag, String shortFlag, String description, boolean isMandatory)` -- `addDefaultStringArrayParameter(String fullFlag, String shortFlag, String description, String[] defaultValue)` - -(see a list of all Methods at the end of this README) - -#### Available Fields for each Parameter: + +#### addParameter method: +The addParameter method is called on an ArgsParser instance +and allows you to add different types of parameters to your parser using specific parameter classes. +Those parameters added to the parser will be checked for several conditions (see "Parse the Arguments"). + +#### Example: +```java + // ... + StrParameter example = parser.addParameter( + new StrParameter("parameterFlag", "pf", "short Description", true)); + IntParameter example2 = parser.addParameter( + new IntParameter("parameterFlag2", "pf2", null, false)); + DblParameter argWithDefault = parser.addParameter( + new DblParameter(5.6, "parameterFlag3", "pf3", "description")); + BolArrParameter booleanArrayParam = parser.addParameter( + new BolArrParameter(new Boolean[]{true, false, false}, "boolArray", "bArr", "Array of several boolean values")); + IntArrParameter integerArrayParam = parser.addParameter( + new IntArrParameter(new Integer[]{1, 2, 3}, "intArray", "iArr", "Array of several integer values")); + Command command = parser.addCommand( + new Command("commandName", "cN", "this is a description for the command")); + // ... +``` + +#### Build-in Parameter types: +Build-in ready to use classes are: +- `StrParameter` / `StrArrParameter` for String arguments. +- `IntParameter` / `IntArrParameter` for Integer arguments. +- `DblParameter` / `DblArrParameter` for Double arguments. +- `BolParameter` / `BolArrParameter` for Boolean arguments. +- `ChrParameter` / `ChrArrParameter` for Character arguments. +- `FltParameter` / `FltArrParameter` for Float arguments. +- `PthParameter` / `PthArrParameter` for Path arguments. + +For each Parameter type, two constructors exist: +`xxxParameter(String fullFlag, String shortFlag, String description, boolean isMandatory)` +or +`xxxParameter(xxx defaultValue, String fullFlag, String shortFlag, String description)` + +#### Fields explained: You can specify several fields for each parameter: - **fullFlag**: The flag name of the parameter. - **shortFlag**: A short version of the flag for the parameter. - **description**: A description of the parameter, insert `null` or an empty string`""` if not needed. - **defaultValue**: A default value that the parameter returns if no argument was provided but accessed in the program. +- **isMandatory**: Determines whether the flag must be provided in the arguments. If set to true and the flag is missing, an ArgsException will be thrown. + +#### The PthParameter +The Parameter handling Paths provides has one additional field in each of the two constructors: +`pathCheck`. +If this is set true, the parser will check if the provided path does exist, if not it will raise an ArgsException! + +#### Add your own Parameters of a desired Type: +By creating a class extending Parameter allows you to use your own Parameters with this ArgsParser! +(see "Create your own Parameters") #### Multiple Arguments to one flag: -A **special type** are the `addArray` methods that are introduced in Version 4.0.0 of the ArgsParser. +A **special type** of Parameters are the `xxxArrParameter` classes. They allow handing several arguments to a single flag: ``` --file path/file1 path/file2 path/file3 ``` -Several of these Array Parameters can be defined without problems. +Several of these Array Parameters can be defined without problems: +``` +--file path/file1 path/file2 path/file3 --Integers 1 2 3 +``` #### Commands: @@ -105,17 +153,6 @@ modes or functionalities based on the commands passed. You simply define commands just like regular parameters, and the parser will recognize them when parsing the input arguments. -```java -// ... - Parameter example = parser.addMandatoryStringParameter("parameterFlag", "pf", "short Description"); - Parameter example2 = parser.addOptionalIntegerParameter("parameterFlag2", "pf2", null); - Parameter argWithDefault = parser.addDefaultDoubleParameter("parameterFlag3", "pf3", "description", 5.6); - Parameter booleanArrayParam = parser.addBooleanArrayParameter("boolArray", "bArr", "Array of several boolean values", false); - Parameter integerArrayParam = parser.addDefaultIntegerArrayParameter("intArray", "iArr", "Array of several integer values", new Integer[]{1, 2, 3}); - Command command = parser.addCommand("commandName", "cN", "this is a description for the command"); -// ... -``` - #### Toggles: ArgsParser provides the method .toggle(Command...) which takes several Command instances as arguments. This method @@ -125,11 +162,15 @@ the usage of the provided Commands to only one of them! For example: ```Java -ArgsParser parser = new ArgsParser(); -Command cmd1 = parser.addCommand("commName1", "cmdN1", "Description of command1"); -Command cmd2 = parser.addCommand("commName2", "cmdN2", "Description of command2"); -Command cmd3 = parser.addCommand("commName3", "cmdN3", "Description of command3"); -parser.toggle(cmd1, cmd2); + // ... + Command cmd1 = parser.addCommand( + new Command("commName1", "cmdN1", "Description of command1")); + Command cmd2 = parser.addCommand( + new Command("commName2", "cmdN2", "Description of command2")); + Command cmd3 = parser.addCommand( + new Command("commName3", "cmdN3", "Description of command3")); + parser.toggle(cmd1, cmd2); + // ... ``` with this only cmd1 or cmd2 are allowed to be present in args. If both commands would be present, .parseUnchecked() @@ -153,8 +194,10 @@ issues such as: - Unknown flag (`UnknownFlagArgsException`) - Too many arguments provided (`TooManyArgsProvidedArgsException`) - Invalid argument types (`InvalidArgTypeArgsException`) -- trying to set the same flag twice (`FlagAlreadyProvidedArgsException`) -- calling help at the wrong position (`HelpAtWrongPositionArgsException `) +- Trying to set the same flag twice (`FlagAlreadyProvidedArgsException`) +- Calling help at the wrong position (`HelpAtWrongPositionArgsException `) +- Providing a not existing path to a PthParameter with pathCheck enabled (`NotExistingPathArgsException`) +- Providing two commands that are part of a toggle (`ToggleArgsException`) A `CalledForHelpNotification` can also be thrown if the user requests the help message. Exit with status code 0 for help requests and 1 for errors is recommended. @@ -197,7 +240,7 @@ The **arguments can be used directly in your code**! //... ``` -#### check provision of a command +#### check provision of a command or Parameter For the commands, a simple call of `isProvided` on the Command instance will return if the command was provided in args: ```java //... @@ -285,7 +328,7 @@ while calling `--help` or `-h` with a specific parameter will only print the hel #################################################################################################### ``` -## ArgsException examples +## ArgsException printout examples The ArgsParser will throw an `ArgsException` if the user provides invalid arguments. The printouts of these exceptions look like this: @@ -321,47 +364,56 @@ for misspelled flags, the Parser will even do a suggestion: ``` -## List of all available "addParameter" methods - -#### String type: -- `addMandatoryStringParameter(String fullFlag, String shortFlag, String description)` -- `addOptionalStringParameter(String fullFlag, String shortFlag, String description)` -- `addDefaultStringParameter(String fullFlag, String shortFlag, String description, String defaultValue)` -- `addStringArrayParameter(String fullFlag, String shortFlag, String description, boolean isMandatory)` -- `addDefaultStringArrayParameter(String fullFlag, String shortFlag, String description, String[] defaultValue)` - -#### Integer type: -- `addMandatoryIntegerParameter(String fullFlag, String shortFlag, String description)` -- `addOptionalIntegerParameter(String fullFlag, String shortFlag, String description)` -- `addDefaultIntegerParameter(String fullFlag, String shortFlag, String description, Integer defaultValue)` -- `addIntegerArrayParameter(String fullFlag, String shortFlag, String description, boolean isMandatory)` -- `addDefaultIntegerArrayParameter(String fullFlag, String shortFlag, String description, Integer[] defaultValue)` - -#### Double type: -- `addMandatoryDoubleParameter(String fullFlag, String shortFlag, String description)` -- `addOptionalDoubleParameter(String fullFlag, String shortFlag, String description)` -- `addDefaultDoubleParameter(String fullFlag, String shortFlag, String description, Double defaultValue)` -- `addDoubleArrayParameter(String fullFlag, String shortFlag, String description, boolean isMandatory)` -- `addDefaultDoubleArrayParameter(String fullFlag, String shortFlag, String description, Double[] defaultValue)` - -#### Boolean type: -- `addMandatoryBooleanParameter(String fullFlag, String shortFlag, String description)` -- `addOptionalBooleanParameter(String fullFlag, String shortFlag, String description)` -- `addDefaultBooleanParameter(String fullFlag, String shortFlag, String description, Boolean defaultValue)` -- `addBooleanArrayParameter(String fullFlag, String shortFlag, String description, boolean isMandatory)` -- `addDefaultBooleanArrayParameter(String fullFlag, String shortFlag, String description, Boolean[] defaultValue)` - -#### Character type: -- `addMandatoryCharacterParameter(String fullFlag, String shortFlag, String description)` -- `addOptionalCharacterParameter(String fullFlag, String shortFlag, String description)` -- `addDefaultCharacterParameter(String fullFlag, String shortFlag, String description, Character defaultValue)` -- `addCharacterArrayParameter(String fullFlag, String shortFlag, String description, boolean isMandatory)` -- `addDefaultCharacterArrayParameter(String fullFlag, String shortFlag, String description, Character[] defaultValue)` +## Create your own Parameters: +By creating a class extending Parameter with T of the Type that your Parameter should handle, you can implement +your own Parameters that are compatible with this ArgsParser! + +### To create a custom parameter, follow these steps: +#### 1. Define the Parameter Type: +Determine the type T that the parameter will handle (e.g., Integer, String, etc.). +(We use Integer as T for this example!) +#### 2. Create the Subclass: +Extend the Parameter class, specifying the appropriate type. +```java +public class IntegerParameter extends Parameter { + // Implementation details +} +``` +#### 3. Implement Constructors: +Provide constructors that call the superclass constructors, passing necessary parameters such as flags, description, +mandatory status, and default values if applicable. +```java +public IntegerParameter(String fullFlag, String shortFlag, String description, boolean isMandatory) { + super(fullFlag, shortFlag, description, isMandatory, Integer.class); +} + +public IntegerParameter(Integer defaultValue, String fullFlag, String shortFlag, String description) { + super(defaultValue, fullFlag, shortFlag, description, Integer.class); +} +``` +#### 4. Override castArgument: +Implement the castArgument method to convert the input string to the desired type T. Handle any +necessary validation and exception throwing within this method. +```java +@Override +protected Integer castArgument(String argument) throws InvalidArgTypeArgsException { + try { + return Integer.parseInt(argument); + } catch (NumberFormatException e) { + throw new InvalidArgTypeArgsException(getFullFlag(), "Integer", "Invalid integer value: " + argument); + } +} +``` + +## List of methods: + +#### add a parameter to a parser instance: +- `parser.addParameter()` #### access an Argument of ANY of these Parameters: - `parameter.getArgument()` -#### Command type: +#### add a Command to a parser instance: - `addCommand(String fullCommandName, String shortCommandName, String description)` #### check provision of a specific command: @@ -377,3 +429,54 @@ for misspelled flags, the Parser will even do a suggestion: #### indirect access of parameters / commands: - `getArgumentOf(String fullFlag)` - `checkIfCommandIsProvided(String fullCommandName)` + +## Full Code Example: +```java +public static void main(String[] args) { + // initialize ArgsParser instance + ArgsParser parser = new ArgsParser(args); + + // declare Parameters on the parser instance + StrParameter example = parser.addParameter( + new StrParameter("parameterFlag", "pf", "short Description", true)); + IntParameter example2 = parser.addParameter( + new IntParameter("parameterFlag2", "pf2", null, false)); + DblParameter argWithDefault = parser.addParameter( + new DblParameter(5.6, "parameterFlag3", "pf3", "description")); + BolArrParameter booleanArrayParam = parser.addParameter( + new BolArrParameter(new Boolean[]{true, false, false}, "boolArray", "bArr", "Array of several boolean values")); + IntArrParameter integerArrayParam = parser.addParameter( + new IntArrParameter(new Integer[]{1, 2, 3}, "intArray", "iArr", "Array of several integer values")); + Command command = parser.addCommand( + new Command("commandName", "cN", "this is a description for the command")); + + // declare Commands on the parser instance + Command cmd1 = parser.addCommand( + new Command("commName1", "cmdN1", "Description of command1")); + Command cmd2 = parser.addCommand( + new Command("commName2", "cmdN2", "Description of command2")); + Command cmd3 = parser.addCommand( + new Command("commName3", "cmdN3", "Description of command3")); + parser.toggle(cmd1, cmd2); + + // parser the command-line arguments + parser.parse(); + + // example for direct access of command-line arguments via their parameters + String providedArgument = example.getArgument(); + Double result = example2.getArgument() + argWithDefault.getArgument(); + + // example for checking a command + if (command.isProvided()) System.out.println("command provided"); + + // example for indirect command-line argument access + String providedArgument = parser.getArgumentOf("parameterFlag"); + Integer getInteger = parser.getArgumentOf("parameterFlag2"); + Double getDouble = parser.getArgumentOf("parameterFlag3"); + Double result = getInteger + getDouble; + + // example for indirect command check + if (parser.checkIfCommandIsProvided("commandName")) System.out.println("command still provided"); +} + +``` diff --git a/src/ArgsParser/ArgsExceptions/InvalidArgTypeArgsException.java b/src/ArgsParser/ArgsExceptions/InvalidArgTypeArgsException.java index f5d2f5b..f9c9fb9 100644 --- a/src/ArgsParser/ArgsExceptions/InvalidArgTypeArgsException.java +++ b/src/ArgsParser/ArgsExceptions/InvalidArgTypeArgsException.java @@ -7,6 +7,6 @@ */ public class InvalidArgTypeArgsException extends ArgsException { public InvalidArgTypeArgsException(String flagName, String typeName, String message) { - super("Failed to set argument for " + flagName + " of type " + typeName + ": " + message, true); + super("Failed to set argument for " + flagName + " of type " + typeName + ":\n\t" + message, true); } } diff --git a/src/ArgsParser/ArgsExceptions/NotExistingPathArgsException.java b/src/ArgsParser/ArgsExceptions/NotExistingPathArgsException.java new file mode 100644 index 0000000..f4e26fd --- /dev/null +++ b/src/ArgsParser/ArgsExceptions/NotExistingPathArgsException.java @@ -0,0 +1,11 @@ +package ArgsParser.ArgsExceptions; + +import ArgsParser.ArgsException; + +import java.nio.file.Path; + +public class NotExistingPathArgsException extends ArgsException { + public NotExistingPathArgsException(Path path) { + super(path + " does not exist!\n\tInvalid path!", false); + } +} diff --git a/src/ArgsParser/ArgsParser.java b/src/ArgsParser/ArgsParser.java index bb18c6c..63c51fc 100644 --- a/src/ArgsParser/ArgsParser.java +++ b/src/ArgsParser/ArgsParser.java @@ -9,9 +9,7 @@ import ArgsParser.ArgsExceptions.*; -import java.nio.file.Path; import java.util.*; -import java.util.stream.Collectors; /** * Class, to parse arguments given in the command line, the tool checks for several conditions: @@ -26,25 +24,31 @@ *

The Parser functions as follows:

* *
    - *
  1. Define as many Parameters on a ArgsParser instance as needed by using any of the four "addParameter" Methods - * of the type the argument of the Parameter should be (Parameters can be of type String, Integer, Double, Boolean or Character): + *
  2. Define as many Parameters on a ArgsParser instance as needed by using {@link ArgsParser#addParameter(Parameter)}. + * This method takes a instance of any Parameter type. There are several usage-ready child classes for the most + * common types used. There are also Array type Parameters for each equivalent: + * *
      - *
    • {@link ArgsParser#addMandatoryStringParameter(String, String, String)}
    • - *
    • {@link ArgsParser#addOptionalStringParameter(String, String, String)}
    • - *
    • {@link ArgsParser#addDefaultIntegerParameter(String, String, String, Integer)}
    • - *
    • {@link ArgsParser#addStringArrayParameter(String, String, String, boolean)}
    • + *
    • BolParameter / BolArrParameter Parameter with Boolean type arguments.
    • + *
    • ChrParameter / ChrArrParameter Parameter with Character type arguments
    • + *
    • DbParameter / DblArrParameter Parameter with Double type arguments
    • + *
    • FltParameter / FltArrParameter Parameter with Float type arguments
    • + *
    • IntParameter / IntArrParameter Parameter with Integer type arguments
    • + *
    • PathParameter / PthArrParameter Parameter with Path type arguments
    • + *
    • StrParameter / StrArrParameter Parameter with String type arguments
    • *
    - * Each of this adder methods take several arguments: -
      + * + * Each Parameter has several specified fields: + *
        *
      • Parameters have a full flag name
      • - *
      • Parameters have a short version flags
      • + *
      • Parameters have a short version flag
      • *
      • Parameters can have a description (hand "" or null if not needed)
      • - *
      • addDefaultParameters take a default argument
      • - *
      • addArrayParameters can be specified mandatory or optional
      • + *
      • Parameters can be specified mandatory
      • + *
      • Parameters can have default values (which makes them automatically optional)
      • *
      * There are also Commands available to be defined which are just checked if they are provided or not: *
        - *
      • {@link ArgsParser#addCommand(String, String, String)}
      • + *
      • {@link ArgsParser#addCommand(Command)}
      • *
      * *
    • After all parameters are added, the {@link ArgsParser#parse(String[] args)} method has to be called! (this is mandatory!)
    • @@ -83,89 +87,6 @@ protected boolean parseArgsWasCalled() { return parseArgsWasCalled; } - /** - * Creates a new {@link Parameter} object with the specified attributes, validates the flags, and registers it in the - * parameter map. This method centralizes the logic for creating, configuring, and registering parameters of various types. - * - *

      - * Each parameter can be identified by both a full flag (e.g., --example) and a short flag (e.g., -e). - * The method ensures that the flags are correctly formatted, unique, and not reserved. - *

      - * - *

      Behavior:

      - *
        - *
      • Validates that the full and short flags are not empty, already used, or reserved (e.g., --help).
      • - *
      • Configures the {@link Parameter} with the provided attributes (e.g., description, type, default value).
      • - *
      • Tracks parameter metadata such as mandatory parameters and maximum flag lengths for help display.
      • - *
      • Registers the parameter in the internal flag maps and ensures it is uniquely identified.
      • - *
      - * - *

      Flag Validation Rules:

      - *
        - *
      • Full flag (e.g., --example) and short flag (e.g., -e) must be unique.
      • - *
      • Flags must not be empty or null.
      • - *
      • Reserved flags like --help and -h cannot be reused.
      • - *
      - * - * @param fullFlag The full version of the flag (e.g., --example). - * @param shortFlag The short version of the flag (e.g., -e). - * @param description A brief description of what the parameter represents. - * @param type The data type of the parameter's value. - * @param isMandatory Indicates if the parameter is mandatory. - * @param defaultValue The default value for the parameter, hand null for no default. - * @return The newly created Parameter object. - * @throws IllegalArgumentException If the flag names are already used or reserved (--help/-h). - */ - private Parameter createParameter(String fullFlag, - String shortFlag, - String description, - Class type, - boolean isMandatory, - T defaultValue) throws IllegalArgumentException { - fullFlag = makeFlag(fullFlag, false); - shortFlag = makeFlag(shortFlag, true); - - // check if the flag names are already used / empty or reserved - if (fullFlag.isEmpty() || shortFlag.isEmpty()) { - throw new IllegalArgumentException("No empty strings allowed for flags!"); - } - if (parameterMap.containsKey(fullFlag)) { - throw new IllegalArgumentException("Flag already exists: " + fullFlag); - } - if (parameterMap.containsKey(shortFlag)) { - throw new IllegalArgumentException("Flag already exists: " + shortFlag); - } - if (fullFlag.equals("--help") || fullFlag.equals("--h") || - shortFlag.equals("-h") || shortFlag.equals("-help")) { - throw new IllegalArgumentException("--help/-h is reserved!"); - } - - // create new parameter instance - Parameter parameter = new Parameter(fullFlag, shortFlag, description, type, isMandatory, this); - - if (defaultValue != null) { - parameter.setDefault(defaultValue); - } - - // add parameter to the map - parameterMap.put(parameter.getFullFlag(), parameter); - parameterMap.put(parameter.getShortFlag(), parameter); - - flagsInDefinitionOrder.add(fullFlag); - - // check for the lengths of the name - int nameSize = parameter.getFullFlag().length(); - if (longestFlagSize < nameSize) longestFlagSize = nameSize; - - int shortSize = parameter.getShortFlag().length(); - if (longestShortFlag < shortSize) longestShortFlag = shortSize; - - // add to mandatory parameters if parameter is mandatory - if (parameter.isMandatory()) mandatoryParameters.add(parameter); - - return parameter; - } - /** * Formats a flag string to ensure it conforms to the required syntax for command-line arguments. *

      @@ -190,491 +111,161 @@ private Parameter createParameter(String fullFlag, * @param isShortName true if the flag is a shortFlag (false if fullFlag) * @return flag in the correct format (e.g. --flag or -f) */ - private String makeFlag(String flag, boolean isShortName) { + protected static String makeFlag(String flag, boolean isShortName) { flag = flag.replaceFirst("^-+", ""); return isShortName ? "-" + flag : "--" + flag; } - - // String Parameter constructors - - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @return the created Parameter instance of type {@link String} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addMandatoryStringParameter(String fullFlag, String shortFlag, String description) - throws IllegalArgumentException { - return createParameter(fullFlag, shortFlag, description, String.class, true, null); - } - - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @param defaultValue default value of the parameter - * @return the created Parameter instance of type {@link String} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addDefaultStringParameter(String fullFlag, String shortFlag, - String description, String defaultValue) - throws IllegalArgumentException { - return createParameter(fullFlag, shortFlag, description, String.class, false, defaultValue); - } - - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameterhand empty string "" or null if not needed - * @return the created Parameter instance of type {@link String} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addOptionalStringParameter(String fullFlag, String shortFlag, String description) - throws IllegalArgumentException { - return createParameter(fullFlag, shortFlag, description, String.class, false, null); - } - - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * Array Parameters can take multiple arguments behind their flag - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @param isMandatory true if parameter is mandatory, false if optional - * @return the created Parameter instance of type {@link String[]} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addStringArrayParameter(String fullFlag, String shortFlag, - String description, boolean isMandatory) - throws IllegalArgumentException { - arrayParameters.add(makeFlag(fullFlag, false)); - arrayParameters.add(makeFlag(shortFlag, true)); - return createParameter(fullFlag, shortFlag, description, String[].class, isMandatory, null); - } - - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * Array Parameters can take multiple arguments behind their flag - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @param defaultValue default value of the parameter - * @return the created Parameter instance of type {@link String[]} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addDefaultStringArrayParameter(String fullFlag, String shortFlag, - String description, String[] defaultValue) - throws IllegalArgumentException { - arrayParameters.add(makeFlag(fullFlag, false)); - arrayParameters.add(makeFlag(shortFlag, true)); - return createParameter(fullFlag, shortFlag, description, String[].class, false, defaultValue); - } - - - // Integer Parameter constructors - - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @return the created Parameter instance of type {@link Integer[]} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addMandatoryIntegerParameter(String fullFlag, String shortFlag, String description) - throws IllegalArgumentException { - return createParameter(fullFlag, shortFlag, description, Integer.class, true, null); - } - - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @param defaultValue default value of the parameter - * @return the created Parameter instance of type {@link Integer[]} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addDefaultIntegerParameter(String fullFlag, String shortFlag, - String description, Integer defaultValue) - throws IllegalArgumentException { - return createParameter(fullFlag, shortFlag, description, Integer.class, false, defaultValue); - } - - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @return the created Parameter instance of type {@link Integer[]} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addOptionalIntegerParameter(String fullFlag, String shortFlag, String description) - throws IllegalArgumentException { - return createParameter(fullFlag, shortFlag, description, Integer.class, false, null); - } - - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * Array Parameters can take multiple arguments behind their flag - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @param isMandatory true if parameter is mandatory, false if optional - * @return the created Parameter instance of type {@link Integer[]} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addIntegerArrayParameter(String fullFlag, String shortFlag, - String description, boolean isMandatory) - throws IllegalArgumentException { - arrayParameters.add(makeFlag(fullFlag, false)); - arrayParameters.add(makeFlag(shortFlag, true)); - return createParameter(fullFlag, shortFlag, description, Integer[].class, isMandatory, null); - } - - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * Array Parameters can take multiple arguments behind their flag - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @param defaultValue default value of the parameter - * @return the created Parameter instance of type {@link Integer[]} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addDefaultIntegerArrayParameter(String fullFlag, String shortFlag, - String description, Integer[] defaultValue) - throws IllegalArgumentException { - arrayParameters.add(makeFlag(fullFlag, false)); - arrayParameters.add(makeFlag(shortFlag, true)); - return createParameter(fullFlag, shortFlag, description, Integer[].class, false, defaultValue); - } - - - // Double Parameter constructors - - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @return the created Parameter instance of type {@link Double} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addMandatoryDoubleParameter(String fullFlag, String shortFlag, String description) - throws IllegalArgumentException { - return createParameter(fullFlag, shortFlag, description, Double.class, true, null); - } - - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @param defaultValue default value of the parameter - * @return the created Parameter instance of type {@link Double} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addDefaultDoubleParameter(String fullFlag, String shortFlag, - String description, Double defaultValue) - throws IllegalArgumentException { - return createParameter(fullFlag, shortFlag, description, Double.class, false, defaultValue); - } - - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @return the created Parameter instance of type {@link Double} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addOptionalDoubleParameter(String fullFlag, String shortFlag, String description) - throws IllegalArgumentException { - return createParameter(fullFlag, shortFlag, description, Double.class, false, null); - } - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * Array Parameters can take multiple arguments behind their flag - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @param isMandatory true if parameter is mandatory, false if optional - * @return the created Parameter instance of type {@link Double[]} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addDoubleArrayParameter(String fullFlag, String shortFlag, - String description, boolean isMandatory) - throws IllegalArgumentException { - arrayParameters.add(makeFlag(fullFlag, false)); - arrayParameters.add(makeFlag(shortFlag, true)); - return createParameter(fullFlag, shortFlag, description, Double[].class, isMandatory, null); - } - - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * Array Parameters can take multiple arguments behind their flag - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @param defaultValue default value of the parameter - * @return the created Parameter instance of type {@link Double[]} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addDefaultDoubleArrayParameter(String fullFlag, String shortFlag, - String description, Double[] defaultValue) - throws IllegalArgumentException { - arrayParameters.add(makeFlag(fullFlag, false)); - arrayParameters.add(makeFlag(shortFlag, true)); - return createParameter(fullFlag, shortFlag, description, Double[].class, false, defaultValue); - } - - - // Boolean Parameter constructors - - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @return the created Parameter instance of type {@link Boolean} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addMandatoryBooleanParameter(String fullFlag, String shortFlag, String description) - throws IllegalArgumentException { - return createParameter(fullFlag, shortFlag, description, Boolean.class, true, null); - } - - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @param defaultValue default value of the parameter - * @return the created Parameter instance of type {@link Boolean} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addDefaultBooleanParameter(String fullFlag, String shortFlag, - String description, Boolean defaultValue) - throws IllegalArgumentException { - return createParameter(fullFlag, shortFlag, description, Boolean.class, false, defaultValue); - } - - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @return the created Parameter instance of type {@link Boolean} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addOptionalBooleanParameter(String fullFlag, String shortFlag, String description) - throws IllegalArgumentException { - return createParameter(fullFlag, shortFlag, description, Boolean.class, false, null); + * Validates whether the provided flag names are valid, unique, and not reserved. + *

      + * This method performs multiple checks to ensure that the given full and short flag names: + *

      + *
        + *
      • Are not empty: Both full and short flag names must be non-empty strings.
      • + *
      • Are unique: Neither flag name must already exist in the {@code parameterMap}.
      • + *
      • Are not reserved: Reserved flag names such as `--help`, `--h`, `-h`, and `-help` cannot be used.
      • + *
      + *

      + * If any of these conditions are violated, an {@link IllegalArgumentException} will be thrown. + *

      + * + *

      Examples:

      + *
      +     * checkReservedFlags("--example", "-e"); // Valid
      +     * checkReservedFlags("--help", "-h");    // Throws IllegalArgumentException
      +     * 
      + * + * @param fullVersion The full version of the flag (e.g., "--example"). + * @param shortVersion The short version of the flag (e.g., "-e"). + * @throws IllegalArgumentException if: + *
        + *
      • Either flag name is empty.
      • + *
      • Either flag name already exists in {@code parameterMap}.
      • + *
      • Either flag name matches a reserved flag (`--help`, `--h`, `-h`, `-help`).
      • + *
      + */ + protected void checkReservedFlags(String fullVersion, String shortVersion) { + if (fullVersion.isEmpty() || shortVersion.isEmpty()) { + throw new IllegalArgumentException("No empty strings allowed for flags!"); + } + if (parameterMap.containsKey(fullVersion)) { + throw new IllegalArgumentException("Flag already exists: " + fullVersion); + } + if (parameterMap.containsKey(shortVersion)) { + throw new IllegalArgumentException("Flag already exists: " + shortVersion); + } + if (fullVersion.equals("--help") || fullVersion.equals("--h") || + shortVersion.equals("-h") || shortVersion.equals("-help")) { + throw new IllegalArgumentException("--help/-h is reserved!"); + } } /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * Array Parameters can take multiple arguments behind their flag - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @param isMandatory true if parameter is mandatory, false if optional - * @return the created Parameter instance of type {@link Boolean[]} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) + * Updates the maximum lengths of the full and short flag names for consistent formatting in help text. + *

      + * This method compares the lengths of the provided full and short flag names with the current + * maximum values (`longestFlagSize` and `longestShortFlag`) and updates them if the new flag names + * are longer. This ensures proper alignment when displaying flags in help messages or documentation. + *

      + * + *

      Behavior:

      + *
        + *
      • Compares the length of the provided full flag name with the current maximum length (`longestFlagSize`).
      • + *
      • Updates `longestFlagSize` if the new full flag is longer.
      • + *
      • Compares the length of the provided short flag name with the current maximum length (`longestShortFlag`).
      • + *
      • Updates `longestShortFlag` if the new short flag is longer.
      • + *
      + * + * @param fullVersion The full flag name (e.g., "--example"). + * @param shortVersion The short flag name (e.g., "-e"). */ - public Parameter addBooleanArrayParameter(String fullFlag, String shortFlag, - String description, boolean isMandatory) - throws IllegalArgumentException { - arrayParameters.add(makeFlag(fullFlag, false)); - arrayParameters.add(makeFlag(shortFlag, true)); - return createParameter(fullFlag, shortFlag, description, Boolean[].class, isMandatory, null); - } + protected void setNameSizes(String fullVersion, String shortVersion) { + int nameSize = fullVersion.length(); + if (longestFlagSize < nameSize) longestFlagSize = nameSize; - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * Array Parameters can take multiple arguments behind their flag - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @param defaultValue default value of the parameter - * @return the created Parameter instance of type {@link Boolean[]} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addDefaultBooleanArrayParameter(String fullFlag, String shortFlag, - String description, Boolean[] defaultValue) - throws IllegalArgumentException { - arrayParameters.add(makeFlag(fullFlag, false)); - arrayParameters.add(makeFlag(shortFlag, true)); - return createParameter(fullFlag, shortFlag, description, Boolean[].class, false, defaultValue); + int shortSize = shortVersion.length(); + if (longestShortFlag < shortSize) longestShortFlag = shortSize; } - // Character Parameter constructors - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @return the created Parameter instance of type {@link Character} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addMandatoryCharacterParameter(String fullFlag, String shortFlag, - String description) throws IllegalArgumentException { - return createParameter(fullFlag, shortFlag, description, Character.class, true, null); - } - - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @param defaultValue default value of the parameter - * @return the created Parameter instance of type {@link Character} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) + * Adds a parameter to the parser after validating its flags, uniqueness, and reservation status. + *

      + * This method ensures that the provided parameter has valid flag names, is not already registered, + * and doesn't conflict with reserved flags such as `--help` or `-h`. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the parameter's full and short flags are non-empty and unique.
      • + *
      • Ensures reserved flags (`--help`, `-h`) are not being reused.
      • + *
      • Adds the parameter to internal maps for retrieval and validation.
      • + *
      • Keeps track of the flag's length for consistent help text formatting.
      • + *
      • Registers the parameter in mandatory or array-specific sets if applicable.
      • + *
      + * + * @param The type of the parameter being added, extending {@link Parameter}. + * @param parameter The parameter object to be added to the parser. + * @return The same parameter instance that was added. + * @throws IllegalArgumentException If the flag names are empty, duplicate, or reserved. */ - public Parameter addDefaultCharacterParameter(String fullFlag, String shortFlag, - String description, Character defaultValue) - throws IllegalArgumentException { - return createParameter(fullFlag, shortFlag, description, Character.class, false, defaultValue); - } + public > T addParameter(T parameter) { - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @return the created Parameter instance of type {@link Character} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addOptionalCharacterParameter(String fullFlag, String shortFlag, String description) - throws IllegalArgumentException { - return createParameter(fullFlag, shortFlag, description, Character.class, false, null); - } + // check if the flag names are already used / empty or reserved + checkReservedFlags(parameter.getFullFlag(), parameter.getShortFlag()); - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * Array Parameters can take multiple arguments behind their flag - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @param isMandatory true if parameter is mandatory, false if optional - * @return the created Parameter instance of type {@link Character[]} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addCharacterArrayParameter(String fullFlag, String shortFlag, - String description, boolean isMandatory) - throws IllegalArgumentException { - arrayParameters.add(makeFlag(fullFlag, false)); - arrayParameters.add(makeFlag(shortFlag, true)); - return createParameter(fullFlag, shortFlag, description, Character[].class, isMandatory, null); - } + // set name sizes + setNameSizes(parameter.getFullFlag(), parameter.getShortFlag()); - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * Array Parameters can take multiple arguments behind their flag - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @param defaultValue default value of the parameter - * @return the created Parameter instance of type {@link Character[]} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addDefaultCharacterArrayParameter(String fullFlag, String shortFlag, - String description, Character[] defaultValue) - throws IllegalArgumentException { - arrayParameters.add(makeFlag(fullFlag, false)); - arrayParameters.add(makeFlag(shortFlag, true)); - return createParameter(fullFlag, shortFlag, description, Character[].class, false, defaultValue); - } + // add parameter to parameterMap + parameterMap.put(parameter.getFullFlag(), parameter); + parameterMap.put(parameter.getShortFlag(), parameter); + // add fullFlag to definition order + flagsInDefinitionOrder.add(parameter.getFullFlag()); - // Path Parameter + // add this parser to the parameter for .parseWasCalled() check + parameter.setParser(this); - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @return the created Parameter instance of type {@link Path} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addMandatoryPathParameter(String fullFlag, String shortFlag, String description) { - return createParameter(fullFlag, shortFlag, description, Path.class, true, null); - } + // add parameter to arrayParameters if isArray + if (parameter.isArray()) { + arrayParameters.add(parameter.getFullFlag()); + arrayParameters.add(parameter.getShortFlag()); + } - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @param defaultValue a default path object - * @return the created Parameter instance of type {@link Path} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addDefaultPathParameter(String fullFlag, String shortFlag, String description, Path defaultValue) { - return createParameter(fullFlag, shortFlag, description, Path.class, false, defaultValue); - } + // add to mandatory parameters if parameter is mandatory + if (parameter.isMandatory()) mandatoryParameters.add(parameter); - /** - * Adds a new parameter that will be checked in args and assigned to the Parameter instance - * @param fullFlag name of the parameter (-- will automatically be added) - * @param shortFlag short version of the parameter (- will automatically be added) - * @param description description of the parameter, hand empty string "" or null if not needed - * @return the created Parameter instance of type {@link Path} - * @throws IllegalArgumentException if the flag names are already defined, empty, or reserved (--help/-h) - */ - public Parameter addOptionalPathParameter(String fullFlag, String shortFlag, String description) { - return createParameter(fullFlag, shortFlag, description, Path.class, false, null); + return parameter; } - // Command /** * Adds a new command with its full name, short name, and description to the existing command set. * - * @param fullCommandName The full name of the command, used as the primary identifier. - * @param shortCommandName The abbreviated name of the command, used as a shorthand identifier. - * @param description A brief description of what the command does. - * @return The newly created and added {@link Command} object. + * @param command the {@link Command} to add to this parser. + * @return The added {@link Command} object. * @throws IllegalArgumentException If the fullCommandName or shortCommandName are already defined, empty, or reserved (--help/-h) */ - public Command addCommand(String fullCommandName, String shortCommandName, String description) { - - if (fullCommandName.isEmpty() || shortCommandName.isEmpty()) { - throw new IllegalArgumentException("No empty strings allowed for flags!"); - } - if (commandMap.containsKey(fullCommandName)) { - throw new IllegalArgumentException("Command name already exists: " + fullCommandName); - } - if (commandMap.containsKey(shortCommandName)) { - throw new IllegalArgumentException("Command name already exists: " + shortCommandName); - } - if (fullCommandName.equals("--help") || fullCommandName.equals("-h") || - shortCommandName.equals("--help") || shortCommandName.equals("-h")) { - throw new IllegalArgumentException("--help/-h is reserved!"); - } + public Command addCommand(Command command) { - Command command = new Command(fullCommandName, shortCommandName, description, this); + // check for reserved flags + checkReservedFlags(command.getFullCommandName(), command.getShortCommandName()); - int nameSize = fullCommandName.length(); - if (longestFlagSize < nameSize) longestFlagSize = nameSize; + // set name sizes + setNameSizes(command.getFullCommandName(), command.getShortCommandName()); - int shortSize = shortCommandName.length(); - if (longestShortFlag < shortSize) longestShortFlag = shortSize; + // add to commandMap + commandMap.put(command.getFullCommandName(), command); + commandMap.put(command.getShortCommandName(), command); - commandMap.put(fullCommandName, command); - commandMap.put(shortCommandName, command); + // add to definition order + commandsInDefinitionOrder.add(command.getFullCommandName()); - commandsInDefinitionOrder.add(fullCommandName); + // add this parser to the command for .parseWasCalled() check + command.setArgsParser(this); return command; } @@ -738,12 +329,13 @@ public void parse(String[] args) throws IllegalArgumentException { * @throws FlagAlreadyProvidedArgsException if a flag is provided more than once. * @throws HelpAtWrongPositionArgsException if the help argument is positioned incorrectly. * @throws IllegalArgumentException if args is null + * @throws NotExistingPathArgsException if a PthParameter with pathCheck was handed a non-existing path */ public void parseUnchecked(String[] args) throws NoArgumentsProvidedArgsException, UnknownFlagArgsException, TooManyArgumentsArgsException, MissingArgArgsException, MandatoryArgNotProvidedArgsException, CalledForHelpNotification, InvalidArgTypeArgsException, IllegalStateException, FlagAlreadyProvidedArgsException, HelpAtWrongPositionArgsException, - IllegalArgumentException, ToggleArgsException { + IllegalArgumentException, ToggleArgsException, NotExistingPathArgsException { if (args == null) throw new IllegalArgumentException("Args cannot be null!"); if(parseArgsWasCalled) throw new IllegalStateException(".parse() was already called!"); @@ -819,10 +411,11 @@ private void checkForHelpCall(String[] args) throws UnknownFlagArgsException, Ca * @throws InvalidArgTypeArgsException If an argument type is invalid. * @throws FlagAlreadyProvidedArgsException If a flag is provided more than once. * @throws HelpAtWrongPositionArgsException If the help flag is not in the correct position. + * @throws NotExistingPathArgsException if a PthParameter with pathCheck was handed a non-existing path */ private Set> parseArguments(String[] args) throws UnknownFlagArgsException, TooManyArgumentsArgsException, MissingArgArgsException, InvalidArgTypeArgsException, FlagAlreadyProvidedArgsException, - HelpAtWrongPositionArgsException { + HelpAtWrongPositionArgsException, NotExistingPathArgsException { Set> givenParameters = new HashSet<>(); @@ -835,28 +428,29 @@ private Set> parseArguments(String[] args) throws UnknownFlagArgsEx Parameter currentParameter = null; boolean longFlagUsed = false; for (int i = 0; i < args.length; i++) { + String arg = args[i]; - boolean currentPositionIsFlag = args[i].startsWith("-"); + boolean currentPositionIsFlag = arg.startsWith("-"); if (currentPositionIsFlag) { - currentParameter = parameterMap.get(args[i]); - longFlagUsed = args[i].startsWith("--"); + currentParameter = parameterMap.get(arg); + longFlagUsed = arg.startsWith("--"); } - boolean currentPositionIsCommand = commandMap.get(args[i]) != null; - boolean flagExists = parameterMap.get(args[i]) != null; + boolean currentPositionIsCommand = commandMap.get(arg) != null; + boolean flagExists = parameterMap.get(arg) != null; boolean isLastEntry = i == args.length - 1; boolean currentParameterNotNull = currentParameter != null; - boolean argumentSet = currentParameterNotNull && currentParameter.hasArgument(); + boolean argumentSet = currentParameterNotNull && currentParameter.readArgument() != null; boolean lastPositionWasFlag = i >= 1 && args[i - 1].startsWith("-"); boolean flagAlreadyProvided = false; if (flagExists) flagAlreadyProvided = givenParameters.contains(currentParameter); - boolean isHelpCall = ("--help".equals(args[i]) || "-h".equals(args[i])); + boolean isHelpCall = ("--help".equals(arg) || "-h".equals(arg)); boolean helpCallInWrongPosition = isHelpCall && (i > 1 || (i == 0 && args.length == 2)); if (helpCallInWrongPosition) { throw new HelpAtWrongPositionArgsException(); } else if (currentPositionIsFlag && !flagExists) { // if flag is unknown - throw new UnknownFlagArgsException(args[i], parameterMap.keySet(), commandMap.keySet(), false); + throw new UnknownFlagArgsException(arg, parameterMap.keySet(), commandMap.keySet(), false); } else if (currentPositionIsFlag && flagAlreadyProvided) { // if the flag already was set throw new FlagAlreadyProvidedArgsException(currentParameter.getFullFlag(), @@ -871,24 +465,22 @@ private Set> parseArguments(String[] args) throws UnknownFlagArgsEx throw new MissingArgArgsException(args[i - 1]); } else if (isLastEntry && currentPositionIsFlag) { //if last Flag has no argument - throw new MissingArgArgsException(args[i]); + throw new MissingArgArgsException(arg); } else if (currentPositionIsCommand) { // if current position is a command - commandMap.get(args[i]).setCommand(); // set the command to true + commandMap.get(arg).setCommand(); // set the command to true } else if (lastPositionWasFlag && currentParameterNotNull) { // if the current position is an argument boolean isArrayParam = arrayParameters.contains(args[i - 1]); if (isArrayParam) { // "collect" all following arguments after an array parameter in a StringBuilder - StringBuilder arguments = new StringBuilder(); - arguments.append(args[i]).append("==="); // every entry in the array gets seperated by === + currentParameter.setArgument(args[i]); while(i + 1 < args.length && !args[i + 1].startsWith("-") && !commandMap.containsKey(args[i + 1])) { // loop through all arguments - arguments.append(args[++i]).append("==="); + currentParameter.setArgument(args[++i]); } - currentParameter.setArgument(arguments.toString()); } else { - currentParameter.setArgument(args[i]); + currentParameter.setArgument(arg); } currentParameter.setProvided(); diff --git a/src/ArgsParser/CalledForHelpNotification.java b/src/ArgsParser/CalledForHelpNotification.java index 80f06e2..cc598b8 100644 --- a/src/ArgsParser/CalledForHelpNotification.java +++ b/src/ArgsParser/CalledForHelpNotification.java @@ -14,12 +14,16 @@ public class CalledForHelpNotification extends Exception { private static final int consoleWidth = 100; private static final Map shortFlagTypes = new HashMap<>(){{ put("String", "s"); + put("Path", "p"); put("Integer", "i"); + put("Float", "f"); put("Double", "d"); put("Boolean", "b"); put("Character", "c"); put("String[]", "s+"); + put("Path[]", "p+"); put("Integer[]", "i+"); + put("Float[]", "f+"); put("Double[]", "d+"); put("Boolean[]", "b+"); put("Character[]", "c+"); @@ -90,12 +94,12 @@ private static String centerString(String stringToCenter) { int freeSpace = (consoleWidth - stringToCenter.length()) / 2 - 1; return "#" + " ".repeat(freeSpace) + stringToCenter; } - + + //TODO abstract commandHelpString and ParameterHelpString private static String commandHelpString(Command command, int longestFlagSize, int longestShortFlag) { String fullCommandName = command.getFullCommandName(); String shortCommandName = command.getShortCommandName(); String description = command.getDescription(); - String isMandatory = " "; StringBuilder helpString = new StringBuilder("### "); // check if a description is available: diff --git a/src/ArgsParser/Command.java b/src/ArgsParser/Command.java index cb7ca6b..9889323 100644 --- a/src/ArgsParser/Command.java +++ b/src/ArgsParser/Command.java @@ -1,10 +1,10 @@ package ArgsParser; public class Command { - private final ArgsParser argsParser; private final String fullCommandName; private final String shortCommandName; private final String description; + private ArgsParser argsParser; private boolean status = false; /** @@ -13,12 +13,14 @@ public class Command { * @param fullCommandName the detailed or long form flag for this command * @param shortCommandName the abbreviated or short form flag for this command * @param description a brief description of what this command does - * @param argsParser the parser responsible for handling command-line arguments */ - public Command(String fullCommandName, String shortCommandName, String description, ArgsParser argsParser) { + public Command(String fullCommandName, String shortCommandName, String description) { this.fullCommandName = fullCommandName; this.shortCommandName = shortCommandName; this.description = description; + } + + protected void setArgsParser(ArgsParser argsParser) { this.argsParser = argsParser; } @@ -61,8 +63,10 @@ protected void setCommand() { * * @return true if the command is provided, false otherwise. * @throws IllegalArgumentException if the {@link ArgsParser#parse(String[] args)} method was not called before checking the command. + * or if this Command was not added to any {@link ArgsParser}! */ - public boolean isProvided() throws IllegalArgumentException { + public boolean isProvided() throws IllegalStateException { + if (argsParser == null) throw new IllegalStateException("Command: " + this + " is not assigned to any parser instance!"); if (!argsParser.parseArgsWasCalled()) throw new IllegalStateException("parse() was not called before trying to check the command!"); return status; } diff --git a/src/ArgsParser/Parameter.java b/src/ArgsParser/Parameter.java index d50ee68..0bbf139 100644 --- a/src/ArgsParser/Parameter.java +++ b/src/ArgsParser/Parameter.java @@ -8,45 +8,223 @@ */ import ArgsParser.ArgsExceptions.InvalidArgTypeArgsException; +import ArgsParser.ArgsExceptions.NotExistingPathArgsException; -import java.lang.reflect.Array; -import java.nio.file.Path; -import java.util.*; -import java.util.function.Function; +import java.util.Objects; /** - * Parameter class with fields for each attribute of the Parameter including the argument. + * Abstract base class for defining command-line parameters. + * + *

      + * The {@code Parameter} class serves as a foundation for creating specific types of command-line parameters + * within the {@link ArgsParser} framework. To create a functional parameter, developers must extend this class + * and implement the abstract {@code castArgument} method to handle the conversion of string inputs to the desired type. + *

      + * + *

      Extending Parameter<T>

      + * + *

      + * To create a custom parameter, follow these steps: + *

      + * + *
        + *
      1. + * Define the Parameter Type: + * Determine the type {@code T} that the parameter will handle (e.g., {@link Integer}, {@link String}, etc.). + *
      2. + *
      3. + * Create the Subclass: + * Extend the {@code Parameter} class, specifying the appropriate type. + *
        {@code
        + * public class IntegerParameter extends Parameter {
        + *     // Implementation details
        + * }
        + * }
        + *
      4. + *
      5. + * Implement Constructors: + * Provide constructors that call the superclass constructors, passing necessary parameters such as flags, description, + * mandatory status, and default values if applicable. + *
        {@code
        + * public IntegerParameter(String fullFlag, String shortFlag, String description, boolean isMandatory) {
        + *     super(fullFlag, shortFlag, description, isMandatory, Integer.class);
        + * }
        + *
        + * public IntegerParameter(Integer defaultValue, String fullFlag, String shortFlag, String description) {
        + *     super(defaultValue, fullFlag, shortFlag, description, Integer.class);
        + * }
        + * }
        + *
      6. + *
      7. + * Override castArgument: + * Implement the {@code castArgument} method to convert the input string to the desired type {@code T}. + * Handle any necessary validation and exception throwing within this method. + *
        {@code
        + * @Override
        + * protected Integer castArgument(String argument) throws InvalidArgTypeArgsException {
        + *     try {
        + *         return Integer.parseInt(argument);
        + *     } catch (NumberFormatException e) {
        + *         throw new InvalidArgTypeArgsException(getFullFlag(), "Integer", "Invalid integer value: " + argument);
        + *     }
        + * }
        + * }
        + *
      8. + *
      + * + *

      Key Components

      + * + *
        + *
      • Flags: Define both full (e.g., {@code --verbose}) and short (e.g., {@code -v}) flags to identify the parameter in command-line arguments.
      • + *
      • Description: Provide a clear description of what the parameter represents, aiding users in understanding its purpose.
      • + *
      • Mandatory Status: Indicate whether the parameter is required for the application to run.
      • + *
      • Default Values: Optionally set a default value that will be used if the parameter is not explicitly provided.
      • + *
      + * + *

      Exception Handling

      + * + *

      + * When implementing {@code castArgument}, ensure that any invalid input is properly handled by throwing relevant exceptions, + * such as {@link InvalidArgTypeArgsException} or custom exceptions as needed. + *

      + * + *

      Example Implementation

      + * + *
      {@code
      + * public class StringParameter extends Parameter {
      + *
      + *     public StringParameter(String fullFlag, String shortFlag, String description, boolean isMandatory) {
      + *         super(fullFlag, shortFlag, description, isMandatory, String.class);
      + *     }
      + *
      + *     public StringParameter(Integer defaultValue, String fullFlag, String shortFlag, String description) {
      + *         super(defaultValue, fullFlag, shortFlag, description, String.class);
      + *     }
      + *
      + *     @Override
      + *     protected String castArgument(String argument) {
      + *         if (argument == null || argument.isEmpty()) {
      + *             throw new InvalidArgTypeArgsException(getFullFlag(), "String", "Argument cannot be null or empty.");
      + *         }
      + *         return Integer.parseInt(argument);
      + *     }
      + * }
      + * }
      + * + *

      Integration with ArgsParser

      + * + *

      + * After creating a subclass, register the parameter with an instance of {@link ArgsParser}. Ensure that flags are unique + * and adhere to the validation rules defined in {@link Parameter}. + *

      + * + * @param The type of the parameter value (e.g., {@link Integer}, {@link String}, {@link Boolean}). + * @see ArgsParser + * @see InvalidArgTypeArgsException + * @see NotExistingPathArgsException */ -public class Parameter { - private final ArgsParser argsParser; +public abstract class Parameter { private final String fullFlag; private final String shortFlag; private final String description; private final boolean isMandatory; - private final Class type; - private T defaultValue = null; - private boolean hasDefault = false; private T argument = null; - private boolean hasArgument = false; + private T defaultValue = null; + private ArgsParser argsParser; + private Class type; private boolean isProvided = false; /** - * Constructor for the Parameter class with type definition - * @param fullFlag name of the parameter - * @param shortFlag short name of the parameter - * @param description description of the parameter - * @param type type of the parameter - * @param isMandatory true if the parameter is mandatory, false otherwise + * Constructs a new {@link Parameter} instance with the specified flags, description, and mandatory status. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @param isMandatory Indicates if this parameter is mandatory. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. */ - protected Parameter(String fullFlag, String shortFlag, String description, Class type, boolean isMandatory, ArgsParser argsParser) { - this.fullFlag = fullFlag; - this.shortFlag = shortFlag; + protected Parameter(String fullFlag, String shortFlag, String description, boolean isMandatory, Class type) { + this.fullFlag = ArgsParser.makeFlag(fullFlag, false); + this.shortFlag = ArgsParser.makeFlag(shortFlag, true); this.description = description; this.isMandatory = isMandatory; this.type = type; + } + + /** + * Constructs a new {@link Parameter} instance with the specified flags, description, and a default value. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param defaultValue Sets a default value for this Parameter & makes it not mandatory. + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + protected Parameter(T defaultValue, String fullFlag, String shortFlag, String description, Class type) { + this(fullFlag, shortFlag, description, false, type); + this.defaultValue = defaultValue; + } + + /** + * add the ArgsParser instance on which this Parameter was added. + * @param argsParser parser instance on which this parameter was added. + */ + protected void setParser(ArgsParser argsParser) { this.argsParser = argsParser; } + /** + * returns the argument as is + * @return argument or null if no argument is set + */ + protected T readArgument() { + return argument; + } + + /** + * Checks if the parameter type represents an array. + * @return true if the parameter type is an array, false otherwise. + */ + protected boolean isArray() { + return type.isArray(); + } + /** * getter method for the fullFlag * @return fullFlag @@ -92,7 +270,7 @@ protected String getType() { * @return true if this Parameter was created with a default value, false otherwise */ protected boolean hasDefault() { - return hasDefault; + return defaultValue != null; } /** @@ -104,12 +282,12 @@ protected T getDefaultValue() { } /** - * Checks if the parameter has an (actual) Argument that is not null!. + * Checks if the parameter has an Argument or default value that is not null!. * - * @return true if the parameter has an argument, false otherwise + * @return true if the parameter has an argument or default value, false otherwise */ public boolean hasArgument() { - return hasArgument; + return argument != null || defaultValue != null; } /** @@ -132,43 +310,44 @@ public boolean isProvided() { /** * getter method for the argument attribute - * @return argument as String + * @return argument if this parameter got a command-line argument, return default value if a default was specified + * and no command-line argument provided, return null if no default value specified and no command-line argument provided * @throws IllegalStateException if {@link ArgsParser#parse(String[] args)} was not called before trying to access this argument + * or if this Parameter was not added to any {@link ArgsParser}! */ public T getArgument() throws IllegalStateException { + if (argsParser == null) throw new IllegalStateException("Parameter: " + this + " is not assigned to any parser instance!"); if (!argsParser.parseArgsWasCalled()) throw new IllegalStateException("parse() was not called before trying to access the argument!"); - if (!hasArgument && !hasDefault) return null; - return argument; + if (argument != null) return argument; + else if (defaultValue != null) return defaultValue; + else return null; } /** * setter method for the argument attribute, sets parsed status of this parameter instance to true * @param argument argument * @throws InvalidArgTypeArgsException if the given Argument is not of the target type + * @throws NotExistingPathArgsException if a PthParameter with pathCheck was handed a non-existing path */ - protected void setArgument(String argument) throws InvalidArgTypeArgsException { + protected void setArgument(String argument) throws InvalidArgTypeArgsException, NotExistingPathArgsException { try { - ArgumentConverter argumentConverter = ArgumentConverter.fromClass(type); - this.argument = type.cast(argumentConverter.convert(argument)); - this.hasArgument = true; - } catch (IllegalArgumentException e) { - throw new InvalidArgTypeArgsException(this.fullFlag, type.getSimpleName(), "Unsupported type!"); + this.argument = castArgument(argument); + } catch (NumberFormatException nfe) { + throw new InvalidArgTypeArgsException(fullFlag, type.getSimpleName(), "Provided argument does not match the parameter type!"); + } catch (NotExistingPathArgsException argsExcep) { + throw argsExcep; } catch (Exception e) { - throw new InvalidArgTypeArgsException(this.fullFlag, type.getSimpleName(), e.getMessage()); + throw new InvalidArgTypeArgsException(fullFlag, type.getSimpleName(), e.getMessage()); } } /** - * Sets the default value for the argument and assigns it to the corresponding type-specific field. - * The value is also converted to a string and stored in the 'argument' field. - * - * @param defaultValue the default value to be set, which can be of type Integer, Double, Character, or Boolean - * @throws IllegalArgumentException if the type of defaultValue is unsupported + * Casts the argument to type T + * @param argument to be cast + * @return the argument as type T + * @throws NotExistingPathArgsException if a PthParameter with pathCheck was handed a non-existing path */ - protected void setDefault(T defaultValue) { - this.defaultValue = this.argument = defaultValue; - hasDefault = true; - } + protected abstract T castArgument(String argument) throws NotExistingPathArgsException; @Override public boolean equals(Object o) { @@ -183,73 +362,9 @@ public int hashCode() { return Objects.hash(fullFlag); } - /** - * The ArgumentConverter enum provides a mapping between argument types and their - * corresponding conversion logic. It supports both array and non-array types for - * several common data types such as Integer, String, Boolean, Double, and Character. - */ - private enum ArgumentConverter { - INTEGER_ARRAY(Integer[].class, Integer::parseInt), - INTEGER(Integer.class, Integer::parseInt), - STRING_ARRAY(String[].class, Function.identity()), - STRING(String.class, Function.identity()), - BOOLEAN_ARRAY(Boolean[].class, Boolean::parseBoolean), - BOOLEAN(Boolean.class, Boolean::parseBoolean), - DOUBLE_ARRAY(Double[].class, Double::parseDouble), - DOUBLE(Double.class, Double::parseDouble), - CHARACTER_ARRAY(Character[].class, s -> s.charAt(0)), - CHARACTER(Character.class, s -> s.charAt(0)), - PATH(Path.class, Path::of); - - private final Class typeClass; - private final Function mapper; - - /** - * Constructs an ArgumentConverter with the specified type class and mapping function. - * - * @param typeClass the class type this ArgumentConverter will handle. Can be an array class or a single class. - * @param mapper a function that converts a String argument to an instance of the specified class type. - */ - ArgumentConverter(Class typeClass, Function mapper) { - this.typeClass = typeClass; - this.mapper = mapper; - } - - /** - * Converts the provided argument string into an Object of the appropriate type, - * handling both array and non-array types. - * - * @param argument the argument string to be converted - * @return the converted object, either as a single instance or an array - */ - private Object convert(String argument) { - if (typeClass.isArray()) { - String[] parts = argument.split("==="); - Object array = Array.newInstance(typeClass.getComponentType(), parts.length); - for (int i = 0; i < parts.length; i++) { - Array.set(array, i, mapper.apply(parts[i])); - } - return array; - } else { - return mapper.apply(argument); - } - } - - /** - * Returns an ArgumentConverter that matches the provided class type. - * - * @param cls the class type to match against the available ArgumentConverters - * @return the ArgumentConverter corresponding to the provided class type - * @throws IllegalArgumentException if the provided class type is not supported - */ - private static ArgumentConverter fromClass(Class cls) { - for (ArgumentConverter argumentConverter : values()) { - if (argumentConverter.typeClass.equals(cls)) { - return argumentConverter; - } - } - throw new IllegalArgumentException("Unsupported type: " + cls.getSimpleName()); - } + @Override + public String toString() { + return "[" + fullFlag + " / " + shortFlag + "]"; } } diff --git a/src/ArgsParser/ParameterTypes/BolArrParameter.java b/src/ArgsParser/ParameterTypes/BolArrParameter.java new file mode 100644 index 0000000..94f6819 --- /dev/null +++ b/src/ArgsParser/ParameterTypes/BolArrParameter.java @@ -0,0 +1,95 @@ +package ArgsParser.ParameterTypes; + +import ArgsParser.Parameter; + +import java.util.Arrays; + +/** + * Represents a parameter that holds an array of boolean values. + * + * This class extends {@link Parameter} to manage parameters of type {@link Boolean[]}. + * It provides constructors for defining the parameter with flags, descriptions, + * mandatory status, and default values. + * + *

      + * The {@code castArgument} method is overridden to parse string arguments into {@link Boolean} values + * and add them to the existing array of booleans. + *

      + */ +public class BolArrParameter extends Parameter { + /** + * Constructs a new {@link Parameter} of type {@link Boolean}-array instance with the specified flags, description, and mandatory status. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @param isMandatory Indicates if this parameter is mandatory. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public BolArrParameter(String fullFlag, String shortFlag, String description, boolean isMandatory) { + super(fullFlag, shortFlag, description, isMandatory, Boolean[].class); + } + + /** + * Constructs a new {@link Parameter} of type {@link Boolean}-array instance with the specified flags, description, and a default value. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param defaultValue Sets a default value for this Parameter & makes it not mandatory. + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public BolArrParameter(Boolean[] defaultValue, String fullFlag, String shortFlag, String description) { + super(defaultValue, fullFlag, shortFlag, description, Boolean[].class); + } + + /** + * Casts the argument to type T + * + * @param argument to be cast + * @return the argument as type T + */ + @Override + protected Boolean[] castArgument(String argument) { + Boolean[] array = super.readArgument(); + array = array == null ? new Boolean[1] : Arrays.copyOf(array, array.length + 1); + array[array.length - 1] = Boolean.parseBoolean(argument); + return array; + } +} diff --git a/src/ArgsParser/ParameterTypes/BolParameter.java b/src/ArgsParser/ParameterTypes/BolParameter.java new file mode 100644 index 0000000..7f477dd --- /dev/null +++ b/src/ArgsParser/ParameterTypes/BolParameter.java @@ -0,0 +1,89 @@ +package ArgsParser.ParameterTypes; + +import ArgsParser.Parameter; + +/** + * Represents a parameter that holds a boolean value. + * + * This class extends {@link Parameter} to manage parameters of type {@link Boolean}. + * It provides constructors for defining the parameter with flags, descriptions, + * mandatory status, and default values. + * + *

      + * The {@code castArgument} method is overridden to parse string arguments into {@link Boolean} values. + *

      + */ +public class BolParameter extends Parameter { + /** + * Constructs a new {@link Parameter} of type {@link Boolean} instance with the specified flags, description, and mandatory status. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @param isMandatory Indicates if this parameter is mandatory. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public BolParameter(String fullFlag, String shortFlag, String description, boolean isMandatory) { + super(fullFlag, shortFlag, description, isMandatory, Boolean.class); + } + + /** + * Constructs a new {@link Parameter} of type {@link Boolean} instance with the specified flags, description, and a default value. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param defaultValue Sets a default value for this Parameter & makes it not mandatory. + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public BolParameter(Boolean defaultValue, String fullFlag, String shortFlag, String description) { + super(defaultValue, fullFlag, shortFlag, description, Boolean.class); + } + + /** + * Casts the argument to type T + * + * @param argument to be cast + * @return the argument as type T + */ + @Override + protected Boolean castArgument(String argument) { + return Boolean.parseBoolean(argument); + } +} diff --git a/src/ArgsParser/ParameterTypes/ChrArrParameter.java b/src/ArgsParser/ParameterTypes/ChrArrParameter.java new file mode 100644 index 0000000..8f3cb88 --- /dev/null +++ b/src/ArgsParser/ParameterTypes/ChrArrParameter.java @@ -0,0 +1,95 @@ +package ArgsParser.ParameterTypes; + +import ArgsParser.Parameter; + +import java.util.Arrays; + +/** + * Represents a parameter that holds an array of characters. + * + * This class extends {@link Parameter} to manage parameters of type {@link Character}-array. + * It provides constructors for defining the parameter with full and short flags, descriptions, + * mandatory status, and default values. + * + *

      + * The {@code castArgument} method is overridden to parse string arguments into {@link Character} values + * and add them to the existing array of characters. + *

      + */ +public class ChrArrParameter extends Parameter { + /** + * Constructs a new {@link Parameter} of type {@link Character}-array instance with the specified flags, description, and mandatory status. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @param isMandatory Indicates if this parameter is mandatory. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public ChrArrParameter(String fullFlag, String shortFlag, String description, boolean isMandatory) { + super(fullFlag, shortFlag, description, isMandatory, Character[].class); + } + + /** + * Constructs a new {@link Parameter} of type {@link Character}-array instance with the specified flags, description, and a default value. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param defaultValue Sets a default value for this Parameter & makes it not mandatory. + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public ChrArrParameter(Character[] defaultValue, String fullFlag, String shortFlag, String description) { + super(defaultValue, fullFlag, shortFlag, description, Character[].class); + } + + /** + * Casts the argument to type T + * + * @param argument to be cast + * @return the argument as type T + */ + @Override + protected Character[] castArgument(String argument) { + Character[] array = super.readArgument(); + array = array == null ? new Character[1] : Arrays.copyOf(array, array.length + 1); + array[array.length - 1] = argument.charAt(0); + return array; + } +} diff --git a/src/ArgsParser/ParameterTypes/ChrParameter.java b/src/ArgsParser/ParameterTypes/ChrParameter.java new file mode 100644 index 0000000..ac3c1fe --- /dev/null +++ b/src/ArgsParser/ParameterTypes/ChrParameter.java @@ -0,0 +1,89 @@ +package ArgsParser.ParameterTypes; + +import ArgsParser.Parameter; + +/** + * Represents a parameter that holds a character value. + * + * This class extends {@link Parameter} to manage parameters of type {@link Character}. + * It provides constructors for defining the parameter with full and short flags, descriptions, + * mandatory status, and default values. + * + *

      + * The {@code castArgument} method is overridden to parse string arguments into {@link Character} values. + *

      + */ +public class ChrParameter extends Parameter { + /** + * Constructs a new {@link Parameter} of type {@link Character} instance with the specified flags, description, and mandatory status. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @param isMandatory Indicates if this parameter is mandatory. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public ChrParameter(String fullFlag, String shortFlag, String description, boolean isMandatory) { + super(fullFlag, shortFlag, description, isMandatory, Character.class); + } + + /** + * Constructs a new {@link Parameter} of type {@link Character} instance with the specified flags, description, and a default value. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param defaultValue Sets a default value for this Parameter & makes it not mandatory. + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public ChrParameter(Character defaultValue, String fullFlag, String shortFlag, String description) { + super(defaultValue, fullFlag, shortFlag, description, Character.class); + } + + /** + * Casts the argument to type T + * + * @param argument to be cast + * @return the argument as type T + */ + @Override + protected Character castArgument(String argument) { + return argument.charAt(0); + } +} diff --git a/src/ArgsParser/ParameterTypes/DblArrParameter.java b/src/ArgsParser/ParameterTypes/DblArrParameter.java new file mode 100644 index 0000000..797619f --- /dev/null +++ b/src/ArgsParser/ParameterTypes/DblArrParameter.java @@ -0,0 +1,95 @@ +package ArgsParser.ParameterTypes; + +import ArgsParser.Parameter; + +import java.util.Arrays; + +/** + * Represents a parameter that holds an array of double values. + * + * This class extends {@link Parameter} to manage parameters of type {@link Double}-array. + * It provides constructors for defining the parameter with flags, descriptions, mandatory status, + * and default values. + * + *

      + * The {@code castArgument} method is overridden to parse string arguments into {@link Double} values + * and add them to the existing array of doubles. + *

      + */ +public class DblArrParameter extends Parameter { + /** + * Constructs a new {@link Parameter} of type {@link Double}-array instance with the specified flags, description, and mandatory status. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @param isMandatory Indicates if this parameter is mandatory. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public DblArrParameter(String fullFlag, String shortFlag, String description, boolean isMandatory) { + super(fullFlag, shortFlag, description, isMandatory, Double[].class); + } + + /** + * Constructs a new {@link Parameter} of type {@link Double}-array instance with the specified flags, description, and a default value. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param defaultValue Sets a default value for this Parameter & makes it not mandatory. + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public DblArrParameter(Double[] defaultValue, String fullFlag, String shortFlag, String description) { + super(defaultValue, fullFlag, shortFlag, description, Double[].class); + } + + /** + * Casts the argument to type T + * + * @param argument to be cast + * @return the argument as type T + */ + @Override + protected Double[] castArgument(String argument) { + Double[] array = super.readArgument(); + array = array == null ? new Double[1] : Arrays.copyOf(array, array.length + 1); + array[array.length - 1] = Double.parseDouble(argument); + return array; + } +} diff --git a/src/ArgsParser/ParameterTypes/DblParameter.java b/src/ArgsParser/ParameterTypes/DblParameter.java new file mode 100644 index 0000000..bf534de --- /dev/null +++ b/src/ArgsParser/ParameterTypes/DblParameter.java @@ -0,0 +1,89 @@ +package ArgsParser.ParameterTypes; + +import ArgsParser.Parameter; + +/** + * Represents a parameter that holds a double-precision floating-point value. + * + * This class extends {@link Parameter} to manage parameters of type {@link Double}. + * It provides constructors for defining the parameter with flags, descriptions, mandatory status, + * and default values. + * + *

      + * The {@code castArgument} method is overridden to parse string arguments into {@link Double} values. + *

      + */ +public class DblParameter extends Parameter { + /** + * Constructs a new {@link Parameter} of type {@link Double} instance with the specified flags, description, and mandatory status. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @param isMandatory Indicates if this parameter is mandatory. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public DblParameter(String fullFlag, String shortFlag, String description, boolean isMandatory) { + super(fullFlag, shortFlag, description, isMandatory, Double.class); + } + + /** + * Constructs a new {@link Parameter} of type {@link Double} instance with the specified flags, description, and a default value. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param defaultValue Sets a default value for this Parameter & makes it not mandatory. + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public DblParameter(Double defaultValue, String fullFlag, String shortFlag, String description) { + super(defaultValue, fullFlag, shortFlag, description, Double.class); + } + + /** + * Casts the argument to type T + * + * @param argument to be cast + * @return the argument as type T + */ + @Override + protected Double castArgument(String argument) { + return Double.parseDouble(argument); + } +} diff --git a/src/ArgsParser/ParameterTypes/FltArrParameter.java b/src/ArgsParser/ParameterTypes/FltArrParameter.java new file mode 100644 index 0000000..d680361 --- /dev/null +++ b/src/ArgsParser/ParameterTypes/FltArrParameter.java @@ -0,0 +1,95 @@ +package ArgsParser.ParameterTypes; + +import ArgsParser.Parameter; + +import java.util.Arrays; + +/** + * Represents a parameter that holds an array of floating-point values. + * + * This class extends {@link Parameter} to manage parameters of type {@link Float}-array. + * It provides constructors for defining the parameter with flags, descriptions, mandatory status, + * and default values. + * + *

      + * The {@code castArgument} method is overridden to parse string arguments into {@link Float} values + * and add them to the existing array of floats. + *

      + */ +public class FltArrParameter extends Parameter { + /** + * Constructs a new {@link Parameter} of type {@link Float}-array instance with the specified flags, description, and mandatory status. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @param isMandatory Indicates if this parameter is mandatory. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public FltArrParameter(String fullFlag, String shortFlag, String description, boolean isMandatory) { + super(fullFlag, shortFlag, description, isMandatory, Float[].class); + } + + /** + * Constructs a new {@link Parameter} of type {@link Float}-array instance with the specified flags, description, and a default value. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param defaultValue Sets a default value for this Parameter & makes it not mandatory. + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public FltArrParameter(Float[] defaultValue, String fullFlag, String shortFlag, String description) { + super(defaultValue, fullFlag, shortFlag, description, Float[].class); + } + + /** + * Casts the argument to type T + * + * @param argument to be cast + * @return the argument as type T + */ + @Override + protected Float[] castArgument(String argument) { + Float[] array = super.readArgument(); + array = array == null ? new Float[1] : Arrays.copyOf(array, array.length + 1); + array[array.length - 1] = Float.parseFloat(argument); + return array; + } +} diff --git a/src/ArgsParser/ParameterTypes/FltParameter.java b/src/ArgsParser/ParameterTypes/FltParameter.java new file mode 100644 index 0000000..26b4f92 --- /dev/null +++ b/src/ArgsParser/ParameterTypes/FltParameter.java @@ -0,0 +1,89 @@ +package ArgsParser.ParameterTypes; + +import ArgsParser.Parameter; + +/** + * Represents a parameter that holds a floating-point value. + * + * This class extends {@link Parameter} to manage parameters of type {@link Float}. + * It provides constructors for defining the parameter with flags, descriptions, mandatory status, + * and default values. + * + *

      + * The {@code castArgument} method is overridden to parse string arguments into {@link Float} values. + *

      + */ +public class FltParameter extends Parameter { + /** + * Constructs a new {@link Parameter} of type {@link Float} instance with the specified flags, description, and mandatory status. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @param isMandatory Indicates if this parameter is mandatory. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public FltParameter(String fullFlag, String shortFlag, String description, boolean isMandatory) { + super(fullFlag, shortFlag, description, isMandatory, Float.class); + } + + /** + * Constructs a new {@link Parameter} of type {@link Float} instance with the specified flags, description, and a default value. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param defaultValue Sets a default value for this Parameter & makes it not mandatory. + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public FltParameter(Float defaultValue, String fullFlag, String shortFlag, String description) { + super(defaultValue, fullFlag, shortFlag, description, Float.class); + } + + /** + * Casts the argument to type T + * + * @param argument to be cast + * @return the argument as type T + */ + @Override + protected Float castArgument(String argument) { + return Float.parseFloat(argument); + } +} diff --git a/src/ArgsParser/ParameterTypes/IntArrParameter.java b/src/ArgsParser/ParameterTypes/IntArrParameter.java new file mode 100644 index 0000000..7d12435 --- /dev/null +++ b/src/ArgsParser/ParameterTypes/IntArrParameter.java @@ -0,0 +1,95 @@ +package ArgsParser.ParameterTypes; + +import ArgsParser.Parameter; + +import java.util.Arrays; + +/** + * Represents a parameter that holds an array of integers. + * + * This class extends {@link Parameter} to manage parameters of type {@link Integer}-array. + * It provides constructors for defining the parameter with flags, descriptions, mandatory status, + * and default values. + * + *

      + * The {@code castArgument} method is overridden to parse string arguments into integers and + * add them to the existing array of integers. + *

      + */ +public class IntArrParameter extends Parameter { + /** + * Constructs a new {@link Parameter} of type {@link Integer}-array instance with the specified flags, description, and mandatory status. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @param isMandatory Indicates if this parameter is mandatory. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public IntArrParameter(String fullFlag, String shortFlag, String description, boolean isMandatory) { + super(fullFlag, shortFlag, description, isMandatory, Integer[].class); + } + + /** + * Constructs a new {@link Parameter} of type {@link Integer}-array instance with the specified flags, description, and a default value. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param defaultValue Sets a default value for this Parameter & makes it not mandatory. + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public IntArrParameter(Integer[] defaultValue, String fullFlag, String shortFlag, String description) { + super(defaultValue, fullFlag, shortFlag, description, Integer[].class); + } + + /** + * Casts the argument to type T + * + * @param argument to be cast + * @return the argument as type T + */ + @Override + protected Integer[] castArgument(String argument) { + Integer[] array = super.readArgument(); + array = array == null ? new Integer[1] : Arrays.copyOf(array, array.length + 1); + array[array.length - 1] = Integer.parseInt(argument); + return array; + } +} diff --git a/src/ArgsParser/ParameterTypes/IntParameter.java b/src/ArgsParser/ParameterTypes/IntParameter.java new file mode 100644 index 0000000..14d3e8e --- /dev/null +++ b/src/ArgsParser/ParameterTypes/IntParameter.java @@ -0,0 +1,86 @@ +package ArgsParser.ParameterTypes; + +import ArgsParser.Parameter; + +/** + * Represents a parameter that holds an integer value. + * + * This class extends {@link Parameter} to manage parameters of type {@link Integer}. + * It provides constructors for defining the parameter with flags, descriptions, mandatory status, + * and default values. Additionally, it overrides the {@code castArgument} method to parse + * string arguments into integers. + */ +public class IntParameter extends Parameter { + /** + * Constructs a new {@link Parameter} of type {@link Integer} instance with the specified flags, description, and mandatory status. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @param isMandatory Indicates if this parameter is mandatory. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public IntParameter(String fullFlag, String shortFlag, String description, boolean isMandatory) { + super(fullFlag, shortFlag, description, isMandatory, Integer.class); + } + + /** + * Constructs a new {@link Parameter} of type {@link Integer} instance with the specified flags, description, and a default value. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param defaultValue Sets a default value for this Parameter & makes it not mandatory. + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public IntParameter(Integer defaultValue, String fullFlag, String shortFlag, String description) { + super(defaultValue, fullFlag, shortFlag, description, Integer.class); + } + + /** + * Casts the argument to type T + * + * @param argument to be cast + * @return the argument as type T + */ + @Override + protected Integer castArgument(String argument) { + return Integer.parseInt(argument); + } +} diff --git a/src/ArgsParser/ParameterTypes/PthArrParameter.java b/src/ArgsParser/ParameterTypes/PthArrParameter.java new file mode 100644 index 0000000..d2eaaad --- /dev/null +++ b/src/ArgsParser/ParameterTypes/PthArrParameter.java @@ -0,0 +1,106 @@ +package ArgsParser.ParameterTypes; + +import ArgsParser.ArgsExceptions.NotExistingPathArgsException; +import ArgsParser.Parameter; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; + +/** + * Represents a parameter that holds an array of file system paths. + * + * This class extends {@link Parameter} to manage parameters of type {@link Path}-array. + * It provides constructors for defining the parameter with flags, descriptions, mandatory status, + * default values, and the option to validate the existence of each path. + * + *

      + * The {@code pathCheck} field determines whether the existence of the specified paths + * should be validated during parsing. + *

      + */ +public class PthArrParameter extends Parameter { + + private final boolean pathCheck; + + /** + * Constructs a new {@link Parameter} of type {@link Path}-array instance with the specified flags, description, and mandatory status. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @param isMandatory Indicates if this parameter is mandatory. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public PthArrParameter(String fullFlag, String shortFlag, String description, boolean isMandatory, boolean pathCheck) { + super(fullFlag, shortFlag, description, isMandatory, Path[].class); + this.pathCheck = pathCheck; + } + + /** + * Constructs a new {@link Parameter} of type {@link Path}-array instance with the specified flags, description, and a default value. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param defaultValue Sets a default value for this Parameter & makes it not mandatory. + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public PthArrParameter(Path[] defaultValue, String fullFlag, String shortFlag, String description, boolean pathCheck) { + super(defaultValue, fullFlag, shortFlag, description, Path[].class); + this.pathCheck = pathCheck; + } + + /** + * Casts the argument to type T + * + * @param argument to be cast + * @return the argument as type T + * @throws NotExistingPathArgsException if a PthParameter with pathCheck was handed a non-existing path + */ + @Override + protected Path[] castArgument(String argument) throws NotExistingPathArgsException { + Path[] array = super.readArgument(); + array = array == null ? new Path[1] : Arrays.copyOf(array, array.length + 1); + Path pathToAdd = Path.of(argument); + if (pathCheck && !Files.exists(pathToAdd)) throw new NotExistingPathArgsException(pathToAdd); + array[array.length - 1] = pathToAdd; + return array; + } +} diff --git a/src/ArgsParser/ParameterTypes/PthParameter.java b/src/ArgsParser/ParameterTypes/PthParameter.java new file mode 100644 index 0000000..1f86bf0 --- /dev/null +++ b/src/ArgsParser/ParameterTypes/PthParameter.java @@ -0,0 +1,122 @@ +package ArgsParser.ParameterTypes; + +import ArgsParser.ArgsExceptions.NotExistingPathArgsException; +import ArgsParser.Parameter; + +import java.nio.file.Files; +import java.nio.file.Path; + +/** + * Represents a parameter that holds a file system path. + * + * This class extends {@link Parameter} to manage parameters of type {@link Path}. + * It provides constructors for defining the parameter with flags, descriptions, + * mandatory status, default values, and the option to check if the path exists. + * + *

      + * The {@code pathCheck} field determines whether the existence of the specified path + * should be validated during parsing. + *

      + */ +public class PthParameter extends Parameter { + + private final boolean pathCheck; + + /** + * Constructs a new {@link Parameter} of type {@link Path} instance with the specified flags, description, and mandatory status. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @param isMandatory Indicates if this parameter is mandatory. + * @param pathCheck Specify whether to automatically check if the path exists or to not check while parsing. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public PthParameter(String fullFlag, String shortFlag, String description, boolean isMandatory, boolean pathCheck) { + super(fullFlag, shortFlag, description, isMandatory, Path.class); + this.pathCheck = pathCheck; + } + + /** + * Constructs a new {@link Parameter} of type {@link Path} instance with the specified flags, description, and a default value. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param defaultValue Sets a default value for this Parameter & makes it not mandatory. + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public PthParameter(Path defaultValue, String fullFlag, String shortFlag, String description, boolean pathCheck) { + super(defaultValue, fullFlag, shortFlag, description, Path.class); + this.pathCheck = pathCheck; + } + + /** + * Checks if the path specified by the current argument exists in the file system. + *

      + * This method retrieves the argument value associated with this parameter, + * interprets it as a file system path, and verifies whether it exists. + *

      + * + *

      Behavior:

      + *
        + *
      • Returns {@code true} if the path exists, otherwise {@code false}.
      • + *
      • If the argument is invalid or null, this method may throw a {@link NullPointerException}.
      • + *
      + * + * @return {@code true} if the path exists, otherwise {@code false}. + */ + public boolean pathExists() { + return Files.exists(super.getArgument()); + } + + /** + * Casts the argument to type T + * + * @param argument to be cast + * @return the argument as type T + * @throws NotExistingPathArgsException if a PthParameter with pathCheck was handed a non-existing path + */ + @Override + protected Path castArgument(String argument) throws NotExistingPathArgsException { + Path path = Path.of(argument); + if (pathCheck && !Files.exists(path)) throw new NotExistingPathArgsException(path); + return path; + } +} diff --git a/src/ArgsParser/ParameterTypes/StrArrParameter.java b/src/ArgsParser/ParameterTypes/StrArrParameter.java new file mode 100644 index 0000000..10ef47d --- /dev/null +++ b/src/ArgsParser/ParameterTypes/StrArrParameter.java @@ -0,0 +1,90 @@ +package ArgsParser.ParameterTypes; + +import ArgsParser.Parameter; + +import java.util.Arrays; + +/** + * Represents a parameter that holds an array of strings. + * + * This class extends {@link Parameter} to manage parameters of type {@link String}-array. + * It provides constructors for defining the parameter with flags, descriptions, mandatory status, and default values. + */ +public class StrArrParameter extends Parameter { + + /** + * Constructs a new {@link Parameter} of type {@link String}-Array instance with the specified flags, description, and mandatory status. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @param isMandatory Indicates if this parameter is mandatory. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public StrArrParameter(String fullFlag, String shortFlag, String description, boolean isMandatory) { + super(fullFlag, shortFlag, description, isMandatory, String[].class); + } + + /** + * Constructs a new {@link Parameter} of type {@link String}-Array instance with the specified flags, description, and a default value. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param defaultValue Sets a default value for this Parameter & makes it not mandatory. + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public StrArrParameter(String[] defaultValue, String fullFlag, String shortFlag, String description) { + super(defaultValue, fullFlag, shortFlag, description, String[].class); + } + + /** + * Casts the argument to type T + * + * @param argument to be cast + * @return the argument as type T + */ + @Override + protected String[] castArgument(String argument) { + String[] array = super.readArgument(); + array = array == null ? new String[1] : Arrays.copyOf(array, array.length + 1); + array[array.length - 1] = argument; + return array; + } +} diff --git a/src/ArgsParser/ParameterTypes/StrParameter.java b/src/ArgsParser/ParameterTypes/StrParameter.java new file mode 100644 index 0000000..922d618 --- /dev/null +++ b/src/ArgsParser/ParameterTypes/StrParameter.java @@ -0,0 +1,86 @@ +package ArgsParser.ParameterTypes; + +import ArgsParser.Parameter; + +/** + * Represents a string parameter for argument parsing. + * + * This class extends {@link Parameter} to handle parameters of type {@link String}. + * It provides constructors to define the parameter with flags, descriptions, mandatory status, + * and default values. + */ +public class StrParameter extends Parameter { + + /** + * Constructs a new {@link Parameter} of type {@link String} instance with the specified flags, description, and mandatory status. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @param isMandatory Indicates if this parameter is mandatory. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public StrParameter(String fullFlag, String shortFlag, String description, boolean isMandatory) { + super(fullFlag, shortFlag, description, isMandatory, String.class); + } + + /** + * Constructs a new {@link Parameter} of type {@link String} instance with the specified flags, description, and a default value. + *

      + * The constructor validates and formats the provided flag names. + *

      + * + *

      Behavior:

      + *
        + *
      • Validates that the full and short flags are correctly formatted and non-empty.
      • + *
      • Stores the description and mandatory status of the parameter.
      • + *
      • Initializes internal fields for argument management and default values.
      • + *
      + * + *

      Flag Validation Rules:

      + *
        + *
      • Full Flag: Full words recommended (e.g., example), two dashes `--` will automatically be added.
      • + *
      • Short Flag: Abbreviations of the fullFlag are recommended (e.g., e), one dash `-`will automatically be added.
      • + *
      • Reserved Flags: The flags `--help` and `-h` cannot be used.
      • + *
      • Uniqueness: Full and short flags must be unique and must not already be defined.
      • + *
      + * + * @param defaultValue Sets a default value for this Parameter & makes it not mandatory. + * @param fullFlag The full version of the flag (e.g., `--example`). + * @param shortFlag The short version of the flag (e.g., `-e`). + * @param description A brief description of what the parameter represents. + * @throws IllegalArgumentException If the flag names are invalid, empty, or reserved. + */ + public StrParameter(String defaultValue, String fullFlag, String shortFlag, String description) { + super(defaultValue, fullFlag, shortFlag, description, String.class); + } + + /** + * Casts the argument to type T + * + * @param argument to be cast + * @return the argument as type T + */ + @Override + protected String castArgument(String argument) { + return argument; + } +} diff --git a/src/ArgsParser/RuntimeExeptions/ParameterTypeNotDefined.java b/src/ArgsParser/RuntimeExeptions/ParameterTypeNotDefined.java deleted file mode 100644 index 2d37b1c..0000000 --- a/src/ArgsParser/RuntimeExeptions/ParameterTypeNotDefined.java +++ /dev/null @@ -1,10 +0,0 @@ -package ArgsParser.RuntimeExeptions; - -/** - * Exception thrown when the type of a parameter is not defined but a non-String type argument is tried to access. - */ -public class ParameterTypeNotDefined extends RuntimeException { - public ParameterTypeNotDefined(String flagName) { - super("Type for parameter: " + flagName + " not defined!"); - } -} diff --git a/src/test/TestAddParameterMethods.java b/src/test/TestAddParameterMethods.java index ed35f46..b892b18 100644 --- a/src/test/TestAddParameterMethods.java +++ b/src/test/TestAddParameterMethods.java @@ -2,6 +2,7 @@ import static org.junit.jupiter.api.Assertions.*; import ArgsParser.ArgsExceptions.ToggleArgsException; +import ArgsParser.ParameterTypes.*; import org.junit.jupiter.api.Test; import java.nio.file.Path; @@ -19,7 +20,7 @@ public class TestAddParameterMethods { public void testAddMandatoryStringParameter() { String[] args = {"--String", "this is a string"}; ArgsParser parser = new ArgsParser(); - Parameter str = parser.addMandatoryStringParameter("String", "s", "desc"); + StrParameter str = parser.addParameter(new StrParameter("String", "s", "desc", true)); parser.parse(args); assertEquals("this is a string", str.getArgument()); @@ -29,7 +30,7 @@ public void testAddMandatoryStringParameter() { public void testAddOptionalStringParameter() { String[] args = {"--String", "this is a string"}; ArgsParser parser = new ArgsParser(); - Parameter str = parser.addOptionalStringParameter("String", "s", "desc"); + StrParameter str = parser.addParameter(new StrParameter("String", "s", "desc", false)); parser.parse(args); assertEquals("this is a string", str.getArgument()); @@ -39,27 +40,27 @@ public void testAddOptionalStringParameter() { public void testAddDefaultStringParameterWithoutArgument() { String[] args = new String[0]; ArgsParser parser = new ArgsParser(); - Parameter deafult = parser.addDefaultStringParameter("DefaultString", "df", "desc", "this is the default"); + StrParameter defString = parser.addParameter(new StrParameter("This is the default", "DefaultString", "df", "desc")); parser.parse(args); - assertEquals("this is the default", deafult.getArgument()); + assertEquals("This is the default", defString.getArgument()); } @Test public void testAddDefaultStringParameterWithArgument() { String[] args = {"--DefaultString", "this is a string"}; ArgsParser parser = new ArgsParser(); - Parameter defaultParam = parser.addDefaultStringParameter("DefaultString", "df", "desc", "this is the default"); + StrParameter defString = parser.addParameter(new StrParameter("This is the default", "DefaultString", "df", "desc")); parser.parse(args); - assertEquals("this is a string", defaultParam.getArgument()); + assertEquals("this is a string", defString.getArgument()); } @Test public void testAddStringArrayParameter() { String[] args = {"--StringArray", "this is a string", "and this is another"}; ArgsParser parser = new ArgsParser(); - Parameter stringArray = parser.addStringArrayParameter("StringArray", "strA", "desc", true); + StrArrParameter stringArray = parser.addParameter(new StrArrParameter("StringArray", "strA", "desc", true)); parser.parse(args); assertArrayEquals(new String[]{"this is a string", "and this is another"}, stringArray.getArgument()); @@ -69,7 +70,7 @@ public void testAddStringArrayParameter() { public void testAddDefaultStringArrayParameterWithoutArgument() { String[] args = new String[0]; ArgsParser parser = new ArgsParser(); - Parameter defaultStringArray = parser.addDefaultStringArrayParameter("StringArray", "strA", "desc", new String[]{"this is the default", "and this is another"}); + StrArrParameter defaultStringArray = parser.addParameter(new StrArrParameter(new String[]{"this is the default", "and this is another"},"StringArray", "strA", "desc")); parser.parse(args); assertArrayEquals(new String[]{"this is the default", "and this is another"}, defaultStringArray.getArgument()); @@ -79,7 +80,7 @@ public void testAddDefaultStringArrayParameterWithoutArgument() { public void testAddStringArrayParameterWithArgument() { String[] args = {"--StringArray", "this is a string", "and this is another"}; ArgsParser parser = new ArgsParser(); - Parameter defaultStringArray = parser.addDefaultStringArrayParameter("StringArray", "strA", "desc", new String[]{"this", "is", "default"}); + StrArrParameter defaultStringArray = parser.addParameter(new StrArrParameter(new String[]{"this", "is", "default"}, "StringArray", "strA", "desc")); parser.parse(args); assertArrayEquals(new String[]{"this is a string", "and this is another"}, defaultStringArray.getArgument()); @@ -92,27 +93,27 @@ public void testAddStringArrayParameterWithArgument() { public void testAddMandatoryIntegerParameter() { String[] args = {"--Integer", "42"}; ArgsParser parser = new ArgsParser(); - Parameter integerParam = parser.addMandatoryIntegerParameter("Integer", "i", "desc"); + IntParameter intParam = parser.addParameter(new IntParameter("Integer", "i", "desc", true)); parser.parse(args); - assertEquals(42, integerParam.getArgument()); + assertEquals(42, intParam.getArgument()); } @Test public void testAddOptionalIntegerParameter() { String[] args = {"--Integer", "42"}; ArgsParser parser = new ArgsParser(); - Parameter integerParam = parser.addOptionalIntegerParameter("Integer", "i", "desc"); + IntParameter intParam = parser.addParameter(new IntParameter("Integer", "i", "desc", false)); parser.parse(args); - assertEquals(42, integerParam.getArgument()); + assertEquals(42, intParam.getArgument()); } @Test public void testAddDefaultIntegerParameterWithoutArgument() { String[] args = new String[0]; ArgsParser parser = new ArgsParser(); - Parameter defaultInteger = parser.addDefaultIntegerParameter("DefaultInteger", "di", "desc", 10); + IntParameter defaultInteger = parser.addParameter(new IntParameter(10, "DefaultInteger", "di", "desc")); parser.parse(args); assertEquals(10, defaultInteger.getArgument()); @@ -122,7 +123,7 @@ public void testAddDefaultIntegerParameterWithoutArgument() { public void testAddDefaultIntegerParameterWithArgument() { String[] args = {"--DefaultInteger", "42"}; ArgsParser parser = new ArgsParser(); - Parameter defaultInteger = parser.addDefaultIntegerParameter("DefaultInteger", "di", "desc", 10); + IntParameter defaultInteger = parser.addParameter(new IntParameter(10, "DefaultInteger", "di", "desc")); parser.parse(args); assertEquals(42, defaultInteger.getArgument()); @@ -132,7 +133,7 @@ public void testAddDefaultIntegerParameterWithArgument() { public void testAddIntegerArrayParameter() { String[] args = {"--IntegerArray", "1", "2", "3"}; ArgsParser parser = new ArgsParser(); - Parameter integerArray = parser.addIntegerArrayParameter("IntegerArray", "intA", "desc", true); + IntArrParameter integerArray = parser.addParameter(new IntArrParameter("IntegerArray", "intA", "desc", true)); parser.parse(args); assertArrayEquals(new Integer[]{1, 2, 3}, integerArray.getArgument()); @@ -142,7 +143,7 @@ public void testAddIntegerArrayParameter() { public void testAddDefaultIntegerArrayParameterWithoutArgument() { String[] args = new String[0]; ArgsParser parser = new ArgsParser(); - Parameter defaultIntegerArray = parser.addDefaultIntegerArrayParameter("IntegerArray", "intA", "desc", new Integer[]{4, 5, 6}); + IntArrParameter defaultIntegerArray = parser.addParameter(new IntArrParameter(new Integer[]{4, 5, 6}, "IntegerArray", "intA", "desc")); parser.parse(args); assertArrayEquals(new Integer[]{4, 5, 6}, defaultIntegerArray.getArgument()); @@ -152,7 +153,7 @@ public void testAddDefaultIntegerArrayParameterWithoutArgument() { public void testAddIntegerArrayParameterWithArgument() { String[] args = {"--IntegerArray", "1", "2", "3"}; ArgsParser parser = new ArgsParser(); - Parameter intArray = parser.addDefaultIntegerArrayParameter("IntegerArray", "intA", "desc", new Integer[]{4, 5, 6}); + IntArrParameter intArray = parser.addParameter(new IntArrParameter(new Integer[]{4, 5, 6}, "IntegerArray", "intA", "desc")); parser.parse(args); assertArrayEquals(new Integer[]{1, 2, 3}, intArray.getArgument()); @@ -165,7 +166,7 @@ public void testAddIntegerArrayParameterWithArgument() { public void testAddMandatoryDoubleParameter() { String[] args = {"--Double", "42.0"}; ArgsParser parser = new ArgsParser(); - Parameter doubleParam = parser.addMandatoryDoubleParameter("Double", "d", "desc"); + DblParameter doubleParam = parser.addParameter(new DblParameter("Double", "d", "desc", true)); parser.parse(args); assertEquals(42.0, doubleParam.getArgument()); @@ -175,7 +176,7 @@ public void testAddMandatoryDoubleParameter() { public void testAddOptionalDoubleParameter() { String[] args = {"--Double", "42.0"}; ArgsParser parser = new ArgsParser(); - Parameter doubleParam = parser.addOptionalDoubleParameter("Double", "d", "desc"); + DblParameter doubleParam = parser.addParameter(new DblParameter("Double", "d", "desc", false)); parser.parse(args); assertEquals(42.0, doubleParam.getArgument()); @@ -185,7 +186,7 @@ public void testAddOptionalDoubleParameter() { public void testAddDefaultDoubleParameterWithoutArgument() { String[] args = new String[0]; ArgsParser parser = new ArgsParser(); - Parameter defaultDouble = parser.addDefaultDoubleParameter("DefaultDouble", "dd", "desc", 10.0); + DblParameter defaultDouble = parser.addParameter(new DblParameter( 10.0, "DefaultDouble", "dd", "desc")); parser.parse(args); assertEquals(10.0, defaultDouble.getArgument()); @@ -195,7 +196,7 @@ public void testAddDefaultDoubleParameterWithoutArgument() { public void testAddDefaultDoubleParameterWithArgument() { String[] args = {"--DefaultDouble", "42.0"}; ArgsParser parser = new ArgsParser(); - Parameter defaultDouble = parser.addDefaultDoubleParameter("DefaultDouble", "dd", "desc", 10.0); + DblParameter defaultDouble = parser.addParameter(new DblParameter( 10.0, "DefaultDouble", "dd", "desc")); parser.parse(args); assertEquals(42.0, defaultDouble.getArgument()); @@ -205,7 +206,7 @@ public void testAddDefaultDoubleParameterWithArgument() { public void testAddDoubleArrayParameter() { String[] args = {"--DoubleArray", "1.1", "2.2", "3.3"}; ArgsParser parser = new ArgsParser(); - Parameter doubleArray = parser.addDoubleArrayParameter("DoubleArray", "dblA", "desc", true); + DblArrParameter doubleArray = parser.addParameter(new DblArrParameter("DoubleArray", "dblA", "desc", true)); parser.parse(args); assertArrayEquals(new Double[]{1.1, 2.2, 3.3}, doubleArray.getArgument()); @@ -215,7 +216,7 @@ public void testAddDoubleArrayParameter() { public void testAddDefaultDoubleArrayParameterWithoutArgument() { String[] args = new String[0]; ArgsParser parser = new ArgsParser(); - Parameter defaultDoubleArray = parser.addDefaultDoubleArrayParameter("DoubleArray", "dblA", "desc", new Double[]{4.4, 5.5, 6.6}); + DblArrParameter defaultDoubleArray = parser.addParameter(new DblArrParameter(new Double[]{4.4, 5.5, 6.6}, "DoubleArray", "dblA", "desc")); parser.parse(args); assertArrayEquals(new Double[]{4.4, 5.5, 6.6}, defaultDoubleArray.getArgument()); @@ -225,7 +226,7 @@ public void testAddDefaultDoubleArrayParameterWithoutArgument() { public void testAddDefaultDoubleArrayParameterWithArgument() { String[] args = {"--DoubleArray", "1.1", "2.2", "3.3"}; ArgsParser parser = new ArgsParser(); - Parameter defaultDoubleArray = parser.addDefaultDoubleArrayParameter("DoubleArray", "dblA", "desc", new Double[]{4.4, 5.5, 6.6}); + DblArrParameter defaultDoubleArray = parser.addParameter(new DblArrParameter(new Double[]{4.4, 5.5, 6.6}, "DoubleArray", "dblA", "desc")); parser.parse(args); assertArrayEquals(new Double[]{1.1, 2.2, 3.3}, defaultDoubleArray.getArgument()); @@ -238,7 +239,7 @@ public void testAddDefaultDoubleArrayParameterWithArgument() { public void testAddMandatoryBooleanParameter() { String[] args = {"--Boolean", "true"}; ArgsParser parser = new ArgsParser(); - Parameter booleanParam = parser.addMandatoryBooleanParameter("Boolean", "b", "desc"); + BolParameter booleanParam = parser.addParameter(new BolParameter("Boolean", "b", "desc", true)); parser.parse(args); assertTrue(booleanParam.getArgument()); @@ -248,7 +249,7 @@ public void testAddMandatoryBooleanParameter() { public void testAddOptionalBooleanParameter() { String[] args = {"--Boolean", "true"}; ArgsParser parser = new ArgsParser(); - Parameter booleanParam = parser.addOptionalBooleanParameter("Boolean", "b", "desc"); + BolParameter booleanParam = parser.addParameter(new BolParameter("Boolean", "b", "desc", false)); parser.parse(args); assertTrue(booleanParam.getArgument()); @@ -258,7 +259,7 @@ public void testAddOptionalBooleanParameter() { public void testAddDefaultBooleanParameterWithoutArgument() { String[] args = new String[0]; ArgsParser parser = new ArgsParser(); - Parameter defaultBoolean = parser.addDefaultBooleanParameter("DefaultBoolean", "db", "desc", true); + BolParameter defaultBoolean = parser.addParameter(new BolParameter(true, "DefaultBoolean", "db", "desc")); parser.parse(args); assertTrue(defaultBoolean.getArgument()); @@ -268,7 +269,7 @@ public void testAddDefaultBooleanParameterWithoutArgument() { public void testAddDefaultBooleanParameterWithArgument() { String[] args = {"--DefaultBoolean", "false"}; ArgsParser parser = new ArgsParser(); - Parameter defaultBoolean = parser.addDefaultBooleanParameter("DefaultBoolean", "db", "desc", true); + BolParameter defaultBoolean = parser.addParameter(new BolParameter(true, "DefaultBoolean", "db", "desc")); parser.parse(args); assertFalse(defaultBoolean.getArgument()); @@ -278,7 +279,10 @@ public void testAddDefaultBooleanParameterWithArgument() { public void testAddBooleanArrayParameter() { String[] args = {"--BooleanArray", "true", "false", "true"}; ArgsParser parser = new ArgsParser(); - Parameter booleanArray = parser.addBooleanArrayParameter("BooleanArray", "boolA", "desc", true); + // Using the new BolArrParameter (without default value, isMandatory = true) + BolArrParameter booleanArray = parser.addParameter( + new BolArrParameter("BooleanArray", "boolA", "desc", true) + ); parser.parse(args); assertArrayEquals(new Boolean[]{true, false, true}, booleanArray.getArgument()); @@ -288,9 +292,13 @@ public void testAddBooleanArrayParameter() { public void testAddDefaultBooleanArrayParameterWithoutArgument() { String[] args = new String[0]; ArgsParser parser = new ArgsParser(); - Parameter defaultBooleanArray = parser.addDefaultBooleanArrayParameter("BooleanArray", "boolA", "desc", new Boolean[]{true, false, true}); + // Using the new BolArrParameter with a default value (isMandatory omitted) + BolArrParameter defaultBooleanArray = parser.addParameter( + new BolArrParameter(new Boolean[]{true, false, true}, "BooleanArray", "boolA", "desc") + ); parser.parse(args); + // Since no arguments were passed, we expect the default array assertArrayEquals(new Boolean[]{true, false, true}, defaultBooleanArray.getArgument()); } @@ -298,21 +306,26 @@ public void testAddDefaultBooleanArrayParameterWithoutArgument() { public void testAddDefaultBooleanArrayParameterWithArgument() { String[] args = {"--BooleanArray", "false", "true", "false"}; ArgsParser parser = new ArgsParser(); - Parameter defaultBooleanArray = parser.addDefaultBooleanArrayParameter("BooleanArray", "boolA", "desc", new Boolean[]{true, false, true}); + // Same default-based constructor + BolArrParameter defaultBooleanArray = parser.addParameter( + new BolArrParameter(new Boolean[]{true, false, true}, "BooleanArray", "boolA", "desc") + ); parser.parse(args); + // We override the default with the passed arguments assertArrayEquals(new Boolean[]{false, true, false}, defaultBooleanArray.getArgument()); } - - -// Character Methods + // Character Methods @Test public void testAddMandatoryCharacterParameter() { String[] args = {"--Character", "a"}; ArgsParser parser = new ArgsParser(); - Parameter characterParam = parser.addMandatoryCharacterParameter("Character", "c", "desc"); + // Using the new ChrParameter (no default, isMandatory = true) + ChrParameter characterParam = parser.addParameter( + new ChrParameter("Character", "c", "desc", true) + ); parser.parse(args); assertEquals('a', characterParam.getArgument()); @@ -322,7 +335,10 @@ public void testAddMandatoryCharacterParameter() { public void testAddOptionalCharacterParameter() { String[] args = {"--Character", "a"}; ArgsParser parser = new ArgsParser(); - Parameter characterParam = parser.addOptionalCharacterParameter("Character", "c", "desc"); + // Using the new ChrParameter (no default, isMandatory = false) + ChrParameter characterParam = parser.addParameter( + new ChrParameter("Character", "c", "desc", false) + ); parser.parse(args); assertEquals('a', characterParam.getArgument()); @@ -332,9 +348,13 @@ public void testAddOptionalCharacterParameter() { public void testAddDefaultCharacterParameterWithoutArgument() { String[] args = new String[0]; ArgsParser parser = new ArgsParser(); - Parameter defaultCharacter = parser.addDefaultCharacterParameter("DefaultCharacter", "dc", "desc", 'z'); + // Using the new ChrParameter (with default value) + ChrParameter defaultCharacter = parser.addParameter( + new ChrParameter('z', "DefaultCharacter", "dc", "desc") + ); parser.parse(args); + // Since no argument was passed, 'z' is expected assertEquals('z', defaultCharacter.getArgument()); } @@ -342,9 +362,13 @@ public void testAddDefaultCharacterParameterWithoutArgument() { public void testAddDefaultCharacterParameterWithArgument() { String[] args = {"--DefaultCharacter", "x"}; ArgsParser parser = new ArgsParser(); - Parameter defaultCharacter = parser.addDefaultCharacterParameter("DefaultCharacter", "dc", "desc", 'z'); + // Using the new ChrParameter (with default value) + ChrParameter defaultCharacter = parser.addParameter( + new ChrParameter('z', "DefaultCharacter", "dc", "desc") + ); parser.parse(args); + // The default 'z' should be overridden by the parsed argument 'x' assertEquals('x', defaultCharacter.getArgument()); } @@ -352,7 +376,10 @@ public void testAddDefaultCharacterParameterWithArgument() { public void testAddCharacterArrayParameter() { String[] args = {"--CharacterArray", "a", "b", "c"}; ArgsParser parser = new ArgsParser(); - Parameter characterArray = parser.addCharacterArrayParameter("CharacterArray", "charA", "desc", true); + // Using the new ChrArrParameter (no default, isMandatory = true) + ChrArrParameter characterArray = parser.addParameter( + new ChrArrParameter("CharacterArray", "charA", "desc", true) + ); parser.parse(args); assertArrayEquals(new Character[]{'a', 'b', 'c'}, characterArray.getArgument()); @@ -362,9 +389,13 @@ public void testAddCharacterArrayParameter() { public void testAddDefaultCharacterArrayParameterWithoutArgument() { String[] args = new String[0]; ArgsParser parser = new ArgsParser(); - Parameter defaultCharacterArray = parser.addDefaultCharacterArrayParameter("CharacterArray", "charA", "desc", new Character[]{'x', 'y', 'z'}); + // Using the new ChrArrParameter (with a default array) + ChrArrParameter defaultCharacterArray = parser.addParameter( + new ChrArrParameter(new Character[]{'x', 'y', 'z'}, "CharacterArray", "charA", "desc") + ); parser.parse(args); + // Since no arguments were passed, the default array is expected assertArrayEquals(new Character[]{'x', 'y', 'z'}, defaultCharacterArray.getArgument()); } @@ -372,21 +403,23 @@ public void testAddDefaultCharacterArrayParameterWithoutArgument() { public void testAddDefaultCharacterArrayParameterWithArgument() { String[] args = {"--CharacterArray", "a", "b", "c"}; ArgsParser parser = new ArgsParser(); - Parameter defaultCharacterArray = parser.addDefaultCharacterArrayParameter("CharacterArray", "charA", "desc", new Character[]{'x', 'y', 'z'}); + // Using the new ChrArrParameter (with a default array) + ChrArrParameter defaultCharacterArray = parser.addParameter( + new ChrArrParameter(new Character[]{'x', 'y', 'z'}, "CharacterArray", "charA", "desc") + ); parser.parse(args); + // The default array gets overridden by "a", "b", "c" assertArrayEquals(new Character[]{'a', 'b', 'c'}, defaultCharacterArray.getArgument()); } - - // Path parameters @Test public void testAddMandatoryPathParameter() { String[] args = {"--Path", "/Users/user/Source/Code"}; ArgsParser parser = new ArgsParser(); - Parameter path = parser.addMandatoryPathParameter("Path", "pathA", "desc"); + PthParameter path = parser.addParameter(new PthParameter("Path", "pathA", "desc", true, false)); parser.parse(args); assertEquals("/Users/user/Source/Code", path.getArgument().toString()); } @@ -395,7 +428,7 @@ public void testAddMandatoryPathParameter() { public void testAddDefaultPathParameterWithoutArgument() { String[] args = new String[0]; ArgsParser parser = new ArgsParser(); - Parameter path = parser.addDefaultPathParameter("Path", "pathA", "desc", Path.of("home/")); + PthParameter path = parser.addParameter(new PthParameter(Path.of("home/"), "Path", "pathA", "desc", false)); parser.parse(args); assertEquals(Path.of("home/"), path.getArgument()); } @@ -404,7 +437,7 @@ public void testAddDefaultPathParameterWithoutArgument() { public void testAddOptionalPathParameter() { String[] args = {"--Path", "/Users/user/Source/Code"}; ArgsParser parser = new ArgsParser(); - Parameter path = parser.addOptionalPathParameter("Path", "pathA", "desc"); + PthParameter path = parser.addParameter(new PthParameter("Path", "pathA", "desc", true, false)); parser.parse(args); assertEquals("/Users/user/Source/Code", path.getArgument().toString()); } @@ -417,7 +450,7 @@ public void testAddOptionalPathParameter() { public void testCommand() { String[] args = {"command"}; ArgsParser parser = new ArgsParser(); - Command command = parser.addCommand("command", "c", ""); + Command command = parser.addCommand(new Command("command", "c", "")); parser.parse(args); assertTrue(command.isProvided()); @@ -427,7 +460,7 @@ public void testCommand() { public void testIndirectCommandCheck() { String[] args = {"command"}; ArgsParser parser = new ArgsParser(); - Command command = parser.addCommand("command", "c", ""); + Command command = parser.addCommand(new Command("command", "c", "")); parser.parse(args); assertTrue(parser.checkIfCommandIsProvided("command")); @@ -441,17 +474,58 @@ public void testIndirectCommandCheck() { public void testCombinationOfMandatoryArguments() { String[] args = new String[]{"-s", "stringInput", "-sArr", "string", "array", "-i", "12", "-iArr", "1", "2", "-d", "12.3", "-dArr", "1.2", "2.3", "-b", "true", "-bArr", "true", "false", "-c", "a", "-cArr", "d", "c"}; + ArgsParser parser = new ArgsParser(); - Parameter stringParam = parser.addMandatoryStringParameter("String", "s", "desc"); - Parameter stringArrayParam = parser.addStringArrayParameter("StringArray", "sArr", "", false); - Parameter intParam = parser.addMandatoryIntegerParameter("Int", "i", "desc"); - Parameter integerArrayParam = parser.addIntegerArrayParameter("IntArray", "iArr", "", false); - Parameter doubleParam = parser.addMandatoryDoubleParameter("Double", "d", "desc"); - Parameter doubleArrayParam = parser.addDoubleArrayParameter("DoubleArray", "dArr", "", false); - Parameter booleanParam = parser.addMandatoryBooleanParameter("Boolean", "b", "desc"); - Parameter booleanArrayParam = parser.addBooleanArrayParameter("BooleanArray", "bArr", "", false); - Parameter characterParameter = parser.addMandatoryCharacterParameter("Character", "c", "desc"); - Parameter characterArrayParam = parser.addCharacterArrayParameter("CharacterArray", "cArr", "", false); + // String (mandatory) + StrParameter stringParam = parser.addParameter( + new StrParameter("String", "s", "desc", true) + ); + + // String array (optional in this example) + StrArrParameter stringArrayParam = parser.addParameter( + new StrArrParameter("StringArray", "sArr", "", false) + ); + + // Integer (mandatory) + IntParameter intParam = parser.addParameter( + new IntParameter("Int", "i", "desc", true) + ); + + // Integer array (optional) + IntArrParameter integerArrayParam = parser.addParameter( + new IntArrParameter("IntArray", "iArr", "", false) + ); + + // Double (mandatory) + DblParameter doubleParam = parser.addParameter( + new DblParameter("Double", "d", "desc", true) + ); + + // Double array (optional) + DblArrParameter doubleArrayParam = parser.addParameter( + new DblArrParameter("DoubleArray", "dArr", "", false) + ); + + // Boolean (mandatory) + BolParameter booleanParam = parser.addParameter( + new BolParameter("Boolean", "b", "desc", true) + ); + + // Boolean array (optional) + BolArrParameter booleanArrayParam = parser.addParameter( + new BolArrParameter("BooleanArray", "bArr", "", false) + ); + + // Character (mandatory) + ChrParameter characterParameter = parser.addParameter( + new ChrParameter("Character", "c", "desc", true) + ); + + // Character array (optional) + ChrArrParameter characterArrayParam = parser.addParameter( + new ChrArrParameter("CharacterArray", "cArr", "", false) + ); + parser.parse(args); assertEquals("stringInput", stringParam.getArgument()); @@ -468,50 +542,160 @@ public void testCombinationOfMandatoryArguments() { @Test public void testCombinationOfMandatoryAndOptionalArguments() { - String[] args = new String[]{"-s", "stringInput", "-sArr", "string", "array", "-iArr", "1", "2", - "-d", "12.3", "-b", "true", "-bArr", "true", "false", "-cArr", "d", "c"}; + String[] args = new String[]{ + "-s", "stringInput", + "-sArr", "string", "array", + "-iArr", "1", "2", + "-d", "12.3", + "-b", "true", + "-bArr", "true", "false", + "-cArr", "d", "c" + }; + ArgsParser parser = new ArgsParser(); - Parameter stringParam = parser.addMandatoryStringParameter("String", "s", "desc"); - Parameter stringArrayParam = parser.addStringArrayParameter("StringArray", "sArr", "", false); - Parameter intParam = parser.addOptionalIntegerParameter("Int", "i", "desc"); - Parameter integerArrayParam = parser.addIntegerArrayParameter("IntArray", "iArr", "", false); - Parameter doubleParam = parser.addMandatoryDoubleParameter("Double", "d", "desc"); - Parameter doubleArrayParam = parser.addDoubleArrayParameter("DoubleArray", "dArr", "", false); - Parameter booleanParam = parser.addMandatoryBooleanParameter("Boolean", "b", "desc"); - Parameter booleanArrayParam = parser.addBooleanArrayParameter("BooleanArray", "bArr", "", false); - Parameter characterParameter = parser.addOptionalCharacterParameter("Character", "c", "desc"); - Parameter characterArrayParam = parser.addCharacterArrayParameter("CharacterArray", "cArr", "", false); + + // String (mandatory) + StrParameter stringParam = parser.addParameter( + new StrParameter("String", "s", "desc", true) + ); + + // String array (optional) + StrArrParameter stringArrayParam = parser.addParameter( + new StrArrParameter("StringArray", "sArr", "", false) + ); + + // Integer (optional) + IntParameter intParam = parser.addParameter( + new IntParameter("Int", "i", "desc", false) + ); + + // Integer array (optional) + IntArrParameter integerArrayParam = parser.addParameter( + new IntArrParameter("IntArray", "iArr", "", false) + ); + + // Double (mandatory) + DblParameter doubleParam = parser.addParameter( + new DblParameter("Double", "d", "desc", true) + ); + + // Double array (optional) + DblArrParameter doubleArrayParam = parser.addParameter( + new DblArrParameter("DoubleArray", "dArr", "", false) + ); + + // Boolean (mandatory) + BolParameter booleanParam = parser.addParameter( + new BolParameter("Boolean", "b", "desc", true) + ); + + // Boolean array (optional) + BolArrParameter booleanArrayParam = parser.addParameter( + new BolArrParameter("BooleanArray", "bArr", "", false) + ); + + // Character (optional) + ChrParameter characterParameter = parser.addParameter( + new ChrParameter("Character", "c", "desc", false) + ); + + // Character array (optional) + ChrArrParameter characterArrayParam = parser.addParameter( + new ChrArrParameter("CharacterArray", "cArr", "", false) + ); + parser.parse(args); assertEquals("stringInput", stringParam.getArgument()); assertArrayEquals(new String[]{"string", "array"}, stringArrayParam.getArgument()); + // 'Int' was not passed => should be null (optional) assertNull(intParam.getArgument()); + // We did pass -iArr => expect [1,2] assertArrayEquals(new Integer[]{1, 2}, integerArrayParam.getArgument()); + // Double is mandatory => 12.3 assertEquals(12.3, doubleParam.getArgument(), 0.001); - assertArrayEquals(null, doubleArrayParam.getArgument()); - assertEquals(true, booleanParam.getArgument()); + // Double array not passed => should be null + assertNull(doubleArrayParam.getArgument()); + // Boolean is mandatory => true + assertTrue(booleanParam.getArgument()); + // Boolean array => [true,false] assertArrayEquals(new Boolean[]{true, false}, booleanArrayParam.getArgument()); + // Character optional => not passed => null assertNull(characterParameter.getArgument()); + // Character array => ['d','c'] assertArrayEquals(new Character[]{'d', 'c'}, characterArrayParam.getArgument()); } @Test public void testGetArgumentTypes() { - String[] args = new String[]{"-s", "stringInput", "-sArr", "string", "array", "-i", "12", "-iArr", "1", "2", - "-d", "12.3", "-dArr", "1.2", "2.3", "-b", "true", "-bArr", "true", "false", "-c", "a", "-cArr", "d", "c"}; + String[] args = new String[]{ + "-s", "stringInput", + "-sArr", "string", "array", + "-i", "12", + "-iArr", "1", "2", + "-d", "12.3", + "-dArr", "1.2", "2.3", + "-b", "true", + "-bArr", "true", "false", + "-c", "a", + "-cArr", "d", "c" + }; + ArgsParser parser = new ArgsParser(); - Parameter stringParam = parser.addMandatoryStringParameter("String", "s", "desc"); - Parameter stringArrayParam = parser.addStringArrayParameter("StringArray", "sArr", "", false); - Parameter intParam = parser.addMandatoryIntegerParameter("Int", "i", "desc"); - Parameter integerArrayParam = parser.addIntegerArrayParameter("IntArray", "iArr", "", false); - Parameter doubleParam = parser.addMandatoryDoubleParameter("Double", "d", "desc"); - Parameter doubleArrayParam = parser.addDoubleArrayParameter("DoubleArray", "dArr", "", false); - Parameter booleanParam = parser.addMandatoryBooleanParameter("Boolean", "b", "desc"); - Parameter booleanArrayParam = parser.addBooleanArrayParameter("BooleanArray", "bArr", "", false); - Parameter characterParameter = parser.addMandatoryCharacterParameter("Character", "c", "desc"); - Parameter characterArrayParam = parser.addCharacterArrayParameter("CharacterArray", "cArr", "", false); + + // String (mandatory) + StrParameter stringParam = parser.addParameter( + new StrParameter("String", "s", "desc", true) + ); + + // String array (optional) + StrArrParameter stringArrayParam = parser.addParameter( + new StrArrParameter("StringArray", "sArr", "", false) + ); + + // Integer (mandatory) + IntParameter intParam = parser.addParameter( + new IntParameter("Int", "i", "desc", true) + ); + + // Integer array (optional) + IntArrParameter integerArrayParam = parser.addParameter( + new IntArrParameter("IntArray", "iArr", "", false) + ); + + // Double (mandatory) + DblParameter doubleParam = parser.addParameter( + new DblParameter("Double", "d", "desc", true) + ); + + // Double array (optional) + DblArrParameter doubleArrayParam = parser.addParameter( + new DblArrParameter("DoubleArray", "dArr", "", false) + ); + + // Boolean (mandatory) + BolParameter booleanParam = parser.addParameter( + new BolParameter("Boolean", "b", "desc", true) + ); + + // Boolean array (optional) + BolArrParameter booleanArrayParam = parser.addParameter( + new BolArrParameter("BooleanArray", "bArr", "", false) + ); + + // Character (mandatory) + ChrParameter characterParameter = parser.addParameter( + new ChrParameter("Character", "c", "desc", true) + ); + + // Character array (optional) + ChrArrParameter characterArrayParam = parser.addParameter( + new ChrArrParameter("CharacterArray", "cArr", "", false) + ); + parser.parse(args); + // Each .getArgument() should have the correct runtime type: assertEquals(String.class, stringParam.getArgument().getClass()); assertEquals(String[].class, stringArrayParam.getArgument().getClass()); assertEquals(Integer.class, intParam.getArgument().getClass()); @@ -523,7 +707,7 @@ public void testGetArgumentTypes() { assertEquals(Character.class, characterParameter.getArgument().getClass()); assertEquals(Character[].class, characterArrayParam.getArgument().getClass()); } - + @Test public void testGetArgumentOf() { String[] args = new String[]{ @@ -540,30 +724,66 @@ public void testGetArgumentOf() { }; ArgsParser parser = new ArgsParser(); - parser.addMandatoryStringParameter("String", "s", "desc"); - parser.addStringArrayParameter("StringArray", "sArr", "", false); - parser.addMandatoryIntegerParameter("Int", "i", "desc"); - parser.addIntegerArrayParameter("IntArray", "iArr", "", false); - parser.addMandatoryDoubleParameter("Double", "d", "desc"); - parser.addDoubleArrayParameter("DoubleArray", "dArr", "", false); - parser.addMandatoryBooleanParameter("Boolean", "b", "desc"); - parser.addBooleanArrayParameter("BooleanArray", "bArr", "", false); - parser.addMandatoryCharacterParameter("Character", "c", "desc"); - parser.addCharacterArrayParameter("CharacterArray", "cArr", "", false); - - parser.parse(args); - - // Verifying results of getArgumentOf method + // Using new parameter classes instead of addMandatoryXYZParameter, etc. + parser.addParameter( + new StrParameter("String", "s", "desc", true) + ); + parser.addParameter( + new StrArrParameter("StringArray", "sArr", "", false) + ); + parser.addParameter( + new IntParameter("Int", "i", "desc", true) + ); + parser.addParameter( + new IntArrParameter("IntArray", "iArr", "", false) + ); + parser.addParameter( + new DblParameter("Double", "d", "desc", true) + ); + parser.addParameter( + new DblArrParameter("DoubleArray", "dArr", "", false) + ); + parser.addParameter( + new BolParameter("Boolean", "b", "desc", true) + ); + parser.addParameter( + new BolArrParameter("BooleanArray", "bArr", "", false) + ); + parser.addParameter( + new ChrParameter("Character", "c", "desc", true) + ); + parser.addParameter( + new ChrArrParameter("CharacterArray", "cArr", "", false) + ); + + parser.parse(args); + + // Now verify the results of parser.getArgumentOf(...) assertEquals("stringInput", parser.getArgumentOf("--String")); - assertArrayEquals(new String[]{"arr1", "arr2"}, (String[]) parser.getArgumentOf("--StringArray")); + assertArrayEquals( + new String[]{"arr1", "arr2"}, + (String[]) parser.getArgumentOf("--StringArray") + ); assertEquals(42, (Integer) parser.getArgumentOf("--Int")); - assertArrayEquals(new Integer[]{1, 2}, (Integer[]) parser.getArgumentOf("--IntArray")); + assertArrayEquals( + new Integer[]{1, 2}, + (Integer[]) parser.getArgumentOf("--IntArray") + ); assertEquals(3.14, parser.getArgumentOf("--Double")); - assertArrayEquals(new Double[]{1.1, 2.2}, (Double[]) parser.getArgumentOf("--DoubleArray")); + assertArrayEquals( + new Double[]{1.1, 2.2}, + (Double[]) parser.getArgumentOf("--DoubleArray") + ); assertEquals(true, parser.getArgumentOf("--Boolean")); - assertArrayEquals(new Boolean[]{true, false}, (Boolean[]) parser.getArgumentOf("--BooleanArray")); + assertArrayEquals( + new Boolean[]{true, false}, + (Boolean[]) parser.getArgumentOf("--BooleanArray") + ); assertEquals('x', (Character) parser.getArgumentOf("--Character")); - assertArrayEquals(new Character[]{'a', 'z'}, (Character[]) parser.getArgumentOf("--CharacterArray")); + assertArrayEquals( + new Character[]{'a', 'z'}, + (Character[]) parser.getArgumentOf("--CharacterArray") + ); } @Test @@ -577,20 +797,44 @@ public void testCombinationsOfCommandsAndFlags() { "-iArr", "1", "2", "command2" }; + ArgsParser parser = new ArgsParser(); - Parameter stringPar = parser.addMandatoryStringParameter("String", "s", "desc"); - Parameter stringArrPar = parser.addStringArrayParameter("StringArray", "sArr", "", false); - Parameter intPar = parser.addMandatoryIntegerParameter("Int", "i", "desc"); - Parameter intArrPar = parser.addIntegerArrayParameter("IntArray", "iArr", "", false); - Command command1 = parser.addCommand("command1", "c1", null); - Command command2 = parser.addCommand("command2", "c2", null); - Command command3 = parser.addCommand("command3", "c3", null); + + // String (mandatory) + StrParameter stringPar = parser.addParameter( + new StrParameter("String", "s", "desc", true) + ); + + // String array (optional) + StrArrParameter stringArrPar = parser.addParameter( + new StrArrParameter("StringArray", "sArr", "", false) + ); + + // Integer (mandatory) + IntParameter intPar = parser.addParameter( + new IntParameter("Int", "i", "desc", true) + ); + + // Integer array (optional) + IntArrParameter intArrPar = parser.addParameter( + new IntArrParameter("IntArray", "iArr", "", false) + ); + + // Commands + Command command1 = parser.addCommand(new Command("command1", "c1", null)); + Command command2 = parser.addCommand(new Command("command2", "c2", null)); + Command command3 = parser.addCommand(new Command("command3", "c3", null)); + + // Parse parser.parse(args); - assertEquals("stringInput", parser.getArgumentOf("--String")); + // Verify parsed parameter values + assertEquals("stringInput", stringPar.getArgument()); assertArrayEquals(new String[]{"arr1", "arr2"}, stringArrPar.getArgument()); assertEquals(42, intPar.getArgument()); - assertArrayEquals(new Integer[]{1, 2}, (Integer[]) intArrPar.getArgument()); + assertArrayEquals(new Integer[]{1, 2}, intArrPar.getArgument()); + + // Verify provided commands assertTrue(command1.isProvided()); assertTrue(command2.isProvided()); assertTrue(command3.isProvided()); @@ -600,8 +844,8 @@ public void testCombinationsOfCommandsAndFlags() { public void testToggle() { String[] args = {"comm2"}; ArgsParser parser = new ArgsParser(); - Command comd = parser.addCommand("command", "comm", "command1"); - Command comd2 = parser.addCommand("command2", "comm2", "command2"); + Command comd = parser.addCommand(new Command("command", "comm", "command1")); + Command comd2 = parser.addCommand(new Command("command2", "comm2", "command2")); parser.toggle(comd, comd2); parser.parse(args); diff --git a/src/test/TestArgsExceptions.java b/src/test/TestArgsExceptions.java index 479d310..e48e28e 100644 --- a/src/test/TestArgsExceptions.java +++ b/src/test/TestArgsExceptions.java @@ -1,7 +1,11 @@ import ArgsParser.*; import ArgsParser.ArgsExceptions.*; +import ArgsParser.ParameterTypes.*; import org.junit.jupiter.api.Test; +import java.nio.file.Path; +import java.nio.file.Paths; + import static org.junit.jupiter.api.Assertions.*; public class TestArgsExceptions { @@ -13,7 +17,7 @@ public void testHelpForSingleFlag() { String[] args = {"-pf4", "--help"}; ArgsParser parser = new ArgsParser(); - Parameter doub = parser.addDefaultDoubleParameter("parameterFlag4", "pf4", "description", 5.6); + DblParameter doub = parser.addParameter(new DblParameter(5.6, "parameterFlag4", "pf4", "description")); Exception exception = assertThrows(CalledForHelpNotification.class, () -> parser.parseUnchecked(args)); String expected = """ @@ -36,25 +40,175 @@ public void testHelpWithEachParameter() { String[] args = {"--help"}; ArgsParser parser = new ArgsParser(); - Parameter mandatoryString = parser.addMandatoryStringParameter("mandatory_string", "ms", "mandatory string description"); - Parameter optionalString = parser.addOptionalStringParameter("optional_string", "os", "optional string description"); - Parameter defaultString = parser.addDefaultStringParameter("default_string", "ds", "default string description", "default"); + // ------------------------------------------------------------------- + // STRING + // ------------------------------------------------------------------- + + // Mandatory string + StrParameter mandatoryString = parser.addParameter( + new StrParameter("mandatory_string", "ms", "mandatory string description", true) + ); + // Optional string + StrParameter optionalString = parser.addParameter( + new StrParameter("optional_string", "os", "optional string description", false) + ); + // Default string + StrParameter defaultString = parser.addParameter( + new StrParameter("default", "default_string", "ds", "default string description") + ); + + + // ------------------------------------------------------------------- + // DOUBLE + // ------------------------------------------------------------------- + + // Mandatory double + DblParameter mandatoryDouble = parser.addParameter( + new DblParameter("mandatory_double", "md", "mandatory double description", true) + ); + // Optional double + DblParameter optionalDouble = parser.addParameter( + new DblParameter("optional_double", "d", "this one is optional", false) + ); + // Default double + DblParameter defaultDouble = parser.addParameter( + new DblParameter(7.89, "default_double", "dd", "default double description") + ); + + + // ------------------------------------------------------------------- + // INTEGER + // ------------------------------------------------------------------- + + // Mandatory integer + IntParameter mandatoryInteger = parser.addParameter( + new IntParameter("mandatory_integer", "mi", "mandatory integer description", true) + ); + // Optional integer + IntParameter optionalInteger = parser.addParameter( + new IntParameter("optional_integer", "oi", "optional integer description", false) + ); + // Default integer + IntParameter defaultInteger = parser.addParameter( + new IntParameter(5, "default_integer", "i", "No description available!") + ); + + + // ------------------------------------------------------------------- + // CHARACTER + // ------------------------------------------------------------------- + + // Mandatory character + ChrParameter mandatoryChar = parser.addParameter( + new ChrParameter("mandatory_character", "mc", "mandatory character description", true) + ); + // Optional character + ChrParameter optionalChar = parser.addParameter( + new ChrParameter("optional_character", "oc", "optional character description", false) + ); + // Default character + ChrParameter defaultChar = parser.addParameter( + new ChrParameter('a', "default_character", "dc", "default character description") + ); + + + // ------------------------------------------------------------------- + // BOOLEAN + // ------------------------------------------------------------------- + + // Mandatory boolean + BolParameter mandatoryBoolean = parser.addParameter( + new BolParameter("mandatory_boolean", "mb", "mandatory boolean description", true) + ); + // Optional boolean + BolParameter optionalBoolean = parser.addParameter( + new BolParameter("optional_boolean", "ob", "optional boolean description", false) + ); + // Default boolean + BolParameter defaultBoolean = parser.addParameter( + new BolParameter(true, "default_boolean", "db", "default boolean description") + ); + - Parameter mandatoryDouble = parser.addMandatoryDoubleParameter("mandatory_double", "md", "mandatory double description"); - Parameter optionalDouble = parser.addOptionalDoubleParameter("optional_double", "d", "this one is optional"); - Parameter defaultDouble = parser.addDefaultDoubleParameter("default_double", "dd", "default double description", 7.89); + // ------------------------------------------------------------------- + // FLOAT (NEW) + // ------------------------------------------------------------------- - Parameter mandatoryInteger = parser.addMandatoryIntegerParameter("mandatory_integer", "mi", "mandatory integer description"); - Parameter optionalInteger = parser.addOptionalIntegerParameter("optional_integer", "oi", "optional integer description"); - Parameter defaultInteger = parser.addDefaultIntegerParameter("default_integer", "i", null, 5); + // Mandatory float + FltParameter mandatoryFloat = parser.addParameter( + new FltParameter("mandatory_float", "mf", "mandatory float description", true) + ); + // Optional float + FltParameter optionalFloat = parser.addParameter( + new FltParameter("optional_float", "of", "optional float description", false) + ); + // Default float + FltParameter defaultFloat = parser.addParameter( + new FltParameter(3.14f, "default_float", "df", "default float description") + ); - Parameter mandatoryChar = parser.addMandatoryCharacterParameter("mandatory_character", "mc", "mandatory character description"); - Parameter optionalChar = parser.addOptionalCharacterParameter("optional_character", "oc", "optional character description"); - Parameter defaultChar = parser.addDefaultCharacterParameter("default_character", "dc", "default character description", 'a'); - Parameter mandatoryBoolean = parser.addMandatoryBooleanParameter("mandatory_boolean", "mb", "mandatory boolean description"); - Parameter optionalBoolean = parser.addOptionalBooleanParameter("optional_boolean", "ob", "optional boolean description"); - Parameter defaultBoolean = parser.addDefaultBooleanParameter("default_boolean", "db", "default boolean description", true); + // ------------------------------------------------------------------- + // PATH (NEW) + // ------------------------------------------------------------------- + + // Mandatory path + PthParameter mandatoryPath = parser.addParameter( + new PthParameter("mandatory_path", "mp", "mandatory path description", true, false) + ); + // Optional path + PthParameter optionalPath = parser.addParameter( + new PthParameter("optional_path", "op", "optional path description", false, false) + ); + // Default path + PthParameter defaultPath = parser.addParameter( + new PthParameter(Path.of("/some/default/path"), "default_path", "dp", "default path description", false) + ); + + + // ------------------------------------------------------------------- + // STRING ARRAY (example from original code, optional) + // ------------------------------------------------------------------- + + StrArrParameter strArrParam = parser.addParameter( + new StrArrParameter("stringArray", "sArr", "description for string array", false) + ); + + + // ------------------------------------------------------------------- + // FLOAT ARRAY (NEW) + // ------------------------------------------------------------------- + + FltArrParameter mandatoryFloatArray = parser.addParameter( + new FltArrParameter("mandatory_float_array", "mfa", "mandatory float array description", true) + ); + FltArrParameter optionalFloatArray = parser.addParameter( + new FltArrParameter("optional_float_array", "ofa", "optional float array description", false) + ); + FltArrParameter defaultFloatArray = parser.addParameter( + new FltArrParameter(new Float[]{1.1f, 2.2f}, "default_float_array", "dfa", "default float array description") + ); + + + // ------------------------------------------------------------------- + // PATH ARRAY (NEW) + // ------------------------------------------------------------------- + + PthArrParameter mandatoryPathArray = parser.addParameter( + new PthArrParameter("mandatory_path_array", "mpa", "mandatory path array description", true, false) + ); + PthArrParameter optionalPathArray = parser.addParameter( + new PthArrParameter("optional_path_array", "opa", "optional path array description", false, false) + ); + PthArrParameter defaultPathArray = parser.addParameter( + new PthArrParameter( + new Path[]{Path.of("/path/one"), Path.of("/path/two")}, + "default_path_array", + "dpa", + "default path array description", + false + ) + ); Exception exception = assertThrows(CalledForHelpNotification.class, () -> parser.parseUnchecked(args)); String expected = """ @@ -66,40 +220,70 @@ public void testHelpWithEachParameter() { # # Available Parameters: # - ### --mandatory_string -ms [s] (!) mandatory string description + ### --mandatory_string -ms [s] (!) mandatory string description + # + ### --optional_string -os [s] (?) optional string description + # + ### --default_string -ds [s] (?) default string description + # default: default + # + ### --mandatory_double -md [d] (!) mandatory double description + # + ### --optional_double -d [d] (?) this one is optional + # + ### --default_double -dd [d] (?) default double description + # default: 7.89 # - ### --optional_string -os [s] (?) optional string description + ### --mandatory_integer -mi [i] (!) mandatory integer description # - ### --default_string -ds [s] (?) default string description - # default: default + ### --optional_integer -oi [i] (?) optional integer description # - ### --mandatory_double -md [d] (!) mandatory double description + ### --default_integer -i [i] (?) No description available! + # default: 5 # - ### --optional_double -d [d] (?) this one is optional + ### --mandatory_character -mc [c] (!) mandatory character description # - ### --default_double -dd [d] (?) default double description - # default: 7.89 + ### --optional_character -oc [c] (?) optional character description # - ### --mandatory_integer -mi [i] (!) mandatory integer description + ### --default_character -dc [c] (?) default character description + # default: a # - ### --optional_integer -oi [i] (?) optional integer description + ### --mandatory_boolean -mb [b] (!) mandatory boolean description # - ### --default_integer -i [i] (?) No description available! - # default: 5 + ### --optional_boolean -ob [b] (?) optional boolean description # - ### --mandatory_character -mc [c] (!) mandatory character description + ### --default_boolean -db [b] (?) default boolean description + # default: true # - ### --optional_character -oc [c] (?) optional character description + ### --mandatory_float -mf [f] (!) mandatory float description # - ### --default_character -dc [c] (?) default character description - # default: a + ### --optional_float -of [f] (?) optional float description # - ### --mandatory_boolean -mb [b] (!) mandatory boolean description + ### --default_float -df [f] (?) default float description + # default: 3.14 # - ### --optional_boolean -ob [b] (?) optional boolean description + ### --mandatory_path -mp [p] (!) mandatory path description # - ### --default_boolean -db [b] (?) default boolean description - # default: true + ### --optional_path -op [p] (?) optional path description + # + ### --default_path -dp [p] (?) default path description + # default: /some/default/path + # + ### --stringArray -sArr [s+] (?) description for string array + # + ### --mandatory_float_array -mfa [f+] (!) mandatory float array description + # + ### --optional_float_array -ofa [f+] (?) optional float array description + # + ### --default_float_array -dfa [f+] (?) default float array description + # default: [1.1, 2.2] + # + ### --mandatory_path_array -mpa [p+] (!) mandatory path array description + # + ### --optional_path_array -opa [p+] (?) optional path array description + # + ### --default_path_array -dpa [p+] (?) default path array description + # default: [/path/one, /path/two] # ####################################################################################################"""; assertEquals(expected, exception.getMessage()); @@ -111,17 +295,51 @@ public void testHelpWithArrayParameters() { String[] args = {"--help"}; ArgsParser parser = new ArgsParser(); - Parameter stringArray = parser.addStringArrayParameter("stringArrayParam", "hap", "descr", true); - Parameter defaultStringArray = parser.addDefaultStringArrayParameter("stringArray", "sAr", "descr", new String[]{"string1", "string2", "string3"}); - Parameter doubleArray = parser.addDoubleArrayParameter("doubleArrayParam", "dap", "description", false); - Parameter defaultDoubleArray = parser.addDefaultDoubleArrayParameter("doubleArray", "da", "description", new Double[]{1.1, 2.2, 3.3}); - Parameter integerArray = parser.addIntegerArrayParameter("integerArrayParam", "iap", "description", true); - Parameter defaultIntegerArray = parser.addDefaultIntegerArrayParameter("integerArray", "ia", "description", new Integer[]{1, 2, 3}); - Parameter booleanArray = parser.addBooleanArrayParameter("booleanArrayParam", "bap", "description", false); - Parameter defaultBooleanArray = parser.addDefaultBooleanArrayParameter("booleanArray", "ba", "description", new Boolean[]{true, false, true}); - Parameter characterArray = parser.addCharacterArrayParameter("characterArrayParam", "cap", "description", true); - Parameter defaultCharacterArray = parser.addDefaultCharacterArrayParameter("characterArray", "ca", "description", new Character[]{'a', 'b', 'c'}); - + // String Array (mandatory) + StrArrParameter stringArray = parser.addParameter( + new StrArrParameter("stringArrayParam", "hap", "descr", true) + ); + // String Array with default + StrArrParameter defaultStringArray = parser.addParameter( + new StrArrParameter(new String[]{"string1", "string2", "string3"}, + "stringArray", "sAr", "descr") + ); + // Double Array (optional) + DblArrParameter doubleArray = parser.addParameter( + new DblArrParameter("doubleArrayParam", "dap", "description", false) + ); + // Double Array with default + DblArrParameter defaultDoubleArray = parser.addParameter( + new DblArrParameter(new Double[]{1.1, 2.2, 3.3}, + "doubleArray", "da", "description") + ); + // Integer Array (mandatory) + IntArrParameter integerArray = parser.addParameter( + new IntArrParameter("integerArrayParam", "iap", "description", true) + ); + // Integer Array with default + IntArrParameter defaultIntegerArray = parser.addParameter( + new IntArrParameter(new Integer[]{1, 2, 3}, + "integerArray", "ia", "description") + ); + // Boolean Array (optional) + BolArrParameter booleanArray = parser.addParameter( + new BolArrParameter("booleanArrayParam", "bap", "description", false) + ); + // Boolean Array with default + BolArrParameter defaultBooleanArray = parser.addParameter( + new BolArrParameter(new Boolean[]{true, false, true}, + "booleanArray", "ba", "description") + ); + // Character Array (mandatory) + ChrArrParameter characterArray = parser.addParameter( + new ChrArrParameter("characterArrayParam", "cap", "description", true) + ); + // Character Array with default + ChrArrParameter defaultCharacterArray = parser.addParameter( + new ChrArrParameter(new Character[]{'a', 'b', 'c'}, + "characterArray", "ca", "description") + ); Exception exception = assertThrows(CalledForHelpNotification.class, () -> parser.parseUnchecked(args)); String expected = """ @@ -167,7 +385,7 @@ public void testHelpWithCommand() { String[] args = {"--help"}; ArgsParser parser = new ArgsParser(); - Command command = parser.addCommand("command", "c", "this is a command"); + Command command = parser.addCommand(new Command("command", "c", "this is a command")); Exception exception = assertThrows(CalledForHelpNotification.class, () -> parser.parseUnchecked(args)); String expected = """ @@ -187,10 +405,10 @@ public void testHelpWithCommand() { public void testHelpWithCommandsAndParameters() { String[] args = {"--help"}; ArgsParser parser = new ArgsParser(); - Command command = parser.addCommand("command", "c", "this is a command"); - Parameter newParam1 = parser.addMandatoryStringParameter("newParam1", "np1", "this is the first new parameter"); - Parameter newParam2 = parser.addOptionalIntegerParameter("newParam2", "np2", "this is the second new parameter"); - Command newCommand = parser.addCommand("newCommand", "nc", "this is another command"); + Command command = parser.addCommand(new Command("command", "c", "this is a command")); + StrParameter newParam1 = parser.addParameter(new StrParameter("newParam1", "np1", "this is the first new parameter", true)); + IntParameter newParam2 = parser.addParameter(new IntParameter("newParam2", "np2", "this is the second new parameter", false)); + Command newCommand = parser.addCommand(new Command("newCommand", "nc", "this is another command")); Exception exception = assertThrows(CalledForHelpNotification.class, () -> parser.parseUnchecked(args)); String expected = """ @@ -220,8 +438,8 @@ public void testHelpWithCommandsAndParameters() { public void testOneCommandAndOneParameter() { String[] args = {"--help"}; ArgsParser parser = new ArgsParser(); - Command command = parser.addCommand("command", "c", "this is a command"); - Parameter newParam1 = parser.addMandatoryStringParameter("newParam1", "np1", "this is the first new parameter"); + Command command = parser.addCommand(new Command("command", "c", "this is a command")); + StrParameter newParam1 = parser.addParameter(new StrParameter("newParam1", "np1", "this is the first new parameter", true)); Exception exception = assertThrows(CalledForHelpNotification.class, () -> parser.parseUnchecked(args)); String expected = """ @@ -248,13 +466,13 @@ public void testHelpWithNewLineInDescription() { String[] args = {"--help"}; ArgsParser parser = new ArgsParser(); - Parameter longString = parser.addDefaultStringParameter("longString", "ls", - "This description is so long, it will " + - "force the automatic help printout to " + - "introduce a new line and still have a nice look :)", - "this/path/is/so/long/it/is/actually/longer/than/any" + - "/existing/path/that/I/have/on/my/PC/Do/You/Know/The/Word" + - "Oberwesedampfschifffahrtsgesellschaftskapitän"); + StrParameter longString = parser.addParameter(new StrParameter("this/path/is/so/long/it/is/actually/longer/than/any" + + "/existing/path/that/I/have/on/my/PC/Do/You/Know/The/Word" + + "Oberwesedampfschifffahrtsgesellschaftskapitän", + "longString", "ls", + "This description is so long, it will " + + "force the automatic help printout to " + + "introduce a new line and still have a nice look :)")); Exception exception = assertThrows(CalledForHelpNotification.class, () -> parser.parseUnchecked(args)); String expected = """ @@ -279,12 +497,30 @@ public void testNoDescriptionAvailable() { String[] args = {"--help"}; ArgsParser parser = new ArgsParser(); - Parameter strParam = parser.addMandatoryStringParameter("string", "s", ""); - Parameter intParam = parser.addOptionalIntegerParameter("integer", "i", null); - Parameter charParam = parser.addDefaultCharacterParameter("char", "c", null, 'c'); - Parameter booleanParam = parser.addOptionalBooleanParameter("boolean", "b", ""); - Parameter doubleParam = parser.addMandatoryDoubleParameter("double", "d", null); - Parameter strArrParam = parser.addStringArrayParameter("stringArray", "sArr", null, false); + // String (mandatory) + StrParameter strParam = parser.addParameter( + new StrParameter("string", "s", "", true) + ); + // Integer (optional) + IntParameter intParam = parser.addParameter( + new IntParameter("integer", "i", null, false) + ); + // Character (with default value) + ChrParameter charParam = parser.addParameter( + new ChrParameter('c', "char", "c", null) + ); + // Boolean (optional) + BolParameter booleanParam = parser.addParameter( + new BolParameter("boolean", "b", "", false) + ); + // Double (mandatory) + DblParameter doubleParam = parser.addParameter( + new DblParameter("double", "d", null, true) + ); + // String array (optional) + StrArrParameter strArrParam = parser.addParameter( + new StrArrParameter("stringArray", "sArr", null, false) + ); Exception exception = assertThrows(CalledForHelpNotification.class, () -> parser.parseUnchecked(args)); String expected = """ @@ -320,7 +556,7 @@ public void testHelpAtWrongPosition() { String[] args = {"--file", "file.txt", "--help"}; ArgsParser parser = new ArgsParser(); - Parameter file = parser.addMandatoryStringParameter("file", "f", "descr"); + StrParameter file = parser.addParameter(new StrParameter("file", "f", "descr", true)); Exception exception = assertThrows(HelpAtWrongPositionArgsException.class, () -> parser.parseUnchecked(args)); } @@ -330,7 +566,7 @@ public void testHelpBeforeFlag() { String[] args = {"--help", "--file"}; ArgsParser parser = new ArgsParser(); - Parameter file = parser.addMandatoryStringParameter("file", "f", "descr"); + StrParameter file = parser.addParameter(new StrParameter("file", "f", "descr", true)); Exception exception = assertThrows(HelpAtWrongPositionArgsException.class, () -> parser.parseUnchecked(args)); } @@ -342,8 +578,8 @@ public void testSameFlagProvidedTwice() { String[] args = {"--file", "file.txt", "-f", "file2.txt"}; ArgsParser parser = new ArgsParser(); - Parameter file = parser.addMandatoryStringParameter("file", "f", "descr"); - Parameter file2 = parser.addMandatoryStringParameter("file2", "f2", "descr"); + StrParameter file = parser.addParameter(new StrParameter("file", "f", "descr", true)); + StrParameter file2 = parser.addParameter(new StrParameter("file2", "f2", "descr", true)); Exception exception = assertThrows(FlagAlreadyProvidedArgsException.class, () -> parser.parseUnchecked(args)); assertEquals(""" @@ -361,11 +597,11 @@ public void testGetArgumentAsDoubleWithWrongInput() { String[] args = {"--file", "file.txt", "--double", "5.5.5"}; ArgsParser parser = new ArgsParser(); - Parameter file = parser.addMandatoryStringParameter("file", "f", "descr"); - Parameter doub = parser.addMandatoryDoubleParameter("double", "d", "descr"); + StrParameter file = parser.addParameter(new StrParameter("file", "f", "descr", true)); + DblParameter doub = parser.addParameter(new DblParameter("double", "d", "descr", true)); Exception exception = assertThrows(InvalidArgTypeArgsException.class, () -> parser.parseUnchecked(args)); - assertEquals(new InvalidArgTypeArgsException("--double", "Double", "Unsupported type!").getMessage(), exception.getMessage()); + assertEquals(new InvalidArgTypeArgsException("--double", "Double", "Provided argument does not match the parameter type!").getMessage(), exception.getMessage()); } // MandatoryArgNotProvidedArgsException @@ -375,12 +611,14 @@ public void testMandatoryArgMissing() { String[] args = {"--file", "file.txt", "--optional", "optional.txt"}; ArgsParser parser = new ArgsParser(); - Parameter file = parser.addMandatoryStringParameter("file", "f", "descr"); - Parameter save = parser.addMandatoryStringParameter("save", "s", "descr"); - Parameter optional = parser.addMandatoryStringParameter("optional", "o", "descr"); + // Using the new StrParameter for mandatory parameters + StrParameter file = parser.addParameter(new StrParameter("file", "f", "descr", true)); + StrParameter save = parser.addParameter(new StrParameter("save", "s", "descr", true)); + StrParameter optional = parser.addParameter(new StrParameter("optional", "o", "descr", true)); Exception exception = assertThrows(MandatoryArgNotProvidedArgsException.class, () -> parser.parseUnchecked(args)); - assertEquals(new MandatoryArgNotProvidedArgsException("Mandatory parameters are missing:\n--save").getMessage(), exception.getMessage()); + assertEquals(new MandatoryArgNotProvidedArgsException("Mandatory parameters are missing:\n--save").getMessage(), + exception.getMessage()); } @Test @@ -388,12 +626,16 @@ public void testMultipleMandatoryArgumentsMissing() { String[] args = {"--load", "file.txt"}; ArgsParser parser = new ArgsParser(); - Parameter load = parser.addMandatoryStringParameter("load", "l", "descr"); - Parameter file = parser.addMandatoryStringParameter("file", "f", "descr"); - Parameter save = parser.addMandatoryStringParameter("save", "s", "descr"); + // Again, switching to StrParameter with isMandatory = true + StrParameter load = parser.addParameter(new StrParameter("load", "l", "descr", true)); + StrParameter file = parser.addParameter(new StrParameter("file", "f", "descr", true)); + StrParameter save = parser.addParameter(new StrParameter("save", "s", "descr", true)); Exception exception = assertThrows(MandatoryArgNotProvidedArgsException.class, () -> parser.parseUnchecked(args)); - assertEquals(new MandatoryArgNotProvidedArgsException("Mandatory parameters are missing:\n--save\n--file").getMessage(), exception.getMessage()); + assertEquals( + new MandatoryArgNotProvidedArgsException("Mandatory parameters are missing:\n--save\n--file").getMessage(), + exception.getMessage() + ); } // MissingArgArgsException @@ -403,8 +645,8 @@ public void testMissingArgument() { String[] args = {"--file", "--save", "save.txt"}; ArgsParser parser = new ArgsParser(); - Parameter file = parser.addMandatoryStringParameter("file", "m", "descr"); - Parameter save = parser.addMandatoryStringParameter("save", "s", "descr"); + StrParameter file = parser.addParameter(new StrParameter("file", "m", "descr", true)); + StrParameter save = parser.addParameter(new StrParameter("save", "s", "descr", true)); Exception exception = assertThrows(MissingArgArgsException.class, () -> parser.parseUnchecked(args)); assertEquals(new MissingArgArgsException("--file").getMessage(), exception.getMessage()); @@ -415,8 +657,8 @@ public void testMissingLastArgument() { String[] args = {"--file", "file.txt", "--save"}; ArgsParser parser = new ArgsParser(); - Parameter file = parser.addMandatoryStringParameter("--file", "f", "descr"); - Parameter save = parser.addMandatoryStringParameter("--save", "s", "descr"); + StrParameter file = parser.addParameter(new StrParameter("file", "f", "descr", true)); + StrParameter save = parser.addParameter(new StrParameter("save", "s", "descr", true)); Exception exception = assertThrows(MissingArgArgsException.class, () -> parser.parseUnchecked(args)); assertEquals(new MissingArgArgsException("--save").getMessage(), exception.getMessage()); @@ -429,7 +671,7 @@ public void testNoArgumentsProvidedWithMandatoryParams() { String[] args = {}; ArgsParser parser = new ArgsParser(); - Parameter mandatoryParam = parser.addMandatoryStringParameter("optional", "o", null); + StrParameter mandatoryParam = parser.addParameter(new StrParameter("optional", "o", null, true)); Exception exception = assertThrows(NoArgumentsProvidedArgsException.class, () -> parser.parseUnchecked(args)); assertEquals(""" @@ -445,7 +687,7 @@ public void testNoArgumentsProvidedWithOnlyOptionalParams() { // just checks if String[] args = {}; ArgsParser parser = new ArgsParser(); - Parameter stringParam = parser.addOptionalStringParameter("optional", "o", null); + StrParameter stringParam = parser.addParameter(new StrParameter("optional", "o", null, false)); assertDoesNotThrow(() -> parser.parseUnchecked(args)); } @@ -457,8 +699,8 @@ public void testTooManyArguments() { String[] args = {"--file", "file.txt", "--save", "save.txt", "extra"}; ArgsParser parser = new ArgsParser(); - Parameter file = parser.addMandatoryStringParameter("file", "f", "descr"); - Parameter save = parser.addMandatoryStringParameter("save", "s", "descr"); + StrParameter file = parser.addParameter(new StrParameter("file", "f", "descr", true)); + StrParameter save = parser.addParameter(new StrParameter("save", "s", "descr", true)); Exception exception = assertThrows(TooManyArgumentsArgsException.class, () -> parser.parseUnchecked(args)); assertEquals(new TooManyArgumentsArgsException("--save").getMessage(), exception.getMessage()); @@ -471,8 +713,8 @@ public void testUnknownFlag() { String[] args = {"-w", "file.txt", "-s", "save.txt"}; ArgsParser parser = new ArgsParser(); - Parameter file = parser.addMandatoryStringParameter("file", "f", "descr"); - Parameter save = parser.addMandatoryStringParameter("save", "s", "descr"); + StrParameter file = parser.addParameter(new StrParameter("file", "f", "descr", true)); + StrParameter save = parser.addParameter(new StrParameter("save", "s", "descr", true)); Exception exception = assertThrows(UnknownFlagArgsException.class, () -> parser.parseUnchecked(args)); assertEquals(""" @@ -488,8 +730,8 @@ public void testUnknownFlagWithMultipleFlagsAndWrongInput() { String[] args = {"-f", "file.txt", "--save", "save.txt", "-s"}; ArgsParser parser = new ArgsParser(); - Parameter file = parser.addMandatoryStringParameter("file", "f", "descr"); - Parameter save = parser.addMandatoryStringParameter("save", "w", "descr"); + StrParameter file = parser.addParameter(new StrParameter("file", "f", "descr", true)); + StrParameter save = parser.addParameter(new StrParameter("save", "w", "descr", true)); Exception exception = assertThrows(UnknownFlagArgsException.class, () -> parser.parseUnchecked(args)); assertEquals(""" @@ -506,8 +748,8 @@ public void testMissingShorts() { String[] args = {"-f", "/to/file", "--save", "save.txt"}; ArgsParser parser = new ArgsParser(); - Parameter file = parser.addMandatoryStringParameter("--file", "m", "descr"); - Parameter save = parser.addMandatoryStringParameter("--save", "s", null); + StrParameter file = parser.addParameter(new StrParameter("--file", "m", "descr", true)); + StrParameter save = parser.addParameter(new StrParameter("--save", "s", null, true)); Exception exception = assertThrows(UnknownFlagArgsException.class, () -> parser.parseUnchecked(args)); assertEquals(""" @@ -524,8 +766,8 @@ public void testMisspelledHelp() { String[] args = {"--hp"}; ArgsParser parser = new ArgsParser(); - Parameter file = parser.addMandatoryStringParameter("--file", "f", "descr"); - Parameter save = parser.addMandatoryStringParameter("--save", "s", null); + StrParameter file = parser.addParameter(new StrParameter("--file", "f", "descr", true)); + StrParameter save = parser.addParameter(new StrParameter("--save", "s", null, true)); Exception exception = assertThrows(UnknownFlagArgsException.class, () -> parser.parseUnchecked(args)); assertEquals(""" @@ -542,8 +784,8 @@ public void testSuggestionForFullFlag() { String[] args = {"-f", "/to/file", "--sve", "save.txt"}; ArgsParser parser = new ArgsParser(); - Parameter file = parser.addMandatoryStringParameter("--file", "f", "descr"); - Parameter save = parser.addMandatoryStringParameter("--save", "s", null); + StrParameter file = parser.addParameter(new StrParameter("--file", "f", "descr", true)); + StrParameter save = parser.addParameter(new StrParameter("--save", "s", null, true)); Exception exception = assertThrows(UnknownFlagArgsException.class, () -> parser.parseUnchecked(args)); assertEquals(""" @@ -560,7 +802,7 @@ public void testNoFlags() { String[] args = {"file.txt"}; ArgsParser parser = new ArgsParser(); - Parameter string = parser.addMandatoryStringParameter("file", "f", "descr"); + StrParameter string = parser.addParameter(new StrParameter("file", "f", "descr", true)); Exception exception = assertThrows(UnknownFlagArgsException.class, () -> parser.parseUnchecked(args)); String expected = """ @@ -582,11 +824,11 @@ public void testDefinitionOfSameFlagTwice() { String[] args = {"--file", "file.txt", "--file2", "file2.txt"}; ArgsParser parser = new ArgsParser(); - parser.addMandatoryStringParameter("file", "f", "descr"); + parser.addParameter(new StrParameter("file", "f", "descr", true)); // Hier wird erwartet, dass beim Hinzufügen eines Parameters mit demselben Namen eine IllegalArgumentException geworfen wird IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> - parser.addMandatoryStringParameter("file", "f2", "descr") + parser.addParameter(new StrParameter("file", "f2", "descr", true)) ); assertEquals("Flag already exists: --file", exception.getMessage()); @@ -596,8 +838,8 @@ public void testDefinitionOfSameFlagTwice() { public void testDoubleParseCall() { String[] args = {"--file", "file.txt", "--file2", "file2.txt"}; ArgsParser parser = new ArgsParser(); - Parameter file = parser.addMandatoryStringParameter("file", "f", "descr"); - Parameter file2 = parser.addMandatoryStringParameter("file2", "f2", "descr"); + StrParameter file = parser.addParameter(new StrParameter("file", "f", "descr", true)); + StrParameter file2 = parser.addParameter(new StrParameter("file2", "f2", "descr", true)); parser.parse(args); Exception exception = assertThrows(IllegalStateException.class, () -> parser.parseUnchecked(args)); @@ -618,16 +860,16 @@ public void testTryToUseHelpAsFlagName() { ArgsParser parser = new ArgsParser(); assertThrows(IllegalArgumentException.class, () -> { - parser.addMandatoryStringParameter("help", "f", ""); + parser.addParameter(new StrParameter("help", "f", "", true)); }); assertThrows(IllegalArgumentException.class, () -> { - parser.addMandatoryStringParameter("hlp", "h", ""); + parser.addParameter(new StrParameter("hlp", "h", "", true)); }); assertThrows(IllegalArgumentException.class, () -> { - parser.addCommand("--help", "f", ""); + parser.addCommand(new Command("--help", "f", "")); }); assertThrows(IllegalArgumentException.class, () -> { - parser.addCommand("hlp", "-h", ""); + parser.addCommand(new Command("hlp", "-h", "")); }); } @@ -635,8 +877,8 @@ public void testTryToUseHelpAsFlagName() { public void testToggle() { String[] args = {"comm", "comm2"}; ArgsParser parser = new ArgsParser(); - Command comd = parser.addCommand("command", "comm", "command1"); - Command comd2 = parser.addCommand("command2", "comm2", "command2"); + Command comd = parser.addCommand(new Command("command", "comm", "command1")); + Command comd2 = parser.addCommand(new Command("command2", "comm2", "command2")); parser.toggle(comd, comd2); Exception exception = assertThrows(ToggleArgsException.class, () -> parser.parseUnchecked(args)); @@ -647,4 +889,17 @@ public void testToggle() { [command2 / comm2]"""; assertEquals(expected, exception.getMessage()); } + + @Test + public void testNotExistingPathArgsException() { + String[] args = {"--path", "/home/ExampleUser"}; + ArgsParser parser = new ArgsParser(); + PthParameter pathParam = parser.addParameter(new PthParameter("path", "p", "path example", true, true)); + Exception exception = assertThrows(NotExistingPathArgsException.class, () -> parser.parseUnchecked(args)); + String expected = """ + + /home/ExampleUser does not exist! + Invalid path!"""; + assertEquals(expected, exception.getMessage()); + } }