首页 > 解决方案 > git for Windows:提交时删除尾随空格

问题描述

我已经pre-commit为 Windows 2.27.0.windows.1 编写了一个钩子来使用 git 删除尾随空格。这似乎是一个经过充分研究的主题,但不幸的是,我无法让它发挥应有的作用。这是我的.git\hooks\pre-commit文件:

#!/bin/sh
if git rev-parse --verify HEAD >/dev/null 2>&1
then
    against=HEAD
else
    # Initial commit: diff against an empty tree object
    against=$(git hash-object -t tree /dev/null)
fi

git diff --cached --name-only --diff-filter=ACM -z $against | xargs -0 | while read LINE
do 
    if [ -n "$LINE" ]; then
        remove_whitespace "$LINE"
        git add "$LINE"
    fi
done

假设我test.txt已经提交了一个文件并且它没有尾随空格。现在我在某处添加尾随空格,我希望pre-commit删除该空格并且不提交任何内容(因为没有更改)。但这就是发生的事情:

C:\> git status
On branch test
Your branch is ahead of 'origin/test' by 17 commits.
(use "git push" to publish your local commits)

Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
        modified:   test.txt

no changes added to commit (use "git add" and/or "git commit -a")

C:\> git commit test.txt -m test
test.txt
[test 30cb9c0] test

C:\> git status
On branch test
Your branch is ahead of 'origin/test' by 18 commits.
(use "git push" to publish your local commits)

Changes to be committed:
(use "git restore --staged <file>..." to unstage)
        modified:   test.txt

Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
        modified:   test.txt

C:\> git add test.txt

C:\> git status
On branch test
Your branch is ahead of 'origin/test' by 18 commits.
(use "git push" to publish your local commits)

nothing to commit, working tree clean        

它确实确实从 中删除了尾随空格test.txt,因为当我add用它清理的文件git add test.txt显示没有更多更改时。但是该pre-commit钩子似乎导致带有尾随空格的文件位于暂存区域中,而没有尾随空格的文件尚未暂存以进行提交。

如何处理即将提交的所有文件,提交所述处理的输出,但前提是这会导致对已提交版本的更改?

标签: gitgithookstrailing-whitespace

解决方案


推荐阅读