Tamarin/lib/util.sh

138 lines
2.3 KiB
Bash

#!/usr/bin/env bash
HOOKS_DIR="${BASE_DIR}/hooks"
DEFAULT_OPTS_FILE="${BASE_DIR}/default_opts"
OPT_FILE="${BASE_DIR}/tmp/.tamarin_opts"
OPT_PREFIX="tamarin_opt_"
# Colors
COLOR_INFO='\e[0;36m'
COLOR_FATAL='\e[0;31m'
COLOR_WARN='\e[0;33m'
COLOR_SUCCESS='\e[0;32m'
COLOR_ERR='\e[0;37m'
COLOR_OUT='\e[0;37m'
COLOR_DEBUG='\e[0;35m'
function stderr {
if [ -z "$@" ]; then
while read str; do
log ERR "${str}"
done
else
log stderr "$@"
fi
}
function stdout {
if [ -z "$@" ]; then
while read str; do
log OUT "${str}"
done
else
log OUT "$@"
fi
}
function info {
if [ -z "$@" ]; then
while read str; do
log INFO "${str}"
done
else
log INFO "$@"
fi
}
function warn {
if [ -z "$@" ]; then
while read str; do
log WARN "${str}"
done
else
log WARN "$@"
fi
}
function debug {
if [ -z "$@" ]; then
while read str; do
log DEBUG "${str}"
done
else
log DEBUG "$@"
fi
}
function fatal {
if [ -z "$@" ]; then
while read str; do
log FATAL "${str}" >&2
done
else
log FATAL "$@" >&2
fi
exit 1
}
function success {
if [ -z "$@" ]; then
while read str; do
log SUCCESS "${str}"
done
else
log SUCCESS "$@"
fi
}
function log {
local args=( $@ )
local color=COLOR_${args[0]}
echo -e "${!color}[${HOSTNAME}] [${args[0]}] $(remove_ansi ${args[@]:1})\e[0m"
}
function remove_ansi {
echo "$@" | sed 's,\x1B\[[0-9;]*[a-zA-Z],,g'
}
function get_opt {
local opt_name=${OPT_PREFIX}${1}
local default_value=${2}
touch "${OPT_FILE}"
source "${OPT_FILE}"
echo ${!opt_name:-${default_value}}
}
function set_opt {
local opt_name=${1}
local opt_value=${2}
touch "${OPT_FILE}"
sed -i "s/^${OPT_PREFIX}${opt_name}*$//" "${OPT_FILE}"
echo "${OPT_PREFIX}${opt_name}=\"${opt_value}\"" >> "${OPT_FILE}"
}
function exec_hooks {
local hook=${1}
local workspace=${2}
local hook_scripts=$( find "${HOOKS_DIR}" -type f -name "*${hook}" -executable | sort )
for hook_script in ${hook_scripts}; do
info "[${hook}] >> ${hook_script}"
( cd "${workspace}" && "${hook_script}" ) 2> >(stderr) 1> >(stdout)
# If the script did not execute properly, we stop here
if [ $? != 0 ]; then
fatal "The '${hook_script}' hook script did not finished properly !"
fi
info "[${hook}] << ${hook_script}"
done
}