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
#### arrays
41

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

    
44
reverse () # usage: array=($(reverse args...))
45
{
46
	local i
47
	for (( i=$#; i >= 1; i-- )); do printf '%q ' "${!i}"; done
48
}
49

    
50
#### verbose output
51

    
52
: "${verbosity:=$verbose}" "${verbosity:=0}"
53

    
54
log_level=1 # must always be > 0 so verbosity=0 turns off all logging
55

    
56
can_log () { test "$log_level" -le "$verbosity"; }
57

    
58
echo_cmd () { echo "$PS4$*" >&2; }
59

    
60
echo_run () { echo_cmd "$@"; "$@"; }
61

    
62
if test "$verbosity" -ge 1; then
63
	alias env="echo_run env" # automatically echo commands that use env
64
fi
65

    
66
canon_rel_path ()
67
{
68
	local path="$1"
69
	path="$(realpath "$path")" # canonicalize
70
	path="${path#$(pwd -P)/}" # remove any shared prefix with the current dir
71
	echo "$path"
72
}
73

    
74
fi # allow unalias to take effect
75
unalias echo_func
76
if self_being_included; then
77

    
78
echo_func ()
79
{
80
	local script="$(canon_rel_path "${BASH_SOURCE[1]}")"
81
	echo_cmd "$script:${BASH_LINENO[0]}" "${FUNCNAME[1]}" "$@"
82
}
83

    
84
fi # always restore the alias
85
alias echo_func='"echo_func" "$@"' # usage: func () { echo_func; ...; }
86
if self_being_included; then
87

    
88
echo_stdin () # usage: input|echo_stdin|cmd
89
{
90
	echo ----- >&2
91
	tee -a /dev/stderr;
92
	echo ----- >&2
93
}
94

    
95
echo_vars () # usage: echo_vars var...
96
{ { echo -n "$PS4"; declare -p "${@%%=*}";} >&2; }
97

    
98
echo_export ()
99
{
100
	builtin export "$@"
101
	echo_vars "$@"
102
}
103

    
104
if test "$verbosity" -ge 2; then
105
	alias export="echo_export" # automatically echo env vars when they are set
106
fi
107

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

    
110
fi # load new aliases
111
if self_being_included; then
112

    
113
#### strings
114

    
115
sed_ere_flag="$(test "$(uname)" = Darwin && echo E || echo r)"
116

    
117
sed () { env sed -"$sed_ere_flag" "$@";}
118

    
119
#### vars
120

    
121
set_var () { eval "$1"'="$2"'; }
122

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

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

    
128
# usage: local prefix=..._; import_vars
129
alias import_vars="$(cat <<'EOF'
130
: "${prefix:?}"
131
local src_var dest_var
132
for src_var in $(eval echo '${!'$prefix'*}'); do
133
	dest_var="${src_var#$prefix}"
134
	local "$dest_var=${!src_var}"; echo_vars "$dest_var"
135
done
136
EOF
137
)"
138

    
139
#### commands
140

    
141
top_dir="$(dirname "$0")" # outermost script
142

    
143
run_args_cmd () # runs the command line args command
144
{
145
	test "$?" -eq 0 || return
146
	eval set -- "$(reverse "${BASH_ARGV[@]}")"
147
	test "$#" -ge 1 || set -- all
148
	echo_cmd "$(canon_rel_path "$0")" "$@"; "$@"
149
}
150

    
151
fwd () # usage: subdirs=(...); fwd "$FUNCNAME" "$@"
152
{
153
	echo_func
154
	: "${subdirs?}"
155
	
156
	for subdir in "${subdirs[@]}"; do
157
		"$(dirname "${BASH_SOURCE[1]}")"/"$subdir"/run "$@"
158
	done
159
}
160

    
161
#### make
162

    
163
# usage: target_filename/command () { echo_func; set_make_vars; ...; }
164
alias set_make_vars="$(cat <<'EOF'
165
local command="${FUNCNAME##*/}"; echo_vars command
166
local target_filename="${FUNCNAME%/*}"; echo_vars target_filename
167
local target="$top_dir/$target_filename"; echo_vars target
168
EOF
169
)"
170

    
171
make ()
172
{
173
	echo_func
174
	env make --directory="$top_dir" "$@"
175
}
176

    
177
if false; then ## usage:
178
inline_make 3<<'EOF'
179
target:
180
	$(self_dir)/cmd >$@
181
EOF
182
# target will be run automatically because it's first in the makefile
183
fi ##
184
inline_make ()
185
{
186
	echo_func
187
	local self="$(readlink -f "${BASH_SOURCE[1]}")"
188
	local self_dir="$(dirname "$self")"
189
	export self self_dir
190
	
191
	make --makefile=<((
192
		cat /dev/fd/3
193
		echo -n "
194
.SUFFIXES: # turn off built-in suffix rules
195
.SECONDARY: # don't automatically delete intermediate files
196
.DELETE_ON_ERROR: # delete target if recipe fails
197
"
198
	)|echo_stdin) "$@"
199
}
200

    
201
#### compression
202

    
203
### zip
204

    
205
zip ()
206
{
207
	try env zip "$@"
208
	ignore 12 # "zip has nothing to do" (`man zip`)
209
	end_try
210
}
211

    
212
alias unzip="echo_run unzip"
213
set_inv force
214
alias zip_newer="zip${no_force:+ -u}"
215
alias unzip_newer="unzip${no_force:+ -u} -o"
216
	# -o is safe because -u only extracts newer files
217

    
218
#### databases
219

    
220
# using prefixed connection vars
221
alias use_local="declare prefix=local_; import_vars"
222
alias use_remote="declare prefix=remote_; import_vars"
223
alias use_local_remote="use_local; use_remote"
224

    
225
quote='"'
226

    
227
esc_name () { echo "$quote${1//$quote/$quote$quote}$quote"; }
228

    
229
mk_esc_name () { set_var "$1"_esc "$(esc_name "${!1}")"; }
230

    
231
alias mk_schema_esc="declare schema_esc; mk_esc_name schema"
232
alias mk_table_esc="declare table_esc; mk_esc_name table"
233

    
234
fi # load new aliases
235
if self_being_included; then
236

    
237
log_sql () { test "$verbosity" -ge 2; }
238

    
239
### MySQL
240

    
241
# auto-adds connection/login opts when specified
242
mysql_cmd () # usage: mysql* () { ...; mysql_cmd "$@"; }
243
{
244
	echo_func
245
	if test _"$ssh_server" = _"$(hostname -f)"; then local ssh_server=; fi
246
	if test -n "$ssh_server"; then
247
		local ssh_dest="${ssh_dest-${ssh_user:+$ssh_user@}$ssh_server}"
248
	fi
249
	if test -n "$schema"; then local database="${database-$schema}"; fi
250
	
251
	local var=ssh_dest; local_inv
252
	echo_run ${no_ssh_dest:+env }${ssh_dest:+ssh "$ssh_dest" }"${FUNCNAME[1]}" \
253
${server:+ --host="$server" }${user:+--user="$user" } --password\
254
${password+="$password"} ${database:+--databases "$database" --tables } "$@"
255
}
256

    
257
mysql ()
258
{
259
	echo_func
260
	mysql_cmd --verbose "$@"
261
}
262

    
263
mysql_ANSI ()
264
{
265
	echo_func
266
	(echo "SET sql_mode = 'ANSI';"; cat)|mysql "$@"
267
}
268

    
269
mysqldump () # usage: [schema=1 | data=1] mysqldump db [table...]
270
{
271
	echo_func
272
	mysql_cmd --quick --lock-tables=false --set-charset \
273
${postgres_compat:+--compatible=postgresql --add-locks=false }\
274
${schema:+--no-data }${data:+--no-create-info }"$@"
275
}
276

    
277
mysqldump_diffable ()
278
{
279
	echo_func
280
	mysqldump "$@"|sed 's/^(-- Dump completed).*$/\1/'
281
}
282

    
283
### PostgreSQL
284

    
285
pg_copy_to ()
286
{
287
	echo_func
288
	if test -z "$source"; then
289
		: "${table:?}"; mk_table_esc
290
		if test -z "$limit"; then local source="$table_esc"
291
		else local source="(SELECT * FROM $table_esc LIMIT $limit)"
292
		fi
293
	fi
294
	local pg_copy_format="${pg_copy_format-CSV HEADER}"
295
	
296
	psql "$@" <<<"COPY $source TO STDOUT $pg_copy_format;"
297
}
298

    
299
pg_header ()
300
{
301
	echo_func
302
	local pg_copy_format="CSV HEADER" limit=0
303
	pg_copy_to "$@"|echo_stdin
304
}
305

    
306
pg_export_table_no_header ()
307
{
308
	echo_func
309
	local pg_copy_format="CSV"
310
	pg_copy_to "$@"
311
}
312

    
313
pg_export_table_to_dir_no_header ()
314
{
315
	echo_func
316
	local table="$1"; shift; mk_table_esc
317
	local cols="$(pg_header)"
318
	pg_export_table_no_header "$@" >"$exports_dir/$table.no_header.cols=$cols.csv"
319
}
320

    
321
fi
(46-46/51)