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

    
35
try_ () { { "$@"; e="$?";} || true; }
36
alias try='declare e; try_ ' # trailing space alias-expands next word
37

    
38
catch () { test "$e" -eq "$1"; e=0; }
39

    
40
ignore () { catch "$@" || true; }
41

    
42
alias end_try='return "$e"'
43
alias end_try_subshell='exit "$e"'
44

    
45
#### integers
46

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

    
50
#### arrays
51

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

    
54
reverse () # usage: array=($(reverse args...))
55
{
56
	local i
57
	for (( i=$#; i >= 1; i-- )); do printf '%q ' "${!i}"; done
58
}
59

    
60
#### verbose output
61

    
62
# usage: (stdout2stderr; cmd...) || exit
63
# `|| exit` needed on Mac because of bug where -e doesn't apply to ()
64
stdout2stderr () { exec >&2; }
65

    
66
: "${verbosity:=$verbose}" "${verbosity:=0}"
67

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

    
70
: "${log_indent=  }"
71

    
72
# usage: in func:      inc_log_level; ...
73
#        outside func: inc_log_level; ...; dec_log_level
74
alias inc_log_level='declare verbosity="$verbosity" PS4="$log_indent$PS4"
75
let verbosity--'
76
alias dec_log_level='declare verbosity="$verbosity" PS4="${PS4#$log_indent}"
77
let verbosity++'
78

    
79
# usage: (log_stderr; cmd...) || exit
80
# `|| exit` needed on Mac because of bug where -e doesn't apply to ()
81
log_stderr () { if ! can_log; then exec 2>/dev/null; fi; }
82

    
83
log_stderr_cmd () # usage: [stdout2stderr=1] log_stderr_cmd cmd...
84
{
85
	(log_stderr
86
		if test -n "$stdout2stderr"; then stdout2stderr; fi
87
		"$@"
88
	) || return
89
}
90

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

    
93
echo_run () { echo_cmd "$@"; "$@"; }
94

    
95
alias echo_run_extern='echo_run log_stderr_cmd "extern"'
96

    
97
alias extern="echo_run_extern" # automatically echo external commands
98

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

    
101
# commands that are always external
102
for cmd in env; do alias "$cmd=extern $cmd"; done; unset cmd
103

    
104
canon_rel_path ()
105
{
106
	local path="$1"
107
	path="$(realpath "$path")" # canonicalize
108
	path="${path#$(pwd -P)/}" # remove any shared prefix with the current dir
109
	echo "$path"
110
}
111

    
112
fi # load new aliases
113
if self_being_included; then
114

    
115
function echo_func ()
116
{
117
	inc_log_level
118
	local script="$(canon_rel_path "${BASH_SOURCE[1]}")"
119
	echo_cmd "$script:${BASH_LINENO[0]}" "${FUNCNAME[1]}" "$@"
120
}
121

    
122
echo_stdin () # usage: input|echo_stdin|cmd
123
{
124
	inc_log_level
125
	if can_log; then
126
		sleep 0.1 # s; display after leading output of the echoed-to command
127
		echo ----- >&2
128
		tee -a /dev/stderr;
129
		echo ----- >&2
130
	else cat
131
	fi
132
}
133

    
134
echo_vars () # usage: echo_vars var...
135
{
136
	inc_log_level; inc_log_level
137
	if can_log; then
138
		local var
139
		for var in "${@%%=*}"; do { echo -n "$PS4"; declare -p "$var";} >&2;done
140
	fi
141
}
142

    
143
echo_export ()
144
{
145
	builtin export "$@"
146
	echo_vars "$@"
147
}
148

    
149
if test "$verbosity" -ge 2; then
150
	alias export="echo_export" # automatically echo env vars when they are set
151
fi
152

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

    
155
fi # load new aliases
156
if self_being_included; then
157

    
158
#### strings
159

    
160
sed_ere_flag="$(test "$(uname)" = Darwin && echo E || echo r)"
161

    
162
sed () { self -"$sed_ere_flag" "$@";}
163

    
164
#### vars
165

    
166
set_var () { eval "$1"'="$2"'; }
167

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

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

    
173
# usage: local prefix=..._; import_vars
174
alias import_vars="$(cat <<'EOF'
175
: "${prefix:?}"
176
local src_var dest_var
177
for src_var in $(eval echo '${!'$prefix'*}'); do
178
	dest_var="${src_var#$prefix}"
179
	local "$dest_var=${!src_var}"; echo_vars "$dest_var"
180
done
181
EOF
182
)"
183

    
184
#### commands
185

    
186
top_script="$0" # outermost script
187
top_dir="$(dirname "$top_script")"
188
top_file="${top_script%.run}"
189
top_filename="$(basename "$top_file")"
190

    
191
run_args_cmd () # runs the command line args command
192
{
193
	test "$?" -eq 0 || return
194
	eval set -- "$(reverse "${BASH_ARGV[@]}")"
195
	test "$#" -ge 1 || set -- all
196
	echo_cmd "$(canon_rel_path "$0")" "$@"; "$@"
197
}
198

    
199
fwd () # usage: subdirs=(...); fwd "$FUNCNAME" "$@"
200
{
201
	echo_func
202
	: "${subdirs?}"
203
	
204
	for subdir in "${subdirs[@]}"; do
205
		"$(dirname "${BASH_SOURCE[1]}")"/"$subdir"/run "$@"
206
	done
207
}
208

    
209
#### make
210

    
211
# usage: target_filename/command () { echo_func; set_make_vars; ...; }
212
alias set_make_vars="$(cat <<'EOF'
213
local command="${FUNCNAME##*/}"; echo_vars command
214
local target_filename="${FUNCNAME%/*}"; echo_vars target_filename
215
local target="$top_dir/$target_filename"; echo_vars target
216
EOF
217
)"
218

    
219
make () { echo_func; stdout2stderr=1 self "$@"; }
220

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

    
245
#### compression
246

    
247
### zip
248

    
249
zip ()
250
{
251
	stdout2stderr=1 try self "$@"
252
	ignore 12 # "zip has nothing to do" (`man zip`)
253
	end_try
254
}
255

    
256
unzip () { stdout2stderr=1 self "$@"; }
257

    
258
set_inv force
259
alias zip_newer="zip${no_force:+ -u}"
260
alias unzip_newer="unzip${no_force:+ -u} -o"
261
	# -o is safe because -u only extracts newer files
262

    
263
#### URLs
264

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

    
267
#### databases
268

    
269
# using prefixed connection vars
270
alias use_local="declare prefix=local_; import_vars"
271
alias use_remote="declare prefix=remote_; import_vars"
272
alias use_local_remote="use_local; use_remote"
273

    
274
quote='"'
275

    
276
esc_name () { echo "$quote${1//$quote/$quote$quote}$quote"; }
277

    
278
mk_esc_name () { set_var "$1"_esc "$(esc_name "${!1}")"; }
279

    
280
alias mk_schema_esc="declare schema_esc; mk_esc_name schema"
281
alias mk_table_esc="declare table_esc; mk_esc_name table"
282

    
283
fi # load new aliases
284
if self_being_included; then
285

    
286
log_sql () { test "$verbosity" -ge 2; }
287

    
288
### MySQL
289

    
290
# auto-adds connection/login opts when specified
291
mysql_cmd () # usage: mysql* () { ...; mysql_cmd "$@"; }
292
{
293
	echo_func
294
	local ssh_server="$(localize_url "$ssh_server")"
295
	local server="$(localize_url "$server")"
296
	if test -n "$ssh_server"; then
297
		local ssh_dest="${ssh_dest-${ssh_user:+$ssh_user@}$ssh_server}"
298
	fi
299
	if test -n "$schema"; then local database="${database-$schema}"; fi
300
	
301
	local var=ssh_dest; local_inv
302
	extern ${ssh_dest:+ssh "$ssh_dest" }"${FUNCNAME[1]}" \
303
${server:+ --host="$server" }${user:+--user="$user" } --password\
304
${password+="$password"} ${database:+--databases "$database" --tables } "$@"
305
}
306

    
307
mysql () { echo_func; mysql_cmd --verbose "$@"; }
308

    
309
mysql_ANSI ()
310
{
311
	echo_func
312
	(echo "SET sql_mode = 'ANSI';"; cat)|mysql "$@"
313
}
314

    
315
mysqldump () # usage: [schema=1 | data=1] mysqldump db [table...]
316
{
317
	echo_func
318
	mysql_cmd --quick --lock-tables=false --set-charset \
319
${postgres_compat:+--compatible=postgresql --add-locks=false }\
320
${schema:+--no-data }${data:+--no-create-info }"$@"
321
}
322

    
323
mysqldump_diffable ()
324
{
325
	echo_func
326
	mysqldump "$@"|sed 's/^(-- Dump completed).*$/\1/'
327
}
328

    
329
### PostgreSQL
330

    
331
pg_copy_to ()
332
{
333
	echo_func
334
	if test -z "$source"; then
335
		: "${table:?}"; mk_table_esc
336
		if test -z "$limit"; then local source="$table_esc"
337
		else local source="(SELECT * FROM $table_esc LIMIT $limit)"
338
		fi
339
	fi
340
	local pg_copy_format="${pg_copy_format-CSV HEADER}"
341
	
342
	psql "$@" <<<"COPY $source TO STDOUT $pg_copy_format;"
343
}
344

    
345
pg_header ()
346
{
347
	echo_func
348
	local pg_copy_format="CSV HEADER" limit=0
349
	pg_copy_to "$@"|echo_stdin
350
}
351

    
352
pg_export_table_no_header ()
353
{
354
	echo_func
355
	local pg_copy_format="CSV"
356
	pg_copy_to "$@"
357
}
358

    
359
pg_export_table_to_dir_no_header ()
360
{
361
	echo_func
362
	local table="$1"; shift; mk_table_esc
363
	local cols="$(pg_header)"
364
	pg_export_table_no_header "$@" >"$exports_dir/$table.no_header.cols=$cols.csv"
365
}
366

    
367
fi
(46-46/51)