summaryrefslogtreecommitdiff
path: root/tools/lib/subcmd/parse-options.c
diff options
context:
space:
mode:
Diffstat (limited to 'tools/lib/subcmd/parse-options.c')
-rw-r--r--tools/lib/subcmd/parse-options.c44
1 files changed, 29 insertions, 15 deletions
diff --git a/tools/lib/subcmd/parse-options.c b/tools/lib/subcmd/parse-options.c
index 9fa75943f2ed..4b60ec03b0bb 100644
--- a/tools/lib/subcmd/parse-options.c
+++ b/tools/lib/subcmd/parse-options.c
@@ -633,11 +633,10 @@ int parse_options_subcommand(int argc, const char **argv, const struct option *o
const char *const subcommands[], const char *usagestr[], int flags)
{
struct parse_opt_ctx_t ctx;
+ char *buf = NULL;
/* build usage string if it's not provided */
if (subcommands && !usagestr[0]) {
- char *buf = NULL;
-
astrcatf(&buf, "%s %s [<options>] {", subcmd_config.exec_name, argv[0]);
for (int i = 0; subcommands[i]; i++) {
@@ -679,7 +678,10 @@ int parse_options_subcommand(int argc, const char **argv, const struct option *o
astrcatf(&error_buf, "unknown switch `%c'", *ctx.opt);
usage_with_options(usagestr, options);
}
-
+ if (buf) {
+ usagestr[0] = NULL;
+ free(buf);
+ }
return parse_options_end(&ctx);
}
@@ -806,18 +808,30 @@ static int option__cmp(const void *va, const void *vb)
static struct option *options__order(const struct option *opts)
{
- int nr_opts = 0, nr_group = 0, len;
- const struct option *o = opts;
- struct option *opt, *ordered, *group;
-
- for (o = opts; o->type != OPTION_END; o++)
- ++nr_opts;
-
- len = sizeof(*o) * (nr_opts + 1);
- ordered = malloc(len);
- if (!ordered)
- goto out;
- memcpy(ordered, opts, len);
+ int nr_opts = 0, nr_group = 0, nr_parent = 0, len;
+ const struct option *o, *p = opts;
+ struct option *opt, *ordered = NULL, *group;
+
+ /* flatten the options that have parents */
+ for (p = opts; p != NULL; p = o->parent) {
+ for (o = p; o->type != OPTION_END; o++)
+ ++nr_opts;
+
+ /*
+ * the length is given by the number of options plus a null
+ * terminator for the last loop iteration.
+ */
+ len = sizeof(*o) * (nr_opts + !o->parent);
+ group = realloc(ordered, len);
+ if (!group)
+ goto out;
+ ordered = group;
+ memcpy(&ordered[nr_parent], p, sizeof(*o) * (nr_opts - nr_parent));
+
+ nr_parent = nr_opts;
+ }
+ /* copy the last OPTION_END */
+ memcpy(&ordered[nr_opts], o, sizeof(*o));
/* sort each option group individually */
for (opt = group = ordered; opt->type != OPTION_END; opt++) {