2 * getopt.c - Enhanced implementation of BSD getopt(1)
3 * Copyright (c) 1997-2005 Frodo Looijaard <frodo@frodo.looijaard.name>
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.
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.
15 * 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.
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
43 * 0) No errors, successful 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
49 #define GETOPT_EXIT_CODE 1
50 #define PARAMETER_EXIT_CODE 2
51 #define XALLOC_EXIT_CODE 3
52 #define TEST_EXIT_CODE 4
61 #include "closestream.h"
65 /* NON_OPT is the code that is returned when a non-option is found in '+'
68 /* LONG_OPT is the code that is returned when a long option is found. */
71 /* The shells recognized. */
72 typedef enum { BASH
, TCSH
} shell_t
;
75 /* Some global variables that tells us how to parse. */
76 static shell_t shell
= BASH
; /* The shell we generate output for. */
77 static int quiet_errors
= 0; /* 0 is not quiet. */
78 static int quiet_output
= 0; /* 0 is not quiet. */
79 static int quote
= 1; /* 1 is do quote. */
81 /* Allow changing which getopt is in use with function pointer */
82 int (*getopt_long_fp
) (int argc
, char *const *argv
, const char *optstr
,
83 const struct option
* longopts
, int *longindex
);
85 /* Function prototypes */
86 static const char *normalize(const char *arg
);
87 static int generate_output(char *argv
[], int argc
, const char *optstr
,
88 const struct option
*longopts
);
89 static void parse_error(const char *message
);
90 static void add_long_options(char *options
);
91 static void add_longopt(const char *name
, int has_arg
);
92 static void print_help(void);
93 static void set_shell(const char *new_shell
);
96 * This function 'normalizes' a single argument: it puts single quotes
97 * around it and escapes other special characters. If quote is false, it
98 * just returns its argument.
100 * Bash only needs special treatment for single quotes; tcsh also recognizes
101 * exclamation marks within single quotes, and nukes whitespace. This
102 * function returns a pointer to a buffer that is overwritten by each call.
104 static const char *normalize(const char *arg
)
106 static char *BUFFER
= NULL
;
107 const char *argptr
= arg
;
112 BUFFER
= xmalloc(strlen(arg
) + 1);
118 * Each character in arg may take up to four characters in the
119 * result: For a quote we need a closing quote, a backslash, a quote
120 * and an opening quote! We need also the global opening and closing
121 * quote, and one extra character for '\0'.
123 BUFFER
= xmalloc(strlen(arg
) * 4 + 3);
129 if (*argptr
== '\'') {
130 /* Quote: replace it with: '\'' */
135 } else if (shell
== TCSH
&& *argptr
== '!') {
136 /* Exclamation mark: replace it with: \! */
141 } else if (shell
== TCSH
&& *argptr
== '\n') {
142 /* Newline: replace it with: \n */
145 } else if (shell
== TCSH
&& isspace(*argptr
)) {
146 /* Non-newline whitespace: replace it with \<ws> */
162 * Generate the output. argv[0] is the program name (used for reporting errors).
163 * argv[1..] contains the options to be parsed. argc must be the number of
164 * elements in argv (ie. 1 if there are no options, only the program name),
165 * optstr must contain the short options, and longopts the long options.
166 * Other settings are found in global variables.
168 static int generate_output(char *argv
[], int argc
, const char *optstr
,
169 const struct option
*longopts
)
171 int exit_code
= EXIT_SUCCESS
; /* Assume everything will be OK */
177 /* No error reporting from getopt(3) */
179 /* Reset getopt(3) */
183 (getopt_long_fp(argc
, argv
, optstr
, longopts
, &longindex
)))
185 if (opt
== '?' || opt
== ':')
186 exit_code
= GETOPT_EXIT_CODE
;
187 else if (!quiet_output
) {
188 if (opt
== LONG_OPT
) {
189 printf(" --%s", longopts
[longindex
].name
);
190 if (longopts
[longindex
].has_arg
)
191 printf(" %s", normalize(optarg
? optarg
: ""));
192 } else if (opt
== NON_OPT
)
193 printf(" %s", normalize(optarg
));
196 charptr
= strchr(optstr
, opt
);
197 if (charptr
!= NULL
&& *++charptr
== ':')
198 printf(" %s", normalize(optarg
? optarg
: ""));
204 while (optind
< argc
)
205 printf(" %s", normalize(argv
[optind
++]));
212 * Report an error when parsing getopt's own arguments. If message is NULL,
213 * we already sent a message, we just exit with a helpful hint.
215 static void __attribute__ ((__noreturn__
)) parse_error(const char *message
)
218 warnx("%s", message
);
219 fprintf(stderr
, _("Try `%s --help' for more information.\n"),
220 program_invocation_short_name
);
221 exit(PARAMETER_EXIT_CODE
);
224 static struct option
*long_options
= NULL
;
225 static int long_options_length
= 0; /* Length of array */
226 static int long_options_nr
= 0; /* Nr of used elements in array */
227 #define LONG_OPTIONS_INCR 10
228 #define init_longopt() add_longopt(NULL,0)
230 /* Register a long option. The contents of name is copied. */
231 static void add_longopt(const char *name
, int has_arg
)
238 long_options_length
= 0;
242 if (long_options_nr
== long_options_length
) {
243 long_options_length
+= LONG_OPTIONS_INCR
;
244 long_options
= xrealloc(long_options
,
245 sizeof(struct option
) *
246 long_options_length
);
249 long_options
[long_options_nr
].name
= NULL
;
250 long_options
[long_options_nr
].has_arg
= 0;
251 long_options
[long_options_nr
].flag
= NULL
;
252 long_options
[long_options_nr
].val
= 0;
254 if (long_options_nr
&& name
) {
256 long_options
[long_options_nr
- 1].has_arg
= has_arg
;
257 long_options
[long_options_nr
- 1].flag
= NULL
;
258 long_options
[long_options_nr
- 1].val
= LONG_OPT
;
259 tmp
= xmalloc(strlen(name
) + 1);
261 long_options
[long_options_nr
- 1].name
= tmp
;
268 * Register several long options. options is a string of long options,
269 * separated by commas or whitespace. This nukes options!
271 static void add_long_options(char *options
)
274 char *tokptr
= strtok(options
, ", \t\n");
276 arg_opt
= no_argument
;
277 if (strlen(tokptr
) > 0) {
278 if (tokptr
[strlen(tokptr
) - 1] == ':') {
279 if (tokptr
[strlen(tokptr
) - 2] == ':') {
280 tokptr
[strlen(tokptr
) - 2] = '\0';
281 arg_opt
= optional_argument
;
283 tokptr
[strlen(tokptr
) - 1] = '\0';
284 arg_opt
= required_argument
;
286 if (strlen(tokptr
) == 0)
288 ("empty long option after "
289 "-l or --long argument"));
291 add_longopt(tokptr
, arg_opt
);
293 tokptr
= strtok(NULL
, ", \t\n");
297 static void set_shell(const char *new_shell
)
299 if (!strcmp(new_shell
, "bash"))
301 else if (!strcmp(new_shell
, "tcsh"))
303 else if (!strcmp(new_shell
, "sh"))
305 else if (!strcmp(new_shell
, "csh"))
309 ("unknown shell after -s or --shell argument"));
312 static void __attribute__ ((__noreturn__
)) print_help(void)
314 fputs(_("\nUsage:\n"), stderr
);
317 " %1$s optstring parameters\n"
318 " %1$s [options] [--] optstring parameters\n"
319 " %1$s [options] -o|--options optstring [options] [--] parameters\n"),
320 program_invocation_short_name
);
322 fputs(_("\nOptions:\n"), stderr
);
323 fputs(_(" -a, --alternative Allow long options starting with single -\n"), stderr
);
324 fputs(_(" -h, --help This small usage guide\n"), stderr
);
325 fputs(_(" -l, --longoptions <longopts> Long options to be recognized\n"), stderr
);
326 fputs(_(" -n, --name <progname> The name under which errors are reported\n"), stderr
);
327 fputs(_(" -o, --options <optstring> Short options to be recognized\n"), stderr
);
328 fputs(_(" -q, --quiet Disable error reporting by getopt(3)\n"), stderr
);
329 fputs(_(" -Q, --quiet-output No normal output\n"), stderr
);
330 fputs(_(" -s, --shell <shell> Set shell quoting conventions\n"), stderr
);
331 fputs(_(" -T, --test Test for getopt(1) version\n"), stderr
);
332 fputs(_(" -u, --unquote Do not quote the output\n"), stderr
);
333 fputs(_(" -V, --version Output version information\n"), stderr
);
336 exit(PARAMETER_EXIT_CODE
);
339 int main(int argc
, char *argv
[])
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 {"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'},
363 setlocale(LC_ALL
, "");
364 bindtextdomain(PACKAGE
, LOCALEDIR
);
366 atexit(close_stdout
);
369 getopt_long_fp
= getopt_long
;
371 if (getenv("GETOPT_COMPATIBLE"))
377 * For some reason, the original getopt gave no
378 * error when there were no arguments.
383 parse_error(_("missing optstring argument"));
386 if (argv
[1][0] != '-' || compatible
) {
388 optstr
= xmalloc(strlen(argv
[1]) + 1);
389 strcpy(optstr
, argv
[1] + strspn(argv
[1], "-+"));
391 return generate_output(argv
+ 1, argc
- 1, optstr
,
396 getopt_long(argc
, argv
, shortopts
, longopts
, NULL
)) != EOF
)
399 getopt_long_fp
= getopt_long_only
;
405 optstr
= xmalloc(strlen(optarg
) + 1);
406 strcpy(optstr
, optarg
);
409 add_long_options(optarg
);
413 name
= xmalloc(strlen(optarg
) + 1);
414 strcpy(name
, optarg
);
426 return TEST_EXIT_CODE
;
431 printf(UTIL_LINUX_VERSION
);
437 parse_error(_("internal error, contact the author."));
442 parse_error(_("missing optstring argument"));
444 optstr
= xmalloc(strlen(argv
[optind
]) + 1);
445 strcpy(optstr
, argv
[optind
]);
450 argv
[optind
- 1] = name
;
452 argv
[optind
- 1] = argv
[0];
454 return generate_output(argv
+ optind
- 1, argc
-optind
+ 1,
455 optstr
, long_options
);