/[public]/getopt/trunk/getopt.c
ViewVC logotype

Contents of /getopt/trunk/getopt.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 371 - (show annotations)
Mon Nov 24 10:51:27 2014 UTC (9 years, 4 months ago) by frodo
File MIME type: text/plain
File size: 13402 byte(s)
(Frodo) Learn to spell ambiguous

1 /*
2 * getopt.c - Enhanced implementation of BSD getopt(1)
3 * Copyright (c) 1997-2014 Frodo Looijaard <frodo@frodo.looijaard.name>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 /*
21 * Version 1.0-b4: Tue Sep 23 1997. First public release.
22 * Version 1.0: Wed Nov 19 1997.
23 * Bumped up the version number to 1.0
24 * Fixed minor typo (CSH instead of TCSH)
25 * Version 1.0.1: Tue Jun 3 1998
26 * Fixed sizeof instead of strlen bug
27 * Bumped up the version number to 1.0.1
28 * Version 1.0.2: Thu Jun 11 1998 (not present)
29 * Fixed gcc-2.8.1 warnings
30 * Fixed --version/-V option (not present)
31 * Version 1.0.5: Tue Jun 22 1999
32 * Make -u option work (not present)
33 * Version 1.0.6: Tue Jun 27 2000
34 * No important changes
35 * Version 1.1.0: Tue Jun 30 2000
36 * Added NLS support (partly written by Arkadiusz Miƛkiewicz
37 * <misiek@pld.org.pl>)
38 * Version 1.1.4: Mon Nov 7 2005
39 * Fixed a few type's in the manpage
40 * Version 1.1.5: Sun Aug 12 2012
41 * Sync with util-linux-2.21, fixed build problems, many new translations
42 * Version 1.1.6: ??? 2014
43 * Sync with util-linux git 20141120, detect ambiguous long options
44 */
45
46 /* Exit codes:
47 * 0) No errors, successful operation.
48 * 1) getopt(3) returned an error.
49 * 2) A problem with parameter parsing for getopt(1).
50 * 3) Internal error, out of memory
51 * 4) Returned for -T
52 */
53 #define GETOPT_EXIT_CODE 1
54 #define PARAMETER_EXIT_CODE 2
55 #define XALLOC_EXIT_CODE 3
56 #define TEST_EXIT_CODE 4
57
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <unistd.h>
62 #include <ctype.h>
63
64 #if LIBCGETOPT
65 #include <getopt.h>
66 #else
67 #include "getopt.h"
68 #endif
69
70 #include "util-linux-compat.h"
71 #include "nls.h"
72 #include "xalloc.h"
73
74 /* NON_OPT is the code that is returned when a non-option is found in '+'
75 * mode */
76 #define NON_OPT 1
77 /* LONG_OPT is the code that is returned when a long option is found. */
78 #define LONG_OPT 0
79
80 /* The shells recognized. */
81 typedef enum { BASH, TCSH } shell_t;
82
83
84 /* Some global variables that tells us how to parse. */
85 static shell_t shell = BASH; /* The shell we generate output for. */
86 static int quiet_errors = 0; /* 0 is not quiet. */
87 static int quiet_output = 0; /* 0 is not quiet. */
88 static int quote = 1; /* 1 is do quote. */
89
90 /* Allow changing which getopt is in use with function pointer */
91 int (*getopt_long_fp) (int argc, char *const *argv, const char *optstr,
92 const struct option * longopts, int *longindex);
93
94 /* Function prototypes */
95 static const char *normalize(const char *arg);
96 static int generate_output(char *argv[], int argc, const char *optstr,
97 const struct option *longopts);
98 static void parse_error(const char *message);
99 static void add_long_options(char *options);
100 static void add_longopt(const char *name, int has_arg);
101 static void print_help(void);
102 static void set_shell(const char *new_shell);
103
104 /*
105 * This function 'normalizes' a single argument: it puts single quotes
106 * around it and escapes other special characters. If quote is false, it
107 * just returns its argument.
108 *
109 * Bash only needs special treatment for single quotes; tcsh also recognizes
110 * exclamation marks within single quotes, and nukes whitespace. This
111 * function returns a pointer to a buffer that is overwritten by each call.
112 */
113 static const char *normalize(const char *arg)
114 {
115 static char *BUFFER = NULL;
116 const char *argptr = arg;
117 char *bufptr;
118
119 free(BUFFER);
120
121 if (!quote) {
122 /* Just copy arg */
123 BUFFER = xmalloc(strlen(arg) + 1);
124 strcpy(BUFFER, arg);
125 return BUFFER;
126 }
127
128 /*
129 * Each character in arg may take up to four characters in the
130 * result: For a quote we need a closing quote, a backslash, a quote
131 * and an opening quote! We need also the global opening and closing
132 * quote, and one extra character for '\0'.
133 */
134 BUFFER = xmalloc(strlen(arg) * 4 + 3);
135
136 bufptr = BUFFER;
137 *bufptr++ = '\'';
138
139 while (*argptr) {
140 if (*argptr == '\'') {
141 /* Quote: replace it with: '\'' */
142 *bufptr++ = '\'';
143 *bufptr++ = '\\';
144 *bufptr++ = '\'';
145 *bufptr++ = '\'';
146 } else if (shell == TCSH && *argptr == '!') {
147 /* Exclamation mark: replace it with: \! */
148 *bufptr++ = '\'';
149 *bufptr++ = '\\';
150 *bufptr++ = '!';
151 *bufptr++ = '\'';
152 } else if (shell == TCSH && *argptr == '\n') {
153 /* Newline: replace it with: \n */
154 *bufptr++ = '\\';
155 *bufptr++ = 'n';
156 } else if (shell == TCSH && isspace(*argptr)) {
157 /* Non-newline whitespace: replace it with \<ws> */
158 *bufptr++ = '\'';
159 *bufptr++ = '\\';
160 *bufptr++ = *argptr;
161 *bufptr++ = '\'';
162 } else
163 /* Just copy */
164 *bufptr++ = *argptr;
165 argptr++;
166 }
167 *bufptr++ = '\'';
168 *bufptr++ = '\0';
169 return BUFFER;
170 }
171
172 /*
173 * Generate the output. argv[0] is the program name (used for reporting errors).
174 * argv[1..] contains the options to be parsed. argc must be the number of
175 * elements in argv (ie. 1 if there are no options, only the program name),
176 * optstr must contain the short options, and longopts the long options.
177 * Other settings are found in global variables.
178 */
179 static int generate_output(char *argv[], int argc, const char *optstr,
180 const struct option *longopts)
181 {
182 int exit_code = EXIT_SUCCESS; /* Assume everything will be OK */
183 int opt;
184 int longindex;
185 const char *charptr;
186
187 if (quiet_errors)
188 /* No error reporting from getopt(3) */
189 opterr = 0;
190 /* Reset getopt(3) */
191 optind = 0;
192
193 while ((opt =
194 (getopt_long_fp(argc, argv, optstr, longopts, &longindex)))
195 != EOF)
196 if (opt == '?' || opt == ':')
197 exit_code = GETOPT_EXIT_CODE;
198 else if (!quiet_output) {
199 if (opt == LONG_OPT) {
200 printf(" --%s", longopts[longindex].name);
201 if (longopts[longindex].has_arg)
202 printf(" %s", normalize(optarg ? optarg : ""));
203 } else if (opt == NON_OPT)
204 printf(" %s", normalize(optarg ? optarg : ""));
205 else {
206 printf(" -%c", opt);
207 charptr = strchr(optstr, opt);
208 if (charptr != NULL && *++charptr == ':')
209 printf(" %s", normalize(optarg ? optarg : ""));
210 }
211 }
212
213 if (!quiet_output) {
214 printf(" --");
215 while (optind < argc)
216 printf(" %s", normalize(argv[optind++]));
217 printf("\n");
218 }
219 return exit_code;
220 }
221
222 /*
223 * Report an error when parsing getopt's own arguments. If message is NULL,
224 * we already sent a message, we just exit with a helpful hint.
225 */
226 static void __attribute__ ((__noreturn__)) parse_error(const char *message)
227 {
228 if (message)
229 warnx("%s", message);
230 fprintf(stderr, _("Try `%s --help' for more information.\n"),
231 program_invocation_short_name);
232 exit(PARAMETER_EXIT_CODE);
233 }
234
235 static struct option *long_options = NULL;
236 static int long_options_length = 0; /* Length of array */
237 static int long_options_nr = 0; /* Nr of used elements in array */
238 #define LONG_OPTIONS_INCR 10
239 #define init_longopt() add_longopt(NULL,0)
240
241 /* Register a long option. The contents of name is copied. */
242 static void add_longopt(const char *name, int has_arg)
243 {
244 char *tmp;
245 static int flag;
246
247 if (!name) {
248 /* init */
249 free(long_options);
250 long_options = NULL;
251 long_options_length = 0;
252 long_options_nr = 0;
253 }
254
255 if (long_options_nr == long_options_length) {
256 long_options_length += LONG_OPTIONS_INCR;
257 long_options = xrealloc(long_options,
258 sizeof(struct option) *
259 long_options_length);
260 }
261
262 long_options[long_options_nr].name = NULL;
263 long_options[long_options_nr].has_arg = 0;
264 long_options[long_options_nr].flag = NULL;
265 long_options[long_options_nr].val = 0;
266
267 if (long_options_nr && name) {
268 /* Not for init! */
269 long_options[long_options_nr - 1].has_arg = has_arg;
270 long_options[long_options_nr - 1].flag = &flag;
271 long_options[long_options_nr - 1].val = long_options_nr;
272 tmp = xmalloc(strlen(name) + 1);
273 strcpy(tmp, name);
274 long_options[long_options_nr - 1].name = tmp;
275 }
276 long_options_nr++;
277 }
278
279
280 /*
281 * Register several long options. options is a string of long options,
282 * separated by commas or whitespace. This nukes options!
283 */
284 static void add_long_options(char *options)
285 {
286 int arg_opt;
287 char *tokptr = strtok(options, ", \t\n");
288 while (tokptr) {
289 arg_opt = no_argument;
290 if (strlen(tokptr) > 0) {
291 if (tokptr[strlen(tokptr) - 1] == ':') {
292 if (tokptr[strlen(tokptr) - 2] == ':') {
293 tokptr[strlen(tokptr) - 2] = '\0';
294 arg_opt = optional_argument;
295 } else {
296 tokptr[strlen(tokptr) - 1] = '\0';
297 arg_opt = required_argument;
298 }
299 if (strlen(tokptr) == 0)
300 parse_error(_
301 ("empty long option after "
302 "-l or --long argument"));
303 }
304 add_longopt(tokptr, arg_opt);
305 }
306 tokptr = strtok(NULL, ", \t\n");
307 }
308 }
309
310 static void set_shell(const char *new_shell)
311 {
312 if (!strcmp(new_shell, "bash"))
313 shell = BASH;
314 else if (!strcmp(new_shell, "tcsh"))
315 shell = TCSH;
316 else if (!strcmp(new_shell, "sh"))
317 shell = BASH;
318 else if (!strcmp(new_shell, "csh"))
319 shell = TCSH;
320 else
321 parse_error(_
322 ("unknown shell after -s or --shell argument"));
323 }
324
325 static void __attribute__ ((__noreturn__)) print_help(void)
326 {
327 fputs(USAGE_HEADER, stderr);
328 fprintf(stderr, _(
329 " %1$s optstring parameters\n"
330 " %1$s [options] [--] optstring parameters\n"
331 " %1$s [options] -o|--options optstring [options] [--] parameters\n"),
332 program_invocation_short_name);
333
334 fputs(USAGE_OPTIONS, stderr);
335 fputs(_(" -a, --alternative Allow long options starting with single -\n"), stderr);
336 fputs(_(" -l, --longoptions <longopts> Long options to be recognized\n"), stderr);
337 fputs(_(" -n, --name <progname> The name under which errors are reported\n"), stderr);
338 fputs(_(" -o, --options <optstring> Short options to be recognized\n"), stderr);
339 fputs(_(" -q, --quiet Disable error reporting by getopt(3)\n"), stderr);
340 fputs(_(" -Q, --quiet-output No normal output\n"), stderr);
341 fputs(_(" -s, --shell <shell> Set shell quoting conventions\n"), stderr);
342 fputs(_(" -T, --test Test for getopt(1) version\n"), stderr);
343 fputs(_(" -u, --unquoted Do not quote the output\n"), stderr);
344 fputs(USAGE_SEPARATOR, stderr);
345 fputs(USAGE_HELP, stderr);
346 fputs(USAGE_VERSION, stderr);
347 fprintf(stderr, USAGE_MAN_TAIL("getopt(1)"));
348 exit(PARAMETER_EXIT_CODE);
349 }
350
351 int main(int argc, char *argv[])
352 {
353 char *optstr = NULL;
354 char *name = NULL;
355 int opt;
356 int compatible = 0;
357
358 /* Stop scanning as soon as a non-option argument is found! */
359 static const char *shortopts = "+ao:l:n:qQs:TuhV";
360 static const struct option longopts[] = {
361 {"options", required_argument, NULL, 'o'},
362 {"longoptions", required_argument, NULL, 'l'},
363 {"quiet", no_argument, NULL, 'q'},
364 {"quiet-output", no_argument, NULL, 'Q'},
365 {"shell", required_argument, NULL, 's'},
366 {"test", no_argument, NULL, 'T'},
367 {"unquoted", no_argument, NULL, 'u'},
368 {"help", no_argument, NULL, 'h'},
369 {"alternative", no_argument, NULL, 'a'},
370 {"name", required_argument, NULL, 'n'},
371 {"version", no_argument, NULL, 'V'},
372 {NULL, 0, NULL, 0}
373 };
374
375 setlocale(LC_ALL, "");
376 bindtextdomain(PACKAGE, LOCALEDIR);
377 textdomain(PACKAGE);
378
379 init_longopt();
380 getopt_long_fp = getopt_long;
381
382 if (getenv("GETOPT_COMPATIBLE"))
383 compatible = 1;
384
385 if (argc == 1) {
386 if (compatible) {
387 /*
388 * For some reason, the original getopt gave no
389 * error when there were no arguments.
390 */
391 printf(" --\n");
392 return EXIT_SUCCESS;
393 } else
394 parse_error(_("missing optstring argument"));
395 }
396
397 if (argv[1][0] != '-' || compatible) {
398 quote = 0;
399 optstr = xmalloc(strlen(argv[1]) + 1);
400 strcpy(optstr, argv[1] + strspn(argv[1], "-+"));
401 argv[1] = argv[0];
402 return generate_output(argv + 1, argc - 1, optstr,
403 long_options);
404 }
405
406 while ((opt =
407 getopt_long(argc, argv, shortopts, longopts, NULL)) != EOF)
408 switch (opt) {
409 case 'a':
410 getopt_long_fp = getopt_long_only;
411 break;
412 case 'h':
413 print_help();
414 case 'o':
415 free(optstr);
416 optstr = xmalloc(strlen(optarg) + 1);
417 strcpy(optstr, optarg);
418 break;
419 case 'l':
420 add_long_options(optarg);
421 break;
422 case 'n':
423 free(name);
424 name = xmalloc(strlen(optarg) + 1);
425 strcpy(name, optarg);
426 break;
427 case 'q':
428 quiet_errors = 1;
429 break;
430 case 'Q':
431 quiet_output = 1;
432 break;
433 case 's':
434 set_shell(optarg);
435 break;
436 case 'T':
437 return TEST_EXIT_CODE;
438 case 'u':
439 quote = 0;
440 break;
441 case 'V':
442 printf(UTIL_LINUX_VERSION);
443 return EXIT_SUCCESS;
444 case '?':
445 case ':':
446 parse_error(NULL);
447 default:
448 parse_error(_("internal error, contact the author."));
449 }
450
451 if (!optstr) {
452 if (optind >= argc)
453 parse_error(_("missing optstring argument"));
454 else {
455 optstr = xmalloc(strlen(argv[optind]) + 1);
456 strcpy(optstr, argv[optind]);
457 optind++;
458 }
459 }
460 if (name)
461 argv[optind - 1] = name;
462 else
463 argv[optind - 1] = argv[0];
464
465 return generate_output(argv + optind - 1, argc-optind + 1,
466 optstr, long_options);
467 }

frodo@frodo.looijaard.name
ViewVC Help
Powered by ViewVC 1.1.26