You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by js...@apache.org on 2002/06/10 20:01:16 UTC
cvs commit: jakarta-commons/cli/xdocs index.xml
jstrachan 2002/06/10 11:01:16
Added: cli/src/test/org/apache/commons/cli
PatternOptionBuilderTest.java
HelpFormatterExamples.java ValueTest.java
ValuesTest.java TestHelpFormatter.java
OptionGroupTest.java BuildTest.java ParseTest.java
ParseRequiredTest.java
cli build-gump.xml .cvsignore build.xml LICENSE.txt
README.txt project.xml project.properties gump.xml
cli/src/java/org/apache/commons/cli Option.java
MissingOptionException.java ParseException.java
AlreadySelectedException.java package.html
Options.java HelpFormatter.java TypeHandler.java
OptionGroup.java PatternOptionBuilder.java
UnrecognizedOptionException.java CommandLine.java
MissingArgumentException.java overview.html
cli/src/conf MANIFEST.MF
cli/xdocs index.xml
Log:
moved cli over from the sandbox to commons proper
Revision Changes Path
1.1 jakarta-commons/cli/src/test/org/apache/commons/cli/PatternOptionBuilderTest.java
Index: PatternOptionBuilderTest.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE file.
*
* $Id: PatternOptionBuilderTest.java,v 1.1 2002/06/06 22:09:25 bayard Exp $
*/
package org.apache.commons.cli;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import java.io.StringWriter;
import java.io.PrintWriter;
/**
* Test case for the PatternOptionBuilder class
*
* @author Henri Yandell
**/
public class PatternOptionBuilderTest
extends TestCase
{
public static void main( String[] args )
{
String[] testName = { PatternOptionBuilderTest.class.getName() };
junit.textui.TestRunner.main(testName);
}
public static TestSuite suite()
{
return new TestSuite(PatternOptionBuilderTest.class);
}
public PatternOptionBuilderTest( String s )
{
super( s );
}
public void testSimplePattern()
throws Exception
{
Options options = PatternOptionBuilder.parsePattern("a:b@cde>f+n%t/");
String[] args = new String[] { "-c", "-a", "foo", "-b", "java.util.Vector", "-e", "build.xml", "-f", "java.util.Calendar", "-n", "4.5", "-t", "http://jakarta.apache.org/" };
CommandLine line = options.parse(args);
assertEquals("flag a", "foo", line.getOptionValue('a'));
assertEquals("string flag a", "foo", line.getOptionObject('a'));
assertEquals("object flag b", new java.util.Vector(), line.getOptionObject('b'));
assertEquals("boolean true flag c", true, line.hasOption('c'));
assertEquals("boolean false flag d", false, line.hasOption('d'));
assertEquals("file flag e", new java.io.File("build.xml"), line.getOptionObject('e'));
assertEquals("class flag f", java.util.Calendar.class, line.getOptionObject('f'));
assertEquals("number flag n", new Float(4.5), line.getOptionObject('n'));
assertEquals("url flag t", new java.net.URL("http://jakarta.apache.org/"), line.getOptionObject('t'));
/// DATES NOT SUPPORTED YET.
// assertEquals("number flag t", new java.util.Date(1023400137276L), line.getOptionObject('z'));
// input is: "Thu Jun 06 17:48:57 EDT 2002"
}
}
1.1 jakarta-commons/cli/src/test/org/apache/commons/cli/HelpFormatterExamples.java
Index: HelpFormatterExamples.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE file.
*
* $Id: HelpFormatterExamples.java,v 1.2 2002/05/17 11:44:32 jstrachan Exp $
*/
package org.apache.commons.cli;
/**
* A sample program shpwing the use of Options and the HelpFormatter class
*
* @author Slawek Zachcial
**/
public class HelpFormatterExamples
{
// --------------------------------------------------------------- Constants
// ------------------------------------------------------------------ Static
public static void main( String[] args )
{
System.out.println("\n#\n# 'man' example\n#");
manExample();
/*
System.out.println("\n#\n# 'bzip2' example\n#");
bzip2Example();
System.out.println("\n#\n# 'ls' example\n#");
lsExample();
*/
}
static void manExample()
{
String cmdLine =
"man [-c|-f|-k|-w|-tZT device] [-adlhu7V] [-Mpath] [-Ppager] [-Slist] " +
"[-msystem] [-pstring] [-Llocale] [-eextension] [section] page ...";
Options opts =
new Options().
addOption('a', "all", false, "find all matching manual pages.").
addOption('d', "debug", false, "emit debugging messages.").
addOption('e', "extension", false, "limit search to extension type 'extension'.").
addOption('f', "whatis", false, "equivalent to whatis.").
addOption('k', "apropos", false, "equivalent to apropos.").
addOption('w', "location", false, "print physical location of man page(s).").
addOption('l', "local-file", false, "interpret 'page' argument(s) as local filename(s)").
addOption('u', "update", false, "force a cache consistency check.").
//FIXME - should generate -r,--prompt string
addOption('r', "prompt", true, "provide 'less' pager with prompt.").
addOption('c', "catman", false, "used by catman to reformat out of date cat pages.").
addOption('7', "ascii", false, "display ASCII translation or certain latin1 chars.").
addOption('t', "troff", false, "use troff format pages.").
//FIXME - should generate -T,--troff-device device
addOption('T', "troff-device", true, "use groff with selected device.").
addOption('Z', "ditroff", false, "use groff with selected device.").
addOption('D', "default", false, "reset all options to their default values.").
//FIXME - should generate -M,--manpath path
addOption('M', "manpath", true, "set search path for manual pages to 'path'.").
//FIXME - should generate -P,--pager pager
addOption('P', "pager", true, "use program 'pager' to display output.").
//FIXME - should generate -S,--sections list
addOption('S', "sections", true, "use colon separated section list.").
//FIXME - should generate -m,--systems system
addOption('m', "systems", true, "search for man pages from other unix system(s).").
//FIXME - should generate -L,--locale locale
addOption('L', "locale", true, "defaine the locale for this particular man search.").
//FIXME - should generate -p,--preprocessor string
addOption('p', "preprocessor", true, "string indicates which preprocessor to run.\n" +
" e - [n]eqn p - pic t - tbl\n" +
" g - grap r - refer v - vgrind").
addOption('V', "version", false, "show version.").
addOption('h', "help", false, "show this usage message.");
HelpFormatter hf = new HelpFormatter();
//hf.printHelp(cmdLine, opts);
hf.printHelp(60, cmdLine, null, opts, null);
}
static void bzip2Example()
{
System.out.println( "Coming soon" );
}
static void lsExample()
{
System.out.println( "Coming soon" );
}
// -------------------------------------------------------------- Attributes
// ------------------------------------------------------------ Constructors
// ------------------------------------------------------------------ Public
// --------------------------------------------------------------- Protected
// ------------------------------------------------------- Package protected
// ----------------------------------------------------------------- Private
// ----------------------------------------------------------- Inner classes
}
1.1 jakarta-commons/cli/src/test/org/apache/commons/cli/ValueTest.java
Index: ValueTest.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE file.
*
* $Id: ValueTest.java,v 1.1 2001/12/19 18:16:25 jstrachan Exp $
*/
package org.apache.commons.cli;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class ValueTest extends TestCase
{
public static Test suite() {
return new TestSuite(ValueTest.class);
/*
TestSuite suite = new TestSuite();
suite.addTest( new ValueTest("testLongNoArg") );
return suite;
*/
}
private CommandLine _cl = null;
public ValueTest(String name)
{
super(name);
}
public void setUp()
{
Options opts = new Options();
opts.addOption('a',
false,
"toggle -a");
opts.addOption('b',
true,
"set -b");
opts.addOption('c',
"c",
false,
"toggle -c");
opts.addOption('d',
"d",
true,
"set -d");
/*
try
{
opts.addOption('a',
false,
"toggle -a");
opts.addOption('b',
true,
"set -b");
opts.addOption('c',
"c",
false,
"toggle -c");
opts.addOption('d',
"d",
true,
"set -d");
}
catch (DuplicateOptionException e)
{
fail("Cannot setUp() Options: " + e.toString());
}
*/
String[] args = new String[] { "-a",
"-b", "foo",
"--c",
"--d", "bar" };
try
{
_cl = opts.parse(args);
}
catch (ParseException e)
{
fail("Cannot setUp() CommandLine: " + e.toString());
}
}
public void tearDown()
{
}
public void testShortNoArg()
{
assertTrue( _cl.hasOption('a') );
assertNull( _cl.getOptionValue('a') );
}
public void testShortWithArg()
{
assertTrue( _cl.hasOption('b') );
assertNotNull( _cl.getOptionValue('b') );
assertEquals( _cl.getOptionValue('b'), "foo");
}
public void testLongNoArg()
{
assertTrue( _cl.hasOption('c') );
assertNull( _cl.getOptionValue('c') );
}
public void testLongWithArg()
{
assertTrue( _cl.hasOption('d') );
assertNotNull( _cl.getOptionValue('d') );
assertEquals( _cl.getOptionValue('d'), "bar");
}
}
1.1 jakarta-commons/cli/src/test/org/apache/commons/cli/ValuesTest.java
Index: ValuesTest.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE file.
*
* $Id: ValueTest.java,v 1.1 2001/12/19 18:16:25 jstrachan Exp $
*/
package org.apache.commons.cli;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class ValuesTest extends TestCase
{
public static Test suite() {
return new TestSuite(ValuesTest.class);
/*
TestSuite suite = new TestSuite();
suite.addTest( new ValueTest("testLongNoArg") );
return suite;
*/
}
private CommandLine _cl = null;
public ValuesTest(String name)
{
super(name);
}
public void setUp()
{
Options opts = new Options();
opts.addOption('a',
false,
"toggle -a");
opts.addOption('b',
true,
"set -b");
opts.addOption('c',
"c",
false,
"toggle -c");
opts.addOption('d',
"d",
true,
"set -d");
opts.addOption('e',
"e",
true,
"set -e",
false,
true);
opts.addOption('f',
"f",
false,
"jk");
String[] args = new String[] { "-a",
"-b", "foo",
"--c",
"--d", "bar",
"-e", "one", "two",
"-f",
"arg1", "arg2" };
try
{
_cl = opts.parse(args);
}
catch (ParseException e)
{
fail("Cannot setUp() CommandLine: " + e.toString());
}
}
public void tearDown()
{
}
public void testShortArgs()
{
assertTrue( _cl.hasOption('a') );
assertTrue( _cl.hasOption('c') );
assertNull( _cl.getOptionValues('a') );
assertNull( _cl.getOptionValues('c') );
}
public void testShortArgsWithValue()
{
assertTrue( _cl.hasOption('b') );
assertTrue( _cl.getOptionValue('b').equals("foo"));
assertTrue( _cl.getOptionValues('b').length == 1);
assertTrue( _cl.hasOption('d') );
assertTrue( _cl.getOptionValue('d').equals("bar"));
assertTrue( _cl.getOptionValues('d').length == 1);
}
public void testMultipleArgValues()
{
String[] result = _cl.getOptionValues('e');
String[] values = new String[] { "one", "two" };
assertTrue( _cl.hasOption('e') );
assertTrue( _cl.getOptionValues('e').length == 2);
assertTrue( java.util.Arrays.equals( values, _cl.getOptionValues('e') ) );
}
public void testExtraArgs()
{
String[] args = new String[] { "arg1", "arg2" };
assertTrue( _cl.getArgs().length == 2);
assertTrue( java.util.Arrays.equals( args, _cl.getArgs() ) );
}
}
1.1 jakarta-commons/cli/src/test/org/apache/commons/cli/TestHelpFormatter.java
Index: TestHelpFormatter.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE file.
*
* $Id: TestHelpFormatter.java,v 1.2 2002/05/17 11:44:32 jstrachan Exp $
*/
package org.apache.commons.cli;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import java.io.StringWriter;
import java.io.PrintWriter;
/**
* Test case for the HelpFormatter class
*
* @author Slawek Zachcial
**/
public class TestHelpFormatter
extends TestCase
{
// --------------------------------------------------------------- Constants
// ------------------------------------------------------------------ Static
public static void main( String[] args )
{
String[] testName = { TestHelpFormatter.class.getName() };
junit.textui.TestRunner.main(testName);
}
public static TestSuite suite()
{
return new TestSuite(TestHelpFormatter.class);
}
// -------------------------------------------------------------- Attributes
// ------------------------------------------------------------ Constructors
public TestHelpFormatter( String s )
{
super( s );
}
// ------------------------------------------------------------------ Public
public void testFindWrapPos()
throws Exception
{
HelpFormatter hf = new HelpFormatter();
String text = "This is a test.";
//text width should be max 8; the wrap postition is 7
assertEquals("wrap position", 7, hf.findWrapPos(text, 8, 0));
//starting from 8 must give -1 - the wrap pos is after end
assertEquals("wrap position 2", -1, hf.findWrapPos(text, 8, 8));
//if there is no a good position before width to make a wrapping look for the next one
text = "aaaa aa";
assertEquals("wrap position 3", 4, hf.findWrapPos(text, 3, 0));
}
public void testPrintWrapped()
throws Exception
{
StringBuffer sb = new StringBuffer();
HelpFormatter hf = new HelpFormatter();
String text = "This is a test.";
String expected;
expected = "This is a" + hf.defaultNewLine + "test.";
hf.renderWrappedText(sb, 12, 0, text);
assertEquals("single line text", expected, sb.toString());
sb.setLength(0);
expected = "This is a" + hf.defaultNewLine + " test.";
hf.renderWrappedText(sb, 12, 4, text);
assertEquals("single line padded text", expected, sb.toString());
text =
"aaaa aaaa aaaa" + hf.defaultNewLine +
"aaaaaa" + hf.defaultNewLine +
"aaaaa";
expected = text;
sb.setLength(0);
hf.renderWrappedText(sb, 16, 0, text);
assertEquals("multi line text", expected, sb.toString());
expected =
"aaaa aaaa aaaa" + hf.defaultNewLine +
" aaaaaa" + hf.defaultNewLine +
" aaaaa";
sb.setLength(0);
hf.renderWrappedText(sb, 16, 4, text);
assertEquals("multi-line padded text", expected, sb.toString());
}
public void testPrintOptions()
throws Exception
{
StringBuffer sb = new StringBuffer();
HelpFormatter hf = new HelpFormatter();
final int leftPad = 1;
final int descPad = 3;
final String lpad = hf.createPadding(leftPad);
final String dpad = hf.createPadding(descPad);
Options options = null;
String expected = null;
options = new Options().addOption('a', false, "aaaa aaaa aaaa aaaa aaaa");
expected = lpad + "-a" + dpad + "aaaa aaaa aaaa aaaa aaaa";
hf.renderOptions(sb, 60, options, leftPad, descPad);
assertEquals("simple non-wrapped option", expected, sb.toString());
int nextLineTabStop = leftPad+descPad+"-a".length();
expected =
lpad + "-a" + dpad + "aaaa aaaa aaaa" + hf.defaultNewLine +
hf.createPadding(nextLineTabStop) + "aaaa aaaa";
sb.setLength(0);
hf.renderOptions(sb, nextLineTabStop+17, options, leftPad, descPad);
assertEquals("simple wrapped option", expected, sb.toString());
options = new Options().addOption('a', "aaa", false, "dddd dddd dddd dddd");
expected = lpad + "-a,--aaa" + dpad + "dddd dddd dddd dddd";
sb.setLength(0);
hf.renderOptions(sb, 60, options, leftPad, descPad);
assertEquals("long non-wrapped option", expected, sb.toString());
nextLineTabStop = leftPad+descPad+"-a,--aaa".length();
expected =
lpad + "-a,--aaa" + dpad + "dddd dddd" + hf.defaultNewLine +
hf.createPadding(nextLineTabStop) + "dddd dddd";
sb.setLength(0);
hf.renderOptions(sb, 25, options, leftPad, descPad);
assertEquals("long wrapped option", expected, sb.toString());
options = new Options().
addOption('a', "aaa", false, "dddd dddd dddd dddd").
addOption('b', false, "feeee eeee eeee eeee");
expected =
lpad + "-a,--aaa" + dpad + "dddd dddd" + hf.defaultNewLine +
hf.createPadding(nextLineTabStop) + "dddd dddd" + hf.defaultNewLine +
lpad + "-b " + dpad + "feeee eeee" + hf.defaultNewLine +
hf.createPadding(nextLineTabStop) + "eeee eeee";
sb.setLength(0);
hf.renderOptions(sb, 25, options, leftPad, descPad);
assertEquals("multiple wrapped options", expected, sb.toString());
}
// --------------------------------------------------------------- Protected
// ------------------------------------------------------- Package protected
// ----------------------------------------------------------------- Private
// ----------------------------------------------------------- Inner classes
}
1.1 jakarta-commons/cli/src/test/org/apache/commons/cli/OptionGroupTest.java
Index: OptionGroupTest.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE file.
*
* $Id: OptionGroupTest.java,v 1.1 2002/04/23 16:08:02 jstrachan Exp $
*/
package org.apache.commons.cli;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* @author John Keyes (john at integralsource.com)
* @version $Revision: 1.1 $
*/
public class OptionGroupTest extends TestCase
{
private Options _options = null;
public static Test suite()
{
return new TestSuite ( OptionGroupTest.class );
}
public OptionGroupTest( String name )
{
super( name );
}
public void setUp()
{
Option file = new Option( 'f', "file", false, "file to process" );
Option dir = new Option( 'd', "directory", false, "directory to process" );
OptionGroup group = new OptionGroup();
group.addOption( file );
group.addOption( dir );
_options = new Options().addOptionGroup( group );
Option section = new Option( 's', "section", false, "section to process" );
Option chapter = new Option( 'c', "chapter", false, "chapter to process" );
OptionGroup group2 = new OptionGroup();
group2.addOption( section );
group2.addOption( chapter );
_options.addOptionGroup( group2 );
_options.addOption( 'r', "revision", false, "revision number" );
}
public void tearDown()
{
}
public void testSingleOptionFromGroup()
{
String[] args = new String[] { "-f" };
try
{
CommandLine cl = _options.parse(args);
assertTrue( "Confirm -r is NOT set", !cl.hasOption('r') );
assertTrue( "Confirm -f is set", cl.hasOption('f') );
assertTrue( "Confirm -d is NOT set", !cl.hasOption('d') );
assertTrue( "Confirm -s is NOT set", !cl.hasOption('s') );
assertTrue( "Confirm -c is NOT set", !cl.hasOption('c') );
assertTrue( "Confirm no extra args", cl.getArgList().size() == 0);
}
catch (ParseException e)
{
fail( e.toString() );
}
}
public void testSingleOption()
{
String[] args = new String[] { "-r" };
try
{
CommandLine cl = _options.parse(args);
assertTrue( "Confirm -r is set", cl.hasOption('r') );
assertTrue( "Confirm -f is NOT set", !cl.hasOption('f') );
assertTrue( "Confirm -d is NOT set", !cl.hasOption('d') );
assertTrue( "Confirm -s is NOT set", !cl.hasOption('s') );
assertTrue( "Confirm -c is NOT set", !cl.hasOption('c') );
assertTrue( "Confirm no extra args", cl.getArgList().size() == 0);
}
catch (ParseException e)
{
fail( e.toString() );
}
}
public void testTwoValidOptions()
{
String[] args = new String[] { "-r", "-f" };
try
{
CommandLine cl = _options.parse(args);
assertTrue( "Confirm -r is set", cl.hasOption('r') );
assertTrue( "Confirm -f is set", cl.hasOption('f') );
assertTrue( "Confirm -d is NOT set", !cl.hasOption('d') );
assertTrue( "Confirm -s is NOT set", !cl.hasOption('s') );
assertTrue( "Confirm -c is NOT set", !cl.hasOption('c') );
assertTrue( "Confirm no extra args", cl.getArgList().size() == 0);
}
catch (ParseException e)
{
fail( e.toString() );
}
}
public void testSingleLongOption()
{
String[] args = new String[] { "--file" };
try
{
CommandLine cl = _options.parse(args);
assertTrue( "Confirm -r is NOT set", !cl.hasOption('r') );
assertTrue( "Confirm -f is set", cl.hasOption('f') );
assertTrue( "Confirm -d is NOT set", !cl.hasOption('d') );
assertTrue( "Confirm -s is NOT set", !cl.hasOption('s') );
assertTrue( "Confirm -c is NOT set", !cl.hasOption('c') );
assertTrue( "Confirm no extra args", cl.getArgList().size() == 0);
}
catch (ParseException e)
{
fail( e.toString() );
}
}
public void testTwoValidLongOptions()
{
String[] args = new String[] { "--revision", "--file" };
try
{
CommandLine cl = _options.parse(args);
assertTrue( "Confirm -r is set", cl.hasOption('r') );
assertTrue( "Confirm -f is set", cl.hasOption('f') );
assertTrue( "Confirm -d is NOT set", !cl.hasOption('d') );
assertTrue( "Confirm -s is NOT set", !cl.hasOption('s') );
assertTrue( "Confirm -c is NOT set", !cl.hasOption('c') );
assertTrue( "Confirm no extra args", cl.getArgList().size() == 0);
}
catch (ParseException e)
{
fail( e.toString() );
}
}
public void testNoOptionsExtraArgs()
{
String[] args = new String[] { "arg1", "arg2" };
try
{
CommandLine cl = _options.parse(args);
assertTrue( "Confirm -r is NOT set", !cl.hasOption('r') );
assertTrue( "Confirm -f is NOT set", !cl.hasOption('f') );
assertTrue( "Confirm -d is NOT set", !cl.hasOption('d') );
assertTrue( "Confirm -s is NOT set", !cl.hasOption('s') );
assertTrue( "Confirm -c is NOT set", !cl.hasOption('c') );
assertTrue( "Confirm TWO extra args", cl.getArgList().size() == 2);
}
catch (ParseException e)
{
fail( e.toString() );
}
}
public void testTwoOptionsFromGroup()
{
String[] args = new String[] { "-f", "-d" };
try
{
CommandLine cl = _options.parse(args);
fail( "two arguments from group not allowed" );
}
catch (ParseException e)
{
if( !( e instanceof AlreadySelectedException ) )
{
fail( "incorrect exception caught:" + e.getMessage() );
}
}
}
public void testTwoLongOptionsFromGroup()
{
String[] args = new String[] { "--file", "--directory" };
try
{
CommandLine cl = _options.parse(args);
fail( "two arguments from group not allowed" );
}
catch (ParseException e)
{
if( !( e instanceof AlreadySelectedException ) )
{
fail( "incorrect exception caught:" + e.getMessage() );
}
}
}
public void testTwoOptionsFromDifferentGroup()
{
String[] args = new String[] { "-f", "-s" };
try
{
CommandLine cl = _options.parse(args);
assertTrue( "Confirm -r is NOT set", !cl.hasOption('r') );
assertTrue( "Confirm -f is set", cl.hasOption('f') );
assertTrue( "Confirm -d is NOT set", !cl.hasOption('d') );
assertTrue( "Confirm -s is set", cl.hasOption('s') );
assertTrue( "Confirm -c is NOT set", !cl.hasOption('c') );
assertTrue( "Confirm NO extra args", cl.getArgList().size() == 0);
}
catch (ParseException e)
{
fail( e.toString() );
}
}
}
1.1 jakarta-commons/cli/src/test/org/apache/commons/cli/BuildTest.java
Index: BuildTest.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE file.
*
* $Id: BuildTest.java,v 1.1 2001/12/19 18:16:25 jstrachan Exp $
*/
package org.apache.commons.cli;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class BuildTest extends TestCase
{
public static Test suite() {
return new TestSuite(BuildTest.class);
}
public BuildTest(String name)
{
super(name);
}
public void setUp()
{
}
public void tearDown()
{
}
public void testSimple()
{
Options opts = new Options();
opts.addOption('a',
false,
"toggle -a");
opts.addOption('b',
true,
"toggle -b");
/*
try
{
opts.addOption('a',
false,
"toggle -a");
opts.addOption('b',
true,
"toggle -b");
}
catch (DuplicateOptionException e)
{
fail(e.toString());
}
*/
}
public void testDuplicateSimple()
{
Options opts = new Options();
opts.addOption('a',
false,
"toggle -a");
opts.addOption('a',
true,
"toggle -a*");
assertEquals( "last one in wins", "toggle -a*", opts.getOption('a').getDescription() );
/*
try
{
opts.addOption('a',
false,
"toggle -a");
opts.addOption('a',
true,
"toggle -a");
fail("Should've thrown DuplicateOptionException");
}
catch (DuplicateOptionException e)
{
}
*/
}
public void testLong()
{
Options opts = new Options();
opts.addOption('a',
"--a",
false,
"toggle -a");
opts.addOption('b',
"--b",
true,
"set -b");
/*
try
{
opts.addOption('a',
"--a",
false,
"toggle -a");
opts.addOption('b',
"--b",
true,
"set -b");
}
catch (DuplicateOptionException e)
{
fail(e.toString());
}
*/
}
public void testDuplicateLong()
{
Options opts = new Options();
opts.addOption('a',
"--a",
false,
"toggle -a");
opts.addOption('a',
"--a",
false,
"toggle -a*");
assertEquals( "last one in wins", "toggle -a*", opts.getOption('a').getDescription() );
/*
try
{
opts.addOption('a',
"--a",
false,
"toggle -a");
opts.addOption('a',
"--a",
false,
"toggle -a");
fail("Should've thrown DuplicateOptionException");
}
catch (DuplicateOptionException e)
{
}
*/
}
}
1.1 jakarta-commons/cli/src/test/org/apache/commons/cli/ParseTest.java
Index: ParseTest.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE file.
*
* $Id: ParseTest.java,v 1.1 2001/12/19 18:16:25 jstrachan Exp $
*/
package org.apache.commons.cli;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
public class ParseTest extends TestCase
{
private Options _options = null;
public static Test suite() {
return new TestSuite(ParseTest.class);
}
public ParseTest(String name)
{
super(name);
}
public void setUp()
{
_options = new Options()
.addOption('a',
"enable-a",
false,
"turn [a] on or off")
.addOption('b',
"bfile",
true,
"set the value of [b]")
.addOption('c',
"copt",
false,
"turn [c] on or off");
/*
try
{
_options
.addOption('a',
"enable-a",
false,
"turn [a] on or off")
.addOption('b',
"bfile",
true,
"set the value of [b]")
.addOption('c',
"copt",
false,
"turn [c] on or off");
}
catch (CLIException e)
{
e.printStackTrace();
}
*/
}
public void tearDown()
{
}
public void testSimpleShort()
{
String[] args = new String[] { "-a",
"-b", "toast",
"foo", "bar" };
try
{
CommandLine cl = _options.parse(args);
assertTrue( "Confirm -a is set", cl.hasOption('a') );
assertTrue( "Confirm -b is set", cl.hasOption('b') );
assertTrue( "Confirm arg of -b", cl.getOptionValue('b').equals("toast") );
assertTrue( "Confirm size of extra args", cl.getArgList().size() == 2);
}
catch (ParseException e)
{
fail( e.toString() );
}
}
public void testSimpleLong()
{
String[] args = new String[] { "--enable-a",
"--bfile", "toast",
"foo", "bar" };
try
{
CommandLine cl = _options.parse(args);
assertTrue( "Confirm -a is set", cl.hasOption('a') );
assertTrue( "Confirm -b is set", cl.hasOption('b') );
assertTrue( "Confirm arg of -b", cl.getOptionValue('b').equals("toast") );
assertTrue( "Confirm size of extra args", cl.getArgList().size() == 2);
}
catch (ParseException e)
{
fail( e.toString() );
}
}
public void testComplexShort()
{
String[] args = new String[] { "-acbtoast",
"foo", "bar" };
try
{
CommandLine cl = _options.parse(args);
assertTrue( "Confirm -a is set", cl.hasOption('a') );
assertTrue( "Confirm -b is set", cl.hasOption('b') );
assertTrue( "Confirm -c is set", cl.hasOption('c') );
assertTrue( "Confirm arg of -b", cl.getOptionValue('b').equals("toast") );
assertTrue( "Confirm size of extra args", cl.getArgList().size() == 2);
}
catch (ParseException e)
{
fail( e.toString() );
}
}
public void testExtraOption()
{
String[] args = new String[] { "-adbtoast",
"foo", "bar" };
boolean caught = false;
try
{
CommandLine cl = _options.parse(args);
assertTrue( "Confirm -a is set", cl.hasOption('a') );
assertTrue( "Confirm -b is set", cl.hasOption('b') );
assertTrue( "confirm arg of -b", cl.getOptionValue('b').equals("toast") );
assertTrue( "Confirm size of extra args", cl.getArgList().size() == 3);
}
catch (UnrecognizedOptionException e)
{
caught = true;
}
catch (ParseException e)
{
fail( e.toString() );
}
assertTrue( "Confirm UnrecognizedOptionException caught", caught );
}
public void testMissingArg()
{
String[] args = new String[] { "-acb" };
boolean caught = false;
try
{
CommandLine cl = _options.parse(args);
}
catch (MissingArgumentException e)
{
caught = true;
}
catch (ParseException e)
{
fail( e.toString() );
}
assertTrue( "Confirm MissingArgumentException caught", caught );
}
public void testStop()
{
String[] args = new String[] { "-c",
"foober",
"-btoast" };
try
{
CommandLine cl = _options.parse(args,
true);
assertTrue( "Confirm -c is set", cl.hasOption('c') );
assertTrue( "Confirm 2 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 2);
}
catch (ParseException e)
{
fail( e.toString() );
}
}
public void testMultiple()
{
String[] args = new String[] { "-c",
"foobar",
"-btoast" };
try
{
CommandLine cl = _options.parse(args,
true);
assertTrue( "Confirm -c is set", cl.hasOption('c') );
assertTrue( "Confirm 2 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 2);
cl = _options.parse( cl.getArgList() );
assertTrue( "Confirm -c is not set", ! cl.hasOption('c') );
assertTrue( "Confirm -b is set", cl.hasOption('b') );
assertTrue( "Confirm arg of -b", cl.getOptionValue('b').equals("toast") );
assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1);
assertTrue( "Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar") );
}
catch (ParseException e)
{
fail( e.toString() );
}
}
public void testMultipleWithLong()
{
String[] args = new String[] { "--copt",
"foobar",
"--bfile", "toast" };
try
{
CommandLine cl = _options.parse(args,
true);
assertTrue( "Confirm -c is set", cl.hasOption('c') );
assertTrue( "Confirm 3 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 3);
cl = _options.parse( cl.getArgList() );
assertTrue( "Confirm -c is not set", ! cl.hasOption('c') );
assertTrue( "Confirm -b is set", cl.hasOption('b') );
assertTrue( "Confirm arg of -b", cl.getOptionValue('b').equals("toast") );
assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1);
assertTrue( "Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("foobar") );
}
catch (ParseException e)
{
fail( e.toString() );
}
}
public void testDoubleDash()
{
String[] args = new String[] { "--copt",
"--",
"-b", "toast" };
try
{
CommandLine cl = _options.parse(args);
assertTrue( "Confirm -c is set", cl.hasOption('c') );
assertTrue( "Confirm -b is not set", ! cl.hasOption('b') );
assertTrue( "Confirm 2 extra args: " + cl.getArgList().size(), cl.getArgList().size() == 2);
}
catch (ParseException e)
{
fail( e.toString() );
}
}
public void testSingleDash()
{
String[] args = new String[] { "--copt",
"-b", "-",
"-a",
"-" };
try
{
CommandLine cl = _options.parse(args);
assertTrue( "Confirm -a is set", cl.hasOption('a') );
assertTrue( "Confirm -b is set", cl.hasOption('b') );
assertTrue( "Confirm arg of -b", cl.getOptionValue('b').equals("-") );
assertTrue( "Confirm 1 extra arg: " + cl.getArgList().size(), cl.getArgList().size() == 1);
assertTrue( "Confirm value of extra arg: " + cl.getArgList().get(0), cl.getArgList().get(0).equals("-") );
}
catch (ParseException e)
{
fail( e.toString() );
}
}
}
1.1 jakarta-commons/cli/src/test/org/apache/commons/cli/ParseRequiredTest.java
Index: ParseRequiredTest.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE file.
*
* $Id: ParseRequiredTest.java,v 1.1 2002/04/23 16:08:02 jstrachan Exp $
*/
package org.apache.commons.cli;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* @author John Keyes (john at integralsource.com)
* @version $Revision: 1.1 $
*/
public class ParseRequiredTest extends TestCase
{
private Options _options = null;
public static Test suite() {
return new TestSuite(ParseRequiredTest.class);
}
public ParseRequiredTest(String name)
{
super(name);
}
public void setUp()
{
_options = new Options()
.addOption('a',
"enable-a",
false,
"turn [a] on or off")
.addOption('b',
"bfile",
true,
"set the value of [b]",
true);
}
public void tearDown()
{
}
public void testWithRequiredOption()
{
String[] args = new String[] { "-b", "file" };
try
{
CommandLine cl = _options.parse(args);
assertTrue( "Confirm -a is NOT set", !cl.hasOption('a') );
assertTrue( "Confirm -b is set", cl.hasOption('b') );
assertTrue( "Confirm arg of -b", cl.getOptionValue('b').equals("file") );
assertTrue( "Confirm NO of extra args", cl.getArgList().size() == 0);
}
catch (ParseException e)
{
fail( e.toString() );
}
}
public void testOptionAndRequiredOption()
{
String[] args = new String[] { "-a", "-b", "file" };
try
{
CommandLine cl = _options.parse(args);
assertTrue( "Confirm -a is set", cl.hasOption('a') );
assertTrue( "Confirm -b is set", cl.hasOption('b') );
assertTrue( "Confirm arg of -b", cl.getOptionValue('b').equals("file") );
assertTrue( "Confirm NO of extra args", cl.getArgList().size() == 0);
}
catch (ParseException e)
{
fail( e.toString() );
}
}
public void testMissingRequiredOption()
{
String[] args = new String[] { "-a" };
try
{
CommandLine cl = _options.parse(args);
fail( "exception should have been thrown" );
}
catch (ParseException e)
{
if( !( e instanceof MissingOptionException ) )
{
fail( "expected to catch MissingOptionException" );
}
}
}
}
1.1 jakarta-commons/cli/build-gump.xml
Index: build-gump.xml
===================================================================
<!--
WARNING: This file is generated! Do not edit by hand!
-->
<project name="maven" default="jar" basedir=".">
<target
name="jar">
<property name="maven.build.dir" value="target"/>
<property name="maven.build.dest" value="${maven.build.dir}/classes"/>
<mkdir dir="${maven.build.dest}"/>
<javac
destdir="${maven.build.dest}"
excludes="**/package.html"
debug="false"
deprecation="false"
optimize="false">
<src>
<pathelement location="src/java"/>
</src>
</javac>
<jar
jarfile="${maven.build.dir}/${maven.final.name}.jar"
basedir="${maven.build.dest}"
excludes="**/package.html"
/>
</target>
</project>
1.1 jakarta-commons/cli/.cvsignore
Index: .cvsignore
===================================================================
build.properties
dist
target
velocity.log
.project
maven.log
1.1 jakarta-commons/cli/build.xml
Index: build.xml
===================================================================
<?xml version="1.0"?>
<project name="cli" default="maven:jar" basedir=".">
<!-- Give user a chance to override without editing this file
(and without typing -D each time they invoke a target) -->
<!-- Allow any user specific values to override the defaults -->
<property file="${user.home}/build.properties" />
<!-- Allow user defaults for this project -->
<property file="build.properties" />
<!-- Set default values for the build -->
<property file="project.properties" />
<!-- maven:start -->
<!-- ================================================================== -->
<!-- D E L E G A T O R S -->
<!-- ================================================================== -->
<target name="maven:gump-descriptor">
<ant antfile="${maven.home}/plugins/core/build.xml" target="gump-descriptor"/>
</target>
<target name="maven:maven-update">
<ant antfile="${maven.home}/plugins/core/build.xml" target="maven-update"/>
</target>
<target name="maven:update-jars">
<ant antfile="${maven.home}/plugins/core/build.xml" target="update-jars"/>
</target>
<target name="maven:jar">
<ant antfile="${maven.home}/plugins/core/build.xml" target="jar"/>
</target>
<target name="maven:docs-quick">
<ant antfile="${maven.home}/plugins/docs/build.xml" target="docs-quick"/>
</target>
<target name="maven:run-singletest">
<ant antfile="${maven.home}/plugins/test/build.xml" target="run-singletest"/>
</target>
<target name="maven:compile">
<ant antfile="${maven.home}/plugins/core/build.xml" target="compile"/>
</target>
<target name="maven:jar-resources">
<ant antfile="${maven.home}/plugins/core/build.xml" target="jar-resources"/>
</target>
<target name="maven:fo">
<ant antfile="${maven.home}/plugins/docs/build.xml" target="fo"/>
</target>
<target name="maven:cvs-change-log">
<ant antfile="${maven.home}/plugins/docs/build.xml" target="cvs-change-log"/>
</target>
<target name="maven:war">
<ant antfile="${maven.home}/plugins/j2ee/build.xml" target="war"/>
</target>
<target name="maven:generate-reactor">
<ant antfile="${maven.home}/build-reactor.xml" target="generate-reactor"/>
</target>
<target name="maven:cross-ref">
<ant antfile="${maven.home}/plugins/docs/build.xml" target="cross-ref"/>
</target>
<target name="maven:deploy-site">
<ant antfile="${maven.home}/plugins/docs/build.xml" target="deploy-site"/>
</target>
<target name="maven:ear">
<ant antfile="${maven.home}/plugins/j2ee/build.xml" target="ear"/>
</target>
<target name="maven:install-jar">
<ant antfile="${maven.home}/plugins/core/build.xml" target="install-jar"/>
</target>
<target name="maven:task-list">
<ant antfile="${maven.home}/plugins/docs/build.xml" target="task-list"/>
</target>
<target name="maven:docs">
<ant antfile="${maven.home}/plugins/docs/build.xml" target="docs"/>
</target>
<target name="maven:site">
<ant antfile="${maven.home}/plugins/docs/build.xml" target="site"/>
</target>
<target name="maven:deploy-dist">
<ant antfile="${maven.home}/plugins/core/build.xml" target="deploy-dist"/>
</target>
<target name="maven:javadocs">
<ant antfile="${maven.home}/plugins/docs/build.xml" target="javadocs"/>
</target>
<target name="maven:announce">
<ant antfile="${maven.home}/plugins/core/build.xml" target="announce"/>
</target>
<target name="maven:check-source">
<ant antfile="${maven.home}/plugins/core/build.xml" target="check-source"/>
</target>
<target name="maven:dist">
<ant antfile="${maven.home}/plugins/core/build.xml" target="dist"/>
</target>
<target name="maven:dist-build">
<ant antfile="${maven.home}/plugins/core/build.xml" target="dist-build"/>
</target>
<target name="maven:metrics">
<ant antfile="${maven.home}/plugins/metrics/build.xml" target="metrics"/>
</target>
<target name="maven:clean">
<ant antfile="${maven.home}/plugins/core/build.xml" target="clean"/>
</target>
<target name="maven:env">
<ant antfile="${maven.home}/plugins/core/build.xml" target="env"/>
</target>
<target name="maven:test">
<ant antfile="${maven.home}/plugins/test/build.xml" target="test"/>
</target>
<target name="maven:pdf">
<ant antfile="${maven.home}/plugins/docs/build.xml" target="pdf"/>
</target>
<target name="maven:iutest">
<ant antfile="${maven.home}/plugins/iutest/build.xml" target="iutest"/>
</target>
<target name="maven:activity-log">
<ant antfile="${maven.home}/plugins/docs/build.xml" target="activity-log"/>
</target>
<target name="maven:verify-project">
<ant antfile="${maven.home}/plugins/core/build.xml" target="verify-project"/>
</target>
<target name="maven:validate-pom">
<ant antfile="${maven.home}/plugins/core/build.xml" target="validate-pom"/>
</target>
<target name="maven:validate-war">
<ant antfile="${maven.home}/plugins/j2ee/build.xml" target="validate-war"/>
</target>
<!-- maven:end -->
<!-- ========== Helper Targets ============================================ -->
<target name="clean" depends="maven:clean">
<delete file="velocity.log"/>
</target>
<target name="site" depends="maven:site"/>
<target name="test" depends="maven:test"/>
<target name="compile" depends="maven:compile, maven:jar-resources"/>
<target name="dist" depends="maven:dist-build"/>
</project>
1.1 jakarta-commons/cli/LICENSE.txt
Index: LICENSE.txt
===================================================================
/*
* $Header: /home/cvs/jakarta-commons/LICENSE,v 1.4 2002/04/11 13:24:02 dion Exp $
* $Revision: 1.4 $
* $Date: 2002/04/11 13:24:02 $
*
* ====================================================================
*
* 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/>.
*
*/
1.1 jakarta-commons/cli/README.txt
Index: README.txt
===================================================================
Jakarta Commons CLI
===================
Welcome to the CLI component of the Jakarta Commons project.
This component requires the excellent Ant utility. It can
be found here :
http://jakarta.apache.org/ant/
For testing the project, you will also need JUnit:
http://www.junit.org/
CLI uses the new jakarta-turbine-maven system for producing
lovely metrics and such:
http://jakarta.apache.org/turbine/maven/
Once you have these three components installed and configured,
simple type:
ant
The system will build and test itself.
For complete documentation and to create a local copy of the
CLI project website, type:
ant maven:site
Good luck!
-The CLI Team
1.1 jakarta-commons/cli/project.xml
Index: project.xml
===================================================================
<?xml version="1.0" encoding="UTF-8"?>
<project>
<pomVersion>3</pomVersion>
<name>commons-cli</name>
<id>commons-cli</id>
<currentVersion>1.0-dev</currentVersion>
<organization>
<name>Apache Software Foundation</name>
<url>http://www.apache.org</url>
</organization>
<inceptionYear>2002</inceptionYear>
<package>org.apache.commons.cli</package>
<shortDescription>Commons CLI</shortDescription>
<gumpRepositoryId>jakarta</gumpRepositoryId>
<description>
Commons CLI provdes a simple API for working with the command line arguments and options.
</description>
<url>http://jakarta.apache.org/commons/cli.html</url>
<issueTrackingUrl>http://nagoya.apache.org/</issueTrackingUrl>
<siteAddress>jakarta.apache.org</siteAddress>
<siteDirectory>/www/jakarta.apache.org/commons/cli/</siteDirectory>
<distributionDirectory>/www/jakarta.apache.org/builds/jakarta-commons/cli/</distributionDirectory>
<repository>
<connection>scm:cvs:pserver:anoncvs@cvs.apache.org:/home/cvspublic:jakarta-commons/cli</connection>
<url>http://cvs.apache.org/viewcvs/jakarta-commons/cli/</url>
</repository>
<mailingLists>
<mailingList>
<name>Commons Dev List</name>
<subscribe>commons-dev-subscribe@jakarta.apache.org</subscribe>
<unsubscribe>commons-dev-unsubscribe@jakarta.apache.org</unsubscribe>
<archive>http://nagoya.apache.org/eyebrowse/SummarizeList?listName=commons-dev@jakarta.apache.org</archive>
</mailingList>
</mailingLists>
<developers>
<developer>
<name>James Strachan</name>
<id>jstrachan</id>
<email>jstrachan@apache.org</email>
<organization>SpiritSoft, Inc.</organization>
</developer>
<developer>
<name>bob mcwhirter</name>
<id>bob</id>
<email>bob@werken.com</email>
<organization>Werken</organization>
</developer>
<developer>
<name>John Keys</name>
<id>johnkeys</id>
<email/>
<organization/>
</developer>
</developers>
<dependencies>
<dependency>
<id>commons-logging</id>
<type>required</type>
<version>1.0</version>
<!-- <jar>commons-logging-1.0.jar</jar> -->
</dependency>
<dependency>
<id>commons-lang</id>
<type>required</type>
<version>0.1-dev</version>
</dependency>
</dependencies>
<build>
<nagEmailAddress>commons-dev@jakarta.apache.org</nagEmailAddress>
<sourceDirectory>src/java</sourceDirectory>
<unitTestSourceDirectory>src/test</unitTestSourceDirectory>
<integrationUnitTestSourceDirectory/>
<aspectSourceDirectory/>
<!-- Unit test classes -->
<unitTestPatterns>
<unitTestPattern>include = **/*Test*.java</unitTestPattern>
</unitTestPatterns>
<!-- Integration unit test classes -->
<integrationUnitTestPatterns></integrationUnitTestPatterns>
<!-- J A R R E S O U R C E S -->
<!-- Resources that are packaged up inside the JAR file -->
<jarResources>
<jarResource>include = **/*.properties</jarResource>
</jarResources>
</build>
</project>
1.1 jakarta-commons/cli/project.properties
Index: project.properties
===================================================================
# -------------------------------------------------------------------
# P R O J E C T P R O P E R T I E S
# -------------------------------------------------------------------
compile.debug = on
compile.optimize = off
compile.deprecation = off
maven.jarResources.basedir=${basedir}/src/java
# coding standards
maven.checkstyle.lcurly.type = ignore
maven.checkstyle.lcurly.method = ignore
maven.checkstyle.lcurly.other = ignore
maven.checkstyle.header.file = LICENSE.txt
maven.checkstyle.header.ignore.line = 1,2,3,4
maven.checkstyle.const.pattern = ^[a-z][a-zA-Z0-9]*$
maven.checkstyle.member.pattern = ^[_]?[a-z]?[a-zA-Z0-9]*$
maven.checkstyle.ignore.line.len.pattern = ^[ \* \$]+[.]*
maven.checkstyle.javadoc.scope = protected
# disable these non-critical errors to highlight
# more important ones like missing javadoc
maven.checkstyle.max.line.len = 100
maven.checkstyle.ignore.whitespace = true
maven.checkstyle.ignore.public.in.interface = true
1.1 jakarta-commons/cli/gump.xml
Index: gump.xml
===================================================================
<module name="commons-cli">
<description>Commons CLI</description>
<url href="http://jakarta.apache.org/commons/sandbox/cli.html"/>
<cvs repository="jakarta"/>
<!-- This is really the cvs module. We need to change this but -->
<!-- I will leave this for now until everything works. -->
<project name="commons-cli">
<!-- Standard Maven target to produce Javadocs, source -->
<!-- and binary distributions. -->
<ant buildfile="build-gump.xml" target="jar">
<property name="maven.final.name" value="commons-cli-@@DATE@@"/>
</ant>
<package>org.apache.commons.cli</package>
<!-- All Maven projects need Ant and Xerces to build. -->
<depend project="jakarta-ant"/>
<depend project="xml-xerces"/>
<depend project="commons-logging"/>
<depend project="commons-lang"/>
<work nested="target/classes"/>
<home nested="target"/>
<jar name="commons-cli-@@DATE@@.jar"/>
<javadoc nested="docs/apidocs"/>
<nag from="Maven Developers <turbine-maven-dev@jakarta.apache.org>"
to="commons-dev@jakarta.apache.org"/>
</project>
</module>
1.1 jakarta-commons/cli/src/java/org/apache/commons/cli/Option.java
Index: Option.java
===================================================================
/*
* $Header: /home/cvs/jakarta-commons-sandbox/cli/src/java/org/apache/commons/cli/Option.java,v 1.6 2002/06/06 22:50:14 bayard Exp $
* $Revision: 1.6 $
* $Date: 2002/06/06 22:50:14 $
*
* ====================================================================
*
* 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/>.
*
*/
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE file.
*
* $Id: Option.java,v 1.6 2002/06/06 22:50:14 bayard Exp $
*/
package org.apache.commons.cli;
import java.util.ArrayList;
/** <p>Describes a single command-line option. It maintains
* information regarding the short-name of the option, the long-name,
* if any exists, a flag indicating if an argument is required for
* this option, and a self-documenting description of the option.</p>
*
* <p>An Option is not created independantly, but is create through
* an instance of {@link Options}.<p>
*
* @see org.apache.commons.cli.Options
* @see org.apache.commons.cli.CommandLine
*
* @author bob mcwhirter (bob @ werken.com)
* @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
* @version $Revision: 1.6 $
*/
public class Option {
/** opt the single character representation of the option */
private Character opt = null;
/** longOpt is the long representation of the option */
private String longOpt = null;
/** hasArg specifies whether this option has an associated argument */
private boolean hasArg = false;
/** description of the option */
private String description = null;
/** required specifies whether this option is required to be present */
private boolean required = false;
/** multipleArgs specifies whether this option has multiple argument values */
private boolean multipleArgs = false;
/** the type of this Option */
private Object type = null;
/** ?? **/
private ArrayList values = new ArrayList();
/**
* Creates an Option using the specified parameters.
*
* @param opt character representation of the option
* @param hasArg specifies whether the Option takes an argument or not
* @param description describes the function of the option
*/
public Option(char opt, boolean hasArg, String description) {
this(opt, null, hasArg, description, false, false);
}
/**
* Creates an Option using the specified parameters.
*
* @param opt character representation of the option
* @param longOpt the long representation of the option
* @param hasArg specifies whether the Option takes an argument or not
* @param description describes the function of the option
*/
public Option(char opt, String longOpt, boolean hasArg, String description) {
this(opt, longOpt, hasArg, description, false, false );
}
/**
* Creates an Option using the specified parameters.
*
* @param opt character representation of the option
* @param longOpt the long representation of the option
* @param hasArg specifies whether the Option takes an argument or not
* @param description describes the function of the option
* @param required specifies whether the option is required or not
*/
public Option(char opt, String longOpt, boolean hasArg, String description,
boolean required ) {
this(opt, longOpt, hasArg, description, required, false );
}
/**
* Creates an Option using the specified parameters.
*
* @param opt character representation of the option
* @param longOpt the long representation of the option
* @param hasArg specifies whether the Option takes an argument or not
* @param description describes the function of the option
* @param required specifies whether the option is required or not
* @param multipleArgs specifies whether the option has multiple argument
* values
*/
public Option(char opt, String longOpt, boolean hasArg, String description,
boolean required, boolean multipleArgs ) {
this(opt, longOpt, hasArg, description, required, multipleArgs, null );
}
public Option(char opt, String longOpt, boolean hasArg, String description,
boolean required, boolean multipleArgs, Object type ) {
this.opt = new Character( opt );
this.longOpt = longOpt;
this.hasArg = hasArg;
this.description = description;
this.required = required;
this.multipleArgs = multipleArgs;
this.type = type;
}
/** <p>Retrieve the single-character name of this Option</p>
*
* <p>It is this character which can be used with
* {@link CommandLine#hasOption(char opt)} and
* {@link CommandLine#getOptionValue(char opt)} to check
* for existence and argument.<p>
*
* @return Single character name of this option
*/
public char getOpt() {
return this.opt.charValue();
}
public Object getType() {
return this.type;
}
/** <p>Retrieve the long name of this Option</p>
*
* @return Long name of this option, or null, if there is no long name
*/
public String getLongOpt() {
return this.longOpt;
}
/** <p>Query to see if this Option has a long name</p>
*
* @return boolean flag indicating existence of a long name
*/
public boolean hasLongOpt() {
return ( this.longOpt != null );
}
/** <p>Query to see if this Option requires an argument</p>
*
* @return boolean flag indicating if an argument is required
*/
public boolean hasArg() {
return this.hasArg;
}
/** <p>Retrieve the self-documenting description of this Option</p>
*
* @return The string description of this option
*/
public String getDescription() {
return this.description;
}
/** <p>Query to see if this Option requires an argument</p>
*
* @return boolean flag indicating if an argument is required
*/
public boolean isRequired() {
return this.required;
}
/** <p>Query to see if this Option can take multiple values</p>
*
* @return boolean flag indicating if multiple values are allowed
*/
public boolean hasMultipleArgs() {
return this.multipleArgs;
}
/** <p>Dump state, suitable for debugging.</p>
*
* @return Stringified form of this object
*/
public String toString() {
StringBuffer buf = new StringBuffer().append("[ option: ");
buf.append( this.opt );
if ( this.longOpt != null ) {
buf.append(" ")
.append(this.longOpt);
}
buf.append(" ");
if ( hasArg ) {
buf.append( "+ARG" );
}
buf.append(" :: ")
.append( this.description );
if ( this.type != null ) {
buf.append(" :: ")
.append( this.type );
}
buf.append(" ]");
return buf.toString();
}
/**
* Adds the specified value to this Option
*
* @param value is a/the value of this Option
*/
public void addValue( String value ) {
this.values.add( value );
}
/**
* @return the value/first value of this Option or null if there are no
* values
*/
public String getValue() {
return this.values.size()==0 ? null : (String)this.values.get( 0 );
}
/**
* @return the values of this Option or null if there are no
* values
*/
public String[] getValues() {
return this.values.size()==0 ? null : (String[])this.values.toArray(new String[]{});
}
}
1.1 jakarta-commons/cli/src/java/org/apache/commons/cli/MissingOptionException.java
Index: MissingOptionException.java
===================================================================
/*
* $Header: /home/cvs/jakarta-commons-sandbox/cli/src/java/org/apache/commons/cli/MissingOptionException.java,v 1.2 2002/06/06 09:37:26 jstrachan Exp $
* $Revision: 1.2 $
* $Date: 2002/06/06 09:37:26 $
*
* ====================================================================
*
* 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;
/** <p>Exception thrown when an option requiring an argument
* is not provided with an argument.</p>
*
* @author bob mcwhirter (bob @ werken.com)
* @version $Revision: 1.2 $
*/
public class MissingOptionException extends ParseException {
/** Construct a new Exception with a message
*
* @param msg Explanation of the exception
*/
public MissingOptionException(String msg) {
super(msg);
}
}
1.1 jakarta-commons/cli/src/java/org/apache/commons/cli/ParseException.java
Index: ParseException.java
===================================================================
/*
* $Header: /home/cvs/jakarta-commons-sandbox/cli/src/java/org/apache/commons/cli/ParseException.java,v 1.2 2002/06/06 09:37:26 jstrachan Exp $
* $Revision: 1.2 $
* $Date: 2002/06/06 09:37:26 $
*
* ====================================================================
*
* 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;
/** <p>Base for Exceptions thrown during parsing of a command-line<p>
*
* @author bob mcwhirter (bob @ werken.com)
* @version $Revision: 1.2 $
*/
public class ParseException extends Exception
{
/** Construct a new Exception with a message
*
* @param msg Explanation of the exception
*/
public ParseException(String msg) {
super(msg);
}
}
1.1 jakarta-commons/cli/src/java/org/apache/commons/cli/AlreadySelectedException.java
Index: AlreadySelectedException.java
===================================================================
/*
* $Header: /home/cvs/jakarta-commons-sandbox/cli/src/java/org/apache/commons/cli/AlreadySelectedException.java,v 1.4 2002/06/06 09:37:26 jstrachan Exp $
* $Revision: 1.4 $
* $Date: 2002/06/06 09:37:26 $
*
* ====================================================================
*
* 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;
/** <p>Exception thrown when more than one option in an option group
* has been provided.</p>
*
* @author John Keyes (john @ integralsource.com)
* @version $Revision: 1.4 $
*/
class AlreadySelectedException extends ParseException {
/** Construct a new Exception with a message
*
* @param message Explanation of the exception
*/
public AlreadySelectedException( String message ) {
super( message );
}
}
1.1 jakarta-commons/cli/src/java/org/apache/commons/cli/package.html
Index: package.html
===================================================================
<body>
<p>Commons CLI -- version ##VERSION## (##QUALITY##)</p>
</body>
1.1 jakarta-commons/cli/src/java/org/apache/commons/cli/Options.java
Index: Options.java
===================================================================
/*
* $Header: /home/cvs/jakarta-commons-sandbox/cli/src/java/org/apache/commons/cli/Options.java,v 1.5 2002/06/06 22:32:37 bayard Exp $
* $Revision: 1.5 $
* $Date: 2002/06/06 22:32:37 $
*
* ====================================================================
*
* 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.Map;
import java.util.Set;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.Collections;
/** <p>Main entry-point into the <code>werken.opt</code> library.</p>
*
* <p>Options represents a collection of {@link Option} objects, which
* describe the possible options for a command-line.<p>
*
* <p>It may flexibly parse long and short options, with or without
* values. Additionally, it may parse only a portion of a commandline,
* allowing for flexible multi-stage parsing.<p>
*
* @see org.apache.commons.cli.CommandLine
*
* @author bob mcwhirter (bob @ werken.com)
* @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
* @version $Revision: 1.5 $
*/
public class Options {
/** the list of options */
private List options = new ArrayList();
/** a map of the options with the character key */
private Map shortOpts = new HashMap();
/** a map of the options with the long key */
private Map longOpts = new HashMap();
/** a map of the required options */
private Map requiredOpts = new HashMap();
/** a map of the option groups */
private Map optionGroups = new HashMap();
/** <p>Construct a new Options descriptor</p>
*/
public Options() {
}
/**
* <p>Add the specified option group.</p>
*
* @param group the OptionGroup that is to be added
* @return the resulting Options instance
*/
public Options addOptionGroup( OptionGroup group ) {
Iterator options = group.getOptions().iterator();
while( options.hasNext() ) {
Option option = (Option)options.next();
addOption( option );
optionGroups.put( option, group );
}
return this;
}
/** <p>Add an option that only contains a short-name</p>
* <p>It may be specified as requiring an argument.</p>
*
* @param opt Short single-character name of the option.
* @param hasArg flag signally if an argument is required after this option
* @param description Self-documenting description
* @return the resulting Options instance
*/
public Options addOption(char opt, boolean hasArg, String description) {
addOption( opt, null, hasArg, description, false );
return this;
}
/** <p>Add an option that contains a short-name and a long-name</p>
* <p>It may be specified as requiring an argument.</p>
*
* @param opt Short single-character name of the option.
* @param longOpt Long multi-character name of the option.
* @param hasArg flag signally if an argument is required after this option
* @param description Self-documenting description
* @return the resulting Options instance
*/
public Options addOption(char opt, String longOpt, boolean hasArg, String description) {
addOption( opt, longOpt, hasArg, description, false );
return this;
}
/** <p>Add an option that contains a short-name and a long-name</p>
* <p>It may be specified as requiring an argument.</p>
*
* @param opt Short single-character name of the option.
* @param longOpt Long multi-character name of the option.
* @param hasArg flag signally if an argument is required after this option
* @param description Self-documenting description
* @param required specifies if this option is required
* @return the resulting Options instance
*/
public Options addOption(char opt, String longOpt, boolean hasArg, String description,
boolean required) {
addOption( new Option(opt, longOpt, hasArg, description, required) );
return this;
}
/** <p>Add an option that contains a short-name and a long-name</p>
* <p>It may be specified as requiring an argument.</p>
*
* @param opt Short single-character name of the option.
* @param longOpt Long multi-character name of the option.
* @param hasArg flag signally if an argument is required after this option
* @param description Self-documenting description
* @param required specifies if this option is required
* @param multipleArgs specifies if this option can accept multiple argument values
* @return the resulting Options instance
*/
public Options addOption(char opt, String longOpt, boolean hasArg, String description,
boolean required, boolean multipleArgs) {
addOption( new Option(opt, longOpt, hasArg, description, required, multipleArgs) );
return this;
}
public Options addOption(char opt, String longOpt, boolean hasArg, String description,
boolean required, boolean multipleArgs, Object type) {
addOption( new Option(opt, longOpt, hasArg, description, required, multipleArgs, type) );
return this;
}
/** <p>Parse the given list of arguments against this descriptor<p>
*
* @param args Args to parse
*
* @return {@link CommandLine} containing information related to parse state
*
* @throws MissingArgumentException if an argument value for an option is not present
* @throws UnrecognizedOptionException if an unrecognised option is present
* @throws MissingOptionException if a required option is not present
* @throws AlreadySelectedException if the same option appears more than once
*/
public CommandLine parse(String[] args)
throws MissingArgumentException, UnrecognizedOptionException,
MissingOptionException, AlreadySelectedException {
return parse( args, 0, args.length, false);
}
/** <p>Parse the given list of arguments against this descriptor</p>
*
* <p>This method will cease parsing upon the first non-option token,
* storing the rest of the tokens for access through {@link CommandLine#getArgs()}.</p>
*
* <p>This is useful for parsing a command-line in pieces, such as:</p>
*
* <p><code>
* <pre>
* myApp -s <server> -p <port> command -p <printer> -s <style>
* </pre>
* </code></p>
*
* <p>Here, it'll parse up-to, but not including <code>command</code>. The
* tokens <code>command -p <printer> -s <style></code> are available
* through {@link CommandLine#getArgs()}, which may subsequently be parsed by
* another different <code>Options</code> instance.<p>
*
* @param args Args to parse
* @param stopAtNonOption stop parsing at the first non-option token
*
* @return {@link CommandLine} containing information related to parse state
*
* @throws MissingArgumentException if an argument value for an option is not present
* @throws UnrecognizedOptionException if an unrecognised option is present
* @throws MissingOptionException if a required option is not present
* @throws AlreadySelectedException if the same option appears more than once
*/
public CommandLine parse(String[] args, boolean stopAtNonOption)
throws MissingArgumentException, UnrecognizedOptionException,
MissingOptionException, AlreadySelectedException {
return parse( args, 0, args.length, stopAtNonOption);
}
/** <p>Parse the given list of arguments against this descriptor</p>
*
* <p>This method allows parsing from <code>formIndex</code> inclusive
* to <code>toIndex</code> exclusive, of the <code>args</code> parameter,
* to allow parsing a specific portion of a command-line.<p>
*
* @param args Args to parse
* @param fromIndex index of args to start parsing
* @param toIndex index of args to stop parsing
*
* @return {@link CommandLine} containing information related to parse state
*
* @throws MissingArgumentException if an argument value for an option is not present
* @throws UnrecognizedOptionException if an unrecognised option is present
* @throws MissingOptionException if a required option is not present
* @throws AlreadySelectedException if the same option appears more than once
*/
public CommandLine parse(String[] args, int fromIndex, int toIndex)
throws MissingArgumentException, UnrecognizedOptionException,
MissingOptionException, AlreadySelectedException {
return parse( args, fromIndex, toIndex, false );
}
/** <p>Parse the given list of arguments against this descriptor</p>
*
* <p>This method will cease parsing upon the first non-option token,
* storing the rest of the tokens for access through {@link CommandLine#getArgs()}.</p>
*
* <p>This is useful for parsing a command-line in pieces, such as:</p>
*
* <p><code>
* <pre>
* myApp -s <server> -p <port> command -p <printer> -s <style>
* </pre>
* </code></p>
*
* <p>Here, it'll parse up-to, but not including <code>command</code>. The
* tokens <code>command -p <printer> -s <style></code> are available
* through {@link CommandLine#getArgs()}, which may subsequently be parsed by
* another different <code>Options</code> instance.<p>
*
* <p>This method also allows parsing from <code>formIndex</code> inclusive
* to <code>toIndex</code> exclusive, of the <code>args</code> parameter,
* to allow parsing a specific portion of a command-line.<p>
*
* @param args Args to parse
* @param fromIndex index of args to start parsing
* @param toIndex index of args to stop parsing
* @param stopAtNonOption stop parsing at the first non-option token
*
* @return {@link CommandLine} containing information related to parse state
*
* @throws MissingArgumentException if an argument value for an option is not present
* @throws UnrecognizedOptionException if an unrecognised option is present
* @throws MissingOptionException if a required option is not present
* @throws AlreadySelectedException if the same option appears more than once
*/
public CommandLine parse(String[] args, int fromIndex, int toIndex, boolean stopAtNonOption)
throws MissingArgumentException, UnrecognizedOptionException,
MissingOptionException, AlreadySelectedException {
List argList = java.util.Arrays.asList( args );
return parse( argList, stopAtNonOption);
}
/** <p>Parse the given list of arguments against this descriptor</p>
*
* @param args Args to parse
*
* @return {@link CommandLine} containing information related to parse state
*
* @throws MissingArgumentException if an argument value for an option is not present
* @throws UnrecognizedOptionException if an unrecognised option is present
* @throws MissingOptionException if a required option is not present
* @throws AlreadySelectedException if the same option appears more than once
*/
public CommandLine parse(List args)
throws MissingArgumentException, UnrecognizedOptionException,
MissingOptionException, AlreadySelectedException {
return parse( args, false );
}
/** <p>Parse the given list of arguments against this descriptor</p>
*
* <p>This method will cease parsing upon the first non-option token,
* storing the rest of the tokens for access through {@link CommandLine#getArgs()}.</p>
*
* <p>This is useful for parsing a command-line in pieces, such as:</p>
*
* <p><code>
* <pre>
* myApp -s <server> -p <port> command -p <printer> -s <style>
* </pre>
* </code></p>
*
* <p>Here, it'll parse up-to, but not including <code>command</code>. The
* tokens <code>command -p <printer> -s <style></code> are available
* through {@link CommandLine#getArgs()}, which may subsequently be parsed by
* another different <code>Options</code> instance.<p>
*
* <p>This method also allows parsing from <code>formIndex</code> inclusive
* to <code>toIndex</code> exclusive, of the <code>args</code> parameter,
* to allow parsing a specific portion of a command-line.<p>
*
* @param inArgs Arguments to parse
* @param stopAtNonOption stop parsing at the first non-option token
*
* @return {@link CommandLine} containing information related to parse state
*
* @throws MissingArgumentException if an argument value for an option is not present
* @throws UnrecognizedOptionException if an unrecognised option is present
* @throws MissingOptionException if a required option is not present
* @throws AlreadySelectedException if the same option appears more than once
*/
public CommandLine parse(List inArgs, boolean stopAtNonOption)
throws MissingArgumentException, UnrecognizedOptionException,
MissingOptionException, AlreadySelectedException {
CommandLine cl = new CommandLine();
List args = burst( inArgs, stopAtNonOption );
ListIterator argIter = args.listIterator();
String eachArg = null;
Option eachOpt = null;
boolean eatTheRest = false;
while ( argIter.hasNext() ) {
eachArg = (String) argIter.next();
if ( eachArg.equals("--") ) {
// signalled end-of-opts. Eat the rest
eatTheRest = true;
}
else if ( eachArg.startsWith("--") ) {
eachOpt = (Option) longOpts.get( eachArg );
processOption( eachArg, eachOpt, argIter, cl );
}
else if ( eachArg.equals("-") ) {
// Just-another-argument
if ( stopAtNonOption ) {
eatTheRest = true;
}
else {
cl.addArg( eachArg );
}
}
else if ( eachArg.startsWith("-") ) {
eachOpt = (Option) shortOpts.get( eachArg );
processOption( eachArg, eachOpt, argIter, cl );
}
else {
cl.addArg( eachArg );
if ( stopAtNonOption ) {
eatTheRest = true;
}
}
if ( eatTheRest ) {
while ( argIter.hasNext() ) {
eachArg = (String) argIter.next();
cl.addArg( eachArg );
}
}
}
// this will throw a MissingOptionException
checkRequiredOptions();
return cl;
}
/**
* @throws MissingOptionException if all of the required options are
* not present.
*/
private void checkRequiredOptions() throws MissingOptionException {
if( requiredOpts.size() > 0 ) {
Set optKeys = requiredOpts.keySet();
Iterator iter = optKeys.iterator();
StringBuffer buff = new StringBuffer();
while( iter.hasNext() ) {
Option missing = (Option)requiredOpts.get( iter.next() );
buff.append( "-" );
buff.append( missing.getOpt() );
buff.append( " " );
buff.append( missing.getDescription() );
}
throw new MissingOptionException( buff.toString() );
}
}
/**
* <p>processOption rakes the current option and checks if it is
* an unrecognised option, whether the argument value is missing or
* whether the option has already been selected.</p>
*
* @param eachArg the current option read from command line
* @param option the current option corresponding to eachArg
* @param argIter the argument iterator
* @param cl the current command line
*
* @throws MissingArgumentException if an argument value for an option is not present
* @throws UnrecognizedOptionException if an unrecognised option is present
* @throws AlreadySelectedException if the same option appears more than once
*/
private void processOption( String eachArg, Option option, ListIterator argIter,
CommandLine cl)
throws UnrecognizedOptionException, AlreadySelectedException,
MissingArgumentException {
if ( option == null ) {
throw new UnrecognizedOptionException("Unrecognized option: " + eachArg);
}
else {
if ( optionGroups.get( option ) != null ) {
( (OptionGroup)( optionGroups.get( option ) ) ).setSelected( option );
}
// if required remove from list
if ( option.isRequired() ) {
requiredOpts.remove( "-" + option.getOpt() );
}
if ( option.hasArg() ) {
if ( argIter.hasNext() ) {
eachArg = (String) argIter.next();
option.addValue( eachArg );
if( option.hasMultipleArgs() ) {
while( argIter.hasNext() ) {
eachArg = (String)argIter.next();
if( eachArg.startsWith("-") ) {
argIter.previous();
cl.setOpt( option );
break;
}
else {
option.addValue( eachArg );
}
}
}
else {
cl.setOpt( option );
return;
}
if( !argIter.hasNext() ) {
cl.setOpt( option );
}
}
else {
throw new MissingArgumentException( eachArg + " requires an argument.");
}
}
else {
//option.addValue( null );
cl.setOpt( option );
}
}
}
/**
* <p>Processes the argument list according to POSIX command line
* processing rules.</p>
*
* @param inArgs the argument list
* @param stopAtNonOption stop processing when the first non option
* is encountered.
* @return the processed list of arguments.
*/
private List burst(List inArgs, boolean stopAtNonOption) {
List args = new LinkedList();
Iterator argIter = inArgs.iterator();
String eachArg = null;
boolean eatTheRest = false;
while ( argIter.hasNext() ) {
eachArg = (String) argIter.next();
if ( eachArg.equals("--") ) {
// Look for -- to indicate end-of-options, and
// just stuff it, along with everything past it
// into the returned list.
args.add( eachArg );
eatTheRest = true;
}
else if ( eachArg.startsWith("--") ) {
// It's a long-option, so doesn't need any
// bursting applied to it.
args.add( eachArg );
}
else if ( eachArg.startsWith("-") ) {
// It might be a short arg needing
// some bursting
if ( eachArg.length() == 1) {
// It's not really an option, so
// just drop it on the list
if ( stopAtNonOption ) {
eatTheRest = true;
}
else {
args.add( eachArg );
}
}
else if ( eachArg.length() == 2 ) {
// No bursting required
args.add( eachArg );
}
else {
// Needs bursting. Figure out
// if we have multiple options,
// or maybe an option plus an arg,
// or some combination thereof.
for ( int i = 1 ; i < eachArg.length() ; ++i ) {
String optStr = "-" + eachArg.charAt(i);
Option opt = (Option) shortOpts.get( optStr );
if ( (opt != null) && (opt.hasArg()) ) {
// If the current option has an argument,
// then consider the rest of the eachArg
// to be that argument.
args.add( optStr );
if ( (i+1) < eachArg.length() ) {
String optArg = eachArg.substring(i+1);
args.add( optArg );
}
break;
}
else {
// No argument, so prepend the single dash,
// and then drop it into the arglist.
args.add( optStr );
}
}
}
}
else {
// It's just a normal non-option arg,
// so dump it into the list of returned
// values.
args.add( eachArg );
if ( stopAtNonOption ) {
eatTheRest = true;
}
}
if ( eatTheRest ) {
while ( argIter.hasNext() ) {
args.add( argIter.next() );
}
}
}
return args;
}
/**
* <p>Adds the option to the necessary member lists</p>
*
* @param opt the option that is to be added
*/
private void addOption(Option opt) {
String shortOptStr = "-" + opt.getOpt();
if ( opt.hasLongOpt() ) {
longOpts.put( "--" + opt.getLongOpt(), opt );
}
if ( opt.isRequired() ) {
requiredOpts.put( "-" + opt.getOpt(), opt );
}
shortOpts.put( "-" + opt.getOpt(), opt );
options.add( opt );
}
/** <p>Retrieve a read-only list of options in this set</p>
*
* @return read-only List of {@link Option} objects in this descriptor
*/
public List getOptions() {
return Collections.unmodifiableList(options);
}
/** <p>Retrieve the named {@link Option}<p>
*
* @param opt short single-character name of the {@link Option}
* @return the option represented by opt
*/
public Option getOption(char opt) {
return (Option) shortOpts.get( "-" + opt );
}
/** <p>Retrieve the named {@link Option}<p>
*
* @param longOpt long name of the {@link Option}
* @return the option represented by longOpt
*/
public Option getOption(String longOpt) {
return (Option) longOpts.get( longOpt );
}
/** <p>Dump state, suitable for debugging.</p>
*
* @return Stringified form of this object
*/
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("[ Options: [ short ");
buf.append( shortOpts.toString() );
buf.append( " ] [ long " );
buf.append( longOpts );
buf.append( " ]");
return buf.toString();
}
}
1.1 jakarta-commons/cli/src/java/org/apache/commons/cli/HelpFormatter.java
Index: HelpFormatter.java
===================================================================
/*
* Copyright (C) The Apache Software Foundation. All rights reserved.
*
* This software is published under the terms of the Apache Software License
* version 1.1, a copy of which has been included with this distribution in
* the LICENSE file.
*
* $Id: HelpFormatter.java,v 1.2 2002/05/17 11:44:32 jstrachan Exp $
*/
package org.apache.commons.cli;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* A formatter of help messages for the current command line options
*
* @author Slawek Zachcial
**/
public class HelpFormatter
{
// --------------------------------------------------------------- Constants
public static final int DEFAULT_WIDTH = 80;
public static final int DEFAULT_LEFT_PAD = 1;
public static final int DEFAULT_DESC_PAD = 3;
public static final String DEFAULT_SYNTAX_PREFIX = "usage: ";
public static final String DEFAULT_OPT_PREFIX = "-";
public static final String DEFAULT_LONG_OPT_PREFIX = "--";
public static final String DEFAULT_ARG_NAME = "arg";
// ------------------------------------------------------------------ Static
// -------------------------------------------------------------- Attributes
public int defaultWidth;
public int defaultLeftPad;
public int defaultDescPad;
public String defaultSyntaxPrefix;
public String defaultNewLine;
public String defaultOptPrefix;
public String defaultLongOptPrefix;
public String defaultArgName;
// ------------------------------------------------------------ Constructors
public HelpFormatter()
{
defaultWidth = DEFAULT_WIDTH;
defaultLeftPad = DEFAULT_LEFT_PAD;
defaultDescPad = DEFAULT_DESC_PAD;
defaultSyntaxPrefix = DEFAULT_SYNTAX_PREFIX;
defaultNewLine = System.getProperty("line.separator");
defaultOptPrefix = DEFAULT_OPT_PREFIX;
defaultLongOptPrefix = DEFAULT_LONG_OPT_PREFIX;
defaultArgName = DEFAULT_ARG_NAME;
}
// ------------------------------------------------------------------ Public
public void printHelp( String cmdLineSyntax,
Options options )
{
printHelp( defaultWidth, cmdLineSyntax, null, options, null );
}
public void printHelp( String cmdLineSyntax,
String header,
Options options,
String footer )
{
printHelp(defaultWidth, cmdLineSyntax, header, options, footer);
}
public void printHelp( int width,
String cmdLineSyntax,
String header,
Options options,
String footer )
{
PrintWriter pw = new PrintWriter(System.out);
printHelp( pw, width, cmdLineSyntax, header,
options, defaultLeftPad, defaultDescPad, footer );
pw.flush();
}
public void printHelp( PrintWriter pw,
int width,
String cmdLineSyntax,
String header,
Options options,
int leftPad,
int descPad,
String footer )
throws IllegalArgumentException
{
if ( cmdLineSyntax == null || cmdLineSyntax.length() == 0 )
{
throw new IllegalArgumentException("cmdLineSyntax not provided");
}
printUsage( pw, width, cmdLineSyntax );
if ( header != null && header.trim().length() > 0 )
{
printWrapped( pw, width, header );
}
printOptions( pw, width, options, leftPad, descPad );
if ( footer != null && footer.trim().length() > 0 )
{
printWrapped( pw, width, footer );
}
}
public void printUsage( PrintWriter pw, int width, String cmdLineSyntax )
{
int argPos = cmdLineSyntax.indexOf(' ') + 1;
printWrapped(pw, width, defaultSyntaxPrefix.length() + argPos,
defaultSyntaxPrefix + cmdLineSyntax);
}
public void printOptions( PrintWriter pw, int width, Options options, int leftPad, int descPad )
{
StringBuffer sb = new StringBuffer();
renderOptions(sb, width, options, leftPad, descPad);
pw.println(sb.toString());
}
public void printWrapped( PrintWriter pw, int width, String text )
{
printWrapped(pw, width, 0, text);
}
public void printWrapped( PrintWriter pw, int width, int nextLineTabStop, String text )
{
StringBuffer sb = new StringBuffer(text.length());
renderWrappedText(sb, width, nextLineTabStop, text);
pw.println(sb.toString());
}
// --------------------------------------------------------------- Protected
protected StringBuffer renderOptions( StringBuffer sb,
int width,
Options options,
int leftPad,
int descPad )
{
final String lpad = createPadding(leftPad);
final String dpad = createPadding(descPad);
//first create list containing only <lpad>-a,--aaa where -a is opt and --aaa is
//long opt; in parallel look for the longest opt string
//this list will be then used to sort options ascending
int max = 0;
StringBuffer optBuf;
List prefixList = new ArrayList();
Option option;
for ( Iterator i = options.getOptions().iterator(); i.hasNext(); )
{
option = (Option) i.next();
optBuf = new StringBuffer(8);
optBuf.append(lpad).append(defaultOptPrefix).append(option.getOpt());
if ( option.hasLongOpt() )
{
optBuf.append(',').append(defaultLongOptPrefix).append(option.getLongOpt());
}
if ( option.hasArg() )
{
//FIXME - should have a way to specify arg name per option
optBuf.append(' ').append(defaultArgName);
}
prefixList.add(optBuf);
max = optBuf.length() > max ? optBuf.length() : max;
}
//right pad the prefixes
for ( Iterator i = prefixList.iterator(); i.hasNext(); )
{
optBuf = (StringBuffer) i.next();
if ( optBuf.length() < max )
{
optBuf.append(createPadding(max-optBuf.length()));
}
optBuf.append(dpad);
}
//sort this list ascending
Collections.sort(prefixList, new StringBufferComparator());
//finally render options
int nextLineTabStop = max + descPad;
char opt;
int optOffset = leftPad + defaultOptPrefix.length();
for ( Iterator i = prefixList.iterator(); i.hasNext(); )
{
optBuf = (StringBuffer) i.next();
opt = optBuf.charAt(optOffset);
option = options.getOption(opt);
renderWrappedText(sb, width, nextLineTabStop,
optBuf.append(option.getDescription()).toString());
if ( i.hasNext() )
{
sb.append(defaultNewLine);
}
}
return sb;
}
protected StringBuffer renderWrappedText( StringBuffer sb,
int width,
int nextLineTabStop,
String text )
{
int pos = findWrapPos( text, width, 0);
if ( pos == -1 )
{
sb.append(rtrim(text));
return sb;
}
else
{
sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine);
}
//all following lines must be padded with nextLineTabStop space characters
final String padding = createPadding(nextLineTabStop);
while ( true )
{
text = padding + text.substring(pos).trim();
pos = findWrapPos( text, width, nextLineTabStop );
if ( pos == -1 )
{
sb.append(text);
return sb;
}
sb.append(rtrim(text.substring(0, pos))).append(defaultNewLine);
}
}
/**
* Finds the next text wrap position after <code>startPos</code> for the text
* in <code>sb</code> with the column width <code>width</code>.
* The wrap point is the last postion before startPos+width having a whitespace
* character (space, \n, \r).
*
* @param sb text to be analyzed
* @param width width of the wrapped text
* @param startPos position from which to start the lookup whitespace character
* @return postion on which the text must be wrapped or -1 if the wrap position is at the end
* of the text
*/
protected int findWrapPos( String text, int width, int startPos )
{
int pos = -1;
// the line ends before the max wrap pos or a new line char found
if ( ((pos = text.indexOf('\n', startPos)) != -1 && pos <= width) ||
((pos = text.indexOf('\t', startPos)) != -1 && pos <= width) )
{
return pos;
}
else if ( (startPos + width) >= text.length() )
{
return -1;
}
//look for the last whitespace character before startPos+width
pos = startPos + width;
char c;
while ( pos >= startPos && (c = text.charAt(pos)) != ' ' && c != '\n' && c != '\r' )
{
--pos;
}
//if we found it - just return
if ( pos > startPos )
{
return pos;
}
else
{
//must look for the first whitespace chearacter after startPos + width
pos = startPos + width;
while ( pos <= text.length() && (c = text.charAt(pos)) != ' ' && c != '\n' && c != '\r' )
{
++pos;
}
return pos == text.length() ? -1 : pos;
}
}
protected String createPadding(int len)
{
StringBuffer sb = new StringBuffer(len);
for ( int i = 0; i < len; ++i )
{
sb.append(' ');
}
return sb.toString();
}
protected String rtrim( String s )
{
if ( s == null || s.length() == 0 )
{
return s;
}
int pos = s.length();
while ( pos >= 0 && Character.isWhitespace(s.charAt(pos-1)) )
{
--pos;
}
return s.substring(0, pos);
}
// ------------------------------------------------------- Package protected
// ----------------------------------------------------------------- Private
// ----------------------------------------------------------- Inner classes
private static class StringBufferComparator
implements Comparator
{
public int compare( Object o1, Object o2 )
{
return ((StringBuffer) o1).toString().compareTo(((StringBuffer) o2).toString());
}
}
}
1.1 jakarta-commons/cli/src/java/org/apache/commons/cli/TypeHandler.java
Index: TypeHandler.java
===================================================================
/*
* $Header: /home/cvs/jakarta-commons-sandbox/cli/src/java/org/apache/commons/cli/TypeHandler.java,v 1.2 2002/06/06 22:49:36 bayard Exp $
* $Revision: 1.2 $
* $Date: 2002/06/06 22:49:36 $
*
* ====================================================================
*
* 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.io.File;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.Date;
import org.apache.commons.lang.Numbers;
/**
* This is a temporary implementation. TypeHandler will handle the
* pluggableness of OptionTypes and it will direct all of these types
* of conversion functionalities to ConvertUtils component in Commons
* alreayd. BeanUtils I think.
*
* @author Henri Yandell (bayard @ generationjava.com)
* @version $Revision: 1.2 $
*/
public class TypeHandler {
static public Object createValue(String str, Object obj) {
return createValue(str, (Class)obj);
}
static public Object createValue(String str, Class clazz) {
if( PatternOptionBuilder.STRING_VALUE == clazz) {
return str;
} else
if( PatternOptionBuilder.OBJECT_VALUE == clazz) {
return createObject(str);
} else
if( PatternOptionBuilder.NUMBER_VALUE == clazz) {
return createNumber(str);
} else
if( PatternOptionBuilder.DATE_VALUE == clazz) {
return createDate(str);
} else
if( PatternOptionBuilder.CLASS_VALUE == clazz) {
return createClass(str);
} else
if( PatternOptionBuilder.FILE_VALUE == clazz) {
return createFile(str);
} else
if( PatternOptionBuilder.EXISTING_FILE_VALUE == clazz) {
return createFile(str);
} else
if( PatternOptionBuilder.FILES_VALUE == clazz) {
return createFiles(str);
} else
if( PatternOptionBuilder.URL_VALUE == clazz) {
return createURL(str);
} else {
return null;
}
}
/**
* Create an Object from the classname and empty constructor.
* Returns null if it couldn't create the Object.
*/
static public Object createObject(String str) {
Class cl = null;
try {
cl = Class.forName(str);
} catch (ClassNotFoundException cnfe) {
System.err.println("Unable to find: "+str);
return null;
}
Object instance = null;
try {
instance = cl.newInstance();
} catch (InstantiationException cnfe) {
System.err.println("InstantiationException; Unable to create: "+str);
return null;
}
catch (IllegalAccessException cnfe) {
System.err.println("IllegalAccessException; Unable to create: "+str);
return null;
}
return instance;
}
/**
* Create a number from a String.
*/
static public Number createNumber(String str) {
// Needs to be able to create
try {
// do searching for decimal point etc, but atm just make an Integer
return Numbers.createNumber(str);
} catch (NumberFormatException nfe) {
System.err.println(nfe.getMessage());
return null;
}
}
static public Class createClass(String str) {
try {
return Class.forName(str);
} catch (ClassNotFoundException cnfe) {
System.err.println("Unable to find: "+str);
return null;
}
}
static public Date createDate(String str) {
Date date = null;
if(date == null) {
System.err.println("Unable to parse: "+str);
}
return date;
}
static public URL createURL(String str) {
try {
return new URL(str);
} catch (MalformedURLException mue) {
System.err.println("Unable to parse: "+str);
return null;
}
}
static public File createFile(String str) {
return new File(str);
}
static public File[] createFiles(String str) {
// to implement/port:
// return FileW.findFiles(str);
return null;
}
}
1.1 jakarta-commons/cli/src/java/org/apache/commons/cli/OptionGroup.java
Index: OptionGroup.java
===================================================================
/*
* $Header: /home/cvs/jakarta-commons-sandbox/cli/src/java/org/apache/commons/cli/OptionGroup.java,v 1.2 2002/06/06 09:37:26 jstrachan Exp $
* $Revision: 1.2 $
* $Date: 2002/06/06 09:37:26 $
*
* ====================================================================
*
* 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.Collection;
import java.util.HashMap;
import java.util.Iterator;
/**
* A group of mutually exclusive options.
* @author John Keyes ( john at integralsource.com )
* @version $Revision: 1.2 $
*/
public class OptionGroup {
/** hold the options */
private HashMap optionMap = new HashMap();
/** the name of the selected option */
private Option selected;
/**
* add <code>opt</code> to this group
*
* @param opt the option to add to this group
* @return this option group with opt added
*/
public OptionGroup addOption(Option opt) {
// key - option name
// value - the option
optionMap.put( "-" + opt.getOpt(), opt );
return this;
}
/**
* @return the names of the options in this group as a
* <code>Collection</code>
*/
private Collection getNames() {
// the key set is the collection of names
return optionMap.keySet();
}
/**
* @return the options in this group as a <code>Collection</code>
*/
public Collection getOptions() {
// the values are the collection of options
return optionMap.values();
}
/**
* set the selected option of this group to <code>name</code>.
* @param opt the option that is selected
* @throws AlreadySelectedException if an option from this group has
* already been selected.
*/
public void setSelected(Option opt) throws AlreadySelectedException {
// if no option has already been selected or the
// same option is being reselected then set the
// selected member variable
if ( this.selected == null || this.selected.equals( opt ) ) {
this.selected = opt;
}
else {
throw new AlreadySelectedException( "an option from this group has " +
"already been selected: '" +
selected + "'");
}
}
/**
* @return the selected option name
*/
public Option getSelected() {
return selected;
}
/**
* @return the usage string for this option group
*/
/*
public String usageString()
{
StringBuffer buff = new StringBuffer();
buff.append( "<\n");
Iterator oiter = getOptions().iterator();
while( oiter.hasNext() )
{
Option option = (Option)oiter.next();
Collection names = option.getNames();
Iterator iter = names.iterator();
while( iter.hasNext() )
{
buff.append( option.getPrefix() );
buff.append( iter.next() );
if( iter.hasNext() )
{
buff.append( " | " );
}
}
buff.append( " " );
buff.append( option.getDescription( ) );
if ( oiter.hasNext() )
{
buff.append( "\n or\n" );
}
}
buff.append( "\n>");
buff.append( "\n" );
return buff.toString();
}
*/
/**
* <p>Returns the stringified version of this OptionGroup.</p>
* @return the stringified representation of this group
*/
public String toString() {
StringBuffer buff = new StringBuffer();
Iterator iter = getOptions().iterator();
buff.append( "[" );
while( iter.hasNext() ) {
Option option = (Option)iter.next();
buff.append( "-" );
buff.append( option.getOpt() );
buff.append( " " );
buff.append( option.getDescription( ) );
if( iter.hasNext() ) {
buff.append( ", " );
}
}
buff.append( "]" );
return buff.toString();
}
}
1.1 jakarta-commons/cli/src/java/org/apache/commons/cli/PatternOptionBuilder.java
Index: PatternOptionBuilder.java
===================================================================
/*
* $Header: /home/cvs/jakarta-commons-sandbox/cli/src/java/org/apache/commons/cli/PatternOptionBuilder.java,v 1.2 2002/06/06 22:49:36 bayard Exp $
* $Revision: 1.2 $
* $Date: 2002/06/06 22:49:36 $
*
* ====================================================================
*
* 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;
/**
* Allows Options to be created from a single String.
*
*
* @author Henri Yandell (bayard @ generationjava.com)
* @version $Revision: 1.2 $
*/
public class PatternOptionBuilder {
/// TODO: These need to break out to OptionType and also to be pluggable.
static public final Class STRING_VALUE = java.lang.String.class;
static public final Class OBJECT_VALUE = java.lang.Object.class;
static public final Class NUMBER_VALUE = java.lang.Number.class;
static public final Class DATE_VALUE = java.util.Date.class;
static public final Class CLASS_VALUE = java.lang.Class.class;
/// can we do this one??
// is meant to check that the file exists, else it errors.
// ie) it's for reading not writing.
static public final Class EXISTING_FILE_VALUE = java.io.FileInputStream.class;
static public final Class FILE_VALUE = java.io.File.class;
static public final Class FILES_VALUE = java.io.File[].class;
static public final Class URL_VALUE = java.net.URL.class;
static public Object getValueClass(char ch) {
if (ch == '@') {
return PatternOptionBuilder.OBJECT_VALUE;
} else if (ch == ':') {
return PatternOptionBuilder.STRING_VALUE;
} else if (ch == '%') {
return PatternOptionBuilder.NUMBER_VALUE;
} else if (ch == '+') {
return PatternOptionBuilder.CLASS_VALUE;
} else if (ch == '#') {
return PatternOptionBuilder.DATE_VALUE;
} else if (ch == '<') {
return PatternOptionBuilder.EXISTING_FILE_VALUE;
} else if (ch == '>') {
return PatternOptionBuilder.FILE_VALUE;
} else if (ch == '*') {
return PatternOptionBuilder.FILES_VALUE;
} else if (ch == '/') {
return PatternOptionBuilder.URL_VALUE;
}
return null;
}
static public boolean isValueCode(char ch) {
if( (ch != '@') &&
(ch != ':') &&
(ch != '%') &&
(ch != '+') &&
(ch != '#') &&
(ch != '<') &&
(ch != '>') &&
(ch != '*') &&
(ch != '/')
)
{
return false;
}
return true;
}
static public Options parsePattern(String pattern) {
int sz = pattern.length();
char opt = ' ';
char ch = ' ';
boolean required = false;
Object type = null;
Options options = new Options();
for(int i=0; i<sz; i++) {
ch = pattern.charAt(i);
// a value code comes after an option and specifies
// details about it
if(!isValueCode(ch)) {
if(opt != ' ') {
// we have a previous one to deal with
options.addOption(opt, null, (type != null), "", required, false, type);
required = false;
type = null;
opt = ' ';
}
opt = ch;
} else
if(ch == '!') {
required = true;
} else {
type = getValueClass(ch);
}
}
if(opt != ' ') {
// we have a final one to deal with
options.addOption(opt, null, (type != null), "", required, false, type);
}
return options;
}
}
1.1 jakarta-commons/cli/src/java/org/apache/commons/cli/UnrecognizedOptionException.java
Index: UnrecognizedOptionException.java
===================================================================
/*
* $Header: /home/cvs/jakarta-commons-sandbox/cli/src/java/org/apache/commons/cli/UnrecognizedOptionException.java,v 1.2 2002/06/06 09:37:26 jstrachan Exp $
* $Revision: 1.2 $
* $Date: 2002/06/06 09:37:26 $
*
* ====================================================================
*
* 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;
/** <p>Exception thrown during parsing signalling an unrecognized
* option was seen.<p>
*
*
* @author bob mcwhiter (bob @ werken.com)
* @version $Revision: 1.2 $
*/
public class UnrecognizedOptionException extends ParseException {
/** Construct a new Exception with a message
*
* @param msg Explanation of the exception
*/
public UnrecognizedOptionException(String msg) {
super(msg);
}
}
1.1 jakarta-commons/cli/src/java/org/apache/commons/cli/CommandLine.java
Index: CommandLine.java
===================================================================
/*
* $Header: /home/cvs/jakarta-commons-sandbox/cli/src/java/org/apache/commons/cli/CommandLine.java,v 1.4 2002/06/06 22:32:37 bayard Exp $
* $Revision: 1.4 $
* $Date: 2002/06/06 22:32:37 $
*
* ====================================================================
*
* 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.List;
import java.util.LinkedList;
import java.util.Map;
import java.util.HashMap;
/** <p>Represents list of arguments parsed against
* a {@link Options} descriptor.<p>
*
* <p>It allows querying of a boolean {@link #hasOption(char opt)},
* in addition to retrieving the {@link #getOptionValue(char opt)}
* for options requiring arguments.</p>
*
* <p>Additionally, any left-over or unrecognized arguments,
* are available for further processing.</p>
*
* @author bob mcwhirter (bob @ werken.com)
* @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
* @version $Revision: 1.4 $
*/
public class CommandLine {
/** the unrecognised options/arguments */
private List args = new LinkedList();
/** the recognised options/arguments */
private Map options = new HashMap();
/** the option types */
private Map types = new HashMap();
/**
* <p>Creates a command line.</p>
*/
CommandLine() {
}
/** <p>Query to see if an option has been set.</p>
*
* @param opt Short single-character name of the option
* @return true if set, false if not
*/
public boolean hasOption(char opt) {
return options.containsKey( new Character(opt) );
}
public Object getOptionObject(char opt) {
String[] result = (String[])options.get( new Character(opt) );
Object type = types.get( new Character(opt) );
String res = result == null ? null : result[0];
if(res == null) {
return null;
}
return TypeHandler.createValue(res, type);
}
/** <p>Retrieve the argument, if any, of an option.</p>
*
* @param opt Short single-character name of the option
* @return Value of the argument if option is set, and has an argument, else null.
*/
public String getOptionValue(char opt) {
String[] result = (String[])options.get( new Character(opt) );
return result == null ? null : result[0];
}
/** <p>Retrieves the array of values, if any, of an option.</p>
*
* @param opt Single-character name of the option
* @return An array of values if the option is set, and has an argument, else null.
*/
public String[] getOptionValues(char opt) {
String[] result = (String[])options.get( new Character(opt) );
return result == null ? null : result;
}
/** <p>Retrieve the argument, if any, of an option.</p>
*
* @param opt Short single-character name of the option
* @param defaultValue is the default value to be returned if the option is not specified
* @return Value of the argument if option is set, and has an argument, else null.
*/
public String getOptionValue(char opt, String defaultValue) {
String answer = getOptionValue(opt);
return (answer != null) ? answer : defaultValue;
}
/** <p>Retrieve any left-over non-recognized options and arguments</p>
*
* @return an array of remaining items passed in but not parsed
*/
public String[] getArgs() {
String[] answer = new String[ args.size() ];
args.toArray( answer );
return answer;
}
/** <p>Retrieve any left-over non-recognized options and arguments</p>
*
* @return List of remaining items passed in but not parsed
*/
public List getArgList() {
return args;
}
/** <p>Dump state, suitable for debugging.</p>
*
* @return Stringified form of this object
*/
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append( "[ CommandLine: [ options: " );
buf.append( options.toString() );
buf.append( " ] [ args: ");
buf.append( args.toString() );
buf.append( " ] ]" );
return buf.toString();
}
/**
* <p>Add left-over unrecognized option/argument.</p>
*
* @param arg the unrecognised option/argument.
*/
void addArg(String arg) {
args.add( arg );
}
/**
* <p>Add an option that does not have any value to the
* command line.</p>
*
* @param opt the processed option
*/
void setOpt(char opt) {
options.put( new Character(opt), null );
}
/**
* <p>Add an option with the specified value to the
* command line.</p>
*
* @param opt the processed option
* @param value the value of the option
*/
void setOpt(char opt, String value) {
options.put( new Character(opt), value );
}
/**
* <p>Add an option to the command line. The values of
* the option are stored.</p>
*
* @param opt the processed option
*/
void setOpt(Option opt) {
Character chr = new Character( opt.getOpt() );
options.put( chr, opt.getValues() );
types.put( chr, opt.getType() );
}
}
1.1 jakarta-commons/cli/src/java/org/apache/commons/cli/MissingArgumentException.java
Index: MissingArgumentException.java
===================================================================
/*
* $Header: /home/cvs/jakarta-commons-sandbox/cli/src/java/org/apache/commons/cli/MissingArgumentException.java,v 1.2 2002/06/06 09:37:26 jstrachan Exp $
* $Revision: 1.2 $
* $Date: 2002/06/06 09:37:26 $
*
* ====================================================================
*
* 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;
/** <p>Exception thrown when an option requiring an argument
* is not provided with an argument.</p>
*
* @author bob mcwhirter (bob @ werken.com)
* @version $Revision: 1.2 $
*/
public class MissingArgumentException extends ParseException {
/** Construct a new Exception with a message
*
* @param msg Explanation of the exception
*/
public MissingArgumentException(String msg) {
super(msg);
}
}
1.1 jakarta-commons/cli/src/java/org/apache/commons/cli/overview.html
Index: overview.html
===================================================================
<body>
<p>Commons CLI -- version ##VERSION## (##QUALITY##)</p>
<p>The commons-cli package aides in parsing command-line arguments.</p>
<p>Allow command-line arguments to be parsed against a descriptor of
valid options (long and short), potentially with arguments.</p>
<p>command-line arguments may be of the typical <code>String[]</code>
form, but also may be a <code>java.util.List</code>. Indexes allow
for parsing only a portion of the command-line. Also, functionality
for parsing the command-line in phases is built in, allowing for
'cvs-style' command-lines, where some global options are specified
before a 'command' argument, and command-specific options are
specified after the command argument:
<code>
<pre>
myApp -p <port> command -p <printer>
</pre>
</code>
<p>The homepage for the project is
<a href="http://jakarta.apache.org/commons/">jakarta commons/</a>
</body>
1.1 jakarta-commons/cli/src/conf/MANIFEST.MF
Index: MANIFEST.MF
===================================================================
Extension-Name: org.apache.commons.cli
Specification-Vendor: Apache Software Foundation
Specification-Version: 1.0
Implementation-Vendor: Apache Software Foundation
Implementation-Version: 1.0-dev
1.1 jakarta-commons/cli/xdocs/index.xml
Index: index.xml
===================================================================
<?xml version="1.0"?>
<document>
<properties>
<title></title>
<author email="jstrachan@apache.org">James Strachan</author>
</properties>
<body>
<section name="CLI : Command Line Interface">
<p>
The CLI library provides a simple and easy to use API for working
with the command line arguments and options.</p>
<p>
CLI is based on ideas and code from
<ul>
<li>werken.opt by Bob Mcwhirter</li>
<li>The cli package in Avalon Excalibur by Peter Donald</li>
<li>Optz by John Keyes</li>
</ul>
</p>
</section>
</body>
</document>
--
To unsubscribe, e-mail: <ma...@jakarta.apache.org>
For additional commands, e-mail: <ma...@jakarta.apache.org>