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
# usage: cmd || { save_e; ...; rethrow; }
49
alias export_e='e=$?'
50
alias save_e='declare e=$?'
51
alias rethrow='return "$e"'
52
alias rethrow_subshell='exit "$e"'
53

    
54
fi # load new aliases
55
if self_being_included; then
56

    
57
function log_e () # usage: log_e cmd... [ || use $e (or $?) ]
58
{
59
	if "$@"; then :; else # don't use ! because that resets $?
60
		export_e
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 () { e=0; "$@" || { export_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
fi # load new aliases
81
if self_being_included; then
82

    
83

    
84
#### functions
85

    
86
func_exists () { declare -f "$1" >/dev/null; }
87

    
88
copy_func () # usage: from=... to=... copy_func
89
{
90
	: "${from:?}" "${to:?}"
91
	local from_def="$(declare -f "$from")"
92
	eval "$to${from_def#$from}"
93
}
94

    
95

    
96
#### integers
97

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

    
101
bool2int () { try test -z "$1"; echo "$e"; } # empty->0; non-empty->1
102

    
103

    
104
#### arrays
105

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

    
108
reverse () # usage: array=($(reverse args...))
109
{
110
	local i
111
	for (( i=$#; i >= 1; i-- )); do printf '%q ' "${!i}"; done
112
}
113

    
114

    
115
#### verbose output
116

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

    
121
# set verbosity
122
if isset verbose; then : "${verbosity:=$(bool2int "$verbose")}"; fi
123
: "${verbosity=3}" # default
124
: "${verbosity:=0}" # ensure non-empty
125
declare -i verbosity # ensure integer
126
export verbosity # propagate the verbosity to invoked commands
127

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

    
130
: "${log_indent=  }"
131

    
132
# usage: in func:      inc_log_level; ...
133
#        outside func: inc_log_level; ...; dec_log_level
134
alias inc_log_level='declare verbosity="$verbosity" PS4="$log_indent$PS4"
135
let verbosity--'
136
alias dec_log_level='declare verbosity="$verbosity" PS4="${PS4#$log_indent}"
137
let verbosity++'
138

    
139
fi # load new aliases
140
if self_being_included; then
141

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

    
146
limit_stderr_cmd () # usage: [stdout2stderr=1] limit_stderr_cmd cmd...
147
{
148
	case "$1" in echo_run) shift; echo_cmd "$@";; esac
149
	(limit_stderr
150
		if test -n "$stdout2stderr"; then stdout2stderr; fi
151
		"$@"
152
	) || return
153
}
154
alias limit_stderr_cmd='limit_stderr_cmd ' # last space alias-expands next word
155

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

    
158
echo_run () { echo_cmd "$@"; "$@"; }
159

    
160
# auto-echo common external commands
161
for cmd in rm; do alias "$cmd=echo_run $cmd"; done; unset cmd
162

    
163
# echo all external commands
164
alias extern="echo_run extern " # last space alias-expands next word
165

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

    
168
# commands that are always external
169
for cmd in env; do alias "$cmd=extern $cmd"; done; unset cmd
170

    
171
canon_rel_path ()
172
{
173
	local path="$1"
174
	path="$(realpath "$path")" # canonicalize
175
	path="${path#$(pwd -P)/}" # remove any shared prefix with the current dir
176
	echo "$path"
177
}
178

    
179
function echo_func ()
180
{
181
	inc_log_level
182
	local script="$(canon_rel_path "${BASH_SOURCE[1]}")"
183
	echo_cmd "$script:${BASH_LINENO[0]}" "${FUNCNAME[1]}" "$@"
184
}
185

    
186
# usage: cmd1 | { pipe_delay; cmd2; }
187
alias pipe_delay='sleep 0.1' # s; display after leading output of cmd1
188

    
189
fi # load new aliases
190
if self_being_included; then
191

    
192
echo_stdin () # usage: input|echo_stdin|cmd
193
{
194
	inc_log_level
195
	if can_log; then
196
		pipe_delay
197
		echo ----- >&2
198
		tee -a /dev/stderr;
199
		echo ----- >&2
200
	else cat
201
	fi
202
}
203

    
204
echo_vars () # usage: echo_vars var...
205
{
206
	inc_log_level; inc_log_level
207
	if can_log; then
208
		local var
209
		for var in "${@%%=*}"; do { echo -n "$PS4"; declare -p "$var";} >&2;done
210
	fi
211
}
212

    
213
echo_export () { builtin export "$@"; echo_vars "$@"; }
214

    
215
if test "$verbosity" -ge 2; then
216
	alias export="echo_export" # automatically echo env vars when they are set
217
fi
218

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

    
221
fi # load new aliases
222
if self_being_included; then
223

    
224

    
225
#### strings
226

    
227
sed_ere_flag="$(test "$(uname)" = Darwin && echo E || echo r)"
228

    
229
sed () { self -"$sed_ere_flag" "$@";}
230

    
231

    
232
#### vars
233

    
234
set_var () { eval "$1"'="$2"'; }
235

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

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

    
241
# usage: local prefix=..._; import_vars
242
alias import_vars="$(cat <<'EOF'
243
: "${prefix:?}"
244
local src_var dest_var
245
for src_var in $(eval echo '${!'$prefix'*}'); do
246
	dest_var="${src_var#$prefix}"
247
	local "$dest_var=${!src_var}"; echo_vars "$dest_var"
248
done
249
EOF
250
)"
251

    
252

    
253
#### commands
254

    
255
top_script="$0" # outermost script
256
top_dir="$(dirname "$top_script")"
257

    
258
# auto-removes a command's output file on error (like make's .DELETE_ON_ERROR)
259
function to_file () # usage: stdout=... to_file cmd...
260
{ : "${stdout?}"; log_e "$@" >"$stdout" || { save_e; rm "$stdout"; rethrow; }; }
261
alias to_file='to_file ' # last space alias-expands next word
262

    
263
run_args_cmd () # runs the command line args command
264
{
265
	test $? -eq 0 || return
266
	eval set -- "$(reverse "${BASH_ARGV[@]}")"
267
	test $# -ge 1 || set -- all
268
	echo_cmd "$(canon_rel_path "$0")" "$@"; "$@"
269
}
270

    
271
fwd () # usage: subdirs=(...); fwd "$FUNCNAME" "$@"
272
{
273
	echo_func
274
	: "${subdirs?}"
275
	
276
	for subdir in "${subdirs[@]}"; do
277
		"$(dirname "${BASH_SOURCE[1]}")"/"$subdir"/run "$@"
278
	done
279
}
280

    
281

    
282
#### URLs
283

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

    
286
fi
(5-5/5)