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

Annotation of /getopt/trunk/getopt.c

Parent Directory Parent Directory | Revision Log Revision Log


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

1 frodo 259 /*
2 frodo 317 * getopt.c - Enhanced implementation of BSD getopt(1)
3 frodo 367 * Copyright (c) 1997-2014 Frodo Looijaard <frodo@frodo.looijaard.name>
4 frodo 317 *
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 frodo 364 * 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 frodo 317 */
19 frodo 259
20 frodo 364 /*
21 frodo 259 * Version 1.0-b4: Tue Sep 23 1997. First public release.
22 frodo 364 * Version 1.0: Wed Nov 19 1997.
23 frodo 259 * 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 frodo 364 * Added NLS support (partly written by Arkadiusz Miƛkiewicz
37 frodo 259 * <misiek@pld.org.pl>)
38 frodo 263 * Version 1.1.4: Mon Nov 7 2005
39     * Fixed a few type's in the manpage
40 frodo 361 * Version 1.1.5: Sun Aug 12 2012
41 frodo 327 * Sync with util-linux-2.21, fixed build problems, many new translations
42 frodo 370 * Version 1.1.6: ??? 2014
43 frodo 371 * Sync with util-linux git 20141120, detect ambiguous long options
44 frodo 259 */
45    
46 frodo 318 /* Exit codes:
47 frodo 364 * 0) No errors, successful operation.
48 frodo 318 * 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 frodo 259 #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 frodo 363 #include "util-linux-compat.h"
71 frodo 259 #include "nls.h"
72 frodo 322 #include "xalloc.h"
73 frodo 259
74 frodo 364 /* NON_OPT is the code that is returned when a non-option is found in '+'
75 frodo 317 * mode */
76 frodo 259 #define NON_OPT 1
77     /* LONG_OPT is the code that is returned when a long option is found. */
78 frodo 370 #define LONG_OPT 0
79 frodo 259
80     /* The shells recognized. */
81 frodo 320 typedef enum { BASH, TCSH } shell_t;
82 frodo 259
83    
84     /* Some global variables that tells us how to parse. */
85 frodo 321 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 frodo 259
90 frodo 322 /* Allow changing which getopt is in use with function pointer */
91 frodo 319 int (*getopt_long_fp) (int argc, char *const *argv, const char *optstr,
92 frodo 320 const struct option * longopts, int *longindex);
93 frodo 319
94 frodo 259 /* Function prototypes */
95 frodo 321 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 frodo 259
104     /*
105 frodo 317 * 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 frodo 259 * Bash only needs special treatment for single quotes; tcsh also recognizes
110 frodo 317 * exclamation marks within single quotes, and nukes whitespace. This
111     * function returns a pointer to a buffer that is overwritten by each call.
112 frodo 259 */
113 frodo 321 static const char *normalize(const char *arg)
114 frodo 259 {
115 frodo 320 static char *BUFFER = NULL;
116     const char *argptr = arg;
117 frodo 259 char *bufptr;
118    
119 frodo 322 free(BUFFER);
120 frodo 259
121 frodo 320 if (!quote) {
122 frodo 317 /* Just copy arg */
123 frodo 322 BUFFER = xmalloc(strlen(arg) + 1);
124 frodo 320 strcpy(BUFFER, arg);
125 frodo 259 return BUFFER;
126     }
127    
128 frodo 317 /*
129 frodo 364 * Each character in arg may take up to four characters in the
130 frodo 317 * 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 frodo 322 BUFFER = xmalloc(strlen(arg) * 4 + 3);
135 frodo 259
136 frodo 320 bufptr = BUFFER;
137     *bufptr++ = '\'';
138 frodo 259
139     while (*argptr) {
140     if (*argptr == '\'') {
141     /* Quote: replace it with: '\'' */
142 frodo 320 *bufptr++ = '\'';
143     *bufptr++ = '\\';
144     *bufptr++ = '\'';
145     *bufptr++ = '\'';
146     } else if (shell == TCSH && *argptr == '!') {
147 frodo 259 /* Exclamation mark: replace it with: \! */
148 frodo 320 *bufptr++ = '\'';
149     *bufptr++ = '\\';
150     *bufptr++ = '!';
151     *bufptr++ = '\'';
152     } else if (shell == TCSH && *argptr == '\n') {
153 frodo 259 /* Newline: replace it with: \n */
154 frodo 320 *bufptr++ = '\\';
155     *bufptr++ = 'n';
156     } else if (shell == TCSH && isspace(*argptr)) {
157 frodo 259 /* Non-newline whitespace: replace it with \<ws> */
158 frodo 320 *bufptr++ = '\'';
159     *bufptr++ = '\\';
160     *bufptr++ = *argptr;
161     *bufptr++ = '\'';
162 frodo 259 } else
163     /* Just copy */
164 frodo 320 *bufptr++ = *argptr;
165 frodo 259 argptr++;
166     }
167 frodo 320 *bufptr++ = '\'';
168     *bufptr++ = '\0';
169 frodo 259 return BUFFER;
170     }
171    
172 frodo 364 /*
173 frodo 259 * 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 frodo 321 static int generate_output(char *argv[], int argc, const char *optstr,
180     const struct option *longopts)
181 frodo 259 {
182 frodo 318 int exit_code = EXIT_SUCCESS; /* Assume everything will be OK */
183 frodo 259 int opt;
184     int longindex;
185     const char *charptr;
186    
187 frodo 320 if (quiet_errors)
188 frodo 317 /* No error reporting from getopt(3) */
189 frodo 320 opterr = 0;
190 frodo 317 /* Reset getopt(3) */
191 frodo 320 optind = 0;
192 frodo 259
193 frodo 320 while ((opt =
194 frodo 319 (getopt_long_fp(argc, argv, optstr, longopts, &longindex)))
195 frodo 320 != EOF)
196     if (opt == '?' || opt == ':')
197 frodo 318 exit_code = GETOPT_EXIT_CODE;
198 frodo 320 else if (!quiet_output) {
199 frodo 259 if (opt == LONG_OPT) {
200 frodo 320 printf(" --%s", longopts[longindex].name);
201     if (longopts[longindex].has_arg)
202     printf(" %s", normalize(optarg ? optarg : ""));
203     } else if (opt == NON_OPT)
204 frodo 359 printf(" %s", normalize(optarg ? optarg : ""));
205 frodo 259 else {
206 frodo 320 printf(" -%c", opt);
207     charptr = strchr(optstr, opt);
208 frodo 259 if (charptr != NULL && *++charptr == ':')
209 frodo 320 printf(" %s", normalize(optarg ? optarg : ""));
210 frodo 259 }
211     }
212 frodo 320
213     if (!quiet_output) {
214 frodo 259 printf(" --");
215 frodo 320 while (optind < argc)
216     printf(" %s", normalize(argv[optind++]));
217 frodo 259 printf("\n");
218     }
219     return exit_code;
220     }
221    
222     /*
223 frodo 317 * 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 frodo 259 */
226 frodo 321 static void __attribute__ ((__noreturn__)) parse_error(const char *message)
227 frodo 259 {
228     if (message)
229 frodo 364 warnx("%s", message);
230 frodo 323 fprintf(stderr, _("Try `%s --help' for more information.\n"),
231     program_invocation_short_name);
232 frodo 318 exit(PARAMETER_EXIT_CODE);
233 frodo 259 }
234    
235 frodo 320 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 frodo 259 #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 frodo 321 static void add_longopt(const char *name, int has_arg)
243 frodo 259 {
244     char *tmp;
245 frodo 370 static int flag;
246    
247 frodo 320 if (!name) {
248 frodo 317 /* init */
249 frodo 259 free(long_options);
250 frodo 320 long_options = NULL;
251     long_options_length = 0;
252     long_options_nr = 0;
253 frodo 259 }
254    
255     if (long_options_nr == long_options_length) {
256     long_options_length += LONG_OPTIONS_INCR;
257 frodo 322 long_options = xrealloc(long_options,
258     sizeof(struct option) *
259     long_options_length);
260 frodo 259 }
261    
262 frodo 320 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 frodo 259
267 frodo 359 if (long_options_nr && name) {
268 frodo 317 /* Not for init! */
269 frodo 320 long_options[long_options_nr - 1].has_arg = has_arg;
270 frodo 370 long_options[long_options_nr - 1].flag = &flag;
271     long_options[long_options_nr - 1].val = long_options_nr;
272 frodo 322 tmp = xmalloc(strlen(name) + 1);
273 frodo 320 strcpy(tmp, name);
274     long_options[long_options_nr - 1].name = tmp;
275 frodo 259 }
276     long_options_nr++;
277     }
278    
279 frodo 320
280 frodo 364 /*
281 frodo 317 * Register several long options. options is a string of long options,
282     * separated by commas or whitespace. This nukes options!
283 frodo 259 */
284 frodo 321 static void add_long_options(char *options)
285 frodo 259 {
286     int arg_opt;
287 frodo 320 char *tokptr = strtok(options, ", \t\n");
288 frodo 259 while (tokptr) {
289 frodo 320 arg_opt = no_argument;
290 frodo 259 if (strlen(tokptr) > 0) {
291 frodo 320 if (tokptr[strlen(tokptr) - 1] == ':') {
292     if (tokptr[strlen(tokptr) - 2] == ':') {
293     tokptr[strlen(tokptr) - 2] = '\0';
294     arg_opt = optional_argument;
295 frodo 259 } else {
296 frodo 320 tokptr[strlen(tokptr) - 1] = '\0';
297     arg_opt = required_argument;
298 frodo 259 }
299     if (strlen(tokptr) == 0)
300 frodo 320 parse_error(_
301     ("empty long option after "
302     "-l or --long argument"));
303 frodo 259 }
304 frodo 320 add_longopt(tokptr, arg_opt);
305 frodo 259 }
306 frodo 320 tokptr = strtok(NULL, ", \t\n");
307 frodo 259 }
308     }
309    
310 frodo 321 static void set_shell(const char *new_shell)
311 frodo 259 {
312 frodo 320 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 frodo 259 else
321 frodo 320 parse_error(_
322     ("unknown shell after -s or --shell argument"));
323 frodo 259 }
324    
325 frodo 321 static void __attribute__ ((__noreturn__)) print_help(void)
326 frodo 259 {
327 frodo 363 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 frodo 320 fputs(_(" -a, --alternative Allow long options starting with single -\n"), stderr);
336 frodo 323 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 frodo 320 fputs(_(" -q, --quiet Disable error reporting by getopt(3)\n"), stderr);
340     fputs(_(" -Q, --quiet-output No normal output\n"), stderr);
341 frodo 323 fputs(_(" -s, --shell <shell> Set shell quoting conventions\n"), stderr);
342 frodo 320 fputs(_(" -T, --test Test for getopt(1) version\n"), stderr);
343 frodo 362 fputs(_(" -u, --unquoted Do not quote the output\n"), stderr);
344 frodo 363 fputs(USAGE_SEPARATOR, stderr);
345     fputs(USAGE_HELP, stderr);
346     fputs(USAGE_VERSION, stderr);
347     fprintf(stderr, USAGE_MAN_TAIL("getopt(1)"));
348 frodo 318 exit(PARAMETER_EXIT_CODE);
349 frodo 259 }
350    
351 frodo 321 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 frodo 320 {"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 frodo 364
375 frodo 320 setlocale(LC_ALL, "");
376 frodo 259 bindtextdomain(PACKAGE, LOCALEDIR);
377     textdomain(PACKAGE);
378    
379     init_longopt();
380 frodo 319 getopt_long_fp = getopt_long;
381 frodo 259
382 frodo 320 if (getenv("GETOPT_COMPATIBLE"))
383     compatible = 1;
384 frodo 259
385 frodo 320 if (argc == 1) {
386 frodo 259 if (compatible) {
387 frodo 320 /*
388     * For some reason, the original getopt gave no
389     * error when there were no arguments.
390 frodo 317 */
391 frodo 259 printf(" --\n");
392 frodo 318 return EXIT_SUCCESS;
393 frodo 320 } else
394 frodo 259 parse_error(_("missing optstring argument"));
395 frodo 319 }
396 frodo 320
397 frodo 259 if (argv[1][0] != '-' || compatible) {
398 frodo 320 quote = 0;
399 frodo 322 optstr = xmalloc(strlen(argv[1]) + 1);
400 frodo 320 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 frodo 259 }
405 frodo 320
406     while ((opt =
407     getopt_long(argc, argv, shortopts, longopts, NULL)) != EOF)
408 frodo 259 switch (opt) {
409     case 'a':
410 frodo 319 getopt_long_fp = getopt_long_only;
411 frodo 259 break;
412     case 'h':
413     print_help();
414     case 'o':
415 frodo 322 free(optstr);
416     optstr = xmalloc(strlen(optarg) + 1);
417 frodo 320 strcpy(optstr, optarg);
418 frodo 259 break;
419     case 'l':
420     add_long_options(optarg);
421     break;
422     case 'n':
423 frodo 322 free(name);
424     name = xmalloc(strlen(optarg) + 1);
425 frodo 320 strcpy(name, optarg);
426 frodo 259 break;
427     case 'q':
428 frodo 320 quiet_errors = 1;
429 frodo 259 break;
430     case 'Q':
431 frodo 320 quiet_output = 1;
432 frodo 259 break;
433     case 's':
434     set_shell(optarg);
435     break;
436     case 'T':
437 frodo 318 return TEST_EXIT_CODE;
438 frodo 259 case 'u':
439 frodo 320 quote = 0;
440 frodo 259 break;
441     case 'V':
442 frodo 363 printf(UTIL_LINUX_VERSION);
443 frodo 318 return EXIT_SUCCESS;
444 frodo 259 case '?':
445     case ':':
446     parse_error(NULL);
447     default:
448     parse_error(_("internal error, contact the author."));
449     }
450 frodo 364
451 frodo 320 if (!optstr) {
452 frodo 259 if (optind >= argc)
453     parse_error(_("missing optstring argument"));
454     else {
455 frodo 322 optstr = xmalloc(strlen(argv[optind]) + 1);
456 frodo 320 strcpy(optstr, argv[optind]);
457 frodo 259 optind++;
458     }
459     }
460     if (name)
461 frodo 320 argv[optind - 1] = name;
462 frodo 259 else
463 frodo 320 argv[optind - 1] = argv[0];
464 frodo 364
465 frodo 320 return generate_output(argv + optind - 1, argc-optind + 1,
466     optstr, long_options);
467 frodo 259 }

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