git remove trailing whitespace in new files before commit

前端 未结 4 1632
孤街浪徒
孤街浪徒 2020-12-05 03:10

I know removing trailing whitespace can be done with a pre-commit hook. I am interested in doing it manually. I read the question here:
Make git automatically remove tra

4条回答
  •  爱一瞬间的悲伤
    2020-12-05 03:49

    Simple fix

    The command you quoted

    (export GIT_EDITOR=: && git -c apply.whitespace=fix add -ue .) && git checkout . && git reset
    

    works if you first add the files you want to fix with git add -N . The add -N essentially tells Git to pretend you'd previously committed empty versions of the files.

    Error you got

    I don't understand why you get fatal: Empty patch. Aborted. error with add -Ae, but it looks like a bug, since doing plain git add -A . && git diff --cached shows that the patch should not actually be empty.

    Better whitespace fixer

    I recently updated my answer that you linked to with a better Git alias for fixing whitespace. Here's a rewrite of that alias using Luke's rebase trick and a less redundant control flow:

    fixws =!"\
      if (! git diff-index --quiet --cached HEAD); then \
        \
        git diff-files --quiet `git rev-parse --show-toplevel` ; \
        export NEED_TO_STASH=$? ; \
        \
        git commit -m FIXWS_SAVE_INDEX && \
        if [ 1 = $NEED_TO_STASH ] ; then git stash save FIXWS_SAVE_TREE; fi && \
        git rebase --whitespace=fix HEAD~ && \
        git reset --soft HEAD~ && \
        if [ 1 = $NEED_TO_STASH ] ; then git stash pop; fi ; \
      fi"
    

    This fixes whitespace in the index, while preserving the index, and leaving the tree untouched. With this alias, you can fix unversioned files in the repo with

    git add --all :/ && git fixws && git reset
    

    But, it also handles the more common case of fixing up whitespace in a commit you're working on. It's complicated because it works even when the index or tree are clean.

提交回复
热议问题