1 | #!/usr/bin/env bash
|
2 | #
|
3 | # Common shell functions for task scripts.
|
4 | #
|
5 | # Usage:
|
6 | # source $LIB_OSH/task-five.sh
|
7 | #
|
8 | # test-foo() { # define task functions
|
9 | # echo foo
|
10 | # }
|
11 | # task-five "$@"
|
12 |
|
13 | # Definition of a "task"
|
14 | #
|
15 | # - File invokes task-five "$@"
|
16 | # - or maybe you can look at its source
|
17 | # - It's a shell function
|
18 | # - Has ### docstring
|
19 | # - Doesn't start with _
|
20 |
|
21 | : ${LIB_OSH=stdlib/osh}
|
22 | source $LIB_OSH/byo-server.sh
|
23 |
|
24 |
|
25 | # List all functions defined in this file (and not in sourced files).
|
26 | _bash-print-funcs() {
|
27 | ### Print shell functions in this file that don't start with _ (bash reflection)
|
28 |
|
29 | local funcs
|
30 | funcs=($(compgen -A function))
|
31 | # extdebug makes `declare -F` print the file path, but, annoyingly, only
|
32 | # if you pass the function names as arguments.
|
33 | shopt -s extdebug
|
34 | declare -F "${funcs[@]}" | grep --fixed-strings " $0" | awk '{print $1}'
|
35 | shopt -u extdebug
|
36 | }
|
37 |
|
38 | _awk-print-funcs() {
|
39 | ### Print shell functions in this file that don't start with _ (awk parsing)
|
40 |
|
41 | # Using gawk because it has match()
|
42 | # - doesn't start with _
|
43 |
|
44 | # space = / ' '* /
|
45 | # shfunc = / %begin
|
46 | # <capture !['_' ' '] ![' ']*>
|
47 | # '()' space '{' space
|
48 | # %end /
|
49 | # docstring = / %begin
|
50 | # space '###' ' '+
|
51 | # <capture dot*>
|
52 | # %end /
|
53 | awk '
|
54 | match($0, /^([^_ ][^ ]*)\(\)[ ]*{[ ]*$/, m) {
|
55 | print NR " shfunc " m[1]
|
56 | #print m[0]
|
57 | }
|
58 |
|
59 | match($0, /^[ ]*###[ ]+(.*)$/, m) {
|
60 | print NR " docstring " m[1]
|
61 | }
|
62 | ' $0
|
63 | }
|
64 |
|
65 | _show-help() {
|
66 | # TODO:
|
67 | # - Use awk to find comments at the top of the file?
|
68 | # - Use OSH to extract docstrings
|
69 | # - BYO_COMMAND=list-tasks will reuse that logic? It only applies to the
|
70 | # current file, not anything in a different file?
|
71 |
|
72 | echo "Usage: $0 TASK_NAME ARGS..."
|
73 | echo
|
74 | echo "To complete tasks, run:"
|
75 | echo " source devtools/completion.bash"
|
76 | echo
|
77 | echo "Tasks:"
|
78 |
|
79 | if command -v column >/dev/null; then
|
80 | _bash-print-funcs | column
|
81 | else
|
82 | _bash-print-funcs
|
83 | fi
|
84 | }
|
85 |
|
86 | task-five() {
|
87 | # Respond to BYO_COMMAND=list-tasks, etc. All task files need this.
|
88 | byo-maybe-run
|
89 |
|
90 | case ${1:-} in
|
91 | ''|--help|-h)
|
92 | _show-help
|
93 | exit 0
|
94 | ;;
|
95 | esac
|
96 |
|
97 | if ! declare -f "$1" >/dev/null; then
|
98 | echo "$0: '$1' isn't an action in this task file. Try '$0 --help'"
|
99 | exit 1
|
100 | fi
|
101 |
|
102 | "$@"
|
103 | }
|