Instant branching and merging are the most lethal of Git’s killer features.
Problem: External factors inevitably necessitate context switching. A severe bug manifests in the released version without warning. The deadline for a certain feature is moved closer. A developer whose help you need for a key section of the project is about to leave. In all cases, you must abruptly drop what you are doing and focus on a completely different task.
Interrupting your train of thought can be detrimental to your productivity, and the more cumbersome it is to switch contexts, the greater the loss. With centralized version control we must download a fresh working copy from the central server. Distributed systems fare better, as we can clone the desired version locally.
But cloning still entails copying the whole working directory as well as the entire history up to the given point. Even though Git reduces the cost of this with file sharing and hard links, the project files themselves must be recreated in their entirety in the new working directory.
Solution: Git has a better tool for these situations that is much faster and more space-efficient than cloning: git branch.
With this magic word, the files in your directory suddenly shapeshift from one version to another. This transformation can do more than merely go back or forward in history. Your files can morph from the last release to the experimental version to the current development version to your friend’s version and so on.
Ever play one of those games where at the push of a button ("the boss key"), the screen would instantly display a spreadsheet or something? So if the boss walked in the office while you were playing the game you could quickly hide it away?
In some directory:
$ echo "I'm smarter than my boss" > myfile.txt $ git init $ git add . $ git commit -m "Initial commit"
We have created a Git repository that tracks one text file containing a certain message. Now type:
$ git checkout -b boss # nothing seems to change after this $ echo "My boss is smarter than me" > myfile.txt $ git commit -a -m "Another commit"
It looks like we’ve just overwritten our file and committed it. But it’s an illusion. Type:
$ git checkout master # switch to original version of the file
and hey presto! The text file is restored. And if the boss decides to snoop around this directory, type:
$ git checkout boss # switch to version suitable for boss' eyes
You can switch between the two versions of the file as much as you like, and commit to each independently.
Say you’re working on some feature, and for some reason, you need to go back to an old version and temporarily put in a few prints statements to see how something works. Then:
$ git commit -a $ git checkout SHA1_HASH
Now you can add ugly temporary code all over the place. You can even commit these changes. When you’re done,
$ git checkout master
to return to your original work. Observe that any uncommitted changes are carried over.
What if you wanted to save the temporary changes after all? Easy:
$ git checkout -b dirty
and commit before switching back to the master branch. Whenever you want to return to the dirty changes, simply type
$ git checkout dirty
We touched upon this command in an earlier chapter, when discussing loading old states. At last we can tell the whole story: the files change to the requested state, but we must leave the master branch. Any commits made from now on take your files down a different road, which can be named later.
In other words, after checking out an old state, Git automatically puts you in a new, unnamed branch, which can be named and saved with git checkout -b.
You’re in the middle of something when you are told to drop everything and fix a newly discovered bug:
$ git commit -a $ git checkout -b fixes SHA1_HASH
Then once you’ve fixed the bug:
$ git commit -a -m "Bug fixed" $ git push # to the central repository $ git checkout master
and resume work on your original task.
Often in hardware projects, the second step of a plan must wait for the first step to be completed before it can begin. A car undergoing repairs might sit idly in a garage until a particular part arrives from the factory. A prototype might wait for a chip to be fabricated before construction can continue.
Software projects can be similar. The second part of a new feature may have to wait until the first part has been released and tested. Some projects require your code to be reviewed before accepting it, so you might wait until the first part is approved before starting the second part.
In Git, thanks to painless branching and merging, we can
bend the rules and work on Part II before Part I is
officially ready. Suppose you have committed Part I and sent
it for review. Let’s say you’re in the master
branch. Then branch off:
$ git checkout -b part2
Next, work on Part II, committing your changes along the way. To err is human, and often you’ll want to go back and fix something in Part I. If you’re lucky, or very good, you can skip these lines.
$ git checkout master # Go back to Part I. $ edit files # Fix Part I. $ git checkout part2 # Go back to Part II. $ git merge master # Merge in those fixes.
Eventually, Part I is approved:
$ git checkout master # Go back to Part I. $ some_command # Some command you're supposed to run when the # current working directory is officially ready. $ git merge part2 # Merge in Part II. $ git branch -d part2
Now you’re in the master
branch again, with Part II in the working directory.
It’s easy to extend this trick for any number of parts. It’s also easy to branch off retroactively: suppose you belatedly realize you should have created a branch several commits ago. Then type:
$ git branch -m master part2 # Rename "master" branch to "part2". $ git checkout SHA1 -b master # The commit representing Part I.
The master
branch now
contains just Part I, and the part2
branch contains the rest.
Perhaps you like to work on all aspects of a project in the same branch. You want to keep works-in-progress to yourself and want others to see your commits only when they have been neatly organized. Start a couple of branches:
$ git checkout -b sanitized $ git checkout -b medley
Next, work on anything: fix bugs, add features, add temporary code, and so forth, committing often along the way. Then:
$ git checkout sanitized $ git cherry-pick SHA1_HASH
applies a given commit to the "sanitized" branch. With appropriate cherry-picks you can construct a branch that contains only permanent code, and has related commits grouped together.
List all branches by typing:
$ git branch
By default, you start in a branch named "master". Some advocate leaving the "master" branch untouched and creating new branches for your own edits.
The -d and -m options allow you to delete and move (rename) branches. See git help branch.
The "master" branch is a useful convention. Others may assume that your repository has a branch with this name, and that it contains the official version of your project. You can rename or obliterate the "master" branch, but you might as well respect this custom.
After a while you may realize you are creating short-lived branches frequently for similar reasons: every other branch merely serves to save the current state so you can briefly hop back to an older state to fix a high-priority bug or something.
It’s analogous to changing the TV channel temporarily to see what else is on. But instead of pushing a couple of buttons, you have to create, check out and delete temporary branches and commits. Luckily, Git has a shortcut that is as convenient as a TV remote control:
$ git stash
This saves the current state in a temporary location (a stash) and restores the previous state. Your working directory appears exactly as it was before you started editing, and you can fix bugs, pull in upstream changes, and so on. When you want to go back to the stashed state, type:
$ git stash apply # You may need to resolve some conflicts.
You can have multiple stashes, and manipulate them in various ways. See git help stash. As you may have guessed, Git maintains branches behind the scenes to perform this magic trick.
Applications such as Mozilla Firefox allow you to open multiple tabs and multiple windows. Switching tabs gives you different content in the same window. Git branching is like tabs for your working directory. Continuing this analogy, Git cloning is like opening a new window. Being able to do both improves the user experience.
On a higher level, several window managers support multiple desktops. Branching in Git is similar to switching to a different desktop, while cloning is similar to attaching another monitor to gain another desktop.
Yet another example is the screen utility. This gem lets you create, destroy and switch between multiple terminal sessions in the same terminal. Instead of opening new terminals (clone), you can use the same one if you run screen (branch). In fact, you can do a lot more with screen but that’s a topic for another text.
Cloning, branching, and merging are fast and local in Git, encouraging you to use the combination that best suits you. Git lets you work exactly how you want.