Git 分支删除后恢复

如果本地功能分支删除了,发现远程仓库也没有提交怎么办?

如,当前 FileServer 项目本地分支如下

➜ FileServer git:(master) git branch 
 download
 js-post-upload
 kekule
* master

删除 download 分支,查看本地分支,没有 download 分支了

➜  FileServer git:(master) git branch -D download 
Deleted branch download (was 260b35d).
➜  FileServer git:(master) git branch
  js-post-upload
  kekule
* master

找回删除分支

使用 git log -g 查看所有 commit,根据 commit 记录查找功能分支(download)的 commit 提交,删除的分支 commit 没有分支记录,如: commit 260b35df028dde0e467786c0489558be0e943ee4

➜  FileServer git:(master) git log -g

Author: gyw123 
Date:   Sun Jun 10 22:52:00 2018 +0800

    add 3d

commit 260b35df028dde0e467786c0489558be0e943ee4
Reflog: HEAD@{1} (gywgithub )
Reflog message: commit: add a.txt
Author: gywgithub 
Date:   Wed Feb 26 18:34:03 2020 +0800

    add a.txt

commit d80a60f37d6c1d1ed633fb9bfab6e09ac06df6e8 (origin/js-post-upload, origin/js-post-upload, js-post-upload)
Reflog: HEAD@{2} (gywgithub )
Reflog message: checkout: moving from js-post-upload to download
Author: username 
Date:   Thu Nov 14 17:18:29 2019 +0800

    add post_403

commit d80a60f37d6c1d1ed633fb9bfab6e09ac06df6e8 (origin/js-post-upload, origin/js-post-upload, js-post-upload)
Reflog: HEAD@{3} (gyw123 )
Reflog message: checkout: moving from d80a60f37d6c1d1ed633fb9bfab6e09ac06df6e8 to js-post-upload
Author: username 
Date:   Thu Nov 14 17:18:29 2019 +0800

    add post_403

commit d80a60f37d6c1d1ed633fb9bfab6e09ac06df6e8 (origin/js-post-upload, origin/js-post-upload, js-post-upload)
Reflog: HEAD@{4} (gyw123 )
Reflog message: checkout: moving from master to origin/js-post-upload
Author: username 
Date:   Thu Nov 14 17:18:29 2019 +0800

    add post_403

由于记得在功能分支(download)中最后添加了 a.txt 文件,现在可以确定 commit 260b35df028dde0e467786c0489558be0e943ee4 是功能分支(download)的提交

使用 git branch new_branch commitId 命令创建功能分支(download),这样创建出来的分支就保留了 commitId 的对应的代码修改

➜  FileServer git:(master) git branch download 260b35df028dde0e467786c0489558be0e943ee4
➜  FileServer git:(master) git branch 
➜  FileServer git:(master) git checkout download 
Switched to branch 'download'
➜  FileServer git:(download) git log

commit 260b35df028dde0e467786c0489558be0e943ee4 (HEAD -> download)
Author: gywgithub 
Date:   Wed Feb 26 18:34:03 2020 +0800

    add a.txt
...
提示

如果 commit 记录很多,可以使用 git log -g --grep 'xxx' 命令根据 commit 提交的信息模糊搜索;或者使用 git log -g --author='[email protected]' 命令根据用户名模糊搜索。

git 命令参数文档查找可以使用 git log --help , git --help

你可能感兴趣的:(Git 分支删除后恢复)