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 8995 aaronmk
fi # load new aliases
100
if self_being_included; then
101
102 8994 aaronmk
# usage: (limit_stderr; cmd...) || return
103 8973 aaronmk
# `|| return` needed on Mac because of bug where -e doesn't apply to ()
104 8995 aaronmk
limit_stderr () { inc_log_level; if ! can_log; then exec 2>/dev/null; fi; }
105 8904 aaronmk
106 8994 aaronmk
limit_stderr_cmd () # usage: [stdout2stderr=1] limit_stderr_cmd cmd...
107 8915 aaronmk
{
108 8996 aaronmk
	echo_cmd "$@"
109 8994 aaronmk
	(limit_stderr
110 8915 aaronmk
		if test -n "$stdout2stderr"; then stdout2stderr; fi
111
		"$@"
112 8955 aaronmk
	) || return
113 8915 aaronmk
}
114 8911 aaronmk
115 8897 aaronmk
echo_cmd () { if can_log; then echo "$PS4$*" >&2; fi; }
116 8272 aaronmk
117 8278 aaronmk
echo_run () { echo_cmd "$@"; "$@"; }
118
119 8984 aaronmk
# auto-echo common external commands
120
for cmd in rm; do alias "$cmd=echo_run $cmd"; done; unset cmd
121
122 8994 aaronmk
# limits stderr of (and echoes) an external command
123 8996 aaronmk
alias limit_stderr_extern='limit_stderr_cmd "extern" '
124 8983 aaronmk
	# last space alias-expands next word
125 8906 aaronmk
126 8994 aaronmk
# echo and limit stderr of all external commands
127
alias extern="limit_stderr_extern " # last space alias-expands next word
128 8907 aaronmk
129 8929 aaronmk
alias self='extern "$FUNCNAME"' # usage: wrapper () { self ...; }
130
131 8908 aaronmk
# commands that are always external
132
for cmd in env; do alias "$cmd=extern $cmd"; done; unset cmd
133 8872 aaronmk
134 8646 aaronmk
canon_rel_path ()
135
{
136
	local path="$1"
137 8716 aaronmk
	path="$(realpath "$path")" # canonicalize
138 8773 aaronmk
	path="${path#$(pwd -P)/}" # remove any shared prefix with the current dir
139 8646 aaronmk
	echo "$path"
140
}
141
142 8909 aaronmk
fi # load new aliases
143 8884 aaronmk
if self_being_included; then
144
145 8909 aaronmk
function echo_func ()
146 8463 aaronmk
{
147 8901 aaronmk
	inc_log_level
148 8647 aaronmk
	local script="$(canon_rel_path "${BASH_SOURCE[1]}")"
149
	echo_cmd "$script:${BASH_LINENO[0]}" "${FUNCNAME[1]}" "$@"
150 8463 aaronmk
}
151 8885 aaronmk
152 8702 aaronmk
echo_stdin () # usage: input|echo_stdin|cmd
153
{
154 8901 aaronmk
	inc_log_level
155 8897 aaronmk
	if can_log; then
156 8960 aaronmk
		sleep 0.1 # s; display after leading output of the echoed-to command
157 8897 aaronmk
		echo ----- >&2
158
		tee -a /dev/stderr;
159
		echo ----- >&2
160
	else cat
161
	fi
162 8702 aaronmk
}
163 8275 aaronmk
164 8856 aaronmk
echo_vars () # usage: echo_vars var...
165 8901 aaronmk
{
166 8922 aaronmk
	inc_log_level; inc_log_level
167 8921 aaronmk
	if can_log; then
168
		local var
169
		for var in "${@%%=*}"; do { echo -n "$PS4"; declare -p "$var";} >&2;done
170
	fi
171 8901 aaronmk
}
172 8641 aaronmk
173
echo_export ()
174
{
175 8700 aaronmk
	builtin export "$@"
176 8641 aaronmk
	echo_vars "$@"
177
}
178
179 8713 aaronmk
if test "$verbosity" -ge 2; then
180 8711 aaronmk
	alias export="echo_export" # automatically echo env vars when they are set
181
fi
182 8642 aaronmk
183 8272 aaronmk
usage () { echo "Usage: $1" >&2; (exit 2); }
184
185 8873 aaronmk
fi # load new aliases
186
if self_being_included; then
187
188 8871 aaronmk
#### strings
189
190
sed_ere_flag="$(test "$(uname)" = Darwin && echo E || echo r)"
191
192 8930 aaronmk
sed () { self -"$sed_ere_flag" "$@";}
193 8871 aaronmk
194 8854 aaronmk
#### vars
195
196
set_var () { eval "$1"'="$2"'; }
197
198 8857 aaronmk
set_inv () { set_var no_"$1" "$(test -n "${!1}" || echo 1)"; }
199
200 8859 aaronmk
# usage: local var=...; local_inv
201 8888 aaronmk
alias local_inv='declare "no_$var=$(test -n "${!var}" || echo 1)"'
202 8859 aaronmk
203 8863 aaronmk
# usage: local prefix=..._; import_vars
204
alias import_vars="$(cat <<'EOF'
205
: "${prefix:?}"
206
local src_var dest_var
207
for src_var in $(eval echo '${!'$prefix'*}'); do
208
	dest_var="${src_var#$prefix}"
209
	local "$dest_var=${!src_var}"; echo_vars "$dest_var"
210
done
211
EOF
212
)"
213
214 8854 aaronmk
#### commands
215
216 8934 aaronmk
top_script="$0" # outermost script
217
top_dir="$(dirname "$top_script")"
218 8272 aaronmk
219 8986 aaronmk
# auto-removes a command's output file on error (like make's .DELETE_ON_ERROR)
220
function to_file () # usage: stdout=... to_file cmd...
221
{ : "${stdout?}"; log_e "$@" >"$stdout" || { rm "$stdout"; rethrow; }; }
222
alias to_file='to_file ' # last space alias-expands next word
223
224 8465 aaronmk
run_args_cmd () # runs the command line args command
225 8272 aaronmk
{
226 8971 aaronmk
	test $? -eq 0 || return
227 8693 aaronmk
	eval set -- "$(reverse "${BASH_ARGV[@]}")"
228 8971 aaronmk
	test $# -ge 1 || set -- all
229 8648 aaronmk
	echo_cmd "$(canon_rel_path "$0")" "$@"; "$@"
230 8272 aaronmk
}
231
232 8284 aaronmk
fwd () # usage: subdirs=(...); fwd "$FUNCNAME" "$@"
233 8272 aaronmk
{
234 8881 aaronmk
	echo_func
235 8284 aaronmk
	: "${subdirs?}"
236
237 8272 aaronmk
	for subdir in "${subdirs[@]}"; do
238 8280 aaronmk
		"$(dirname "${BASH_SOURCE[1]}")"/"$subdir"/run "$@"
239 8272 aaronmk
	done
240
}
241
242 8854 aaronmk
#### make
243
244 8881 aaronmk
# usage: target_filename/command () { echo_func; set_make_vars; ...; }
245 8880 aaronmk
alias set_make_vars="$(cat <<'EOF'
246
local command="${FUNCNAME##*/}"; echo_vars command
247
local target_filename="${FUNCNAME%/*}"; echo_vars target_filename
248
local target="$top_dir/$target_filename"; echo_vars target
249
EOF
250
)"
251
252 8989 aaronmk
# usage: set_make_vars; check_target_exists
253
alias check_target_exists='! test -e "$target" || return 0'
254
255 8987 aaronmk
# usage: set_make_vars; to_target cmd...
256
alias to_target='stdout="$target" to_file ' # last space alias-expands next word
257
258 8959 aaronmk
make () { echo_func; stdout2stderr=1 self "$@"; }
259 8272 aaronmk
260 8276 aaronmk
if false; then ## usage:
261 8652 aaronmk
inline_make 3<<'EOF'
262 8276 aaronmk
target:
263
	$(self_dir)/cmd >$@
264
EOF
265
# target will be run automatically because it's first in the makefile
266
fi ##
267
inline_make ()
268
{
269 8881 aaronmk
	echo_func
270 8640 aaronmk
	local self="$(readlink -f "${BASH_SOURCE[1]}")"
271
	local self_dir="$(dirname "$self")"
272 8645 aaronmk
	export self self_dir
273 8640 aaronmk
274 8651 aaronmk
	make --makefile=<((
275 8652 aaronmk
		cat /dev/fd/3
276 8651 aaronmk
		echo -n "
277 8276 aaronmk
.SUFFIXES: # turn off built-in suffix rules
278
.SECONDARY: # don't automatically delete intermediate files
279
.DELETE_ON_ERROR: # delete target if recipe fails
280 8651 aaronmk
"
281
	)|echo_stdin) "$@"
282 8276 aaronmk
}
283 8658 aaronmk
284 8854 aaronmk
#### compression
285
286
### zip
287
288 8887 aaronmk
zip ()
289
{
290 8930 aaronmk
	stdout2stderr=1 try self "$@"
291 8887 aaronmk
	ignore 12 # "zip has nothing to do" (`man zip`)
292
	end_try
293
}
294
295 8930 aaronmk
unzip () { stdout2stderr=1 self "$@"; }
296 8902 aaronmk
297 8858 aaronmk
set_inv force
298 8974 aaronmk
alias zip_newer='zip ${no_force:+-u }'
299
alias unzip_newer='unzip ${no_force:+-u }-o'
300 8858 aaronmk
	# -o is safe because -u only extracts newer files
301 8704 aaronmk
302 8966 aaronmk
#### URLs
303
304
localize_url () { test _"$1" = _"$(hostname -f)" || echo "$1"; }
305
306 8775 aaronmk
#### databases
307
308 8868 aaronmk
# using prefixed connection vars
309 8975 aaronmk
alias use_local='declare prefix=local_; import_vars'
310
alias use_remote='declare prefix=remote_; import_vars'
311
alias use_local_remote='use_local; use_remote'
312 8864 aaronmk
313 8775 aaronmk
quote='"'
314
315
esc_name () { echo "$quote${1//$quote/$quote$quote}$quote"; }
316
317
mk_esc_name () { set_var "$1"_esc "$(esc_name "${!1}")"; }
318
319 8975 aaronmk
alias mk_schema_esc='declare schema_esc; mk_esc_name schema'
320
alias mk_table_esc='declare table_esc; mk_esc_name table'
321 8796 aaronmk
322
fi # load new aliases
323
if self_being_included; then
324
325
log_sql () { test "$verbosity" -ge 2; }
326
327
### MySQL
328
329 8862 aaronmk
# auto-adds connection/login opts when specified
330 8865 aaronmk
mysql_cmd () # usage: mysql* () { ...; mysql_cmd "$@"; }
331 8860 aaronmk
{
332 8881 aaronmk
	echo_func
333 8967 aaronmk
	local ssh_server="$(localize_url "$ssh_server")"
334 8968 aaronmk
	local server="$(localize_url "$server")"
335 8869 aaronmk
	if test -n "$ssh_server"; then
336
		local ssh_dest="${ssh_dest-${ssh_user:+$ssh_user@}$ssh_server}"
337
	fi
338 8875 aaronmk
	if test -n "$schema"; then local database="${database-$schema}"; fi
339 8869 aaronmk
340 8860 aaronmk
	local var=ssh_dest; local_inv
341 8910 aaronmk
	extern ${ssh_dest:+ssh "$ssh_dest" }"${FUNCNAME[1]}" \
342 8879 aaronmk
${server:+ --host="$server" }${user:+--user="$user" } --password\
343
${password+="$password"} ${database:+--databases "$database" --tables } "$@"
344 8860 aaronmk
}
345
346 8959 aaronmk
mysql () { echo_func; mysql_cmd --verbose "$@"; }
347 8775 aaronmk
348
mysql_ANSI ()
349
{
350 8881 aaronmk
	echo_func
351 8775 aaronmk
	(echo "SET sql_mode = 'ANSI';"; cat)|mysql "$@"
352
}
353
354 8866 aaronmk
mysqldump () # usage: [schema=1 | data=1] mysqldump db [table...]
355
{
356 8881 aaronmk
	echo_func
357 8866 aaronmk
	mysql_cmd --quick --lock-tables=false --set-charset \
358
${postgres_compat:+--compatible=postgresql --add-locks=false }\
359
${schema:+--no-data }${data:+--no-create-info }"$@"
360
}
361
362 8867 aaronmk
mysqldump_diffable ()
363
{
364 8881 aaronmk
	echo_func
365 8867 aaronmk
	mysqldump "$@"|sed 's/^(-- Dump completed).*$/\1/'
366
}
367
368 8796 aaronmk
### PostgreSQL
369
370
pg_copy_to ()
371
{
372 8881 aaronmk
	echo_func
373 8805 aaronmk
	if test -z "$source"; then
374
		: "${table:?}"; mk_table_esc
375 8834 aaronmk
		if test -z "$limit"; then local source="$table_esc"
376
		else local source="(SELECT * FROM $table_esc LIMIT $limit)"
377 8805 aaronmk
		fi
378
	fi
379 8834 aaronmk
	local pg_copy_format="${pg_copy_format-CSV HEADER}"
380 8805 aaronmk
381 8807 aaronmk
	psql "$@" <<<"COPY $source TO STDOUT $pg_copy_format;"
382 8796 aaronmk
}
383
384
pg_header ()
385
{
386 8881 aaronmk
	echo_func
387 8806 aaronmk
	local pg_copy_format="CSV HEADER" limit=0
388 8807 aaronmk
	pg_copy_to "$@"|echo_stdin
389 8796 aaronmk
}
390
391
pg_export_table_no_header ()
392
{
393 8881 aaronmk
	echo_func
394 8796 aaronmk
	local pg_copy_format="CSV"
395 8807 aaronmk
	pg_copy_to "$@"
396 8796 aaronmk
}
397
398
pg_export_table_to_dir_no_header ()
399
{
400 8881 aaronmk
	echo_func
401 8796 aaronmk
	local table="$1"; shift; mk_table_esc
402 8807 aaronmk
	local cols="$(pg_header)"
403 8796 aaronmk
	pg_export_table_no_header "$@" >"$exports_dir/$table.no_header.cols=$cols.csv"
404
}
405
406 8704 aaronmk
fi