]> git.ipfire.org Git - thirdparty/util-linux.git/blob - getopt-1.0.3b/getopt.c
Imported from util-linux-2.10m tarball.
[thirdparty/util-linux.git] / getopt-1.0.3b / getopt.c
1 /*
2 getopt.c - Enhanced implementation of BSD getopt(1)
3 Copyright (c) 1997, 1998 Frodo Looijaard <frodol@dds.nl>
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.3
32 * 1999-02-22 Arkadiusz Mi¶kiewicz <misiek@misiek.eu.org>
33 * - added Native Language Support
34 *
35 */
36
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <unistd.h>
41 #include <ctype.h>
42 #include "../lib/nls.h"
43
44 #if LIBCGETOPT
45 #include <getopt.h>
46 #else
47 #include "getopt.h"
48 #endif
49
50 /* NON_OPT is the code that is returned when a non-option is found in '+'
51 mode */
52 #define NON_OPT 1
53 /* LONG_OPT is the code that is returned when a long option is found. */
54 #define LONG_OPT 2
55
56 /* The shells recognized. */
57 typedef enum {BASH,TCSH} shell_t;
58
59
60 /* Some global variables that tells us how to parse. */
61 shell_t shell=BASH; /* The shell we generate output for. */
62 int quiet_errors=0; /* 0 is not quiet. */
63 int quiet_output=0; /* 0 is not quiet. */
64 int quote=1; /* 1 is do quote. */
65 int alternative=0; /* 0 is getopt_long, 1 is getopt_long_only */
66
67 /* Function prototypes */
68 void *our_malloc(size_t size);
69 void *our_realloc(void *ptr, size_t size);
70 const char *normalize(const char *arg);
71 int generate_output(char * argv[],int argc,const char *optstr,
72 const struct option *longopts);
73 int main(int argc, char *argv[]);
74 void parse_error(const char *message);
75 void add_long_options(char *options);
76 void add_longopt(const char *name,int has_arg);
77 void print_help(void);
78 void set_shell(const char *new_shell);
79 void set_initial_shell(void);
80
81 void *our_malloc(size_t size)
82 {
83 void *ret=malloc(size);
84 if (! ret) {
85 fprintf(stderr,_("%s: Out of memory!\n"),"getopt");
86 exit(3);
87 }
88 return(ret);
89 }
90
91 void *our_realloc(void *ptr, size_t size)
92 {
93 void *ret=realloc(ptr,size);
94 if (! ret && size) {
95 fprintf(stderr,_("%s: Out of memory!\n"), "getopt");
96 exit(3);
97 }
98 return(ret);
99 }
100
101 /*
102 * This function 'normalizes' a single argument: it puts single quotes around
103 * it and escapes other special characters. If quote is false, it just
104 * returns its argument.
105 * Bash only needs special treatment for single quotes; tcsh also recognizes
106 * exclamation marks within single quotes, and nukes whitespace.
107 * This function returns a pointer to a buffer that is overwritten by
108 * each call.
109 */
110 const char *normalize(const char *arg)
111 {
112 static char *BUFFER=NULL;
113 const char *argptr=arg;
114 char *bufptr;
115
116 if (BUFFER != NULL)
117 free(BUFFER);
118
119 if (!quote) { /* Just copy arg */
120 BUFFER=our_malloc(strlen(arg)+1);
121
122 strcpy(BUFFER,arg);
123 return BUFFER;
124 }
125
126 /* Each character in arg may take upto four characters in the result:
127 For a quote we need a closing quote, a backslash, a quote and an
128 opening quote! We need also the global opening and closing quote,
129 and one extra character for '\0'. */
130 BUFFER=our_malloc(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 int generate_output(char * argv[],int argc,const char *optstr,
176 const struct option *longopts)
177 {
178 int exit_code = 0; /* We assume everything will be OK */
179 int opt;
180 int longindex;
181 const char *charptr;
182
183 if (quiet_errors) /* No error reporting from getopt(3) */
184 opterr=0;
185 optind=0; /* Reset getopt(3) */
186
187 while ((opt = (alternative?
188 getopt_long_only(argc,argv,optstr,longopts,&longindex):
189 getopt_long(argc,argv,optstr,longopts,&longindex)))
190 != EOF)
191 if (opt == '?' || opt == ':' )
192 exit_code = 1;
193 else if (!quiet_output)
194 {
195 if (opt == LONG_OPT) {
196 printf(" --%s",longopts[longindex].name);
197 if (longopts[longindex].has_arg)
198 printf(" %s",
199 normalize(optarg?optarg:""));
200 } else if (opt == NON_OPT)
201 printf(" %s",normalize(optarg));
202 else {
203 printf(" -%c",opt);
204 charptr = strchr(optstr,opt);
205 if (charptr != NULL && *++charptr == ':')
206 printf(" %s",
207 normalize(optarg?optarg:""));
208 }
209 }
210
211 if (! quiet_output) {
212 printf(" --");
213 while (optind < argc)
214 printf(" %s",normalize(argv[optind++]));
215 printf("\n");
216 }
217 return exit_code;
218 }
219
220 /*
221 * Report an error when parsing getopt's own arguments.
222 * If message is NULL, we already sent a message, we just exit with a helpful
223 * hint.
224 */
225 void parse_error(const char *message)
226 {
227 if (message)
228 fprintf(stderr,"getopt: %s\n",message);
229 fputs(_("Try `getopt --help' for more information.\n"),stderr);
230 exit(2);
231 }
232
233 static struct option *long_options=NULL;
234 static int long_options_length=0; /* Length of array */
235 static int long_options_nr=0; /* Nr of used elements in array */
236 #define LONG_OPTIONS_INCR 10
237 #define init_longopt() add_longopt(NULL,0)
238
239 /* Register a long option. The contents of name is copied. */
240 void add_longopt(const char *name,int has_arg)
241 {
242 char *tmp;
243 if (!name) { /* init */
244 free(long_options);
245 long_options=NULL;
246 long_options_length=0;
247 long_options_nr=0;
248 }
249
250 if (long_options_nr == long_options_length) {
251 long_options_length += LONG_OPTIONS_INCR;
252 long_options=our_realloc(long_options,
253 sizeof(struct option) *
254 long_options_length);
255 }
256
257 long_options[long_options_nr].name=NULL;
258 long_options[long_options_nr].has_arg=0;
259 long_options[long_options_nr].flag=NULL;
260 long_options[long_options_nr].val=0;
261
262 if (long_options_nr) { /* 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 = our_malloc(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.
277 * This nukes options!
278 */
279 void add_long_options(char *options)
280 {
281 int arg_opt;
282 char *tokptr=strtok(options,", \t\n");
283 while (tokptr) {
284 arg_opt=no_argument;
285 if (strlen(tokptr) > 0) {
286 if (tokptr[strlen(tokptr)-1] == ':') {
287 if (tokptr[strlen(tokptr)-2] == ':') {
288 tokptr[strlen(tokptr)-2]='\0';
289 arg_opt=optional_argument;
290 } else {
291 tokptr[strlen(tokptr)-1]='\0';
292 arg_opt=required_argument;
293 }
294 if (strlen(tokptr) == 0)
295 parse_error(_("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 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(_("unknown shell after -s or --shell argument"));
316 }
317
318 void print_help(void)
319 {
320 fputs(_("Usage: getopt optstring parameters\n"),stderr);
321 fputs(_(" getopt [options] [--] optstring parameters\n"),stderr);
322 fputs(_(" getopt [options] -o|--options optstring [options] [--]\n"),stderr);
323 fputs(_(" parameters\n"),stderr);
324 fputs(_(" -a, --alternative Allow long options starting with single -\n"),stderr);
325 fputs(_(" -h, --help This small usage guide\n"),stderr);
326 fputs(_(" -l, --longoptions=longopts Long options to be recognized\n"),stderr);
327 fputs(_(" -n, --name=progname The name under which errors are reported\n"),stderr);
328 fputs(_(" -o, --options=optstring Short options to be recognized\n"),stderr);
329 fputs(_(" -q, --quiet Disable error reporting by getopt(3)\n"),stderr);
330 fputs(_(" -Q, --quiet-output No normal output\n"),stderr);
331 fputs(_(" -s, --shell=shell Set shell quoting conventions\n"),stderr);
332 fputs(_(" -T, --test Test for getopt(1) version\n"),stderr);
333 fputs(_(" -V, --version Output version information\n"),stderr);
334 exit(2);
335 }
336
337 /* Exit codes:
338 * 0) No errors, succesful operation.
339 * 1) getopt(3) returned an error.
340 * 2) A problem with parameter parsing for getopt(1).
341 * 3) Internal error, out of memory
342 * 4) Returned for -T
343 */
344
345 static struct option longopts[]={ {"options",required_argument,NULL,'o'},
346 {"longoptions",required_argument,NULL,'l'},
347 {"quiet",no_argument,NULL,'q'},
348 {"quiet-output",no_argument,NULL,'Q'},
349 {"shell",required_argument,NULL,'s'},
350 {"test",no_argument,NULL,'T'},
351 {"unquoted",no_argument,NULL,'u'},
352 {"help",no_argument,NULL,'h'},
353 {"alternative",no_argument,NULL,'a'},
354 {"name",required_argument,NULL,'n'},
355 {"version",no_argument,NULL,'V'},
356 {NULL,0,NULL,0}
357 };
358
359 /* Stop scanning as soon as a non-option argument is found! */
360 static const char *shortopts="+ao:l:n:qQs:TuhV";
361
362 int main(int argc, char *argv[])
363 {
364 char *optstr=NULL;
365 char *name=NULL;
366 int opt;
367 int compatible=0;
368
369 setlocale(LC_ALL, "");
370 bindtextdomain(PACKAGE, LOCALEDIR);
371 textdomain(PACKAGE);
372
373 init_longopt();
374
375 if (getenv("GETOPT_COMPATIBLE"))
376 compatible=1;
377
378 if (argc == 1)
379 {
380 if (compatible) {
381 /* For some reason, the original getopt gave no error
382 when there were no arguments. */
383 printf(" --\n");
384 exit(0);
385 }
386 else
387 parse_error(_("missing optstring argument"));
388 }
389
390 if (argv[1][0] != '-' || compatible) {
391 quote=0;
392 optstr=our_malloc(strlen(argv[1])+1);
393 strcpy(optstr,argv[1]+strspn(argv[1],"-+"));
394 argv[1]=argv[0];
395 exit(generate_output(argv+1,argc-1,optstr,long_options));
396 }
397
398 while ((opt=getopt_long(argc,argv,shortopts,longopts,NULL)) != EOF)
399 switch (opt) {
400 case 'a':
401 alternative=1;
402 break;
403 case 'h':
404 print_help();
405 exit(0);
406 case 'o':
407 if (optstr)
408 free(optstr);
409 optstr=our_malloc(strlen(optarg)+1);
410 strcpy(optstr,optarg);
411 break;
412 case 'l':
413 add_long_options(optarg);
414 break;
415 case 'n':
416 if (name)
417 free(name);
418 name=our_malloc(strlen(optarg)+1);
419 strcpy(name,optarg);
420 break;
421 case 'q':
422 quiet_errors=1;
423 break;
424 case 'Q':
425 quiet_output=1;
426 break;
427 case 's':
428 set_shell(optarg);
429 break;
430 case 'T':
431 exit(4);
432 case 'V':
433 printf(_("getopt (enhanced) 1.0.3\n"));
434 exit(0);
435 case '?':
436 case ':':
437 parse_error(NULL);
438 default:
439 parse_error(_("internal error, contact the author."));
440 }
441
442 if (!optstr)
443 {
444 if (optind >= argc)
445 parse_error(_("missing optstring argument"));
446 else {
447 optstr=our_malloc(strlen(argv[optind])+1);
448 strcpy(optstr,argv[optind]);
449 optind++;
450 }
451 }
452 if (name)
453 argv[optind-1]=name;
454 else
455 argv[optind-1]=argv[0];
456 exit(generate_output(argv+optind-1,argc-optind+1,optstr,long_options));
457 }