Deleting all commit history in Git

To delete all commit history, you can simple delete .git folder. But if you still want to keep the repository, there is a safe and easy method. The idea is using a new orphan branch to replace the existing branch. The new orphan branch will have no parents and it will be the root of a new history totally disconnected from all the other branches and commits.

Delete all commit history

Follow below steps, assuming that you are on branch master:

# Step 1. Create a new orphan branch and swith to it.
# --orphan, create a new orphan branch and swith to it.
$ git checkout --orphan new-master

# Step 2. Delete the old branch
$ git branch -D master

# Step 3. Rename the new orphan branch to the old branch
$ git branch -m master

Now you have a new history that has no commits yet, you can do your first commit at the moment.

If you want to delete all the related commit objects immediately, run git gc to do an immediate garbage collection to remove them.


Deleting untracked files in Git

git clean command is used to remove untracked files in the working tree.

To delete all untracked files in the current directory, a safe way is to do 2 steps:

# Step 1, check what files will be deleted. 
# -n or --dry-run,  show what files will be deleted without actually deleting them.
$ git clean -n -d

# Step2, do actual deleting action.
# Delete untracked files and untracked directories. 
# -d, delete untracked dirctories. 
# -f, force to delete, if 'clean.requireForce' in Git confiuration is set to false, 
# 'git clean' (without '-f' option) will clean nothing .
$ git clean -f -d

To remove untracked files with or without ignored files:

# Delete only ignored files.
$ git clean -f -X

# Delete untracked files, untracked directories and ignored files.
$ git clean -f -d -x