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

mos*_*ted 82 git

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

只有一个分支(主).

我知道包含错误的提交.

我可以使用父提交的sha1哈希来恢复目录的状态,因为它是在包含错误之前的状态吗?

我想过这样的事情:

git checkout 348ce0aa02d3738e55ac9085080028b548e3d8d3 path/to/the/folder/
Run Code Online (Sandbox Code Playgroud)

但它不起作用.

Car*_*rós 139

尝试在修订版和路径之间添加" - ":

git checkout 348ce0aa02d3738e55ac9085080028b548e3d8d3 -- path/to/the/folder/ 
Run Code Online (Sandbox Code Playgroud)

  • 但有一个问题:OP没有指定目录是否仍然存在.要将现有目录还原到提交状态,应首先删除目录的内容.在其他情况下,旧提交中不存在的现有文件将不会被删除. (17认同)
  • +1 @Alberto肯定同意.我做了`rm -Rf path/to/the/folder`然后`git checkout 348ce0aa02d3738e55ac9085080028b548e3d8d3 - path/to/the/folder /` - 结果:该路径与该提交中的文件完全相同,没有差异也没有此提交后创建的额外文件.这就是我想要的. (7认同)
  • “-”是做什么的? (2认同)
  • @RayFoss它告诉git以下参数是文件(否则它们可能与提交哈希,分支或其他东西混淆).通常它们不是必需的,但放入它们并没有什么坏处 (2认同)

upt*_*you 10

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

git restore -s commit-sha-that-contains-dir relative/path/to/folder
Run Code Online (Sandbox Code Playgroud)

男人参考:

-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.
Run Code Online (Sandbox Code Playgroud)