psf/black

Only format git diff (similar to clang-format-diff)

Rikorose opened this issue · 6 comments

Relevant yapf issue: google/yapf#190

It would be really helpfull to only format code that was changed which also helps to minimize the diff.

clang-format-diff example:

git diff -U0 --no-color HEAD^ | clang-format-diff.py -p1 -i
svn diff --diff-cmd=diff -x-U0 | clang-format-diff.py -i
ambv commented

Black is unable to format line ranges. This would be rather problematic given how it's currently implemented. More importantly, this goes against PEP 8's philosophy of staying consistent within a file (and more generally, within a project). See #134 for a longer explanation.

You can format the whole file and only commit relevant changes via git add -p and revert what you don't want to change.

ambv commented

This is not a planned feature.

Also FYI, I wrote darker which can apply Black formatting only to lines which have changed in the Git working tree since the last commit.

For quick solution, run the following script.

#!/bin/bash

# Get a list of changed Python files in the diff
changed_files=$(git diff --name-only --diff-filter=d HEAD | grep '\.py$')

# Apply isort and black to the changed files
for file in $changed_files; do
  isort "$file"
  black "$file"
done