gpt4 book ai didi

Git 直接修改索引的内容,用于pre-commit formatting hook

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

我想在文件添加到 Git 索引之前自动格式化我的文件。现在,我有一个如下所示的预提交 Hook :

#!/bin/bash

set -e
exec 1>&2

workingext="working.$$"
ext="bak.$$"
git diff -z --cached --name-only | egrep -z '\.(pl|pm|t)$' | \
while read -d'' -r f; do
# First modify the file in the index
mv "$f" "$f.$workingext"
git show :"$f" > "$f"
perl -c "$f"
perltidy -pbp -nst -b -bext="$ext" "$f";
rm -f "$f.$ext"
git add "$f"
mv "$f.$workingext" "$f"
# Then the working copy
perl -c "$f"
perltidy -pbp -nst -b -bext="$ext" "$f";
rm -f "$f.$ext"
done

基本上,我备份工作副本,检查索引副本,格式化它们,将它们添加到索引,然后恢复工作副本并格式化它们,这样工作副本和索引副本之间的差异就不会不要长得太大。我首先使用 perl -c 检查文件的语法,这样格式化程序 perltidy 就不会被语法无效的文件弄糊涂了。

到目前为止,这似乎运作良好。但是,我想知道是否有办法将一个文件的内容添加到另一个文件名下的索引中。也就是说,像 git update-index-from-file --from-file foo.pl.tmp foo.pl 这样的命令会更新文件 foo.pl 这样它在索引中的内容完全来自 foo.pl.tmp,但其在工作目录中的版本保持不变。这可能会避免我现在正在做的重命名之舞(尽管这可能有助于确保我不会无可挽回地丢失索引的内容)。

最佳答案

是的,这是可能的。首先,您需要通过运行以下命令从您的文件创建一个 blob:

git hash-object -w foo.pl.tmp

参见此处:http://www.kernel.org/pub/software/scm/git/docs/git-hash-object.html

Computes the object ID value for an object with specified type with the contents of the named file (which can be outside of the work tree), and optionally writes the resulting object into the object database. Reports its object ID to its standard output.

使用 git hash-object 发送到 STDOUT 的 blob sha,您现在可以通过运行将此 blob 作为“foo.pl”添加到您的索引中

git update-index --add --cacheinfo 100644 *YOURSHA* foo.pl

来自manpage of update-index :

--cacheinfo is used to register a file that is not in the current working directory. This is useful for minimum-checkout merging.

To pretend you have a file with mode and sha1 at path, say:

$ git update-index --cacheinfo mode sha1 path

但我想指出,您的情况看起来很像您实际上应该使用涂抹滤镜来做这些事情。请参阅此处以了解它们:https://git-scm.com/book/en/v2/Customizing-Git-Git-Attributes#Keyword-Expansion

关于Git 直接修改索引的内容,用于pre-commit formatting hook,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14410733/

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