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;; esac
118
	echo_cmd "$@"
119
	(limit_stderr
120
		if test -n "$stdout2stderr"; then stdout2stderr; fi
121
		"$@"
122
	) || return
123
}
124
alias limit_stderr_cmd='limit_stderr_cmd ' # last space alias-expands next word
125

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
205
#### strings
206

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

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

    
211
#### vars
212

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

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

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

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

    
231
#### commands
232

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

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

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

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

    
259
#### make
260

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

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

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

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

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

    
301
#### compression
302

    
303
### zip
304

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

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

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

    
319
#### URLs
320

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

    
323
#### databases
324

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

    
330
quote='"'
331

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

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

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

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

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

    
344
### MySQL
345

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

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

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

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

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

    
385
### PostgreSQL
386

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

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

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

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

    
423
fi
(46-46/51)