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

Annotation of /getopt/trunk/getopt.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 367 - (hide annotations)
Sun Nov 23 10:49:55 2014 UTC (5 years ago) by frodo
File MIME type: text/plain
File size: 13279 byte(s)
(Frodo) Bump copyright year

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

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