continue edit clone.txt
[gitmagic.git] / vi / branch.txt
blob1d4d4c8cfd928487af9284761eea671677191b6a
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 played 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 three versions and temporarily put in a few print statements to see how something works. Then:
49  $ git commit -a
50  $ git checkout HEAD~3
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 in commit `1b6d...`:
74  $ git commit -a
75  $ git checkout -b fixes 1b6d
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 You can even 'merge' in the bugfix you just made, either by typing:
87  $ git merge fixes
89 or:
91  $ git pull
93 since you have already pushed the bugfix to the main repository.
95 === Merging ===
97 With some version control systems, creating branches is easy but merging them
98 back together is tough. With Git, merging is so trivial that you might be
99 unaware of it happening.
101 We actually encountered merging long ago. The *pull* command in fact 'fetches'
102 commits and then merges them into your current branch. If you have no local
103 changes, then the merge is a 'fast forward', a degenerate case akin to fetching
104 the latest version in a centralized version control system. But if you do have
105 local changes, Git will automatically merge, and report any conflicts.
107 Ordinarily, a commit has exactly one 'parent commit', namely, the previous
108 commit. Merging branches together produces a commit with at least two parents.
109 This begs the question: what commit does `HEAD~10` really refer to? A commit
110 could have multiple parents, so which one do we follow?
112 It turns out this notation chooses the first parent every time. This is
113 desirable because the current branch becomes the first parent during a merge;
114 frequently you're only concerned with the changes you made in the current
115 branch, as opposed to changes merged in from other branches.
117 You can refer to a specific parent with a caret. For example, to show
118 the logs from the second parent:
120  $ git log HEAD^2
122 You may omit the number for the first parent. For example, to show the
123 differences with the first parent:
125  $ git diff HEAD^
127 You can combine this notation with other types. For example:
129  $ git checkout 1b6d^^2~10 -b ancient
131 starts a new branch ``ancient'' representing the state 10 commits back from the
132 second parent of the first parent of the commit starting with 1b6d.
134 === Uninterrupted Workflow ===
136 Often in hardware projects, the second step of a plan must await the completion of the first step. 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.
138 Software projects can be similar. The second part of a new feature may have to
139 wait until the first part has been released and tested. Some projects require
140 your code to be reviewed before accepting it, so you might wait until the first
141 part is approved before starting the second part.
143 Thanks to painless branching and merging, we can bend the rules and work on
144 Part II before Part I is officially ready. Suppose you have committed Part I
145 and sent it for review. Let's say you're in the `master` branch. Then branch
146 off:
148  $ git checkout -b part2
150 Next, work on Part II, committing your changes along the way. To err is human,
151 and often you'll want to go back and fix something in Part I.
152 If you're lucky, or very good, you can skip these lines.
154  $ git checkout master  # Go back to Part I.
155  $ fix_problem
156  $ git commit -a        # Commit the fixes.
157  $ git checkout part2   # Go back to Part II.
158  $ git merge master     # Merge in those fixes.
160 Eventually, Part I is approved:
162  $ git checkout master  # Go back to Part I.
163  $ submit files         # Release to the world!
164  $ git merge part2      # Merge in Part II.
165  $ git branch -d part2
167 Now you're in the `master` branch again, with Part II in the working directory.
169 It's easy to extend this trick for any number of parts. It's also easy to
170 branch off retroactively: suppose you belatedly realize you should have created
171 a branch 7 commits ago. Then type:
173  $ git branch -m master part2
174  $  # Rename "master" branch to "part2".
175  $ git checkout HEAD~7 -b master
177 The `master` branch now contains just Part I, and the `part2` branch contains
178 the rest.
180 === Reorganizing a Medley ===
182 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:
184   $ git checkout -b sanitized
185   $ git checkout -b medley
187 Next, work on anything: fix bugs, add features, add temporary code, and so forth, committing often along the way. Then:
189   $ git checkout sanitized
190   $ git cherry-pick medley^^
192 applies the grandparent of the head commit of the ``medley'' branch to the ``sanitized'' branch. With appropriate cherry-picks you can construct a branch that contains only permanent code, and has related commits grouped together.
194 === Managing Branches ===
196 List all branches by typing:
198  $ git branch
200 By default, you start in a branch named ``master''. Some advocate leaving the
201 ``master'' branch untouched and creating new branches for your own edits.
203 The *-d* and *-m* options allow you to delete and move (rename) branches.
204 See *git help branch*.
206 The ``master'' branch is a useful custom. Others may assume that your
207 repository has a branch with this name, and that it contains the official
208 version of your project. Although you can rename or obliterate the ``master''
209 branch, you might as well respect this convention.
211 === Temporary Branches ===
213 After a while you may realize you are creating short-lived branches
214 frequently for similar reasons: every other branch merely serves to
215 save the current state so you can briefly hop back to an older state to
216 fix a high-priority bug or something.
218 It's analogous to changing the TV channel temporarily to see what else is on.
219 But instead of pushing a couple of buttons, you have to create, check out,
220 merge, and delete temporary branches. Luckily, Git has a shortcut that is as
221 convenient as a TV remote control:
223  $ git stash
225 This saves the current state in a temporary location (a 'stash') and
226 restores the previous state. Your working directory appears exactly as it was
227 before you started editing, and you can fix bugs, pull in upstream changes, and
228 so on. When you want to go back to the stashed state, type:
230  $ git stash apply  # You may need to resolve some conflicts.
232 You can have multiple stashes, and manipulate them in various ways. See
233 *git help stash*. As you may have guessed, Git maintains branches behind the scenes to perform this magic trick.
235 === Work How You Want ===
237 You might wonder if branches are worth the bother. After all, clones are almost
238 as fast, and you can switch between them with *cd* instead of esoteric Git
239 commands.
241 Consider web browsers. Why support multiple tabs as well as multiple windows?
242 Because allowing both accommodates a wide variety of styles. Some users like to
243 keep only one browser window open, and use tabs for multiple webpages. Others
244 might insist on the other extreme: multiple windows with no tabs anywhere.
245 Others still prefer something in between.
247 Branching is like tabs for your working directory, and cloning is like opening
248 a new browser window. These operations are fast and local, so why not
249 experiment to find the combination that best suits you? Git lets you work
250 exactly how you want.