parse-options: only insert newline in help text if needed

Currently, when parse_options() produces a help message it always emits a blank line after the usage text to separate it from the options text. If the option spec does not define any switches, or only defines hidden switches that will not be displayed, then the help text will end up with two trailing blank lines instead of one. Let's defer emitting the blank line between the usage text and the options text until it is clear that the options section will not be empty. Fixes t1502.5, t1502.6. Signed-off-by: Brandon Casey <drafnel@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Brandon Casey committed Sep 24, 2017 at 21:08 UTC a6304fa4c2f57b08ec0acea9f91c188f284f8374
2 files changed +10 -4
parse-options.c
+8 -2
@@ -581,6 +581,7 @@ static int usage_with_options_internal(struct parse_opt_ctx_t *ctx,
581 const struct option *opts, int full, int err)
582 {
583 FILE *outfile = err ? stderr : stdout;
584 + int need_newline;
585
586 if (!usagestr)
587 return PARSE_OPT_HELP;
@@ -603,8 +604,7 @@ static int usage_with_options_internal(struct parse_opt_ctx_t *ctx,
604 usagestr++;
605 }
606
606 - if (opts->type != OPTION_GROUP)
607 - fputc('\n', outfile);
607 + need_newline = 1;
608
609 for (; opts->type != OPTION_END; opts++) {
610 size_t pos;
@@ -612,6 +612,7 @@ static int usage_with_options_internal(struct parse_opt_ctx_t *ctx,
612
613 if (opts->type == OPTION_GROUP) {
614 fputc('\n', outfile);
615 + need_newline = 0;
616 if (*opts->help)
617 fprintf(outfile, "%s\n", _(opts->help));
618 continue;
@@ -619,6 +620,11 @@ static int usage_with_options_internal(struct parse_opt_ctx_t *ctx,
620 if (!full && (opts->flags & PARSE_OPT_HIDDEN))
621 continue;
622
623 + if (need_newline) {
624 + fputc('\n', outfile);
625 + need_newline = 0;
626 + }
627 +
628 pos = fprintf(outfile, " ");
629 if (opts->short_name) {
630 if (opts->flags & PARSE_OPT_NODASH)
t/t1502-rev-parse-parseopt.sh
+2 -2
@@ -98,7 +98,7 @@ END_EXPECT
98 test_i18ncmp expect output
99 '
100
101 -test_expect_failure 'test --parseopt help output no switches' '
101 +test_expect_success 'test --parseopt help output no switches' '
102 sed -e "s/^|//" >expect <<\END_EXPECT &&
103 |cat <<\EOF
104 |usage: some-command [options] <args>...
@@ -111,7 +111,7 @@ END_EXPECT
111 test_i18ncmp expect output
112 '
113
114 -test_expect_failure 'test --parseopt help output hidden switches' '
114 +test_expect_success 'test --parseopt help output hidden switches' '
115 sed -e "s/^|//" >expect <<\END_EXPECT &&
116 |cat <<\EOF
117 |usage: some-command [options] <args>...