Automating Python project setup
Feb. 7th, 2015 07:18 pm![[personal profile]](https://www.dreamwidth.org/img/silk/identity/user.png)
- Forgetting to add a package to requirements
- Forgetting to run the linter
- (rarely, but it does happen) Forgetting to run unit tests
I make use of piplint to check requirements. Note that the pypi version doesn't work on Python 3, but I have an updated fork installable with:
pip install -e git://github.com/jessamynsmith/piplint.git@6ce1540c3d5dda20c234ba3e49416f54d74cc81e#egg=piplint
As it turns out, virtualenvwrapper is highly customizable, and all I had to do was edit mkvirtualenv in WORKON_HOME to have it modify my activate scripts. While I was in there, I decided to make a skeleton pre-commit hook for the project:
#!/bin/bash
# This hook is run after a new virtualenv is created and before it is activated.
# Automatically set django settings for the virtualenv
echo "export DJANGO_SETTINGS_MODULE=$1.settings.development" >> "$1/bin/activate"
# Create a pre-commit hook script that can be copied over as desired
echo "#!/bin/sh
set -e
. $WORKON_HOME/$1/bin/activate
piplint -x requirements/*
flake8
jshint $1/static/js
python manage.py test $1
" >> "$1/bin/pre-commit"
Now every new virtualenv comes with Django settings prepopulated. If it's not a Django project, that unused environment variable isn't going to hurt anything.
You can add more environment variables later by editing ~/.virtualenvs/<VIRTUAL_ENV_NAME>/bin/activate and adding "export <ENV_VAR>=<VALUE>" entries to the end of the file.
I don't automatically move that pre-commit hook because there is no guarantee I have anywhere to put it. Sometimes I make the virtualenv before I initialized a git repo. However, the hard work has been done so once I make a project, I can simply copy over the hook. Note that the git hook must be made executable or it will be ignored.