aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/tools/lib/subcmd/parse-options.c
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--tools/lib/subcmd/parse-options.c57
1 files changed, 41 insertions, 16 deletions
diff --git a/tools/lib/subcmd/parse-options.c b/tools/lib/subcmd/parse-options.c
index 39ebf6192016..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,20 +808,43 @@ static int option__cmp(const void *va, const void *vb)
static struct option *options__order(const struct option *opts)
{
- int nr_opts = 0, len;
- const struct option *o = opts;
- struct option *ordered;
-
- 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++) {
+ if (opt->type == OPTION_GROUP) {
+ qsort(group, nr_group, sizeof(*opt), option__cmp);
+ group = opt + 1;
+ nr_group = 0;
+ continue;
+ }
+ nr_group++;
+ }
+ qsort(group, nr_group, sizeof(*opt), option__cmp);
- qsort(ordered, nr_opts, sizeof(*o), option__cmp);
out:
return ordered;
}