且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Git恢复已删除的文件并保留文件历史记录

更新时间:2023-12-04 20:57:52

可以 执行此操作!方法如下:

You CAN do this! Here's how:

  1. 从要撤消的删除操作之前的提交开始一个新分支.
  2. 使用 git merge< sha>合并有问题的更改-s我们的.
  3. 如果除了要保留的删除内容之外,提交还进行了其他更改:
  1. Start a new branch from the commit preceding the delete that you want to undo.
  2. Merge the offending change with git merge <sha> -s ours.
  3. If the commit had changes besides the deletion that you want to keep:
  1. 使用 git diff< sha> ^.重新应用对工作副本的更改.|git apply .
  2. 舍弃删除操作(可以使用多种技术; git checkout -p 可能对您来说很好).
  1. Reapply the changes to your working copy with git diff <sha>^..<sha> | git apply.
  2. Discard the deletions (many techniques are available; git checkout -p may work well for you).

  • 将此分支合并回到主分支(例如master).
  • 这将产生一个具有两个分支的历史记录;一种是删除文件的文件,另一种是从未删除文件的文件.结果,git无需使用诸如 -C -C -C 之类的英雄来跟踪文件的历史记录.(实际上,即使使用 -C -C -C ,该文件也不会还原",因为git看到的是创建了一个新文件作为副本之前存在的文件.通过这种技术,您可以将同一文件重新引入到存储库中.)

    This produces a history with two branches; one in which the file was deleted, and one in which it was never deleted. As a result, git is able to track the file history without resorting to heroics such as -C -C -C. (In fact, even with -C -C -C, the file isn't "restored", because what git sees is that a new file was created as a copy of a previously existing file. With this technique, you are reintroducing the same file to the repository.)