Hackernoon logoDoing Quick Experiments In Git by@dat-tran

Doing Quick Experiments In Git

Dat Tran Hacker Noon profile picture

@dat-tranDat Tran

I'm a developer. I love to learn new things. I write about WordPress at http://binarycarpenter.com/

Sometimes in the middle of software development, you want to try some crazy idea out but don't want to mess up with current code. What should you do?

The scenario

Let's say I'm developing a website. The current text color of the main tag is red, as shown here:

main {
    color: red;

Currently, this is the whole git history:

What if I want to try using color blue for main instead?

Checkout a commit

Instead of creating a new branch, I can checkout the branch where I want to start the experiment. In this example, I'm going to checkout the latest branch.

git warns me about what I did. HEAD is not pointing to any branch now and it's in "detached" mode.

What's special about this mode? Here are some:

  • All changes, commits in detached HEAD don't belong to any branch
  • You can try new code, add commit... as you can with regular branch
  • When you exit detached HEAD mode (by checking out other branches), the changes you made while in this mode are orphaned and will be purge in the next garbage collection run

Now, let's try changing the text color to blue and commit the change.

Exit the detached HEAD mode

Let's say I'm done with the experiment. If I don't like the new color, I can just checkout other branch and forget about changes I made in detached HEAD mode. They will be garbage collected.

However, if I like the changes. I can start a new branch from existing code in detached HEAD mode. Now, the changes are persisted in the new branch. Creating a new branch in the detached HEAD mode is simple. In the code below, I create a new branch with a name "bluetext"

git branch bluetext

Now, if I checkout other branch (master) and then checking back to blue text, all changes I made in the detached HEAD mode are there.


I find this trick is quite useful when I want to test out new ideas or small features. I can skip the work of creating new branch. Also, if the idea doesn't work, I can just leave it there and let the garbage collector do its job.


    Join Hacker Noon

    Create your free account to unlock your custom reading experience.