Project

General

Profile

1
#!/bin/bash -e
2
realpath () { readlink -f -- "$1"; }
3

    
4
include_guard_var () { realpath "$1"|sed 's/[^a-zA-Z0-9_]/_/g'; }
5

    
6
self_not_included () # usage: if self_not_included; then ... fi
7
{
8
	test "$#" -ge 1 || set -- "${BASH_SOURCE[1]}"
9
	local include_guard="$(include_guard_var "$1")"
10
	alias self_being_included=false
11
	test -z "${!include_guard+t}" && \
12
	{ eval "$include_guard"=1; alias self_being_included=true; }
13
}
14

    
15
# to load newly-defined aliases for use in functions in the same file:
16
## fi # load new aliases
17
## if self_being_included; then
18
# this is needed because aliases defined inside an if statement are not
19
# available inside that if statement
20

    
21
if self_not_included "${BASH_SOURCE[0]}"; then
22

    
23
shopt -s expand_aliases
24

    
25
unalias () { builtin unalias "$@" 2>&- || true; } # no error if undefined
26

    
27
#### exceptions
28

    
29
# usage: try cmd...; ignore status; if catch status; then ...; fi; end_try
30

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

    
34
catch () { test "$e" -eq "$1"; e=0; }
35

    
36
ignore () { catch "$@" || true; }
37

    
38
alias end_try='return "$e"'
39
alias end_try_subshell='exit "$e"'
40

    
41
#### integers
42

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

    
46
#### arrays
47

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

    
50
reverse () # usage: array=($(reverse args...))
51
{
52
	local i
53
	for (( i=$#; i >= 1; i-- )); do printf '%q ' "${!i}"; done
54
}
55

    
56
#### verbose output
57

    
58
: "${verbosity:=$verbose}" "${verbosity:=0}"
59

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

    
62
# usage: in func:      inc_log_level; ...
63
#        outside func: inc_log_level; ...; dec_log_level
64
alias inc_log_level='declare verbosity="$verbosity"; let verbosity--'
65
alias dec_log_level='declare verbosity="$verbosity"; let verbosity++'
66

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

    
69
echo_run () { echo_cmd "$@"; "$@"; }
70

    
71
if test "$verbosity" -ge 1; then
72
	alias env="echo_run env" # automatically echo commands that use env
73
fi
74

    
75
canon_rel_path ()
76
{
77
	local path="$1"
78
	path="$(realpath "$path")" # canonicalize
79
	path="${path#$(pwd -P)/}" # remove any shared prefix with the current dir
80
	echo "$path"
81
}
82

    
83
fi # allow unalias to take effect
84
unalias echo_func
85
if self_being_included; then
86

    
87
echo_func ()
88
{
89
	inc_log_level
90
	local script="$(canon_rel_path "${BASH_SOURCE[1]}")"
91
	echo_cmd "$script:${BASH_LINENO[0]}" "${FUNCNAME[1]}" "$@"
92
}
93

    
94
fi # always restore the alias
95
alias echo_func='"echo_func" "$@"' # usage: func () { echo_func; ...; }
96
if self_being_included; then
97

    
98
echo_stdin () # usage: input|echo_stdin|cmd
99
{
100
	inc_log_level
101
	if can_log; then
102
		echo ----- >&2
103
		tee -a /dev/stderr;
104
		echo ----- >&2
105
	else cat
106
	fi
107
}
108

    
109
echo_vars () # usage: echo_vars var...
110
{
111
	inc_log_level
112
	if can_log; then { echo -n "$PS4"; declare -p "${@%%=*}";} >&2; fi
113
}
114

    
115
echo_export ()
116
{
117
	builtin export "$@"
118
	echo_vars "$@"
119
}
120

    
121
if test "$verbosity" -ge 2; then
122
	alias export="echo_export" # automatically echo env vars when they are set
123
fi
124

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

    
127
fi # load new aliases
128
if self_being_included; then
129

    
130
#### strings
131

    
132
sed_ere_flag="$(test "$(uname)" = Darwin && echo E || echo r)"
133

    
134
sed () { env sed -"$sed_ere_flag" "$@";}
135

    
136
#### vars
137

    
138
set_var () { eval "$1"'="$2"'; }
139

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

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

    
145
# usage: local prefix=..._; import_vars
146
alias import_vars="$(cat <<'EOF'
147
: "${prefix:?}"
148
local src_var dest_var
149
for src_var in $(eval echo '${!'$prefix'*}'); do
150
	dest_var="${src_var#$prefix}"
151
	local "$dest_var=${!src_var}"; echo_vars "$dest_var"
152
done
153
EOF
154
)"
155

    
156
#### commands
157

    
158
top_dir="$(dirname "$0")" # outermost script
159

    
160
run_args_cmd () # runs the command line args command
161
{
162
	test "$?" -eq 0 || return
163
	eval set -- "$(reverse "${BASH_ARGV[@]}")"
164
	test "$#" -ge 1 || set -- all
165
	echo_cmd "$(canon_rel_path "$0")" "$@"; "$@"
166
}
167

    
168
fwd () # usage: subdirs=(...); fwd "$FUNCNAME" "$@"
169
{
170
	echo_func
171
	: "${subdirs?}"
172
	
173
	for subdir in "${subdirs[@]}"; do
174
		"$(dirname "${BASH_SOURCE[1]}")"/"$subdir"/run "$@"
175
	done
176
}
177

    
178
#### make
179

    
180
# usage: target_filename/command () { echo_func; set_make_vars; ...; }
181
alias set_make_vars="$(cat <<'EOF'
182
local command="${FUNCNAME##*/}"; echo_vars command
183
local target_filename="${FUNCNAME%/*}"; echo_vars target_filename
184
local target="$top_dir/$target_filename"; echo_vars target
185
EOF
186
)"
187

    
188
make ()
189
{
190
	echo_func
191
	env make --directory="$top_dir" "$@"
192
}
193

    
194
if false; then ## usage:
195
inline_make 3<<'EOF'
196
target:
197
	$(self_dir)/cmd >$@
198
EOF
199
# target will be run automatically because it's first in the makefile
200
fi ##
201
inline_make ()
202
{
203
	echo_func
204
	local self="$(readlink -f "${BASH_SOURCE[1]}")"
205
	local self_dir="$(dirname "$self")"
206
	export self self_dir
207
	
208
	make --makefile=<((
209
		cat /dev/fd/3
210
		echo -n "
211
.SUFFIXES: # turn off built-in suffix rules
212
.SECONDARY: # don't automatically delete intermediate files
213
.DELETE_ON_ERROR: # delete target if recipe fails
214
"
215
	)|echo_stdin) "$@"
216
}
217

    
218
#### compression
219

    
220
### zip
221

    
222
zip ()
223
{
224
	try env zip "$@" >&2
225
	ignore 12 # "zip has nothing to do" (`man zip`)
226
	end_try
227
}
228

    
229
unzip () { env unzip "$@" >&2; }
230

    
231
set_inv force
232
alias zip_newer="zip${no_force:+ -u}"
233
alias unzip_newer="unzip${no_force:+ -u} -o"
234
	# -o is safe because -u only extracts newer files
235

    
236
#### databases
237

    
238
# using prefixed connection vars
239
alias use_local="declare prefix=local_; import_vars"
240
alias use_remote="declare prefix=remote_; import_vars"
241
alias use_local_remote="use_local; use_remote"
242

    
243
quote='"'
244

    
245
esc_name () { echo "$quote${1//$quote/$quote$quote}$quote"; }
246

    
247
mk_esc_name () { set_var "$1"_esc "$(esc_name "${!1}")"; }
248

    
249
alias mk_schema_esc="declare schema_esc; mk_esc_name schema"
250
alias mk_table_esc="declare table_esc; mk_esc_name table"
251

    
252
fi # load new aliases
253
if self_being_included; then
254

    
255
log_sql () { test "$verbosity" -ge 2; }
256

    
257
### MySQL
258

    
259
# auto-adds connection/login opts when specified
260
mysql_cmd () # usage: mysql* () { ...; mysql_cmd "$@"; }
261
{
262
	echo_func
263
	if test _"$ssh_server" = _"$(hostname -f)"; then local ssh_server=; fi
264
	if test -n "$ssh_server"; then
265
		local ssh_dest="${ssh_dest-${ssh_user:+$ssh_user@}$ssh_server}"
266
	fi
267
	if test -n "$schema"; then local database="${database-$schema}"; fi
268
	
269
	local var=ssh_dest; local_inv
270
	echo_run ${no_ssh_dest:+env }${ssh_dest:+ssh "$ssh_dest" }"${FUNCNAME[1]}" \
271
${server:+ --host="$server" }${user:+--user="$user" } --password\
272
${password+="$password"} ${database:+--databases "$database" --tables } "$@"
273
}
274

    
275
mysql ()
276
{
277
	echo_func
278
	mysql_cmd --verbose "$@"
279
}
280

    
281
mysql_ANSI ()
282
{
283
	echo_func
284
	(echo "SET sql_mode = 'ANSI';"; cat)|mysql "$@"
285
}
286

    
287
mysqldump () # usage: [schema=1 | data=1] mysqldump db [table...]
288
{
289
	echo_func
290
	mysql_cmd --quick --lock-tables=false --set-charset \
291
${postgres_compat:+--compatible=postgresql --add-locks=false }\
292
${schema:+--no-data }${data:+--no-create-info }"$@"
293
}
294

    
295
mysqldump_diffable ()
296
{
297
	echo_func
298
	mysqldump "$@"|sed 's/^(-- Dump completed).*$/\1/'
299
}
300

    
301
### PostgreSQL
302

    
303
pg_copy_to ()
304
{
305
	echo_func
306
	if test -z "$source"; then
307
		: "${table:?}"; mk_table_esc
308
		if test -z "$limit"; then local source="$table_esc"
309
		else local source="(SELECT * FROM $table_esc LIMIT $limit)"
310
		fi
311
	fi
312
	local pg_copy_format="${pg_copy_format-CSV HEADER}"
313
	
314
	psql "$@" <<<"COPY $source TO STDOUT $pg_copy_format;"
315
}
316

    
317
pg_header ()
318
{
319
	echo_func
320
	local pg_copy_format="CSV HEADER" limit=0
321
	pg_copy_to "$@"|echo_stdin
322
}
323

    
324
pg_export_table_no_header ()
325
{
326
	echo_func
327
	local pg_copy_format="CSV"
328
	pg_copy_to "$@"
329
}
330

    
331
pg_export_table_to_dir_no_header ()
332
{
333
	echo_func
334
	local table="$1"; shift; mk_table_esc
335
	local cols="$(pg_header)"
336
	pg_export_table_no_header "$@" >"$exports_dir/$table.no_header.cols=$cols.csv"
337
}
338

    
339
fi
(46-46/51)