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

Contents of /getopt/trunk/getopt.c

Parent Directory Parent Directory | Revision Log Revision Log


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

1 /*
2 * 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
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 * Version 1.1.4: Mon Nov 7 2005
39 * Fixed a few type's in the manpage
40 */
41
42 /* 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 #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 #include "xalloc.h"
68
69 /* NON_OPT is the code that is returned when a non-option is found in '+'
70 * mode */
71 #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 typedef enum { BASH, TCSH } shell_t;
77
78
79 /* Some global variables that tells us how to parse. */
80 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
85 /* Allow changing which getopt is in use with function pointer */
86 int (*getopt_long_fp) (int argc, char *const *argv, const char *optstr,
87 const struct option * longopts, int *longindex);
88
89 /* Function prototypes */
90 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 int main(int argc, char *argv[]);
94 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
100 /*
101 * 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 * Bash only needs special treatment for single quotes; tcsh also recognizes
106 * exclamation marks within single quotes, and nukes whitespace. This
107 * function returns a pointer to a buffer that is overwritten by each call.
108 */
109 static const char *normalize(const char *arg)
110 {
111 static char *BUFFER = NULL;
112 const char *argptr = arg;
113 char *bufptr;
114
115 free(BUFFER);
116
117 if (!quote) {
118 /* Just copy arg */
119 BUFFER = xmalloc(strlen(arg) + 1);
120 strcpy(BUFFER, arg);
121 return BUFFER;
122 }
123
124 /*
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 BUFFER = xmalloc(strlen(arg) * 4 + 3);
131
132 bufptr = BUFFER;
133 *bufptr++ = '\'';
134
135 while (*argptr) {
136 if (*argptr == '\'') {
137 /* Quote: replace it with: '\'' */
138 *bufptr++ = '\'';
139 *bufptr++ = '\\';
140 *bufptr++ = '\'';
141 *bufptr++ = '\'';
142 } else if (shell == TCSH && *argptr == '!') {
143 /* Exclamation mark: replace it with: \! */
144 *bufptr++ = '\'';
145 *bufptr++ = '\\';
146 *bufptr++ = '!';
147 *bufptr++ = '\'';
148 } else if (shell == TCSH && *argptr == '\n') {
149 /* Newline: replace it with: \n */
150 *bufptr++ = '\\';
151 *bufptr++ = 'n';
152 } else if (shell == TCSH && isspace(*argptr)) {
153 /* Non-newline whitespace: replace it with \<ws> */
154 *bufptr++ = '\'';
155 *bufptr++ = '\\';
156 *bufptr++ = *argptr;
157 *bufptr++ = '\'';
158 } else
159 /* Just copy */
160 *bufptr++ = *argptr;
161 argptr++;
162 }
163 *bufptr++ = '\'';
164 *bufptr++ = '\0';
165 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 static int generate_output(char *argv[], int argc, const char *optstr,
176 const struct option *longopts)
177 {
178 int exit_code = EXIT_SUCCESS; /* Assume everything will be OK */
179 int opt;
180 int longindex;
181 const char *charptr;
182
183 if (quiet_errors)
184 /* No error reporting from getopt(3) */
185 opterr = 0;
186 /* Reset getopt(3) */
187 optind = 0;
188
189 while ((opt =
190 (getopt_long_fp(argc, argv, optstr, longopts, &longindex)))
191 != EOF)
192 if (opt == '?' || opt == ':')
193 exit_code = GETOPT_EXIT_CODE;
194 else if (!quiet_output) {
195 if (opt == LONG_OPT) {
196 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 else {
202 printf(" -%c", opt);
203 charptr = strchr(optstr, opt);
204 if (charptr != NULL && *++charptr == ':')
205 printf(" %s", normalize(optarg ? optarg : ""));
206 }
207 }
208
209 if (!quiet_output) {
210 printf(" --");
211 while (optind < argc)
212 printf(" %s", normalize(argv[optind++]));
213 printf("\n");
214 }
215 return exit_code;
216 }
217
218 /*
219 * 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 */
222 static void __attribute__ ((__noreturn__)) parse_error(const char *message)
223 {
224 if (message)
225 fprintf(stderr, "%s: %s\n", program_invocation_short_name, message);
226 fprintf(stderr, _("Try `%s --help' for more information.\n"),
227 program_invocation_short_name);
228 exit(PARAMETER_EXIT_CODE);
229 }
230
231 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 #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 static void add_longopt(const char *name, int has_arg)
239 {
240 char *tmp;
241 if (!name) {
242 /* init */
243 free(long_options);
244 long_options = NULL;
245 long_options_length = 0;
246 long_options_nr = 0;
247 }
248
249 if (long_options_nr == long_options_length) {
250 long_options_length += LONG_OPTIONS_INCR;
251 long_options = xrealloc(long_options,
252 sizeof(struct option) *
253 long_options_length);
254 }
255
256 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
261 if (long_options_nr) {
262 /* Not for init! */
263 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 tmp = xmalloc(strlen(name) + 1);
267 strcpy(tmp, name);
268 long_options[long_options_nr - 1].name = tmp;
269 }
270 long_options_nr++;
271 }
272
273
274 /*
275 * Register several long options. options is a string of long options,
276 * separated by commas or whitespace. This nukes options!
277 */
278 static void add_long_options(char *options)
279 {
280 int arg_opt;
281 char *tokptr = strtok(options, ", \t\n");
282 while (tokptr) {
283 arg_opt = no_argument;
284 if (strlen(tokptr) > 0) {
285 if (tokptr[strlen(tokptr) - 1] == ':') {
286 if (tokptr[strlen(tokptr) - 2] == ':') {
287 tokptr[strlen(tokptr) - 2] = '\0';
288 arg_opt = optional_argument;
289 } else {
290 tokptr[strlen(tokptr) - 1] = '\0';
291 arg_opt = required_argument;
292 }
293 if (strlen(tokptr) == 0)
294 parse_error(_
295 ("empty long option after "
296 "-l or --long argument"));
297 }
298 add_longopt(tokptr, arg_opt);
299 }
300 tokptr = strtok(NULL, ", \t\n");
301 }
302 }
303
304 static void set_shell(const char *new_shell)
305 {
306 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 else
315 parse_error(_
316 ("unknown shell after -s or --shell argument"));
317 }
318
319 static void __attribute__ ((__noreturn__)) print_help(void)
320 {
321 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 fputs(_("\nOptions:\n"), stderr);
326 fputs(_(" -a, --alternative Allow long options starting with single -\n"), stderr);
327 fputs(_(" -h, --help This small usage guide\n"), stderr);
328 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 fputs(_(" -q, --quiet Disable error reporting by getopt(3)\n"), stderr);
332 fputs(_(" -Q, --quiet-output No normal output\n"), stderr);
333 fputs(_(" -s, --shell <shell> Set shell quoting conventions\n"), stderr);
334 fputs(_(" -T, --test Test for getopt(1) version\n"), stderr);
335 fputs(_(" -u, --unquote Do not quote the output\n"), stderr);
336 fputs(_(" -V, --version Output version information\n"), stderr);
337 fputc('\n', stderr);
338
339 exit(PARAMETER_EXIT_CODE);
340 }
341
342 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 {"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 bindtextdomain(PACKAGE, LOCALEDIR);
367 textdomain(PACKAGE);
368
369 init_longopt();
370 getopt_long_fp = getopt_long;
371
372 if (getenv("GETOPT_COMPATIBLE"))
373 compatible = 1;
374
375 if (argc == 1) {
376 if (compatible) {
377 /*
378 * For some reason, the original getopt gave no
379 * error when there were no arguments.
380 */
381 printf(" --\n");
382 return EXIT_SUCCESS;
383 } else
384 parse_error(_("missing optstring argument"));
385 }
386
387
388 if (argv[1][0] != '-' || compatible) {
389 quote = 0;
390 optstr = xmalloc(strlen(argv[1]) + 1);
391 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 }
396
397 while ((opt =
398 getopt_long(argc, argv, shortopts, longopts, NULL)) != EOF)
399 switch (opt) {
400 case 'a':
401 getopt_long_fp = getopt_long_only;
402 break;
403 case 'h':
404 print_help();
405 case 'o':
406 free(optstr);
407 optstr = xmalloc(strlen(optarg) + 1);
408 strcpy(optstr, optarg);
409 break;
410 case 'l':
411 add_long_options(optarg);
412 break;
413 case 'n':
414 free(name);
415 name = xmalloc(strlen(optarg) + 1);
416 strcpy(name, optarg);
417 break;
418 case 'q':
419 quiet_errors = 1;
420 break;
421 case 'Q':
422 quiet_output = 1;
423 break;
424 case 's':
425 set_shell(optarg);
426 break;
427 case 'T':
428 return TEST_EXIT_CODE;
429 case 'u':
430 quote = 0;
431 break;
432 case 'V':
433 printf(_("%s (enhanced) %s\n"), program_invocation_short_name, program_version);
434 return EXIT_SUCCESS;
435 case '?':
436 case ':':
437 parse_error(NULL);
438 default:
439 parse_error(_("internal error, contact the author."));
440 }
441
442 if (!optstr) {
443 if (optind >= argc)
444 parse_error(_("missing optstring argument"));
445 else {
446 optstr = xmalloc(strlen(argv[optind]) + 1);
447 strcpy(optstr, argv[optind]);
448 optind++;
449 }
450 }
451 if (name)
452 argv[optind - 1] = name;
453 else
454 argv[optind - 1] = argv[0];
455 return generate_output(argv + optind - 1, argc-optind + 1,
456 optstr, long_options);
457 }

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