Uncommon Case: How to Wipe All Commits from a Repo and Start Fresh

There are times when you might find yourself needing to start over in a Git repository. Whether it’s because you’re working on a project that has gone in a completely different direction, or you’ve inherited a repo filled with a messy commit history, starting fresh can sometimes be the best option. In this article, we’ll walk through the steps to wipe your Git repository clean and start with a new “Initial Commit.”

Precautions

Before we dive in, it’s crucial to understand that this process will erase your commit history. Make sure to backup your repository or ensure that you won’t need the old commits in the future.

Step 1: Create a New Orphan Branch

First, let’s create a new branch that will serve as our new starting point. We’ll use the --orphan switch to do this.

git checkout --orphan fresh-start

The --orphan switch creates a new branch, devoid of commit history, which allows us to start anew. When you switch to this new branch, you’ll notice that it doesn’t carry over the old commits, giving you a clean slate.

Step 2: Stage Your Files

Now, stage all the files you want to keep in your new branch. This step is similar to what you’d do when setting up a new project.

git add --all

Step 3: Make the Initial Commit

Commit the staged files to establish the new history.

git commit -m "Initial Commit"

Step 4: Delete the Old Main Branch

Now that we have our new starting point, it’s time to get rid of the old main branch. We’ll use the -D flag, which is a shorthand for --delete --force. This flag deletes the branch regardless of its push status, so use it cautiously.

git branch -D main

The -D flag forcefully deletes the 'main' branch, so make sure you are absolutely certain that you want to lose that history before running this command.

Step 5: Rename the New Branch to main

Rename your new branch to 'main' to make it the default branch. We’ll use the -m flag here, which stands for “move” or “rename.”

git branch -m main

The -m flag renames the current branch to 'main'. This is useful for making the new branch the default one, aligning it with the conventional naming scheme. Not too long ago, the main branch used to be called 'master'… but that’s a story for another time. 🙂

Step 6: Force Push to Remote

Finally, let’s update the remote repository with our new main branch. Be cautious, as this will overwrite the remote repository.

git push -f origin main

Wrapping Up

And there you have it! You’ve successfully wiped your Git repository clean and started anew. This process can be useful in various scenarios, but it’s not something to be taken lightly. Always make sure to backup your repository and consult with your team before taking such a drastic step.

Share