Git恢复已删除的文件并保留文件历史记录 [英] Git revert deleted file and preserve file history

查看:103
本文介绍了Git恢复已删除的文件并保留文件历史记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个文件 a.txt .有一天,我将其删除,提交并推送.

Suppose I have a file a.txt. One day, I deleted it, committed, and pushed.

第二天,我想恢复上一次提交,并恢复 a.txt .我尝试使用 git revert ,但是当我执行 git blame 时,所有行都显示了还原提交哈希.原始的责任历史丢失了.

The next day, I wanted like to revert the last commit, bringing back a.txt. I tried using git revert, but when I did git blame, all lines are showing the revert commit hash. The original blame history is lost.

我可以恢复文件并保留文件历史记录,即好像以前从未删除过文件一样吗?请注意,我不能更改历史记录,因为提交已被推送.

Can I recover the file and preserve the file history, i.e., as if the file has not been deleted before? Note that I must not change the history as the commit has been pushed.

谢谢!

推荐答案

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

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.)

    这篇关于Git恢复已删除的文件并保留文件历史记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆