Merge branch 'typos' of git://github.com/sunny256/gitmagic
[gitmagic.git] / en / branch.txt
blob047eeb021be7f26b1775f7c10f08777ae11d98e4
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 many 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 Indeed, though we have just introduced *git merge*, we encountered merging long ago. The *pull* command in fact fetches commits and then merges them into your current branch. If you have no local changes, then the merge is a 'fast forward', a degenerate case akin to fetching the latest version in a centralized version control system. But if you do have local changes, Git will automatically merge, and report any conflicts.
103 Ordinarily, a commit has exactly one parent, namely, the previous commit.
104 Merging other branches creates a commit with at least two parents. This begs
105 the question: what commit does `HEAD~10` really refer to? A commit could have
106 multiple parents, so which one do we follow?
108 It turns out we follow the first parent at every step. This is usually desired,
109 because commits in the current branch always become first parents in a *git
110 merge*; frequently you're only concerned with the changes you made in the
111 current branch, as opposed to changes merged in from other branches.
113 You can refer to a specific parent with a caret. For example, to show
114 the logs from the second parent:
116  $ git log HEAD^2
118 If you want the first parent, you can leave out the number. For example, to
119 show the differences with the first parent:
121  $ git diff HEAD^
123 You can combine this notation with other types. For example:
125  $ git checkout 1bd6^^2~10 -b ancient
127 starts a new branch ``ancient'' representing the state 10 commits back from the
128 second parent of the first parent of the commit starting with 1bd6.
130 === Uninterrupted Workflow ===
132 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.
134 Software projects can be similar. The second part of a new feature may have to
135 wait until the first part has been released and tested. Some projects require
136 your code to be reviewed before accepting it, so you might wait until the first
137 part is approved before starting the second part.
139 Thanks to painless branching and merging, we can bend the rules and work on
140 Part II before Part I is officially ready. Suppose you have committed Part I
141 and sent it for review. Let's say you're in the `master` branch. Then branch
142 off:
144  $ git checkout -b part2
146 Next, work on Part II, committing your changes along the way. To err is human,
147 and often you'll want to go back and fix something in Part I.
148 If you're lucky, or very good, you can skip these lines.
150  $ git checkout master  # Go back to Part I.
151  $ edit files           # Fix Part I.
152  $ git checkout part2   # Go back to Part II.
153  $ git merge master     # Merge in those fixes.
155 Eventually, Part I is approved:
157  $ git checkout master  # Go back to Part I.
158  $ some_command         # Some command you're supposed to run when the
159                         # current working directory is officially ready.
160  $ git merge part2      # Merge in Part II.
161  $ git branch -d part2
163 Now you're in the `master` branch again, with Part II in the working directory.
165 It's easy to extend this trick for any number of parts. It's also easy to
166 branch off retroactively: suppose you belatedly realize you should have created
167 a branch 7 commits ago. Then type:
169  $ git branch -m master part2   # Rename "master" branch to "part2".
170  $ git checkout HEAD~7 -b master
172 The `master` branch now contains just Part I, and the `part2` branch contains
173 the rest.
175 === Reorganizing a Medley ===
177 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:
179   $ git checkout -b sanitized
180   $ git checkout -b medley
182 Next, work on anything: fix bugs, add features, add temporary code, and so forth, committing often along the way. Then:
184   $ git checkout sanitized
185   $ git cherry-pick medley^^
187 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.
189 === Managing Branches ===
191 List all branches by typing:
193  $ git branch
195 By default, you start in a branch named ``master''. Some advocate leaving the
196 ``master'' branch untouched and creating new branches for your own edits.
198 The *-d* and *-m* options allow you to delete and move (rename) branches.
199 See *git help branch*.
201 The ``master'' branch is a useful custom. Others may assume that your
202 repository has a branch with this name, and that it contains the official
203 version of your project. Although you can rename or obliterate the ``master''
204 branch, you might as well respect this convention.
206 === Temporary Branches ===
208 After a while you may realize you are creating short-lived branches
209 frequently for similar reasons: every other branch merely serves to
210 save the current state so you can briefly hop back to an older state to
211 fix a high-priority bug or something.
213 It's analogous to changing the TV channel temporarily to see what else is on.
214 But instead of pushing a couple of buttons, you have to create, check out,
215 merge, and delete temporary branches. Luckily, Git has a shortcut that is as
216 convenient as a TV remote control:
218  $ git stash
220 This saves the current state in a temporary location (a 'stash') and
221 restores the previous state. Your working directory appears exactly as it was
222 before you started editing, and you can fix bugs, pull in upstream changes, and
223 so on. When you want to go back to the stashed state, type:
225  $ git stash apply  # You may need to resolve some conflicts.
227 You can have multiple stashes, and manipulate them in various ways. See
228 *git help stash*. As you may have guessed, Git maintains branches behind the scenes to perform this magic trick.
230 === Work How You Want ===
232 You might wonder if branches are worth the bother. After all, clones are almost
233 as fast, and you can use *cd* to switch between them, instead of esoteric Git
234 commands.
236 Consider web browsers. Why support multiple tabs as well as multiple windows?
237 Because allowing both accommodates a wide variety of styles. Some users like to
238 keep only one browser window open, and use tabs for multiple webpages. Others
239 might insist on the other extreme: multiple windows with no extra tabs anywhere.
240 Yet others prefer something in between.
242 Branching is like tabs for your working directory, and cloning is like opening
243 a new browser window. These operations are fast and local, so why not
244 experiment to find the combination that best suits you? Git lets you work
245 exactly how you want.