How to hard delete an orphan commit in git?
To fully delete a commit, you need to delete all references to it, and then force an aggressive garbage-collection.
If you still have branches pointing to the commit, delete those first.
Next you will need to flush the commit from the reflog, which keeps references to every commit you have visited in the past 90 days by default (replace [commit-hash] with the first 8 characters of the commit hash):
git reflog | grep [commit-hash] | cut -d' ' -f2 | cut -d':' -f1 | tac | xargs git reflog delete
(I used tac
to reverse the order of deletions because if the commit shows up multiple times in the reflog, deleting an entry shifts all the entries following it)
Finally, force the garbage collection:
git gc --prune=now --aggressive
After this, git show [commit-hash]
will no longer show the commit, so you will know it is really deleted.
To remove a commit, you just need to make sure that it's no longer part of any branch. That is, for each branch in your repository, make sure the bad commit is not part of the child-to-parent chain of commits defining that branch. If you do find such a branch, either delete it, or change its history so that it no longer includes the bad commit.
Once that's true, the bad commit will be garbage-collected eventually.
If the commit is not referenced by anything, it will be removed with git's garbage collection, in time.
If you want to force it before hand, use git gc --prune=now --aggressive