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

    
40
#### integers
41

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

    
45
#### arrays
46

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

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

    
55
#### verbose output
56

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

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

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

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

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

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

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

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

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

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

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

    
106
echo_vars () # usage: echo_vars var...
107
{ if can_log; then { echo -n "$PS4"; declare -p "${@%%=*}";} >&2; fi; }
108

    
109
echo_export ()
110
{
111
	builtin export "$@"
112
	echo_vars "$@"
113
}
114

    
115
if test "$verbosity" -ge 2; then
116
	alias export="echo_export" # automatically echo env vars when they are set
117
fi
118

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

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

    
124
#### strings
125

    
126
sed_ere_flag="$(test "$(uname)" = Darwin && echo E || echo r)"
127

    
128
sed () { env sed -"$sed_ere_flag" "$@";}
129

    
130
#### vars
131

    
132
set_var () { eval "$1"'="$2"'; }
133

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

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

    
139
# usage: local prefix=..._; import_vars
140
alias import_vars="$(cat <<'EOF'
141
: "${prefix:?}"
142
local src_var dest_var
143
for src_var in $(eval echo '${!'$prefix'*}'); do
144
	dest_var="${src_var#$prefix}"
145
	local "$dest_var=${!src_var}"; echo_vars "$dest_var"
146
done
147
EOF
148
)"
149

    
150
#### commands
151

    
152
top_dir="$(dirname "$0")" # outermost script
153

    
154
run_args_cmd () # runs the command line args command
155
{
156
	test "$?" -eq 0 || return
157
	eval set -- "$(reverse "${BASH_ARGV[@]}")"
158
	test "$#" -ge 1 || set -- all
159
	echo_cmd "$(canon_rel_path "$0")" "$@"; "$@"
160
}
161

    
162
fwd () # usage: subdirs=(...); fwd "$FUNCNAME" "$@"
163
{
164
	echo_func
165
	: "${subdirs?}"
166
	
167
	for subdir in "${subdirs[@]}"; do
168
		"$(dirname "${BASH_SOURCE[1]}")"/"$subdir"/run "$@"
169
	done
170
}
171

    
172
#### make
173

    
174
# usage: target_filename/command () { echo_func; set_make_vars; ...; }
175
alias set_make_vars="$(cat <<'EOF'
176
local command="${FUNCNAME##*/}"; echo_vars command
177
local target_filename="${FUNCNAME%/*}"; echo_vars target_filename
178
local target="$top_dir/$target_filename"; echo_vars target
179
EOF
180
)"
181

    
182
make ()
183
{
184
	echo_func
185
	env make --directory="$top_dir" "$@"
186
}
187

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

    
212
#### compression
213

    
214
### zip
215

    
216
zip ()
217
{
218
	try env zip "$@"
219
	ignore 12 # "zip has nothing to do" (`man zip`)
220
	end_try
221
}
222

    
223
alias unzip="echo_run unzip"
224
set_inv force
225
alias zip_newer="zip${no_force:+ -u}"
226
alias unzip_newer="unzip${no_force:+ -u} -o"
227
	# -o is safe because -u only extracts newer files
228

    
229
#### databases
230

    
231
# using prefixed connection vars
232
alias use_local="declare prefix=local_; import_vars"
233
alias use_remote="declare prefix=remote_; import_vars"
234
alias use_local_remote="use_local; use_remote"
235

    
236
quote='"'
237

    
238
esc_name () { echo "$quote${1//$quote/$quote$quote}$quote"; }
239

    
240
mk_esc_name () { set_var "$1"_esc "$(esc_name "${!1}")"; }
241

    
242
alias mk_schema_esc="declare schema_esc; mk_esc_name schema"
243
alias mk_table_esc="declare table_esc; mk_esc_name table"
244

    
245
fi # load new aliases
246
if self_being_included; then
247

    
248
log_sql () { test "$verbosity" -ge 2; }
249

    
250
### MySQL
251

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

    
268
mysql ()
269
{
270
	echo_func
271
	mysql_cmd --verbose "$@"
272
}
273

    
274
mysql_ANSI ()
275
{
276
	echo_func
277
	(echo "SET sql_mode = 'ANSI';"; cat)|mysql "$@"
278
}
279

    
280
mysqldump () # usage: [schema=1 | data=1] mysqldump db [table...]
281
{
282
	echo_func
283
	mysql_cmd --quick --lock-tables=false --set-charset \
284
${postgres_compat:+--compatible=postgresql --add-locks=false }\
285
${schema:+--no-data }${data:+--no-create-info }"$@"
286
}
287

    
288
mysqldump_diffable ()
289
{
290
	echo_func
291
	mysqldump "$@"|sed 's/^(-- Dump completed).*$/\1/'
292
}
293

    
294
### PostgreSQL
295

    
296
pg_copy_to ()
297
{
298
	echo_func
299
	if test -z "$source"; then
300
		: "${table:?}"; mk_table_esc
301
		if test -z "$limit"; then local source="$table_esc"
302
		else local source="(SELECT * FROM $table_esc LIMIT $limit)"
303
		fi
304
	fi
305
	local pg_copy_format="${pg_copy_format-CSV HEADER}"
306
	
307
	psql "$@" <<<"COPY $source TO STDOUT $pg_copy_format;"
308
}
309

    
310
pg_header ()
311
{
312
	echo_func
313
	local pg_copy_format="CSV HEADER" limit=0
314
	pg_copy_to "$@"|echo_stdin
315
}
316

    
317
pg_export_table_no_header ()
318
{
319
	echo_func
320
	local pg_copy_format="CSV"
321
	pg_copy_to "$@"
322
}
323

    
324
pg_export_table_to_dir_no_header ()
325
{
326
	echo_func
327
	local table="$1"; shift; mk_table_esc
328
	local cols="$(pg_header)"
329
	pg_export_table_no_header "$@" >"$exports_dir/$table.no_header.cols=$cols.csv"
330
}
331

    
332
fi
(46-46/51)