Project

General

Profile

1
#!/bin/bash -e
2
set -o errexit # in case caller did not have -e in #! line
3

    
4
function extern () { (exec "$@") || return; }
5

    
6
realpath () { readlink -f -- "$1"; }
7

    
8
include_guard_var () { realpath "$1"|"extern" sed 's/[^a-zA-Z0-9_]/_/g'; }
9

    
10
self_not_included () # usage: if self_not_included; then ... fi
11
{
12
	test $# -ge 1 || set -- "${BASH_SOURCE[1]}"
13
	local include_guard="$(include_guard_var "$1")"
14
	alias self_being_included=false
15
	test -z "${!include_guard+t}" && \
16
	{ eval "$include_guard"=1; alias self_being_included=true; }
17
}
18

    
19
# 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
if self_not_included "${BASH_SOURCE[0]}"; then
26

    
27
shopt -s expand_aliases
28

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

    
31
#### exceptions
32

    
33
alias rethrow='return "$e"'
34
alias rethrow_subshell='exit "$e"'
35

    
36
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
function log_e () # usage: log_e cmd... [ || use $e (or $?) ]
44
{
45
	if ! save_e "$@"; then
46
		echo "! $*" >&2
47
		echo "! command exited with error $e" >&2
48
		rethrow
49
	fi
50
}
51
alias log_e='log_e ' # last space alias-expands next word
52

    
53
# usage: try cmd...; ignore status; if catch status; then ...; fi; end_try
54

    
55
function try () { "save_e" "$@" || true; }
56
alias try='declare e; try ' # last space alias-expands next word
57

    
58
catch () { test "$e" -eq "$1"; e=0; }
59

    
60
ignore () { catch "$@" || true; }
61

    
62
alias end_try='rethrow'
63
alias end_try_subshell='rethrow_subshell'
64

    
65
#### integers
66

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

    
70
#### arrays
71

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

    
74
reverse () # usage: array=($(reverse args...))
75
{
76
	local i
77
	for (( i=$#; i >= 1; i-- )); do printf '%q ' "${!i}"; done
78
}
79

    
80
#### verbose output
81

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

    
86
: "${verbosity:=$verbose}" "${verbosity:=0}"
87

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

    
90
: "${log_indent=  }"
91

    
92
# usage: in func:      inc_log_level; ...
93
#        outside func: inc_log_level; ...; dec_log_level
94
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

    
99
# usage: (log_stderr; cmd...) || return
100
# `|| return` needed on Mac because of bug where -e doesn't apply to ()
101
log_stderr () { if ! can_log; then exec 2>/dev/null; fi; }
102

    
103
log_stderr_cmd () # usage: [stdout2stderr=1] log_stderr_cmd cmd...
104
{
105
	(log_stderr
106
		if test -n "$stdout2stderr"; then stdout2stderr; fi
107
		"$@"
108
	) || return
109
}
110

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

    
113
echo_run () { echo_cmd "$@"; "$@"; }
114

    
115
alias echo_run_extern='echo_run log_stderr_cmd "extern"'
116

    
117
alias extern="echo_run_extern" # automatically echo external commands
118

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

    
121
# commands that are always external
122
for cmd in env; do alias "$cmd=extern $cmd"; done; unset cmd
123

    
124
canon_rel_path ()
125
{
126
	local path="$1"
127
	path="$(realpath "$path")" # canonicalize
128
	path="${path#$(pwd -P)/}" # remove any shared prefix with the current dir
129
	echo "$path"
130
}
131

    
132
fi # load new aliases
133
if self_being_included; then
134

    
135
function echo_func ()
136
{
137
	inc_log_level
138
	local script="$(canon_rel_path "${BASH_SOURCE[1]}")"
139
	echo_cmd "$script:${BASH_LINENO[0]}" "${FUNCNAME[1]}" "$@"
140
}
141

    
142
echo_stdin () # usage: input|echo_stdin|cmd
143
{
144
	inc_log_level
145
	if can_log; then
146
		sleep 0.1 # s; display after leading output of the echoed-to command
147
		echo ----- >&2
148
		tee -a /dev/stderr;
149
		echo ----- >&2
150
	else cat
151
	fi
152
}
153

    
154
echo_vars () # usage: echo_vars var...
155
{
156
	inc_log_level; inc_log_level
157
	if can_log; then
158
		local var
159
		for var in "${@%%=*}"; do { echo -n "$PS4"; declare -p "$var";} >&2;done
160
	fi
161
}
162

    
163
echo_export ()
164
{
165
	builtin export "$@"
166
	echo_vars "$@"
167
}
168

    
169
if test "$verbosity" -ge 2; then
170
	alias export="echo_export" # automatically echo env vars when they are set
171
fi
172

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

    
175
fi # load new aliases
176
if self_being_included; then
177

    
178
#### strings
179

    
180
sed_ere_flag="$(test "$(uname)" = Darwin && echo E || echo r)"
181

    
182
sed () { self -"$sed_ere_flag" "$@";}
183

    
184
#### vars
185

    
186
set_var () { eval "$1"'="$2"'; }
187

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

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

    
193
# usage: local prefix=..._; import_vars
194
alias import_vars="$(cat <<'EOF'
195
: "${prefix:?}"
196
local src_var dest_var
197
for src_var in $(eval echo '${!'$prefix'*}'); do
198
	dest_var="${src_var#$prefix}"
199
	local "$dest_var=${!src_var}"; echo_vars "$dest_var"
200
done
201
EOF
202
)"
203

    
204
#### commands
205

    
206
top_script="$0" # outermost script
207
top_dir="$(dirname "$top_script")"
208
top_file="${top_script%.run}"
209
top_filename="$(basename "$top_file")"
210

    
211
run_args_cmd () # runs the command line args command
212
{
213
	test $? -eq 0 || return
214
	eval set -- "$(reverse "${BASH_ARGV[@]}")"
215
	test $# -ge 1 || set -- all
216
	echo_cmd "$(canon_rel_path "$0")" "$@"; "$@"
217
}
218

    
219
fwd () # usage: subdirs=(...); fwd "$FUNCNAME" "$@"
220
{
221
	echo_func
222
	: "${subdirs?}"
223
	
224
	for subdir in "${subdirs[@]}"; do
225
		"$(dirname "${BASH_SOURCE[1]}")"/"$subdir"/run "$@"
226
	done
227
}
228

    
229
#### make
230

    
231
# usage: target_filename/command () { echo_func; set_make_vars; ...; }
232
alias set_make_vars="$(cat <<'EOF'
233
local command="${FUNCNAME##*/}"; echo_vars command
234
local target_filename="${FUNCNAME%/*}"; echo_vars target_filename
235
local target="$top_dir/$target_filename"; echo_vars target
236
EOF
237
)"
238

    
239
make () { echo_func; stdout2stderr=1 self "$@"; }
240

    
241
if false; then ## usage:
242
inline_make 3<<'EOF'
243
target:
244
	$(self_dir)/cmd >$@
245
EOF
246
# target will be run automatically because it's first in the makefile
247
fi ##
248
inline_make ()
249
{
250
	echo_func
251
	local self="$(readlink -f "${BASH_SOURCE[1]}")"
252
	local self_dir="$(dirname "$self")"
253
	export self self_dir
254
	
255
	make --makefile=<((
256
		cat /dev/fd/3
257
		echo -n "
258
.SUFFIXES: # turn off built-in suffix rules
259
.SECONDARY: # don't automatically delete intermediate files
260
.DELETE_ON_ERROR: # delete target if recipe fails
261
"
262
	)|echo_stdin) "$@"
263
}
264

    
265
#### compression
266

    
267
### zip
268

    
269
zip ()
270
{
271
	stdout2stderr=1 try self "$@"
272
	ignore 12 # "zip has nothing to do" (`man zip`)
273
	end_try
274
}
275

    
276
unzip () { stdout2stderr=1 self "$@"; }
277

    
278
set_inv force
279
alias zip_newer='zip ${no_force:+-u }'
280
alias unzip_newer='unzip ${no_force:+-u }-o'
281
	# -o is safe because -u only extracts newer files
282

    
283
#### URLs
284

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

    
287
#### databases
288

    
289
# using prefixed connection vars
290
alias use_local='declare prefix=local_; import_vars'
291
alias use_remote='declare prefix=remote_; import_vars'
292
alias use_local_remote='use_local; use_remote'
293

    
294
quote='"'
295

    
296
esc_name () { echo "$quote${1//$quote/$quote$quote}$quote"; }
297

    
298
mk_esc_name () { set_var "$1"_esc "$(esc_name "${!1}")"; }
299

    
300
alias mk_schema_esc='declare schema_esc; mk_esc_name schema'
301
alias mk_table_esc='declare table_esc; mk_esc_name table'
302

    
303
fi # load new aliases
304
if self_being_included; then
305

    
306
log_sql () { test "$verbosity" -ge 2; }
307

    
308
### MySQL
309

    
310
# auto-adds connection/login opts when specified
311
mysql_cmd () # usage: mysql* () { ...; mysql_cmd "$@"; }
312
{
313
	echo_func
314
	local ssh_server="$(localize_url "$ssh_server")"
315
	local server="$(localize_url "$server")"
316
	if test -n "$ssh_server"; then
317
		local ssh_dest="${ssh_dest-${ssh_user:+$ssh_user@}$ssh_server}"
318
	fi
319
	if test -n "$schema"; then local database="${database-$schema}"; fi
320
	
321
	local var=ssh_dest; local_inv
322
	extern ${ssh_dest:+ssh "$ssh_dest" }"${FUNCNAME[1]}" \
323
${server:+ --host="$server" }${user:+--user="$user" } --password\
324
${password+="$password"} ${database:+--databases "$database" --tables } "$@"
325
}
326

    
327
mysql () { echo_func; mysql_cmd --verbose "$@"; }
328

    
329
mysql_ANSI ()
330
{
331
	echo_func
332
	(echo "SET sql_mode = 'ANSI';"; cat)|mysql "$@"
333
}
334

    
335
mysqldump () # usage: [schema=1 | data=1] mysqldump db [table...]
336
{
337
	echo_func
338
	mysql_cmd --quick --lock-tables=false --set-charset \
339
${postgres_compat:+--compatible=postgresql --add-locks=false }\
340
${schema:+--no-data }${data:+--no-create-info }"$@"
341
}
342

    
343
mysqldump_diffable ()
344
{
345
	echo_func
346
	mysqldump "$@"|sed 's/^(-- Dump completed).*$/\1/'
347
}
348

    
349
### PostgreSQL
350

    
351
pg_copy_to ()
352
{
353
	echo_func
354
	if test -z "$source"; then
355
		: "${table:?}"; mk_table_esc
356
		if test -z "$limit"; then local source="$table_esc"
357
		else local source="(SELECT * FROM $table_esc LIMIT $limit)"
358
		fi
359
	fi
360
	local pg_copy_format="${pg_copy_format-CSV HEADER}"
361
	
362
	psql "$@" <<<"COPY $source TO STDOUT $pg_copy_format;"
363
}
364

    
365
pg_header ()
366
{
367
	echo_func
368
	local pg_copy_format="CSV HEADER" limit=0
369
	pg_copy_to "$@"|echo_stdin
370
}
371

    
372
pg_export_table_no_header ()
373
{
374
	echo_func
375
	local pg_copy_format="CSV"
376
	pg_copy_to "$@"
377
}
378

    
379
pg_export_table_to_dir_no_header ()
380
{
381
	echo_func
382
	local table="$1"; shift; mk_table_esc
383
	local cols="$(pg_header)"
384
	pg_export_table_no_header "$@" >"$exports_dir/$table.no_header.cols=$cols.csv"
385
}
386

    
387
fi
(46-46/51)