Matthieu Vergne's Homepage

Last update: 06/01/2022 17:50:20

How to Completely Forget a Git Commits History?

Context

Commits aggregate in your banch depending on your development. You may find new features, additional fixes, refactoring, retakes, merge commits, cherry-picks from other branches, etc. As the natural development process unfolds, your branch shows how chaotic it was. At the end, it can be hard to figure out what was actually done. Although it is the normal way to go, it does not mean that it is satifactory. We plan here to forget all the history and preserve only the final state of the branch: what actually remains from your changes.

Question

How to Completely Forget a Git Commits History?

Method

Rewriting a Git history can be done in plenty of ways. Unfortunately, messing it up can be done as well. If you feel unsafe about rewriting the history, give a look here first. Better feel safe than sorry.

All you need is to squash everything into a single commit that you can split later if required. Be aware that you will be the sole author of this commit, which might be unwanted. Either provide authors information in the commit details or, after splitting, amend the relevant commits with the right authors.

Here is what you need to prepare:


BRANCH=$(git rev-parse --abbrev-ref HEAD) # Current branch to rewrite
COMMIT_START=<commit SHA-1>               # Commit after which we want to produce our single commit
MESSAGE="<message>"                       # Message of the single commit to produce

Notice that COMMIT_START should point to a commit that is already part of the branch. Either a commit that you produced yourself or a commit from a branch that you merged in yours. If it is not the case, you need first to merge this commit into your branch. You can merge or rebase, as you prefer, as long as you resolve the potential conflicts.

Once all is set up, here is how you retrieve all your changes into a single, additional commit:


git reset --soft ${COMMIT_START} # Restart the branch from the identified commit while preserving the current state uncommitted
git commit -m "${MESSAGE}"       # Commit the changes

At this point, all the changes not known at the level of the targetted commit are reduced to a single additional commit. You can split it if required.

Answer

Forgetting all the history of a branch is done with git reset --soft. It moves the branch back to a previous commit while preserving the current files. You can use then git commit to create an additional commit with the remaining changes.

Bibliography