/
assertions.sh
119 lines (109 loc) · 2.87 KB
/
assertions.sh
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
##
## Assertions
##
[[ $__assertions_sourced__ ]] && return
__assertions_sourced__=1
#
# Given a version like x.y, where x and y are numbers, asserts that
# bash version is at least x.y
#
assert_minimum_bash_version() {
local version=$1 message=$2
local version_array curr_version version_re='^[0-9]+\.[0-9]+$'
assert_arg_count $# 1 "Usage: assert_minimum_bash_version version"
assert_regex_match "$version" "$version_re" "Version should be in the format x.y where x and y are integers"
version_array=(${version//\./ })
((BASH_VERSINFO[0] < version_array[0] ||
((BASH_VERSINFO[0] == version_array[0] && BASH_VERSINFO[1] < version_array[1])))) && {
curr_version="${BASH_VERSINFO[@]:0:4}"
[[ $message ]] || message="Running with Bash version ${curr_version// /.}; need $version or above"
printf '%s\n' "$message" >&2
exit 1
}
return 0
}
#
# exit if number of arguments passed doesn't meet expectations
# example call:
# assert_arg_count $# 2 "Need exactly two arguments"
#
assert_arg_count() {
local actual=$1 expected=$2 message=$3
((actual != expected)) && {
[[ $message ]] || message="Expected $expected arguments, got $actual arguments"
printf '%s\n' "$message" >&2
exit 1
}
}
assert_regex_match() {
local string=$1 regex=$2 message=$3
[[ $string =~ $regex ]] || {
[[ $message ]] || message="String '$string' does not match regex '$regex'"
printf '%s\n' "$message" >&2
exit 1
}
}
#
# assert if variables are set
# if any variable is not set, exit 1 (when -f option is set) or return 1 otherwise
#
# Usage: assert_var_not_null [-f] variable ...
#
assert_var_not_null() {
local fatal var num_null=0
[[ "$1" = "-f" ]] && { shift; fatal=1; }
for var in "$@"; do
[[ -z "${!var}" ]] && printf '%s\n' "Variable '$var' not set" >&2 &&
((num_null++))
done
if ((num_null > 0)); then
[[ "$fatal" ]] && exit 1
return 1
fi
return 0
}
#
# assert if $1 is a valid URL
#
assert_valid_url() {
(($#)) || return 0
local url=$1
curl --fail --head -o /dev/null --silent "$url" || fatal_error "Invalid URL - '$url'"
}
#
# assert if directories do exist
#
assert_dir_exists() {
local dir
local rc=0
for dir; do
if [[ ! -d "$dir" ]]; then
log_error "Directory '$dir' does not exist"
((rc++))
fi
done
((rc)) && exit 1
}
#
# assert if directories do exist
#
assert_file_exists() {
local file
local rc=0
for file; do
if [[ ! -f "$file" ]]; then
log_error "File '$file' does not exist"
((rc++))
fi
done
((rc)) && exit 1
}
#
# assert that we are running on the right OS
#
assert_os() {
(($#)) || return
if [[ $BASE_OS != "$1" ]]; then
fatal_error "Required OS: $1, current OS: $BASE_OS"
fi
}