Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /*
    * Copyright (C) 2011 Tatsuhiro Tsujikawa
    *
    * Permission is hereby granted, free of charge, to any person
    * obtaining a copy of this software and associated documentation
    * files (the "Software"), to deal in the Software without
    * restriction, including without limitation the rights to use, copy,
    * modify, merge, publish, distribute, sublicense, and/or sell copies
    * of the Software, and to permit persons to whom the Software is
   * furnished to do so, subject to the following conditions:
   *
   * The above copyright notice and this permission notice shall be
   * included in all copies or substantial portions of the Software.
   *
   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
   * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
   * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
   * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
   * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
   * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
   * SOFTWARE.
   */
  package net.sourceforge.argparse4j.internal;
  
  import java.util.HashMap;
  import java.util.HashSet;
  import java.util.List;
  import java.util.Map;
  import java.util.Set;
  
The application code must not use this class directly.
  
  public final class ArgumentParserImpl implements ArgumentParser {
  
      private Map<StringArgumentImploptargIndex_ = new HashMap<StringArgumentImpl>();
      private List<ArgumentImploptargs_ = new ArrayList<ArgumentImpl>();
      private List<ArgumentImplposargs_ = new ArrayList<ArgumentImpl>();
      private List<ArgumentGroupImplarggroups_ = new ArrayList<ArgumentGroupImpl>();
      private Map<StringObjectdefaults_ = new HashMap<StringObject>();
      private SubparsersImpl subparsers_ = new SubparsersImpl(this);
      private ArgumentParserImpl mainParser_;
      private String command_;
      private String prog_;
      private String usage_ = "";
      private String description_ = "";
      private String epilog_ = "";
      private String version_ = "";
      private PrefixPattern prefixPattern_;
      private boolean defaultHelp_ = false;
      private boolean negNumFlag_ = false;
      private TextWidthCounter textWidthCounter_;
      private static final Pattern NEG_NUM_PATTERN = Pattern.compile("-\\d+");
      private static final Pattern SHORT_OPTS_PATTERN = Pattern
              .compile("-[^-].*");
  
      public ArgumentParserImpl(String prog) {
          this(progtrue.null,
                  new ASCIITextWidthCounter(), nullnull);
      }
  
      public ArgumentParserImpl(String progboolean addHelp) {
          this(progaddHelp.null,
                  new ASCIITextWidthCounter(), nullnull);
      }
  
     public ArgumentParserImpl(String progboolean addHelpString prefixChars) {
         this(progaddHelpprefixCharsnullnew ASCIITextWidthCounter(),
                 nullnull);
     }
 
     public ArgumentParserImpl(String progboolean addHelpString prefixChars,
             String fromFilePrefix) {
         this(progaddHelpprefixCharsfromFilePrefix,
                 new ASCIITextWidthCounter(), nullnull);
     }
 
     public ArgumentParserImpl(String progboolean addHelpString prefixChars,
             String fromFilePrefixTextWidthCounter textWidthCounter) {
         this(progaddHelpprefixCharsfromFilePrefixtextWidthCounter,
                 nullnull);
     }
 
     public ArgumentParserImpl(String progboolean addHelpString prefixChars,
             String fromFilePrefixTextWidthCounter textWidthCounter,
             String commandArgumentParserImpl mainParser) {
         this. = TextHelper.nonNull(prog);
         this. = command;
         this. = mainParser;
         this. = textWidthCounter;
         if (prefixChars == null || prefixChars.isEmpty()) {
             throw new IllegalArgumentException(
                     "prefixChars cannot be a null or empty");
         }
         this. = new PrefixPattern(prefixChars);
         if (fromFilePrefix != null) {
             this. = new PrefixPattern(fromFilePrefix);
         }
         if (addHelp) {
             String prefix = prefixChars.substring(0, 1);
             addArgument(prefix + "h"prefix + prefix + "help")
                     .action(Arguments.help())
                     .help("show this help message and exit")
                     .setDefault(.);
         }
     }
 
     @Override
     public ArgumentImpl addArgument(String... nameOrFlags) {
         return addArgument(nullnameOrFlags);
     }
 
     public ArgumentImpl addArgument(ArgumentGroupImpl group,
             String... nameOrFlags) {
         ArgumentImpl arg = new ArgumentImpl(groupnameOrFlags);
         if (arg.isOptionalArgument()) {
             for (String flag : arg.getFlags()) {
                 ArgumentImpl another = .get(flag);
                 if (another != null) {
                     // TODO No conflict handler ATM
                     throw new IllegalArgumentException(String.format(
                             "argument %s: conflicting option string(s): %s",
                             flaganother.textualName()));
                 }
             }
             for (String flag : arg.getFlags()) {
                 if (.matcher(flag).matches()) {
                      = true;
                 }
                 .put(flagarg);
             }
             .add(arg);
         } else {
             for (ArgumentImpl another : ) {
                 if (arg.getName().equals(another.getName())) {
                     // TODO No conflict handler ATM
                     throw new IllegalArgumentException(String.format(
                             "argument %s: conflicting option string(s): %s",
                             arg.getName(), another.textualName()));
                 }
             }
             .add(arg);
         }
         return arg;
     }
 
     @Override
     public SubparsersImpl addSubparsers() {
         return ;
     }
 
     @Override
     public ArgumentGroup addArgumentGroup(String title) {
         ArgumentGroupImpl group = new ArgumentGroupImpl(thistitle);
         group.setIndex(.size());
         .add(group);
         return group;
     }
 
     @Override
         return addMutuallyExclusiveGroup("");
     }
 
     @Override
         ArgumentGroupImpl group = new ArgumentGroupImpl(thistitle);
         group.setIndex(.size());
         group.setMutex(true);
         .add(group);
         return group;
     }
 
     @Override
     public ArgumentParserImpl usage(String usage) {
          = TextHelper.nonNull(usage);
         return this;
     }

    
Set text to display before the argument help.

Parameters:
description text to display before the argument help
Returns:
this
 
     @Override
     public ArgumentParserImpl description(String description) {
          = TextHelper.nonNull(description);
         return this;
     }
 
     @Override
     public ArgumentParserImpl epilog(String epilog) {
          = TextHelper.nonNull(epilog);
         return this;
     }
 
     @Override
     public ArgumentParserImpl version(String version) {
          = TextHelper.nonNull(version);
         return this;
     }
 
     @Override
     public ArgumentParserImpl defaultHelp(boolean defaultHelp) {
          = defaultHelp;
         return this;
     }
 
     public boolean isDefaultHelp() {
         return ;
     }
 
     private void printArgumentHelp(PrintWriter writerList<ArgumentImplargs,
             int format_width) {
         for (ArgumentImpl arg : args) {
             if (arg.getArgumentGroup() == null
                     || !arg.getArgumentGroup().isSeparateHelp()) {
                 arg.printHelp(writer,
                         format_width);
             }
         }
     }
 
     @Override
     public void printHelp() {
         PrintWriter writer = new PrintWriter(.);
         printHelp(writer);
         writer.close();
     }
 
     @Override
     public void printHelp(PrintWriter writer) {
         int formatWidth = ArgumentParsers.getFormatWidth();
         printUsage(writerformatWidth);
         if (!.isEmpty()) {
             writer.format("%n%s%n", TextHelper.wrap(,
                     formatWidth, 0, """"));
         }
         boolean subparsersUntitled = .getTitle().isEmpty()
                 && .getDescription().isEmpty();
         if (checkDefaultGroup()
                 || (.hasSubCommand() && subparsersUntitled)) {
             writer.format("%npositional arguments:%n");
             printArgumentHelp(writerformatWidth);
             if (.hasSubCommand() && subparsersUntitled) {
                 .printSubparserHelp(writerformatWidth);
             }
         }
         if (checkDefaultGroup()) {
             writer.format("%noptional arguments:%n");
             printArgumentHelp(writerformatWidth);
         }
         if (.hasSubCommand() && !subparsersUntitled) {
             writer.format("%n%s:%n",
                     .getTitle().isEmpty() ? "subcommands"
                             : .getTitle());
             if (!.getDescription().isEmpty()) {
                 writer.format("  %s%n%n", TextHelper.wrap(,
                         .getDescription(), formatWidth, 2, """  "));
             }
             .printSubparserHelp(writerformatWidth);
         }
         for (ArgumentGroupImpl group : ) {
             if (group.isSeparateHelp()) {
                 writer.println();
                 group.printHelp(writerformatWidth);
             }
         }
         if (!.isEmpty()) {
             writer.format("%n%s%n", TextHelper.wrap(,
                     formatWidth, 0, """"));
         }
         writer.flush();
     }
 
     private boolean checkDefaultGroup(List<ArgumentImplargs) {
         if (args.isEmpty()) {
             return false;
         }
         for (ArgumentImpl arg : args) {
             if (arg.getArgumentGroup() == null
                     || !arg.getArgumentGroup().isSeparateHelp()) {
                 return true;
             }
         }
         return false;
     }
 
     @Override
     public String formatHelp() {
         StringWriter writer = new StringWriter();
         printHelp(new PrintWriter(writer));
         return writer.toString();
     }
 
     private void printArgumentUsage(PrintWriter writerList<Stringopts,
             int offsetString firstIndentString subsequentIndent,
             int format_width) {
         int currentWidth = offset + firstIndent.length();
         writer.print(firstIndent);
         boolean first = true;
         for (String syntax : opts) {
             if (!first && currentWidth + syntax.length() + 1 > format_width) {
                 writer.println();
                 writer.print(subsequentIndent);
                 writer.print(" ");
                 writer.print(syntax);
                 currentWidth = subsequentIndent.length() + 1 + syntax.length();
             } else {
                 writer.print(" ");
                 writer.print(syntax);
                 currentWidth += 1 + syntax.length();
                 first = false;
             }
         }
         writer.println();
     }
 
     @Override
     public void printUsage() {
         printUsage(new PrintWriter(.));
     }
 
     @Override
     public void printUsage(PrintWriter writer) {
         printUsage(writer, ArgumentParsers.getFormatWidth());
     }
 
     private void printUsage(PrintWriter writerint format_width) {
         if (!.isEmpty()) {
             writer.format("usage: %s%n"substitutePlaceholder());
             return;
         }
         String usageprog = String.format("usage: %s");
         writer.print(usageprog);
         int offset;
         String firstIndent;
         String subsequentIndent;
         String indent = "                              ";
         int usageprogWidth = .width(usageprog);
         if (usageprogWidth > indent.length()) {
             writer.println();
             offset = 6;
             firstIndent = subsequentIndent = indent.substring(0, offset);
         } else {
             offset = usageprogWidth;
             firstIndent = "";
             subsequentIndent = indent.substring(0, offset);
         }
         List<Stringopts = new ArrayList<String>();
         addUpperParserUsage(opts);
         if ( != null) {
             opts.add();
         }
         for (ArgumentImpl arg : ) {
             if (arg.getHelpControl() != .
                     && (arg.getArgumentGroup() == null || !arg
                             .getArgumentGroup().isMutex())) {
                 opts.add(arg.formatShortSyntax());
             }
         }
         for (ArgumentGroupImpl group : ) {
             List<ArgumentImplargs = filterSuppressedArgs(group.getArgs());
             int numArgs = args.size();
             if (group.isMutex()) {
                 if (numArgs > 1) {
                     opts.add((group.isRequired() ? "(" : "[")
                             + args.get(0).formatShortSyntaxNoBracket());
                     for (int i = 1; i < numArgs - 1; ++i) {
                         ArgumentImpl arg = args.get(i);
                         opts.add("|");
                         opts.add(arg.formatShortSyntaxNoBracket());
                     }
                     opts.add("|");
                     opts.add(args.get(numArgs - 1).formatShortSyntaxNoBracket()
                             + (group.isRequired() ? ")" : "]"));
                 } else if (numArgs == 1) {
                     if (group.isRequired()) {
                         opts.add(args.get(0).formatShortSyntaxNoBracket());
                     } else {
                         opts.add(args.get(0).formatShortSyntax());
                     }
                 }
             }
         }
         for (ArgumentImpl arg : ) {
             if (arg.getHelpControl() != .) {
                 opts.add(arg.formatShortSyntax());
             }
         }
         if (.hasSubCommand()) {
             opts.add(.formatShortSyntax());
             opts.add("...");
         }
         printArgumentUsage(writeroptsoffsetfirstIndentsubsequentIndent,
                 format_width);
     }

    
Returns arguments in args whose net.sourceforge.argparse4j.inf.Argument.getHelpControl() do not return net.sourceforge.argparse4j.impl.Arguments.SUPPRESS.

Parameters:
args
Returns:
filtered list of arguments
 
     private static List<ArgumentImplfilterSuppressedArgs(
             Collection<ArgumentImplargs) {
         ArrayList<ArgumentImplres = new ArrayList<ArgumentImpl>();
         for (ArgumentImpl arg : args) {
             if (arg.getHelpControl() != .) {
                 res.add(arg);
             }
         }
         return res;
     }

    
Appends command, required optional arguments and positional arguments in parser to opts recursively. Most upper parser stores first, just like post order traversal.

Parameters:
opts Command, required optional arguments and positional arguments.
parser The parser
 
     private void addUpperParserUsage(List<Stringopts,
             ArgumentParserImpl parser) {
         if (parser == null) {
             return;
         }
         addUpperParserUsage(optsparser.mainParser_);
         if (parser.command_ != null) {
             opts.add(parser.command_);
         }
         for (ArgumentImpl arg : parser.optargs_) {
             if (arg.getHelpControl() != .
                     && arg.isRequired()
                     && (arg.getArgumentGroup() == null || !arg
                             .getArgumentGroup().isMutex())) {
                 opts.add(arg.formatShortSyntax());
             }
         }
 
         for (ArgumentGroupImpl group : parser.arggroups_) {
             List<ArgumentImplargs = filterSuppressedArgs(group.getArgs());
             int numArgs = args.size();
             if (group.isMutex()) {
                 if (numArgs > 1) {
                     if (group.isRequired()) {
                         opts.add("(" + args.get(0).formatShortSyntaxNoBracket());
                         for (int i = 1; i < numArgs - 1; ++i) {
                             ArgumentImpl arg = args.get(i);
                             opts.add("|");
                             opts.add(arg.formatShortSyntaxNoBracket());
                         }
                         opts.add("|");
                         opts.add(args.get(numArgs - 1)
                                 .formatShortSyntaxNoBracket() + ")");
                     }
                 } else if (numArgs == 1) {
                     if (group.isRequired()) {
                         opts.add(args.get(0).formatShortSyntaxNoBracket());
                     } else if (args.get(0).isRequired()) {
                         opts.add(args.get(0).formatShortSyntax());
                     }
                 }
             }
         }
 
         for (ArgumentImpl arg : parser.posargs_) {
             if (arg.getHelpControl() != .) {
                 opts.add(arg.formatShortSyntax());
             }
         }
     }
 
     @Override
     public String formatUsage() {
         StringWriter writer = new StringWriter();
         printUsage(new PrintWriter(writer));
         return writer.toString();
     }
 
     @Override
     public ArgumentParserImpl setDefault(String destObject value) {
         .put(destvalue);
         return this;
     }
 
     @Override
     public ArgumentParserImpl setDefaults(Map<StringObjectattrs) {
         .putAll(attrs);
         return this;
     }

    
Returns default value set by ArgumentImpl.setDefault(java.lang.Object) or setDefault(java.lang.String,java.lang.Object). Please note that while parser-level defaults always override argument-level defaults while parsing, this method examines argument-level defaults first. If no default value is found, then check parser-level defaults.

Parameters:
dest attribute name of default value to get.
Returns:
default value of given dest.
 
     @Override
     public Object getDefault(String dest) {
         for (ArgumentImpl arg : ) {
             if (dest.equals(arg.getDest()) && arg.getDefault() != null) {
                 return arg.getDefault();
             }
         }
         for (ArgumentImpl arg : ) {
             if (dest.equals(arg.getDest()) && arg.getDefault() != null) {
                 return arg.getDefault();
             }
         }
         return .get(dest);
     }
 
     @Override
     public Namespace parseArgsOrFail(String args[]) {
         try {
             Namespace ns = parseArgs(args);
             return ns;
         } catch (ArgumentParserException e) {
             handleError(e);
             System.exit(1);
         }
         return null;
     }
 
     @Override
     public Namespace parseArgs(String args[]) throws ArgumentParserException {
         Map<StringObjectattrs = new HashMap<StringObject>();
         parseArgs(argsattrs);
         return new Namespace(attrs);
     }
 
     @Override
     public void parseArgs(String[] argsMap<StringObjectattrs)
             throws ArgumentParserException {
         parseArgs(args, 0, attrs);
     }
 
     @Override
     public void parseArgs(String[] argsObject userData)
             throws ArgumentParserException {
         Map<StringObjectopts = new HashMap<StringObject>();
         parseArgs(argsoptsuserData);
     }
 
     @Override
     public void parseArgs(String[] argsMap<StringObjectattrs,
             Object userDatathrows ArgumentParserException {
         parseArgs(args, 0, attrs);
 
         Class userClass = userData.getClass();
         while (userClass != null) {
             for (final Field field : userClass.getDeclaredFields()) {
                 Arg ann = field.getAnnotation(Arg.class);
                 if (ann != null) {
                     String argDest = ann.dest();
                     if (argDest.isEmpty()) {
                         argDest = field.getName();
                     }
                     if (!attrs.containsKey(argDest)) {
                         continue;
                     }
                     Object val = attrs.get(argDest);
                     try {
                         AccessController
                                 .doPrivileged(new PrivilegedAction<Void>() {
 
                                     @Override
                                     public Void run() {
                                         field.setAccessible(true);
                                         return null;
                                     }
                                 });
                         field.set(userData,
                                 ReflectHelper.list2Array(field.getType(), val));
                     } catch (RuntimeException e) {
                         if (!ann.ignoreError()) {
                             throw e;
                         }
                     } catch (Exception e) {
                         if (!ann.ignoreError()) {
                             throw new IllegalArgumentException(String.format(
                                     "Could not set %s to field %s"val,
                                     field.getName()), e);
                         }
                     }
                 }
             }
             for (final Method method : userClass.getDeclaredMethods()) {
                 Arg ann = method.getAnnotation(Arg.class);
                 if (ann != null) {
                     String argDest = ann.dest();
                     if (argDest.isEmpty()) {
                         argDest = method.getName();
                     }
                     if (!attrs.containsKey(argDest)) {
                         continue;
                     }
                     Object val = attrs.get(argDest);
                     Class<?>[] fargs = method.getParameterTypes();
                     if (fargs.length != 1) {
                         throw new IllegalArgumentException(String.format(
                                 "Method %s must have one formal parameter",
                                 method.getName()));
                     }
                     try {
                         AccessController
                                 .doPrivileged(new PrivilegedAction<Void>() {
 
                                     @Override
                                     public Void run() {
                                         method.setAccessible(true);
                                         return null;
                                     }
                                 });
                         method.invoke(userData,
                                 ReflectHelper.list2Array(fargs[0], val));
                     } catch (RuntimeException e) {
                         if (!ann.ignoreError()) {
                             throw e;
                         }
                     } catch (Exception e) {
                         if (!ann.ignoreError()) {
                             throw new IllegalArgumentException(String.format(
                                     "Could not call method %s with %s",
                                     method.getName(), val), e);
                         }
                     }
                 }
             }
             userClass = userClass.getSuperclass();
         }
 
     }
 
     public void parseArgs(String args[], int offsetMap<StringObjectattrs)
             throws ArgumentParserException {
         ParseState state = new ParseState(argsoffset);
         parseArgs(stateattrs);
     }

    
Check that term forms a valid concatenated short options. Note that this option does not actually process arguments. Therefore, true from this function does not mean all arguments in term are acceptable.

Parameters:
term string to inspect
Returns:
true if term forms a valid concatenated short options.
 
     private boolean checkConcatenatedShortOpts(String term) {
         if (.matcher(term).matches()) {
             for (int i = 1, termlen = term.length(); i < termlen; ++i) {
                 String shortFlag = "-" + term.charAt(i);
                 ArgumentImpl arg = .get(shortFlag);
                 if (arg == null) {
                     return false;
                 }
                 if (arg.getAction().consumeArgument()) {
                     return true;
                 }
             }
             return true;
         } else {
             return false;
         }
     }

    
Returns optional argument ArgumentImpl which matches given flag. This function handles abbreviation as well. If flag is ambiguous, net.sourceforge.argparse4j.inf.ArgumentParserException will be thrown. If flag does not match nay ArgumentImpl, this function returns null.

Parameters:
flag flag to match
Returns:
ArgumentImpl which matches flag if it succeeds, or null
Throws:
net.sourceforge.argparse4j.inf.ArgumentParserException if flag is ambiguous
 
     private ArgumentImpl resolveNextFlag(String flag)
             throws ArgumentParserException {
         ArgumentImpl arg = .get(flag);
         if (arg != null) {
             return arg;
         }
         List<Stringcand = TextHelper.findPrefix(.keySet(), flag);
         if (cand.isEmpty()) {
             return null;
         } else if (checkConcatenatedShortOpts(flag)) {
             // Get first short option
             cand.add(flag.substring(0, 2));
         } else if (cand.size() == 1) {
             return .get(cand.get(0));
         }
         // At this point, more than 1 flags were found from optargIndex_
         // and/or flag forms concatenated short options.
         // Sort in order to make unit test easier.
         Collections.sort(cand);
         throw new ArgumentParserException(String.format(
                 "ambiguous option: %s could match %s"flag,
                 TextHelper.concat(cand, 0, ", ")), this);
     }
 
     public void parseArgs(ParseState stateMap<StringObjectattrs)
             throws ArgumentParserException {
         populateDefaults(attrs);
         Set<ArgumentImplused = new HashSet<ArgumentImpl>();
         ArgumentImpl[] groupUsed = new ArgumentImpl[.size()];
         int posargIndex = 0;
         int posargsLen = .size();
         while (state.isArgAvail()) {
             // We first evaluate flagFound(state) before comparing arg to "--"
             // in order to expand arguments from file.
             if (flagFound(state) && !"--".equals(state.getArg())) {
                 String term = state.getArg();
                 int p = term.indexOf("=");
                 String flag;
                 String embeddedValue;
                 if (p == -1) {
                     flag = term;
                     embeddedValue = null;
                 } else {
                     flag = term.substring(0, p);
                     embeddedValue = term.substring(p + 1);
                 }
                 ArgumentImpl arg = resolveNextFlag(flag);
                 if (arg == null) {
                     // Assign null for clarity
                     embeddedValue = null;
                     boolean shortOptsFound = false;
                     if (.matcher(term).matches()) {
                         shortOptsFound = true;
                         // Possible concatenated short options
                         for (int i = 1, termlen = term.length(); i < termlen; ++i) {
                             String shortFlag = "-" + term.charAt(i);
                             arg = .get(shortFlag);
                             if (arg == null) {
                                 shortOptsFound = false;
                                 break;
                             }
                             if (arg.getAction().consumeArgument()) {
                                 flag = shortFlag;
                                 shortOptsFound = true;
                                 if (term.length() > i + 1) {
                                     embeddedValue = term.substring(i + 1);
                                 }
                                 break;
                             }
                             checkMutex(arggroupUsed);
                             arg.run(thisattrsshortFlagnull);
                             used.add(arg);
                             // Set null to avoid using it twice.
                             arg = null;
                         }
                     }
                     if (!shortOptsFound) {
                         throw new UnrecognizedArgumentException(
                                 formatUnrecognizedArgumentErrorMessage(state,
                                         term), thisterm);
                     }
                 }
                 ++state.index;
                 if (arg != null) {
                     checkMutex(arggroupUsed);
                     processArg(attrsstateargflagembeddedValue);
                     used.add(arg);
                 }
             } else if ("--".equals(state.getArg()) && !state.consumedSeparator) {
                 state.consumedSeparator = true;
                 state.negNumFlag = false;
                 ++state.index;
             } else if (posargIndex < posargsLen) {
                 ArgumentImpl arg = .get(posargIndex++);
                 processArg(attrsstateargnullnull);
             } else if (!state.consumedSeparator && .hasSubCommand()) {
                 checkRequiredArgument(usedposargIndex);
                 checkRequiredMutex(groupUsed);
                 .parseArg(stateattrs);
                 return;
             } else {
                 throw new ArgumentParserException(
                         formatUnrecognizedArgumentErrorMessage(state,
                                 TextHelper.concat(state.argsstate.index" ")),
                         this);
             }
         }
         if (.hasSubCommand()) {
             throw new ArgumentParserException("too few arguments"this);
         }
         while (posargIndex < posargsLen) {
             ArgumentImpl arg = .get(posargIndex++);
             processArg(attrsstateargnullnull);
         }
         checkRequiredArgument(usedposargIndex);
         checkRequiredMutex(groupUsed);
     }

    
Format message for "Unrecognized arguments" error.

Parameters:
state Current parser state
args Textual representation of unrecognized arguments to be included in the message as is.
Returns:
formatted error message
 
             String args) {
         return String
                 .format("unrecognized arguments: '%s'%s",
                         args,
                         state.index > state.lastFromFileArgIndex ? ""
                                 : String.format(
                                         "%nChecking trailing white spaces or new lines in %sfile may help.",
                                         .getPrefixChars()
                                                 .length() == 1 ? 
                                                 .getPrefixChars() : "["
                                                 + 
                                                         .getPrefixChars() + "]"));
     }

    
Check that another option in mutually exclusive group has already been specified. If so, throw an exception.

Parameters:
arg The argument currently processed
groupUsed The cache of used argument in each groups.
Throws:
net.sourceforge.argparse4j.inf.ArgumentParserException If another option in mutually exclusive group has already been used.
 
     private void checkMutex(ArgumentImpl argArgumentImpl[] groupUsed)
             throws ArgumentParserException {
         if (arg.getArgumentGroup() != null) {
             if (arg.getArgumentGroup().isMutex()) {
                 ArgumentImpl usedMutexArg = groupUsed[arg.getArgumentGroup()
                         .getIndex()];
                 if (usedMutexArg == null) {
                     groupUsed[arg.getArgumentGroup().getIndex()] = arg;
                 } else if (usedMutexArg != arg) {
                     throw new ArgumentParserException(String.format(
                             "not allowed with argument %s",
                             usedMutexArg.textualName()), thisarg);
                 }
             }
         }
     }

    

Parameters:
res
state state.offset points to the argument next to flag
arg
flag
embeddedValue If optional argument is given as "foo=bar" or "-fbar" (short option), embedded value is "bar". Otherwise null
Throws:
net.sourceforge.argparse4j.inf.ArgumentParserException
 
     private void processArg(Map<StringObjectresParseState state,
             ArgumentImpl argString flagString embeddedValue)
             throws ArgumentParserException {
         if (!arg.getAction().consumeArgument()) {
             if (embeddedValue == null) {
                 arg.run(thisresflagnull);
                 return;
             } else {
                 throw new ArgumentParserException(String.format(
                         "ignore implicit argument '%s'"embeddedValue), this,
                         arg);
             }
         }
         if (arg.getMinNumArg() == -1
                 || (arg.getMinNumArg() == 0 && arg.getMaxNumArg() == 1)) {
             // In case of: option takes exactly one argument, or nargs("?")
             String argval = null;
             if (embeddedValue == null) {
                 if (state.isArgAvail() && !flagFound(state)) {
                     argval = state.getArg();
                     ++state.index;
                 }
             } else {
                 argval = embeddedValue;
             }
             if (argval == null) {
                 if (arg.getMinNumArg() == -1) {
                     if (arg.isOptionalArgument()) {
                         throw new ArgumentParserException(
                                 "expected one argument"thisarg);
                     } else {
                         throw new ArgumentParserException("too few arguments",
                                 this);
                     }
                 } else if (arg.isOptionalArgument()) {
                     // This is a special treatment for nargs("?"). If flag is
                     // given but no argument follows, produce const value.
                     arg.run(thisresflagarg.getConst());
                 }
             } else {
                 arg.run(thisresflagarg.convert(thisargval));
             }
         } else {
             List<Objectlist = new ArrayList<Object>();
             if (embeddedValue == null) {
                 for (int i = 0; i < arg.getMaxNumArg() && state.isArgAvail(); ++i, ++state.index) {
                     if (flagFound(state)) {
                         break;
                     }
                     list.add(arg.convert(thisstate.getArg()));
                 }
             } else {
                 list.add(arg.convert(thisembeddedValue));
             }
             if (list.size() < arg.getMinNumArg()) {
                 if (arg.isOptionalArgument()) {
                     throw new ArgumentParserException(String.format(
                             "expected %d argument(s)"arg.getMinNumArg()),
                             thisarg);
                 } else {
                     throw new ArgumentParserException("too few arguments"this);
                 }
             }
             // For optional arguments, always process the list even if it is
             // empty.
             // For positional arguments, empty list means no positional argument
             // is given. In this case, we want to keep default value, so
             // don't process the list.
             if (arg.isOptionalArgument() || !list.isEmpty()) {
                 arg.run(thisresflaglist);
             }
         }
     }

    
Returns true if state.getArg() is flag. Note that if "--" is met and not consumed, this function returns true, because "--" is treated as special optional argument. If prefixFileChar is found in prefix of argument, read arguments from that file and expand arguments in state necessary.

 
     private boolean flagFound(ParseState statethrows ArgumentParserException {
         while (fromFileFound(state)) {
             extendArgs(state,
                     .removePrefix(state.getArg()));
         }
         String term = state.getArg();
         if (state.consumedSeparator) {
             return false;
        } else if ("--".equals(term)) {
            return true;
        }
        return .match(term)
                && (state.negNumFlag || !.matcher(term)
                        .matches());
    }
    private boolean fromFileFound(ParseState state) {
        return  != null
                && .match(state.getArg());
    }

    
Extends arguments by reading additional arguments from file.

Parameters:
state Current parser state.
file File from which additional arguments are read.
Throws:
net.sourceforge.argparse4j.inf.ArgumentParserException
    private void extendArgs(ParseState stateString file)
            throws ArgumentParserException {
        List<Stringlist = new ArrayList<String>();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(
                    new FileInputStream(file), "utf-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                list.add(line);
            }
        } catch (IOException e) {
            throw new ArgumentParserException(String.format(
                    "Could not read arguments from file '%s'"file), ethis);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
            }
        }
        int offset = state.index + 1;
        String[] newargs = new String[list.size() + state.args.length - offset];
        list.toArray(newargs);
        System.arraycopy(state.argsoffsetnewargslist.size(),
                state.args.length - offset);
        if (state.lastFromFileArgIndex < offset) {
            state.lastFromFileArgIndex = list.size() - 1;
        } else {
            state.lastFromFileArgIndex += -offset + list.size();
        }
        state.resetArgs(newargs);
    }
    private void checkRequiredArgument(Set<ArgumentImplusedint posargIndex)
            throws ArgumentParserException {
        for (ArgumentImpl arg : ) {
            if (arg.isRequired() && !used.contains(arg)) {
                throw new ArgumentParserException(String.format(
                        "argument %s is required"arg.textualName()), this);
            }
        }
        if (.size() > posargIndex) {
            throw new