If for some reason you want to restart your git repostory (delete all old commits), this is “tutorial” for you. This will create a fresh starting point in your Git repository while preserving the current state of your project (files and content), but discarding all previous commit history.
Steps
-
Create a New Orphan Branch:
git checkout --orphan new_old
This command creates a new branch named
new_old
which is not based on any existing branch, effectively having no commit history. After running this command, you’ll be on thenew_old
branch. -
Stage All Changes:
git add -A
This command stages all changes in your project (new, modified, and deleted files). It prepares all your current project files to be committed as a new initial commit on the
new_old
branch. -
Commit the Changes:
git commit -m "Initial commit"
This creates a new commit in the
new_old
branch with the message “Initial commit”. This commit will act as the new starting point for your project history. -
Switch Back to Main Branch:
git checkout main
Switches your working directory back to the
main
branch. Themain
branch still contains the old commit history at this point. -
Replace Main Branch History:
git reset --hard new_old
This command resets the
main
branch to match the state of thenew_old
branch. All the commit history inmain
is replaced with the single commit fromnew_old
. -
Delete the Temporary Orphan Branch:
git branch -D new_old
Deletes the
new_old
branch as it’s no longer needed. Themain
branch now contains the current state of your project with a clean history. -
Force Push to Remote Repository:
git push origin main --force
Forcefully updates the
main
branch on the remote repository. Warning: This step rewrites history on the remote. It’s a potentially destructive operation and can impact collaborators.
Important Notes
- Always communicate with your team before rewriting the project’s history if you’re working collaboratively.
- It’s a good practice to backup your repository before performing operations that rewrite history.
- This process is often used to clean up a repository or to reduce its size by removing old and unnecessary commit history.