Fix typo in remote branch example in git user manual
[git/mingw.git] / Documentation / user-manual.txt
blob25695fe77e0cc5224862c5ec22746b2ba685b25d
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
46 to download a copy of an existing repository for a project that you
47 are interested in.  If you don't already have a project in mind, here
48 are some interesting examples:
50 ------------------------------------------------
51         # git itself (approx. 10MB download):
52 $ git clone git://git.kernel.org/pub/scm/git/git.git
53         # the linux kernel (approx. 150MB download):
54 $ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git
55 ------------------------------------------------
57 The initial clone may be time-consuming for a large project, but you
58 will only need to clone once.
60 The clone command creates a new directory named after the project
61 ("git" or "linux-2.6" in the examples above).  After you cd into this
62 directory, you will see that it contains a copy of the project files,
63 together with a special top-level directory named ".git", which
64 contains all the information about the history of the project.
66 In most of the following, examples will be taken from one of the two
67 repositories above.
69 [[how-to-check-out]]
70 How to check out a different version of a project
71 -------------------------------------------------
73 Git is best thought of as a tool for storing the history of a
74 collection of files.  It stores the history as a compressed
75 collection of interrelated snapshots (versions) of the project's
76 contents.
78 A single git repository may contain multiple branches.  It keeps track
79 of them by keeping a list of <<def_head,heads>> which reference the
80 latest version on each branch; the gitlink:git-branch[1] command shows
81 you the list of branch heads:
83 ------------------------------------------------
84 $ git branch
85 * master
86 ------------------------------------------------
88 A freshly cloned repository contains a single branch head, by default
89 named "master", with the working directory initialized to the state of
90 the project referred to by that branch head.
92 Most projects also use <<def_tag,tags>>.  Tags, like heads, are
93 references into the project's history, and can be listed using the
94 gitlink:git-tag[1] command:
96 ------------------------------------------------
97 $ git tag -l
98 v2.6.11
99 v2.6.11-tree
100 v2.6.12
101 v2.6.12-rc2
102 v2.6.12-rc3
103 v2.6.12-rc4
104 v2.6.12-rc5
105 v2.6.12-rc6
106 v2.6.13
108 ------------------------------------------------
110 Tags are expected to always point at the same version of a project,
111 while heads are expected to advance as development progresses.
113 Create a new branch head pointing to one of these versions and check it
114 out using gitlink:git-checkout[1]:
116 ------------------------------------------------
117 $ git checkout -b new v2.6.13
118 ------------------------------------------------
120 The working directory then reflects the contents that the project had
121 when it was tagged v2.6.13, and gitlink:git-branch[1] shows two
122 branches, with an asterisk marking the currently checked-out branch:
124 ------------------------------------------------
125 $ git branch
126   master
127 * new
128 ------------------------------------------------
130 If you decide that you'd rather see version 2.6.17, you can modify
131 the current branch to point at v2.6.17 instead, with
133 ------------------------------------------------
134 $ git reset --hard v2.6.17
135 ------------------------------------------------
137 Note that if the current branch head was your only reference to a
138 particular point in history, then resetting that branch may leave you
139 with no way to find the history it used to point to; so use this command
140 carefully.
142 [[understanding-commits]]
143 Understanding History: Commits
144 ------------------------------
146 Every change in the history of a project is represented by a commit.
147 The gitlink:git-show[1] command shows the most recent commit on the
148 current branch:
150 ------------------------------------------------
151 $ git show
152 commit 2b5f6dcce5bf94b9b119e9ed8d537098ec61c3d2
153 Author: Jamal Hadi Salim <hadi@cyberus.ca>
154 Date:   Sat Dec 2 22:22:25 2006 -0800
156     [XFRM]: Fix aevent structuring to be more complete.
157     
158     aevents can not uniquely identify an SA. We break the ABI with this
159     patch, but consensus is that since it is not yet utilized by any
160     (known) application then it is fine (better do it now than later).
161     
162     Signed-off-by: Jamal Hadi Salim <hadi@cyberus.ca>
163     Signed-off-by: David S. Miller <davem@davemloft.net>
165 diff --git a/Documentation/networking/xfrm_sync.txt b/Documentation/networking/xfrm_sync.txt
166 index 8be626f..d7aac9d 100644
167 --- a/Documentation/networking/xfrm_sync.txt
168 +++ b/Documentation/networking/xfrm_sync.txt
169 @@ -47,10 +47,13 @@ aevent_id structure looks like:
171     struct xfrm_aevent_id {
172               struct xfrm_usersa_id           sa_id;
173 +             xfrm_address_t                  saddr;
174               __u32                           flags;
175 +             __u32                           reqid;
176     };
178 ------------------------------------------------
180 As you can see, a commit shows who made the latest change, what they
181 did, and why.
183 Every commit has a 40-hexdigit id, sometimes called the "object name" or the
184 "SHA1 id", shown on the first line of the "git show" output.  You can usually
185 refer to a commit by a shorter name, such as a tag or a branch name, but this
186 longer name can also be useful.  Most importantly, it is a globally unique
187 name for this commit: so if you tell somebody else the object name (for
188 example in email), then you are guaranteed that name will refer to the same
189 commit in their repository that it does in yours (assuming their repository
190 has that commit at all).  Since the object name is computed as a hash over the
191 contents of the commit, you are guaranteed that the commit can never change
192 without its name also changing.
194 In fact, in <<git-internals>> we shall see that everything stored in git
195 history, including file data and directory contents, is stored in an object
196 with a name that is a hash of its contents.
198 [[understanding-reachability]]
199 Understanding history: commits, parents, and reachability
200 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
202 Every commit (except the very first commit in a project) also has a
203 parent commit which shows what happened before this commit.
204 Following the chain of parents will eventually take you back to the
205 beginning of the project.
207 However, the commits do not form a simple list; git allows lines of
208 development to diverge and then reconverge, and the point where two
209 lines of development reconverge is called a "merge".  The commit
210 representing a merge can therefore have more than one parent, with
211 each parent representing the most recent commit on one of the lines
212 of development leading to that point.
214 The best way to see how this works is using the gitlink:gitk[1]
215 command; running gitk now on a git repository and looking for merge
216 commits will help understand how the git organizes history.
218 In the following, we say that commit X is "reachable" from commit Y
219 if commit X is an ancestor of commit Y.  Equivalently, you could say
220 that Y is a descendent of X, or that there is a chain of parents
221 leading from commit Y to commit X.
223 [[history-diagrams]]
224 Understanding history: History diagrams
225 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
227 We will sometimes represent git history using diagrams like the one
228 below.  Commits are shown as "o", and the links between them with
229 lines drawn with - / and \.  Time goes left to right:
232 ................................................
233          o--o--o <-- Branch A
234         /
235  o--o--o <-- master
236         \
237          o--o--o <-- Branch B
238 ................................................
240 If we need to talk about a particular commit, the character "o" may
241 be replaced with another letter or number.
243 [[what-is-a-branch]]
244 Understanding history: What is a branch?
245 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
247 When we need to be precise, we will use the word "branch" to mean a line
248 of development, and "branch head" (or just "head") to mean a reference
249 to the most recent commit on a branch.  In the example above, the branch
250 head named "A" is a pointer to one particular commit, but we refer to
251 the line of three commits leading up to that point as all being part of
252 "branch A".
254 However, when no confusion will result, we often just use the term
255 "branch" both for branches and for branch heads.
257 [[manipulating-branches]]
258 Manipulating branches
259 ---------------------
261 Creating, deleting, and modifying branches is quick and easy; here's
262 a summary of the commands:
264 git branch::
265         list all branches
266 git branch <branch>::
267         create a new branch named <branch>, referencing the same
268         point in history as the current branch
269 git branch <branch> <start-point>::
270         create a new branch named <branch>, referencing
271         <start-point>, which may be specified any way you like,
272         including using a branch name or a tag name
273 git branch -d <branch>::
274         delete the branch <branch>; if the branch you are deleting
275         points to a commit which is not reachable from the current
276         branch, this command will fail with a warning.
277 git branch -D <branch>::
278         even if the branch points to a commit not reachable
279         from the current branch, you may know that that commit
280         is still reachable from some other branch or tag.  In that
281         case it is safe to use this command to force git to delete
282         the branch.
283 git checkout <branch>::
284         make the current branch <branch>, updating the working
285         directory to reflect the version referenced by <branch>
286 git checkout -b <new> <start-point>::
287         create a new branch <new> referencing <start-point>, and
288         check it out.
290 The special symbol "HEAD" can always be used to refer to the current
291 branch.  In fact, git uses a file named "HEAD" in the .git directory to
292 remember which branch is current:
294 ------------------------------------------------
295 $ cat .git/HEAD
296 ref: refs/heads/master
297 ------------------------------------------------
299 [[detached-head]]
300 Examining an old version without creating a new branch
301 ------------------------------------------------------
303 The git-checkout command normally expects a branch head, but will also
304 accept an arbitrary commit; for example, you can check out the commit
305 referenced by a tag:
307 ------------------------------------------------
308 $ git checkout v2.6.17
309 Note: moving to "v2.6.17" which isn't a local branch
310 If you want to create a new branch from this checkout, you may do so
311 (now or later) by using -b with the checkout command again. Example:
312   git checkout -b <new_branch_name>
313 HEAD is now at 427abfa... Linux v2.6.17
314 ------------------------------------------------
316 The HEAD then refers to the SHA1 of the commit instead of to a branch,
317 and git branch shows that you are no longer on a branch:
319 ------------------------------------------------
320 $ cat .git/HEAD
321 427abfa28afedffadfca9dd8b067eb6d36bac53f
322 $ git branch
323 * (no branch)
324   master
325 ------------------------------------------------
327 In this case we say that the HEAD is "detached".
329 This is an easy way to check out a particular version without having to
330 make up a name for the new branch.   You can still create a new branch
331 (or tag) for this version later if you decide to.
333 [[examining-remote-branches]]
334 Examining branches from a remote repository
335 -------------------------------------------
337 The "master" branch that was created at the time you cloned is a copy
338 of the HEAD in the repository that you cloned from.  That repository
339 may also have had other branches, though, and your local repository
340 keeps branches which track each of those remote branches, which you
341 can view using the "-r" option to gitlink:git-branch[1]:
343 ------------------------------------------------
344 $ git branch -r
345   origin/HEAD
346   origin/html
347   origin/maint
348   origin/man
349   origin/master
350   origin/next
351   origin/pu
352   origin/todo
353 ------------------------------------------------
355 You cannot check out these remote-tracking branches, but you can
356 examine them on a branch of your own, just as you would a tag:
358 ------------------------------------------------
359 $ git checkout -b my-todo-copy origin/todo
360 ------------------------------------------------
362 Note that the name "origin" is just the name that git uses by default
363 to refer to the repository that you cloned from.
365 [[how-git-stores-references]]
366 Naming branches, tags, and other references
367 -------------------------------------------
369 Branches, remote-tracking branches, and tags are all references to
370 commits.  All references are named with a slash-separated path name
371 starting with "refs"; the names we've been using so far are actually
372 shorthand:
374         - The branch "test" is short for "refs/heads/test".
375         - The tag "v2.6.18" is short for "refs/tags/v2.6.18".
376         - "origin/master" is short for "refs/remotes/origin/master".
378 The full name is occasionally useful if, for example, there ever
379 exists a tag and a branch with the same name.
381 As another useful shortcut, the "HEAD" of a repository can be referred
382 to just using the name of that repository.  So, for example, "origin"
383 is usually a shortcut for the HEAD branch in the repository "origin".
385 For the complete list of paths which git checks for references, and
386 the order it uses to decide which to choose when there are multiple
387 references with the same shorthand name, see the "SPECIFYING
388 REVISIONS" section of gitlink:git-rev-parse[1].
390 [[Updating-a-repository-with-git-fetch]]
391 Updating a repository with git fetch
392 ------------------------------------
394 Eventually the developer cloned from will do additional work in her
395 repository, creating new commits and advancing the branches to point
396 at the new commits.
398 The command "git fetch", with no arguments, will update all of the
399 remote-tracking branches to the latest version found in her
400 repository.  It will not touch any of your own branches--not even the
401 "master" branch that was created for you on clone.
403 [[fetching-branches]]
404 Fetching branches from other repositories
405 -----------------------------------------
407 You can also track branches from repositories other than the one you
408 cloned from, using gitlink:git-remote[1]:
410 -------------------------------------------------
411 $ git remote add linux-nfs git://linux-nfs.org/pub/nfs-2.6.git
412 $ git fetch linux-nfs
413 * refs/remotes/linux-nfs/master: storing branch 'master' ...
414   commit: bf81b46
415 -------------------------------------------------
417 New remote-tracking branches will be stored under the shorthand name
418 that you gave "git remote add", in this case linux-nfs:
420 -------------------------------------------------
421 $ git branch -r
422 linux-nfs/master
423 origin/master
424 -------------------------------------------------
426 If you run "git fetch <remote>" later, the tracking branches for the
427 named <remote> will be updated.
429 If you examine the file .git/config, you will see that git has added
430 a new stanza:
432 -------------------------------------------------
433 $ cat .git/config
435 [remote "linux-nfs"]
436         url = git://linux-nfs.org/pub/nfs-2.6.git
437         fetch = +refs/heads/*:refs/remotes/linux-nfs/*
439 -------------------------------------------------
441 This is what causes git to track the remote's branches; you may modify
442 or delete these configuration options by editing .git/config with a
443 text editor.  (See the "CONFIGURATION FILE" section of
444 gitlink:git-config[1] for details.)
446 [[exploring-git-history]]
447 Exploring git history
448 =====================
450 Git is best thought of as a tool for storing the history of a
451 collection of files.  It does this by storing compressed snapshots of
452 the contents of a file heirarchy, together with "commits" which show
453 the relationships between these snapshots.
455 Git provides extremely flexible and fast tools for exploring the
456 history of a project.
458 We start with one specialized tool that is useful for finding the
459 commit that introduced a bug into a project.
461 [[using-bisect]]
462 How to use bisect to find a regression
463 --------------------------------------
465 Suppose version 2.6.18 of your project worked, but the version at
466 "master" crashes.  Sometimes the best way to find the cause of such a
467 regression is to perform a brute-force search through the project's
468 history to find the particular commit that caused the problem.  The
469 gitlink:git-bisect[1] command can help you do this:
471 -------------------------------------------------
472 $ git bisect start
473 $ git bisect good v2.6.18
474 $ git bisect bad master
475 Bisecting: 3537 revisions left to test after this
476 [65934a9a028b88e83e2b0f8b36618fe503349f8e] BLOCK: Make USB storage depend on SCSI rather than selecting it [try #6]
477 -------------------------------------------------
479 If you run "git branch" at this point, you'll see that git has
480 temporarily moved you to a new branch named "bisect".  This branch
481 points to a commit (with commit id 65934...) that is reachable from
482 v2.6.19 but not from v2.6.18.  Compile and test it, and see whether
483 it crashes.  Assume it does crash.  Then:
485 -------------------------------------------------
486 $ git bisect bad
487 Bisecting: 1769 revisions left to test after this
488 [7eff82c8b1511017ae605f0c99ac275a7e21b867] i2c-core: Drop useless bitmaskings
489 -------------------------------------------------
491 checks out an older version.  Continue like this, telling git at each
492 stage whether the version it gives you is good or bad, and notice
493 that the number of revisions left to test is cut approximately in
494 half each time.
496 After about 13 tests (in this case), it will output the commit id of
497 the guilty commit.  You can then examine the commit with
498 gitlink:git-show[1], find out who wrote it, and mail them your bug
499 report with the commit id.  Finally, run
501 -------------------------------------------------
502 $ git bisect reset
503 -------------------------------------------------
505 to return you to the branch you were on before and delete the
506 temporary "bisect" branch.
508 Note that the version which git-bisect checks out for you at each
509 point is just a suggestion, and you're free to try a different
510 version if you think it would be a good idea.  For example,
511 occasionally you may land on a commit that broke something unrelated;
514 -------------------------------------------------
515 $ git bisect visualize
516 -------------------------------------------------
518 which will run gitk and label the commit it chose with a marker that
519 says "bisect".  Chose a safe-looking commit nearby, note its commit
520 id, and check it out with:
522 -------------------------------------------------
523 $ git reset --hard fb47ddb2db...
524 -------------------------------------------------
526 then test, run "bisect good" or "bisect bad" as appropriate, and
527 continue.
529 [[naming-commits]]
530 Naming commits
531 --------------
533 We have seen several ways of naming commits already:
535         - 40-hexdigit object name
536         - branch name: refers to the commit at the head of the given
537           branch
538         - tag name: refers to the commit pointed to by the given tag
539           (we've seen branches and tags are special cases of
540           <<how-git-stores-references,references>>).
541         - HEAD: refers to the head of the current branch
543 There are many more; see the "SPECIFYING REVISIONS" section of the
544 gitlink:git-rev-parse[1] man page for the complete list of ways to
545 name revisions.  Some examples:
547 -------------------------------------------------
548 $ git show fb47ddb2 # the first few characters of the object name
549                     # are usually enough to specify it uniquely
550 $ git show HEAD^    # the parent of the HEAD commit
551 $ git show HEAD^^   # the grandparent
552 $ git show HEAD~4   # the great-great-grandparent
553 -------------------------------------------------
555 Recall that merge commits may have more than one parent; by default,
556 ^ and ~ follow the first parent listed in the commit, but you can
557 also choose:
559 -------------------------------------------------
560 $ git show HEAD^1   # show the first parent of HEAD
561 $ git show HEAD^2   # show the second parent of HEAD
562 -------------------------------------------------
564 In addition to HEAD, there are several other special names for
565 commits:
567 Merges (to be discussed later), as well as operations such as
568 git-reset, which change the currently checked-out commit, generally
569 set ORIG_HEAD to the value HEAD had before the current operation.
571 The git-fetch operation always stores the head of the last fetched
572 branch in FETCH_HEAD.  For example, if you run git fetch without
573 specifying a local branch as the target of the operation
575 -------------------------------------------------
576 $ git fetch git://example.com/proj.git theirbranch
577 -------------------------------------------------
579 the fetched commits will still be available from FETCH_HEAD.
581 When we discuss merges we'll also see the special name MERGE_HEAD,
582 which refers to the other branch that we're merging in to the current
583 branch.
585 The gitlink:git-rev-parse[1] command is a low-level command that is
586 occasionally useful for translating some name for a commit to the object
587 name for that commit:
589 -------------------------------------------------
590 $ git rev-parse origin
591 e05db0fd4f31dde7005f075a84f96b360d05984b
592 -------------------------------------------------
594 [[creating-tags]]
595 Creating tags
596 -------------
598 We can also create a tag to refer to a particular commit; after
599 running
601 -------------------------------------------------
602 $ git tag stable-1 1b2e1d63ff
603 -------------------------------------------------
605 You can use stable-1 to refer to the commit 1b2e1d63ff.
607 This creates a "lightweight" tag.  If you would also like to include a
608 comment with the tag, and possibly sign it cryptographically, then you
609 should create a tag object instead; see the gitlink:git-tag[1] man page
610 for details.
612 [[browsing-revisions]]
613 Browsing revisions
614 ------------------
616 The gitlink:git-log[1] command can show lists of commits.  On its
617 own, it shows all commits reachable from the parent commit; but you
618 can also make more specific requests:
620 -------------------------------------------------
621 $ git log v2.5..        # commits since (not reachable from) v2.5
622 $ git log test..master  # commits reachable from master but not test
623 $ git log master..test  # ...reachable from test but not master
624 $ git log master...test # ...reachable from either test or master,
625                         #    but not both
626 $ git log --since="2 weeks ago" # commits from the last 2 weeks
627 $ git log Makefile      # commits which modify Makefile
628 $ git log fs/           # ... which modify any file under fs/
629 $ git log -S'foo()'     # commits which add or remove any file data
630                         # matching the string 'foo()'
631 -------------------------------------------------
633 And of course you can combine all of these; the following finds
634 commits since v2.5 which touch the Makefile or any file under fs:
636 -------------------------------------------------
637 $ git log v2.5.. Makefile fs/
638 -------------------------------------------------
640 You can also ask git log to show patches:
642 -------------------------------------------------
643 $ git log -p
644 -------------------------------------------------
646 See the "--pretty" option in the gitlink:git-log[1] man page for more
647 display options.
649 Note that git log starts with the most recent commit and works
650 backwards through the parents; however, since git history can contain
651 multiple independent lines of development, the particular order that
652 commits are listed in may be somewhat arbitrary.
654 [[generating-diffs]]
655 Generating diffs
656 ----------------
658 You can generate diffs between any two versions using
659 gitlink:git-diff[1]:
661 -------------------------------------------------
662 $ git diff master..test
663 -------------------------------------------------
665 Sometimes what you want instead is a set of patches:
667 -------------------------------------------------
668 $ git format-patch master..test
669 -------------------------------------------------
671 will generate a file with a patch for each commit reachable from test
672 but not from master.  Note that if master also has commits which are
673 not reachable from test, then the combined result of these patches
674 will not be the same as the diff produced by the git-diff example.
676 [[viewing-old-file-versions]]
677 Viewing old file versions
678 -------------------------
680 You can always view an old version of a file by just checking out the
681 correct revision first.  But sometimes it is more convenient to be
682 able to view an old version of a single file without checking
683 anything out; this command does that:
685 -------------------------------------------------
686 $ git show v2.5:fs/locks.c
687 -------------------------------------------------
689 Before the colon may be anything that names a commit, and after it
690 may be any path to a file tracked by git.
692 [[history-examples]]
693 Examples
694 --------
696 [[counting-commits-on-a-branch]]
697 Counting the number of commits on a branch
698 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
700 Suppose you want to know how many commits you've made on "mybranch"
701 since it diverged from "origin":
703 -------------------------------------------------
704 $ git log --pretty=oneline origin..mybranch | wc -l
705 -------------------------------------------------
707 Alternatively, you may often see this sort of thing done with the
708 lower-level command gitlink:git-rev-list[1], which just lists the SHA1's
709 of all the given commits:
711 -------------------------------------------------
712 $ git rev-list origin..mybranch | wc -l
713 -------------------------------------------------
715 [[checking-for-equal-branches]]
716 Check whether two branches point at the same history
717 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
719 Suppose you want to check whether two branches point at the same point
720 in history.
722 -------------------------------------------------
723 $ git diff origin..master
724 -------------------------------------------------
726 will tell you whether the contents of the project are the same at the
727 two branches; in theory, however, it's possible that the same project
728 contents could have been arrived at by two different historical
729 routes.  You could compare the object names:
731 -------------------------------------------------
732 $ git rev-list origin
733 e05db0fd4f31dde7005f075a84f96b360d05984b
734 $ git rev-list master
735 e05db0fd4f31dde7005f075a84f96b360d05984b
736 -------------------------------------------------
738 Or you could recall that the ... operator selects all commits
739 contained reachable from either one reference or the other but not
740 both: so
742 -------------------------------------------------
743 $ git log origin...master
744 -------------------------------------------------
746 will return no commits when the two branches are equal.
748 [[finding-tagged-descendants]]
749 Find first tagged version including a given fix
750 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
752 Suppose you know that the commit e05db0fd fixed a certain problem.
753 You'd like to find the earliest tagged release that contains that
754 fix.
756 Of course, there may be more than one answer--if the history branched
757 after commit e05db0fd, then there could be multiple "earliest" tagged
758 releases.
760 You could just visually inspect the commits since e05db0fd:
762 -------------------------------------------------
763 $ gitk e05db0fd..
764 -------------------------------------------------
766 Or you can use gitlink:git-name-rev[1], which will give the commit a
767 name based on any tag it finds pointing to one of the commit's
768 descendants:
770 -------------------------------------------------
771 $ git name-rev --tags e05db0fd
772 e05db0fd tags/v1.5.0-rc1^0~23
773 -------------------------------------------------
775 The gitlink:git-describe[1] command does the opposite, naming the
776 revision using a tag on which the given commit is based:
778 -------------------------------------------------
779 $ git describe e05db0fd
780 v1.5.0-rc0-260-ge05db0f
781 -------------------------------------------------
783 but that may sometimes help you guess which tags might come after the
784 given commit.
786 If you just want to verify whether a given tagged version contains a
787 given commit, you could use gitlink:git-merge-base[1]:
789 -------------------------------------------------
790 $ git merge-base e05db0fd v1.5.0-rc1
791 e05db0fd4f31dde7005f075a84f96b360d05984b
792 -------------------------------------------------
794 The merge-base command finds a common ancestor of the given commits,
795 and always returns one or the other in the case where one is a
796 descendant of the other; so the above output shows that e05db0fd
797 actually is an ancestor of v1.5.0-rc1.
799 Alternatively, note that
801 -------------------------------------------------
802 $ git log v1.5.0-rc1..e05db0fd
803 -------------------------------------------------
805 will produce empty output if and only if v1.5.0-rc1 includes e05db0fd,
806 because it outputs only commits that are not reachable from v1.5.0-rc1.
808 As yet another alternative, the gitlink:git-show-branch[1] command lists
809 the commits reachable from its arguments with a display on the left-hand
810 side that indicates which arguments that commit is reachable from.  So,
811 you can run something like
813 -------------------------------------------------
814 $ git show-branch e05db0fd v1.5.0-rc0 v1.5.0-rc1 v1.5.0-rc2
815 ! [e05db0fd] Fix warnings in sha1_file.c - use C99 printf format if
816 available
817  ! [v1.5.0-rc0] GIT v1.5.0 preview
818   ! [v1.5.0-rc1] GIT v1.5.0-rc1
819    ! [v1.5.0-rc2] GIT v1.5.0-rc2
821 -------------------------------------------------
823 then search for a line that looks like
825 -------------------------------------------------
826 + ++ [e05db0fd] Fix warnings in sha1_file.c - use C99 printf format if
827 available
828 -------------------------------------------------
830 Which shows that e05db0fd is reachable from itself, from v1.5.0-rc1, and
831 from v1.5.0-rc2, but not from v1.5.0-rc0.
833 [[showing-commits-unique-to-a-branch]]
834 Showing commits unique to a given branch
835 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
837 Suppose you would like to see all the commits reachable from the branch
838 head named "master" but not from any other head in your repository.
840 We can list all the heads in this repository with
841 gitlink:git-show-ref[1]:
843 -------------------------------------------------
844 $ git show-ref --heads
845 bf62196b5e363d73353a9dcf094c59595f3153b7 refs/heads/core-tutorial
846 db768d5504c1bb46f63ee9d6e1772bd047e05bf9 refs/heads/maint
847 a07157ac624b2524a059a3414e99f6f44bebc1e7 refs/heads/master
848 24dbc180ea14dc1aebe09f14c8ecf32010690627 refs/heads/tutorial-2
849 1e87486ae06626c2f31eaa63d26fc0fd646c8af2 refs/heads/tutorial-fixes
850 -------------------------------------------------
852 We can get just the branch-head names, and remove "master", with
853 the help of the standard utilities cut and grep:
855 -------------------------------------------------
856 $ git show-ref --heads | cut -d' ' -f2 | grep -v '^refs/heads/master'
857 refs/heads/core-tutorial
858 refs/heads/maint
859 refs/heads/tutorial-2
860 refs/heads/tutorial-fixes
861 -------------------------------------------------
863 And then we can ask to see all the commits reachable from master
864 but not from these other heads:
866 -------------------------------------------------
867 $ gitk master --not $( git show-ref --heads | cut -d' ' -f2 |
868                                 grep -v '^refs/heads/master' )
869 -------------------------------------------------
871 Obviously, endless variations are possible; for example, to see all
872 commits reachable from some head but not from any tag in the repository:
874 -------------------------------------------------
875 $ gitk $( git show-ref --heads ) --not  $( git show-ref --tags )
876 -------------------------------------------------
878 (See gitlink:git-rev-parse[1] for explanations of commit-selecting
879 syntax such as `--not`.)
881 [[making-a-release]]
882 Creating a changelog and tarball for a software release
883 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
885 The gitlink:git-archive[1] command can create a tar or zip archive from
886 any version of a project; for example:
888 -------------------------------------------------
889 $ git archive --format=tar --prefix=project/ HEAD | gzip >latest.tar.gz
890 -------------------------------------------------
892 will use HEAD to produce a tar archive in which each filename is
893 preceded by "prefix/".
895 If you're releasing a new version of a software project, you may want
896 to simultaneously make a changelog to include in the release
897 announcement.
899 Linus Torvalds, for example, makes new kernel releases by tagging them,
900 then running:
902 -------------------------------------------------
903 $ release-script 2.6.12 2.6.13-rc6 2.6.13-rc7
904 -------------------------------------------------
906 where release-script is a shell script that looks like:
908 -------------------------------------------------
909 #!/bin/sh
910 stable="$1"
911 last="$2"
912 new="$3"
913 echo "# git tag v$new"
914 echo "git archive --prefix=linux-$new/ v$new | gzip -9 > ../linux-$new.tar.gz"
915 echo "git diff v$stable v$new | gzip -9 > ../patch-$new.gz"
916 echo "git log --no-merges v$new ^v$last > ../ChangeLog-$new"
917 echo "git shortlog --no-merges v$new ^v$last > ../ShortLog"
918 echo "git diff --stat --summary -M v$last v$new > ../diffstat-$new"
919 -------------------------------------------------
921 and then he just cut-and-pastes the output commands after verifying that
922 they look OK.
924 Finding commits referencing a file with given content
925 -----------------------------------------------------
927 Somebody hands you a copy of a file, and asks which commits modified a
928 file such that it contained the given content either before or after the
929 commit.  You can find out with this:
931 -------------------------------------------------
932 $  git log --raw -r --abbrev=40 --pretty=oneline -- filename |
933         grep -B 1 `git hash-object filename`
934 -------------------------------------------------
936 Figuring out why this works is left as an exercise to the (advanced)
937 student.  The gitlink:git-log[1], gitlink:git-diff-tree[1], and
938 gitlink:git-hash-object[1] man pages may prove helpful.
940 [[Developing-with-git]]
941 Developing with git
942 ===================
944 [[telling-git-your-name]]
945 Telling git your name
946 ---------------------
948 Before creating any commits, you should introduce yourself to git.  The
949 easiest way to do so is to make sure the following lines appear in a
950 file named .gitconfig in your home directory:
952 ------------------------------------------------
953 [user]
954         name = Your Name Comes Here
955         email = you@yourdomain.example.com
956 ------------------------------------------------
958 (See the "CONFIGURATION FILE" section of gitlink:git-config[1] for
959 details on the configuration file.)
962 [[creating-a-new-repository]]
963 Creating a new repository
964 -------------------------
966 Creating a new repository from scratch is very easy:
968 -------------------------------------------------
969 $ mkdir project
970 $ cd project
971 $ git init
972 -------------------------------------------------
974 If you have some initial content (say, a tarball):
976 -------------------------------------------------
977 $ tar -xzvf project.tar.gz
978 $ cd project
979 $ git init
980 $ git add . # include everything below ./ in the first commit:
981 $ git commit
982 -------------------------------------------------
984 [[how-to-make-a-commit]]
985 How to make a commit
986 --------------------
988 Creating a new commit takes three steps:
990         1. Making some changes to the working directory using your
991            favorite editor.
992         2. Telling git about your changes.
993         3. Creating the commit using the content you told git about
994            in step 2.
996 In practice, you can interleave and repeat steps 1 and 2 as many
997 times as you want: in order to keep track of what you want committed
998 at step 3, git maintains a snapshot of the tree's contents in a
999 special staging area called "the index."
1001 At the beginning, the content of the index will be identical to
1002 that of the HEAD.  The command "git diff --cached", which shows
1003 the difference between the HEAD and the index, should therefore
1004 produce no output at that point.
1006 Modifying the index is easy:
1008 To update the index with the new contents of a modified file, use
1010 -------------------------------------------------
1011 $ git add path/to/file
1012 -------------------------------------------------
1014 To add the contents of a new file to the index, use
1016 -------------------------------------------------
1017 $ git add path/to/file
1018 -------------------------------------------------
1020 To remove a file from the index and from the working tree,
1022 -------------------------------------------------
1023 $ git rm path/to/file
1024 -------------------------------------------------
1026 After each step you can verify that
1028 -------------------------------------------------
1029 $ git diff --cached
1030 -------------------------------------------------
1032 always shows the difference between the HEAD and the index file--this
1033 is what you'd commit if you created the commit now--and that
1035 -------------------------------------------------
1036 $ git diff
1037 -------------------------------------------------
1039 shows the difference between the working tree and the index file.
1041 Note that "git add" always adds just the current contents of a file
1042 to the index; further changes to the same file will be ignored unless
1043 you run git-add on the file again.
1045 When you're ready, just run
1047 -------------------------------------------------
1048 $ git commit
1049 -------------------------------------------------
1051 and git will prompt you for a commit message and then create the new
1052 commit.  Check to make sure it looks like what you expected with
1054 -------------------------------------------------
1055 $ git show
1056 -------------------------------------------------
1058 As a special shortcut,
1059                 
1060 -------------------------------------------------
1061 $ git commit -a
1062 -------------------------------------------------
1064 will update the index with any files that you've modified or removed
1065 and create a commit, all in one step.
1067 A number of commands are useful for keeping track of what you're
1068 about to commit:
1070 -------------------------------------------------
1071 $ git diff --cached # difference between HEAD and the index; what
1072                     # would be commited if you ran "commit" now.
1073 $ git diff          # difference between the index file and your
1074                     # working directory; changes that would not
1075                     # be included if you ran "commit" now.
1076 $ git diff HEAD     # difference between HEAD and working tree; what
1077                     # would be committed if you ran "commit -a" now.
1078 $ git status        # a brief per-file summary of the above.
1079 -------------------------------------------------
1081 [[creating-good-commit-messages]]
1082 Creating good commit messages
1083 -----------------------------
1085 Though not required, it's a good idea to begin the commit message
1086 with a single short (less than 50 character) line summarizing the
1087 change, followed by a blank line and then a more thorough
1088 description.  Tools that turn commits into email, for example, use
1089 the first line on the Subject line and the rest of the commit in the
1090 body.
1092 [[ignoring-files]]
1093 Ignoring files
1094 --------------
1096 A project will often generate files that you do 'not' want to track with git.
1097 This typically includes files generated by a build process or temporary
1098 backup files made by your editor. Of course, 'not' tracking files with git
1099 is just a matter of 'not' calling "`git add`" on them. But it quickly becomes
1100 annoying to have these untracked files lying around; e.g. they make
1101 "`git add .`" and "`git commit -a`" practically useless, and they keep
1102 showing up in the output of "`git status`", etc.
1104 Git therefore provides "exclude patterns" for telling git which files to
1105 actively ignore. Exclude patterns are thoroughly explained in the
1106 gitlink:gitignore[5] manual page, but the heart of the concept is simply
1107 a list of files which git should ignore. Entries in the list may contain
1108 globs to specify multiple files, or may be prefixed by "`!`" to
1109 explicitly include (un-ignore) a previously excluded (ignored) file
1110 (i.e. later exclude patterns override earlier ones).  The following
1111 example should illustrate such patterns:
1113 -------------------------------------------------
1114 # Lines starting with '#' are considered comments.
1115 # Ignore foo.txt.
1116 foo.txt
1117 # Ignore (generated) html files,
1118 *.html
1119 # except foo.html which is maintained by hand.
1120 !foo.html
1121 # Ignore objects and archives.
1122 *.[oa]
1123 -------------------------------------------------
1125 The next question is where to put these exclude patterns so that git can
1126 find them. Git looks for exclude patterns in the following files:
1128 `.gitignore` files in your working tree:::
1129            You may store multiple `.gitignore` files at various locations in your
1130            working tree. Each `.gitignore` file is applied to the directory where
1131            it's located, including its subdirectories. Furthermore, the
1132            `.gitignore` files can be tracked like any other files in your working
1133            tree; just do a "`git add .gitignore`" and commit. `.gitignore` is
1134            therefore the right place to put exclude patterns that are meant to
1135            be shared between all project participants, such as build output files
1136            (e.g. `\*.o`), etc.
1137 `.git/info/exclude` in your repo:::
1138            Exclude patterns in this file are applied to the working tree as a
1139            whole. Since the file is not located in your working tree, it does
1140            not follow push/pull/clone like `.gitignore` can do. This is therefore
1141            the place to put exclude patterns that are local to your copy of the
1142            repo (i.e. 'not' shared between project participants), such as
1143            temporary backup files made by your editor (e.g. `\*~`), etc.
1144 The file specified by the `core.excludesfile` config directive:::
1145            By setting the `core.excludesfile` config directive you can tell git
1146            where to find more exclude patterns (see gitlink:git-config[1] for
1147            more information on configuration options). This config directive
1148            can be set in the per-repo `.git/config` file, in which case the
1149            exclude patterns will apply to that repo only. Alternatively, you
1150            can set the directive in the global `~/.gitconfig` file to apply
1151            the exclude pattern to all your git repos. As with the above
1152            `.git/info/exclude` (and, indeed, with git config directives in
1153            general), this directive does not follow push/pull/clone, but remain
1154            local to your repo(s).
1156 [NOTE]
1157 In addition to the above alternatives, there are git commands that can take
1158 exclude patterns directly on the command line. See gitlink:git-ls-files[1]
1159 for an example of this.
1161 [[how-to-merge]]
1162 How to merge
1163 ------------
1165 You can rejoin two diverging branches of development using
1166 gitlink:git-merge[1]:
1168 -------------------------------------------------
1169 $ git merge branchname
1170 -------------------------------------------------
1172 merges the development in the branch "branchname" into the current
1173 branch.  If there are conflicts--for example, if the same file is
1174 modified in two different ways in the remote branch and the local
1175 branch--then you are warned; the output may look something like this:
1177 -------------------------------------------------
1178 $ git merge next
1179  100% (4/4) done
1180 Auto-merged file.txt
1181 CONFLICT (content): Merge conflict in file.txt
1182 Automatic merge failed; fix conflicts and then commit the result.
1183 -------------------------------------------------
1185 Conflict markers are left in the problematic files, and after
1186 you resolve the conflicts manually, you can update the index
1187 with the contents and run git commit, as you normally would when
1188 creating a new file.
1190 If you examine the resulting commit using gitk, you will see that it
1191 has two parents, one pointing to the top of the current branch, and
1192 one to the top of the other branch.
1194 [[resolving-a-merge]]
1195 Resolving a merge
1196 -----------------
1198 When a merge isn't resolved automatically, git leaves the index and
1199 the working tree in a special state that gives you all the
1200 information you need to help resolve the merge.
1202 Files with conflicts are marked specially in the index, so until you
1203 resolve the problem and update the index, gitlink:git-commit[1] will
1204 fail:
1206 -------------------------------------------------
1207 $ git commit
1208 file.txt: needs merge
1209 -------------------------------------------------
1211 Also, gitlink:git-status[1] will list those files as "unmerged", and the
1212 files with conflicts will have conflict markers added, like this:
1214 -------------------------------------------------
1215 <<<<<<< HEAD:file.txt
1216 Hello world
1217 =======
1218 Goodbye
1219 >>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
1220 -------------------------------------------------
1222 All you need to do is edit the files to resolve the conflicts, and then
1224 -------------------------------------------------
1225 $ git add file.txt
1226 $ git commit
1227 -------------------------------------------------
1229 Note that the commit message will already be filled in for you with
1230 some information about the merge.  Normally you can just use this
1231 default message unchanged, but you may add additional commentary of
1232 your own if desired.
1234 The above is all you need to know to resolve a simple merge.  But git
1235 also provides more information to help resolve conflicts:
1237 [[conflict-resolution]]
1238 Getting conflict-resolution help during a merge
1239 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1241 All of the changes that git was able to merge automatically are
1242 already added to the index file, so gitlink:git-diff[1] shows only
1243 the conflicts.  It uses an unusual syntax:
1245 -------------------------------------------------
1246 $ git diff
1247 diff --cc file.txt
1248 index 802992c,2b60207..0000000
1249 --- a/file.txt
1250 +++ b/file.txt
1251 @@@ -1,1 -1,1 +1,5 @@@
1252 ++<<<<<<< HEAD:file.txt
1253  +Hello world
1254 ++=======
1255 + Goodbye
1256 ++>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
1257 -------------------------------------------------
1259 Recall that the commit which will be commited after we resolve this
1260 conflict will have two parents instead of the usual one: one parent
1261 will be HEAD, the tip of the current branch; the other will be the
1262 tip of the other branch, which is stored temporarily in MERGE_HEAD.
1264 During the merge, the index holds three versions of each file.  Each of
1265 these three "file stages" represents a different version of the file:
1267 -------------------------------------------------
1268 $ git show :1:file.txt  # the file in a common ancestor of both branches
1269 $ git show :2:file.txt  # the version from HEAD, but including any
1270                         # nonconflicting changes from MERGE_HEAD
1271 $ git show :3:file.txt  # the version from MERGE_HEAD, but including any
1272                         # nonconflicting changes from HEAD.
1273 -------------------------------------------------
1275 Since the stage 2 and stage 3 versions have already been updated with
1276 nonconflicting changes, the only remaining differences between them are
1277 the important ones; thus gitlink:git-diff[1] can use the information in
1278 the index to show only those conflicts.
1280 The diff above shows the differences between the working-tree version of
1281 file.txt and the stage 2 and stage 3 versions.  So instead of preceding
1282 each line by a single "+" or "-", it now uses two columns: the first
1283 column is used for differences between the first parent and the working
1284 directory copy, and the second for differences between the second parent
1285 and the working directory copy.  (See the "COMBINED DIFF FORMAT" section
1286 of gitlink:git-diff-files[1] for a details of the format.)
1288 After resolving the conflict in the obvious way (but before updating the
1289 index), the diff will look like:
1291 -------------------------------------------------
1292 $ git diff
1293 diff --cc file.txt
1294 index 802992c,2b60207..0000000
1295 --- a/file.txt
1296 +++ b/file.txt
1297 @@@ -1,1 -1,1 +1,1 @@@
1298 - Hello world
1299  -Goodbye
1300 ++Goodbye world
1301 -------------------------------------------------
1303 This shows that our resolved version deleted "Hello world" from the
1304 first parent, deleted "Goodbye" from the second parent, and added
1305 "Goodbye world", which was previously absent from both.
1307 Some special diff options allow diffing the working directory against
1308 any of these stages:
1310 -------------------------------------------------
1311 $ git diff -1 file.txt          # diff against stage 1
1312 $ git diff --base file.txt      # same as the above
1313 $ git diff -2 file.txt          # diff against stage 2
1314 $ git diff --ours file.txt      # same as the above
1315 $ git diff -3 file.txt          # diff against stage 3
1316 $ git diff --theirs file.txt    # same as the above.
1317 -------------------------------------------------
1319 The gitlink:git-log[1] and gitk[1] commands also provide special help
1320 for merges:
1322 -------------------------------------------------
1323 $ git log --merge
1324 $ gitk --merge
1325 -------------------------------------------------
1327 These will display all commits which exist only on HEAD or on
1328 MERGE_HEAD, and which touch an unmerged file.
1330 You may also use gitlink:git-mergetool[1], which lets you merge the
1331 unmerged files using external tools such as emacs or kdiff3.
1333 Each time you resolve the conflicts in a file and update the index:
1335 -------------------------------------------------
1336 $ git add file.txt
1337 -------------------------------------------------
1339 the different stages of that file will be "collapsed", after which
1340 git-diff will (by default) no longer show diffs for that file.
1342 [[undoing-a-merge]]
1343 Undoing a merge
1344 ---------------
1346 If you get stuck and decide to just give up and throw the whole mess
1347 away, you can always return to the pre-merge state with
1349 -------------------------------------------------
1350 $ git reset --hard HEAD
1351 -------------------------------------------------
1353 Or, if you've already commited the merge that you want to throw away,
1355 -------------------------------------------------
1356 $ git reset --hard ORIG_HEAD
1357 -------------------------------------------------
1359 However, this last command can be dangerous in some cases--never
1360 throw away a commit you have already committed if that commit may
1361 itself have been merged into another branch, as doing so may confuse
1362 further merges.
1364 [[fast-forwards]]
1365 Fast-forward merges
1366 -------------------
1368 There is one special case not mentioned above, which is treated
1369 differently.  Normally, a merge results in a merge commit, with two
1370 parents, one pointing at each of the two lines of development that
1371 were merged.
1373 However, if the current branch is a descendant of the other--so every
1374 commit present in the one is already contained in the other--then git
1375 just performs a "fast forward"; the head of the current branch is moved
1376 forward to point at the head of the merged-in branch, without any new
1377 commits being created.
1379 [[fixing-mistakes]]
1380 Fixing mistakes
1381 ---------------
1383 If you've messed up the working tree, but haven't yet committed your
1384 mistake, you can return the entire working tree to the last committed
1385 state with
1387 -------------------------------------------------
1388 $ git reset --hard HEAD
1389 -------------------------------------------------
1391 If you make a commit that you later wish you hadn't, there are two
1392 fundamentally different ways to fix the problem:
1394         1. You can create a new commit that undoes whatever was done
1395         by the previous commit.  This is the correct thing if your
1396         mistake has already been made public.
1398         2. You can go back and modify the old commit.  You should
1399         never do this if you have already made the history public;
1400         git does not normally expect the "history" of a project to
1401         change, and cannot correctly perform repeated merges from
1402         a branch that has had its history changed.
1404 [[reverting-a-commit]]
1405 Fixing a mistake with a new commit
1406 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1408 Creating a new commit that reverts an earlier change is very easy;
1409 just pass the gitlink:git-revert[1] command a reference to the bad
1410 commit; for example, to revert the most recent commit:
1412 -------------------------------------------------
1413 $ git revert HEAD
1414 -------------------------------------------------
1416 This will create a new commit which undoes the change in HEAD.  You
1417 will be given a chance to edit the commit message for the new commit.
1419 You can also revert an earlier change, for example, the next-to-last:
1421 -------------------------------------------------
1422 $ git revert HEAD^
1423 -------------------------------------------------
1425 In this case git will attempt to undo the old change while leaving
1426 intact any changes made since then.  If more recent changes overlap
1427 with the changes to be reverted, then you will be asked to fix
1428 conflicts manually, just as in the case of <<resolving-a-merge,
1429 resolving a merge>>.
1431 [[fixing-a-mistake-by-editing-history]]
1432 Fixing a mistake by editing history
1433 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1435 If the problematic commit is the most recent commit, and you have not
1436 yet made that commit public, then you may just
1437 <<undoing-a-merge,destroy it using git-reset>>.
1439 Alternatively, you
1440 can edit the working directory and update the index to fix your
1441 mistake, just as if you were going to <<how-to-make-a-commit,create a
1442 new commit>>, then run
1444 -------------------------------------------------
1445 $ git commit --amend
1446 -------------------------------------------------
1448 which will replace the old commit by a new commit incorporating your
1449 changes, giving you a chance to edit the old commit message first.
1451 Again, you should never do this to a commit that may already have
1452 been merged into another branch; use gitlink:git-revert[1] instead in
1453 that case.
1455 It is also possible to edit commits further back in the history, but
1456 this is an advanced topic to be left for
1457 <<cleaning-up-history,another chapter>>.
1459 [[checkout-of-path]]
1460 Checking out an old version of a file
1461 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1463 In the process of undoing a previous bad change, you may find it
1464 useful to check out an older version of a particular file using
1465 gitlink:git-checkout[1].  We've used git checkout before to switch
1466 branches, but it has quite different behavior if it is given a path
1467 name: the command
1469 -------------------------------------------------
1470 $ git checkout HEAD^ path/to/file
1471 -------------------------------------------------
1473 replaces path/to/file by the contents it had in the commit HEAD^, and
1474 also updates the index to match.  It does not change branches.
1476 If you just want to look at an old version of the file, without
1477 modifying the working directory, you can do that with
1478 gitlink:git-show[1]:
1480 -------------------------------------------------
1481 $ git show HEAD^:path/to/file
1482 -------------------------------------------------
1484 which will display the given version of the file.
1486 [[ensuring-good-performance]]
1487 Ensuring good performance
1488 -------------------------
1490 On large repositories, git depends on compression to keep the history
1491 information from taking up to much space on disk or in memory.
1493 This compression is not performed automatically.  Therefore you
1494 should occasionally run gitlink:git-gc[1]:
1496 -------------------------------------------------
1497 $ git gc
1498 -------------------------------------------------
1500 to recompress the archive.  This can be very time-consuming, so
1501 you may prefer to run git-gc when you are not doing other work.
1504 [[ensuring-reliability]]
1505 Ensuring reliability
1506 --------------------
1508 [[checking-for-corruption]]
1509 Checking the repository for corruption
1510 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1512 The gitlink:git-fsck[1] command runs a number of self-consistency checks
1513 on the repository, and reports on any problems.  This may take some
1514 time.  The most common warning by far is about "dangling" objects:
1516 -------------------------------------------------
1517 $ git fsck
1518 dangling commit 7281251ddd2a61e38657c827739c57015671a6b3
1519 dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a63
1520 dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b5
1521 dangling blob 218761f9d90712d37a9c5e36f406f92202db07eb
1522 dangling commit bf093535a34a4d35731aa2bd90fe6b176302f14f
1523 dangling commit 8e4bec7f2ddaa268bef999853c25755452100f8e
1524 dangling tree d50bb86186bf27b681d25af89d3b5b68382e4085
1525 dangling tree b24c2473f1fd3d91352a624795be026d64c8841f
1527 -------------------------------------------------
1529 Dangling objects are not a problem.  At worst they may take up a little
1530 extra disk space.  They can sometimes provide a last-resort method of
1531 recovery lost work--see <<dangling-objects>> for details.  However, if
1532 you want, you may remove them with gitlink:git-prune[1] or the --prune
1533 option to gitlink:git-gc[1]:
1535 -------------------------------------------------
1536 $ git gc --prune
1537 -------------------------------------------------
1539 This may be time-consuming.  Unlike most other git operations (including
1540 git-gc when run without any options), it is not safe to prune while
1541 other git operations are in progress in the same repository.
1543 [[recovering-lost-changes]]
1544 Recovering lost changes
1545 ~~~~~~~~~~~~~~~~~~~~~~~
1547 [[reflogs]]
1548 Reflogs
1549 ^^^^^^^
1551 Say you modify a branch with gitlink:git-reset[1] --hard, and then
1552 realize that the branch was the only reference you had to that point in
1553 history.
1555 Fortunately, git also keeps a log, called a "reflog", of all the
1556 previous values of each branch.  So in this case you can still find the
1557 old history using, for example, 
1559 -------------------------------------------------
1560 $ git log master@{1}
1561 -------------------------------------------------
1563 This lists the commits reachable from the previous version of the head.
1564 This syntax can be used to with any git command that accepts a commit,
1565 not just with git log.  Some other examples:
1567 -------------------------------------------------
1568 $ git show master@{2}           # See where the branch pointed 2,
1569 $ git show master@{3}           # 3, ... changes ago.
1570 $ gitk master@{yesterday}       # See where it pointed yesterday,
1571 $ gitk master@{"1 week ago"}    # ... or last week
1572 $ git log --walk-reflogs master # show reflog entries for master
1573 -------------------------------------------------
1575 A separate reflog is kept for the HEAD, so
1577 -------------------------------------------------
1578 $ git show HEAD@{"1 week ago"}
1579 -------------------------------------------------
1581 will show what HEAD pointed to one week ago, not what the current branch
1582 pointed to one week ago.  This allows you to see the history of what
1583 you've checked out.
1585 The reflogs are kept by default for 30 days, after which they may be
1586 pruned.  See gitlink:git-reflog[1] and gitlink:git-gc[1] to learn
1587 how to control this pruning, and see the "SPECIFYING REVISIONS"
1588 section of gitlink:git-rev-parse[1] for details.
1590 Note that the reflog history is very different from normal git history.
1591 While normal history is shared by every repository that works on the
1592 same project, the reflog history is not shared: it tells you only about
1593 how the branches in your local repository have changed over time.
1595 [[dangling-object-recovery]]
1596 Examining dangling objects
1597 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1599 In some situations the reflog may not be able to save you.  For example,
1600 suppose you delete a branch, then realize you need the history it
1601 contained.  The reflog is also deleted; however, if you have not yet
1602 pruned the repository, then you may still be able to find the lost
1603 commits in the dangling objects that git-fsck reports.  See
1604 <<dangling-objects>> for the details.
1606 -------------------------------------------------
1607 $ git fsck
1608 dangling commit 7281251ddd2a61e38657c827739c57015671a6b3
1609 dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a63
1610 dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b5
1612 -------------------------------------------------
1614 You can examine
1615 one of those dangling commits with, for example,
1617 ------------------------------------------------
1618 $ gitk 7281251ddd --not --all
1619 ------------------------------------------------
1621 which does what it sounds like: it says that you want to see the commit
1622 history that is described by the dangling commit(s), but not the
1623 history that is described by all your existing branches and tags.  Thus
1624 you get exactly the history reachable from that commit that is lost.
1625 (And notice that it might not be just one commit: we only report the
1626 "tip of the line" as being dangling, but there might be a whole deep
1627 and complex commit history that was dropped.)
1629 If you decide you want the history back, you can always create a new
1630 reference pointing to it, for example, a new branch:
1632 ------------------------------------------------
1633 $ git branch recovered-branch 7281251ddd 
1634 ------------------------------------------------
1636 Other types of dangling objects (blobs and trees) are also possible, and
1637 dangling objects can arise in other situations.
1640 [[sharing-development]]
1641 Sharing development with others
1642 ===============================
1644 [[getting-updates-with-git-pull]]
1645 Getting updates with git pull
1646 -----------------------------
1648 After you clone a repository and make a few changes of your own, you
1649 may wish to check the original repository for updates and merge them
1650 into your own work.
1652 We have already seen <<Updating-a-repository-with-git-fetch,how to
1653 keep remote tracking branches up to date>> with gitlink:git-fetch[1],
1654 and how to merge two branches.  So you can merge in changes from the
1655 original repository's master branch with:
1657 -------------------------------------------------
1658 $ git fetch
1659 $ git merge origin/master
1660 -------------------------------------------------
1662 However, the gitlink:git-pull[1] command provides a way to do this in
1663 one step:
1665 -------------------------------------------------
1666 $ git pull origin master
1667 -------------------------------------------------
1669 In fact, "origin" is normally the default repository to pull from,
1670 and the default branch is normally the HEAD of the remote repository,
1671 so often you can accomplish the above with just
1673 -------------------------------------------------
1674 $ git pull
1675 -------------------------------------------------
1677 See the descriptions of the branch.<name>.remote and branch.<name>.merge
1678 options in gitlink:git-config[1] to learn how to control these defaults
1679 depending on the current branch.  Also note that the --track option to
1680 gitlink:git-branch[1] and gitlink:git-checkout[1] can be used to
1681 automatically set the default remote branch to pull from at the time
1682 that a branch is created:
1684 -------------------------------------------------
1685 $ git checkout --track -b maint origin/maint
1686 -------------------------------------------------
1688 In addition to saving you keystrokes, "git pull" also helps you by
1689 producing a default commit message documenting the branch and
1690 repository that you pulled from.
1692 (But note that no such commit will be created in the case of a
1693 <<fast-forwards,fast forward>>; instead, your branch will just be
1694 updated to point to the latest commit from the upstream branch.)
1696 The git-pull command can also be given "." as the "remote" repository,
1697 in which case it just merges in a branch from the current repository; so
1698 the commands
1700 -------------------------------------------------
1701 $ git pull . branch
1702 $ git merge branch
1703 -------------------------------------------------
1705 are roughly equivalent.  The former is actually very commonly used.
1707 [[submitting-patches]]
1708 Submitting patches to a project
1709 -------------------------------
1711 If you just have a few changes, the simplest way to submit them may
1712 just be to send them as patches in email:
1714 First, use gitlink:git-format-patch[1]; for example:
1716 -------------------------------------------------
1717 $ git format-patch origin
1718 -------------------------------------------------
1720 will produce a numbered series of files in the current directory, one
1721 for each patch in the current branch but not in origin/HEAD.
1723 You can then import these into your mail client and send them by
1724 hand.  However, if you have a lot to send at once, you may prefer to
1725 use the gitlink:git-send-email[1] script to automate the process.
1726 Consult the mailing list for your project first to determine how they
1727 prefer such patches be handled.
1729 [[importing-patches]]
1730 Importing patches to a project
1731 ------------------------------
1733 Git also provides a tool called gitlink:git-am[1] (am stands for
1734 "apply mailbox"), for importing such an emailed series of patches.
1735 Just save all of the patch-containing messages, in order, into a
1736 single mailbox file, say "patches.mbox", then run
1738 -------------------------------------------------
1739 $ git am -3 patches.mbox
1740 -------------------------------------------------
1742 Git will apply each patch in order; if any conflicts are found, it
1743 will stop, and you can fix the conflicts as described in
1744 "<<resolving-a-merge,Resolving a merge>>".  (The "-3" option tells
1745 git to perform a merge; if you would prefer it just to abort and
1746 leave your tree and index untouched, you may omit that option.)
1748 Once the index is updated with the results of the conflict
1749 resolution, instead of creating a new commit, just run
1751 -------------------------------------------------
1752 $ git am --resolved
1753 -------------------------------------------------
1755 and git will create the commit for you and continue applying the
1756 remaining patches from the mailbox.
1758 The final result will be a series of commits, one for each patch in
1759 the original mailbox, with authorship and commit log message each
1760 taken from the message containing each patch.
1762 [[public-repositories]]
1763 Public git repositories
1764 -----------------------
1766 Another way to submit changes to a project is to tell the maintainer of
1767 that project to pull the changes from your repository using git-pull[1].
1768 In the section "<<getting-updates-with-git-pull, Getting updates with
1769 git pull>>" we described this as a way to get updates from the "main"
1770 repository, but it works just as well in the other direction.
1772 If you and the maintainer both have accounts on the same machine, then
1773 you can just pull changes from each other's repositories directly;
1774 commands that accepts repository URLs as arguments will also accept a
1775 local directory name:
1777 -------------------------------------------------
1778 $ git clone /path/to/repository
1779 $ git pull /path/to/other/repository
1780 -------------------------------------------------
1782 However, the more common way to do this is to maintain a separate public
1783 repository (usually on a different host) for others to pull changes
1784 from.  This is usually more convenient, and allows you to cleanly
1785 separate private work in progress from publicly visible work.
1787 You will continue to do your day-to-day work in your personal
1788 repository, but periodically "push" changes from your personal
1789 repository into your public repository, allowing other developers to
1790 pull from that repository.  So the flow of changes, in a situation
1791 where there is one other developer with a public repository, looks
1792 like this:
1794                         you push
1795   your personal repo ------------------> your public repo
1796         ^                                     |
1797         |                                     |
1798         | you pull                            | they pull
1799         |                                     |
1800         |                                     |
1801         |               they push             V
1802   their public repo <------------------- their repo
1804 [[setting-up-a-public-repository]]
1805 Setting up a public repository
1806 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1808 Assume your personal repository is in the directory ~/proj.  We
1809 first create a new clone of the repository and tell git-daemon that it
1810 is meant to be public:
1812 -------------------------------------------------
1813 $ git clone --bare ~/proj proj.git
1814 $ touch proj.git/git-daemon-export-ok
1815 -------------------------------------------------
1817 The resulting directory proj.git contains a "bare" git repository--it is
1818 just the contents of the ".git" directory, without any files checked out
1819 around it.
1821 Next, copy proj.git to the server where you plan to host the
1822 public repository.  You can use scp, rsync, or whatever is most
1823 convenient.
1825 [[exporting-via-git]]
1826 Exporting a git repository via the git protocol
1827 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1829 This is the preferred method.
1831 If someone else administers the server, they should tell you what
1832 directory to put the repository in, and what git:// url it will appear
1833 at.  You can then skip to the section
1834 "<<pushing-changes-to-a-public-repository,Pushing changes to a public
1835 repository>>", below.
1837 Otherwise, all you need to do is start gitlink:git-daemon[1]; it will
1838 listen on port 9418.  By default, it will allow access to any directory
1839 that looks like a git directory and contains the magic file
1840 git-daemon-export-ok.  Passing some directory paths as git-daemon
1841 arguments will further restrict the exports to those paths.
1843 You can also run git-daemon as an inetd service; see the
1844 gitlink:git-daemon[1] man page for details.  (See especially the
1845 examples section.)
1847 [[exporting-via-http]]
1848 Exporting a git repository via http
1849 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1851 The git protocol gives better performance and reliability, but on a
1852 host with a web server set up, http exports may be simpler to set up.
1854 All you need to do is place the newly created bare git repository in
1855 a directory that is exported by the web server, and make some
1856 adjustments to give web clients some extra information they need:
1858 -------------------------------------------------
1859 $ mv proj.git /home/you/public_html/proj.git
1860 $ cd proj.git
1861 $ git --bare update-server-info
1862 $ chmod a+x hooks/post-update
1863 -------------------------------------------------
1865 (For an explanation of the last two lines, see
1866 gitlink:git-update-server-info[1], and the documentation
1867 link:hooks.html[Hooks used by git].)
1869 Advertise the url of proj.git.  Anybody else should then be able to
1870 clone or pull from that url, for example with a commandline like:
1872 -------------------------------------------------
1873 $ git clone http://yourserver.com/~you/proj.git
1874 -------------------------------------------------
1876 (See also
1877 link:howto/setup-git-server-over-http.txt[setup-git-server-over-http]
1878 for a slightly more sophisticated setup using WebDAV which also
1879 allows pushing over http.)
1881 [[pushing-changes-to-a-public-repository]]
1882 Pushing changes to a public repository
1883 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1885 Note that the two techniques outlined above (exporting via
1886 <<exporting-via-http,http>> or <<exporting-via-git,git>>) allow other
1887 maintainers to fetch your latest changes, but they do not allow write
1888 access, which you will need to update the public repository with the
1889 latest changes created in your private repository.
1891 The simplest way to do this is using gitlink:git-push[1] and ssh; to
1892 update the remote branch named "master" with the latest state of your
1893 branch named "master", run
1895 -------------------------------------------------
1896 $ git push ssh://yourserver.com/~you/proj.git master:master
1897 -------------------------------------------------
1899 or just
1901 -------------------------------------------------
1902 $ git push ssh://yourserver.com/~you/proj.git master
1903 -------------------------------------------------
1905 As with git-fetch, git-push will complain if this does not result in
1906 a <<fast-forwards,fast forward>>.  Normally this is a sign of
1907 something wrong.  However, if you are sure you know what you're
1908 doing, you may force git-push to perform the update anyway by
1909 proceeding the branch name by a plus sign:
1911 -------------------------------------------------
1912 $ git push ssh://yourserver.com/~you/proj.git +master
1913 -------------------------------------------------
1915 As with git-fetch, you may also set up configuration options to
1916 save typing; so, for example, after
1918 -------------------------------------------------
1919 $ cat >>.git/config <<EOF
1920 [remote "public-repo"]
1921         url = ssh://yourserver.com/~you/proj.git
1923 -------------------------------------------------
1925 you should be able to perform the above push with just
1927 -------------------------------------------------
1928 $ git push public-repo master
1929 -------------------------------------------------
1931 See the explanations of the remote.<name>.url, branch.<name>.remote,
1932 and remote.<name>.push options in gitlink:git-config[1] for
1933 details.
1935 [[setting-up-a-shared-repository]]
1936 Setting up a shared repository
1937 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1939 Another way to collaborate is by using a model similar to that
1940 commonly used in CVS, where several developers with special rights
1941 all push to and pull from a single shared repository.  See
1942 link:cvs-migration.html[git for CVS users] for instructions on how to
1943 set this up.
1945 However, while there is nothing wrong with git's support for shared
1946 repositories, this mode of operation is not generally recommended,
1947 simply because the mode of collaboration that git supports--by
1948 exchanging patches and pulling from public repositories--has so many
1949 advantages over the central shared repository:
1951         - Git's ability to quickly import and merge patches allows a
1952           single maintainer to process incoming changes even at very
1953           high rates.  And when that becomes too much, git-pull provides
1954           an easy way for that maintainer to delegate this job to other
1955           maintainers while still allowing optional review of incoming
1956           changes.
1957         - Since every developer's repository has the same complete copy
1958           of the project history, no repository is special, and it is
1959           trivial for another developer to take over maintenance of a
1960           project, either by mutual agreement, or because a maintainer
1961           becomes unresponsive or difficult to work with.
1962         - The lack of a central group of "committers" means there is
1963           less need for formal decisions about who is "in" and who is
1964           "out".
1966 [[setting-up-gitweb]]
1967 Allowing web browsing of a repository
1968 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1970 The gitweb cgi script provides users an easy way to browse your
1971 project's files and history without having to install git; see the file
1972 gitweb/INSTALL in the git source tree for instructions on setting it up.
1974 [[sharing-development-examples]]
1975 Examples
1976 --------
1978 [[maintaining-topic-branches]]
1979 Maintaining topic branches for a Linux subsystem maintainer
1980 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1982 This describes how Tony Luck uses git in his role as maintainer of the
1983 IA64 architecture for the Linux kernel.
1985 He uses two public branches:
1987  - A "test" tree into which patches are initially placed so that they
1988    can get some exposure when integrated with other ongoing development.
1989    This tree is available to Andrew for pulling into -mm whenever he
1990    wants.
1992  - A "release" tree into which tested patches are moved for final sanity
1993    checking, and as a vehicle to send them upstream to Linus (by sending
1994    him a "please pull" request.)
1996 He also uses a set of temporary branches ("topic branches"), each
1997 containing a logical grouping of patches.
1999 To set this up, first create your work tree by cloning Linus's public
2000 tree:
2002 -------------------------------------------------
2003 $ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git work
2004 $ cd work
2005 -------------------------------------------------
2007 Linus's tree will be stored in the remote branch named origin/master,
2008 and can be updated using gitlink:git-fetch[1]; you can track other
2009 public trees using gitlink:git-remote[1] to set up a "remote" and
2010 git-fetch[1] to keep them up-to-date; see <<repositories-and-branches>>.
2012 Now create the branches in which you are going to work; these start out
2013 at the current tip of origin/master branch, and should be set up (using
2014 the --track option to gitlink:git-branch[1]) to merge changes in from
2015 Linus by default.
2017 -------------------------------------------------
2018 $ git branch --track test origin/master
2019 $ git branch --track release origin/master
2020 -------------------------------------------------
2022 These can be easily kept up to date using gitlink:git-pull[1]
2024 -------------------------------------------------
2025 $ git checkout test && git pull
2026 $ git checkout release && git pull
2027 -------------------------------------------------
2029 Important note!  If you have any local changes in these branches, then
2030 this merge will create a commit object in the history (with no local
2031 changes git will simply do a "Fast forward" merge).  Many people dislike
2032 the "noise" that this creates in the Linux history, so you should avoid
2033 doing this capriciously in the "release" branch, as these noisy commits
2034 will become part of the permanent history when you ask Linus to pull
2035 from the release branch.
2037 A few configuration variables (see gitlink:git-config[1]) can
2038 make it easy to push both branches to your public tree.  (See
2039 <<setting-up-a-public-repository>>.)
2041 -------------------------------------------------
2042 $ cat >> .git/config <<EOF
2043 [remote "mytree"]
2044         url =  master.kernel.org:/pub/scm/linux/kernel/git/aegl/linux-2.6.git
2045         push = release
2046         push = test
2048 -------------------------------------------------
2050 Then you can push both the test and release trees using
2051 gitlink:git-push[1]:
2053 -------------------------------------------------
2054 $ git push mytree
2055 -------------------------------------------------
2057 or push just one of the test and release branches using:
2059 -------------------------------------------------
2060 $ git push mytree test
2061 -------------------------------------------------
2065 -------------------------------------------------
2066 $ git push mytree release
2067 -------------------------------------------------
2069 Now to apply some patches from the community.  Think of a short
2070 snappy name for a branch to hold this patch (or related group of
2071 patches), and create a new branch from the current tip of Linus's
2072 branch:
2074 -------------------------------------------------
2075 $ git checkout -b speed-up-spinlocks origin
2076 -------------------------------------------------
2078 Now you apply the patch(es), run some tests, and commit the change(s).  If
2079 the patch is a multi-part series, then you should apply each as a separate
2080 commit to this branch.
2082 -------------------------------------------------
2083 $ ... patch ... test  ... commit [ ... patch ... test ... commit ]*
2084 -------------------------------------------------
2086 When you are happy with the state of this change, you can pull it into the
2087 "test" branch in preparation to make it public:
2089 -------------------------------------------------
2090 $ git checkout test && git pull . speed-up-spinlocks
2091 -------------------------------------------------
2093 It is unlikely that you would have any conflicts here ... but you might if you
2094 spent a while on this step and had also pulled new versions from upstream.
2096 Some time later when enough time has passed and testing done, you can pull the
2097 same branch into the "release" tree ready to go upstream.  This is where you
2098 see the value of keeping each patch (or patch series) in its own branch.  It
2099 means that the patches can be moved into the "release" tree in any order.
2101 -------------------------------------------------
2102 $ git checkout release && git pull . speed-up-spinlocks
2103 -------------------------------------------------
2105 After a while, you will have a number of branches, and despite the
2106 well chosen names you picked for each of them, you may forget what
2107 they are for, or what status they are in.  To get a reminder of what
2108 changes are in a specific branch, use:
2110 -------------------------------------------------
2111 $ git log linux..branchname | git-shortlog
2112 -------------------------------------------------
2114 To see whether it has already been merged into the test or release branches
2115 use:
2117 -------------------------------------------------
2118 $ git log test..branchname
2119 -------------------------------------------------
2123 -------------------------------------------------
2124 $ git log release..branchname
2125 -------------------------------------------------
2127 (If this branch has not yet been merged you will see some log entries.
2128 If it has been merged, then there will be no output.)
2130 Once a patch completes the great cycle (moving from test to release,
2131 then pulled by Linus, and finally coming back into your local
2132 "origin/master" branch) the branch for this change is no longer needed.
2133 You detect this when the output from:
2135 -------------------------------------------------
2136 $ git log origin..branchname
2137 -------------------------------------------------
2139 is empty.  At this point the branch can be deleted:
2141 -------------------------------------------------
2142 $ git branch -d branchname
2143 -------------------------------------------------
2145 Some changes are so trivial that it is not necessary to create a separate
2146 branch and then merge into each of the test and release branches.  For
2147 these changes, just apply directly to the "release" branch, and then
2148 merge that into the "test" branch.
2150 To create diffstat and shortlog summaries of changes to include in a "please
2151 pull" request to Linus you can use:
2153 -------------------------------------------------
2154 $ git diff --stat origin..release
2155 -------------------------------------------------
2159 -------------------------------------------------
2160 $ git log -p origin..release | git shortlog
2161 -------------------------------------------------
2163 Here are some of the scripts that simplify all this even further.
2165 -------------------------------------------------
2166 ==== update script ====
2167 # Update a branch in my GIT tree.  If the branch to be updated
2168 # is origin, then pull from kernel.org.  Otherwise merge
2169 # origin/master branch into test|release branch
2171 case "$1" in
2172 test|release)
2173         git checkout $1 && git pull . origin
2174         ;;
2175 origin)
2176         before=$(cat .git/refs/remotes/origin/master)
2177         git fetch origin
2178         after=$(cat .git/refs/remotes/origin/master)
2179         if [ $before != $after ]
2180         then
2181                 git log $before..$after | git shortlog
2182         fi
2183         ;;
2185         echo "Usage: $0 origin|test|release" 1>&2
2186         exit 1
2187         ;;
2188 esac
2189 -------------------------------------------------
2191 -------------------------------------------------
2192 ==== merge script ====
2193 # Merge a branch into either the test or release branch
2195 pname=$0
2197 usage()
2199         echo "Usage: $pname branch test|release" 1>&2
2200         exit 1
2203 if [ ! -f .git/refs/heads/"$1" ]
2204 then
2205         echo "Can't see branch <$1>" 1>&2
2206         usage
2209 case "$2" in
2210 test|release)
2211         if [ $(git log $2..$1 | wc -c) -eq 0 ]
2212         then
2213                 echo $1 already merged into $2 1>&2
2214                 exit 1
2215         fi
2216         git checkout $2 && git pull . $1
2217         ;;
2219         usage
2220         ;;
2221 esac
2222 -------------------------------------------------
2224 -------------------------------------------------
2225 ==== status script ====
2226 # report on status of my ia64 GIT tree
2228 gb=$(tput setab 2)
2229 rb=$(tput setab 1)
2230 restore=$(tput setab 9)
2232 if [ `git rev-list test..release | wc -c` -gt 0 ]
2233 then
2234         echo $rb Warning: commits in release that are not in test $restore
2235         git log test..release
2238 for branch in `ls .git/refs/heads`
2240         if [ $branch = test -o $branch = release ]
2241         then
2242                 continue
2243         fi
2245         echo -n $gb ======= $branch ====== $restore " "
2246         status=
2247         for ref in test release origin/master
2248         do
2249                 if [ `git rev-list $ref..$branch | wc -c` -gt 0 ]
2250                 then
2251                         status=$status${ref:0:1}
2252                 fi
2253         done
2254         case $status in
2255         trl)
2256                 echo $rb Need to pull into test $restore
2257                 ;;
2258         rl)
2259                 echo "In test"
2260                 ;;
2261         l)
2262                 echo "Waiting for linus"
2263                 ;;
2264         "")
2265                 echo $rb All done $restore
2266                 ;;
2267         *)
2268                 echo $rb "<$status>" $restore
2269                 ;;
2270         esac
2271         git log origin/master..$branch | git shortlog
2272 done
2273 -------------------------------------------------
2276 [[cleaning-up-history]]
2277 Rewriting history and maintaining patch series
2278 ==============================================
2280 Normally commits are only added to a project, never taken away or
2281 replaced.  Git is designed with this assumption, and violating it will
2282 cause git's merge machinery (for example) to do the wrong thing.
2284 However, there is a situation in which it can be useful to violate this
2285 assumption.
2287 [[patch-series]]
2288 Creating the perfect patch series
2289 ---------------------------------
2291 Suppose you are a contributor to a large project, and you want to add a
2292 complicated feature, and to present it to the other developers in a way
2293 that makes it easy for them to read your changes, verify that they are
2294 correct, and understand why you made each change.
2296 If you present all of your changes as a single patch (or commit), they
2297 may find that it is too much to digest all at once.
2299 If you present them with the entire history of your work, complete with
2300 mistakes, corrections, and dead ends, they may be overwhelmed.
2302 So the ideal is usually to produce a series of patches such that:
2304         1. Each patch can be applied in order.
2306         2. Each patch includes a single logical change, together with a
2307            message explaining the change.
2309         3. No patch introduces a regression: after applying any initial
2310            part of the series, the resulting project still compiles and
2311            works, and has no bugs that it didn't have before.
2313         4. The complete series produces the same end result as your own
2314            (probably much messier!) development process did.
2316 We will introduce some tools that can help you do this, explain how to
2317 use them, and then explain some of the problems that can arise because
2318 you are rewriting history.
2320 [[using-git-rebase]]
2321 Keeping a patch series up to date using git-rebase
2322 --------------------------------------------------
2324 Suppose that you create a branch "mywork" on a remote-tracking branch
2325 "origin", and create some commits on top of it:
2327 -------------------------------------------------
2328 $ git checkout -b mywork origin
2329 $ vi file.txt
2330 $ git commit
2331 $ vi otherfile.txt
2332 $ git commit
2334 -------------------------------------------------
2336 You have performed no merges into mywork, so it is just a simple linear
2337 sequence of patches on top of "origin":
2339 ................................................
2340  o--o--o <-- origin
2341         \
2342          o--o--o <-- mywork
2343 ................................................
2345 Some more interesting work has been done in the upstream project, and
2346 "origin" has advanced:
2348 ................................................
2349  o--o--O--o--o--o <-- origin
2350         \
2351          a--b--c <-- mywork
2352 ................................................
2354 At this point, you could use "pull" to merge your changes back in;
2355 the result would create a new merge commit, like this:
2357 ................................................
2358  o--o--O--o--o--o <-- origin
2359         \        \
2360          a--b--c--m <-- mywork
2361 ................................................
2363 However, if you prefer to keep the history in mywork a simple series of
2364 commits without any merges, you may instead choose to use
2365 gitlink:git-rebase[1]:
2367 -------------------------------------------------
2368 $ git checkout mywork
2369 $ git rebase origin
2370 -------------------------------------------------
2372 This will remove each of your commits from mywork, temporarily saving
2373 them as patches (in a directory named ".dotest"), update mywork to
2374 point at the latest version of origin, then apply each of the saved
2375 patches to the new mywork.  The result will look like:
2378 ................................................
2379  o--o--O--o--o--o <-- origin
2380                  \
2381                   a'--b'--c' <-- mywork
2382 ................................................
2384 In the process, it may discover conflicts.  In that case it will stop
2385 and allow you to fix the conflicts; after fixing conflicts, use "git
2386 add" to update the index with those contents, and then, instead of
2387 running git-commit, just run
2389 -------------------------------------------------
2390 $ git rebase --continue
2391 -------------------------------------------------
2393 and git will continue applying the rest of the patches.
2395 At any point you may use the --abort option to abort this process and
2396 return mywork to the state it had before you started the rebase:
2398 -------------------------------------------------
2399 $ git rebase --abort
2400 -------------------------------------------------
2402 [[modifying-one-commit]]
2403 Modifying a single commit
2404 -------------------------
2406 We saw in <<fixing-a-mistake-by-editing-history>> that you can replace the
2407 most recent commit using
2409 -------------------------------------------------
2410 $ git commit --amend
2411 -------------------------------------------------
2413 which will replace the old commit by a new commit incorporating your
2414 changes, giving you a chance to edit the old commit message first.
2416 You can also use a combination of this and gitlink:git-rebase[1] to edit
2417 commits further back in your history.  First, tag the problematic commit with
2419 -------------------------------------------------
2420 $ git tag bad mywork~5
2421 -------------------------------------------------
2423 (Either gitk or git-log may be useful for finding the commit.)
2425 Then check out that commit, edit it, and rebase the rest of the series
2426 on top of it (note that we could check out the commit on a temporary
2427 branch, but instead we're using a <<detached-head,detached head>>):
2429 -------------------------------------------------
2430 $ git checkout bad
2431 $ # make changes here and update the index
2432 $ git commit --amend
2433 $ git rebase --onto HEAD bad mywork
2434 -------------------------------------------------
2436 When you're done, you'll be left with mywork checked out, with the top
2437 patches on mywork reapplied on top of your modified commit.  You can
2438 then clean up with
2440 -------------------------------------------------
2441 $ git tag -d bad
2442 -------------------------------------------------
2444 Note that the immutable nature of git history means that you haven't really
2445 "modified" existing commits; instead, you have replaced the old commits with
2446 new commits having new object names.
2448 [[reordering-patch-series]]
2449 Reordering or selecting from a patch series
2450 -------------------------------------------
2452 Given one existing commit, the gitlink:git-cherry-pick[1] command
2453 allows you to apply the change introduced by that commit and create a
2454 new commit that records it.  So, for example, if "mywork" points to a
2455 series of patches on top of "origin", you might do something like:
2457 -------------------------------------------------
2458 $ git checkout -b mywork-new origin
2459 $ gitk origin..mywork &
2460 -------------------------------------------------
2462 And browse through the list of patches in the mywork branch using gitk,
2463 applying them (possibly in a different order) to mywork-new using
2464 cherry-pick, and possibly modifying them as you go using commit
2465 --amend.
2467 Another technique is to use git-format-patch to create a series of
2468 patches, then reset the state to before the patches:
2470 -------------------------------------------------
2471 $ git format-patch origin
2472 $ git reset --hard origin
2473 -------------------------------------------------
2475 Then modify, reorder, or eliminate patches as preferred before applying
2476 them again with gitlink:git-am[1].
2478 [[patch-series-tools]]
2479 Other tools
2480 -----------
2482 There are numerous other tools, such as stgit, which exist for the
2483 purpose of maintaining a patch series.  These are outside of the scope of
2484 this manual.
2486 [[problems-with-rewriting-history]]
2487 Problems with rewriting history
2488 -------------------------------
2490 The primary problem with rewriting the history of a branch has to do
2491 with merging.  Suppose somebody fetches your branch and merges it into
2492 their branch, with a result something like this:
2494 ................................................
2495  o--o--O--o--o--o <-- origin
2496         \        \
2497          t--t--t--m <-- their branch:
2498 ................................................
2500 Then suppose you modify the last three commits:
2502 ................................................
2503          o--o--o <-- new head of origin
2504         /
2505  o--o--O--o--o--o <-- old head of origin
2506 ................................................
2508 If we examined all this history together in one repository, it will
2509 look like:
2511 ................................................
2512          o--o--o <-- new head of origin
2513         /
2514  o--o--O--o--o--o <-- old head of origin
2515         \        \
2516          t--t--t--m <-- their branch:
2517 ................................................
2519 Git has no way of knowing that the new head is an updated version of
2520 the old head; it treats this situation exactly the same as it would if
2521 two developers had independently done the work on the old and new heads
2522 in parallel.  At this point, if someone attempts to merge the new head
2523 in to their branch, git will attempt to merge together the two (old and
2524 new) lines of development, instead of trying to replace the old by the
2525 new.  The results are likely to be unexpected.
2527 You may still choose to publish branches whose history is rewritten,
2528 and it may be useful for others to be able to fetch those branches in
2529 order to examine or test them, but they should not attempt to pull such
2530 branches into their own work.
2532 For true distributed development that supports proper merging,
2533 published branches should never be rewritten.
2535 [[advanced-branch-management]]
2536 Advanced branch management
2537 ==========================
2539 [[fetching-individual-branches]]
2540 Fetching individual branches
2541 ----------------------------
2543 Instead of using gitlink:git-remote[1], you can also choose just
2544 to update one branch at a time, and to store it locally under an
2545 arbitrary name:
2547 -------------------------------------------------
2548 $ git fetch origin todo:my-todo-work
2549 -------------------------------------------------
2551 The first argument, "origin", just tells git to fetch from the
2552 repository you originally cloned from.  The second argument tells git
2553 to fetch the branch named "todo" from the remote repository, and to
2554 store it locally under the name refs/heads/my-todo-work.
2556 You can also fetch branches from other repositories; so
2558 -------------------------------------------------
2559 $ git fetch git://example.com/proj.git master:example-master
2560 -------------------------------------------------
2562 will create a new branch named "example-master" and store in it the
2563 branch named "master" from the repository at the given URL.  If you
2564 already have a branch named example-master, it will attempt to
2565 <<fast-forwards,fast-forward>> to the commit given by example.com's
2566 master branch.  In more detail:
2568 [[fetch-fast-forwards]]
2569 git fetch and fast-forwards
2570 ---------------------------
2572 In the previous example, when updating an existing branch, "git
2573 fetch" checks to make sure that the most recent commit on the remote
2574 branch is a descendant of the most recent commit on your copy of the
2575 branch before updating your copy of the branch to point at the new
2576 commit.  Git calls this process a <<fast-forwards,fast forward>>.
2578 A fast forward looks something like this:
2580 ................................................
2581  o--o--o--o <-- old head of the branch
2582            \
2583             o--o--o <-- new head of the branch
2584 ................................................
2587 In some cases it is possible that the new head will *not* actually be
2588 a descendant of the old head.  For example, the developer may have
2589 realized she made a serious mistake, and decided to backtrack,
2590 resulting in a situation like:
2592 ................................................
2593  o--o--o--o--a--b <-- old head of the branch
2594            \
2595             o--o--o <-- new head of the branch
2596 ................................................
2598 In this case, "git fetch" will fail, and print out a warning.
2600 In that case, you can still force git to update to the new head, as
2601 described in the following section.  However, note that in the
2602 situation above this may mean losing the commits labeled "a" and "b",
2603 unless you've already created a reference of your own pointing to
2604 them.
2606 [[forcing-fetch]]
2607 Forcing git fetch to do non-fast-forward updates
2608 ------------------------------------------------
2610 If git fetch fails because the new head of a branch is not a
2611 descendant of the old head, you may force the update with:
2613 -------------------------------------------------
2614 $ git fetch git://example.com/proj.git +master:refs/remotes/example/master
2615 -------------------------------------------------
2617 Note the addition of the "+" sign.  Alternatively, you can use the "-f"
2618 flag to force updates of all the fetched branches, as in:
2620 -------------------------------------------------
2621 $ git fetch -f origin
2622 -------------------------------------------------
2624 Be aware that commits that the old version of example/master pointed at
2625 may be lost, as we saw in the previous section.
2627 [[remote-branch-configuration]]
2628 Configuring remote branches
2629 ---------------------------
2631 We saw above that "origin" is just a shortcut to refer to the
2632 repository that you originally cloned from.  This information is
2633 stored in git configuration variables, which you can see using
2634 gitlink:git-config[1]:
2636 -------------------------------------------------
2637 $ git config -l
2638 core.repositoryformatversion=0
2639 core.filemode=true
2640 core.logallrefupdates=true
2641 remote.origin.url=git://git.kernel.org/pub/scm/git/git.git
2642 remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
2643 branch.master.remote=origin
2644 branch.master.merge=refs/heads/master
2645 -------------------------------------------------
2647 If there are other repositories that you also use frequently, you can
2648 create similar configuration options to save typing; for example,
2649 after
2651 -------------------------------------------------
2652 $ git config remote.example.url git://example.com/proj.git
2653 -------------------------------------------------
2655 then the following two commands will 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 -------------------------------------------------
2662 Even better, if you add one more option:
2664 -------------------------------------------------
2665 $ git config remote.example.fetch master:refs/remotes/example/master
2666 -------------------------------------------------
2668 then the following commands will all do the same thing:
2670 -------------------------------------------------
2671 $ git fetch git://example.com/proj.git master:refs/remotes/example/master
2672 $ git fetch example master:refs/remotes/example/master
2673 $ git fetch example
2674 -------------------------------------------------
2676 You can also add a "+" to force the update each time:
2678 -------------------------------------------------
2679 $ git config remote.example.fetch +master:ref/remotes/example/master
2680 -------------------------------------------------
2682 Don't do this unless you're sure you won't mind "git fetch" possibly
2683 throwing away commits on mybranch.
2685 Also note that all of the above configuration can be performed by
2686 directly editing the file .git/config instead of using
2687 gitlink:git-config[1].
2689 See gitlink:git-config[1] for more details on the configuration
2690 options mentioned above.
2693 [[git-internals]]
2694 Git internals
2695 =============
2697 Git depends on two fundamental abstractions: the "object database", and
2698 the "current directory cache" aka "index".
2700 [[the-object-database]]
2701 The Object Database
2702 -------------------
2704 The object database is literally just a content-addressable collection
2705 of objects.  All objects are named by their content, which is
2706 approximated by the SHA1 hash of the object itself.  Objects may refer
2707 to other objects (by referencing their SHA1 hash), and so you can
2708 build up a hierarchy of objects.
2710 All objects have a statically determined "type" which is
2711 determined at object creation time, and which identifies the format of
2712 the object (i.e. how it is used, and how it can refer to other
2713 objects).  There are currently four different object types: "blob",
2714 "tree", "commit", and "tag".
2716 A <<def_blob_object,"blob" object>> cannot refer to any other object,
2717 and is, as the name implies, a pure storage object containing some
2718 user data.  It is used to actually store the file data, i.e. a blob
2719 object is associated with some particular version of some file.
2721 A <<def_tree_object,"tree" object>> is an object that ties one or more
2722 "blob" objects into a directory structure. In addition, a tree object
2723 can refer to other tree objects, thus creating a directory hierarchy.
2725 A <<def_commit_object,"commit" object>> ties such directory hierarchies
2726 together into a <<def_DAG,directed acyclic graph>> of revisions - each
2727 "commit" is associated with exactly one tree (the directory hierarchy at
2728 the time of the commit). In addition, a "commit" refers to one or more
2729 "parent" commit objects that describe the history of how we arrived at
2730 that directory hierarchy.
2732 As a special case, a commit object with no parents is called the "root"
2733 commit, and is the point of an initial project commit.  Each project
2734 must have at least one root, and while you can tie several different
2735 root objects together into one project by creating a commit object which
2736 has two or more separate roots as its ultimate parents, that's probably
2737 just going to confuse people.  So aim for the notion of "one root object
2738 per project", even if git itself does not enforce that. 
2740 A <<def_tag_object,"tag" object>> symbolically identifies and can be
2741 used to sign other objects. It contains the identifier and type of
2742 another object, a symbolic name (of course!) and, optionally, a
2743 signature.
2745 Regardless of object type, all objects share the following
2746 characteristics: they are all deflated with zlib, and have a header
2747 that not only specifies their type, but also provides size information
2748 about the data in the object.  It's worth noting that the SHA1 hash
2749 that is used to name the object is the hash of the original data
2750 plus this header, so `sha1sum` 'file' does not match the object name
2751 for 'file'.
2752 (Historical note: in the dawn of the age of git the hash
2753 was the sha1 of the 'compressed' object.)
2755 As a result, the general consistency of an object can always be tested
2756 independently of the contents or the type of the object: all objects can
2757 be validated by verifying that (a) their hashes match the content of the
2758 file and (b) the object successfully inflates to a stream of bytes that
2759 forms a sequence of <ascii type without space> + <space> + <ascii decimal
2760 size> + <byte\0> + <binary object data>. 
2762 The structured objects can further have their structure and
2763 connectivity to other objects verified. This is generally done with
2764 the `git-fsck` program, which generates a full dependency graph
2765 of all objects, and verifies their internal consistency (in addition
2766 to just verifying their superficial consistency through the hash).
2768 The object types in some more detail:
2770 [[blob-object]]
2771 Blob Object
2772 -----------
2774 A "blob" object is nothing but a binary blob of data, and doesn't
2775 refer to anything else.  There is no signature or any other
2776 verification of the data, so while the object is consistent (it 'is'
2777 indexed by its sha1 hash, so the data itself is certainly correct), it
2778 has absolutely no other attributes.  No name associations, no
2779 permissions.  It is purely a blob of data (i.e. normally "file
2780 contents").
2782 In particular, since the blob is entirely defined by its data, if two
2783 files in a directory tree (or in multiple different versions of the
2784 repository) have the same contents, they will share the same blob
2785 object. The object is totally independent of its location in the
2786 directory tree, and renaming a file does not change the object that
2787 file is associated with in any way.
2789 A blob is typically created when gitlink:git-update-index[1]
2790 is run, and its data can be accessed by gitlink:git-cat-file[1].
2792 [[tree-object]]
2793 Tree Object
2794 -----------
2796 The next hierarchical object type is the "tree" object.  A tree object
2797 is a list of mode/name/blob data, sorted by name.  Alternatively, the
2798 mode data may specify a directory mode, in which case instead of
2799 naming a blob, that name is associated with another TREE object.
2801 Like the "blob" object, a tree object is uniquely determined by the
2802 set contents, and so two separate but identical trees will always
2803 share the exact same object. This is true at all levels, i.e. it's
2804 true for a "leaf" tree (which does not refer to any other trees, only
2805 blobs) as well as for a whole subdirectory.
2807 For that reason a "tree" object is just a pure data abstraction: it
2808 has no history, no signatures, no verification of validity, except
2809 that since the contents are again protected by the hash itself, we can
2810 trust that the tree is immutable and its contents never change.
2812 So you can trust the contents of a tree to be valid, the same way you
2813 can trust the contents of a blob, but you don't know where those
2814 contents 'came' from.
2816 Side note on trees: since a "tree" object is a sorted list of
2817 "filename+content", you can create a diff between two trees without
2818 actually having to unpack two trees.  Just ignore all common parts,
2819 and your diff will look right.  In other words, you can effectively
2820 (and efficiently) tell the difference between any two random trees by
2821 O(n) where "n" is the size of the difference, rather than the size of
2822 the tree.
2824 Side note 2 on trees: since the name of a "blob" depends entirely and
2825 exclusively on its contents (i.e. there are no names or permissions
2826 involved), you can see trivial renames or permission changes by
2827 noticing that the blob stayed the same.  However, renames with data
2828 changes need a smarter "diff" implementation.
2830 A tree is created with gitlink:git-write-tree[1] and
2831 its data can be accessed by gitlink:git-ls-tree[1].
2832 Two trees can be compared with gitlink:git-diff-tree[1].
2834 [[commit-object]]
2835 Commit Object
2836 -------------
2838 The "commit" object is an object that introduces the notion of
2839 history into the picture.  In contrast to the other objects, it
2840 doesn't just describe the physical state of a tree, it describes how
2841 we got there, and why.
2843 A "commit" is defined by the tree-object that it results in, the
2844 parent commits (zero, one or more) that led up to that point, and a
2845 comment on what happened.  Again, a commit is not trusted per se:
2846 the contents are well-defined and "safe" due to the cryptographically
2847 strong signatures at all levels, but there is no reason to believe
2848 that the tree is "good" or that the merge information makes sense.
2849 The parents do not have to actually have any relationship with the
2850 result, for example.
2852 Note on commits: unlike some SCM's, commits do not contain
2853 rename information or file mode change information.  All of that is
2854 implicit in the trees involved (the result tree, and the result trees
2855 of the parents), and describing that makes no sense in this idiotic
2856 file manager.
2858 A commit is created with gitlink:git-commit-tree[1] and
2859 its data can be accessed by gitlink:git-cat-file[1].
2861 [[trust]]
2862 Trust
2863 -----
2865 An aside on the notion of "trust". Trust is really outside the scope
2866 of "git", but it's worth noting a few things.  First off, since
2867 everything is hashed with SHA1, you 'can' trust that an object is
2868 intact and has not been messed with by external sources.  So the name
2869 of an object uniquely identifies a known state - just not a state that
2870 you may want to trust.
2872 Furthermore, since the SHA1 signature of a commit refers to the
2873 SHA1 signatures of the tree it is associated with and the signatures
2874 of the parent, a single named commit specifies uniquely a whole set
2875 of history, with full contents.  You can't later fake any step of the
2876 way once you have the name of a commit.
2878 So to introduce some real trust in the system, the only thing you need
2879 to do is to digitally sign just 'one' special note, which includes the
2880 name of a top-level commit.  Your digital signature shows others
2881 that you trust that commit, and the immutability of the history of
2882 commits tells others that they can trust the whole history.
2884 In other words, you can easily validate a whole archive by just
2885 sending out a single email that tells the people the name (SHA1 hash)
2886 of the top commit, and digitally sign that email using something
2887 like GPG/PGP.
2889 To assist in this, git also provides the tag object...
2891 [[tag-object]]
2892 Tag Object
2893 ----------
2895 Git provides the "tag" object to simplify creating, managing and
2896 exchanging symbolic and signed tokens.  The "tag" object at its
2897 simplest simply symbolically identifies another object by containing
2898 the sha1, type and symbolic name.
2900 However it can optionally contain additional signature information
2901 (which git doesn't care about as long as there's less than 8k of
2902 it). This can then be verified externally to git.
2904 Note that despite the tag features, "git" itself only handles content
2905 integrity; the trust framework (and signature provision and
2906 verification) has to come from outside.
2908 A tag is created with gitlink:git-mktag[1],
2909 its data can be accessed by gitlink:git-cat-file[1],
2910 and the signature can be verified by
2911 gitlink:git-verify-tag[1].
2914 [[the-index]]
2915 The "index" aka "Current Directory Cache"
2916 -----------------------------------------
2918 The index is a simple binary file, which contains an efficient
2919 representation of the contents of a virtual directory.  It
2920 does so by a simple array that associates a set of names, dates,
2921 permissions and content (aka "blob") objects together.  The cache is
2922 always kept ordered by name, and names are unique (with a few very
2923 specific rules) at any point in time, but the cache has no long-term
2924 meaning, and can be partially updated at any time.
2926 In particular, the index certainly does not need to be consistent with
2927 the current directory contents (in fact, most operations will depend on
2928 different ways to make the index 'not' be consistent with the directory
2929 hierarchy), but it has three very important attributes:
2931 '(a) it can re-generate the full state it caches (not just the
2932 directory structure: it contains pointers to the "blob" objects so
2933 that it can regenerate the data too)'
2935 As a special case, there is a clear and unambiguous one-way mapping
2936 from a current directory cache to a "tree object", which can be
2937 efficiently created from just the current directory cache without
2938 actually looking at any other data.  So a directory cache at any one
2939 time uniquely specifies one and only one "tree" object (but has
2940 additional data to make it easy to match up that tree object with what
2941 has happened in the directory)
2943 '(b) it has efficient methods for finding inconsistencies between that
2944 cached state ("tree object waiting to be instantiated") and the
2945 current state.'
2947 '(c) it can additionally efficiently represent information about merge
2948 conflicts between different tree objects, allowing each pathname to be
2949 associated with sufficient information about the trees involved that
2950 you can create a three-way merge between them.'
2952 Those are the ONLY three things that the directory cache does.  It's a
2953 cache, and the normal operation is to re-generate it completely from a
2954 known tree object, or update/compare it with a live tree that is being
2955 developed.  If you blow the directory cache away entirely, you generally
2956 haven't lost any information as long as you have the name of the tree
2957 that it described. 
2959 At the same time, the index is at the same time also the
2960 staging area for creating new trees, and creating a new tree always
2961 involves a controlled modification of the index file.  In particular,
2962 the index file can have the representation of an intermediate tree that
2963 has not yet been instantiated.  So the index can be thought of as a
2964 write-back cache, which can contain dirty information that has not yet
2965 been written back to the backing store.
2969 [[the-workflow]]
2970 The Workflow
2971 ------------
2973 Generally, all "git" operations work on the index file. Some operations
2974 work *purely* on the index file (showing the current state of the
2975 index), but most operations move data to and from the index file. Either
2976 from the database or from the working directory. Thus there are four
2977 main combinations: 
2979 [[working-directory-to-index]]
2980 working directory -> index
2981 ~~~~~~~~~~~~~~~~~~~~~~~~~~
2983 You update the index with information from the working directory with
2984 the gitlink:git-update-index[1] command.  You
2985 generally update the index information by just specifying the filename
2986 you want to update, like so:
2988 -------------------------------------------------
2989 $ git-update-index filename
2990 -------------------------------------------------
2992 but to avoid common mistakes with filename globbing etc, the command
2993 will not normally add totally new entries or remove old entries,
2994 i.e. it will normally just update existing cache entries.
2996 To tell git that yes, you really do realize that certain files no
2997 longer exist, or that new files should be added, you
2998 should use the `--remove` and `--add` flags respectively.
3000 NOTE! A `--remove` flag does 'not' mean that subsequent filenames will
3001 necessarily be removed: if the files still exist in your directory
3002 structure, the index will be updated with their new status, not
3003 removed. The only thing `--remove` means is that update-cache will be
3004 considering a removed file to be a valid thing, and if the file really
3005 does not exist any more, it will update the index accordingly.
3007 As a special case, you can also do `git-update-index --refresh`, which
3008 will refresh the "stat" information of each index to match the current
3009 stat information. It will 'not' update the object status itself, and
3010 it will only update the fields that are used to quickly test whether
3011 an object still matches its old backing store object.
3013 [[index-to-object-database]]
3014 index -> object database
3015 ~~~~~~~~~~~~~~~~~~~~~~~~
3017 You write your current index file to a "tree" object with the program
3019 -------------------------------------------------
3020 $ git-write-tree
3021 -------------------------------------------------
3023 that doesn't come with any options - it will just write out the
3024 current index into the set of tree objects that describe that state,
3025 and it will return the name of the resulting top-level tree. You can
3026 use that tree to re-generate the index at any time by going in the
3027 other direction:
3029 [[object-database-to-index]]
3030 object database -> index
3031 ~~~~~~~~~~~~~~~~~~~~~~~~
3033 You read a "tree" file from the object database, and use that to
3034 populate (and overwrite - don't do this if your index contains any
3035 unsaved state that you might want to restore later!) your current
3036 index.  Normal operation is just
3038 -------------------------------------------------
3039 $ git-read-tree <sha1 of tree>
3040 -------------------------------------------------
3042 and your index file will now be equivalent to the tree that you saved
3043 earlier. However, that is only your 'index' file: your working
3044 directory contents have not been modified.
3046 [[index-to-working-directory]]
3047 index -> working directory
3048 ~~~~~~~~~~~~~~~~~~~~~~~~~~
3050 You update your working directory from the index by "checking out"
3051 files. This is not a very common operation, since normally you'd just
3052 keep your files updated, and rather than write to your working
3053 directory, you'd tell the index files about the changes in your
3054 working directory (i.e. `git-update-index`).
3056 However, if you decide to jump to a new version, or check out somebody
3057 else's version, or just restore a previous tree, you'd populate your
3058 index file with read-tree, and then you need to check out the result
3059 with
3061 -------------------------------------------------
3062 $ git-checkout-index filename
3063 -------------------------------------------------
3065 or, if you want to check out all of the index, use `-a`.
3067 NOTE! git-checkout-index normally refuses to overwrite old files, so
3068 if you have an old version of the tree already checked out, you will
3069 need to use the "-f" flag ('before' the "-a" flag or the filename) to
3070 'force' the checkout.
3073 Finally, there are a few odds and ends which are not purely moving
3074 from one representation to the other:
3076 [[tying-it-all-together]]
3077 Tying it all together
3078 ~~~~~~~~~~~~~~~~~~~~~
3080 To commit a tree you have instantiated with "git-write-tree", you'd
3081 create a "commit" object that refers to that tree and the history
3082 behind it - most notably the "parent" commits that preceded it in
3083 history.
3085 Normally a "commit" has one parent: the previous state of the tree
3086 before a certain change was made. However, sometimes it can have two
3087 or more parent commits, in which case we call it a "merge", due to the
3088 fact that such a commit brings together ("merges") two or more
3089 previous states represented by other commits.
3091 In other words, while a "tree" represents a particular directory state
3092 of a working directory, a "commit" represents that state in "time",
3093 and explains how we got there.
3095 You create a commit object by giving it the tree that describes the
3096 state at the time of the commit, and a list of parents:
3098 -------------------------------------------------
3099 $ git-commit-tree <tree> -p <parent> [-p <parent2> ..]
3100 -------------------------------------------------
3102 and then giving the reason for the commit on stdin (either through
3103 redirection from a pipe or file, or by just typing it at the tty).
3105 git-commit-tree will return the name of the object that represents
3106 that commit, and you should save it away for later use. Normally,
3107 you'd commit a new `HEAD` state, and while git doesn't care where you
3108 save the note about that state, in practice we tend to just write the
3109 result to the file pointed at by `.git/HEAD`, so that we can always see
3110 what the last committed state was.
3112 Here is an ASCII art by Jon Loeliger that illustrates how
3113 various pieces fit together.
3115 ------------
3117                      commit-tree
3118                       commit obj
3119                        +----+
3120                        |    |
3121                        |    |
3122                        V    V
3123                     +-----------+
3124                     | Object DB |
3125                     |  Backing  |
3126                     |   Store   |
3127                     +-----------+
3128                        ^
3129            write-tree  |     |
3130              tree obj  |     |
3131                        |     |  read-tree
3132                        |     |  tree obj
3133                              V
3134                     +-----------+
3135                     |   Index   |
3136                     |  "cache"  |
3137                     +-----------+
3138          update-index  ^
3139              blob obj  |     |
3140                        |     |
3141     checkout-index -u  |     |  checkout-index
3142              stat      |     |  blob obj
3143                              V
3144                     +-----------+
3145                     |  Working  |
3146                     | Directory |
3147                     +-----------+
3149 ------------
3152 [[examining-the-data]]
3153 Examining the data
3154 ------------------
3156 You can examine the data represented in the object database and the
3157 index with various helper tools. For every object, you can use
3158 gitlink:git-cat-file[1] to examine details about the
3159 object:
3161 -------------------------------------------------
3162 $ git-cat-file -t <objectname>
3163 -------------------------------------------------
3165 shows the type of the object, and once you have the type (which is
3166 usually implicit in where you find the object), you can use
3168 -------------------------------------------------
3169 $ git-cat-file blob|tree|commit|tag <objectname>
3170 -------------------------------------------------
3172 to show its contents. NOTE! Trees have binary content, and as a result
3173 there is a special helper for showing that content, called
3174 `git-ls-tree`, which turns the binary content into a more easily
3175 readable form.
3177 It's especially instructive to look at "commit" objects, since those
3178 tend to be small and fairly self-explanatory. In particular, if you
3179 follow the convention of having the top commit name in `.git/HEAD`,
3180 you can do
3182 -------------------------------------------------
3183 $ git-cat-file commit HEAD
3184 -------------------------------------------------
3186 to see what the top commit was.
3188 [[merging-multiple-trees]]
3189 Merging multiple trees
3190 ----------------------
3192 Git helps you do a three-way merge, which you can expand to n-way by
3193 repeating the merge procedure arbitrary times until you finally
3194 "commit" the state.  The normal situation is that you'd only do one
3195 three-way merge (two parents), and commit it, but if you like to, you
3196 can do multiple parents in one go.
3198 To do a three-way merge, you need the two sets of "commit" objects
3199 that you want to merge, use those to find the closest common parent (a
3200 third "commit" object), and then use those commit objects to find the
3201 state of the directory ("tree" object) at these points.
3203 To get the "base" for the merge, you first look up the common parent
3204 of two commits with
3206 -------------------------------------------------
3207 $ git-merge-base <commit1> <commit2>
3208 -------------------------------------------------
3210 which will return you the commit they are both based on.  You should
3211 now look up the "tree" objects of those commits, which you can easily
3212 do with (for example)
3214 -------------------------------------------------
3215 $ git-cat-file commit <commitname> | head -1
3216 -------------------------------------------------
3218 since the tree object information is always the first line in a commit
3219 object.
3221 Once you know the three trees you are going to merge (the one "original"
3222 tree, aka the common tree, and the two "result" trees, aka the branches
3223 you want to merge), you do a "merge" read into the index. This will
3224 complain if it has to throw away your old index contents, so you should
3225 make sure that you've committed those - in fact you would normally
3226 always do a merge against your last commit (which should thus match what
3227 you have in your current index anyway).
3229 To do the merge, do
3231 -------------------------------------------------
3232 $ git-read-tree -m -u <origtree> <yourtree> <targettree>
3233 -------------------------------------------------
3235 which will do all trivial merge operations for you directly in the
3236 index file, and you can just write the result out with
3237 `git-write-tree`.
3240 [[merging-multiple-trees-2]]
3241 Merging multiple trees, continued
3242 ---------------------------------
3244 Sadly, many merges aren't trivial. If there are files that have
3245 been added.moved or removed, or if both branches have modified the
3246 same file, you will be left with an index tree that contains "merge
3247 entries" in it. Such an index tree can 'NOT' be written out to a tree
3248 object, and you will have to resolve any such merge clashes using
3249 other tools before you can write out the result.
3251 You can examine such index state with `git-ls-files --unmerged`
3252 command.  An example:
3254 ------------------------------------------------
3255 $ git-read-tree -m $orig HEAD $target
3256 $ git-ls-files --unmerged
3257 100644 263414f423d0e4d70dae8fe53fa34614ff3e2860 1       hello.c
3258 100644 06fa6a24256dc7e560efa5687fa84b51f0263c3a 2       hello.c
3259 100644 cc44c73eb783565da5831b4d820c962954019b69 3       hello.c
3260 ------------------------------------------------
3262 Each line of the `git-ls-files --unmerged` output begins with
3263 the blob mode bits, blob SHA1, 'stage number', and the
3264 filename.  The 'stage number' is git's way to say which tree it
3265 came from: stage 1 corresponds to `$orig` tree, stage 2 `HEAD`
3266 tree, and stage3 `$target` tree.
3268 Earlier we said that trivial merges are done inside
3269 `git-read-tree -m`.  For example, if the file did not change
3270 from `$orig` to `HEAD` nor `$target`, or if the file changed
3271 from `$orig` to `HEAD` and `$orig` to `$target` the same way,
3272 obviously the final outcome is what is in `HEAD`.  What the
3273 above example shows is that file `hello.c` was changed from
3274 `$orig` to `HEAD` and `$orig` to `$target` in a different way.
3275 You could resolve this by running your favorite 3-way merge
3276 program, e.g.  `diff3`, `merge`, or git's own merge-file, on
3277 the blob objects from these three stages yourself, like this:
3279 ------------------------------------------------
3280 $ git-cat-file blob 263414f... >hello.c~1
3281 $ git-cat-file blob 06fa6a2... >hello.c~2
3282 $ git-cat-file blob cc44c73... >hello.c~3
3283 $ git merge-file hello.c~2 hello.c~1 hello.c~3
3284 ------------------------------------------------
3286 This would leave the merge result in `hello.c~2` file, along
3287 with conflict markers if there are conflicts.  After verifying
3288 the merge result makes sense, you can tell git what the final
3289 merge result for this file is by:
3291 -------------------------------------------------
3292 $ mv -f hello.c~2 hello.c
3293 $ git-update-index hello.c
3294 -------------------------------------------------
3296 When a path is in unmerged state, running `git-update-index` for
3297 that path tells git to mark the path resolved.
3299 The above is the description of a git merge at the lowest level,
3300 to help you understand what conceptually happens under the hood.
3301 In practice, nobody, not even git itself, uses three `git-cat-file`
3302 for this.  There is `git-merge-index` program that extracts the
3303 stages to temporary files and calls a "merge" script on it:
3305 -------------------------------------------------
3306 $ git-merge-index git-merge-one-file hello.c
3307 -------------------------------------------------
3309 and that is what higher level `git merge -s resolve` is implemented with.
3311 [[pack-files]]
3312 How git stores objects efficiently: pack files
3313 ----------------------------------------------
3315 We've seen how git stores each object in a file named after the
3316 object's SHA1 hash.
3318 Unfortunately this system becomes inefficient once a project has a
3319 lot of objects.  Try this on an old project:
3321 ------------------------------------------------
3322 $ git count-objects
3323 6930 objects, 47620 kilobytes
3324 ------------------------------------------------
3326 The first number is the number of objects which are kept in
3327 individual files.  The second is the amount of space taken up by
3328 those "loose" objects.
3330 You can save space and make git faster by moving these loose objects in
3331 to a "pack file", which stores a group of objects in an efficient
3332 compressed format; the details of how pack files are formatted can be
3333 found in link:technical/pack-format.txt[technical/pack-format.txt].
3335 To put the loose objects into a pack, just run git repack:
3337 ------------------------------------------------
3338 $ git repack
3339 Generating pack...
3340 Done counting 6020 objects.
3341 Deltifying 6020 objects.
3342  100% (6020/6020) done
3343 Writing 6020 objects.
3344  100% (6020/6020) done
3345 Total 6020, written 6020 (delta 4070), reused 0 (delta 0)
3346 Pack pack-3e54ad29d5b2e05838c75df582c65257b8d08e1c created.
3347 ------------------------------------------------
3349 You can then run
3351 ------------------------------------------------
3352 $ git prune
3353 ------------------------------------------------
3355 to remove any of the "loose" objects that are now contained in the
3356 pack.  This will also remove any unreferenced objects (which may be
3357 created when, for example, you use "git reset" to remove a commit).
3358 You can verify that the loose objects are gone by looking at the
3359 .git/objects directory or by running
3361 ------------------------------------------------
3362 $ git count-objects
3363 0 objects, 0 kilobytes
3364 ------------------------------------------------
3366 Although the object files are gone, any commands that refer to those
3367 objects will work exactly as they did before.
3369 The gitlink:git-gc[1] command performs packing, pruning, and more for
3370 you, so is normally the only high-level command you need.
3372 [[dangling-objects]]
3373 Dangling objects
3374 ----------------
3376 The gitlink:git-fsck[1] command will sometimes complain about dangling
3377 objects.  They are not a problem.
3379 The most common cause of dangling objects is that you've rebased a
3380 branch, or you have pulled from somebody else who rebased a branch--see
3381 <<cleaning-up-history>>.  In that case, the old head of the original
3382 branch still exists, as does everything it pointed to. The branch
3383 pointer itself just doesn't, since you replaced it with another one.
3385 There are also other situations that cause dangling objects. For
3386 example, a "dangling blob" may arise because you did a "git add" of a
3387 file, but then, before you actually committed it and made it part of the
3388 bigger picture, you changed something else in that file and committed
3389 that *updated* thing - the old state that you added originally ends up
3390 not being pointed to by any commit or tree, so it's now a dangling blob
3391 object.
3393 Similarly, when the "recursive" merge strategy runs, and finds that
3394 there are criss-cross merges and thus more than one merge base (which is
3395 fairly unusual, but it does happen), it will generate one temporary
3396 midway tree (or possibly even more, if you had lots of criss-crossing
3397 merges and more than two merge bases) as a temporary internal merge
3398 base, and again, those are real objects, but the end result will not end
3399 up pointing to them, so they end up "dangling" in your repository.
3401 Generally, dangling objects aren't anything to worry about. They can
3402 even be very useful: if you screw something up, the dangling objects can
3403 be how you recover your old tree (say, you did a rebase, and realized
3404 that you really didn't want to - you can look at what dangling objects
3405 you have, and decide to reset your head to some old dangling state).
3407 For commits, you can just use:
3409 ------------------------------------------------
3410 $ gitk <dangling-commit-sha-goes-here> --not --all
3411 ------------------------------------------------
3413 This asks for all the history reachable from the given commit but not
3414 from any branch, tag, or other reference.  If you decide it's something
3415 you want, you can always create a new reference to it, e.g.,
3417 ------------------------------------------------
3418 $ git branch recovered-branch <dangling-commit-sha-goes-here>
3419 ------------------------------------------------
3421 For blobs and trees, you can't do the same, but you can still examine
3422 them.  You can just do
3424 ------------------------------------------------
3425 $ git show <dangling-blob/tree-sha-goes-here>
3426 ------------------------------------------------
3428 to show what the contents of the blob were (or, for a tree, basically
3429 what the "ls" for that directory was), and that may give you some idea
3430 of what the operation was that left that dangling object.
3432 Usually, dangling blobs and trees aren't very interesting. They're
3433 almost always the result of either being a half-way mergebase (the blob
3434 will often even have the conflict markers from a merge in it, if you
3435 have had conflicting merges that you fixed up by hand), or simply
3436 because you interrupted a "git fetch" with ^C or something like that,
3437 leaving _some_ of the new objects in the object database, but just
3438 dangling and useless.
3440 Anyway, once you are sure that you're not interested in any dangling 
3441 state, you can just prune all unreachable objects:
3443 ------------------------------------------------
3444 $ git prune
3445 ------------------------------------------------
3447 and they'll be gone. But you should only run "git prune" on a quiescent
3448 repository - it's kind of like doing a filesystem fsck recovery: you
3449 don't want to do that while the filesystem is mounted.
3451 (The same is true of "git-fsck" itself, btw - but since 
3452 git-fsck never actually *changes* the repository, it just reports 
3453 on what it found, git-fsck itself is never "dangerous" to run. 
3454 Running it while somebody is actually changing the repository can cause 
3455 confusing and scary messages, but it won't actually do anything bad. In 
3456 contrast, running "git prune" while somebody is actively changing the 
3457 repository is a *BAD* idea).
3459 [[birdview-on-the-source-code]]
3460 A birds-eye view of Git's source code
3461 -------------------------------------
3463 It is not always easy for new developers to find their way through Git's
3464 source code.  This section gives you a little guidance to show where to
3465 start.
3467 A good place to start is with the contents of the initial commit, with:
3469 ----------------------------------------------------
3470 $ git checkout e83c5163
3471 ----------------------------------------------------
3473 The initial revision lays the foundation for almost everything git has
3474 today, but is small enough to read in one sitting.
3476 Note that terminology has changed since that revision.  For example, the
3477 README in that revision uses the word "changeset" to describe what we
3478 now call a <<def_commit_object,commit>>.
3480 Also, we do not call it "cache" any more, but "index", however, the
3481 file is still called `cache.h`.  Remark: Not much reason to change it now,
3482 especially since there is no good single name for it anyway, because it is
3483 basically _the_ header file which is included by _all_ of Git's C sources.
3485 If you grasp the ideas in that initial commit, you should check out a
3486 more recent version and skim `cache.h`, `object.h` and `commit.h`.
3488 In the early days, Git (in the tradition of UNIX) was a bunch of programs
3489 which were extremely simple, and which you used in scripts, piping the
3490 output of one into another. This turned out to be good for initial
3491 development, since it was easier to test new things.  However, recently
3492 many of these parts have become builtins, and some of the core has been
3493 "libified", i.e. put into libgit.a for performance, portability reasons,
3494 and to avoid code duplication.
3496 By now, you know what the index is (and find the corresponding data
3497 structures in `cache.h`), and that there are just a couple of object types
3498 (blobs, trees, commits and tags) which inherit their common structure from
3499 `struct object`, which is their first member (and thus, you can cast e.g.
3500 `(struct object *)commit` to achieve the _same_ as `&commit->object`, i.e.
3501 get at the object name and flags).
3503 Now is a good point to take a break to let this information sink in.
3505 Next step: get familiar with the object naming.  Read <<naming-commits>>.
3506 There are quite a few ways to name an object (and not only revisions!).
3507 All of these are handled in `sha1_name.c`. Just have a quick look at
3508 the function `get_sha1()`. A lot of the special handling is done by
3509 functions like `get_sha1_basic()` or the likes.
3511 This is just to get you into the groove for the most libified part of Git:
3512 the revision walker.
3514 Basically, the initial version of `git log` was a shell script:
3516 ----------------------------------------------------------------
3517 $ git-rev-list --pretty $(git-rev-parse --default HEAD "$@") | \
3518         LESS=-S ${PAGER:-less}
3519 ----------------------------------------------------------------
3521 What does this mean?
3523 `git-rev-list` is the original version of the revision walker, which
3524 _always_ printed a list of revisions to stdout.  It is still functional,
3525 and needs to, since most new Git programs start out as scripts using
3526 `git-rev-list`.
3528 `git-rev-parse` is not as important any more; it was only used to filter out
3529 options that were relevant for the different plumbing commands that were
3530 called by the script.
3532 Most of what `git-rev-list` did is contained in `revision.c` and
3533 `revision.h`.  It wraps the options in a struct named `rev_info`, which
3534 controls how and what revisions are walked, and more.
3536 The original job of `git-rev-parse` is now taken by the function
3537 `setup_revisions()`, which parses the revisions and the common command line
3538 options for the revision walker. This information is stored in the struct
3539 `rev_info` for later consumption. You can do your own command line option
3540 parsing after calling `setup_revisions()`. After that, you have to call
3541 `prepare_revision_walk()` for initialization, and then you can get the
3542 commits one by one with the function `get_revision()`.
3544 If you are interested in more details of the revision walking process,
3545 just have a look at the first implementation of `cmd_log()`; call
3546 `git-show v1.3.0~155^2~4` and scroll down to that function (note that you
3547 no longer need to call `setup_pager()` directly).
3549 Nowadays, `git log` is a builtin, which means that it is _contained_ in the
3550 command `git`.  The source side of a builtin is
3552 - a function called `cmd_<bla>`, typically defined in `builtin-<bla>.c`,
3553   and declared in `builtin.h`,
3555 - an entry in the `commands[]` array in `git.c`, and
3557 - an entry in `BUILTIN_OBJECTS` in the `Makefile`.
3559 Sometimes, more than one builtin is contained in one source file.  For
3560 example, `cmd_whatchanged()` and `cmd_log()` both reside in `builtin-log.c`,
3561 since they share quite a bit of code.  In that case, the commands which are
3562 _not_ named like the `.c` file in which they live have to be listed in
3563 `BUILT_INS` in the `Makefile`.
3565 `git log` looks more complicated in C than it does in the original script,
3566 but that allows for a much greater flexibility and performance.
3568 Here again it is a good point to take a pause.
3570 Lesson three is: study the code.  Really, it is the best way to learn about
3571 the organization of Git (after you know the basic concepts).
3573 So, think about something which you are interested in, say, "how can I
3574 access a blob just knowing the object name of it?".  The first step is to
3575 find a Git command with which you can do it.  In this example, it is either
3576 `git show` or `git cat-file`.
3578 For the sake of clarity, let's stay with `git cat-file`, because it
3580 - is plumbing, and
3582 - was around even in the initial commit (it literally went only through
3583   some 20 revisions as `cat-file.c`, was renamed to `builtin-cat-file.c`
3584   when made a builtin, and then saw less than 10 versions).
3586 So, look into `builtin-cat-file.c`, search for `cmd_cat_file()` and look what
3587 it does.
3589 ------------------------------------------------------------------
3590         git_config(git_default_config);
3591         if (argc != 3)
3592                 usage("git-cat-file [-t|-s|-e|-p|<type>] <sha1>");
3593         if (get_sha1(argv[2], sha1))
3594                 die("Not a valid object name %s", argv[2]);
3595 ------------------------------------------------------------------
3597 Let's skip over the obvious details; the only really interesting part
3598 here is the call to `get_sha1()`.  It tries to interpret `argv[2]` as an
3599 object name, and if it refers to an object which is present in the current
3600 repository, it writes the resulting SHA-1 into the variable `sha1`.
3602 Two things are interesting here:
3604 - `get_sha1()` returns 0 on _success_.  This might surprise some new
3605   Git hackers, but there is a long tradition in UNIX to return different
3606   negative numbers in case of different errors -- and 0 on success.
3608 - the variable `sha1` in the function signature of `get_sha1()` is `unsigned
3609   char \*`, but is actually expected to be a pointer to `unsigned
3610   char[20]`.  This variable will contain the 160-bit SHA-1 of the given
3611   commit.  Note that whenever a SHA-1 is passed as `unsigned char \*`, it
3612   is the binary representation, as opposed to the ASCII representation in
3613   hex characters, which is passed as `char *`.
3615 You will see both of these things throughout the code.
3617 Now, for the meat:
3619 -----------------------------------------------------------------------------
3620         case 0:
3621                 buf = read_object_with_reference(sha1, argv[1], &size, NULL);
3622 -----------------------------------------------------------------------------
3624 This is how you read a blob (actually, not only a blob, but any type of
3625 object).  To know how the function `read_object_with_reference()` actually
3626 works, find the source code for it (something like `git grep
3627 read_object_with | grep ":[a-z]"` in the git repository), and read
3628 the source.
3630 To find out how the result can be used, just read on in `cmd_cat_file()`:
3632 -----------------------------------
3633         write_or_die(1, buf, size);
3634 -----------------------------------
3636 Sometimes, you do not know where to look for a feature.  In many such cases,
3637 it helps to search through the output of `git log`, and then `git show` the
3638 corresponding commit.
3640 Example: If you know that there was some test case for `git bundle`, but
3641 do not remember where it was (yes, you _could_ `git grep bundle t/`, but that
3642 does not illustrate the point!):
3644 ------------------------
3645 $ git log --no-merges t/
3646 ------------------------
3648 In the pager (`less`), just search for "bundle", go a few lines back,
3649 and see that it is in commit 18449ab0...  Now just copy this object name,
3650 and paste it into the command line
3652 -------------------
3653 $ git show 18449ab0
3654 -------------------
3656 Voila.
3658 Another example: Find out what to do in order to make some script a
3659 builtin:
3661 -------------------------------------------------
3662 $ git log --no-merges --diff-filter=A builtin-*.c
3663 -------------------------------------------------
3665 You see, Git is actually the best tool to find out about the source of Git
3666 itself!
3668 [[glossary]]
3669 include::glossary.txt[]
3671 [[git-quick-start]]
3672 Appendix A: Git Quick Reference
3673 ===============================
3675 This is a quick summary of the major commands; the previous chapters
3676 explain how these work in more detail.
3678 [[quick-creating-a-new-repository]]
3679 Creating a new repository
3680 -------------------------
3682 From a tarball:
3684 -----------------------------------------------
3685 $ tar xzf project.tar.gz
3686 $ cd project
3687 $ git init
3688 Initialized empty Git repository in .git/
3689 $ git add .
3690 $ git commit
3691 -----------------------------------------------
3693 From a remote repository:
3695 -----------------------------------------------
3696 $ git clone git://example.com/pub/project.git
3697 $ cd project
3698 -----------------------------------------------
3700 [[managing-branches]]
3701 Managing branches
3702 -----------------
3704 -----------------------------------------------
3705 $ git branch         # list all local branches in this repo
3706 $ git checkout test  # switch working directory to branch "test"
3707 $ git branch new     # create branch "new" starting at current HEAD
3708 $ git branch -d new  # delete branch "new"
3709 -----------------------------------------------
3711 Instead of basing new branch on current HEAD (the default), use:
3713 -----------------------------------------------
3714 $ git branch new test    # branch named "test"
3715 $ git branch new v2.6.15 # tag named v2.6.15
3716 $ git branch new HEAD^   # commit before the most recent
3717 $ git branch new HEAD^^  # commit before that
3718 $ git branch new test~10 # ten commits before tip of branch "test"
3719 -----------------------------------------------
3721 Create and switch to a new branch at the same time:
3723 -----------------------------------------------
3724 $ git checkout -b new v2.6.15
3725 -----------------------------------------------
3727 Update and examine branches from the repository you cloned from:
3729 -----------------------------------------------
3730 $ git fetch             # update
3731 $ git branch -r         # list
3732   origin/master
3733   origin/next
3734   ...
3735 $ git checkout -b masterwork origin/master
3736 -----------------------------------------------
3738 Fetch a branch from a different repository, and give it a new
3739 name in your repository:
3741 -----------------------------------------------
3742 $ git fetch git://example.com/project.git theirbranch:mybranch
3743 $ git fetch git://example.com/project.git v2.6.15:mybranch
3744 -----------------------------------------------
3746 Keep a list of repositories you work with regularly:
3748 -----------------------------------------------
3749 $ git remote add example git://example.com/project.git
3750 $ git remote                    # list remote repositories
3751 example
3752 origin
3753 $ git remote show example       # get details
3754 * remote example
3755   URL: git://example.com/project.git
3756   Tracked remote branches
3757     master next ...
3758 $ git fetch example             # update branches from example
3759 $ git branch -r                 # list all remote branches
3760 -----------------------------------------------
3763 [[exploring-history]]
3764 Exploring history
3765 -----------------
3767 -----------------------------------------------
3768 $ gitk                      # visualize and browse history
3769 $ git log                   # list all commits
3770 $ git log src/              # ...modifying src/
3771 $ git log v2.6.15..v2.6.16  # ...in v2.6.16, not in v2.6.15
3772 $ git log master..test      # ...in branch test, not in branch master
3773 $ git log test..master      # ...in branch master, but not in test
3774 $ git log test...master     # ...in one branch, not in both
3775 $ git log -S'foo()'         # ...where difference contain "foo()"
3776 $ git log --since="2 weeks ago"
3777 $ git log -p                # show patches as well
3778 $ git show                  # most recent commit
3779 $ git diff v2.6.15..v2.6.16 # diff between two tagged versions
3780 $ git diff v2.6.15..HEAD    # diff with current head
3781 $ git grep "foo()"          # search working directory for "foo()"
3782 $ git grep v2.6.15 "foo()"  # search old tree for "foo()"
3783 $ git show v2.6.15:a.txt    # look at old version of a.txt
3784 -----------------------------------------------
3786 Search for regressions:
3788 -----------------------------------------------
3789 $ git bisect start
3790 $ git bisect bad                # current version is bad
3791 $ git bisect good v2.6.13-rc2   # last known good revision
3792 Bisecting: 675 revisions left to test after this
3793                                 # test here, then:
3794 $ git bisect good               # if this revision is good, or
3795 $ git bisect bad                # if this revision is bad.
3796                                 # repeat until done.
3797 -----------------------------------------------
3799 [[making-changes]]
3800 Making changes
3801 --------------
3803 Make sure git knows who to blame:
3805 ------------------------------------------------
3806 $ cat >>~/.gitconfig <<\EOF
3807 [user]
3808         name = Your Name Comes Here
3809         email = you@yourdomain.example.com
3811 ------------------------------------------------
3813 Select file contents to include in the next commit, then make the
3814 commit:
3816 -----------------------------------------------
3817 $ git add a.txt    # updated file
3818 $ git add b.txt    # new file
3819 $ git rm c.txt     # old file
3820 $ git commit
3821 -----------------------------------------------
3823 Or, prepare and create the commit in one step:
3825 -----------------------------------------------
3826 $ git commit d.txt # use latest content only of d.txt
3827 $ git commit -a    # use latest content of all tracked files
3828 -----------------------------------------------
3830 [[merging]]
3831 Merging
3832 -------
3834 -----------------------------------------------
3835 $ git merge test   # merge branch "test" into the current branch
3836 $ git pull git://example.com/project.git master
3837                    # fetch and merge in remote branch
3838 $ git pull . test  # equivalent to git merge test
3839 -----------------------------------------------
3841 [[sharing-your-changes]]
3842 Sharing your changes
3843 --------------------
3845 Importing or exporting patches:
3847 -----------------------------------------------
3848 $ git format-patch origin..HEAD # format a patch for each commit
3849                                 # in HEAD but not in origin
3850 $ git am mbox # import patches from the mailbox "mbox"
3851 -----------------------------------------------
3853 Fetch a branch in a different git repository, then merge into the
3854 current branch:
3856 -----------------------------------------------
3857 $ git pull git://example.com/project.git theirbranch
3858 -----------------------------------------------
3860 Store the fetched branch into a local branch before merging into the
3861 current branch:
3863 -----------------------------------------------
3864 $ git pull git://example.com/project.git theirbranch:mybranch
3865 -----------------------------------------------
3867 After creating commits on a local branch, update the remote
3868 branch with your commits:
3870 -----------------------------------------------
3871 $ git push ssh://example.com/project.git mybranch:theirbranch
3872 -----------------------------------------------
3874 When remote and local branch are both named "test":
3876 -----------------------------------------------
3877 $ git push ssh://example.com/project.git test
3878 -----------------------------------------------
3880 Shortcut version for a frequently used remote repository:
3882 -----------------------------------------------
3883 $ git remote add example ssh://example.com/project.git
3884 $ git push example test
3885 -----------------------------------------------
3887 [[repository-maintenance]]
3888 Repository maintenance
3889 ----------------------
3891 Check for corruption:
3893 -----------------------------------------------
3894 $ git fsck
3895 -----------------------------------------------
3897 Recompress, remove unused cruft:
3899 -----------------------------------------------
3900 $ git gc
3901 -----------------------------------------------
3904 [[todo]]
3905 Appendix B: Notes and todo list for this manual
3906 ===============================================
3908 This is a work in progress.
3910 The basic requirements:
3911         - It must be readable in order, from beginning to end, by
3912           someone intelligent with a basic grasp of the unix
3913           commandline, but without any special knowledge of git.  If
3914           necessary, any other prerequisites should be specifically
3915           mentioned as they arise.
3916         - Whenever possible, section headings should clearly describe
3917           the task they explain how to do, in language that requires
3918           no more knowledge than necessary: for example, "importing
3919           patches into a project" rather than "the git-am command"
3921 Think about how to create a clear chapter dependency graph that will
3922 allow people to get to important topics without necessarily reading
3923 everything in between.
3925 Scan Documentation/ for other stuff left out; in particular:
3926         howto's
3927         some of technical/?
3928         hooks
3929         list of commands in gitlink:git[1]
3931 Scan email archives for other stuff left out
3933 Scan man pages to see if any assume more background than this manual
3934 provides.
3936 Simplify beginning by suggesting disconnected head instead of
3937 temporary branch creation?
3939 Add more good examples.  Entire sections of just cookbook examples
3940 might be a good idea; maybe make an "advanced examples" section a
3941 standard end-of-chapter section?
3943 Include cross-references to the glossary, where appropriate.
3945 Document shallow clones?  See draft 1.5.0 release notes for some
3946 documentation.
3948 Add a section on working with other version control systems, including
3949 CVS, Subversion, and just imports of series of release tarballs.
3951 More details on gitweb?
3953 Write a chapter on using plumbing and writing scripts.