source: josm/trunk/src/gnu/getopt/Getopt.java@ 5279

Last change on this file since 5279 was 5279, checked in by bastiK, 13 years ago

use gnu getopt for command line processing

improvements:

  • long options can be separated by space from the argument (currently

only "=" works as seperator)

  • short options can be grouped (there aren't many short options at the moment, this is for later)
File size: 48.5 KB
Line 
1/**************************************************************************
2/* Getopt.java -- Java port of GNU getopt from glibc 2.0.6
3/*
4/* Copyright (c) 1987-1997 Free Software Foundation, Inc.
5/* Java Port Copyright (c) 1998 by Aaron M. Renn (arenn@urbanophile.com)
6/*
7/* This program is free software; you can redistribute it and/or modify
8/* it under the terms of the GNU Library General Public License as published
9/* by the Free Software Foundation; either version 2 of the License or
10/* (at your option) any later version.
11/*
12/* This program is distributed in the hope that it will be useful, but
13/* WITHOUT ANY WARRANTY; without even the implied warranty of
14/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15/* GNU Library General Public License for more details.
16/*
17/* You should have received a copy of the GNU Library General Public License
18/* along with this program; see the file COPYING.LIB. If not, write to
19/* the Free Software Foundation Inc., 59 Temple Place - Suite 330,
20/* Boston, MA 02111-1307 USA
21/**************************************************************************/
22
23package gnu.getopt;
24
25import static org.openstreetmap.josm.tools.I18n.tr;
26
27import java.text.MessageFormat;
28import java.util.HashMap;
29import java.util.Map;
30
31/**************************************************************************/
32
33/**
34 * This is a Java port of GNU getopt, a class for parsing command line
35 * arguments passed to programs. It it based on the C getopt() functions
36 * in glibc 2.0.6 and should parse options in a 100% compatible manner.
37 * If it does not, that is a bug. The programmer's interface is also
38 * very compatible.
39 * <p>
40 * To use Getopt, create a Getopt object with a argv array passed to the
41 * main method, then call the getopt() method in a loop. It will return an
42 * int that contains the value of the option character parsed from the
43 * command line. When there are no more options to be parsed, it
44 * returns -1.
45 * <p>
46 * A command line option can be defined to take an argument. If an
47 * option has an argument, the value of that argument is stored in an
48 * instance variable called optarg, which can be accessed using the
49 * getOptarg() method. If an option that requires an argument is
50 * found, but there is no argument present, then an error message is
51 * printed. Normally getopt() returns a '?' in this situation, but
52 * that can be changed as described below.
53 * <p>
54 * If an invalid option is encountered, an error message is printed
55 * to the standard error and getopt() returns a '?'. The value of the
56 * invalid option encountered is stored in the instance variable optopt
57 * which can be retrieved using the getOptopt() method. To suppress
58 * the printing of error messages for this or any other error, set
59 * the value of the opterr instance variable to false using the
60 * setOpterr() method.
61 * <p>
62 * Between calls to getopt(), the instance variable optind is used to
63 * keep track of where the object is in the parsing process. After all
64 * options have been returned, optind is the index in argv of the first
65 * non-option argument. This variable can be accessed with the getOptind()
66 * method.
67 * <p>
68 * Note that this object expects command line options to be passed in the
69 * traditional Unix manner. That is, proceeded by a '-' character.
70 * Multiple options can follow the '-'. For example "-abc" is equivalent
71 * to "-a -b -c". If an option takes a required argument, the value
72 * of the argument can immediately follow the option character or be
73 * present in the next argv element. For example, "-cfoo" and "-c foo"
74 * both represent an option character of 'c' with an argument of "foo"
75 * assuming c takes a required argument. If an option takes an argument
76 * that is not required, then any argument must immediately follow the
77 * option character in the same argv element. For example, if c takes
78 * a non-required argument, then "-cfoo" represents option character 'c'
79 * with an argument of "foo" while "-c foo" represents the option
80 * character 'c' with no argument, and a first non-option argv element
81 * of "foo".
82 * <p>
83 * The user can stop getopt() from scanning any further into a command line
84 * by using the special argument "--" by itself. For example:
85 * "-a -- -d" would return an option character of 'a', then return -1
86 * The "--" is discarded and "-d" is pointed to by optind as the first
87 * non-option argv element.
88 * <p>
89 * Here is a basic example of using Getopt:
90 * <p>
91 * <pre>
92 * Getopt g = new Getopt("testprog", argv, "ab:c::d");
93 * //
94 * int c;
95 * String arg;
96 * while ((c = g.getopt()) != -1)
97 * {
98 * switch(c)
99 * {
100 * case 'a':
101 * case 'd':
102 * System.out.print("You picked " + (char)c + "\n");
103 * break;
104 * //
105 * case 'b':
106 * case 'c':
107 * arg = g.getOptarg();
108 * System.out.print("You picked " + (char)c +
109 * " with an argument of " +
110 * ((arg != null) ? arg : "null") + "\n");
111 * break;
112 * //
113 * case '?':
114 * break; // getopt() already printed an error
115 * //
116 * default:
117 * System.out.print("getopt() returned " + c + "\n");
118 * }
119 * }
120 * </pre>
121 * <p>
122 * In this example, a new Getopt object is created with three params.
123 * The first param is the program name. This is for printing error
124 * messages in the form "program: error message". In the C version, this
125 * value is taken from argv[0], but in Java the program name is not passed
126 * in that element, thus the need for this parameter. The second param is
127 * the argument list that was passed to the main() method. The third
128 * param is the list of valid options. Each character represents a valid
129 * option. If the character is followed by a single colon, then that
130 * option has a required argument. If the character is followed by two
131 * colons, then that option has an argument that is not required.
132 * <p>
133 * Note in this example that the value returned from getopt() is cast to
134 * a char prior to printing. This is required in order to make the value
135 * display correctly as a character instead of an integer.
136 * <p>
137 * If the first character in the option string is a colon, for example
138 * ":abc::d", then getopt() will return a ':' instead of a '?' when it
139 * encounters an option with a missing required argument. This allows the
140 * caller to distinguish between invalid options and valid options that
141 * are simply incomplete.
142 * <p>
143 * In the traditional Unix getopt(), -1 is returned when the first non-option
144 * charcter is encountered. In GNU getopt(), the default behavior is to
145 * allow options to appear anywhere on the command line. The getopt()
146 * method permutes the argument to make it appear to the caller that all
147 * options were at the beginning of the command line, and all non-options
148 * were at the end. For example, calling getopt() with command line args
149 * of "-a foo bar -d" returns options 'a' and 'd', then sets optind to
150 * point to "foo". The program would read the last two argv elements as
151 * "foo" and "bar", just as if the user had typed "-a -d foo bar".
152 * <p>
153 * The user can force getopt() to stop scanning the command line with
154 * the special argument "--" by itself. Any elements occuring before the
155 * "--" are scanned and permuted as normal. Any elements after the "--"
156 * are returned as is as non-option argv elements. For example,
157 * "foo -a -- bar -d" would return option 'a' then -1. optind would point
158 * to "foo", "bar" and "-d" as the non-option argv elements. The "--"
159 * is discarded by getopt().
160 * <p>
161 * There are two ways this default behavior can be modified. The first is
162 * to specify traditional Unix getopt() behavior (which is also POSIX
163 * behavior) in which scanning stops when the first non-option argument
164 * encountered. (Thus "-a foo bar -d" would return 'a' as an option and
165 * have "foo", "bar", and "-d" as non-option elements). The second is to
166 * allow options anywhere, but to return all elements in the order they
167 * occur on the command line. When a non-option element is ecountered,
168 * an integer 1 is returned and the value of the non-option element is
169 * stored in optarg is if it were the argument to that option. For
170 * example, "-a foo -d", returns first 'a', then 1 (with optarg set to
171 * "foo") then 'd' then -1. When this "return in order" functionality
172 * is enabled, the only way to stop getopt() from scanning all command
173 * line elements is to use the special "--" string by itself as described
174 * above. An example is "-a foo -b -- bar", which would return 'a', then
175 * integer 1 with optarg set to "foo", then 'b', then -1. optind would
176 * then point to "bar" as the first non-option argv element. The "--"
177 * is discarded.
178 * <p>
179 * The POSIX/traditional behavior is enabled by either setting the
180 * property "gnu.posixly_correct" or by putting a '+' sign as the first
181 * character of the option string. The difference between the two
182 * methods is that setting the gnu.posixly_correct property also forces
183 * certain error messages to be displayed in POSIX format. To enable
184 * the "return in order" functionality, put a '-' as the first character
185 * of the option string. Note that after determining the proper
186 * behavior, Getopt strips this leading '+' or '-', meaning that a ':'
187 * placed as the second character after one of those two will still cause
188 * getopt() to return a ':' instead of a '?' if a required option
189 * argument is missing.
190 * <p>
191 * In addition to traditional single character options, GNU Getopt also
192 * supports long options. These are preceeded by a "--" sequence and
193 * can be as long as desired. Long options provide a more user-friendly
194 * way of entering command line options. For example, in addition to a
195 * "-h" for help, a program could support also "--help".
196 * <p>
197 * Like short options, long options can also take a required or non-required
198 * argument. Required arguments can either be specified by placing an
199 * equals sign after the option name, then the argument, or by putting the
200 * argument in the next argv element. For example: "--outputdir=foo" and
201 * "--outputdir foo" both represent an option of "outputdir" with an
202 * argument of "foo", assuming that outputdir takes a required argument.
203 * If a long option takes a non-required argument, then the equals sign
204 * form must be used to specify the argument. In this case,
205 * "--outputdir=foo" would represent option outputdir with an argument of
206 * "foo" while "--outputdir foo" would represent the option outputdir
207 * with no argument and a first non-option argv element of "foo".
208 * <p>
209 * Long options can also be specified using a special POSIX argument
210 * format (one that I highly discourage). This form of entry is
211 * enabled by placing a "W;" (yes, 'W' then a semi-colon) in the valid
212 * option string. This causes getopt to treat the name following the
213 * "-W" as the name of the long option. For example, "-W outputdir=foo"
214 * would be equivalent to "--outputdir=foo". The name can immediately
215 * follow the "-W" like so: "-Woutputdir=foo". Option arguments are
216 * handled identically to normal long options. If a string follows the
217 * "-W" that does not represent a valid long option, then getopt() returns
218 * 'W' and the caller must decide what to do. Otherwise getopt() returns
219 * a long option value as described below.
220 * <p>
221 * While long options offer convenience, they can also be tedious to type
222 * in full. So it is permissible to abbreviate the option name to as
223 * few characters as required to uniquely identify it. If the name can
224 * represent multiple long options, then an error message is printed and
225 * getopt() returns a '?'.
226 * <p>
227 * If an invalid option is specified or a required option argument is
228 * missing, getopt() prints an error and returns a '?' or ':' exactly
229 * as for short options. Note that when an invalid long option is
230 * encountered, the optopt variable is set to integer 0 and so cannot
231 * be used to identify the incorrect option the user entered.
232 * <p>
233 * Long options are defined by LongOpt objects. These objects are created
234 * with a contructor that takes four params: a String representing the
235 * object name, a integer specifying what arguments the option takes
236 * (the value is one of LongOpt.NO_ARGUMENT, LongOpt.REQUIRED_ARGUMENT,
237 * or LongOpt.OPTIONAL_ARGUMENT), a StringBuffer flag object (described
238 * below), and an integer value (described below).
239 * <p>
240 * To enable long option parsing, create an array of LongOpt's representing
241 * the legal options and pass it to the Getopt() constructor. WARNING: If
242 * all elements of the array are not populated with LongOpt objects, the
243 * getopt() method will throw a NullPointerException.
244 * <p>
245 * When getopt() is called and a long option is encountered, one of two
246 * things can be returned. If the flag field in the LongOpt object
247 * representing the long option is non-null, then the integer value field
248 * is stored there and an integer 0 is returned to the caller. The val
249 * field can then be retrieved from the flag field. Note that since the
250 * flag field is a StringBuffer, the appropriate String to integer converions
251 * must be performed in order to get the actual int value stored there.
252 * If the flag field in the LongOpt object is null, then the value field
253 * of the LongOpt is returned. This can be the character of a short option.
254 * This allows an app to have both a long and short option sequence
255 * (say, "-h" and "--help") that do the exact same thing.
256 * <p>
257 * With long options, there is an alternative method of determining
258 * which option was selected. The method getLongind() will return the
259 * the index in the long option array (NOT argv) of the long option found.
260 * So if multiple long options are configured to return the same value,
261 * the application can use getLongind() to distinguish between them.
262 * <p>
263 * Here is an expanded Getopt example using long options and various
264 * techniques described above:
265 * <p>
266 * <pre>
267 * int c;
268 * String arg;
269 * LongOpt[] longopts = new LongOpt[3];
270 * //
271 * StringBuffer sb = new StringBuffer();
272 * longopts[0] = new LongOpt("help", LongOpt.NO_ARGUMENT, null, 'h');
273 * longopts[1] = new LongOpt("outputdir", LongOpt.REQUIRED_ARGUMENT, sb, 'o');
274 * longopts[2] = new LongOpt("maximum", LongOpt.OPTIONAL_ARGUMENT, null, 2);
275 * //
276 * Getopt g = new Getopt("testprog", argv, "-:bc::d:hW;", longopts);
277 * g.setOpterr(false); // We'll do our own error handling
278 * //
279 * while ((c = g.getopt()) != -1)
280 * switch (c)
281 * {
282 * case 0:
283 * arg = g.getOptarg();
284 * System.out.println("Got long option with value '" +
285 * (char)(new Integer(sb.toString())).intValue()
286 * + "' with argument " +
287 * ((arg != null) ? arg : "null"));
288 * break;
289 * //
290 * case 1:
291 * System.out.println("I see you have return in order set and that " +
292 * "a non-option argv element was just found " +
293 * "with the value '" + g.getOptarg() + "'");
294 * break;
295 * //
296 * case 2:
297 * arg = g.getOptarg();
298 * System.out.println("I know this, but pretend I didn't");
299 * System.out.println("We picked option " +
300 * longopts[g.getLongind()].getName() +
301 * " with value " +
302 * ((arg != null) ? arg : "null"));
303 * break;
304 * //
305 * case 'b':
306 * System.out.println("You picked plain old option " + (char)c);
307 * break;
308 * //
309 * case 'c':
310 * case 'd':
311 * arg = g.getOptarg();
312 * System.out.println("You picked option '" + (char)c +
313 * "' with argument " +
314 * ((arg != null) ? arg : "null"));
315 * break;
316 * //
317 * case 'h':
318 * System.out.println("I see you asked for help");
319 * break;
320 * //
321 * case 'W':
322 * System.out.println("Hmmm. You tried a -W with an incorrect long " +
323 * "option name");
324 * break;
325 * //
326 * case ':':
327 * System.out.println("Doh! You need an argument for option " +
328 * (char)g.getOptopt());
329 * break;
330 * //
331 * case '?':
332 * System.out.println("The option '" + (char)g.getOptopt() +
333 * "' is not valid");
334 * break;
335 * //
336 * default:
337 * System.out.println("getopt() returned " + c);
338 * break;
339 * }
340 * //
341 * for (int i = g.getOptind(); i < argv.length ; i++)
342 * System.out.println("Non option argv element: " + argv[i] + "\n");
343 * </pre>
344 * <p>
345 * There is an alternative form of the constructor used for long options
346 * above. This takes a trailing boolean flag. If set to false, Getopt
347 * performs identically to the example, but if the boolean flag is true
348 * then long options are allowed to start with a single '-' instead of
349 * "--". If the first character of the option is a valid short option
350 * character, then the option is treated as if it were the short option.
351 * Otherwise it behaves as if the option is a long option. Note that
352 * the name given to this option - long_only - is very counter-intuitive.
353 * It does not cause only long options to be parsed but instead enables
354 * the behavior described above.
355 * <p>
356 * Note that the functionality and variable names used are driven from
357 * the C lib version as this object is a port of the C code, not a
358 * new implementation. This should aid in porting existing C/C++ code,
359 * as well as helping programmers familiar with the glibc version to
360 * adapt to the Java version even if it seems very non-Java at times.
361 * <p>
362 * In this release I made all instance variables protected due to
363 * overwhelming public demand. Any code which relied on optarg,
364 * opterr, optind, or optopt being public will need to be modified to
365 * use the appropriate access methods.
366 * <p>
367 * Please send all bug reports, requests, and comments to
368 * <a href="mailto:arenn@urbanophile.com">arenn@urbanophile.com</a>.
369 *
370 * @version 1.0.7
371 *
372 * @author Roland McGrath (roland@gnu.ai.mit.edu)
373 * @author Ulrich Drepper (drepper@cygnus.com)
374 * @author Aaron M. Renn (arenn@urbanophile.com)
375 *
376 * @see LongOpt
377 */
378public class Getopt extends Object
379{
380
381/**************************************************************************/
382
383/*
384 * Class Variables
385 */
386
387/**
388 * Describe how to deal with options that follow non-option ARGV-elements.
389 *
390 * If the caller did not specify anything,
391 * the default is REQUIRE_ORDER if the property
392 * gnu.posixly_correct is defined, PERMUTE otherwise.
393 *
394 * The special argument `--' forces an end of option-scanning regardless
395 * of the value of `ordering'. In the case of RETURN_IN_ORDER, only
396 * `--' can cause `getopt' to return -1 with `optind' != ARGC.
397 *
398 * REQUIRE_ORDER means don't recognize them as options;
399 * stop option processing when the first non-option is seen.
400 * This is what Unix does.
401 * This mode of operation is selected by either setting the property
402 * gnu.posixly_correct, or using `+' as the first character
403 * of the list of option characters.
404 */
405protected static final int REQUIRE_ORDER = 1;
406
407/**
408 * PERMUTE is the default. We permute the contents of ARGV as we scan,
409 * so that eventually all the non-options are at the end. This allows options
410 * to be given in any order, even with programs that were not written to
411 * expect this.
412 */
413protected static final int PERMUTE = 2;
414
415/**
416 * RETURN_IN_ORDER is an option available to programs that were written
417 * to expect options and other ARGV-elements in any order and that care about
418 * the ordering of the two. We describe each non-option ARGV-element
419 * as if it were the argument of an option with character code 1.
420 * Using `-' as the first character of the list of option characters
421 * selects this mode of operation.
422 */
423protected static final int RETURN_IN_ORDER = 3;
424
425/**************************************************************************/
426
427/*
428 * Instance Variables
429 */
430
431/**
432 * For communication from `getopt' to the caller.
433 * When `getopt' finds an option that takes an argument,
434 * the argument value is returned here.
435 * Also, when `ordering' is RETURN_IN_ORDER,
436 * each non-option ARGV-element is returned here.
437 */
438protected String optarg;
439
440/**
441 * Index in ARGV of the next element to be scanned.
442 * This is used for communication to and from the caller
443 * and for communication between successive calls to `getopt'.
444 *
445 * On entry to `getopt', zero means this is the first call; initialize.
446 *
447 * When `getopt' returns -1, this is the index of the first of the
448 * non-option elements that the caller should itself scan.
449 *
450 * Otherwise, `optind' communicates from one call to the next
451 * how much of ARGV has been scanned so far.
452 */
453protected int optind = 0;
454
455/**
456 * Callers store false here to inhibit the error message
457 * for unrecognized options.
458 */
459protected boolean opterr = true;
460
461/**
462 * When an unrecognized option is encountered, getopt will return a '?'
463 * and store the value of the invalid option here.
464 */
465protected int optopt = '?';
466
467/**
468 * The next char to be scanned in the option-element
469 * in which the last option character we returned was found.
470 * This allows us to pick up the scan where we left off.
471 *
472 * If this is zero, or a null string, it means resume the scan
473 * by advancing to the next ARGV-element.
474 */
475protected String nextchar;
476
477/**
478 * This is the string describing the valid short options.
479 */
480protected String optstring;
481
482/**
483 * This is an array of LongOpt objects which describ the valid long
484 * options.
485 */
486protected LongOpt[] long_options;
487
488/**
489 * This flag determines whether or not we are parsing only long args
490 */
491protected boolean long_only;
492
493/**
494 * Stores the index into the long_options array of the long option found
495 */
496protected int longind;
497
498/**
499 * The flag determines whether or not we operate in strict POSIX compliance
500 */
501protected boolean posixly_correct;
502
503/**
504 * A flag which communicates whether or not checkLongOption() did all
505 * necessary processing for the current option
506 */
507protected boolean longopt_handled;
508
509/**
510 * The index of the first non-option in argv[]
511 */
512protected int first_nonopt = 1;
513
514/**
515 * The index of the last non-option in argv[]
516 */
517protected int last_nonopt = 1;
518
519/**
520 * Flag to tell getopt to immediately return -1 the next time it is
521 * called.
522 */
523private boolean endparse = false;
524
525/**
526 * Saved argument list passed to the program
527 */
528protected String[] argv;
529
530/**
531 * Determines whether we permute arguments or not
532 */
533protected int ordering;
534
535/**
536 * Name to print as the program name in error messages. This is necessary
537 * since Java does not place the program name in argv[0]
538 */
539protected String progname;
540
541/**
542 * The localized strings are kept in a separate file
543 */
544private OptI18n _messages = new OptI18n(); // ResourceBundle.getBundle("gnu/getopt/MessagesBundle", Locale.getDefault());
545
546/**************************************************************************/
547
548/*
549 * Constructors
550 */
551
552/**
553 * Construct a basic Getopt instance with the given input data. Note that
554 * this handles "short" options only.
555 *
556 * @param progname The name to display as the program name when printing errors
557 * @param argv The String array passed as the command line to the program.
558 * @param optstring A String containing a description of the valid args for this program
559 */
560public
561Getopt(String progname, String[] argv, String optstring)
562{
563 this(progname, argv, optstring, null, false);
564}
565
566/**************************************************************************/
567
568/**
569 * Construct a Getopt instance with given input data that is capable of
570 * parsing long options as well as short.
571 *
572 * @param progname The name to display as the program name when printing errors
573 * @param argv The String array passed as the command ilne to the program
574 * @param optstring A String containing a description of the valid short args for this program
575 * @param long_options An array of LongOpt objects that describes the valid long args for this program
576 */
577public
578Getopt(String progname, String[] argv, String optstring,
579 LongOpt[] long_options)
580{
581 this(progname, argv, optstring, long_options, false);
582}
583
584/**************************************************************************/
585
586static class OptI18n {
587 public OptI18n() {
588 add("getopt.ambigious", tr("{0}: option ''{1}'' is ambiguous"));
589 add("getopt.arguments1", tr("{0}: option ''--{1}'' doesn't allow an argument"));
590 add("getopt.arguments2", tr("{0}: option ''{1}{2}'' doesn't allow an argument"));
591 add("getopt.requires", tr("{0}: option ''{1}'' requires an argument"));
592 add("getopt.unrecognized", tr("{0}: unrecognized option ''--{1}''"));
593 add("getopt.unrecognized2", tr("{0}: unrecognized option ''{1}{2}''"));
594 add("getopt.illegal", tr("{0}: illegal option -- {1}"));
595 add("getopt.invalid", tr("{0}: invalid option -- {1}"));
596 add("getopt.requires2", tr("{0}: option requires an argument -- {1}"));
597 add("getopt.invalidValue", tr("Invalid value {0} for parameter ''has_arg''"));
598 }
599
600 Map<String, String> trns = new HashMap<String, String>();
601
602 private void add(String key, String value) {
603 trns.put(key, value);
604 }
605
606 public String getString(String s) {
607 String val = trns.get(s);
608 if (val == null) throw new IllegalArgumentException();
609 return val.replace("'", "''");
610 }
611}
612
613/**
614 * Construct a Getopt instance with given input data that is capable of
615 * parsing long options and short options. Contrary to what you might
616 * think, the flag 'long_only' does not determine whether or not we
617 * scan for only long arguments. Instead, a value of true here allows
618 * long arguments to start with a '-' instead of '--' unless there is a
619 * conflict with a short option name.
620 *
621 * @param progname The name to display as the program name when printing errors
622 * @param argv The String array passed as the command ilne to the program
623 * @param optstring A String containing a description of the valid short args for this program
624 * @param long_options An array of LongOpt objects that describes the valid long args for this program
625 * @param long_only true if long options that do not conflict with short options can start with a '-' as well as '--'
626 */
627public
628Getopt(String progname, String[] argv, String optstring,
629 LongOpt[] long_options, boolean long_only)
630{
631 if (optstring.length() == 0)
632 optstring = " ";
633
634 // This function is essentially _getopt_initialize from GNU getopt
635 this.progname = progname;
636 this.argv = argv;
637 this.optstring = optstring;
638 this.long_options = long_options;
639 this.long_only = long_only;
640
641 // Check for property "gnu.posixly_correct" to determine whether to
642 // strictly follow the POSIX standard. This replaces the "POSIXLY_CORRECT"
643 // environment variable in the C version
644 if (System.getProperty("gnu.posixly_correct", null) == null)
645 posixly_correct = false;
646 else
647 {
648 posixly_correct = true;
649 _messages = new OptI18n();//ResourceBundle.getBundle("gnu/getopt/MessagesBundle",
650 // Locale.US);
651 }
652
653 // Determine how to handle the ordering of options and non-options
654 if (optstring.charAt(0) == '-')
655 {
656 ordering = RETURN_IN_ORDER;
657 if (optstring.length() > 1)
658 this.optstring = optstring.substring(1);
659 }
660 else if (optstring.charAt(0) == '+')
661 {
662 ordering = REQUIRE_ORDER;
663 if (optstring.length() > 1)
664 this.optstring = optstring.substring(1);
665 }
666 else if (posixly_correct)
667 {
668 ordering = REQUIRE_ORDER;
669 }
670 else
671 {
672 ordering = PERMUTE; // The normal default case
673 }
674}
675
676/**************************************************************************/
677
678/*
679 * Instance Methods
680 */
681
682/**
683 * In GNU getopt, it is possible to change the string containg valid options
684 * on the fly because it is passed as an argument to getopt() each time. In
685 * this version we do not pass the string on every call. In order to allow
686 * dynamic option string changing, this method is provided.
687 *
688 * @param optstring The new option string to use
689 */
690public void
691setOptstring(String optstring)
692{
693 if (optstring.length() == 0)
694 optstring = " ";
695
696 this.optstring = optstring;
697}
698
699/**************************************************************************/
700
701/**
702 * optind it the index in ARGV of the next element to be scanned.
703 * This is used for communication to and from the caller
704 * and for communication between successive calls to `getopt'.
705 *
706 * When `getopt' returns -1, this is the index of the first of the
707 * non-option elements that the caller should itself scan.
708 *
709 * Otherwise, `optind' communicates from one call to the next
710 * how much of ARGV has been scanned so far.
711 */
712public int
713getOptind()
714{
715 return(optind);
716}
717
718/**************************************************************************/
719
720/**
721 * This method allows the optind index to be set manually. Normally this
722 * is not necessary (and incorrect usage of this method can lead to serious
723 * lossage), but optind is a public symbol in GNU getopt, so this method
724 * was added to allow it to be modified by the caller if desired.
725 *
726 * @param optind The new value of optind
727 */
728public void
729setOptind(int optind)
730{
731 this.optind = optind;
732}
733
734/**************************************************************************/
735
736/**
737 * Since in GNU getopt() the argument vector is passed back in to the
738 * function every time, the caller can swap out argv on the fly. Since
739 * passing argv is not required in the Java version, this method allows
740 * the user to override argv. Note that incorrect use of this method can
741 * lead to serious lossage.
742 *
743 * @param argv New argument list
744 */
745public void
746setArgv(String[] argv)
747{
748 this.argv = argv;
749}
750
751/**************************************************************************/
752
753/**
754 * For communication from `getopt' to the caller.
755 * When `getopt' finds an option that takes an argument,
756 * the argument value is returned here.
757 * Also, when `ordering' is RETURN_IN_ORDER,
758 * each non-option ARGV-element is returned here.
759 * No set method is provided because setting this variable has no effect.
760 */
761public String
762getOptarg()
763{
764 return(optarg);
765}
766
767/**************************************************************************/
768
769/**
770 * Normally Getopt will print a message to the standard error when an
771 * invalid option is encountered. This can be suppressed (or re-enabled)
772 * by calling this method. There is no get method for this variable
773 * because if you can't remember the state you set this to, why should I?
774 */
775public void
776setOpterr(boolean opterr)
777{
778 this.opterr = opterr;
779}
780
781/**************************************************************************/
782
783/**
784 * When getopt() encounters an invalid option, it stores the value of that
785 * option in optopt which can be retrieved with this method. There is
786 * no corresponding set method because setting this variable has no effect.
787 */
788public int
789getOptopt()
790{
791 return(optopt);
792}
793
794/**************************************************************************/
795
796/**
797 * Returns the index into the array of long options (NOT argv) representing
798 * the long option that was found.
799 */
800public int
801getLongind()
802{
803 return(longind);
804}
805
806/**************************************************************************/
807
808/**
809 * Exchange the shorter segment with the far end of the longer segment.
810 * That puts the shorter segment into the right place.
811 * It leaves the longer segment in the right place overall,
812 * but it consists of two parts that need to be swapped next.
813 * This method is used by getopt() for argument permutation.
814 */
815protected void
816exchange(String[] argv)
817{
818 int bottom = first_nonopt;
819 int middle = last_nonopt;
820 int top = optind;
821 String tem;
822
823 while (top > middle && middle > bottom)
824 {
825 if (top - middle > middle - bottom)
826 {
827 // Bottom segment is the short one.
828 int len = middle - bottom;
829 int i;
830
831 // Swap it with the top part of the top segment.
832 for (i = 0; i < len; i++)
833 {
834 tem = argv[bottom + i];
835 argv[bottom + i] = argv[top - (middle - bottom) + i];
836 argv[top - (middle - bottom) + i] = tem;
837 }
838 // Exclude the moved bottom segment from further swapping.
839 top -= len;
840 }
841 else
842 {
843 // Top segment is the short one.
844 int len = top - middle;
845 int i;
846
847 // Swap it with the bottom part of the bottom segment.
848 for (i = 0; i < len; i++)
849 {
850 tem = argv[bottom + i];
851 argv[bottom + i] = argv[middle + i];
852 argv[middle + i] = tem;
853 }
854 // Exclude the moved top segment from further swapping.
855 bottom += len;
856 }
857 }
858
859 // Update records for the slots the non-options now occupy.
860
861 first_nonopt += (optind - last_nonopt);
862 last_nonopt = optind;
863}
864
865/**************************************************************************/
866
867/**
868 * Check to see if an option is a valid long option. Called by getopt().
869 * Put in a separate method because this needs to be done twice. (The
870 * C getopt authors just copy-pasted the code!).
871 *
872 * @param longind A buffer in which to store the 'val' field of found LongOpt
873 *
874 * @return Various things depending on circumstances
875 */
876protected int
877checkLongOption()
878{
879 LongOpt pfound = null;
880 int nameend;
881 boolean ambig;
882 boolean exact;
883
884 longopt_handled = true;
885 ambig = false;
886 exact = false;
887 longind = -1;
888
889 nameend = nextchar.indexOf("=");
890 if (nameend == -1)
891 nameend = nextchar.length();
892
893 // Test all lnog options for either exact match or abbreviated matches
894 for (int i = 0; i < long_options.length; i++)
895 {
896 if (long_options[i].getName().startsWith(nextchar.substring(0, nameend)))
897 {
898 if (long_options[i].getName().equals(nextchar.substring(0, nameend)))
899 {
900 // Exact match found
901 pfound = long_options[i];
902 longind = i;
903 exact = true;
904 break;
905 }
906 else if (pfound == null)
907 {
908 // First nonexact match found
909 pfound = long_options[i];
910 longind = i;
911 }
912 else
913 {
914 // Second or later nonexact match found
915 ambig = true;
916 }
917 }
918 } // for
919
920 // Print out an error if the option specified was ambiguous
921 if (ambig && !exact)
922 {
923 if (opterr)
924 {
925 Object[] msgArgs = { progname, argv[optind] };
926 System.err.println(MessageFormat.format(
927 _messages.getString("getopt.ambigious"),
928 msgArgs));
929 }
930
931 nextchar = "";
932 optopt = 0;
933 ++optind;
934
935 return('?');
936 }
937
938 if (pfound != null)
939 {
940 ++optind;
941
942 if (nameend != nextchar.length())
943 {
944 if (pfound.has_arg != LongOpt.NO_ARGUMENT)
945 {
946 if (nextchar.substring(nameend).length() > 1)
947 optarg = nextchar.substring(nameend+1);
948 else
949 optarg = "";
950 }
951 else
952 {
953 if (opterr)
954 {
955 // -- option
956 if (argv[optind - 1].startsWith("--"))
957 {
958 Object[] msgArgs = { progname, pfound.name };
959 System.err.println(MessageFormat.format(
960 _messages.getString("getopt.arguments1"),
961 msgArgs));
962 }
963 // +option or -option
964 else
965 {
966 Object[] msgArgs = { progname, new
967 Character(argv[optind-1].charAt(0)).toString(),
968 pfound.name };
969 System.err.println(MessageFormat.format(
970 _messages.getString("getopt.arguments2"),
971 msgArgs));
972 }
973 }
974
975 nextchar = "";
976 optopt = pfound.val;
977
978 return('?');
979 }
980 } // if (nameend)
981 else if (pfound.has_arg == LongOpt.REQUIRED_ARGUMENT)
982 {
983 if (optind < argv.length)
984 {
985 optarg = argv[optind];
986 ++optind;
987 }
988 else
989 {
990 if (opterr)
991 {
992 Object[] msgArgs = { progname, argv[optind-1] };
993 System.err.println(MessageFormat.format(
994 _messages.getString("getopt.requires"),
995 msgArgs));
996 }
997
998 nextchar = "";
999 optopt = pfound.val;
1000 if (optstring.charAt(0) == ':')
1001 return(':');
1002 else
1003 return('?');
1004 }
1005 } // else if (pfound)
1006
1007 nextchar = "";
1008
1009 if (pfound.flag != null)
1010 {
1011 pfound.flag.setLength(0);
1012 pfound.flag.append(pfound.val);
1013
1014 return(0);
1015 }
1016
1017 return(pfound.val);
1018 } // if (pfound != null)
1019
1020 longopt_handled = false;
1021
1022 return(0);
1023}
1024
1025/**************************************************************************/
1026
1027/**
1028 * This method returns a char that is the current option that has been
1029 * parsed from the command line. If the option takes an argument, then
1030 * the internal variable 'optarg' is set which is a String representing
1031 * the the value of the argument. This value can be retrieved by the
1032 * caller using the getOptarg() method. If an invalid option is found,
1033 * an error message is printed and a '?' is returned. The name of the
1034 * invalid option character can be retrieved by calling the getOptopt()
1035 * method. When there are no more options to be scanned, this method
1036 * returns -1. The index of first non-option element in argv can be
1037 * retrieved with the getOptind() method.
1038 *
1039 * @return Various things as described above
1040 */
1041public int
1042getopt()
1043{
1044 optarg = null;
1045
1046 if (endparse == true)
1047 return(-1);
1048
1049 if ((nextchar == null) || (nextchar.equals("")))
1050 {
1051 // If we have just processed some options following some non-options,
1052 // exchange them so that the options come first.
1053 if (last_nonopt > optind)
1054 last_nonopt = optind;
1055 if (first_nonopt > optind)
1056 first_nonopt = optind;
1057
1058 if (ordering == PERMUTE)
1059 {
1060 // If we have just processed some options following some non-options,
1061 // exchange them so that the options come first.
1062 if ((first_nonopt != last_nonopt) && (last_nonopt != optind))
1063 exchange(argv);
1064 else if (last_nonopt != optind)
1065 first_nonopt = optind;
1066
1067 // Skip any additional non-options
1068 // and extend the range of non-options previously skipped.
1069 while ((optind < argv.length) && (argv[optind].equals("") ||
1070 (argv[optind].charAt(0) != '-') || argv[optind].equals("-")))
1071 {
1072 optind++;
1073 }
1074
1075 last_nonopt = optind;
1076 }
1077
1078 // The special ARGV-element `--' means premature end of options.
1079 // Skip it like a null option,
1080 // then exchange with previous non-options as if it were an option,
1081 // then skip everything else like a non-option.
1082 if ((optind != argv.length) && argv[optind].equals("--"))
1083 {
1084 optind++;
1085
1086 if ((first_nonopt != last_nonopt) && (last_nonopt != optind))
1087 exchange (argv);
1088 else if (first_nonopt == last_nonopt)
1089 first_nonopt = optind;
1090
1091 last_nonopt = argv.length;
1092
1093 optind = argv.length;
1094 }
1095
1096 // If we have done all the ARGV-elements, stop the scan
1097 // and back over any non-options that we skipped and permuted.
1098 if (optind == argv.length)
1099 {
1100 // Set the next-arg-index to point at the non-options
1101 // that we previously skipped, so the caller will digest them.
1102 if (first_nonopt != last_nonopt)
1103 optind = first_nonopt;
1104
1105 return(-1);
1106 }
1107
1108 // If we have come to a non-option and did not permute it,
1109 // either stop the scan or describe it to the caller and pass it by.
1110 if (argv[optind].equals("") || (argv[optind].charAt(0) != '-') ||
1111 argv[optind].equals("-"))
1112 {
1113 if (ordering == REQUIRE_ORDER)
1114 return(-1);
1115
1116 optarg = argv[optind++];
1117 return(1);
1118 }
1119
1120 // We have found another option-ARGV-element.
1121 // Skip the initial punctuation.
1122 if (argv[optind].startsWith("--"))
1123 nextchar = argv[optind].substring(2);
1124 else
1125 nextchar = argv[optind].substring(1);
1126 }
1127
1128 // Decode the current option-ARGV-element.
1129
1130 /* Check whether the ARGV-element is a long option.
1131
1132 If long_only and the ARGV-element has the form "-f", where f is
1133 a valid short option, don't consider it an abbreviated form of
1134 a long option that starts with f. Otherwise there would be no
1135 way to give the -f short option.
1136
1137 On the other hand, if there's a long option "fubar" and
1138 the ARGV-element is "-fu", do consider that an abbreviation of
1139 the long option, just like "--fu", and not "-f" with arg "u".
1140
1141 This distinction seems to be the most useful approach. */
1142 if ((long_options != null) && (argv[optind].startsWith("--")
1143 || (long_only && ((argv[optind].length() > 2) ||
1144 (optstring.indexOf(argv[optind].charAt(1)) == -1)))))
1145 {
1146 int c = checkLongOption();
1147
1148 if (longopt_handled)
1149 return(c);
1150
1151 // Can't find it as a long option. If this is not getopt_long_only,
1152 // or the option starts with '--' or is not a valid short
1153 // option, then it's an error.
1154 // Otherwise interpret it as a short option.
1155 if (!long_only || argv[optind].startsWith("--")
1156 || (optstring.indexOf(nextchar.charAt(0)) == -1))
1157 {
1158 if (opterr)
1159 {
1160 if (argv[optind].startsWith("--"))
1161 {
1162 Object[] msgArgs = { progname, nextchar };
1163 System.err.println(MessageFormat.format(
1164 _messages.getString("getopt.unrecognized"),
1165 msgArgs));
1166 }
1167 else
1168 {
1169 Object[] msgArgs = { progname, new
1170 Character(argv[optind].charAt(0)).toString(),
1171 nextchar };
1172 System.err.println(MessageFormat.format(
1173 _messages.getString("getopt.unrecognized2"),
1174 msgArgs));
1175 }
1176 }
1177
1178 nextchar = "";
1179 ++optind;
1180 optopt = 0;
1181
1182 return('?');
1183 }
1184 } // if (longopts)
1185
1186 // Look at and handle the next short option-character */
1187 int c = nextchar.charAt(0); //**** Do we need to check for empty str?
1188 if (nextchar.length() > 1)
1189 nextchar = nextchar.substring(1);
1190 else
1191 nextchar = "";
1192
1193 String temp = null;
1194 if (optstring.indexOf(c) != -1)
1195 temp = optstring.substring(optstring.indexOf(c));
1196
1197 if (nextchar.equals(""))
1198 ++optind;
1199
1200 if ((temp == null) || (c == ':'))
1201 {
1202 if (opterr)
1203 {
1204 if (posixly_correct)
1205 {
1206 // 1003.2 specifies the format of this message
1207 Object[] msgArgs = { progname, new
1208 Character((char)c).toString() };
1209 System.err.println(MessageFormat.format(
1210 _messages.getString("getopt.illegal"), msgArgs));
1211 }
1212 else
1213 {
1214 Object[] msgArgs = { progname, new
1215 Character((char)c).toString() };
1216 System.err.println(MessageFormat.format(
1217 _messages.getString("getopt.invalid"), msgArgs));
1218 }
1219 }
1220
1221 optopt = c;
1222
1223 return('?');
1224 }
1225
1226 // Convenience. Treat POSIX -W foo same as long option --foo
1227 if ((temp.charAt(0) == 'W') && (temp.length() > 1) && (temp.charAt(1) == ';'))
1228 {
1229 if (!nextchar.equals(""))
1230 {
1231 optarg = nextchar;
1232 }
1233 // No further cars in this argv element and no more argv elements
1234 else if (optind == argv.length)
1235 {
1236 if (opterr)
1237 {
1238 // 1003.2 specifies the format of this message.
1239 Object[] msgArgs = { progname, new
1240 Character((char)c).toString() };
1241 System.err.println(MessageFormat.format(
1242 _messages.getString("getopt.requires2"), msgArgs));
1243 }
1244
1245 optopt = c;
1246 if (optstring.charAt(0) == ':')
1247 return(':');
1248 else
1249 return('?');
1250 }
1251 else
1252 {
1253 // We already incremented `optind' once;
1254 // increment it again when taking next ARGV-elt as argument.
1255 nextchar = argv[optind];
1256 optarg = argv[optind];
1257 }
1258
1259 c = checkLongOption();
1260
1261 if (longopt_handled)
1262 return(c);
1263 else
1264 // Let the application handle it
1265 {
1266 nextchar = null;
1267 ++optind;
1268 return('W');
1269 }
1270 }
1271
1272 if ((temp.length() > 1) && (temp.charAt(1) == ':'))
1273 {
1274 if ((temp.length() > 2) && (temp.charAt(2) == ':'))
1275 // This is an option that accepts and argument optionally
1276 {
1277 if (!nextchar.equals(""))
1278 {
1279 optarg = nextchar;
1280 ++optind;
1281 }
1282 else
1283 {
1284 optarg = null;
1285 }
1286
1287 nextchar = null;
1288 }
1289 else
1290 {
1291 if (!nextchar.equals(""))
1292 {
1293 optarg = nextchar;
1294 ++optind;
1295 }
1296 else if (optind == argv.length)
1297 {
1298 if (opterr)
1299 {
1300 // 1003.2 specifies the format of this message
1301 Object[] msgArgs = { progname, new
1302 Character((char)c).toString() };
1303 System.err.println(MessageFormat.format(
1304 _messages.getString("getopt.requires2"), msgArgs));
1305 }
1306
1307 optopt = c;
1308
1309 if (optstring.charAt(0) == ':')
1310 return(':');
1311 else
1312 return('?');
1313 }
1314 else
1315 {
1316 optarg = argv[optind];
1317 ++optind;
1318
1319 // Ok, here's an obscure Posix case. If we have o:, and
1320 // we get -o -- foo, then we're supposed to skip the --,
1321 // end parsing of options, and make foo an operand to -o.
1322 // Only do this in Posix mode.
1323 if ((posixly_correct) && optarg.equals("--"))
1324 {
1325 // If end of argv, error out
1326 if (optind == argv.length)
1327 {
1328 if (opterr)
1329 {
1330 // 1003.2 specifies the format of this message
1331 Object[] msgArgs = { progname, new
1332 Character((char)c).toString() };
1333 System.err.println(MessageFormat.format(
1334 _messages.getString("getopt.requires2"), msgArgs));
1335 }
1336
1337 optopt = c;
1338
1339 if (optstring.charAt(0) == ':')
1340 return(':');
1341 else
1342 return('?');
1343 }
1344
1345 // Set new optarg and set to end
1346 // Don't permute as we do on -- up above since we
1347 // know we aren't in permute mode because of Posix.
1348 optarg = argv[optind];
1349 ++optind;
1350 first_nonopt = optind;
1351 last_nonopt = argv.length;
1352 endparse = true;
1353 }
1354 }
1355
1356 nextchar = null;
1357 }
1358 }
1359
1360 return(c);
1361}
1362
1363} // Class Getopt
1364
1365
Note: See TracBrowser for help on using the repository browser.