gpt4 book ai didi

git - 如何确定一个文件是否与 git 历史记录中的文件相同

转载 作者:太空狗 更新时间:2023-10-29 14:13:58 26 4
gpt4 key购买 nike

我有任意文件 foo,没有提交给 git。

我还有一个文件,它的整个历史都保存在 git 中,bar

我如何确定 foo 是否与曾经存在的任何版本的 bar 相同?

最佳答案

很容易判断文件 foo 的内容是否出现在 repo 的某个地方:

file=foo  # or argument to script, etc
sha1=$(git hash-object -t blob $file)
repotype=$(git cat-file -t $sha1 2>/dev/null) || {
echo "file \"$file\" is not in the repo"
exit 1
}
[ $repotype = blob ] || {
echo "uh oh: file \"$file\" matches non-file ($repotype) object"
exit 1
}

但是,仅仅因为 foo 作为一个 blob 出现在 repo 中,并不意味着它出现在名称 bar 下(或者甚至可能根本没有,它可能有被 git add 编辑但从未在提交下 checkin )。所以现在查看每个(合理的?)提交,提取目标路径的 blob-ID,如果不存在则跳过提交:

target_path=bar

git rev-list --branches | # or --all, or HEAD, or (etc)
while read id; do
file_id=$(git rev-parse -q --verify $id:$target_path) || continue
[ $file_id = $sha1 ] || continue
echo "found \"$file\" as \"$target_path\" in $id"
# do more here if you like, e.g., git show $id
done

如果您想在任何 名称下找到它,而不是某个特定的显式名称,您可以git ls-tree -r 每次提交以查找所有 blob 并检查它们的 ID。

(注意:除了零碎的之外未经测试,偶尔可能会重新打字或在此过程中更改,谨防错别字或愚蠢的错误)

关于git - 如何确定一个文件是否与 git 历史记录中的文件相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19397475/

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