parse-options: allow -h as a short option
Let callers provide their own handler for the short option -h even without the flag PARSE_OPT_NO_INTERNAL_HELP, but call the internal handler (showing usage information) if that is the only parameter. Implement the first part by checking for -h only if parse_short_opt() can't find it and returns -2. Signed-off-by: Rene Scharfe <l.s.r@web.de> Signed-off-by: Jeff King <peff@peff.net>
René Scharfe committed
Nov 17, 2015 at 11:25 UTC
5ad0d3d5266b83aa767a7efa09cb574d3c2968b3
2 files changed
+11
-6
parse-options.c
+10
-5
@@ -410,7 +410,7 @@ void parse_options_start(struct parse_opt_ctx_t *ctx,
410
const struct option *options, int flags)
411
{
412
memset(ctx, 0, sizeof(*ctx));
413
- ctx->argc = argc - 1;
413
+ ctx->argc = ctx->total = argc - 1;
414
ctx->argv = argv + 1;
415
ctx->out = argv;
416
ctx->prefix = prefix;
@@ -448,27 +448,32 @@ int parse_options_step(struct parse_opt_ctx_t *ctx,
448
continue;
449
}
450
451
+ /* lone -h asks for help */
452
+ if (internal_help && ctx->total == 1 && !strcmp(arg + 1, "h"))
453
+ goto show_usage;
454
+
455
if (arg[1] != '-') {
456
ctx->opt = arg + 1;
453
- if (internal_help && *ctx->opt == 'h')
454
- goto show_usage;
457
switch (parse_short_opt(ctx, options)) {
458
case -1:
459
goto show_usage_error;
460
case -2:
461
if (ctx->opt)
462
check_typos(arg + 1, options);
463
+ if (internal_help && *ctx->opt == 'h')
464
+ goto show_usage;
465
goto unknown;
466
}
467
if (ctx->opt)
468
check_typos(arg + 1, options);
469
while (ctx->opt) {
466
- if (internal_help && *ctx->opt == 'h')
467
- goto show_usage;
470
switch (parse_short_opt(ctx, options)) {
471
case -1:
472
goto show_usage_error;
473
case -2:
474
+ if (internal_help && *ctx->opt == 'h')
475
+ goto show_usage;
476
+
477
/* fake a short option thing to hide the fact that we may have
478
* started to parse aggregated stuff
479
*
parse-options.h
+1
-1
@@ -199,7 +199,7 @@ enum {
199
struct parse_opt_ctx_t {
200
const char **argv;
201
const char **out;
202
- int argc, cpidx;
202
+ int argc, cpidx, total;
203
const char *opt;
204
int flags;
205
const char *prefix;