Search code examples
github-api

How to get GitHub REST API to restore a deleted branch


I've been looking for a way to automate a task, one manual part that needs automation is this restore branch button, is there a way to do this using Github API? I've read these two documents and couldn't find anything, Thank you.

https://docs.github.com/en/rest/reference/pulls

https://docs.github.com/en/rest/reference/branches

same functionality as this button


Solution

  • Following off the advice from here: git can I view the reflog of a remote?

    I was able to restore a PR branch via the GitHub CLI/API by...

    Getting the SHA of the HEAD of the branch to restore with:

    gh pr view {pr_number} --json commits

    where the last commit in the "commits" array will have a "oid" value (which I believe stands for orphan id), and that can be used to create the restored branch with

    gh api repos/{owner}/{repo}/git/refs -f ref=refs/heads/{new_branch_name} -f sha={oid}
    
    # set new_branch_name to the name of the PR branch to keep same behavior as button
    

    and now the branch can be fetch'd when within a cloned instance of the repository:

    git fetch

    but is also available via API as there is now a new remote branch

    Sorry if you can't use gh. This worked for me and I don't mind the dependency. If someone likes they can figure out a full REST API only way.