Cleaning up as you go along
Wouldn’t it be nice if everyone cleaned up as they went along? It’s easy to ignore until you are faced with a big clean up.
This is especially true when coding when the pressure is to get something working not matter what so of mess you leave as you progress.
Why not use a tool to keep your messier instincts under control?
Here is where https://pre-commit.com/ comes in. This easy to configure tool sits between your rushed bad habits and committing locally. When you try to commit a set of tests are run on the files being committed. If the tests fail, you will have to fix your code. Usually pre-commit can clean up for you, but sometimes you will have to clean up your own mess.
To get started follow the excellent guide at https://pre-commit.com/ but for a quick start to the following:
pip install pre_commit wget https://gist.githubusercontent.com/bassdread/15f4dd8c830a1d151774acf7d8d9efc9/raw/601623b3cd4891a158106bea377b3083e9c19a8e/.pre-commit-config.yaml pre-commit install -f --install-hooks
The configuration is in .pre-commit-config.yaml, an example of which is below:
# See http://pre-commit.com for more information # See http://pre-commit.com/hooks.html for more hooks - repo: https://github.com/FalconSocial/pre-commit-python-sorter rev: master hooks: - id: python-import-sorter args: ['--silent-overwrite'] - repo: https://github.com/pre-commit/mirrors-mypy rev: v0.720 hooks: - id: mypy args: [--ignore-missing-imports] - repo: https://github.com/pre-commit/pre-commit-hooks rev: v2.3.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: check-yaml - id: check-json - id: debug-statements - id: double-quote-string-fixer - id: requirements-txt-fixer - id: flake8 args: ['--max-line-length=79']
Now when you attempt to commit code the following
hooks will run over the changed files.
Run Against a Single File
pre-commit run --file app.py
Run Against all Files
pre-commit run --all-files *