Hi there,

I'm trying to implement a command line parser using Apache Commons CLI v. 1.2 
(unfortunately I am forced to use that version). The syntax to be accepted is 
quite simple:

MyProg [ -x path[:path]... ] [ file1 ... ]

Option '-x' should accept a search path like sequence of directories (separated 
by ':') optionally followed by zero or more file names. My code looks as 
follows:

Option dbPath = OptionBuilder.withLongOpt("db_path")
                             .withDescription("DB search path")
                             .hasArgs()
                             .withValueSeparator(':')
                             .withArgName("Path[:Path]...")
                             .create('x');
Options opts = new Options();
opts.addOption(dbPath);

String[] args = new String[] { "-x", "path1:path2", "file1", "file2" };

CommandLineParser parser = new PosixParser();
CommandLine cmdLine = null;
try {
    cmdLine = parser.parse(opts, args);
} catch (ParseException ex) {
    System.out.println("Syntax error: " + ex.getMessage());
    return;
}
if (cmdLine.hasOption('x')) {
    for (String path : cmdLine.getOptionValues('x'))
        System.out.println("path: " + path);
}
for (Object file : cmdLine.getArgList()) {
    System.out.println("file: " + file);
}

Surprisingly this doesn't function as expected. This is the output I get:

path: path1
path: path2
path: file1
path: file2

Not only the two '-x' option values ('path1', 'path2') but also the file 
arguments are returned when the getOptionValues('x') function is called. No 
matter which parser class I use (BasicParser, GnuParser or PosixParser), the 
result is always the same.

What am I doing wrong?

Adalbert.

Reply via email to