-
Notifications
You must be signed in to change notification settings - Fork 0
/
run_lib.sh
69 lines (58 loc) · 2.14 KB
/
run_lib.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/usr/bin/env bash
#
# Version: v0.1.0
# Author: James Cole
# Email: james@binarism.net
#
# Shows and exectues functions in the sourcing file.
# See https://github.com/jamescoleuk/run_lib for more details.
# Exit the script on any error
set -e
# Shell colour constants for use in 'echo -e'
RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[1;33m'
BLUE='\033[1;34m'
LGREY='\e[37m'
DGREY='\e[90m'
NC='\033[0m' # No colour
show_help() {
# Get the full name of the file sourcing this one.
this_script="$(pwd)/`basename "$0"`"
# Two things happening here:
# 1. grep the sourcing file to get lines with functions on them
# 2. get rid of white-space, which will cause extra elements in the array
# No idea why shellcheck is complaining.
functions=($(grep -n '^[A-Za-z0-9 -_]*()[ ]*{' ${this_script} | tr -d ' '))
# That was easy, but we also want comments for each function.
for i in "${functions[@]}"
do
# Pull out the line number from the grep
IFS=: read line_number rest <<< $i
# Just keep the function name.
# TODO: use a capture group in the original grep. This would avoid the tr too.
function_name=$(sed 's/(){$//' <<< $rest)
# Ignore any function that starts with _
if [[ $function_name != _* ]];
then
# This $((...)) bullshit is the "arithmetic expansion operator".
# Bash treats things as strings or numbers depending on context,
# so we need to use this operator to treat $line_number as a number.
previous_line_number=$(($line_number-1))
# sed out the previous line, to use as a comment
# TODO: what about sedding out all previous commented lines?
previous_line=$(sed "${previous_line_number}q;d" ${this_script})
# TODO Check that the previous line is in fact a comment
output="${output}\n${YELLOW}${function_name}${NC}+++${BLUE}${previous_line}${NC}"
fi
done
echo -e "${LGREY}The following functions are available:${NC}"
echo -e ${output} | column -t -s+++
}
# If there aren't any arguments then display the help.
if [ $# -eq 0 ]; then
show_help "$@"
else
# This will call the first argument as a function, passing in the subsequent arguments
"$@"
fi