This is one of those things that’s obvious once you see it, but perhaps not obvious when you’re looking for it.

Let’s say you find yourself in an environment where you don’t have easy access to a shell, such as working on a project using Code Sandbox, Codepen, or some other in-the-browser cloud-based Javascript programming environment. It’s common in these environments to be able to commit changes to a Git repository—indeed, that might be the only way to publish and test changes to your project.

Now imagine you’ve spent two hours trying to figure out why something’s not working and you’ve given up for today. Now you have 38 extra commits that you’d like to delete, but you only have access to your programming environment and What do you do?

If you had a shell, you’d type something like git reset --hard HEAD~38 and be done with it, but you can’t do that in Code Sandbox nor at Github. What now?!

A Solution

Refactor your Git branches at Github. No, really.

  1. Visit Github, specifically the Branches in your project.
  2. For safety, create a branch level with your current working branch (which I’ll call main). I’ll call the newly-created branch old-main-delete-me.
  3. If main is the default branch, and it often is, then change the default branch to old-main-delete-me.
  4. Now that main is not the default branch, delete branch main.
  5. Return to your project’s code, then visit the Commits.
  6. Select the commit you’d like to roll back to, which I’ll call the “target commit”. In our example, that’s 38 commits before old-main-delete-me.
  7. Create a branch called main at the target commit.
  8. Change the default branch back to main. Now is a good time to verify that main correctly points to the target commit.
  9. Delete the branch old-main-delete-me. Wait for Github to throw away your abandoned commits, whenever it gets around to doing garbage collection in your repository.

And now main points 38 commits earlier than it used to. Enjoy!