How to restore orphaned or deleted commits
From time to time, you may encounter a situation where someone has accidentally pushed their changes to Bitbucket Cloud without first pulling the changes from the server. When this happens, Bitbucket Cloud will show that all the commits have been 'stripped'. Unfortunately, this means you now have a limited amount of time to fix this situation. The good news is that you can almost always fix this yourself locally, without any intervention from Bitbucket Cloud support. Here's the basics:
Your commits aren't gone (yet)
When you use --force, you are adding new commits to Git and updating the branch reference of your branch. You have only orphaned the existing previous line of work as it is no longer referenced by anything. Git will gc (garbage collect) orphaned data on its own. It checks to see if it should gc every time you interact with Git. This means the moment it happens, you need to start work to recover it. There may be other ways to do this, but this is by far the easiest if you have a copy of the repo with the orphaned commits:
- Make a backup of the repo locally.
- Find the last commit that your 'master' (or other) branch should have been on before the push. You can use the 'stripped' hashes to find this or find another user who has a clone of the repo in the state you expect it to be in.
Create a new branch in your local repository with that commit as the head of the branch:
$ git branch master-recovery fg378o78
- Verify that your data is in a state you expect it to be in
Now, push that branch into the 'master' branch
git push origin master-recovery:/refs/heads/master --force
- You will be telling the remote Git that you want the current commit of master-recovery to be the current commit of master.
Now, pull master again from Bitbucket Cloud:
git pull origin master
- You should now have your data locally and on Bitbucket Cloud back in the state it was in before the accidental push.
To prevent this in the future, you can disable non-fast-forward pushes from any repository's admin page.