Can I recover a branch after its deletion in Git?

后端 未结 20 2133
广开言路
广开言路 2020-11-22 05:53

If I run git branch -d XYZ, is there a way to recover the branch? Is there a way to go back as if I didn\'t run the delete branch command?

20条回答
  •  臣服心动
    2020-11-22 06:30

    For GitHub users without Git installed:

    If you want to restore it from GitHub website, you can use their API to get a list of repo-related events:

    First

    • find those SHAs (commit hashes):

      curl -i https://api.github.com/repos/PublicUser/PublicRepo/events

      ... or for private repos:

      curl -su YourUserName https://api.github.com/repos/YourUserName/YourProject/events

      (will be prompted for GitHub password)

      • (If the repo rquires two-factor auth, see the comments on this answer below.)

    Next

    • go to GitHub and create a new temporary branch which will be deleted for ever (Chrome is preferable).

       •  Go to branches and delete that one.

       •  On the same page, without reloading, open DevTools, Network panel. Now prepare...

       •  Click restore. You will notice a new "line". Right-click on it and select "Copy as cURL" and save this text in some editor.

       •  Append to the end of the copied line of code, this one: -H "Cookie=".

    You should now get something like:

        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
    

    Final step

    • replace "BranchSHA" with your SHA-hash and BranchName with desired name (BTW, it is great hack to rename branch from web). If you were not too slow, you need to make this request anyhow. For example, just copy-paste to a terminal.

    P.S.

    I realize this may not be the "simplest solution" or the "right" solution, but it is offered in case someone finds it useful.

提交回复
热议问题