Skip to content

Instantly share code, notes, and snippets.

@jamesfolberth
Created March 8, 2019 04:41
Show Gist options
  • Save jamesfolberth/a0223b97344f03aa534e4ec68e604d08 to your computer and use it in GitHub Desktop.
Save jamesfolberth/a0223b97344f03aa534e4ec68e604d08 to your computer and use it in GitHub Desktop.
Simple git pre-commit hook that checks IPython/Jupyter notebooks for output
#!/bin/sh
# Check for .ipynb files with output cells;
# ask the user if they really want to commit them
ipynb_files=`git diff --staged --name-only | awk "/.ipynb/"`
have_output=""
if [ -n "$ipynb_files" ]; then
while read filename; do
if [ $(git show :$filename | grep -cm1 "\"output_type\":") -ge 1 ]; then
have_output="${have_output}"$'\n'"$filename"
fi
done <<< $ipynb_files
# use here string to run in main shell: https://stackoverflow.com/a/16854326
fi
if [ -n "$have_output" ]; then
# https://stackoverflow.com/a/10015707
exec < /dev/tty # allows us to grab user input
echo "You appear to be committing Jupyter notebooks"
echo "that contain output:"
echo "$have_output"$'\n'
while true; do
read -p "Proceed with commit (y/n)?: " resp
case $resp in
[Yy]* ) exit_status=0; break;;
[Nn]* ) exit_status=1; break;;
* ) echo "Please answer y or n";;
esac
done
exit $exit_status
fi
@jamesfolberth
Copy link
Author

I've already made a couple updates to this thing, so I decided to make it a gist. See here for a description of the use case and those updates.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment