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
isset () { test -n "${!1+isset}"; }
7

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

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

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

    
21
# to load newly-defined aliases for use in functions in the same file:
22
## fi # load new aliases
23
## if self_being_included; then
24
# this is needed because aliases defined inside an if statement are not
25
# available inside that if statement
26

    
27
if self_not_included "${BASH_SOURCE[0]}"; then
28

    
29
shopt -s expand_aliases
30

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

    
33
#### exceptions
34

    
35
alias rethrow='return "$e"'
36
alias rethrow_subshell='exit "$e"'
37

    
38
fi # load new aliases
39
if self_being_included; then
40

    
41
# usage: save_e cmd... || use $e (or $?)
42
function save_e () { "$@"; e=$?; rethrow; } # rethrow because e= clears $?
43
alias save_e='declare e; save_e ' # last space alias-expands next word
44

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

    
55
# usage: try cmd...; ignore status; if catch status; then ...; fi; end_try
56

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

    
60
catch () { test "$e" -eq "$1"; e=0; }
61

    
62
ignore () { catch "$@" || true; }
63

    
64
alias end_try='rethrow'
65
alias end_try_subshell='rethrow_subshell'
66

    
67
#### integers
68

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

    
72
bool2int () { save_e test -z "$1"; echo "$e"; } # empty->0; non-empty->1
73

    
74
#### arrays
75

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

    
78
reverse () # usage: array=($(reverse args...))
79
{
80
	local i
81
	for (( i=$#; i >= 1; i-- )); do printf '%q ' "${!i}"; done
82
}
83

    
84
#### verbose output
85

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

    
90
# set verbosity
91
if isset verbose; then : "${verbosity:=$(bool2int "$verbose")}"; fi
92
: "${verbosity=3}" # default
93
: "${verbosity:=0}" # ensure non-empty
94
declare -i verbosity # ensure integer
95
export verbosity # propagate the verbosity to invoked commands
96

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

    
99
: "${log_indent=  }"
100

    
101
# usage: in func:      inc_log_level; ...
102
#        outside func: inc_log_level; ...; dec_log_level
103
alias inc_log_level='declare verbosity="$verbosity" PS4="$log_indent$PS4"
104
let verbosity--'
105
alias dec_log_level='declare verbosity="$verbosity" PS4="${PS4#$log_indent}"
106
let verbosity++'
107

    
108
fi # load new aliases
109
if self_being_included; then
110

    
111
# usage: (limit_stderr; cmd...) || return
112
# `|| return` needed on Mac because of bug where -e doesn't apply to ()
113
limit_stderr () { inc_log_level; if ! can_log; then exec 2>/dev/null; fi; }
114

    
115
limit_stderr_cmd () # usage: [stdout2stderr=1] limit_stderr_cmd cmd...
116
{
117
	case "$1" in echo_run) shift; echo_cmd "$@";; esac
118
	(limit_stderr
119
		if test -n "$stdout2stderr"; then stdout2stderr; fi
120
		"$@"
121
	) || return
122
}
123
alias limit_stderr_cmd='limit_stderr_cmd ' # last space alias-expands next word
124

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

    
127
echo_run () { echo_cmd "$@"; "$@"; }
128

    
129
# auto-echo common external commands
130
for cmd in rm; do alias "$cmd=echo_run $cmd"; done; unset cmd
131

    
132
# limits stderr of (and echoes) an external command
133
alias limit_stderr_extern='limit_stderr_cmd echo_run "extern" '
134
	# last space alias-expands next word
135

    
136
# echo and limit stderr of all external commands
137
alias extern="limit_stderr_extern " # last space alias-expands next word
138

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

    
141
# commands that are always external
142
for cmd in env; do alias "$cmd=extern $cmd"; done; unset cmd
143

    
144
canon_rel_path ()
145
{
146
	local path="$1"
147
	path="$(realpath "$path")" # canonicalize
148
	path="${path#$(pwd -P)/}" # remove any shared prefix with the current dir
149
	echo "$path"
150
}
151

    
152
fi # load new aliases
153
if self_being_included; then
154

    
155
function echo_func ()
156
{
157
	inc_log_level
158
	local script="$(canon_rel_path "${BASH_SOURCE[1]}")"
159
	echo_cmd "$script:${BASH_LINENO[0]}" "${FUNCNAME[1]}" "$@"
160
}
161

    
162
# usage: cmd1 | { pipe_delay; cmd2; }
163
alias pipe_delay='sleep 0.1' # s; display after leading output of cmd1
164

    
165
fi # load new aliases
166
if self_being_included; then
167

    
168
echo_stdin () # usage: input|echo_stdin|cmd
169
{
170
	inc_log_level
171
	if can_log; then
172
		pipe_delay
173
		echo ----- >&2
174
		tee -a /dev/stderr;
175
		echo ----- >&2
176
	else cat
177
	fi
178
}
179

    
180
echo_vars () # usage: echo_vars var...
181
{
182
	inc_log_level; inc_log_level
183
	if can_log; then
184
		local var
185
		for var in "${@%%=*}"; do { echo -n "$PS4"; declare -p "$var";} >&2;done
186
	fi
187
}
188

    
189
echo_export ()
190
{
191
	builtin export "$@"
192
	echo_vars "$@"
193
}
194

    
195
if test "$verbosity" -ge 2; then
196
	alias export="echo_export" # automatically echo env vars when they are set
197
fi
198

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

    
201
fi # load new aliases
202
if self_being_included; then
203

    
204
#### strings
205

    
206
sed_ere_flag="$(test "$(uname)" = Darwin && echo E || echo r)"
207

    
208
sed () { self -"$sed_ere_flag" "$@";}
209

    
210
#### vars
211

    
212
set_var () { eval "$1"'="$2"'; }
213

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

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

    
219
# usage: local prefix=..._; import_vars
220
alias import_vars="$(cat <<'EOF'
221
: "${prefix:?}"
222
local src_var dest_var
223
for src_var in $(eval echo '${!'$prefix'*}'); do
224
	dest_var="${src_var#$prefix}"
225
	local "$dest_var=${!src_var}"; echo_vars "$dest_var"
226
done
227
EOF
228
)"
229

    
230
#### commands
231

    
232
top_script="$0" # outermost script
233
top_dir="$(dirname "$top_script")"
234

    
235
# auto-removes a command's output file on error (like make's .DELETE_ON_ERROR)
236
function to_file () # usage: stdout=... to_file cmd...
237
{ : "${stdout?}"; log_e "$@" >"$stdout" || { rm "$stdout"; rethrow; }; }
238
alias to_file='to_file ' # last space alias-expands next word
239

    
240
run_args_cmd () # runs the command line args command
241
{
242
	test $? -eq 0 || return
243
	eval set -- "$(reverse "${BASH_ARGV[@]}")"
244
	test $# -ge 1 || set -- all
245
	echo_cmd "$(canon_rel_path "$0")" "$@"; "$@"
246
}
247

    
248
fwd () # usage: subdirs=(...); fwd "$FUNCNAME" "$@"
249
{
250
	echo_func
251
	: "${subdirs?}"
252
	
253
	for subdir in "${subdirs[@]}"; do
254
		"$(dirname "${BASH_SOURCE[1]}")"/"$subdir"/run "$@"
255
	done
256
}
257

    
258
#### make
259

    
260
# usage: target_filename/command () { echo_func; set_make_vars; ...; }
261
alias set_make_vars="$(cat <<'EOF'
262
local command="${FUNCNAME##*/}"; echo_vars command
263
local target_filename="${FUNCNAME%/*}"; echo_vars target_filename
264
local target="$top_dir/$target_filename"; echo_vars target
265
EOF
266
)"
267

    
268
# usage: set_make_vars; check_target_exists
269
alias check_target_exists='! test -e "$target" || return 0'
270

    
271
# usage: set_make_vars; to_target cmd...
272
alias to_target='stdout="$target" to_file ' # last space alias-expands next word
273

    
274
make () { echo_func; stdout2stderr=1 self "$@"; }
275

    
276
if false; then ## usage:
277
inline_make 3<<'EOF'
278
target:
279
	$(self_dir)/cmd >$@
280
EOF
281
# target will be run automatically because it's first in the makefile
282
fi ##
283
inline_make ()
284
{
285
	echo_func
286
	local self="$(readlink -f "${BASH_SOURCE[1]}")"
287
	local self_dir="$(dirname "$self")"
288
	export self self_dir
289
	
290
	make --makefile=<((
291
		cat /dev/fd/3
292
		echo -n "
293
.SUFFIXES: # turn off built-in suffix rules
294
.SECONDARY: # don't automatically delete intermediate files
295
.DELETE_ON_ERROR: # delete target if recipe fails
296
"
297
	)|echo_stdin) "$@"
298
}
299

    
300
#### compression
301

    
302
### zip
303

    
304
zip ()
305
{
306
	stdout2stderr=1 try self "$@"
307
	ignore 12 # "zip has nothing to do" (`man zip`)
308
	end_try
309
}
310

    
311
unzip () { stdout2stderr=1 self "$@"; }
312

    
313
set_inv force
314
alias zip_newer='zip ${no_force:+-u }'
315
alias unzip_newer='unzip ${no_force:+-u }-o'
316
	# -o is safe because -u only extracts newer files
317

    
318
#### URLs
319

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

    
322
#### databases
323

    
324
# using prefixed connection vars
325
alias use_local='declare prefix=local_; import_vars'
326
alias use_remote='declare prefix=remote_; import_vars'
327
alias use_local_remote='use_local; use_remote'
328

    
329
quote='"'
330

    
331
esc_name () { echo "$quote${1//$quote/$quote$quote}$quote"; }
332

    
333
mk_esc_name () { set_var "$1"_esc "$(esc_name "${!1}")"; }
334

    
335
alias mk_schema_esc='declare schema_esc; mk_esc_name schema'
336
alias mk_table_esc='declare table_esc; mk_esc_name table'
337

    
338
fi # load new aliases
339
if self_being_included; then
340

    
341
log_sql () { test "$verbosity" -ge 2; }
342

    
343
### MySQL
344

    
345
# auto-adds connection/login opts when specified
346
mysql_cmd () # usage: mysql* () { ...; mysql_cmd "$@"; }
347
{
348
	echo_func
349
	local ssh_server="$(localize_url "$ssh_server")"
350
	local server="$(localize_url "$server")"
351
	if test -n "$ssh_server"; then
352
		local ssh_dest="${ssh_dest-${ssh_user:+$ssh_user@}$ssh_server}"
353
	fi
354
	if test -n "$schema"; then local database="${database-$schema}"; fi
355
	
356
	local var=ssh_dest; local_inv
357
	extern ${ssh_dest:+ssh "$ssh_dest" }"${FUNCNAME[1]}" \
358
${server:+ --host="$server" }${user:+--user="$user" } --password\
359
${password+="$password"} ${database:+--databases "$database" --tables } "$@"
360
}
361

    
362
mysql () { echo_func; mysql_cmd --verbose "$@"; }
363

    
364
mysql_ANSI ()
365
{
366
	echo_func
367
	(echo "SET sql_mode = 'ANSI';"; cat)|mysql "$@"
368
}
369

    
370
mysqldump () # usage: [schema=1 | data=1] mysqldump db [table...]
371
{
372
	echo_func
373
	mysql_cmd --quick --lock-tables=false --set-charset \
374
${postgres_compat:+--compatible=postgresql --add-locks=false }\
375
${schema:+--no-data }${data:+--no-create-info }"$@"
376
}
377

    
378
mysqldump_diffable ()
379
{
380
	echo_func
381
	mysqldump "$@"|sed 's/^(-- Dump completed).*$/\1/'
382
}
383

    
384
### PostgreSQL
385

    
386
pg_copy_to ()
387
{
388
	echo_func
389
	if test -z "$source"; then
390
		: "${table:?}"; mk_table_esc
391
		if test -z "$limit"; then local source="$table_esc"
392
		else local source="(SELECT * FROM $table_esc LIMIT $limit)"
393
		fi
394
	fi
395
	local pg_copy_format="${pg_copy_format-CSV HEADER}"
396
	
397
	psql "$@" <<<"COPY $source TO STDOUT $pg_copy_format;"
398
}
399

    
400
pg_header ()
401
{
402
	echo_func
403
	local pg_copy_format="CSV HEADER" limit=0
404
	pg_copy_to "$@"|echo_stdin
405
}
406

    
407
pg_export_table_no_header ()
408
{
409
	echo_func
410
	local pg_copy_format="CSV"
411
	pg_copy_to "$@"
412
}
413

    
414
pg_export_table_to_dir_no_header ()
415
{
416
	echo_func
417
	local table="$1"; shift; mk_table_esc
418
	local cols="$(pg_header)"
419
	pg_export_table_no_header "$@" >"$exports_dir/$table.no_header.cols=$cols.csv"
420
}
421

    
422
fi
(46-46/51)