home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 35 Internet / 35-Internet.zip / syslog.zip / getopt.c < prev    next >
Text File  |  1994-10-16  |  16KB  |  546 lines

  1. /* getopt.c -- changed for emx by Eberhard Mattes -- Feb 1992 */
  2.  
  3. /* Getopt for GNU.
  4.    Copyright (C) 1987, 1989 Free Software Foundation, Inc.
  5.  
  6.    This program is free software; you can redistribute it and/or modify
  7.    it under the terms of the GNU General Public License as published by
  8.    the Free Software Foundation; either version 1, or (at your option)
  9.    any later version.
  10.  
  11.    This program is distributed in the hope that it will be useful,
  12.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  13.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14.    GNU General Public License for more details.
  15.  
  16.    You should have received a copy of the GNU General Public License
  17.    along with this program; if not, write to the Free Software
  18.    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
  19.  
  20. #define CONST const
  21.  
  22. /* This version of `getopt' appears to the caller like standard Unix `getopt'
  23.    but it behaves differently for the user, since it allows the user
  24.    to intersperse the options with the other arguments.
  25.  
  26.    As `getopt' works, it permutes the elements of `argv' so that,
  27.    when it is done, all the options precede everything else.  Thus
  28.    all application programs are extended to handle flexible argument order.
  29.  
  30.    Setting the environment variable _POSIX_OPTION_ORDER disables permutation.
  31.    Then the behavior is completely standard.
  32.  
  33.    GNU application programs can use a third alternative mode in which
  34.    they can distinguish the relative order of options and other arguments.  */
  35.  
  36. #include <stdio.h>
  37.  
  38. /* If compiled with GNU C, use the built-in alloca */
  39. char *alloca ();
  40.  
  41. #include <stdlib.h>
  42. #include <string.h>
  43. #define bcopy(s, d, n) memcpy ((d), (s), (n))
  44. #define index strchr
  45.  
  46. /* For communication from `getopt' to the caller.
  47.    When `getopt' finds an option that takes an argument,
  48.    the argument value is returned here.
  49.    Also, when `ordering' is RETURN_IN_ORDER,
  50.    each non-option ARGV-element is returned here.  */
  51.  
  52. char *optarg = 0;
  53.  
  54. /* Index in ARGV of the next element to be scanned.
  55.    This is used for communication to and from the caller
  56.    and for communication between successive calls to `getopt'.
  57.  
  58.    On entry to `getopt', zero means this is the first call; initialize.
  59.  
  60.    When `getopt' returns EOF, this is the index of the first of the
  61.    non-option elements that the caller should itself scan.
  62.  
  63.    Otherwise, `optind' communicates from one call to the next
  64.    how much of ARGV has been scanned so far.  */
  65.  
  66. int optind = 0;
  67.  
  68. /* The next char to be scanned in the option-element
  69.    in which the last option character we returned was found.
  70.    This allows us to pick up the scan where we left off.
  71.  
  72.    If this is zero, or a null string, it means resume the scan
  73.    by advancing to the next ARGV-element.  */
  74.  
  75. static char *nextchar;
  76.  
  77. /* Callers store zero here to inhibit the error message
  78.    for unrecognized options.  */
  79.  
  80. int opterr = 1;
  81.  
  82. /* Describe how to deal with options that follow non-option ARGV-elements.
  83.  
  84.    If the caller did not specify anything,
  85.    the default is REQUIRE_ORDER if the environment variable
  86.    _POSIX_OPTION_ORDER is defined, PERMUTE otherwise.
  87.  
  88.    REQUIRE_ORDER means don't recognize them as options.
  89.    Stop option processing when the first non-option is seen.
  90.    This is what Unix does.
  91.  
  92.    PERMUTE is the default.  We permute the contents of ARGV as we scan,
  93.    so that eventually all the options are at the end.  This allows options
  94.    to be given in any order, even with programs that were not written to
  95.    expect this.
  96.  
  97.    RETURN_IN_ORDER is an option available to programs that were written
  98.    to expect options and other ARGV-elements in any order and that care about
  99.    the ordering of the two.  We describe each non-option ARGV-element
  100.    as if it were the argument of an option with character code one.
  101.    Using `-' as the first character of the list of option characters
  102.    requests this mode of operation.
  103.  
  104.    The special argument `--' forces an end of option-scanning regardless
  105.    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
  106.    `--' can cause `getopt' to return EOF with `optind' != ARGC.  */
  107.  
  108. static enum { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER } ordering;
  109.  
  110. /* Describe the long-named options requested by the application.
  111.    _GETOPT_LONG_OPTIONS is a vector of `struct option' terminated by an
  112.    element containing a name which is zero.
  113.    The field `has_arg' is 1 if the option takes an argument, 
  114.    2 if it takes an optional argument.  */
  115.  
  116. struct option
  117. {
  118.   char *name;
  119.   int has_arg;
  120.   int *flag;
  121.   int val;
  122. };
  123.  
  124. CONST struct option *_getopt_long_options;
  125.  
  126. int _getopt_long_only = 0;
  127.  
  128. /* Index in _GETOPT_LONG_OPTIONS of the long-named option actually found.
  129.    Only valid when a long-named option was found. */
  130.  
  131. int option_index;
  132.  
  133. /* Handle permutation of arguments.  */
  134.  
  135. /* Describe the part of ARGV that contains non-options that have
  136.    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
  137.    `last_nonopt' is the index after the last of them.  */
  138.  
  139. static int first_nonopt;
  140. static int last_nonopt;
  141.  
  142. /* Exchange two adjacent subsequences of ARGV.
  143.    One subsequence is elements [first_nonopt,last_nonopt)
  144.     which contains all the non-options that have been skipped so far.
  145.    The other is elements [last_nonopt,optind), which contains all
  146.     the options processed since those non-options were skipped.
  147.  
  148.    `first_nonopt' and `last_nonopt' are relocated so that they describe
  149.     the new indices of the non-options in ARGV after they are moved.  */
  150.  
  151. static void
  152. exchange (argv)
  153.      char **argv;
  154. {
  155.   int nonopts_size
  156.     = (last_nonopt - first_nonopt) * sizeof (char *);
  157.   char **temp = (char **) alloca (nonopts_size);
  158.  
  159.   /* Interchange the two blocks of data in argv.  */
  160.  
  161.   bcopy (&argv[first_nonopt], temp, nonopts_size);
  162.   bcopy (&argv[last_nonopt], &argv[first_nonopt],
  163.      (optind - last_nonopt) * sizeof (char *));
  164.   bcopy (temp, &argv[first_nonopt + optind - last_nonopt],
  165.      nonopts_size);
  166.  
  167.   /* Update records for the slots the non-options now occupy.  */
  168.  
  169.   first_nonopt += (optind - last_nonopt);
  170.   last_nonopt = optind;
  171. }
  172.  
  173. /* Scan elements of ARGV (whose length is ARGC) for option characters
  174.    given in OPTSTRING.
  175.  
  176.    If an element of ARGV starts with '-', and is not exactly "-" or "--",
  177.    then it is an option element.  The characters of this element
  178.    (aside from the initial '-') are option characters.  If `getopt'
  179.    is called repeatedly, it returns successively each of the option characters
  180.    from each of the option elements.
  181.  
  182.    If `getopt' finds another option character, it returns that character,
  183.    updating `optind' and `nextchar' so that the next call to `getopt' can
  184.    resume the scan with the following option character or ARGV-element.
  185.  
  186.    If there are no more option characters, `getopt' returns `EOF'.
  187.    Then `optind' is the index in ARGV of the first ARGV-element
  188.    that is not an option.  (The ARGV-elements have been permuted
  189.    so that those that are not options now come last.)
  190.  
  191.    OPTSTRING is a string containing the legitimate option characters.
  192.    If an option character is seen that is not listed in OPTSTRING,
  193.    return '?' after printing an error message.  If you set `opterr' to
  194.    zero, the error message is suppressed but we still return '?'.
  195.  
  196.    If a char in OPTSTRING is followed by a colon, that means it wants an arg,
  197.    so the following text in the same ARGV-element, or the text of the following
  198.    ARGV-element, is returned in `optarg'.  Two colons mean an option that
  199.    wants an optional arg; if there is text in the current ARGV-element,
  200.    it is returned in `optarg', otherwise `optarg' is set to zero.
  201.  
  202.    If OPTSTRING starts with `-', it requests a different method of handling the
  203.    non-option ARGV-elements.  See the comments about RETURN_IN_ORDER, above.
  204.  
  205.    Long-named options begin with `+' instead of `-'.
  206.    Their names may be abbreviated as long as the abbreviation is unique
  207.    or is an exact match for some defined option.  If they have an
  208.    argument, it follows the option name in the same ARGV-element, separated
  209.    from the option name by a `=', or else the in next ARGV-element.
  210.    `getopt' returns 0 when it finds a long-named option.  */
  211.  
  212. int
  213. getopt (argc, argv, optstring)
  214.      int argc;
  215.      char **argv;
  216.      char *optstring;
  217. {
  218.   optarg = 0;
  219.  
  220.   /* Initialize the internal data when the first call is made.
  221.      Start processing options with ARGV-element 1 (since ARGV-element 0
  222.      is the program name); the sequence of previously skipped
  223.      non-option ARGV-elements is empty.  */
  224.  
  225.   if (optind == 0)
  226.     {
  227.       first_nonopt = last_nonopt = optind = 1;
  228.  
  229.       nextchar = 0;
  230.  
  231.       /* Determine how to handle the ordering of options and nonoptions.  */
  232.  
  233.       if (optstring[0] == '-') {
  234.     ordering = RETURN_IN_ORDER;
  235.     optstring++;
  236.       } else if (optstring[0] == '+') {
  237.     ordering = REQUIRE_ORDER;
  238.     optstring++;
  239.       } else
  240.     ordering = PERMUTE;
  241.     }
  242.  
  243.   if (nextchar == 0 || *nextchar == 0)
  244.     {
  245.       if (ordering == PERMUTE)
  246.     {
  247.       /* If we have just processed some options following some non-options,
  248.          exchange them so that the options come first.  */
  249.  
  250.       if (first_nonopt != last_nonopt && last_nonopt != optind)
  251.         exchange (argv);
  252.       else if (last_nonopt != optind)
  253.         first_nonopt = optind;
  254.  
  255.       /* Now skip any additional non-options
  256.          and extend the range of non-options previously skipped.  */
  257.  
  258.       while (optind < argc
  259.          && (argv[optind][0] != '-'
  260.              || argv[optind][1] == 0)
  261.          && (_getopt_long_options == 0
  262.              || argv[optind][0] != '+'
  263.              || argv[optind][1] == 0))
  264.         optind++;
  265.       last_nonopt = optind;
  266.     }
  267.  
  268.       /* Special ARGV-element `--' means premature end of options.
  269.      Skip it like a null option,
  270.      then exchange with previous non-options as if it were an option,
  271.      then skip everything else like a non-option.  */
  272.  
  273.       if (optind != argc && !strcmp (argv[optind], "--"))
  274.     {
  275.       optind++;
  276.  
  277.       if (first_nonopt != last_nonopt && last_nonopt != optind)
  278.         exchange (argv);
  279.       else if (first_nonopt == last_nonopt)
  280.         first_nonopt = optind;
  281.       last_nonopt = argc;
  282.  
  283.       optind = argc;
  284.     }
  285.  
  286.       /* If we have done all the ARGV-elements, stop the scan
  287.      and back over any non-options that we skipped and permuted.  */
  288.  
  289.       if (optind == argc)
  290.     {
  291.       /* Set the next-arg-index to point at the non-options
  292.          that we previously skipped, so the caller will digest them.  */
  293.       if (first_nonopt != last_nonopt)
  294.         optind = first_nonopt;
  295.       return EOF;
  296.     }
  297.      
  298.       /* If we have come to a non-option and did not permute it,
  299.      either stop the scan or describe it to the caller and pass it by.  */
  300.  
  301.       if ((argv[optind][0] != '-' || argv[optind][1] == 0)
  302.       && (_getopt_long_options == 0
  303.           || argv[optind][0] != '+' || argv[optind][1] == 0))
  304.     {
  305.       if (ordering == REQUIRE_ORDER)
  306.         return EOF;
  307.       optarg = argv[optind++];
  308.       return 1;
  309.     }
  310.  
  311.       /* We have found another option-ARGV-element.
  312.      Start decoding its characters.  */
  313.  
  314.       nextchar = argv[optind] + 1;
  315.     }
  316.  
  317.   if (_getopt_long_options != 0
  318.       && (argv[optind][0] == '+'
  319.       || (_getopt_long_only && argv[optind][0] == '-'))
  320.       )
  321.     {
  322.       CONST struct option *p;
  323.       char *s = nextchar;
  324.       int exact = 0;
  325.       int ambig = 0;
  326.       CONST struct option *pfound = 0;
  327.       int indfound;
  328.  
  329.       while (*s && *s != '=') s++;
  330.  
  331.       /* Test all options for either exact match or abbreviated matches.  */
  332.       for (p = _getopt_long_options, option_index = 0; p->name; 
  333.        p++, option_index++)
  334.     if (!strncmp (p->name, nextchar, s - nextchar))
  335.       {
  336.         if (s - nextchar == strlen (p->name))
  337.           {
  338.         /* Exact match found.  */
  339.         pfound = p;
  340.         indfound = option_index;
  341.         exact = 1;
  342.         break;
  343.           }
  344.         else if (pfound == 0)
  345.           {
  346.         /* First nonexact match found.  */
  347.         pfound = p;
  348.         indfound = option_index;
  349.           }
  350.         else
  351.           /* Second nonexact match found.  */
  352.           ambig = 1;
  353.       }
  354.  
  355.       if (ambig && !exact)
  356.     {
  357.       fprintf (stderr, "%s: option `%s' is ambiguous\n",
  358.            argv[0], argv[optind]);
  359.       nextchar += strlen (nextchar);               
  360.       return '?';
  361.     }
  362.  
  363.       if (pfound != 0)
  364.     {
  365.       option_index = indfound;
  366.       optind++;
  367.       if (*s)
  368.         {
  369.           if (pfound->has_arg > 0)
  370.         optarg = s + 1;
  371.           else
  372.         {
  373.           fprintf (stderr,
  374.                "%s: option `%c%s' doesn't allow an argument\n",
  375.                argv[0], argv[optind - 1][0], pfound->name);
  376.           nextchar += strlen (nextchar);               
  377.           return '?';
  378.         }
  379.         }
  380.       else if (pfound->has_arg == 1)
  381.         {
  382.           if (optind < argc)
  383.         optarg = argv[optind++];
  384.           else
  385.         {
  386.           fprintf (stderr, "%s: option `%s' requires an argument\n",
  387.                argv[0], argv[optind - 1]);
  388.           nextchar += strlen (nextchar);           
  389.           return '?';
  390.         }
  391.         }
  392.       nextchar += strlen (nextchar);
  393.       if (pfound->flag)
  394.         *(pfound->flag) = pfound->val;
  395.       return 0;
  396.     }
  397.       /* Can't find it as a long option.  If this is getopt_long_only,
  398.      and the option starts with '-' and is a valid short
  399.      option, then interpret it as a short option.  Otherwise it's
  400.      an error.  */
  401.       if (_getopt_long_only == 0 || argv[optind][0] == '+' ||
  402.       index (optstring, *nextchar) == 0)
  403.     {
  404.       if (opterr != 0)
  405.         fprintf (stderr, "%s: unrecognized option `%c%s'\n",
  406.              argv[0], argv[optind][0], nextchar);
  407.       nextchar += strlen (nextchar);           
  408.       return '?';
  409.     }
  410.     }
  411.  
  412.   /* Look at and handle the next option-character.  */
  413.  
  414.   {
  415.     char c = *nextchar++;
  416.     char *temp = index (optstring, c);
  417.  
  418.     /* Increment `optind' when we start to process its last character.  */
  419.     if (*nextchar == 0)
  420.       optind++;
  421.  
  422.     if (temp == 0 || c == ':')
  423.       {
  424.     if (opterr != 0)
  425.       {
  426.         if (c < 040 || c >= 0177)
  427.           fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
  428.                argv[0], c);
  429.         else
  430.           fprintf (stderr, "%s: unrecognized option `-%c'\n",
  431.                argv[0], c);
  432.       }
  433.     return '?';
  434.       }
  435.     if (temp[1] == ':')
  436.       {
  437.     if (temp[2] == ':')
  438.       {
  439.         /* This is an option that accepts an argument optionally.  */
  440.         if (*nextchar != 0)
  441.           {
  442.             optarg = nextchar;
  443.         optind++;
  444.           }
  445.         else
  446.           optarg = 0;
  447.         nextchar = 0;
  448.       }
  449.     else
  450.       {
  451.         /* This is an option that requires an argument.  */
  452.         if (*nextchar != 0)
  453.           {
  454.         optarg = nextchar;
  455.         /* If we end this ARGV-element by taking the rest as an arg,
  456.            we must advance to the next element now.  */
  457.         optind++;
  458.           }
  459.         else if (optind == argc)
  460.           {
  461.         if (opterr != 0)
  462.           fprintf (stderr, "%s: option `-%c' requires an argument\n",
  463.                argv[0], c);
  464.         c = '?';
  465.           }
  466.         else
  467.           /* We already incremented `optind' once;
  468.          increment it again when taking next ARGV-elt as argument.  */
  469.           optarg = argv[optind++];
  470.         nextchar = 0;
  471.       }
  472.       }
  473.     return c;
  474.   }
  475. }
  476.  
  477. #ifdef TEST
  478.  
  479. /* Compile with -DTEST to make an executable for use in testing
  480.    the above definition of `getopt'.  */
  481.  
  482. int
  483. main (argc, argv)
  484.      int argc;
  485.      char **argv;
  486. {
  487.   char c;
  488.   int digit_optind = 0;
  489.  
  490.   while (1)
  491.     {
  492.       int this_option_optind = optind;
  493.       if ((c = getopt (argc, argv, "abc:d:0123456789")) == EOF)
  494.     break;
  495.  
  496.       switch (c)
  497.     {
  498.     case '0':
  499.     case '1':
  500.     case '2':
  501.     case '3':
  502.     case '4':
  503.     case '5':
  504.     case '6':
  505.     case '7':
  506.     case '8':
  507.     case '9':
  508.       if (digit_optind != 0 && digit_optind != this_option_optind)
  509.         printf ("digits occur in two different argv-elements.\n");
  510.       digit_optind = this_option_optind;
  511.       printf ("option %c\n", c);
  512.       break;
  513.  
  514.     case 'a':
  515.       printf ("option a\n");
  516.       break;
  517.  
  518.     case 'b':
  519.       printf ("option b\n");
  520.       break;
  521.  
  522.     case 'c':
  523.       printf ("option c with value `%s'\n", optarg);
  524.       break;
  525.  
  526.     case '?':
  527.       break;
  528.  
  529.     default:
  530.       printf ("?? getopt returned character code 0%o ??\n", c);
  531.     }
  532.     }
  533.  
  534.   if (optind < argc)
  535.     {
  536.       printf ("non-option ARGV-elements: ");
  537.       while (optind < argc)
  538.     printf ("%s ", argv[optind++]);
  539.       printf ("\n");
  540.     }
  541.  
  542.   return 0;
  543. }
  544.  
  545. #endif /* TEST */
  546.