diff options
Diffstat (limited to 'bash-lib.sh')
-rw-r--r-- | bash-lib.sh | 98 |
1 files changed, 98 insertions, 0 deletions
diff --git a/bash-lib.sh b/bash-lib.sh new file mode 100644 index 0000000..83819df --- /dev/null +++ b/bash-lib.sh | |||
@@ -0,0 +1,98 @@ | |||
1 | #!/usr/bin/env bash | ||
2 | |||
3 | set -euo pipefail | ||
4 | IFS=$'\n\t' | ||
5 | |||
6 | shopt -s nullglob | ||
7 | |||
8 | tput() { | ||
9 | # If tput fails, it just means less colors | ||
10 | command tput "$@" 2> /dev/null || true | ||
11 | } | ||
12 | |||
13 | NORMAL="$(tput sgr0)" | ||
14 | readonly NORMAL | ||
15 | BOLD="$(tput bold)" | ||
16 | readonly BOLD | ||
17 | |||
18 | RED="$(tput setaf 1)" | ||
19 | readonly RED | ||
20 | GREEN="$(tput setaf 2)" | ||
21 | readonly GREEN | ||
22 | YELLOW="$(tput setaf 3)" | ||
23 | readonly YELLOW | ||
24 | BLUE="$(tput setaf 4)" | ||
25 | readonly BLUE | ||
26 | PURPLE="$(tput setaf 5)" | ||
27 | readonly PURPLE | ||
28 | CYAN="$(tput setaf 6)" | ||
29 | readonly CYAN | ||
30 | WHITE="$(tput setaf 7)" | ||
31 | readonly WHITE | ||
32 | |||
33 | readonly BASH_LIB_DEBUG_VAR="${BASH_LIB_NAME:-BASH}_DEBUG" | ||
34 | |||
35 | is_debug() { | ||
36 | [ "${!BASH_LIB_DEBUG_VAR:-0}" -ge 1 ] | ||
37 | } | ||
38 | |||
39 | is_trace() { | ||
40 | [ "${!BASH_LIB_DEBUG_VAR:-0}" -ge 2 ] | ||
41 | } | ||
42 | |||
43 | declare -a VERBOSE_ARG | ||
44 | if is_debug; then | ||
45 | VERBOSE_ARG=("--verbose") | ||
46 | else | ||
47 | VERBOSE_ARG=() | ||
48 | fi | ||
49 | readonly VERBOSE_ARG | ||
50 | |||
51 | echoe() { | ||
52 | IFS=" " echo "$@" >&2 | ||
53 | } | ||
54 | |||
55 | log() { | ||
56 | local level="$1" | ||
57 | local color="$2" | ||
58 | local message="$3" | ||
59 | shift 3 | ||
60 | local rest="$@" | ||
61 | |||
62 | echoe "${BOLD}${color}${level} ${WHITE}${message}${NORMAL}" "${rest[@]}" | ||
63 | } | ||
64 | |||
65 | trace() { | ||
66 | if is_trace; then | ||
67 | log "Trace: " "${PURPLE}" "$@" | ||
68 | fi | ||
69 | } | ||
70 | |||
71 | debug() { | ||
72 | if is_debug; then | ||
73 | log "Debug: " "${GREEN}" "$@" | ||
74 | fi | ||
75 | } | ||
76 | |||
77 | info() { | ||
78 | log "Info: " "${CYAN}" "$@" | ||
79 | } | ||
80 | |||
81 | warn() { | ||
82 | log "Warning:" "${YELLOW}" "$@" | ||
83 | } | ||
84 | |||
85 | error() { | ||
86 | log "Error: " "${RED}" "$@" | ||
87 | } | ||
88 | |||
89 | critical() { | ||
90 | error "$@" | ||
91 | # Useful for triggering the error trap system | ||
92 | false | ||
93 | } | ||
94 | |||
95 | fatal() { | ||
96 | error "$@" | ||
97 | exit 1 | ||
98 | } | ||