parse-options API: add a usage_msg_optf()

Add a usage_msg_optf() as a shorthand for the sort of usage_msg_opt(xstrfmt(...)) used in builtin/stash.c. I'll make more use of this function in builtin/cat-file.c shortly. The disconnect between the "..." and "fmt" is a bit unusual, but it works just fine and this keeps it consistent with usage_msg_opt(), i.e. a caller of it can be moved to usage_msg_optf() and not have to have its arguments re-arranged. Signed-off-by: Ævar Arnfjörð Bjarmason <avarab@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Ævar Arnfjörð Bjarmason committed Dec 28, 2021 at 14:28 UTC fa476be8f0963d4dd512eaf8ee23b3cd3986a500
3 files changed +25 -2
builtin/stash.c
+2 -2
@@ -1811,8 +1811,8 @@ int cmd_stash(int argc, const char **argv, const char *prefix)
1811 else if (!strcmp(argv[0], "save"))
1812 return !!save_stash(argc, argv, prefix);
1813 else if (*argv[0] != '-')
1814 - usage_msg_opt(xstrfmt(_("unknown subcommand: %s"), argv[0]),
1815 - git_stash_usage, options);
1814 + usage_msg_optf(_("unknown subcommand: %s"),
1815 + git_stash_usage, options, argv[0]);
1816
1817 /* Assume 'stash push' */
1818 strvec_push(&args, "push");
parse-options.c
+13
@@ -1078,3 +1078,16 @@ void NORETURN usage_msg_opt(const char *msg,
1078 fprintf(stderr, "fatal: %s\n\n", msg);
1079 usage_with_options(usagestr, options);
1080 }
1081 +
1082 +void NORETURN usage_msg_optf(const char * const fmt,
1083 + const char * const *usagestr,
1084 + const struct option *options, ...)
1085 +{
1086 + struct strbuf msg = STRBUF_INIT;
1087 + va_list ap;
1088 + va_start(ap, options);
1089 + strbuf_vaddf(&msg, fmt, ap);
1090 + va_end(ap);
1091 +
1092 + usage_msg_opt(msg.buf, usagestr, options);
1093 +}
parse-options.h
+10
@@ -225,6 +225,16 @@ NORETURN void usage_msg_opt(const char *msg,
225 const char * const *usagestr,
226 const struct option *options);
227
228 +/**
229 + * usage_msg_optf() is like usage_msg_opt() except that the first
230 + * argument is a format string, and optional format arguments follow
231 + * after the 3rd option.
232 + */
233 +__attribute__((format (printf,1,4)))
234 +void NORETURN usage_msg_optf(const char *fmt,
235 + const char * const *usagestr,
236 + const struct option *options, ...);
237 +
238 /*
239 * Use these assertions for callbacks that expect to be called with NONEG and
240 * NOARG respectively, and do not otherwise handle the "unset" and "arg"