For some reason or another, there may come a time when you want to completely remove all previous commits to start afresh from a Git repository without wanting to delete and recreate it.
The following are the instructions to keep the files but remove all commits history.
- Change to the repository directory.
- Checkout the current code to a new branch because you cannot delete the branch you are on.
- Add all the files.
- Commit all the changes.
- Delete the previous
master
branch. - Rename the current branch to the new
master
. - Force update your repository.
An example of the instructions are given below.
cd repository
git checkout --orphan latest_branch
git add -A
git commit -a -m "Git Cleanup."
git branch -D master
git branch -m master
git push -f origin master
The following are the instructions to start again from a clean empty repository without any previous commits or files.
- Change to the repository directory.
- Checkout the current code to a new branch because you cannot delete the branch you are on.
- Remove all the files from the folder.
- Add all the files.
- Commit all the changes.
- Delete the previous
master
branch. - Rename the current branch to the new
master
. - Force update your repository.
An example of the instructions are given below.
cd repository
git checkout --orphan latest_branch
rm -fr *
git add -A
git commit -a -m "Git Cleanup."
git branch -D master
git branch -m master
git push -f origin master
Have fun with your repository and only execute the above commands if you really need it. Once you execute them, you cannot go back (unless you have another backup somewhere) :smile: