0

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.

anthony sottile
  • 61,815
  • 15
  • 148
  • 207
Luca
  • 10,458
  • 24
  • 107
  • 234

2 Answers2

4

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.

Manas Sambare
  • 1,158
  • 2
  • 11
  • 22
1

This will work.

fail_fast: true
repos:
  - repo: local
    hooks:
      - id: black
        name: Black
        entry: poetry run black
        language: system
        types: [file, python]
        stages: [commit]

Explanation:

  1. Remove pass_filenames: false to use the default true.
  2. Remove . from the poetry run black command. When pre-commit runs it will append the file names to the end. I.e: poetry run black file1 file2 file3
  3. Specify the file types.
  4. Optional: specify the stage.
André Sionek
  • 81
  • 1
  • 4