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

Annotation of /getopt/trunk/getopt.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 363 - (hide annotations)
Thu Nov 20 12:05:38 2014 UTC (10 years ago) by frodo
File MIME type: text/plain
File size: 13344 byte(s)
(Frodo) Use util-linux macro's when printing help or version numbers

A new file util-linux-compat.h has been introduced; it more or less contains
what c.h contains in util-linux.

This implements the following util-linux git commits:
  db433bf737a5fd4e1c7cca5e3603934743eebd1c
  a587cc55209c1bed49f6573aa00f652fcd276bbb
  e421313dc253856af67cc267d2b33f856f18b0e3

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