All examples in basic.txt now concrete.
[gitmagic.git] / en / branch.txt
blob41a6cf1e517386f861fabca87b14d925341a3297
1 == Branch Wizardry ==
3 Instant branching and merging are the most lethal of Git's killer features.
5 *Problem*: External factors inevitably necessitate context switching. A severe
6 bug manifests in the released version without warning. The deadline for a
7 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.
9 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.
11 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.
13 *Solution*: Git has a better tool for these situations that is much faster and more space-efficient than cloning: *git branch*.
15 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.
17 === The Boss Key ===
19 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?
21 In some directory:
23  $ echo "I'm smarter than my boss" > myfile.txt
24  $ git init
25  $ git add .
26  $ git commit -m "Initial commit"
28 We have created a Git repository that tracks one text file containing a certain message. Now type:
30  $ git checkout -b boss  # nothing seems to change after this
31  $ echo "My boss is smarter than me" > myfile.txt
32  $ git commit -a -m "Another commit"
34 It looks like we've just overwritten our file and committed it. But it's an illusion. Type:
36  $ git checkout master  # switch to original version of the file
38 and hey presto! The text file is restored. And if the boss decides to snoop around this directory, type:
40  $ git checkout boss  # switch to version suitable for boss' eyes
42 You can switch between the two versions of the file as much as you like, and commit to each independently.
44 === Dirty Work ===
46 [[branch]]
47 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:
49  $ git commit -a
50  $ git checkout SHA1_HASH
52 Now you can add ugly temporary code all over the place. You can even commit these changes. When you're done,
54  $ git checkout master
56 to return to your original work. Observe that any uncommitted changes are carried over.
58 What if you wanted to save the temporary changes after all? Easy:
60  $ git checkout -b dirty
62 and commit before switching back to the master branch. Whenever you want to return to the dirty changes, simply type
64  $ git checkout dirty
66 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.
68 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*.
70 === Quick Fixes ===
72 You're in the middle of something when you are told to drop everything and fix a newly discovered bug:
74  $ git commit -a
75  $ git checkout -b fixes SHA1_HASH
77 Then once you've fixed the bug:
79  $ git commit -a -m "Bug fixed"
80  $ git push  # to the central repository
81  $ git checkout master
83 and resume work on your original task.
85 === Uninterrupted Workflow ===
87 Often in hardware projects, the second step of a plan must wait for the first
88 step to be completed before it can begin. A car undergoing repairs might sit
89 idly in a garage until a particular part arrives from the factory. A prototype
90 might wait for a chip to be fabricated before construction can continue.
92 Software projects can be similar. The second part of a new feature may have to
93 wait until the first part has been released and tested. Some projects require
94 your code to be reviewed before accepting it, so you might wait until the first
95 part is approved before starting the second part.
97 In Git, thanks to painless branching and merging, we can bend the rules and
98 work on Part II before Part I is officially ready. Suppose you have committed
99 Part I and sent it for review. Let's say you're in the `master` branch. Then
100 branch off:
102  $ git checkout -b part2
104 Next, work on Part II, committing your changes along the way. To err is human,
105 and often you'll want to go back and fix something in Part I.
106 If you're lucky, or very good, you can skip these lines.
108  $ git checkout master  # Go back to Part I.
109  $ edit files           # Fix Part I.
110  $ git checkout part2   # Go back to Part II.
111  $ git merge master     # Merge in those fixes.
113 Eventually, Part I is approved:
115  $ git checkout master  # Go back to Part I.
116  $ some_command         # Some command you're supposed to run when the
117                         # current working directory is officially ready.
118  $ git merge part2      # Merge in Part II.
119  $ git branch -d part2
121 Now you're in the `master` branch again, with Part II in the working directory.
123 It's easy to extend this trick for any number of parts. It's also easy to
124 branch off retroactively: suppose you belatedly realize you should have created
125 a branch several commits ago. Then type:
127  $ git branch -m master part2   # Rename "master" branch to "part2".
128  $ git checkout SHA1 -b master  # The commit representing Part I.
130 The `master` branch now contains just Part I, and the `part2` branch contains
131 the rest.
133 === Reorganizing a Medley ===
135 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:
137   $ git checkout -b sanitized
138   $ git checkout -b medley
140 Next, work on anything: fix bugs, add features, add temporary code, and so forth, committing often along the way. Then:
142   $ git checkout sanitized
143   $ git cherry-pick SHA1_HASH
145 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.
147 === Managing Branches ===
149 List all branches by typing:
151  $ git branch
153 By default, you start in a branch named "master". Some advocate leaving the
154 "master" branch untouched and creating new branches for your own edits.
156 The *-d* and *-m* options allow you to delete and move (rename) branches.
157 See *git help branch*.
159 The "master" branch is a useful convention. Others may assume that your
160 repository has a branch with this name, and that it contains the official
161 version of your project. You can rename or obliterate the "master" branch, but
162 you might as well respect this custom.
164 === Temporary Branches ===
166 After a while you may realize you are creating short-lived branches
167 frequently for similar reasons: every other branch merely serves to
168 save the current state so you can briefly hop back to an older state to
169 fix a high-priority bug or something.
171 It's analogous to changing the TV channel temporarily to see what else is on.
172 But instead of pushing a couple of buttons, you have to create, check out and
173 delete temporary branches and commits. Luckily, Git has a shortcut that
174 is as convenient as a TV remote control:
176  $ git stash
178 This saves the current state in a temporary location (a 'stash') and
179 restores the previous state. Your working directory appears exactly as it was
180 before you started editing, and you can fix bugs, pull in upstream changes, and
181 so on. When you want to go back to the stashed state, type:
183  $ git stash apply  # You may need to resolve some conflicts.
185 You can have multiple stashes, and manipulate them in various ways. See
186 *git help stash*. As you may have guessed, Git maintains branches behind the scenes to perform this magic trick.
188 === Work How You Want ===
190 Applications such as http://www.mozilla.com/[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.
192 On a higher level, several window managers support multiple desktops. Branching
193 in Git is similar to switching to a different desktop, while cloning is similar
194 to attaching another monitor to gain another desktop.
196 Yet another example is the http://www.gnu.org/software/screen/[*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.
198 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.