git for Windows:提交时删除尾随空格

git for Windows:提交时删除尾随空格,git,githooks,trailing-whitespace,Git,Githooks,Trailing Whitespace,我已经编写了一个pre-commithook,用git for Windows 2.27.0.Windows.1删除尾部空白。这似乎是一个研究得很好的课题,但不幸的是,我无法让它发挥应有的作用。这是我的.git\hooks\pre-commit文件: #!/bin/sh if git rev-parse --verify HEAD >/dev/null 2>&1 then against=HEAD else # Initial commit: diff aga

我已经编写了一个
pre-commit
hook,用git for Windows 2.27.0.Windows.1删除尾部空白。这似乎是一个研究得很好的课题,但不幸的是,我无法让它发挥应有的作用。这是我的
.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
,并且没有尾随空格。现在我在它的某个地方添加了尾随空格,我希望
预提交
删除该空格,而不提交任何内容(因为没有任何更改)。但事实就是这样:

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        
C:\>git状态
分支测试
您的分支比“原始/测试”提前17次提交。
(使用“git push”发布本地提交)
未为提交而暂存的更改:
(使用“git add…”更新将提交的内容)
(使用“git restore…”放弃工作目录中的更改)
修改:test.txt
未向提交添加任何更改(使用“git add”和/或“git commit-a”)
C:\>git commit test.txt-m test
test.txt
[测试30cb9c0]测试
C:\>git状态
分支测试
您的分支比“原始/测试”提前18次提交。
(使用“git push”发布本地提交)
要提交的更改:
(使用“git还原--暂存…”取消暂存)
修改:test.txt
未为提交而暂存的更改:
(使用“git add…”更新将提交的内容)
(使用“git restore…”放弃工作目录中的更改)
修改:test.txt
C:\>git add test.txt
C:\>git状态
分支测试
您的分支比“原始/测试”提前18次提交。
(使用“git push”发布本地提交)
没什么要承诺的,正在清理树
它确实从
test.txt
中删除了尾随空格,因为当我
add
使用
git add test.txt
清理文件时,它不再显示任何更改。但是
预提交
钩子似乎会导致带有尾随空格的文件位于暂存区域,而没有尾随空格的文件尚未暂存以进行提交


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

为什么在读取行时
git diff-z | xargs-0 |?为什么不在读取行时只执行
git diff |?否则带有空格的文件名会造成麻烦。也许可以将
-n1
添加到
xargs
参数中,以确保它一次只处理一个文件,因为我很确定这正是您想要的。(另外,为了清楚起见,我将
$LINE
重命名为
$FILE