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

Annotation of /getopt/trunk/getopt.c

Parent Directory Parent Directory | Revision Log Revision Log


Revision 322 - (hide annotations)
Tue Jul 17 15:27:08 2012 UTC (11 years, 8 months ago) by frodo
File MIME type: text/plain
File size: 13189 byte(s)
(Frodo) Revamped the memory management to get in line with util-linux-2.26.
Added an xalloc.h with the memory functions.

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
121     strcpy(BUFFER, arg);
122 frodo 259 return BUFFER;
123     }
124    
125 frodo 317 /*
126     * Each character in arg may take upto four characters in the
127     * result: For a quote we need a closing quote, a backslash, a quote
128     * and an opening quote! We need also the global opening and closing
129     * quote, and one extra character for '\0'.
130     */
131 frodo 322 BUFFER = xmalloc(strlen(arg) * 4 + 3);
132 frodo 259
133 frodo 320 bufptr = BUFFER;
134     *bufptr++ = '\'';
135 frodo 259
136     while (*argptr) {
137     if (*argptr == '\'') {
138     /* Quote: replace it with: '\'' */
139 frodo 320 *bufptr++ = '\'';
140     *bufptr++ = '\\';
141     *bufptr++ = '\'';
142     *bufptr++ = '\'';
143     } else if (shell == TCSH && *argptr == '!') {
144 frodo 259 /* Exclamation mark: replace it with: \! */
145 frodo 320 *bufptr++ = '\'';
146     *bufptr++ = '\\';
147     *bufptr++ = '!';
148     *bufptr++ = '\'';
149     } else if (shell == TCSH && *argptr == '\n') {
150 frodo 259 /* Newline: replace it with: \n */
151 frodo 320 *bufptr++ = '\\';
152     *bufptr++ = 'n';
153     } else if (shell == TCSH && isspace(*argptr)) {
154 frodo 259 /* Non-newline whitespace: replace it with \<ws> */
155 frodo 320 *bufptr++ = '\'';
156     *bufptr++ = '\\';
157     *bufptr++ = *argptr;
158     *bufptr++ = '\'';
159 frodo 259 } else
160     /* Just copy */
161 frodo 320 *bufptr++ = *argptr;
162 frodo 259 argptr++;
163     }
164 frodo 320 *bufptr++ = '\'';
165     *bufptr++ = '\0';
166 frodo 259 return BUFFER;
167     }
168    
169     /*
170     * Generate the output. argv[0] is the program name (used for reporting errors).
171     * argv[1..] contains the options to be parsed. argc must be the number of
172     * elements in argv (ie. 1 if there are no options, only the program name),
173     * optstr must contain the short options, and longopts the long options.
174     * Other settings are found in global variables.
175     */
176 frodo 321 static int generate_output(char *argv[], int argc, const char *optstr,
177     const struct option *longopts)
178 frodo 259 {
179 frodo 318 int exit_code = EXIT_SUCCESS; /* Assume everything will be OK */
180 frodo 259 int opt;
181     int longindex;
182     const char *charptr;
183    
184 frodo 320 if (quiet_errors)
185 frodo 317 /* No error reporting from getopt(3) */
186 frodo 320 opterr = 0;
187 frodo 317 /* Reset getopt(3) */
188 frodo 320 optind = 0;
189 frodo 259
190 frodo 320 while ((opt =
191 frodo 319 (getopt_long_fp(argc, argv, optstr, longopts, &longindex)))
192 frodo 320 != EOF)
193     if (opt == '?' || opt == ':')
194 frodo 318 exit_code = GETOPT_EXIT_CODE;
195 frodo 320 else if (!quiet_output) {
196 frodo 259 if (opt == LONG_OPT) {
197 frodo 320 printf(" --%s", longopts[longindex].name);
198     if (longopts[longindex].has_arg)
199     printf(" %s", normalize(optarg ? optarg : ""));
200     } else if (opt == NON_OPT)
201     printf(" %s", normalize(optarg));
202 frodo 259 else {
203 frodo 320 printf(" -%c", opt);
204     charptr = strchr(optstr, opt);
205 frodo 259 if (charptr != NULL && *++charptr == ':')
206 frodo 320 printf(" %s", normalize(optarg ? optarg : ""));
207 frodo 259 }
208     }
209 frodo 320
210     if (!quiet_output) {
211 frodo 259 printf(" --");
212 frodo 320 while (optind < argc)
213     printf(" %s", normalize(argv[optind++]));
214 frodo 259 printf("\n");
215     }
216     return exit_code;
217     }
218    
219     /*
220 frodo 317 * Report an error when parsing getopt's own arguments. If message is NULL,
221     * we already sent a message, we just exit with a helpful hint.
222 frodo 259 */
223 frodo 321 static void __attribute__ ((__noreturn__)) parse_error(const char *message)
224 frodo 259 {
225     if (message)
226 frodo 320 fprintf(stderr, "getopt: %s\n", message);
227     fputs(_("Try `getopt --help' for more information.\n"), stderr);
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     fputs(_(" -a, --alternative Allow long options starting with single -\n"), stderr);
326     fputs(_(" -h, --help This small usage guide\n"), stderr);
327     fputs(_(" -l, --longoptions=longopts Long options to be recognized\n"), stderr);
328     fputs(_(" -n, --name=progname The name under which errors are reported\n"), stderr);
329     fputs(_(" -o, --options=optstring Short options to be recognized\n"), stderr);
330     fputs(_(" -q, --quiet Disable error reporting by getopt(3)\n"), stderr);
331     fputs(_(" -Q, --quiet-output No normal output\n"), stderr);
332     fputs(_(" -s, --shell=shell Set shell quoting conventions\n"), stderr);
333     fputs(_(" -T, --test Test for getopt(1) version\n"), stderr);
334     fputs(_(" -u, --unqote Do not quote the output\n"), stderr);
335     fputs(_(" -V, --version Output version information\n"), stderr);
336 frodo 318 exit(PARAMETER_EXIT_CODE);
337 frodo 259 }
338    
339 frodo 321 int main(int argc, char *argv[])
340     {
341     char *optstr = NULL;
342     char *name = NULL;
343     int opt;
344     int compatible = 0;
345    
346     /* Stop scanning as soon as a non-option argument is found! */
347     static const char *shortopts = "+ao:l:n:qQs:TuhV";
348     static const struct option longopts[] = {
349 frodo 320 {"options", required_argument, NULL, 'o'},
350     {"longoptions", required_argument, NULL, 'l'},
351     {"quiet", no_argument, NULL, 'q'},
352     {"quiet-output", no_argument, NULL, 'Q'},
353     {"shell", required_argument, NULL, 's'},
354     {"test", no_argument, NULL, 'T'},
355     {"unquoted", no_argument, NULL, 'u'},
356     {"help", no_argument, NULL, 'h'},
357     {"alternative", no_argument, NULL, 'a'},
358     {"name", required_argument, NULL, 'n'},
359     {"version", no_argument, NULL, 'V'},
360     {NULL, 0, NULL, 0}
361     };
362 frodo 259 #if WITHOUT_GETTEXT
363     #else
364 frodo 320 setlocale(LC_ALL, "");
365 frodo 259 bindtextdomain(PACKAGE, LOCALEDIR);
366     textdomain(PACKAGE);
367     #endif
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 263 printf(_("getopt (enhanced) 1.1.4\n"));
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