Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
[Python Auto Generate API Documentation] Python Auto Generate API Documentation #tags: python, git, bash, make
set -e
err_report() {
echo "There was an issue with one of the pre-commit hooks"
echo ".git/hooks/pre-commit-*"
echo "Error on line $1"
trap 'err_report $LINENO' ERR
for commit_hook in .git/hooks/pre-commit-*; do
source "$commit_hook"
# grab list of file names that have been staged ready for commit
PY_FILES=($(git diff --staged --name-only | grep "\.py$" || true))
# construct list of directories that have changes (there will be duplicates)
for i in "${PY_FILES[@]}"; do
PY_DIRS+=("$(echo $i | cut -d '/' -f 1)")
# remove duplicates
PY_DIRS=($(echo "${PY_DIRS[*]}" | tr ' ' '\n' | sort | uniq))
# run pydoc for each directory with changes
if [ ${#PY_DIRS[@]} -gt 0 ]; then
printf '\n********** Documentation Generation **********\n\n'
for i in "${PY_DIRS[@]}"; do
pushd "./$i"
pycco -p -i -d ./docs/api -- ./**/*.py 2>/dev/null || \
echo "uh-oh, something went wrong with $i"
printf "\nThere are no python changes that would cause us to run pydoc\n\n"
# pycco -h
# -p, --paths Preserve path structure of original files
# -d, --directory The output directory that the rendered files should go
# -i, --generate_index Generate an index.html document with sitemap content
REPO := $(shell git rev-parse --show-toplevel)
GIT := ".git/hooks"
HOOK := ".custom-hooks"
define copy_base_hooks
@cp "$(REPO)/$(HOOK)/pre-commit" "$(REPO)/$(GIT)/pre-commit"
define copy_template_hooks
@cp "$(REPO)/$(HOOK)/pre-commit-pydoc" "$(REPO)/$(GIT)/pre-commit-pydoc"
@pycco -h 1>/dev/null 2>&1 || (echo "Looks like you don't have the pycco executable, we need that to auto generate documentation" && exit 1)
-@rm $(REPO)/$(GIT)/pre-commit.sample &> /dev/null || true
-@rm $(REPO)/$(GIT)/pre-commit &> /dev/null || true
-@rm $(REPO)/$(GIT)/pre-commit-* &> /dev/null || true
hooks: check_hook_requirements clean_hooks
$(call copy_base_hooks)
$(call copy_template_hooks)
# Explanation of clean_precommits syntax:
# - ...allows errors to be ignored (i.e. don't stop further execution steps)
# @ ...stops makefile from printing command that was executed
# &> ...redirects stdout/stderr to /dev/null (as command can sometimes error)
# || true ...prevents Make from printing 'error ignored'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.