2 * getopt.c - Enhanced implementation of BSD getopt(1)
3 * Copyright (c) 1997-2014 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Ć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 * Version 1.1.5: Sun Aug 12 2012
41 * Sync with util-linux-2.21, fixed build problems, many new translations
42 * Version 1.1.6: Mon Nov 24 2014
43 * Sync with util-linux git 20141120, detect ambiguous long options, fix
44 * backslash problem in tcsh
48 * 0) No errors, successful operation.
49 * 1) getopt(3) returned an error.
50 * 2) A problem with parameter parsing for getopt(1).
51 * 3) Internal error, out of memory
54 #define GETOPT_EXIT_CODE 1
55 #define PARAMETER_EXIT_CODE 2
56 #define XALLOC_EXIT_CODE 3
57 #define TEST_EXIT_CODE 4
66 #include "closestream.h"
70 /* NON_OPT is the code that is returned getopt(3) when a non-option is
71 * found in 'char optstring[]="-abc...";', e.g., it begins by '-' */
73 /* LONG_OPT is the code that is returned when a long option is found. */
76 /* The shells recognized. */
77 typedef enum { BASH
, TCSH
} shell_t
;
79 struct getopt_control
{
80 shell_t shell
; /* the shell we generate output for */
81 char *optstr
; /* getopt(3) optstring */
82 struct option
*long_options
; /* long options */
83 int long_options_length
; /* length of options array */
84 int long_options_nr
; /* number of used elements in array */
86 compatible
:1, /* compatibility mode for 'difficult' programs */
87 quiet_errors
:1, /* print errors */
88 quiet_output
:1, /* print output */
89 quote
:1; /* quote output */
92 enum { REALLOC_INCREMENT
= 8 };
94 /* Allow changing which getopt is in use with function pointer */
95 int (*getopt_long_fp
) (int argc
, char *const *argv
, const char *optstr
,
96 const struct option
* longopts
, int *longindex
);
99 * This function 'normalizes' a single argument: it puts single quotes
100 * around it and escapes other special characters. If quote is false, it
101 * just returns its argument.
103 * Bash only needs special treatment for single quotes; tcsh also recognizes
104 * exclamation marks within single quotes, and nukes whitespace. This
105 * function returns a pointer to a buffer that is overwritten by each call.
107 static void normalize(const struct getopt_control
*ctl
, const char *arg
)
110 const char *argptr
= arg
;
119 * Each character in arg may take up to four characters in the
120 * result: For a quote we need a closing quote, a backslash, a quote
121 * and an opening quote! We need also the global opening and closing
122 * quote, and one extra character for '\0'.
124 buf
= xmalloc(strlen(arg
) * 4 + 3);
130 if (*argptr
== '\'') {
131 /* Quote: replace it with: '\'' */
136 } else if (ctl
->shell
== TCSH
&& *argptr
== '\\') {
137 /* Backslash: replace it with: '\\' */
140 } else if (ctl
->shell
== TCSH
&& *argptr
== '!') {
141 /* Exclamation mark: replace it with: \! */
146 } else if (ctl
->shell
== TCSH
&& *argptr
== '\n') {
147 /* Newline: replace it with: \n */
150 } else if (ctl
->shell
== TCSH
&& isspace(*argptr
)) {
151 /* Non-newline whitespace: replace it with \<ws> */
168 * Generate the output. argv[0] is the program name (used for reporting errors).
169 * argv[1..] contains the options to be parsed. argc must be the number of
170 * elements in argv (ie. 1 if there are no options, only the program name),
171 * optstr must contain the short options, and longopts the long options.
172 * Other settings are found in global variables.
174 static int generate_output(const struct getopt_control
*ctl
, char *argv
[], int argc
)
176 int exit_code
= EXIT_SUCCESS
; /* Assume everything will be OK */
181 if (ctl
->quiet_errors
)
182 /* No error reporting from getopt(3) */
184 /* Reset getopt(3) */
188 (getopt_long_fp(argc
, argv
, ctl
->optstr
, ctl
->long_options
, &longindex
)))
190 if (opt
== '?' || opt
== ':')
191 exit_code
= GETOPT_EXIT_CODE
;
192 else if (!ctl
->quiet_output
) {
193 if (opt
== LONG_OPT
) {
194 printf(" --%s", ctl
->long_options
[longindex
].name
);
195 if (ctl
->long_options
[longindex
].has_arg
)
196 normalize(ctl
, optarg
? optarg
: "");
197 } else if (opt
== NON_OPT
)
198 normalize(ctl
, optarg
? optarg
: "");
201 charptr
= strchr(ctl
->optstr
, opt
);
202 if (charptr
!= NULL
&& *++charptr
== ':')
203 normalize(ctl
, optarg
? optarg
: "");
207 if (!ctl
->quiet_output
) {
209 while (optind
< argc
)
210 normalize(ctl
, argv
[optind
++]);
217 * Report an error when parsing getopt's own arguments. If message is NULL,
218 * we already sent a message, we just exit with a helpful hint.
220 static void __attribute__ ((__noreturn__
)) parse_error(const char *message
)
223 warnx("%s", message
);
224 fprintf(stderr
, _("Try `%s --help' for more information.\n"),
225 program_invocation_short_name
);
226 exit(PARAMETER_EXIT_CODE
);
230 /* Register a long option. The contents of name is copied. */
231 static void add_longopt(struct getopt_control
*ctl
, const char *name
, int has_arg
)
237 free(ctl
->long_options
);
238 ctl
->long_options
= NULL
;
239 ctl
->long_options_length
= 0;
240 ctl
->long_options_nr
= 0;
243 if (ctl
->long_options_nr
== ctl
->long_options_length
) {
244 ctl
->long_options_length
+= REALLOC_INCREMENT
;
245 ctl
->long_options
= xrealloc(ctl
->long_options
,
246 sizeof(struct option
) *
247 ctl
->long_options_length
);
250 ctl
->long_options
[ctl
->long_options_nr
].name
= NULL
;
251 ctl
->long_options
[ctl
->long_options_nr
].has_arg
= 0;
252 ctl
->long_options
[ctl
->long_options_nr
].flag
= NULL
;
253 ctl
->long_options
[ctl
->long_options_nr
].val
= 0;
255 if (ctl
->long_options_nr
&& name
) {
257 ctl
->long_options
[ctl
->long_options_nr
- 1].has_arg
= has_arg
;
258 ctl
->long_options
[ctl
->long_options_nr
- 1].flag
= &flag
;
259 ctl
->long_options
[ctl
->long_options_nr
- 1].val
= ctl
->long_options_nr
;
260 ctl
->long_options
[ctl
->long_options_nr
- 1].name
= xstrdup(name
);
262 ctl
->long_options_nr
++;
267 * Register several long options. options is a string of long options,
268 * separated by commas or whitespace. This nukes options!
270 static void add_long_options(struct getopt_control
*ctl
, char *options
)
273 char *tokptr
= strtok(options
, ", \t\n");
275 arg_opt
= no_argument
;
276 if (strlen(tokptr
) > 0) {
277 if (tokptr
[strlen(tokptr
) - 1] == ':') {
278 if (tokptr
[strlen(tokptr
) - 2] == ':') {
279 tokptr
[strlen(tokptr
) - 2] = '\0';
280 arg_opt
= optional_argument
;
282 tokptr
[strlen(tokptr
) - 1] = '\0';
283 arg_opt
= required_argument
;
285 if (strlen(tokptr
) == 0)
287 ("empty long option after "
288 "-l or --long argument"));
290 add_longopt(ctl
, tokptr
, arg_opt
);
292 tokptr
= strtok(NULL
, ", \t\n");
296 static void set_shell(struct getopt_control
*ctl
, const char *new_shell
)
298 if (!strcmp(new_shell
, "bash"))
300 else if (!strcmp(new_shell
, "tcsh"))
302 else if (!strcmp(new_shell
, "sh"))
304 else if (!strcmp(new_shell
, "csh"))
308 ("unknown shell after -s or --shell argument"));
311 static void __attribute__ ((__noreturn__
)) print_help(void)
313 fputs(USAGE_HEADER
, stderr
);
315 " %1$s optstring parameters\n"
316 " %1$s [options] [--] optstring parameters\n"
317 " %1$s [options] -o|--options optstring [options] [--] parameters\n"),
318 program_invocation_short_name
);
320 fputs(USAGE_OPTIONS
, stderr
);
321 fputs(_(" -a, --alternative Allow long options starting with single -\n"), stderr
);
322 fputs(_(" -l, --longoptions <longopts> Long options to be recognized\n"), stderr
);
323 fputs(_(" -n, --name <progname> The name under which errors are reported\n"), stderr
);
324 fputs(_(" -o, --options <optstring> Short options to be recognized\n"), stderr
);
325 fputs(_(" -q, --quiet Disable error reporting by getopt(3)\n"), stderr
);
326 fputs(_(" -Q, --quiet-output No normal output\n"), stderr
);
327 fputs(_(" -s, --shell <shell> Set shell quoting conventions\n"), stderr
);
328 fputs(_(" -T, --test Test for getopt(1) version\n"), stderr
);
329 fputs(_(" -u, --unquoted Do not quote the output\n"), stderr
);
330 fputs(USAGE_SEPARATOR
, stderr
);
331 fputs(USAGE_HELP
, stderr
);
332 fputs(USAGE_VERSION
, stderr
);
333 fprintf(stderr
, USAGE_MAN_TAIL("getopt(1)"));
334 exit(PARAMETER_EXIT_CODE
);
337 int main(int argc
, char *argv
[])
339 struct getopt_control ctl
= {
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
);
368 add_longopt(&ctl
, NULL
, 0); /* init */
369 getopt_long_fp
= getopt_long
;
371 if (getenv("GETOPT_COMPATIBLE"))
375 if (ctl
.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] != '-' || ctl
.compatible
) {
388 ctl
.optstr
= xmalloc(strlen(argv
[1]) + 1);
389 strcpy(ctl
.optstr
, argv
[1] + strspn(argv
[1], "-+"));
391 return generate_output(&ctl
, argv
+ 1, argc
- 1);
395 getopt_long(argc
, argv
, shortopts
, longopts
, NULL
)) != EOF
)
398 getopt_long_fp
= getopt_long_only
;
404 ctl
.optstr
= xstrdup(optarg
);
407 add_long_options(&ctl
, optarg
);
411 name
= xstrdup(optarg
);
414 ctl
.quiet_errors
= 1;
417 ctl
.quiet_output
= 1;
420 set_shell(&ctl
, optarg
);
423 return TEST_EXIT_CODE
;
428 printf(UTIL_LINUX_VERSION
);
434 parse_error(_("internal error, contact the author."));
439 parse_error(_("missing optstring argument"));
441 ctl
.optstr
= xstrdup(argv
[optind
]);
446 argv
[optind
- 1] = name
;
448 argv
[optind
- 1] = argv
[0];
450 return generate_output(&ctl
, argv
+ optind
- 1, argc
- optind
+ 1);