Skip to content

Commit

Permalink
A better pre-commit script
Browse files Browse the repository at this point in the history
This script doesn't complain about the linting on unstaged files.
  • Loading branch information
rousseab committed Feb 23, 2024
1 parent 5927511 commit d2b5d6e
Showing 1 changed file with 42 additions and 6 deletions.
48 changes: 42 additions & 6 deletions hooks/pre-commit
Original file line number Diff line number Diff line change
@@ -1,12 +1,48 @@
#!/bin/sh
#!/bin/sh

# exit at the first error
set -e

# linting
flake8 --ignore D,W503 --max-line-length=120 . # Check everything but docstrings
flake8 --select D --ignore D104,D100,D401 --docstring-convention google --exclude tests/ # Check only the docstrings
isort --check . # Check imports
# flake8 linting

# Only extract the python files that git has staged; no need to lint WIP files that are not staged.

# We'll use files to use intermediate results; it's easier to use grep on files.
staged_file_name="staged_file.tmp"
python_staged_file_name="python_staged_file.tmp"

git diff --name-only --cached > $staged_file_name

# Grep has the following behavior:
# the exit code is 0 if there is a match
# the exit code is 1 if there is no match
# the exit code is >1 if there is an error
#
# No match is a legitimate result, but the exit code of 1 is interpreted as an error by bash.
# To work around this issue, we'll use
# grep [...] || [[ $? == 1]]
# which has an exit code of 0 if there is a match or if there are no match.

grep '.*py$' $staged_file_name > $python_staged_file_name || [[ $? == 1 ]]
python_staged_files=`cat $python_staged_file_name`

python_non_tests_staged_files=`grep -v '^tests' $python_staged_file_name || [[ $? == 1 ]]`

rm $python_staged_file_name $staged_file_name


if [ -z "${python_staged_files}" ]; then
echo "No python file to lint"
else
flake8 --ignore D,W503 --max-line-length=120 $python_staged_files # Check everything but docstrings
fi

if [ -z "${python_non_tests_staged_files}" ]; then
echo "No non-test python file to docstring lint"
else
flake8 --select D --ignore D104,D100,D401 --docstring-convention google --exclude tests/ $python_non_tests_staged_files # Check only the docstrings
fi


# Raise error if any staged notebooks contain outputs
GITDIR=$(git rev-parse --show-toplevel) # Full path to git working directory
Expand All @@ -18,7 +54,7 @@ if [ "$IPYNB_FILES" != "" ] && [ -z $ALLOW_IPYNB ]; then
if [ "$DIFF" != "" ]; then
echo "
The notebook $GITDIR/$f contains outputs.
Remove them all before committing.
Remove them all before committing.
***Hint*** use the command:
jupyter nbconvert --ClearOutputPreprocessor.enabled=True --ClearMetadataPreprocessor.enabled=True --to notebook --inplace $GITDIR/$f
Expand Down

0 comments on commit d2b5d6e

Please sign in to comment.