1Git User's Manual 2_________________ 3 4This manual is designed to be readable by someone with basic unix 5command-line skills, but no previous knowledge of git. 6 7Chapter 1 gives a brief overview of git commands, without any 8explanation; you may prefer to skip to chapter 2 on a first reading. 9 10Chapters 2 and 3 explain how to fetch and study a project using 11git--the tools you'd need to build and test a particular version of a 12software project, to search for regressions, and so on. 13 14Chapter 4 explains how to do development with git, and chapter 5 how 15to share that development with others. 16 17Further chapters cover more specialized topics. 18 19Comprehensive reference documentation is available through the man 20pages. For a command such as "git clone", just use 21 22------------------------------------------------ 23$ man git-clone 24------------------------------------------------ 25 26Git Quick Start 27=============== 28 29This is a quick summary of the major commands; the following chapters 30will explain how these work in more detail. 31 32Creating a new repository 33------------------------- 34 35From a tarball: 36 37----------------------------------------------- 38$ tar xzf project.tar.gz 39$ cd project 40$ git init 41Initialized empty Git repository in .git/ 42$ git add . 43$ git commit 44----------------------------------------------- 45 46From a remote repository: 47 48----------------------------------------------- 49$ git clone git://example.com/pub/project.git 50$ cd project 51----------------------------------------------- 52 53Managing branches 54----------------- 55 56----------------------------------------------- 57$ git branch # list all branches in this repo 58$ git checkout test # switch working directory to branch "test" 59$ git branch new # create branch "new" starting at current HEAD 60$ git branch -d new # delete branch "new" 61----------------------------------------------- 62 63Instead of basing new branch on current HEAD (the default), use: 64 65----------------------------------------------- 66$ git branch new test # branch named "test" 67$ git branch new v2.6.15 # tag named v2.6.15 68$ git branch new HEAD^ # commit before the most recent 69$ git branch new HEAD^^ # commit before that 70$ git branch new test~10 # ten commits before tip of branch "test" 71----------------------------------------------- 72 73Create and switch to a new branch at the same time: 74 75----------------------------------------------- 76$ git checkout -b new v2.6.15 77----------------------------------------------- 78 79Update and examine branches from the repository you cloned from: 80 81----------------------------------------------- 82$ git fetch # update 83$ git branch -r # list 84 origin/master 85 origin/next 86 ... 87$ git checkout -b masterwork origin/master 88----------------------------------------------- 89 90Fetch a branch from a different repository, and give it a new 91name in your repository: 92 93----------------------------------------------- 94$ git fetch git://example.com/project.git theirbranch:mybranch 95$ git fetch git://example.com/project.git v2.6.15:mybranch 96----------------------------------------------- 97 98Keep a list of repositories you work with regularly: 99 100----------------------------------------------- 101$ git remote add example git://example.com/project.git 102$ git remote # list remote repositories 103example 104origin 105$ git remote show example # get details 106* remote example 107 URL: git://example.com/project.git 108 Tracked remote branches 109 master next ... 110$ git fetch example # update branches from example 111$ git branch -r # list all remote branches 112----------------------------------------------- 113 114 115Exploring history 116----------------- 117 118----------------------------------------------- 119$ gitk # visualize and browse history 120$ git log # list all commits 121$ git log src/ # ...modifying src/ 122$ git log v2.6.15..v2.6.16 # ...in v2.6.16, not in v2.6.15 123$ git log master..test # ...in branch test, not in branch master 124$ git log test..master # ...in branch master, but not in test 125$ git log test...master # ...in one branch, not in both 126$ git log -S'foo()' # ...where difference contain "foo()" 127$ git log --since="2 weeks ago" 128$ git log -p # show patches as well 129$ git show # most recent commit 130$ git diff v2.6.15..v2.6.16 # diff between two tagged versions 131$ git diff v2.6.15..HEAD # diff with current head 132$ git grep "foo()" # search working directory for "foo()" 133$ git grep v2.6.15 "foo()" # search old tree for "foo()" 134$ git show v2.6.15:a.txt # look at old version of a.txt 135----------------------------------------------- 136 137Search for regressions: 138 139----------------------------------------------- 140$ git bisect start 141$ git bisect bad # current version is bad 142$ git bisect good v2.6.13-rc2 # last known good revision 143Bisecting: 675 revisions left to test after this 144 # test here, then: 145$ git bisect good # if this revision is good, or 146$ git bisect bad # if this revision is bad. 147 # repeat until done. 148----------------------------------------------- 149 150Making changes 151-------------- 152 153Make sure git knows who to blame: 154 155------------------------------------------------ 156$ cat >~/.gitconfig <<\EOF 157[user] 158 name = Your Name Comes Here 159 email = you@yourdomain.example.com 160EOF 161------------------------------------------------ 162 163Select file contents to include in the next commit, then make the 164commit: 165 166----------------------------------------------- 167$ git add a.txt # updated file 168$ git add b.txt # new file 169$ git rm c.txt # old file 170$ git commit 171----------------------------------------------- 172 173Or, prepare and create the commit in one step: 174 175----------------------------------------------- 176$ git commit d.txt # use latest content only of d.txt 177$ git commit -a # use latest content of all tracked files 178----------------------------------------------- 179 180Merging 181------- 182 183----------------------------------------------- 184$ git merge test # merge branch "test" into the current branch 185$ git pull git://example.com/project.git master 186 # fetch and merge in remote branch 187$ git pull . test # equivalent to git merge test 188----------------------------------------------- 189 190Sharing your changes 191-------------------- 192 193Importing or exporting patches: 194 195----------------------------------------------- 196$ git format-patch origin..HEAD # format a patch for each commit 197 # in HEAD but not in origin 198$ git am mbox # import patches from the mailbox "mbox" 199----------------------------------------------- 200 201Fetch a branch in a different git repository, then merge into the 202current branch: 203 204----------------------------------------------- 205$ git pull git://example.com/project.git theirbranch 206----------------------------------------------- 207 208Store the fetched branch into a local branch before merging into the 209current branch: 210 211----------------------------------------------- 212$ git pull git://example.com/project.git theirbranch:mybranch 213----------------------------------------------- 214 215After creating commits on a local branch, update the remote 216branch with your commits: 217 218----------------------------------------------- 219$ git push ssh://example.com/project.git mybranch:theirbranch 220----------------------------------------------- 221 222When remote and local branch are both named "test": 223 224----------------------------------------------- 225$ git push ssh://example.com/project.git test 226----------------------------------------------- 227 228Shortcut version for a frequently used remote repository: 229 230----------------------------------------------- 231$ git remote add example ssh://example.com/project.git 232$ git push example test 233----------------------------------------------- 234 235Repository maintenance 236---------------------- 237 238Check for corruption: 239 240----------------------------------------------- 241$ git fsck 242----------------------------------------------- 243 244Recompress, remove unused cruft: 245 246----------------------------------------------- 247$ git gc 248----------------------------------------------- 249 250Repositories and Branches 251========================= 252 253How to get a git repository 254--------------------------- 255 256It will be useful to have a git repository to experiment with as you 257read this manual. 258 259The best way to get one is by using the gitlink:git-clone[1] command 260to download a copy of an existing repository for a project that you 261are interested in. If you don't already have a project in mind, here 262are some interesting examples: 263 264------------------------------------------------ 265 # git itself (approx. 10MB download): 266$ git clone git://git.kernel.org/pub/scm/git/git.git 267 # the linux kernel (approx. 150MB download): 268$ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git 269------------------------------------------------ 270 271The initial clone may be time-consuming for a large project, but you 272will only need to clone once. 273 274The clone command creates a new directory named after the project 275("git" or "linux-2.6" in the examples above). After you cd into this 276directory, you will see that it contains a copy of the project files, 277together with a special top-level directory named ".git", which 278contains all the information about the history of the project. 279 280In most of the following, examples will be taken from one of the two 281repositories above. 282 283How to check out a different version of a project 284------------------------------------------------- 285 286Git is best thought of as a tool for storing the history of a 287collection of files. It stores the history as a compressed 288collection of interrelated snapshots (versions) of the project's 289contents. 290 291A single git repository may contain multiple branches. It keeps track 292of them by keeping a list of <<def_head,heads>> which reference the 293latest version on each branch; the gitlink:git-branch[1] command shows 294you the list of branch heads: 295 296------------------------------------------------ 297$ git branch 298* master 299------------------------------------------------ 300 301A freshly cloned repository contains a single branch head, by default 302named "master", with the working directory initialized to the state of 303the project referred to by that branch head. 304 305Most projects also use <<def_tag,tags>>. Tags, like heads, are 306references into the project's history, and can be listed using the 307gitlink:git-tag[1] command: 308 309------------------------------------------------ 310$ git tag -l 311v2.6.11 312v2.6.11-tree 313v2.6.12 314v2.6.12-rc2 315v2.6.12-rc3 316v2.6.12-rc4 317v2.6.12-rc5 318v2.6.12-rc6 319v2.6.13 320... 321------------------------------------------------ 322 323Tags are expected to always point at the same version of a project, 324while heads are expected to advance as development progresses. 325 326Create a new branch head pointing to one of these versions and check it 327out using gitlink:git-checkout[1]: 328 329------------------------------------------------ 330$ git checkout -b new v2.6.13 331------------------------------------------------ 332 333The working directory then reflects the contents that the project had 334when it was tagged v2.6.13, and gitlink:git-branch[1] shows two 335branches, with an asterisk marking the currently checked-out branch: 336 337------------------------------------------------ 338$ git branch 339 master 340* new 341------------------------------------------------ 342 343If you decide that you'd rather see version 2.6.17, you can modify 344the current branch to point at v2.6.17 instead, with 345 346------------------------------------------------ 347$ git reset --hard v2.6.17 348------------------------------------------------ 349 350Note that if the current branch head was your only reference to a 351particular point in history, then resetting that branch may leave you 352with no way to find the history it used to point to; so use this command 353carefully. 354 355Understanding History: Commits 356------------------------------ 357 358Every change in the history of a project is represented by a commit. 359The gitlink:git-show[1] command shows the most recent commit on the 360current branch: 361 362------------------------------------------------ 363$ git show 364commit 2b5f6dcce5bf94b9b119e9ed8d537098ec61c3d2 365Author: Jamal Hadi Salim <hadi@cyberus.ca> 366Date: Sat Dec 2 22:22:25 2006 -0800 367 368 [XFRM]: Fix aevent structuring to be more complete. 369 370 aevents can not uniquely identify an SA. We break the ABI with this 371 patch, but consensus is that since it is not yet utilized by any 372 (known) application then it is fine (better do it now than later). 373 374 Signed-off-by: Jamal Hadi Salim <hadi@cyberus.ca> 375 Signed-off-by: David S. Miller <davem@davemloft.net> 376 377diff --git a/Documentation/networking/xfrm_sync.txt b/Documentation/networking/xfrm_sync.txt 378index 8be626f..d7aac9d 100644 379--- a/Documentation/networking/xfrm_sync.txt 380+++ b/Documentation/networking/xfrm_sync.txt 381@@ -47,10 +47,13 @@ aevent_id structure looks like: 382 383 struct xfrm_aevent_id { 384 struct xfrm_usersa_id sa_id; 385+ xfrm_address_t saddr; 386 __u32 flags; 387+ __u32 reqid; 388 }; 389... 390------------------------------------------------ 391 392As you can see, a commit shows who made the latest change, what they 393did, and why. 394 395Every commit has a 40-hexdigit id, sometimes called the "object name" or the 396"SHA1 id", shown on the first line of the "git show" output. You can usually 397refer to a commit by a shorter name, such as a tag or a branch name, but this 398longer name can also be useful. Most importantly, it is a globally unique 399name for this commit: so if you tell somebody else the object name (for 400example in email), then you are guaranteed that name will refer to the same 401commit in their repository that it does in yours (assuming their repository 402has that commit at all). Since the object name is computed as a hash over the 403contents of the commit, you are guaranteed that the commit can never change 404without its name also changing. 405 406In fact, in <<git-internals>> we shall see that everything stored in git 407history, including file data and directory contents, is stored in an object 408with a name that is a hash of its contents. 409 410Understanding history: commits, parents, and reachability 411~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 412 413Every commit (except the very first commit in a project) also has a 414parent commit which shows what happened before this commit. 415Following the chain of parents will eventually take you back to the 416beginning of the project. 417 418However, the commits do not form a simple list; git allows lines of 419development to diverge and then reconverge, and the point where two 420lines of development reconverge is called a "merge". The commit 421representing a merge can therefore have more than one parent, with 422each parent representing the most recent commit on one of the lines 423of development leading to that point. 424 425The best way to see how this works is using the gitlink:gitk[1] 426command; running gitk now on a git repository and looking for merge 427commits will help understand how the git organizes history. 428 429In the following, we say that commit X is "reachable" from commit Y 430if commit X is an ancestor of commit Y. Equivalently, you could say 431that Y is a descendent of X, or that there is a chain of parents 432leading from commit Y to commit X. 433 434Understanding history: History diagrams 435~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 436 437We will sometimes represent git history using diagrams like the one 438below. Commits are shown as "o", and the links between them with 439lines drawn with - / and \. Time goes left to right: 440 441 442................................................ 443 o--o--o <-- Branch A 444 / 445 o--o--o <-- master 446 \ 447 o--o--o <-- Branch B 448................................................ 449 450If we need to talk about a particular commit, the character "o" may 451be replaced with another letter or number. 452 453Understanding history: What is a branch? 454~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 455 456When we need to be precise, we will use the word "branch" to mean a line 457of development, and "branch head" (or just "head") to mean a reference 458to the most recent commit on a branch. In the example above, the branch 459head named "A" is a pointer to one particular commit, but we refer to 460the line of three commits leading up to that point as all being part of 461"branch A". 462 463However, when no confusion will result, we often just use the term 464"branch" both for branches and for branch heads. 465 466Manipulating branches 467--------------------- 468 469Creating, deleting, and modifying branches is quick and easy; here's 470a summary of the commands: 471 472git branch:: 473 list all branches 474git branch <branch>:: 475 create a new branch named <branch>, referencing the same 476 point in history as the current branch 477git branch <branch> <start-point>:: 478 create a new branch named <branch>, referencing 479 <start-point>, which may be specified any way you like, 480 including using a branch name or a tag name 481git branch -d <branch>:: 482 delete the branch <branch>; if the branch you are deleting 483 points to a commit which is not reachable from this branch, 484 this command will fail with a warning. 485git branch -D <branch>:: 486 even if the branch points to a commit not reachable 487 from the current branch, you may know that that commit 488 is still reachable from some other branch or tag. In that 489 case it is safe to use this command to force git to delete 490 the branch. 491git checkout <branch>:: 492 make the current branch <branch>, updating the working 493 directory to reflect the version referenced by <branch> 494git checkout -b <new> <start-point>:: 495 create a new branch <new> referencing <start-point>, and 496 check it out. 497 498The special symbol "HEAD" can always be used to refer to the current 499branch. In fact, git uses a file named "HEAD" in the .git directory to 500remember which branch is current: 501 502------------------------------------------------ 503$ cat .git/HEAD 504ref: refs/heads/master 505------------------------------------------------ 506 507Examining an old version without creating a new branch 508------------------------------------------------------ 509 510The git-checkout command normally expects a branch head, but will also 511accept an arbitrary commit; for example, you can check out the commit 512referenced by a tag: 513 514------------------------------------------------ 515$ git checkout v2.6.17 516Note: moving to "v2.6.17" which isn't a local branch 517If you want to create a new branch from this checkout, you may do so 518(now or later) by using -b with the checkout command again. Example: 519 git checkout -b <new_branch_name> 520HEAD is now at 427abfa... Linux v2.6.17 521------------------------------------------------ 522 523The HEAD then refers to the SHA1 of the commit instead of to a branch, 524and git branch shows that you are no longer on a branch: 525 526------------------------------------------------ 527$ cat .git/HEAD 528427abfa28afedffadfca9dd8b067eb6d36bac53f 529git branch 530* (no branch) 531 master 532------------------------------------------------ 533 534In this case we say that the HEAD is "detached". 535 536This can be an easy way to check out a particular version without having 537to make up a name for a new branch. However, keep in mind that when you 538switch away from the (for example, by checking out something else), you 539can lose track of what the HEAD used to point to. 540 541Examining branches from a remote repository 542------------------------------------------- 543 544The "master" branch that was created at the time you cloned is a copy 545of the HEAD in the repository that you cloned from. That repository 546may also have had other branches, though, and your local repository 547keeps branches which track each of those remote branches, which you 548can view using the "-r" option to gitlink:git-branch[1]: 549 550------------------------------------------------ 551$ git branch -r 552 origin/HEAD 553 origin/html 554 origin/maint 555 origin/man 556 origin/master 557 origin/next 558 origin/pu 559 origin/todo 560------------------------------------------------ 561 562You cannot check out these remote-tracking branches, but you can 563examine them on a branch of your own, just as you would a tag: 564 565------------------------------------------------ 566$ git checkout -b my-todo-copy origin/todo 567------------------------------------------------ 568 569Note that the name "origin" is just the name that git uses by default 570to refer to the repository that you cloned from. 571 572[[how-git-stores-references]] 573Naming branches, tags, and other references 574------------------------------------------- 575 576Branches, remote-tracking branches, and tags are all references to 577commits. All references are named with a slash-separated path name 578starting with "refs"; the names we've been using so far are actually 579shorthand: 580 581 - The branch "test" is short for "refs/heads/test". 582 - The tag "v2.6.18" is short for "refs/tags/v2.6.18". 583 - "origin/master" is short for "refs/remotes/origin/master". 584 585The full name is occasionally useful if, for example, there ever 586exists a tag and a branch with the same name. 587 588As another useful shortcut, if the repository "origin" posesses only 589a single branch, you can refer to that branch as just "origin". 590 591More generally, if you have defined a remote repository named 592"example", you can refer to the branch in that repository as 593"example". And for a repository with multiple branches, this will 594refer to the branch designated as the "HEAD" branch. 595 596For the complete list of paths which git checks for references, and 597the order it uses to decide which to choose when there are multiple 598references with the same shorthand name, see the "SPECIFYING 599REVISIONS" section of gitlink:git-rev-parse[1]. 600 601[[Updating-a-repository-with-git-fetch]] 602Updating a repository with git fetch 603------------------------------------ 604 605Eventually the developer cloned from will do additional work in her 606repository, creating new commits and advancing the branches to point 607at the new commits. 608 609The command "git fetch", with no arguments, will update all of the 610remote-tracking branches to the latest version found in her 611repository. It will not touch any of your own branches--not even the 612"master" branch that was created for you on clone. 613 614Fetching branches from other repositories 615----------------------------------------- 616 617You can also track branches from repositories other than the one you 618cloned from, using gitlink:git-remote[1]: 619 620------------------------------------------------- 621$ git remote add linux-nfs git://linux-nfs.org/pub/nfs-2.6.git 622$ git fetch linux-nfs 623* refs/remotes/linux-nfs/master: storing branch 'master' ... 624 commit: bf81b46 625------------------------------------------------- 626 627New remote-tracking branches will be stored under the shorthand name 628that you gave "git remote add", in this case linux-nfs: 629 630------------------------------------------------- 631$ git branch -r 632linux-nfs/master 633origin/master 634------------------------------------------------- 635 636If you run "git fetch <remote>" later, the tracking branches for the 637named <remote> will be updated. 638 639If you examine the file .git/config, you will see that git has added 640a new stanza: 641 642------------------------------------------------- 643$ cat .git/config 644... 645[remote "linux-nfs"] 646 url = git://linux-nfs.org/pub/nfs-2.6.git 647 fetch = +refs/heads/*:refs/remotes/linux-nfs/* 648... 649------------------------------------------------- 650 651This is what causes git to track the remote's branches; you may modify 652or delete these configuration options by editing .git/config with a 653text editor. (See the "CONFIGURATION FILE" section of 654gitlink:git-config[1] for details.) 655 656Exploring git history 657===================== 658 659Git is best thought of as a tool for storing the history of a 660collection of files. It does this by storing compressed snapshots of 661the contents of a file heirarchy, together with "commits" which show 662the relationships between these snapshots. 663 664Git provides extremely flexible and fast tools for exploring the 665history of a project. 666 667We start with one specialized tool that is useful for finding the 668commit that introduced a bug into a project. 669 670How to use bisect to find a regression 671-------------------------------------- 672 673Suppose version 2.6.18 of your project worked, but the version at 674"master" crashes. Sometimes the best way to find the cause of such a 675regression is to perform a brute-force search through the project's 676history to find the particular commit that caused the problem. The 677gitlink:git-bisect[1] command can help you do this: 678 679------------------------------------------------- 680$ git bisect start 681$ git bisect good v2.6.18 682$ git bisect bad master 683Bisecting: 3537 revisions left to test after this 684[65934a9a028b88e83e2b0f8b36618fe503349f8e] BLOCK: Make USB storage depend on SCSI rather than selecting it [try #6] 685------------------------------------------------- 686 687If you run "git branch" at this point, you'll see that git has 688temporarily moved you to a new branch named "bisect". This branch 689points to a commit (with commit id 65934...) that is reachable from 690v2.6.19 but not from v2.6.18. Compile and test it, and see whether 691it crashes. Assume it does crash. Then: 692 693------------------------------------------------- 694$ git bisect bad 695Bisecting: 1769 revisions left to test after this 696[7eff82c8b1511017ae605f0c99ac275a7e21b867] i2c-core: Drop useless bitmaskings 697------------------------------------------------- 698 699checks out an older version. Continue like this, telling git at each 700stage whether the version it gives you is good or bad, and notice 701that the number of revisions left to test is cut approximately in 702half each time. 703 704After about 13 tests (in this case), it will output the commit id of 705the guilty commit. You can then examine the commit with 706gitlink:git-show[1], find out who wrote it, and mail them your bug 707report with the commit id. Finally, run 708 709------------------------------------------------- 710$ git bisect reset 711------------------------------------------------- 712 713to return you to the branch you were on before and delete the 714temporary "bisect" branch. 715 716Note that the version which git-bisect checks out for you at each 717point is just a suggestion, and you're free to try a different 718version if you think it would be a good idea. For example, 719occasionally you may land on a commit that broke something unrelated; 720run 721 722------------------------------------------------- 723$ git bisect visualize 724------------------------------------------------- 725 726which will run gitk and label the commit it chose with a marker that 727says "bisect". Chose a safe-looking commit nearby, note its commit 728id, and check it out with: 729 730------------------------------------------------- 731$ git reset --hard fb47ddb2db... 732------------------------------------------------- 733 734then test, run "bisect good" or "bisect bad" as appropriate, and 735continue. 736 737Naming commits 738-------------- 739 740We have seen several ways of naming commits already: 741 742 - 40-hexdigit object name 743 - branch name: refers to the commit at the head of the given 744 branch 745 - tag name: refers to the commit pointed to by the given tag 746 (we've seen branches and tags are special cases of 747 <<how-git-stores-references,references>>). 748 - HEAD: refers to the head of the current branch 749 750There are many more; see the "SPECIFYING REVISIONS" section of the 751gitlink:git-rev-parse[1] man page for the complete list of ways to 752name revisions. Some examples: 753 754------------------------------------------------- 755$ git show fb47ddb2 # the first few characters of the object name 756 # are usually enough to specify it uniquely 757$ git show HEAD^ # the parent of the HEAD commit 758$ git show HEAD^^ # the grandparent 759$ git show HEAD~4 # the great-great-grandparent 760------------------------------------------------- 761 762Recall that merge commits may have more than one parent; by default, 763^ and ~ follow the first parent listed in the commit, but you can 764also choose: 765 766------------------------------------------------- 767$ git show HEAD^1 # show the first parent of HEAD 768$ git show HEAD^2 # show the second parent of HEAD 769------------------------------------------------- 770 771In addition to HEAD, there are several other special names for 772commits: 773 774Merges (to be discussed later), as well as operations such as 775git-reset, which change the currently checked-out commit, generally 776set ORIG_HEAD to the value HEAD had before the current operation. 777 778The git-fetch operation always stores the head of the last fetched 779branch in FETCH_HEAD. For example, if you run git fetch without 780specifying a local branch as the target of the operation 781 782------------------------------------------------- 783$ git fetch git://example.com/proj.git theirbranch 784------------------------------------------------- 785 786the fetched commits will still be available from FETCH_HEAD. 787 788When we discuss merges we'll also see the special name MERGE_HEAD, 789which refers to the other branch that we're merging in to the current 790branch. 791 792The gitlink:git-rev-parse[1] command is a low-level command that is 793occasionally useful for translating some name for a commit to the object 794name for that commit: 795 796------------------------------------------------- 797$ git rev-parse origin 798e05db0fd4f31dde7005f075a84f96b360d05984b 799------------------------------------------------- 800 801Creating tags 802------------- 803 804We can also create a tag to refer to a particular commit; after 805running 806 807------------------------------------------------- 808$ git tag stable-1 1b2e1d63ff 809------------------------------------------------- 810 811You can use stable-1 to refer to the commit 1b2e1d63ff. 812 813This creates a "lightweight" tag. If the tag is a tag you wish to 814share with others, and possibly sign cryptographically, then you 815should create a tag object instead; see the gitlink:git-tag[1] man 816page for details. 817 818Browsing revisions 819------------------ 820 821The gitlink:git-log[1] command can show lists of commits. On its 822own, it shows all commits reachable from the parent commit; but you 823can also make more specific requests: 824 825------------------------------------------------- 826$ git log v2.5.. # commits since (not reachable from) v2.5 827$ git log test..master # commits reachable from master but not test 828$ git log master..test # ...reachable from test but not master 829$ git log master...test # ...reachable from either test or master, 830 # but not both 831$ git log --since="2 weeks ago" # commits from the last 2 weeks 832$ git log Makefile # commits which modify Makefile 833$ git log fs/ # ... which modify any file under fs/ 834$ git log -S'foo()' # commits which add or remove any file data 835 # matching the string 'foo()' 836------------------------------------------------- 837 838And of course you can combine all of these; the following finds 839commits since v2.5 which touch the Makefile or any file under fs: 840 841------------------------------------------------- 842$ git log v2.5.. Makefile fs/ 843------------------------------------------------- 844 845You can also ask git log to show patches: 846 847------------------------------------------------- 848$ git log -p 849------------------------------------------------- 850 851See the "--pretty" option in the gitlink:git-log[1] man page for more 852display options. 853 854Note that git log starts with the most recent commit and works 855backwards through the parents; however, since git history can contain 856multiple independent lines of development, the particular order that 857commits are listed in may be somewhat arbitrary. 858 859Generating diffs 860---------------- 861 862You can generate diffs between any two versions using 863gitlink:git-diff[1]: 864 865------------------------------------------------- 866$ git diff master..test 867------------------------------------------------- 868 869Sometimes what you want instead is a set of patches: 870 871------------------------------------------------- 872$ git format-patch master..test 873------------------------------------------------- 874 875will generate a file with a patch for each commit reachable from test 876but not from master. Note that if master also has commits which are 877not reachable from test, then the combined result of these patches 878will not be the same as the diff produced by the git-diff example. 879 880Viewing old file versions 881------------------------- 882 883You can always view an old version of a file by just checking out the 884correct revision first. But sometimes it is more convenient to be 885able to view an old version of a single file without checking 886anything out; this command does that: 887 888------------------------------------------------- 889$ git show v2.5:fs/locks.c 890------------------------------------------------- 891 892Before the colon may be anything that names a commit, and after it 893may be any path to a file tracked by git. 894 895Examples 896-------- 897 898Check whether two branches point at the same history 899~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 900 901Suppose you want to check whether two branches point at the same point 902in history. 903 904------------------------------------------------- 905$ git diff origin..master 906------------------------------------------------- 907 908will tell you whether the contents of the project are the same at the 909two branches; in theory, however, it's possible that the same project 910contents could have been arrived at by two different historical 911routes. You could compare the object names: 912 913------------------------------------------------- 914$ git rev-list origin 915e05db0fd4f31dde7005f075a84f96b360d05984b 916$ git rev-list master 917e05db0fd4f31dde7005f075a84f96b360d05984b 918------------------------------------------------- 919 920Or you could recall that the ... operator selects all commits 921contained reachable from either one reference or the other but not 922both: so 923 924------------------------------------------------- 925$ git log origin...master 926------------------------------------------------- 927 928will return no commits when the two branches are equal. 929 930Find first tagged version including a given fix 931~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 932 933Suppose you know that the commit e05db0fd fixed a certain problem. 934You'd like to find the earliest tagged release that contains that 935fix. 936 937Of course, there may be more than one answer--if the history branched 938after commit e05db0fd, then there could be multiple "earliest" tagged 939releases. 940 941You could just visually inspect the commits since e05db0fd: 942 943------------------------------------------------- 944$ gitk e05db0fd.. 945------------------------------------------------- 946 947Or you can use gitlink:git-name-rev[1], which will give the commit a 948name based on any tag it finds pointing to one of the commit's 949descendants: 950 951------------------------------------------------- 952$ git name-rev --tags e05db0fd 953e05db0fd tags/v1.5.0-rc1^0~23 954------------------------------------------------- 955 956The gitlink:git-describe[1] command does the opposite, naming the 957revision using a tag on which the given commit is based: 958 959------------------------------------------------- 960$ git describe e05db0fd 961v1.5.0-rc0-260-ge05db0f 962------------------------------------------------- 963 964but that may sometimes help you guess which tags might come after the 965given commit. 966 967If you just want to verify whether a given tagged version contains a 968given commit, you could use gitlink:git-merge-base[1]: 969 970------------------------------------------------- 971$ git merge-base e05db0fd v1.5.0-rc1 972e05db0fd4f31dde7005f075a84f96b360d05984b 973------------------------------------------------- 974 975The merge-base command finds a common ancestor of the given commits, 976and always returns one or the other in the case where one is a 977descendant of the other; so the above output shows that e05db0fd 978actually is an ancestor of v1.5.0-rc1. 979 980Alternatively, note that 981 982------------------------------------------------- 983$ git log v1.5.0-rc1..e05db0fd 984------------------------------------------------- 985 986will produce empty output if and only if v1.5.0-rc1 includes e05db0fd, 987because it outputs only commits that are not reachable from v1.5.0-rc1. 988 989As yet another alternative, the gitlink:git-show-branch[1] command lists 990the commits reachable from its arguments with a display on the left-hand 991side that indicates which arguments that commit is reachable from. So, 992you can run something like 993 994------------------------------------------------- 995$ git show-branch e05db0fd v1.5.0-rc0 v1.5.0-rc1 v1.5.0-rc2 996! [e05db0fd] Fix warnings in sha1_file.c - use C99 printf format if 997available 998 ! [v1.5.0-rc0] GIT v1.5.0 preview 999 ! [v1.5.0-rc1] GIT v1.5.0-rc11000 ! [v1.5.0-rc2] GIT v1.5.0-rc21001...1002-------------------------------------------------10031004then search for a line that looks like10051006-------------------------------------------------1007+ ++ [e05db0fd] Fix warnings in sha1_file.c - use C99 printf format if1008available1009-------------------------------------------------10101011Which shows that e05db0fd is reachable from itself, from v1.5.0-rc1, and1012from v1.5.0-rc2, but not from v1.5.0-rc0.101310141015Developing with git1016===================10171018Telling git your name1019---------------------10201021Before creating any commits, you should introduce yourself to git. The1022easiest way to do so is:10231024------------------------------------------------1025$ cat >~/.gitconfig <<\EOF1026[user]1027 name = Your Name Comes Here1028 email = you@yourdomain.example.com1029EOF1030------------------------------------------------10311032(See the "CONFIGURATION FILE" section of gitlink:git-config[1] for1033details on the configuration file.)103410351036Creating a new repository1037-------------------------10381039Creating a new repository from scratch is very easy:10401041-------------------------------------------------1042$ mkdir project1043$ cd project1044$ git init1045-------------------------------------------------10461047If you have some initial content (say, a tarball):10481049-------------------------------------------------1050$ tar -xzvf project.tar.gz1051$ cd project1052$ git init1053$ git add . # include everything below ./ in the first commit:1054$ git commit1055-------------------------------------------------10561057[[how-to-make-a-commit]]1058How to make a commit1059--------------------10601061Creating a new commit takes three steps:10621063 1. Making some changes to the working directory using your1064 favorite editor.1065 2. Telling git about your changes.1066 3. Creating the commit using the content you told git about1067 in step 2.10681069In practice, you can interleave and repeat steps 1 and 2 as many1070times as you want: in order to keep track of what you want committed1071at step 3, git maintains a snapshot of the tree's contents in a1072special staging area called "the index."10731074At the beginning, the content of the index will be identical to1075that of the HEAD. The command "git diff --cached", which shows1076the difference between the HEAD and the index, should therefore1077produce no output at that point.10781079Modifying the index is easy:10801081To update the index with the new contents of a modified file, use10821083-------------------------------------------------1084$ git add path/to/file1085-------------------------------------------------10861087To add the contents of a new file to the index, use10881089-------------------------------------------------1090$ git add path/to/file1091-------------------------------------------------10921093To remove a file from the index and from the working tree,10941095-------------------------------------------------1096$ git rm path/to/file1097-------------------------------------------------10981099After each step you can verify that11001101-------------------------------------------------1102$ git diff --cached1103-------------------------------------------------11041105always shows the difference between the HEAD and the index file--this1106is what you'd commit if you created the commit now--and that11071108-------------------------------------------------1109$ git diff1110-------------------------------------------------11111112shows the difference between the working tree and the index file.11131114Note that "git add" always adds just the current contents of a file1115to the index; further changes to the same file will be ignored unless1116you run git-add on the file again.11171118When you're ready, just run11191120-------------------------------------------------1121$ git commit1122-------------------------------------------------11231124and git will prompt you for a commit message and then create the new1125commit. Check to make sure it looks like what you expected with11261127-------------------------------------------------1128$ git show1129-------------------------------------------------11301131As a special shortcut,11321133-------------------------------------------------1134$ git commit -a1135-------------------------------------------------11361137will update the index with any files that you've modified or removed1138and create a commit, all in one step.11391140A number of commands are useful for keeping track of what you're1141about to commit:11421143-------------------------------------------------1144$ git diff --cached # difference between HEAD and the index; what1145 # would be commited if you ran "commit" now.1146$ git diff # difference between the index file and your1147 # working directory; changes that would not1148 # be included if you ran "commit" now.1149$ git status # a brief per-file summary of the above.1150-------------------------------------------------11511152Creating good commit messages1153-----------------------------11541155Though not required, it's a good idea to begin the commit message1156with a single short (less than 50 character) line summarizing the1157change, followed by a blank line and then a more thorough1158description. Tools that turn commits into email, for example, use1159the first line on the Subject line and the rest of the commit in the1160body.11611162How to merge1163------------11641165You can rejoin two diverging branches of development using1166gitlink:git-merge[1]:11671168-------------------------------------------------1169$ git merge branchname1170-------------------------------------------------11711172merges the development in the branch "branchname" into the current1173branch. If there are conflicts--for example, if the same file is1174modified in two different ways in the remote branch and the local1175branch--then you are warned; the output may look something like this:11761177-------------------------------------------------1178$ git merge next1179 100% (4/4) done1180Auto-merged file.txt1181CONFLICT (content): Merge conflict in file.txt1182Automatic merge failed; fix conflicts and then commit the result.1183-------------------------------------------------11841185Conflict markers are left in the problematic files, and after1186you resolve the conflicts manually, you can update the index1187with the contents and run git commit, as you normally would when1188creating a new file.11891190If you examine the resulting commit using gitk, you will see that it1191has two parents, one pointing to the top of the current branch, and1192one to the top of the other branch.11931194In more detail:11951196[[resolving-a-merge]]1197Resolving a merge1198-----------------11991200When a merge isn't resolved automatically, git leaves the index and1201the working tree in a special state that gives you all the1202information you need to help resolve the merge.12031204Files with conflicts are marked specially in the index, so until you1205resolve the problem and update the index, gitlink:git-commit[1] will1206fail:12071208-------------------------------------------------1209$ git commit1210file.txt: needs merge1211-------------------------------------------------12121213Also, gitlink:git-status[1] will list those files as "unmerged", and the1214files with conflicts will have conflict markers added, like this:12151216-------------------------------------------------1217<<<<<<< HEAD:file.txt1218Hello world1219=======1220Goodbye1221>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt1222-------------------------------------------------12231224All you need to do is edit the files to resolve the conflicts, and then12251226-------------------------------------------------1227$ git add file.txt1228$ git commit1229-------------------------------------------------12301231Note that the commit message will already be filled in for you with1232some information about the merge. Normally you can just use this1233default message unchanged, but you may add additional commentary of1234your own if desired.12351236The above is all you need to know to resolve a simple merge. But git1237also provides more information to help resolve conflicts:12381239Getting conflict-resolution help during a merge1240~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~12411242All of the changes that git was able to merge automatically are1243already added to the index file, so gitlink:git-diff[1] shows only1244the conflicts. It uses an unusual syntax:12451246-------------------------------------------------1247$ git diff1248diff --cc file.txt1249index 802992c,2b60207..00000001250--- a/file.txt1251+++ b/file.txt1252@@@ -1,1 -1,1 +1,5 @@@1253++<<<<<<< HEAD:file.txt1254 +Hello world1255++=======1256+ Goodbye1257++>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt1258-------------------------------------------------12591260Recall that the commit which will be commited after we resolve this1261conflict will have two parents instead of the usual one: one parent1262will be HEAD, the tip of the current branch; the other will be the1263tip of the other branch, which is stored temporarily in MERGE_HEAD.12641265During the merge, the index holds three versions of each file. Each of1266these three "file stages" represents a different version of the file:12671268-------------------------------------------------1269$ git show :1:file.txt # the file in a common ancestor of both branches1270$ git show :2:file.txt # the version from HEAD, but including any1271 # nonconflicting changes from MERGE_HEAD1272$ git show :3:file.txt # the version from MERGE_HEAD, but including any1273 # nonconflicting changes from HEAD.1274-------------------------------------------------12751276Since the stage 2 and stage 3 versions have already been updated with1277nonconflicting changes, the only remaining differences between them are1278the important ones; thus gitlink:git-diff[1] can use the information in1279the index to show only those conflicts.12801281The diff above shows the differences between the working-tree version of1282file.txt and the stage 2 and stage 3 versions. So instead of preceding1283each line by a single "+" or "-", it now uses two columns: the first1284column is used for differences between the first parent and the working1285directory copy, and the second for differences between the second parent1286and the working directory copy. (See the "COMBINED DIFF FORMAT" section1287of gitlink:git-diff-files[1] for a details of the format.)12881289After resolving the conflict in the obvious way (but before updating the1290index), the diff will look like:12911292-------------------------------------------------1293$ git diff1294diff --cc file.txt1295index 802992c,2b60207..00000001296--- a/file.txt1297+++ b/file.txt1298@@@ -1,1 -1,1 +1,1 @@@1299- Hello world1300 -Goodbye1301++Goodbye world1302-------------------------------------------------13031304This shows that our resolved version deleted "Hello world" from the1305first parent, deleted "Goodbye" from the second parent, and added1306"Goodbye world", which was previously absent from both.13071308Some special diff options allow diffing the working directory against1309any of these stages:13101311-------------------------------------------------1312$ git diff -1 file.txt # diff against stage 11313$ git diff --base file.txt # same as the above1314$ git diff -2 file.txt # diff against stage 21315$ git diff --ours file.txt # same as the above1316$ git diff -3 file.txt # diff against stage 31317$ git diff --theirs file.txt # same as the above.1318-------------------------------------------------13191320The gitlink:git-log[1] and gitk[1] commands also provide special help1321for merges:13221323-------------------------------------------------1324$ git log --merge1325$ gitk --merge1326-------------------------------------------------13271328These will display all commits which exist only on HEAD or on1329MERGE_HEAD, and which touch an unmerged file.13301331Each time you resolve the conflicts in a file and update the index:13321333-------------------------------------------------1334$ git add file.txt1335-------------------------------------------------13361337the different stages of that file will be "collapsed", after which1338git-diff will (by default) no longer show diffs for that file.13391340[[undoing-a-merge]]1341Undoing a merge1342---------------13431344If you get stuck and decide to just give up and throw the whole mess1345away, you can always return to the pre-merge state with13461347-------------------------------------------------1348$ git reset --hard HEAD1349-------------------------------------------------13501351Or, if you've already commited the merge that you want to throw away,13521353-------------------------------------------------1354$ git reset --hard ORIG_HEAD1355-------------------------------------------------13561357However, this last command can be dangerous in some cases--never1358throw away a commit you have already committed if that commit may1359itself have been merged into another branch, as doing so may confuse1360further merges.13611362Fast-forward merges1363-------------------13641365There is one special case not mentioned above, which is treated1366differently. Normally, a merge results in a merge commit, with two1367parents, one pointing at each of the two lines of development that1368were merged.13691370However, if one of the two lines of development is completely1371contained within the other--so every commit present in the one is1372already contained in the other--then git just performs a1373<<fast-forwards,fast forward>>; the head of the current branch is1374moved forward to point at the head of the merged-in branch, without1375any new commits being created.13761377Fixing mistakes1378---------------13791380If you've messed up the working tree, but haven't yet committed your1381mistake, you can return the entire working tree to the last committed1382state with13831384-------------------------------------------------1385$ git reset --hard HEAD1386-------------------------------------------------13871388If you make a commit that you later wish you hadn't, there are two1389fundamentally different ways to fix the problem:13901391 1. You can create a new commit that undoes whatever was done1392 by the previous commit. This is the correct thing if your1393 mistake has already been made public.13941395 2. You can go back and modify the old commit. You should1396 never do this if you have already made the history public;1397 git does not normally expect the "history" of a project to1398 change, and cannot correctly perform repeated merges from1399 a branch that has had its history changed.14001401Fixing a mistake with a new commit1402~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~14031404Creating a new commit that reverts an earlier change is very easy;1405just pass the gitlink:git-revert[1] command a reference to the bad1406commit; for example, to revert the most recent commit:14071408-------------------------------------------------1409$ git revert HEAD1410-------------------------------------------------14111412This will create a new commit which undoes the change in HEAD. You1413will be given a chance to edit the commit message for the new commit.14141415You can also revert an earlier change, for example, the next-to-last:14161417-------------------------------------------------1418$ git revert HEAD^1419-------------------------------------------------14201421In this case git will attempt to undo the old change while leaving1422intact any changes made since then. If more recent changes overlap1423with the changes to be reverted, then you will be asked to fix1424conflicts manually, just as in the case of <<resolving-a-merge,1425resolving a merge>>.14261427[[fixing-a-mistake-by-editing-history]]1428Fixing a mistake by editing history1429~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~14301431If the problematic commit is the most recent commit, and you have not1432yet made that commit public, then you may just1433<<undoing-a-merge,destroy it using git-reset>>.14341435Alternatively, you1436can edit the working directory and update the index to fix your1437mistake, just as if you were going to <<how-to-make-a-commit,create a1438new commit>>, then run14391440-------------------------------------------------1441$ git commit --amend1442-------------------------------------------------14431444which will replace the old commit by a new commit incorporating your1445changes, giving you a chance to edit the old commit message first.14461447Again, you should never do this to a commit that may already have1448been merged into another branch; use gitlink:git-revert[1] instead in1449that case.14501451It is also possible to edit commits further back in the history, but1452this is an advanced topic to be left for1453<<cleaning-up-history,another chapter>>.14541455Checking out an old version of a file1456~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~14571458In the process of undoing a previous bad change, you may find it1459useful to check out an older version of a particular file using1460gitlink:git-checkout[1]. We've used git checkout before to switch1461branches, but it has quite different behavior if it is given a path1462name: the command14631464-------------------------------------------------1465$ git checkout HEAD^ path/to/file1466-------------------------------------------------14671468replaces path/to/file by the contents it had in the commit HEAD^, and1469also updates the index to match. It does not change branches.14701471If you just want to look at an old version of the file, without1472modifying the working directory, you can do that with1473gitlink:git-show[1]:14741475-------------------------------------------------1476$ git show HEAD^:path/to/file1477-------------------------------------------------14781479which will display the given version of the file.14801481Ensuring good performance1482-------------------------14831484On large repositories, git depends on compression to keep the history1485information from taking up to much space on disk or in memory.14861487This compression is not performed automatically. Therefore you1488should occasionally run gitlink:git-gc[1]:14891490-------------------------------------------------1491$ git gc1492-------------------------------------------------14931494to recompress the archive. This can be very time-consuming, so1495you may prefer to run git-gc when you are not doing other work.14961497Ensuring reliability1498--------------------14991500Checking the repository for corruption1501~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~15021503The gitlink:git-fsck[1] command runs a number of self-consistency checks1504on the repository, and reports on any problems. This may take some1505time. The most common warning by far is about "dangling" objects:15061507-------------------------------------------------1508$ git fsck1509dangling commit 7281251ddd2a61e38657c827739c57015671a6b31510dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a631511dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b51512dangling blob 218761f9d90712d37a9c5e36f406f92202db07eb1513dangling commit bf093535a34a4d35731aa2bd90fe6b176302f14f1514dangling commit 8e4bec7f2ddaa268bef999853c25755452100f8e1515dangling tree d50bb86186bf27b681d25af89d3b5b68382e40851516dangling tree b24c2473f1fd3d91352a624795be026d64c8841f1517...1518-------------------------------------------------15191520Dangling objects are objects that are harmless, but also unnecessary;1521you can remove them at any time with gitlink:git-prune[1] or the --prune1522option to gitlink:git-gc[1]:15231524-------------------------------------------------1525$ git gc --prune1526-------------------------------------------------15271528This may be time-consuming. Unlike most other git operations (including1529git-gc when run without any options), it is not safe to prune while1530other git operations are in progress in the same repository.15311532For more about dangling objects, see <<dangling-objects>>.153315341535Recovering lost changes1536~~~~~~~~~~~~~~~~~~~~~~~15371538Reflogs1539^^^^^^^15401541Say you modify a branch with gitlink:git-reset[1] --hard, and then1542realize that the branch was the only reference you had to that point in1543history.15441545Fortunately, git also keeps a log, called a "reflog", of all the1546previous values of each branch. So in this case you can still find the1547old history using, for example, 15481549-------------------------------------------------1550$ git log master@{1}1551-------------------------------------------------15521553This lists the commits reachable from the previous version of the head.1554This syntax can be used to with any git command that accepts a commit,1555not just with git log. Some other examples:15561557-------------------------------------------------1558$ git show master@{2} # See where the branch pointed 2,1559$ git show master@{3} # 3, ... changes ago.1560$ gitk master@{yesterday} # See where it pointed yesterday,1561$ gitk master@{"1 week ago"} # ... or last week1562-------------------------------------------------15631564The reflogs are kept by default for 30 days, after which they may be1565pruned. See gitlink:git-reflog[1] and gitlink:git-gc[1] to learn1566how to control this pruning, and see the "SPECIFYING REVISIONS"1567section of gitlink:git-rev-parse[1] for details.15681569Note that the reflog history is very different from normal git history.1570While normal history is shared by every repository that works on the1571same project, the reflog history is not shared: it tells you only about1572how the branches in your local repository have changed over time.15731574Examining dangling objects1575^^^^^^^^^^^^^^^^^^^^^^^^^^15761577In some situations the reflog may not be able to save you. For1578example, suppose you delete a branch, then realize you need the history1579it contained. The reflog is also deleted; however, if you have not1580yet pruned the repository, then you may still be able to find1581the lost commits; run git-fsck and watch for output that mentions1582"dangling commits":15831584-------------------------------------------------1585$ git fsck1586dangling commit 7281251ddd2a61e38657c827739c57015671a6b31587dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a631588dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b51589...1590-------------------------------------------------15911592You can examine1593one of those dangling commits with, for example,15941595------------------------------------------------1596$ gitk 7281251ddd --not --all1597------------------------------------------------15981599which does what it sounds like: it says that you want to see the commit1600history that is described by the dangling commit(s), but not the1601history that is described by all your existing branches and tags. Thus1602you get exactly the history reachable from that commit that is lost.1603(And notice that it might not be just one commit: we only report the1604"tip of the line" as being dangling, but there might be a whole deep1605and complex commit history that was dropped.)16061607If you decide you want the history back, you can always create a new1608reference pointing to it, for example, a new branch:16091610------------------------------------------------1611$ git branch recovered-branch 7281251ddd 1612------------------------------------------------161316141615Sharing development with others1616===============================16171618[[getting-updates-with-git-pull]]1619Getting updates with git pull1620-----------------------------16211622After you clone a repository and make a few changes of your own, you1623may wish to check the original repository for updates and merge them1624into your own work.16251626We have already seen <<Updating-a-repository-with-git-fetch,how to1627keep remote tracking branches up to date>> with gitlink:git-fetch[1],1628and how to merge two branches. So you can merge in changes from the1629original repository's master branch with:16301631-------------------------------------------------1632$ git fetch1633$ git merge origin/master1634-------------------------------------------------16351636However, the gitlink:git-pull[1] command provides a way to do this in1637one step:16381639-------------------------------------------------1640$ git pull origin master1641-------------------------------------------------16421643In 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 just16461647-------------------------------------------------1648$ git pull1649-------------------------------------------------16501651See the descriptions of the branch.<name>.remote and1652branch.<name>.merge options in gitlink:git-config[1] to learn1653how to control these defaults depending on the current branch.16541655In addition to saving you keystrokes, "git pull" also helps you by1656producing a default commit message documenting the branch and1657repository that you pulled from.16581659(But note that no such commit will be created in the case of a1660<<fast-forwards,fast forward>>; instead, your branch will just be1661updated to point to the latest commit from the upstream branch.)16621663The git-pull command can also be given "." as the "remote" repository,1664in which case it just merges in a branch from the current repository; so1665the commands16661667-------------------------------------------------1668$ git pull . branch1669$ git merge branch1670-------------------------------------------------16711672are roughly equivalent. The former is actually very commonly used.16731674Submitting patches to a project1675-------------------------------16761677If you just have a few changes, the simplest way to submit them may1678just be to send them as patches in email:16791680First, use gitlink:git-format-patch[1]; for example:16811682-------------------------------------------------1683$ git format-patch origin1684-------------------------------------------------16851686will produce a numbered series of files in the current directory, one1687for each patch in the current branch but not in origin/HEAD.16881689You can then import these into your mail client and send them by1690hand. However, if you have a lot to send at once, you may prefer to1691use the gitlink:git-send-email[1] script to automate the process.1692Consult the mailing list for your project first to determine how they1693prefer such patches be handled.16941695Importing patches to a project1696------------------------------16971698Git also provides a tool called gitlink:git-am[1] (am stands for1699"apply mailbox"), for importing such an emailed series of patches.1700Just save all of the patch-containing messages, in order, into a1701single mailbox file, say "patches.mbox", then run17021703-------------------------------------------------1704$ git am -3 patches.mbox1705-------------------------------------------------17061707Git will apply each patch in order; if any conflicts are found, it1708will stop, and you can fix the conflicts as described in1709"<<resolving-a-merge,Resolving a merge>>". (The "-3" option tells1710git to perform a merge; if you would prefer it just to abort and1711leave your tree and index untouched, you may omit that option.)17121713Once the index is updated with the results of the conflict1714resolution, instead of creating a new commit, just run17151716-------------------------------------------------1717$ git am --resolved1718-------------------------------------------------17191720and git will create the commit for you and continue applying the1721remaining patches from the mailbox.17221723The final result will be a series of commits, one for each patch in1724the original mailbox, with authorship and commit log message each1725taken from the message containing each patch.17261727[[setting-up-a-public-repository]]1728Setting up a public repository1729------------------------------17301731Another way to submit changes to a project is to simply tell the1732maintainer of that project to pull from your repository, exactly as1733you did in the section "<<getting-updates-with-git-pull, Getting1734updates with git pull>>".17351736If you and maintainer both have accounts on the same machine, then1737then you can just pull changes from each other's repositories1738directly; note that all of the commands (gitlink:git-clone[1],1739git-fetch[1], git-pull[1], etc.) that accept a URL as an argument1740will also accept a local directory name; so, for example, you can1741use17421743-------------------------------------------------1744$ git clone /path/to/repository1745$ git pull /path/to/other/repository1746-------------------------------------------------17471748If this sort of setup is inconvenient or impossible, another (more1749common) option is to set up a public repository on a public server.1750This also allows you to cleanly separate private work in progress1751from publicly visible work.17521753You will continue to do your day-to-day work in your personal1754repository, but periodically "push" changes from your personal1755repository into your public repository, allowing other developers to1756pull from that repository. So the flow of changes, in a situation1757where there is one other developer with a public repository, looks1758like this:17591760 you push1761 your personal repo ------------------> your public repo1762 ^ |1763 | |1764 | you pull | they pull1765 | |1766 | |1767 | they push V1768 their public repo <------------------- their repo17691770Now, assume your personal repository is in the directory ~/proj. We1771first create a new clone of the repository:17721773-------------------------------------------------1774$ git clone --bare proj-clone.git1775-------------------------------------------------17761777The resulting directory proj-clone.git will contains a "bare" git1778repository--it is just the contents of the ".git" directory, without1779a checked-out copy of a working directory.17801781Next, copy proj-clone.git to the server where you plan to host the1782public repository. You can use scp, rsync, or whatever is most1783convenient.17841785If somebody else maintains the public server, they may already have1786set up a git service for you, and you may skip to the section1787"<<pushing-changes-to-a-public-repository,Pushing changes to a public1788repository>>", below.17891790Otherwise, the following sections explain how to export your newly1791created public repository:17921793[[exporting-via-http]]1794Exporting a git repository via http1795-----------------------------------17961797The git protocol gives better performance and reliability, but on a1798host with a web server set up, http exports may be simpler to set up.17991800All you need to do is place the newly created bare git repository in1801a directory that is exported by the web server, and make some1802adjustments to give web clients some extra information they need:18031804-------------------------------------------------1805$ mv proj.git /home/you/public_html/proj.git1806$ cd proj.git1807$ git update-server-info1808$ chmod a+x hooks/post-update1809-------------------------------------------------18101811(For an explanation of the last two lines, see1812gitlink:git-update-server-info[1], and the documentation1813link:hooks.txt[Hooks used by git].)18141815Advertise the url of proj.git. Anybody else should then be able to1816clone or pull from that url, for example with a commandline like:18171818-------------------------------------------------1819$ git clone http://yourserver.com/~you/proj.git1820-------------------------------------------------18211822(See also1823link:howto/setup-git-server-over-http.txt[setup-git-server-over-http]1824for a slightly more sophisticated setup using WebDAV which also1825allows pushing over http.)18261827[[exporting-via-git]]1828Exporting a git repository via the git protocol1829-----------------------------------------------18301831This is the preferred method.18321833For now, we refer you to the gitlink:git-daemon[1] man page for1834instructions. (See especially the examples section.)18351836[[pushing-changes-to-a-public-repository]]1837Pushing changes to a public repository1838--------------------------------------18391840Note that the two techniques outline above (exporting via1841<<exporting-via-http,http>> or <<exporting-via-git,git>>) allow other1842maintainers to fetch your latest changes, but they do not allow write1843access, which you will need to update the public repository with the1844latest changes created in your private repository.18451846The simplest way to do this is using gitlink:git-push[1] and ssh; to1847update the remote branch named "master" with the latest state of your1848branch named "master", run18491850-------------------------------------------------1851$ git push ssh://yourserver.com/~you/proj.git master:master1852-------------------------------------------------18531854or just18551856-------------------------------------------------1857$ git push ssh://yourserver.com/~you/proj.git master1858-------------------------------------------------18591860As with git-fetch, git-push will complain if this does not result in1861a <<fast-forwards,fast forward>>. Normally this is a sign of1862something wrong. However, if you are sure you know what you're1863doing, you may force git-push to perform the update anyway by1864proceeding the branch name by a plus sign:18651866-------------------------------------------------1867$ git push ssh://yourserver.com/~you/proj.git +master1868-------------------------------------------------18691870As with git-fetch, you may also set up configuration options to1871save typing; so, for example, after18721873-------------------------------------------------1874$ cat >.git/config <<EOF1875[remote "public-repo"]1876 url = ssh://yourserver.com/~you/proj.git1877EOF1878-------------------------------------------------18791880you should be able to perform the above push with just18811882-------------------------------------------------1883$ git push public-repo master1884-------------------------------------------------18851886See the explanations of the remote.<name>.url, branch.<name>.remote,1887and remote.<name>.push options in gitlink:git-config[1] for1888details.18891890Setting up a shared repository1891------------------------------18921893Another way to collaborate is by using a model similar to that1894commonly used in CVS, where several developers with special rights1895all push to and pull from a single shared repository. See1896link:cvs-migration.txt[git for CVS users] for instructions on how to1897set this up.18981899Allow web browsing of a repository1900----------------------------------19011902The gitweb cgi script provides users an easy way to browse your1903project's files and history without having to install git; see the file1904gitweb/INSTALL in the git source tree for instructions on setting it up.19051906Examples1907--------19081909TODO: topic branches, typical roles as in everyday.txt, ?191019111912[[cleaning-up-history]]1913Rewriting history and maintaining patch series1914==============================================19151916Normally commits are only added to a project, never taken away or1917replaced. Git is designed with this assumption, and violating it will1918cause git's merge machinery (for example) to do the wrong thing.19191920However, there is a situation in which it can be useful to violate this1921assumption.19221923Creating the perfect patch series1924---------------------------------19251926Suppose you are a contributor to a large project, and you want to add a1927complicated feature, and to present it to the other developers in a way1928that makes it easy for them to read your changes, verify that they are1929correct, and understand why you made each change.19301931If you present all of your changes as a single patch (or commit), they1932may find that it is too much to digest all at once.19331934If you present them with the entire history of your work, complete with1935mistakes, corrections, and dead ends, they may be overwhelmed.19361937So the ideal is usually to produce a series of patches such that:19381939 1. Each patch can be applied in order.19401941 2. Each patch includes a single logical change, together with a1942 message explaining the change.19431944 3. No patch introduces a regression: after applying any initial1945 part of the series, the resulting project still compiles and1946 works, and has no bugs that it didn't have before.19471948 4. The complete series produces the same end result as your own1949 (probably much messier!) development process did.19501951We will introduce some tools that can help you do this, explain how to1952use them, and then explain some of the problems that can arise because1953you are rewriting history.19541955Keeping a patch series up to date using git-rebase1956--------------------------------------------------19571958Suppose that you create a branch "mywork" on a remote-tracking branch1959"origin", and create some commits on top of it:19601961-------------------------------------------------1962$ git checkout -b mywork origin1963$ vi file.txt1964$ git commit1965$ vi otherfile.txt1966$ git commit1967...1968-------------------------------------------------19691970You have performed no merges into mywork, so it is just a simple linear1971sequence of patches on top of "origin":19721973................................................1974 o--o--o <-- origin1975 \1976 o--o--o <-- mywork1977................................................19781979Some more interesting work has been done in the upstream project, and1980"origin" has advanced:19811982................................................1983 o--o--O--o--o--o <-- origin1984 \1985 a--b--c <-- mywork1986................................................19871988At this point, you could use "pull" to merge your changes back in;1989the result would create a new merge commit, like this:19901991................................................1992 o--o--O--o--o--o <-- origin1993 \ \1994 a--b--c--m <-- mywork1995................................................19961997However, if you prefer to keep the history in mywork a simple series of1998commits without any merges, you may instead choose to use1999gitlink:git-rebase[1]:20002001-------------------------------------------------2002$ git checkout mywork2003$ git rebase origin2004-------------------------------------------------20052006This will remove each of your commits from mywork, temporarily saving2007them as patches (in a directory named ".dotest"), update mywork to2008point at the latest version of origin, then apply each of the saved2009patches to the new mywork. The result will look like:201020112012................................................2013 o--o--O--o--o--o <-- origin2014 \2015 a'--b'--c' <-- mywork2016................................................20172018In the process, it may discover conflicts. In that case it will stop2019and allow you to fix the conflicts; after fixing conflicts, use "git2020add" to update the index with those contents, and then, instead of2021running git-commit, just run20222023-------------------------------------------------2024$ git rebase --continue2025-------------------------------------------------20262027and git will continue applying the rest of the patches.20282029At any point you may use the --abort option to abort this process and2030return mywork to the state it had before you started the rebase:20312032-------------------------------------------------2033$ git rebase --abort2034-------------------------------------------------20352036Modifying a single commit2037-------------------------20382039We saw in <<fixing-a-mistake-by-editing-history>> that you can replace the2040most recent commit using20412042-------------------------------------------------2043$ git commit --amend2044-------------------------------------------------20452046which will replace the old commit by a new commit incorporating your2047changes, giving you a chance to edit the old commit message first.20482049You can also use a combination of this and gitlink:git-rebase[1] to edit2050commits further back in your history. First, tag the problematic commit with20512052-------------------------------------------------2053$ git tag bad mywork~52054-------------------------------------------------20552056(Either gitk or git-log may be useful for finding the commit.)20572058Then check out a new branch at that commit, edit it, and rebase the rest of2059the series on top of it:20602061-------------------------------------------------2062$ git checkout -b TMP bad2063$ # make changes here and update the index2064$ git commit --amend2065$ git rebase --onto TMP bad mywork2066-------------------------------------------------20672068When you're done, you'll be left with mywork checked out, with the top patches2069on mywork reapplied on top of the modified commit you created in TMP. You can2070then clean up with20712072-------------------------------------------------2073$ git branch -d TMP2074$ git tag -d bad2075-------------------------------------------------20762077Note that the immutable nature of git history means that you haven't really2078"modified" existing commits; instead, you have replaced the old commits with2079new commits having new object names.20802081Reordering or selecting from a patch series2082-------------------------------------------20832084Given one existing commit, the gitlink:git-cherry-pick[1] command2085allows you to apply the change introduced by that commit and create a2086new commit that records it. So, for example, if "mywork" points to a2087series of patches on top of "origin", you might do something like:20882089-------------------------------------------------2090$ git checkout -b mywork-new origin2091$ gitk origin..mywork &2092-------------------------------------------------20932094And browse through the list of patches in the mywork branch using gitk,2095applying them (possibly in a different order) to mywork-new using2096cherry-pick, and possibly modifying them as you go using commit2097--amend.20982099Another technique is to use git-format-patch to create a series of2100patches, then reset the state to before the patches:21012102-------------------------------------------------2103$ git format-patch origin2104$ git reset --hard origin2105-------------------------------------------------21062107Then modify, reorder, or eliminate patches as preferred before applying2108them again with gitlink:git-am[1].21092110Other tools2111-----------21122113There are numerous other tools, such as stgit, which exist for the2114purpose of maintaining a patch series. These are outside of the scope of2115this manual.21162117Problems with rewriting history2118-------------------------------21192120The primary problem with rewriting the history of a branch has to do2121with merging. Suppose somebody fetches your branch and merges it into2122their branch, with a result something like this:21232124................................................2125 o--o--O--o--o--o <-- origin2126 \ \2127 t--t--t--m <-- their branch:2128................................................21292130Then suppose you modify the last three commits:21312132................................................2133 o--o--o <-- new head of origin2134 /2135 o--o--O--o--o--o <-- old head of origin2136................................................21372138If we examined all this history together in one repository, it will2139look like:21402141................................................2142 o--o--o <-- new head of origin2143 /2144 o--o--O--o--o--o <-- old head of origin2145 \ \2146 t--t--t--m <-- their branch:2147................................................21482149Git has no way of knowing that the new head is an updated version of2150the old head; it treats this situation exactly the same as it would if2151two developers had independently done the work on the old and new heads2152in parallel. At this point, if someone attempts to merge the new head2153in to their branch, git will attempt to merge together the two (old and2154new) lines of development, instead of trying to replace the old by the2155new. The results are likely to be unexpected.21562157You may still choose to publish branches whose history is rewritten,2158and it may be useful for others to be able to fetch those branches in2159order to examine or test them, but they should not attempt to pull such2160branches into their own work.21612162For true distributed development that supports proper merging,2163published branches should never be rewritten.21642165Advanced branch management2166==========================21672168Fetching individual branches2169----------------------------21702171Instead of using gitlink:git-remote[1], you can also choose just2172to update one branch at a time, and to store it locally under an2173arbitrary name:21742175-------------------------------------------------2176$ git fetch origin todo:my-todo-work2177-------------------------------------------------21782179The first argument, "origin", just tells git to fetch from the2180repository you originally cloned from. The second argument tells git2181to fetch the branch named "todo" from the remote repository, and to2182store it locally under the name refs/heads/my-todo-work.21832184You can also fetch branches from other repositories; so21852186-------------------------------------------------2187$ git fetch git://example.com/proj.git master:example-master2188-------------------------------------------------21892190will create a new branch named "example-master" and store in it the2191branch named "master" from the repository at the given URL. If you2192already have a branch named example-master, it will attempt to2193"fast-forward" to the commit given by example.com's master branch. So2194next we explain what a fast-forward is:21952196[[fast-forwards]]2197Understanding git history: fast-forwards2198----------------------------------------21992200In the previous example, when updating an existing branch, "git2201fetch" checks to make sure that the most recent commit on the remote2202branch is a descendant of the most recent commit on your copy of the2203branch before updating your copy of the branch to point at the new2204commit. Git calls this process a "fast forward".22052206A fast forward looks something like this:22072208................................................2209 o--o--o--o <-- old head of the branch2210 \2211 o--o--o <-- new head of the branch2212................................................221322142215In some cases it is possible that the new head will *not* actually be2216a descendant of the old head. For example, the developer may have2217realized she made a serious mistake, and decided to backtrack,2218resulting in a situation like:22192220................................................2221 o--o--o--o--a--b <-- old head of the branch2222 \2223 o--o--o <-- new head of the branch2224................................................22252226In this case, "git fetch" will fail, and print out a warning.22272228In that case, you can still force git to update to the new head, as2229described in the following section. However, note that in the2230situation above this may mean losing the commits labeled "a" and "b",2231unless you've already created a reference of your own pointing to2232them.22332234Forcing git fetch to do non-fast-forward updates2235------------------------------------------------22362237If git fetch fails because the new head of a branch is not a2238descendant of the old head, you may force the update with:22392240-------------------------------------------------2241$ git fetch git://example.com/proj.git +master:refs/remotes/example/master2242-------------------------------------------------22432244Note the addition of the "+" sign. Be aware that commits that the2245old version of example/master pointed at may be lost, as we saw in2246the previous section.22472248Configuring remote branches2249---------------------------22502251We saw above that "origin" is just a shortcut to refer to the2252repository that you originally cloned from. This information is2253stored in git configuration variables, which you can see using2254gitlink:git-config[1]:22552256-------------------------------------------------2257$ git config -l2258core.repositoryformatversion=02259core.filemode=true2260core.logallrefupdates=true2261remote.origin.url=git://git.kernel.org/pub/scm/git/git.git2262remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*2263branch.master.remote=origin2264branch.master.merge=refs/heads/master2265-------------------------------------------------22662267If there are other repositories that you also use frequently, you can2268create similar configuration options to save typing; for example,2269after22702271-------------------------------------------------2272$ git config remote.example.url git://example.com/proj.git2273-------------------------------------------------22742275then the following two commands will do the same thing:22762277-------------------------------------------------2278$ git fetch git://example.com/proj.git master:refs/remotes/example/master2279$ git fetch example master:refs/remotes/example/master2280-------------------------------------------------22812282Even better, if you add one more option:22832284-------------------------------------------------2285$ git config remote.example.fetch master:refs/remotes/example/master2286-------------------------------------------------22872288then the following commands will all do the same thing:22892290-------------------------------------------------2291$ git fetch git://example.com/proj.git master:ref/remotes/example/master2292$ git fetch example master:ref/remotes/example/master2293$ git fetch example example/master2294$ git fetch example2295-------------------------------------------------22962297You can also add a "+" to force the update each time:22982299-------------------------------------------------2300$ git config remote.example.fetch +master:ref/remotes/example/master2301-------------------------------------------------23022303Don't do this unless you're sure you won't mind "git fetch" possibly2304throwing away commits on mybranch.23052306Also note that all of the above configuration can be performed by2307directly editing the file .git/config instead of using2308gitlink:git-config[1].23092310See gitlink:git-config[1] for more details on the configuration2311options mentioned above.231223132314[[git-internals]]2315Git internals2316=============23172318There are two object abstractions: the "object database", and the2319"current directory cache" aka "index".23202321The Object Database2322-------------------23232324The object database is literally just a content-addressable collection2325of objects. All objects are named by their content, which is2326approximated by the SHA1 hash of the object itself. Objects may refer2327to other objects (by referencing their SHA1 hash), and so you can2328build up a hierarchy of objects.23292330All objects have a statically determined "type" aka "tag", which is2331determined at object creation time, and which identifies the format of2332the object (i.e. how it is used, and how it can refer to other2333objects). There are currently four different object types: "blob",2334"tree", "commit" and "tag".23352336A "blob" object cannot refer to any other object, and is, like the type2337implies, a pure storage object containing some user data. It is used to2338actually store the file data, i.e. a blob object is associated with some2339particular version of some file. 23402341A "tree" object is an object that ties one or more "blob" objects into a2342directory structure. In addition, a tree object can refer to other tree2343objects, thus creating a directory hierarchy. 23442345A "commit" object ties such directory hierarchies together into2346a DAG of revisions - each "commit" is associated with exactly one tree2347(the directory hierarchy at the time of the commit). In addition, a2348"commit" refers to one or more "parent" commit objects that describe the2349history of how we arrived at that directory hierarchy.23502351As a special case, a commit object with no parents is called the "root"2352object, and is the point of an initial project commit. Each project2353must have at least one root, and while you can tie several different2354root objects together into one project by creating a commit object which2355has two or more separate roots as its ultimate parents, that's probably2356just going to confuse people. So aim for the notion of "one root object2357per project", even if git itself does not enforce that. 23582359A "tag" object symbolically identifies and can be used to sign other2360objects. It contains the identifier and type of another object, a2361symbolic name (of course!) and, optionally, a signature.23622363Regardless of object type, all objects share the following2364characteristics: they are all deflated with zlib, and have a header2365that not only specifies their type, but also provides size information2366about the data in the object. It's worth noting that the SHA1 hash2367that is used to name the object is the hash of the original data2368plus this header, so `sha1sum` 'file' does not match the object name2369for 'file'.2370(Historical note: in the dawn of the age of git the hash2371was the sha1 of the 'compressed' object.)23722373As a result, the general consistency of an object can always be tested2374independently of the contents or the type of the object: all objects can2375be validated by verifying that (a) their hashes match the content of the2376file and (b) the object successfully inflates to a stream of bytes that2377forms a sequence of <ascii type without space> + <space> + <ascii decimal2378size> + <byte\0> + <binary object data>. 23792380The structured objects can further have their structure and2381connectivity to other objects verified. This is generally done with2382the `git-fsck` program, which generates a full dependency graph2383of all objects, and verifies their internal consistency (in addition2384to just verifying their superficial consistency through the hash).23852386The object types in some more detail:23872388Blob Object2389-----------23902391A "blob" object is nothing but a binary blob of data, and doesn't2392refer to anything else. There is no signature or any other2393verification of the data, so while the object is consistent (it 'is'2394indexed by its sha1 hash, so the data itself is certainly correct), it2395has absolutely no other attributes. No name associations, no2396permissions. It is purely a blob of data (i.e. normally "file2397contents").23982399In particular, since the blob is entirely defined by its data, if two2400files in a directory tree (or in multiple different versions of the2401repository) have the same contents, they will share the same blob2402object. The object is totally independent of its location in the2403directory tree, and renaming a file does not change the object that2404file is associated with in any way.24052406A blob is typically created when gitlink:git-update-index[1]2407is run, and its data can be accessed by gitlink:git-cat-file[1].24082409Tree Object2410-----------24112412The next hierarchical object type is the "tree" object. A tree object2413is a list of mode/name/blob data, sorted by name. Alternatively, the2414mode data may specify a directory mode, in which case instead of2415naming a blob, that name is associated with another TREE object.24162417Like the "blob" object, a tree object is uniquely determined by the2418set contents, and so two separate but identical trees will always2419share the exact same object. This is true at all levels, i.e. it's2420true for a "leaf" tree (which does not refer to any other trees, only2421blobs) as well as for a whole subdirectory.24222423For that reason a "tree" object is just a pure data abstraction: it2424has no history, no signatures, no verification of validity, except2425that since the contents are again protected by the hash itself, we can2426trust that the tree is immutable and its contents never change.24272428So you can trust the contents of a tree to be valid, the same way you2429can trust the contents of a blob, but you don't know where those2430contents 'came' from.24312432Side note on trees: since a "tree" object is a sorted list of2433"filename+content", you can create a diff between two trees without2434actually having to unpack two trees. Just ignore all common parts,2435and your diff will look right. In other words, you can effectively2436(and efficiently) tell the difference between any two random trees by2437O(n) where "n" is the size of the difference, rather than the size of2438the tree.24392440Side note 2 on trees: since the name of a "blob" depends entirely and2441exclusively on its contents (i.e. there are no names or permissions2442involved), you can see trivial renames or permission changes by2443noticing that the blob stayed the same. However, renames with data2444changes need a smarter "diff" implementation.24452446A tree is created with gitlink:git-write-tree[1] and2447its data can be accessed by gitlink:git-ls-tree[1].2448Two trees can be compared with gitlink:git-diff-tree[1].24492450Commit Object2451-------------24522453The "commit" object is an object that introduces the notion of2454history into the picture. In contrast to the other objects, it2455doesn't just describe the physical state of a tree, it describes how2456we got there, and why.24572458A "commit" is defined by the tree-object that it results in, the2459parent commits (zero, one or more) that led up to that point, and a2460comment on what happened. Again, a commit is not trusted per se:2461the contents are well-defined and "safe" due to the cryptographically2462strong signatures at all levels, but there is no reason to believe2463that the tree is "good" or that the merge information makes sense.2464The parents do not have to actually have any relationship with the2465result, for example.24662467Note on commits: unlike real SCM's, commits do not contain2468rename information or file mode change information. All of that is2469implicit in the trees involved (the result tree, and the result trees2470of the parents), and describing that makes no sense in this idiotic2471file manager.24722473A commit is created with gitlink:git-commit-tree[1] and2474its data can be accessed by gitlink:git-cat-file[1].24752476Trust2477-----24782479An aside on the notion of "trust". Trust is really outside the scope2480of "git", but it's worth noting a few things. First off, since2481everything is hashed with SHA1, you 'can' trust that an object is2482intact and has not been messed with by external sources. So the name2483of an object uniquely identifies a known state - just not a state that2484you may want to trust.24852486Furthermore, since the SHA1 signature of a commit refers to the2487SHA1 signatures of the tree it is associated with and the signatures2488of the parent, a single named commit specifies uniquely a whole set2489of history, with full contents. You can't later fake any step of the2490way once you have the name of a commit.24912492So to introduce some real trust in the system, the only thing you need2493to do is to digitally sign just 'one' special note, which includes the2494name of a top-level commit. Your digital signature shows others2495that you trust that commit, and the immutability of the history of2496commits tells others that they can trust the whole history.24972498In other words, you can easily validate a whole archive by just2499sending out a single email that tells the people the name (SHA1 hash)2500of the top commit, and digitally sign that email using something2501like GPG/PGP.25022503To assist in this, git also provides the tag object...25042505Tag Object2506----------25072508Git provides the "tag" object to simplify creating, managing and2509exchanging symbolic and signed tokens. The "tag" object at its2510simplest simply symbolically identifies another object by containing2511the sha1, type and symbolic name.25122513However it can optionally contain additional signature information2514(which git doesn't care about as long as there's less than 8k of2515it). This can then be verified externally to git.25162517Note that despite the tag features, "git" itself only handles content2518integrity; the trust framework (and signature provision and2519verification) has to come from outside.25202521A tag is created with gitlink:git-mktag[1],2522its data can be accessed by gitlink:git-cat-file[1],2523and the signature can be verified by2524gitlink:git-verify-tag[1].252525262527The "index" aka "Current Directory Cache"2528-----------------------------------------25292530The index is a simple binary file, which contains an efficient2531representation of a virtual directory content at some random time. It2532does so by a simple array that associates a set of names, dates,2533permissions and content (aka "blob") objects together. The cache is2534always kept ordered by name, and names are unique (with a few very2535specific rules) at any point in time, but the cache has no long-term2536meaning, and can be partially updated at any time.25372538In particular, the index certainly does not need to be consistent with2539the current directory contents (in fact, most operations will depend on2540different ways to make the index 'not' be consistent with the directory2541hierarchy), but it has three very important attributes:25422543'(a) it can re-generate the full state it caches (not just the2544directory structure: it contains pointers to the "blob" objects so2545that it can regenerate the data too)'25462547As a special case, there is a clear and unambiguous one-way mapping2548from a current directory cache to a "tree object", which can be2549efficiently created from just the current directory cache without2550actually looking at any other data. So a directory cache at any one2551time uniquely specifies one and only one "tree" object (but has2552additional data to make it easy to match up that tree object with what2553has happened in the directory)25542555'(b) it has efficient methods for finding inconsistencies between that2556cached state ("tree object waiting to be instantiated") and the2557current state.'25582559'(c) it can additionally efficiently represent information about merge2560conflicts between different tree objects, allowing each pathname to be2561associated with sufficient information about the trees involved that2562you can create a three-way merge between them.'25632564Those are the ONLY three things that the directory cache does. It's a2565cache, and the normal operation is to re-generate it completely from a2566known tree object, or update/compare it with a live tree that is being2567developed. If you blow the directory cache away entirely, you generally2568haven't lost any information as long as you have the name of the tree2569that it described. 25702571At the same time, the index is at the same time also the2572staging area for creating new trees, and creating a new tree always2573involves a controlled modification of the index file. In particular,2574the index file can have the representation of an intermediate tree that2575has not yet been instantiated. So the index can be thought of as a2576write-back cache, which can contain dirty information that has not yet2577been written back to the backing store.2578257925802581The Workflow2582------------25832584Generally, all "git" operations work on the index file. Some operations2585work *purely* on the index file (showing the current state of the2586index), but most operations move data to and from the index file. Either2587from the database or from the working directory. Thus there are four2588main combinations: 25892590working directory -> index2591~~~~~~~~~~~~~~~~~~~~~~~~~~25922593You update the index with information from the working directory with2594the gitlink:git-update-index[1] command. You2595generally update the index information by just specifying the filename2596you want to update, like so:25972598-------------------------------------------------2599$ git-update-index filename2600-------------------------------------------------26012602but to avoid common mistakes with filename globbing etc, the command2603will not normally add totally new entries or remove old entries,2604i.e. it will normally just update existing cache entries.26052606To tell git that yes, you really do realize that certain files no2607longer exist, or that new files should be added, you2608should use the `--remove` and `--add` flags respectively.26092610NOTE! A `--remove` flag does 'not' mean that subsequent filenames will2611necessarily be removed: if the files still exist in your directory2612structure, the index will be updated with their new status, not2613removed. The only thing `--remove` means is that update-cache will be2614considering a removed file to be a valid thing, and if the file really2615does not exist any more, it will update the index accordingly.26162617As a special case, you can also do `git-update-index --refresh`, which2618will refresh the "stat" information of each index to match the current2619stat information. It will 'not' update the object status itself, and2620it will only update the fields that are used to quickly test whether2621an object still matches its old backing store object.26222623index -> object database2624~~~~~~~~~~~~~~~~~~~~~~~~26252626You write your current index file to a "tree" object with the program26272628-------------------------------------------------2629$ git-write-tree2630-------------------------------------------------26312632that doesn't come with any options - it will just write out the2633current index into the set of tree objects that describe that state,2634and it will return the name of the resulting top-level tree. You can2635use that tree to re-generate the index at any time by going in the2636other direction:26372638object database -> index2639~~~~~~~~~~~~~~~~~~~~~~~~26402641You read a "tree" file from the object database, and use that to2642populate (and overwrite - don't do this if your index contains any2643unsaved state that you might want to restore later!) your current2644index. Normal operation is just26452646-------------------------------------------------2647$ git-read-tree <sha1 of tree>2648-------------------------------------------------26492650and your index file will now be equivalent to the tree that you saved2651earlier. However, that is only your 'index' file: your working2652directory contents have not been modified.26532654index -> working directory2655~~~~~~~~~~~~~~~~~~~~~~~~~~26562657You update your working directory from the index by "checking out"2658files. This is not a very common operation, since normally you'd just2659keep your files updated, and rather than write to your working2660directory, you'd tell the index files about the changes in your2661working directory (i.e. `git-update-index`).26622663However, if you decide to jump to a new version, or check out somebody2664else's version, or just restore a previous tree, you'd populate your2665index file with read-tree, and then you need to check out the result2666with26672668-------------------------------------------------2669$ git-checkout-index filename2670-------------------------------------------------26712672or, if you want to check out all of the index, use `-a`.26732674NOTE! git-checkout-index normally refuses to overwrite old files, so2675if you have an old version of the tree already checked out, you will2676need to use the "-f" flag ('before' the "-a" flag or the filename) to2677'force' the checkout.267826792680Finally, there are a few odds and ends which are not purely moving2681from one representation to the other:26822683Tying it all together2684~~~~~~~~~~~~~~~~~~~~~26852686To commit a tree you have instantiated with "git-write-tree", you'd2687create a "commit" object that refers to that tree and the history2688behind it - most notably the "parent" commits that preceded it in2689history.26902691Normally a "commit" has one parent: the previous state of the tree2692before a certain change was made. However, sometimes it can have two2693or more parent commits, in which case we call it a "merge", due to the2694fact that such a commit brings together ("merges") two or more2695previous states represented by other commits.26962697In other words, while a "tree" represents a particular directory state2698of a working directory, a "commit" represents that state in "time",2699and explains how we got there.27002701You create a commit object by giving it the tree that describes the2702state at the time of the commit, and a list of parents:27032704-------------------------------------------------2705$ git-commit-tree <tree> -p <parent> [-p <parent2> ..]2706-------------------------------------------------27072708and then giving the reason for the commit on stdin (either through2709redirection from a pipe or file, or by just typing it at the tty).27102711git-commit-tree will return the name of the object that represents2712that commit, and you should save it away for later use. Normally,2713you'd commit a new `HEAD` state, and while git doesn't care where you2714save the note about that state, in practice we tend to just write the2715result to the file pointed at by `.git/HEAD`, so that we can always see2716what the last committed state was.27172718Here is an ASCII art by Jon Loeliger that illustrates how2719various pieces fit together.27202721------------27222723 commit-tree2724 commit obj2725 +----+2726 | |2727 | |2728 V V2729 +-----------+2730 | Object DB |2731 | Backing |2732 | Store |2733 +-----------+2734 ^2735 write-tree | |2736 tree obj | |2737 | | read-tree2738 | | tree obj2739 V2740 +-----------+2741 | Index |2742 | "cache" |2743 +-----------+2744 update-index ^2745 blob obj | |2746 | |2747 checkout-index -u | | checkout-index2748 stat | | blob obj2749 V2750 +-----------+2751 | Working |2752 | Directory |2753 +-----------+27542755------------275627572758Examining the data2759------------------27602761You can examine the data represented in the object database and the2762index with various helper tools. For every object, you can use2763gitlink:git-cat-file[1] to examine details about the2764object:27652766-------------------------------------------------2767$ git-cat-file -t <objectname>2768-------------------------------------------------27692770shows the type of the object, and once you have the type (which is2771usually implicit in where you find the object), you can use27722773-------------------------------------------------2774$ git-cat-file blob|tree|commit|tag <objectname>2775-------------------------------------------------27762777to show its contents. NOTE! Trees have binary content, and as a result2778there is a special helper for showing that content, called2779`git-ls-tree`, which turns the binary content into a more easily2780readable form.27812782It's especially instructive to look at "commit" objects, since those2783tend to be small and fairly self-explanatory. In particular, if you2784follow the convention of having the top commit name in `.git/HEAD`,2785you can do27862787-------------------------------------------------2788$ git-cat-file commit HEAD2789-------------------------------------------------27902791to see what the top commit was.27922793Merging multiple trees2794----------------------27952796Git helps you do a three-way merge, which you can expand to n-way by2797repeating the merge procedure arbitrary times until you finally2798"commit" the state. The normal situation is that you'd only do one2799three-way merge (two parents), and commit it, but if you like to, you2800can do multiple parents in one go.28012802To do a three-way merge, you need the two sets of "commit" objects2803that you want to merge, use those to find the closest common parent (a2804third "commit" object), and then use those commit objects to find the2805state of the directory ("tree" object) at these points.28062807To get the "base" for the merge, you first look up the common parent2808of two commits with28092810-------------------------------------------------2811$ git-merge-base <commit1> <commit2>2812-------------------------------------------------28132814which will return you the commit they are both based on. You should2815now look up the "tree" objects of those commits, which you can easily2816do with (for example)28172818-------------------------------------------------2819$ git-cat-file commit <commitname> | head -12820-------------------------------------------------28212822since the tree object information is always the first line in a commit2823object.28242825Once you know the three trees you are going to merge (the one "original"2826tree, aka the common case, and the two "result" trees, aka the branches2827you want to merge), you do a "merge" read into the index. This will2828complain if it has to throw away your old index contents, so you should2829make sure that you've committed those - in fact you would normally2830always do a merge against your last commit (which should thus match what2831you have in your current index anyway).28322833To do the merge, do28342835-------------------------------------------------2836$ git-read-tree -m -u <origtree> <yourtree> <targettree>2837-------------------------------------------------28382839which will do all trivial merge operations for you directly in the2840index file, and you can just write the result out with2841`git-write-tree`.284228432844Merging multiple trees, continued2845---------------------------------28462847Sadly, many merges aren't trivial. If there are files that have2848been added.moved or removed, or if both branches have modified the2849same file, you will be left with an index tree that contains "merge2850entries" in it. Such an index tree can 'NOT' be written out to a tree2851object, and you will have to resolve any such merge clashes using2852other tools before you can write out the result.28532854You can examine such index state with `git-ls-files --unmerged`2855command. An example:28562857------------------------------------------------2858$ git-read-tree -m $orig HEAD $target2859$ git-ls-files --unmerged2860100644 263414f423d0e4d70dae8fe53fa34614ff3e2860 1 hello.c2861100644 06fa6a24256dc7e560efa5687fa84b51f0263c3a 2 hello.c2862100644 cc44c73eb783565da5831b4d820c962954019b69 3 hello.c2863------------------------------------------------28642865Each line of the `git-ls-files --unmerged` output begins with2866the blob mode bits, blob SHA1, 'stage number', and the2867filename. The 'stage number' is git's way to say which tree it2868came from: stage 1 corresponds to `$orig` tree, stage 2 `HEAD`2869tree, and stage3 `$target` tree.28702871Earlier we said that trivial merges are done inside2872`git-read-tree -m`. For example, if the file did not change2873from `$orig` to `HEAD` nor `$target`, or if the file changed2874from `$orig` to `HEAD` and `$orig` to `$target` the same way,2875obviously the final outcome is what is in `HEAD`. What the2876above example shows is that file `hello.c` was changed from2877`$orig` to `HEAD` and `$orig` to `$target` in a different way.2878You could resolve this by running your favorite 3-way merge2879program, e.g. `diff3` or `merge`, on the blob objects from2880these three stages yourself, like this:28812882------------------------------------------------2883$ git-cat-file blob 263414f... >hello.c~12884$ git-cat-file blob 06fa6a2... >hello.c~22885$ git-cat-file blob cc44c73... >hello.c~32886$ merge hello.c~2 hello.c~1 hello.c~32887------------------------------------------------28882889This would leave the merge result in `hello.c~2` file, along2890with conflict markers if there are conflicts. After verifying2891the merge result makes sense, you can tell git what the final2892merge result for this file is by:28932894-------------------------------------------------2895$ mv -f hello.c~2 hello.c2896$ git-update-index hello.c2897-------------------------------------------------28982899When a path is in unmerged state, running `git-update-index` for2900that path tells git to mark the path resolved.29012902The above is the description of a git merge at the lowest level,2903to help you understand what conceptually happens under the hood.2904In practice, nobody, not even git itself, uses three `git-cat-file`2905for this. There is `git-merge-index` program that extracts the2906stages to temporary files and calls a "merge" script on it:29072908-------------------------------------------------2909$ git-merge-index git-merge-one-file hello.c2910-------------------------------------------------29112912and that is what higher level `git merge -s resolve` is implemented with.29132914How git stores objects efficiently: pack files2915----------------------------------------------29162917We've seen how git stores each object in a file named after the2918object's SHA1 hash.29192920Unfortunately this system becomes inefficient once a project has a2921lot of objects. Try this on an old project:29222923------------------------------------------------2924$ git count-objects29256930 objects, 47620 kilobytes2926------------------------------------------------29272928The first number is the number of objects which are kept in2929individual files. The second is the amount of space taken up by2930those "loose" objects.29312932You can save space and make git faster by moving these loose objects in2933to a "pack file", which stores a group of objects in an efficient2934compressed format; the details of how pack files are formatted can be2935found in link:technical/pack-format.txt[technical/pack-format.txt].29362937To put the loose objects into a pack, just run git repack:29382939------------------------------------------------2940$ git repack2941Generating pack...2942Done counting 6020 objects.2943Deltifying 6020 objects.2944 100% (6020/6020) done2945Writing 6020 objects.2946 100% (6020/6020) done2947Total 6020, written 6020 (delta 4070), reused 0 (delta 0)2948Pack pack-3e54ad29d5b2e05838c75df582c65257b8d08e1c created.2949------------------------------------------------29502951You can then run29522953------------------------------------------------2954$ git prune2955------------------------------------------------29562957to remove any of the "loose" objects that are now contained in the2958pack. This will also remove any unreferenced objects (which may be2959created when, for example, you use "git reset" to remove a commit).2960You can verify that the loose objects are gone by looking at the2961.git/objects directory or by running29622963------------------------------------------------2964$ git count-objects29650 objects, 0 kilobytes2966------------------------------------------------29672968Although the object files are gone, any commands that refer to those2969objects will work exactly as they did before.29702971The gitlink:git-gc[1] command performs packing, pruning, and more for2972you, so is normally the only high-level command you need.29732974[[dangling-objects]]2975Dangling objects2976----------------29772978The gitlink:git-fsck[1] command will sometimes complain about dangling2979objects. They are not a problem.29802981The most common cause of dangling objects is that you've rebased a2982branch, or you have pulled from somebody else who rebased a branch--see2983<<cleaning-up-history>>. In that case, the old head of the original2984branch still exists, as does obviously everything it pointed to. The2985branch pointer itself just doesn't, since you replaced it with another2986one.29872988There are also other situations too that cause dangling objects. For2989example, a "dangling blob" may arise because you did a "git add" of a2990file, but then, before you actually committed it and made it part of the2991bigger picture, you changed something else in that file and committed2992that *updated* thing - the old state that you added originally ends up2993not being pointed to by any commit or tree, so it's now a dangling blob2994object.29952996Similarly, when the "recursive" merge strategy runs, and finds that2997there are criss-cross merges and thus more than one merge base (which is2998fairly unusual, but it does happen), it will generate one temporary2999midway tree (or possibly even more, if you had lots of criss-crossing3000merges and more than two merge bases) as a temporary internal merge3001base, and again, those are real objects, but the end result will not end3002up pointing to them, so they end up "dangling" in your repository.30033004Generally, dangling objects aren't anything to worry about. They can3005even be very useful: if you screw something up, the dangling objects can3006be how you recover your old tree (say, you did a rebase, and realized3007that you really didn't want to - you can look at what dangling objects3008you have, and decide to reset your head to some old dangling state).30093010For commits, the most useful thing to do with dangling objects tends to3011be to do a simple30123013------------------------------------------------3014$ gitk <dangling-commit-sha-goes-here> --not --all3015------------------------------------------------30163017For blobs and trees, you can't do the same, but you can examine them.3018You can just do30193020------------------------------------------------3021$ git show <dangling-blob/tree-sha-goes-here>3022------------------------------------------------30233024to show what the contents of the blob were (or, for a tree, basically3025what the "ls" for that directory was), and that may give you some idea3026of what the operation was that left that dangling object.30273028Usually, dangling blobs and trees aren't very interesting. They're3029almost always the result of either being a half-way mergebase (the blob3030will often even have the conflict markers from a merge in it, if you3031have had conflicting merges that you fixed up by hand), or simply3032because you interrupted a "git fetch" with ^C or something like that,3033leaving _some_ of the new objects in the object database, but just3034dangling and useless.30353036Anyway, once you are sure that you're not interested in any dangling 3037state, you can just prune all unreachable objects:30383039------------------------------------------------3040$ git prune3041------------------------------------------------30423043and they'll be gone. But you should only run "git prune" on a quiescent3044repository - it's kind of like doing a filesystem fsck recovery: you3045don't want to do that while the filesystem is mounted.30463047(The same is true of "git-fsck" itself, btw - but since 3048git-fsck never actually *changes* the repository, it just reports 3049on what it found, git-fsck itself is never "dangerous" to run. 3050Running it while somebody is actually changing the repository can cause 3051confusing and scary messages, but it won't actually do anything bad. In 3052contrast, running "git prune" while somebody is actively changing the 3053repository is a *BAD* idea).30543055include::glossary.txt[]30563057Notes and todo list for this manual3058===================================30593060This is a work in progress.30613062The basic requirements:3063 - It must be readable in order, from beginning to end, by3064 someone intelligent with a basic grasp of the unix3065 commandline, but without any special knowledge of git. If3066 necessary, any other prerequisites should be specifically3067 mentioned as they arise.3068 - Whenever possible, section headings should clearly describe3069 the task they explain how to do, in language that requires3070 no more knowledge than necessary: for example, "importing3071 patches into a project" rather than "the git-am command"30723073Think about how to create a clear chapter dependency graph that will3074allow people to get to important topics without necessarily reading3075everything in between.30763077Say something about .gitignore.30783079Scan Documentation/ for other stuff left out; in particular:3080 howto's3081 some of technical/?3082 hooks3083 list of commands in gitlink:git[1]30843085Scan email archives for other stuff left out30863087Scan man pages to see if any assume more background than this manual3088provides.30893090Simplify beginning by suggesting disconnected head instead of3091temporary branch creation?30923093Add more good examples. Entire sections of just cookbook examples3094might be a good idea; maybe make an "advanced examples" section a3095standard end-of-chapter section?30963097Include cross-references to the glossary, where appropriate.30983099Document shallow clones? See draft 1.5.0 release notes for some3100documentation.31013102Add a section on working with other version control systems, including3103CVS, Subversion, and just imports of series of release tarballs.31043105More details on gitweb?31063107Write a chapter on using plumbing and writing scripts.