Search code examples
pre-commit-hookpre-commitpre-commit.com

Running black only on committed python files


I am just trying to use precommit as a git hook on my python project. What I want to do is to run black only on the committed files. I am also running black through poetry.

At the moment my config looks like:

fail_fast: true
repos:
  - repo: local
    hooks:
      - id: system
        name: Black
        entry: poetry run black .
        pass_filenames: false
        language: system

This, of course, runs black on the whole project structure and this is not what I want.

Is it possible to just run black on the committed files.


Solution

  • If you are not constrained by using poetry, you can use the following that will solve your purpose:

      - repo: https://github.com/psf/black
        rev: 22.6.0
        hooks:
          - id: black
            language_version: python3.9 # Change this with your python version
            args:
              - --target-version=py39 # Change this with your python version
    

    This will respect any and all settings you may have defined in pyproject.toml.