From 71f05097a5fd40d666f02ac6118757e2d62e6a2f Mon Sep 17 00:00:00 2001 From: Rob Landley Date: Fri, 1 Mar 2024 21:25:17 -0600 Subject: [PATCH] Cleanup pass. --- toys/pending/getopt.c | 46 +++++++++++++++++++++++-------------------- 1 file changed, 25 insertions(+), 21 deletions(-) diff --git a/toys/pending/getopt.c b/toys/pending/getopt.c index e6e239a5..6ee58f16 100644 --- a/toys/pending/getopt.c +++ b/toys/pending/getopt.c @@ -3,7 +3,6 @@ * Copyright 2019 The Android Open Source Project * * See https://man7.org/linux/man-pages/man1/getopt.1.html - * No standard USE_GETOPT(NEWTOY(getopt, "^a(alternative)n:(name)o:(options)l*(long)(longoptions)Tu", TOYFLAG_USR|TOYFLAG_BIN)) @@ -11,16 +10,23 @@ config GETOPT bool "getopt" default n help - usage: getopt [OPTIONS] [--] ARG... - - Parse command-line options for use in shell scripts. - - -a Allow long options starting with a single -. - -l OPTS Specify long options. - -n NAME Command name for error messages. - -o OPTS Specify short options. - -T Test whether this is a modern getopt. - -u Output options unquoted. + usage: getopt [-aTu] [-lo OPTIONS] [-n NAME] [OPTIONS] ARG... + + Outputs command line with recognized OPTIONS character arguments moved to + front, then "--", then non-option arguments. Returns 1 if unknown options. + OPTIONS followed by : take an argument, or :: for optional arguments (which + must be attached, ala -xblah or --long=blah). + + -a Allow long options starting with a single - + -l Long OPTIONS (repeated or comma separated) + -n Command NAME for error messages + -o Short OPTIONS (instead of using first argument) + -T Test whether this is a modern getopt + -u Unquoted output (default if no other options set) + + Example: + $ getopt -l long:,arg:: abc command --long -b there --arg + --long '-b' --arg '' -- 'command' 'there' */ #define FOR_getopt @@ -55,17 +61,16 @@ static char *parse_long_opt(void *data, char *str, int len) if (!len || lopt->has_arg>2) return str; lopt->name = xstrndup(str, len); - (*lopt_ptr)++; + return 0; } void getopt_main(void) { - int argc = toys.optc+1; + int argc = toys.optc+1, i = 0, j = 0, ch; char **argv = xzalloc(sizeof(char *)*(argc+1)); struct option *lopts = xzalloc(sizeof(struct option)*argc), *lopt = lopts; - int i = 0, j = 0, ch; if (FLAG(T)) { toys.exitval = 4; @@ -73,25 +78,24 @@ void getopt_main(void) } comma_args(TT.l, &lopt, "bad -l", parse_long_opt); - argv[j++] = TT.n ? TT.n : "getopt"; + argv[j++] = TT.n ? : "getopt"; - // Legacy mode: don't quote output and take the first argument as OPTSTR. if (!FLAG(o)) { - toys.optflags |= FLAG_u; TT.o = toys.optargs[i++]; - if (!TT.o) error_exit("no OPTSTR"); - --argc; + argc--; } + if (!TT.o) error_exit("no OPTSTR"); + if (!toys.optflags) toys.optflags = FLAG_u; while (i