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

标签 git code-formatting githooks

我想在文件添加到 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/

相关文章:

c# - Visual Studio 类似 Eclipse 的格式设置

python - 编写 argparse 解析器的最佳实践

java - 整理导入打扰评论

git - 如何通过压缩提交来节省git存储库中的空间?

node.js - 从单个存储库发布多个包

git - 提交后使用 git hook

git - 如何在服务器端创建一个git钩子(Hook),以便在收到推送后 pull (在需要root权限才能修改的路径中)?

git - 设置一个 git hook 以在远程服务器上自动 git pull

git - git bisect 如何选择一个没有第一个好的提交作为祖先的提交? (使用 --first-parent)

git - 在没有 --stdlayout 的情况下从 Git-Svn 克隆中恢复