在 Git 中删除分支后可以恢复分支吗?

如果我运行git branch -d XYZ ,是否有办法恢复分支?有没有办法像我没有运行 delete branch 命令一样返回?

答案

git checkout -b <branch> <sha>
git fsck --full --no-reflogs --unreachable --lost-found | grep commit | cut -d\  -f3 | xargs -n 1 git log -n 1 --pretty=oneline > .git/lost-found.txt
git config --global alias.rescue '!git fsck --full --no-reflogs --unreachable --lost-found | grep commit | cut -d\  -f3 | xargs -n 1 git log -n 1 --pretty=oneline > .git/lost-found.txt'
git cat-file -p 48540dfa438ad8e442b18e57a5a255c0ecad0560
git log -p 48540dfa438ad8e442b18e57a5a255c0ecad0560
git branch commit_rescued 48540dfa438ad8e442b18e57a5a255c0ecad0560
gitk --reflog
git checkout <sha>
git checkout -b <branch>
git checkout -b <branch> <sha>
git branch <branch> <sha>
git branch -m <restored branch> <final branch>

添加到tfe答案 :Git 源(在 git.git 存储库中)的contrib/区域中也有git-resurrect.sh脚本,可能会对您有所帮助。

git-resurrect <name>尝试查找名为<name>的分支提示的痕迹,然后尝试将其恢复。当前,在 reflog 中搜索签出消息,并且使用-r还可以合并消息。使用-m-t ,将扫描所有裁判的历史记录,以将Merge <name> into other Merge <other> into <name> Merge <name> into other /“ Merge <other> into <name> (分别)提交主题,这虽然很慢,但可以让您复活其他人的主题分支。

find . -ctime -12h -type f | sed 's/[./]//g' | git cat-file --batch-check | grep commit
curl 'https://github.com/UserName/ProjectName/branches?branch=BranchSHA&name=BranchName' -H 'Cookie:' -H 'Origin: https://github.com' -H 'Accept-Encoding: gzip, deflate, br' -H 'Accept-Language: en-US' -H 'User-Agent: User-Agent' -H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' -H 'Accept: */*' -H 'Referer: https://github.com/UserName/ProjectName/branches' -H 'X-Requested-With: XMLHttpRequest' -H 'Connection: keep-alive' --data 'utf8=%E2%9C%93&authenticity_token=token' --compressed
git branch -d [branch]
git branch -D [branch]
$ git fsck --full --no-reflogs --unreachable --lost-found > lost
$ cat lost | cut -d\  -f3 > commits
$ cat commits | xargs -n 1 git log -n 1 --pretty=oneline
$ git checkout -b NEW-BRANCH GIT-SHA
git fsck --full --no-reflogs --unreachable --lost-found > lost
cat lost | cut -d\  -f3 > commits
for c in `cat commits`; do  git show $c; read; done