Debian Codegraph @

build-aux/options-parser

raw
1 #! /bin/sh
2
3 # A portable, pluggable option parser for Bourne shell.
4 # Written by Gary V. Vaughan, 2010
5
6 # This is free software. There is NO warranty; not even for
7 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
8 #
9 # Copyright (C) 2010-2019, 2021, 2023 Bootstrap Authors
10 #
11 # This file is dual licensed under the terms of the MIT license
12 # <https://opensource.org/licenses/MIT>, and GPL version 2 or later
13 # <https://www.gnu.org/licenses/gpl-2.0.html>. You must apply one of
14 # these licenses when using or redistributing this software or any of
15 # the files within it. See the URLs above, or the file `LICENSE`
16 # included in the Bootstrap distribution for the full license texts.
17
18 # Please report bugs or propose patches to:
19 # <https://github.com/gnulib-modules/bootstrap/issues>
20
21 # Set a version string for this script.
22 scriptversion=2019-02-19.15; # UTC
23
24
25 ## ------ ##
26 ## Usage. ##
27 ## ------ ##
28
29 # This file is a library for parsing options in your shell scripts along
30 # with assorted other useful supporting features that you can make use
31 # of too.
32 #
33 # For the simplest scripts you might need only:
34 #
35 # #!/bin/sh
36 # . relative/path/to/funclib.sh
37 # . relative/path/to/options-parser
38 # scriptversion=1.0
39 # func_options ${1+"$@"}
40 # eval set dummy "$func_options_result"; shift
41 # ...rest of your script...
42 #
43 # In order for the '--version' option to work, you will need to have a
44 # suitably formatted comment like the one at the top of this file
45 # starting with '# Written by ' and ending with '# Copyright'.
46 #
47 # For '-h' and '--help' to work, you will also need a one line
48 # description of your script's purpose in a comment directly above the
49 # '# Written by ' line, like the one at the top of this file.
50 #
51 # The default options also support '--debug', which will turn on shell
52 # execution tracing (see the comment above debug_cmd below for another
53 # use), and '--verbose' and the func_verbose function to allow your script
54 # to display verbose messages only when your user has specified
55 # '--verbose'.
56 #
57 # After sourcing this file, you can plug in processing for additional
58 # options by amending the variables from the 'Configuration' section
59 # below, and following the instructions in the 'Option parsing'
60 # section further down.
61
62 ## -------------- ##
63 ## Configuration. ##
64 ## -------------- ##
65
66 # You should override these variables in your script after sourcing this
67 # file so that they reflect the customisations you have added to the
68 # option parser.
69
70 # The usage line for option parsing errors and the start of '-h' and
71 # '--help' output messages. You can embed shell variables for delayed
72 # expansion at the time the message is displayed, but you will need to
73 # quote other shell meta-characters carefully to prevent them being
74 # expanded when the contents are evaled.
75 usage='$progpath [OPTION]...'
76
77 # Short help message in response to '-h' and '--help'. Add to this or
78 # override it after sourcing this library to reflect the full set of
79 # options your script accepts.
80 usage_message="\
81 --debug enable verbose shell tracing
82 -W, --warnings=CATEGORY
83 report the warnings falling in CATEGORY [all]
84 -v, --verbose verbosely report processing
85 --version print version information and exit
86 -h, --help print short or long help message and exit
87 "
88
89 # Additional text appended to 'usage_message' in response to '--help'.
90 long_help_message="
91 Warning categories include:
92 'all' show all warnings
93 'none' turn off all the warnings
94 'error' warnings are treated as fatal errors"
95
96 # Help message printed before fatal option parsing errors.
97 fatal_help="Try '\$progname --help' for more information."
98
99
100
101 ## ------------------------- ##
102 ## Hook function management. ##
103 ## ------------------------- ##
104
105 # This section contains functions for adding, removing, and running hooks
106 # in the main code. A hook is just a list of function names that can be
107 # run in order later on.
108
109 # func_hookable FUNC_NAME
110 # -----------------------
111 # Declare that FUNC_NAME will run hooks added with
112 # 'func_add_hook FUNC_NAME ...'.
113 func_hookable ()
114 {
115 $debug_cmd
116
117 func_append hookable_fns " $1"
118 }
119
120
121 # func_add_hook FUNC_NAME HOOK_FUNC
122 # ---------------------------------
123 # Request that FUNC_NAME call HOOK_FUNC before it returns. FUNC_NAME must
124 # first have been declared "hookable" by a call to 'func_hookable'.
125 func_add_hook ()
126 {
127 $debug_cmd
128
129 case " $hookable_fns " in
130 *" $1 "*) ;;
131 *) func_fatal_error "'$1' does not accept hook functions." ;;
132 esac
133
134 eval func_append ${1}_hooks '" $2"'
135 }
136
137
138 # func_remove_hook FUNC_NAME HOOK_FUNC
139 # ------------------------------------
140 # Remove HOOK_FUNC from the list of hook functions to be called by
141 # FUNC_NAME.
142 func_remove_hook ()
143 {
144 $debug_cmd
145
146 eval ${1}_hooks='`$ECHO "\$'$1'_hooks" |$SED "s| '$2'||"`'
147 }
148
149
150 # func_propagate_result FUNC_NAME_A FUNC_NAME_B
151 # ---------------------------------------------
152 # If the *_result variable of FUNC_NAME_A _is set_, assign its value to
153 # *_result variable of FUNC_NAME_B.
154 func_propagate_result ()
155 {
156 $debug_cmd
157
158 func_propagate_result_result=:
159 if eval "test \"\${${1}_result+set}\" = set"
160 then
161 eval "${2}_result=\$${1}_result"
162 else
163 func_propagate_result_result=false
164 fi
165 }
166
167
168 # func_run_hooks FUNC_NAME [ARG]...
169 # ---------------------------------
170 # Run all hook functions registered to FUNC_NAME.
171 # It's assumed that the list of hook functions contains nothing more
172 # than a whitespace-delimited list of legal shell function names, and
173 # no effort is wasted trying to catch shell meta-characters or preserve
174 # whitespace.
175 func_run_hooks ()
176 {
177 $debug_cmd
178
179 case " $hookable_fns " in
180 *" $1 "*) ;;
181 *) func_fatal_error "'$1' does not support hook functions." ;;
182 esac
183
184 eval _G_hook_fns=\$$1_hooks; shift
185
186 for _G_hook in $_G_hook_fns; do
187 func_unset "${_G_hook}_result"
188 eval $_G_hook '${1+"$@"}'
189 func_propagate_result $_G_hook func_run_hooks
190 if $func_propagate_result_result; then
191 eval set dummy "$func_run_hooks_result"; shift
192 fi
193 done
194 }
195
196
197
198 ## --------------- ##
199 ## Option parsing. ##
200 ## --------------- ##
201
202 # In order to add your own option parsing hooks, you must accept the
203 # full positional parameter list from your hook function. You may remove
204 # or edit any options that you action, and then pass back the remaining
205 # unprocessed options in '<hooked_function_name>_result', escaped
206 # suitably for 'eval'.
207 #
208 # The '<hooked_function_name>_result' variable is automatically unset
209 # before your hook gets called; for best performance, only set the
210 # *_result variable when necessary (i.e. don't call the 'func_quote'
211 # function unnecessarily because it can be an expensive operation on some
212 # machines).
213 #
214 # Like this:
215 #
216 # my_options_prep ()
217 # {
218 # $debug_cmd
219 #
220 # # Extend the existing usage message.
221 # usage_message=$usage_message'
222 # -s, --silent don'\''t print informational messages
223 # '
224 # # No change in '$@' (ignored completely by this hook). Leave
225 # # my_options_prep_result variable intact.
226 # }
227 # func_add_hook func_options_prep my_options_prep
228 #
229 #
230 # my_silent_option ()
231 # {
232 # $debug_cmd
233 #
234 # args_changed=false
235 #
236 # # Note that, for efficiency, we parse as many options as we can
237 # # recognise in a loop before passing the remainder back to the
238 # # caller on the first unrecognised argument we encounter.
239 # while test $# -gt 0; do
240 # opt=$1; shift
241 # case $opt in
242 # --silent|-s) opt_silent=:
243 # args_changed=:
244 # ;;
245 # # Separate non-argument short options:
246 # -s*) func_split_short_opt "$_G_opt"
247 # set dummy "$func_split_short_opt_name" \
248 # "-$func_split_short_opt_arg" ${1+"$@"}
249 # shift
250 # args_changed=:
251 # ;;
252 # *) # Make sure the first unrecognised option "$_G_opt"
253 # # is added back to "$@" in case we need it later,
254 # # if $args_changed was set to 'true'.
255 # set dummy "$_G_opt" ${1+"$@"}; shift; break ;;
256 # esac
257 # done
258 #
259 # # Only call 'func_quote' here if we processed at least one argument.
260 # if $args_changed; then
261 # func_quote eval ${1+"$@"}
262 # my_silent_option_result=$func_quote_result
263 # fi
264 # }
265 # func_add_hook func_parse_options my_silent_option
266 #
267 #
268 # my_option_validation ()
269 # {
270 # $debug_cmd
271 #
272 # $opt_silent && $opt_verbose && func_fatal_help "\
273 # '--silent' and '--verbose' options are mutually exclusive."
274 # }
275 # func_add_hook func_validate_options my_option_validation
276 #
277 # You'll also need to manually amend $usage_message to reflect the extra
278 # options you parse. It's preferable to append if you can, so that
279 # multiple option parsing hooks can be added safely.
280
281
282 # func_options_finish [ARG]...
283 # ----------------------------
284 # Finishing the option parse loop (call 'func_options' hooks ATM).
285 func_options_finish ()
286 {
287 $debug_cmd
288
289 func_run_hooks func_options ${1+"$@"}
290 func_propagate_result func_run_hooks func_options_finish
291 }
292
293
294 # func_options [ARG]...
295 # ---------------------
296 # All the functions called inside func_options are hookable. See the
297 # individual implementations for details.
298 func_hookable func_options
299 func_options ()
300 {
301 $debug_cmd
302
303 _G_options_quoted=false
304
305 for my_func in options_prep parse_options validate_options options_finish
306 do
307 func_unset func_${my_func}_result
308 func_unset func_run_hooks_result
309 eval func_$my_func '${1+"$@"}'
310 func_propagate_result func_$my_func func_options
311 if $func_propagate_result_result; then
312 eval set dummy "$func_options_result"; shift
313 _G_options_quoted=:
314 fi
315 done
316
317 $_G_options_quoted || {
318 # As we (func_options) are top-level options-parser function and
319 # nobody quoted "$@" for us yet, we need to do it explicitly for
320 # caller.
321 func_quote eval ${1+"$@"}
322 func_options_result=$func_quote_result
323 }
324 }
325
326
327 # func_options_prep [ARG]...
328 # --------------------------
329 # All initialisations required before starting the option parse loop.
330 # Note that when calling hook functions, we pass through the list of
331 # positional parameters. If a hook function modifies that list, and
332 # needs to propagate that back to rest of this script, then the complete
333 # modified list must be put in 'func_run_hooks_result' before returning.
334 func_hookable func_options_prep
335 func_options_prep ()
336 {
337 $debug_cmd
338
339 # Option defaults:
340 opt_verbose=false
341 opt_warning_types=
342
343 func_run_hooks func_options_prep ${1+"$@"}
344 func_propagate_result func_run_hooks func_options_prep
345 }
346
347
348 # func_parse_options [ARG]...
349 # ---------------------------
350 # The main option parsing loop.
351 func_hookable func_parse_options
352 func_parse_options ()
353 {
354 $debug_cmd
355
356 _G_parse_options_requote=false
357 # this just eases exit handling
358 while test $# -gt 0; do
359 # Defer to hook functions for initial option parsing, so they
360 # get priority in the event of reusing an option name.
361 func_run_hooks func_parse_options ${1+"$@"}
362 func_propagate_result func_run_hooks func_parse_options
363 if $func_propagate_result_result; then
364 eval set dummy "$func_parse_options_result"; shift
365 # Even though we may have changed "$@", we passed the "$@" array
366 # down into the hook and it quoted it for us (because we are in
367 # this if-branch). No need to quote it again.
368 _G_parse_options_requote=false
369 fi
370
371 # Break out of the loop if we already parsed every option.
372 test $# -gt 0 || break
373
374 # We expect that one of the options parsed in this function matches
375 # and thus we remove _G_opt from "$@" and need to re-quote.
376 _G_match_parse_options=:
377 _G_opt=$1
378 shift
379 case $_G_opt in
380 --debug|-x) debug_cmd='set -x'
381 func_echo "enabling shell trace mode" >&2
382 $debug_cmd
383 ;;
384
385 --no-warnings|--no-warning|--no-warn)
386 set dummy --warnings none ${1+"$@"}
387 shift
388 ;;
389
390 --warnings|--warning|-W)
391 if test $# = 0 && func_missing_arg $_G_opt; then
392 _G_parse_options_requote=:
393 break
394 fi
395 case " $warning_categories $1" in
396 *" $1 "*)
397 # trailing space prevents matching last $1 above
398 func_append_uniq opt_warning_types " $1"
399 ;;
400 *all)
401 opt_warning_types=$warning_categories
402 ;;
403 *none)
404 opt_warning_types=none
405 warning_func=:
406 ;;
407 *error)
408 opt_warning_types=$warning_categories
409 warning_func=func_fatal_error
410 ;;
411 *)
412 func_fatal_error \
413 "unsupported warning category: '$1'"
414 ;;
415 esac
416 shift
417 ;;
418
419 --verbose|-v) opt_verbose=: ;;
420 --version) func_version ;;
421 -\?|-h) func_usage ;;
422 --help) func_help ;;
423
424 # Separate optargs to long options (plugins may need this):
425 --*=*) func_split_equals "$_G_opt"
426 set dummy "$func_split_equals_lhs" \
427 "$func_split_equals_rhs" ${1+"$@"}
428 shift
429 ;;
430
431 # Separate optargs to short options:
432 -W*)
433 func_split_short_opt "$_G_opt"
434 set dummy "$func_split_short_opt_name" \
435 "$func_split_short_opt_arg" ${1+"$@"}
436 shift
437 ;;
438
439 # Separate non-argument short options:
440 -\?*|-h*|-v*|-x*)
441 func_split_short_opt "$_G_opt"
442 set dummy "$func_split_short_opt_name" \
443 "-$func_split_short_opt_arg" ${1+"$@"}
444 shift
445 ;;
446
447 --) _G_parse_options_requote=: ; break ;;
448 -*) func_fatal_help "unrecognised option: '$_G_opt'" ;;
449 *) set dummy "$_G_opt" ${1+"$@"}; shift
450 _G_match_parse_options=false
451 break
452 ;;
453 esac
454
455 if $_G_match_parse_options; then
456 _G_parse_options_requote=:
457 fi
458 done
459
460 if $_G_parse_options_requote; then
461 # save modified positional parameters for caller
462 func_quote eval ${1+"$@"}
463 func_parse_options_result=$func_quote_result
464 fi
465 }
466
467
468 # func_validate_options [ARG]...
469 # ------------------------------
470 # Perform any sanity checks on option settings and/or unconsumed
471 # arguments.
472 func_hookable func_validate_options
473 func_validate_options ()
474 {
475 $debug_cmd
476
477 # Display all warnings if -W was not given.
478 test -n "$opt_warning_types" || opt_warning_types=" $warning_categories"
479
480 func_run_hooks func_validate_options ${1+"$@"}
481 func_propagate_result func_run_hooks func_validate_options
482
483 # Bail if the options were screwed!
484 $exit_cmd $EXIT_FAILURE
485 }
486
487
488
489 ## ----------------- ##
490 ## Helper functions. ##
491 ## ----------------- ##
492
493 # This section contains the helper functions used by the rest of the
494 # hookable option parser framework in ascii-betical order.
495
496
497 # func_fatal_help ARG...
498 # ----------------------
499 # Echo program name prefixed message to standard error, followed by
500 # a help hint, and exit.
501 func_fatal_help ()
502 {
503 $debug_cmd
504
505 eval \$ECHO \""Usage: $usage"\"
506 eval \$ECHO \""$fatal_help"\"
507 func_error ${1+"$@"}
508 exit $EXIT_FAILURE
509 }
510
511
512 # func_help
513 # ---------
514 # Echo long help message to standard output and exit.
515 func_help ()
516 {
517 $debug_cmd
518
519 func_usage_message
520 $ECHO "$long_help_message"
521 exit 0
522 }
523
524
525 # func_missing_arg ARGNAME
526 # ------------------------
527 # Echo program name prefixed message to standard error and set global
528 # exit_cmd.
529 func_missing_arg ()
530 {
531 $debug_cmd
532
533 func_error "Missing argument for '$1'."
534 exit_cmd=exit
535 }
536
537
538 # func_split_equals STRING
539 # ------------------------
540 # Set func_split_equals_lhs and func_split_equals_rhs shell variables
541 # after splitting STRING at the '=' sign.
542 test -z "$_G_HAVE_XSI_OPS" \
543 && (eval 'x=a/b/c;
544 test 5aa/bb/cc = "${#x}${x%%/*}${x%/*}${x#*/}${x##*/}"') 2>/dev/null \
545 && _G_HAVE_XSI_OPS=yes
546
547 if test yes = "$_G_HAVE_XSI_OPS"
548 then
549 # This is an XSI compatible shell, allowing a faster implementation...
550 eval 'func_split_equals ()
551 {
552 $debug_cmd
553
554 func_split_equals_lhs=${1%%=*}
555 func_split_equals_rhs=${1#*=}
556 if test "x$func_split_equals_lhs" = "x$1"; then
557 func_split_equals_rhs=
558 fi
559 }'
560 else
561 # ...otherwise fall back to using expr, which is often a shell builtin.
562 func_split_equals ()
563 {
564 $debug_cmd
565
566 func_split_equals_lhs=`expr "x$1" : 'x\([^=]*\)'`
567 func_split_equals_rhs=
568 test "x$func_split_equals_lhs=" = "x$1" \
569 || func_split_equals_rhs=`expr "x$1" : 'x[^=]*=\(.*\)$'`
570 }
571 fi #func_split_equals
572
573
574 # func_split_short_opt SHORTOPT
575 # -----------------------------
576 # Set func_split_short_opt_name and func_split_short_opt_arg shell
577 # variables after splitting SHORTOPT after the 2nd character.
578 if test yes = "$_G_HAVE_XSI_OPS"
579 then
580 # This is an XSI compatible shell, allowing a faster implementation...
581 eval 'func_split_short_opt ()
582 {
583 $debug_cmd
584
585 func_split_short_opt_arg=${1#??}
586 func_split_short_opt_name=${1%"$func_split_short_opt_arg"}
587 }'
588 else
589 # ...otherwise fall back to using expr, which is often a shell builtin.
590 func_split_short_opt ()
591 {
592 $debug_cmd
593
594 func_split_short_opt_name=`expr "x$1" : 'x\(-.\)'`
595 func_split_short_opt_arg=`expr "x$1" : 'x-.\(.*\)$'`
596 }
597 fi #func_split_short_opt
598
599
600 # func_usage
601 # ----------
602 # Echo short help message to standard output and exit.
603 func_usage ()
604 {
605 $debug_cmd
606
607 func_usage_message
608 $ECHO "Run '$progname --help |${PAGER-more}' for full usage"
609 exit 0
610 }
611
612
613 # func_usage_message
614 # ------------------
615 # Echo short help message to standard output.
616 func_usage_message ()
617 {
618 $debug_cmd
619
620 eval \$ECHO \""Usage: $usage"\"
621 echo
622 $SED -n 's|^# ||
623 /^Written by/{
624 x;p;x
625 }
626 h
627 /^Written by/q' < "$progpath"
628 echo
629 eval \$ECHO \""$usage_message"\"
630 }
631
632
633 # func_version
634 # ------------
635 # Echo version message to standard output and exit.
636 # The version message is extracted from the calling file's header
637 # comments, with leading '# ' stripped:
638 # 1. First display the progname and version
639 # 2. Followed by the header comment line matching /^# Written by /
640 # 3. Then a blank line followed by the first following line matching
641 # /^# Copyright /
642 # 4. Immediately followed by any lines between the previous matches,
643 # except lines preceding the intervening completely blank line.
644 # For example, see the header comments of this file.
645 func_version ()
646 {
647 $debug_cmd
648
649 printf '%s\n' "$progname $scriptversion"
650 $SED -n '
651 /^# Written by /!b
652 s|^# ||; p; n
653
654 :fwd2blnk
655 /./ {
656 n
657 b fwd2blnk
658 }
659 p; n
660
661 :holdwrnt
662 s|^# ||
663 s|^# *$||
664 /^Copyright /!{
665 /./H
666 n
667 b holdwrnt
668 }
669
670 s|\((C)\)[ 0-9,-]*[ ,-]\([1-9][0-9]* \)|\1 \2|
671 G
672 s|\(\n\)\n*|\1|g
673 p; q' < "$progpath"
674
675 exit $?
676 }
677
678
679 # Local variables:
680 # mode: shell-script
681 # sh-indentation: 2
682 # eval: (add-hook 'before-save-hook 'time-stamp)
683 # time-stamp-pattern: "30/scriptversion=%:y-%02m-%02d.%02H; # UTC"
684 # time-stamp-time-zone: "UTC"
685 # End: