Project

General

Profile

1
#!/bin/bash -e
2
set -o errexit -o pipefail # errexit in case caller's #! line missing -e
3

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

    
7
isset() { test "${!1+isset}"; }
8

    
9
realpath() { readlink -f -- "$1"; }
10

    
11
str2varname() { echo "${1//[^a-zA-Z0-9_]/_}"; }
12

    
13
include_guard_var() { str2varname "$(realpath "$1")"; }
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
#### vars
42

    
43
set_var() { eval "$1"'="$2"'; }
44

    
45
set_inv() { set_var no_"$1" "$(test "${!1}" || echo 1)"; }
46

    
47
# usage: local var=...; local_inv
48
alias local_inv='declare "no_$var=$(test "${!var}" || echo 1)"'
49

    
50
unexport() { export -n "$@"; }
51
	# `declare +x` won't work because it defines the var if it isn't set
52

    
53
alias local_export='declare -x' # combines effects of local and export
54

    
55
get_prefix_vars() { : "${prefix:?}"; eval echo '${!'$prefix'*}'; }
56

    
57
# usage: local prefix=..._; import_vars
58
# when used inside another alias 2+ levels deep, *must* be run inside a function
59
alias import_vars="$(cat <<'EOF'
60
: "${prefix:?}"
61
declare src_var dest_var
62
for src_var in $(get_prefix_vars); do
63
	dest_var="${src_var#$prefix}"
64
	declare "$dest_var=${!src_var}"; echo_vars "$dest_var"
65
done
66
EOF
67
)"
68

    
69

    
70
#### caching
71

    
72
## shell-variable-based caching
73

    
74
# usage: local cache_key=...; load_cache; \
75
# if ! cached; then save_cache value || return; fi; echo_cached_value
76
# cache_key for function inputs: "$(declare -p "$kw_param"...) $*"
77
alias load_cache='declare cache_var="$(str2varname "${FUNCNAME}___$cache_key")"'
78
alias cached='isset "$cache_var"'
79
alias save_cache='set_var "$cache_var"'
80
alias echo_cached_value='echo "${!cache_var}"'
81

    
82
clear_cache() # usage: func=... clear_cache
83
{ : "${func:?}"; unset $(prefix="${func}___" get_prefix_vars); }
84

    
85
fi # load new aliases
86
if self_being_included; then
87

    
88

    
89
#### aliases
90

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

    
93
# usage: alias alias_='var=value run_cmd '
94
function run_cmd() { "$@"; }
95
alias run_cmd='"run_cmd" ' # last space alias-expands next word
96

    
97

    
98
#### functions
99

    
100
kw_params() # usage: func() { kw_params param_var...; }; ...; param_var=... cmd
101
# removes keyword-param-only vars from the environment
102
{ unexport "$@"; }
103

    
104
alias self='command "$FUNCNAME"' # usage: wrapper() { self ...; }
105

    
106

    
107
#### exceptions
108

    
109
# usage: cmd || { save_e; ...; rethrow; }
110
alias export_e='e=$?'
111
alias save_e='declare e=$?'
112
alias rethrow='return "$e"'
113
alias rethrow_subshell='exit "$e"'
114

    
115
fi # load new aliases
116
if self_being_included; then
117

    
118
# usage: try cmd...; ignore status; if catch status; then ...; fi; end_try
119

    
120
function try() { e=0; "$@" || { export_e; true; }; }
121
alias try='declare e; "try" ' # last space alias-expands next word
122

    
123
catch() { test "$e" -eq "$1"; e=0; }
124

    
125
ignore() { catch "$@" || true; }
126

    
127
alias end_try='rethrow'
128
alias end_try_subshell='rethrow_subshell'
129

    
130
fi # load new aliases
131
if self_being_included; then
132

    
133

    
134
#### integers
135

    
136
let!() { let "$@" || true; } # always returns true; safe to use for setting
137
	# "If the last ARG evaluates to 0, let returns 1" (`help let`)
138

    
139
bool2int() { try test ! "$1"; echo "$e"; } # empty->0; non-empty->1
140

    
141

    
142
#### floats
143

    
144
int_part() { echo "${1%%.*}"; }
145

    
146
dec_suffix() { echo "${1#$(int_part "$1")}"; }
147

    
148
round_down() { int_part "$1"; }
149

    
150
float+int() { echo "$(($(int_part "$1")+$2))$(dec_suffix "$1")"; }
151

    
152

    
153
#### strings
154

    
155
repeat() # usage: str=... n=... repeat
156
{
157
	: "${str?}" "${n:?}"; local result= n="$n" # n will be modified in function
158
	for (( ; n > 0; n-- )); do result="$result$str"; done
159
	echo "$result"
160
}
161

    
162
sed_ere_flag="$(test "$(uname)" = Darwin && echo E || echo r)"
163

    
164
sed() { self -"$sed_ere_flag" "$@";}
165

    
166
rtrim() { sed 's/[[:space:]]+$//' <<<"$1"; }
167

    
168

    
169
#### arrays
170

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

    
173
reverse() # usage: array=($(reverse args...))
174
{
175
	local i
176
	for (( i=$#; i > 0; i-- )); do printf '%q ' "${!i}"; done
177
}
178

    
179
contains() # usage: contains value in_array...
180
{
181
	local value="$1"; shift
182
	local elem
183
	for elem in "$@"; do if test "$elem" = "$value"; then return 0; fi; done
184
	return 1
185
}
186

    
187

    
188
#### verbose output
189

    
190

    
191
err_fd=2 # stderr
192

    
193
usage() { echo "Usage: $1" >&2; return 2; }
194

    
195

    
196
### logging
197

    
198
log_fd=2 # initially stderr
199

    
200
if test "$explicit_errors_only"; then verbosity=0; fi # hide startup logging
201

    
202
# set verbosity
203
if isset verbose; then : "${verbosity:=$(bool2int "$verbose")}"; fi
204
if isset vb; then : "${verbosity:=$vb}"; fi
205
: "${verbosity=1}" # default
206
: "${verbosity:=0}" # ensure non-empty
207
export verbosity # propagate to invoked commands
208

    
209
# verbosities:
210
# 0: just print errors. useful for cron jobs.
211
# 1: also external commands run. useful for running at the command line.
212
# 2: full graphical call tree. useful for determining where error occurred.
213
# 3: also values of kw params and variables. useful for low-level debugging.
214
# 4: also variables in util.sh commands. useful for debugging util.sh.
215
# 5: also variables in logging commands themselves. useful for debugging echo_*.
216
# 6+: not currently used (i.e. same as 5)
217

    
218
# definition: the log_level is the minimum verbosity needed to display a message
219
# for messages that use can_log(), the log_level starts with *1*, not 0
220
# for unfiltered messages, the log_level is 0 (i.e. still output at verbosity=0)
221
# to view a message's log_level, count the # of + signs before it in the output
222

    
223
alias PS4_prefix_n='str="${PS4:0:1}" n=$1 repeat'
224

    
225
fi # load new aliases
226
if self_being_included; then
227

    
228
# usage: in func:      log++; ...         OR  log_local; "log++"; ...
229
#        outside func: log++; ...; log--
230
#        before cmd:   log++ cmd...
231
# without a cmd, "$@" expands to nothing and assignments are applied to caller
232
# "${@:2}" expands to all of $@ after *1st* arg, not 2nd ($@ indexes start at 1)
233
log+()  { PS4="$(PS4_prefix_n)$PS4" verbosity=$((verbosity - $1)) "${@:2}"; }
234
log-()  { PS4="${PS4:$1}"           verbosity=$((verbosity + $1)) "${@:2}"; }
235
log++() { log+ 1 "$@"; }
236
log--() { log- 1 "$@"; }
237
alias log_local='declare PS4="$PS4" verbosity="$verbosity"'
238
alias log+='log_local; "log+" ' # last space alias-expands next word
239
alias log-='log_local; "log-" ' # last space alias-expands next word
240
alias log++='log_local; "log++" ' # last space alias-expands next word
241
alias log--='log_local; "log--" ' # last space alias-expands next word
242

    
243

    
244
# indent for call tree. this is *not* the log_level (below).
245
: "${log_level_indent=| }" "${log_indent=}"
246
export log_level_indent log_indent # propagate to invoked commands
247

    
248
__caller_indent='log_indent="$log_indent$log_level_indent"'
249
alias caller_indent="$__caller_indent"
250
alias indent="declare $__caller_indent"
251

    
252

    
253
fi # load new aliases
254
if self_being_included; then
255

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

    
258
log() { if can_log; then echo "$log_indent$PS4$1" >&"$log_fd"; fi; }
259

    
260
log_custom() # usage: symbol=... log_custom msg
261
{ log_indent="${log_indent//[^ ]/$symbol}" PS4="${PS4//[^ ]/$symbol}" log "$@";}
262

    
263
log_err() { symbol='#' verbosity=1 log_fd="$err_fd" log_custom "$@"; }
264

    
265
log_info() { symbol=: log_custom "$@"; }
266

    
267
log_e() # usage: cmd || { save_e; log_e; ...; rethrow; }
268
{ log_err "command exited with error $e"; }
269

    
270
die() # usage: cmd || [type=...] die msg
271
{ save_e; kw_params type; "log_${type:-err}" "$1"; rethrow; }
272

    
273

    
274
#### functions
275

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

    
278
copy_func() # usage: from=... to=... copy_func
279
# $to must not exist. to get around the no-clobber restriction, use `unset -f`.
280
{
281
	: "${from:?}" "${to:?}"
282
	func_exists "$from" || die "function does not exist: $from"
283
	! func_exists "$to" || die "function already exists: $to"
284
	local from_def="$(declare -f "$from")"
285
	eval "$to${from_def#$from}"
286
}
287

    
288
func_override() # usage: func_override old_name__suffix
289
{ from="${1%%__*}" to="$1" copy_func; }
290

    
291
ensure_nested_func() # usage: func__nested_func() { ensure_nested_func; ... }
292
{
293
	local nested_func="${FUNCNAME[1]}"
294
	local func="${nested_func%%__*}"
295
	contains "$func" "${FUNCNAME[@]}" || \
296
		die "$nested_func() must be used by $func()"
297
}
298

    
299

    
300
#### paths
301

    
302
# cache realpath
303
: "${realpath_cache=}" # default off because slower than without
304
if test "$realpath_cache"; then
305
func_override realpath__no_cache
306
realpath() # caches the last result for efficiency
307
{
308
	local cache_key="$*"; load_cache
309
	if ! cached; then save_cache "$(realpath__no_cache "$@")" || return; fi
310
	echo_cached_value
311
}
312
fi
313

    
314
rel_path() # usage: base_dir=... path=... rel_path
315
{
316
	log++; kw_params base_dir path
317
	: "${base_dir:?}" "${path:?}"
318
	
319
	local path="$path/" # add *extra* / to match path when exactly = base_dir
320
	path="${path#$base_dir/}" # remove prefix shared with base_dir
321
	path="${path%/}" # remove any remaining extra trailing /
322
	
323
	if test ! "$path"; then path=.; fi # ensure non-empty
324
	
325
	echo_vars path
326
	echo "$path"
327
}
328

    
329
cd -P . # expand symlinks in $PWD so it matches the output of realpath
330
# do before setting $top_script_abs so realpath has less symlinks to resolve
331

    
332
canon_rel_path()
333
{
334
	local path; path="$(realpath "$1")" || return
335
	base_dir="$PWD" rel_path
336
}
337

    
338
# makes $1 a canon_rel_path if it's a filesystem path
339
alias cmd2rel_path="$(cat <<'EOF'
340
if test "$(type -t "$1")" = file && test -e "$1"; then # not relative to PATH
341
	declare _1="$1"; shift
342
	_1="$(canon_rel_path "$_1")" || return
343
	set -- "$_1" "$@"
344
fi
345
EOF
346
)"
347

    
348

    
349
#### verbose output
350

    
351

    
352
### command echoing
353

    
354
alias echo_params='log "$*"'
355

    
356
fi # load new aliases
357
if self_being_included; then
358

    
359
echo_cmd() { echo_params; }
360

    
361
echo_eval() { echo_params; builtin eval "$@"; }
362

    
363
## vars
364

    
365
echo_vars() # usage: echo_vars var...
366
{
367
	log+ 2
368
	if can_log; then
369
		local var
370
		for var in "${@%%=*}"; do
371
			if isset "$var"; then log "$(declare -p "$var")"; fi
372
		done
373
	fi
374
}
375

    
376
echo_export() { builtin export "$@"; echo_vars "$@"; }
377

    
378
if test "$verbosity" -ge 2; then
379
	alias export="echo_export" # automatically echo env vars when they are set
380
fi
381

    
382
func_override kw_params__lang
383
kw_params() { kw_params__lang "$@"; echo_vars "$@"; } # echo all keyword params
384

    
385
## functions
386

    
387
# usage: local func=...; set_func_loc; use $file, $line
388
alias set_func_loc="$(cat <<'EOF'
389
: "${func:?}"
390
local func_info="$(shopt -s extdebug; declare -F "$func")" # 'func line file'
391
func_info="${func_info#$func }"
392
local line="${func_info%% *}"
393
local file="${func_info#$line }"
394
EOF
395
)"
396

    
397
fi # load new aliases
398
if self_being_included; then
399

    
400
func_loc() # gets where function declared in the format file:line
401
{
402
	local func="$1"; set_func_loc
403
	file="$(canon_rel_path "$file")" || return
404
	echo "$file:$line"
405
}
406

    
407
# usage: func() { [minor=1] echo_func; ... }
408
function echo_func()
409
# usage: [minor=1] "echo_func" "$FUNCNAME" "$@" && indent || true
410
# exit status: whether function call was echoed
411
{
412
	kw_params minor
413
	local func="$1"; shift
414
	
415
	log++; if test "$minor"; then log++; fi
416
	local loc; loc="$(func_loc "$func")" || return
417
	echo_cmd "$loc" "$func" "$@"
418
	can_log
419
}
420
alias echo_func='"echo_func" "$FUNCNAME" "$@" && indent || true'
421

    
422
fi # load new aliases
423
if self_being_included; then
424

    
425

    
426
#### streams
427

    
428
fd_exists() { (: <&"$1") 2>/dev/null; }
429

    
430
require_fd_not_exists() # usage: require_fd_not_exists fd || return 0
431
{ ! fd_exists "$1" || type=info die "fd $1 already exists, skipping"; }
432

    
433
set_fds() { echo_func; echo_eval exec "$@"; } # usage: set_fds redirect...
434

    
435
fd_set_default() # usage: fd_set_default 'dest[<>]src'
436
{
437
	echo_func
438
	local dest="${1%%[<>]*}"
439
	require_fd_not_exists "$dest" || return 0
440
	set_fds "$1"
441
}
442

    
443
# convention: use fd 10/11/12 for command-specific alternate stdin/stdout/stderr
444

    
445
setup_log_fd() # view logging output at verbosity >= 5
446
{
447
	log+ 4; log-- echo_func 
448
	fd_set_default '30>&2' || true # stdlog
449
	log_fd=30 # stdlog
450
}
451
setup_log_fd
452

    
453
set_global_fds()
454
# allows commands to access global stdin/stdout/stderr using fd 20/21/22
455
# this works even when /dev/tty isn't available
456
# view logging output at verbosity >= 3
457
{
458
	log+ 2; log-- echo_func
459
	# ignore errors if a source fd isn't open
460
	fd_set_default '20<&0' || true
461
	fd_set_default '21>&1' || true
462
	fd_set_default '22>&2' || true
463
}
464
set_global_fds
465
err_fd=22 # global stderr
466

    
467
# usage: explicit_errors_only=1 script...
468
# show only explicitly-displayed errors (which have been redirected to fd 22)
469
# most of the time this has the same effect as `verbosity=0 script...`,
470
# which displays everything that isn't explicitly hidden
471
# this option should only be used for testing the explicit error displaying
472
if test "$explicit_errors_only"; then disable_logging; fi
473

    
474

    
475
#### paths
476

    
477
top_script_abs="$(realpath "$0")"; echo_vars top_script_abs # outermost script
478
	# realpath this before doing any cd so this points to the right place
479

    
480
set_paths()
481
{
482
	top_script="$(canon_rel_path "$top_script_abs")" || return
483
		echo_vars top_script
484
	top_dir="$(dirname "$top_script")" || return; echo_vars top_dir
485
}
486
set_paths
487

    
488

    
489
#### verbose output
490

    
491

    
492
## internal commands
493

    
494
.()
495
{
496
	cmd2rel_path; set -- "$FUNCNAME" "$@"
497
	(log++; echo_params; can_log) && indent || true
498
	builtin "$@"
499
}
500

    
501
cd() # indent is permanent within subshell cd was used in
502
{
503
	cmd2rel_path; echo_cmd "$FUNCNAME" "$@"
504
	can_log && caller_indent || true
505
	# -P: expand symlinks so $PWD matches the output of realpath
506
	builtin "$FUNCNAME" -P "$@"
507
	
508
	func=realpath clear_cache
509
	set_paths
510
}
511

    
512
## external commands
513

    
514
disable_logging() { set_fds "$log_fd>/dev/null"; }
515

    
516
function command() # usage: [cmd_log_fd=|1|2|#] command extern_cmd...
517
# to view only explicitly-displayed errors: explicit_errors_only=1 script...
518
{
519
	kw_params cmd_log_fd
520
	# if no cmd_log_fd, limit log_fd in case command uses util.sh
521
	local cmd_log_fd="${cmd_log_fd-$log_fd}"
522
	
523
	cmd2rel_path; (echo_params; can_log) && indent || true
524
	(
525
		# the following redirections must happen in exactly this order
526
		if test "$cmd_log_fd"; then command__set_fds; fi
527
		if test "$cmd_log_fd" != 2; then # fd 2 not used for logging
528
			exec 2>&"$err_fd" # assume fd 2 used for errors
529
		fi
530
		
531
		exec -- "$@" # -- so cmd name not treated as `exec` option
532
	) || return
533
}
534
function command__set_fds()
535
{
536
	ensure_nested_func
537
	if can_log; then
538
		if test "$cmd_log_fd" = "$log_fd"; then return 0; fi # no redir needed
539
		local src="&$log_fd"
540
	else local src=/dev/null
541
	fi
542
	log++ set_fds "$cmd_log_fd>$src"
543
}
544

    
545
# auto-echo common external commands
546
for cmd in env rm; do alias "$cmd=command $cmd"; done; unset cmd
547

    
548

    
549
### external command input/output
550

    
551
pipe_delay() # usage: cmd1 | { pipe_delay; cmd2; }
552
{ sleep 0.1; } # s; display after leading output of cmd1
553

    
554
fi # load new aliases
555
if self_being_included; then
556

    
557
echo_stdin() # usage: input|echo_stdin|cmd
558
{
559
	if can_log; then
560
		pipe_delay
561
		echo ----- >&"$log_fd"
562
		tee -a /dev/fd/"$log_fd";
563
		echo ----- >&"$log_fd"
564
	else cat
565
	fi
566
}
567

    
568
echo_stdout() { echo_stdin; } # usage: cmd|echo_stdout
569

    
570

    
571
#### commands
572

    
573
require_not_exists() # usage: require_not_exists file || return 0
574
{ test ! -e "$1" || type=info die "file "$1" already exists, skipping"; }
575

    
576
function to_file() # usage: stdout=... [if_not_exists=1] to_file cmd...
577
# auto-removes a command's output file on error (like make's .DELETE_ON_ERROR)
578
{
579
	echo_func; kw_params stdout
580
	: "${stdout?}"
581
	test ! "$if_not_exists" || require_not_exists "$stdout" || return 0
582
	"$@" >"$stdout" || { save_e; log_e; rm "$stdout"; rethrow; }
583
}
584
alias to_file='"to_file" ' # last space alias-expands next word
585

    
586
run_args_cmd() # runs the command line args command
587
{
588
	eval set -- "$(reverse "${BASH_ARGV[@]}")"
589
	test $# -ge 1 || set -- all
590
	echo_cmd "$top_script" "$@"; "$@"
591
}
592

    
593
fwd() # usage: subdirs=(...); fwd "$FUNCNAME" "$@"
594
{
595
	echo_func
596
	: "${subdirs?}"
597
	
598
	for subdir in "${subdirs[@]}"; do "$top_dir"/"$subdir"/run "$@"; done
599
}
600

    
601

    
602
#### URLs
603

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

    
606
fi
(5-5/5)