public String [ ] parse ( String [ ] args ) throws ArgException { List < String > nonOptions = new ArrayList <> ( ) ; // If true, then "--" has been seen and any argument starting with "-" // is processed as an ordinary argument, not as an option. boolean ignoreOptions = false ; // Loop through each argument String tail = "" ; String arg ; for ( int ii = 0 ; ii < args . length ; ) { // If there was a ',' separator in previous arg, use the tail as // current arg; otherwise, fetch the next arg from args list. if ( tail . length ( ) > 0 ) { arg = tail ; tail = "" ; } else { arg = args [ ii ] ; } if ( arg . equals ( "--" ) ) { ignoreOptions = true ; } else if ( ( arg . startsWith ( "--" ) || arg . startsWith ( "-" ) ) && ! ignoreOptions ) { String argName ; String argValue ; // Allow ',' as an argument separator to get around // some command line quoting problems. (markro) int splitPos = arg . indexOf ( ",-" ) ; if ( splitPos == 0 ) { // Just discard the ',' if ",-" occurs at begining of string arg = arg . substring ( 1 ) ; splitPos = arg . indexOf ( ",-" ) ; } if ( splitPos > 0 ) { tail = arg . substring ( splitPos + 1 ) ; arg = arg . substring ( 0 , splitPos ) ; } int eqPos = arg . indexOf ( ' ' ) ; if ( eqPos == - 1 ) { argName = arg ; argValue = null ; } else { argName = arg . substring ( 0 , eqPos ) ; argValue = arg . substring ( eqPos + 1 ) ; } OptionInfo oi = nameMap . get ( argName ) ; if ( oi == null ) { StringBuilder msg = new StringBuilder ( ) ; msg . append ( String . format ( "unknown option name '%s' in arg '%s'" , argName , arg ) ) ; if ( false ) { // for debugging msg . append ( "; known options:" ) ; for ( String optionName : sortedKeySet ( nameMap ) ) { msg . append ( " " ) ; msg . append ( optionName ) ; } } throw new ArgException ( msg . toString ( ) ) ; } if ( oi . argumentRequired ( ) && ( argValue == null ) ) { ii ++ ; if ( ii >= args . length ) { throw new ArgException ( "option %s requires an argument" , arg ) ; } argValue = args [ ii ] ; } // System.out.printf ("argName = '%s', argValue='%s'%n", argName, // argValue); setArg ( oi , argName , argValue ) ; } else { // not an option if ( ! parseAfterArg ) { ignoreOptions = true ; } nonOptions . add ( arg ) ; } // If no ',' tail, advance to next args option if ( tail . length ( ) == 0 ) { ii ++ ; } } String [ ] result = nonOptions . toArray ( new String [ nonOptions . size ( ) ] ) ; return result ; }
Sets option variables from the given command line .