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
unalias () { builtin unalias "$@" 2>&- || true; } # no error if undefined
22

    
23
if self_not_included "${BASH_SOURCE[0]}"; then
24

    
25
shopt -s expand_aliases
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
echo_cmd () { echo "$PS4$*" >&2; }
55

    
56
echo_run () { echo_cmd "$@"; "$@"; }
57

    
58
if test "$verbosity" -ge 1; then
59
	alias env="echo_run env" # automatically echo commands that use env
60
fi
61

    
62
canon_rel_path ()
63
{
64
	local path="$1"
65
	path="$(realpath "$path")" # canonicalize
66
	path="${path#$(pwd -P)/}" # remove any shared prefix with the current dir
67
	echo "$path"
68
}
69

    
70
fi # allow unalias to take effect
71
unalias echo_func
72
if self_being_included; then
73

    
74
echo_func ()
75
{
76
	local script="$(canon_rel_path "${BASH_SOURCE[1]}")"
77
	echo_cmd "$script:${BASH_LINENO[0]}" "${FUNCNAME[1]}" "$@"
78
}
79

    
80
fi # always restore the alias
81
alias echo_func='"echo_func" "$@"' # usage: func () { echo_func; ...; }
82
if self_being_included; then
83

    
84
echo_stdin () # usage: input|echo_stdin|cmd
85
{
86
	echo ----- >&2
87
	tee -a /dev/stderr;
88
	echo ----- >&2
89
}
90

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

    
94
echo_export ()
95
{
96
	builtin export "$@"
97
	echo_vars "$@"
98
}
99

    
100
if test "$verbosity" -ge 2; then
101
	alias export="echo_export" # automatically echo env vars when they are set
102
fi
103

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

    
106
fi # load new aliases
107
if self_being_included; then
108

    
109
#### strings
110

    
111
sed_ere_flag="$(test "$(uname)" = Darwin && echo E || echo r)"
112

    
113
sed () { env sed -"$sed_ere_flag" "$@";}
114

    
115
#### vars
116

    
117
set_var () { eval "$1"'="$2"'; }
118

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

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

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

    
135
#### commands
136

    
137
top_dir="$(dirname "$0")" # outermost script
138

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

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

    
157
#### make
158

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

    
167
make ()
168
{
169
	echo_func
170
	env make --directory="$top_dir" "$@"
171
}
172

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

    
197
#### compression
198

    
199
### zip
200

    
201
zip ()
202
{
203
	try env zip "$@"
204
	ignore 12 # "zip has nothing to do" (`man zip`)
205
	end_try
206
}
207

    
208
alias unzip="echo_run unzip"
209
set_inv force
210
alias zip_newer="zip${no_force:+ -u}"
211
alias unzip_newer="unzip${no_force:+ -u} -o"
212
	# -o is safe because -u only extracts newer files
213

    
214
#### databases
215

    
216
# using prefixed connection vars
217
alias use_local="declare prefix=local_; import_vars"
218
alias use_remote="declare prefix=remote_; import_vars"
219
alias use_local_remote="use_local; use_remote"
220

    
221
quote='"'
222

    
223
esc_name () { echo "$quote${1//$quote/$quote$quote}$quote"; }
224

    
225
mk_esc_name () { set_var "$1"_esc "$(esc_name "${!1}")"; }
226

    
227
alias mk_schema_esc="declare schema_esc; mk_esc_name schema"
228
alias mk_table_esc="declare table_esc; mk_esc_name table"
229

    
230
fi # load new aliases
231
if self_being_included; then
232

    
233
log_sql () { test "$verbosity" -ge 2; }
234

    
235
### MySQL
236

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

    
253
mysql ()
254
{
255
	echo_func
256
	mysql_cmd --verbose "$@"
257
}
258

    
259
mysql_ANSI ()
260
{
261
	echo_func
262
	(echo "SET sql_mode = 'ANSI';"; cat)|mysql "$@"
263
}
264

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

    
273
mysqldump_diffable ()
274
{
275
	echo_func
276
	mysqldump "$@"|sed 's/^(-- Dump completed).*$/\1/'
277
}
278

    
279
### PostgreSQL
280

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

    
295
pg_header ()
296
{
297
	echo_func
298
	local pg_copy_format="CSV HEADER" limit=0
299
	pg_copy_to "$@"|echo_stdin
300
}
301

    
302
pg_export_table_no_header ()
303
{
304
	echo_func
305
	local pg_copy_format="CSV"
306
	pg_copy_to "$@"
307
}
308

    
309
pg_export_table_to_dir_no_header ()
310
{
311
	echo_func
312
	local table="$1"; shift; mk_table_esc
313
	local cols="$(pg_header)"
314
	pg_export_table_no_header "$@" >"$exports_dir/$table.no_header.cols=$cols.csv"
315
}
316

    
317
fi
(45-45/50)