【问题标题】:How does this pre-commit hook fix trailing whitespace?这个预提交钩子如何修复尾随空格?
【发布时间】:2010-04-20 17:51:26
【问题描述】:

this pre-commit hook 发生了什么?我认为更改文件会导致它们被重新暂存。

#!/bin/sh
#
# A git hook script to find and fix trailing whitespace
# in your commits. Bypass it with the --no-verify option
# to git-commit
#

if git-rev-parse --verify HEAD >/dev/null 2>&1 ; then
    against=HEAD
else
    # Initial commit: diff against an empty tree object
    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# Find files with trailing whitespace
for FILE in `exec git diff-index --check --cached $against -- | sed '/^[+-]/d' | sed -r 's/:[0-9]+:.*//' | uniq` ; do
    # Fix them!
    sed -i 's/[[:space:]]*$//' "$FILE"
done

# Now we can commit
exit

我认为这个想法是删除此提交涉及的所有文件中的尾随空格。

【问题讨论】:

    标签: git hook pre-commit-hook pre-commit


    【解决方案1】:

    关键是提交正确的内容,即:

    • 只有阶段(并添加到索引中)
    • 加上一些由预提交挂钩引入的修改

    第一点是通过git diff-index实现的

    将通过树对象找到的 blob 的内容和模式与当前索引的内容进行比较,并且可以选择忽略磁盘上文件的状态。

    exec git diff-index --check --cached $against --
    

    使用选项--cached:

    根本不考虑磁盘文件

    任何修改都会被视为新提交的一部分。

    你可以看看source of commit.c

    static int prepare_to_commit(const char *index_file, const char *prefix,
                     struct wt_status *s)
    {
    ...
    
        if (!no_verify && run_hook(index_file, "pre-commit", NULL))
            return 0;
    ...
    
    
    /*
     * Re-read the index as pre-commit hook could have updated it,
     * and write it out as a tree.  We must do this before we invoke
     * the editor and after we invoke run_status above.
     */
    discard_cache();
    read_cache_from(index_file);
    

    【讨论】:

    • 索引的任何修改都会被考虑在内,是的。不过,您仍然需要 git addpre-commit 挂钩中修改的任何文件。
    【解决方案2】:

    除非这不起作用。我尝试在我的预提交挂钩结束时执行以下操作:

    exec git diff-index --check --cached $against --
    

    但是在这些钩子中所做的更改实际上仍然没有被提交(至少在 git 1.7.3.4 中)。

    如果您真的希望更改生效,则必须明确

    git add "$file"
    

    对于您在预提交阶段修改的每个文件。

    【讨论】:

      【解决方案3】:

      这是可能的,但需要一个棘手的脚本。

      在这里您可以找到同样的问题已解决。在那里,它在每次提交时更新文件版本,而不是颤抖空格。它完全正常工作: https://github.com/addonszz/Galileo/tree/master/githooks

      然后,您只需将文件“updateVersion.sh”上的“版本文件替换”算法替换为“Trilling Spaces”算法。也许您需要更改一些内容,例如删除分支限制,因为那里的脚本只有在您位于“开发”分支时才会运行。

      此外,它只会更改文件(如果已暂存)。如果文件没有暂存,那么它什么也不做。更准确地说,它会打印出每一步都在做什么。

      【讨论】:

        猜你喜欢
        • 2020-03-09
        • 2017-01-07
        • 1970-01-01
        • 2013-12-15
        • 2017-02-08
        • 2016-09-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多