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