feat: improve scripts and write tests
This commit is contained in:
32 files changed
+3817
-723
No files matched your search
@@ -0,0 +1,68 @@
|
||||
# shellcheck shell=bash
|
||||
# Shared helpers for the scripts in this directory. Source it; don't execute it.
|
||||
#
|
||||
# SCRIPT_DIR="$(cd -- "$(dirname -- "$(readlink -f -- "${BASH_SOURCE[0]}")")" && pwd -P)"
|
||||
# source "$SCRIPT_DIR/lib/common.sh"
|
||||
#
|
||||
# Conventions: human-readable status goes to stderr, data goes to stdout.
|
||||
# Colors are disabled when stderr is not a terminal or NO_COLOR is set.
|
||||
|
||||
[[ -n "${_NOTFILES_COMMON_SH:-}" ]] && return 0
|
||||
_NOTFILES_COMMON_SH=1
|
||||
|
||||
if [[ -t 2 && -z "${NO_COLOR:-}" ]]; then
|
||||
C_GREEN=$'\e[32m' C_YELLOW=$'\e[33m' C_RED=$'\e[31m' C_BLUE=$'\e[34m'
|
||||
C_BOLD=$'\e[1m' C_RESET=$'\e[0m'
|
||||
else
|
||||
C_GREEN="" C_YELLOW="" C_RED="" C_BLUE="" C_BOLD="" C_RESET=""
|
||||
fi
|
||||
|
||||
log() { printf '%s[+]%s %s\n' "$C_GREEN" "$C_RESET" "$*" >&2; }
|
||||
info() { printf '%s[i]%s %s\n' "$C_BLUE" "$C_RESET" "$*" >&2; }
|
||||
warn() { printf '%s[!]%s %s\n' "$C_YELLOW" "$C_RESET" "$*" >&2; }
|
||||
err() { printf '%s[-]%s %s\n' "$C_RED" "$C_RESET" "$*" >&2; }
|
||||
|
||||
# die MESSAGE [EXIT_CODE]
|
||||
die() { err "$1"; exit "${2:-1}"; }
|
||||
|
||||
# need_value FLAG "$@"-remaining: fail clearly if an option is missing its value.
|
||||
# --iso) need_value "$@"; ISO="$2"; shift 2 ;;
|
||||
need_value() {
|
||||
(($# >= 2)) || die "option $1 requires a value" 2
|
||||
}
|
||||
|
||||
# need_cmd CMD...: fail unless every command is on PATH.
|
||||
need_cmd() {
|
||||
local missing=() c
|
||||
for c in "$@"; do
|
||||
command -v "$c" >/dev/null 2>&1 || missing+=("$c")
|
||||
done
|
||||
((${#missing[@]} == 0)) || die "missing required command(s): ${missing[*]}" 3
|
||||
}
|
||||
|
||||
# Must stay in sync with HOST_RE in register-host.py.
|
||||
valid_hostname() {
|
||||
[[ "$1" =~ ^[a-z]([a-z0-9-]{0,61}[a-z0-9])?$ ]]
|
||||
}
|
||||
|
||||
# sha256_of FILE: print the lowercase hex digest. Works with GNU coreutils,
|
||||
# macOS (shasum), or OpenSSL.
|
||||
sha256_of() {
|
||||
local out
|
||||
if command -v sha256sum >/dev/null 2>&1; then
|
||||
out="$(sha256sum -- "$1")" || return 1
|
||||
elif command -v shasum >/dev/null 2>&1; then
|
||||
out="$(shasum -a 256 -- "$1")" || return 1
|
||||
elif command -v openssl >/dev/null 2>&1; then
|
||||
out="$(openssl dgst -sha256 -r -- "$1")" || return 1
|
||||
else
|
||||
err "no sha256 tool found (need sha256sum, shasum, or openssl)"
|
||||
return 1
|
||||
fi
|
||||
printf '%s\n' "${out%% *}"
|
||||
}
|
||||
|
||||
# human BYTES: 1073741824 -> 1.0GiB (falls back to raw bytes without numfmt).
|
||||
human() {
|
||||
numfmt --to=iec-i --suffix=B "$1" 2>/dev/null || printf '%s B\n' "$1"
|
||||
}
|
||||
Reference in new issue
Block a user