Code

5f7ecec3f130865c61d029d72ba976b5e00dee38
[git.git] / Documentation / user-manual.txt
1 Git User's Manual (for version 1.5.3 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
107 ...
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.
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).
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     };
177 ...
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 descendant 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
434 ...
435 [remote "linux-nfs"]
436         url = git://linux-nfs.org/pub/nfs-2.6.git
437         fetch = +refs/heads/*:refs/remotes/linux-nfs/*
438 ...
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 hierarchy, 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;
512 run
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
820 ...
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 "project/".
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-comments-with-given-content]]
925 Finding commits referencing a file with given content
926 -----------------------------------------------------
928 Somebody hands you a copy of a file, and asks which commits modified a
929 file such that it contained the given content either before or after the
930 commit.  You can find out with this:
932 -------------------------------------------------
933 $  git log --raw -r --abbrev=40 --pretty=oneline -- filename |
934         grep -B 1 `git hash-object filename`
935 -------------------------------------------------
937 Figuring out why this works is left as an exercise to the (advanced)
938 student.  The gitlink:git-log[1], gitlink:git-diff-tree[1], and
939 gitlink:git-hash-object[1] man pages may prove helpful.
941 [[Developing-with-git]]
942 Developing with git
943 ===================
945 [[telling-git-your-name]]
946 Telling git your name
947 ---------------------
949 Before creating any commits, you should introduce yourself to git.  The
950 easiest way to do so is to make sure the following lines appear in a
951 file named .gitconfig in your home directory:
953 ------------------------------------------------
954 [user]
955         name = Your Name Comes Here
956         email = you@yourdomain.example.com
957 ------------------------------------------------
959 (See the "CONFIGURATION FILE" section of gitlink:git-config[1] for
960 details on the configuration file.)
963 [[creating-a-new-repository]]
964 Creating a new repository
965 -------------------------
967 Creating a new repository from scratch is very easy:
969 -------------------------------------------------
970 $ mkdir project
971 $ cd project
972 $ git init
973 -------------------------------------------------
975 If you have some initial content (say, a tarball):
977 -------------------------------------------------
978 $ tar -xzvf project.tar.gz
979 $ cd project
980 $ git init
981 $ git add . # include everything below ./ in the first commit:
982 $ git commit
983 -------------------------------------------------
985 [[how-to-make-a-commit]]
986 How to make a commit
987 --------------------
989 Creating a new commit takes three steps:
991         1. Making some changes to the working directory using your
992            favorite editor.
993         2. Telling git about your changes.
994         3. Creating the commit using the content you told git about
995            in step 2.
997 In practice, you can interleave and repeat steps 1 and 2 as many
998 times as you want: in order to keep track of what you want committed
999 at step 3, git maintains a snapshot of the tree's contents in a
1000 special staging area called "the index."
1002 At the beginning, the content of the index will be identical to
1003 that of the HEAD.  The command "git diff --cached", which shows
1004 the difference between the HEAD and the index, should therefore
1005 produce no output at that point.
1007 Modifying the index is easy:
1009 To update the index with the new contents of a modified file, use
1011 -------------------------------------------------
1012 $ git add path/to/file
1013 -------------------------------------------------
1015 To add the contents of a new file to the index, use
1017 -------------------------------------------------
1018 $ git add path/to/file
1019 -------------------------------------------------
1021 To remove a file from the index and from the working tree,
1023 -------------------------------------------------
1024 $ git rm path/to/file
1025 -------------------------------------------------
1027 After each step you can verify that
1029 -------------------------------------------------
1030 $ git diff --cached
1031 -------------------------------------------------
1033 always shows the difference between the HEAD and the index file--this
1034 is what you'd commit if you created the commit now--and that
1036 -------------------------------------------------
1037 $ git diff
1038 -------------------------------------------------
1040 shows the difference between the working tree and the index file.
1042 Note that "git add" always adds just the current contents of a file
1043 to the index; further changes to the same file will be ignored unless
1044 you run git-add on the file again.
1046 When you're ready, just run
1048 -------------------------------------------------
1049 $ git commit
1050 -------------------------------------------------
1052 and git will prompt you for a commit message and then create the new
1053 commit.  Check to make sure it looks like what you expected with
1055 -------------------------------------------------
1056 $ git show
1057 -------------------------------------------------
1059 As a special shortcut,
1061 -------------------------------------------------
1062 $ git commit -a
1063 -------------------------------------------------
1065 will update the index with any files that you've modified or removed
1066 and create a commit, all in one step.
1068 A number of commands are useful for keeping track of what you're
1069 about to commit:
1071 -------------------------------------------------
1072 $ git diff --cached # difference between HEAD and the index; what
1073                     # would be committed if you ran "commit" now.
1074 $ git diff          # difference between the index file and your
1075                     # working directory; changes that would not
1076                     # be included if you ran "commit" now.
1077 $ git diff HEAD     # difference between HEAD and working tree; what
1078                     # would be committed if you ran "commit -a" now.
1079 $ git status        # a brief per-file summary of the above.
1080 -------------------------------------------------
1082 You can also use gitlink:git-gui[1] to create commits, view changes in
1083 the index and the working tree files, and individually select diff hunks
1084 for inclusion in the index (by right-clicking on the diff hunk and
1085 choosing "Stage Hunk For Commit").
1087 [[creating-good-commit-messages]]
1088 Creating good commit messages
1089 -----------------------------
1091 Though not required, it's a good idea to begin the commit message
1092 with a single short (less than 50 character) line summarizing the
1093 change, followed by a blank line and then a more thorough
1094 description.  Tools that turn commits into email, for example, use
1095 the first line on the Subject line and the rest of the commit in the
1096 body.
1098 [[ignoring-files]]
1099 Ignoring files
1100 --------------
1102 A project will often generate files that you do 'not' want to track with git.
1103 This typically includes files generated by a build process or temporary
1104 backup files made by your editor. Of course, 'not' tracking files with git
1105 is just a matter of 'not' calling "`git add`" on them. But it quickly becomes
1106 annoying to have these untracked files lying around; e.g. they make
1107 "`git add .`" and "`git commit -a`" practically useless, and they keep
1108 showing up in the output of "`git status`", etc.
1110 Git therefore provides "exclude patterns" for telling git which files to
1111 actively ignore. Exclude patterns are thoroughly explained in the
1112 gitlink:gitignore[5] manual page, but the heart of the concept is simply
1113 a list of files which git should ignore. Entries in the list may contain
1114 globs to specify multiple files, or may be prefixed by "`!`" to
1115 explicitly include (un-ignore) a previously excluded (ignored) file
1116 (i.e. later exclude patterns override earlier ones).  The following
1117 example should illustrate such patterns:
1119 -------------------------------------------------
1120 # Lines starting with '#' are considered comments.
1121 # Ignore foo.txt.
1122 foo.txt
1123 # Ignore (generated) html files,
1124 *.html
1125 # except foo.html which is maintained by hand.
1126 !foo.html
1127 # Ignore objects and archives.
1128 *.[oa]
1129 -------------------------------------------------
1131 The next question is where to put these exclude patterns so that git can
1132 find them. Git looks for exclude patterns in the following files:
1134 `.gitignore` files in your working tree:::
1135            You may store multiple `.gitignore` files at various locations in your
1136            working tree. Each `.gitignore` file is applied to the directory where
1137            it's located, including its subdirectories. Furthermore, the
1138            `.gitignore` files can be tracked like any other files in your working
1139            tree; just do a "`git add .gitignore`" and commit. `.gitignore` is
1140            therefore the right place to put exclude patterns that are meant to
1141            be shared between all project participants, such as build output files
1142            (e.g. `\*.o`), etc.
1143 `.git/info/exclude` in your repo:::
1144            Exclude patterns in this file are applied to the working tree as a
1145            whole. Since the file is not located in your working tree, it does
1146            not follow push/pull/clone like `.gitignore` can do. This is therefore
1147            the place to put exclude patterns that are local to your copy of the
1148            repo (i.e. 'not' shared between project participants), such as
1149            temporary backup files made by your editor (e.g. `\*~`), etc.
1150 The file specified by the `core.excludesfile` config directive:::
1151            By setting the `core.excludesfile` config directive you can tell git
1152            where to find more exclude patterns (see gitlink:git-config[1] for
1153            more information on configuration options). This config directive
1154            can be set in the per-repo `.git/config` file, in which case the
1155            exclude patterns will apply to that repo only. Alternatively, you
1156            can set the directive in the global `~/.gitconfig` file to apply
1157            the exclude pattern to all your git repos. As with the above
1158            `.git/info/exclude` (and, indeed, with git config directives in
1159            general), this directive does not follow push/pull/clone, but remain
1160            local to your repo(s).
1162 [NOTE]
1163 In addition to the above alternatives, there are git commands that can take
1164 exclude patterns directly on the command line. See gitlink:git-ls-files[1]
1165 for an example of this.
1167 [[how-to-merge]]
1168 How to merge
1169 ------------
1171 You can rejoin two diverging branches of development using
1172 gitlink:git-merge[1]:
1174 -------------------------------------------------
1175 $ git merge branchname
1176 -------------------------------------------------
1178 merges the development in the branch "branchname" into the current
1179 branch.  If there are conflicts--for example, if the same file is
1180 modified in two different ways in the remote branch and the local
1181 branch--then you are warned; the output may look something like this:
1183 -------------------------------------------------
1184 $ git merge next
1185  100% (4/4) done
1186 Auto-merged file.txt
1187 CONFLICT (content): Merge conflict in file.txt
1188 Automatic merge failed; fix conflicts and then commit the result.
1189 -------------------------------------------------
1191 Conflict markers are left in the problematic files, and after
1192 you resolve the conflicts manually, you can update the index
1193 with the contents and run git commit, as you normally would when
1194 creating a new file.
1196 If you examine the resulting commit using gitk, you will see that it
1197 has two parents, one pointing to the top of the current branch, and
1198 one to the top of the other branch.
1200 [[resolving-a-merge]]
1201 Resolving a merge
1202 -----------------
1204 When a merge isn't resolved automatically, git leaves the index and
1205 the working tree in a special state that gives you all the
1206 information you need to help resolve the merge.
1208 Files with conflicts are marked specially in the index, so until you
1209 resolve the problem and update the index, gitlink:git-commit[1] will
1210 fail:
1212 -------------------------------------------------
1213 $ git commit
1214 file.txt: needs merge
1215 -------------------------------------------------
1217 Also, gitlink:git-status[1] will list those files as "unmerged", and the
1218 files with conflicts will have conflict markers added, like this:
1220 -------------------------------------------------
1221 <<<<<<< HEAD:file.txt
1222 Hello world
1223 =======
1224 Goodbye
1225 >>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
1226 -------------------------------------------------
1228 All you need to do is edit the files to resolve the conflicts, and then
1230 -------------------------------------------------
1231 $ git add file.txt
1232 $ git commit
1233 -------------------------------------------------
1235 Note that the commit message will already be filled in for you with
1236 some information about the merge.  Normally you can just use this
1237 default message unchanged, but you may add additional commentary of
1238 your own if desired.
1240 The above is all you need to know to resolve a simple merge.  But git
1241 also provides more information to help resolve conflicts:
1243 [[conflict-resolution]]
1244 Getting conflict-resolution help during a merge
1245 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1247 All of the changes that git was able to merge automatically are
1248 already added to the index file, so gitlink:git-diff[1] shows only
1249 the conflicts.  It uses an unusual syntax:
1251 -------------------------------------------------
1252 $ git diff
1253 diff --cc file.txt
1254 index 802992c,2b60207..0000000
1255 --- a/file.txt
1256 +++ b/file.txt
1257 @@@ -1,1 -1,1 +1,5 @@@
1258 ++<<<<<<< HEAD:file.txt
1259  +Hello world
1260 ++=======
1261 + Goodbye
1262 ++>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt
1263 -------------------------------------------------
1265 Recall that the commit which will be committed after we resolve this
1266 conflict will have two parents instead of the usual one: one parent
1267 will be HEAD, the tip of the current branch; the other will be the
1268 tip of the other branch, which is stored temporarily in MERGE_HEAD.
1270 During the merge, the index holds three versions of each file.  Each of
1271 these three "file stages" represents a different version of the file:
1273 -------------------------------------------------
1274 $ git show :1:file.txt  # the file in a common ancestor of both branches
1275 $ git show :2:file.txt  # the version from HEAD, but including any
1276                         # nonconflicting changes from MERGE_HEAD
1277 $ git show :3:file.txt  # the version from MERGE_HEAD, but including any
1278                         # nonconflicting changes from HEAD.
1279 -------------------------------------------------
1281 Since the stage 2 and stage 3 versions have already been updated with
1282 nonconflicting changes, the only remaining differences between them are
1283 the important ones; thus gitlink:git-diff[1] can use the information in
1284 the index to show only those conflicts.
1286 The diff above shows the differences between the working-tree version of
1287 file.txt and the stage 2 and stage 3 versions.  So instead of preceding
1288 each line by a single "+" or "-", it now uses two columns: the first
1289 column is used for differences between the first parent and the working
1290 directory copy, and the second for differences between the second parent
1291 and the working directory copy.  (See the "COMBINED DIFF FORMAT" section
1292 of gitlink:git-diff-files[1] for a details of the format.)
1294 After resolving the conflict in the obvious way (but before updating the
1295 index), the diff will look like:
1297 -------------------------------------------------
1298 $ git diff
1299 diff --cc file.txt
1300 index 802992c,2b60207..0000000
1301 --- a/file.txt
1302 +++ b/file.txt
1303 @@@ -1,1 -1,1 +1,1 @@@
1304 - Hello world
1305  -Goodbye
1306 ++Goodbye world
1307 -------------------------------------------------
1309 This shows that our resolved version deleted "Hello world" from the
1310 first parent, deleted "Goodbye" from the second parent, and added
1311 "Goodbye world", which was previously absent from both.
1313 Some special diff options allow diffing the working directory against
1314 any of these stages:
1316 -------------------------------------------------
1317 $ git diff -1 file.txt          # diff against stage 1
1318 $ git diff --base file.txt      # same as the above
1319 $ git diff -2 file.txt          # diff against stage 2
1320 $ git diff --ours file.txt      # same as the above
1321 $ git diff -3 file.txt          # diff against stage 3
1322 $ git diff --theirs file.txt    # same as the above.
1323 -------------------------------------------------
1325 The gitlink:git-log[1] and gitk[1] commands also provide special help
1326 for merges:
1328 -------------------------------------------------
1329 $ git log --merge
1330 $ gitk --merge
1331 -------------------------------------------------
1333 These will display all commits which exist only on HEAD or on
1334 MERGE_HEAD, and which touch an unmerged file.
1336 You may also use gitlink:git-mergetool[1], which lets you merge the
1337 unmerged files using external tools such as emacs or kdiff3.
1339 Each time you resolve the conflicts in a file and update the index:
1341 -------------------------------------------------
1342 $ git add file.txt
1343 -------------------------------------------------
1345 the different stages of that file will be "collapsed", after which
1346 git-diff will (by default) no longer show diffs for that file.
1348 [[undoing-a-merge]]
1349 Undoing a merge
1350 ---------------
1352 If you get stuck and decide to just give up and throw the whole mess
1353 away, you can always return to the pre-merge state with
1355 -------------------------------------------------
1356 $ git reset --hard HEAD
1357 -------------------------------------------------
1359 Or, if you've already committed the merge that you want to throw away,
1361 -------------------------------------------------
1362 $ git reset --hard ORIG_HEAD
1363 -------------------------------------------------
1365 However, this last command can be dangerous in some cases--never
1366 throw away a commit you have already committed if that commit may
1367 itself have been merged into another branch, as doing so may confuse
1368 further merges.
1370 [[fast-forwards]]
1371 Fast-forward merges
1372 -------------------
1374 There is one special case not mentioned above, which is treated
1375 differently.  Normally, a merge results in a merge commit, with two
1376 parents, one pointing at each of the two lines of development that
1377 were merged.
1379 However, if the current branch is a descendant of the other--so every
1380 commit present in the one is already contained in the other--then git
1381 just performs a "fast forward"; the head of the current branch is moved
1382 forward to point at the head of the merged-in branch, without any new
1383 commits being created.
1385 [[fixing-mistakes]]
1386 Fixing mistakes
1387 ---------------
1389 If you've messed up the working tree, but haven't yet committed your
1390 mistake, you can return the entire working tree to the last committed
1391 state with
1393 -------------------------------------------------
1394 $ git reset --hard HEAD
1395 -------------------------------------------------
1397 If you make a commit that you later wish you hadn't, there are two
1398 fundamentally different ways to fix the problem:
1400         1. You can create a new commit that undoes whatever was done
1401         by the previous commit.  This is the correct thing if your
1402         mistake has already been made public.
1404         2. You can go back and modify the old commit.  You should
1405         never do this if you have already made the history public;
1406         git does not normally expect the "history" of a project to
1407         change, and cannot correctly perform repeated merges from
1408         a branch that has had its history changed.
1410 [[reverting-a-commit]]
1411 Fixing a mistake with a new commit
1412 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1414 Creating a new commit that reverts an earlier change is very easy;
1415 just pass the gitlink:git-revert[1] command a reference to the bad
1416 commit; for example, to revert the most recent commit:
1418 -------------------------------------------------
1419 $ git revert HEAD
1420 -------------------------------------------------
1422 This will create a new commit which undoes the change in HEAD.  You
1423 will be given a chance to edit the commit message for the new commit.
1425 You can also revert an earlier change, for example, the next-to-last:
1427 -------------------------------------------------
1428 $ git revert HEAD^
1429 -------------------------------------------------
1431 In this case git will attempt to undo the old change while leaving
1432 intact any changes made since then.  If more recent changes overlap
1433 with the changes to be reverted, then you will be asked to fix
1434 conflicts manually, just as in the case of <<resolving-a-merge,
1435 resolving a merge>>.
1437 [[fixing-a-mistake-by-editing-history]]
1438 Fixing a mistake by editing history
1439 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1441 If the problematic commit is the most recent commit, and you have not
1442 yet made that commit public, then you may just
1443 <<undoing-a-merge,destroy it using git-reset>>.
1445 Alternatively, you
1446 can edit the working directory and update the index to fix your
1447 mistake, just as if you were going to <<how-to-make-a-commit,create a
1448 new commit>>, then run
1450 -------------------------------------------------
1451 $ git commit --amend
1452 -------------------------------------------------
1454 which will replace the old commit by a new commit incorporating your
1455 changes, giving you a chance to edit the old commit message first.
1457 Again, you should never do this to a commit that may already have
1458 been merged into another branch; use gitlink:git-revert[1] instead in
1459 that case.
1461 It is also possible to edit commits further back in the history, but
1462 this is an advanced topic to be left for
1463 <<cleaning-up-history,another chapter>>.
1465 [[checkout-of-path]]
1466 Checking out an old version of a file
1467 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1469 In the process of undoing a previous bad change, you may find it
1470 useful to check out an older version of a particular file using
1471 gitlink:git-checkout[1].  We've used git checkout before to switch
1472 branches, but it has quite different behavior if it is given a path
1473 name: the command
1475 -------------------------------------------------
1476 $ git checkout HEAD^ path/to/file
1477 -------------------------------------------------
1479 replaces path/to/file by the contents it had in the commit HEAD^, and
1480 also updates the index to match.  It does not change branches.
1482 If you just want to look at an old version of the file, without
1483 modifying the working directory, you can do that with
1484 gitlink:git-show[1]:
1486 -------------------------------------------------
1487 $ git show HEAD^:path/to/file
1488 -------------------------------------------------
1490 which will display the given version of the file.
1492 [[interrupted-work]]
1493 Temporarily setting aside work in progress
1494 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1496 While you are in the middle of working on something complicated, you
1497 find an unrelated but obvious and trivial bug.  You would like to fix it
1498 before continuing.  You can use gitlink:git-stash[1] to save the current
1499 state of your work, and after fixing the bug (or, optionally after doing
1500 so on a different branch and then coming back), unstash the
1501 work-in-progress changes.
1503 ------------------------------------------------
1504 $ git stash "work in progress for foo feature"
1505 ------------------------------------------------
1507 This command will save your changes away to the `stash`, and
1508 reset your working tree and the index to match the tip of your
1509 current branch.  Then you can make your fix as usual.
1511 ------------------------------------------------
1512 ... edit and test ...
1513 $ git commit -a -m "blorpl: typofix"
1514 ------------------------------------------------
1516 After that, you can go back to what you were working on with
1517 `git stash apply`:
1519 ------------------------------------------------
1520 $ git stash apply
1521 ------------------------------------------------
1524 [[ensuring-good-performance]]
1525 Ensuring good performance
1526 -------------------------
1528 On large repositories, git depends on compression to keep the history
1529 information from taking up to much space on disk or in memory.
1531 This compression is not performed automatically.  Therefore you
1532 should occasionally run gitlink:git-gc[1]:
1534 -------------------------------------------------
1535 $ git gc
1536 -------------------------------------------------
1538 to recompress the archive.  This can be very time-consuming, so
1539 you may prefer to run git-gc when you are not doing other work.
1542 [[ensuring-reliability]]
1543 Ensuring reliability
1544 --------------------
1546 [[checking-for-corruption]]
1547 Checking the repository for corruption
1548 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1550 The gitlink:git-fsck[1] command runs a number of self-consistency checks
1551 on the repository, and reports on any problems.  This may take some
1552 time.  The most common warning by far is about "dangling" objects:
1554 -------------------------------------------------
1555 $ git fsck
1556 dangling commit 7281251ddd2a61e38657c827739c57015671a6b3
1557 dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a63
1558 dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b5
1559 dangling blob 218761f9d90712d37a9c5e36f406f92202db07eb
1560 dangling commit bf093535a34a4d35731aa2bd90fe6b176302f14f
1561 dangling commit 8e4bec7f2ddaa268bef999853c25755452100f8e
1562 dangling tree d50bb86186bf27b681d25af89d3b5b68382e4085
1563 dangling tree b24c2473f1fd3d91352a624795be026d64c8841f
1564 ...
1565 -------------------------------------------------
1567 Dangling objects are not a problem.  At worst they may take up a little
1568 extra disk space.  They can sometimes provide a last-resort method for
1569 recovering lost work--see <<dangling-objects>> for details.  However, if
1570 you wish, you can remove them with gitlink:git-prune[1] or the --prune
1571 option to gitlink:git-gc[1]:
1573 -------------------------------------------------
1574 $ git gc --prune
1575 -------------------------------------------------
1577 This may be time-consuming.  Unlike most other git operations (including
1578 git-gc when run without any options), it is not safe to prune while
1579 other git operations are in progress in the same repository.
1581 [[recovering-lost-changes]]
1582 Recovering lost changes
1583 ~~~~~~~~~~~~~~~~~~~~~~~
1585 [[reflogs]]
1586 Reflogs
1587 ^^^^^^^
1589 Say you modify a branch with gitlink:git-reset[1] --hard, and then
1590 realize that the branch was the only reference you had to that point in
1591 history.
1593 Fortunately, git also keeps a log, called a "reflog", of all the
1594 previous values of each branch.  So in this case you can still find the
1595 old history using, for example,
1597 -------------------------------------------------
1598 $ git log master@{1}
1599 -------------------------------------------------
1601 This lists the commits reachable from the previous version of the head.
1602 This syntax can be used to with any git command that accepts a commit,
1603 not just with git log.  Some other examples:
1605 -------------------------------------------------
1606 $ git show master@{2}           # See where the branch pointed 2,
1607 $ git show master@{3}           # 3, ... changes ago.
1608 $ gitk master@{yesterday}       # See where it pointed yesterday,
1609 $ gitk master@{"1 week ago"}    # ... or last week
1610 $ git log --walk-reflogs master # show reflog entries for master
1611 -------------------------------------------------
1613 A separate reflog is kept for the HEAD, so
1615 -------------------------------------------------
1616 $ git show HEAD@{"1 week ago"}
1617 -------------------------------------------------
1619 will show what HEAD pointed to one week ago, not what the current branch
1620 pointed to one week ago.  This allows you to see the history of what
1621 you've checked out.
1623 The reflogs are kept by default for 30 days, after which they may be
1624 pruned.  See gitlink:git-reflog[1] and gitlink:git-gc[1] to learn
1625 how to control this pruning, and see the "SPECIFYING REVISIONS"
1626 section of gitlink:git-rev-parse[1] for details.
1628 Note that the reflog history is very different from normal git history.
1629 While normal history is shared by every repository that works on the
1630 same project, the reflog history is not shared: it tells you only about
1631 how the branches in your local repository have changed over time.
1633 [[dangling-object-recovery]]
1634 Examining dangling objects
1635 ^^^^^^^^^^^^^^^^^^^^^^^^^^
1637 In some situations the reflog may not be able to save you.  For example,
1638 suppose you delete a branch, then realize you need the history it
1639 contained.  The reflog is also deleted; however, if you have not yet
1640 pruned the repository, then you may still be able to find the lost
1641 commits in the dangling objects that git-fsck reports.  See
1642 <<dangling-objects>> for the details.
1644 -------------------------------------------------
1645 $ git fsck
1646 dangling commit 7281251ddd2a61e38657c827739c57015671a6b3
1647 dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a63
1648 dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b5
1649 ...
1650 -------------------------------------------------
1652 You can examine
1653 one of those dangling commits with, for example,
1655 ------------------------------------------------
1656 $ gitk 7281251ddd --not --all
1657 ------------------------------------------------
1659 which does what it sounds like: it says that you want to see the commit
1660 history that is described by the dangling commit(s), but not the
1661 history that is described by all your existing branches and tags.  Thus
1662 you get exactly the history reachable from that commit that is lost.
1663 (And notice that it might not be just one commit: we only report the
1664 "tip of the line" as being dangling, but there might be a whole deep
1665 and complex commit history that was dropped.)
1667 If you decide you want the history back, you can always create a new
1668 reference pointing to it, for example, a new branch:
1670 ------------------------------------------------
1671 $ git branch recovered-branch 7281251ddd
1672 ------------------------------------------------
1674 Other types of dangling objects (blobs and trees) are also possible, and
1675 dangling objects can arise in other situations.
1678 [[sharing-development]]
1679 Sharing development with others
1680 ===============================
1682 [[getting-updates-with-git-pull]]
1683 Getting updates with git pull
1684 -----------------------------
1686 After you clone a repository and make a few changes of your own, you
1687 may wish to check the original repository for updates and merge them
1688 into your own work.
1690 We have already seen <<Updating-a-repository-with-git-fetch,how to
1691 keep remote tracking branches up to date>> with gitlink:git-fetch[1],
1692 and how to merge two branches.  So you can merge in changes from the
1693 original repository's master branch with:
1695 -------------------------------------------------
1696 $ git fetch
1697 $ git merge origin/master
1698 -------------------------------------------------
1700 However, the gitlink:git-pull[1] command provides a way to do this in
1701 one step:
1703 -------------------------------------------------
1704 $ git pull origin master
1705 -------------------------------------------------
1707 In fact, if you have "master" checked out, then by default "git pull"
1708 merges from the HEAD branch of the origin repository.  So often you can
1709 accomplish the above with just a simple
1711 -------------------------------------------------
1712 $ git pull
1713 -------------------------------------------------
1715 More generally, a branch that is created from a remote branch will pull
1716 by default from that branch.  See the descriptions of the
1717 branch.<name>.remote and branch.<name>.merge options in
1718 gitlink:git-config[1], and the discussion of the --track option in
1719 gitlink:git-checkout[1], to learn how to control these defaults.
1721 In addition to saving you keystrokes, "git pull" also helps you by
1722 producing a default commit message documenting the branch and
1723 repository that you pulled from.
1725 (But note that no such commit will be created in the case of a
1726 <<fast-forwards,fast forward>>; instead, your branch will just be
1727 updated to point to the latest commit from the upstream branch.)
1729 The git-pull command can also be given "." as the "remote" repository,
1730 in which case it just merges in a branch from the current repository; so
1731 the commands
1733 -------------------------------------------------
1734 $ git pull . branch
1735 $ git merge branch
1736 -------------------------------------------------
1738 are roughly equivalent.  The former is actually very commonly used.
1740 [[submitting-patches]]
1741 Submitting patches to a project
1742 -------------------------------
1744 If you just have a few changes, the simplest way to submit them may
1745 just be to send them as patches in email:
1747 First, use gitlink:git-format-patch[1]; for example:
1749 -------------------------------------------------
1750 $ git format-patch origin
1751 -------------------------------------------------
1753 will produce a numbered series of files in the current directory, one
1754 for each patch in the current branch but not in origin/HEAD.
1756 You can then import these into your mail client and send them by
1757 hand.  However, if you have a lot to send at once, you may prefer to
1758 use the gitlink:git-send-email[1] script to automate the process.
1759 Consult the mailing list for your project first to determine how they
1760 prefer such patches be handled.
1762 [[importing-patches]]
1763 Importing patches to a project
1764 ------------------------------
1766 Git also provides a tool called gitlink:git-am[1] (am stands for
1767 "apply mailbox"), for importing such an emailed series of patches.
1768 Just save all of the patch-containing messages, in order, into a
1769 single mailbox file, say "patches.mbox", then run
1771 -------------------------------------------------
1772 $ git am -3 patches.mbox
1773 -------------------------------------------------
1775 Git will apply each patch in order; if any conflicts are found, it
1776 will stop, and you can fix the conflicts as described in
1777 "<<resolving-a-merge,Resolving a merge>>".  (The "-3" option tells
1778 git to perform a merge; if you would prefer it just to abort and
1779 leave your tree and index untouched, you may omit that option.)
1781 Once the index is updated with the results of the conflict
1782 resolution, instead of creating a new commit, just run
1784 -------------------------------------------------
1785 $ git am --resolved
1786 -------------------------------------------------
1788 and git will create the commit for you and continue applying the
1789 remaining patches from the mailbox.
1791 The final result will be a series of commits, one for each patch in
1792 the original mailbox, with authorship and commit log message each
1793 taken from the message containing each patch.
1795 [[public-repositories]]
1796 Public git repositories
1797 -----------------------
1799 Another way to submit changes to a project is to tell the maintainer
1800 of that project to pull the changes from your repository using
1801 gitlink:git-pull[1].  In the section "<<getting-updates-with-git-pull,
1802 Getting updates with git pull>>" we described this as a way to get
1803 updates from the "main" repository, but it works just as well in the
1804 other direction.
1806 If you and the maintainer both have accounts on the same machine, then
1807 you can just pull changes from each other's repositories directly;
1808 commands that accept repository URLs as arguments will also accept a
1809 local directory name:
1811 -------------------------------------------------
1812 $ git clone /path/to/repository
1813 $ git pull /path/to/other/repository
1814 -------------------------------------------------
1816 or an ssh url:
1818 -------------------------------------------------
1819 $ git clone ssh://yourhost/~you/repository
1820 -------------------------------------------------
1822 For projects with few developers, or for synchronizing a few private
1823 repositories, this may be all you need.
1825 However, the more common way to do this is to maintain a separate public
1826 repository (usually on a different host) for others to pull changes
1827 from.  This is usually more convenient, and allows you to cleanly
1828 separate private work in progress from publicly visible work.
1830 You will continue to do your day-to-day work in your personal
1831 repository, but periodically "push" changes from your personal
1832 repository into your public repository, allowing other developers to
1833 pull from that repository.  So the flow of changes, in a situation
1834 where there is one other developer with a public repository, looks
1835 like this:
1837                         you push
1838   your personal repo ------------------> your public repo
1839         ^                                     |
1840         |                                     |
1841         | you pull                            | they pull
1842         |                                     |
1843         |                                     |
1844         |               they push             V
1845   their public repo <------------------- their repo
1847 We explain how to do this in the following sections.
1849 [[setting-up-a-public-repository]]
1850 Setting up a public repository
1851 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1853 Assume your personal repository is in the directory ~/proj.  We
1854 first create a new clone of the repository and tell git-daemon that it
1855 is meant to be public:
1857 -------------------------------------------------
1858 $ git clone --bare ~/proj proj.git
1859 $ touch proj.git/git-daemon-export-ok
1860 -------------------------------------------------
1862 The resulting directory proj.git contains a "bare" git repository--it is
1863 just the contents of the ".git" directory, without any files checked out
1864 around it.
1866 Next, copy proj.git to the server where you plan to host the
1867 public repository.  You can use scp, rsync, or whatever is most
1868 convenient.
1870 [[exporting-via-git]]
1871 Exporting a git repository via the git protocol
1872 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1874 This is the preferred method.
1876 If someone else administers the server, they should tell you what
1877 directory to put the repository in, and what git:// url it will appear
1878 at.  You can then skip to the section
1879 "<<pushing-changes-to-a-public-repository,Pushing changes to a public
1880 repository>>", below.
1882 Otherwise, all you need to do is start gitlink:git-daemon[1]; it will
1883 listen on port 9418.  By default, it will allow access to any directory
1884 that looks like a git directory and contains the magic file
1885 git-daemon-export-ok.  Passing some directory paths as git-daemon
1886 arguments will further restrict the exports to those paths.
1888 You can also run git-daemon as an inetd service; see the
1889 gitlink:git-daemon[1] man page for details.  (See especially the
1890 examples section.)
1892 [[exporting-via-http]]
1893 Exporting a git repository via http
1894 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1896 The git protocol gives better performance and reliability, but on a
1897 host with a web server set up, http exports may be simpler to set up.
1899 All you need to do is place the newly created bare git repository in
1900 a directory that is exported by the web server, and make some
1901 adjustments to give web clients some extra information they need:
1903 -------------------------------------------------
1904 $ mv proj.git /home/you/public_html/proj.git
1905 $ cd proj.git
1906 $ git --bare update-server-info
1907 $ chmod a+x hooks/post-update
1908 -------------------------------------------------
1910 (For an explanation of the last two lines, see
1911 gitlink:git-update-server-info[1], and the documentation
1912 link:hooks.html[Hooks used by git].)
1914 Advertise the url of proj.git.  Anybody else should then be able to
1915 clone or pull from that url, for example with a command line like:
1917 -------------------------------------------------
1918 $ git clone http://yourserver.com/~you/proj.git
1919 -------------------------------------------------
1921 (See also
1922 link:howto/setup-git-server-over-http.txt[setup-git-server-over-http]
1923 for a slightly more sophisticated setup using WebDAV which also
1924 allows pushing over http.)
1926 [[pushing-changes-to-a-public-repository]]
1927 Pushing changes to a public repository
1928 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1930 Note that the two techniques outlined above (exporting via
1931 <<exporting-via-http,http>> or <<exporting-via-git,git>>) allow other
1932 maintainers to fetch your latest changes, but they do not allow write
1933 access, which you will need to update the public repository with the
1934 latest changes created in your private repository.
1936 The simplest way to do this is using gitlink:git-push[1] and ssh; to
1937 update the remote branch named "master" with the latest state of your
1938 branch named "master", run
1940 -------------------------------------------------
1941 $ git push ssh://yourserver.com/~you/proj.git master:master
1942 -------------------------------------------------
1944 or just
1946 -------------------------------------------------
1947 $ git push ssh://yourserver.com/~you/proj.git master
1948 -------------------------------------------------
1950 As with git-fetch, git-push will complain if this does not result in
1951 a <<fast-forwards,fast forward>>.  Normally this is a sign of
1952 something wrong.  However, if you are sure you know what you're
1953 doing, you may force git-push to perform the update anyway by
1954 proceeding the branch name by a plus sign:
1956 -------------------------------------------------
1957 $ git push ssh://yourserver.com/~you/proj.git +master
1958 -------------------------------------------------
1960 Note that the target of a "push" is normally a
1961 <<def_bare_repository,bare>> repository.  You can also push to a
1962 repository that has a checked-out working tree, but the working tree
1963 will not be updated by the push.  This may lead to unexpected results if
1964 the branch you push to is the currently checked-out branch!
1966 As with git-fetch, you may also set up configuration options to
1967 save typing; so, for example, after
1969 -------------------------------------------------
1970 $ cat >>.git/config <<EOF
1971 [remote "public-repo"]
1972         url = ssh://yourserver.com/~you/proj.git
1973 EOF
1974 -------------------------------------------------
1976 you should be able to perform the above push with just
1978 -------------------------------------------------
1979 $ git push public-repo master
1980 -------------------------------------------------
1982 See the explanations of the remote.<name>.url, branch.<name>.remote,
1983 and remote.<name>.push options in gitlink:git-config[1] for
1984 details.
1986 [[setting-up-a-shared-repository]]
1987 Setting up a shared repository
1988 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1990 Another way to collaborate is by using a model similar to that
1991 commonly used in CVS, where several developers with special rights
1992 all push to and pull from a single shared repository.  See
1993 link:cvs-migration.html[git for CVS users] for instructions on how to
1994 set this up.
1996 However, while there is nothing wrong with git's support for shared
1997 repositories, this mode of operation is not generally recommended,
1998 simply because the mode of collaboration that git supports--by
1999 exchanging patches and pulling from public repositories--has so many
2000 advantages over the central shared repository:
2002         - Git's ability to quickly import and merge patches allows a
2003           single maintainer to process incoming changes even at very
2004           high rates.  And when that becomes too much, git-pull provides
2005           an easy way for that maintainer to delegate this job to other
2006           maintainers while still allowing optional review of incoming
2007           changes.
2008         - Since every developer's repository has the same complete copy
2009           of the project history, no repository is special, and it is
2010           trivial for another developer to take over maintenance of a
2011           project, either by mutual agreement, or because a maintainer
2012           becomes unresponsive or difficult to work with.
2013         - The lack of a central group of "committers" means there is
2014           less need for formal decisions about who is "in" and who is
2015           "out".
2017 [[setting-up-gitweb]]
2018 Allowing web browsing of a repository
2019 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2021 The gitweb cgi script provides users an easy way to browse your
2022 project's files and history without having to install git; see the file
2023 gitweb/INSTALL in the git source tree for instructions on setting it up.
2025 [[sharing-development-examples]]
2026 Examples
2027 --------
2029 [[maintaining-topic-branches]]
2030 Maintaining topic branches for a Linux subsystem maintainer
2031 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2033 This describes how Tony Luck uses git in his role as maintainer of the
2034 IA64 architecture for the Linux kernel.
2036 He uses two public branches:
2038  - A "test" tree into which patches are initially placed so that they
2039    can get some exposure when integrated with other ongoing development.
2040    This tree is available to Andrew for pulling into -mm whenever he
2041    wants.
2043  - A "release" tree into which tested patches are moved for final sanity
2044    checking, and as a vehicle to send them upstream to Linus (by sending
2045    him a "please pull" request.)
2047 He also uses a set of temporary branches ("topic branches"), each
2048 containing a logical grouping of patches.
2050 To set this up, first create your work tree by cloning Linus's public
2051 tree:
2053 -------------------------------------------------
2054 $ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git work
2055 $ cd work
2056 -------------------------------------------------
2058 Linus's tree will be stored in the remote branch named origin/master,
2059 and can be updated using gitlink:git-fetch[1]; you can track other
2060 public trees using gitlink:git-remote[1] to set up a "remote" and
2061 gitlink:git-fetch[1] to keep them up-to-date; see
2062 <<repositories-and-branches>>.
2064 Now create the branches in which you are going to work; these start out
2065 at the current tip of origin/master branch, and should be set up (using
2066 the --track option to gitlink:git-branch[1]) to merge changes in from
2067 Linus by default.
2069 -------------------------------------------------
2070 $ git branch --track test origin/master
2071 $ git branch --track release origin/master
2072 -------------------------------------------------
2074 These can be easily kept up to date using gitlink:git-pull[1]
2076 -------------------------------------------------
2077 $ git checkout test && git pull
2078 $ git checkout release && git pull
2079 -------------------------------------------------
2081 Important note!  If you have any local changes in these branches, then
2082 this merge will create a commit object in the history (with no local
2083 changes git will simply do a "Fast forward" merge).  Many people dislike
2084 the "noise" that this creates in the Linux history, so you should avoid
2085 doing this capriciously in the "release" branch, as these noisy commits
2086 will become part of the permanent history when you ask Linus to pull
2087 from the release branch.
2089 A few configuration variables (see gitlink:git-config[1]) can
2090 make it easy to push both branches to your public tree.  (See
2091 <<setting-up-a-public-repository>>.)
2093 -------------------------------------------------
2094 $ cat >> .git/config <<EOF
2095 [remote "mytree"]
2096         url =  master.kernel.org:/pub/scm/linux/kernel/git/aegl/linux-2.6.git
2097         push = release
2098         push = test
2099 EOF
2100 -------------------------------------------------
2102 Then you can push both the test and release trees using
2103 gitlink:git-push[1]:
2105 -------------------------------------------------
2106 $ git push mytree
2107 -------------------------------------------------
2109 or push just one of the test and release branches using:
2111 -------------------------------------------------
2112 $ git push mytree test
2113 -------------------------------------------------
2115 or
2117 -------------------------------------------------
2118 $ git push mytree release
2119 -------------------------------------------------
2121 Now to apply some patches from the community.  Think of a short
2122 snappy name for a branch to hold this patch (or related group of
2123 patches), and create a new branch from the current tip of Linus's
2124 branch:
2126 -------------------------------------------------
2127 $ git checkout -b speed-up-spinlocks origin
2128 -------------------------------------------------
2130 Now you apply the patch(es), run some tests, and commit the change(s).  If
2131 the patch is a multi-part series, then you should apply each as a separate
2132 commit to this branch.
2134 -------------------------------------------------
2135 $ ... patch ... test  ... commit [ ... patch ... test ... commit ]*
2136 -------------------------------------------------
2138 When you are happy with the state of this change, you can pull it into the
2139 "test" branch in preparation to make it public:
2141 -------------------------------------------------
2142 $ git checkout test && git pull . speed-up-spinlocks
2143 -------------------------------------------------
2145 It is unlikely that you would have any conflicts here ... but you might if you
2146 spent a while on this step and had also pulled new versions from upstream.
2148 Some time later when enough time has passed and testing done, you can pull the
2149 same branch into the "release" tree ready to go upstream.  This is where you
2150 see the value of keeping each patch (or patch series) in its own branch.  It
2151 means that the patches can be moved into the "release" tree in any order.
2153 -------------------------------------------------
2154 $ git checkout release && git pull . speed-up-spinlocks
2155 -------------------------------------------------
2157 After a while, you will have a number of branches, and despite the
2158 well chosen names you picked for each of them, you may forget what
2159 they are for, or what status they are in.  To get a reminder of what
2160 changes are in a specific branch, use:
2162 -------------------------------------------------
2163 $ git log linux..branchname | git-shortlog
2164 -------------------------------------------------
2166 To see whether it has already been merged into the test or release branches
2167 use:
2169 -------------------------------------------------
2170 $ git log test..branchname
2171 -------------------------------------------------
2173 or
2175 -------------------------------------------------
2176 $ git log release..branchname
2177 -------------------------------------------------
2179 (If this branch has not yet been merged you will see some log entries.
2180 If it has been merged, then there will be no output.)
2182 Once a patch completes the great cycle (moving from test to release,
2183 then pulled by Linus, and finally coming back into your local
2184 "origin/master" branch) the branch for this change is no longer needed.
2185 You detect this when the output from:
2187 -------------------------------------------------
2188 $ git log origin..branchname
2189 -------------------------------------------------
2191 is empty.  At this point the branch can be deleted:
2193 -------------------------------------------------
2194 $ git branch -d branchname
2195 -------------------------------------------------
2197 Some changes are so trivial that it is not necessary to create a separate
2198 branch and then merge into each of the test and release branches.  For
2199 these changes, just apply directly to the "release" branch, and then
2200 merge that into the "test" branch.
2202 To create diffstat and shortlog summaries of changes to include in a "please
2203 pull" request to Linus you can use:
2205 -------------------------------------------------
2206 $ git diff --stat origin..release
2207 -------------------------------------------------
2209 and
2211 -------------------------------------------------
2212 $ git log -p origin..release | git shortlog
2213 -------------------------------------------------
2215 Here are some of the scripts that simplify all this even further.
2217 -------------------------------------------------
2218 ==== update script ====
2219 # Update a branch in my GIT tree.  If the branch to be updated
2220 # is origin, then pull from kernel.org.  Otherwise merge
2221 # origin/master branch into test|release branch
2223 case "$1" in
2224 test|release)
2225         git checkout $1 && git pull . origin
2226         ;;
2227 origin)
2228         before=$(cat .git/refs/remotes/origin/master)
2229         git fetch origin
2230         after=$(cat .git/refs/remotes/origin/master)
2231         if [ $before != $after ]
2232         then
2233                 git log $before..$after | git shortlog
2234         fi
2235         ;;
2236 *)
2237         echo "Usage: $0 origin|test|release" 1>&2
2238         exit 1
2239         ;;
2240 esac
2241 -------------------------------------------------
2243 -------------------------------------------------
2244 ==== merge script ====
2245 # Merge a branch into either the test or release branch
2247 pname=$0
2249 usage()
2251         echo "Usage: $pname branch test|release" 1>&2
2252         exit 1
2255 if [ ! -f .git/refs/heads/"$1" ]
2256 then
2257         echo "Can't see branch <$1>" 1>&2
2258         usage
2259 fi
2261 case "$2" in
2262 test|release)
2263         if [ $(git log $2..$1 | wc -c) -eq 0 ]
2264         then
2265                 echo $1 already merged into $2 1>&2
2266                 exit 1
2267         fi
2268         git checkout $2 && git pull . $1
2269         ;;
2270 *)
2271         usage
2272         ;;
2273 esac
2274 -------------------------------------------------
2276 -------------------------------------------------
2277 ==== status script ====
2278 # report on status of my ia64 GIT tree
2280 gb=$(tput setab 2)
2281 rb=$(tput setab 1)
2282 restore=$(tput setab 9)
2284 if [ `git rev-list test..release | wc -c` -gt 0 ]
2285 then
2286         echo $rb Warning: commits in release that are not in test $restore
2287         git log test..release
2288 fi
2290 for branch in `ls .git/refs/heads`
2291 do
2292         if [ $branch = test -o $branch = release ]
2293         then
2294                 continue
2295         fi
2297         echo -n $gb ======= $branch ====== $restore " "
2298         status=
2299         for ref in test release origin/master
2300         do
2301                 if [ `git rev-list $ref..$branch | wc -c` -gt 0 ]
2302                 then
2303                         status=$status${ref:0:1}
2304                 fi
2305         done
2306         case $status in
2307         trl)
2308                 echo $rb Need to pull into test $restore
2309                 ;;
2310         rl)
2311                 echo "In test"
2312                 ;;
2313         l)
2314                 echo "Waiting for linus"
2315                 ;;
2316         "")
2317                 echo $rb All done $restore
2318                 ;;
2319         *)
2320                 echo $rb "<$status>" $restore
2321                 ;;
2322         esac
2323         git log origin/master..$branch | git shortlog
2324 done
2325 -------------------------------------------------
2328 [[cleaning-up-history]]
2329 Rewriting history and maintaining patch series
2330 ==============================================
2332 Normally commits are only added to a project, never taken away or
2333 replaced.  Git is designed with this assumption, and violating it will
2334 cause git's merge machinery (for example) to do the wrong thing.
2336 However, there is a situation in which it can be useful to violate this
2337 assumption.
2339 [[patch-series]]
2340 Creating the perfect patch series
2341 ---------------------------------
2343 Suppose you are a contributor to a large project, and you want to add a
2344 complicated feature, and to present it to the other developers in a way
2345 that makes it easy for them to read your changes, verify that they are
2346 correct, and understand why you made each change.
2348 If you present all of your changes as a single patch (or commit), they
2349 may find that it is too much to digest all at once.
2351 If you present them with the entire history of your work, complete with
2352 mistakes, corrections, and dead ends, they may be overwhelmed.
2354 So the ideal is usually to produce a series of patches such that:
2356         1. Each patch can be applied in order.
2358         2. Each patch includes a single logical change, together with a
2359            message explaining the change.
2361         3. No patch introduces a regression: after applying any initial
2362            part of the series, the resulting project still compiles and
2363            works, and has no bugs that it didn't have before.
2365         4. The complete series produces the same end result as your own
2366            (probably much messier!) development process did.
2368 We will introduce some tools that can help you do this, explain how to
2369 use them, and then explain some of the problems that can arise because
2370 you are rewriting history.
2372 [[using-git-rebase]]
2373 Keeping a patch series up to date using git-rebase
2374 --------------------------------------------------
2376 Suppose that you create a branch "mywork" on a remote-tracking branch
2377 "origin", and create some commits on top of it:
2379 -------------------------------------------------
2380 $ git checkout -b mywork origin
2381 $ vi file.txt
2382 $ git commit
2383 $ vi otherfile.txt
2384 $ git commit
2385 ...
2386 -------------------------------------------------
2388 You have performed no merges into mywork, so it is just a simple linear
2389 sequence of patches on top of "origin":
2391 ................................................
2392  o--o--o <-- origin
2393         \
2394          o--o--o <-- mywork
2395 ................................................
2397 Some more interesting work has been done in the upstream project, and
2398 "origin" has advanced:
2400 ................................................
2401  o--o--O--o--o--o <-- origin
2402         \
2403          a--b--c <-- mywork
2404 ................................................
2406 At this point, you could use "pull" to merge your changes back in;
2407 the result would create a new merge commit, like this:
2409 ................................................
2410  o--o--O--o--o--o <-- origin
2411         \        \
2412          a--b--c--m <-- mywork
2413 ................................................
2415 However, if you prefer to keep the history in mywork a simple series of
2416 commits without any merges, you may instead choose to use
2417 gitlink:git-rebase[1]:
2419 -------------------------------------------------
2420 $ git checkout mywork
2421 $ git rebase origin
2422 -------------------------------------------------
2424 This will remove each of your commits from mywork, temporarily saving
2425 them as patches (in a directory named ".dotest"), update mywork to
2426 point at the latest version of origin, then apply each of the saved
2427 patches to the new mywork.  The result will look like:
2430 ................................................
2431  o--o--O--o--o--o <-- origin
2432                  \
2433                   a'--b'--c' <-- mywork
2434 ................................................
2436 In the process, it may discover conflicts.  In that case it will stop
2437 and allow you to fix the conflicts; after fixing conflicts, use "git
2438 add" to update the index with those contents, and then, instead of
2439 running git-commit, just run
2441 -------------------------------------------------
2442 $ git rebase --continue
2443 -------------------------------------------------
2445 and git will continue applying the rest of the patches.
2447 At any point you may use the --abort option to abort this process and
2448 return mywork to the state it had before you started the rebase:
2450 -------------------------------------------------
2451 $ git rebase --abort
2452 -------------------------------------------------
2454 [[modifying-one-commit]]
2455 Modifying a single commit
2456 -------------------------
2458 We saw in <<fixing-a-mistake-by-editing-history>> that you can replace the
2459 most recent commit using
2461 -------------------------------------------------
2462 $ git commit --amend
2463 -------------------------------------------------
2465 which will replace the old commit by a new commit incorporating your
2466 changes, giving you a chance to edit the old commit message first.
2468 You can also use a combination of this and gitlink:git-rebase[1] to edit
2469 commits further back in your history.  First, tag the problematic commit with
2471 -------------------------------------------------
2472 $ git tag bad mywork~5
2473 -------------------------------------------------
2475 (Either gitk or git-log may be useful for finding the commit.)
2477 Then check out that commit, edit it, and rebase the rest of the series
2478 on top of it (note that we could check out the commit on a temporary
2479 branch, but instead we're using a <<detached-head,detached head>>):
2481 -------------------------------------------------
2482 $ git checkout bad
2483 $ # make changes here and update the index
2484 $ git commit --amend
2485 $ git rebase --onto HEAD bad mywork
2486 -------------------------------------------------
2488 When you're done, you'll be left with mywork checked out, with the top
2489 patches on mywork reapplied on top of your modified commit.  You can
2490 then clean up with
2492 -------------------------------------------------
2493 $ git tag -d bad
2494 -------------------------------------------------
2496 Note that the immutable nature of git history means that you haven't really
2497 "modified" existing commits; instead, you have replaced the old commits with
2498 new commits having new object names.
2500 [[reordering-patch-series]]
2501 Reordering or selecting from a patch series
2502 -------------------------------------------
2504 Given one existing commit, the gitlink:git-cherry-pick[1] command
2505 allows you to apply the change introduced by that commit and create a
2506 new commit that records it.  So, for example, if "mywork" points to a
2507 series of patches on top of "origin", you might do something like:
2509 -------------------------------------------------
2510 $ git checkout -b mywork-new origin
2511 $ gitk origin..mywork &
2512 -------------------------------------------------
2514 And browse through the list of patches in the mywork branch using gitk,
2515 applying them (possibly in a different order) to mywork-new using
2516 cherry-pick, and possibly modifying them as you go using commit --amend.
2517 The gitlink:git-gui[1] command may also help as it allows you to
2518 individually select diff hunks for inclusion in the index (by
2519 right-clicking on the diff hunk and choosing "Stage Hunk for Commit").
2521 Another technique is to use git-format-patch to create a series of
2522 patches, then reset the state to before the patches:
2524 -------------------------------------------------
2525 $ git format-patch origin
2526 $ git reset --hard origin
2527 -------------------------------------------------
2529 Then modify, reorder, or eliminate patches as preferred before applying
2530 them again with gitlink:git-am[1].
2532 [[patch-series-tools]]
2533 Other tools
2534 -----------
2536 There are numerous other tools, such as StGIT, which exist for the
2537 purpose of maintaining a patch series.  These are outside of the scope of
2538 this manual.
2540 [[problems-with-rewriting-history]]
2541 Problems with rewriting history
2542 -------------------------------
2544 The primary problem with rewriting the history of a branch has to do
2545 with merging.  Suppose somebody fetches your branch and merges it into
2546 their branch, with a result something like this:
2548 ................................................
2549  o--o--O--o--o--o <-- origin
2550         \        \
2551          t--t--t--m <-- their branch:
2552 ................................................
2554 Then suppose you modify the last three commits:
2556 ................................................
2557          o--o--o <-- new head of origin
2558         /
2559  o--o--O--o--o--o <-- old head of origin
2560 ................................................
2562 If we examined all this history together in one repository, it will
2563 look like:
2565 ................................................
2566          o--o--o <-- new head of origin
2567         /
2568  o--o--O--o--o--o <-- old head of origin
2569         \        \
2570          t--t--t--m <-- their branch:
2571 ................................................
2573 Git has no way of knowing that the new head is an updated version of
2574 the old head; it treats this situation exactly the same as it would if
2575 two developers had independently done the work on the old and new heads
2576 in parallel.  At this point, if someone attempts to merge the new head
2577 in to their branch, git will attempt to merge together the two (old and
2578 new) lines of development, instead of trying to replace the old by the
2579 new.  The results are likely to be unexpected.
2581 You may still choose to publish branches whose history is rewritten,
2582 and it may be useful for others to be able to fetch those branches in
2583 order to examine or test them, but they should not attempt to pull such
2584 branches into their own work.
2586 For true distributed development that supports proper merging,
2587 published branches should never be rewritten.
2589 [[advanced-branch-management]]
2590 Advanced branch management
2591 ==========================
2593 [[fetching-individual-branches]]
2594 Fetching individual branches
2595 ----------------------------
2597 Instead of using gitlink:git-remote[1], you can also choose just
2598 to update one branch at a time, and to store it locally under an
2599 arbitrary name:
2601 -------------------------------------------------
2602 $ git fetch origin todo:my-todo-work
2603 -------------------------------------------------
2605 The first argument, "origin", just tells git to fetch from the
2606 repository you originally cloned from.  The second argument tells git
2607 to fetch the branch named "todo" from the remote repository, and to
2608 store it locally under the name refs/heads/my-todo-work.
2610 You can also fetch branches from other repositories; so
2612 -------------------------------------------------
2613 $ git fetch git://example.com/proj.git master:example-master
2614 -------------------------------------------------
2616 will create a new branch named "example-master" and store in it the
2617 branch named "master" from the repository at the given URL.  If you
2618 already have a branch named example-master, it will attempt to
2619 <<fast-forwards,fast-forward>> to the commit given by example.com's
2620 master branch.  In more detail:
2622 [[fetch-fast-forwards]]
2623 git fetch and fast-forwards
2624 ---------------------------
2626 In the previous example, when updating an existing branch, "git
2627 fetch" checks to make sure that the most recent commit on the remote
2628 branch is a descendant of the most recent commit on your copy of the
2629 branch before updating your copy of the branch to point at the new
2630 commit.  Git calls this process a <<fast-forwards,fast forward>>.
2632 A fast forward looks something like this:
2634 ................................................
2635  o--o--o--o <-- old head of the branch
2636            \
2637             o--o--o <-- new head of the branch
2638 ................................................
2641 In some cases it is possible that the new head will *not* actually be
2642 a descendant of the old head.  For example, the developer may have
2643 realized she made a serious mistake, and decided to backtrack,
2644 resulting in a situation like:
2646 ................................................
2647  o--o--o--o--a--b <-- old head of the branch
2648            \
2649             o--o--o <-- new head of the branch
2650 ................................................
2652 In this case, "git fetch" will fail, and print out a warning.
2654 In that case, you can still force git to update to the new head, as
2655 described in the following section.  However, note that in the
2656 situation above this may mean losing the commits labeled "a" and "b",
2657 unless you've already created a reference of your own pointing to
2658 them.
2660 [[forcing-fetch]]
2661 Forcing git fetch to do non-fast-forward updates
2662 ------------------------------------------------
2664 If git fetch fails because the new head of a branch is not a
2665 descendant of the old head, you may force the update with:
2667 -------------------------------------------------
2668 $ git fetch git://example.com/proj.git +master:refs/remotes/example/master
2669 -------------------------------------------------
2671 Note the addition of the "+" sign.  Alternatively, you can use the "-f"
2672 flag to force updates of all the fetched branches, as in:
2674 -------------------------------------------------
2675 $ git fetch -f origin
2676 -------------------------------------------------
2678 Be aware that commits that the old version of example/master pointed at
2679 may be lost, as we saw in the previous section.
2681 [[remote-branch-configuration]]
2682 Configuring remote branches
2683 ---------------------------
2685 We saw above that "origin" is just a shortcut to refer to the
2686 repository that you originally cloned from.  This information is
2687 stored in git configuration variables, which you can see using
2688 gitlink:git-config[1]:
2690 -------------------------------------------------
2691 $ git config -l
2692 core.repositoryformatversion=0
2693 core.filemode=true
2694 core.logallrefupdates=true
2695 remote.origin.url=git://git.kernel.org/pub/scm/git/git.git
2696 remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
2697 branch.master.remote=origin
2698 branch.master.merge=refs/heads/master
2699 -------------------------------------------------
2701 If there are other repositories that you also use frequently, you can
2702 create similar configuration options to save typing; for example,
2703 after
2705 -------------------------------------------------
2706 $ git config remote.example.url git://example.com/proj.git
2707 -------------------------------------------------
2709 then the following two commands will do the same thing:
2711 -------------------------------------------------
2712 $ git fetch git://example.com/proj.git master:refs/remotes/example/master
2713 $ git fetch example master:refs/remotes/example/master
2714 -------------------------------------------------
2716 Even better, if you add one more option:
2718 -------------------------------------------------
2719 $ git config remote.example.fetch master:refs/remotes/example/master
2720 -------------------------------------------------
2722 then the following commands will all do the same thing:
2724 -------------------------------------------------
2725 $ git fetch git://example.com/proj.git master:refs/remotes/example/master
2726 $ git fetch example master:refs/remotes/example/master
2727 $ git fetch example
2728 -------------------------------------------------
2730 You can also add a "+" to force the update each time:
2732 -------------------------------------------------
2733 $ git config remote.example.fetch +master:ref/remotes/example/master
2734 -------------------------------------------------
2736 Don't do this unless you're sure you won't mind "git fetch" possibly
2737 throwing away commits on mybranch.
2739 Also note that all of the above configuration can be performed by
2740 directly editing the file .git/config instead of using
2741 gitlink:git-config[1].
2743 See gitlink:git-config[1] for more details on the configuration
2744 options mentioned above.
2747 [[git-internals]]
2748 Git internals
2749 =============
2751 Git depends on two fundamental abstractions: the "object database", and
2752 the "current directory cache" aka "index".
2754 [[the-object-database]]
2755 The Object Database
2756 -------------------
2758 The object database is literally just a content-addressable collection
2759 of objects.  All objects are named by their content, which is
2760 approximated by the SHA1 hash of the object itself.  Objects may refer
2761 to other objects (by referencing their SHA1 hash), and so you can
2762 build up a hierarchy of objects.
2764 All objects have a statically determined "type" which is
2765 determined at object creation time, and which identifies the format of
2766 the object (i.e. how it is used, and how it can refer to other
2767 objects).  There are currently four different object types: "blob",
2768 "tree", "commit", and "tag".
2770 A <<def_blob_object,"blob" object>> cannot refer to any other object,
2771 and is, as the name implies, a pure storage object containing some
2772 user data.  It is used to actually store the file data, i.e. a blob
2773 object is associated with some particular version of some file.
2775 A <<def_tree_object,"tree" object>> is an object that ties one or more
2776 "blob" objects into a directory structure. In addition, a tree object
2777 can refer to other tree objects, thus creating a directory hierarchy.
2779 A <<def_commit_object,"commit" object>> ties such directory hierarchies
2780 together into a <<def_DAG,directed acyclic graph>> of revisions - each
2781 "commit" is associated with exactly one tree (the directory hierarchy at
2782 the time of the commit). In addition, a "commit" refers to one or more
2783 "parent" commit objects that describe the history of how we arrived at
2784 that directory hierarchy.
2786 As a special case, a commit object with no parents is called the "root"
2787 commit, and is the point of an initial project commit.  Each project
2788 must have at least one root, and while you can tie several different
2789 root objects together into one project by creating a commit object which
2790 has two or more separate roots as its ultimate parents, that's probably
2791 just going to confuse people.  So aim for the notion of "one root object
2792 per project", even if git itself does not enforce that.
2794 A <<def_tag_object,"tag" object>> symbolically identifies and can be
2795 used to sign other objects. It contains the identifier and type of
2796 another object, a symbolic name (of course!) and, optionally, a
2797 signature.
2799 Regardless of object type, all objects share the following
2800 characteristics: they are all deflated with zlib, and have a header
2801 that not only specifies their type, but also provides size information
2802 about the data in the object.  It's worth noting that the SHA1 hash
2803 that is used to name the object is the hash of the original data
2804 plus this header, so `sha1sum` 'file' does not match the object name
2805 for 'file'.
2806 (Historical note: in the dawn of the age of git the hash
2807 was the sha1 of the 'compressed' object.)
2809 As a result, the general consistency of an object can always be tested
2810 independently of the contents or the type of the object: all objects can
2811 be validated by verifying that (a) their hashes match the content of the
2812 file and (b) the object successfully inflates to a stream of bytes that
2813 forms a sequence of <ascii type without space> {plus} <space> {plus} <ascii decimal
2814 size> {plus} <byte\0> {plus} <binary object data>.
2816 The structured objects can further have their structure and
2817 connectivity to other objects verified. This is generally done with
2818 the `git-fsck` program, which generates a full dependency graph
2819 of all objects, and verifies their internal consistency (in addition
2820 to just verifying their superficial consistency through the hash).
2822 The object types in some more detail:
2824 [[blob-object]]
2825 Blob Object
2826 -----------
2828 A "blob" object is nothing but a binary blob of data, and doesn't
2829 refer to anything else.  There is no signature or any other
2830 verification of the data, so while the object is consistent (it 'is'
2831 indexed by its sha1 hash, so the data itself is certainly correct), it
2832 has absolutely no other attributes.  No name associations, no
2833 permissions.  It is purely a blob of data (i.e. normally "file
2834 contents").
2836 In particular, since the blob is entirely defined by its data, if two
2837 files in a directory tree (or in multiple different versions of the
2838 repository) have the same contents, they will share the same blob
2839 object. The object is totally independent of its location in the
2840 directory tree, and renaming a file does not change the object that
2841 file is associated with in any way.
2843 A blob is typically created when gitlink:git-update-index[1]
2844 is run, and its data can be accessed by gitlink:git-cat-file[1].
2846 [[tree-object]]
2847 Tree Object
2848 -----------
2850 The next hierarchical object type is the "tree" object.  A tree object
2851 is a list of mode/name/blob data, sorted by name.  Alternatively, the
2852 mode data may specify a directory mode, in which case instead of
2853 naming a blob, that name is associated with another TREE object.
2855 Like the "blob" object, a tree object is uniquely determined by the
2856 set contents, and so two separate but identical trees will always
2857 share the exact same object. This is true at all levels, i.e. it's
2858 true for a "leaf" tree (which does not refer to any other trees, only
2859 blobs) as well as for a whole subdirectory.
2861 For that reason a "tree" object is just a pure data abstraction: it
2862 has no history, no signatures, no verification of validity, except
2863 that since the contents are again protected by the hash itself, we can
2864 trust that the tree is immutable and its contents never change.
2866 So you can trust the contents of a tree to be valid, the same way you
2867 can trust the contents of a blob, but you don't know where those
2868 contents 'came' from.
2870 Side note on trees: since a "tree" object is a sorted list of
2871 "filename+content", you can create a diff between two trees without
2872 actually having to unpack two trees.  Just ignore all common parts,
2873 and your diff will look right.  In other words, you can effectively
2874 (and efficiently) tell the difference between any two random trees by
2875 O(n) where "n" is the size of the difference, rather than the size of
2876 the tree.
2878 Side note 2 on trees: since the name of a "blob" depends entirely and
2879 exclusively on its contents (i.e. there are no names or permissions
2880 involved), you can see trivial renames or permission changes by
2881 noticing that the blob stayed the same.  However, renames with data
2882 changes need a smarter "diff" implementation.
2884 A tree is created with gitlink:git-write-tree[1] and
2885 its data can be accessed by gitlink:git-ls-tree[1].
2886 Two trees can be compared with gitlink:git-diff-tree[1].
2888 [[commit-object]]
2889 Commit Object
2890 -------------
2892 The "commit" object is an object that introduces the notion of
2893 history into the picture.  In contrast to the other objects, it
2894 doesn't just describe the physical state of a tree, it describes how
2895 we got there, and why.
2897 A "commit" is defined by the tree-object that it results in, the
2898 parent commits (zero, one or more) that led up to that point, and a
2899 comment on what happened.  Again, a commit is not trusted per se:
2900 the contents are well-defined and "safe" due to the cryptographically
2901 strong signatures at all levels, but there is no reason to believe
2902 that the tree is "good" or that the merge information makes sense.
2903 The parents do not have to actually have any relationship with the
2904 result, for example.
2906 Note on commits: unlike some SCM's, commits do not contain
2907 rename information or file mode change information.  All of that is
2908 implicit in the trees involved (the result tree, and the result trees
2909 of the parents), and describing that makes no sense in this idiotic
2910 file manager.
2912 A commit is created with gitlink:git-commit-tree[1] and
2913 its data can be accessed by gitlink:git-cat-file[1].
2915 [[trust]]
2916 Trust
2917 -----
2919 An aside on the notion of "trust". Trust is really outside the scope
2920 of "git", but it's worth noting a few things.  First off, since
2921 everything is hashed with SHA1, you 'can' trust that an object is
2922 intact and has not been messed with by external sources.  So the name
2923 of an object uniquely identifies a known state - just not a state that
2924 you may want to trust.
2926 Furthermore, since the SHA1 signature of a commit refers to the
2927 SHA1 signatures of the tree it is associated with and the signatures
2928 of the parent, a single named commit specifies uniquely a whole set
2929 of history, with full contents.  You can't later fake any step of the
2930 way once you have the name of a commit.
2932 So to introduce some real trust in the system, the only thing you need
2933 to do is to digitally sign just 'one' special note, which includes the
2934 name of a top-level commit.  Your digital signature shows others
2935 that you trust that commit, and the immutability of the history of
2936 commits tells others that they can trust the whole history.
2938 In other words, you can easily validate a whole archive by just
2939 sending out a single email that tells the people the name (SHA1 hash)
2940 of the top commit, and digitally sign that email using something
2941 like GPG/PGP.
2943 To assist in this, git also provides the tag object...
2945 [[tag-object]]
2946 Tag Object
2947 ----------
2949 Git provides the "tag" object to simplify creating, managing and
2950 exchanging symbolic and signed tokens.  The "tag" object at its
2951 simplest simply symbolically identifies another object by containing
2952 the sha1, type and symbolic name.
2954 However it can optionally contain additional signature information
2955 (which git doesn't care about as long as there's less than 8k of
2956 it). This can then be verified externally to git.
2958 Note that despite the tag features, "git" itself only handles content
2959 integrity; the trust framework (and signature provision and
2960 verification) has to come from outside.
2962 A tag is created with gitlink:git-mktag[1],
2963 its data can be accessed by gitlink:git-cat-file[1],
2964 and the signature can be verified by
2965 gitlink:git-verify-tag[1].
2968 [[the-index]]
2969 The "index" aka "Current Directory Cache"
2970 -----------------------------------------
2972 The index is a simple binary file, which contains an efficient
2973 representation of the contents of a virtual directory.  It
2974 does so by a simple array that associates a set of names, dates,
2975 permissions and content (aka "blob") objects together.  The cache is
2976 always kept ordered by name, and names are unique (with a few very
2977 specific rules) at any point in time, but the cache has no long-term
2978 meaning, and can be partially updated at any time.
2980 In particular, the index certainly does not need to be consistent with
2981 the current directory contents (in fact, most operations will depend on
2982 different ways to make the index 'not' be consistent with the directory
2983 hierarchy), but it has three very important attributes:
2985 '(a) it can re-generate the full state it caches (not just the
2986 directory structure: it contains pointers to the "blob" objects so
2987 that it can regenerate the data too)'
2989 As a special case, there is a clear and unambiguous one-way mapping
2990 from a current directory cache to a "tree object", which can be
2991 efficiently created from just the current directory cache without
2992 actually looking at any other data.  So a directory cache at any one
2993 time uniquely specifies one and only one "tree" object (but has
2994 additional data to make it easy to match up that tree object with what
2995 has happened in the directory)
2997 '(b) it has efficient methods for finding inconsistencies between that
2998 cached state ("tree object waiting to be instantiated") and the
2999 current state.'
3001 '(c) it can additionally efficiently represent information about merge
3002 conflicts between different tree objects, allowing each pathname to be
3003 associated with sufficient information about the trees involved that
3004 you can create a three-way merge between them.'
3006 Those are the ONLY three things that the directory cache does.  It's a
3007 cache, and the normal operation is to re-generate it completely from a
3008 known tree object, or update/compare it with a live tree that is being
3009 developed.  If you blow the directory cache away entirely, you generally
3010 haven't lost any information as long as you have the name of the tree
3011 that it described.
3013 At the same time, the index is also the staging area for creating
3014 new trees, and creating a new tree always involves a controlled
3015 modification of the index file.  In particular, the index file can
3016 have the representation of an intermediate tree that has not yet been
3017 instantiated.  So the index can be thought of as a write-back cache,
3018 which can contain dirty information that has not yet been written back
3019 to the backing store.
3023 [[the-workflow]]
3024 The Workflow
3025 ------------
3027 Generally, all "git" operations work on the index file. Some operations
3028 work *purely* on the index file (showing the current state of the
3029 index), but most operations move data to and from the index file. Either
3030 from the database or from the working directory. Thus there are four
3031 main combinations:
3033 [[working-directory-to-index]]
3034 working directory -> index
3035 ~~~~~~~~~~~~~~~~~~~~~~~~~~
3037 You update the index with information from the working directory with
3038 the gitlink:git-update-index[1] command.  You
3039 generally update the index information by just specifying the filename
3040 you want to update, like so:
3042 -------------------------------------------------
3043 $ git-update-index filename
3044 -------------------------------------------------
3046 but to avoid common mistakes with filename globbing etc, the command
3047 will not normally add totally new entries or remove old entries,
3048 i.e. it will normally just update existing cache entries.
3050 To tell git that yes, you really do realize that certain files no
3051 longer exist, or that new files should be added, you
3052 should use the `--remove` and `--add` flags respectively.
3054 NOTE! A `--remove` flag does 'not' mean that subsequent filenames will
3055 necessarily be removed: if the files still exist in your directory
3056 structure, the index will be updated with their new status, not
3057 removed. The only thing `--remove` means is that update-cache will be
3058 considering a removed file to be a valid thing, and if the file really
3059 does not exist any more, it will update the index accordingly.
3061 As a special case, you can also do `git-update-index --refresh`, which
3062 will refresh the "stat" information of each index to match the current
3063 stat information. It will 'not' update the object status itself, and
3064 it will only update the fields that are used to quickly test whether
3065 an object still matches its old backing store object.
3067 [[index-to-object-database]]
3068 index -> object database
3069 ~~~~~~~~~~~~~~~~~~~~~~~~
3071 You write your current index file to a "tree" object with the program
3073 -------------------------------------------------
3074 $ git-write-tree
3075 -------------------------------------------------
3077 that doesn't come with any options - it will just write out the
3078 current index into the set of tree objects that describe that state,
3079 and it will return the name of the resulting top-level tree. You can
3080 use that tree to re-generate the index at any time by going in the
3081 other direction:
3083 [[object-database-to-index]]
3084 object database -> index
3085 ~~~~~~~~~~~~~~~~~~~~~~~~
3087 You read a "tree" file from the object database, and use that to
3088 populate (and overwrite - don't do this if your index contains any
3089 unsaved state that you might want to restore later!) your current
3090 index.  Normal operation is just
3092 -------------------------------------------------
3093 $ git-read-tree <sha1 of tree>
3094 -------------------------------------------------
3096 and your index file will now be equivalent to the tree that you saved
3097 earlier. However, that is only your 'index' file: your working
3098 directory contents have not been modified.
3100 [[index-to-working-directory]]
3101 index -> working directory
3102 ~~~~~~~~~~~~~~~~~~~~~~~~~~
3104 You update your working directory from the index by "checking out"
3105 files. This is not a very common operation, since normally you'd just
3106 keep your files updated, and rather than write to your working
3107 directory, you'd tell the index files about the changes in your
3108 working directory (i.e. `git-update-index`).
3110 However, if you decide to jump to a new version, or check out somebody
3111 else's version, or just restore a previous tree, you'd populate your
3112 index file with read-tree, and then you need to check out the result
3113 with
3115 -------------------------------------------------
3116 $ git-checkout-index filename
3117 -------------------------------------------------
3119 or, if you want to check out all of the index, use `-a`.
3121 NOTE! git-checkout-index normally refuses to overwrite old files, so
3122 if you have an old version of the tree already checked out, you will
3123 need to use the "-f" flag ('before' the "-a" flag or the filename) to
3124 'force' the checkout.
3127 Finally, there are a few odds and ends which are not purely moving
3128 from one representation to the other:
3130 [[tying-it-all-together]]
3131 Tying it all together
3132 ~~~~~~~~~~~~~~~~~~~~~
3134 To commit a tree you have instantiated with "git-write-tree", you'd
3135 create a "commit" object that refers to that tree and the history
3136 behind it - most notably the "parent" commits that preceded it in
3137 history.
3139 Normally a "commit" has one parent: the previous state of the tree
3140 before a certain change was made. However, sometimes it can have two
3141 or more parent commits, in which case we call it a "merge", due to the
3142 fact that such a commit brings together ("merges") two or more
3143 previous states represented by other commits.
3145 In other words, while a "tree" represents a particular directory state
3146 of a working directory, a "commit" represents that state in "time",
3147 and explains how we got there.
3149 You create a commit object by giving it the tree that describes the
3150 state at the time of the commit, and a list of parents:
3152 -------------------------------------------------
3153 $ git-commit-tree <tree> -p <parent> [-p <parent2> ..]
3154 -------------------------------------------------
3156 and then giving the reason for the commit on stdin (either through
3157 redirection from a pipe or file, or by just typing it at the tty).
3159 git-commit-tree will return the name of the object that represents
3160 that commit, and you should save it away for later use. Normally,
3161 you'd commit a new `HEAD` state, and while git doesn't care where you
3162 save the note about that state, in practice we tend to just write the
3163 result to the file pointed at by `.git/HEAD`, so that we can always see
3164 what the last committed state was.
3166 Here is an ASCII art by Jon Loeliger that illustrates how
3167 various pieces fit together.
3169 ------------
3171                      commit-tree
3172                       commit obj
3173                        +----+
3174                        |    |
3175                        |    |
3176                        V    V
3177                     +-----------+
3178                     | Object DB |
3179                     |  Backing  |
3180                     |   Store   |
3181                     +-----------+
3182                        ^
3183            write-tree  |     |
3184              tree obj  |     |
3185                        |     |  read-tree
3186                        |     |  tree obj
3187                              V
3188                     +-----------+
3189                     |   Index   |
3190                     |  "cache"  |
3191                     +-----------+
3192          update-index  ^
3193              blob obj  |     |
3194                        |     |
3195     checkout-index -u  |     |  checkout-index
3196              stat      |     |  blob obj
3197                              V
3198                     +-----------+
3199                     |  Working  |
3200                     | Directory |
3201                     +-----------+
3203 ------------
3206 [[examining-the-data]]
3207 Examining the data
3208 ------------------
3210 You can examine the data represented in the object database and the
3211 index with various helper tools. For every object, you can use
3212 gitlink:git-cat-file[1] to examine details about the
3213 object:
3215 -------------------------------------------------
3216 $ git-cat-file -t <objectname>
3217 -------------------------------------------------
3219 shows the type of the object, and once you have the type (which is
3220 usually implicit in where you find the object), you can use
3222 -------------------------------------------------
3223 $ git-cat-file blob|tree|commit|tag <objectname>
3224 -------------------------------------------------
3226 to show its contents. NOTE! Trees have binary content, and as a result
3227 there is a special helper for showing that content, called
3228 `git-ls-tree`, which turns the binary content into a more easily
3229 readable form.
3231 It's especially instructive to look at "commit" objects, since those
3232 tend to be small and fairly self-explanatory. In particular, if you
3233 follow the convention of having the top commit name in `.git/HEAD`,
3234 you can do
3236 -------------------------------------------------
3237 $ git-cat-file commit HEAD
3238 -------------------------------------------------
3240 to see what the top commit was.
3242 [[merging-multiple-trees]]
3243 Merging multiple trees
3244 ----------------------
3246 Git helps you do a three-way merge, which you can expand to n-way by
3247 repeating the merge procedure arbitrary times until you finally
3248 "commit" the state.  The normal situation is that you'd only do one
3249 three-way merge (two parents), and commit it, but if you like to, you
3250 can do multiple parents in one go.
3252 To do a three-way merge, you need the two sets of "commit" objects
3253 that you want to merge, use those to find the closest common parent (a
3254 third "commit" object), and then use those commit objects to find the
3255 state of the directory ("tree" object) at these points.
3257 To get the "base" for the merge, you first look up the common parent
3258 of two commits with
3260 -------------------------------------------------
3261 $ git-merge-base <commit1> <commit2>
3262 -------------------------------------------------
3264 which will return you the commit they are both based on.  You should
3265 now look up the "tree" objects of those commits, which you can easily
3266 do with (for example)
3268 -------------------------------------------------
3269 $ git-cat-file commit <commitname> | head -1
3270 -------------------------------------------------
3272 since the tree object information is always the first line in a commit
3273 object.
3275 Once you know the three trees you are going to merge (the one "original"
3276 tree, aka the common tree, and the two "result" trees, aka the branches
3277 you want to merge), you do a "merge" read into the index. This will
3278 complain if it has to throw away your old index contents, so you should
3279 make sure that you've committed those - in fact you would normally
3280 always do a merge against your last commit (which should thus match what
3281 you have in your current index anyway).
3283 To do the merge, do
3285 -------------------------------------------------
3286 $ git-read-tree -m -u <origtree> <yourtree> <targettree>
3287 -------------------------------------------------
3289 which will do all trivial merge operations for you directly in the
3290 index file, and you can just write the result out with
3291 `git-write-tree`.
3294 [[merging-multiple-trees-2]]
3295 Merging multiple trees, continued
3296 ---------------------------------
3298 Sadly, many merges aren't trivial. If there are files that have
3299 been added.moved or removed, or if both branches have modified the
3300 same file, you will be left with an index tree that contains "merge
3301 entries" in it. Such an index tree can 'NOT' be written out to a tree
3302 object, and you will have to resolve any such merge clashes using
3303 other tools before you can write out the result.
3305 You can examine such index state with `git-ls-files --unmerged`
3306 command.  An example:
3308 ------------------------------------------------
3309 $ git-read-tree -m $orig HEAD $target
3310 $ git-ls-files --unmerged
3311 100644 263414f423d0e4d70dae8fe53fa34614ff3e2860 1       hello.c
3312 100644 06fa6a24256dc7e560efa5687fa84b51f0263c3a 2       hello.c
3313 100644 cc44c73eb783565da5831b4d820c962954019b69 3       hello.c
3314 ------------------------------------------------
3316 Each line of the `git-ls-files --unmerged` output begins with
3317 the blob mode bits, blob SHA1, 'stage number', and the
3318 filename.  The 'stage number' is git's way to say which tree it
3319 came from: stage 1 corresponds to `$orig` tree, stage 2 `HEAD`
3320 tree, and stage3 `$target` tree.
3322 Earlier we said that trivial merges are done inside
3323 `git-read-tree -m`.  For example, if the file did not change
3324 from `$orig` to `HEAD` nor `$target`, or if the file changed
3325 from `$orig` to `HEAD` and `$orig` to `$target` the same way,
3326 obviously the final outcome is what is in `HEAD`.  What the
3327 above example shows is that file `hello.c` was changed from
3328 `$orig` to `HEAD` and `$orig` to `$target` in a different way.
3329 You could resolve this by running your favorite 3-way merge
3330 program, e.g.  `diff3`, `merge`, or git's own merge-file, on
3331 the blob objects from these three stages yourself, like this:
3333 ------------------------------------------------
3334 $ git-cat-file blob 263414f... >hello.c~1
3335 $ git-cat-file blob 06fa6a2... >hello.c~2
3336 $ git-cat-file blob cc44c73... >hello.c~3
3337 $ git merge-file hello.c~2 hello.c~1 hello.c~3
3338 ------------------------------------------------
3340 This would leave the merge result in `hello.c~2` file, along
3341 with conflict markers if there are conflicts.  After verifying
3342 the merge result makes sense, you can tell git what the final
3343 merge result for this file is by:
3345 -------------------------------------------------
3346 $ mv -f hello.c~2 hello.c
3347 $ git-update-index hello.c
3348 -------------------------------------------------
3350 When a path is in unmerged state, running `git-update-index` for
3351 that path tells git to mark the path resolved.
3353 The above is the description of a git merge at the lowest level,
3354 to help you understand what conceptually happens under the hood.
3355 In practice, nobody, not even git itself, uses three `git-cat-file`
3356 for this.  There is `git-merge-index` program that extracts the
3357 stages to temporary files and calls a "merge" script on it:
3359 -------------------------------------------------
3360 $ git-merge-index git-merge-one-file hello.c
3361 -------------------------------------------------
3363 and that is what higher level `git merge -s resolve` is implemented with.
3365 [[pack-files]]
3366 How git stores objects efficiently: pack files
3367 ----------------------------------------------
3369 We've seen how git stores each object in a file named after the
3370 object's SHA1 hash.
3372 Unfortunately this system becomes inefficient once a project has a
3373 lot of objects.  Try this on an old project:
3375 ------------------------------------------------
3376 $ git count-objects
3377 6930 objects, 47620 kilobytes
3378 ------------------------------------------------
3380 The first number is the number of objects which are kept in
3381 individual files.  The second is the amount of space taken up by
3382 those "loose" objects.
3384 You can save space and make git faster by moving these loose objects in
3385 to a "pack file", which stores a group of objects in an efficient
3386 compressed format; the details of how pack files are formatted can be
3387 found in link:technical/pack-format.txt[technical/pack-format.txt].
3389 To put the loose objects into a pack, just run git repack:
3391 ------------------------------------------------
3392 $ git repack
3393 Generating pack...
3394 Done counting 6020 objects.
3395 Deltifying 6020 objects.
3396  100% (6020/6020) done
3397 Writing 6020 objects.
3398  100% (6020/6020) done
3399 Total 6020, written 6020 (delta 4070), reused 0 (delta 0)
3400 Pack pack-3e54ad29d5b2e05838c75df582c65257b8d08e1c created.
3401 ------------------------------------------------
3403 You can then run
3405 ------------------------------------------------
3406 $ git prune
3407 ------------------------------------------------
3409 to remove any of the "loose" objects that are now contained in the
3410 pack.  This will also remove any unreferenced objects (which may be
3411 created when, for example, you use "git reset" to remove a commit).
3412 You can verify that the loose objects are gone by looking at the
3413 .git/objects directory or by running
3415 ------------------------------------------------
3416 $ git count-objects
3417 0 objects, 0 kilobytes
3418 ------------------------------------------------
3420 Although the object files are gone, any commands that refer to those
3421 objects will work exactly as they did before.
3423 The gitlink:git-gc[1] command performs packing, pruning, and more for
3424 you, so is normally the only high-level command you need.
3426 [[dangling-objects]]
3427 Dangling objects
3428 ----------------
3430 The gitlink:git-fsck[1] command will sometimes complain about dangling
3431 objects.  They are not a problem.
3433 The most common cause of dangling objects is that you've rebased a
3434 branch, or you have pulled from somebody else who rebased a branch--see
3435 <<cleaning-up-history>>.  In that case, the old head of the original
3436 branch still exists, as does everything it pointed to. The branch
3437 pointer itself just doesn't, since you replaced it with another one.
3439 There are also other situations that cause dangling objects. For
3440 example, a "dangling blob" may arise because you did a "git add" of a
3441 file, but then, before you actually committed it and made it part of the
3442 bigger picture, you changed something else in that file and committed
3443 that *updated* thing - the old state that you added originally ends up
3444 not being pointed to by any commit or tree, so it's now a dangling blob
3445 object.
3447 Similarly, when the "recursive" merge strategy runs, and finds that
3448 there are criss-cross merges and thus more than one merge base (which is
3449 fairly unusual, but it does happen), it will generate one temporary
3450 midway tree (or possibly even more, if you had lots of criss-crossing
3451 merges and more than two merge bases) as a temporary internal merge
3452 base, and again, those are real objects, but the end result will not end
3453 up pointing to them, so they end up "dangling" in your repository.
3455 Generally, dangling objects aren't anything to worry about. They can
3456 even be very useful: if you screw something up, the dangling objects can
3457 be how you recover your old tree (say, you did a rebase, and realized
3458 that you really didn't want to - you can look at what dangling objects
3459 you have, and decide to reset your head to some old dangling state).
3461 For commits, you can just use:
3463 ------------------------------------------------
3464 $ gitk <dangling-commit-sha-goes-here> --not --all
3465 ------------------------------------------------
3467 This asks for all the history reachable from the given commit but not
3468 from any branch, tag, or other reference.  If you decide it's something
3469 you want, you can always create a new reference to it, e.g.,
3471 ------------------------------------------------
3472 $ git branch recovered-branch <dangling-commit-sha-goes-here>
3473 ------------------------------------------------
3475 For blobs and trees, you can't do the same, but you can still examine
3476 them.  You can just do
3478 ------------------------------------------------
3479 $ git show <dangling-blob/tree-sha-goes-here>
3480 ------------------------------------------------
3482 to show what the contents of the blob were (or, for a tree, basically
3483 what the "ls" for that directory was), and that may give you some idea
3484 of what the operation was that left that dangling object.
3486 Usually, dangling blobs and trees aren't very interesting. They're
3487 almost always the result of either being a half-way mergebase (the blob
3488 will often even have the conflict markers from a merge in it, if you
3489 have had conflicting merges that you fixed up by hand), or simply
3490 because you interrupted a "git fetch" with ^C or something like that,
3491 leaving _some_ of the new objects in the object database, but just
3492 dangling and useless.
3494 Anyway, once you are sure that you're not interested in any dangling
3495 state, you can just prune all unreachable objects:
3497 ------------------------------------------------
3498 $ git prune
3499 ------------------------------------------------
3501 and they'll be gone. But you should only run "git prune" on a quiescent
3502 repository - it's kind of like doing a filesystem fsck recovery: you
3503 don't want to do that while the filesystem is mounted.
3505 (The same is true of "git-fsck" itself, btw - but since
3506 git-fsck never actually *changes* the repository, it just reports
3507 on what it found, git-fsck itself is never "dangerous" to run.
3508 Running it while somebody is actually changing the repository can cause
3509 confusing and scary messages, but it won't actually do anything bad. In
3510 contrast, running "git prune" while somebody is actively changing the
3511 repository is a *BAD* idea).
3513 [[birdview-on-the-source-code]]
3514 A birds-eye view of Git's source code
3515 -------------------------------------
3517 It is not always easy for new developers to find their way through Git's
3518 source code.  This section gives you a little guidance to show where to
3519 start.
3521 A good place to start is with the contents of the initial commit, with:
3523 ----------------------------------------------------
3524 $ git checkout e83c5163
3525 ----------------------------------------------------
3527 The initial revision lays the foundation for almost everything git has
3528 today, but is small enough to read in one sitting.
3530 Note that terminology has changed since that revision.  For example, the
3531 README in that revision uses the word "changeset" to describe what we
3532 now call a <<def_commit_object,commit>>.
3534 Also, we do not call it "cache" any more, but "index", however, the
3535 file is still called `cache.h`.  Remark: Not much reason to change it now,
3536 especially since there is no good single name for it anyway, because it is
3537 basically _the_ header file which is included by _all_ of Git's C sources.
3539 If you grasp the ideas in that initial commit, you should check out a
3540 more recent version and skim `cache.h`, `object.h` and `commit.h`.
3542 In the early days, Git (in the tradition of UNIX) was a bunch of programs
3543 which were extremely simple, and which you used in scripts, piping the
3544 output of one into another. This turned out to be good for initial
3545 development, since it was easier to test new things.  However, recently
3546 many of these parts have become builtins, and some of the core has been
3547 "libified", i.e. put into libgit.a for performance, portability reasons,
3548 and to avoid code duplication.
3550 By now, you know what the index is (and find the corresponding data
3551 structures in `cache.h`), and that there are just a couple of object types
3552 (blobs, trees, commits and tags) which inherit their common structure from
3553 `struct object`, which is their first member (and thus, you can cast e.g.
3554 `(struct object *)commit` to achieve the _same_ as `&commit->object`, i.e.
3555 get at the object name and flags).
3557 Now is a good point to take a break to let this information sink in.
3559 Next step: get familiar with the object naming.  Read <<naming-commits>>.
3560 There are quite a few ways to name an object (and not only revisions!).
3561 All of these are handled in `sha1_name.c`. Just have a quick look at
3562 the function `get_sha1()`. A lot of the special handling is done by
3563 functions like `get_sha1_basic()` or the likes.
3565 This is just to get you into the groove for the most libified part of Git:
3566 the revision walker.
3568 Basically, the initial version of `git log` was a shell script:
3570 ----------------------------------------------------------------
3571 $ git-rev-list --pretty $(git-rev-parse --default HEAD "$@") | \
3572         LESS=-S ${PAGER:-less}
3573 ----------------------------------------------------------------
3575 What does this mean?
3577 `git-rev-list` is the original version of the revision walker, which
3578 _always_ printed a list of revisions to stdout.  It is still functional,
3579 and needs to, since most new Git programs start out as scripts using
3580 `git-rev-list`.
3582 `git-rev-parse` is not as important any more; it was only used to filter out
3583 options that were relevant for the different plumbing commands that were
3584 called by the script.
3586 Most of what `git-rev-list` did is contained in `revision.c` and
3587 `revision.h`.  It wraps the options in a struct named `rev_info`, which
3588 controls how and what revisions are walked, and more.
3590 The original job of `git-rev-parse` is now taken by the function
3591 `setup_revisions()`, which parses the revisions and the common command line
3592 options for the revision walker. This information is stored in the struct
3593 `rev_info` for later consumption. You can do your own command line option
3594 parsing after calling `setup_revisions()`. After that, you have to call
3595 `prepare_revision_walk()` for initialization, and then you can get the
3596 commits one by one with the function `get_revision()`.
3598 If you are interested in more details of the revision walking process,
3599 just have a look at the first implementation of `cmd_log()`; call
3600 `git-show v1.3.0~155^2~4` and scroll down to that function (note that you
3601 no longer need to call `setup_pager()` directly).
3603 Nowadays, `git log` is a builtin, which means that it is _contained_ in the
3604 command `git`.  The source side of a builtin is
3606 - a function called `cmd_<bla>`, typically defined in `builtin-<bla>.c`,
3607   and declared in `builtin.h`,
3609 - an entry in the `commands[]` array in `git.c`, and
3611 - an entry in `BUILTIN_OBJECTS` in the `Makefile`.
3613 Sometimes, more than one builtin is contained in one source file.  For
3614 example, `cmd_whatchanged()` and `cmd_log()` both reside in `builtin-log.c`,
3615 since they share quite a bit of code.  In that case, the commands which are
3616 _not_ named like the `.c` file in which they live have to be listed in
3617 `BUILT_INS` in the `Makefile`.
3619 `git log` looks more complicated in C than it does in the original script,
3620 but that allows for a much greater flexibility and performance.
3622 Here again it is a good point to take a pause.
3624 Lesson three is: study the code.  Really, it is the best way to learn about
3625 the organization of Git (after you know the basic concepts).
3627 So, think about something which you are interested in, say, "how can I
3628 access a blob just knowing the object name of it?".  The first step is to
3629 find a Git command with which you can do it.  In this example, it is either
3630 `git show` or `git cat-file`.
3632 For the sake of clarity, let's stay with `git cat-file`, because it
3634 - is plumbing, and
3636 - was around even in the initial commit (it literally went only through
3637   some 20 revisions as `cat-file.c`, was renamed to `builtin-cat-file.c`
3638   when made a builtin, and then saw less than 10 versions).
3640 So, look into `builtin-cat-file.c`, search for `cmd_cat_file()` and look what
3641 it does.
3643 ------------------------------------------------------------------
3644         git_config(git_default_config);
3645         if (argc != 3)
3646                 usage("git-cat-file [-t|-s|-e|-p|<type>] <sha1>");
3647         if (get_sha1(argv[2], sha1))
3648                 die("Not a valid object name %s", argv[2]);
3649 ------------------------------------------------------------------
3651 Let's skip over the obvious details; the only really interesting part
3652 here is the call to `get_sha1()`.  It tries to interpret `argv[2]` as an
3653 object name, and if it refers to an object which is present in the current
3654 repository, it writes the resulting SHA-1 into the variable `sha1`.
3656 Two things are interesting here:
3658 - `get_sha1()` returns 0 on _success_.  This might surprise some new
3659   Git hackers, but there is a long tradition in UNIX to return different
3660   negative numbers in case of different errors -- and 0 on success.
3662 - the variable `sha1` in the function signature of `get_sha1()` is `unsigned
3663   char \*`, but is actually expected to be a pointer to `unsigned
3664   char[20]`.  This variable will contain the 160-bit SHA-1 of the given
3665   commit.  Note that whenever a SHA-1 is passed as `unsigned char \*`, it
3666   is the binary representation, as opposed to the ASCII representation in
3667   hex characters, which is passed as `char *`.
3669 You will see both of these things throughout the code.
3671 Now, for the meat:
3673 -----------------------------------------------------------------------------
3674         case 0:
3675                 buf = read_object_with_reference(sha1, argv[1], &size, NULL);
3676 -----------------------------------------------------------------------------
3678 This is how you read a blob (actually, not only a blob, but any type of
3679 object).  To know how the function `read_object_with_reference()` actually
3680 works, find the source code for it (something like `git grep
3681 read_object_with | grep ":[a-z]"` in the git repository), and read
3682 the source.
3684 To find out how the result can be used, just read on in `cmd_cat_file()`:
3686 -----------------------------------
3687         write_or_die(1, buf, size);
3688 -----------------------------------
3690 Sometimes, you do not know where to look for a feature.  In many such cases,
3691 it helps to search through the output of `git log`, and then `git show` the
3692 corresponding commit.
3694 Example: If you know that there was some test case for `git bundle`, but
3695 do not remember where it was (yes, you _could_ `git grep bundle t/`, but that
3696 does not illustrate the point!):
3698 ------------------------
3699 $ git log --no-merges t/
3700 ------------------------
3702 In the pager (`less`), just search for "bundle", go a few lines back,
3703 and see that it is in commit 18449ab0...  Now just copy this object name,
3704 and paste it into the command line
3706 -------------------
3707 $ git show 18449ab0
3708 -------------------
3710 Voila.
3712 Another example: Find out what to do in order to make some script a
3713 builtin:
3715 -------------------------------------------------
3716 $ git log --no-merges --diff-filter=A builtin-*.c
3717 -------------------------------------------------
3719 You see, Git is actually the best tool to find out about the source of Git
3720 itself!
3722 [[glossary]]
3723 include::glossary.txt[]
3725 [[git-quick-start]]
3726 Appendix A: Git Quick Reference
3727 ===============================
3729 This is a quick summary of the major commands; the previous chapters
3730 explain how these work in more detail.
3732 [[quick-creating-a-new-repository]]
3733 Creating a new repository
3734 -------------------------
3736 From a tarball:
3738 -----------------------------------------------
3739 $ tar xzf project.tar.gz
3740 $ cd project
3741 $ git init
3742 Initialized empty Git repository in .git/
3743 $ git add .
3744 $ git commit
3745 -----------------------------------------------
3747 From a remote repository:
3749 -----------------------------------------------
3750 $ git clone git://example.com/pub/project.git
3751 $ cd project
3752 -----------------------------------------------
3754 [[managing-branches]]
3755 Managing branches
3756 -----------------
3758 -----------------------------------------------
3759 $ git branch         # list all local branches in this repo
3760 $ git checkout test  # switch working directory to branch "test"
3761 $ git branch new     # create branch "new" starting at current HEAD
3762 $ git branch -d new  # delete branch "new"
3763 -----------------------------------------------
3765 Instead of basing new branch on current HEAD (the default), use:
3767 -----------------------------------------------
3768 $ git branch new test    # branch named "test"
3769 $ git branch new v2.6.15 # tag named v2.6.15
3770 $ git branch new HEAD^   # commit before the most recent
3771 $ git branch new HEAD^^  # commit before that
3772 $ git branch new test~10 # ten commits before tip of branch "test"
3773 -----------------------------------------------
3775 Create and switch to a new branch at the same time:
3777 -----------------------------------------------
3778 $ git checkout -b new v2.6.15
3779 -----------------------------------------------
3781 Update and examine branches from the repository you cloned from:
3783 -----------------------------------------------
3784 $ git fetch             # update
3785 $ git branch -r         # list
3786   origin/master
3787   origin/next
3788   ...
3789 $ git checkout -b masterwork origin/master
3790 -----------------------------------------------
3792 Fetch a branch from a different repository, and give it a new
3793 name in your repository:
3795 -----------------------------------------------
3796 $ git fetch git://example.com/project.git theirbranch:mybranch
3797 $ git fetch git://example.com/project.git v2.6.15:mybranch
3798 -----------------------------------------------
3800 Keep a list of repositories you work with regularly:
3802 -----------------------------------------------
3803 $ git remote add example git://example.com/project.git
3804 $ git remote                    # list remote repositories
3805 example
3806 origin
3807 $ git remote show example       # get details
3808 * remote example
3809   URL: git://example.com/project.git
3810   Tracked remote branches
3811     master next ...
3812 $ git fetch example             # update branches from example
3813 $ git branch -r                 # list all remote branches
3814 -----------------------------------------------
3817 [[exploring-history]]
3818 Exploring history
3819 -----------------
3821 -----------------------------------------------
3822 $ gitk                      # visualize and browse history
3823 $ git log                   # list all commits
3824 $ git log src/              # ...modifying src/
3825 $ git log v2.6.15..v2.6.16  # ...in v2.6.16, not in v2.6.15
3826 $ git log master..test      # ...in branch test, not in branch master
3827 $ git log test..master      # ...in branch master, but not in test
3828 $ git log test...master     # ...in one branch, not in both
3829 $ git log -S'foo()'         # ...where difference contain "foo()"
3830 $ git log --since="2 weeks ago"
3831 $ git log -p                # show patches as well
3832 $ git show                  # most recent commit
3833 $ git diff v2.6.15..v2.6.16 # diff between two tagged versions
3834 $ git diff v2.6.15..HEAD    # diff with current head
3835 $ git grep "foo()"          # search working directory for "foo()"
3836 $ git grep v2.6.15 "foo()"  # search old tree for "foo()"
3837 $ git show v2.6.15:a.txt    # look at old version of a.txt
3838 -----------------------------------------------
3840 Search for regressions:
3842 -----------------------------------------------
3843 $ git bisect start
3844 $ git bisect bad                # current version is bad
3845 $ git bisect good v2.6.13-rc2   # last known good revision
3846 Bisecting: 675 revisions left to test after this
3847                                 # test here, then:
3848 $ git bisect good               # if this revision is good, or
3849 $ git bisect bad                # if this revision is bad.
3850                                 # repeat until done.
3851 -----------------------------------------------
3853 [[making-changes]]
3854 Making changes
3855 --------------
3857 Make sure git knows who to blame:
3859 ------------------------------------------------
3860 $ cat >>~/.gitconfig <<\EOF
3861 [user]
3862         name = Your Name Comes Here
3863         email = you@yourdomain.example.com
3864 EOF
3865 ------------------------------------------------
3867 Select file contents to include in the next commit, then make the
3868 commit:
3870 -----------------------------------------------
3871 $ git add a.txt    # updated file
3872 $ git add b.txt    # new file
3873 $ git rm c.txt     # old file
3874 $ git commit
3875 -----------------------------------------------
3877 Or, prepare and create the commit in one step:
3879 -----------------------------------------------
3880 $ git commit d.txt # use latest content only of d.txt
3881 $ git commit -a    # use latest content of all tracked files
3882 -----------------------------------------------
3884 [[merging]]
3885 Merging
3886 -------
3888 -----------------------------------------------
3889 $ git merge test   # merge branch "test" into the current branch
3890 $ git pull git://example.com/project.git master
3891                    # fetch and merge in remote branch
3892 $ git pull . test  # equivalent to git merge test
3893 -----------------------------------------------
3895 [[sharing-your-changes]]
3896 Sharing your changes
3897 --------------------
3899 Importing or exporting patches:
3901 -----------------------------------------------
3902 $ git format-patch origin..HEAD # format a patch for each commit
3903                                 # in HEAD but not in origin
3904 $ git am mbox # import patches from the mailbox "mbox"
3905 -----------------------------------------------
3907 Fetch a branch in a different git repository, then merge into the
3908 current branch:
3910 -----------------------------------------------
3911 $ git pull git://example.com/project.git theirbranch
3912 -----------------------------------------------
3914 Store the fetched branch into a local branch before merging into the
3915 current branch:
3917 -----------------------------------------------
3918 $ git pull git://example.com/project.git theirbranch:mybranch
3919 -----------------------------------------------
3921 After creating commits on a local branch, update the remote
3922 branch with your commits:
3924 -----------------------------------------------
3925 $ git push ssh://example.com/project.git mybranch:theirbranch
3926 -----------------------------------------------
3928 When remote and local branch are both named "test":
3930 -----------------------------------------------
3931 $ git push ssh://example.com/project.git test
3932 -----------------------------------------------
3934 Shortcut version for a frequently used remote repository:
3936 -----------------------------------------------
3937 $ git remote add example ssh://example.com/project.git
3938 $ git push example test
3939 -----------------------------------------------
3941 [[repository-maintenance]]
3942 Repository maintenance
3943 ----------------------
3945 Check for corruption:
3947 -----------------------------------------------
3948 $ git fsck
3949 -----------------------------------------------
3951 Recompress, remove unused cruft:
3953 -----------------------------------------------
3954 $ git gc
3955 -----------------------------------------------
3958 [[todo]]
3959 Appendix B: Notes and todo list for this manual
3960 ===============================================
3962 This is a work in progress.
3964 The basic requirements:
3965         - It must be readable in order, from beginning to end, by
3966           someone intelligent with a basic grasp of the UNIX
3967           command line, but without any special knowledge of git.  If
3968           necessary, any other prerequisites should be specifically
3969           mentioned as they arise.
3970         - Whenever possible, section headings should clearly describe
3971           the task they explain how to do, in language that requires
3972           no more knowledge than necessary: for example, "importing
3973           patches into a project" rather than "the git-am command"
3975 Think about how to create a clear chapter dependency graph that will
3976 allow people to get to important topics without necessarily reading
3977 everything in between.
3979 Scan Documentation/ for other stuff left out; in particular:
3980         howto's
3981         some of technical/?
3982         hooks
3983         list of commands in gitlink:git[1]
3985 Scan email archives for other stuff left out
3987 Scan man pages to see if any assume more background than this manual
3988 provides.
3990 Simplify beginning by suggesting disconnected head instead of
3991 temporary branch creation?
3993 Add more good examples.  Entire sections of just cookbook examples
3994 might be a good idea; maybe make an "advanced examples" section a
3995 standard end-of-chapter section?
3997 Include cross-references to the glossary, where appropriate.
3999 Document shallow clones?  See draft 1.5.0 release notes for some
4000 documentation.
4002 Add a section on working with other version control systems, including
4003 CVS, Subversion, and just imports of series of release tarballs.
4005 More details on gitweb?
4007 Write a chapter on using plumbing and writing scripts.
4009 Alternates, clone -reference, etc.
4011 git unpack-objects -r for recovery