Orphaned Git Branches

This post demonstrates how to reset your commit history using orphan branches.

git checkout --orphan <new-branch> 

Using --orphan flag on git checkoutor switch commands creates a copy of the parent branch with all its content without the preceding commit history.

Use cases

  • When you change your private repository visibility, making it public, you may need to reset git logs to remove sensitive information that was committed earlier.
  • You may need to reduce the size of your repository by truncating its commit history.

Reset commit logs in a remote repository

The following workflow removes commit history from a remote git repository

After switching to an orphan branch (❷):

  • The git log command returns the message fatal: your current branch <branch-name> does not have any commit yet.
  • The git status command is going to list every file from the previous branch as a newly added file ready to be committed (that is, already staged)

If you don’t want to include all files from the previous branch, run git reset . to unstage everything and add only the files you need.

If you don’t need any files from the parent branch, run git rm -rf . right after creating an orphan branch (❷), which will remove all staged files. Another way to do it would be by running git switch --orphan=<new-branch> (instead of git checkout...). This will create a new branch without files from the parent branch.

By default, git doesn’t like commits without any changes, and to bypass that add the --allow-empty flag when making your initial commit as follows:

git commit --allow-empty -m "Initial commit"

<start-point> argument

In order to reset the initial state of a repository to a certain commit, add a <start-point> argument to the git checkout command:

git checkout --orphan <new-branch> [<start-point>]

The head of the new branch will point to this commit. It may be given as a commit-id, a tag, or even another branch name. If this option is omitted, the current HEAD will be used instead.

That’s it for today!

Conclusion

The example above demonstrated how to manage the commit history of a git repository with the standard git commands.

You may run into situations where you don’t want to wipe out the entire git history and only need to remove a sensitive file from your repository’s history without removing the commit itself. If that’s your case check out the git-filter repo or the BFG Repo-Cleaner tools that will help you to remove a file from every commit that it was involved with.

Resources:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store