Skip to content

Instantly share code, notes, and snippets.

@yitsushi
Last active February 4, 2022 01:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yitsushi/7fce5d1499dbe7daa18433b62430ef66 to your computer and use it in GitHub Desktop.
Save yitsushi/7fce5d1499dbe7daa18433b62430ef66 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
function printDebug() {
if [ -z "${1}" ]; then
return 1
fi
# That 2:
# FUNCNAME contains the printDebug call too and we want to ignore it.
if [[ ${#FUNCNAME[@]} -gt 2 ]]; then
echo "<debug> [$(date +'%H:%M%P')] Called from '${FUNCNAME[1]}'"
else
echo "Do not call me, bitch!"
return 1
fi
return 0
}
function trace() {
rndID=$RANDOM
echo "==== TRACE (traceID: ${rndID}) ===="
echo "Call tree:"
i=-1
for fn in ${FUNCNAME[@]}; do
i=$(( i + 1 ))
if [[ i -eq 0 ]]; then
continue
fi
indent=$(( i - 1 ))
printf "%$(( indent * 2 ))s=> %s\n" "" "${fn}"
done
echo -e "\nArguments:"
i=1
for arg in "${@}"; do
echo " ${i} -> ${arg}"
i=$(( i + 1 ))
done
echo "==== TRACE END (traceID: ${rndID}) ===="
}
function fstRequired() {
if [ -z "${2}" ]; then
echo "Missing argument (${1})" >&2
shift
trace "${@}"
return 1
fi
return 0
}
function sndRequired() {
if [ -z "${3}" ]; then
echo "Missing argument (${1})" >&2
shift
trace "${@}"
return 1
fi
return 0
}
function fancyFunc() {
fstRequired "host" "$@" || return 1
sndRequired "port" "$@" || return 1
printDebug "$@"
echo "${1} -> ${2}"
}
echo ">>>>> This should print out a trace:"
fancyFunc "localhost"
echo -e "\n\n>>>>> This should be fine because it has second argument:"
fancyFunc "localhost" "9876"
echo -e "\n\n>>>>> This should tell you to feck off:"
printDebug "call me maybe"
>>>>> This should print out a trace:
Missing argument (port)
==== TRACE (traceID: 16942) ====
Call tree:
=> sndRequired
=> fancyFunc
=> main
Arguments:
1 -> localhost
==== TRACE END (traceID: 16942) ====
>>>>> This should be fine because it has second argument:
<debug> [02:17am] Called from 'fancyFunc'
localhost -> 9876
>>>>> This should tell you to feck off:
Do not call me, bitch!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment