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

Annotation of /getopt/trunk/getopt.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 325 - (hide annotations)
Tue Jul 31 19:53:07 2012 UTC (7 years, 4 months ago) by frodo
File MIME type: text/plain
File size: 13312 byte(s)
(Frodo) Fix several issues when compiling without gettext support

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

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