If you’ve ever wanted to clean up your Git repository by removing its commit history while keeping the latest version of your code intact, have a read. This post explains how to achieve this using Git.
Why Clear Git History?
There are a few reasons you might want to clean up your commit history:
- You would like your repo to have a clean commit history.
- Sensitive data was accidentally pushed and needs removal.
- The repository has too many unnecessary or cluttered commits.
Important Note: The process below is irreversible. Proceed with caution!
Steps to Remove Git History While Keeping the Main Branch Intact
Step 1: Clone the Repository
git clone https://github.com/username/repository.git
cd repository
Step 2: Create a New Branch Without History
git checkout --orphan new-main
This creates a fresh branch with no previous commit history.
Step 3: Add All Files
git add .
Stage all files from the working directory.
Step 4: Commit the Current State
git commit -m "Initial commit with current state"
Make a new commit reflecting the current project state.
Step 5: Delete the Old Main Branch
git branch -D main
Remove the old branch locally.
Step 6: Rename the New Branch to Main
git branch -m main
Rename the new branch to main
.
Step 7: Force Push to GitHub
git push --force origin main
Push the new branch to the remote repository, overwriting the old history.
What About GitHub Activities?
Even after removing commit history, GitHub's Activities tab will still display past events like pushes, pull requests, and issue tracking. This happens because GitHub tracks these separately from your Git commit history.
How to Limit Activity Visibility:
-
Make the Repository Private:
- Go to Settings in your GitHub repository.
- Scroll down to Danger Zone and click Make Private.
-
Create a New Repository:
- Delete the old repository if historical activity is problematic.
- Create a new repository and push the cleaned code.
-
Transfer Repository Ownership:
- Transfer the repository to another account, which can reset some public logs.
-
Consider GitHub Enterprise:
- Use GitHub Enterprise for advanced control over activity visibility.
Final Thoughts
Removing Git commit history is useful for starting fresh, but keep in mind that GitHub’s Activities tab will still retain a record of past events. If a completely clean public record is essential, creating a new repository is your best option.
Top comments (0)