Git home

One of the tools I use to stay out of git messes regularly is a git alias I call git home. It’s nothing innovative, but I found myself typing the following four commands together a lot. It does save me some time.

Terminal window
git home branch-name
# or just
git home

Instead of writing:

Terminal window
git reset --hard; git clean -d -f; git checkout branch-name; git pull

I use it in these situations:

  • I’ve committed everything I want to in my branch and submitted a PR to my colleagues for code review, but my working tree is still messy.
  • I was just testing out an idea, and I made a mess. I want to get the project back to a stable place to do other work.

What does it do?

  1. Hard resets → resets all files in the working tree back to HEAD.
  2. Cleans → Removes untracked files from the working tree. I use the -d option, which removes untracked directories, and also -f (force), so it actually deletes the files.
  3. Checks out the specified branch
  4. Pulls all of the latest changes

The reason I made this command specify a branch is so that you clean things up in a certain direction.

If you don’t specify a branch and just do git home, that makes the 3rd step equivalent to git checkout, which is equivalent to git checkout HEAD, which does nothing.

Therefore git home is the same as git home HEAD, which won’t move the HEAD pointer at all, and is a totally valid use case.

🚧 It is destructive

This is a destructive command. In fact it combines two of the most destructive git commands: reset and clean.

It will remove anything that isn’t committed or stashed.

git home is only for situations where everything you want to keep is already committed or stashed.

Add it as an alias

You can add git home as a git alias by running:

Terminal window
git config --global alias.home '!f() { git reset --hard; git clean -d -f; git checkout $1; git pull; }; f'

Then check to make sure it’s in your .gitconfig.

Terminal window
[alias]
home = "!f() { git reset --hard; git clean -d -f; git checkout $1; git pull; }; f"

Wow! You read the whole thing. People who make it this far sometimes want to receive emails when I post something new.

I also have an RSS feed.