Skip to content

Commit 5ad0d3d

Browse files
rscharfepeff
authored andcommitted
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 <[email protected]> Signed-off-by: Jeff King <[email protected]>
1 parent d3d1f8c commit 5ad0d3d

File tree

2 files changed

+11
-6
lines changed

2 files changed

+11
-6
lines changed

parse-options.c

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -410,7 +410,7 @@ void parse_options_start(struct parse_opt_ctx_t *ctx,
410410
const struct option *options, int flags)
411411
{
412412
memset(ctx, 0, sizeof(*ctx));
413-
ctx->argc = argc - 1;
413+
ctx->argc = ctx->total = argc - 1;
414414
ctx->argv = argv + 1;
415415
ctx->out = argv;
416416
ctx->prefix = prefix;
@@ -448,27 +448,32 @@ int parse_options_step(struct parse_opt_ctx_t *ctx,
448448
continue;
449449
}
450450

451+
/* lone -h asks for help */
452+
if (internal_help && ctx->total == 1 && !strcmp(arg + 1, "h"))
453+
goto show_usage;
454+
451455
if (arg[1] != '-') {
452456
ctx->opt = arg + 1;
453-
if (internal_help && *ctx->opt == 'h')
454-
goto show_usage;
455457
switch (parse_short_opt(ctx, options)) {
456458
case -1:
457459
goto show_usage_error;
458460
case -2:
459461
if (ctx->opt)
460462
check_typos(arg + 1, options);
463+
if (internal_help && *ctx->opt == 'h')
464+
goto show_usage;
461465
goto unknown;
462466
}
463467
if (ctx->opt)
464468
check_typos(arg + 1, options);
465469
while (ctx->opt) {
466-
if (internal_help && *ctx->opt == 'h')
467-
goto show_usage;
468470
switch (parse_short_opt(ctx, options)) {
469471
case -1:
470472
goto show_usage_error;
471473
case -2:
474+
if (internal_help && *ctx->opt == 'h')
475+
goto show_usage;
476+
472477
/* fake a short option thing to hide the fact that we may have
473478
* started to parse aggregated stuff
474479
*

parse-options.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ enum {
199199
struct parse_opt_ctx_t {
200200
const char **argv;
201201
const char **out;
202-
int argc, cpidx;
202+
int argc, cpidx, total;
203203
const char *opt;
204204
int flags;
205205
const char *prefix;

0 commit comments

Comments
 (0)