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 CLOSE_EXIT_CODE XALLOC_EXIT_CODE
58 #define TEST_EXIT_CODE 4
66 #ifdef HAVE_SYS_PARAM_H
67 # include <sys/param.h> /* BSD */
70 #include "closestream.h"
75 /* NON_OPT is the code that is returned getopt(3) when a non-option is
76 * found in 'char optstring[]="-abc...";', e.g., it begins by '-' */
78 /* LONG_OPT is the code that is returned when a long option is found. */
81 /* The shells recognized. */
82 typedef enum { BASH
, TCSH
} shell_t
;
84 struct getopt_control
{
85 shell_t shell
; /* the shell we generate output for */
86 char *optstr
; /* getopt(3) optstring */
88 struct option
*long_options
; /* long options */
89 int long_options_length
; /* length of options array */
90 int long_options_nr
; /* number of used elements in array */
92 compatible
:1, /* compatibility mode for 'difficult' programs */
93 quiet_errors
:1, /* print errors */
94 quiet_output
:1, /* print output */
95 quote
:1; /* quote output */
98 enum { REALLOC_INCREMENT
= 8 };
100 /* Allow changing which getopt is in use with function pointer. */
101 static int (*getopt_long_fp
) (int argc
, char *const *argv
, const char *optstr
,
102 const struct option
* longopts
, int *longindex
);
105 * This function 'normalizes' a single argument: it puts single quotes
106 * around it and escapes other special characters. If quote is false, it
107 * just returns its argument.
109 * Bash only needs special treatment for single quotes; tcsh also recognizes
110 * exclamation marks within single quotes, and nukes whitespace. This
111 * function returns a pointer to a buffer that is overwritten by each call.
113 static void print_normalized(const struct getopt_control
*ctl
, const char *arg
)
116 const char *argptr
= arg
;
125 * Each character in arg may take up to 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'.
130 buf
= xmalloc(strlen(arg
) * 4 + 3);
133 for (*bufptr
++ = '\''; *argptr
; argptr
++) {
134 if (ctl
->shell
== TCSH
) {
137 /* Backslash: replace it with: '\\' */
142 /* Exclamation mark: replace it with: \! */
149 /* Newline: replace it with: \n */
154 if (isspace(*argptr
)) {
155 /* Non-newline whitespace: replace it with \<ws> */
163 if (*argptr
== '\'') {
164 /* Quote: replace it with: '\'' */
181 * Generate the output. argv[0] is the program name (used for reporting errors).
182 * argv[1..] contains the options to be parsed. argc must be the number of
183 * elements in argv (ie. 1 if there are no options, only the program name),
184 * optstr must contain the short options, and longopts the long options.
185 * Other settings are found in global variables.
187 static int generate_output(struct getopt_control
*ctl
, char *argv
[], int argc
)
189 int exit_code
= EXIT_SUCCESS
; /* Assume everything will be OK */
194 if (ctl
->quiet_errors
)
195 /* No error reporting from getopt(3) */
197 /* Reset getopt(3) */
202 (argc
, argv
, ctl
->optstr
,
203 (const struct option
*)ctl
->long_options
, &longindex
)))
205 if (opt
== '?' || opt
== ':')
206 exit_code
= GETOPT_EXIT_CODE
;
207 else if (!ctl
->quiet_output
) {
210 printf(" --%s", ctl
->long_options
[longindex
].name
);
211 if (ctl
->long_options
[longindex
].has_arg
)
212 print_normalized(ctl
, optarg
? optarg
: "");
215 print_normalized(ctl
, optarg
? optarg
: "");
219 charptr
= strchr(ctl
->optstr
, opt
);
220 if (charptr
!= NULL
&& *++charptr
== ':')
221 print_normalized(ctl
, optarg
? optarg
: "");
225 if (!ctl
->quiet_output
) {
227 while (optind
< argc
)
228 print_normalized(ctl
, argv
[optind
++]);
231 for (longindex
= 0; longindex
< ctl
->long_options_nr
; longindex
++)
232 free((char *)ctl
->long_options
[longindex
].name
);
233 free(ctl
->long_options
);
240 * Report an error when parsing getopt's own arguments. If message is NULL,
241 * we already sent a message, we just exit with a helpful hint.
243 static void __attribute__ ((__noreturn__
)) parse_error(const char *message
)
246 warnx("%s", message
);
247 errtryhelp(PARAMETER_EXIT_CODE
);
251 /* Register a long option. The contents of name is copied. */
252 static void add_longopt(struct getopt_control
*ctl
, const char *name
, int has_arg
)
255 int nr
= ctl
->long_options_nr
;
257 if (ctl
->long_options_nr
== ctl
->long_options_length
) {
258 ctl
->long_options_length
+= REALLOC_INCREMENT
;
259 ctl
->long_options
= xreallocarray(ctl
->long_options
,
260 ctl
->long_options_length
,
261 sizeof(struct option
));
265 ctl
->long_options
[nr
].has_arg
= has_arg
;
266 ctl
->long_options
[nr
].flag
= &flag
;
267 ctl
->long_options
[nr
].val
= ctl
->long_options_nr
;
268 ctl
->long_options
[nr
].name
= xstrdup(name
);
270 /* lets use add_longopt(ct, NULL, 0) to terminate the array */
271 ctl
->long_options
[nr
].name
= NULL
;
272 ctl
->long_options
[nr
].has_arg
= 0;
273 ctl
->long_options
[nr
].flag
= NULL
;
274 ctl
->long_options
[nr
].val
= 0;
279 static void add_short_options(struct getopt_control
*ctl
, char *options
)
282 if (*options
!= '+' && getenv("POSIXLY_CORRECT"))
283 ctl
->optstr
= strconcat("+", options
);
285 ctl
->optstr
= xstrdup(options
);
292 * Register several long options. options is a string of long options,
293 * separated by commas or whitespace. This nukes options!
295 static void add_long_options(struct getopt_control
*ctl
, char *options
)
298 char *tokptr
= strtok(options
, ", \t\n");
301 size_t len
= strlen(tokptr
);
303 arg_opt
= no_argument
;
305 if (tokptr
[len
- 1] == ':') {
306 if (tokptr
[len
- 2] == ':') {
307 tokptr
[len
- 2] = '\0';
308 arg_opt
= optional_argument
;
310 tokptr
[len
- 1] = '\0';
311 arg_opt
= required_argument
;
315 ("empty long option after "
316 "-l or --long argument"));
318 add_longopt(ctl
, tokptr
, arg_opt
);
319 ctl
->long_options_nr
++;
321 tokptr
= strtok(NULL
, ", \t\n");
323 add_longopt(ctl
, NULL
, 0); /* ensure long_options[] is not full */
326 static shell_t
shell_type(const char *new_shell
)
328 if (!strcmp(new_shell
, "bash"))
330 if (!strcmp(new_shell
, "sh"))
332 if (!strcmp(new_shell
, "tcsh"))
334 if (!strcmp(new_shell
, "csh"))
336 parse_error(_("unknown shell after -s or --shell argument"));
339 static void __attribute__((__noreturn__
)) usage(void)
341 fputs(USAGE_HEADER
, stdout
);
343 " %1$s <optstring> <parameters>\n"
344 " %1$s [options] [--] <optstring> <parameters>\n"
345 " %1$s [options] -o|--options <optstring> [options] [--] <parameters>\n"),
346 program_invocation_short_name
);
348 fputs(USAGE_SEPARATOR
, stdout
);
349 fputs(_("Parse command options.\n"), stdout
);
351 fputs(USAGE_OPTIONS
, stdout
);
352 fputs(_(" -a, --alternative allow long options starting with single -\n"), stdout
);
353 fputs(_(" -l, --longoptions <longopts> the long options to be recognized\n"), stdout
);
354 fputs(_(" -n, --name <progname> the name under which errors are reported\n"), stdout
);
355 fputs(_(" -o, --options <optstring> the short options to be recognized\n"), stdout
);
356 fputs(_(" -q, --quiet disable error reporting by getopt(3)\n"), stdout
);
357 fputs(_(" -Q, --quiet-output no normal output\n"), stdout
);
358 fputs(_(" -s, --shell <shell> set quoting conventions to those of <shell>\n"), stdout
);
359 fputs(_(" -T, --test test for getopt(1) version\n"), stdout
);
360 fputs(_(" -u, --unquoted do not quote the output\n"), stdout
);
361 fputs(USAGE_SEPARATOR
, stdout
);
362 fprintf(stdout
, USAGE_HELP_OPTIONS(31));
363 fprintf(stdout
, USAGE_MAN_TAIL("getopt(1)"));
367 int main(int argc
, char *argv
[])
369 struct getopt_control ctl
= {
375 /* Stop scanning as soon as a non-option argument is found! */
376 static const char *shortopts
= "+ao:l:n:qQs:TuhV";
377 static const struct option longopts
[] = {
378 {"options", required_argument
, NULL
, 'o'},
379 {"longoptions", required_argument
, NULL
, 'l'},
380 {"quiet", no_argument
, NULL
, 'q'},
381 {"quiet-output", no_argument
, NULL
, 'Q'},
382 {"shell", required_argument
, NULL
, 's'},
383 {"test", no_argument
, NULL
, 'T'},
384 {"unquoted", no_argument
, NULL
, 'u'},
385 {"help", no_argument
, NULL
, 'h'},
386 {"alternative", no_argument
, NULL
, 'a'},
387 {"name", required_argument
, NULL
, 'n'},
388 {"version", no_argument
, NULL
, 'V'},
392 setlocale(LC_ALL
, "");
393 bindtextdomain(PACKAGE
, LOCALEDIR
);
395 close_stdout_atexit();
397 if (getenv("GETOPT_COMPATIBLE"))
401 if (ctl
.compatible
) {
403 * For some reason, the original getopt gave no
404 * error when there were no arguments.
409 parse_error(_("missing optstring argument"));
412 add_longopt(&ctl
, NULL
, 0); /* init */
413 getopt_long_fp
= getopt_long
;
415 if (argv
[1][0] != '-' || ctl
.compatible
) {
417 ctl
.optstr
= xmalloc(strlen(argv
[1]) + 1);
418 strcpy(ctl
.optstr
, argv
[1] + strspn(argv
[1], "-+"));
420 return generate_output(&ctl
, argv
+ 1, argc
- 1);
424 getopt_long(argc
, argv
, shortopts
, longopts
, NULL
)) != EOF
)
427 getopt_long_fp
= getopt_long_only
;
430 add_short_options(&ctl
, optarg
);
433 add_long_options(&ctl
, optarg
);
437 ctl
.name
= xstrdup(optarg
);
440 ctl
.quiet_errors
= 1;
443 ctl
.quiet_output
= 1;
446 ctl
.shell
= shell_type(optarg
);
449 free(ctl
.long_options
);
450 return TEST_EXIT_CODE
;
456 print_version(EXIT_SUCCESS
);
463 parse_error(_("internal error, contact the author."));
468 parse_error(_("missing optstring argument"));
470 add_short_options(&ctl
, argv
[optind
]);
476 argv
[optind
- 1] = ctl
.name
;
477 #if defined (HAVE_SETPROGNAME) && !defined (__linux__)
478 setprogname(ctl
.name
);
481 argv
[optind
- 1] = argv
[0];
483 return generate_output(&ctl
, argv
+ optind
- 1, argc
- optind
+ 1);