interplane.Get Omega
Read in your language

git

[Ported from github.com/git/git] Sync with Git 2.56.1

Brought by drakestapleton

branch master Branches Tags History

git / Documentation / technical / api-parse-options.adoc

433 lines · 16207 bytes Raw Blame History
1parse-options API
2=================
3
4The parse-options API is used to parse and massage options in Git
5and to provide a usage help with consistent look.
6
7Basics
8------
9
10The argument vector `argv[]` may usually contain mandatory or optional
11'non-option arguments', e.g. a filename or a branch, 'options', and
12'subcommands'.
13Options are optional arguments that start with a dash and
14that allow to change the behavior of a command.
15
16* There are basically three types of options:
17 'boolean' options,
18 options with (mandatory) 'arguments' and
19 options with 'optional arguments'
20 (i.e. a boolean option that can be adjusted).
21
22* There are basically two forms of options:
23 'Short options' consist of one dash (`-`) and one alphanumeric
24 character.
25 'Long options' begin with two dashes (`--`) and some
26 alphanumeric characters.
27
28* Options are case-sensitive.
29 Please define 'lower-case long options' only.
30
31The parse-options API allows:
32
33* 'stuck' and 'separate form' of options with arguments.
34 `-oArg` is stuck, `-o Arg` is separate form.
35 `--option=Arg` is stuck, `--option Arg` is separate form.
36
37* Long options may be 'abbreviated', as long as the abbreviation
38 is unambiguous.
39
40* Short options may be bundled, e.g. `-a -b` can be specified as `-ab`.
41
42* Boolean long options can be 'negated' (or 'unset') by prepending
43 `no-`, e.g. `--no-abbrev` instead of `--abbrev`. Conversely,
44 options that begin with `no-` can be 'negated' by removing it.
45 Other long options can be unset (e.g., set string to NULL, set
46 integer to 0) by prepending `no-`.
47
48* Options and non-option arguments can clearly be separated using the `--`
49 option, e.g. `-a -b --option -- --this-is-a-file` indicates that
50 `--this-is-a-file` must not be processed as an option.
51
52Subcommands are special in a couple of ways:
53
54* Subcommands only have long form, and they have no double dash prefix, no
55 negated form, and no description, and they don't take any arguments, and
56 can't be abbreviated.
57
58* There must be exactly one subcommand among the arguments, or zero if the
59 command has a default operation mode.
60
61* All arguments following the subcommand are considered to be arguments of
62 the subcommand, and, conversely, arguments meant for the subcommand may
63 not precede the subcommand.
64
65Therefore, if the options array contains at least one subcommand and
66`parse_options()` encounters the first dashless argument, it will either:
67
68* stop and return, if that dashless argument is a known subcommand, setting
69 `value` to the function pointer associated with that subcommand, storing
70 the name of the subcommand in argv[0], and leaving the rest of the
71 arguments unprocessed, or
72
73* stop and return, if it was invoked with the `PARSE_OPT_SUBCOMMAND_OPTIONAL`
74 flag and that dashless argument doesn't match any subcommands, leaving
75 `value` unchanged and the rest of the arguments unprocessed, or
76
77* show error and usage, and abort.
78
79Steps to parse options
80----------------------
81
82. `#include "parse-options.h"`
83
84. define a NULL-terminated
85 `static const char * const builtin_foo_usage[]` array
86 containing alternative usage strings
87
88. define `builtin_foo_options` array as described below
89 in section 'Data Structure'.
90
91. in `cmd_foo(int argc, const char **argv, const char *prefix)`
92 call
93
94 argc = parse_options(argc, argv, prefix, builtin_foo_options, builtin_foo_usage, flags);
95+
96`parse_options()` will filter out the processed options of `argv[]` and leave the
97non-option arguments in `argv[]`.
98`argc` is updated appropriately because of the assignment.
99+
100You can also pass NULL instead of a usage array as the fifth parameter of
101parse_options(), to avoid displaying a help screen with usage info and
102option list. This should only be done if necessary, e.g. to implement
103a limited parser for only a subset of the options that needs to be run
104before the full parser, which in turn shows the full help message.
105+
106Flags are the bitwise-or of:
107
108`PARSE_OPT_KEEP_DASHDASH`::
109 Keep the `--` that usually separates options from
110 non-option arguments.
111
112`PARSE_OPT_STOP_AT_NON_OPTION`::
113 Usually the whole argument vector is massaged and reordered.
114 Using this flag, processing is stopped at the first non-option
115 argument.
116
117`PARSE_OPT_KEEP_ARGV0`::
118 Keep the first argument, which contains the program name. It's
119 removed from argv[] by default.
120
121`PARSE_OPT_KEEP_UNKNOWN_OPT`::
122 Keep unknown options instead of erroring out. This doesn't
123 work for all combinations of arguments as users might expect
124 it to do. E.g. if the first argument in `--unknown --known`
125 takes a value (which we can't know), the second one is
126 mistakenly interpreted as a known option. Similarly, if
127 `PARSE_OPT_STOP_AT_NON_OPTION` is set, the second argument in
128 `--unknown value` will be mistakenly interpreted as a
129 non-option, not as a value belonging to the unknown option,
130 the parser early. That's why parse_options() errors out if
131 both options are set.
132 Note that non-option arguments are always kept, even without
133 this flag.
134
135`PARSE_OPT_NO_INTERNAL_HELP`::
136 By default, parse_options() handles `-h`, `--help` and
137 `--help-all` internally, by showing a help screen. This option
138 turns it off and allows one to add custom handlers for these
139 options, or to just leave them unknown.
140
141`PARSE_OPT_SUBCOMMAND_OPTIONAL`::
142 Don't error out when no subcommand is specified.
143
144Note that `PARSE_OPT_STOP_AT_NON_OPTION` is incompatible with subcommands;
145while `PARSE_OPT_KEEP_DASHDASH` and `PARSE_OPT_KEEP_UNKNOWN_OPT` can only be
146used with subcommands when combined with `PARSE_OPT_SUBCOMMAND_OPTIONAL`.
147
148Data Structure
149--------------
150
151The main data structure is an array of the `option` struct,
152say `static struct option builtin_add_options[]`.
153
154Option flags
155~~~~~~~~~~~~
156
157Each option can carry flags in the `flags` field of its `option`
158struct. These are per-option flags and are distinct from the
159`parse_options()` flags described above; they are usually set through
160the `OPT_*_F()` macro variants (see below) rather than by hand. They
161are the bitwise-or of:
162
163`PARSE_OPT_OPTARG`::
164 The option's argument is optional, i.e. both `--option` and
165 `--option=<value>` are accepted.
166
167`PARSE_OPT_NOARG`::
168 The option takes no argument at all. Using `--option=<value>`
169 is rejected.
170
171`PARSE_OPT_NONEG`::
172 Disable the automatically generated negated `--no-option`
173 form.
174
175`PARSE_OPT_HIDDEN`::
176 Hide the option: it is omitted from the usage shown by
177 `git <cmd> -h`, but is still shown by `git <cmd> --help-all`.
178 The option is parsed as usual either way. This is meant for
179 deprecated, advanced or otherwise uncommon options.
180
181`PARSE_OPT_LASTARG_DEFAULT`::
182 The no-argument form is only accepted when the option is the
183 last token on the command line; used earlier, it still
184 requires an argument. Should not be combined with
185 `PARSE_OPT_OPTARG`.
186
187`PARSE_OPT_NODASH`::
188 The option is a single character without a leading dash, such
189 as the `+` used by some commands.
190
191`PARSE_OPT_LITERAL_ARGHELP`::
192 Use the argument help string (`argh`) verbatim in the usage
193 output instead of surrounding it with `<>` or `[]`. Useful when
194 `argh` already contains a hand-formatted description.
195
196`PARSE_OPT_FROM_ALIAS`::
197 Internal flag, set on options that were expanded from a
198 configured alias. It should not be set by callers.
199
200`PARSE_OPT_NOCOMPLETE`::
201 Do not offer this option for completion.
202
203`PARSE_OPT_COMP_ARG`::
204 The option's argument, rather than the option itself, is what
205 should be completed.
206
207`PARSE_OPT_CMDMODE`::
208 The option is one of several mutually exclusive "command mode"
209 options that share the same variable. Using more than one of
210 them at once is rejected.
211
212Macros
213~~~~~~
214
215There are some macros to easily define options:
216
217Many of the macros below have an `_F` variant (for example `OPT_BOOL_F`,
218`OPT_STRING_F`, `OPT_INTEGER_F`, `OPT_SET_INT_F`, `OPT_BIT_F` and
219`OPT_CALLBACK_F`) that takes an additional trailing `flags` argument.
220That argument is the bitwise-or of the per-option flags described in the
221"Option flags" section above; the non-`_F` macros are simply defined
222with `flags` set to `0`.
223
224`OPT__ABBREV(&int_var)`::
225 Add `--abbrev[=<n>]`.
226
227`OPT__COLOR(&int_var, description)`::
228 Add `--color[=<when>]` and `--no-color`.
229
230`OPT__DRY_RUN(&int_var, description)`::
231 Add `-n, --dry-run`.
232
233`OPT__FORCE(&int_var, description)`::
234 Add `-f, --force`.
235
236`OPT__QUIET(&int_var, description)`::
237 Add `-q, --quiet`.
238
239`OPT__VERBOSE(&int_var, description)`::
240 Add `-v, --verbose`.
241
242`OPT_GROUP(description)`::
243 Start an option group. `description` is a short string that
244 describes the group or an empty string.
245 Start the description with an upper-case letter.
246 Groups apply to options and subcommands that have a help string.
247
248`OPT_HIDDEN_GROUP(description)`::
249 Like `OPT_GROUP()`, but the group header carries
250 `PARSE_OPT_HIDDEN`, so it is only shown by `--help-all` and not
251 by `-h`. Use it to label a group that contains only hidden
252 options, which would otherwise show an empty header under `-h`.
253
254`OPT_BOOL(short, long, &int_var, description)`::
255 Introduce a boolean option. `int_var` is set to one with
256 `--option` and set to zero with `--no-option`.
257
258`OPT_HIDDEN_BOOL(short, long, &int_var, description)`::
259 Like `OPT_BOOL()`, but the option carries `PARSE_OPT_HIDDEN`,
260 so it is hidden from `-h` while still being shown by
261 `--help-all`.
262
263`OPT_COUNTUP(short, long, &int_var, description)`::
264 Introduce a count-up option.
265 Each use of `--option` increments `int_var`, starting from zero
266 (even if initially negative), and `--no-option` resets it to
267 zero. To determine if `--option` or `--no-option` was encountered at
268 all, initialize `int_var` to a negative value, and if it is still
269 negative after parse_options(), then neither `--option` nor
270 `--no-option` was seen.
271
272`OPT_BIT(short, long, &int_var, description, mask)`::
273 Introduce a boolean option.
274 If used, `int_var` is bitwise-ored with `mask`.
275
276`OPT_NEGBIT(short, long, &int_var, description, mask)`::
277 Introduce a boolean option.
278 If used, `int_var` is bitwise-anded with the inverted `mask`.
279
280`OPT_SET_INT(short, long, &int_var, description, integer)`::
281 Introduce an integer option.
282 `int_var` is set to `integer` with `--option`, and
283 reset to zero with `--no-option`.
284
285`OPT_STRING(short, long, &str_var, arg_str, description)`::
286 Introduce an option with string argument.
287 The string argument is put into `str_var`.
288
289`OPT_STRING_LIST(short, long, &struct string_list, arg_str, description)`::
290 Introduce an option with string argument.
291 The string argument is stored as an element in `string_list`.
292 Use of `--no-option` will clear the list of preceding values.
293
294`OPT_INTEGER(short, long, &int_var, description)`::
295 Introduce an option with integer argument. The argument must be a
296 integer and may include a suffix of 'k', 'm' or 'g' to
297 scale the provided value by 1024, 1024^2 or 1024^3 respectively.
298 The scaled value is put into `int_var`.
299
300`OPT_UNSIGNED(short, long, &unsigned_long_var, description)`::
301 Introduce an option with an unsigned integer argument. The argument must be a
302 non-negative integer and may include a suffix of 'k', 'm' or 'g' to
303 scale the provided value by 1024, 1024^2 or 1024^3 respectively.
304 The scaled value is put into `unsigned_long_var`.
305
306`OPT_EXPIRY_DATE(short, long, &timestamp_t_var, description)`::
307 Introduce an option with expiry date argument, see `parse_expiry_date()`.
308 The timestamp is put into `timestamp_t_var`.
309
310`OPT_CALLBACK(short, long, &var, arg_str, description, func_ptr)`::
311 Introduce an option with argument.
312 The argument will be fed into the function given by `func_ptr`
313 and the result will be put into `var`.
314 See 'Option Callbacks' below for a more elaborate description.
315
316`OPT_FILENAME(short, long, &var, description)`::
317 Introduce an option with a filename argument.
318 The filename will be prefixed by passing the filename along with
319 the prefix argument of `parse_options()` to `prefix_filename()`.
320
321`OPT_NUMBER_CALLBACK(&var, description, func_ptr)`::
322 Recognize numerical options like -123 and feed the integer as
323 if it was an argument to the function given by `func_ptr`.
324 The result will be put into `var`. There can be only one such
325 option definition. It cannot be negated and it takes no
326 arguments. Short options that happen to be digits take
327 precedence over it.
328
329`OPT_COLOR_FLAG(short, long, &int_var, description)`::
330 Introduce an option that takes an optional argument that can
331 have one of three values: "always", "never", or "auto". If the
332 argument is not given, it defaults to "always". The `--no-` form
333 works like `--long=never`; it cannot take an argument. If
334 "always", set `int_var` to 1; if "never", set `int_var` to 0; if
335 "auto", set `int_var` to 1 if stdout is a tty or a pager,
336 0 otherwise.
337
338`OPT_NOOP_NOARG(short, long)`::
339 Introduce an option that has no effect and takes no arguments.
340 Use it to hide deprecated options that are still to be recognized
341 and ignored silently.
342
343`OPT_PASSTHRU(short, long, &char_var, arg_str, description, flags)`::
344 Introduce an option that will be reconstructed into a char* string,
345 which must be initialized to NULL. This is useful when you need to
346 pass the command-line option to another command. Any previous value
347 will be overwritten, so this should only be used for options where
348 the last one specified on the command line wins.
349
350`OPT_PASSTHRU_ARGV(short, long, &strvec_var, arg_str, description, flags)`::
351 Introduce an option where all instances of it on the command-line will
352 be reconstructed into a strvec. This is useful when you need to
353 pass the command-line option, which can be specified multiple times,
354 to another command.
355
356`OPT_CMDMODE(short, long, &int_var, description, enum_val)`::
357 Define an "operation mode" option, only one of which in the same
358 group of "operating mode" options that share the same `int_var`
359 can be given by the user. `int_var` is set to `enum_val` when the
360 option is used, but an error is reported if other "operating mode"
361 option has already set its value to the same `int_var`.
362 In new commands consider using subcommands instead.
363
364`OPT_SUBCOMMAND(long, &fn_ptr, subcommand_fn)`::
365 Define a subcommand. `subcommand_fn` is put into `fn_ptr` when
366 this subcommand is used. The subcommand is not listed in the
367 usage output.
368
369The last element of the array must be `OPT_END()`.
370
371If not stated otherwise, interpret the arguments as follows:
372
373* `short` is a character for the short option
374 (e.g. `'e'` for `-e`, use `0` to omit),
375
376* `long` is a string for the long option
377 (e.g. `"example"` for `--example`, use `NULL` to omit),
378
379* `int_var` is an integer variable,
380
381* `str_var` is a string variable (`char *`),
382
383* `arg_str` is the string that is shown as argument
384 (e.g. `"branch"` will result in `<branch>`).
385 If set to `NULL`, three dots (`...`) will be displayed.
386
387* `description` is a short string to describe the effect of the option.
388 It shall begin with a lower-case letter and a full stop (`.`) shall be
389 omitted at the end.
390
391Option Callbacks
392----------------
393
394The function must be defined in this form:
395
396 int func(const struct option *opt, const char *arg, int unset)
397
398The callback mechanism is as follows:
399
400* Inside `func`, the only interesting member of the structure
401 given by `opt` is the void pointer `opt->value`.
402 `*opt->value` will be the value that is saved into `var`, if you
403 use `OPT_CALLBACK()`.
404 For example, do `*(unsigned long *)opt->value = 42;` to get 42
405 into an `unsigned long` variable.
406
407* Return value `0` indicates success and non-zero return
408 value will invoke `usage_with_options()` and, thus, die.
409
410* If the user negates the option, `arg` is `NULL` and `unset` is 1.
411
412Sophisticated option parsing
413----------------------------
414
415If you need, for example, option callbacks with optional arguments
416or without arguments at all, or if you need other special cases,
417that are not handled by the macros above, you need to specify the
418members of the `option` structure manually.
419
420This is not covered in this document, but well documented
421in `parse-options.h` itself.
422
423Examples
424--------
425
426See `test-parse-options.c` and
427`builtin/add.c`,
428`builtin/clone.c`,
429`builtin/commit.c`,
430`builtin/fetch.c`,
431`builtin/fsck.c`,
432`builtin/rm.c`
433for real-world examples.