a11yist/bin/loxecute

57 lines
1.4 KiB
Text
Raw Normal View History

2024-10-30 00:05:18 +01:00
#!/usr/bin/env bash
set -eo pipefail
# SYNTAX:
# catch STDOUT_VARIABLE STDERR_VARIABLE COMMAND [ARG1[ ARG2[ ...[ ARGN]]]]
catch() {
{
IFS=$'\n' read -r -d '' "${1}";
IFS=$'\n' read -r -d '' "${2}";
(IFS=$'\n' read -r -d '' _ERRNO_; return ${_ERRNO_});
} < <((printf '\0%s\0%d\0' "$(((({ shift 2; "${@}"; echo "${?}" 1>&3-; } | tr -d '\0' 1>&4-) 4>&2- 2>&1- | tr -d '\0' 1>&4-) 3>&1- | exit "$(cat)") 4>&1-)" "${?}" 1>&2) 2>&1)
}
# " This line fixes my syntax highlighting
# Only log rails generator commands (for now)
should_log() {
cmd=$(basename ${1})
if [ "${cmd}" == "rails" ];then
case ${2} in
g | generate | d | delete)
echo 0
;;
*)
echo 1
;;
esac
else
echo 1
fi
}
# Execute catching output and error seperately
catch output errors "$@"
exit_code=$?
# Show the command's output
cat <<< ${output}
if [ ${exit_code} -eq 0 ] && [ -z "${errors}" ];then
# Was the command interesting?
log_it=$(should_log $@)
if [ ${log_it} -eq 0 ]; then
# Log date, command and output
comment="# $(date)"
msg="$@"
printf "${comment}\n${msg}\n" >> /app/config/generation.sh
cat <<< "${output}" | sed -e 's/^#*/# /' >> /app/config/generation.sh
fi
else
# Show the error.
# TODO: Ask user if the command should be stored anyways
echo "The command exited with \"${exit_code}\" wrote the following to STDERR:"
cat <<< "${errors}"
fi