Use Black in Vim 8, pre-commit hooks and CI/CD
It’s important to choose a specific Black version to use (rather than just “master”). The versions you use in Vim, pre-commit, and used by other contributors must be the same so there are no inconsistencies.
This method uses the built-in plugin management in Vim 8+.
sudo rm -rf ~/.vim/black mkdir -p ~/.vim/pack/start/black/plugin curl https://raw.githubusercontent.com/psf/black/21.6b0/plugin/black.vim -o ~/.vim/pack/start/black/plugin/black.vim
Add the following to
~/.vimrc to format with Black every time you save.
autocmd BufWritePre *.py execute ':Black'
Next time you open a Python file in Vim, Black will install.
Add to the
.pre-commit-config.yaml file in the root of your repository,
replacing 20.8b1 with the Black version you want to use.
repos: - repo: https://github.com/ambv/black rev: 20.8b1 hooks: - id: black args: [--diff, --check]
This will abort a commit if a module hasn’t been formatted.
I like to fail builds if code hasn’t been formatted. This ensures every developer must format their code. Add the following to your build scripts.
black --diff --check /path/to/code
Black will exit with a non-zero exit status if code isn’t formatted, which should fail your build.