You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by jk...@apache.org on 2002/08/25 00:15:32 UTC
cvs commit: jakarta-commons/cli/src/java/org/apache/commons/cli BasicParser.java Parser.java CommandLineParserFactory.java GnuParser.java PosixParser.java
jkeyes 2002/08/24 15:15:32
Modified: cli/src/java/org/apache/commons/cli
CommandLineParserFactory.java GnuParser.java
PosixParser.java
Added: cli/src/java/org/apache/commons/cli BasicParser.java
Parser.java
Log:
separated the argument flattening from the Option processing
Revision Changes Path
1.3 +8 -3 jakarta-commons/cli/src/java/org/apache/commons/cli/CommandLineParserFactory.java
Index: CommandLineParserFactory.java
===================================================================
RCS file: /home/cvs/jakarta-commons/cli/src/java/org/apache/commons/cli/CommandLineParserFactory.java,v
retrieving revision 1.2
retrieving revision 1.3
diff -u -r1.2 -r1.3
--- CommandLineParserFactory.java 25 Jul 2002 21:40:08 -0000 1.2
+++ CommandLineParserFactory.java 24 Aug 2002 22:15:31 -0000 1.3
@@ -79,8 +79,12 @@
return newParser( DEFAULT_PARSER );
}
+ /**
+ * @return the CommandLineParser specified by <code>classname</code>.
+ */
public static CommandLineParser newParser( String classname ) {
try {
+ // return the new CommandLineParser
return (CommandLineParser)Class.forName( classname ).newInstance();
}
catch( Exception exp ) {
@@ -93,6 +97,7 @@
// this will not happen ?
}
}
+ // must return something
return null;
}
}
1.7 +21 -278 jakarta-commons/cli/src/java/org/apache/commons/cli/GnuParser.java
Index: GnuParser.java
===================================================================
RCS file: /home/cvs/jakarta-commons/cli/src/java/org/apache/commons/cli/GnuParser.java,v
retrieving revision 1.6
retrieving revision 1.7
diff -u -r1.6 -r1.7
--- GnuParser.java 15 Aug 2002 22:05:18 -0000 1.6
+++ GnuParser.java 24 Aug 2002 22:15:31 -0000 1.7
@@ -1,301 +1,44 @@
-/*
- * $Header$
- * $Revision$
- * $Date$
- *
- * ====================================================================
- *
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 1999-2001 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowlegement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowlegement may appear in the software itself,
- * if and wherever such third-party acknowlegements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Group.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- */
package org.apache.commons.cli;
import java.util.Arrays;
+import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
-import java.util.ListIterator;
import java.util.Map;
+import java.util.Iterator;
/**
- * GnuParser parses the command line arguments using the GNU style.
- * For example, -buildfile can only be interpreted as the option
- * 'buildfile'.
- *
* @author John Keyes (jbjk at mac.com)
*/
-public class GnuParser implements CommandLineParser {
-
- /** current options instance */
- private Options options;
-
- /** convience member for the command line */
- private CommandLine cmd;
+public class GnuParser extends Parser {
- /** required options subset of options */
- private Map requiredOptions;
+ private ArrayList tokens = new ArrayList();
- /**
- * Parse the arguments according to the specified options.
- *
- * @param options the specified Options
- * @param arguments the command line arguments
- * @return the list of atomic option and value tokens
- * @throws ParseException if there are any problems encountered
- * while parsing the command line tokens.
- */
- public CommandLine parse( Options options, String[] arguments )
- throws ParseException
- {
- return parse( options, arguments, false );
+ private void init() {
+ tokens.clear();
}
- /**
- * Parse the arguments according to the specified options.
- *
- * @param opts the specified Options
- * @param arguments the command line arguments
- * @param stopAtNonOption specifies whether to continue parsing the
- * arguments if a non option is encountered.
- * @return the CommandLine
- * @throws ParseException if there are any problems encountered
- * while parsing the command line tokens.
- */
- public CommandLine parse( Options opts, String[] arguments, boolean stopAtNonOption )
- throws ParseException
+ protected String[] flatten( Options options,
+ String[] arguments,
+ boolean stopAtNonOption )
{
- // set the member instances
- options = opts;
- cmd = new CommandLine();
- requiredOptions = options.getRequiredOptions();
-
- ListIterator iter = Arrays.asList( arguments ).listIterator();
- String token = null;
-
- // flag to indicate whether the remainder of the tokens should
- // be added to the other arguments list
- boolean eatTheRest = false;
-
- while ( iter.hasNext() ) {
- token = (String) iter.next();
- if ( token.equals("--") ) {
- eatTheRest = true;
- }
- else if ( token.startsWith("--") ) {
- //process the long-option
- processOption( token, iter );
- }
- else if ( token.startsWith("-") ) {
- if ( token.length() == 1) {
- // It's not really an option, so
- // just drop it on the list
- if ( stopAtNonOption ) {
- eatTheRest = true;
- }
- else {
- cmd.addArg( token );
- }
+ init();
+ for( int i = 0; i < arguments.length; i++ ) {
+ Option option = options.getOption( arguments[i] );
+ try {
+ Option specialOption = options.getOption( arguments[i].substring(0,2) );
+ if( specialOption != null && option == null ) {
+ tokens.add( arguments[i].substring(0,2) );
+ tokens.add( arguments[i].substring(2) );
}
else {
- processOption( token, iter );
+ tokens.add( arguments[i] );
}
}
- else {
- // It's just a normal non-option arg,
- // so dump it into the list of returned
- // values.
-
- cmd.addArg( token );
-
- if ( stopAtNonOption ) {
- eatTheRest = true;
- }
- }
-
- if ( eatTheRest ) {
- while ( iter.hasNext() ) {
- cmd.addArg( (String)iter.next() );
- }
+ catch( IndexOutOfBoundsException exp ) {
+ tokens.add( arguments[i] );
}
}
-
- // see if all required options have been processed
- checkRequiredOptions( );
-
- return cmd;
+ return (String[])tokens.toArray( new String[] {} );
}
-
- /**
- * It the option can accept multiple argument values then
- * keep adding values until the next option token is encountered.
- *
- * @param opt the specified option
- * @param iter the iterator over the command line tokens
- */
- public void processArgs( Option opt, ListIterator iter )
- throws ParseException
- {
- if( !iter.hasNext() && !opt.hasOptionalArg() ) {
- throw new MissingArgumentException( "no argument for:" + opt.getOpt() );
- }
- // loop until an option is found
- while( iter.hasNext() ) {
- String var = (String)iter.next();
-
- // its an option
- if( !var.equals( "-" ) && var.startsWith( "-" ) ) {
- // set the iterator pointer back a position
- iter.previous();
- break;
- }
- // its a value
- else if( !opt.addValue( var ) ) {
- iter.previous();
- return;
- }
- }
- }
-
- /**
- * Process the option represented by <code>arg</code>.
- *
- * @param arg the string representation of an option
- * @param iter the command line token iterator
- */
- private void processOption( String arg, ListIterator iter )
- throws ParseException
- {
- String value = null;
-
- // see if it is a single character special option
- Option opt = (Option) options.getOption( arg );
- Option specialOption = (Option) options.getOption( arg.substring(0,2 ) );
- if( specialOption != null && opt == null) {
- opt = specialOption;
- value = arg.substring( 2 );
- char sep = opt.getValueSeparator();
-
- if( sep > 0 ) {
- int findex;
- while( ( findex = value.indexOf( sep ) ) != -1 ) {
- String val = value.substring( 0, findex );
- value = value.substring( findex + 1);
- if( !opt.addValue( val ) ) {
- cmd.addArg( val );
- }
- }
- if( !opt.addValue( value ) ) {
- cmd.addArg( value );
- }
- }
- else {
- // add the argument value
- opt.addValue( value );
- }
- }
-
- // if there is no option throw an UnrecognisedOptionException
- if( opt == null ) {
- throw new UnrecognizedOptionException("Unrecognized option: " + arg);
- }
-
- // if the option is a required option remove the option from
- // the requiredOptions list
- if ( opt.isRequired() ) {
- requiredOptions.remove( opt );
- }
-
- // if the option is in an OptionGroup make that option the selected
- // option of the group
- if ( options.getOptionGroup( opt ) != null ) {
- ( (OptionGroup)( options.getOptionGroup( opt ) ) ).setSelected( opt );
- }
-
- // if the option takes an argument value
- if ( opt.hasArg() ) {
- processArgs( opt, iter );
- }
-
- // set the option on the command line
- cmd.setOpt( opt );
- }
-
- /**
- * Ensures that all required options are present.
- *
- * @throws ParseException if all of the required options
- * are not present.
- */
- private void checkRequiredOptions( )
- throws ParseException {
-
- // if there are required options that have not been
- // processsed
- if( requiredOptions.size() > 0 ) {
- Iterator iter = requiredOptions.values().iterator();
- StringBuffer buff = new StringBuffer();
-
- // loop through the required options
- while( iter.hasNext() ) {
- Option missing = (Option)iter.next();
- buff.append( "-" );
- buff.append( missing.getOpt() );
- buff.append( " " );
- buff.append( missing.getDescription() );
- }
-
- // throw the MissingOptionException
- throw new MissingOptionException( buff.toString() );
- }
- }
-
}
1.8 +84 -284 jakarta-commons/cli/src/java/org/apache/commons/cli/PosixParser.java
Index: PosixParser.java
===================================================================
RCS file: /home/cvs/jakarta-commons/cli/src/java/org/apache/commons/cli/PosixParser.java,v
retrieving revision 1.7
retrieving revision 1.8
diff -u -r1.7 -r1.8
--- PosixParser.java 15 Aug 2002 22:05:18 -0000 1.7
+++ PosixParser.java 24 Aug 2002 22:15:31 -0000 1.8
@@ -1,337 +1,137 @@
-/*
- * $Header$
- * $Revision$
- * $Date$
- *
- * ====================================================================
- *
- * The Apache Software License, Version 1.1
- *
- * Copyright (c) 1999-2001 The Apache Software Foundation. All rights
- * reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in
- * the documentation and/or other materials provided with the
- * distribution.
- *
- * 3. The end-user documentation included with the redistribution, if
- * any, must include the following acknowlegement:
- * "This product includes software developed by the
- * Apache Software Foundation (http://www.apache.org/)."
- * Alternately, this acknowlegement may appear in the software itself,
- * if and wherever such third-party acknowlegements normally appear.
- *
- * 4. The names "The Jakarta Project", "Commons", and "Apache Software
- * Foundation" must not be used to endorse or promote products derived
- * from this software without prior written permission. For written
- * permission, please contact apache@apache.org.
- *
- * 5. Products derived from this software may not be called "Apache"
- * nor may "Apache" appear in their names without prior written
- * permission of the Apache Group.
- *
- * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
- * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
- * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
- * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
- * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- * ====================================================================
- *
- * This software consists of voluntary contributions made by many
- * individuals on behalf of the Apache Software Foundation. For more
- * information on the Apache Software Foundation, please see
- * <http://www.apache.org/>.
- *
- */
package org.apache.commons.cli;
import java.util.Arrays;
+import java.util.ArrayList;
import java.util.Collection;
-import java.util.ListIterator;
-import java.util.Map;
import java.util.Iterator;
+import java.util.Map;
/**
- * PosixParser parses the command line arguments using the Posix style.
- * For example, -buildfile can only be interpreted as the option
- * 'b' with value 'uildfile' or it could be interpreted as the options
- * 'b','u','i','l','d','f','i','l','e'.
- *
* @author John Keyes (jbjk at mac.com)
*/
-public class PosixParser implements CommandLineParser {
+public class PosixParser extends Parser {
- /** current options instance */
+ private ArrayList tokens = new ArrayList();
+ private boolean eatTheRest;
+ private Option currentOption;
private Options options;
- /** convience member for the command line */
- private CommandLine cmd;
-
- /** required options subset of options */
- private Map requiredOptions;
-
- /**
- * Parse the arguments according to the specified options.
- *
- * @param options the specified Options
- * @param arguments the command line arguments
- * @return the list of atomic option and value tokens
- * @throws ParseException if there are any problems encountered
- * while parsing the command line tokens.
- */
- public CommandLine parse( Options options, String[] arguments )
- throws ParseException
- {
- return parse( options, arguments, false );
+ private void init() {
+ eatTheRest = false;
+ tokens.clear();
+ currentOption = null;
}
- /**
- * Parse the arguments according to the specified options.
- *
- * @param opts the specified Options
- * @param arguments the command line arguments
- * @param stopAtNonOption specifies whether to continue parsing the
- * arguments if a non option is encountered.
- * @return the CommandLine
- * @throws ParseException if there are any problems encountered
- * while parsing the command line tokens.
- */
- public CommandLine parse( Options opts, String[] arguments, boolean stopAtNonOption )
- throws ParseException
+ protected String[] flatten( Options options,
+ String[] arguments,
+ boolean stopAtNonOption )
{
- // set the member instances
- options = opts;
- cmd = new CommandLine();
- requiredOptions = options.getRequiredOptions();
+ init();
+ this.options = options;
// an iterator for the command line tokens
- ListIterator iter = Arrays.asList( arguments ).listIterator();
+ Iterator iter = Arrays.asList( arguments ).iterator();
String token = null;
- // flag to indicate whether the remainder of the tokens should
- // be added to the other arguments list
- boolean eatTheRest = false;
-
// process each command line token
while ( iter.hasNext() ) {
// get the next command line token
token = (String) iter.next();
-
- // Look for -- to indicate end-of-options, and
- // just stuff it, along with everything past it
- // into the returned list.
- if ( token.equals("--") ) {
- eatTheRest = true;
- }
- else if ( token.startsWith("--") ) {
- // process the long-option
- processOption( token, iter );
- }
- else if ( token.startsWith("-") ) {
- // it might be a short arg needing some bursting
- if ( token.length() == 1) {
- // not an option, so just drop it on the argument list
- if ( stopAtNonOption ) {
- eatTheRest = true;
- }
- else {
- cmd.addArg( token );
- }
- }
- else if ( token.length() == 2 ) {
- processOption( token, iter );
+
+ // handle SPECIAL TOKEN
+ if( token.startsWith( "--" ) ) {
+ tokens.add( token );
+ }
+ // single hyphen
+ else if( "-".equals( token ) ) {
+ processSingleHyphen( token );
+ }
+ else if( token.startsWith( "-" ) ) {
+ int tokenLength = token.length();
+ if( tokenLength == 2 ) {
+ processOptionToken( token, stopAtNonOption );
}
+ // requires bursting
else {
- // Needs bursting. Figure out if we have multiple
- // options, or maybe an option plus an arg, or some
- // combination thereof.
-
- // iterate over each character in the token
- for ( int i = 1 ; i < token.length() ; ++i ) {
-
- String argname = String.valueOf( token.charAt(i) );
- // retrieve the associated option
- boolean hasOption = options.hasOption( argname );
-
- Option opt = null;
-
- // if there is an associated option
- if ( hasOption ) {
- opt = options.getOption( argname );
-
- // if the option requires an argument value
- if ( opt.hasArg() ) {
- // consider the rest of the token
- // to be the argument value
-
- // if there is no argument value
- if( token.substring(i+1).length() == 0 && !opt.hasOptionalArg() ) {
- throw new MissingArgumentException( "Missing argument value for " + opt.getOpt() );
- }
- else {
- opt.addValue( token.substring(i+1) );
- }
-
- // set the option
- cmd.setOpt( opt );
-
- // don't process any more characters
- break;
- }
-
- // if the option does not require an argument
- cmd.setOpt( opt );
- }
- // this is an unrecognized option
- else {
- throw new UnrecognizedOptionException( String.valueOf( token.charAt(i) ) );
- }
- }
+ burstToken( token, stopAtNonOption );
}
}
else {
- // It's just a normal non-option arg, so dump it into the
- // list of returned values.
- cmd.addArg( token );
-
- if ( stopAtNonOption ) {
- eatTheRest = true;
+ if( stopAtNonOption ) {
+ process( token );
}
- }
-
- // add all unprocessed tokens to the arg list
- if ( eatTheRest ) {
- while ( iter.hasNext() ) {
- cmd.addArg( (String)iter.next() );
+ else {
+ tokens.add( token );
}
}
+
+ gobble( iter );
}
-
- // see if all required options have been processed
- checkRequiredOptions( );
- // return the CommandLine instance
- return cmd;
+ return (String[])tokens.toArray( new String[] {} );
}
- /**
- * Process the option represented by <code>arg</code>.
- *
- * @param arg the string representation of an option
- * @param iter the command line token iterator
- */
- private void processOption( String arg, ListIterator iter )
- throws ParseException
- {
- // get the option represented by arg
- Option opt = null;
-
- boolean hasOption = options.hasOption( arg );
+ private void gobble( Iterator iter ) {
+ if( eatTheRest ) {
+ while( iter.hasNext() ) {
+ tokens.add( iter.next() );
+ }
+ }
+ }
- // if there is no option throw an UnrecognisedOptionException
- if( !hasOption ) {
- throw new UnrecognizedOptionException("Unrecognized option: " + arg);
+ private void process( String value ) {
+ if( currentOption != null && currentOption.hasArg() ) {
+ if( currentOption.hasArg() ) {
+ tokens.add( value );
+ currentOption = null;
+ }
+ else if (currentOption.hasArgs() ) {
+ tokens.add( value );
+ }
}
else {
- opt = (Option) options.getOption( arg );
+ eatTheRest = true;
+ tokens.add( "--" );
+ tokens.add( value );
}
+ }
- // if the option is a required option remove the option from
- // the requiredOptions list
- if ( opt.isRequired() ) {
- requiredOptions.remove( "-" + opt.getOpt() );
- }
+ private void processSingleHyphen( String hyphen ) {
+ tokens.add( hyphen );
+ }
- // if the option is in an OptionGroup make that option the selected
- // option of the group
- if ( options.getOptionGroup( opt ) != null ) {
- ( (OptionGroup)( options.getOptionGroup( opt ) ) ).setSelected( opt );
+ private void processOptionToken( String token, boolean stop ) {
+ if( this.options.hasOption( token ) ) {
+ currentOption = this.options.getOption( token );
+ tokens.add( token );
}
-
- // if the option takes an argument value
- if ( opt.hasArg() ) {
- processArgs( opt, iter );
+ else if( stop ) {
+ eatTheRest = true;
}
-
- // set the option on the command line
- cmd.setOpt( opt );
}
- /**
- * It the option can accept multiple argument values then
- * keep adding values until the next option token is encountered.
- *
- * @param opt the specified option
- * @param iter the iterator over the command line tokens
- */
- public void processArgs( Option opt, ListIterator iter )
- throws ParseException
- {
- if( !iter.hasNext() && !opt.hasOptionalArg() ) {
- throw new MissingArgumentException( "no argument for:" + opt.getOpt() );
- }
- // loop until an option is found
- while( iter.hasNext() ) {
- String var = (String)iter.next();
-
- // its an option
- if( !var.equals( "-" ) && var.startsWith( "-" ) ) {
- // set the iterator pointer back a position
- iter.previous();
- break;
- }
- // its a value
- else {
- if( !opt.addValue( var ) ) {
- iter.previous();
+ private void burstToken( String token, boolean stop ) {
+ int tokenLength = token.length();
+
+ for( int i = 1; i < tokenLength; i++) {
+ String ch = String.valueOf( token.charAt( i ) );
+ boolean hasOption = options.hasOption( ch );
+
+ if( hasOption ) {
+ tokens.add( "-" + ch );
+ currentOption = options.getOption( ch );
+ if( currentOption.hasArg() && token.length()!=i+1 ) {
+ tokens.add( token.substring( i+1 ) );
break;
}
}
- }
- }
-
- /**
- * Ensures that all required options are present.
- *
- * @throws ParseException if all of the required options
- * are not present.
- */
- private void checkRequiredOptions( )
- throws ParseException {
-
- // if there are required options that have not been
- // processsed
- if( requiredOptions.size() > 0 ) {
- Iterator iter = requiredOptions.values().iterator();
- StringBuffer buff = new StringBuffer();
-
- // loop through the required options
- while( iter.hasNext() ) {
- Option missing = (Option)iter.next();
- buff.append( "-" );
- buff.append( missing.getOpt() );
- buff.append( " " );
- buff.append( missing.getDescription() );
+ else if( stop ) {
+ process( token.substring( i ) );
+ }
+ else {
+ tokens.add( "-" + ch );
}
-
- // throw the MissingOptionException
- throw new MissingOptionException( buff.toString() );
}
}
}
1.1 jakarta-commons/cli/src/java/org/apache/commons/cli/BasicParser.java
Index: BasicParser.java
===================================================================
package org.apache.commons.cli;
/**
* @author John Keyes (jbjk at mac.com)
*/
public class BasicParser extends Parser {
protected String[] flatten( Options options,
String[] arguments,
boolean stopAtNonOption )
{
return arguments;
}
}
1.1 jakarta-commons/cli/src/java/org/apache/commons/cli/Parser.java
Index: Parser.java
===================================================================
package org.apache.commons.cli;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
public abstract class Parser implements CommandLineParser {
private CommandLine cmd;
private Options options;
private Map requiredOptions;
abstract protected String[] flatten( Options opts,
String[] args,
boolean stopAtNonOption );
public CommandLine parse( Options opts, String[] args )
throws ParseException
{
return parse( opts, args, false );
}
public CommandLine parse( Options opts,
String[] args,
boolean stopAtNonOption )
throws ParseException
{
options = opts;
requiredOptions = options.getRequiredOptions();
String[] tokens = flatten( opts, args, stopAtNonOption );
List tokenList = Arrays.asList( tokens );
ListIterator iterator = tokenList.listIterator();
cmd = new CommandLine();
boolean eatTheRest = false;
while( iterator.hasNext() ) {
String t = (String)iterator.next();
if( "--".equals( t ) ) {
eatTheRest = true;
}
else if( t.startsWith( "-" ) ) {
if( t.length() == 1 ) {
// not an option, so just drop it on the argument list
if ( stopAtNonOption ) {
eatTheRest = true;
}
else {
cmd.addArg( t );
}
}
else {
processOption( t, iterator );
}
}
else {
cmd.addArg( t );
if( stopAtNonOption ) {
eatTheRest = true;
}
}
if( eatTheRest ) {
while( iterator.hasNext() ) {
cmd.addArg( (String)iterator.next() );
}
}
}
checkRequiredOptions();
return cmd;
}
private void checkRequiredOptions( )
throws ParseException {
// if there are required options that have not been
// processsed
if( requiredOptions.size() > 0 ) {
Iterator iter = requiredOptions.values().iterator();
StringBuffer buff = new StringBuffer();
// loop through the required options
while( iter.hasNext() ) {
Option missing = (Option)iter.next();
buff.append( "-" );
buff.append( missing.getOpt() );
buff.append( " " );
buff.append( missing.getDescription() );
}
// throw the MissingOptionException
throw new MissingOptionException( buff.toString() );
}
}
public void processArgs( Option opt, ListIterator iter )
throws ParseException
{
if( !iter.hasNext() && !opt.hasOptionalArg() ) {
throw new MissingArgumentException( "no argument for:" + opt.getOpt() );
}
// loop until an option is found
while( iter.hasNext() ) {
String var = (String)iter.next();
if( options.hasOption( var ) ) {
iter.previous();
break;
}
// its a value
else {
if( !opt.addValue( var ) ) {
iter.previous();
break;
}
}
}
}
private void processOption( String arg, ListIterator iter )
throws ParseException
{
// get the option represented by arg
Option opt = null;
boolean hasOption = options.hasOption( arg );
// if there is no option throw an UnrecognisedOptionException
if( !hasOption ) {
throw new UnrecognizedOptionException("Unrecognized option: " + arg);
}
else {
opt = (Option) options.getOption( arg );
}
// if the option is a required option remove the option from
// the requiredOptions list
if ( opt.isRequired() ) {
requiredOptions.remove( "-" + opt.getOpt() );
}
// if the option is in an OptionGroup make that option the selected
// option of the group
if ( options.getOptionGroup( opt ) != null ) {
( (OptionGroup)( options.getOptionGroup( opt ) ) ).setSelected( opt );
}
// if the option takes an argument value
if ( opt.hasArg() ) {
processArgs( opt, iter );
}
// set the option on the command line
cmd.setOpt( opt );
}
}
--
To unsubscribe, e-mail: <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>