Code

user-manual: minor editing for conciseness
[git.git] / Documentation / user-manual.txt
1 Git User's Manual (for version 1.5.1 or newer)
2 ______________________________________________
5 Git is a fast distributed revision control system.
7 This manual is designed to be readable by someone with basic unix
8 command-line skills, but no previous knowledge of git.
10 <<repositories-and-branches>> and <<exploring-git-history>> explain how
11 to fetch and study a project using git--read these chapters to learn how
12 to build and test a particular version of a software project, search for
13 regressions, and so on.
15 People needing to do actual development will also want to read
16 <<Developing-with-git>> and <<sharing-development>>.
18 Further chapters cover more specialized topics.
20 Comprehensive reference documentation is available through the man
21 pages.  For a command such as "git clone", just use
23 ------------------------------------------------
24 $ man git-clone
25 ------------------------------------------------
27 See also <<git-quick-start>> for a brief overview of git commands,
28 without any explanation.
30 Finally, see <<todo>> for ways that you can help make this manual more
31 complete.
34 [[repositories-and-branches]]
35 Repositories and Branches
36 =========================
38 [[how-to-get-a-git-repository]]
39 How to get a git repository
40 ---------------------------
42 It will be useful to have a git repository to experiment with as you
43 read this manual.
45 The best way to get one is by using the gitlink:git-clone[1] command to
46 download a copy of an existing repository.  If you don't already have a
47 project in mind, here are some interesting examples:
49 ------------------------------------------------
50         # git itself (approx. 10MB download):
51 $ git clone git://git.kernel.org/pub/scm/git/git.git
52         # the linux kernel (approx. 150MB download):
53 $ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git
54 ------------------------------------------------
56 The initial clone may be time-consuming for a large project, but you
57 will only need to clone once.
59 The clone command creates a new directory named after the project
60 ("git" or "linux-2.6" in the examples above).  After you cd into this
61 directory, you will see that it contains a copy of the project files,
62 together with a special top-level directory named ".git", which
63 contains all the information about the history of the project.
65 [[how-to-check-out]]
66 How to check out a different version of a project
67 -------------------------------------------------
69 Git is best thought of as a tool for storing the history of a
70 collection of files.  It stores the history as a compressed
71 collection of interrelated snapshots (versions) of the project's
72 contents.
74 A single git repository may contain multiple branches.  It keeps track
75 of them by keeping a list of <<def_head,heads>> which reference the
76 latest version on each branch; the gitlink:git-branch[1] command shows
77 you the list of branch heads:
79 ------------------------------------------------
80 $ git branch
81 * master
82 ------------------------------------------------
84 A freshly cloned repository contains a single branch head, by default
85 named "master", with the working directory initialized to the state of
86 the project referred to by that branch head.
88 Most projects also use <<def_tag,tags>>.  Tags, like heads, are
89 references into the project's history, and can be listed using the
90 gitlink:git-tag[1] command:
92 ------------------------------------------------
93 $ git tag -l
94 v2.6.11
95 v2.6.11-tree
96 v2.6.12
97 v2.6.12-rc2
98 v2.6.12-rc3
99 v2.6.12-rc4
100 v2.6.12-rc5
101 v2.6.12-rc6
102 v2.6.13
103 ...
104 ------------------------------------------------
106 Tags are expected to always point at the same version of a project,
107 while heads are expected to advance as development progresses.
109 Create a new branch head pointing to one of these versions and check it
110 out using gitlink:git-checkout[1]:
112 ------------------------------------------------
113 $ git checkout -b new v2.6.13
114 ------------------------------------------------
116 The working directory then reflects the contents that the project had
117 when it was tagged v2.6.13, and gitlink:git-branch[1] shows two
118 branches, with an asterisk marking the currently checked-out branch:
120 ------------------------------------------------
121 $ git branch
122   master
123 * new
124 ------------------------------------------------
126 If you decide that you'd rather see version 2.6.17, you can modify
127 the current branch to point at v2.6.17 instead, with
129 ------------------------------------------------
130 $ git reset --hard v2.6.17
131 ------------------------------------------------
133 Note that if the current branch head was your only reference to a
134 particular point in history, then resetting that branch may leave you
135 with no way to find the history it used to point to; so use this command
136 carefully.
138 [[understanding-commits]]
139 Understanding History: Commits
140 ------------------------------
142 Every change in the history of a project is represented by a commit.
143 The gitlink:git-show[1] command shows the most recent commit on the
144 current branch:
146 ------------------------------------------------
147 $ git show
148 commit 2b5f6dcce5bf94b9b119e9ed8d537098ec61c3d2
149 Author: Jamal Hadi Salim <hadi@cyberus.ca>
150 Date:   Sat Dec 2 22:22:25 2006 -0800
152     [XFRM]: Fix aevent structuring to be more complete.
153     
154     aevents can not uniquely identify an SA. We break the ABI with this
155     patch, but consensus is that since it is not yet utilized by any
156     (known) application then it is fine (better do it now than later).
157     
158     Signed-off-by: Jamal Hadi Salim <hadi@cyberus.ca>
159     Signed-off-by: David S. Miller <davem@davemloft.net>
161 diff --git a/Documentation/networking/xfrm_sync.txt b/Documentation/networking/xfrm_sync.txt
162 index 8be626f..d7aac9d 100644
163 --- a/Documentation/networking/xfrm_sync.txt
164 +++ b/Documentation/networking/xfrm_sync.txt
165 @@ -47,10 +47,13 @@ aevent_id structure looks like:
166  
167     struct xfrm_aevent_id {
168               struct xfrm_usersa_id           sa_id;
169 +             xfrm_address_t                  saddr;
170               __u32                           flags;
171 +             __u32                           reqid;
172     };
173 ...
174 ------------------------------------------------
176 As you can see, a commit shows who made the latest change, what they
177 did, and why.
179 Every commit has a 40-hexdigit id, sometimes called the "object name" or the
180 "SHA1 id", shown on the first line of the "git show" output.  You can usually
181 refer to a commit by a shorter name, such as a tag or a branch name, but this
182 longer name can also be useful.  Most importantly, it is a globally unique
183 name for this commit: so if you tell somebody else the object name (for
184 example in email), then you are guaranteed that name will refer to the same
185 commit in their repository that it does in yours (assuming their repository
186 has that commit at all).  Since the object name is computed as a hash over the
187 contents of the commit, you are guaranteed that the commit can never change
188 without its name also changing.
190 In fact, in <<git-internals>> we shall see that everything stored in git
191 history, including file data and directory contents, is stored in an object
192 with a name that is a hash of its contents.
194 [[understanding-reachability]]
195 Understanding history: commits, parents, and reachability
196 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
198 Every commit (except the very first commit in a project) also has a
199 parent commit which shows what happened before this commit.
200 Following the chain of parents will eventually take you back to the
201 beginning of the project.
203 However, the commits do not form a simple list; git allows lines of
204 development to diverge and then reconverge, and the point where two
205 lines of development reconverge is called a "merge".  The commit
206 representing a merge can therefore have more than one parent, with
207 each parent representing the most recent commit on one of the lines
208 of development leading to that point.
210 The best way to see how this works is using the gitlink:gitk[1]
211 command; running gitk now on a git repository and looking for merge
212 commits will help understand how the git organizes history.
214 In the following, we say that commit X is "reachable" from commit Y
215 if commit X is an ancestor of commit Y.  Equivalently, you could say
216 that Y is a descendent of X, or that there is a chain of parents
217 leading from commit Y to commit X.
219 [[history-diagrams]]
220 Understanding history: History diagrams
221 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
223 We will sometimes represent git history using diagrams like the one
224 below.  Commits are shown as "o", and the links between them with
225 lines drawn with - / and \.  Time goes left to right:
228 ................................................
229          o--o--o <-- Branch A
230         /
231  o--o--o <-- master
232         \
233          o--o--o <-- Branch B
234 ................................................
236 If we need to talk about a particular commit, the character "o" may
237 be replaced with another letter or number.
239 [[what-is-a-branch]]
240 Understanding history: What is a branch?
241 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
243 When we need to be precise, we will use the word "branch" to mean a line
244 of development, and "branch head" (or just "head") to mean a reference
245 to the most recent commit on a branch.  In the example above, the branch
246 head named "A" is a pointer to one particular commit, but we refer to
247 the line of three commits leading up to that point as all being part of
248 "branch A".
250 However, when no confusion will result, we often just use the term
251 "branch" both for branches and for branch heads.
253 [[manipulating-branches]]
254 Manipulating branches
255 ---------------------
257 Creating, deleting, and modifying branches is quick and easy; here's
258 a summary of the commands:
260 git branch::
261         list all branches
262 git branch <branch>::
263         create a new branch named <branch>, referencing the same
264         point in history as the current branch
265 git branch <branch> <start-point>::
266         create a new branch named <branch>, referencing
267         <start-point>, which may be specified any way you like,
268         including using a branch name or a tag name
269 git branch -d <branch>::
270         delete the branch <branch>; if the branch you are deleting
271         points to a commit which is not reachable from the current
272         branch, this command will fail with a warning.
273 git branch -D <branch>::
274         even if the branch points to a commit not reachable
275         from the current branch, you may know that that commit
276         is still reachable from some other branch or tag.  In that
277         case it is safe to use this command to force git to delete
278         the branch.
279 git checkout <branch>::
280         make the current branch <branch>, updating the working
281         directory to reflect the version referenced by <branch>
282 git checkout -b <new> <start-point>::
283         create a new branch <new> referencing <start-point>, and
284         check it out.
286 The special symbol "HEAD" can always be used to refer to the current
287 branch.  In fact, git uses a file named "HEAD" in the .git directory to
288 remember which branch is current:
290 ------------------------------------------------
291 $ cat .git/HEAD
292 ref: refs/heads/master
293 ------------------------------------------------
295 [[detached-head]]
296 Examining an old version without creating a new branch
297 ------------------------------------------------------
299 The git-checkout command normally expects a branch head, but will also
300 accept an arbitrary commit; for example, you can check out the commit
301 referenced by a tag:
303 ------------------------------------------------
304 $ git checkout v2.6.17
305 Note: moving to "v2.6.17" which isn't a local branch
306 If you want to create a new branch from this checkout, you may do so
307 (now or later) by using -b with the checkout command again. Example:
308   git checkout -b <new_branch_name>
309 HEAD is now at 427abfa... Linux v2.6.17
310 ------------------------------------------------
312 The HEAD then refers to the SHA1 of the commit instead of to a branch,
313 and git branch shows that you are no longer on a branch:
315 ------------------------------------------------
316 $ cat .git/HEAD
317 427abfa28afedffadfca9dd8b067eb6d36bac53f
318 $ git branch
319 * (no branch)
320   master
321 ------------------------------------------------
323 In this case we say that the HEAD is "detached".
325 This is an easy way to check out a particular version without having to
326 make up a name for the new branch.   You can still create a new branch
327 (or tag) for this version later if you decide to.
329 [[examining-remote-branches]]
330 Examining branches from a remote repository
331 -------------------------------------------
333 The "master" branch that was created at the time you cloned is a copy
334 of the HEAD in the repository that you cloned from.  That repository
335 may also have had other branches, though, and your local repository
336 keeps branches which track each of those remote branches, which you
337 can view using the "-r" option to gitlink:git-branch[1]:
339 ------------------------------------------------
340 $ git branch -r
341   origin/HEAD
342   origin/html
343   origin/maint
344   origin/man
345   origin/master
346   origin/next
347   origin/pu
348   origin/todo
349 ------------------------------------------------
351 You cannot check out these remote-tracking branches, but you can
352 examine them on a branch of your own, just as you would a tag:
354 ------------------------------------------------
355 $ git checkout -b my-todo-copy origin/todo
356 ------------------------------------------------
358 Note that the name "origin" is just the name that git uses by default
359 to refer to the repository that you cloned from.
361 [[how-git-stores-references]]
362 Naming branches, tags, and other references
363 -------------------------------------------
365 Branches, remote-tracking branches, and tags are all references to
366 commits.  All references are named with a slash-separated path name
367 starting with "refs"; the names we've been using so far are actually
368 shorthand:
370         - The branch "test" is short for "refs/heads/test".
371         - The tag "v2.6.18" is short for "refs/tags/v2.6.18".
372         - "origin/master" is short for "refs/remotes/origin/master".
374 The full name is occasionally useful if, for example, there ever
375 exists a tag and a branch with the same name.
377 As another useful shortcut, the "HEAD" of a repository can be referred
378 to just using the name of that repository.  So, for example, "origin"
379 is usually a shortcut for the HEAD branch in the repository "origin".
381 For the complete list of paths which git checks for references, and
382 the order it uses to decide which to choose when there are multiple
383 references with the same shorthand name, see the "SPECIFYING
384 REVISIONS" section of gitlink:git-rev-parse[1].
386 [[Updating-a-repository-with-git-fetch]]
387 Updating a repository with git fetch
388 ------------------------------------
390 Eventually the developer cloned from will do additional work in her
391 repository, creating new commits and advancing the branches to point
392 at the new commits.
394 The command "git fetch", with no arguments, will update all of the
395 remote-tracking branches to the latest version found in her
396 repository.  It will not touch any of your own branches--not even the
397 "master" branch that was created for you on clone.
399 [[fetching-branches]]
400 Fetching branches from other repositories
401 -----------------------------------------
403 You can also track branches from repositories other than the one you
404 cloned from, using gitlink:git-remote[1]:
406 -------------------------------------------------
407 $ git remote add linux-nfs git://linux-nfs.org/pub/nfs-2.6.git
408 $ git fetch linux-nfs
409 * refs/remotes/linux-nfs/master: storing branch 'master' ...
410   commit: bf81b46
411 -------------------------------------------------
413 New remote-tracking branches will be stored under the shorthand name
414 that you gave "git remote add", in this case linux-nfs:
416 -------------------------------------------------
417 $ git branch -r
418 linux-nfs/master
419 origin/master
420 -------------------------------------------------
422 If you run "git fetch <remote>" later, the tracking branches for the
423 named <remote> will be updated.
425 If you examine the file .git/config, you will see that git has added
426 a new stanza:
428 -------------------------------------------------
429 $ cat .git/config
430 ...
431 [remote "linux-nfs"]
432         url = git://linux-nfs.org/pub/nfs-2.6.git
433         fetch = +refs/heads/*:refs/remotes/linux-nfs/*
434 ...
435 -------------------------------------------------
437 This is what causes git to track the remote's branches; you may modify
438 or delete these configuration options by editing .git/config with a
439 text editor.  (See the "CONFIGURATION FILE" section of
440 gitlink:git-config[1] for details.)
442 [[exploring-git-history]]
443 Exploring git history
444 =====================
446 Git is best thought of as a tool for storing the history of a
447 collection of files.  It does this by storing compressed snapshots of
448 the contents of a file heirarchy, together with "commits" which show
449 the relationships between these snapshots.
451 Git provides extremely flexible and fast tools for exploring the
452 history of a project.
454 We start with one specialized tool that is useful for finding the
455 commit that introduced a bug into a project.
457 [[using-bisect]]
458 How to use bisect to find a regression
459 --------------------------------------
461 Suppose version 2.6.18 of your project worked, but the version at
462 "master" crashes.  Sometimes the best way to find the cause of such a
463 regression is to perform a brute-force search through the project's
464 history to find the particular commit that caused the problem.  The
465 gitlink:git-bisect[1] command can help you do this:
467 -------------------------------------------------
468 $ git bisect start
469 $ git bisect good v2.6.18
470 $ git bisect bad master
471 Bisecting: 3537 revisions left to test after this
472 [65934a9a028b88e83e2b0f8b36618fe503349f8e] BLOCK: Make USB storage depend on SCSI rather than selecting it [try #6]
473 -------------------------------------------------
475 If you run "git branch" at this point, you'll see that git has
476 temporarily moved you to a new branch named "bisect".  This branch
477 points to a commit (with commit id 65934...) that is reachable from
478 v2.6.19 but not from v2.6.18.  Compile and test it, and see whether
479 it crashes.  Assume it does crash.  Then:
481 -------------------------------------------------
482 $ git bisect bad
483 Bisecting: 1769 revisions left to test after this
484 [7eff82c8b1511017ae605f0c99ac275a7e21b867] i2c-core: Drop useless bitmaskings
485 -------------------------------------------------
487 checks out an older version.  Continue like this, telling git at each
488 stage whether the version it gives you is good or bad, and notice
489 that the number of revisions left to test is cut approximately in
490 half each time.
492 After about 13 tests (in this case), it will output the commit id of
493 the guilty commit.  You can then examine the commit with
494 gitlink:git-show[1], find out who wrote it, and mail them your bug
495 report with the commit id.  Finally, run
497 -------------------------------------------------
498 $ git bisect reset
499 -------------------------------------------------
501 to return you to the branch you were on before and delete the
502 temporary "bisect" branch.
504 Note that the version which git-bisect checks out for you at each
505 point is just a suggestion, and you're free to try a different
506 version if you think it would be a good idea.  For example,
507 occasionally you may land on a commit that broke something unrelated;
508 run
510 -------------------------------------------------
511 $ git bisect visualize
512 -------------------------------------------------
514 which will run gitk and label the commit it chose with a marker that
515 says "bisect".  Chose a safe-looking commit nearby, note its commit
516 id, and check it out with:
518 -------------------------------------------------
519 $ git reset --hard fb47ddb2db...
520 -------------------------------------------------
522 then test, run "bisect good" or "bisect bad" as appropriate, and
523 continue.
525 [[naming-commits]]
526 Naming commits
527 --------------
529 We have seen several ways of naming commits already:
531         - 40-hexdigit object name
532         - branch name: refers to the commit at the head of the given
533           branch
534         - tag name: refers to the commit pointed to by the given tag
535           (we've seen branches and tags are special cases of
536           <<how-git-stores-references,references>>).
537         - HEAD: refers to the head of the current branch
539 There are many more; see the "SPECIFYING REVISIONS" section of the
540 gitlink:git-rev-parse[1] man page for the complete list of ways to
541 name revisions.  Some examples:
543 -------------------------------------------------
544 $ git show fb47ddb2 # the first few characters of the object name
545                     # are usually enough to specify it uniquely
546 $ git show HEAD^    # the parent of the HEAD commit
547 $ git show HEAD^^   # the grandparent
548 $ git show HEAD~4   # the great-great-grandparent
549 -------------------------------------------------
551 Recall that merge commits may have more than one parent; by default,
552 ^ and ~ follow the first parent listed in the commit, but you can
553 also choose:
555 -------------------------------------------------
556 $ git show HEAD^1   # show the first parent of HEAD
557 $ git show HEAD^2   # show the second parent of HEAD
558 -------------------------------------------------
560 In addition to HEAD, there are several other special names for
561 commits:
563 Merges (to be discussed later), as well as operations such as
564 git-reset, which change the currently checked-out commit, generally
565 set ORIG_HEAD to the value HEAD had before the current operation.
567 The git-fetch operation always stores the head of the last fetched
568 branch in FETCH_HEAD.  For example, if you run git fetch without
569 specifying a local branch as the target of the operation
571 -------------------------------------------------
572 $ git fetch git://example.com/proj.git theirbranch
573 -------------------------------------------------
575 the fetched commits will still be available from FETCH_HEAD.
577 When we discuss merges we'll also see the special name MERGE_HEAD,
578 which refers to the other branch that we're merging in to the current
579 branch.
581 The gitlink:git-rev-parse[1] command is a low-level command that is
582 occasionally useful for translating some name for a commit to the object
583 name for that commit:
585 -------------------------------------------------
586 $ git rev-parse origin
587 e05db0fd4f31dde7005f075a84f96b360d05984b
588 -------------------------------------------------
590 [[creating-tags]]
591 Creating tags
592 -------------
594 We can also create a tag to refer to a particular commit; after
595 running
597 -------------------------------------------------
598 $ git tag stable-1 1b2e1d63ff
599 -------------------------------------------------
601 You can use stable-1 to refer to the commit 1b2e1d63ff.
603 This creates a "lightweight" tag.  If you would also like to include a
604 comment with the tag, and possibly sign it cryptographically, then you
605 should create a tag object instead; see the gitlink:git-tag[1] man page
606 for details.
608 [[browsing-revisions]]
609 Browsing revisions
610 ------------------
612 The gitlink:git-log[1] command can show lists of commits.  On its
613 own, it shows all commits reachable from the parent commit; but you
614 can also make more specific requests:
616 -------------------------------------------------
617 $ git log v2.5..        # commits since (not reachable from) v2.5
618 $ git log test..master  # commits reachable from master but not test
619 $ git log master..test  # ...reachable from test but not master
620 $ git log master...test # ...reachable from either test or master,
621                         #    but not both
622 $ git log --since="2 weeks ago" # commits from the last 2 weeks
623 $ git log Makefile      # commits which modify Makefile
624 $ git log fs/           # ... which modify any file under fs/
625 $ git log -S'foo()'     # commits which add or remove any file data
626                         # matching the string 'foo()'
627 -------------------------------------------------
629 And of course you can combine all of these; the following finds
630 commits since v2.5 which touch the Makefile or any file under fs:
632 -------------------------------------------------
633 $ git log v2.5.. Makefile fs/
634 -------------------------------------------------
636 You can also ask git log to show patches:
638 -------------------------------------------------
639 $ git log -p
640 -------------------------------------------------
642 See the "--pretty" option in the gitlink:git-log[1] man page for more
643 display options.
645 Note that git log starts with the most recent commit and works
646 backwards through the parents; however, since git history can contain
647 multiple independent lines of development, the particular order that
648 commits are listed in may be somewhat arbitrary.
650 [[generating-diffs]]
651 Generating diffs
652 ----------------
654 You can generate diffs between any two versions using
655 gitlink:git-diff[1]:
657 -------------------------------------------------
658 $ git diff master..test
659 -------------------------------------------------
661 Sometimes what you want instead is a set of patches:
663 -------------------------------------------------
664 $ git format-patch master..test
665 -------------------------------------------------
667 will generate a file with a patch for each commit reachable from test
668 but not from master.  Note that if master also has commits which are
669 not reachable from test, then the combined result of these patches
670 will not be the same as the diff produced by the git-diff example.
672 [[viewing-old-file-versions]]
673 Viewing old file versions
674 -------------------------
676 You can always view an old version of a file by just checking out the
677 correct revision first.  But sometimes it is more convenient to be
678 able to view an old version of a single file without checking
679 anything out; this command does that:
681 -------------------------------------------------
682 $ git show v2.5:fs/locks.c
683 -------------------------------------------------
685 Before the colon may be anything that names a commit, and after it
686 may be any path to a file tracked by git.
688 [[history-examples]]
689 Examples
690 --------
692 [[counting-commits-on-a-branch]]
693 Counting the number of commits on a branch
694 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
696 Suppose you want to know how many commits you've made on "mybranch"
697 since it diverged from "origin":
699 -------------------------------------------------
700 $ git log --pretty=oneline origin..mybranch | wc -l
701 -------------------------------------------------
703 Alternatively, you may often see this sort of thing done with the
704 lower-level command gitlink:git-rev-list[1], which just lists the SHA1's
705 of all the given commits:
707 -------------------------------------------------
708 $ git rev-list origin..mybranch | wc -l
709 -------------------------------------------------
711 [[checking-for-equal-branches]]
712 Check whether two branches point at the same history
713 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
715 Suppose you want to check whether two branches point at the same point
716 in history.
718 -------------------------------------------------
719 $ git diff origin..master
720 -------------------------------------------------
722 will tell you whether the contents of the project are the same at the
723 two branches; in theory, however, it's possible that the same project
724 contents could have been arrived at by two different historical
725 routes.  You could compare the object names:
727 -------------------------------------------------
728 $ git rev-list origin
729 e05db0fd4f31dde7005f075a84f96b360d05984b
730 $ git rev-list master
731 e05db0fd4f31dde7005f075a84f96b360d05984b
732 -------------------------------------------------
734 Or you could recall that the ... operator selects all commits
735 contained reachable from either one reference or the other but not
736 both: so
738 -------------------------------------------------
739 $ git log origin...master
740 -------------------------------------------------
742 will return no commits when the two branches are equal.
744 [[finding-tagged-descendants]]
745 Find first tagged version including a given fix
746 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
748 Suppose you know that the commit e05db0fd fixed a certain problem.
749 You'd like to find the earliest tagged release that contains that
750 fix.
752 Of course, there may be more than one answer--if the history branched
753 after commit e05db0fd, then there could be multiple "earliest" tagged
754 releases.
756 You could just visually inspect the commits since e05db0fd:
758 -------------------------------------------------
759 $ gitk e05db0fd..
760 -------------------------------------------------
762 Or you can use gitlink:git-name-rev[1], which will give the commit a
763 name based on any tag it finds pointing to one of the commit's
764 descendants:
766 -------------------------------------------------
767 $ git name-rev --tags e05db0fd
768 e05db0fd tags/v1.5.0-rc1^0~23
769 -------------------------------------------------
771 The gitlink:git-describe[1] command does the opposite, naming the
772 revision using a tag on which the given commit is based:
774 -------------------------------------------------
775 $ git describe e05db0fd
776 v1.5.0-rc0-260-ge05db0f
777 -------------------------------------------------
779 but that may sometimes help you guess which tags might come after the
780 given commit.
782 If you just want to verify whether a given tagged version contains a
783 given commit, you could use gitlink:git-merge-base[1]:
785 -------------------------------------------------
786 $ git merge-base e05db0fd v1.5.0-rc1
787 e05db0fd4f31dde7005f075a84f96b360d05984b
788 -------------------------------------------------
790 The merge-base command finds a common ancestor of the given commits,
791 and always returns one or the other in the case where one is a
792 descendant of the other; so the above output shows that e05db0fd
793 actually is an ancestor of v1.5.0-rc1.
795 Alternatively, note that
797 -------------------------------------------------
798 $ git log v1.5.0-rc1..e05db0fd
799 -------------------------------------------------
801 will produce empty output if and only if v1.5.0-rc1 includes e05db0fd,
802 because it outputs only commits that are not reachable from v1.5.0-rc1.
804 As yet another alternative, the gitlink:git-show-branch[1] command lists
805 the commits reachable from its arguments with a display on the left-hand
806 side that indicates which arguments that commit is reachable from.  So,
807 you can run something like
809 -------------------------------------------------
810 $ git show-branch e05db0fd v1.5.0-rc0 v1.5.0-rc1 v1.5.0-rc2
811 ! [e05db0fd] Fix warnings in sha1_file.c - use C99 printf format if
812 available
813  ! [v1.5.0-rc0] GIT v1.5.0 preview
814   ! [v1.5.0-rc1] GIT v1.5.0-rc1
815    ! [v1.5.0-rc2] GIT v1.5.0-rc2
816 ...
817 -------------------------------------------------
819 then search for a line that looks like
821 -------------------------------------------------
822 + ++ [e05db0fd] Fix warnings in sha1_file.c - use C99 printf format if
823 available
824 -------------------------------------------------
826 Which shows that e05db0fd is reachable from itself, from v1.5.0-rc1, and
827 from v1.5.0-rc2, but not from v1.5.0-rc0.
829 [[showing-commits-unique-to-a-branch]]
830 Showing commits unique to a given branch
831 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
833 Suppose you would like to see all the commits reachable from the branch
834 head named "master" but not from any other head in your repository.
836 We can list all the heads in this repository with
837 gitlink:git-show-ref[1]:
839 -------------------------------------------------
840 $ git show-ref --heads
841 bf62196b5e363d73353a9dcf094c59595f3153b7 refs/heads/core-tutorial
842 db768d5504c1bb46f63ee9d6e1772bd047e05bf9 refs/heads/maint
843 a07157ac624b2524a059a3414e99f6f44bebc1e7 refs/heads/master
844 24dbc180ea14dc1aebe09f14c8ecf32010690627 refs/heads/tutorial-2
845 1e87486ae06626c2f31eaa63d26fc0fd646c8af2 refs/heads/tutorial-fixes
846 -------------------------------------------------
848 We can get just the branch-head names, and remove "master", with
849 the help of the standard utilities cut and grep:
851 -------------------------------------------------
852 $ git show-ref --heads | cut -d' ' -f2 | grep -v '^refs/heads/master'
853 refs/heads/core-tutorial
854 refs/heads/maint
855 refs/heads/tutorial-2
856 refs/heads/tutorial-fixes
857 -------------------------------------------------
859 And then we can ask to see all the commits reachable from master
860 but not from these other heads:
862 -------------------------------------------------
863 $ gitk master --not $( git show-ref --heads | cut -d' ' -f2 |
864                                 grep -v '^refs/heads/master' )
865 -------------------------------------------------
867 Obviously, endless variations are possible; for example, to see all
868 commits reachable from some head but not from any tag in the repository:
870 -------------------------------------------------
871 $ gitk $( git show-ref --heads ) --not  $( git show-ref --tags )
872 -------------------------------------------------
874 (See gitlink:git-rev-parse[1] for explanations of commit-selecting
875 syntax such as `--not`.)
877 [[making-a-release]]
878 Creating a changelog and tarball for a software release
879 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
881 The gitlink:git-archive[1] command can create a tar or zip archive from
882 any version of a project; for example:
884 -------------------------------------------------
885 $ git archive --format=tar --prefix=project/ HEAD | gzip >latest.tar.gz
886 -------------------------------------------------
888 will use HEAD to produce a tar archive in which each filename is
889 preceded by "project/".
891 If you're releasing a new version of a software project, you may want
892 to simultaneously make a changelog to include in the release
893 announcement.
895 Linus Torvalds, for example, makes new kernel releases by tagging them,
896 then running:
898 -------------------------------------------------
899 $ release-script 2.6.12 2.6.13-rc6 2.6.13-rc7
900 -------------------------------------------------
902 where release-script is a shell script that looks like:
904 -------------------------------------------------
905 #!/bin/sh
906 stable="$1"
907 last="$2"
908 new="$3"
909 echo "# git tag v$new"
910 echo "git archive --prefix=linux-$new/ v$new | gzip -9 > ../linux-$new.tar.gz"
911 echo "git diff v$stable v$new | gzip -9 > ../patch-$new.gz"
912 echo "git log --no-merges v$new ^v$last > ../ChangeLog-$new"
913 echo "git shortlog --no-merges v$new ^v$last > ../ShortLog"
914 echo "git diff --stat --summary -M v$last v$new > ../diffstat-$new"
915 -------------------------------------------------
917 and then he just cut-and-pastes the output commands after verifying that
918 they look OK.
920 [[Finding-comments-with-given-content]]
921 Finding commits referencing a file with given content
922 -----------------------------------------------------
924 Somebody hands you a copy of a file, and asks which commits modified a
925 file such that it contained the given content either before or after the
926 commit.  You can find out with this:
928 -------------------------------------------------
929 $  git log --raw -r --abbrev=40 --pretty=oneline -- filename |
930         grep -B 1 `git hash-object filename`
931 -------------------------------------------------
933 Figuring out why this works is left as an exercise to the (advanced)
934 student.  The gitlink:git-log[1], gitlink:git-diff-tree[1], and
935 gitlink:git-hash-object[1] man pages may prove helpful.
937 [[Developing-with-git]]
938 Developing with git
939 ===================
941 [[telling-git-your-name]]
942 Telling git your name
943 ---------------------
945 Before creating any commits, you should introduce yourself to git.  The
946 easiest way to do so is to make sure the following lines appear in a
947 file named .gitconfig in your home directory:
949 ------------------------------------------------
950 [user]
951         name = Your Name Comes Here
952         email = you@yourdomain.example.com
953 ------------------------------------------------
955 (See the "CONFIGURATION FILE" section of gitlink:git-config[1] for
956 details on the configuration file.)
959 [[creating-a-new-repository]]
960 Creating a new repository
961 -------------------------
963 Creating a new repository from scratch is very easy:
965 -------------------------------------------------
966 $ mkdir project
967 $ cd project
968 $ git init
969 -------------------------------------------------
971 If you have some initial content (say, a tarball):
973 -------------------------------------------------
974 $ tar -xzvf project.tar.gz
975 $ cd project
976 $ git init
977 $ git add . # include everything below ./ in the first commit:
978 $ git commit
979 -------------------------------------------------
981 [[how-to-make-a-commit]]
982 How to make a commit
983 --------------------
985 Creating a new commit takes three steps:
987         1. Making some changes to the working directory using your
988            favorite editor.
989         2. Telling git about your changes.
990         3. Creating the commit using the content you told git about
991            in step 2.
993 In practice, you can interleave and repeat steps 1 and 2 as many
994 times as you want: in order to keep track of what you want committed
995 at step 3, git maintains a snapshot of the tree's contents in a
996 special staging area called "the index."
998 At the beginning, the content of the index will be identical to
999 that of the HEAD.  The command "git diff --cached", which shows
1000 the difference between the HEAD and the index, should therefore
1001 produce no output at that point.
1003 Modifying the index is easy:
1005 To update the index with the new contents of a modified file, use
1007 -------------------------------------------------
1008 $ git add path/to/file
1009 -------------------------------------------------
1011 To add the contents of a new file to the index, use
1013 -------------------------------------------------
1014 $ git add path/to/file
1015 -------------------------------------------------
1017 To remove a file from the index and from the working tree,
1019 -------------------------------------------------
1020 $ git rm path/to/file
1021 -------------------------------------------------
1023 After each step you can verify that
1025 -------------------------------------------------
1026 $ git diff --cached
1027 -------------------------------------------------
1029 always shows the difference between the HEAD and the index file--this
1030 is what you'd commit if you created the commit now--and that
1032 -------------------------------------------------
1033 $ git diff
1034 -------------------------------------------------
1036 shows the difference between the working tree and the index file.
1038 Note that "git add" always adds just the current contents of a file
1039 to the index; further changes to the same file will be ignored unless
1040 you run git-add on the file again.
1042 When you're ready, just run
1044 -------------------------------------------------
1045 $ git commit
1046 -------------------------------------------------
1048 and git will prompt you for a commit message and then create the new
1049 commit.  Check to make sure it looks like what you expected with
1051 -------------------------------------------------
1052 $ git show
1053 -------------------------------------------------
1055 As a special shortcut,
1056                 
1057 -------------------------------------------------
1058 $ git commit -a
1059 -------------------------------------------------
1061 will update the index with any files that you've modified or removed
1062 and create a commit, all in one step.
1064 A number of commands are useful for keeping track of what you're
1065 about to commit:
1067 -------------------------------------------------
1068 $ git diff --cached # difference between HEAD and the index; what
1069                     # would be commited if you ran "commit" now.
1070 $ git diff          # difference between the index file and your
1071                     # working directory; changes that would not
1072                     # be included if you ran "commit" now.
1073 $ git diff HEAD     # difference between HEAD and working tree; what
1074                     # would be committed if you ran "commit -a" now.
1075 $ git status        # a brief per-file summary of the above.
1076 -------------------------------------------------
1078 [[creating-good-commit-messages]]
1079 Creating good commit messages
1080 -----------------------------
1082 Though not required, it's a good idea to begin the commit message
1083 with a single short (less than 50 character) line summarizing the
1084 change, followed by a blank line and then a more thorough
1085 description.  Tools that turn commits into email, for example, use
1086 the first line on the Subject line and the rest of the commit in the
1087 body.
1089 [[ignoring-files]]
1090 Ignoring files
1091 --------------
1093 A project will often generate files that you do 'not' want to track with git.
1094 This typically includes files generated by a build process or temporary
1095 backup files made by your editor. Of course, 'not' tracking files with git
1096 is just a matter of 'not' calling "`git add`" on them. But it quickly becomes
1097 annoying to have these untracked files lying around; e.g. they make
1098 "`git add .`" and "`git commit -a`" practically useless, and they keep
1099 showing up in the output of "`git status`".
1101 You can tell git to ignore certain files by creating a file called .gitignore
1102 in the top level of your working directory, with contents such as:
1104 -------------------------------------------------
1105 # Lines starting with '#' are considered comments.
1106 # Ignore any file named foo.txt.
1107 foo.txt
1108 # Ignore (generated) html files,
1109 *.html
1110 # except foo.html which is maintained by hand.
1111 !foo.html
1112 # Ignore objects and archives.
1113 *.[oa]
1114 -------------------------------------------------
1116 See gitlink:gitignore[5] for a detailed explanation of the syntax.  You can
1117 also place .gitignore files in other directories in your working tree, and they
1118 will apply to those directories and their subdirectories.  The `.gitignore`
1119 files can be added to your repository like any other files (just run `git add
1120 .gitignore` and `git commit`, as usual), which is convenient when the exclude
1121 patterns (such as patterns matching build output files) would also make sense
1122 for other users who clone your repository.
1124 If you wish the exclude patterns to affect only certain repositories
1125 (instead of every repository for a given project), you may instead put
1126 them in a file in your repository named .git/info/exclude, or in any file
1127 specified by the `core.excludesfile` configuration variable.  Some git
1128 commands can also take exclude patterns directly on the command line.
1129 See gitlink:gitignore[5] for the details.
1131 [[how-to-merge]]
1132 How to merge
1133 ------------
1135 You can rejoin two diverging branches of development using
1136 gitlink:git-merge[1]:
1138 -------------------------------------------------
1139 $ git merge branchname
1140 -------------------------------------------------
1142 merges the development in the branch "branchname" into the current
1143 branch.  If there are conflicts--for example, if the same file is
1144 modified in two different ways in the remote branch and the local
1145 branch--then you are warned; the output may look something like this:
1147 -------------------------------------------------
1148 $ git merge next
1149  100% (4/4) done
1150 Auto-merged file.txt
1151 CONFLICT (content): Merge conflict in file.txt
1152 Automatic merge failed; fix conflicts and then commit the result.
1153 -------------------------------------------------
1155 Conflict markers are left in the problematic files, and after
1156 you resolve the conflicts manually, you can update the index
1157 with the contents and run git commit, as you normally would when
1158 creating a new file.
1160 If you examine the resulting commit using gitk, you will see that it
1161 has two parents, one pointing to the top of the current branch, and
1162 one to the top of the other branch.
1164 [[resolving-a-merge]]
1165 Resolving a merge
1166 -----------------
1168 When a merge isn't resolved automatically, git leaves the index and
1169 the working tree in a special state that gives you all the
1170 information you need to help resolve the merge.
1172 Files with conflicts are marked specially in the index, so until you
1173 resolve the problem and update the index, gitlink:git-commit[1] will
1174 fail:
1176 -------------------------------------------------
1177 $ git commit
1178 file.txt: needs merge
1179 -------------------------------------------------
1181 Also, gitlink:git-status[1] will list those files as "unmerged", and the
1182 files with conflicts will have conflict markers added, like this:
1184 -------------------------------------------------
1185 <<<<<<< HEAD:file.txt
1186 Hello world
1187 =======
1188 Goodbye
1189 >>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
1190 -------------------------------------------------
1192 All you need to do is edit the files to resolve the conflicts, and then
1194 -------------------------------------------------
1195 $ git add file.txt
1196 $ git commit
1197 -------------------------------------------------
1199 Note that the commit message will already be filled in for you with
1200 some information about the merge.  Normally you can just use this
1201 default message unchanged, but you may add additional commentary of
1202 your own if desired.
1204 The above is all you need to know to resolve a simple merge.  But git
1205 also provides more information to help resolve conflicts:
1207 [[conflict-resolution]]
1208 Getting conflict-resolution help during a merge
1209 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1211 All of the changes that git was able to merge automatically are
1212 already added to the index file, so gitlink:git-diff[1] shows only
1213 the conflicts.  It uses an unusual syntax:
1215 -------------------------------------------------
1216 $ git diff
1217 diff --cc file.txt
1218 index 802992c,2b60207..0000000
1219 --- a/file.txt
1220 +++ b/file.txt
1221 @@@ -1,1 -1,1 +1,5 @@@
1222 ++<<<<<<< HEAD:file.txt
1223  +Hello world
1224 ++=======
1225 + Goodbye
1226 ++>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
1227 -------------------------------------------------
1229 Recall that the commit which will be commited after we resolve this
1230 conflict will have two parents instead of the usual one: one parent
1231 will be HEAD, the tip of the current branch; the other will be the
1232 tip of the other branch, which is stored temporarily in MERGE_HEAD.
1234 During the merge, the index holds three versions of each file.  Each of
1235 these three "file stages" represents a different version of the file:
1237 -------------------------------------------------
1238 $ git show :1:file.txt  # the file in a common ancestor of both branches
1239 $ git show :2:file.txt  # the version from HEAD, but including any
1240                         # nonconflicting changes from MERGE_HEAD
1241 $ git show :3:file.txt  # the version from MERGE_HEAD, but including any
1242                         # nonconflicting changes from HEAD.
1243 -------------------------------------------------
1245 Since the stage 2 and stage 3 versions have already been updated with
1246 nonconflicting changes, the only remaining differences between them are
1247 the important ones; thus gitlink:git-diff[1] can use the information in
1248 the index to show only those conflicts.
1250 The diff above shows the differences between the working-tree version of
1251 file.txt and the stage 2 and stage 3 versions.  So instead of preceding
1252 each line by a single "+" or "-", it now uses two columns: the first
1253 column is used for differences between the first parent and the working
1254 directory copy, and the second for differences between the second parent
1255 and the working directory copy.  (See the "COMBINED DIFF FORMAT" section
1256 of gitlink:git-diff-files[1] for a details of the format.)
1258 After resolving the conflict in the obvious way (but before updating the
1259 index), the diff will look like:
1261 -------------------------------------------------
1262 $ git diff
1263 diff --cc file.txt
1264 index 802992c,2b60207..0000000
1265 --- a/file.txt
1266 +++ b/file.txt
1267 @@@ -1,1 -1,1 +1,1 @@@
1268 - Hello world
1269  -Goodbye
1270 ++Goodbye world
1271 -------------------------------------------------
1273 This shows that our resolved version deleted "Hello world" from the
1274 first parent, deleted "Goodbye" from the second parent, and added
1275 "Goodbye world", which was previously absent from both.
1277 Some special diff options allow diffing the working directory against
1278 any of these stages:
1280 -------------------------------------------------
1281 $ git diff -1 file.txt          # diff against stage 1
1282 $ git diff --base file.txt      # same as the above
1283 $ git diff -2 file.txt          # diff against stage 2
1284 $ git diff --ours file.txt      # same as the above
1285 $ git diff -3 file.txt          # diff against stage 3
1286 $ git diff --theirs file.txt    # same as the above.
1287 -------------------------------------------------
1289 The gitlink:git-log[1] and gitk[1] commands also provide special help
1290 for merges:
1292 -------------------------------------------------
1293 $ git log --merge
1294 $ gitk --merge
1295 -------------------------------------------------
1297 These will display all commits which exist only on HEAD or on
1298 MERGE_HEAD, and which touch an unmerged file.
1300 You may also use gitlink:git-mergetool[1], which lets you merge the
1301 unmerged files using external tools such as emacs or kdiff3.
1303 Each time you resolve the conflicts in a file and update the index:
1305 -------------------------------------------------
1306 $ git add file.txt
1307 -------------------------------------------------
1309 the different stages of that file will be "collapsed", after which
1310 git-diff will (by default) no longer show diffs for that file.
1312 [[undoing-a-merge]]
1313 Undoing a merge
1314 ---------------
1316 If you get stuck and decide to just give up and throw the whole mess
1317 away, you can always return to the pre-merge state with
1319 -------------------------------------------------
1320 $ git reset --hard HEAD
1321 -------------------------------------------------
1323 Or, if you've already commited the merge that you want to throw away,
1325 -------------------------------------------------
1326 $ git reset --hard ORIG_HEAD
1327 -------------------------------------------------
1329 However, this last command can be dangerous in some cases--never
1330 throw away a commit you have already committed if that commit may
1331 itself have been merged into another branch, as doing so may confuse
1332 further merges.
1334 [[fast-forwards]]
1335 Fast-forward merges
1336 -------------------
1338 There is one special case not mentioned above, which is treated
1339 differently.  Normally, a merge results in a merge commit, with two
1340 parents, one pointing at each of the two lines of development that
1341 were merged.
1343 However, if the current branch is a descendant of the other--so every
1344 commit present in the one is already contained in the other--then git
1345 just performs a "fast forward"; the head of the current branch is moved
1346 forward to point at the head of the merged-in branch, without any new
1347 commits being created.
1349 [[fixing-mistakes]]
1350 Fixing mistakes
1351 ---------------
1353 If you've messed up the working tree, but haven't yet committed your
1354 mistake, you can return the entire working tree to the last committed
1355 state with
1357 -------------------------------------------------
1358 $ git reset --hard HEAD
1359 -------------------------------------------------
1361 If you make a commit that you later wish you hadn't, there are two
1362 fundamentally different ways to fix the problem:
1364         1. You can create a new commit that undoes whatever was done
1365         by the previous commit.  This is the correct thing if your
1366         mistake has already been made public.
1368         2. You can go back and modify the old commit.  You should
1369         never do this if you have already made the history public;
1370         git does not normally expect the "history" of a project to
1371         change, and cannot correctly perform repeated merges from
1372         a branch that has had its history changed.
1374 [[reverting-a-commit]]
1375 Fixing a mistake with a new commit
1376 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1378 Creating a new commit that reverts an earlier change is very easy;
1379 just pass the gitlink:git-revert[1] command a reference to the bad
1380 commit; for example, to revert the most recent commit:
1382 -------------------------------------------------
1383 $ git revert HEAD
1384 -------------------------------------------------
1386 This will create a new commit which undoes the change in HEAD.  You
1387 will be given a chance to edit the commit message for the new commit.
1389 You can also revert an earlier change, for example, the next-to-last:
1391 -------------------------------------------------
1392 $ git revert HEAD^
1393 -------------------------------------------------
1395 In this case git will attempt to undo the old change while leaving
1396 intact any changes made since then.  If more recent changes overlap
1397 with the changes to be reverted, then you will be asked to fix
1398 conflicts manually, just as in the case of <<resolving-a-merge,
1399 resolving a merge>>.
1401 [[fixing-a-mistake-by-editing-history]]
1402 Fixing a mistake by editing history
1403 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1405 If the problematic commit is the most recent commit, and you have not
1406 yet made that commit public, then you may just
1407 <<undoing-a-merge,destroy it using git-reset>>.
1409 Alternatively, you
1410 can edit the working directory and update the index to fix your
1411 mistake, just as if you were going to <<how-to-make-a-commit,create a
1412 new commit>>, then run
1414 -------------------------------------------------
1415 $ git commit --amend
1416 -------------------------------------------------
1418 which will replace the old commit by a new commit incorporating your
1419 changes, giving you a chance to edit the old commit message first.
1421 Again, you should never do this to a commit that may already have
1422 been merged into another branch; use gitlink:git-revert[1] instead in
1423 that case.
1425 It is also possible to edit commits further back in the history, but
1426 this is an advanced topic to be left for
1427 <<cleaning-up-history,another chapter>>.
1429 [[checkout-of-path]]
1430 Checking out an old version of a file
1431 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1433 In the process of undoing a previous bad change, you may find it
1434 useful to check out an older version of a particular file using
1435 gitlink:git-checkout[1].  We've used git checkout before to switch
1436 branches, but it has quite different behavior if it is given a path
1437 name: the command
1439 -------------------------------------------------
1440 $ git checkout HEAD^ path/to/file
1441 -------------------------------------------------
1443 replaces path/to/file by the contents it had in the commit HEAD^, and
1444 also updates the index to match.  It does not change branches.
1446 If you just want to look at an old version of the file, without
1447 modifying the working directory, you can do that with
1448 gitlink:git-show[1]:
1450 -------------------------------------------------
1451 $ git show HEAD^:path/to/file
1452 -------------------------------------------------
1454 which will display the given version of the file.
1456 [[ensuring-good-performance]]
1457 Ensuring good performance
1458 -------------------------
1460 On large repositories, git depends on compression to keep the history
1461 information from taking up to much space on disk or in memory.
1463 This compression is not performed automatically.  Therefore you
1464 should occasionally run gitlink:git-gc[1]:
1466 -------------------------------------------------
1467 $ git gc
1468 -------------------------------------------------
1470 to recompress the archive.  This can be very time-consuming, so
1471 you may prefer to run git-gc when you are not doing other work.
1474 [[ensuring-reliability]]
1475 Ensuring reliability
1476 --------------------
1478 [[checking-for-corruption]]
1479 Checking the repository for corruption
1480 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1482 The gitlink:git-fsck[1] command runs a number of self-consistency checks
1483 on the repository, and reports on any problems.  This may take some
1484 time.  The most common warning by far is about "dangling" objects:
1486 -------------------------------------------------
1487 $ git fsck
1488 dangling commit 7281251ddd2a61e38657c827739c57015671a6b3
1489 dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a63
1490 dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b5
1491 dangling blob 218761f9d90712d37a9c5e36f406f92202db07eb
1492 dangling commit bf093535a34a4d35731aa2bd90fe6b176302f14f
1493 dangling commit 8e4bec7f2ddaa268bef999853c25755452100f8e
1494 dangling tree d50bb86186bf27b681d25af89d3b5b68382e4085
1495 dangling tree b24c2473f1fd3d91352a624795be026d64c8841f
1496 ...
1497 -------------------------------------------------
1499 Dangling objects are not a problem.  At worst they may take up a little
1500 extra disk space.  They can sometimes provide a last-resort method for
1501 recovering lost work--see <<dangling-objects>> for details.  However, if
1502 you wish, you can remove them with gitlink:git-prune[1] or the --prune
1503 option to gitlink:git-gc[1]:
1505 -------------------------------------------------
1506 $ git gc --prune
1507 -------------------------------------------------
1509 This may be time-consuming.  Unlike most other git operations (including
1510 git-gc when run without any options), it is not safe to prune while
1511 other git operations are in progress in the same repository.
1513 [[recovering-lost-changes]]
1514 Recovering lost changes
1515 ~~~~~~~~~~~~~~~~~~~~~~~
1517 [[reflogs]]
1518 Reflogs
1519 ^^^^^^^
1521 Say you modify a branch with gitlink:git-reset[1] --hard, and then
1522 realize that the branch was the only reference you had to that point in
1523 history.
1525 Fortunately, git also keeps a log, called a "reflog", of all the
1526 previous values of each branch.  So in this case you can still find the
1527 old history using, for example, 
1529 -------------------------------------------------
1530 $ git log master@{1}
1531 -------------------------------------------------
1533 This lists the commits reachable from the previous version of the head.
1534 This syntax can be used to with any git command that accepts a commit,
1535 not just with git log.  Some other examples:
1537 -------------------------------------------------
1538 $ git show master@{2}           # See where the branch pointed 2,
1539 $ git show master@{3}           # 3, ... changes ago.
1540 $ gitk master@{yesterday}       # See where it pointed yesterday,
1541 $ gitk master@{"1 week ago"}    # ... or last week
1542 $ git log --walk-reflogs master # show reflog entries for master
1543 -------------------------------------------------
1545 A separate reflog is kept for the HEAD, so
1547 -------------------------------------------------
1548 $ git show HEAD@{"1 week ago"}
1549 -------------------------------------------------
1551 will show what HEAD pointed to one week ago, not what the current branch
1552 pointed to one week ago.  This allows you to see the history of what
1553 you've checked out.
1555 The reflogs are kept by default for 30 days, after which they may be
1556 pruned.  See gitlink:git-reflog[1] and gitlink:git-gc[1] to learn
1557 how to control this pruning, and see the "SPECIFYING REVISIONS"
1558 section of gitlink:git-rev-parse[1] for details.
1560 Note that the reflog history is very different from normal git history.
1561 While normal history is shared by every repository that works on the
1562 same project, the reflog history is not shared: it tells you only about
1563 how the branches in your local repository have changed over time.
1565 [[dangling-object-recovery]]
1566 Examining dangling objects
1567 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1569 In some situations the reflog may not be able to save you.  For example,
1570 suppose you delete a branch, then realize you need the history it
1571 contained.  The reflog is also deleted; however, if you have not yet
1572 pruned the repository, then you may still be able to find the lost
1573 commits in the dangling objects that git-fsck reports.  See
1574 <<dangling-objects>> for the details.
1576 -------------------------------------------------
1577 $ git fsck
1578 dangling commit 7281251ddd2a61e38657c827739c57015671a6b3
1579 dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a63
1580 dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b5
1581 ...
1582 -------------------------------------------------
1584 You can examine
1585 one of those dangling commits with, for example,
1587 ------------------------------------------------
1588 $ gitk 7281251ddd --not --all
1589 ------------------------------------------------
1591 which does what it sounds like: it says that you want to see the commit
1592 history that is described by the dangling commit(s), but not the
1593 history that is described by all your existing branches and tags.  Thus
1594 you get exactly the history reachable from that commit that is lost.
1595 (And notice that it might not be just one commit: we only report the
1596 "tip of the line" as being dangling, but there might be a whole deep
1597 and complex commit history that was dropped.)
1599 If you decide you want the history back, you can always create a new
1600 reference pointing to it, for example, a new branch:
1602 ------------------------------------------------
1603 $ git branch recovered-branch 7281251ddd 
1604 ------------------------------------------------
1606 Other types of dangling objects (blobs and trees) are also possible, and
1607 dangling objects can arise in other situations.
1610 [[sharing-development]]
1611 Sharing development with others
1612 ===============================
1614 [[getting-updates-with-git-pull]]
1615 Getting updates with git pull
1616 -----------------------------
1618 After you clone a repository and make a few changes of your own, you
1619 may wish to check the original repository for updates and merge them
1620 into your own work.
1622 We have already seen <<Updating-a-repository-with-git-fetch,how to
1623 keep remote tracking branches up to date>> with gitlink:git-fetch[1],
1624 and how to merge two branches.  So you can merge in changes from the
1625 original repository's master branch with:
1627 -------------------------------------------------
1628 $ git fetch
1629 $ git merge origin/master
1630 -------------------------------------------------
1632 However, the gitlink:git-pull[1] command provides a way to do this in
1633 one step:
1635 -------------------------------------------------
1636 $ git pull origin master
1637 -------------------------------------------------
1639 In fact, "origin" is normally the default repository to pull from,
1640 and the default branch is normally the HEAD of the remote repository,
1641 so often you can accomplish the above with just
1643 -------------------------------------------------
1644 $ git pull
1645 -------------------------------------------------
1647 See the descriptions of the branch.<name>.remote and branch.<name>.merge
1648 options in gitlink:git-config[1] to learn how to control these defaults
1649 depending on the current branch.  Also note that the --track option to
1650 gitlink:git-branch[1] and gitlink:git-checkout[1] can be used to
1651 automatically set the default remote branch to pull from at the time
1652 that a branch is created:
1654 -------------------------------------------------
1655 $ git checkout --track -b maint origin/maint
1656 -------------------------------------------------
1658 In addition to saving you keystrokes, "git pull" also helps you by
1659 producing a default commit message documenting the branch and
1660 repository that you pulled from.
1662 (But note that no such commit will be created in the case of a
1663 <<fast-forwards,fast forward>>; instead, your branch will just be
1664 updated to point to the latest commit from the upstream branch.)
1666 The git-pull command can also be given "." as the "remote" repository,
1667 in which case it just merges in a branch from the current repository; so
1668 the commands
1670 -------------------------------------------------
1671 $ git pull . branch
1672 $ git merge branch
1673 -------------------------------------------------
1675 are roughly equivalent.  The former is actually very commonly used.
1677 [[submitting-patches]]
1678 Submitting patches to a project
1679 -------------------------------
1681 If you just have a few changes, the simplest way to submit them may
1682 just be to send them as patches in email:
1684 First, use gitlink:git-format-patch[1]; for example:
1686 -------------------------------------------------
1687 $ git format-patch origin
1688 -------------------------------------------------
1690 will produce a numbered series of files in the current directory, one
1691 for each patch in the current branch but not in origin/HEAD.
1693 You can then import these into your mail client and send them by
1694 hand.  However, if you have a lot to send at once, you may prefer to
1695 use the gitlink:git-send-email[1] script to automate the process.
1696 Consult the mailing list for your project first to determine how they
1697 prefer such patches be handled.
1699 [[importing-patches]]
1700 Importing patches to a project
1701 ------------------------------
1703 Git also provides a tool called gitlink:git-am[1] (am stands for
1704 "apply mailbox"), for importing such an emailed series of patches.
1705 Just save all of the patch-containing messages, in order, into a
1706 single mailbox file, say "patches.mbox", then run
1708 -------------------------------------------------
1709 $ git am -3 patches.mbox
1710 -------------------------------------------------
1712 Git will apply each patch in order; if any conflicts are found, it
1713 will stop, and you can fix the conflicts as described in
1714 "<<resolving-a-merge,Resolving a merge>>".  (The "-3" option tells
1715 git to perform a merge; if you would prefer it just to abort and
1716 leave your tree and index untouched, you may omit that option.)
1718 Once the index is updated with the results of the conflict
1719 resolution, instead of creating a new commit, just run
1721 -------------------------------------------------
1722 $ git am --resolved
1723 -------------------------------------------------
1725 and git will create the commit for you and continue applying the
1726 remaining patches from the mailbox.
1728 The final result will be a series of commits, one for each patch in
1729 the original mailbox, with authorship and commit log message each
1730 taken from the message containing each patch.
1732 [[public-repositories]]
1733 Public git repositories
1734 -----------------------
1736 Another way to submit changes to a project is to tell the maintainer of
1737 that project to pull the changes from your repository using git-pull[1].
1738 In the section "<<getting-updates-with-git-pull, Getting updates with
1739 git pull>>" we described this as a way to get updates from the "main"
1740 repository, but it works just as well in the other direction.
1742 If you and the maintainer both have accounts on the same machine, then
1743 you can just pull changes from each other's repositories directly;
1744 commands that accept repository URLs as arguments will also accept a
1745 local directory name:
1747 -------------------------------------------------
1748 $ git clone /path/to/repository
1749 $ git pull /path/to/other/repository
1750 -------------------------------------------------
1752 or an ssh url:
1754 -------------------------------------------------
1755 $ git clone ssh://yourhost/~you/repository
1756 -------------------------------------------------
1758 For projects with few developers, or for synchronizing a few private
1759 repositories, this may be all you need.
1761 However, the more common way to do this is to maintain a separate public
1762 repository (usually on a different host) for others to pull changes
1763 from.  This is usually more convenient, and allows you to cleanly
1764 separate private work in progress from publicly visible work.
1766 You will continue to do your day-to-day work in your personal
1767 repository, but periodically "push" changes from your personal
1768 repository into your public repository, allowing other developers to
1769 pull from that repository.  So the flow of changes, in a situation
1770 where there is one other developer with a public repository, looks
1771 like this:
1773                         you push
1774   your personal repo ------------------> your public repo
1775         ^                                     |
1776         |                                     |
1777         | you pull                            | they pull
1778         |                                     |
1779         |                                     |
1780         |               they push             V
1781   their public repo <------------------- their repo
1783 We explain how to do this in the following sections.
1785 [[setting-up-a-public-repository]]
1786 Setting up a public repository
1787 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1789 Assume your personal repository is in the directory ~/proj.  We
1790 first create a new clone of the repository and tell git-daemon that it
1791 is meant to be public:
1793 -------------------------------------------------
1794 $ git clone --bare ~/proj proj.git
1795 $ touch proj.git/git-daemon-export-ok
1796 -------------------------------------------------
1798 The resulting directory proj.git contains a "bare" git repository--it is
1799 just the contents of the ".git" directory, without any files checked out
1800 around it.
1802 Next, copy proj.git to the server where you plan to host the
1803 public repository.  You can use scp, rsync, or whatever is most
1804 convenient.
1806 [[exporting-via-git]]
1807 Exporting a git repository via the git protocol
1808 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1810 This is the preferred method.
1812 If someone else administers the server, they should tell you what
1813 directory to put the repository in, and what git:// url it will appear
1814 at.  You can then skip to the section
1815 "<<pushing-changes-to-a-public-repository,Pushing changes to a public
1816 repository>>", below.
1818 Otherwise, all you need to do is start gitlink:git-daemon[1]; it will
1819 listen on port 9418.  By default, it will allow access to any directory
1820 that looks like a git directory and contains the magic file
1821 git-daemon-export-ok.  Passing some directory paths as git-daemon
1822 arguments will further restrict the exports to those paths.
1824 You can also run git-daemon as an inetd service; see the
1825 gitlink:git-daemon[1] man page for details.  (See especially the
1826 examples section.)
1828 [[exporting-via-http]]
1829 Exporting a git repository via http
1830 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1832 The git protocol gives better performance and reliability, but on a
1833 host with a web server set up, http exports may be simpler to set up.
1835 All you need to do is place the newly created bare git repository in
1836 a directory that is exported by the web server, and make some
1837 adjustments to give web clients some extra information they need:
1839 -------------------------------------------------
1840 $ mv proj.git /home/you/public_html/proj.git
1841 $ cd proj.git
1842 $ git --bare update-server-info
1843 $ chmod a+x hooks/post-update
1844 -------------------------------------------------
1846 (For an explanation of the last two lines, see
1847 gitlink:git-update-server-info[1], and the documentation
1848 link:hooks.html[Hooks used by git].)
1850 Advertise the url of proj.git.  Anybody else should then be able to
1851 clone or pull from that url, for example with a commandline like:
1853 -------------------------------------------------
1854 $ git clone http://yourserver.com/~you/proj.git
1855 -------------------------------------------------
1857 (See also
1858 link:howto/setup-git-server-over-http.txt[setup-git-server-over-http]
1859 for a slightly more sophisticated setup using WebDAV which also
1860 allows pushing over http.)
1862 [[pushing-changes-to-a-public-repository]]
1863 Pushing changes to a public repository
1864 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1866 Note that the two techniques outlined above (exporting via
1867 <<exporting-via-http,http>> or <<exporting-via-git,git>>) allow other
1868 maintainers to fetch your latest changes, but they do not allow write
1869 access, which you will need to update the public repository with the
1870 latest changes created in your private repository.
1872 The simplest way to do this is using gitlink:git-push[1] and ssh; to
1873 update the remote branch named "master" with the latest state of your
1874 branch named "master", run
1876 -------------------------------------------------
1877 $ git push ssh://yourserver.com/~you/proj.git master:master
1878 -------------------------------------------------
1880 or just
1882 -------------------------------------------------
1883 $ git push ssh://yourserver.com/~you/proj.git master
1884 -------------------------------------------------
1886 As with git-fetch, git-push will complain if this does not result in
1887 a <<fast-forwards,fast forward>>.  Normally this is a sign of
1888 something wrong.  However, if you are sure you know what you're
1889 doing, you may force git-push to perform the update anyway by
1890 proceeding the branch name by a plus sign:
1892 -------------------------------------------------
1893 $ git push ssh://yourserver.com/~you/proj.git +master
1894 -------------------------------------------------
1896 Note that the target of a "push" is normally a
1897 <<def_bare_repository,bare>> repository.  You can also push to a
1898 repository that has a checked-out working tree, but the working tree
1899 will not be updated by the push.  This may lead to unexpected results if
1900 the branch you push to is the currently checked-out branch!
1902 As with git-fetch, you may also set up configuration options to
1903 save typing; so, for example, after
1905 -------------------------------------------------
1906 $ cat >>.git/config <<EOF
1907 [remote "public-repo"]
1908         url = ssh://yourserver.com/~you/proj.git
1909 EOF
1910 -------------------------------------------------
1912 you should be able to perform the above push with just
1914 -------------------------------------------------
1915 $ git push public-repo master
1916 -------------------------------------------------
1918 See the explanations of the remote.<name>.url, branch.<name>.remote,
1919 and remote.<name>.push options in gitlink:git-config[1] for
1920 details.
1922 [[setting-up-a-shared-repository]]
1923 Setting up a shared repository
1924 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1926 Another way to collaborate is by using a model similar to that
1927 commonly used in CVS, where several developers with special rights
1928 all push to and pull from a single shared repository.  See
1929 link:cvs-migration.html[git for CVS users] for instructions on how to
1930 set this up.
1932 However, while there is nothing wrong with git's support for shared
1933 repositories, this mode of operation is not generally recommended,
1934 simply because the mode of collaboration that git supports--by
1935 exchanging patches and pulling from public repositories--has so many
1936 advantages over the central shared repository:
1938         - Git's ability to quickly import and merge patches allows a
1939           single maintainer to process incoming changes even at very
1940           high rates.  And when that becomes too much, git-pull provides
1941           an easy way for that maintainer to delegate this job to other
1942           maintainers while still allowing optional review of incoming
1943           changes.
1944         - Since every developer's repository has the same complete copy
1945           of the project history, no repository is special, and it is
1946           trivial for another developer to take over maintenance of a
1947           project, either by mutual agreement, or because a maintainer
1948           becomes unresponsive or difficult to work with.
1949         - The lack of a central group of "committers" means there is
1950           less need for formal decisions about who is "in" and who is
1951           "out".
1953 [[setting-up-gitweb]]
1954 Allowing web browsing of a repository
1955 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1957 The gitweb cgi script provides users an easy way to browse your
1958 project's files and history without having to install git; see the file
1959 gitweb/INSTALL in the git source tree for instructions on setting it up.
1961 [[sharing-development-examples]]
1962 Examples
1963 --------
1965 [[maintaining-topic-branches]]
1966 Maintaining topic branches for a Linux subsystem maintainer
1967 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1969 This describes how Tony Luck uses git in his role as maintainer of the
1970 IA64 architecture for the Linux kernel.
1972 He uses two public branches:
1974  - A "test" tree into which patches are initially placed so that they
1975    can get some exposure when integrated with other ongoing development.
1976    This tree is available to Andrew for pulling into -mm whenever he
1977    wants.
1979  - A "release" tree into which tested patches are moved for final sanity
1980    checking, and as a vehicle to send them upstream to Linus (by sending
1981    him a "please pull" request.)
1983 He also uses a set of temporary branches ("topic branches"), each
1984 containing a logical grouping of patches.
1986 To set this up, first create your work tree by cloning Linus's public
1987 tree:
1989 -------------------------------------------------
1990 $ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git work
1991 $ cd work
1992 -------------------------------------------------
1994 Linus's tree will be stored in the remote branch named origin/master,
1995 and can be updated using gitlink:git-fetch[1]; you can track other
1996 public trees using gitlink:git-remote[1] to set up a "remote" and
1997 git-fetch[1] to keep them up-to-date; see <<repositories-and-branches>>.
1999 Now create the branches in which you are going to work; these start out
2000 at the current tip of origin/master branch, and should be set up (using
2001 the --track option to gitlink:git-branch[1]) to merge changes in from
2002 Linus by default.
2004 -------------------------------------------------
2005 $ git branch --track test origin/master
2006 $ git branch --track release origin/master
2007 -------------------------------------------------
2009 These can be easily kept up to date using gitlink:git-pull[1]
2011 -------------------------------------------------
2012 $ git checkout test && git pull
2013 $ git checkout release && git pull
2014 -------------------------------------------------
2016 Important note!  If you have any local changes in these branches, then
2017 this merge will create a commit object in the history (with no local
2018 changes git will simply do a "Fast forward" merge).  Many people dislike
2019 the "noise" that this creates in the Linux history, so you should avoid
2020 doing this capriciously in the "release" branch, as these noisy commits
2021 will become part of the permanent history when you ask Linus to pull
2022 from the release branch.
2024 A few configuration variables (see gitlink:git-config[1]) can
2025 make it easy to push both branches to your public tree.  (See
2026 <<setting-up-a-public-repository>>.)
2028 -------------------------------------------------
2029 $ cat >> .git/config <<EOF
2030 [remote "mytree"]
2031         url =  master.kernel.org:/pub/scm/linux/kernel/git/aegl/linux-2.6.git
2032         push = release
2033         push = test
2034 EOF
2035 -------------------------------------------------
2037 Then you can push both the test and release trees using
2038 gitlink:git-push[1]:
2040 -------------------------------------------------
2041 $ git push mytree
2042 -------------------------------------------------
2044 or push just one of the test and release branches using:
2046 -------------------------------------------------
2047 $ git push mytree test
2048 -------------------------------------------------
2050 or
2052 -------------------------------------------------
2053 $ git push mytree release
2054 -------------------------------------------------
2056 Now to apply some patches from the community.  Think of a short
2057 snappy name for a branch to hold this patch (or related group of
2058 patches), and create a new branch from the current tip of Linus's
2059 branch:
2061 -------------------------------------------------
2062 $ git checkout -b speed-up-spinlocks origin
2063 -------------------------------------------------
2065 Now you apply the patch(es), run some tests, and commit the change(s).  If
2066 the patch is a multi-part series, then you should apply each as a separate
2067 commit to this branch.
2069 -------------------------------------------------
2070 $ ... patch ... test  ... commit [ ... patch ... test ... commit ]*
2071 -------------------------------------------------
2073 When you are happy with the state of this change, you can pull it into the
2074 "test" branch in preparation to make it public:
2076 -------------------------------------------------
2077 $ git checkout test && git pull . speed-up-spinlocks
2078 -------------------------------------------------
2080 It is unlikely that you would have any conflicts here ... but you might if you
2081 spent a while on this step and had also pulled new versions from upstream.
2083 Some time later when enough time has passed and testing done, you can pull the
2084 same branch into the "release" tree ready to go upstream.  This is where you
2085 see the value of keeping each patch (or patch series) in its own branch.  It
2086 means that the patches can be moved into the "release" tree in any order.
2088 -------------------------------------------------
2089 $ git checkout release && git pull . speed-up-spinlocks
2090 -------------------------------------------------
2092 After a while, you will have a number of branches, and despite the
2093 well chosen names you picked for each of them, you may forget what
2094 they are for, or what status they are in.  To get a reminder of what
2095 changes are in a specific branch, use:
2097 -------------------------------------------------
2098 $ git log linux..branchname | git-shortlog
2099 -------------------------------------------------
2101 To see whether it has already been merged into the test or release branches
2102 use:
2104 -------------------------------------------------
2105 $ git log test..branchname
2106 -------------------------------------------------
2108 or
2110 -------------------------------------------------
2111 $ git log release..branchname
2112 -------------------------------------------------
2114 (If this branch has not yet been merged you will see some log entries.
2115 If it has been merged, then there will be no output.)
2117 Once a patch completes the great cycle (moving from test to release,
2118 then pulled by Linus, and finally coming back into your local
2119 "origin/master" branch) the branch for this change is no longer needed.
2120 You detect this when the output from:
2122 -------------------------------------------------
2123 $ git log origin..branchname
2124 -------------------------------------------------
2126 is empty.  At this point the branch can be deleted:
2128 -------------------------------------------------
2129 $ git branch -d branchname
2130 -------------------------------------------------
2132 Some changes are so trivial that it is not necessary to create a separate
2133 branch and then merge into each of the test and release branches.  For
2134 these changes, just apply directly to the "release" branch, and then
2135 merge that into the "test" branch.
2137 To create diffstat and shortlog summaries of changes to include in a "please
2138 pull" request to Linus you can use:
2140 -------------------------------------------------
2141 $ git diff --stat origin..release
2142 -------------------------------------------------
2144 and
2146 -------------------------------------------------
2147 $ git log -p origin..release | git shortlog
2148 -------------------------------------------------
2150 Here are some of the scripts that simplify all this even further.
2152 -------------------------------------------------
2153 ==== update script ====
2154 # Update a branch in my GIT tree.  If the branch to be updated
2155 # is origin, then pull from kernel.org.  Otherwise merge
2156 # origin/master branch into test|release branch
2158 case "$1" in
2159 test|release)
2160         git checkout $1 && git pull . origin
2161         ;;
2162 origin)
2163         before=$(cat .git/refs/remotes/origin/master)
2164         git fetch origin
2165         after=$(cat .git/refs/remotes/origin/master)
2166         if [ $before != $after ]
2167         then
2168                 git log $before..$after | git shortlog
2169         fi
2170         ;;
2171 *)
2172         echo "Usage: $0 origin|test|release" 1>&2
2173         exit 1
2174         ;;
2175 esac
2176 -------------------------------------------------
2178 -------------------------------------------------
2179 ==== merge script ====
2180 # Merge a branch into either the test or release branch
2182 pname=$0
2184 usage()
2186         echo "Usage: $pname branch test|release" 1>&2
2187         exit 1
2190 if [ ! -f .git/refs/heads/"$1" ]
2191 then
2192         echo "Can't see branch <$1>" 1>&2
2193         usage
2194 fi
2196 case "$2" in
2197 test|release)
2198         if [ $(git log $2..$1 | wc -c) -eq 0 ]
2199         then
2200                 echo $1 already merged into $2 1>&2
2201                 exit 1
2202         fi
2203         git checkout $2 && git pull . $1
2204         ;;
2205 *)
2206         usage
2207         ;;
2208 esac
2209 -------------------------------------------------
2211 -------------------------------------------------
2212 ==== status script ====
2213 # report on status of my ia64 GIT tree
2215 gb=$(tput setab 2)
2216 rb=$(tput setab 1)
2217 restore=$(tput setab 9)
2219 if [ `git rev-list test..release | wc -c` -gt 0 ]
2220 then
2221         echo $rb Warning: commits in release that are not in test $restore
2222         git log test..release
2223 fi
2225 for branch in `ls .git/refs/heads`
2226 do
2227         if [ $branch = test -o $branch = release ]
2228         then
2229                 continue
2230         fi
2232         echo -n $gb ======= $branch ====== $restore " "
2233         status=
2234         for ref in test release origin/master
2235         do
2236                 if [ `git rev-list $ref..$branch | wc -c` -gt 0 ]
2237                 then
2238                         status=$status${ref:0:1}
2239                 fi
2240         done
2241         case $status in
2242         trl)
2243                 echo $rb Need to pull into test $restore
2244                 ;;
2245         rl)
2246                 echo "In test"
2247                 ;;
2248         l)
2249                 echo "Waiting for linus"
2250                 ;;
2251         "")
2252                 echo $rb All done $restore
2253                 ;;
2254         *)
2255                 echo $rb "<$status>" $restore
2256                 ;;
2257         esac
2258         git log origin/master..$branch | git shortlog
2259 done
2260 -------------------------------------------------
2263 [[cleaning-up-history]]
2264 Rewriting history and maintaining patch series
2265 ==============================================
2267 Normally commits are only added to a project, never taken away or
2268 replaced.  Git is designed with this assumption, and violating it will
2269 cause git's merge machinery (for example) to do the wrong thing.
2271 However, there is a situation in which it can be useful to violate this
2272 assumption.
2274 [[patch-series]]
2275 Creating the perfect patch series
2276 ---------------------------------
2278 Suppose you are a contributor to a large project, and you want to add a
2279 complicated feature, and to present it to the other developers in a way
2280 that makes it easy for them to read your changes, verify that they are
2281 correct, and understand why you made each change.
2283 If you present all of your changes as a single patch (or commit), they
2284 may find that it is too much to digest all at once.
2286 If you present them with the entire history of your work, complete with
2287 mistakes, corrections, and dead ends, they may be overwhelmed.
2289 So the ideal is usually to produce a series of patches such that:
2291         1. Each patch can be applied in order.
2293         2. Each patch includes a single logical change, together with a
2294            message explaining the change.
2296         3. No patch introduces a regression: after applying any initial
2297            part of the series, the resulting project still compiles and
2298            works, and has no bugs that it didn't have before.
2300         4. The complete series produces the same end result as your own
2301            (probably much messier!) development process did.
2303 We will introduce some tools that can help you do this, explain how to
2304 use them, and then explain some of the problems that can arise because
2305 you are rewriting history.
2307 [[using-git-rebase]]
2308 Keeping a patch series up to date using git-rebase
2309 --------------------------------------------------
2311 Suppose that you create a branch "mywork" on a remote-tracking branch
2312 "origin", and create some commits on top of it:
2314 -------------------------------------------------
2315 $ git checkout -b mywork origin
2316 $ vi file.txt
2317 $ git commit
2318 $ vi otherfile.txt
2319 $ git commit
2320 ...
2321 -------------------------------------------------
2323 You have performed no merges into mywork, so it is just a simple linear
2324 sequence of patches on top of "origin":
2326 ................................................
2327  o--o--o <-- origin
2328         \
2329          o--o--o <-- mywork
2330 ................................................
2332 Some more interesting work has been done in the upstream project, and
2333 "origin" has advanced:
2335 ................................................
2336  o--o--O--o--o--o <-- origin
2337         \
2338          a--b--c <-- mywork
2339 ................................................
2341 At this point, you could use "pull" to merge your changes back in;
2342 the result would create a new merge commit, like this:
2344 ................................................
2345  o--o--O--o--o--o <-- origin
2346         \        \
2347          a--b--c--m <-- mywork
2348 ................................................
2349  
2350 However, if you prefer to keep the history in mywork a simple series of
2351 commits without any merges, you may instead choose to use
2352 gitlink:git-rebase[1]:
2354 -------------------------------------------------
2355 $ git checkout mywork
2356 $ git rebase origin
2357 -------------------------------------------------
2359 This will remove each of your commits from mywork, temporarily saving
2360 them as patches (in a directory named ".dotest"), update mywork to
2361 point at the latest version of origin, then apply each of the saved
2362 patches to the new mywork.  The result will look like:
2365 ................................................
2366  o--o--O--o--o--o <-- origin
2367                  \
2368                   a'--b'--c' <-- mywork
2369 ................................................
2371 In the process, it may discover conflicts.  In that case it will stop
2372 and allow you to fix the conflicts; after fixing conflicts, use "git
2373 add" to update the index with those contents, and then, instead of
2374 running git-commit, just run
2376 -------------------------------------------------
2377 $ git rebase --continue
2378 -------------------------------------------------
2380 and git will continue applying the rest of the patches.
2382 At any point you may use the --abort option to abort this process and
2383 return mywork to the state it had before you started the rebase:
2385 -------------------------------------------------
2386 $ git rebase --abort
2387 -------------------------------------------------
2389 [[modifying-one-commit]]
2390 Modifying a single commit
2391 -------------------------
2393 We saw in <<fixing-a-mistake-by-editing-history>> that you can replace the
2394 most recent commit using
2396 -------------------------------------------------
2397 $ git commit --amend
2398 -------------------------------------------------
2400 which will replace the old commit by a new commit incorporating your
2401 changes, giving you a chance to edit the old commit message first.
2403 You can also use a combination of this and gitlink:git-rebase[1] to edit
2404 commits further back in your history.  First, tag the problematic commit with
2406 -------------------------------------------------
2407 $ git tag bad mywork~5
2408 -------------------------------------------------
2410 (Either gitk or git-log may be useful for finding the commit.)
2412 Then check out that commit, edit it, and rebase the rest of the series
2413 on top of it (note that we could check out the commit on a temporary
2414 branch, but instead we're using a <<detached-head,detached head>>):
2416 -------------------------------------------------
2417 $ git checkout bad
2418 $ # make changes here and update the index
2419 $ git commit --amend
2420 $ git rebase --onto HEAD bad mywork
2421 -------------------------------------------------
2423 When you're done, you'll be left with mywork checked out, with the top
2424 patches on mywork reapplied on top of your modified commit.  You can
2425 then clean up with
2427 -------------------------------------------------
2428 $ git tag -d bad
2429 -------------------------------------------------
2431 Note that the immutable nature of git history means that you haven't really
2432 "modified" existing commits; instead, you have replaced the old commits with
2433 new commits having new object names.
2435 [[reordering-patch-series]]
2436 Reordering or selecting from a patch series
2437 -------------------------------------------
2439 Given one existing commit, the gitlink:git-cherry-pick[1] command
2440 allows you to apply the change introduced by that commit and create a
2441 new commit that records it.  So, for example, if "mywork" points to a
2442 series of patches on top of "origin", you might do something like:
2444 -------------------------------------------------
2445 $ git checkout -b mywork-new origin
2446 $ gitk origin..mywork &
2447 -------------------------------------------------
2449 And browse through the list of patches in the mywork branch using gitk,
2450 applying them (possibly in a different order) to mywork-new using
2451 cherry-pick, and possibly modifying them as you go using commit
2452 --amend.
2454 Another technique is to use git-format-patch to create a series of
2455 patches, then reset the state to before the patches:
2457 -------------------------------------------------
2458 $ git format-patch origin
2459 $ git reset --hard origin
2460 -------------------------------------------------
2462 Then modify, reorder, or eliminate patches as preferred before applying
2463 them again with gitlink:git-am[1].
2465 [[patch-series-tools]]
2466 Other tools
2467 -----------
2469 There are numerous other tools, such as stgit, which exist for the
2470 purpose of maintaining a patch series.  These are outside of the scope of
2471 this manual.
2473 [[problems-with-rewriting-history]]
2474 Problems with rewriting history
2475 -------------------------------
2477 The primary problem with rewriting the history of a branch has to do
2478 with merging.  Suppose somebody fetches your branch and merges it into
2479 their branch, with a result something like this:
2481 ................................................
2482  o--o--O--o--o--o <-- origin
2483         \        \
2484          t--t--t--m <-- their branch:
2485 ................................................
2487 Then suppose you modify the last three commits:
2489 ................................................
2490          o--o--o <-- new head of origin
2491         /
2492  o--o--O--o--o--o <-- old head of origin
2493 ................................................
2495 If we examined all this history together in one repository, it will
2496 look like:
2498 ................................................
2499          o--o--o <-- new head of origin
2500         /
2501  o--o--O--o--o--o <-- old head of origin
2502         \        \
2503          t--t--t--m <-- their branch:
2504 ................................................
2506 Git has no way of knowing that the new head is an updated version of
2507 the old head; it treats this situation exactly the same as it would if
2508 two developers had independently done the work on the old and new heads
2509 in parallel.  At this point, if someone attempts to merge the new head
2510 in to their branch, git will attempt to merge together the two (old and
2511 new) lines of development, instead of trying to replace the old by the
2512 new.  The results are likely to be unexpected.
2514 You may still choose to publish branches whose history is rewritten,
2515 and it may be useful for others to be able to fetch those branches in
2516 order to examine or test them, but they should not attempt to pull such
2517 branches into their own work.
2519 For true distributed development that supports proper merging,
2520 published branches should never be rewritten.
2522 [[advanced-branch-management]]
2523 Advanced branch management
2524 ==========================
2526 [[fetching-individual-branches]]
2527 Fetching individual branches
2528 ----------------------------
2530 Instead of using gitlink:git-remote[1], you can also choose just
2531 to update one branch at a time, and to store it locally under an
2532 arbitrary name:
2534 -------------------------------------------------
2535 $ git fetch origin todo:my-todo-work
2536 -------------------------------------------------
2538 The first argument, "origin", just tells git to fetch from the
2539 repository you originally cloned from.  The second argument tells git
2540 to fetch the branch named "todo" from the remote repository, and to
2541 store it locally under the name refs/heads/my-todo-work.
2543 You can also fetch branches from other repositories; so
2545 -------------------------------------------------
2546 $ git fetch git://example.com/proj.git master:example-master
2547 -------------------------------------------------
2549 will create a new branch named "example-master" and store in it the
2550 branch named "master" from the repository at the given URL.  If you
2551 already have a branch named example-master, it will attempt to
2552 <<fast-forwards,fast-forward>> to the commit given by example.com's
2553 master branch.  In more detail:
2555 [[fetch-fast-forwards]]
2556 git fetch and fast-forwards
2557 ---------------------------
2559 In the previous example, when updating an existing branch, "git
2560 fetch" checks to make sure that the most recent commit on the remote
2561 branch is a descendant of the most recent commit on your copy of the
2562 branch before updating your copy of the branch to point at the new
2563 commit.  Git calls this process a <<fast-forwards,fast forward>>.
2565 A fast forward looks something like this:
2567 ................................................
2568  o--o--o--o <-- old head of the branch
2569            \
2570             o--o--o <-- new head of the branch
2571 ................................................
2574 In some cases it is possible that the new head will *not* actually be
2575 a descendant of the old head.  For example, the developer may have
2576 realized she made a serious mistake, and decided to backtrack,
2577 resulting in a situation like:
2579 ................................................
2580  o--o--o--o--a--b <-- old head of the branch
2581            \
2582             o--o--o <-- new head of the branch
2583 ................................................
2585 In this case, "git fetch" will fail, and print out a warning.
2587 In that case, you can still force git to update to the new head, as
2588 described in the following section.  However, note that in the
2589 situation above this may mean losing the commits labeled "a" and "b",
2590 unless you've already created a reference of your own pointing to
2591 them.
2593 [[forcing-fetch]]
2594 Forcing git fetch to do non-fast-forward updates
2595 ------------------------------------------------
2597 If git fetch fails because the new head of a branch is not a
2598 descendant of the old head, you may force the update with:
2600 -------------------------------------------------
2601 $ git fetch git://example.com/proj.git +master:refs/remotes/example/master
2602 -------------------------------------------------
2604 Note the addition of the "+" sign.  Alternatively, you can use the "-f"
2605 flag to force updates of all the fetched branches, as in:
2607 -------------------------------------------------
2608 $ git fetch -f origin
2609 -------------------------------------------------
2611 Be aware that commits that the old version of example/master pointed at
2612 may be lost, as we saw in the previous section.
2614 [[remote-branch-configuration]]
2615 Configuring remote branches
2616 ---------------------------
2618 We saw above that "origin" is just a shortcut to refer to the
2619 repository that you originally cloned from.  This information is
2620 stored in git configuration variables, which you can see using
2621 gitlink:git-config[1]:
2623 -------------------------------------------------
2624 $ git config -l
2625 core.repositoryformatversion=0
2626 core.filemode=true
2627 core.logallrefupdates=true
2628 remote.origin.url=git://git.kernel.org/pub/scm/git/git.git
2629 remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
2630 branch.master.remote=origin
2631 branch.master.merge=refs/heads/master
2632 -------------------------------------------------
2634 If there are other repositories that you also use frequently, you can
2635 create similar configuration options to save typing; for example,
2636 after
2638 -------------------------------------------------
2639 $ git config remote.example.url git://example.com/proj.git
2640 -------------------------------------------------
2642 then the following two commands will do the same thing:
2644 -------------------------------------------------
2645 $ git fetch git://example.com/proj.git master:refs/remotes/example/master
2646 $ git fetch example master:refs/remotes/example/master
2647 -------------------------------------------------
2649 Even better, if you add one more option:
2651 -------------------------------------------------
2652 $ git config remote.example.fetch master:refs/remotes/example/master
2653 -------------------------------------------------
2655 then the following commands will all do the same thing:
2657 -------------------------------------------------
2658 $ git fetch git://example.com/proj.git master:refs/remotes/example/master
2659 $ git fetch example master:refs/remotes/example/master
2660 $ git fetch example
2661 -------------------------------------------------
2663 You can also add a "+" to force the update each time:
2665 -------------------------------------------------
2666 $ git config remote.example.fetch +master:ref/remotes/example/master
2667 -------------------------------------------------
2669 Don't do this unless you're sure you won't mind "git fetch" possibly
2670 throwing away commits on mybranch.
2672 Also note that all of the above configuration can be performed by
2673 directly editing the file .git/config instead of using
2674 gitlink:git-config[1].
2676 See gitlink:git-config[1] for more details on the configuration
2677 options mentioned above.
2680 [[git-internals]]
2681 Git internals
2682 =============
2684 Git depends on two fundamental abstractions: the "object database", and
2685 the "current directory cache" aka "index".
2687 [[the-object-database]]
2688 The Object Database
2689 -------------------
2691 The object database is literally just a content-addressable collection
2692 of objects.  All objects are named by their content, which is
2693 approximated by the SHA1 hash of the object itself.  Objects may refer
2694 to other objects (by referencing their SHA1 hash), and so you can
2695 build up a hierarchy of objects.
2697 All objects have a statically determined "type" which is
2698 determined at object creation time, and which identifies the format of
2699 the object (i.e. how it is used, and how it can refer to other
2700 objects).  There are currently four different object types: "blob",
2701 "tree", "commit", and "tag".
2703 A <<def_blob_object,"blob" object>> cannot refer to any other object,
2704 and is, as the name implies, a pure storage object containing some
2705 user data.  It is used to actually store the file data, i.e. a blob
2706 object is associated with some particular version of some file.
2708 A <<def_tree_object,"tree" object>> is an object that ties one or more
2709 "blob" objects into a directory structure. In addition, a tree object
2710 can refer to other tree objects, thus creating a directory hierarchy.
2712 A <<def_commit_object,"commit" object>> ties such directory hierarchies
2713 together into a <<def_DAG,directed acyclic graph>> of revisions - each
2714 "commit" is associated with exactly one tree (the directory hierarchy at
2715 the time of the commit). In addition, a "commit" refers to one or more
2716 "parent" commit objects that describe the history of how we arrived at
2717 that directory hierarchy.
2719 As a special case, a commit object with no parents is called the "root"
2720 commit, and is the point of an initial project commit.  Each project
2721 must have at least one root, and while you can tie several different
2722 root objects together into one project by creating a commit object which
2723 has two or more separate roots as its ultimate parents, that's probably
2724 just going to confuse people.  So aim for the notion of "one root object
2725 per project", even if git itself does not enforce that. 
2727 A <<def_tag_object,"tag" object>> symbolically identifies and can be
2728 used to sign other objects. It contains the identifier and type of
2729 another object, a symbolic name (of course!) and, optionally, a
2730 signature.
2732 Regardless of object type, all objects share the following
2733 characteristics: they are all deflated with zlib, and have a header
2734 that not only specifies their type, but also provides size information
2735 about the data in the object.  It's worth noting that the SHA1 hash
2736 that is used to name the object is the hash of the original data
2737 plus this header, so `sha1sum` 'file' does not match the object name
2738 for 'file'.
2739 (Historical note: in the dawn of the age of git the hash
2740 was the sha1 of the 'compressed' object.)
2742 As a result, the general consistency of an object can always be tested
2743 independently of the contents or the type of the object: all objects can
2744 be validated by verifying that (a) their hashes match the content of the
2745 file and (b) the object successfully inflates to a stream of bytes that
2746 forms a sequence of <ascii type without space> {plus} <space> {plus} <ascii decimal
2747 size> {plus} <byte\0> {plus} <binary object data>.
2749 The structured objects can further have their structure and
2750 connectivity to other objects verified. This is generally done with
2751 the `git-fsck` program, which generates a full dependency graph
2752 of all objects, and verifies their internal consistency (in addition
2753 to just verifying their superficial consistency through the hash).
2755 The object types in some more detail:
2757 [[blob-object]]
2758 Blob Object
2759 -----------
2761 A "blob" object is nothing but a binary blob of data, and doesn't
2762 refer to anything else.  There is no signature or any other
2763 verification of the data, so while the object is consistent (it 'is'
2764 indexed by its sha1 hash, so the data itself is certainly correct), it
2765 has absolutely no other attributes.  No name associations, no
2766 permissions.  It is purely a blob of data (i.e. normally "file
2767 contents").
2769 In particular, since the blob is entirely defined by its data, if two
2770 files in a directory tree (or in multiple different versions of the
2771 repository) have the same contents, they will share the same blob
2772 object. The object is totally independent of its location in the
2773 directory tree, and renaming a file does not change the object that
2774 file is associated with in any way.
2776 A blob is typically created when gitlink:git-update-index[1]
2777 is run, and its data can be accessed by gitlink:git-cat-file[1].
2779 [[tree-object]]
2780 Tree Object
2781 -----------
2783 The next hierarchical object type is the "tree" object.  A tree object
2784 is a list of mode/name/blob data, sorted by name.  Alternatively, the
2785 mode data may specify a directory mode, in which case instead of
2786 naming a blob, that name is associated with another TREE object.
2788 Like the "blob" object, a tree object is uniquely determined by the
2789 set contents, and so two separate but identical trees will always
2790 share the exact same object. This is true at all levels, i.e. it's
2791 true for a "leaf" tree (which does not refer to any other trees, only
2792 blobs) as well as for a whole subdirectory.
2794 For that reason a "tree" object is just a pure data abstraction: it
2795 has no history, no signatures, no verification of validity, except
2796 that since the contents are again protected by the hash itself, we can
2797 trust that the tree is immutable and its contents never change.
2799 So you can trust the contents of a tree to be valid, the same way you
2800 can trust the contents of a blob, but you don't know where those
2801 contents 'came' from.
2803 Side note on trees: since a "tree" object is a sorted list of
2804 "filename+content", you can create a diff between two trees without
2805 actually having to unpack two trees.  Just ignore all common parts,
2806 and your diff will look right.  In other words, you can effectively
2807 (and efficiently) tell the difference between any two random trees by
2808 O(n) where "n" is the size of the difference, rather than the size of
2809 the tree.
2811 Side note 2 on trees: since the name of a "blob" depends entirely and
2812 exclusively on its contents (i.e. there are no names or permissions
2813 involved), you can see trivial renames or permission changes by
2814 noticing that the blob stayed the same.  However, renames with data
2815 changes need a smarter "diff" implementation.
2817 A tree is created with gitlink:git-write-tree[1] and
2818 its data can be accessed by gitlink:git-ls-tree[1].
2819 Two trees can be compared with gitlink:git-diff-tree[1].
2821 [[commit-object]]
2822 Commit Object
2823 -------------
2825 The "commit" object is an object that introduces the notion of
2826 history into the picture.  In contrast to the other objects, it
2827 doesn't just describe the physical state of a tree, it describes how
2828 we got there, and why.
2830 A "commit" is defined by the tree-object that it results in, the
2831 parent commits (zero, one or more) that led up to that point, and a
2832 comment on what happened.  Again, a commit is not trusted per se:
2833 the contents are well-defined and "safe" due to the cryptographically
2834 strong signatures at all levels, but there is no reason to believe
2835 that the tree is "good" or that the merge information makes sense.
2836 The parents do not have to actually have any relationship with the
2837 result, for example.
2839 Note on commits: unlike some SCM's, commits do not contain
2840 rename information or file mode change information.  All of that is
2841 implicit in the trees involved (the result tree, and the result trees
2842 of the parents), and describing that makes no sense in this idiotic
2843 file manager.
2845 A commit is created with gitlink:git-commit-tree[1] and
2846 its data can be accessed by gitlink:git-cat-file[1].
2848 [[trust]]
2849 Trust
2850 -----
2852 An aside on the notion of "trust". Trust is really outside the scope
2853 of "git", but it's worth noting a few things.  First off, since
2854 everything is hashed with SHA1, you 'can' trust that an object is
2855 intact and has not been messed with by external sources.  So the name
2856 of an object uniquely identifies a known state - just not a state that
2857 you may want to trust.
2859 Furthermore, since the SHA1 signature of a commit refers to the
2860 SHA1 signatures of the tree it is associated with and the signatures
2861 of the parent, a single named commit specifies uniquely a whole set
2862 of history, with full contents.  You can't later fake any step of the
2863 way once you have the name of a commit.
2865 So to introduce some real trust in the system, the only thing you need
2866 to do is to digitally sign just 'one' special note, which includes the
2867 name of a top-level commit.  Your digital signature shows others
2868 that you trust that commit, and the immutability of the history of
2869 commits tells others that they can trust the whole history.
2871 In other words, you can easily validate a whole archive by just
2872 sending out a single email that tells the people the name (SHA1 hash)
2873 of the top commit, and digitally sign that email using something
2874 like GPG/PGP.
2876 To assist in this, git also provides the tag object...
2878 [[tag-object]]
2879 Tag Object
2880 ----------
2882 Git provides the "tag" object to simplify creating, managing and
2883 exchanging symbolic and signed tokens.  The "tag" object at its
2884 simplest simply symbolically identifies another object by containing
2885 the sha1, type and symbolic name.
2887 However it can optionally contain additional signature information
2888 (which git doesn't care about as long as there's less than 8k of
2889 it). This can then be verified externally to git.
2891 Note that despite the tag features, "git" itself only handles content
2892 integrity; the trust framework (and signature provision and
2893 verification) has to come from outside.
2895 A tag is created with gitlink:git-mktag[1],
2896 its data can be accessed by gitlink:git-cat-file[1],
2897 and the signature can be verified by
2898 gitlink:git-verify-tag[1].
2901 [[the-index]]
2902 The "index" aka "Current Directory Cache"
2903 -----------------------------------------
2905 The index is a simple binary file, which contains an efficient
2906 representation of the contents of a virtual directory.  It
2907 does so by a simple array that associates a set of names, dates,
2908 permissions and content (aka "blob") objects together.  The cache is
2909 always kept ordered by name, and names are unique (with a few very
2910 specific rules) at any point in time, but the cache has no long-term
2911 meaning, and can be partially updated at any time.
2913 In particular, the index certainly does not need to be consistent with
2914 the current directory contents (in fact, most operations will depend on
2915 different ways to make the index 'not' be consistent with the directory
2916 hierarchy), but it has three very important attributes:
2918 '(a) it can re-generate the full state it caches (not just the
2919 directory structure: it contains pointers to the "blob" objects so
2920 that it can regenerate the data too)'
2922 As a special case, there is a clear and unambiguous one-way mapping
2923 from a current directory cache to a "tree object", which can be
2924 efficiently created from just the current directory cache without
2925 actually looking at any other data.  So a directory cache at any one
2926 time uniquely specifies one and only one "tree" object (but has
2927 additional data to make it easy to match up that tree object with what
2928 has happened in the directory)
2930 '(b) it has efficient methods for finding inconsistencies between that
2931 cached state ("tree object waiting to be instantiated") and the
2932 current state.'
2934 '(c) it can additionally efficiently represent information about merge
2935 conflicts between different tree objects, allowing each pathname to be
2936 associated with sufficient information about the trees involved that
2937 you can create a three-way merge between them.'
2939 Those are the ONLY three things that the directory cache does.  It's a
2940 cache, and the normal operation is to re-generate it completely from a
2941 known tree object, or update/compare it with a live tree that is being
2942 developed.  If you blow the directory cache away entirely, you generally
2943 haven't lost any information as long as you have the name of the tree
2944 that it described. 
2946 At the same time, the index is at the same time also the
2947 staging area for creating new trees, and creating a new tree always
2948 involves a controlled modification of the index file.  In particular,
2949 the index file can have the representation of an intermediate tree that
2950 has not yet been instantiated.  So the index can be thought of as a
2951 write-back cache, which can contain dirty information that has not yet
2952 been written back to the backing store.
2956 [[the-workflow]]
2957 The Workflow
2958 ------------
2960 Generally, all "git" operations work on the index file. Some operations
2961 work *purely* on the index file (showing the current state of the
2962 index), but most operations move data to and from the index file. Either
2963 from the database or from the working directory. Thus there are four
2964 main combinations: 
2966 [[working-directory-to-index]]
2967 working directory -> index
2968 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2970 You update the index with information from the working directory with
2971 the gitlink:git-update-index[1] command.  You
2972 generally update the index information by just specifying the filename
2973 you want to update, like so:
2975 -------------------------------------------------
2976 $ git-update-index filename
2977 -------------------------------------------------
2979 but to avoid common mistakes with filename globbing etc, the command
2980 will not normally add totally new entries or remove old entries,
2981 i.e. it will normally just update existing cache entries.
2983 To tell git that yes, you really do realize that certain files no
2984 longer exist, or that new files should be added, you
2985 should use the `--remove` and `--add` flags respectively.
2987 NOTE! A `--remove` flag does 'not' mean that subsequent filenames will
2988 necessarily be removed: if the files still exist in your directory
2989 structure, the index will be updated with their new status, not
2990 removed. The only thing `--remove` means is that update-cache will be
2991 considering a removed file to be a valid thing, and if the file really
2992 does not exist any more, it will update the index accordingly.
2994 As a special case, you can also do `git-update-index --refresh`, which
2995 will refresh the "stat" information of each index to match the current
2996 stat information. It will 'not' update the object status itself, and
2997 it will only update the fields that are used to quickly test whether
2998 an object still matches its old backing store object.
3000 [[index-to-object-database]]
3001 index -> object database
3002 ~~~~~~~~~~~~~~~~~~~~~~~~
3004 You write your current index file to a "tree" object with the program
3006 -------------------------------------------------
3007 $ git-write-tree
3008 -------------------------------------------------
3010 that doesn't come with any options - it will just write out the
3011 current index into the set of tree objects that describe that state,
3012 and it will return the name of the resulting top-level tree. You can
3013 use that tree to re-generate the index at any time by going in the
3014 other direction:
3016 [[object-database-to-index]]
3017 object database -> index
3018 ~~~~~~~~~~~~~~~~~~~~~~~~
3020 You read a "tree" file from the object database, and use that to
3021 populate (and overwrite - don't do this if your index contains any
3022 unsaved state that you might want to restore later!) your current
3023 index.  Normal operation is just
3025 -------------------------------------------------
3026 $ git-read-tree <sha1 of tree>
3027 -------------------------------------------------
3029 and your index file will now be equivalent to the tree that you saved
3030 earlier. However, that is only your 'index' file: your working
3031 directory contents have not been modified.
3033 [[index-to-working-directory]]
3034 index -> working directory
3035 ~~~~~~~~~~~~~~~~~~~~~~~~~~
3037 You update your working directory from the index by "checking out"
3038 files. This is not a very common operation, since normally you'd just
3039 keep your files updated, and rather than write to your working
3040 directory, you'd tell the index files about the changes in your
3041 working directory (i.e. `git-update-index`).
3043 However, if you decide to jump to a new version, or check out somebody
3044 else's version, or just restore a previous tree, you'd populate your
3045 index file with read-tree, and then you need to check out the result
3046 with
3048 -------------------------------------------------
3049 $ git-checkout-index filename
3050 -------------------------------------------------
3052 or, if you want to check out all of the index, use `-a`.
3054 NOTE! git-checkout-index normally refuses to overwrite old files, so
3055 if you have an old version of the tree already checked out, you will
3056 need to use the "-f" flag ('before' the "-a" flag or the filename) to
3057 'force' the checkout.
3060 Finally, there are a few odds and ends which are not purely moving
3061 from one representation to the other:
3063 [[tying-it-all-together]]
3064 Tying it all together
3065 ~~~~~~~~~~~~~~~~~~~~~
3067 To commit a tree you have instantiated with "git-write-tree", you'd
3068 create a "commit" object that refers to that tree and the history
3069 behind it - most notably the "parent" commits that preceded it in
3070 history.
3072 Normally a "commit" has one parent: the previous state of the tree
3073 before a certain change was made. However, sometimes it can have two
3074 or more parent commits, in which case we call it a "merge", due to the
3075 fact that such a commit brings together ("merges") two or more
3076 previous states represented by other commits.
3078 In other words, while a "tree" represents a particular directory state
3079 of a working directory, a "commit" represents that state in "time",
3080 and explains how we got there.
3082 You create a commit object by giving it the tree that describes the
3083 state at the time of the commit, and a list of parents:
3085 -------------------------------------------------
3086 $ git-commit-tree <tree> -p <parent> [-p <parent2> ..]
3087 -------------------------------------------------
3089 and then giving the reason for the commit on stdin (either through
3090 redirection from a pipe or file, or by just typing it at the tty).
3092 git-commit-tree will return the name of the object that represents
3093 that commit, and you should save it away for later use. Normally,
3094 you'd commit a new `HEAD` state, and while git doesn't care where you
3095 save the note about that state, in practice we tend to just write the
3096 result to the file pointed at by `.git/HEAD`, so that we can always see
3097 what the last committed state was.
3099 Here is an ASCII art by Jon Loeliger that illustrates how
3100 various pieces fit together.
3102 ------------
3104                      commit-tree
3105                       commit obj
3106                        +----+
3107                        |    |
3108                        |    |
3109                        V    V
3110                     +-----------+
3111                     | Object DB |
3112                     |  Backing  |
3113                     |   Store   |
3114                     +-----------+
3115                        ^
3116            write-tree  |     |
3117              tree obj  |     |
3118                        |     |  read-tree
3119                        |     |  tree obj
3120                              V
3121                     +-----------+
3122                     |   Index   |
3123                     |  "cache"  |
3124                     +-----------+
3125          update-index  ^
3126              blob obj  |     |
3127                        |     |
3128     checkout-index -u  |     |  checkout-index
3129              stat      |     |  blob obj
3130                              V
3131                     +-----------+
3132                     |  Working  |
3133                     | Directory |
3134                     +-----------+
3136 ------------
3139 [[examining-the-data]]
3140 Examining the data
3141 ------------------
3143 You can examine the data represented in the object database and the
3144 index with various helper tools. For every object, you can use
3145 gitlink:git-cat-file[1] to examine details about the
3146 object:
3148 -------------------------------------------------
3149 $ git-cat-file -t <objectname>
3150 -------------------------------------------------
3152 shows the type of the object, and once you have the type (which is
3153 usually implicit in where you find the object), you can use
3155 -------------------------------------------------
3156 $ git-cat-file blob|tree|commit|tag <objectname>
3157 -------------------------------------------------
3159 to show its contents. NOTE! Trees have binary content, and as a result
3160 there is a special helper for showing that content, called
3161 `git-ls-tree`, which turns the binary content into a more easily
3162 readable form.
3164 It's especially instructive to look at "commit" objects, since those
3165 tend to be small and fairly self-explanatory. In particular, if you
3166 follow the convention of having the top commit name in `.git/HEAD`,
3167 you can do
3169 -------------------------------------------------
3170 $ git-cat-file commit HEAD
3171 -------------------------------------------------
3173 to see what the top commit was.
3175 [[merging-multiple-trees]]
3176 Merging multiple trees
3177 ----------------------
3179 Git helps you do a three-way merge, which you can expand to n-way by
3180 repeating the merge procedure arbitrary times until you finally
3181 "commit" the state.  The normal situation is that you'd only do one
3182 three-way merge (two parents), and commit it, but if you like to, you
3183 can do multiple parents in one go.
3185 To do a three-way merge, you need the two sets of "commit" objects
3186 that you want to merge, use those to find the closest common parent (a
3187 third "commit" object), and then use those commit objects to find the
3188 state of the directory ("tree" object) at these points.
3190 To get the "base" for the merge, you first look up the common parent
3191 of two commits with
3193 -------------------------------------------------
3194 $ git-merge-base <commit1> <commit2>
3195 -------------------------------------------------
3197 which will return you the commit they are both based on.  You should
3198 now look up the "tree" objects of those commits, which you can easily
3199 do with (for example)
3201 -------------------------------------------------
3202 $ git-cat-file commit <commitname> | head -1
3203 -------------------------------------------------
3205 since the tree object information is always the first line in a commit
3206 object.
3208 Once you know the three trees you are going to merge (the one "original"
3209 tree, aka the common tree, and the two "result" trees, aka the branches
3210 you want to merge), you do a "merge" read into the index. This will
3211 complain if it has to throw away your old index contents, so you should
3212 make sure that you've committed those - in fact you would normally
3213 always do a merge against your last commit (which should thus match what
3214 you have in your current index anyway).
3216 To do the merge, do
3218 -------------------------------------------------
3219 $ git-read-tree -m -u <origtree> <yourtree> <targettree>
3220 -------------------------------------------------
3222 which will do all trivial merge operations for you directly in the
3223 index file, and you can just write the result out with
3224 `git-write-tree`.
3227 [[merging-multiple-trees-2]]
3228 Merging multiple trees, continued
3229 ---------------------------------
3231 Sadly, many merges aren't trivial. If there are files that have
3232 been added.moved or removed, or if both branches have modified the
3233 same file, you will be left with an index tree that contains "merge
3234 entries" in it. Such an index tree can 'NOT' be written out to a tree
3235 object, and you will have to resolve any such merge clashes using
3236 other tools before you can write out the result.
3238 You can examine such index state with `git-ls-files --unmerged`
3239 command.  An example:
3241 ------------------------------------------------
3242 $ git-read-tree -m $orig HEAD $target
3243 $ git-ls-files --unmerged
3244 100644 263414f423d0e4d70dae8fe53fa34614ff3e2860 1       hello.c
3245 100644 06fa6a24256dc7e560efa5687fa84b51f0263c3a 2       hello.c
3246 100644 cc44c73eb783565da5831b4d820c962954019b69 3       hello.c
3247 ------------------------------------------------
3249 Each line of the `git-ls-files --unmerged` output begins with
3250 the blob mode bits, blob SHA1, 'stage number', and the
3251 filename.  The 'stage number' is git's way to say which tree it
3252 came from: stage 1 corresponds to `$orig` tree, stage 2 `HEAD`
3253 tree, and stage3 `$target` tree.
3255 Earlier we said that trivial merges are done inside
3256 `git-read-tree -m`.  For example, if the file did not change
3257 from `$orig` to `HEAD` nor `$target`, or if the file changed
3258 from `$orig` to `HEAD` and `$orig` to `$target` the same way,
3259 obviously the final outcome is what is in `HEAD`.  What the
3260 above example shows is that file `hello.c` was changed from
3261 `$orig` to `HEAD` and `$orig` to `$target` in a different way.
3262 You could resolve this by running your favorite 3-way merge
3263 program, e.g.  `diff3`, `merge`, or git's own merge-file, on
3264 the blob objects from these three stages yourself, like this:
3266 ------------------------------------------------
3267 $ git-cat-file blob 263414f... >hello.c~1
3268 $ git-cat-file blob 06fa6a2... >hello.c~2
3269 $ git-cat-file blob cc44c73... >hello.c~3
3270 $ git merge-file hello.c~2 hello.c~1 hello.c~3
3271 ------------------------------------------------
3273 This would leave the merge result in `hello.c~2` file, along
3274 with conflict markers if there are conflicts.  After verifying
3275 the merge result makes sense, you can tell git what the final
3276 merge result for this file is by:
3278 -------------------------------------------------
3279 $ mv -f hello.c~2 hello.c
3280 $ git-update-index hello.c
3281 -------------------------------------------------
3283 When a path is in unmerged state, running `git-update-index` for
3284 that path tells git to mark the path resolved.
3286 The above is the description of a git merge at the lowest level,
3287 to help you understand what conceptually happens under the hood.
3288 In practice, nobody, not even git itself, uses three `git-cat-file`
3289 for this.  There is `git-merge-index` program that extracts the
3290 stages to temporary files and calls a "merge" script on it:
3292 -------------------------------------------------
3293 $ git-merge-index git-merge-one-file hello.c
3294 -------------------------------------------------
3296 and that is what higher level `git merge -s resolve` is implemented with.
3298 [[pack-files]]
3299 How git stores objects efficiently: pack files
3300 ----------------------------------------------
3302 We've seen how git stores each object in a file named after the
3303 object's SHA1 hash.
3305 Unfortunately this system becomes inefficient once a project has a
3306 lot of objects.  Try this on an old project:
3308 ------------------------------------------------
3309 $ git count-objects
3310 6930 objects, 47620 kilobytes
3311 ------------------------------------------------
3313 The first number is the number of objects which are kept in
3314 individual files.  The second is the amount of space taken up by
3315 those "loose" objects.
3317 You can save space and make git faster by moving these loose objects in
3318 to a "pack file", which stores a group of objects in an efficient
3319 compressed format; the details of how pack files are formatted can be
3320 found in link:technical/pack-format.txt[technical/pack-format.txt].
3322 To put the loose objects into a pack, just run git repack:
3324 ------------------------------------------------
3325 $ git repack
3326 Generating pack...
3327 Done counting 6020 objects.
3328 Deltifying 6020 objects.
3329  100% (6020/6020) done
3330 Writing 6020 objects.
3331  100% (6020/6020) done
3332 Total 6020, written 6020 (delta 4070), reused 0 (delta 0)
3333 Pack pack-3e54ad29d5b2e05838c75df582c65257b8d08e1c created.
3334 ------------------------------------------------
3336 You can then run
3338 ------------------------------------------------
3339 $ git prune
3340 ------------------------------------------------
3342 to remove any of the "loose" objects that are now contained in the
3343 pack.  This will also remove any unreferenced objects (which may be
3344 created when, for example, you use "git reset" to remove a commit).
3345 You can verify that the loose objects are gone by looking at the
3346 .git/objects directory or by running
3348 ------------------------------------------------
3349 $ git count-objects
3350 0 objects, 0 kilobytes
3351 ------------------------------------------------
3353 Although the object files are gone, any commands that refer to those
3354 objects will work exactly as they did before.
3356 The gitlink:git-gc[1] command performs packing, pruning, and more for
3357 you, so is normally the only high-level command you need.
3359 [[dangling-objects]]
3360 Dangling objects
3361 ----------------
3363 The gitlink:git-fsck[1] command will sometimes complain about dangling
3364 objects.  They are not a problem.
3366 The most common cause of dangling objects is that you've rebased a
3367 branch, or you have pulled from somebody else who rebased a branch--see
3368 <<cleaning-up-history>>.  In that case, the old head of the original
3369 branch still exists, as does everything it pointed to. The branch
3370 pointer itself just doesn't, since you replaced it with another one.
3372 There are also other situations that cause dangling objects. For
3373 example, a "dangling blob" may arise because you did a "git add" of a
3374 file, but then, before you actually committed it and made it part of the
3375 bigger picture, you changed something else in that file and committed
3376 that *updated* thing - the old state that you added originally ends up
3377 not being pointed to by any commit or tree, so it's now a dangling blob
3378 object.
3380 Similarly, when the "recursive" merge strategy runs, and finds that
3381 there are criss-cross merges and thus more than one merge base (which is
3382 fairly unusual, but it does happen), it will generate one temporary
3383 midway tree (or possibly even more, if you had lots of criss-crossing
3384 merges and more than two merge bases) as a temporary internal merge
3385 base, and again, those are real objects, but the end result will not end
3386 up pointing to them, so they end up "dangling" in your repository.
3388 Generally, dangling objects aren't anything to worry about. They can
3389 even be very useful: if you screw something up, the dangling objects can
3390 be how you recover your old tree (say, you did a rebase, and realized
3391 that you really didn't want to - you can look at what dangling objects
3392 you have, and decide to reset your head to some old dangling state).
3394 For commits, you can just use:
3396 ------------------------------------------------
3397 $ gitk <dangling-commit-sha-goes-here> --not --all
3398 ------------------------------------------------
3400 This asks for all the history reachable from the given commit but not
3401 from any branch, tag, or other reference.  If you decide it's something
3402 you want, you can always create a new reference to it, e.g.,
3404 ------------------------------------------------
3405 $ git branch recovered-branch <dangling-commit-sha-goes-here>
3406 ------------------------------------------------
3408 For blobs and trees, you can't do the same, but you can still examine
3409 them.  You can just do
3411 ------------------------------------------------
3412 $ git show <dangling-blob/tree-sha-goes-here>
3413 ------------------------------------------------
3415 to show what the contents of the blob were (or, for a tree, basically
3416 what the "ls" for that directory was), and that may give you some idea
3417 of what the operation was that left that dangling object.
3419 Usually, dangling blobs and trees aren't very interesting. They're
3420 almost always the result of either being a half-way mergebase (the blob
3421 will often even have the conflict markers from a merge in it, if you
3422 have had conflicting merges that you fixed up by hand), or simply
3423 because you interrupted a "git fetch" with ^C or something like that,
3424 leaving _some_ of the new objects in the object database, but just
3425 dangling and useless.
3427 Anyway, once you are sure that you're not interested in any dangling 
3428 state, you can just prune all unreachable objects:
3430 ------------------------------------------------
3431 $ git prune
3432 ------------------------------------------------
3434 and they'll be gone. But you should only run "git prune" on a quiescent
3435 repository - it's kind of like doing a filesystem fsck recovery: you
3436 don't want to do that while the filesystem is mounted.
3438 (The same is true of "git-fsck" itself, btw - but since 
3439 git-fsck never actually *changes* the repository, it just reports 
3440 on what it found, git-fsck itself is never "dangerous" to run. 
3441 Running it while somebody is actually changing the repository can cause 
3442 confusing and scary messages, but it won't actually do anything bad. In 
3443 contrast, running "git prune" while somebody is actively changing the 
3444 repository is a *BAD* idea).
3446 [[birdview-on-the-source-code]]
3447 A birds-eye view of Git's source code
3448 -------------------------------------
3450 It is not always easy for new developers to find their way through Git's
3451 source code.  This section gives you a little guidance to show where to
3452 start.
3454 A good place to start is with the contents of the initial commit, with:
3456 ----------------------------------------------------
3457 $ git checkout e83c5163
3458 ----------------------------------------------------
3460 The initial revision lays the foundation for almost everything git has
3461 today, but is small enough to read in one sitting.
3463 Note that terminology has changed since that revision.  For example, the
3464 README in that revision uses the word "changeset" to describe what we
3465 now call a <<def_commit_object,commit>>.
3467 Also, we do not call it "cache" any more, but "index", however, the
3468 file is still called `cache.h`.  Remark: Not much reason to change it now,
3469 especially since there is no good single name for it anyway, because it is
3470 basically _the_ header file which is included by _all_ of Git's C sources.
3472 If you grasp the ideas in that initial commit, you should check out a
3473 more recent version and skim `cache.h`, `object.h` and `commit.h`.
3475 In the early days, Git (in the tradition of UNIX) was a bunch of programs
3476 which were extremely simple, and which you used in scripts, piping the
3477 output of one into another. This turned out to be good for initial
3478 development, since it was easier to test new things.  However, recently
3479 many of these parts have become builtins, and some of the core has been
3480 "libified", i.e. put into libgit.a for performance, portability reasons,
3481 and to avoid code duplication.
3483 By now, you know what the index is (and find the corresponding data
3484 structures in `cache.h`), and that there are just a couple of object types
3485 (blobs, trees, commits and tags) which inherit their common structure from
3486 `struct object`, which is their first member (and thus, you can cast e.g.
3487 `(struct object *)commit` to achieve the _same_ as `&commit->object`, i.e.
3488 get at the object name and flags).
3490 Now is a good point to take a break to let this information sink in.
3492 Next step: get familiar with the object naming.  Read <<naming-commits>>.
3493 There are quite a few ways to name an object (and not only revisions!).
3494 All of these are handled in `sha1_name.c`. Just have a quick look at
3495 the function `get_sha1()`. A lot of the special handling is done by
3496 functions like `get_sha1_basic()` or the likes.
3498 This is just to get you into the groove for the most libified part of Git:
3499 the revision walker.
3501 Basically, the initial version of `git log` was a shell script:
3503 ----------------------------------------------------------------
3504 $ git-rev-list --pretty $(git-rev-parse --default HEAD "$@") | \
3505         LESS=-S ${PAGER:-less}
3506 ----------------------------------------------------------------
3508 What does this mean?
3510 `git-rev-list` is the original version of the revision walker, which
3511 _always_ printed a list of revisions to stdout.  It is still functional,
3512 and needs to, since most new Git programs start out as scripts using
3513 `git-rev-list`.
3515 `git-rev-parse` is not as important any more; it was only used to filter out
3516 options that were relevant for the different plumbing commands that were
3517 called by the script.
3519 Most of what `git-rev-list` did is contained in `revision.c` and
3520 `revision.h`.  It wraps the options in a struct named `rev_info`, which
3521 controls how and what revisions are walked, and more.
3523 The original job of `git-rev-parse` is now taken by the function
3524 `setup_revisions()`, which parses the revisions and the common command line
3525 options for the revision walker. This information is stored in the struct
3526 `rev_info` for later consumption. You can do your own command line option
3527 parsing after calling `setup_revisions()`. After that, you have to call
3528 `prepare_revision_walk()` for initialization, and then you can get the
3529 commits one by one with the function `get_revision()`.
3531 If you are interested in more details of the revision walking process,
3532 just have a look at the first implementation of `cmd_log()`; call
3533 `git-show v1.3.0~155^2~4` and scroll down to that function (note that you
3534 no longer need to call `setup_pager()` directly).
3536 Nowadays, `git log` is a builtin, which means that it is _contained_ in the
3537 command `git`.  The source side of a builtin is
3539 - a function called `cmd_<bla>`, typically defined in `builtin-<bla>.c`,
3540   and declared in `builtin.h`,
3542 - an entry in the `commands[]` array in `git.c`, and
3544 - an entry in `BUILTIN_OBJECTS` in the `Makefile`.
3546 Sometimes, more than one builtin is contained in one source file.  For
3547 example, `cmd_whatchanged()` and `cmd_log()` both reside in `builtin-log.c`,
3548 since they share quite a bit of code.  In that case, the commands which are
3549 _not_ named like the `.c` file in which they live have to be listed in
3550 `BUILT_INS` in the `Makefile`.
3552 `git log` looks more complicated in C than it does in the original script,
3553 but that allows for a much greater flexibility and performance.
3555 Here again it is a good point to take a pause.
3557 Lesson three is: study the code.  Really, it is the best way to learn about
3558 the organization of Git (after you know the basic concepts).
3560 So, think about something which you are interested in, say, "how can I
3561 access a blob just knowing the object name of it?".  The first step is to
3562 find a Git command with which you can do it.  In this example, it is either
3563 `git show` or `git cat-file`.
3565 For the sake of clarity, let's stay with `git cat-file`, because it
3567 - is plumbing, and
3569 - was around even in the initial commit (it literally went only through
3570   some 20 revisions as `cat-file.c`, was renamed to `builtin-cat-file.c`
3571   when made a builtin, and then saw less than 10 versions).
3573 So, look into `builtin-cat-file.c`, search for `cmd_cat_file()` and look what
3574 it does.
3576 ------------------------------------------------------------------
3577         git_config(git_default_config);
3578         if (argc != 3)
3579                 usage("git-cat-file [-t|-s|-e|-p|<type>] <sha1>");
3580         if (get_sha1(argv[2], sha1))
3581                 die("Not a valid object name %s", argv[2]);
3582 ------------------------------------------------------------------
3584 Let's skip over the obvious details; the only really interesting part
3585 here is the call to `get_sha1()`.  It tries to interpret `argv[2]` as an
3586 object name, and if it refers to an object which is present in the current
3587 repository, it writes the resulting SHA-1 into the variable `sha1`.
3589 Two things are interesting here:
3591 - `get_sha1()` returns 0 on _success_.  This might surprise some new
3592   Git hackers, but there is a long tradition in UNIX to return different
3593   negative numbers in case of different errors -- and 0 on success.
3595 - the variable `sha1` in the function signature of `get_sha1()` is `unsigned
3596   char \*`, but is actually expected to be a pointer to `unsigned
3597   char[20]`.  This variable will contain the 160-bit SHA-1 of the given
3598   commit.  Note that whenever a SHA-1 is passed as `unsigned char \*`, it
3599   is the binary representation, as opposed to the ASCII representation in
3600   hex characters, which is passed as `char *`.
3602 You will see both of these things throughout the code.
3604 Now, for the meat:
3606 -----------------------------------------------------------------------------
3607         case 0:
3608                 buf = read_object_with_reference(sha1, argv[1], &size, NULL);
3609 -----------------------------------------------------------------------------
3611 This is how you read a blob (actually, not only a blob, but any type of
3612 object).  To know how the function `read_object_with_reference()` actually
3613 works, find the source code for it (something like `git grep
3614 read_object_with | grep ":[a-z]"` in the git repository), and read
3615 the source.
3617 To find out how the result can be used, just read on in `cmd_cat_file()`:
3619 -----------------------------------
3620         write_or_die(1, buf, size);
3621 -----------------------------------
3623 Sometimes, you do not know where to look for a feature.  In many such cases,
3624 it helps to search through the output of `git log`, and then `git show` the
3625 corresponding commit.
3627 Example: If you know that there was some test case for `git bundle`, but
3628 do not remember where it was (yes, you _could_ `git grep bundle t/`, but that
3629 does not illustrate the point!):
3631 ------------------------
3632 $ git log --no-merges t/
3633 ------------------------
3635 In the pager (`less`), just search for "bundle", go a few lines back,
3636 and see that it is in commit 18449ab0...  Now just copy this object name,
3637 and paste it into the command line
3639 -------------------
3640 $ git show 18449ab0
3641 -------------------
3643 Voila.
3645 Another example: Find out what to do in order to make some script a
3646 builtin:
3648 -------------------------------------------------
3649 $ git log --no-merges --diff-filter=A builtin-*.c
3650 -------------------------------------------------
3652 You see, Git is actually the best tool to find out about the source of Git
3653 itself!
3655 [[glossary]]
3656 include::glossary.txt[]
3658 [[git-quick-start]]
3659 Appendix A: Git Quick Reference
3660 ===============================
3662 This is a quick summary of the major commands; the previous chapters
3663 explain how these work in more detail.
3665 [[quick-creating-a-new-repository]]
3666 Creating a new repository
3667 -------------------------
3669 From a tarball:
3671 -----------------------------------------------
3672 $ tar xzf project.tar.gz
3673 $ cd project
3674 $ git init
3675 Initialized empty Git repository in .git/
3676 $ git add .
3677 $ git commit
3678 -----------------------------------------------
3680 From a remote repository:
3682 -----------------------------------------------
3683 $ git clone git://example.com/pub/project.git
3684 $ cd project
3685 -----------------------------------------------
3687 [[managing-branches]]
3688 Managing branches
3689 -----------------
3691 -----------------------------------------------
3692 $ git branch         # list all local branches in this repo
3693 $ git checkout test  # switch working directory to branch "test"
3694 $ git branch new     # create branch "new" starting at current HEAD
3695 $ git branch -d new  # delete branch "new"
3696 -----------------------------------------------
3698 Instead of basing new branch on current HEAD (the default), use:
3700 -----------------------------------------------
3701 $ git branch new test    # branch named "test"
3702 $ git branch new v2.6.15 # tag named v2.6.15
3703 $ git branch new HEAD^   # commit before the most recent
3704 $ git branch new HEAD^^  # commit before that
3705 $ git branch new test~10 # ten commits before tip of branch "test"
3706 -----------------------------------------------
3708 Create and switch to a new branch at the same time:
3710 -----------------------------------------------
3711 $ git checkout -b new v2.6.15
3712 -----------------------------------------------
3714 Update and examine branches from the repository you cloned from:
3716 -----------------------------------------------
3717 $ git fetch             # update
3718 $ git branch -r         # list
3719   origin/master
3720   origin/next
3721   ...
3722 $ git checkout -b masterwork origin/master
3723 -----------------------------------------------
3725 Fetch a branch from a different repository, and give it a new
3726 name in your repository:
3728 -----------------------------------------------
3729 $ git fetch git://example.com/project.git theirbranch:mybranch
3730 $ git fetch git://example.com/project.git v2.6.15:mybranch
3731 -----------------------------------------------
3733 Keep a list of repositories you work with regularly:
3735 -----------------------------------------------
3736 $ git remote add example git://example.com/project.git
3737 $ git remote                    # list remote repositories
3738 example
3739 origin
3740 $ git remote show example       # get details
3741 * remote example
3742   URL: git://example.com/project.git
3743   Tracked remote branches
3744     master next ...
3745 $ git fetch example             # update branches from example
3746 $ git branch -r                 # list all remote branches
3747 -----------------------------------------------
3750 [[exploring-history]]
3751 Exploring history
3752 -----------------
3754 -----------------------------------------------
3755 $ gitk                      # visualize and browse history
3756 $ git log                   # list all commits
3757 $ git log src/              # ...modifying src/
3758 $ git log v2.6.15..v2.6.16  # ...in v2.6.16, not in v2.6.15
3759 $ git log master..test      # ...in branch test, not in branch master
3760 $ git log test..master      # ...in branch master, but not in test
3761 $ git log test...master     # ...in one branch, not in both
3762 $ git log -S'foo()'         # ...where difference contain "foo()"
3763 $ git log --since="2 weeks ago"
3764 $ git log -p                # show patches as well
3765 $ git show                  # most recent commit
3766 $ git diff v2.6.15..v2.6.16 # diff between two tagged versions
3767 $ git diff v2.6.15..HEAD    # diff with current head
3768 $ git grep "foo()"          # search working directory for "foo()"
3769 $ git grep v2.6.15 "foo()"  # search old tree for "foo()"
3770 $ git show v2.6.15:a.txt    # look at old version of a.txt
3771 -----------------------------------------------
3773 Search for regressions:
3775 -----------------------------------------------
3776 $ git bisect start
3777 $ git bisect bad                # current version is bad
3778 $ git bisect good v2.6.13-rc2   # last known good revision
3779 Bisecting: 675 revisions left to test after this
3780                                 # test here, then:
3781 $ git bisect good               # if this revision is good, or
3782 $ git bisect bad                # if this revision is bad.
3783                                 # repeat until done.
3784 -----------------------------------------------
3786 [[making-changes]]
3787 Making changes
3788 --------------
3790 Make sure git knows who to blame:
3792 ------------------------------------------------
3793 $ cat >>~/.gitconfig <<\EOF
3794 [user]
3795         name = Your Name Comes Here
3796         email = you@yourdomain.example.com
3797 EOF
3798 ------------------------------------------------
3800 Select file contents to include in the next commit, then make the
3801 commit:
3803 -----------------------------------------------
3804 $ git add a.txt    # updated file
3805 $ git add b.txt    # new file
3806 $ git rm c.txt     # old file
3807 $ git commit
3808 -----------------------------------------------
3810 Or, prepare and create the commit in one step:
3812 -----------------------------------------------
3813 $ git commit d.txt # use latest content only of d.txt
3814 $ git commit -a    # use latest content of all tracked files
3815 -----------------------------------------------
3817 [[merging]]
3818 Merging
3819 -------
3821 -----------------------------------------------
3822 $ git merge test   # merge branch "test" into the current branch
3823 $ git pull git://example.com/project.git master
3824                    # fetch and merge in remote branch
3825 $ git pull . test  # equivalent to git merge test
3826 -----------------------------------------------
3828 [[sharing-your-changes]]
3829 Sharing your changes
3830 --------------------
3832 Importing or exporting patches:
3834 -----------------------------------------------
3835 $ git format-patch origin..HEAD # format a patch for each commit
3836                                 # in HEAD but not in origin
3837 $ git am mbox # import patches from the mailbox "mbox"
3838 -----------------------------------------------
3840 Fetch a branch in a different git repository, then merge into the
3841 current branch:
3843 -----------------------------------------------
3844 $ git pull git://example.com/project.git theirbranch
3845 -----------------------------------------------
3847 Store the fetched branch into a local branch before merging into the
3848 current branch:
3850 -----------------------------------------------
3851 $ git pull git://example.com/project.git theirbranch:mybranch
3852 -----------------------------------------------
3854 After creating commits on a local branch, update the remote
3855 branch with your commits:
3857 -----------------------------------------------
3858 $ git push ssh://example.com/project.git mybranch:theirbranch
3859 -----------------------------------------------
3861 When remote and local branch are both named "test":
3863 -----------------------------------------------
3864 $ git push ssh://example.com/project.git test
3865 -----------------------------------------------
3867 Shortcut version for a frequently used remote repository:
3869 -----------------------------------------------
3870 $ git remote add example ssh://example.com/project.git
3871 $ git push example test
3872 -----------------------------------------------
3874 [[repository-maintenance]]
3875 Repository maintenance
3876 ----------------------
3878 Check for corruption:
3880 -----------------------------------------------
3881 $ git fsck
3882 -----------------------------------------------
3884 Recompress, remove unused cruft:
3886 -----------------------------------------------
3887 $ git gc
3888 -----------------------------------------------
3891 [[todo]]
3892 Appendix B: Notes and todo list for this manual
3893 ===============================================
3895 This is a work in progress.
3897 The basic requirements:
3898         - It must be readable in order, from beginning to end, by
3899           someone intelligent with a basic grasp of the unix
3900           commandline, but without any special knowledge of git.  If
3901           necessary, any other prerequisites should be specifically
3902           mentioned as they arise.
3903         - Whenever possible, section headings should clearly describe
3904           the task they explain how to do, in language that requires
3905           no more knowledge than necessary: for example, "importing
3906           patches into a project" rather than "the git-am command"
3908 Think about how to create a clear chapter dependency graph that will
3909 allow people to get to important topics without necessarily reading
3910 everything in between.
3912 Scan Documentation/ for other stuff left out; in particular:
3913         howto's
3914         some of technical/?
3915         hooks
3916         list of commands in gitlink:git[1]
3918 Scan email archives for other stuff left out
3920 Scan man pages to see if any assume more background than this manual
3921 provides.
3923 Simplify beginning by suggesting disconnected head instead of
3924 temporary branch creation?
3926 Add more good examples.  Entire sections of just cookbook examples
3927 might be a good idea; maybe make an "advanced examples" section a
3928 standard end-of-chapter section?
3930 Include cross-references to the glossary, where appropriate.
3932 Document shallow clones?  See draft 1.5.0 release notes for some
3933 documentation.
3935 Add a section on working with other version control systems, including
3936 CVS, Subversion, and just imports of series of release tarballs.
3938 More details on gitweb?
3940 Write a chapter on using plumbing and writing scripts.
3942 Alternates, clone -reference, etc.
3944 git unpack-objects -r for recovery