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
# 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
	# last space alias-expands next word
117

    
118
# automatically echo external commands
119
alias extern="echo_run_extern " # last space alias-expands next word
120

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

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

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

    
134
fi # load new aliases
135
if self_being_included; then
136

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

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

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

    
165
echo_export ()
166
{
167
	builtin export "$@"
168
	echo_vars "$@"
169
}
170

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

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

    
177
fi # load new aliases
178
if self_being_included; then
179

    
180
#### strings
181

    
182
sed_ere_flag="$(test "$(uname)" = Darwin && echo E || echo r)"
183

    
184
sed () { self -"$sed_ere_flag" "$@";}
185

    
186
#### vars
187

    
188
set_var () { eval "$1"'="$2"'; }
189

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

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

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

    
206
#### commands
207

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

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

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

    
231
#### make
232

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

    
241
make () { echo_func; stdout2stderr=1 self "$@"; }
242

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

    
267
#### compression
268

    
269
### zip
270

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

    
278
unzip () { stdout2stderr=1 self "$@"; }
279

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

    
285
#### URLs
286

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

    
289
#### databases
290

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

    
296
quote='"'
297

    
298
esc_name () { echo "$quote${1//$quote/$quote$quote}$quote"; }
299

    
300
mk_esc_name () { set_var "$1"_esc "$(esc_name "${!1}")"; }
301

    
302
alias mk_schema_esc='declare schema_esc; mk_esc_name schema'
303
alias mk_table_esc='declare table_esc; mk_esc_name table'
304

    
305
fi # load new aliases
306
if self_being_included; then
307

    
308
log_sql () { test "$verbosity" -ge 2; }
309

    
310
### MySQL
311

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

    
329
mysql () { echo_func; mysql_cmd --verbose "$@"; }
330

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

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

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

    
351
### PostgreSQL
352

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

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

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

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

    
389
fi
(46-46/51)