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