Git: 以新名称签出旧版本目录

Git: Checkout old version of directory under new name

如何以新名称签出以前版本的目录?

(我的回购协议中一直有一个目录 foo。我想在我当前的工作树中创建一个目录 foo_old,其内容是 HEAD~2:foo 的目录。我同时需要两个版本,以确保它们给出相同的结果,测试这需要相当多的代码并且需要同时提供两个结果(例如,结果不仅仅是整数),所以我不能简单地结账 HEAD~2 暂时做我想做的)

This question 询问如何以新名称签出文件的先前版本,但接受的答案不能推广到目录。

你可以做的很简单:

git co -b new-branch-name    # create and go to new branch, just to be sure
git slg                      # get the commit hash you need for next step
git co [commit-hash]         # now you get the old folder by the state you need it

然后复制你需要的目录到你的桌面。 (您现在处于 HEAD 分离状态)

git co new-branch-name       # cause you are in detached head go back to new-branch

在桌面上将目录重命名为 foo_old 并将其复制粘贴到项目中需要的位置。

我刚刚写了一个 python script 来从 Git 特定版本的历史记录中复制文件或子目录。

脚本可以在控制台显示内容或保存在某个目录下。它保留了文件执行权限和行尾。

脚本中的主要逻辑是:

  • 通过git ls-tree
  • 获取特定版本目录中的文件列表
  • 遍历列表
    • 读取 git cat-file
    • 修订时的文件内容
    • 设置文件模式