git reflog 和 git cherry-pick 恢复回滚之前的代码

945 阅读1分钟

有时候我们使用 git reset --hard commitId 回滚代码后,有后悔了,需要回到回滚之前的某个 commitId 时刻,可以使用 git reflog + git cheerry-pick 方式,具体看下面:

git reset --hard commitId 回滚代码

git 提交信息如下:

image.png

代码回滚到 test1:

git reset --hard ace9f3c7b6afa52423552f2323d3dc574dd29305

导致 test2 ~ test3 全部丢失

git log 后的信息如下:

image.png

代码恢复

问题来了: 怎么把 test2 ~ test3 的代码恢复?

1. 使用 git reflog 找到所有的日志

git reflog

image.png

2. 回滚到 test2 上

git reset --hard cf7ba9f

查看日志:git log

image.png

3. git cherry-pick 到 test3

git cherry-pick 8338180

查看日志:git log

image.png

代码又回来啦~

ps: 本地分支使用回滚 git reset --hard xxxx 后, push 到远程分支,必须强制推送,否则会不成功,