1 /* Getopt for GNU.
2 NOTE: getopt is now part of the C library, so if you don't know what
3 "Keep this file name-space clean" means, talk to roland@gnu.ai.mit.edu
4 before changing it!
5
6 Copyright (C) 1987, 88, 89, 90, 91, 92, 1993
7 Free Software Foundation, Inc.
8
9 This program is free software; you can redistribute it and/or modify it
10 under the terms of the GNU General Public License as published by the
11 Free Software Foundation; either version 2, or (at your option) any
12 later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. */
22
23
24 #ifdef HAVE_CONFIG_H
25 #include "config.h"
26 #endif
27
28 #ifndef __STDC__
29 # ifndef const
30 # define const
31 # endif
32 #endif
33
34 /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>. */
35 #ifndef _NO_PROTO
36 #define _NO_PROTO
37 #endif
38
39 #include <stdio.h>
40 //#include "tailor.h"
41
42 /* Comment out all this code if we are using the GNU C Library, and are not
43 actually compiling the library itself. This code is part of the GNU C
44 Library, but also included in many other GNU distributions. Compiling
45 and linking in this code is a waste when using the GNU C library
46 (especially if it is a shared library). Rather than having every GNU
47 program understand `configure --with-gnu-libc' and omit the object files,
48 it is simpler to just do this in the source for each such file. */
49
50 #if defined (_LIBC) || !defined (__GNU_LIBRARY__) || !__MacOSX__
51
52
53 /* This needs to come after some library #include
54 to get __GNU_LIBRARY__ defined. */
55 #ifdef __GNU_LIBRARY__
56 /* Don't include stdlib.h for non-GNU C libraries because some of them
57 contain conflicting prototypes for getopt. */
58 #include <stdlib.h>
59 #endif /* GNU C library. */
60
61 /* If GETOPT_COMPAT is defined, `+' as well as `--' can introduce a
62 long-named option. Because this is not POSIX.2 compliant, it is
63 being phased out. */
64 /* #define GETOPT_COMPAT */
65
66 /* This version of `getopt' appears to the caller like standard Unix `getopt'
67 but it behaves differently for the user, since it allows the user
68 to intersperse the options with the other arguments.
69
70 As `getopt' works, it permutes the elements of ARGV so that,
71 when it is done, all the options precede everything else. Thus
72 all application programs are extended to handle flexible argument order.
73
74 Setting the environment variable POSIXLY_CORRECT disables permutation.
75 Then the behavior is completely standard.
76
77 GNU application programs can use a third alternative mode in which
78 they can distinguish the relative order of options and other arguments. */
79
80 #include "getopt.h"
81
82 /* For communication from `getopt' to the caller.
83 When `getopt' finds an option that takes an argument,
84 the argument value is returned here.
85 Also, when `ordering' is RETURN_IN_ORDER,
86 each non-option ARGV-element is returned here. */
87
88 char *optarg = 0;
89
90 /* Index in ARGV of the next element to be scanned.
91 This is used for communication to and from the caller
92 and for communication between successive calls to `getopt'.
93
94 On entry to `getopt', zero means this is the first call; initialize.
95
96 When `getopt' returns EOF, this is the index of the first of the
97 non-option elements that the caller should itself scan.
98
99 Otherwise, `optind' communicates from one call to the next
100 how much of ARGV has been scanned so far. */
101
102 /* XXX 1003.2 says this must be 1 before any call. */
103 int optind = 0;
104
105 /* The next char to be scanned in the option-element
106 in which the last option character we returned was found.
107 This allows us to pick up the scan where we left off.
108
109 If this is zero, or a null string, it means resume the scan
110 by advancing to the next ARGV-element. */
111
112 static char *nextchar;
113
114 /* Callers store zero here to inhibit the error message
115 for unrecognized options. */
116
117 int opterr = 1;
118
119 /* Set to an option character which was unrecognized.
120 This must be initialized on some systems to avoid linking in the
121 system's own getopt implementation. */
122
123 #define BAD_OPTION '\0'
124 int optopt = BAD_OPTION;
125
126 /* Describe how to deal with options that follow non-option ARGV-elements.
127
128 If the caller did not specify anything,
129 the default is REQUIRE_ORDER if the environment variable
130 POSIXLY_CORRECT is defined, PERMUTE otherwise.
131
132 REQUIRE_ORDER means don't recognize them as options;
133 stop option processing when the first non-option is seen.
134 This is what Unix does.
135 This mode of operation is selected by either setting the environment
136 variable POSIXLY_CORRECT, or using `+' as the first character
137 of the list of option characters.
138
139 PERMUTE is the default. We permute the contents of ARGV as we scan,
140 so that eventually all the non-options are at the end. This allows options
141 to be given in any order, even with programs that were not written to
142 expect this.
143
144 RETURN_IN_ORDER is an option available to programs that were written
145 to expect options and other ARGV-elements in any order and that care about
146 the ordering of the two. We describe each non-option ARGV-element
147 as if it were the argument of an option with character code 1.
148 Using `-' as the first character of the list of option characters
149 selects this mode of operation.
150
151 The special argument `--' forces an end of option-scanning regardless
152 of the value of `ordering'. In the case of RETURN_IN_ORDER, only
153 `--' can cause `getopt' to return EOF with `optind' != ARGC. */
154
155 static enum
156 {
157 REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
158 } ordering;
159
160 #if defined(__GNU_LIBRARY__) || defined(__APPLE__)
161 /* We want to avoid inclusion of string.h with non-GNU libraries
162 because there are many ways it can cause trouble.
163 On some systems, it contains special magic macros that don't work
164 in GCC. */
165 #include <string.h>
166 #define my_index strchr
167 #define my_strlen strlen
168 #else
169
170 /* Avoid depending on library functions or files
171 whose names are inconsistent. */
172
173 #if __STDC__ || defined(PROTO)
174 extern char *getenv(const char *name);
175 extern int strcmp (const char *s1, const char *s2);
176 extern int strncmp(const char *s1, const char *s2, size_t n);
177
178 static int my_strlen(const char *s);
179 static char *my_index (const char *str, int chr);
180 #else
181 extern char *getenv ();
182 #endif
183
184 static int
my_strlen(str)185 my_strlen (str)
186 const char *str;
187 {
188 int n = 0;
189 while (*str++)
190 n++;
191 return n;
192 }
193
194 static char *
my_index(str,chr)195 my_index (str, chr)
196 const char *str;
197 int chr;
198 {
199 while (*str)
200 {
201 if (*str == chr)
202 return (char *) str;
203 str++;
204 }
205 return 0;
206 }
207
208 #endif /* GNU C library. */
209
210 /* Handle permutation of arguments. */
211
212 /* Describe the part of ARGV that contains non-options that have
213 been skipped. `first_nonopt' is the index in ARGV of the first of them;
214 `last_nonopt' is the index after the last of them. */
215
216 static int first_nonopt;
217 static int last_nonopt;
218
219 /* Exchange two adjacent subsequences of ARGV.
220 One subsequence is elements [first_nonopt,last_nonopt)
221 which contains all the non-options that have been skipped so far.
222 The other is elements [last_nonopt,optind), which contains all
223 the options processed since those non-options were skipped.
224
225 `first_nonopt' and `last_nonopt' are relocated so that they describe
226 the new indices of the non-options in ARGV after they are moved.
227
228 To perform the swap, we first reverse the order of all elements. So
229 all options now come before all non options, but they are in the
230 wrong order. So we put back the options and non options in original
231 order by reversing them again. For example:
232 original input: a b c -x -y
233 reverse all: -y -x c b a
234 reverse options: -x -y c b a
235 reverse non options: -x -y a b c
236 */
237
238 #if __STDC__ || defined(PROTO)
239 static void exchange (char **argv);
240 #endif
241
242 static void
exchange(argv)243 exchange (argv)
244 char **argv;
245 {
246 char *temp, **first, **last;
247
248 /* Reverse all the elements [first_nonopt, optind) */
249 first = &argv[first_nonopt];
250 last = &argv[optind-1];
251 while (first < last) {
252 temp = *first; *first = *last; *last = temp; first++; last--;
253 }
254 /* Put back the options in order */
255 first = &argv[first_nonopt];
256 first_nonopt += (optind - last_nonopt);
257 last = &argv[first_nonopt - 1];
258 while (first < last) {
259 temp = *first; *first = *last; *last = temp; first++; last--;
260 }
261
262 /* Put back the non options in order */
263 first = &argv[first_nonopt];
264 last_nonopt = optind;
265 last = &argv[last_nonopt-1];
266 while (first < last) {
267 temp = *first; *first = *last; *last = temp; first++; last--;
268 }
269 }
270
271 /* Scan elements of ARGV (whose length is ARGC) for option characters
272 given in OPTSTRING.
273
274 If an element of ARGV starts with '-', and is not exactly "-" or "--",
275 then it is an option element. The characters of this element
276 (aside from the initial '-') are option characters. If `getopt'
277 is called repeatedly, it returns successively each of the option characters
278 from each of the option elements.
279
280 If `getopt' finds another option character, it returns that character,
281 updating `optind' and `nextchar' so that the next call to `getopt' can
282 resume the scan with the following option character or ARGV-element.
283
284 If there are no more option characters, `getopt' returns `EOF'.
285 Then `optind' is the index in ARGV of the first ARGV-element
286 that is not an option. (The ARGV-elements have been permuted
287 so that those that are not options now come last.)
288
289 OPTSTRING is a string containing the legitimate option characters.
290 If an option character is seen that is not listed in OPTSTRING,
291 return BAD_OPTION after printing an error message. If you set `opterr' to
292 zero, the error message is suppressed but we still return BAD_OPTION.
293
294 If a char in OPTSTRING is followed by a colon, that means it wants an arg,
295 so the following text in the same ARGV-element, or the text of the following
296 ARGV-element, is returned in `optarg'. Two colons mean an option that
297 wants an optional arg; if there is text in the current ARGV-element,
298 it is returned in `optarg', otherwise `optarg' is set to zero.
299
300 If OPTSTRING starts with `-' or `+', it requests different methods of
301 handling the non-option ARGV-elements.
302 See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above.
303
304 Long-named options begin with `--' instead of `-'.
305 Their names may be abbreviated as long as the abbreviation is unique
306 or is an exact match for some defined option. If they have an
307 argument, it follows the option name in the same ARGV-element, separated
308 from the option name by a `=', or else the in next ARGV-element.
309 When `getopt' finds a long-named option, it returns 0 if that option's
310 `flag' field is nonzero, the value of the option's `val' field
311 if the `flag' field is zero.
312
313 The elements of ARGV aren't really const, because we permute them.
314 But we pretend they're const in the prototype to be compatible
315 with other systems.
316
317 LONGOPTS is a vector of `struct option' terminated by an
318 element containing a name which is zero.
319
320 LONGIND returns the index in LONGOPT of the long-named option found.
321 It is only valid when a long-named option has been found by the most
322 recent call.
323
324 If LONG_ONLY is nonzero, '-' as well as '--' can introduce
325 long-named options. */
326
327 int
_getopt_internal(argc,argv,optstring,longopts,longind,long_only)328 _getopt_internal (argc, argv, optstring, longopts, longind, long_only)
329 int argc;
330 char *const *argv;
331 const char *optstring;
332 const struct option *longopts;
333 int *longind;
334 int long_only;
335 {
336 int option_index;
337
338 optarg = 0;
339
340 /* Initialize the internal data when the first call is made.
341 Start processing options with ARGV-element 1 (since ARGV-element 0
342 is the program name); the sequence of previously skipped
343 non-option ARGV-elements is empty. */
344
345 if (optind == 0)
346 {
347 first_nonopt = last_nonopt = optind = 1;
348
349 nextchar = NULL;
350
351 /* Determine how to handle the ordering of options and nonoptions. */
352
353 if (optstring[0] == '-')
354 {
355 ordering = RETURN_IN_ORDER;
356 ++optstring;
357 }
358 else if (optstring[0] == '+')
359 {
360 ordering = REQUIRE_ORDER;
361 ++optstring;
362 }
363 else if (getenv ("POSIXLY_CORRECT") != NULL)
364 ordering = REQUIRE_ORDER;
365 else
366 ordering = PERMUTE;
367 }
368
369 if (nextchar == NULL || *nextchar == '\0')
370 {
371 if (ordering == PERMUTE)
372 {
373 /* If we have just processed some options following some non-options,
374 exchange them so that the options come first. */
375
376 if (first_nonopt != last_nonopt && last_nonopt != optind)
377 exchange ((char **) argv);
378 else if (last_nonopt != optind)
379 first_nonopt = optind;
380
381 /* Now skip any additional non-options
382 and extend the range of non-options previously skipped. */
383
384 while (optind < argc
385 && (argv[optind][0] != '-' || argv[optind][1] == '\0')
386 #ifdef GETOPT_COMPAT
387 && (longopts == NULL
388 || argv[optind][0] != '+' || argv[optind][1] == '\0')
389 #endif /* GETOPT_COMPAT */
390 )
391 optind++;
392 last_nonopt = optind;
393 }
394
395 /* Special ARGV-element `--' means premature end of options.
396 Skip it like a null option,
397 then exchange with previous non-options as if it were an option,
398 then skip everything else like a non-option. */
399
400 if (optind != argc && !strcmp (argv[optind], "--"))
401 {
402 optind++;
403
404 if (first_nonopt != last_nonopt && last_nonopt != optind)
405 exchange ((char **) argv);
406 else if (first_nonopt == last_nonopt)
407 first_nonopt = optind;
408 last_nonopt = argc;
409
410 optind = argc;
411 }
412
413 /* If we have done all the ARGV-elements, stop the scan
414 and back over any non-options that we skipped and permuted. */
415
416 if (optind == argc)
417 {
418 /* Set the next-arg-index to point at the non-options
419 that we previously skipped, so the caller will digest them. */
420 if (first_nonopt != last_nonopt)
421 optind = first_nonopt;
422 return EOF;
423 }
424
425 /* If we have come to a non-option and did not permute it,
426 either stop the scan or describe it to the caller and pass it by. */
427
428 if ((argv[optind][0] != '-' || argv[optind][1] == '\0')
429 #ifdef GETOPT_COMPAT
430 && (longopts == NULL
431 || argv[optind][0] != '+' || argv[optind][1] == '\0')
432 #endif /* GETOPT_COMPAT */
433 )
434 {
435 if (ordering == REQUIRE_ORDER)
436 return EOF;
437 optarg = argv[optind++];
438 return 1;
439 }
440
441 /* We have found another option-ARGV-element.
442 Start decoding its characters. */
443
444 nextchar = (argv[optind] + 1
445 + (longopts != NULL && argv[optind][1] == '-'));
446 }
447
448 if (longopts != NULL
449 && ((argv[optind][0] == '-'
450 && (argv[optind][1] == '-' || long_only))
451 #ifdef GETOPT_COMPAT
452 || argv[optind][0] == '+'
453 #endif /* GETOPT_COMPAT */
454 ))
455 {
456 const struct option *p;
457 char *s = nextchar;
458 int exact = 0;
459 int ambig = 0;
460 const struct option *pfound = NULL;
461 int indfound = 0;
462
463 while (*s && *s != '=')
464 s++;
465
466 /* Test all options for either exact match or abbreviated matches. */
467 for (p = longopts, option_index = 0; p->name;
468 p++, option_index++)
469 if (!strncmp (p->name, nextchar, s - nextchar))
470 {
471 if (s - nextchar == my_strlen (p->name))
472 {
473 /* Exact match found. */
474 pfound = p;
475 indfound = option_index;
476 exact = 1;
477 break;
478 }
479 else if (pfound == NULL)
480 {
481 /* First nonexact match found. */
482 pfound = p;
483 indfound = option_index;
484 }
485 else
486 /* Second nonexact match found. */
487 ambig = 1;
488 }
489
490 if (ambig && !exact)
491 {
492 if (opterr)
493 fprintf (stderr, "%s: option `%s' is ambiguous\n",
494 argv[0], argv[optind]);
495 nextchar += my_strlen (nextchar);
496 optind++;
497 return BAD_OPTION;
498 }
499
500 if (pfound != NULL)
501 {
502 option_index = indfound;
503 optind++;
504 if (*s)
505 {
506 /* Don't test has_arg with >, because some C compilers don't
507 allow it to be used on enums. */
508 if (pfound->has_arg)
509 optarg = s + 1;
510 else
511 {
512 if (opterr)
513 {
514 if (argv[optind - 1][1] == '-')
515 /* --option */
516 fprintf (stderr,
517 "%s: option `--%s' doesn't allow an argument\n",
518 argv[0], pfound->name);
519 else
520 /* +option or -option */
521 fprintf (stderr,
522 "%s: option `%c%s' doesn't allow an argument\n",
523 argv[0], argv[optind - 1][0], pfound->name);
524 }
525 nextchar += my_strlen (nextchar);
526 return BAD_OPTION;
527 }
528 }
529 else if (pfound->has_arg == 1)
530 {
531 if (optind < argc)
532 optarg = argv[optind++];
533 else
534 {
535 if (opterr)
536 fprintf (stderr, "%s: option `%s' requires an argument\n",
537 argv[0], argv[optind - 1]);
538 nextchar += my_strlen (nextchar);
539 return optstring[0] == ':' ? ':' : BAD_OPTION;
540 }
541 }
542 nextchar += my_strlen (nextchar);
543 if (longind != NULL)
544 *longind = option_index;
545 if (pfound->flag)
546 {
547 *(pfound->flag) = pfound->val;
548 return 0;
549 }
550 return pfound->val;
551 }
552 /* Can't find it as a long option. If this is not getopt_long_only,
553 or the option starts with '--' or is not a valid short
554 option, then it's an error.
555 Otherwise interpret it as a short option. */
556 if (!long_only || argv[optind][1] == '-'
557 #ifdef GETOPT_COMPAT
558 || argv[optind][0] == '+'
559 #endif /* GETOPT_COMPAT */
560 || my_index (optstring, *nextchar) == NULL)
561 {
562 if (opterr)
563 {
564 if (argv[optind][1] == '-')
565 /* --option */
566 fprintf (stderr, "%s: unrecognized option `--%s'\n",
567 argv[0], nextchar);
568 else
569 /* +option or -option */
570 fprintf (stderr, "%s: unrecognized option `%c%s'\n",
571 argv[0], argv[optind][0], nextchar);
572 }
573 nextchar = (char *) "";
574 optind++;
575 return BAD_OPTION;
576 }
577 }
578
579 /* Look at and handle the next option-character. */
580
581 {
582 char c = *nextchar++;
583 char *temp = my_index (optstring, c);
584
585 /* Increment `optind' when we start to process its last character. */
586 if (*nextchar == '\0')
587 ++optind;
588
589 if (temp == NULL || c == ':')
590 {
591 if (opterr)
592 {
593 #if 0
594 if (c < 040 || c >= 0177)
595 fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
596 argv[0], c);
597 else
598 fprintf (stderr, "%s: unrecognized option `-%c'\n", argv[0], c);
599 #else
600 /* 1003.2 specifies the format of this message. */
601 fprintf (stderr, "%s: illegal option -- %c\n", argv[0], c);
602 #endif
603 }
604 optopt = c;
605 return BAD_OPTION;
606 }
607 if (temp[1] == ':')
608 {
609 if (temp[2] == ':')
610 {
611 /* This is an option that accepts an argument optionally. */
612 if (*nextchar != '\0')
613 {
614 optarg = nextchar;
615 optind++;
616 }
617 else
618 optarg = 0;
619 nextchar = NULL;
620 }
621 else
622 {
623 /* This is an option that requires an argument. */
624 if (*nextchar != '\0')
625 {
626 optarg = nextchar;
627 /* If we end this ARGV-element by taking the rest as an arg,
628 we must advance to the next element now. */
629 optind++;
630 }
631 else if (optind == argc)
632 {
633 if (opterr)
634 {
635 #if 0
636 fprintf (stderr, "%s: option `-%c' requires an argument\n",
637 argv[0], c);
638 #else
639 /* 1003.2 specifies the format of this message. */
640 fprintf (stderr, "%s: option requires an argument -- %c\n",
641 argv[0], c);
642 #endif
643 }
644 optopt = c;
645 if (optstring[0] == ':')
646 c = ':';
647 else
648 c = BAD_OPTION;
649 }
650 else
651 /* We already incremented `optind' once;
652 increment it again when taking next ARGV-elt as argument. */
653 optarg = argv[optind++];
654 nextchar = NULL;
655 }
656 }
657 return c;
658 }
659 }
660
661 int
getopt(argc,argv,optstring)662 getopt (argc, argv, optstring)
663 int argc;
664 char *const *argv;
665 const char *optstring;
666 {
667 return _getopt_internal (argc, argv, optstring,
668 (const struct option *) 0,
669 (int *) 0,
670 0);
671 }
672
673 int
getopt_long(argc,argv,options,long_options,opt_index)674 getopt_long (argc, argv, options, long_options, opt_index)
675 int argc;
676 char *const *argv;
677 const char *options;
678 const struct option *long_options;
679 int *opt_index;
680 {
681 return _getopt_internal (argc, argv, options, long_options, opt_index, 0);
682 }
683
684 #endif /* _LIBC or not __GNU_LIBRARY__. */
685
686 #ifdef TEST
687
688 /* Compile with -DTEST to make an executable for use in testing
689 the above definition of `getopt'. */
690
691 int
main(argc,argv)692 main (argc, argv)
693 int argc;
694 char **argv;
695 {
696 int c;
697 int digit_optind = 0;
698
699 while (1)
700 {
701 int this_option_optind = optind ? optind : 1;
702
703 c = getopt (argc, argv, "abc:d:0123456789");
704 if (c == EOF)
705 break;
706
707 switch (c)
708 {
709 case '0':
710 case '1':
711 case '2':
712 case '3':
713 case '4':
714 case '5':
715 case '6':
716 case '7':
717 case '8':
718 case '9':
719 if (digit_optind != 0 && digit_optind != this_option_optind)
720 printf ("digits occur in two different argv-elements.\n");
721 digit_optind = this_option_optind;
722 printf ("option %c\n", c);
723 break;
724
725 case 'a':
726 printf ("option a\n");
727 break;
728
729 case 'b':
730 printf ("option b\n");
731 break;
732
733 case 'c':
734 printf ("option c with value `%s'\n", optarg);
735 break;
736
737 case BAD_OPTION:
738 break;
739
740 default:
741 printf ("?? getopt returned character code 0%o ??\n", c);
742 }
743 }
744
745 if (optind < argc)
746 {
747 printf ("non-option ARGV-elements: ");
748 while (optind < argc)
749 printf ("%s ", argv[optind++]);
750 printf ("\n");
751 }
752
753 exit (0);
754 }
755
756 #endif /* TEST */
757