gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 13:54:15 27 4
gpt4 key购买 nike

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com