To reset a Git repository and remove all its history (such as to eliminate sensitive information from commits), follow these steps carefully. Be aware that this process is destructive and will rewrite the repository, so ensure this is what you want.
1. Backup the Current Repository
Before making any irreversible changes, create a backup of your repository in case you need to reference the old data later.
2. Create a New Branch Without History
# Move to your repository
cd /path/to/your/repo
# Checkout a new orphan branch
git checkout --orphan clean-history
An orphan branch starts without any history.
3. Stage and Commit Current Files
# Remove all tracked files from the index
git rm -rf --cached .
# Add all current files to the index
git add .
# Commit the current state
git commit -m "Initial clean commit"
4. Delete All Old Branches
# Delete all branches except the new one
git branch -D main
(Replace main
with your default branch name, if different. e.g, master
in some cases)
5. Replace the Default Branch
Rename the new branch to your default branch name:
git branch -m main
6. Force Push to Overwrite Remote Repository(Optional if the repo is not pushed to remote yet)
This step will overwrite the repository on the remote server and remove the history:
git push --force origin main
7. Remove Sensitive Information from Remote Servers
To ensure sensitive information is no longer accessible:
- Verify that the remote repository’s web interface (like GitHub or GitLab) no longer displays the commit history.
- Contact the repository host to remove any cached or archived snapshots, if applicable.
8. Re-clone the Repository(Optional)
To ensure a clean working directory, delete your local copy and re-clone the repository:
rm -rf /path/to/local/repo
git clone <repo-url>
Caution
- Shared repositories: If this repository is shared with collaborators, coordinate with them before force-pushing changes.
- Sensitive data: While this approach removes commit history, the data might still exist in backups or caches (e.g., GitHub’s systems). You may need to contact your hosting provider to ensure complete removal.
Alternative: Use git-filter-repo
If you want to remove specific sensitive data while keeping some history, use a tool like git-filter-repo. This allows you to rewrite history selectively, which may be a better option if you don’t want to lose all commit history.