Git tool to remove lines from staging if they consist only of changes in whitespace

前端 未结 3 1789
感情败类
感情败类 2021-02-05 22:28

The point in removing trailing whitespace is that if everyone does it always then you end up with a diff that is minimal, ie. it consists only of code changes and not whitespace

3条回答
  •  借酒劲吻你
    2021-02-05 23:26

    I'd been using a script based on @GregBacon's answer for years, but at some point git changed the output of git diff -b so that the whitespace changes it didn't show as changes were included in the patch context lines in the after state rather than the before state.

    I found if I reversed the clean diff and the corresponding apply, the script would work again.

    So my complete script used to look like this:

    #!/bin/bash
    
    clean=`git diff --cached -b`
    git apply --cached <(git diff --cached -R)
    echo "$clean" | git apply --cached -
    clean=
    

    And now looks like:

    #!/bin/bash
    
    clean=`git diff --cached -b -R`
    git apply --cached <(git diff --cached -R)
    echo "$clean" | git apply --cached -R -
    clean=
    

    I also have a script to leave only whitespace changes in a commit. This is useful if while you fix something you make some whitespace fixes elsewhere in the file, and you want to commit the whitespace fixes first in a separate commit. It is just:

    git apply --cached -R <(git diff --cached -w)
    

提交回复
热议问题