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