如何在git中找到已重命名文件的新名称

oxalkeyp  于 2023-05-05  发布在  Git
关注(0)|答案(3)|浏览(109)

我正在查看git历史,发现了一些感兴趣的文件。不幸的是,它已经改名了!有没有一个整洁的方法来发现文件的新路径是什么?
我目前的做法是

[dbn repo]$ git log -- -1 --pretty=oneline old_directory/interesting_file.py
5ee1cf move old_directory files
[dbn repo]$ git log --stat -1 5ee1cf
commit 5ee1cf
Author: oh, it was me, the scoundral <dbn@dbn.dbn>

    move old_directory files

{old_directory => new_directory}/interesting_file.py

我可以把它折叠成一行代码,但是move commit可能有一堆我不关心的其他东西。
背景--我现在是手工完成的,但这是我希望编写脚本的一些考古工作的一部分,所以如果能有一个适合脚本的解决方案就好了。

z3yyvxxp

z3yyvxxp1#

也许这可以帮助:

#!/usr/bin/env python3

import sys
import subprocess

# Usage: ./script <file>
file = sys.argv[1]
search_next = True
while search_next:
    sha1 = subprocess.check_output(["git", "log", "--format=%H", "-1", "--", file]).rstrip().decode()
    if sha1 == '':
        exit(0)
    file_stat = subprocess.check_output(["git", "whatchanged", "--format=", "-1", sha1]).strip().decode()
    for line in file_stat.splitlines():
        columns = line.split()
        change_type = columns[4]
        old_file = columns[5]
        if change_type.startswith("R") and old_file == file:
            print(f"File ‘{file}’ was renamed to ‘{columns[6]}’ in commit {sha1}")
            file = columns[6]
            search_next = True
            break
        search_next = False

git whatchanged解析“stat”输出的麻烦较少。
显然,可以将git-log(1)的-M开关传递给git-whatchanged(1)(即控制文件差异检测的东西)。
testing

nhaq1z21

nhaq1z212#

最快的方法就是

git log --oneline -m --first-parent --diff-filter=R --name-status

然后在搜索结果中寻找你感兴趣的路径。

zc0qhyus

zc0qhyus3#

如果创建了文件:

$ touch a
$ git add a
$ git commit -m 'add file'

...后来,改名为:

$ mv a b
$ git add .
$ git commit -m 'rename file'

你可以找到这样的“重命名”提交:

$ git log --oneline -- a
bbbbbbb rename file
aaaaaaa add file

...并显示更改:

$ git show bbbbbbb
...
diff --git a/a b/b
similarity index 100%
rename from a
rename to b

相关问题