blob: 7a8ad176255d0ba84abbf8d087eccf1d09af816a (
plain) (
blame)
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
|
#!/bin/sh
set -o nounset
set -o errexit
# Get the number of cpus of the current system.
#
# STDOUT:
# The number of CPU cores
#
# RETURNS:
# 1 on failure
get_ncpus() {
_get_ncpus_os="$(uname -s)"
if [ "$_get_ncpus_os" = 'Darwin' ]; then
sysctl -n hw.ncpu
else
return 1
fi
}
# Get the total amount of memory on the current system.
#
# ARGS:
# $1 (Optional): The units to retrieve the memory size in.
# Options are: 'b', 'mb', 'kb', 'gb'. Defaults to 'b' (bytes).
#
# STDOUT:
# The total amount of memory.
#
# RETURNS:
# 1 on failure
get_memsize() {
_get_memsize_unit="${1:-b}"
_get_memsize_unit_spec="b mb kb gb"
if ! validate_enum "$_get_memsize_unit" "$_get_memsize_unit_spec"; then
echo "[ERROR] Expected one of: '$_get_memsize_unit_spec'. Got '$_get_memsize_unit'." >&2
return 1
fi
_get_memsize_os="$(uname -s)"
if [ "$_get_memsize_os" = 'Darwin' ]; then
_get_memsize_mem=$(sysctl -n hw.memsize)
else
return 1
fi
case "$_get_memsize_unit" in
b) _get_memsize_divisor=1 ;;
kb) _get_memsize_divisor=1024 ;;
mb) _get_memsize_divisor=1048576 ;;
gb) _get_memsize_divisor=1073741824 ;;
esac
echo $((_get_memsize_mem / _get_memsize_divisor))
}
validate_enum() {
_validate_enum_val=$1
_validate_enum_spec=$2
set -f # Temporarily disable pathname expansion e.g. foo*
# See `set` in `man bash`:
# > Any arguments remaining after option
# > processing are treated as values for the positional parameters and
# > are assigned, in order, to $1, $2, ..., $n.
# shellcheck disable=SC2086
set -- $_validate_enum_spec
set +f
for item in "$@"; do
[ "$_validate_enum_val" = "$item" ] && return 0
done
return 1
}
require_readable_file() {
if [ ! -f "$1" ] || [ ! -r "$1" ]; then
echo "File not found or not readable: $1" >&2
exit 1
fi
}
|