How can you combine git add patch -p mode with diff's ignore-all-space

前端 未结 4 2120
别跟我提以往
别跟我提以往 2021-01-31 08:36

How can I do git add with patch mode but ignoring whitespace changes.

The use case is for when you\'ve reformatted a file and also made changes to it. I want to commit t

4条回答
  •  离开以前
    2021-01-31 09:29

    If you want to do git add --patch but ignore all whitespace like the asker is asking, you can do this in one command:

    git diff -w --no-color | git apply --cached --ignore-whitespace && git checkout -- . && git reset && git add -p
    

    git diff -w --no-color creates a diff

    git apply --cached --ignore-whitespace applies the diff ignoring whitepace, and indexes it

    git checkout -- . removes the unindexed “whitespace” changes

    git reset resets the index to just the non-whitespace changes

    git add -p adds the non-whitespace changes in patch mode

    Wrap this up in an alias, like so:

    alias gwap=“git diff -U0 -w --no-color | git apply --cached --ignore-whitespace --unidiff-zero && git checkout -- . && git reset && git add -p”

    Or if you're on a unix based system like I am:

    gwap= !git diff -U0 -w --no-color | git apply --cached --ignore-whitespace --unidiff-zero && git checkout -- . && git reset && git add -p 
    

    (Notice I added options -U0, and --unidiff-zero respectively to workaround context matching issues, according to this comment.)

    Source: https://til.hashrocket.com/posts/696df00135-remove-whitespace-changes-then-git-add-p

提交回复
热议问题