-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path_common
93 lines (79 loc) · 2.36 KB
/
_common
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
_COMMON_DIR_ON_LOAD=$(pwd)
_COMMON_DEFAULT_WORKDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )/../data" >/dev/null 2>&1 && pwd )"
_COMMON_CALLER_0=($(caller 0))
_COMMON_INCLUDE_SCRIPT_DIR="$(cd "$( dirname "${_COMMON_CALLER_0[2]}")" >/dev/null 2>&1 && pwd )"
# simple function, prints run commands
# to help to user understand what is happening
#
# Setting DRY_RUN will not run the command but print it
# Setting DEBUG_STEPS will wait for input by user before running command
# to help debug.
@exec() {
echo "> $@"
if [ ! -z ${DEBUG+x} ]; then
echo "cd $(pwd)" >> $(@run_dir)/commands.log
echo "$@" >> $(@run_dir)/commands.log
fi
local run_command=y
[ ! -z ${DEBUG_STEPS+x} ] && read -p "(dir:$(pwd)) Run command? [y/n]" run_command </dev/tty
[ ! -z ${DRY_RUN+x} ] && run_command=n
if [[ ! "$run_command" =~ ^[Nn]$ ]]; then
eval $@
return $?
fi
}
# print error kill, script and print call stack
die() {
echo -e "ERROR: $@"
# build and print stacktrace with caller
local cur_call=(${LINENO} ${FUNCNAME[0]} ${BASH_SOURCE[0]})
local i=0
while [[ ! -z "${cur_call[@]}" ]]; do
echo " ${cur_call[2]}:${cur_call[0]} - ${cur_call[1]}"
cur_call=($(caller $i))
i=$((i+1))
done
exit 1
}
# load file from inside script folder
# prefixes name with '@script_dir/_'
@load() {
. "$(@script_dir)/_$1"
}
# return workdir, defaults to {repo}/data, can be overriden
# by setting WORKDIR or passing the first arg
@workdir() {
if [[ ! -z "$1" ]]; then
echo "set WORKDIR"
WORKDIR="$1"
fi
if [ -z ${WORKDIR+x} ]; then
echo $_COMMON_DEFAULT_WORKDIR
else
echo $WORKDIR
fi
}
# return dir of file in which this function was called from
@include_dir() {
echo $_COMMON_INCLUDE_SCRIPT_DIR
}
# return script directory
@script_dir() {
echo "$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
}
# return location from which the script has been run
# !IMPORTANT: _common needs to be included first if that should work
@run_dir() {
echo "${_COMMON_DIR_ON_LOAD}"
}
# runs provided command if first argument is not a command
@run_on_missing() {
COMMAND="$1"
shift
RUN_ON_FAIL="$@"
if ! command -v "$COMMAND" &> /dev/null
then
echo "command '${COMMAND}' not found"
$RUN_ON_FAIL
fi
}