Project

General

Profile

1 8291 aaronmk
#!/bin/bash -e
2 8952 aaronmk
set -o errexit # in case caller did not have -e in #! line
3
4 8957 aaronmk
function extern () { (exec "$@") || return; }
5 8917 aaronmk
6 8716 aaronmk
realpath () { readlink -f -- "$1"; }
7 8703 aaronmk
8 8917 aaronmk
include_guard_var () { realpath "$1"|"extern" sed 's/[^a-zA-Z0-9_]/_/g'; }
9 8716 aaronmk
10 8703 aaronmk
self_not_included () # usage: if self_not_included; then ... fi
11
{
12 8971 aaronmk
	test $# -ge 1 || set -- "${BASH_SOURCE[1]}"
13 8703 aaronmk
	local include_guard="$(include_guard_var "$1")"
14 8793 aaronmk
	alias self_being_included=false
15
	test -z "${!include_guard+t}" && \
16
	{ eval "$include_guard"=1; alias self_being_included=true; }
17 8703 aaronmk
}
18
19 8793 aaronmk
# to load newly-defined aliases for use in functions in the same file:
20
## fi # load new aliases
21
## if self_being_included; then
22
# this is needed because aliases defined inside an if statement are not
23
# available inside that if statement
24
25 8704 aaronmk
if self_not_included "${BASH_SOURCE[0]}"; then
26
27 8709 aaronmk
shopt -s expand_aliases
28
29 8889 aaronmk
unalias () { builtin unalias "$@" 2>&- || true; } # no error if undefined
30
31 8886 aaronmk
#### exceptions
32
33 8976 aaronmk
alias rethrow='return "$e"'
34
alias rethrow_subshell='exit "$e"'
35
36 8978 aaronmk
fi # load new aliases
37
if self_being_included; then
38
39
# usage: save_e cmd... || use $e (or $?)
40
function save_e () { "$@"; e=$?; rethrow; } # rethrow because e= clears $?
41
alias save_e='declare e; save_e ' # last space alias-expands next word
42
43 8981 aaronmk
function log_e () # usage: log_e cmd... [ || use $e (or $?) ]
44
{
45 8982 aaronmk
	if ! "save_e" "$@"; then
46 8981 aaronmk
		echo "! $*" >&2
47
		echo "! command exited with error $e" >&2
48
		rethrow
49
	fi
50
}
51 8982 aaronmk
alias log_e='declare e; log_e ' # last space alias-expands next word
52 8981 aaronmk
53 8886 aaronmk
# usage: try cmd...; ignore status; if catch status; then ...; fi; end_try
54
55 8980 aaronmk
function try () { "save_e" "$@" || true; }
56
alias try='declare e; try ' # last space alias-expands next word
57 8886 aaronmk
58
catch () { test "$e" -eq "$1"; e=0; }
59
60
ignore () { catch "$@" || true; }
61
62 8977 aaronmk
alias end_try='rethrow'
63
alias end_try_subshell='rethrow_subshell'
64 8886 aaronmk
65 8899 aaronmk
#### integers
66
67
let () { builtin let "$@" || true; }
68
	# "If the last ARG evaluates to 0, let returns 1" (`help let`)
69
70 8854 aaronmk
#### arrays
71 8694 aaronmk
72 8833 aaronmk
join () { local IFS="$delim"; echo "$*"; } # usage: delim=... join elems...
73 8816 aaronmk
74 8691 aaronmk
reverse () # usage: array=($(reverse args...))
75
{
76
	local i
77
	for (( i=$#; i >= 1; i-- )); do printf '%q ' "${!i}"; done
78
}
79
80 8854 aaronmk
#### verbose output
81
82 8973 aaronmk
# usage: (stdout2stderr; cmd...) || return
83
# `|| return` needed on Mac because of bug where -e doesn't apply to ()
84 8914 aaronmk
stdout2stderr () { exec >&2; }
85
86 8713 aaronmk
: "${verbosity:=$verbose}" "${verbosity:=0}"
87 8710 aaronmk
88 8898 aaronmk
can_log () { test "$verbosity" -gt 0; } # verbosity=0 turns off all logging
89 8895 aaronmk
90 8920 aaronmk
: "${log_indent=  }"
91 8919 aaronmk
92 8900 aaronmk
# usage: in func:      inc_log_level; ...
93
#        outside func: inc_log_level; ...; dec_log_level
94 8919 aaronmk
alias inc_log_level='declare verbosity="$verbosity" PS4="$log_indent$PS4"
95
let verbosity--'
96
alias dec_log_level='declare verbosity="$verbosity" PS4="${PS4#$log_indent}"
97
let verbosity++'
98 8900 aaronmk
99 8973 aaronmk
# usage: (log_stderr; cmd...) || return
100
# `|| return` needed on Mac because of bug where -e doesn't apply to ()
101 8904 aaronmk
log_stderr () { if ! can_log; then exec 2>/dev/null; fi; }
102
103 8915 aaronmk
log_stderr_cmd () # usage: [stdout2stderr=1] log_stderr_cmd cmd...
104
{
105
	(log_stderr
106
		if test -n "$stdout2stderr"; then stdout2stderr; fi
107
		"$@"
108 8955 aaronmk
	) || return
109 8915 aaronmk
}
110 8911 aaronmk
111 8897 aaronmk
echo_cmd () { if can_log; then echo "$PS4$*" >&2; fi; }
112 8272 aaronmk
113 8278 aaronmk
echo_run () { echo_cmd "$@"; "$@"; }
114
115 8983 aaronmk
alias echo_run_extern='echo_run log_stderr_cmd "extern" '
116
	# last space alias-expands next word
117 8906 aaronmk
118 8983 aaronmk
# automatically echo external commands
119
alias extern="echo_run_extern " # last space alias-expands next word
120 8907 aaronmk
121 8929 aaronmk
alias self='extern "$FUNCNAME"' # usage: wrapper () { self ...; }
122
123 8908 aaronmk
# commands that are always external
124
for cmd in env; do alias "$cmd=extern $cmd"; done; unset cmd
125 8872 aaronmk
126 8646 aaronmk
canon_rel_path ()
127
{
128
	local path="$1"
129 8716 aaronmk
	path="$(realpath "$path")" # canonicalize
130 8773 aaronmk
	path="${path#$(pwd -P)/}" # remove any shared prefix with the current dir
131 8646 aaronmk
	echo "$path"
132
}
133
134 8909 aaronmk
fi # load new aliases
135 8884 aaronmk
if self_being_included; then
136
137 8909 aaronmk
function echo_func ()
138 8463 aaronmk
{
139 8901 aaronmk
	inc_log_level
140 8647 aaronmk
	local script="$(canon_rel_path "${BASH_SOURCE[1]}")"
141
	echo_cmd "$script:${BASH_LINENO[0]}" "${FUNCNAME[1]}" "$@"
142 8463 aaronmk
}
143 8885 aaronmk
144 8702 aaronmk
echo_stdin () # usage: input|echo_stdin|cmd
145
{
146 8901 aaronmk
	inc_log_level
147 8897 aaronmk
	if can_log; then
148 8960 aaronmk
		sleep 0.1 # s; display after leading output of the echoed-to command
149 8897 aaronmk
		echo ----- >&2
150
		tee -a /dev/stderr;
151
		echo ----- >&2
152
	else cat
153
	fi
154 8702 aaronmk
}
155 8275 aaronmk
156 8856 aaronmk
echo_vars () # usage: echo_vars var...
157 8901 aaronmk
{
158 8922 aaronmk
	inc_log_level; inc_log_level
159 8921 aaronmk
	if can_log; then
160
		local var
161
		for var in "${@%%=*}"; do { echo -n "$PS4"; declare -p "$var";} >&2;done
162
	fi
163 8901 aaronmk
}
164 8641 aaronmk
165
echo_export ()
166
{
167 8700 aaronmk
	builtin export "$@"
168 8641 aaronmk
	echo_vars "$@"
169
}
170
171 8713 aaronmk
if test "$verbosity" -ge 2; then
172 8711 aaronmk
	alias export="echo_export" # automatically echo env vars when they are set
173
fi
174 8642 aaronmk
175 8272 aaronmk
usage () { echo "Usage: $1" >&2; (exit 2); }
176
177 8873 aaronmk
fi # load new aliases
178
if self_being_included; then
179
180 8871 aaronmk
#### strings
181
182
sed_ere_flag="$(test "$(uname)" = Darwin && echo E || echo r)"
183
184 8930 aaronmk
sed () { self -"$sed_ere_flag" "$@";}
185 8871 aaronmk
186 8854 aaronmk
#### vars
187
188
set_var () { eval "$1"'="$2"'; }
189
190 8857 aaronmk
set_inv () { set_var no_"$1" "$(test -n "${!1}" || echo 1)"; }
191
192 8859 aaronmk
# usage: local var=...; local_inv
193 8888 aaronmk
alias local_inv='declare "no_$var=$(test -n "${!var}" || echo 1)"'
194 8859 aaronmk
195 8863 aaronmk
# usage: local prefix=..._; import_vars
196
alias import_vars="$(cat <<'EOF'
197
: "${prefix:?}"
198
local src_var dest_var
199
for src_var in $(eval echo '${!'$prefix'*}'); do
200
	dest_var="${src_var#$prefix}"
201
	local "$dest_var=${!src_var}"; echo_vars "$dest_var"
202
done
203
EOF
204
)"
205
206 8854 aaronmk
#### commands
207
208 8934 aaronmk
top_script="$0" # outermost script
209
top_dir="$(dirname "$top_script")"
210
top_file="${top_script%.run}"
211
top_filename="$(basename "$top_file")"
212 8272 aaronmk
213 8465 aaronmk
run_args_cmd () # runs the command line args command
214 8272 aaronmk
{
215 8971 aaronmk
	test $? -eq 0 || return
216 8693 aaronmk
	eval set -- "$(reverse "${BASH_ARGV[@]}")"
217 8971 aaronmk
	test $# -ge 1 || set -- all
218 8648 aaronmk
	echo_cmd "$(canon_rel_path "$0")" "$@"; "$@"
219 8272 aaronmk
}
220
221 8284 aaronmk
fwd () # usage: subdirs=(...); fwd "$FUNCNAME" "$@"
222 8272 aaronmk
{
223 8881 aaronmk
	echo_func
224 8284 aaronmk
	: "${subdirs?}"
225
226 8272 aaronmk
	for subdir in "${subdirs[@]}"; do
227 8280 aaronmk
		"$(dirname "${BASH_SOURCE[1]}")"/"$subdir"/run "$@"
228 8272 aaronmk
	done
229
}
230
231 8854 aaronmk
#### make
232
233 8881 aaronmk
# usage: target_filename/command () { echo_func; set_make_vars; ...; }
234 8880 aaronmk
alias set_make_vars="$(cat <<'EOF'
235
local command="${FUNCNAME##*/}"; echo_vars command
236
local target_filename="${FUNCNAME%/*}"; echo_vars target_filename
237
local target="$top_dir/$target_filename"; echo_vars target
238
EOF
239
)"
240
241 8959 aaronmk
make () { echo_func; stdout2stderr=1 self "$@"; }
242 8272 aaronmk
243 8276 aaronmk
if false; then ## usage:
244 8652 aaronmk
inline_make 3<<'EOF'
245 8276 aaronmk
target:
246
	$(self_dir)/cmd >$@
247
EOF
248
# target will be run automatically because it's first in the makefile
249
fi ##
250
inline_make ()
251
{
252 8881 aaronmk
	echo_func
253 8640 aaronmk
	local self="$(readlink -f "${BASH_SOURCE[1]}")"
254
	local self_dir="$(dirname "$self")"
255 8645 aaronmk
	export self self_dir
256 8640 aaronmk
257 8651 aaronmk
	make --makefile=<((
258 8652 aaronmk
		cat /dev/fd/3
259 8651 aaronmk
		echo -n "
260 8276 aaronmk
.SUFFIXES: # turn off built-in suffix rules
261
.SECONDARY: # don't automatically delete intermediate files
262
.DELETE_ON_ERROR: # delete target if recipe fails
263 8651 aaronmk
"
264
	)|echo_stdin) "$@"
265 8276 aaronmk
}
266 8658 aaronmk
267 8854 aaronmk
#### compression
268
269
### zip
270
271 8887 aaronmk
zip ()
272
{
273 8930 aaronmk
	stdout2stderr=1 try self "$@"
274 8887 aaronmk
	ignore 12 # "zip has nothing to do" (`man zip`)
275
	end_try
276
}
277
278 8930 aaronmk
unzip () { stdout2stderr=1 self "$@"; }
279 8902 aaronmk
280 8858 aaronmk
set_inv force
281 8974 aaronmk
alias zip_newer='zip ${no_force:+-u }'
282
alias unzip_newer='unzip ${no_force:+-u }-o'
283 8858 aaronmk
	# -o is safe because -u only extracts newer files
284 8704 aaronmk
285 8966 aaronmk
#### URLs
286
287
localize_url () { test _"$1" = _"$(hostname -f)" || echo "$1"; }
288
289 8775 aaronmk
#### databases
290
291 8868 aaronmk
# using prefixed connection vars
292 8975 aaronmk
alias use_local='declare prefix=local_; import_vars'
293
alias use_remote='declare prefix=remote_; import_vars'
294
alias use_local_remote='use_local; use_remote'
295 8864 aaronmk
296 8775 aaronmk
quote='"'
297
298
esc_name () { echo "$quote${1//$quote/$quote$quote}$quote"; }
299
300
mk_esc_name () { set_var "$1"_esc "$(esc_name "${!1}")"; }
301
302 8975 aaronmk
alias mk_schema_esc='declare schema_esc; mk_esc_name schema'
303
alias mk_table_esc='declare table_esc; mk_esc_name table'
304 8796 aaronmk
305
fi # load new aliases
306
if self_being_included; then
307
308
log_sql () { test "$verbosity" -ge 2; }
309
310
### MySQL
311
312 8862 aaronmk
# auto-adds connection/login opts when specified
313 8865 aaronmk
mysql_cmd () # usage: mysql* () { ...; mysql_cmd "$@"; }
314 8860 aaronmk
{
315 8881 aaronmk
	echo_func
316 8967 aaronmk
	local ssh_server="$(localize_url "$ssh_server")"
317 8968 aaronmk
	local server="$(localize_url "$server")"
318 8869 aaronmk
	if test -n "$ssh_server"; then
319
		local ssh_dest="${ssh_dest-${ssh_user:+$ssh_user@}$ssh_server}"
320
	fi
321 8875 aaronmk
	if test -n "$schema"; then local database="${database-$schema}"; fi
322 8869 aaronmk
323 8860 aaronmk
	local var=ssh_dest; local_inv
324 8910 aaronmk
	extern ${ssh_dest:+ssh "$ssh_dest" }"${FUNCNAME[1]}" \
325 8879 aaronmk
${server:+ --host="$server" }${user:+--user="$user" } --password\
326
${password+="$password"} ${database:+--databases "$database" --tables } "$@"
327 8860 aaronmk
}
328
329 8959 aaronmk
mysql () { echo_func; mysql_cmd --verbose "$@"; }
330 8775 aaronmk
331
mysql_ANSI ()
332
{
333 8881 aaronmk
	echo_func
334 8775 aaronmk
	(echo "SET sql_mode = 'ANSI';"; cat)|mysql "$@"
335
}
336
337 8866 aaronmk
mysqldump () # usage: [schema=1 | data=1] mysqldump db [table...]
338
{
339 8881 aaronmk
	echo_func
340 8866 aaronmk
	mysql_cmd --quick --lock-tables=false --set-charset \
341
${postgres_compat:+--compatible=postgresql --add-locks=false }\
342
${schema:+--no-data }${data:+--no-create-info }"$@"
343
}
344
345 8867 aaronmk
mysqldump_diffable ()
346
{
347 8881 aaronmk
	echo_func
348 8867 aaronmk
	mysqldump "$@"|sed 's/^(-- Dump completed).*$/\1/'
349
}
350
351 8796 aaronmk
### PostgreSQL
352
353
pg_copy_to ()
354
{
355 8881 aaronmk
	echo_func
356 8805 aaronmk
	if test -z "$source"; then
357
		: "${table:?}"; mk_table_esc
358 8834 aaronmk
		if test -z "$limit"; then local source="$table_esc"
359
		else local source="(SELECT * FROM $table_esc LIMIT $limit)"
360 8805 aaronmk
		fi
361
	fi
362 8834 aaronmk
	local pg_copy_format="${pg_copy_format-CSV HEADER}"
363 8805 aaronmk
364 8807 aaronmk
	psql "$@" <<<"COPY $source TO STDOUT $pg_copy_format;"
365 8796 aaronmk
}
366
367
pg_header ()
368
{
369 8881 aaronmk
	echo_func
370 8806 aaronmk
	local pg_copy_format="CSV HEADER" limit=0
371 8807 aaronmk
	pg_copy_to "$@"|echo_stdin
372 8796 aaronmk
}
373
374
pg_export_table_no_header ()
375
{
376 8881 aaronmk
	echo_func
377 8796 aaronmk
	local pg_copy_format="CSV"
378 8807 aaronmk
	pg_copy_to "$@"
379 8796 aaronmk
}
380
381
pg_export_table_to_dir_no_header ()
382
{
383 8881 aaronmk
	echo_func
384 8796 aaronmk
	local table="$1"; shift; mk_table_esc
385 8807 aaronmk
	local cols="$(pg_header)"
386 8796 aaronmk
	pg_export_table_no_header "$@" >"$exports_dir/$table.no_header.cols=$cols.csv"
387
}
388
389 8704 aaronmk
fi