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