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='declare 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
fi # load new aliases
100
if self_being_included; then
101

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

    
106
limit_stderr_cmd () # usage: [stdout2stderr=1] limit_stderr_cmd cmd...
107
{
108
	echo_cmd "$@"
109
	(limit_stderr
110
		if test -n "$stdout2stderr"; then stdout2stderr; fi
111
		"$@"
112
	) || return
113
}
114

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

    
117
echo_run () { echo_cmd "$@"; "$@"; }
118

    
119
# auto-echo common external commands
120
for cmd in rm; do alias "$cmd=echo_run $cmd"; done; unset cmd
121

    
122
# limits stderr of (and echoes) an external command
123
alias limit_stderr_extern='limit_stderr_cmd "extern" '
124
	# last space alias-expands next word
125

    
126
# echo and limit stderr of all external commands
127
alias extern="limit_stderr_extern " # last space alias-expands next word
128

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

    
131
# commands that are always external
132
for cmd in env; do alias "$cmd=extern $cmd"; done; unset cmd
133

    
134
canon_rel_path ()
135
{
136
	local path="$1"
137
	path="$(realpath "$path")" # canonicalize
138
	path="${path#$(pwd -P)/}" # remove any shared prefix with the current dir
139
	echo "$path"
140
}
141

    
142
fi # load new aliases
143
if self_being_included; then
144

    
145
function echo_func ()
146
{
147
	inc_log_level
148
	local script="$(canon_rel_path "${BASH_SOURCE[1]}")"
149
	echo_cmd "$script:${BASH_LINENO[0]}" "${FUNCNAME[1]}" "$@"
150
}
151

    
152
echo_stdin () # usage: input|echo_stdin|cmd
153
{
154
	inc_log_level
155
	if can_log; then
156
		sleep 0.1 # s; display after leading output of the echoed-to command
157
		echo ----- >&2
158
		tee -a /dev/stderr;
159
		echo ----- >&2
160
	else cat
161
	fi
162
}
163

    
164
echo_vars () # usage: echo_vars var...
165
{
166
	inc_log_level; inc_log_level
167
	if can_log; then
168
		local var
169
		for var in "${@%%=*}"; do { echo -n "$PS4"; declare -p "$var";} >&2;done
170
	fi
171
}
172

    
173
echo_export ()
174
{
175
	builtin export "$@"
176
	echo_vars "$@"
177
}
178

    
179
if test "$verbosity" -ge 2; then
180
	alias export="echo_export" # automatically echo env vars when they are set
181
fi
182

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

    
185
fi # load new aliases
186
if self_being_included; then
187

    
188
#### strings
189

    
190
sed_ere_flag="$(test "$(uname)" = Darwin && echo E || echo r)"
191

    
192
sed () { self -"$sed_ere_flag" "$@";}
193

    
194
#### vars
195

    
196
set_var () { eval "$1"'="$2"'; }
197

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

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

    
203
# 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
#### commands
215

    
216
top_script="$0" # outermost script
217
top_dir="$(dirname "$top_script")"
218

    
219
# 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
run_args_cmd () # runs the command line args command
225
{
226
	test $? -eq 0 || return
227
	eval set -- "$(reverse "${BASH_ARGV[@]}")"
228
	test $# -ge 1 || set -- all
229
	echo_cmd "$(canon_rel_path "$0")" "$@"; "$@"
230
}
231

    
232
fwd () # usage: subdirs=(...); fwd "$FUNCNAME" "$@"
233
{
234
	echo_func
235
	: "${subdirs?}"
236
	
237
	for subdir in "${subdirs[@]}"; do
238
		"$(dirname "${BASH_SOURCE[1]}")"/"$subdir"/run "$@"
239
	done
240
}
241

    
242
#### make
243

    
244
# usage: target_filename/command () { echo_func; set_make_vars; ...; }
245
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
# usage: set_make_vars; check_target_exists
253
alias check_target_exists='! test -e "$target" || return 0'
254

    
255
# usage: set_make_vars; to_target cmd...
256
alias to_target='stdout="$target" to_file ' # last space alias-expands next word
257

    
258
make () { echo_func; stdout2stderr=1 self "$@"; }
259

    
260
if false; then ## usage:
261
inline_make 3<<'EOF'
262
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
	echo_func
270
	local self="$(readlink -f "${BASH_SOURCE[1]}")"
271
	local self_dir="$(dirname "$self")"
272
	export self self_dir
273
	
274
	make --makefile=<((
275
		cat /dev/fd/3
276
		echo -n "
277
.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
"
281
	)|echo_stdin) "$@"
282
}
283

    
284
#### compression
285

    
286
### zip
287

    
288
zip ()
289
{
290
	stdout2stderr=1 try self "$@"
291
	ignore 12 # "zip has nothing to do" (`man zip`)
292
	end_try
293
}
294

    
295
unzip () { stdout2stderr=1 self "$@"; }
296

    
297
set_inv force
298
alias zip_newer='zip ${no_force:+-u }'
299
alias unzip_newer='unzip ${no_force:+-u }-o'
300
	# -o is safe because -u only extracts newer files
301

    
302
#### URLs
303

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

    
306
#### databases
307

    
308
# using prefixed connection vars
309
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

    
313
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
alias mk_schema_esc='declare schema_esc; mk_esc_name schema'
320
alias mk_table_esc='declare table_esc; mk_esc_name table'
321

    
322
fi # load new aliases
323
if self_being_included; then
324

    
325
log_sql () { test "$verbosity" -ge 2; }
326

    
327
### MySQL
328

    
329
# auto-adds connection/login opts when specified
330
mysql_cmd () # usage: mysql* () { ...; mysql_cmd "$@"; }
331
{
332
	echo_func
333
	local ssh_server="$(localize_url "$ssh_server")"
334
	local server="$(localize_url "$server")"
335
	if test -n "$ssh_server"; then
336
		local ssh_dest="${ssh_dest-${ssh_user:+$ssh_user@}$ssh_server}"
337
	fi
338
	if test -n "$schema"; then local database="${database-$schema}"; fi
339
	
340
	local var=ssh_dest; local_inv
341
	extern ${ssh_dest:+ssh "$ssh_dest" }"${FUNCNAME[1]}" \
342
${server:+ --host="$server" }${user:+--user="$user" } --password\
343
${password+="$password"} ${database:+--databases "$database" --tables } "$@"
344
}
345

    
346
mysql () { echo_func; mysql_cmd --verbose "$@"; }
347

    
348
mysql_ANSI ()
349
{
350
	echo_func
351
	(echo "SET sql_mode = 'ANSI';"; cat)|mysql "$@"
352
}
353

    
354
mysqldump () # usage: [schema=1 | data=1] mysqldump db [table...]
355
{
356
	echo_func
357
	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
mysqldump_diffable ()
363
{
364
	echo_func
365
	mysqldump "$@"|sed 's/^(-- Dump completed).*$/\1/'
366
}
367

    
368
### PostgreSQL
369

    
370
pg_copy_to ()
371
{
372
	echo_func
373
	if test -z "$source"; then
374
		: "${table:?}"; mk_table_esc
375
		if test -z "$limit"; then local source="$table_esc"
376
		else local source="(SELECT * FROM $table_esc LIMIT $limit)"
377
		fi
378
	fi
379
	local pg_copy_format="${pg_copy_format-CSV HEADER}"
380
	
381
	psql "$@" <<<"COPY $source TO STDOUT $pg_copy_format;"
382
}
383

    
384
pg_header ()
385
{
386
	echo_func
387
	local pg_copy_format="CSV HEADER" limit=0
388
	pg_copy_to "$@"|echo_stdin
389
}
390

    
391
pg_export_table_no_header ()
392
{
393
	echo_func
394
	local pg_copy_format="CSV"
395
	pg_copy_to "$@"
396
}
397

    
398
pg_export_table_to_dir_no_header ()
399
{
400
	echo_func
401
	local table="$1"; shift; mk_table_esc
402
	local cols="$(pg_header)"
403
	pg_export_table_no_header "$@" >"$exports_dir/$table.no_header.cols=$cols.csv"
404
}
405

    
406
fi
(46-46/51)