Remove commits that have been pushed from commit history

Viewed 113

[For completeness sake: I am in a setting where I am accessing, from a single local copy, a private repo, of which I have sole access. There is no concern related to other users or even cloned versions of the repo in this particular setting.]

I have been trying to figure out how to completely delete a range of commits from a directory.

The important thing is that I am not functionally trying to undo the commit (i.e., I want to revert the repo to the state without the commit, using perhaps a reversing commit), I am trying to concretely remove the commit (i.e., I don't want it appearing in the commit history anymore). I have found a lot of answers that either explain how to do this locally, or how to functionally revert remotely — but not how to remove the commit from history completely.

This is because for the purposes of debugging continuous integrations, I made 40 commits, that I would like to squash.

How can do this? Again, the commits have all been pushed to a repo, and I want to remove these commits from the history. (It would be nice if I can merge all the changes into a single commit, but my main focus is removing the commit history so I can reintroduce the changes by hand if necessary.)

Here is an example repository, say I want to remove or squash the top 10 commits: https://github.com/jlumbroso/push-generated-file/commits/main

Thank you!

2 Answers

You can do this by squashing the commits with git rebase -i BASE_COMMIT. That will open an editor, where you can leave the first commit at pick and change the rest to squash, then save and exit. You will be prompted to edit the commit message for that final commit.

This will result in a single commit with all of the changes that were in those 40 commits.

You'll then need to do a force push (e.g. git push -f origin branch) to the remote server to push the rebased branch. Note that GitHub does not run git gc by default, so anyone who knows the original commit ID of one of the commits can still view it, but it will not be a part of any branch.

It's easy enough to do this, just make the change locally and then force push it. At it's implest that would be something like.

git reset --hard <commit>
git push -f

However you need to be aware of the consequences.While you can remove the commits from the branch on github you can't remove them from your user's local branches. When your users pull, their clients will attempt to merge the commits you deleted with any new commits in the repository potentially resulting in a horrible mess.

This is the reason that, while possible, rewriting git history that you have previously published is discouraged.

Related