Skip to content

Instantly share code, notes, and snippets.

@bryanmr
Created March 4, 2019 18:24
Show Gist options
  • Save bryanmr/252886686622cb818df49e7864a283c5 to your computer and use it in GitHub Desktop.
Save bryanmr/252886686622cb818df49e7864a283c5 to your computer and use it in GitHub Desktop.
A little (incomplete) script I wrote to document functions in a Bash script
#!/bin/bash
# Script to produce documentation skeleton
oops() {
echo "Exit Code: $? ~~ Command before oops: $this_command"
tput bold
echo "$@"
tput sgr0
exit 1
}
main_function_calls() {
awk '/main/ {found=1} found { print " " $1 }' "${CLI_ARGS[0]}" |\
grep -f "$TMP_LOC""functions_list" | sort -u > "$TMP_LOC""tree"
}
build_tree() {
while read -r which_function ; do
found="$(awk '/'"$which_function"'\(/ {found=1;next}
found&&/^}/ { stop=1 }
!/\(\) {$/&&found&&!stop { print " " $1 "()"}
END {print "DONE"}' "${CLI_ARGS[0]}" |\
grep -f "$TMP_LOC""functions_list" | sort -u)"
if [ "$found" == "" ] ; then
echo " $which_function()"
else
echo " $which_function() calls the below functions:"
echo "$found"
fi
done < "$TMP_LOC""tree"
}
count_spaces() {
awk '/'"$1"'\(\)/{ match($0, /^ */);
printf("There are %d spaces leading up to %s\n",
RLENGTH, substr($0,RLENGTH+1)) }' "${CLI_ARGS[0]}"
}
main() {
TMP_LOC=/var/tmp/bash_autodocument/
CLI_ARGS=("$@")
set -uEeo pipefail
mkdir -p "$TMP_LOC"
this_command="false"
previous_command="false"
trap 'previous_command=$this_command; this_command=$BASH_COMMAND' DEBUG
trap 'rm -rf /var/tmp/bash_autodocument/ ;exit' EXIT SIGINT SIGQUIT SIGTERM
trap 'echo "Exit Code: $? ~~ Last Command: $previous_command" ; exit 1' ERR
awk '/\(\)/&&!/^main/&&!/^oops/ {gsub(/\(\)/, "") ; print $1}' \
"$1" >> "$TMP_LOC""functions_list"
if ! grep -q '^main' "$1" ; then
echo "Expect to find main function"
exit 1
fi
main_function_calls || oops "Function tree failed"
echo "main() calls the below functions:"
build_tree || oops "Failed to go down the tree"
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment