]> git.wincent.com - wincent.git/blob - bin/common
1dbaf9e588ceb9075c30d003b7cec501d5784b84
[wincent.git] / bin / common
1 #!/bin/bash
2
3 # https://stackoverflow.com/a/2684300
4 if [[ "${BASH_SOURCE[0]}" = "${0}" ]]; then
5   echo "[error] script \"$0\" is intended to be sourced, not executed directly"
6   exit 1
7 fi
8
9 # Get directory of current script:
10 #
11 #     https://stackoverflow.com/a/12694189/2103996
12
13 # and convert to absolute path:
14 #
15 #     https://stackoverflow.com/a/4045350/2103996
16 #
17 REPO_ROOT=$(cd "${BASH_SOURCE%/*}/.." && pwd)
18
19 BIN_DIR="$REPO_ROOT/bin"
20
21 export PATH="$BIN_DIR":$PATH
22
23 # https://stackoverflow.com/a/5947802/2103996
24 BOLD='\033[0;1m'
25 GREEN='\033[1;32m'
26 PURPLE='\033[1;35m'
27 RED='\033[1;31m'
28 RESET='\033[0m'
29 YELLOW='\033[1;33m'
30
31 # No associative arrays in Bash < v4, so can't do:
32 #
33 #   declare -A LOG_LEVEL
34 #
35 LOG_LEVEL_EMERGENCY=0
36 LOG_LEVEL_ALERT=1
37 LOG_LEVEL_CRITICAL=2
38 LOG_LEVEL_ERROR=3
39 LOG_LEVEL_WARNING=4
40 LOG_LEVEL_NOTICE=5
41 LOG_LEVEL_INFO=6
42 LOG_LEVEL_DEBUG=7
43
44 LOG_LEVEL=$LOG_LEVEL_INFO
45
46 for VAR in "$@"
47 do
48   if [[ $VAR = "--debug" ]]; then
49     LOG_LEVEL=$LOG_LEVEL_DEBUG
50     DEBUG=1
51   elif [[ $VAR = "--quiet" || $VAR = "-q" ]]; then
52     LOG_LEVEL=$LOG_LEVEL_ERROR
53     unset DEBUG
54   fi
55 done
56
57 log_debug() {
58   if [[ $LOG_LEVEL -ge $LOG_LEVEL_DEBUG ]]; then
59     echo -e "${PURPLE}[debug]  ${RESET} $*" > /dev/stderr
60   fi
61 }
62
63 log_error() {
64   if [[ $LOG_LEVEL -ge $LOG_LEVEL_ERROR ]]; then
65     echo -e "${RED}[error]  ${RESET} $*" > /dev/stderr
66   fi
67 }
68
69 log_info() {
70   if [[ $LOG_LEVEL -ge $LOG_LEVEL_INFO ]]; then
71     echo -e "${BOLD}[info]   ${RESET} $*" > /dev/stderr
72   fi
73 }
74
75 log_notice() {
76   if [[ $LOG_LEVEL -ge $LOG_LEVEL_NOTICE ]]; then
77     echo -e "${GREEN}[notice] ${RESET} $*" > /dev/stderr
78   fi
79 }
80
81 log_warn() {
82   if [[ $LOG_LEVEL -ge $LOG_LEVEL_WARNING ]]; then
83     echo -e "${YELLOW}[warning]${RESET} $*" > /dev/stderr
84   fi
85 }