[jargs] 01/07: Imported Upstream version 1.0.0

Tony Mancill tmancill at moszumanska.debian.org
Sat Mar 1 06:10:24 UTC 2014


This is an automated email from the git hooks/post-receive script.

tmancill pushed a commit to branch master
in repository jargs.

commit 002d128f8df947f5e8812797c529cf49f8870016
Author: tony mancill <tmancill at debian.org>
Date:   Fri Feb 28 21:36:39 2014 -0800

    Imported Upstream version 1.0.0
---
 .cvsignore                                         |   5 +
 LICENCE                                            |  29 ++
 README                                             |  60 +++
 TODO                                               |   4 +
 build.xml                                          |  93 ++++
 doc/.cvsignore                                     |   1 +
 doc/CHANGES                                        |  66 +++
 src/jargs/examples/gnu/AutoHelpParser.java         |  87 ++++
 src/jargs/examples/gnu/CustomOptionTest.java       |  73 +++
 .../examples/gnu/OptionParserSubclassTest.java     |  71 +++
 src/jargs/examples/gnu/OptionTest.java             | 139 ++++++
 src/jargs/gnu/CmdLineParser.java                   | 526 +++++++++++++++++++++
 src/jargs/test/gnu/AllTests.java                   |  12 +
 src/jargs/test/gnu/CmdLineParserTestCase.java      | 252 ++++++++++
 src/jargs/test/gnu/CustomOptionTestCase.java       |  71 +++
 15 files changed, 1489 insertions(+)

diff --git a/.cvsignore b/.cvsignore
new file mode 100644
index 0000000..3deafee
--- /dev/null
+++ b/.cvsignore
@@ -0,0 +1,5 @@
+classes
+.classpath
+.project
+jargs.ipr
+jargs.iws
diff --git a/LICENCE b/LICENCE
new file mode 100644
index 0000000..509c1b7
--- /dev/null
+++ b/LICENCE
@@ -0,0 +1,29 @@
+Copyright (c) 2001-2003 Steve Purcell.
+Copyright (c) 2002      Vidar Holen.
+Copyright (c) 2002      Michal Ceresna.
+Copyright (c) 2005      Ewan Mellor.
+
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met: Redistributions of source code must retain the above copyright notice,
+this list of conditions and the following disclaimer. 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. Neither the name of the copyright
+holder nor the names of its contributors may be used to endorse or promote
+products derived from this software without specific prior written
+permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS 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 COPYRIGHT HOLDERS OR 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.
diff --git a/README b/README
new file mode 100644
index 0000000..8ef5e96
--- /dev/null
+++ b/README
@@ -0,0 +1,60 @@
+JArgs command-line argument parsing library
+===========================================
+
+Copyright (c) 2001-2003 Steve Purcell.
+Copyright (c) 2002      Vidar Holen.
+Copyright (c) 2002      Michal Ceresna.
+Copyright (c) 2005      Ewan Mellor.
+
+All rights reserved.
+
+Released under the terms of the BSD licence.  See the file LICENCE for
+details.
+
+
+Prerequisites
+-------------
+
+For each prerequisite, the version with which JArgs has been tested is given 
+in parentheses.  Any version equal to or later than this should work.
+
+Apache Ant (1.4.1), by The Apache Software Foundation, from
+http://ant.apache.org/.  Ant is used to build JArgs, and to run its tests.
+
+JUnit (3.7), by Eric Gamma, et al, from http://sourceforge.net/projects/junit.
+JUnit is used to run the unit tests, and is not needed to run the library
+itself.
+
+
+Installation
+------------
+
+To compile, package, and test the code, run
+
+ant
+
+Two jars are created, one called lib/jargs.jar, which contains the runtime
+library, and one called lib/jargs-test.jar, which contains the unit tests and
+the examples.  The Javadoc APIs are created in doc/api.
+
+To use the library with your own code, simply ensure that lib/jargs.jar is on
+the CLASSPATH.
+
+
+Documentation
+-------------
+
+The main documentation is the detailed worked example in
+src/jargs/examples/gnu/OptionTest.java, plus the generated API documentation
+in doc/api/.
+
+
+Package contents
+----------------
+
+  src/jargs/gnu          -- The library itself.
+  src/jargs/examples/gnu -- Examples showing how to use the library.
+  src/jargs/test/gnu     -- JUnit tests.
+  doc/                   -- API and other documentation.
+  classes/               -- Compiled classes, once built.
+  lib/                   -- JArgs jars, once built.
diff --git a/TODO b/TODO
new file mode 100644
index 0000000..90ccc3c
--- /dev/null
+++ b/TODO
@@ -0,0 +1,4 @@
+JArgs to-do list
+================
+
+Nothing!  (Fate, consider yourself tempted.)
diff --git a/build.xml b/build.xml
new file mode 100644
index 0000000..c6bc60e
--- /dev/null
+++ b/build.xml
@@ -0,0 +1,93 @@
+<project default="build" basedir=".">
+   <property name="Name" value="Jargs"/>
+   <property name="debug" value="on"/>
+   <property name="build.src" value="src"/>
+   <property name="build.classes" value="classes"/>
+   <property name="source-version" value="1.2" />
+   <property name="jdk-version" value="1.1" />
+   <property name="javadoc.outdir" value="doc/api"/>
+   <property name="javadoc.doctitle" value="JArgs command line option parsing library"/>
+   <property name="javadoc.header" value='For updates and more see <a target="_top" href="http://jargs.sourceforge.net/">jargs.sourceforge.net</a>'/>
+   <property name="javadoc.bottom" value='Copyright &copy; 2001-2003 Steve
+Purcell. Copyright &copy; 2002 Vidar Holen.  Copyright &copy; 2002 Michal Ceresna.  Copyright &copy; 2005 Ewan Mellor.  Released under the terms of the BSD licence.'/>
+   <property name="javadoc.packages" value="jargs.gnu"/>
+   <property name="junit.jar" value="/usr/share/java/junit.jar"/>
+
+   <target name="build" description="Build and test Jargs."
+           depends="compile,jars,javadoc,test" />
+
+   <target name="compile">
+      <mkdir dir="classes"/>
+      <javac srcdir="${build.src}" destdir="${build.classes}" debug="${debug}"
+             source="${source-version}" target="${jdk-version}">
+          <classpath path="${build.classes}:${junit.jar}:${java.class.path}"/>
+      </javac>
+   </target>
+
+   <target name="jars" depends="runtimejar,testjar" />
+
+   <target name="runtimejar" depends="compile">
+      <mkdir dir="dist"/>
+      <mkdir dir="lib"/>
+      <copy todir="dist">
+	      <fileset dir="classes"/>
+      </copy>
+      <delete dir="dist/jargs/examples"/>
+      <delete dir="dist/jargs/test"/>
+      <jar jarfile="lib/jargs.jar" basedir="dist"/>
+      <delete dir="dist"/>
+   </target>
+
+   <target name="testjar" depends="compile">
+      <mkdir dir="dist"/>
+      <mkdir dir="lib"/>
+      <copy todir="dist">
+	      <fileset dir="classes"/>
+      </copy>
+      <delete dir="dist/jargs/gnu"/>
+      <jar jarfile="lib/jargs-test.jar" basedir="dist"/>
+      <delete dir="dist"/>
+   </target>
+
+   <target name="test" depends="compile">
+      <java classname="junit.textui.TestRunner"
+       classpath="${build.classes}:${junit.jar}:${java.class.path}">
+         <arg value="jargs.test.gnu.AllTests"/>
+      </java>
+   </target>
+
+   <target name="testgui" depends="compile">
+      <java classname="junit.swingui.TestRunner" fork="true"
+       classpath="${build.classes}:${junit.jar}:${java.class.path}">
+         <arg value="jargs.test.gnu.AllTests"/>
+      </java>
+   </target>
+
+   <target name="clean"
+           description="Remove all generated files.">
+      <delete dir="dist" />
+      <delete dir="classes" />
+      <delete dir="${javadoc.outdir}" />
+      <delete file="lib/jargs.jar" />
+      <delete file="lib/jargs-test.jar" />
+   </target>
+
+   <target name="javadoc">
+      <mkdir dir="${javadoc.outdir}"/>
+         <javadoc
+             sourcepath="${build.src}"
+             protected="true"
+             destdir="${javadoc.outdir}"
+             author="true"
+             version="true"
+             use="true"
+             windowtitle="${javadoc.doctitle}"
+             doctitle="${javadoc.doctitle}"
+             header="${javadoc.header}"
+             footer="${javadoc.header}"
+             bottom="${javadoc.bottom}">
+             <package name="**.*" />
+         </javadoc>
+  </target>
+
+</project>
diff --git a/doc/.cvsignore b/doc/.cvsignore
new file mode 100644
index 0000000..eedd89b
--- /dev/null
+++ b/doc/.cvsignore
@@ -0,0 +1 @@
+api
diff --git a/doc/CHANGES b/doc/CHANGES
new file mode 100644
index 0000000..a05c4b4
--- /dev/null
+++ b/doc/CHANGES
@@ -0,0 +1,66 @@
+Changes from 0.5 to 1.0
+=======================
+
+- Added getOptionValue(Option, Object) which takes an Object as a potential
+  default value for the given Option.  If the option is not present on the
+  command line, the default is returned instead.  This addresses bug 1051346
+  submitted by Tomas Znamenacek, and feature request 527808.
+
+- Added getOptionValues(Option) which will return a list of occurrences of a
+  single option, and added the ability internally to cope with such multiple
+  occurrences.  This accepts and uses patch 1164413, and closes patch 1083615
+  (it solves the same problem in a better way).
+
+- Added support for concatenated boolean options (those written -bcd where -b,
+  -c, and -d are boolean options).  This accepts and uses patch 621087 by
+  Vidar Holen.
+
+- Added some more unit tests.
+
+- Some code clean-ups.
+
+Changes from 0.4 to 0.5
+=======================
+
+- Allow Options that have a long form only
+
+- Added LongOption
+
+- Corrected some typos in example code (thanks Chris McKay)
+
+- More tests
+
+Changes from 0.3 to 0.4
+=======================
+
+- Switched from makefiles to Ant
+
+- Some code clean-ups
+
+- Support locale-dependent parsing of Double options
+
+Changes from 0.2 to 0.3
+=======================
+
+- Added 'DoubleOption' class, and 'addDoubleOption()' convenience method
+  (suggested independently by Nick Roy and Karl Koster)
+
+- Made 'Option.getValue()' and 'Option.parseValue()' take a Locale, so
+  that parsing of values can be locale-dependent. (Locale-specific parsing
+  is not however implemented for DoubleOption and IntegerOption.)
+
+- Constructor of 'IllegalOptionValueException' is now public so that it can
+  be thrown by the 'parseValue()' methods of custom Option subclasses
+
+- 'CmdLineParser.addOption()' now returns the passed in Option, which
+  can make client code less clunky.
+
+- Added 'DoubleOption' to example classes
+
+- Added a 'CustomOptionTest' class to demonstrate subclassing of Option
+  via the implementation of a ShortDateOption class.
+
+- Added this CHANGES file.
+
+- Added overridden CmdLineParser.parse() which takes a Locale instance,
+  and made both versions of the method final.
diff --git a/src/jargs/examples/gnu/AutoHelpParser.java b/src/jargs/examples/gnu/AutoHelpParser.java
new file mode 100644
index 0000000..f42ec5f
--- /dev/null
+++ b/src/jargs/examples/gnu/AutoHelpParser.java
@@ -0,0 +1,87 @@
+package jargs.examples.gnu;
+
+import jargs.gnu.CmdLineParser;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * This example shows how to dynamically create basic output for a --help option. 
+ */
+public class AutoHelpParser extends CmdLineParser {
+	List optionHelpStrings = new ArrayList();
+
+	public Option addHelp(Option option, String helpString) {
+		optionHelpStrings.add(" -" + option.shortForm() + "/--" + option.longForm() + ": " + helpString);
+		return option;
+	}
+	
+	public void printUsage() {
+        System.err.println("usage: prog [options]");
+        for (Iterator i = optionHelpStrings.iterator(); i.hasNext(); ) {
+        	System.err.println(i.next());
+        }
+    }
+
+    public static void main( String[] args ) {
+    	AutoHelpParser parser = new AutoHelpParser();
+    	CmdLineParser.Option verbose = parser.addHelp(
+    			parser.addBooleanOption('v', "verbose"),
+    			"Print extra information");
+        CmdLineParser.Option size = parser.addHelp(
+        		parser.addIntegerOption('s', "size"),
+				"The extent of the thing");
+        CmdLineParser.Option name = parser.addHelp(
+        		parser.addStringOption('n', "name"),
+				"Name given to the widget");
+        CmdLineParser.Option fraction = parser.addHelp(
+        		parser.addDoubleOption('f', "fraction"),
+				"What percentage should be discarded");
+        CmdLineParser.Option help = parser.addHelp(
+        		parser.addBooleanOption('h', "help"),
+				"Show this help message");
+
+        try {
+            parser.parse(args);
+        }
+        catch ( CmdLineParser.OptionException e ) {
+            System.err.println(e.getMessage());
+            parser.printUsage();
+            System.exit(2);
+        }
+
+        if ( Boolean.TRUE.equals(parser.getOptionValue(help))) {
+            parser.printUsage();
+            System.exit(0);
+        }
+
+        // Extract the values entered for the various options -- if the
+        // options were not specified, the corresponding values will be
+        // null.
+        Boolean verboseValue = (Boolean)parser.getOptionValue(verbose);
+        Integer sizeValue = (Integer)parser.getOptionValue(size);
+        String nameValue = (String)parser.getOptionValue(name);
+        Double fractionValue = (Double)parser.getOptionValue(fraction);
+
+        // For testing purposes, we just print out the option values
+        System.out.println("verbose: " + verboseValue);
+        System.out.println("size: " + sizeValue);
+        System.out.println("name: " + nameValue);
+        System.out.println("fraction: " + fractionValue);
+
+        // Extract the trailing command-line arguments ('a_nother') in the
+        // usage string above.
+        String[] otherArgs = parser.getRemainingArgs();
+        System.out.println("remaining args: ");
+        for ( int i = 0; i < otherArgs.length; ++i ) {
+            System.out.println(otherArgs[i]);
+        }
+
+        // In a real program, one would pass the option values and other
+        // arguments to a function that does something more useful.
+
+        System.exit(0);
+    }
+
+}
diff --git a/src/jargs/examples/gnu/CustomOptionTest.java b/src/jargs/examples/gnu/CustomOptionTest.java
new file mode 100644
index 0000000..2a1c45f
--- /dev/null
+++ b/src/jargs/examples/gnu/CustomOptionTest.java
@@ -0,0 +1,73 @@
+package jargs.examples.gnu;
+
+import jargs.gnu.CmdLineParser;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.util.Locale;
+import java.util.Date;
+
+public class CustomOptionTest {
+
+    private static void printUsage() {
+        System.err.println("usage: prog [{-d,--date} date]");
+    }
+
+
+    /**
+     * A custom type of command line option corresponding to a short
+     * date value, e.g. .
+     */
+    public static class ShortDateOption extends CmdLineParser.Option {
+        public ShortDateOption( char shortForm, String longForm ) {
+            super(shortForm, longForm, true);
+        }
+        protected Object parseValue( String arg, Locale locale )
+            throws CmdLineParser.IllegalOptionValueException {
+            try {
+                DateFormat dateFormat =
+                    DateFormat.getDateInstance(DateFormat.SHORT, locale);
+                return dateFormat.parse(arg);
+            }
+            catch (ParseException e) {
+                throw new CmdLineParser.IllegalOptionValueException(this, arg);
+            }
+        }
+    }
+
+    public static void main( String[] args ) {
+        CmdLineParser parser = new CmdLineParser();
+        CmdLineParser.Option date =
+            parser.addOption(new ShortDateOption('d', "date"));
+
+        try {
+            parser.parse(args);
+        }
+        catch ( CmdLineParser.OptionException e ) {
+            System.err.println(e.getMessage());
+            printUsage();
+            System.exit(2);
+        }
+
+        // Extract the values entered for the various options -- if the
+        // options were not specified, the corresponding values will be
+        // null.
+        Date dateValue = (Date)parser.getOptionValue(date);
+
+        // For testing purposes, we just print out the option values
+        System.out.println("date: " + dateValue);
+
+        // Extract the trailing command-line arguments ('a_number') in the
+        // usage string above.
+        String[] otherArgs = parser.getRemainingArgs();
+        System.out.println("remaining args: ");
+        for ( int i = 0; i < otherArgs.length; ++i ) {
+            System.out.println(otherArgs[i]);
+        }
+
+        // In a real program, one would pass the option values and other
+        // arguments to a function that does something more useful.
+
+        System.exit(0);
+    }
+
+}
diff --git a/src/jargs/examples/gnu/OptionParserSubclassTest.java b/src/jargs/examples/gnu/OptionParserSubclassTest.java
new file mode 100644
index 0000000..551abf1
--- /dev/null
+++ b/src/jargs/examples/gnu/OptionParserSubclassTest.java
@@ -0,0 +1,71 @@
+package jargs.examples.gnu;
+
+import jargs.gnu.CmdLineParser;
+
+public class OptionParserSubclassTest {
+
+    private static class MyOptionsParser extends CmdLineParser {
+
+        public static final Option VERBOSE = new
+            CmdLineParser.Option.BooleanOption('v',"verbose");
+
+        public static final Option SIZE = new
+            CmdLineParser.Option.IntegerOption('s',"size");
+
+        public static final Option NAME = new
+            CmdLineParser.Option.StringOption('n',"name");
+
+        public static final Option FRACTION = new
+            CmdLineParser.Option.DoubleOption('f',"fraction");
+
+        public MyOptionsParser() {
+            super();
+            addOption(VERBOSE);
+            addOption(SIZE);
+            addOption(NAME);
+            addOption(FRACTION);
+        }
+    }
+
+    private static void printUsage() {
+        System.err.println("usage: prog [{-v,--verbose}] [{-n,--name} a_name]"+
+                           "[{-s,--size} a_number] [{-f,--fraction} a_float]");
+    }
+
+    public static void main( String[] args ) {
+        MyOptionsParser myOptions = new MyOptionsParser();
+
+        try {
+            myOptions.parse(args);
+        }
+        catch ( CmdLineParser.UnknownOptionException e ) {
+            System.err.println(e.getMessage());
+            printUsage();
+            System.exit(2);
+        }
+        catch ( CmdLineParser.IllegalOptionValueException e ) {
+            System.err.println(e.getMessage());
+            printUsage();
+            System.exit(2);
+        }
+
+        CmdLineParser.Option[] allOptions =
+            new CmdLineParser.Option[] { MyOptionsParser.VERBOSE,
+                                         MyOptionsParser.NAME,
+                                         MyOptionsParser.SIZE,
+                                         MyOptionsParser.FRACTION };
+
+        for ( int j = 0; j<allOptions.length; ++j ) {
+            System.out.println(allOptions[j].longForm() + ": " +
+                               myOptions.getOptionValue(allOptions[j]));
+        }
+
+        String[] otherArgs = myOptions.getRemainingArgs();
+        System.out.println("remaining args: ");
+        for ( int i = 0; i<otherArgs.length; ++i ) {
+            System.out.println(otherArgs[i]);
+        }
+        System.exit(0);
+    }
+
+}
diff --git a/src/jargs/examples/gnu/OptionTest.java b/src/jargs/examples/gnu/OptionTest.java
new file mode 100644
index 0000000..9b38b04
--- /dev/null
+++ b/src/jargs/examples/gnu/OptionTest.java
@@ -0,0 +1,139 @@
+package jargs.examples.gnu;
+
+import java.util.Enumeration;
+import java.util.Vector;
+
+import jargs.gnu.CmdLineParser;
+
+
+public class OptionTest {
+
+    private static void printUsage() {
+        System.err.println(
+"Usage: OptionTest [-d,--debug] [{-v,--verbose}] [{--alt}] [{--name} a_name]\n" +
+"                  [{-s,--size} a_number] [{-f,--fraction} a_float] [a_nother]");
+    }
+
+    public static void main( String[] args ) {
+
+        // First, you must create a CmdLineParser, and add to it the
+        // appropriate Options.
+
+        // To start with, we add the Options -d, -v, -s, and -f, with aliases
+        // --debug, --verbose, --size, and --fraction respectively.
+
+        // The -d and -v options have no associated value -- they are either
+        // present, or they are not.  The -s and -f options take integer and
+        // double-precision floating-point values respectively.
+
+        CmdLineParser parser = new CmdLineParser();
+        CmdLineParser.Option debug = parser.addBooleanOption('d', "debug");
+        CmdLineParser.Option verbose = parser.addBooleanOption('v', "verbose");
+        CmdLineParser.Option size = parser.addIntegerOption('s', "size");
+        CmdLineParser.Option fraction = parser.addDoubleOption('f', "fraction");
+
+        // Options may have just a long form with no corresponding short form.
+        // Here, we add --alt and --name options.
+
+        CmdLineParser.Option alt = parser.addBooleanOption("alt");
+        CmdLineParser.Option name = parser.addStringOption("name");
+
+
+        // Next, you must parse the user-provided command line arguments, and
+        // catch any errors therein.
+
+        // Options may appear on the command line in any order, and may even
+        // appear after some or all of the non-option arguments.
+
+        // If the user needs to specify non-option arguments that start with a
+        // minus, then they may indicate the end of the parsable options with
+        // -- , like this:
+
+        // prog -f 20 -- -10 -fred
+
+        // The -f 20 will be parsed as the fraction option, with the value 20.
+        // The -10 and -fred arguments will be regarded as non-option
+        // arguments, and passed through getRemainingArgs as unparsed Strings.
+
+        // Short boolean options may be specified separately (-d -v) or
+        // together (-dv).
+
+        // Options with values may be given on the command line as -f 1.0 or
+        // --fraction=1.0.
+
+        try {
+            parser.parse(args);
+        }
+        catch ( CmdLineParser.OptionException e ) {
+            System.err.println(e.getMessage());
+            printUsage();
+            System.exit(2);
+        }
+
+
+        // For options that may be specified only zero or one time, the value
+        // of that option may be extracted as shown below.  If the options
+        // were not specified, the corresponding values will be null.
+
+        Boolean debugValue = (Boolean)parser.getOptionValue(debug);
+        String nameValue = (String)parser.getOptionValue(name);
+
+        // Alternatively, you may specify a default value.  This will be
+        // returned (instead of null) when the command line argument is
+        // missing.
+
+        Boolean altValue =
+            (Boolean)parser.getOptionValue(alt, Boolean.FALSE);
+        Integer sizeValue =
+            (Integer)parser.getOptionValue(size, new Integer(42));
+
+        // If your application requires it, options may be specified more than
+        // once.  In this case, you may get all the values specified by the
+        // user, as a Vector:
+
+        Vector fractionValues = parser.getOptionValues(fraction);
+
+        // Alternatively, you may make the loop explicit:
+
+        int verbosity = 0;
+        while (true) {
+            Boolean verboseValue = (Boolean)parser.getOptionValue(verbose);
+
+            if (verboseValue == null) {
+                break;
+            }
+            else {
+                verbosity++;
+            }
+        }
+
+        // The remaining command-line arguments -- those that do not start
+        // with a minus sign -- can be captured like this:
+
+        String[] otherArgs = parser.getRemainingArgs();
+
+
+        // For testing purposes, we just print out the option values and
+        // remaining command-line arguments.  In a real program, of course,
+        // one would pass them to a function that does something more useful.
+
+        System.out.println("debug: " + debugValue);
+        System.out.println("alt: " + altValue);
+        System.out.println("size: " + sizeValue);
+        System.out.println("name: " + nameValue);
+
+        System.out.println("verbosity: " + verbosity);
+
+        Enumeration e = fractionValues.elements();
+        while (e.hasMoreElements()) {
+            System.out.println("fraction: " + (Double)e.nextElement());
+        }
+
+        System.out.println("remaining args: ");
+        for ( int i = 0; i < otherArgs.length; ++i ) {
+            System.out.println(otherArgs[i]);
+        }
+
+        System.exit(0);
+    }
+}
diff --git a/src/jargs/gnu/CmdLineParser.java b/src/jargs/gnu/CmdLineParser.java
new file mode 100644
index 0000000..eddc658
--- /dev/null
+++ b/src/jargs/gnu/CmdLineParser.java
@@ -0,0 +1,526 @@
+package jargs.gnu;
+
+import java.text.NumberFormat;
+import java.text.ParseException;
+import java.util.Hashtable;
+import java.util.Vector;
+import java.util.Enumeration;
+import java.util.Locale;
+
+/**
+ * Largely GNU-compatible command-line options parser. Has short (-v) and
+ * long-form (--verbose) option support, and also allows options with
+ * associated values (-d 2, --debug 2, --debug=2). Option processing
+ * can be explicitly terminated by the argument '--'.
+ *
+ * @author Steve Purcell
+ * @version $Revision: 1.10 $
+ * @see jargs.examples.gnu.OptionTest
+ */
+public class CmdLineParser {
+
+    /**
+     * Base class for exceptions that may be thrown when options are parsed
+     */
+    public static abstract class OptionException extends Exception {
+        OptionException(String msg) { super(msg); }
+    }
+
+    /**
+     * Thrown when the parsed command-line contains an option that is not
+     * recognised. <code>getMessage()</code> returns
+     * an error string suitable for reporting the error to the user (in
+     * English).
+     */
+    public static class UnknownOptionException extends OptionException {
+        UnknownOptionException( String optionName ) {
+            this(optionName, "Unknown option '" + optionName + "'");
+        }
+
+        UnknownOptionException( String optionName, String msg ) {
+            super(msg);
+            this.optionName = optionName;
+        }
+
+        /**
+         * @return the name of the option that was unknown (e.g. "-u")
+         */
+        public String getOptionName() { return this.optionName; }
+        private String optionName = null;
+    }
+
+    /**
+     * Thrown when the parsed commandline contains multiple concatenated
+     * short options, such as -abcd, where one is unknown.
+     * <code>getMessage()</code> returns an english human-readable error
+     * string.
+     * @author Vidar Holen
+     */
+    public static class UnknownSuboptionException
+        extends UnknownOptionException {
+        private char suboption;
+
+        UnknownSuboptionException( String option, char suboption ) {
+            super(option, "Illegal option: '"+suboption+"' in '"+option+"'");
+            this.suboption=suboption;
+        }
+        public char getSuboption() { return suboption; }
+    }
+
+    /**
+     * Thrown when the parsed commandline contains multiple concatenated
+     * short options, such as -abcd, where one or more requires a value.
+     * <code>getMessage()</code> returns an english human-readable error
+     * string.
+     * @author Vidar Holen
+     */
+    public static class NotFlagException extends UnknownOptionException {
+        private char notflag;
+
+        NotFlagException( String option, char unflaggish ) {
+            super(option, "Illegal option: '"+option+"', '"+
+                  unflaggish+"' requires a value");
+            notflag=unflaggish;
+        }
+
+        /**
+         * @return the first character which wasn't a boolean (e.g 'c')
+         */
+        public char getOptionChar() { return notflag; }
+    }
+
+    /**
+     * Thrown when an illegal or missing value is given by the user for
+     * an option that takes a value. <code>getMessage()</code> returns
+     * an error string suitable for reporting the error to the user (in
+     * English).
+     */
+    public static class IllegalOptionValueException extends OptionException {
+        public IllegalOptionValueException( Option opt, String value ) {
+            super("Illegal value '" + value + "' for option " +
+                  (opt.shortForm() != null ? "-" + opt.shortForm() + "/" : "") +
+                  "--" + opt.longForm());
+            this.option = opt;
+            this.value = value;
+        }
+
+        /**
+         * @return the name of the option whose value was illegal (e.g. "-u")
+         */
+        public Option getOption() { return this.option; }
+
+        /**
+         * @return the illegal value
+         */
+        public String getValue() { return this.value; }
+        private Option option;
+        private String value;
+    }
+
+    /**
+     * Representation of a command-line option
+     */
+    public static abstract class Option {
+
+        protected Option( String longForm, boolean wantsValue ) {
+            this(null, longForm, wantsValue);
+        }
+
+        protected Option( char shortForm, String longForm,
+                          boolean wantsValue ) {
+            this(new String(new char[]{shortForm}), longForm, wantsValue);
+        }
+
+        private Option( String shortForm, String longForm, boolean wantsValue ) {
+            if ( longForm == null )
+                throw new IllegalArgumentException("Null longForm not allowed");
+            this.shortForm = shortForm;
+            this.longForm = longForm;
+            this.wantsValue = wantsValue;
+        }
+
+        public String shortForm() { return this.shortForm; }
+
+        public String longForm() { return this.longForm; }
+
+        /**
+         * Tells whether or not this option wants a value
+         */
+        public boolean wantsValue() { return this.wantsValue; }
+
+        public final Object getValue( String arg, Locale locale )
+            throws IllegalOptionValueException {
+            if ( this.wantsValue ) {
+                if ( arg == null ) {
+                    throw new IllegalOptionValueException(this, "");
+                }
+                return this.parseValue(arg, locale);
+            }
+            else {
+                return Boolean.TRUE;
+            }
+        }
+
+        /**
+         * Override to extract and convert an option value passed on the
+         * command-line
+         */
+        protected Object parseValue( String arg, Locale locale )
+            throws IllegalOptionValueException {
+            return null;
+        }
+
+        private String shortForm = null;
+        private String longForm = null;
+        private boolean wantsValue = false;
+
+        public static class BooleanOption extends Option {
+            public BooleanOption( char shortForm, String longForm ) {
+                super(shortForm, longForm, false);
+            }
+            public BooleanOption( String longForm ) {
+                super(longForm, false);
+            }
+        }
+
+        /**
+         * An option that expects an integer value
+         */
+        public static class IntegerOption extends Option {
+            public IntegerOption( char shortForm, String longForm ) {
+                super(shortForm, longForm, true);
+            }
+            public IntegerOption( String longForm ) {
+                super(longForm, true);
+            }
+            protected Object parseValue( String arg, Locale locale )
+                throws IllegalOptionValueException {
+                try {
+                    return new Integer(arg);
+                }
+                catch (NumberFormatException e) {
+                    throw new IllegalOptionValueException(this, arg);
+                }
+            }
+        }
+
+        /**
+         * An option that expects a long integer value
+         */
+        public static class LongOption extends Option {
+            public LongOption( char shortForm, String longForm ) {
+                super(shortForm, longForm, true);
+            }
+            public LongOption( String longForm ) {
+                super(longForm, true);
+            }
+            protected Object parseValue( String arg, Locale locale )
+                throws IllegalOptionValueException {
+                try {
+                    return new Long(arg);
+                }
+                catch (NumberFormatException e) {
+                    throw new IllegalOptionValueException(this, arg);
+                }
+            }
+        }
+
+        /**
+         * An option that expects a floating-point value
+         */
+        public static class DoubleOption extends Option {
+            public DoubleOption( char shortForm, String longForm ) {
+                super(shortForm, longForm, true);
+            }
+            public DoubleOption( String longForm ) {
+                super(longForm, true);
+            }
+            protected Object parseValue( String arg, Locale locale )
+                throws IllegalOptionValueException {
+                try {
+                    NumberFormat format = NumberFormat.getNumberInstance(locale);
+                    Number num = (Number)format.parse(arg);
+                    return new Double(num.doubleValue());
+                }
+                catch (ParseException e) {
+                    throw new IllegalOptionValueException(this, arg);
+                }
+            }
+        }
+
+        /**
+         * An option that expects a string value
+         */
+        public static class StringOption extends Option {
+            public StringOption( char shortForm, String longForm ) {
+                super(shortForm, longForm, true);
+            }
+            public StringOption( String longForm ) {
+                super(longForm, true);
+            }
+            protected Object parseValue( String arg, Locale locale ) {
+                return arg;
+            }
+        }
+    }
+
+    /**
+     * Add the specified Option to the list of accepted options
+     */
+    public final Option addOption( Option opt ) {
+        if ( opt.shortForm() != null )
+            this.options.put("-" + opt.shortForm(), opt);
+        this.options.put("--" + opt.longForm(), opt);
+        return opt;
+    }
+
+    /**
+     * Convenience method for adding a string option.
+     * @return the new Option
+     */
+    public final Option addStringOption( char shortForm, String longForm ) {
+        return addOption(new Option.StringOption(shortForm, longForm));
+    }
+
+    /**
+     * Convenience method for adding a string option.
+     * @return the new Option
+     */
+    public final Option addStringOption( String longForm ) {
+        return addOption(new Option.StringOption(longForm));
+    }
+
+    /**
+     * Convenience method for adding an integer option.
+     * @return the new Option
+     */
+    public final Option addIntegerOption( char shortForm, String longForm ) {
+        return addOption(new Option.IntegerOption(shortForm, longForm));
+    }
+
+    /**
+     * Convenience method for adding an integer option.
+     * @return the new Option
+     */
+    public final Option addIntegerOption( String longForm ) {
+        return addOption(new Option.IntegerOption(longForm));
+    }
+
+    /**
+     * Convenience method for adding a long integer option.
+     * @return the new Option
+     */
+    public final Option addLongOption( char shortForm, String longForm ) {
+        return addOption(new Option.LongOption(shortForm, longForm));
+    }
+
+    /**
+     * Convenience method for adding a long integer option.
+     * @return the new Option
+     */
+    public final Option addLongOption( String longForm ) {
+        return addOption(new Option.LongOption(longForm));
+    }
+
+    /**
+     * Convenience method for adding a double option.
+     * @return the new Option
+     */
+    public final Option addDoubleOption( char shortForm, String longForm ) {
+        return addOption(new Option.DoubleOption(shortForm, longForm));
+    }
+
+    /**
+     * Convenience method for adding a double option.
+     * @return the new Option
+     */
+    public final Option addDoubleOption( String longForm ) {
+        return addOption(new Option.DoubleOption(longForm));
+    }
+
+    /**
+     * Convenience method for adding a boolean option.
+     * @return the new Option
+     */
+    public final Option addBooleanOption( char shortForm, String longForm ) {
+        return addOption(new Option.BooleanOption(shortForm, longForm));
+    }
+
+    /**
+     * Convenience method for adding a boolean option.
+     * @return the new Option
+     */
+    public final Option addBooleanOption( String longForm ) {
+        return addOption(new Option.BooleanOption(longForm));
+    }
+
+    /**
+     * Equivalent to {@link #getOptionValue(Option, Object) getOptionValue(o,
+     * null)}.
+     */
+    public final Object getOptionValue( Option o ) {
+        return getOptionValue(o, null);
+    }
+
+
+    /**
+     * @return the parsed value of the given Option, or null if the
+     * option was not set
+     */
+    public final Object getOptionValue( Option o, Object def ) {
+        Vector v = (Vector)values.get(o.longForm());
+
+        if (v == null) {
+            return def;
+        }
+        else if (v.isEmpty()) {
+            return null;
+        }
+        else {
+            Object result = v.elementAt(0);
+            v.removeElementAt(0);
+            return result;
+        }
+    }
+
+
+    /**
+     * @return A Vector giving the parsed values of all the occurrences of the
+     * given Option, or an empty Vector if the option was not set.
+     */
+    public final Vector getOptionValues( Option option ) {
+        Vector result = new Vector();
+
+        while (true) {
+            Object o = getOptionValue(option, null);
+
+            if (o == null) {
+                return result;
+            }
+            else {
+                result.addElement(o);
+            }
+        }
+    }
+
+
+    /**
+     * @return the non-option arguments
+     */
+    public final String[] getRemainingArgs() {
+        return this.remainingArgs;
+    }
+
+    /**
+     * Extract the options and non-option arguments from the given
+     * list of command-line arguments. The default locale is used for
+     * parsing options whose values might be locale-specific.
+     */
+    public final void parse( String[] argv )
+        throws IllegalOptionValueException, UnknownOptionException {
+
+        // It would be best if this method only threw OptionException, but for
+        // backwards compatibility with old user code we throw the two
+        // exceptions above instead.
+
+        parse(argv, Locale.getDefault());
+    }
+
+    /**
+     * Extract the options and non-option arguments from the given
+     * list of command-line arguments. The specified locale is used for
+     * parsing options whose values might be locale-specific.
+     */
+    public final void parse( String[] argv, Locale locale )
+        throws IllegalOptionValueException, UnknownOptionException {
+
+        // It would be best if this method only threw OptionException, but for
+        // backwards compatibility with old user code we throw the two
+        // exceptions above instead.
+
+        Vector otherArgs = new Vector();
+        int position = 0;
+        this.values = new Hashtable(10);
+        while ( position < argv.length ) {
+            String curArg = argv[position];
+            if ( curArg.startsWith("-") ) {
+                if ( curArg.equals("--") ) { // end of options
+                    position += 1;
+                    break;
+                }
+                String valueArg = null;
+                if ( curArg.startsWith("--") ) { // handle --arg=value
+                    int equalsPos = curArg.indexOf("=");
+                    if ( equalsPos != -1 ) {
+                        valueArg = curArg.substring(equalsPos+1);
+                        curArg = curArg.substring(0,equalsPos);
+                    }
+                } else if(curArg.length() > 2) {  // handle -abcd
+                    for(int i=1; i<curArg.length(); i++) {
+                        Option opt=(Option)this.options.get
+                            ("-"+curArg.charAt(i));
+                        if(opt==null) throw new 
+                            UnknownSuboptionException(curArg,curArg.charAt(i));
+                        if(opt.wantsValue()) throw new
+                            NotFlagException(curArg,curArg.charAt(i));
+                        addValue(opt, opt.getValue(null,locale));
+                        
+                    }
+                    position++;
+                    continue;
+                }
+                
+                Option opt = (Option)this.options.get(curArg);
+                if ( opt == null ) {
+                    throw new UnknownOptionException(curArg);
+                }
+                Object value = null;
+                if ( opt.wantsValue() ) {
+                    if ( valueArg == null ) {
+                        position += 1;
+                        if ( position < argv.length ) {
+                            valueArg = argv[position];
+                        }
+                    }
+                    value = opt.getValue(valueArg, locale);
+                }
+                else {
+                    value = opt.getValue(null, locale);
+                }
+
+                addValue(opt, value);
+
+                position += 1;
+            }
+            else {
+                otherArgs.addElement(curArg);
+                position += 1;
+            }
+        }
+        for ( ; position < argv.length; ++position ) {
+            otherArgs.addElement(argv[position]);
+        }
+
+        this.remainingArgs = new String[otherArgs.size()];
+        otherArgs.copyInto(remainingArgs);
+    }
+
+
+    private void addValue(Option opt, Object value) {
+        String lf = opt.longForm();
+
+        Vector v = (Vector)values.get(lf);
+
+        if (v == null) {
+            v = new Vector();
+            values.put(lf, v);
+        }
+
+        v.addElement(value);
+    }
+
+
+    private String[] remainingArgs = null;
+    private Hashtable options = new Hashtable(10);
+    private Hashtable values = new Hashtable(10);
+}
diff --git a/src/jargs/test/gnu/AllTests.java b/src/jargs/test/gnu/AllTests.java
new file mode 100644
index 0000000..09aadb9
--- /dev/null
+++ b/src/jargs/test/gnu/AllTests.java
@@ -0,0 +1,12 @@
+package jargs.test.gnu;
+
+import junit.framework.TestSuite;
+
+public class AllTests {
+    public static TestSuite suite() {
+        TestSuite s = new TestSuite();
+        s.addTestSuite(CmdLineParserTestCase.class);
+        s.addTestSuite(CustomOptionTestCase.class);
+        return s;
+    }
+}
diff --git a/src/jargs/test/gnu/CmdLineParserTestCase.java b/src/jargs/test/gnu/CmdLineParserTestCase.java
new file mode 100644
index 0000000..6022a87
--- /dev/null
+++ b/src/jargs/test/gnu/CmdLineParserTestCase.java
@@ -0,0 +1,252 @@
+package jargs.test.gnu;
+
+import jargs.gnu.CmdLineParser;
+
+import java.util.Enumeration;
+import java.util.Locale;
+import java.util.Vector;
+
+import junit.framework.TestCase;
+
+public class CmdLineParserTestCase extends TestCase {
+
+	public CmdLineParserTestCase(String name) {
+		super(name);
+	}
+
+	public void testStandardOptions() throws Exception {
+		CmdLineParser parser = new CmdLineParser();
+		CmdLineParser.Option verbose = parser.addBooleanOption('v', "verbose");
+		CmdLineParser.Option size = parser.addIntegerOption('s', "size");
+		CmdLineParser.Option name = parser.addStringOption('n', "name");
+		CmdLineParser.Option fraction = parser.addDoubleOption('f', "fraction");
+		CmdLineParser.Option missing = parser.addBooleanOption('m', "missing");
+		CmdLineParser.Option careful = parser.addBooleanOption("careful");
+		CmdLineParser.Option bignum = parser.addLongOption('b', "bignum");
+		assertEquals(null, parser.getOptionValue(size));
+		Long longValue = new Long(new Long(Integer.MAX_VALUE).longValue() + 1);
+		parser.parse(new String[] { "-v", "--size=100", "-b",
+				longValue.toString(), "-n", "foo", "-f", "0.1", "rest" },
+				Locale.US);
+		assertEquals(null, parser.getOptionValue(missing));
+		assertEquals(Boolean.TRUE, parser.getOptionValue(verbose));
+		assertEquals(100, ((Integer) parser.getOptionValue(size)).intValue());
+		assertEquals("foo", parser.getOptionValue(name));
+		assertEquals(longValue, parser.getOptionValue(bignum));
+		assertEquals(0.1, ((Double) parser.getOptionValue(fraction))
+				.doubleValue(), 0.1e-6);
+		assertArrayEquals(new String[]{"rest"}, parser.getRemainingArgs());
+	}
+
+
+    public void testDefaults() throws Exception {
+		CmdLineParser parser = new CmdLineParser();
+		CmdLineParser.Option boolean1 = parser.addBooleanOption("boolean1");
+		CmdLineParser.Option boolean2 = parser.addBooleanOption("boolean2");
+		CmdLineParser.Option boolean3 = parser.addBooleanOption("boolean3");
+		CmdLineParser.Option boolean4 = parser.addBooleanOption("boolean4");
+		CmdLineParser.Option boolean5 = parser.addBooleanOption("boolean5");
+
+		CmdLineParser.Option int1 = parser.addIntegerOption("int1");
+		CmdLineParser.Option int2 = parser.addIntegerOption("int2");
+		CmdLineParser.Option int3 = parser.addIntegerOption("int3");
+		CmdLineParser.Option int4 = parser.addIntegerOption("int4");
+
+		CmdLineParser.Option string1 = parser.addStringOption("string1");
+		CmdLineParser.Option string2 = parser.addStringOption("string2");
+		CmdLineParser.Option string3 = parser.addStringOption("string3");
+		CmdLineParser.Option string4 = parser.addStringOption("string4");
+
+		parser.parse(new String[] {
+          "--boolean1", "--boolean2",
+          "--int1=42", "--int2=42",
+          "--string1=Hello", "--string2=Hello",
+        });
+
+		assertEquals(Boolean.TRUE, parser.getOptionValue(boolean1));
+		assertEquals(Boolean.TRUE,
+                     parser.getOptionValue(boolean2, Boolean.FALSE));
+		assertEquals(null, parser.getOptionValue(boolean3));
+		assertEquals(Boolean.FALSE,
+                     parser.getOptionValue(boolean4, Boolean.FALSE));
+		assertEquals(Boolean.TRUE,
+                     parser.getOptionValue(boolean5, Boolean.TRUE));
+
+        Integer forty_two  = new Integer(42);
+        Integer thirty_six = new Integer(36);
+
+		assertEquals(forty_two,  parser.getOptionValue(int1));
+		assertEquals(forty_two,  parser.getOptionValue(int2, thirty_six));
+		assertEquals(null,       parser.getOptionValue(int3));
+		assertEquals(thirty_six, parser.getOptionValue(int4, thirty_six));
+
+		assertEquals("Hello",   parser.getOptionValue(string1));
+		assertEquals("Hello",   parser.getOptionValue(string2, "Goodbye"));
+		assertEquals(null,      parser.getOptionValue(string3));
+		assertEquals("Goodbye", parser.getOptionValue(string4, "Goodbye"));
+    }
+
+
+	public void testMultipleUses() throws Exception {
+		CmdLineParser parser = new CmdLineParser();
+		CmdLineParser.Option verbose = parser.addBooleanOption('v', "verbose");
+		CmdLineParser.Option foo = parser.addBooleanOption('f', "foo");
+		CmdLineParser.Option bar = parser.addBooleanOption('b', "bar");
+
+		parser.parse(new String[] {
+          "--foo", "-v", "-v", "--verbose", "-v", "-b", "rest"
+        });
+
+        int verbosity = 0;
+        while (true) {
+            Boolean b = (Boolean)parser.getOptionValue(verbose);
+
+            if (b == null) {
+                break;
+            }
+
+            if (b == Boolean.TRUE) {
+                verbosity++;
+            }
+            else {
+                assertEquals(Boolean.FALSE, b);
+                verbosity--;
+            }
+        }
+
+        assertEquals(4, verbosity);
+    }
+
+
+	public void testCombinedFlags() throws Exception {
+		CmdLineParser parser = new CmdLineParser();
+		CmdLineParser.Option alt = parser.addBooleanOption('a', "alt");
+		CmdLineParser.Option debug = parser.addBooleanOption('d', "debug");
+		CmdLineParser.Option verbose = parser.addBooleanOption('v', "verbose");
+		parser.parse(new String[] {
+          "-dv"
+        });
+
+        assertEquals(null, parser.getOptionValue(alt));
+        assertEquals(Boolean.TRUE, parser.getOptionValue(debug));
+        assertEquals(Boolean.TRUE, parser.getOptionValue(verbose));
+    }
+
+
+	public void testExplictlyTerminatedOptions() throws Exception {
+		CmdLineParser parser = new CmdLineParser();
+		CmdLineParser.Option alt = parser.addBooleanOption('a', "alt");
+		CmdLineParser.Option debug = parser.addBooleanOption('d', "debug");
+		CmdLineParser.Option verbose = parser.addBooleanOption('v', "verbose");
+		CmdLineParser.Option fraction = parser.addDoubleOption('f', "fraction");
+		parser.parse(new String[] {
+          "-a", "hello", "-d", "-f", "10", "--", "goodbye", "-v", "welcome",
+          "-f", "-10"
+        });
+
+        assertEquals(Boolean.TRUE,   parser.getOptionValue(alt));
+        assertEquals(Boolean.TRUE,   parser.getOptionValue(debug));
+        assertEquals(null,           parser.getOptionValue(verbose));
+        assertEquals(new Double(10), parser.getOptionValue(fraction));
+
+		assertArrayEquals(
+          new String[]{"hello", "goodbye", "-v", "welcome", "-f", "-10"},
+          parser.getRemainingArgs());
+    }
+
+
+	public void testGetOptionValues() throws Exception {
+		CmdLineParser parser = new CmdLineParser();
+		CmdLineParser.Option verbose = parser.addBooleanOption('v', "verbose");
+		CmdLineParser.Option foo = parser.addBooleanOption('f', "foo");
+		CmdLineParser.Option bar = parser.addBooleanOption('b', "bar");
+
+		parser.parse(new String[] {
+          "--foo", "-v", "-v", "--verbose", "-v", "-b", "rest"
+        });
+
+        int verbosity = 0;
+        Vector v = parser.getOptionValues(verbose);
+        Enumeration e = v.elements();
+        while (e.hasMoreElements()) {
+            Boolean b = (Boolean)e.nextElement();
+
+            if (b == Boolean.TRUE) {
+                verbosity++;
+            }
+            else {
+                assertEquals(Boolean.FALSE, b);
+                verbosity--;
+            }
+        }
+
+        assertEquals(4, verbosity);
+    }
+
+
+	public void testBadFormat() throws Exception {
+		CmdLineParser parser = new CmdLineParser();
+		CmdLineParser.Option size = parser.addIntegerOption('s', "size");
+		try {
+			parser.parse(new String[] { "--size=blah" });
+			fail("Expected IllegalOptionValueException");
+		} catch (CmdLineParser.IllegalOptionValueException e) {
+			// pass
+		}
+	}
+
+	public void testResetBetweenParse() throws Exception {
+		CmdLineParser parser = new CmdLineParser();
+		CmdLineParser.Option verbose = parser.addBooleanOption('v', "verbose");
+		parser.parse(new String[] { "-v" });
+		assertEquals(Boolean.TRUE, parser.getOptionValue(verbose));
+		parser.parse(new String[] {});
+		assertEquals(null, parser.getOptionValue(verbose));
+	}
+
+	public void testLocale() throws Exception {
+		CmdLineParser parser = new CmdLineParser();
+		CmdLineParser.Option fraction = parser.addDoubleOption('f', "fraction");
+		parser.parse(new String[] { "--fraction=0.2" }, Locale.US);
+		assertEquals(0.2, ((Double) parser.getOptionValue(fraction))
+				.doubleValue(), 0.1e-6);
+		parser.parse(new String[] { "--fraction=0,2" }, Locale.GERMANY);
+		assertEquals(0.2, ((Double) parser.getOptionValue(fraction))
+				.doubleValue(), 0.1e-6);
+	}
+
+	public void testDetachedOption() throws Exception {
+		CmdLineParser parser = new CmdLineParser();
+		CmdLineParser.Option detached = new CmdLineParser.Option.BooleanOption(
+				'v', "verbose");
+		assertEquals(null, parser.getOptionValue(detached));
+		try {
+			parser.parse(new String[] { "-v" });
+			fail("UnknownOptionException expected");
+		} catch (CmdLineParser.UnknownOptionException e) {
+			// pass
+		}
+		assertEquals(null, parser.getOptionValue(detached));
+	}
+
+	public void testMissingValueForStringOption() throws Exception {
+		CmdLineParser parser = new CmdLineParser();
+		parser.addBooleanOption('v', "verbose");
+		parser.addStringOption('c', "config");
+
+		try {
+			parser.parse(new String[] {"-v", "-c"});
+			fail();
+		} catch (CmdLineParser.IllegalOptionValueException e) {
+		}
+	}
+	
+	private void assertArrayEquals(Object[] expected, Object[] actual) {
+		assertNotNull(actual);
+		assertEquals(expected.length, actual.length);
+		for (int i = 0; i < expected.length; ++i) {
+			assertEquals(expected[i], actual[i]);
+		}
+	}
+
+}
diff --git a/src/jargs/test/gnu/CustomOptionTestCase.java b/src/jargs/test/gnu/CustomOptionTestCase.java
new file mode 100644
index 0000000..92f0519
--- /dev/null
+++ b/src/jargs/test/gnu/CustomOptionTestCase.java
@@ -0,0 +1,71 @@
+package jargs.test.gnu;
+
+import jargs.gnu.CmdLineParser;
+
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Locale;
+
+import junit.framework.TestCase;
+
+public class CustomOptionTestCase extends TestCase {
+
+    public CustomOptionTestCase(String name) {
+        super(name);
+    }
+
+    public void testCustomOption() throws Exception {
+        Calendar calendar = Calendar.getInstance();
+        CmdLineParser parser = new CmdLineParser();
+        CmdLineParser.Option date =
+            parser.addOption(new ShortDateOption('d', "date"));
+
+        parser.parse(new String[]{"-d", "11/03/2003"}, Locale.UK);
+        Date d = (Date)parser.getOptionValue(date);
+        calendar.setTime(d);
+        assertEquals(11,             calendar.get(Calendar.DAY_OF_MONTH));
+        assertEquals(Calendar.MARCH, calendar.get(Calendar.MONTH));
+        assertEquals(2003,           calendar.get(Calendar.YEAR));
+
+        parser.parse(new String[]{"-d", "11/03/2003"}, Locale.US);
+        d = (Date)parser.getOptionValue(date);
+        calendar.setTime(d);
+        assertEquals(3,                 calendar.get(Calendar.DAY_OF_MONTH));
+        assertEquals(Calendar.NOVEMBER, calendar.get(Calendar.MONTH));
+        assertEquals(2003,              calendar.get(Calendar.YEAR));
+    }
+
+    public void testIllegalCustomOption() throws Exception {
+        CmdLineParser parser = new CmdLineParser();
+        CmdLineParser.Option date =
+            parser.addOption(new ShortDateOption('d', "date"));
+        try {
+            parser.parse(new String[]{"-d", "foobar"}, Locale.US);
+            fail("Expected IllegalOptionValueException");
+        }
+        catch (CmdLineParser.IllegalOptionValueException e) {
+            //pass
+        }
+    }
+
+    public static class ShortDateOption extends CmdLineParser.Option {
+        public ShortDateOption( char shortForm, String longForm ) {
+            super(shortForm, longForm, true);
+        }
+        protected Object parseValue( String arg, Locale locale )
+            throws CmdLineParser.IllegalOptionValueException {
+            try {
+                DateFormat dateFormat =
+                    DateFormat.getDateInstance(DateFormat.SHORT, locale);
+                return dateFormat.parse(arg);
+            }
+            catch (ParseException e) {
+                throw new CmdLineParser.IllegalOptionValueException(this, arg);
+            }
+        }
+    }
+
+
+}

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-java/jargs.git



More information about the pkg-java-commits mailing list