-
Notifications
You must be signed in to change notification settings - Fork 12
/
stdfunc
399 lines (350 loc) · 10.4 KB
/
stdfunc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
#!/usr/bin/env bash
export PS4='+ [`basename ${BASH_SOURCE[0]}`:$LINENO ${FUNCNAME[0]} \D{%F %T} $$ ] '
# The number of jobs to pass to tools that can run in parallel (such as make
# and dpkg-buildpackage
if [[ -z ${NUM_JOBS} && -e "/proc/cpuinfo" ]]; then
NUM_JOBS=$(grep -c "^processor" /proc/cpuinfo)
fi
# Ensure that any sub scripts we invoke get the max proc count.
export NUM_JOBS
pidof() {
ps acx | egrep -i $@ | awk '{print $1}'
}
# Make sure we have the location and name of the calling script, using
# the current value if it is already set.
#: ${SCRIPT_LOCATION:=$(dirname "$(readlink -f "$0")")}
: ${SCRIPT_LOCATION:=$(cd "$(dirname "$0")"; pwd)}
: ${SCRIPT_NAME:=$(basename "$0")}
# Determine and set up variables needed for fancy color output (if supported).
V_BOLD_RED=
V_BOLD_GREEN=
V_BOLD_YELLOW=
V_REVERSE=
V_VIDOFF=
if tput colors >&/dev/null; then
# order matters: we want VIDOFF last so that when we trace with `set -x`,
# our terminal doesn't bleed colors as bash dumps the values of vars.
V_BOLD_RED=$(tput bold; tput setaf 1)
V_BOLD_GREEN=$(tput bold; tput setaf 2)
V_BOLD_YELLOW=$(tput bold; tput setaf 3)
V_REVERSE=$(tput rev)
V_VIDOFF=$(tput sgr0)
fi
# Declare these asap so that code below can safely assume they exist.
_message() {
local prefix="$1${CROS_LOG_PREFIX:-${SCRIPT_NAME}}"
shift
if [[ $# -eq 0 ]]; then
echo -e "${prefix}:${V_VIDOFF}" >&2
return
fi
(
# Handle newlines in the message, prefixing each chunk correctly.
# Do this in a subshell to avoid having to track IFS/set -f state.
IFS="
"
set +f
set -- $*
IFS=' '
if [[ $# -eq 0 ]]; then
# Empty line was requested.
set -- ''
fi
for line in "$@"; do
echo -e "${prefix}: ${line}${V_VIDOFF}" >&2
done
)
}
info() {
_message "${V_BOLD_GREEN}INFO " "$*"
}
warn() {
_message "${V_BOLD_YELLOW}WARNING " "$*"
}
error() {
_message "${V_BOLD_RED}ERROR " "$*"
}
# Output a backtrace all the way back to the raw invocation, suppressing
# only the _dump_trace frame itself.
_dump_trace() {
local j n p func src line args
p=${#BASH_ARGV[@]}
for (( n = ${#FUNCNAME[@]}; n > 1; --n )); do
func=${FUNCNAME[${n} - 1]}
src=${BASH_SOURCE[${n}]##*/}
line=${BASH_LINENO[${n} - 1]}
args=
if [[ -z ${BASH_ARGC[${n} -1]} ]]; then
args='(args unknown, no debug available)'
else
for (( j = 0; j < ${BASH_ARGC[${n} -1]}; ++j )); do
args="${args:+${args} }'${BASH_ARGV[$(( p - j - 1 ))]}'"
done
! (( p -= ${BASH_ARGC[${n} - 1]} ))
fi
if [[ ${n} == ${#FUNCNAME[@]} ]]; then
error "script called: ${0##*/} ${args}"
error "Backtrace: (most recent call is last)"
else
error "$(printf ' file %s, line %s, called: %s %s' \
"${src}" "${line}" "${func}" "${args}")"
fi
done
}
# For all die functions, they must explicitly force set +eu;
# no reason to have them cause their own crash if we're inthe middle
# of reporting an error condition then exiting.
die_err_trap() {
local command=$1 result=$2
set +e +u
# Per the message, bash misreports 127 as 1 during err trap sometimes.
# Note this fact to ensure users don't place too much faith in the
# exit code in that case.
set -- "Command '${command}' exited with nonzero code: ${result}"
if [[ ${result} -eq 1 ]] && [[ -z $(type -t ${command}) ]]; then
set -- "$@" \
'(Note bash sometimes misreports "command not found" as exit code 1 '\
'instead of 127)'
fi
_dump_trace
error
error "Command failed:"
DIE_PREFIX=' '
die_notrace "$@"
}
# Exit this script due to a failure, outputting a backtrace in the process.
die() {
set +e +u
_dump_trace
error
error "Error was:"
DIE_PREFIX=' '
die_notrace "$@"
}
# Exit this script w/out a backtrace.
die_notrace() {
set +e +u
if [[ $# -eq 0 ]]; then
set -- '(no error message given)'
fi
local line
for line in "$@"; do
error "${DIE_PREFIX}${line}"
done
exit 1
}
assert_not_root_user() {
if [[ ${UID:-$(id -u)} == 0 ]]; then
echo "This script must be run as a non-root user."
exit 1
fi
}
assert_root_user() {
if [[ ${UID:-$(id -u)} != 0 ]] || [[ ${SUDO_USER:-root} == "root" ]]; then
die_notrace "This script must be run using sudo from a non-root user."
fi
}
# Create the specified symlink as the sudo user.
#
# $1 - Link target
# $2 - Link name
user_symlink() {
ln -sfT "$1" "$2"
chown -h ${SUDO_UID}:${SUDO_GID} "$2"
}
# Copies the specified file owned by the user to the specified location.
# If the copy fails as root (e.g. due to root_squash and NFS), retry the copy
# with the user's account before failing.
user_cp() {
cp -p "$@" 2>/dev/null || sudo -u ${SUDO_USER} -- cp -p "$@"
}
# Generate a DIGESTS file, as normally used by Gentoo.
# This is an alternative to shash which doesn't know how to report errors.
# Usage: make_digests -d file.DIGESTS file1 [file2...]
_digest_types="md5 sha1 sha512"
make_digests() {
[[ "$1" == "-d" ]] || die
local digests="$(readlink -f "$2")"
shift 2
pushd "$(dirname "$1")" >/dev/null
echo -n > "${digests}"
for filename in "$@"; do
filename=$(basename "$filename")
info "Computing DIGESTS for ${filename}"
for hash_type in $_digest_types; do
echo "# $hash_type HASH" | tr "a-z" "A-Z" >> "${digests}"
${hash_type}sum "${filename}" >> "${digests}"
done
done
popd >/dev/null
}
# Validate a DIGESTS file. Essentially the inverse of make_digests.
# Usage: verify_digests [-d file.DIGESTS] file1 [file2...]
# If -d is not specified file1.DIGESTS will be used
verify_digests() {
local digests
if [[ "$1" == "-d" ]]; then
[[ -n "$2" ]] || die "-d requires an argument"
digests="$(readlink -f "$2")"
shift 2
else
digests=$(basename "${1}.DIGESTS")
fi
pushd "$(dirname "$1")" >/dev/null
for filename in "$@"; do
filename=$(basename "$filename")
info "Validating DIGESTS for ${filename}"
for hash_type in $_digest_types; do
grep -A1 -i "^# ${hash_type} HASH$" "${digests}" | \
grep "$filename$" | ${hash_type}sum -c - --strict || return 1
# Also check that none of the greps failed in the above pipeline
[[ -z ${PIPESTATUS[*]#0} ]] || return 1
done
done
popd >/dev/null
}
# Get current timestamp. Assumes common.sh runs at startup.
start_time=$(date +%s)
# Get time elapsed since start_time in seconds.
get_elapsed_seconds() {
local end_time=$(date +%s)
local elapsed_seconds=$(( end_time - start_time ))
echo ${elapsed_seconds}
}
# Print time elapsed since start_time.
print_time_elapsed() {
# Optional first arg to specify elapsed_seconds. If not given, will
# recalculate elapsed time to now. Optional second arg to specify
# command name associated with elapsed time.
local elapsed_seconds=${1:-$(get_elapsed_seconds)}
local cmd_base=${2:-}
local minutes=$(( elapsed_seconds / 60 ))
local seconds=$(( elapsed_seconds % 60 ))
if [[ -n ${cmd_base} ]]; then
info "Elapsed time (${cmd_base}): ${minutes}m${seconds}s"
else
info "Elapsed time: ${minutes}m${seconds}s"
fi
}
# Save original command line.
command_line_arr=( "$0" "$@" )
command_completed() {
# Call print_elapsed_time regardless.
local run_time=$(get_elapsed_seconds)
local cmd_base=$(basename "${command_line_arr[0]}")
print_time_elapsed ${run_time} ${cmd_base}
}
# Check that the specified file exists. If the file path is empty or the file
# doesn't exist on the filesystem generate useful error messages. Otherwise
# show the user the name and path of the file that will be used. The padding
# parameter can be used to tabulate multiple name:path pairs. For example:
#
# check_for_file "really long name" "...:" "file.foo"
# check_for_file "short name" ".........:" "another.bar"
#
# Results in the following output:
#
# Using really long name...: file.foo
# Using short name.........: another.bar
#
# If tabulation is not required then passing "" for padding generates the
# output "Using <name> <path>"
check_for_file() {
local name=$1
local padding=$2
local path=$3
if [[ -z ${path} ]]; then
die "No ${name} file specified."
fi
if [[ ! -e ${path} ]]; then
die "No ${name} file found at: ${path}"
else
info "Using ${name}${padding} ${path}"
fi
}
# Get the relative path between two locations. Handy for printing paths to
# the user that will usually make sense both inside and outside the chroot.
relpath() {
local py='import sys, os; print os.path.relpath(sys.argv[1], sys.argv[2])'
python2 -c "${py}" "${1}" "${2:-.}"
}
# Checks that stdin and stderr are both terminals.
# If so, we assume that there is a live user we can interact with.
# This check can be overridden by setting the CROS_NO_PROMPT environment
# variable to a non-empty value.
is_interactive() {
[[ -z ${CROS_NO_PROMPT} && -t 0 && -t 2 ]]
}
assert_interactive() {
if ! is_interactive; then
die "Script ${0##*/} tried to get user input on a non-interactive terminal."
fi
}
which_python() {
for python in /usr/bin/python2.6 /usr/bin/python2.7 /usr/bin/python; do
test -x "$python" && echo "$python" && return
done
echo >&2 'Could not find a Python interpreter.'
exit 1
}
lowercase() {
echo "$1" | tr '[A-Z]' '[a-z]'
}
uppercase() {
echo "$1" | tr '[a-z]' '[A-Z]'
}
opt_quiet=0
function vecho {
(( opt_quiet )) && return
echo "$@"
}
function _warn {
if ! eval "$@"; then
echo >&2 "WARNING: command failed \"$@\""
fi
}
# write to file
function writefile {
file=$1
string=$2 # optional
if [[ ! -w $file ]]; then
echo >&2 "WARNING: file $file not writable/exists. Skipping."
return
fi
vecho "$file, before:"
(( ! opt_quiet )) && cat -n $file
_warn "echo $string > $file"
vecho "$file, after:"
(( ! opt_quiet )) && cat -n $file
vecho
}
resolve_link() {
$(type -p greadlink readlink | head -1) "$1"
}
readlink_mac() {
python -c "import os; print(os.path.realpath('$1'))"
}
abs_dirname() {
local cwd="$(pwd)"
local path="$1"
while [ -n "$path" ]; do
cd "${path%/*}"
local name="${path##*/}"
path="$(resolve_link "$name" || true)"
done
pwd
cd "$cwd"
}
expand_path() {
{ cd "$(dirname "$1")" 2>/dev/null
local dirname="$PWD"
cd "$OLDPWD"
echo "$dirname/$(basename "$1")"
} || echo "$1"
}
#################################
#assert_not_root_user
#assert_root_user
readlink_mac "./"
error "Bad news"
writefile "test" "hello"