Project

General

Profile

1
#!/bin/bash -e
2
set -o errexit # in case caller did not have -e in #! line
3

    
4
if test ! "$_util_sh_include_guard_utils"; then
5
_util_sh_include_guard_utils=1
6

    
7
function extern () { (exec "$@") || return; }
8

    
9
isset () { test -n "${!1+isset}"; }
10

    
11
realpath () { readlink -f -- "$1"; }
12

    
13
include_guard_var () { realpath "$1"|"extern" sed 's/[^a-zA-Z0-9_]/_/g'; }
14

    
15
self_not_included () # usage: if self_not_included; then ... fi
16
{
17
	test $# -ge 1 || set -- "${BASH_SOURCE[1]}"
18
	local include_guard="$(include_guard_var "$1")"
19
	alias self_being_included=false
20
	! isset "$include_guard" && \
21
	{ eval "$include_guard"=1; alias self_being_included=true; }
22
}
23

    
24
# to load newly-defined aliases for use in functions in the same file:
25
## fi # load new aliases
26
## if self_being_included; then
27
# this is needed because aliases defined inside an if statement are not
28
# available inside that if statement
29

    
30
fi
31

    
32

    
33
if self_not_included "${BASH_SOURCE[0]}"; then
34

    
35

    
36
#### options
37

    
38
shopt -s expand_aliases
39

    
40

    
41
#### aliases
42

    
43
unalias () { builtin unalias "$@" 2>&- || true; } # no error if undefined
44

    
45

    
46
#### exceptions
47

    
48
alias rethrow='return "$e"'
49
alias rethrow_subshell='exit "$e"'
50

    
51
fi # load new aliases
52
if self_being_included; then
53

    
54
# usage: save_e cmd... || use $e (or $?)
55
function save_e () { "$@"; e=$?; rethrow; } # rethrow because e= clears $?
56
alias save_e='declare e; save_e ' # last space alias-expands next word
57

    
58
function log_e () # usage: log_e cmd... [ || use $e (or $?) ]
59
{
60
	if ! "save_e" "$@"; then
61
		echo "! $*" >&2
62
		echo "! command exited with error $e" >&2
63
		rethrow
64
	fi
65
}
66
alias log_e='declare e; log_e ' # last space alias-expands next word
67

    
68
# usage: try cmd...; ignore status; if catch status; then ...; fi; end_try
69

    
70
function try () { "save_e" "$@" || true; }
71
alias try='declare e; try ' # last space alias-expands next word
72

    
73
catch () { test "$e" -eq "$1"; e=0; }
74

    
75
ignore () { catch "$@" || true; }
76

    
77
alias end_try='rethrow'
78
alias end_try_subshell='rethrow_subshell'
79

    
80

    
81
#### integers
82

    
83
let () { builtin let "$@" || true; }
84
	# "If the last ARG evaluates to 0, let returns 1" (`help let`)
85

    
86
bool2int () { save_e test -z "$1"; echo "$e"; } # empty->0; non-empty->1
87

    
88

    
89
#### arrays
90

    
91
join () { local IFS="$delim"; echo "$*"; } # usage: delim=... join elems...
92

    
93
reverse () # usage: array=($(reverse args...))
94
{
95
	local i
96
	for (( i=$#; i >= 1; i-- )); do printf '%q ' "${!i}"; done
97
}
98

    
99

    
100
#### verbose output
101

    
102
# usage: (stdout2stderr; cmd...) || return
103
# `|| return` needed on Mac because of bug where -e doesn't apply to ()
104
stdout2stderr () { exec >&2; }
105

    
106
# set verbosity
107
if isset verbose; then : "${verbosity:=$(bool2int "$verbose")}"; fi
108
: "${verbosity=3}" # default
109
: "${verbosity:=0}" # ensure non-empty
110
declare -i verbosity # ensure integer
111
export verbosity # propagate the verbosity to invoked commands
112

    
113
can_log () { test "$verbosity" -gt 0; } # verbosity=0 turns off all logging
114

    
115
: "${log_indent=  }"
116

    
117
# usage: in func:      inc_log_level; ...
118
#        outside func: inc_log_level; ...; dec_log_level
119
alias inc_log_level='declare verbosity="$verbosity" PS4="$log_indent$PS4"
120
let verbosity--'
121
alias dec_log_level='declare verbosity="$verbosity" PS4="${PS4#$log_indent}"
122
let verbosity++'
123

    
124
fi # load new aliases
125
if self_being_included; then
126

    
127
# usage: (limit_stderr; cmd...) || return
128
# `|| return` needed on Mac because of bug where -e doesn't apply to ()
129
limit_stderr () { inc_log_level; if ! can_log; then exec 2>/dev/null; fi; }
130

    
131
limit_stderr_cmd () # usage: [stdout2stderr=1] limit_stderr_cmd cmd...
132
{
133
	case "$1" in echo_run) shift; echo_cmd "$@";; esac
134
	(limit_stderr
135
		if test -n "$stdout2stderr"; then stdout2stderr; fi
136
		"$@"
137
	) || return
138
}
139
alias limit_stderr_cmd='limit_stderr_cmd ' # last space alias-expands next word
140

    
141
echo_cmd () { if can_log; then echo "$PS4$*" >&2; fi; }
142

    
143
echo_run () { echo_cmd "$@"; "$@"; }
144

    
145
# auto-echo common external commands
146
for cmd in rm; do alias "$cmd=echo_run $cmd"; done; unset cmd
147

    
148
# echo all external commands
149
alias extern="echo_run extern " # last space alias-expands next word
150

    
151
alias self='extern "$FUNCNAME"' # usage: wrapper () { self ...; }
152

    
153
# commands that are always external
154
for cmd in env; do alias "$cmd=extern $cmd"; done; unset cmd
155

    
156
canon_rel_path ()
157
{
158
	local path="$1"
159
	path="$(realpath "$path")" # canonicalize
160
	path="${path#$(pwd -P)/}" # remove any shared prefix with the current dir
161
	echo "$path"
162
}
163

    
164
function echo_func ()
165
{
166
	inc_log_level
167
	local script="$(canon_rel_path "${BASH_SOURCE[1]}")"
168
	echo_cmd "$script:${BASH_LINENO[0]}" "${FUNCNAME[1]}" "$@"
169
}
170

    
171
# usage: cmd1 | { pipe_delay; cmd2; }
172
alias pipe_delay='sleep 0.1' # s; display after leading output of cmd1
173

    
174
fi # load new aliases
175
if self_being_included; then
176

    
177
echo_stdin () # usage: input|echo_stdin|cmd
178
{
179
	inc_log_level
180
	if can_log; then
181
		pipe_delay
182
		echo ----- >&2
183
		tee -a /dev/stderr;
184
		echo ----- >&2
185
	else cat
186
	fi
187
}
188

    
189
echo_vars () # usage: echo_vars var...
190
{
191
	inc_log_level; inc_log_level
192
	if can_log; then
193
		local var
194
		for var in "${@%%=*}"; do { echo -n "$PS4"; declare -p "$var";} >&2;done
195
	fi
196
}
197

    
198
echo_export () { builtin export "$@"; echo_vars "$@"; }
199

    
200
if test "$verbosity" -ge 2; then
201
	alias export="echo_export" # automatically echo env vars when they are set
202
fi
203

    
204
usage () { echo "Usage: $1" >&2; (exit 2); }
205

    
206
fi # load new aliases
207
if self_being_included; then
208

    
209

    
210
#### strings
211

    
212
sed_ere_flag="$(test "$(uname)" = Darwin && echo E || echo r)"
213

    
214
sed () { self -"$sed_ere_flag" "$@";}
215

    
216

    
217
#### vars
218

    
219
set_var () { eval "$1"'="$2"'; }
220

    
221
set_inv () { set_var no_"$1" "$(test -n "${!1}" || echo 1)"; }
222

    
223
# usage: local var=...; local_inv
224
alias local_inv='declare "no_$var=$(test -n "${!var}" || echo 1)"'
225

    
226
# usage: local prefix=..._; import_vars
227
alias import_vars="$(cat <<'EOF'
228
: "${prefix:?}"
229
local src_var dest_var
230
for src_var in $(eval echo '${!'$prefix'*}'); do
231
	dest_var="${src_var#$prefix}"
232
	local "$dest_var=${!src_var}"; echo_vars "$dest_var"
233
done
234
EOF
235
)"
236

    
237

    
238
#### commands
239

    
240
top_script="$0" # outermost script
241
top_dir="$(dirname "$top_script")"
242

    
243
# auto-removes a command's output file on error (like make's .DELETE_ON_ERROR)
244
function to_file () # usage: stdout=... to_file cmd...
245
{ : "${stdout?}"; log_e "$@" >"$stdout" || { rm "$stdout"; rethrow; }; }
246
alias to_file='to_file ' # last space alias-expands next word
247

    
248
run_args_cmd () # runs the command line args command
249
{
250
	test $? -eq 0 || return
251
	eval set -- "$(reverse "${BASH_ARGV[@]}")"
252
	test $# -ge 1 || set -- all
253
	echo_cmd "$(canon_rel_path "$0")" "$@"; "$@"
254
}
255

    
256
fwd () # usage: subdirs=(...); fwd "$FUNCNAME" "$@"
257
{
258
	echo_func
259
	: "${subdirs?}"
260
	
261
	for subdir in "${subdirs[@]}"; do
262
		"$(dirname "${BASH_SOURCE[1]}")"/"$subdir"/run "$@"
263
	done
264
}
265

    
266

    
267
#### URLs
268

    
269
localize_url () { test _"$1" = _"$(hostname -f)" || echo "$1"; }
270

    
271
fi
(5-5/5)