parse-options: make OPT_ARGUMENT() more useful

`OPT_ARGUMENT()` is intended to keep the specified long option in `argv` and not to do anything else. However, it would make a lot of sense for the caller to know whether this option was seen at all or not. For example, we want to teach `git difftool` to work outside of any Git worktree, but only when `--no-index` was specified. Note: nothing in Git uses OPT_ARGUMENT(). Even worse, looking through the commit history, one can easily see that nothing even ever used it, apart from the regression test. So not only do we make `OPT_ARGUMENT()` more useful, we are also about to introduce its first real user! Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Johannes Schindelin committed Mar 14, 2019 at 04:25 UTC 1a85b49b87af0e17a503b94df10d0b39472ad5b8
4 files changed +8 -4
Documentation/technical/api-parse-options.txt
+3 -1
@@ -198,8 +198,10 @@ There are some macros to easily define options:
198 The filename will be prefixed by passing the filename along with
199 the prefix argument of `parse_options()` to `prefix_filename()`.
200
201 -`OPT_ARGUMENT(long, description)`::
201 +`OPT_ARGUMENT(long, &int_var, description)`::
202 Introduce a long-option argument that will be kept in `argv[]`.
203 + If this option was seen, `int_var` will be set to one (except
204 + if a `NULL` pointer was passed).
205
206 `OPT_NUMBER_CALLBACK(&var, description, func_ptr)`::
207 Recognize numerical options like -123 and feed the integer as
parse-options.c
+2
@@ -286,6 +286,8 @@ again:
286 optname(options, flags));
287 if (*rest)
288 continue;
289 + if (options->value)
290 + *(int *)options->value = options->defval;
291 p->out[p->cpidx++] = arg - 2;
292 return PARSE_OPT_DONE;
293 }
parse-options.h
+2 -2
@@ -138,8 +138,8 @@ struct option {
138 { OPTION_CALLBACK, (s), (l), (v), (a), (h), (f), (cb) }
139
140 #define OPT_END() { OPTION_END }
141 -#define OPT_ARGUMENT(l, h) { OPTION_ARGUMENT, 0, (l), NULL, NULL, \
142 - (h), PARSE_OPT_NOARG}
141 +#define OPT_ARGUMENT(l, v, h) { OPTION_ARGUMENT, 0, (l), (v), NULL, \
142 + (h), PARSE_OPT_NOARG, NULL, 1 }
143 #define OPT_GROUP(h) { OPTION_GROUP, 0, NULL, NULL, NULL, (h) }
144 #define OPT_BIT(s, l, v, h, b) OPT_BIT_F(s, l, v, h, b, 0)
145 #define OPT_BITOP(s, l, v, h, set, clear) { OPTION_BITOP, (s), (l), (v), NULL, (h), \
t/helper/test-parse-options.c
+1 -1
@@ -132,7 +132,7 @@ int cmd__parse_options(int argc, const char **argv)
132 OPT_NOOP_NOARG(0, "obsolete"),
133 OPT_STRING_LIST(0, "list", &list, "str", "add str to list"),
134 OPT_GROUP("Magic arguments"),
135 - OPT_ARGUMENT("quux", "means --quux"),
135 + OPT_ARGUMENT("quux", NULL, "means --quux"),
136 OPT_NUMBER_CALLBACK(&integer, "set integer to NUM",
137 number_callback),
138 { OPTION_COUNTUP, '+', NULL, &boolean, NULL, "same as -b",