OILS / stdlib / osh / task-five.sh View on Github | oilshell.org

78 lines, 33 significant
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# List all functions defined in this file (and not in sourced files).
22_bash-print-funcs() {
23 ### Print shell functions in this file that don't start with _ (bash reflection)
24
25 local funcs=($(compgen -A function))
26 # extdebug makes `declare -F` print the file path, but, annoyingly, only
27 # if you pass the function names as arguments.
28 shopt -s extdebug
29 declare -F "${funcs[@]}" | grep --fixed-strings " $0" | awk '{print $1}'
30 shopt -u extdebug
31}
32
33_awk-print-funcs() {
34 ### Print shell functions in this file that don't start with _ (awk parsing)
35
36 # Using gawk because it has match()
37 # - doesn't start with _
38
39 awk '
40 match($0, /^([^_ ][^ ]*)\(\)[ ]?{/, m) {
41 print m[1]
42 #print m[0]
43 }
44' $0
45}
46
47_show-help() {
48 # TODO:
49 # - Use awk to find comments at the top of the file?
50 # - Use OSH to extract docstrings
51
52 echo "Usage: $0 TASK_NAME ARGS..."
53 echo
54 echo "To complete tasks, run:"
55 echo " source devtools/completion.bash"
56 echo
57 echo "Tasks:"
58
59 if command -v column >/dev/null; then
60 _bash-print-funcs | column
61 else
62 _bash-print-funcs
63 fi
64}
65
66task-five() {
67 if [[ $# -eq 0 || $1 =~ ^(--help|-h)$ ]]; then
68 _show-help
69 exit
70 fi
71
72 if ! declare -f "$1" >/dev/null; then
73 echo "$0: '$1' isn't an action in this task file. Try '$0 --help'"
74 exit 1
75 fi
76
77 "$@"
78}