1 /***********************************************************************
3 * This software is part of the ast package *
4 * Copyright (c) 1985-2010 AT&T Intellectual Property *
5 * and is licensed under the *
6 * Common Public License, Version 1.0 *
7 * by AT&T Intellectual Property *
9 * A copy of the License is available at *
10 * http://www.opensource.org/licenses/cpl1.0.txt *
11 * (with md5 checksum 059e8cd6165cb4c31e351f2b69388fd9) *
13 * Information and Software Systems Research *
17 * Glenn Fowler <gsf@research.att.com> *
18 * David Korn <dgk@research.att.com> *
19 * Phong Vo <kpv@research.att.com> *
21 ***********************************************************************/
25 #include <ast_getopt.h>
27 #undef _BLD_ast /* enable ast imports since we're user static */
34 static const char* lastoptstring
;
35 static const struct option
* lastlongopts
;
39 static int lastoptind
;
42 golly(int argc
, char* const* argv
, const char* optstring
, const struct option
* longopts
, int* longindex
, int flags
)
45 register const struct option
* o
;
49 if (!up
|| optstring
!= lastoptstring
|| longopts
!= lastlongopts
)
51 if (!up
&& !(up
= sfstropen()))
53 sfprintf(up
, "[-1p%d]", flags
);
54 t
= strdup(optstring
);
55 for (o
= longopts
; o
->name
; o
++)
57 if (o
->flag
|| o
->val
<= 0 || o
->val
> UCHAR_MAX
|| !isalnum(o
->val
))
58 sfprintf(up
, "\n[%d:%s]", UCHAR_MAX
+ 1 + (o
- longopts
), o
->name
);
61 sfprintf(up
, "\n[%c:%s]", o
->val
, o
->name
);
62 if (s
= strchr(t
, o
->val
))
76 if (o
->has_arg
== optional_argument
)
78 sfprintf(up
, "[string]");
85 sfprintf(up
, "\n[%c]", c
);
99 if (!(usage
= sfstruse(up
)))
101 lastoptstring
= optstring
;
102 lastlongopts
= longopts
;
104 opt_info
.index
= (optind
> 1 || optind
== lastoptind
) ? optind
: 0;
105 if (opt_info
.index
>= argc
|| !(c
= optget((char**)argv
, usage
)))
113 if (c
== ':' || c
== '?')
115 if (opterr
&& (!optstring
|| *optstring
!= ':'))
118 error_info
.id
= argv
[0];
119 errormsg(NiL
, c
== '?' ? (ERROR_USAGE
|4) : 2, "%s", opt_info
.arg
);
121 optopt
= opt_info
.option
[1];
124 optarg
= opt_info
.arg
;
127 o
= longopts
- c
- UCHAR_MAX
- 1;
137 lastoptind
= optind
= opt_info
.index
;
142 getopt_long(int argc
, char* const* argv
, const char* optstring
, const struct option
* longopts
, int* longindex
)
144 return golly(argc
, argv
, optstring
, longopts
, longindex
, 2);
148 getopt_long_only(int argc
, char* const* argv
, const char* optstring
, const struct option
* longopts
, int* longindex
)
150 return golly(argc
, argv
, optstring
, longopts
, longindex
, 1);