如何从git仓库的历史记录中恢复整个目录?

123

我想要从我的git存储库的历史记录中恢复一个整个目录(递归)。

只有1个分支(主分支)。

我知道包括错误的提交。

我可以使用父提交的sha1哈希来将目录状态恢复到在包括错误之前的状态吗?

我考虑了像这样的东西:

git checkout 348ce0aa02d3738e55ac9085080028b548e3d8d3 path/to/the/folder/

但是它没有起作用。


10
尝试在修订版本和路径之间添加“--”: git checkout 348ce0aa02d3738e55ac9085080028b548e3d8d3 -- path/to/the/folder/ - Carlos Campderrós
1
@CarlosCampderrós 把它写成一个真正的答案,赶在其他人之前收集你的15分吧 ;) - ralphtheninja
@MagnusSkog 我不确定那会不会起作用,所以我留了个评论来检查。现在我确定它可以工作了,我已经把它写成答案了 :) - Carlos Campderrós
2
作为一般提示,“它没有工作”并不是很有用。最好告诉我们为什么它没有工作,最好附上错误输出(如果非常长,则应进行修剪)。 - me_and
@me_and 你是对的 - 感谢你的反馈。下次我会加入更多信息! - mostwanted
6个回答

209

尝试在修订版本和路径之间添加“--”:

git checkout 348ce0aa02d3738e55ac9085080028b548e3d8d3 -- path/to/the/folder/ 

如果你想从以前的提交中恢复一个目录,你可以将提交哈希替换为HEAD~1,例如:

git checkout HEAD~1 -- path/to/the/folder/ 

23
然而,有一个问题:原帖并未指定该目录是否仍然存在。要将现有目录恢复到提交状态,首先应删除目录的内容。否则,旧提交中不存在的现有文件将不会被删除。 - Alberto
8
+1 @Alberto 确实同意。我执行了 rm -Rf path/to/the/folder,然后执行了 git checkout 348ce0aa02d3738e55ac9085080028b548e3d8d3 -- path/to/the/folder/ - 结果:该路径中的文件与该提交时完全相同,没有任何差异和额外的文件被创建。这正是我想要的。 - therobyouknow
在提交末尾添加插入符号对我很有用。 git checkout <deleting_commit>^ -- <folder_path> - Rady
2
-- 是什么作用? - Ray Foss
2
@RayFoss 它告诉 Git 以下参数是文件(否则它们可能会与提交哈希、分支或其他内容混淆)。通常它们不是必需的,但放置它们也无妨。 - Carlos Campderrós
显示剩余4条评论

9

对于现代git(-s--source):

git restore -s commit-sha-that-contains-dir relative/path/to/folder

man 参考手册:

-s <tree>, --source=<tree>
   Restore the working tree files with the content from the given tree. It is common to specify
   the source tree by naming a commit, branch or tag associated with it.

   If not specified, the contents are restored from HEAD if --staged is given, otherwise from the index.

   As a special case, you may use "A...B" as a shortcut for the merge base of A and B if there
   is exactly one merge base. You can leave out at most one of A and B, in which case it
   defaults to HEAD.

4
有两种简单的方法可以做到这一点:
如果包含错误的提交 包含了错误,则使用 git revert来反转其影响。
如果不是这样的话,简单的路径如下:
  1. git checkout 348…
  2. cp -a path/to/the/folder ../tmp-restore-folder
  3. git checkout HEAD # 或其他分支
  4. rm -rf path/to/the/folder
  5. mv ../tmp-restore-folder path/to/the/folder
  6. git add path/to/the/folder
  7. git commit -m "revert …"

3
git checkout -- path/to/folder/

3

您可以使用git checkout master -- path/to/the/folder-you-want-to-restore/命令从master分支恢复本地分支上的目录或文件。


1

如果你只是执行git checkout <SHA-ID>,那么它会暂时将你移动到该SHA-commit。

每个提交对象都保存了那个时间磁盘的完整结构,因此如果你在那里有文件并且需要将其复制出来,可以这样做。但要注意,你不会处于任何分支上,所以你必须在将文件复制到你的工作树并提交之前回到主分支。


关于“回到主分支”的意思,您是指切换到主分支吗? - Pacerier

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接