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
# usage: try cmd...; ignore status; if catch status; then ...; fi; end_try
44

    
45
try_ () { { "$@"; e=$?;} || true; }
46
alias try='declare e; try_ ' # last space alias-expands next word
47

    
48
catch () { test "$e" -eq "$1"; e=0; }
49

    
50
ignore () { catch "$@" || true; }
51

    
52
alias end_try='rethrow'
53
alias end_try_subshell='rethrow_subshell'
54

    
55
#### integers
56

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

    
60
#### arrays
61

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

    
64
reverse () # usage: array=($(reverse args...))
65
{
66
	local i
67
	for (( i=$#; i >= 1; i-- )); do printf '%q ' "${!i}"; done
68
}
69

    
70
#### verbose output
71

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

    
76
: "${verbosity:=$verbose}" "${verbosity:=0}"
77

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

    
80
: "${log_indent=  }"
81

    
82
# usage: in func:      inc_log_level; ...
83
#        outside func: inc_log_level; ...; dec_log_level
84
alias inc_log_level='declare verbosity="$verbosity" PS4="$log_indent$PS4"
85
let verbosity--'
86
alias dec_log_level='declare verbosity="$verbosity" PS4="${PS4#$log_indent}"
87
let verbosity++'
88

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

    
93
log_stderr_cmd () # usage: [stdout2stderr=1] log_stderr_cmd cmd...
94
{
95
	(log_stderr
96
		if test -n "$stdout2stderr"; then stdout2stderr; fi
97
		"$@"
98
	) || return
99
}
100

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

    
103
echo_run () { echo_cmd "$@"; "$@"; }
104

    
105
alias echo_run_extern='echo_run log_stderr_cmd "extern"'
106

    
107
alias extern="echo_run_extern" # automatically echo external commands
108

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

    
111
# commands that are always external
112
for cmd in env; do alias "$cmd=extern $cmd"; done; unset cmd
113

    
114
canon_rel_path ()
115
{
116
	local path="$1"
117
	path="$(realpath "$path")" # canonicalize
118
	path="${path#$(pwd -P)/}" # remove any shared prefix with the current dir
119
	echo "$path"
120
}
121

    
122
fi # load new aliases
123
if self_being_included; then
124

    
125
function echo_func ()
126
{
127
	inc_log_level
128
	local script="$(canon_rel_path "${BASH_SOURCE[1]}")"
129
	echo_cmd "$script:${BASH_LINENO[0]}" "${FUNCNAME[1]}" "$@"
130
}
131

    
132
echo_stdin () # usage: input|echo_stdin|cmd
133
{
134
	inc_log_level
135
	if can_log; then
136
		sleep 0.1 # s; display after leading output of the echoed-to command
137
		echo ----- >&2
138
		tee -a /dev/stderr;
139
		echo ----- >&2
140
	else cat
141
	fi
142
}
143

    
144
echo_vars () # usage: echo_vars var...
145
{
146
	inc_log_level; inc_log_level
147
	if can_log; then
148
		local var
149
		for var in "${@%%=*}"; do { echo -n "$PS4"; declare -p "$var";} >&2;done
150
	fi
151
}
152

    
153
echo_export ()
154
{
155
	builtin export "$@"
156
	echo_vars "$@"
157
}
158

    
159
if test "$verbosity" -ge 2; then
160
	alias export="echo_export" # automatically echo env vars when they are set
161
fi
162

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

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

    
168
#### strings
169

    
170
sed_ere_flag="$(test "$(uname)" = Darwin && echo E || echo r)"
171

    
172
sed () { self -"$sed_ere_flag" "$@";}
173

    
174
#### vars
175

    
176
set_var () { eval "$1"'="$2"'; }
177

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

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

    
183
# usage: local prefix=..._; import_vars
184
alias import_vars="$(cat <<'EOF'
185
: "${prefix:?}"
186
local src_var dest_var
187
for src_var in $(eval echo '${!'$prefix'*}'); do
188
	dest_var="${src_var#$prefix}"
189
	local "$dest_var=${!src_var}"; echo_vars "$dest_var"
190
done
191
EOF
192
)"
193

    
194
#### commands
195

    
196
top_script="$0" # outermost script
197
top_dir="$(dirname "$top_script")"
198
top_file="${top_script%.run}"
199
top_filename="$(basename "$top_file")"
200

    
201
run_args_cmd () # runs the command line args command
202
{
203
	test $? -eq 0 || return
204
	eval set -- "$(reverse "${BASH_ARGV[@]}")"
205
	test $# -ge 1 || set -- all
206
	echo_cmd "$(canon_rel_path "$0")" "$@"; "$@"
207
}
208

    
209
fwd () # usage: subdirs=(...); fwd "$FUNCNAME" "$@"
210
{
211
	echo_func
212
	: "${subdirs?}"
213
	
214
	for subdir in "${subdirs[@]}"; do
215
		"$(dirname "${BASH_SOURCE[1]}")"/"$subdir"/run "$@"
216
	done
217
}
218

    
219
#### make
220

    
221
# usage: target_filename/command () { echo_func; set_make_vars; ...; }
222
alias set_make_vars="$(cat <<'EOF'
223
local command="${FUNCNAME##*/}"; echo_vars command
224
local target_filename="${FUNCNAME%/*}"; echo_vars target_filename
225
local target="$top_dir/$target_filename"; echo_vars target
226
EOF
227
)"
228

    
229
make () { echo_func; stdout2stderr=1 self "$@"; }
230

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

    
255
#### compression
256

    
257
### zip
258

    
259
zip ()
260
{
261
	stdout2stderr=1 try self "$@"
262
	ignore 12 # "zip has nothing to do" (`man zip`)
263
	end_try
264
}
265

    
266
unzip () { stdout2stderr=1 self "$@"; }
267

    
268
set_inv force
269
alias zip_newer='zip ${no_force:+-u }'
270
alias unzip_newer='unzip ${no_force:+-u }-o'
271
	# -o is safe because -u only extracts newer files
272

    
273
#### URLs
274

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

    
277
#### databases
278

    
279
# using prefixed connection vars
280
alias use_local='declare prefix=local_; import_vars'
281
alias use_remote='declare prefix=remote_; import_vars'
282
alias use_local_remote='use_local; use_remote'
283

    
284
quote='"'
285

    
286
esc_name () { echo "$quote${1//$quote/$quote$quote}$quote"; }
287

    
288
mk_esc_name () { set_var "$1"_esc "$(esc_name "${!1}")"; }
289

    
290
alias mk_schema_esc='declare schema_esc; mk_esc_name schema'
291
alias mk_table_esc='declare table_esc; mk_esc_name table'
292

    
293
fi # load new aliases
294
if self_being_included; then
295

    
296
log_sql () { test "$verbosity" -ge 2; }
297

    
298
### MySQL
299

    
300
# auto-adds connection/login opts when specified
301
mysql_cmd () # usage: mysql* () { ...; mysql_cmd "$@"; }
302
{
303
	echo_func
304
	local ssh_server="$(localize_url "$ssh_server")"
305
	local server="$(localize_url "$server")"
306
	if test -n "$ssh_server"; then
307
		local ssh_dest="${ssh_dest-${ssh_user:+$ssh_user@}$ssh_server}"
308
	fi
309
	if test -n "$schema"; then local database="${database-$schema}"; fi
310
	
311
	local var=ssh_dest; local_inv
312
	extern ${ssh_dest:+ssh "$ssh_dest" }"${FUNCNAME[1]}" \
313
${server:+ --host="$server" }${user:+--user="$user" } --password\
314
${password+="$password"} ${database:+--databases "$database" --tables } "$@"
315
}
316

    
317
mysql () { echo_func; mysql_cmd --verbose "$@"; }
318

    
319
mysql_ANSI ()
320
{
321
	echo_func
322
	(echo "SET sql_mode = 'ANSI';"; cat)|mysql "$@"
323
}
324

    
325
mysqldump () # usage: [schema=1 | data=1] mysqldump db [table...]
326
{
327
	echo_func
328
	mysql_cmd --quick --lock-tables=false --set-charset \
329
${postgres_compat:+--compatible=postgresql --add-locks=false }\
330
${schema:+--no-data }${data:+--no-create-info }"$@"
331
}
332

    
333
mysqldump_diffable ()
334
{
335
	echo_func
336
	mysqldump "$@"|sed 's/^(-- Dump completed).*$/\1/'
337
}
338

    
339
### PostgreSQL
340

    
341
pg_copy_to ()
342
{
343
	echo_func
344
	if test -z "$source"; then
345
		: "${table:?}"; mk_table_esc
346
		if test -z "$limit"; then local source="$table_esc"
347
		else local source="(SELECT * FROM $table_esc LIMIT $limit)"
348
		fi
349
	fi
350
	local pg_copy_format="${pg_copy_format-CSV HEADER}"
351
	
352
	psql "$@" <<<"COPY $source TO STDOUT $pg_copy_format;"
353
}
354

    
355
pg_header ()
356
{
357
	echo_func
358
	local pg_copy_format="CSV HEADER" limit=0
359
	pg_copy_to "$@"|echo_stdin
360
}
361

    
362
pg_export_table_no_header ()
363
{
364
	echo_func
365
	local pg_copy_format="CSV"
366
	pg_copy_to "$@"
367
}
368

    
369
pg_export_table_to_dir_no_header ()
370
{
371
	echo_func
372
	local table="$1"; shift; mk_table_esc
373
	local cols="$(pg_header)"
374
	pg_export_table_no_header "$@" >"$exports_dir/$table.no_header.cols=$cols.csv"
375
}
376

    
377
fi
(46-46/51)