Giter VIP home page Giter VIP logo

argparse's Introduction

Introduction

The purpose of Argparse is to facilitate the process of parsing command-line arguments passed to a program. Command-line arguments are a way for users to provide input to a program when it is run from the command-line, and are a common way to configure the behavior of command-line applications.

Some of the features of Argparse:

  • Support for different types of arguments, such as options, flags, key-value pairs, and positional arguments.
  • Automatic generation of help and usage messages.
  • Automatic error handling, such as handling missing or invalid arguments.

By using an Argparse, developers can make their command-line applications more user-friendly, easier to use, and more robust.

Getting Started

For now it is a single page module, which you can directly copy from here and paste in your project. But if you want to properly install it in your project with the pom.xml file (that includes the dependency tree), then you should look at the Releases and download one of the zip files from there.

API Reference

  • ArgparseOptionType

    This enum includes the type of options that can be given over the command-line if using Argparse as your main parsing program.

    This enum includes the following types of options:

    • ARGPARSE_OPT_GROUP
    • ARGPARSE_OPT_BOOLEAN
    • ARGPARSE_OPT_BIT
    • ARGPARSE_OPT_INTEGER
    • ARGPARSE_OPT_FLOAT
    • ARGPARSE_OPT_STRING
  • ArgparseOption

    This class creates a parser option.

    It has the following attributes attached to its instance:

    • prefix - Flag prefix.
    • shortName - Flag short name.
    • longName - Flag long name.
    • value - Flag value.
    • defaultValue - Flag default value.
    • help - Flag help text.
    • optionType - Type of the flag.
  • Argparse

    Creates the parser instance for your command-line application.

    • Argparse(String[] sysargs, String progname, String usage, String description, String epilog);

      The Argparse constructor initializes the Argparse object with the provided arguments. The constructor takes in the sysargs, progname, usage, description, and epilog arguments.

      If the progname argument is null or empty, it retrieves the program name from the first element of the sysargs array. If the program name has an extension, it removes the extension from the name.

      The usage, description, and epilog arguments are assigned to the corresponding instance variables of the Argparse object.

      The constructor shifts the sysargs array by one position to remove the program name from the array, and assigns it to the sysargs instance variable of the Argparse object.

      The constructor initializes three maps: optionsMap, shortToLongOptionsMap, and longToShortOptionsMap. The optionsMap maps an integer key to an ArgparseOption object. The shortToLongOptionsMap maps short option strings to their corresponding long option strings. The longToShortOptionsMap maps long option strings to their corresponding short option strings.

    • public void addArgument(final ArgparseOption argparseOption) throws InvalidAttributeValueException;

      This function, addArgument, is used to add an argument to the optionsMap, which is a hash map that maps a hash code generated from the short or long name of the argument to the argument itself. The function first checks if the argument's short name or long name is provided, and throws an InvalidAttributeValueException if both are empty. The argument is then added to the optionsMap with its hash code as the key. If the argument has a short name, the short-to-long name mapping is added to shortToLongOptionsMap. If the argument has a long name, the long-to-short name mapping is added to longToShortOptionsMap. This function helps build the argument parser by allowing the user to add arguments and their associated short and long names.

    • public void parse();

      The parse() function is responsible for parsing the command line arguments provided to the program. It first checks if any arguments have been provided and if so, it iterates through them. If an argument contains an equal sign, it splits the argument into the argument name and value, and then looks for the corresponding option in the optionsMap. If it finds a match, it assigns the value to the option's value attribute. If the argument does not contain an equal sign, it checks if the option is a boolean type. If it is, it assigns the value "true" to the option's value attribute, otherwise it errors out. If the argument is not recognized, it also errors out. The function locks the current group argument if it exists before setting the value.

    • public String getArgumentValue(String argument);

      This is a method that returns the value of a given argument if present in the optionsMap hash map. If the argument is not present, it returns null. The method checks if the argument is present in the longToShortOptionsMap and shortToLongOptionsMap hash maps and retrieves the value of the corresponding option from the optionsMap. If the retrieved value is null, it returns the default value for the option.

    • public static void printMessage(final ArgparseOption argparseOption);

      This method prints out a formatted string of an ArgparseOption object, which can be used for debugging purposes.

    • public static void printMessage(final String message);

      This method is a simple wrapper around the System.out.print() method to make it easier to print messages to the console. It takes a string as input and prints it to the console. There are no overloads for integer or float values, so String.format() can be used to pass strings with integer or float values.

    • public void printUsage();

      This function prints the usage string of the program along with the description and epilog, if provided during initialization of the parser. It also uses Argparse.colorEncodedString to add color to the printed output.

    • public void exit();

      The exit() method exits the program and releases the resources acquired by the logger. It calls the System.exit(0) method to terminate the program with a successful status code.

    • public void exit(final int status, final String message);

      This method overloads the exit() method and takes two parameters: an integer status and a String message. It prints the message to the console if it is not null or empty, then exits the program with the specified status code.

    • public void error(final String message);

      This method prints an error message, followed by the usage string, and then exits the program with an error code of 2. The error message indicates that there was an error in the usage of a shell built-in command. The error message is passed as an argument to the method.

Examples

import Argparse;

import javax.management.InvalidAttributeValueException;

class Main {
  public void main(String[] args) {
    Argparse parser = new Argparse(
      args,
      null,  /** Program name is automatically deduced. */
      "Usage: progname --foo\n" +
      "\n" +
      "     --foo=<STRING>\n" +
      "           Just a flag argument like any other flag argument.",
      "This is the program description and the program parses the value for flag 'foo'.",
      "This is the epilog (set the footer here).");

    try {
      parser.addArgument(
          new Argparse.ArgparseOption(
              "f",
              "foo",
              Argparse.ArgparseOptionType.ARGPARSE_OPT_STRING,
              null,
              "bar",
              "Help text for foo."));
    } catch (InvalidAttributeValueException exc) {
      System.err.println(exc.toString());
    }

    parser.parse();
    final String fooValue = parser.getArgumentValue("foo");
    ...
  }
}

argparse's People

Contributors

joshiayush avatar

Watchers

 avatar

argparse's Issues

Remove the duplicate code by refactoring it in a single function call.

if (this.optionsMap
.get(argumentWithoutPrefix.hashCode()).optionType == ArgparseOptionType.ARGPARSE_OPT_GROUP) {
if (isGroupArgumentEncountered) {
this.error(String.format("%s and %s is a part of group, hence can be used only one at a time.",
groupArgument, argumentWithoutPrefix));
}
groupArgument = argumentWithoutPrefix;
}

if (this.optionsMap
.get(argumentWithoutPrefix.hashCode()).optionType == ArgparseOptionType.ARGPARSE_OPT_GROUP) {
if (isGroupArgumentEncountered) {
this.error(String.format("%s and %s is a part of group, hence can be used only one at a time.",
groupArgument, argumentWithoutPrefix));
}
groupArgument = argumentWithoutPrefix;
}

As you can see the above conditional check is repeating itself at line 302 and at line 334 which can easily be refactored into a single function call.

if (this.optionsMap
.get(this.longToShortOptionsMap.get(argumentWithoutPrefix)
.hashCode()).optionType == ArgparseOptionType.ARGPARSE_OPT_GROUP) {
if (isGroupArgumentEncountered) {
this.error(String.format("%s and %s is a part of group, hence can be used only one at a time.",
groupArgument, argumentWithoutPrefix));
}
groupArgument = argumentWithoutPrefix;
}

if (this.optionsMap
.get(this.longToShortOptionsMap.get(argumentWithoutPrefix)
.hashCode()).optionType == ArgparseOptionType.ARGPARSE_OPT_GROUP) {
if (isGroupArgumentEncountered) {
this.error(String.format("%s and %s is a part of group, hence can be used only one at a time.",
groupArgument, argumentWithoutPrefix));
}
groupArgument = argumentWithoutPrefix;
}

As you can see the above conditional check is also repeating itself at line 312 and at line 348 which can easily be refactored into a single function call.

We need to refactor these into separate function calls because as the complexity of our program will increase it will become harder to maintain the program and modify it.

Is it really necessary to add support for `Solaris` operating system?

/**
* Returns true if the Operating System is Solaris.
*/
public static boolean isSolaris() {
return getOsName().toLowerCase().indexOf("sunos") >= 0;
}

I think adding support for Solaris is a bit out-of-scope for me as a developer right now, because I don't have experience using Solaris. I can add support for Mac although that's another operating system that I didn't use but it's a bit similar to Linux which is my primary operating system. And because of the platform independence of Java project argparse will have no issue on Windows. But adding support for Solaris is a bit weird right now. Either remove the function completely or add support for Solaris too.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.