getoptx.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. /* This version of `getopt' appears to the caller like standard Unix getopt()
  2. but it behaves differently for the user, since it allows the user
  3. to intersperse the options with the other arguments.
  4. As getopt() works, it permutes the elements of `argv' so that,
  5. when it is done, all the options precede everything else. Thus
  6. all application programs are extended to handle flexible argument order.
  7. Setting the environment variable _POSIX_OPTION_ORDER disables permutation.
  8. Then the behavior is completely standard.
  9. GNU application programs can use a third alternative mode in which
  10. they can distinguish the relative order of options and other arguments.
  11. */
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include "getoptx.h"
  16. /* Note that on some systems, the header files above declare variables
  17. for use with their native getopt facilities, and those variables have
  18. the same names as we'd like to use. So we use things like optargx
  19. instead of optarg to avoid the collision.
  20. */
  21. /* For communication from `getopt' to the caller.
  22. When `getopt' finds an option that takes an argument,
  23. the argument value is returned here.
  24. */
  25. static char *optargx = 0;
  26. /* Index in ARGV of the next element to be scanned.
  27. This is used for communication to and from the caller
  28. and for communication between successive calls to getoptx().
  29. On entry to getoptx(), zero means this is the first call; initialize.
  30. When getoptx() returns EOF, this is the index of the first of the
  31. non-option elements that the caller should itself scan.
  32. Otherwise, `optindx' communicates from one call to the next
  33. how much of ARGV has been scanned so far.
  34. */
  35. static int optindx = 0;
  36. /* The next char to be scanned in the option-element
  37. in which the last option character we returned was found.
  38. This allows us to pick up the scan where we left off.
  39. If this is zero, or a null string, it means resume the scan
  40. by advancing to the next ARGV-element. */
  41. static char *nextchar;
  42. /* Callers store zero here to inhibit the error message
  43. for unrecognized options.
  44. */
  45. static int opterrx;
  46. /* Index in _GETOPT_LONG_OPTIONS of the long-named option actually found.
  47. Only valid when a long-named option was found. */
  48. static int option_index;
  49. struct optionx * _getopt_long_options;
  50. /* Handle permutation of arguments. */
  51. /* Describe the part of ARGV that contains non-options that have
  52. been skipped. `first_nonopt' is the index in ARGV of the first of them;
  53. `last_nonopt' is the index after the last of them. */
  54. static int first_nonopt;
  55. static int last_nonopt;
  56. /* Exchange two adjacent subsequences of ARGV.
  57. One subsequence is elements [first_nonopt,last_nonopt)
  58. which contains all the non-options that have been skipped so far.
  59. The other is elements [last_nonopt,optindx), which contains all
  60. the options processed since those non-options were skipped.
  61. `first_nonopt' and `last_nonopt' are relocated so that they describe
  62. the new indices of the non-options in ARGV after they are moved. */
  63. static void
  64. exchange(char ** const argv) {
  65. unsigned int const nonopts_size =
  66. (last_nonopt - first_nonopt) * sizeof (char *);
  67. char **temp = (char **) malloc (nonopts_size);
  68. if (temp == NULL)
  69. abort();
  70. /* Interchange the two blocks of data in argv. */
  71. memcpy (temp, &argv[first_nonopt], nonopts_size);
  72. memcpy (&argv[first_nonopt], &argv[last_nonopt],
  73. (optindx - last_nonopt) * sizeof (char *));
  74. memcpy (&argv[first_nonopt + optindx - last_nonopt], temp,
  75. nonopts_size);
  76. /* Update records for the slots the non-options now occupy. */
  77. first_nonopt += (optindx - last_nonopt);
  78. last_nonopt = optindx;
  79. free(temp);
  80. }
  81. /* Scan elements of ARGV (whose length is ARGC) for option characters
  82. given in OPTSTRING.
  83. If an element of ARGV starts with '-', and is not exactly "-" or "--",
  84. then it is an option element. The characters of this element
  85. (aside from the initial '-') are option characters. If getoptx()
  86. is called repeatedly, it returns successively each of the option characters
  87. from each of the option elements.
  88. If getoptx() finds another option character, it returns that character,
  89. updating `optindx' and `nextchar' so that the next call to getoptx() can
  90. resume the scan with the following option character or ARGV-element.
  91. If there are no more option characters, getoptx() returns `EOF'.
  92. Then `optindx' is the index in ARGV of the first ARGV-element
  93. that is not an option. (The ARGV-elements have been permuted
  94. so that those that are not options now come last.)
  95. OPTSTRING is a string containing the legitimate option characters.
  96. If an option character is seen that is not listed in OPTSTRING,
  97. return '?' after printing an error message. If you set `opterrx' to
  98. zero, the error message is suppressed but we still return '?'.
  99. If a char in OPTSTRING is followed by a colon, that means it wants an arg,
  100. so the following text in the same ARGV-element, or the text of the following
  101. ARGV-element, is returned in `optargx'. Two colons mean an option that
  102. wants an optional arg; if there is text in the current ARGV-element,
  103. it is returned in `optargx', otherwise `optargx' is set to zero.
  104. If OPTSTRING starts with `-', it requests a different method of handling the
  105. non-option ARGV-elements. See the comments about RETURN_IN_ORDER, above.
  106. Long-named options begin with `+' instead of `-'.
  107. Their names may be abbreviated as long as the abbreviation is unique
  108. or is an exact match for some defined option. If they have an
  109. argument, it follows the option name in the same ARGV-element, separated
  110. from the option name by a `=', or else the in next ARGV-element.
  111. getoptx() returns 0 when it finds a long-named option. */
  112. static int
  113. getoptx(int const argc,
  114. char ** const argv,
  115. const char * const optstring) {
  116. optargx = 0;
  117. /* Initialize the internal data when the first call is made.
  118. Start processing options with ARGV-element 1 (since ARGV-element 0
  119. is the program name); the sequence of previously skipped
  120. non-option ARGV-elements is empty. */
  121. if (optindx == 0)
  122. {
  123. first_nonopt = last_nonopt = optindx = 1;
  124. nextchar = 0;
  125. }
  126. if (nextchar == 0 || *nextchar == 0)
  127. {
  128. /* If we have just processed some options following some non-options,
  129. exchange them so that the options come first. */
  130. if (first_nonopt != last_nonopt && last_nonopt != optindx)
  131. exchange (argv);
  132. else if (last_nonopt != optindx)
  133. first_nonopt = optindx;
  134. /* Now skip any additional non-options
  135. and extend the range of non-options previously skipped. */
  136. while (optindx < argc
  137. && (argv[optindx][0] != '-'|| argv[optindx][1] == 0)
  138. && (argv[optindx][0] != '+'|| argv[optindx][1] == 0))
  139. optindx++;
  140. last_nonopt = optindx;
  141. /* Special ARGV-element `--' means premature end of options.
  142. Skip it like a null option,
  143. then exchange with previous non-options as if it were an option,
  144. then skip everything else like a non-option. */
  145. if (optindx != argc && !strcmp (argv[optindx], "--"))
  146. {
  147. optindx++;
  148. if (first_nonopt != last_nonopt && last_nonopt != optindx)
  149. exchange (argv);
  150. else if (first_nonopt == last_nonopt)
  151. first_nonopt = optindx;
  152. last_nonopt = argc;
  153. optindx = argc;
  154. }
  155. /* If we have done all the ARGV-elements, stop the scan
  156. and back over any non-options that we skipped and permuted. */
  157. if (optindx == argc)
  158. {
  159. /* Set the next-arg-index to point at the non-options
  160. that we previously skipped, so the caller will digest them. */
  161. if (first_nonopt != last_nonopt)
  162. optindx = first_nonopt;
  163. return EOF;
  164. }
  165. /* If we have come to a non-option and did not permute it,
  166. either stop the scan or describe it to the caller and pass
  167. it by.
  168. */
  169. if ((argv[optindx][0] != '-' || argv[optindx][1] == 0)
  170. && (argv[optindx][0] != '+' || argv[optindx][1] == 0))
  171. {
  172. optargx = argv[optindx++];
  173. return 1;
  174. }
  175. /* We have found another option-ARGV-element.
  176. Start decoding its characters. */
  177. nextchar = argv[optindx] + 1;
  178. }
  179. if ((argv[optindx][0] == '+' || (argv[optindx][0] == '-'))
  180. )
  181. {
  182. struct optionx *p;
  183. char *s = nextchar;
  184. int exact = 0;
  185. int ambig = 0;
  186. struct optionx * pfound;
  187. int indfound;
  188. while (*s && *s != '=') s++;
  189. indfound = 0; /* quite compiler warning */
  190. /* Test all options for either exact match or abbreviated matches. */
  191. for (p = _getopt_long_options, option_index = 0, pfound = NULL;
  192. p->name;
  193. p++, option_index++)
  194. if (!strncmp (p->name, nextchar, s - nextchar))
  195. {
  196. if ((unsigned int)(s - nextchar) == strlen (p->name))
  197. {
  198. /* Exact match found. */
  199. pfound = p;
  200. indfound = option_index;
  201. exact = 1;
  202. break;
  203. }
  204. else if (!pfound)
  205. {
  206. /* First nonexact match found. */
  207. pfound = p;
  208. indfound = option_index;
  209. }
  210. else
  211. /* Second nonexact match found. */
  212. ambig = 1;
  213. }
  214. if (ambig && !exact)
  215. {
  216. fprintf (stderr, "%s: option `%s' is ambiguous\n",
  217. argv[0], argv[optindx]);
  218. nextchar += strlen (nextchar);
  219. return '?';
  220. }
  221. if (pfound)
  222. {
  223. option_index = indfound;
  224. optindx++;
  225. if (*s)
  226. {
  227. if (pfound->has_arg > 0)
  228. optargx = s + 1;
  229. else
  230. {
  231. fprintf (stderr,
  232. "%s: option `%c%s' doesn't allow an argument\n",
  233. argv[0], argv[optindx - 1][0], pfound->name);
  234. nextchar += strlen (nextchar);
  235. return '?';
  236. }
  237. }
  238. else if (pfound->has_arg)
  239. {
  240. if (optindx < argc)
  241. optargx = argv[optindx++];
  242. else if (pfound->has_arg != 2)
  243. {
  244. fprintf (stderr, "%s: option `%s' requires an argument\n",
  245. argv[0], argv[optindx - 1]);
  246. nextchar += strlen (nextchar);
  247. return '?';
  248. }
  249. }
  250. nextchar += strlen (nextchar);
  251. if (pfound->flag)
  252. *(pfound->flag) = pfound->val;
  253. return 0;
  254. }
  255. if (argv[optindx][0] == '+' || strchr (optstring, *nextchar) == 0)
  256. {
  257. if (opterrx != 0)
  258. fprintf (stderr, "%s: unrecognized option `%c%s'\n",
  259. argv[0], argv[optindx][0], nextchar);
  260. nextchar += strlen (nextchar);
  261. return '?';
  262. }
  263. }
  264. /* Look at and handle the next option-character. */
  265. {
  266. char c = *nextchar++;
  267. char *temp = strchr (optstring, c);
  268. /* Increment `optindx' when we start to process its last character. */
  269. if (*nextchar == 0)
  270. optindx++;
  271. if (temp == 0 || c == ':')
  272. {
  273. if (opterrx != 0)
  274. {
  275. if (c < 040 || c >= 0177)
  276. fprintf (stderr, "%s: unrecognized option, "
  277. "character code 0%o\n",
  278. argv[0], c);
  279. else
  280. fprintf (stderr, "%s: unrecognized option `-%c'\n",
  281. argv[0], c);
  282. }
  283. return '?';
  284. }
  285. if (temp[1] == ':')
  286. {
  287. if (temp[2] == ':')
  288. {
  289. /* This is an option that accepts an argument optionally. */
  290. if (*nextchar != 0)
  291. {
  292. optargx = nextchar;
  293. optindx++;
  294. }
  295. else
  296. optargx = 0;
  297. nextchar = 0;
  298. }
  299. else
  300. {
  301. /* This is an option that requires an argument. */
  302. if (*nextchar != 0)
  303. {
  304. optargx = nextchar;
  305. /* If we end this ARGV-element by taking the rest
  306. as an arg, we must advance to the next element
  307. now.
  308. */
  309. optindx++;
  310. }
  311. else if (optindx == argc)
  312. {
  313. if (opterrx != 0)
  314. fprintf (stderr,
  315. "%s: option `-%c' requires an argument\n",
  316. argv[0], c);
  317. c = '?';
  318. }
  319. else
  320. /* We already incremented `optindx' once;
  321. increment it again when taking next ARGV-elt as
  322. argument.
  323. */
  324. optargx = argv[optindx++];
  325. nextchar = 0;
  326. }
  327. }
  328. return c;
  329. }
  330. }
  331. void
  332. getopt_long_onlyx(int const argc,
  333. char ** const argv,
  334. const char * const options,
  335. struct optionx * const long_options,
  336. unsigned int * const opt_index,
  337. int const opterrArg,
  338. int * const end_of_options,
  339. const char ** const optarg_arg,
  340. const char ** const unrecognized_option) {
  341. int rc;
  342. opterrx = opterrArg;
  343. _getopt_long_options = long_options;
  344. rc = getoptx(argc, argv, options);
  345. if (rc == 0)
  346. *opt_index = option_index;
  347. if (rc == '?')
  348. *unrecognized_option = argv[optindx];
  349. else
  350. *unrecognized_option = NULL;
  351. if (rc < 0)
  352. *end_of_options = 1;
  353. else
  354. *end_of_options = 0;
  355. *optarg_arg = optargx;
  356. }
  357. unsigned int
  358. getopt_argstart(void) {
  359. /*----------------------------------------------------------------------------
  360. This is a replacement for what traditional getopt does with global
  361. variables.
  362. You call this after getopt_long_onlyx() has returned "end of
  363. options"
  364. -----------------------------------------------------------------------------*/
  365. return optindx;
  366. }
  367. /* Getopt for GNU.
  368. Copyright (C) 1987, 1989 Free Software Foundation, Inc.
  369. This program is free software; you can redistribute it and/or modify
  370. it under the terms of the GNU General Public License as published by
  371. the Free Software Foundation; either version 1, or (at your option)
  372. any later version.
  373. This program is distributed in the hope that it will be useful,
  374. but WITHOUT ANY WARRANTY; without even the implied warranty of
  375. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  376. GNU General Public License for more details.
  377. You should have received a copy of the GNU General Public License
  378. along with this program; if not, write to the Free Software
  379. Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  380. */