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 $?); rethrow; }
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
fi # load new aliases
81
if self_being_included; then
82

    
83

    
84
#### integers
85

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

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

    
91

    
92
#### arrays
93

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

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

    
102

    
103
#### verbose output
104

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

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

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

    
118
: "${log_indent=  }"
119

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

    
127
fi # load new aliases
128
if self_being_included; then
129

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

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

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

    
146
echo_run () { echo_cmd "$@"; "$@"; }
147

    
148
# auto-echo common external commands
149
for cmd in rm; do alias "$cmd=echo_run $cmd"; done; unset cmd
150

    
151
# echo all external commands
152
alias extern="echo_run extern " # last space alias-expands next word
153

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

    
156
# commands that are always external
157
for cmd in env; do alias "$cmd=extern $cmd"; done; unset cmd
158

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

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

    
174
# usage: cmd1 | { pipe_delay; cmd2; }
175
alias pipe_delay='sleep 0.1' # s; display after leading output of cmd1
176

    
177
fi # load new aliases
178
if self_being_included; then
179

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

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

    
201
echo_export () { builtin export "$@"; echo_vars "$@"; }
202

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

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

    
209
fi # load new aliases
210
if self_being_included; then
211

    
212

    
213
#### strings
214

    
215
sed_ere_flag="$(test "$(uname)" = Darwin && echo E || echo r)"
216

    
217
sed () { self -"$sed_ere_flag" "$@";}
218

    
219

    
220
#### vars
221

    
222
set_var () { eval "$1"'="$2"'; }
223

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

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

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

    
240

    
241
#### commands
242

    
243
top_script="$0" # outermost script
244
top_dir="$(dirname "$top_script")"
245

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

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

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

    
269

    
270
#### URLs
271

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

    
274
fi
(5-5/5)