paint-brush
Doing Quick Experiments In Git by@dat-tran
348 reads
348 reads

Doing Quick Experiments In Git

by Dat TranAugust 20th, 2019
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In this mode, commits in "detached" mode don't belong to any branch. Instead of creating a new branch, you can checkout the branch where you want to start the experiment. The changes you made while in this mode are orphaned and will be purge in the next garbage collection run. If I don't like the new color, I can just checkout other branch and forget about changes I made in detached HEAD mode. Now, if I like the changes, the changes are persisted in the new branch.

Company Mentioned

Mention Thumbnail
featured image - Doing Quick Experiments In Git
Dat Tran HackerNoon profile picture
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.

Conclusion

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.
    바카라사이트 바카라사이트 온라인바카라