Added italian version of branch.txt
[gitmagic.git] / en / branch.txt
blob84c27d0e0e0267c9994a6d46e23c7f1164dd6005
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 checkout master
82 and resume work on your original task. You can even 'merge' in the freshly
83 baked bugfix:
85  $ git merge fixes
87 === Merging ===
89 With some version control systems, creating branches is easy but merging them
90 back together is tough. With Git, merging is so trivial that you might be
91 unaware of it happening.
93 We actually encountered merging long ago. The *pull* command in fact 'fetches'
94 commits and then merges them into your current branch. If you have no local
95 changes, then the merge is a 'fast forward', a degenerate case akin to fetching
96 the latest version in a centralized version control system. But if you do have
97 local changes, Git will automatically merge, and report any conflicts.
99 Ordinarily, a commit has exactly one 'parent commit', namely, the previous
100 commit. Merging branches together produces a commit with at least two parents.
101 This begs the question: what commit does `HEAD~10` really refer to? A commit
102 could have multiple parents, so which one do we follow?
104 It turns out this notation chooses the first parent every time. This is
105 desirable because the current branch becomes the first parent during a merge;
106 frequently you're only concerned with the changes you made in the current
107 branch, as opposed to changes merged in from other branches.
109 You can refer to a specific parent with a caret. For example, to show
110 the logs from the second parent:
112  $ git log HEAD^2
114 You may omit the number for the first parent. For example, to show the
115 differences with the first parent:
117  $ git diff HEAD^
119 You can combine this notation with other types. For example:
121  $ git checkout 1b6d^^2~10 -b ancient
123 starts a new branch ``ancient'' representing the state 10 commits back from the
124 second parent of the first parent of the commit starting with 1b6d.
126 === Uninterrupted Workflow ===
128 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.
130 Software projects can be similar. The second part of a new feature may have to
131 wait until the first part has been released and tested. Some projects require
132 your code to be reviewed before accepting it, so you might wait until the first
133 part is approved before starting the second part.
135 Thanks to painless branching and merging, we can bend the rules and work on
136 Part II before Part I is officially ready. Suppose you have committed Part I
137 and sent it for review. Let's say you're in the `master` branch. Then branch
138 off:
140  $ git checkout -b part2
142 Next, work on Part II, committing your changes along the way. To err is human,
143 and often you'll want to go back and fix something in Part I.
144 If you're lucky, or very good, you can skip these lines.
146  $ git checkout master  # Go back to Part I.
147  $ fix_problem
148  $ git commit -a        # Commit the fixes.
149  $ git checkout part2   # Go back to Part II.
150  $ git merge master     # Merge in those fixes.
152 Eventually, Part I is approved:
154  $ git checkout master  # Go back to Part I.
155  $ submit files         # Release to the world!
156  $ git merge part2      # Merge in Part II.
157  $ git branch -d part2  # Delete "part2" branch.
159 Now you're in the `master` branch again, with Part II in the working directory.
161 It's easy to extend this trick for any number of parts. It's also easy to
162 branch off retroactively: suppose you belatedly realize you should have created
163 a branch 7 commits ago. Then type:
165  $ git branch -m master part2  # Rename "master" branch to "part2".
166  $ git branch master HEAD~7    # Create new "master", 7 commits upstream.
168 The `master` branch now contains just Part I, and the `part2` branch contains
169 the rest. We are in the latter branch; we created `master` without switching to
170 it, because we want to continue work on `part2`. This is unusual. Until now,
171 we've been switching to branches immediately after creation, as in:
173  $ git checkout HEAD~7 -b master  # Create a branch, and switch to it.
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 branch sanitized    # Create a branch for sanitized commits.
180   $ git checkout -b medley  # Create and switch to a branch to work in.
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 switch between them with *cd* 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 tabs anywhere.
240 Others still 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.