Reflog is like a safety net in Git, allowing you to recover lost work and navigate through changes made to your repository. While we briefly touched on it in a previous article about restoring lost commits, today we’ll delve deeper into what reflog does and how you can leverage it to safeguard your work.

The official definition from the man pages is somewhat cryptic:

git-reflog – Manage reflog information

However, a clearer explanation from later in the document states:

Reflog is a mechanism to record when the tip of branches are updated. This command is to manage the information recorded in it.

In simpler terms, reflog keeps track of every action that affects the state of your branches. This includes commits, merges, rebases, branch switches, and more. If you ever feel like you’ve lost work due to an unintended action, reflog is your go-to tool for recovering it.

Imagine you’ve just performed a git reset and inadvertently moved your HEAD back a few commits, only to realize you need code from one of those earlier commits. Running git reflog will display a list of recent commits and actions:

This list includes commit pointers, abbreviated SHA1 hashes, actions, and commit messages. Armed with this information, you can use commands like git show, git checkout, git cherry-pick, or git merge to retrieve lost changes and reintegrate them into your history.

You can also use the –all option to inspect detailed information about different branches and even the stash:

Reflog serves another important purpose: managing old entries to conserve space in your repository. The delete subcommand allows you to remove individual reflogs, while expire is more useful as it can be given a date to remove entries from.

For example, John Wiegley demonstrates how to quickly compress a repository using reflog commands:

$ git reflog expire --expire=1.minute refs/heads/master
$ git fsck --unreachable
$ git prune
$ git gc

This sequence removes reflogs older than a minute for the master branch, deletes any unused commits, and performs general cleanup to optimize the repository’s size.

Explore the manpage for more options, and if you have additional use cases for reflog, feel free to share them!