git - 这个预提交钩子(Hook)如何修复尾随空格?

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

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

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

最佳答案

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

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

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

Compares the content and mode of the blobs found via a tree object with the content of the current index and, optionally ignoring the stat state of the file on disk.

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

使用选项--cached:

do not consider the on-disk file at all

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

你可以看看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 - 这个预提交钩子(Hook)如何修复尾随空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2677425/

相关文章:

C++ Windows : Access same variable from main process and CallWndProc process

windows - CollabNet SVN Edge 的代码审查工具

git - 如何进行git预提交代码检查?

git - 在构建期间向 docker 添加大文件

git - 我是否通过将我的主目录设为存储库然后在其中包含其他存储库来滥用 git?

git - 将非 git 文件夹与 git 文件夹 merge

php - Codeigniter,钩子(Hook)未正确加载输入类

WordPress:将 do_action 的输出保存在变量中

Git 从一个分支 rebase 到另一个分支

windows - 来自脚本的 TortoiseGit Git 提交消息