1Git User's Manual (for version 1.5.1 or newer) 2______________________________________________ 3 4 5Git is a fast distributed revision control system. 6 7This manual is designed to be readable by someone with basic unix 8command-line skills, but no previous knowledge of git. 9 10<<repositories-and-branches>> and <<exploring-git-history>> explain how 11to fetch and study a project using git--read these chapters to learn how 12to build and test a particular version of a software project, search for 13regressions, and so on. 14 15People needing to do actual development will also want to read 16<<Developing-with-git>> and <<sharing-development>>. 17 18Further chapters cover more specialized topics. 19 20Comprehensive reference documentation is available through the man 21pages. For a command such as "git clone", just use 22 23------------------------------------------------ 24$ man git-clone 25------------------------------------------------ 26 27See also <<git-quick-start>> for a brief overview of git commands, 28without any explanation. 29 30Also, see <<todo>> for ways that you can help make this manual more 31complete. 32 33 34[[repositories-and-branches]] 35Repositories and Branches 36========================= 37 38[[how-to-get-a-git-repository]] 39How to get a git repository 40--------------------------- 41 42It will be useful to have a git repository to experiment with as you 43read this manual. 44 45The best way to get one is by using the gitlink:git-clone[1] command 46to download a copy of an existing repository for a project that you 47are interested in. If you don't already have a project in mind, here 48are some interesting examples: 49 50------------------------------------------------ 51 # git itself (approx. 10MB download): 52$ git clone git://git.kernel.org/pub/scm/git/git.git 53 # the linux kernel (approx. 150MB download): 54$ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git 55------------------------------------------------ 56 57The initial clone may be time-consuming for a large project, but you 58will only need to clone once. 59 60The clone command creates a new directory named after the project 61("git" or "linux-2.6" in the examples above). After you cd into this 62directory, you will see that it contains a copy of the project files, 63together with a special top-level directory named ".git", which 64contains all the information about the history of the project. 65 66In most of the following, examples will be taken from one of the two 67repositories above. 68 69[[how-to-check-out]] 70How to check out a different version of a project 71------------------------------------------------- 72 73Git is best thought of as a tool for storing the history of a 74collection of files. It stores the history as a compressed 75collection of interrelated snapshots (versions) of the project's 76contents. 77 78A single git repository may contain multiple branches. It keeps track 79of them by keeping a list of <<def_head,heads>> which reference the 80latest version on each branch; the gitlink:git-branch[1] command shows 81you the list of branch heads: 82 83------------------------------------------------ 84$ git branch 85* master 86------------------------------------------------ 87 88A freshly cloned repository contains a single branch head, by default 89named "master", with the working directory initialized to the state of 90the project referred to by that branch head. 91 92Most projects also use <<def_tag,tags>>. Tags, like heads, are 93references into the project's history, and can be listed using the 94gitlink:git-tag[1] command: 95 96------------------------------------------------ 97$ git tag -l 98v2.6.11 99v2.6.11-tree 100v2.6.12 101v2.6.12-rc2 102v2.6.12-rc3 103v2.6.12-rc4 104v2.6.12-rc5 105v2.6.12-rc6 106v2.6.13 107... 108------------------------------------------------ 109 110Tags are expected to always point at the same version of a project, 111while heads are expected to advance as development progresses. 112 113Create a new branch head pointing to one of these versions and check it 114out using gitlink:git-checkout[1]: 115 116------------------------------------------------ 117$ git checkout -b new v2.6.13 118------------------------------------------------ 119 120The working directory then reflects the contents that the project had 121when it was tagged v2.6.13, and gitlink:git-branch[1] shows two 122branches, with an asterisk marking the currently checked-out branch: 123 124------------------------------------------------ 125$ git branch 126 master 127* new 128------------------------------------------------ 129 130If you decide that you'd rather see version 2.6.17, you can modify 131the current branch to point at v2.6.17 instead, with 132 133------------------------------------------------ 134$ git reset --hard v2.6.17 135------------------------------------------------ 136 137Note that if the current branch head was your only reference to a 138particular point in history, then resetting that branch may leave you 139with no way to find the history it used to point to; so use this command 140carefully. 141 142[[understanding-commits]] 143Understanding History: Commits 144------------------------------ 145 146Every change in the history of a project is represented by a commit. 147The gitlink:git-show[1] command shows the most recent commit on the 148current branch: 149 150------------------------------------------------ 151$ git show 152commit 2b5f6dcce5bf94b9b119e9ed8d537098ec61c3d2 153Author: Jamal Hadi Salim <hadi@cyberus.ca> 154Date: Sat Dec 2 22:22:25 2006 -0800 155 156 [XFRM]: Fix aevent structuring to be more complete. 157 158 aevents can not uniquely identify an SA. We break the ABI with this 159 patch, but consensus is that since it is not yet utilized by any 160 (known) application then it is fine (better do it now than later). 161 162 Signed-off-by: Jamal Hadi Salim <hadi@cyberus.ca> 163 Signed-off-by: David S. Miller <davem@davemloft.net> 164 165diff --git a/Documentation/networking/xfrm_sync.txt b/Documentation/networking/xfrm_sync.txt 166index 8be626f..d7aac9d 100644 167--- a/Documentation/networking/xfrm_sync.txt 168+++ b/Documentation/networking/xfrm_sync.txt 169@@ -47,10 +47,13 @@ aevent_id structure looks like: 170 171 struct xfrm_aevent_id { 172 struct xfrm_usersa_id sa_id; 173+ xfrm_address_t saddr; 174 __u32 flags; 175+ __u32 reqid; 176 }; 177... 178------------------------------------------------ 179 180As you can see, a commit shows who made the latest change, what they 181did, and why. 182 183Every commit has a 40-hexdigit id, sometimes called the "object name" or the 184"SHA1 id", shown on the first line of the "git show" output. You can usually 185refer to a commit by a shorter name, such as a tag or a branch name, but this 186longer name can also be useful. Most importantly, it is a globally unique 187name for this commit: so if you tell somebody else the object name (for 188example in email), then you are guaranteed that name will refer to the same 189commit in their repository that it does in yours (assuming their repository 190has that commit at all). Since the object name is computed as a hash over the 191contents of the commit, you are guaranteed that the commit can never change 192without its name also changing. 193 194In fact, in <<git-internals>> we shall see that everything stored in git 195history, including file data and directory contents, is stored in an object 196with a name that is a hash of its contents. 197 198[[understanding-reachability]] 199Understanding history: commits, parents, and reachability 200~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 201 202Every commit (except the very first commit in a project) also has a 203parent commit which shows what happened before this commit. 204Following the chain of parents will eventually take you back to the 205beginning of the project. 206 207However, the commits do not form a simple list; git allows lines of 208development to diverge and then reconverge, and the point where two 209lines of development reconverge is called a "merge". The commit 210representing a merge can therefore have more than one parent, with 211each parent representing the most recent commit on one of the lines 212of development leading to that point. 213 214The best way to see how this works is using the gitlink:gitk[1] 215command; running gitk now on a git repository and looking for merge 216commits will help understand how the git organizes history. 217 218In the following, we say that commit X is "reachable" from commit Y 219if commit X is an ancestor of commit Y. Equivalently, you could say 220that Y is a descendent of X, or that there is a chain of parents 221leading from commit Y to commit X. 222 223[[history-diagrams]] 224Understanding history: History diagrams 225~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 226 227We will sometimes represent git history using diagrams like the one 228below. Commits are shown as "o", and the links between them with 229lines drawn with - / and \. Time goes left to right: 230 231 232................................................ 233 o--o--o <-- Branch A 234 / 235 o--o--o <-- master 236 \ 237 o--o--o <-- Branch B 238................................................ 239 240If we need to talk about a particular commit, the character "o" may 241be replaced with another letter or number. 242 243[[what-is-a-branch]] 244Understanding history: What is a branch? 245~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 246 247When we need to be precise, we will use the word "branch" to mean a line 248of development, and "branch head" (or just "head") to mean a reference 249to the most recent commit on a branch. In the example above, the branch 250head named "A" is a pointer to one particular commit, but we refer to 251the line of three commits leading up to that point as all being part of 252"branch A". 253 254However, when no confusion will result, we often just use the term 255"branch" both for branches and for branch heads. 256 257[[manipulating-branches]] 258Manipulating branches 259--------------------- 260 261Creating, deleting, and modifying branches is quick and easy; here's 262a summary of the commands: 263 264git branch:: 265 list all branches 266git branch <branch>:: 267 create a new branch named <branch>, referencing the same 268 point in history as the current branch 269git branch <branch> <start-point>:: 270 create a new branch named <branch>, referencing 271 <start-point>, which may be specified any way you like, 272 including using a branch name or a tag name 273git branch -d <branch>:: 274 delete the branch <branch>; if the branch you are deleting 275 points to a commit which is not reachable from the current 276 branch, this command will fail with a warning. 277git branch -D <branch>:: 278 even if the branch points to a commit not reachable 279 from the current branch, you may know that that commit 280 is still reachable from some other branch or tag. In that 281 case it is safe to use this command to force git to delete 282 the branch. 283git checkout <branch>:: 284 make the current branch <branch>, updating the working 285 directory to reflect the version referenced by <branch> 286git checkout -b <new> <start-point>:: 287 create a new branch <new> referencing <start-point>, and 288 check it out. 289 290The special symbol "HEAD" can always be used to refer to the current 291branch. In fact, git uses a file named "HEAD" in the .git directory to 292remember which branch is current: 293 294------------------------------------------------ 295$ cat .git/HEAD 296ref: refs/heads/master 297------------------------------------------------ 298 299[[detached-head]] 300Examining an old version without creating a new branch 301------------------------------------------------------ 302 303The git-checkout command normally expects a branch head, but will also 304accept an arbitrary commit; for example, you can check out the commit 305referenced by a tag: 306 307------------------------------------------------ 308$ git checkout v2.6.17 309Note: moving to "v2.6.17" which isn't a local branch 310If you want to create a new branch from this checkout, you may do so 311(now or later) by using -b with the checkout command again. Example: 312 git checkout -b <new_branch_name> 313HEAD is now at 427abfa... Linux v2.6.17 314------------------------------------------------ 315 316The HEAD then refers to the SHA1 of the commit instead of to a branch, 317and git branch shows that you are no longer on a branch: 318 319------------------------------------------------ 320$ cat .git/HEAD 321427abfa28afedffadfca9dd8b067eb6d36bac53f 322$ git branch 323* (no branch) 324 master 325------------------------------------------------ 326 327In this case we say that the HEAD is "detached". 328 329This is an easy way to check out a particular version without having to 330make up a name for the new branch. You can still create a new branch 331(or tag) for this version later if you decide to. 332 333[[examining-remote-branches]] 334Examining branches from a remote repository 335------------------------------------------- 336 337The "master" branch that was created at the time you cloned is a copy 338of the HEAD in the repository that you cloned from. That repository 339may also have had other branches, though, and your local repository 340keeps branches which track each of those remote branches, which you 341can view using the "-r" option to gitlink:git-branch[1]: 342 343------------------------------------------------ 344$ git branch -r 345 origin/HEAD 346 origin/html 347 origin/maint 348 origin/man 349 origin/master 350 origin/next 351 origin/pu 352 origin/todo 353------------------------------------------------ 354 355You cannot check out these remote-tracking branches, but you can 356examine them on a branch of your own, just as you would a tag: 357 358------------------------------------------------ 359$ git checkout -b my-todo-copy origin/todo 360------------------------------------------------ 361 362Note that the name "origin" is just the name that git uses by default 363to refer to the repository that you cloned from. 364 365[[how-git-stores-references]] 366Naming branches, tags, and other references 367------------------------------------------- 368 369Branches, remote-tracking branches, and tags are all references to 370commits. All references are named with a slash-separated path name 371starting with "refs"; the names we've been using so far are actually 372shorthand: 373 374 - The branch "test" is short for "refs/heads/test". 375 - The tag "v2.6.18" is short for "refs/tags/v2.6.18". 376 - "origin/master" is short for "refs/remotes/origin/master". 377 378The full name is occasionally useful if, for example, there ever 379exists a tag and a branch with the same name. 380 381As another useful shortcut, the "HEAD" of a repository can be referred 382to just using the name of that repository. So, for example, "origin" 383is usually a shortcut for the HEAD branch in the repository "origin". 384 385For the complete list of paths which git checks for references, and 386the order it uses to decide which to choose when there are multiple 387references with the same shorthand name, see the "SPECIFYING 388REVISIONS" section of gitlink:git-rev-parse[1]. 389 390[[Updating-a-repository-with-git-fetch]] 391Updating a repository with git fetch 392------------------------------------ 393 394Eventually the developer cloned from will do additional work in her 395repository, creating new commits and advancing the branches to point 396at the new commits. 397 398The command "git fetch", with no arguments, will update all of the 399remote-tracking branches to the latest version found in her 400repository. It will not touch any of your own branches--not even the 401"master" branch that was created for you on clone. 402 403[[fetching-branches]] 404Fetching branches from other repositories 405----------------------------------------- 406 407You can also track branches from repositories other than the one you 408cloned from, using gitlink:git-remote[1]: 409 410------------------------------------------------- 411$ git remote add linux-nfs git://linux-nfs.org/pub/nfs-2.6.git 412$ git fetch linux-nfs 413* refs/remotes/linux-nfs/master: storing branch 'master' ... 414 commit: bf81b46 415------------------------------------------------- 416 417New remote-tracking branches will be stored under the shorthand name 418that you gave "git remote add", in this case linux-nfs: 419 420------------------------------------------------- 421$ git branch -r 422linux-nfs/master 423origin/master 424------------------------------------------------- 425 426If you run "git fetch <remote>" later, the tracking branches for the 427named <remote> will be updated. 428 429If you examine the file .git/config, you will see that git has added 430a new stanza: 431 432------------------------------------------------- 433$ cat .git/config 434... 435[remote "linux-nfs"] 436 url = git://linux-nfs.org/pub/nfs-2.6.git 437 fetch = +refs/heads/*:refs/remotes/linux-nfs/* 438... 439------------------------------------------------- 440 441This is what causes git to track the remote's branches; you may modify 442or delete these configuration options by editing .git/config with a 443text editor. (See the "CONFIGURATION FILE" section of 444gitlink:git-config[1] for details.) 445 446[[exploring-git-history]] 447Exploring git history 448===================== 449 450Git is best thought of as a tool for storing the history of a 451collection of files. It does this by storing compressed snapshots of 452the contents of a file heirarchy, together with "commits" which show 453the relationships between these snapshots. 454 455Git provides extremely flexible and fast tools for exploring the 456history of a project. 457 458We start with one specialized tool that is useful for finding the 459commit that introduced a bug into a project. 460 461[[using-bisect]] 462How to use bisect to find a regression 463-------------------------------------- 464 465Suppose version 2.6.18 of your project worked, but the version at 466"master" crashes. Sometimes the best way to find the cause of such a 467regression is to perform a brute-force search through the project's 468history to find the particular commit that caused the problem. The 469gitlink:git-bisect[1] command can help you do this: 470 471------------------------------------------------- 472$ git bisect start 473$ git bisect good v2.6.18 474$ git bisect bad master 475Bisecting: 3537 revisions left to test after this 476[65934a9a028b88e83e2b0f8b36618fe503349f8e] BLOCK: Make USB storage depend on SCSI rather than selecting it [try #6] 477------------------------------------------------- 478 479If you run "git branch" at this point, you'll see that git has 480temporarily moved you to a new branch named "bisect". This branch 481points to a commit (with commit id 65934...) that is reachable from 482v2.6.19 but not from v2.6.18. Compile and test it, and see whether 483it crashes. Assume it does crash. Then: 484 485------------------------------------------------- 486$ git bisect bad 487Bisecting: 1769 revisions left to test after this 488[7eff82c8b1511017ae605f0c99ac275a7e21b867] i2c-core: Drop useless bitmaskings 489------------------------------------------------- 490 491checks out an older version. Continue like this, telling git at each 492stage whether the version it gives you is good or bad, and notice 493that the number of revisions left to test is cut approximately in 494half each time. 495 496After about 13 tests (in this case), it will output the commit id of 497the guilty commit. You can then examine the commit with 498gitlink:git-show[1], find out who wrote it, and mail them your bug 499report with the commit id. Finally, run 500 501------------------------------------------------- 502$ git bisect reset 503------------------------------------------------- 504 505to return you to the branch you were on before and delete the 506temporary "bisect" branch. 507 508Note that the version which git-bisect checks out for you at each 509point is just a suggestion, and you're free to try a different 510version if you think it would be a good idea. For example, 511occasionally you may land on a commit that broke something unrelated; 512run 513 514------------------------------------------------- 515$ git bisect visualize 516------------------------------------------------- 517 518which will run gitk and label the commit it chose with a marker that 519says "bisect". Chose a safe-looking commit nearby, note its commit 520id, and check it out with: 521 522------------------------------------------------- 523$ git reset --hard fb47ddb2db... 524------------------------------------------------- 525 526then test, run "bisect good" or "bisect bad" as appropriate, and 527continue. 528 529[[naming-commits]] 530Naming commits 531-------------- 532 533We have seen several ways of naming commits already: 534 535 - 40-hexdigit object name 536 - branch name: refers to the commit at the head of the given 537 branch 538 - tag name: refers to the commit pointed to by the given tag 539 (we've seen branches and tags are special cases of 540 <<how-git-stores-references,references>>). 541 - HEAD: refers to the head of the current branch 542 543There are many more; see the "SPECIFYING REVISIONS" section of the 544gitlink:git-rev-parse[1] man page for the complete list of ways to 545name revisions. Some examples: 546 547------------------------------------------------- 548$ git show fb47ddb2 # the first few characters of the object name 549 # are usually enough to specify it uniquely 550$ git show HEAD^ # the parent of the HEAD commit 551$ git show HEAD^^ # the grandparent 552$ git show HEAD~4 # the great-great-grandparent 553------------------------------------------------- 554 555Recall that merge commits may have more than one parent; by default, 556^ and ~ follow the first parent listed in the commit, but you can 557also choose: 558 559------------------------------------------------- 560$ git show HEAD^1 # show the first parent of HEAD 561$ git show HEAD^2 # show the second parent of HEAD 562------------------------------------------------- 563 564In addition to HEAD, there are several other special names for 565commits: 566 567Merges (to be discussed later), as well as operations such as 568git-reset, which change the currently checked-out commit, generally 569set ORIG_HEAD to the value HEAD had before the current operation. 570 571The git-fetch operation always stores the head of the last fetched 572branch in FETCH_HEAD. For example, if you run git fetch without 573specifying a local branch as the target of the operation 574 575------------------------------------------------- 576$ git fetch git://example.com/proj.git theirbranch 577------------------------------------------------- 578 579the fetched commits will still be available from FETCH_HEAD. 580 581When we discuss merges we'll also see the special name MERGE_HEAD, 582which refers to the other branch that we're merging in to the current 583branch. 584 585The gitlink:git-rev-parse[1] command is a low-level command that is 586occasionally useful for translating some name for a commit to the object 587name for that commit: 588 589------------------------------------------------- 590$ git rev-parse origin 591e05db0fd4f31dde7005f075a84f96b360d05984b 592------------------------------------------------- 593 594[[creating-tags]] 595Creating tags 596------------- 597 598We can also create a tag to refer to a particular commit; after 599running 600 601------------------------------------------------- 602$ git tag stable-1 1b2e1d63ff 603------------------------------------------------- 604 605You can use stable-1 to refer to the commit 1b2e1d63ff. 606 607This creates a "lightweight" tag. If you would also like to include a 608comment with the tag, and possibly sign it cryptographically, then you 609should create a tag object instead; see the gitlink:git-tag[1] man page 610for details. 611 612[[browsing-revisions]] 613Browsing revisions 614------------------ 615 616The gitlink:git-log[1] command can show lists of commits. On its 617own, it shows all commits reachable from the parent commit; but you 618can also make more specific requests: 619 620------------------------------------------------- 621$ git log v2.5.. # commits since (not reachable from) v2.5 622$ git log test..master # commits reachable from master but not test 623$ git log master..test # ...reachable from test but not master 624$ git log master...test # ...reachable from either test or master, 625 # but not both 626$ git log --since="2 weeks ago" # commits from the last 2 weeks 627$ git log Makefile # commits which modify Makefile 628$ git log fs/ # ... which modify any file under fs/ 629$ git log -S'foo()' # commits which add or remove any file data 630 # matching the string 'foo()' 631------------------------------------------------- 632 633And of course you can combine all of these; the following finds 634commits since v2.5 which touch the Makefile or any file under fs: 635 636------------------------------------------------- 637$ git log v2.5.. Makefile fs/ 638------------------------------------------------- 639 640You can also ask git log to show patches: 641 642------------------------------------------------- 643$ git log -p 644------------------------------------------------- 645 646See the "--pretty" option in the gitlink:git-log[1] man page for more 647display options. 648 649Note that git log starts with the most recent commit and works 650backwards through the parents; however, since git history can contain 651multiple independent lines of development, the particular order that 652commits are listed in may be somewhat arbitrary. 653 654[[generating-diffs]] 655Generating diffs 656---------------- 657 658You can generate diffs between any two versions using 659gitlink:git-diff[1]: 660 661------------------------------------------------- 662$ git diff master..test 663------------------------------------------------- 664 665Sometimes what you want instead is a set of patches: 666 667------------------------------------------------- 668$ git format-patch master..test 669------------------------------------------------- 670 671will generate a file with a patch for each commit reachable from test 672but not from master. Note that if master also has commits which are 673not reachable from test, then the combined result of these patches 674will not be the same as the diff produced by the git-diff example. 675 676[[viewing-old-file-versions]] 677Viewing old file versions 678------------------------- 679 680You can always view an old version of a file by just checking out the 681correct revision first. But sometimes it is more convenient to be 682able to view an old version of a single file without checking 683anything out; this command does that: 684 685------------------------------------------------- 686$ git show v2.5:fs/locks.c 687------------------------------------------------- 688 689Before the colon may be anything that names a commit, and after it 690may be any path to a file tracked by git. 691 692[[history-examples]] 693Examples 694-------- 695 696[[counting-commits-on-a-branch]] 697Counting the number of commits on a branch 698~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 699 700Suppose you want to know how many commits you've made on "mybranch" 701since it diverged from "origin": 702 703------------------------------------------------- 704$ git log --pretty=oneline origin..mybranch | wc -l 705------------------------------------------------- 706 707Alternatively, you may often see this sort of thing done with the 708lower-level command gitlink:git-rev-list[1], which just lists the SHA1's 709of all the given commits: 710 711------------------------------------------------- 712$ git rev-list origin..mybranch | wc -l 713------------------------------------------------- 714 715[[checking-for-equal-branches]] 716Check whether two branches point at the same history 717~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 718 719Suppose you want to check whether two branches point at the same point 720in history. 721 722------------------------------------------------- 723$ git diff origin..master 724------------------------------------------------- 725 726will tell you whether the contents of the project are the same at the 727two branches; in theory, however, it's possible that the same project 728contents could have been arrived at by two different historical 729routes. You could compare the object names: 730 731------------------------------------------------- 732$ git rev-list origin 733e05db0fd4f31dde7005f075a84f96b360d05984b 734$ git rev-list master 735e05db0fd4f31dde7005f075a84f96b360d05984b 736------------------------------------------------- 737 738Or you could recall that the ... operator selects all commits 739contained reachable from either one reference or the other but not 740both: so 741 742------------------------------------------------- 743$ git log origin...master 744------------------------------------------------- 745 746will return no commits when the two branches are equal. 747 748[[finding-tagged-descendants]] 749Find first tagged version including a given fix 750~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 751 752Suppose you know that the commit e05db0fd fixed a certain problem. 753You'd like to find the earliest tagged release that contains that 754fix. 755 756Of course, there may be more than one answer--if the history branched 757after commit e05db0fd, then there could be multiple "earliest" tagged 758releases. 759 760You could just visually inspect the commits since e05db0fd: 761 762------------------------------------------------- 763$ gitk e05db0fd.. 764------------------------------------------------- 765 766Or you can use gitlink:git-name-rev[1], which will give the commit a 767name based on any tag it finds pointing to one of the commit's 768descendants: 769 770------------------------------------------------- 771$ git name-rev --tags e05db0fd 772e05db0fd tags/v1.5.0-rc1^0~23 773------------------------------------------------- 774 775The gitlink:git-describe[1] command does the opposite, naming the 776revision using a tag on which the given commit is based: 777 778------------------------------------------------- 779$ git describe e05db0fd 780v1.5.0-rc0-260-ge05db0f 781------------------------------------------------- 782 783but that may sometimes help you guess which tags might come after the 784given commit. 785 786If you just want to verify whether a given tagged version contains a 787given commit, you could use gitlink:git-merge-base[1]: 788 789------------------------------------------------- 790$ git merge-base e05db0fd v1.5.0-rc1 791e05db0fd4f31dde7005f075a84f96b360d05984b 792------------------------------------------------- 793 794The merge-base command finds a common ancestor of the given commits, 795and always returns one or the other in the case where one is a 796descendant of the other; so the above output shows that e05db0fd 797actually is an ancestor of v1.5.0-rc1. 798 799Alternatively, note that 800 801------------------------------------------------- 802$ git log v1.5.0-rc1..e05db0fd 803------------------------------------------------- 804 805will produce empty output if and only if v1.5.0-rc1 includes e05db0fd, 806because it outputs only commits that are not reachable from v1.5.0-rc1. 807 808As yet another alternative, the gitlink:git-show-branch[1] command lists 809the commits reachable from its arguments with a display on the left-hand 810side that indicates which arguments that commit is reachable from. So, 811you can run something like 812 813------------------------------------------------- 814$ git show-branch e05db0fd v1.5.0-rc0 v1.5.0-rc1 v1.5.0-rc2 815! [e05db0fd] Fix warnings in sha1_file.c - use C99 printf format if 816available 817 ! [v1.5.0-rc0] GIT v1.5.0 preview 818 ! [v1.5.0-rc1] GIT v1.5.0-rc1 819 ! [v1.5.0-rc2] GIT v1.5.0-rc2 820... 821------------------------------------------------- 822 823then search for a line that looks like 824 825------------------------------------------------- 826+ ++ [e05db0fd] Fix warnings in sha1_file.c - use C99 printf format if 827available 828------------------------------------------------- 829 830Which shows that e05db0fd is reachable from itself, from v1.5.0-rc1, and 831from v1.5.0-rc2, but not from v1.5.0-rc0. 832 833[[showing-commits-unique-to-a-branch]] 834Showing commits unique to a given branch 835~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 836 837Suppose you would like to see all the commits reachable from the branch 838head named "master" but not from any other head in your repository. 839 840We can list all the heads in this repository with 841gitlink:git-show-ref[1]: 842 843------------------------------------------------- 844$ git show-ref --heads 845bf62196b5e363d73353a9dcf094c59595f3153b7 refs/heads/core-tutorial 846db768d5504c1bb46f63ee9d6e1772bd047e05bf9 refs/heads/maint 847a07157ac624b2524a059a3414e99f6f44bebc1e7 refs/heads/master 84824dbc180ea14dc1aebe09f14c8ecf32010690627 refs/heads/tutorial-2 8491e87486ae06626c2f31eaa63d26fc0fd646c8af2 refs/heads/tutorial-fixes 850------------------------------------------------- 851 852We can get just the branch-head names, and remove "master", with 853the help of the standard utilities cut and grep: 854 855------------------------------------------------- 856$ git show-ref --heads | cut -d' ' -f2 | grep -v '^refs/heads/master' 857refs/heads/core-tutorial 858refs/heads/maint 859refs/heads/tutorial-2 860refs/heads/tutorial-fixes 861------------------------------------------------- 862 863And then we can ask to see all the commits reachable from master 864but not from these other heads: 865 866------------------------------------------------- 867$ gitk master --not $( git show-ref --heads | cut -d' ' -f2 | 868 grep -v '^refs/heads/master' ) 869------------------------------------------------- 870 871Obviously, endless variations are possible; for example, to see all 872commits reachable from some head but not from any tag in the repository: 873 874------------------------------------------------- 875$ gitk ($ git show-ref --heads ) --not $( git show-ref --tags ) 876------------------------------------------------- 877 878(See gitlink:git-rev-parse[1] for explanations of commit-selecting 879syntax such as `--not`.) 880 881[[making-a-release]] 882Creating a changelog and tarball for a software release 883~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 884 885The gitlink:git-archive[1] command can create a tar or zip archive from 886any version of a project; for example: 887 888------------------------------------------------- 889$ git archive --format=tar --prefix=project/ HEAD | gzip >latest.tar.gz 890------------------------------------------------- 891 892will use HEAD to produce a tar archive in which each filename is 893preceded by "prefix/". 894 895If you're releasing a new version of a software project, you may want 896to simultaneously make a changelog to include in the release 897announcement. 898 899Linus Torvalds, for example, makes new kernel releases by tagging them, 900then running: 901 902------------------------------------------------- 903$ release-script 2.6.12 2.6.13-rc6 2.6.13-rc7 904------------------------------------------------- 905 906where release-script is a shell script that looks like: 907 908------------------------------------------------- 909#!/bin/sh 910stable="$1" 911last="$2" 912new="$3" 913echo "# git tag v$new" 914echo "git archive --prefix=linux-$new/ v$new | gzip -9 > ../linux-$new.tar.gz" 915echo "git diff v$stable v$new | gzip -9 > ../patch-$new.gz" 916echo "git log --no-merges v$new ^v$last > ../ChangeLog-$new" 917echo "git shortlog --no-merges v$new ^v$last > ../ShortLog" 918echo "git diff --stat --summary -M v$last v$new > ../diffstat-$new" 919------------------------------------------------- 920 921and then he just cut-and-pastes the output commands after verifying that 922they look OK. 923 924[[Developing-with-git]] 925Developing with git 926=================== 927 928[[telling-git-your-name]] 929Telling git your name 930--------------------- 931 932Before creating any commits, you should introduce yourself to git. The 933easiest way to do so is to make sure the following lines appear in a 934file named .gitconfig in your home directory: 935 936------------------------------------------------ 937[user] 938 name = Your Name Comes Here 939 email = you@yourdomain.example.com 940------------------------------------------------ 941 942(See the "CONFIGURATION FILE" section of gitlink:git-config[1] for 943details on the configuration file.) 944 945 946[[creating-a-new-repository]] 947Creating a new repository 948------------------------- 949 950Creating a new repository from scratch is very easy: 951 952------------------------------------------------- 953$ mkdir project 954$ cd project 955$ git init 956------------------------------------------------- 957 958If you have some initial content (say, a tarball): 959 960------------------------------------------------- 961$ tar -xzvf project.tar.gz 962$ cd project 963$ git init 964$ git add . # include everything below ./ in the first commit: 965$ git commit 966------------------------------------------------- 967 968[[how-to-make-a-commit]] 969How to make a commit 970-------------------- 971 972Creating a new commit takes three steps: 973 974 1. Making some changes to the working directory using your 975 favorite editor. 976 2. Telling git about your changes. 977 3. Creating the commit using the content you told git about 978 in step 2. 979 980In practice, you can interleave and repeat steps 1 and 2 as many 981times as you want: in order to keep track of what you want committed 982at step 3, git maintains a snapshot of the tree's contents in a 983special staging area called "the index." 984 985At the beginning, the content of the index will be identical to 986that of the HEAD. The command "git diff --cached", which shows 987the difference between the HEAD and the index, should therefore 988produce no output at that point. 989 990Modifying the index is easy: 991 992To update the index with the new contents of a modified file, use 993 994------------------------------------------------- 995$ git add path/to/file 996------------------------------------------------- 997 998To add the contents of a new file to the index, use 9991000-------------------------------------------------1001$ git add path/to/file1002-------------------------------------------------10031004To remove a file from the index and from the working tree,10051006-------------------------------------------------1007$ git rm path/to/file1008-------------------------------------------------10091010After each step you can verify that10111012-------------------------------------------------1013$ git diff --cached1014-------------------------------------------------10151016always shows the difference between the HEAD and the index file--this1017is what you'd commit if you created the commit now--and that10181019-------------------------------------------------1020$ git diff1021-------------------------------------------------10221023shows the difference between the working tree and the index file.10241025Note that "git add" always adds just the current contents of a file1026to the index; further changes to the same file will be ignored unless1027you run git-add on the file again.10281029When you're ready, just run10301031-------------------------------------------------1032$ git commit1033-------------------------------------------------10341035and git will prompt you for a commit message and then create the new1036commit. Check to make sure it looks like what you expected with10371038-------------------------------------------------1039$ git show1040-------------------------------------------------10411042As a special shortcut,10431044-------------------------------------------------1045$ git commit -a1046-------------------------------------------------10471048will update the index with any files that you've modified or removed1049and create a commit, all in one step.10501051A number of commands are useful for keeping track of what you're1052about to commit:10531054-------------------------------------------------1055$ git diff --cached # difference between HEAD and the index; what1056 # would be commited if you ran "commit" now.1057$ git diff # difference between the index file and your1058 # working directory; changes that would not1059 # be included if you ran "commit" now.1060$ git diff HEAD # difference between HEAD and working tree; what1061 # would be committed if you ran "commit -a" now.1062$ git status # a brief per-file summary of the above.1063-------------------------------------------------10641065[[creating-good-commit-messages]]1066Creating good commit messages1067-----------------------------10681069Though not required, it's a good idea to begin the commit message1070with a single short (less than 50 character) line summarizing the1071change, followed by a blank line and then a more thorough1072description. Tools that turn commits into email, for example, use1073the first line on the Subject line and the rest of the commit in the1074body.10751076[[how-to-merge]]1077How to merge1078------------10791080You can rejoin two diverging branches of development using1081gitlink:git-merge[1]:10821083-------------------------------------------------1084$ git merge branchname1085-------------------------------------------------10861087merges the development in the branch "branchname" into the current1088branch. If there are conflicts--for example, if the same file is1089modified in two different ways in the remote branch and the local1090branch--then you are warned; the output may look something like this:10911092-------------------------------------------------1093$ git merge next1094 100% (4/4) done1095Auto-merged file.txt1096CONFLICT (content): Merge conflict in file.txt1097Automatic merge failed; fix conflicts and then commit the result.1098-------------------------------------------------10991100Conflict markers are left in the problematic files, and after1101you resolve the conflicts manually, you can update the index1102with the contents and run git commit, as you normally would when1103creating a new file.11041105If you examine the resulting commit using gitk, you will see that it1106has two parents, one pointing to the top of the current branch, and1107one to the top of the other branch.11081109[[resolving-a-merge]]1110Resolving a merge1111-----------------11121113When a merge isn't resolved automatically, git leaves the index and1114the working tree in a special state that gives you all the1115information you need to help resolve the merge.11161117Files with conflicts are marked specially in the index, so until you1118resolve the problem and update the index, gitlink:git-commit[1] will1119fail:11201121-------------------------------------------------1122$ git commit1123file.txt: needs merge1124-------------------------------------------------11251126Also, gitlink:git-status[1] will list those files as "unmerged", and the1127files with conflicts will have conflict markers added, like this:11281129-------------------------------------------------1130<<<<<<< HEAD:file.txt1131Hello world1132=======1133Goodbye1134>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt1135-------------------------------------------------11361137All you need to do is edit the files to resolve the conflicts, and then11381139-------------------------------------------------1140$ git add file.txt1141$ git commit1142-------------------------------------------------11431144Note that the commit message will already be filled in for you with1145some information about the merge. Normally you can just use this1146default message unchanged, but you may add additional commentary of1147your own if desired.11481149The above is all you need to know to resolve a simple merge. But git1150also provides more information to help resolve conflicts:11511152[[conflict-resolution]]1153Getting conflict-resolution help during a merge1154~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~11551156All of the changes that git was able to merge automatically are1157already added to the index file, so gitlink:git-diff[1] shows only1158the conflicts. It uses an unusual syntax:11591160-------------------------------------------------1161$ git diff1162diff --cc file.txt1163index 802992c,2b60207..00000001164--- a/file.txt1165+++ b/file.txt1166@@@ -1,1 -1,1 +1,5 @@@1167++<<<<<<< HEAD:file.txt1168 +Hello world1169++=======1170+ Goodbye1171++>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt1172-------------------------------------------------11731174Recall that the commit which will be commited after we resolve this1175conflict will have two parents instead of the usual one: one parent1176will be HEAD, the tip of the current branch; the other will be the1177tip of the other branch, which is stored temporarily in MERGE_HEAD.11781179During the merge, the index holds three versions of each file. Each of1180these three "file stages" represents a different version of the file:11811182-------------------------------------------------1183$ git show :1:file.txt # the file in a common ancestor of both branches1184$ git show :2:file.txt # the version from HEAD, but including any1185 # nonconflicting changes from MERGE_HEAD1186$ git show :3:file.txt # the version from MERGE_HEAD, but including any1187 # nonconflicting changes from HEAD.1188-------------------------------------------------11891190Since the stage 2 and stage 3 versions have already been updated with1191nonconflicting changes, the only remaining differences between them are1192the important ones; thus gitlink:git-diff[1] can use the information in1193the index to show only those conflicts.11941195The diff above shows the differences between the working-tree version of1196file.txt and the stage 2 and stage 3 versions. So instead of preceding1197each line by a single "+" or "-", it now uses two columns: the first1198column is used for differences between the first parent and the working1199directory copy, and the second for differences between the second parent1200and the working directory copy. (See the "COMBINED DIFF FORMAT" section1201of gitlink:git-diff-files[1] for a details of the format.)12021203After resolving the conflict in the obvious way (but before updating the1204index), the diff will look like:12051206-------------------------------------------------1207$ git diff1208diff --cc file.txt1209index 802992c,2b60207..00000001210--- a/file.txt1211+++ b/file.txt1212@@@ -1,1 -1,1 +1,1 @@@1213- Hello world1214 -Goodbye1215++Goodbye world1216-------------------------------------------------12171218This shows that our resolved version deleted "Hello world" from the1219first parent, deleted "Goodbye" from the second parent, and added1220"Goodbye world", which was previously absent from both.12211222Some special diff options allow diffing the working directory against1223any of these stages:12241225-------------------------------------------------1226$ git diff -1 file.txt # diff against stage 11227$ git diff --base file.txt # same as the above1228$ git diff -2 file.txt # diff against stage 21229$ git diff --ours file.txt # same as the above1230$ git diff -3 file.txt # diff against stage 31231$ git diff --theirs file.txt # same as the above.1232-------------------------------------------------12331234The gitlink:git-log[1] and gitk[1] commands also provide special help1235for merges:12361237-------------------------------------------------1238$ git log --merge1239$ gitk --merge1240-------------------------------------------------12411242These will display all commits which exist only on HEAD or on1243MERGE_HEAD, and which touch an unmerged file.12441245You may also use gitlink:git-mergetool[1], which lets you merge the1246unmerged files using external tools such as emacs or kdiff3.12471248Each time you resolve the conflicts in a file and update the index:12491250-------------------------------------------------1251$ git add file.txt1252-------------------------------------------------12531254the different stages of that file will be "collapsed", after which1255git-diff will (by default) no longer show diffs for that file.12561257[[undoing-a-merge]]1258Undoing a merge1259---------------12601261If you get stuck and decide to just give up and throw the whole mess1262away, you can always return to the pre-merge state with12631264-------------------------------------------------1265$ git reset --hard HEAD1266-------------------------------------------------12671268Or, if you've already commited the merge that you want to throw away,12691270-------------------------------------------------1271$ git reset --hard ORIG_HEAD1272-------------------------------------------------12731274However, this last command can be dangerous in some cases--never1275throw away a commit you have already committed if that commit may1276itself have been merged into another branch, as doing so may confuse1277further merges.12781279[[fast-forwards]]1280Fast-forward merges1281-------------------12821283There is one special case not mentioned above, which is treated1284differently. Normally, a merge results in a merge commit, with two1285parents, one pointing at each of the two lines of development that1286were merged.12871288However, if the current branch is a descendant of the other--so every1289commit present in the one is already contained in the other--then git1290just performs a "fast forward"; the head of the current branch is moved1291forward to point at the head of the merged-in branch, without any new1292commits being created.12931294[[fixing-mistakes]]1295Fixing mistakes1296---------------12971298If you've messed up the working tree, but haven't yet committed your1299mistake, you can return the entire working tree to the last committed1300state with13011302-------------------------------------------------1303$ git reset --hard HEAD1304-------------------------------------------------13051306If you make a commit that you later wish you hadn't, there are two1307fundamentally different ways to fix the problem:13081309 1. You can create a new commit that undoes whatever was done1310 by the previous commit. This is the correct thing if your1311 mistake has already been made public.13121313 2. You can go back and modify the old commit. You should1314 never do this if you have already made the history public;1315 git does not normally expect the "history" of a project to1316 change, and cannot correctly perform repeated merges from1317 a branch that has had its history changed.13181319[[reverting-a-commit]]1320Fixing a mistake with a new commit1321~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~13221323Creating a new commit that reverts an earlier change is very easy;1324just pass the gitlink:git-revert[1] command a reference to the bad1325commit; for example, to revert the most recent commit:13261327-------------------------------------------------1328$ git revert HEAD1329-------------------------------------------------13301331This will create a new commit which undoes the change in HEAD. You1332will be given a chance to edit the commit message for the new commit.13331334You can also revert an earlier change, for example, the next-to-last:13351336-------------------------------------------------1337$ git revert HEAD^1338-------------------------------------------------13391340In this case git will attempt to undo the old change while leaving1341intact any changes made since then. If more recent changes overlap1342with the changes to be reverted, then you will be asked to fix1343conflicts manually, just as in the case of <<resolving-a-merge,1344resolving a merge>>.13451346[[fixing-a-mistake-by-editing-history]]1347Fixing a mistake by editing history1348~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~13491350If the problematic commit is the most recent commit, and you have not1351yet made that commit public, then you may just1352<<undoing-a-merge,destroy it using git-reset>>.13531354Alternatively, you1355can edit the working directory and update the index to fix your1356mistake, just as if you were going to <<how-to-make-a-commit,create a1357new commit>>, then run13581359-------------------------------------------------1360$ git commit --amend1361-------------------------------------------------13621363which will replace the old commit by a new commit incorporating your1364changes, giving you a chance to edit the old commit message first.13651366Again, you should never do this to a commit that may already have1367been merged into another branch; use gitlink:git-revert[1] instead in1368that case.13691370It is also possible to edit commits further back in the history, but1371this is an advanced topic to be left for1372<<cleaning-up-history,another chapter>>.13731374[[checkout-of-path]]1375Checking out an old version of a file1376~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~13771378In the process of undoing a previous bad change, you may find it1379useful to check out an older version of a particular file using1380gitlink:git-checkout[1]. We've used git checkout before to switch1381branches, but it has quite different behavior if it is given a path1382name: the command13831384-------------------------------------------------1385$ git checkout HEAD^ path/to/file1386-------------------------------------------------13871388replaces path/to/file by the contents it had in the commit HEAD^, and1389also updates the index to match. It does not change branches.13901391If you just want to look at an old version of the file, without1392modifying the working directory, you can do that with1393gitlink:git-show[1]:13941395-------------------------------------------------1396$ git show HEAD^:path/to/file1397-------------------------------------------------13981399which will display the given version of the file.14001401[[ensuring-good-performance]]1402Ensuring good performance1403-------------------------14041405On large repositories, git depends on compression to keep the history1406information from taking up to much space on disk or in memory.14071408This compression is not performed automatically. Therefore you1409should occasionally run gitlink:git-gc[1]:14101411-------------------------------------------------1412$ git gc1413-------------------------------------------------14141415to recompress the archive. This can be very time-consuming, so1416you may prefer to run git-gc when you are not doing other work.141714181419[[ensuring-reliability]]1420Ensuring reliability1421--------------------14221423[[checking-for-corruption]]1424Checking the repository for corruption1425~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~14261427The gitlink:git-fsck[1] command runs a number of self-consistency checks1428on the repository, and reports on any problems. This may take some1429time. The most common warning by far is about "dangling" objects:14301431-------------------------------------------------1432$ git fsck1433dangling commit 7281251ddd2a61e38657c827739c57015671a6b31434dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a631435dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b51436dangling blob 218761f9d90712d37a9c5e36f406f92202db07eb1437dangling commit bf093535a34a4d35731aa2bd90fe6b176302f14f1438dangling commit 8e4bec7f2ddaa268bef999853c25755452100f8e1439dangling tree d50bb86186bf27b681d25af89d3b5b68382e40851440dangling tree b24c2473f1fd3d91352a624795be026d64c8841f1441...1442-------------------------------------------------14431444Dangling objects are not a problem. At worst they may take up a little1445extra disk space. They can sometimes provide a last-resort method of1446recovery lost work--see <<dangling-objects>> for details. However, if1447you want, you may remove them with gitlink:git-prune[1] or the --prune1448option to gitlink:git-gc[1]:14491450-------------------------------------------------1451$ git gc --prune1452-------------------------------------------------14531454This may be time-consuming. Unlike most other git operations (including1455git-gc when run without any options), it is not safe to prune while1456other git operations are in progress in the same repository.14571458[[recovering-lost-changes]]1459Recovering lost changes1460~~~~~~~~~~~~~~~~~~~~~~~14611462[[reflogs]]1463Reflogs1464^^^^^^^14651466Say you modify a branch with gitlink:git-reset[1] --hard, and then1467realize that the branch was the only reference you had to that point in1468history.14691470Fortunately, git also keeps a log, called a "reflog", of all the1471previous values of each branch. So in this case you can still find the1472old history using, for example, 14731474-------------------------------------------------1475$ git log master@{1}1476-------------------------------------------------14771478This lists the commits reachable from the previous version of the head.1479This syntax can be used to with any git command that accepts a commit,1480not just with git log. Some other examples:14811482-------------------------------------------------1483$ git show master@{2} # See where the branch pointed 2,1484$ git show master@{3} # 3, ... changes ago.1485$ gitk master@{yesterday} # See where it pointed yesterday,1486$ gitk master@{"1 week ago"} # ... or last week1487$ git log --walk-reflogs master # show reflog entries for master1488-------------------------------------------------14891490A separate reflog is kept for the HEAD, so14911492-------------------------------------------------1493$ git show HEAD@{"1 week ago"}1494-------------------------------------------------14951496will show what HEAD pointed to one week ago, not what the current branch1497pointed to one week ago. This allows you to see the history of what1498you've checked out.14991500The reflogs are kept by default for 30 days, after which they may be1501pruned. See gitlink:git-reflog[1] and gitlink:git-gc[1] to learn1502how to control this pruning, and see the "SPECIFYING REVISIONS"1503section of gitlink:git-rev-parse[1] for details.15041505Note that the reflog history is very different from normal git history.1506While normal history is shared by every repository that works on the1507same project, the reflog history is not shared: it tells you only about1508how the branches in your local repository have changed over time.15091510[[dangling-object-recovery]]1511Examining dangling objects1512^^^^^^^^^^^^^^^^^^^^^^^^^^15131514In some situations the reflog may not be able to save you. For example,1515suppose you delete a branch, then realize you need the history it1516contained. The reflog is also deleted; however, if you have not yet1517pruned the repository, then you may still be able to find the lost1518commits in the dangling objects that git-fsck reports. See1519<<dangling-objects>> for the details.15201521-------------------------------------------------1522$ git fsck1523dangling commit 7281251ddd2a61e38657c827739c57015671a6b31524dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a631525dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b51526...1527-------------------------------------------------15281529You can examine1530one of those dangling commits with, for example,15311532------------------------------------------------1533$ gitk 7281251ddd --not --all1534------------------------------------------------15351536which does what it sounds like: it says that you want to see the commit1537history that is described by the dangling commit(s), but not the1538history that is described by all your existing branches and tags. Thus1539you get exactly the history reachable from that commit that is lost.1540(And notice that it might not be just one commit: we only report the1541"tip of the line" as being dangling, but there might be a whole deep1542and complex commit history that was dropped.)15431544If you decide you want the history back, you can always create a new1545reference pointing to it, for example, a new branch:15461547------------------------------------------------1548$ git branch recovered-branch 7281251ddd 1549------------------------------------------------15501551Other types of dangling objects (blobs and trees) are also possible, and1552dangling objects can arise in other situations.155315541555[[sharing-development]]1556Sharing development with others1557===============================15581559[[getting-updates-with-git-pull]]1560Getting updates with git pull1561-----------------------------15621563After you clone a repository and make a few changes of your own, you1564may wish to check the original repository for updates and merge them1565into your own work.15661567We have already seen <<Updating-a-repository-with-git-fetch,how to1568keep remote tracking branches up to date>> with gitlink:git-fetch[1],1569and how to merge two branches. So you can merge in changes from the1570original repository's master branch with:15711572-------------------------------------------------1573$ git fetch1574$ git merge origin/master1575-------------------------------------------------15761577However, the gitlink:git-pull[1] command provides a way to do this in1578one step:15791580-------------------------------------------------1581$ git pull origin master1582-------------------------------------------------15831584In fact, "origin" is normally the default repository to pull from,1585and the default branch is normally the HEAD of the remote repository,1586so often you can accomplish the above with just15871588-------------------------------------------------1589$ git pull1590-------------------------------------------------15911592See the descriptions of the branch.<name>.remote and branch.<name>.merge1593options in gitlink:git-config[1] to learn how to control these defaults1594depending on the current branch. Also note that the --track option to1595gitlink:git-branch[1] and gitlink:git-checkout[1] can be used to1596automatically set the default remote branch to pull from at the time1597that a branch is created:15981599-------------------------------------------------1600$ git checkout --track -b origin/maint maint1601-------------------------------------------------16021603In addition to saving you keystrokes, "git pull" also helps you by1604producing a default commit message documenting the branch and1605repository that you pulled from.16061607(But note that no such commit will be created in the case of a1608<<fast-forwards,fast forward>>; instead, your branch will just be1609updated to point to the latest commit from the upstream branch.)16101611The git-pull command can also be given "." as the "remote" repository,1612in which case it just merges in a branch from the current repository; so1613the commands16141615-------------------------------------------------1616$ git pull . branch1617$ git merge branch1618-------------------------------------------------16191620are roughly equivalent. The former is actually very commonly used.16211622[[submitting-patches]]1623Submitting patches to a project1624-------------------------------16251626If you just have a few changes, the simplest way to submit them may1627just be to send them as patches in email:16281629First, use gitlink:git-format-patch[1]; for example:16301631-------------------------------------------------1632$ git format-patch origin1633-------------------------------------------------16341635will produce a numbered series of files in the current directory, one1636for each patch in the current branch but not in origin/HEAD.16371638You can then import these into your mail client and send them by1639hand. However, if you have a lot to send at once, you may prefer to1640use the gitlink:git-send-email[1] script to automate the process.1641Consult the mailing list for your project first to determine how they1642prefer such patches be handled.16431644[[importing-patches]]1645Importing patches to a project1646------------------------------16471648Git also provides a tool called gitlink:git-am[1] (am stands for1649"apply mailbox"), for importing such an emailed series of patches.1650Just save all of the patch-containing messages, in order, into a1651single mailbox file, say "patches.mbox", then run16521653-------------------------------------------------1654$ git am -3 patches.mbox1655-------------------------------------------------16561657Git will apply each patch in order; if any conflicts are found, it1658will stop, and you can fix the conflicts as described in1659"<<resolving-a-merge,Resolving a merge>>". (The "-3" option tells1660git to perform a merge; if you would prefer it just to abort and1661leave your tree and index untouched, you may omit that option.)16621663Once the index is updated with the results of the conflict1664resolution, instead of creating a new commit, just run16651666-------------------------------------------------1667$ git am --resolved1668-------------------------------------------------16691670and git will create the commit for you and continue applying the1671remaining patches from the mailbox.16721673The final result will be a series of commits, one for each patch in1674the original mailbox, with authorship and commit log message each1675taken from the message containing each patch.16761677[[public-repositories]]1678Public git repositories1679-----------------------16801681Another way to submit changes to a project is to tell the maintainer of1682that project to pull the changes from your repository using git-pull[1].1683In the section "<<getting-updates-with-git-pull, Getting updates with1684git pull>>" we described this as a way to get updates from the "main"1685repository, but it works just as well in the other direction.16861687If you and the maintainer both have accounts on the same machine, then1688you can just pull changes from each other's repositories directly;1689commands that accepts repository URLs as arguments will also accept a1690local directory name:16911692-------------------------------------------------1693$ git clone /path/to/repository1694$ git pull /path/to/other/repository1695-------------------------------------------------16961697However, the more common way to do this is to maintain a separate public1698repository (usually on a different host) for others to pull changes1699from. This is usually more convenient, and allows you to cleanly1700separate private work in progress from publicly visible work.17011702You will continue to do your day-to-day work in your personal1703repository, but periodically "push" changes from your personal1704repository into your public repository, allowing other developers to1705pull from that repository. So the flow of changes, in a situation1706where there is one other developer with a public repository, looks1707like this:17081709 you push1710 your personal repo ------------------> your public repo1711 ^ |1712 | |1713 | you pull | they pull1714 | |1715 | |1716 | they push V1717 their public repo <------------------- their repo17181719[[setting-up-a-public-repository]]1720Setting up a public repository1721~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~17221723Assume your personal repository is in the directory ~/proj. We1724first create a new clone of the repository and tell git-daemon that it1725is meant to be public:17261727-------------------------------------------------1728$ git clone --bare ~/proj proj.git1729$ touch proj.git/git-daemon-export-ok1730-------------------------------------------------17311732The resulting directory proj.git contains a "bare" git repository--it is1733just the contents of the ".git" directory, without any files checked out1734around it.17351736Next, copy proj.git to the server where you plan to host the1737public repository. You can use scp, rsync, or whatever is most1738convenient.17391740[[exporting-via-git]]1741Exporting a git repository via the git protocol1742~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~17431744This is the preferred method.17451746If someone else administers the server, they should tell you what1747directory to put the repository in, and what git:// url it will appear1748at. You can then skip to the section1749"<<pushing-changes-to-a-public-repository,Pushing changes to a public1750repository>>", below.17511752Otherwise, all you need to do is start gitlink:git-daemon[1]; it will1753listen on port 9418. By default, it will allow access to any directory1754that looks like a git directory and contains the magic file1755git-daemon-export-ok. Passing some directory paths as git-daemon1756arguments will further restrict the exports to those paths.17571758You can also run git-daemon as an inetd service; see the1759gitlink:git-daemon[1] man page for details. (See especially the1760examples section.)17611762[[exporting-via-http]]1763Exporting a git repository via http1764~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~17651766The git protocol gives better performance and reliability, but on a1767host with a web server set up, http exports may be simpler to set up.17681769All you need to do is place the newly created bare git repository in1770a directory that is exported by the web server, and make some1771adjustments to give web clients some extra information they need:17721773-------------------------------------------------1774$ mv proj.git /home/you/public_html/proj.git1775$ cd proj.git1776$ git --bare update-server-info1777$ chmod a+x hooks/post-update1778-------------------------------------------------17791780(For an explanation of the last two lines, see1781gitlink:git-update-server-info[1], and the documentation1782link:hooks.html[Hooks used by git].)17831784Advertise the url of proj.git. Anybody else should then be able to1785clone or pull from that url, for example with a commandline like:17861787-------------------------------------------------1788$ git clone http://yourserver.com/~you/proj.git1789-------------------------------------------------17901791(See also1792link:howto/setup-git-server-over-http.txt[setup-git-server-over-http]1793for a slightly more sophisticated setup using WebDAV which also1794allows pushing over http.)17951796[[pushing-changes-to-a-public-repository]]1797Pushing changes to a public repository1798~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~17991800Note that the two techniques outlined above (exporting via1801<<exporting-via-http,http>> or <<exporting-via-git,git>>) allow other1802maintainers to fetch your latest changes, but they do not allow write1803access, which you will need to update the public repository with the1804latest changes created in your private repository.18051806The simplest way to do this is using gitlink:git-push[1] and ssh; to1807update the remote branch named "master" with the latest state of your1808branch named "master", run18091810-------------------------------------------------1811$ git push ssh://yourserver.com/~you/proj.git master:master1812-------------------------------------------------18131814or just18151816-------------------------------------------------1817$ git push ssh://yourserver.com/~you/proj.git master1818-------------------------------------------------18191820As with git-fetch, git-push will complain if this does not result in1821a <<fast-forwards,fast forward>>. Normally this is a sign of1822something wrong. However, if you are sure you know what you're1823doing, you may force git-push to perform the update anyway by1824proceeding the branch name by a plus sign:18251826-------------------------------------------------1827$ git push ssh://yourserver.com/~you/proj.git +master1828-------------------------------------------------18291830As with git-fetch, you may also set up configuration options to1831save typing; so, for example, after18321833-------------------------------------------------1834$ cat >>.git/config <<EOF1835[remote "public-repo"]1836 url = ssh://yourserver.com/~you/proj.git1837EOF1838-------------------------------------------------18391840you should be able to perform the above push with just18411842-------------------------------------------------1843$ git push public-repo master1844-------------------------------------------------18451846See the explanations of the remote.<name>.url, branch.<name>.remote,1847and remote.<name>.push options in gitlink:git-config[1] for1848details.18491850[[setting-up-a-shared-repository]]1851Setting up a shared repository1852~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~18531854Another way to collaborate is by using a model similar to that1855commonly used in CVS, where several developers with special rights1856all push to and pull from a single shared repository. See1857link:cvs-migration.html[git for CVS users] for instructions on how to1858set this up.18591860[[setting-up-gitweb]]1861Allowing web browsing of a repository1862~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~18631864The gitweb cgi script provides users an easy way to browse your1865project's files and history without having to install git; see the file1866gitweb/INSTALL in the git source tree for instructions on setting it up.18671868[[sharing-development-examples]]1869Examples1870--------18711872[[maintaining-topic-branches]]1873Maintaining topic branches for a Linux subsystem maintainer1874~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~18751876This describes how Tony Luck uses git in his role as maintainer of the1877IA64 architecture for the Linux kernel.18781879He uses two public branches:18801881 - A "test" tree into which patches are initially placed so that they1882 can get some exposure when integrated with other ongoing development.1883 This tree is available to Andrew for pulling into -mm whenever he1884 wants.18851886 - A "release" tree into which tested patches are moved for final sanity1887 checking, and as a vehicle to send them upstream to Linus (by sending1888 him a "please pull" request.)18891890He also uses a set of temporary branches ("topic branches"), each1891containing a logical grouping of patches.18921893To set this up, first create your work tree by cloning Linus's public1894tree:18951896-------------------------------------------------1897$ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git work1898$ cd work1899-------------------------------------------------19001901Linus's tree will be stored in the remote branch named origin/master,1902and can be updated using gitlink:git-fetch[1]; you can track other1903public trees using gitlink:git-remote[1] to set up a "remote" and1904git-fetch[1] to keep them up-to-date; see <<repositories-and-branches>>.19051906Now create the branches in which you are going to work; these start out1907at the current tip of origin/master branch, and should be set up (using1908the --track option to gitlink:git-branch[1]) to merge changes in from1909Linus by default.19101911-------------------------------------------------1912$ git branch --track test origin/master1913$ git branch --track release origin/master1914-------------------------------------------------19151916These can be easily kept up to date using gitlink:git-pull[1]19171918-------------------------------------------------1919$ git checkout test && git pull1920$ git checkout release && git pull1921-------------------------------------------------19221923Important note! If you have any local changes in these branches, then1924this merge will create a commit object in the history (with no local1925changes git will simply do a "Fast forward" merge). Many people dislike1926the "noise" that this creates in the Linux history, so you should avoid1927doing this capriciously in the "release" branch, as these noisy commits1928will become part of the permanent history when you ask Linus to pull1929from the release branch.19301931A few configuration variables (see gitlink:git-config[1]) can1932make it easy to push both branches to your public tree. (See1933<<setting-up-a-public-repository>>.)19341935-------------------------------------------------1936$ cat >> .git/config <<EOF1937[remote "mytree"]1938 url = master.kernel.org:/pub/scm/linux/kernel/git/aegl/linux-2.6.git1939 push = release1940 push = test1941EOF1942-------------------------------------------------19431944Then you can push both the test and release trees using1945gitlink:git-push[1]:19461947-------------------------------------------------1948$ git push mytree1949-------------------------------------------------19501951or push just one of the test and release branches using:19521953-------------------------------------------------1954$ git push mytree test1955-------------------------------------------------19561957or19581959-------------------------------------------------1960$ git push mytree release1961-------------------------------------------------19621963Now to apply some patches from the community. Think of a short1964snappy name for a branch to hold this patch (or related group of1965patches), and create a new branch from the current tip of Linus's1966branch:19671968-------------------------------------------------1969$ git checkout -b speed-up-spinlocks origin1970-------------------------------------------------19711972Now you apply the patch(es), run some tests, and commit the change(s). If1973the patch is a multi-part series, then you should apply each as a separate1974commit to this branch.19751976-------------------------------------------------1977$ ... patch ... test ... commit [ ... patch ... test ... commit ]*1978-------------------------------------------------19791980When you are happy with the state of this change, you can pull it into the1981"test" branch in preparation to make it public:19821983-------------------------------------------------1984$ git checkout test && git pull . speed-up-spinlocks1985-------------------------------------------------19861987It is unlikely that you would have any conflicts here ... but you might if you1988spent a while on this step and had also pulled new versions from upstream.19891990Some time later when enough time has passed and testing done, you can pull the1991same branch into the "release" tree ready to go upstream. This is where you1992see the value of keeping each patch (or patch series) in its own branch. It1993means that the patches can be moved into the "release" tree in any order.19941995-------------------------------------------------1996$ git checkout release && git pull . speed-up-spinlocks1997-------------------------------------------------19981999After a while, you will have a number of branches, and despite the2000well chosen names you picked for each of them, you may forget what2001they are for, or what status they are in. To get a reminder of what2002changes are in a specific branch, use:20032004-------------------------------------------------2005$ git log linux..branchname | git-shortlog2006-------------------------------------------------20072008To see whether it has already been merged into the test or release branches2009use:20102011-------------------------------------------------2012$ git log test..branchname2013-------------------------------------------------20142015or20162017-------------------------------------------------2018$ git log release..branchname2019-------------------------------------------------20202021(If this branch has not yet been merged you will see some log entries.2022If it has been merged, then there will be no output.)20232024Once a patch completes the great cycle (moving from test to release,2025then pulled by Linus, and finally coming back into your local2026"origin/master" branch) the branch for this change is no longer needed.2027You detect this when the output from:20282029-------------------------------------------------2030$ git log origin..branchname2031-------------------------------------------------20322033is empty. At this point the branch can be deleted:20342035-------------------------------------------------2036$ git branch -d branchname2037-------------------------------------------------20382039Some changes are so trivial that it is not necessary to create a separate2040branch and then merge into each of the test and release branches. For2041these changes, just apply directly to the "release" branch, and then2042merge that into the "test" branch.20432044To create diffstat and shortlog summaries of changes to include in a "please2045pull" request to Linus you can use:20462047-------------------------------------------------2048$ git diff --stat origin..release2049-------------------------------------------------20502051and20522053-------------------------------------------------2054$ git log -p origin..release | git shortlog2055-------------------------------------------------20562057Here are some of the scripts that simplify all this even further.20582059-------------------------------------------------2060==== update script ====2061# Update a branch in my GIT tree. If the branch to be updated2062# is origin, then pull from kernel.org. Otherwise merge2063# origin/master branch into test|release branch20642065case "$1" in2066test|release)2067 git checkout $1 && git pull . origin2068 ;;2069origin)2070 before=$(cat .git/refs/remotes/origin/master)2071 git fetch origin2072 after=$(cat .git/refs/remotes/origin/master)2073 if [ $before != $after ]2074 then2075 git log $before..$after | git shortlog2076 fi2077 ;;2078*)2079 echo "Usage: $0 origin|test|release" 1>&22080 exit 12081 ;;2082esac2083-------------------------------------------------20842085-------------------------------------------------2086==== merge script ====2087# Merge a branch into either the test or release branch20882089pname=$020902091usage()2092{2093 echo "Usage: $pname branch test|release" 1>&22094 exit 12095}20962097if [ ! -f .git/refs/heads/"$1" ]2098then2099 echo "Can't see branch <$1>" 1>&22100 usage2101fi21022103case "$2" in2104test|release)2105 if [ $(git log $2..$1 | wc -c) -eq 0 ]2106 then2107 echo $1 already merged into $2 1>&22108 exit 12109 fi2110 git checkout $2 && git pull . $12111 ;;2112*)2113 usage2114 ;;2115esac2116-------------------------------------------------21172118-------------------------------------------------2119==== status script ====2120# report on status of my ia64 GIT tree21212122gb=$(tput setab 2)2123rb=$(tput setab 1)2124restore=$(tput setab 9)21252126if [ `git rev-list test..release | wc -c` -gt 0 ]2127then2128 echo $rb Warning: commits in release that are not in test $restore2129 git log test..release2130fi21312132for branch in `ls .git/refs/heads`2133do2134 if [ $branch = test -o $branch = release ]2135 then2136 continue2137 fi21382139 echo -n $gb ======= $branch ====== $restore " "2140 status=2141 for ref in test release origin/master2142 do2143 if [ `git rev-list $ref..$branch | wc -c` -gt 0 ]2144 then2145 status=$status${ref:0:1}2146 fi2147 done2148 case $status in2149 trl)2150 echo $rb Need to pull into test $restore2151 ;;2152 rl)2153 echo "In test"2154 ;;2155 l)2156 echo "Waiting for linus"2157 ;;2158 "")2159 echo $rb All done $restore2160 ;;2161 *)2162 echo $rb "<$status>" $restore2163 ;;2164 esac2165 git log origin/master..$branch | git shortlog2166done2167-------------------------------------------------216821692170[[cleaning-up-history]]2171Rewriting history and maintaining patch series2172==============================================21732174Normally commits are only added to a project, never taken away or2175replaced. Git is designed with this assumption, and violating it will2176cause git's merge machinery (for example) to do the wrong thing.21772178However, there is a situation in which it can be useful to violate this2179assumption.21802181[[patch-series]]2182Creating the perfect patch series2183---------------------------------21842185Suppose you are a contributor to a large project, and you want to add a2186complicated feature, and to present it to the other developers in a way2187that makes it easy for them to read your changes, verify that they are2188correct, and understand why you made each change.21892190If you present all of your changes as a single patch (or commit), they2191may find that it is too much to digest all at once.21922193If you present them with the entire history of your work, complete with2194mistakes, corrections, and dead ends, they may be overwhelmed.21952196So the ideal is usually to produce a series of patches such that:21972198 1. Each patch can be applied in order.21992200 2. Each patch includes a single logical change, together with a2201 message explaining the change.22022203 3. No patch introduces a regression: after applying any initial2204 part of the series, the resulting project still compiles and2205 works, and has no bugs that it didn't have before.22062207 4. The complete series produces the same end result as your own2208 (probably much messier!) development process did.22092210We will introduce some tools that can help you do this, explain how to2211use them, and then explain some of the problems that can arise because2212you are rewriting history.22132214[[using-git-rebase]]2215Keeping a patch series up to date using git-rebase2216--------------------------------------------------22172218Suppose that you create a branch "mywork" on a remote-tracking branch2219"origin", and create some commits on top of it:22202221-------------------------------------------------2222$ git checkout -b mywork origin2223$ vi file.txt2224$ git commit2225$ vi otherfile.txt2226$ git commit2227...2228-------------------------------------------------22292230You have performed no merges into mywork, so it is just a simple linear2231sequence of patches on top of "origin":22322233................................................2234 o--o--o <-- origin2235 \2236 o--o--o <-- mywork2237................................................22382239Some more interesting work has been done in the upstream project, and2240"origin" has advanced:22412242................................................2243 o--o--O--o--o--o <-- origin2244 \2245 a--b--c <-- mywork2246................................................22472248At this point, you could use "pull" to merge your changes back in;2249the result would create a new merge commit, like this:22502251................................................2252 o--o--O--o--o--o <-- origin2253 \ \2254 a--b--c--m <-- mywork2255................................................22562257However, if you prefer to keep the history in mywork a simple series of2258commits without any merges, you may instead choose to use2259gitlink:git-rebase[1]:22602261-------------------------------------------------2262$ git checkout mywork2263$ git rebase origin2264-------------------------------------------------22652266This will remove each of your commits from mywork, temporarily saving2267them as patches (in a directory named ".dotest"), update mywork to2268point at the latest version of origin, then apply each of the saved2269patches to the new mywork. The result will look like:227022712272................................................2273 o--o--O--o--o--o <-- origin2274 \2275 a'--b'--c' <-- mywork2276................................................22772278In the process, it may discover conflicts. In that case it will stop2279and allow you to fix the conflicts; after fixing conflicts, use "git2280add" to update the index with those contents, and then, instead of2281running git-commit, just run22822283-------------------------------------------------2284$ git rebase --continue2285-------------------------------------------------22862287and git will continue applying the rest of the patches.22882289At any point you may use the --abort option to abort this process and2290return mywork to the state it had before you started the rebase:22912292-------------------------------------------------2293$ git rebase --abort2294-------------------------------------------------22952296[[modifying-one-commit]]2297Modifying a single commit2298-------------------------22992300We saw in <<fixing-a-mistake-by-editing-history>> that you can replace the2301most recent commit using23022303-------------------------------------------------2304$ git commit --amend2305-------------------------------------------------23062307which will replace the old commit by a new commit incorporating your2308changes, giving you a chance to edit the old commit message first.23092310You can also use a combination of this and gitlink:git-rebase[1] to edit2311commits further back in your history. First, tag the problematic commit with23122313-------------------------------------------------2314$ git tag bad mywork~52315-------------------------------------------------23162317(Either gitk or git-log may be useful for finding the commit.)23182319Then check out that commit, edit it, and rebase the rest of the series2320on top of it (note that we could check out the commit on a temporary2321branch, but instead we're using a <<detached-head,detached head>>):23222323-------------------------------------------------2324$ git checkout bad2325$ # make changes here and update the index2326$ git commit --amend2327$ git rebase --onto HEAD bad mywork2328-------------------------------------------------23292330When you're done, you'll be left with mywork checked out, with the top2331patches on mywork reapplied on top of your modified commit. You can2332then clean up with23332334-------------------------------------------------2335$ git tag -d bad2336-------------------------------------------------23372338Note that the immutable nature of git history means that you haven't really2339"modified" existing commits; instead, you have replaced the old commits with2340new commits having new object names.23412342[[reordering-patch-series]]2343Reordering or selecting from a patch series2344-------------------------------------------23452346Given one existing commit, the gitlink:git-cherry-pick[1] command2347allows you to apply the change introduced by that commit and create a2348new commit that records it. So, for example, if "mywork" points to a2349series of patches on top of "origin", you might do something like:23502351-------------------------------------------------2352$ git checkout -b mywork-new origin2353$ gitk origin..mywork &2354-------------------------------------------------23552356And browse through the list of patches in the mywork branch using gitk,2357applying them (possibly in a different order) to mywork-new using2358cherry-pick, and possibly modifying them as you go using commit2359--amend.23602361Another technique is to use git-format-patch to create a series of2362patches, then reset the state to before the patches:23632364-------------------------------------------------2365$ git format-patch origin2366$ git reset --hard origin2367-------------------------------------------------23682369Then modify, reorder, or eliminate patches as preferred before applying2370them again with gitlink:git-am[1].23712372[[patch-series-tools]]2373Other tools2374-----------23752376There are numerous other tools, such as stgit, which exist for the2377purpose of maintaining a patch series. These are outside of the scope of2378this manual.23792380[[problems-with-rewriting-history]]2381Problems with rewriting history2382-------------------------------23832384The primary problem with rewriting the history of a branch has to do2385with merging. Suppose somebody fetches your branch and merges it into2386their branch, with a result something like this:23872388................................................2389 o--o--O--o--o--o <-- origin2390 \ \2391 t--t--t--m <-- their branch:2392................................................23932394Then suppose you modify the last three commits:23952396................................................2397 o--o--o <-- new head of origin2398 /2399 o--o--O--o--o--o <-- old head of origin2400................................................24012402If we examined all this history together in one repository, it will2403look like:24042405................................................2406 o--o--o <-- new head of origin2407 /2408 o--o--O--o--o--o <-- old head of origin2409 \ \2410 t--t--t--m <-- their branch:2411................................................24122413Git has no way of knowing that the new head is an updated version of2414the old head; it treats this situation exactly the same as it would if2415two developers had independently done the work on the old and new heads2416in parallel. At this point, if someone attempts to merge the new head2417in to their branch, git will attempt to merge together the two (old and2418new) lines of development, instead of trying to replace the old by the2419new. The results are likely to be unexpected.24202421You may still choose to publish branches whose history is rewritten,2422and it may be useful for others to be able to fetch those branches in2423order to examine or test them, but they should not attempt to pull such2424branches into their own work.24252426For true distributed development that supports proper merging,2427published branches should never be rewritten.24282429[[advanced-branch-management]]2430Advanced branch management2431==========================24322433[[fetching-individual-branches]]2434Fetching individual branches2435----------------------------24362437Instead of using gitlink:git-remote[1], you can also choose just2438to update one branch at a time, and to store it locally under an2439arbitrary name:24402441-------------------------------------------------2442$ git fetch origin todo:my-todo-work2443-------------------------------------------------24442445The first argument, "origin", just tells git to fetch from the2446repository you originally cloned from. The second argument tells git2447to fetch the branch named "todo" from the remote repository, and to2448store it locally under the name refs/heads/my-todo-work.24492450You can also fetch branches from other repositories; so24512452-------------------------------------------------2453$ git fetch git://example.com/proj.git master:example-master2454-------------------------------------------------24552456will create a new branch named "example-master" and store in it the2457branch named "master" from the repository at the given URL. If you2458already have a branch named example-master, it will attempt to2459<<fast-forwards,fast-forward>> to the commit given by example.com's2460master branch. In more detail:24612462[[fetch-fast-forwards]]2463git fetch and fast-forwards2464---------------------------24652466In the previous example, when updating an existing branch, "git2467fetch" checks to make sure that the most recent commit on the remote2468branch is a descendant of the most recent commit on your copy of the2469branch before updating your copy of the branch to point at the new2470commit. Git calls this process a <<fast-forwards,fast forward>>.24712472A fast forward looks something like this:24732474................................................2475 o--o--o--o <-- old head of the branch2476 \2477 o--o--o <-- new head of the branch2478................................................247924802481In some cases it is possible that the new head will *not* actually be2482a descendant of the old head. For example, the developer may have2483realized she made a serious mistake, and decided to backtrack,2484resulting in a situation like:24852486................................................2487 o--o--o--o--a--b <-- old head of the branch2488 \2489 o--o--o <-- new head of the branch2490................................................24912492In this case, "git fetch" will fail, and print out a warning.24932494In that case, you can still force git to update to the new head, as2495described in the following section. However, note that in the2496situation above this may mean losing the commits labeled "a" and "b",2497unless you've already created a reference of your own pointing to2498them.24992500[[forcing-fetch]]2501Forcing git fetch to do non-fast-forward updates2502------------------------------------------------25032504If git fetch fails because the new head of a branch is not a2505descendant of the old head, you may force the update with:25062507-------------------------------------------------2508$ git fetch git://example.com/proj.git +master:refs/remotes/example/master2509-------------------------------------------------25102511Note the addition of the "+" sign. Alternatively, you can use the "-f"2512flag to force updates of all the fetched branches, as in:25132514-------------------------------------------------2515$ git fetch -f origin2516-------------------------------------------------25172518Be aware that commits that the old version of example/master pointed at2519may be lost, as we saw in the previous section.25202521[[remote-branch-configuration]]2522Configuring remote branches2523---------------------------25242525We saw above that "origin" is just a shortcut to refer to the2526repository that you originally cloned from. This information is2527stored in git configuration variables, which you can see using2528gitlink:git-config[1]:25292530-------------------------------------------------2531$ git config -l2532core.repositoryformatversion=02533core.filemode=true2534core.logallrefupdates=true2535remote.origin.url=git://git.kernel.org/pub/scm/git/git.git2536remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*2537branch.master.remote=origin2538branch.master.merge=refs/heads/master2539-------------------------------------------------25402541If there are other repositories that you also use frequently, you can2542create similar configuration options to save typing; for example,2543after25442545-------------------------------------------------2546$ git config remote.example.url git://example.com/proj.git2547-------------------------------------------------25482549then the following two commands will do the same thing:25502551-------------------------------------------------2552$ git fetch git://example.com/proj.git master:refs/remotes/example/master2553$ git fetch example master:refs/remotes/example/master2554-------------------------------------------------25552556Even better, if you add one more option:25572558-------------------------------------------------2559$ git config remote.example.fetch master:refs/remotes/example/master2560-------------------------------------------------25612562then the following commands will all do the same thing:25632564-------------------------------------------------2565$ git fetch git://example.com/proj.git master:refs/remotes/example/master2566$ git fetch example master:refs/remotes/example/master2567$ git fetch example2568-------------------------------------------------25692570You can also add a "+" to force the update each time:25712572-------------------------------------------------2573$ git config remote.example.fetch +master:ref/remotes/example/master2574-------------------------------------------------25752576Don't do this unless you're sure you won't mind "git fetch" possibly2577throwing away commits on mybranch.25782579Also note that all of the above configuration can be performed by2580directly editing the file .git/config instead of using2581gitlink:git-config[1].25822583See gitlink:git-config[1] for more details on the configuration2584options mentioned above.258525862587[[git-internals]]2588Git internals2589=============25902591Git depends on two fundamental abstractions: the "object database", and2592the "current directory cache" aka "index".25932594[[the-object-database]]2595The Object Database2596-------------------25972598The object database is literally just a content-addressable collection2599of objects. All objects are named by their content, which is2600approximated by the SHA1 hash of the object itself. Objects may refer2601to other objects (by referencing their SHA1 hash), and so you can2602build up a hierarchy of objects.26032604All objects have a statically determined "type" which is2605determined at object creation time, and which identifies the format of2606the object (i.e. how it is used, and how it can refer to other2607objects). There are currently four different object types: "blob",2608"tree", "commit", and "tag".26092610A <<def_blob_object,"blob" object>> cannot refer to any other object,2611and is, as the name implies, a pure storage object containing some2612user data. It is used to actually store the file data, i.e. a blob2613object is associated with some particular version of some file.26142615A <<def_tree_object,"tree" object>> is an object that ties one or more2616"blob" objects into a directory structure. In addition, a tree object2617can refer to other tree objects, thus creating a directory hierarchy.26182619A <<def_commit_object,"commit" object>> ties such directory hierarchies2620together into a <<def_DAG,directed acyclic graph>> of revisions - each2621"commit" is associated with exactly one tree (the directory hierarchy at2622the time of the commit). In addition, a "commit" refers to one or more2623"parent" commit objects that describe the history of how we arrived at2624that directory hierarchy.26252626As a special case, a commit object with no parents is called the "root"2627commit, and is the point of an initial project commit. Each project2628must have at least one root, and while you can tie several different2629root objects together into one project by creating a commit object which2630has two or more separate roots as its ultimate parents, that's probably2631just going to confuse people. So aim for the notion of "one root object2632per project", even if git itself does not enforce that. 26332634A <<def_tag_object,"tag" object>> symbolically identifies and can be2635used to sign other objects. It contains the identifier and type of2636another object, a symbolic name (of course!) and, optionally, a2637signature.26382639Regardless of object type, all objects share the following2640characteristics: they are all deflated with zlib, and have a header2641that not only specifies their type, but also provides size information2642about the data in the object. It's worth noting that the SHA1 hash2643that is used to name the object is the hash of the original data2644plus this header, so `sha1sum` 'file' does not match the object name2645for 'file'.2646(Historical note: in the dawn of the age of git the hash2647was the sha1 of the 'compressed' object.)26482649As a result, the general consistency of an object can always be tested2650independently of the contents or the type of the object: all objects can2651be validated by verifying that (a) their hashes match the content of the2652file and (b) the object successfully inflates to a stream of bytes that2653forms a sequence of <ascii type without space> + <space> + <ascii decimal2654size> + <byte\0> + <binary object data>. 26552656The structured objects can further have their structure and2657connectivity to other objects verified. This is generally done with2658the `git-fsck` program, which generates a full dependency graph2659of all objects, and verifies their internal consistency (in addition2660to just verifying their superficial consistency through the hash).26612662The object types in some more detail:26632664[[blob-object]]2665Blob Object2666-----------26672668A "blob" object is nothing but a binary blob of data, and doesn't2669refer to anything else. There is no signature or any other2670verification of the data, so while the object is consistent (it 'is'2671indexed by its sha1 hash, so the data itself is certainly correct), it2672has absolutely no other attributes. No name associations, no2673permissions. It is purely a blob of data (i.e. normally "file2674contents").26752676In particular, since the blob is entirely defined by its data, if two2677files in a directory tree (or in multiple different versions of the2678repository) have the same contents, they will share the same blob2679object. The object is totally independent of its location in the2680directory tree, and renaming a file does not change the object that2681file is associated with in any way.26822683A blob is typically created when gitlink:git-update-index[1]2684is run, and its data can be accessed by gitlink:git-cat-file[1].26852686[[tree-object]]2687Tree Object2688-----------26892690The next hierarchical object type is the "tree" object. A tree object2691is a list of mode/name/blob data, sorted by name. Alternatively, the2692mode data may specify a directory mode, in which case instead of2693naming a blob, that name is associated with another TREE object.26942695Like the "blob" object, a tree object is uniquely determined by the2696set contents, and so two separate but identical trees will always2697share the exact same object. This is true at all levels, i.e. it's2698true for a "leaf" tree (which does not refer to any other trees, only2699blobs) as well as for a whole subdirectory.27002701For that reason a "tree" object is just a pure data abstraction: it2702has no history, no signatures, no verification of validity, except2703that since the contents are again protected by the hash itself, we can2704trust that the tree is immutable and its contents never change.27052706So you can trust the contents of a tree to be valid, the same way you2707can trust the contents of a blob, but you don't know where those2708contents 'came' from.27092710Side note on trees: since a "tree" object is a sorted list of2711"filename+content", you can create a diff between two trees without2712actually having to unpack two trees. Just ignore all common parts,2713and your diff will look right. In other words, you can effectively2714(and efficiently) tell the difference between any two random trees by2715O(n) where "n" is the size of the difference, rather than the size of2716the tree.27172718Side note 2 on trees: since the name of a "blob" depends entirely and2719exclusively on its contents (i.e. there are no names or permissions2720involved), you can see trivial renames or permission changes by2721noticing that the blob stayed the same. However, renames with data2722changes need a smarter "diff" implementation.27232724A tree is created with gitlink:git-write-tree[1] and2725its data can be accessed by gitlink:git-ls-tree[1].2726Two trees can be compared with gitlink:git-diff-tree[1].27272728[[commit-object]]2729Commit Object2730-------------27312732The "commit" object is an object that introduces the notion of2733history into the picture. In contrast to the other objects, it2734doesn't just describe the physical state of a tree, it describes how2735we got there, and why.27362737A "commit" is defined by the tree-object that it results in, the2738parent commits (zero, one or more) that led up to that point, and a2739comment on what happened. Again, a commit is not trusted per se:2740the contents are well-defined and "safe" due to the cryptographically2741strong signatures at all levels, but there is no reason to believe2742that the tree is "good" or that the merge information makes sense.2743The parents do not have to actually have any relationship with the2744result, for example.27452746Note on commits: unlike some SCM's, commits do not contain2747rename information or file mode change information. All of that is2748implicit in the trees involved (the result tree, and the result trees2749of the parents), and describing that makes no sense in this idiotic2750file manager.27512752A commit is created with gitlink:git-commit-tree[1] and2753its data can be accessed by gitlink:git-cat-file[1].27542755[[trust]]2756Trust2757-----27582759An aside on the notion of "trust". Trust is really outside the scope2760of "git", but it's worth noting a few things. First off, since2761everything is hashed with SHA1, you 'can' trust that an object is2762intact and has not been messed with by external sources. So the name2763of an object uniquely identifies a known state - just not a state that2764you may want to trust.27652766Furthermore, since the SHA1 signature of a commit refers to the2767SHA1 signatures of the tree it is associated with and the signatures2768of the parent, a single named commit specifies uniquely a whole set2769of history, with full contents. You can't later fake any step of the2770way once you have the name of a commit.27712772So to introduce some real trust in the system, the only thing you need2773to do is to digitally sign just 'one' special note, which includes the2774name of a top-level commit. Your digital signature shows others2775that you trust that commit, and the immutability of the history of2776commits tells others that they can trust the whole history.27772778In other words, you can easily validate a whole archive by just2779sending out a single email that tells the people the name (SHA1 hash)2780of the top commit, and digitally sign that email using something2781like GPG/PGP.27822783To assist in this, git also provides the tag object...27842785[[tag-object]]2786Tag Object2787----------27882789Git provides the "tag" object to simplify creating, managing and2790exchanging symbolic and signed tokens. The "tag" object at its2791simplest simply symbolically identifies another object by containing2792the sha1, type and symbolic name.27932794However it can optionally contain additional signature information2795(which git doesn't care about as long as there's less than 8k of2796it). This can then be verified externally to git.27972798Note that despite the tag features, "git" itself only handles content2799integrity; the trust framework (and signature provision and2800verification) has to come from outside.28012802A tag is created with gitlink:git-mktag[1],2803its data can be accessed by gitlink:git-cat-file[1],2804and the signature can be verified by2805gitlink:git-verify-tag[1].280628072808[[the-index]]2809The "index" aka "Current Directory Cache"2810-----------------------------------------28112812The index is a simple binary file, which contains an efficient2813representation of the contents of a virtual directory. It2814does so by a simple array that associates a set of names, dates,2815permissions and content (aka "blob") objects together. The cache is2816always kept ordered by name, and names are unique (with a few very2817specific rules) at any point in time, but the cache has no long-term2818meaning, and can be partially updated at any time.28192820In particular, the index certainly does not need to be consistent with2821the current directory contents (in fact, most operations will depend on2822different ways to make the index 'not' be consistent with the directory2823hierarchy), but it has three very important attributes:28242825'(a) it can re-generate the full state it caches (not just the2826directory structure: it contains pointers to the "blob" objects so2827that it can regenerate the data too)'28282829As a special case, there is a clear and unambiguous one-way mapping2830from a current directory cache to a "tree object", which can be2831efficiently created from just the current directory cache without2832actually looking at any other data. So a directory cache at any one2833time uniquely specifies one and only one "tree" object (but has2834additional data to make it easy to match up that tree object with what2835has happened in the directory)28362837'(b) it has efficient methods for finding inconsistencies between that2838cached state ("tree object waiting to be instantiated") and the2839current state.'28402841'(c) it can additionally efficiently represent information about merge2842conflicts between different tree objects, allowing each pathname to be2843associated with sufficient information about the trees involved that2844you can create a three-way merge between them.'28452846Those are the ONLY three things that the directory cache does. It's a2847cache, and the normal operation is to re-generate it completely from a2848known tree object, or update/compare it with a live tree that is being2849developed. If you blow the directory cache away entirely, you generally2850haven't lost any information as long as you have the name of the tree2851that it described. 28522853At the same time, the index is at the same time also the2854staging area for creating new trees, and creating a new tree always2855involves a controlled modification of the index file. In particular,2856the index file can have the representation of an intermediate tree that2857has not yet been instantiated. So the index can be thought of as a2858write-back cache, which can contain dirty information that has not yet2859been written back to the backing store.2860286128622863[[the-workflow]]2864The Workflow2865------------28662867Generally, all "git" operations work on the index file. Some operations2868work *purely* on the index file (showing the current state of the2869index), but most operations move data to and from the index file. Either2870from the database or from the working directory. Thus there are four2871main combinations: 28722873[[working-directory-to-index]]2874working directory -> index2875~~~~~~~~~~~~~~~~~~~~~~~~~~28762877You update the index with information from the working directory with2878the gitlink:git-update-index[1] command. You2879generally update the index information by just specifying the filename2880you want to update, like so:28812882-------------------------------------------------2883$ git-update-index filename2884-------------------------------------------------28852886but to avoid common mistakes with filename globbing etc, the command2887will not normally add totally new entries or remove old entries,2888i.e. it will normally just update existing cache entries.28892890To tell git that yes, you really do realize that certain files no2891longer exist, or that new files should be added, you2892should use the `--remove` and `--add` flags respectively.28932894NOTE! A `--remove` flag does 'not' mean that subsequent filenames will2895necessarily be removed: if the files still exist in your directory2896structure, the index will be updated with their new status, not2897removed. The only thing `--remove` means is that update-cache will be2898considering a removed file to be a valid thing, and if the file really2899does not exist any more, it will update the index accordingly.29002901As a special case, you can also do `git-update-index --refresh`, which2902will refresh the "stat" information of each index to match the current2903stat information. It will 'not' update the object status itself, and2904it will only update the fields that are used to quickly test whether2905an object still matches its old backing store object.29062907[[index-to-object-database]]2908index -> object database2909~~~~~~~~~~~~~~~~~~~~~~~~29102911You write your current index file to a "tree" object with the program29122913-------------------------------------------------2914$ git-write-tree2915-------------------------------------------------29162917that doesn't come with any options - it will just write out the2918current index into the set of tree objects that describe that state,2919and it will return the name of the resulting top-level tree. You can2920use that tree to re-generate the index at any time by going in the2921other direction:29222923[[object-database-to-index]]2924object database -> index2925~~~~~~~~~~~~~~~~~~~~~~~~29262927You read a "tree" file from the object database, and use that to2928populate (and overwrite - don't do this if your index contains any2929unsaved state that you might want to restore later!) your current2930index. Normal operation is just29312932-------------------------------------------------2933$ git-read-tree <sha1 of tree>2934-------------------------------------------------29352936and your index file will now be equivalent to the tree that you saved2937earlier. However, that is only your 'index' file: your working2938directory contents have not been modified.29392940[[index-to-working-directory]]2941index -> working directory2942~~~~~~~~~~~~~~~~~~~~~~~~~~29432944You update your working directory from the index by "checking out"2945files. This is not a very common operation, since normally you'd just2946keep your files updated, and rather than write to your working2947directory, you'd tell the index files about the changes in your2948working directory (i.e. `git-update-index`).29492950However, if you decide to jump to a new version, or check out somebody2951else's version, or just restore a previous tree, you'd populate your2952index file with read-tree, and then you need to check out the result2953with29542955-------------------------------------------------2956$ git-checkout-index filename2957-------------------------------------------------29582959or, if you want to check out all of the index, use `-a`.29602961NOTE! git-checkout-index normally refuses to overwrite old files, so2962if you have an old version of the tree already checked out, you will2963need to use the "-f" flag ('before' the "-a" flag or the filename) to2964'force' the checkout.296529662967Finally, there are a few odds and ends which are not purely moving2968from one representation to the other:29692970[[tying-it-all-together]]2971Tying it all together2972~~~~~~~~~~~~~~~~~~~~~29732974To commit a tree you have instantiated with "git-write-tree", you'd2975create a "commit" object that refers to that tree and the history2976behind it - most notably the "parent" commits that preceded it in2977history.29782979Normally a "commit" has one parent: the previous state of the tree2980before a certain change was made. However, sometimes it can have two2981or more parent commits, in which case we call it a "merge", due to the2982fact that such a commit brings together ("merges") two or more2983previous states represented by other commits.29842985In other words, while a "tree" represents a particular directory state2986of a working directory, a "commit" represents that state in "time",2987and explains how we got there.29882989You create a commit object by giving it the tree that describes the2990state at the time of the commit, and a list of parents:29912992-------------------------------------------------2993$ git-commit-tree <tree> -p <parent> [-p <parent2> ..]2994-------------------------------------------------29952996and then giving the reason for the commit on stdin (either through2997redirection from a pipe or file, or by just typing it at the tty).29982999git-commit-tree will return the name of the object that represents3000that commit, and you should save it away for later use. Normally,3001you'd commit a new `HEAD` state, and while git doesn't care where you3002save the note about that state, in practice we tend to just write the3003result to the file pointed at by `.git/HEAD`, so that we can always see3004what the last committed state was.30053006Here is an ASCII art by Jon Loeliger that illustrates how3007various pieces fit together.30083009------------30103011 commit-tree3012 commit obj3013 +----+3014 | |3015 | |3016 V V3017 +-----------+3018 | Object DB |3019 | Backing |3020 | Store |3021 +-----------+3022 ^3023 write-tree | |3024 tree obj | |3025 | | read-tree3026 | | tree obj3027 V3028 +-----------+3029 | Index |3030 | "cache" |3031 +-----------+3032 update-index ^3033 blob obj | |3034 | |3035 checkout-index -u | | checkout-index3036 stat | | blob obj3037 V3038 +-----------+3039 | Working |3040 | Directory |3041 +-----------+30423043------------304430453046[[examining-the-data]]3047Examining the data3048------------------30493050You can examine the data represented in the object database and the3051index with various helper tools. For every object, you can use3052gitlink:git-cat-file[1] to examine details about the3053object:30543055-------------------------------------------------3056$ git-cat-file -t <objectname>3057-------------------------------------------------30583059shows the type of the object, and once you have the type (which is3060usually implicit in where you find the object), you can use30613062-------------------------------------------------3063$ git-cat-file blob|tree|commit|tag <objectname>3064-------------------------------------------------30653066to show its contents. NOTE! Trees have binary content, and as a result3067there is a special helper for showing that content, called3068`git-ls-tree`, which turns the binary content into a more easily3069readable form.30703071It's especially instructive to look at "commit" objects, since those3072tend to be small and fairly self-explanatory. In particular, if you3073follow the convention of having the top commit name in `.git/HEAD`,3074you can do30753076-------------------------------------------------3077$ git-cat-file commit HEAD3078-------------------------------------------------30793080to see what the top commit was.30813082[[merging-multiple-trees]]3083Merging multiple trees3084----------------------30853086Git helps you do a three-way merge, which you can expand to n-way by3087repeating the merge procedure arbitrary times until you finally3088"commit" the state. The normal situation is that you'd only do one3089three-way merge (two parents), and commit it, but if you like to, you3090can do multiple parents in one go.30913092To do a three-way merge, you need the two sets of "commit" objects3093that you want to merge, use those to find the closest common parent (a3094third "commit" object), and then use those commit objects to find the3095state of the directory ("tree" object) at these points.30963097To get the "base" for the merge, you first look up the common parent3098of two commits with30993100-------------------------------------------------3101$ git-merge-base <commit1> <commit2>3102-------------------------------------------------31033104which will return you the commit they are both based on. You should3105now look up the "tree" objects of those commits, which you can easily3106do with (for example)31073108-------------------------------------------------3109$ git-cat-file commit <commitname> | head -13110-------------------------------------------------31113112since the tree object information is always the first line in a commit3113object.31143115Once you know the three trees you are going to merge (the one "original"3116tree, aka the common tree, and the two "result" trees, aka the branches3117you want to merge), you do a "merge" read into the index. This will3118complain if it has to throw away your old index contents, so you should3119make sure that you've committed those - in fact you would normally3120always do a merge against your last commit (which should thus match what3121you have in your current index anyway).31223123To do the merge, do31243125-------------------------------------------------3126$ git-read-tree -m -u <origtree> <yourtree> <targettree>3127-------------------------------------------------31283129which will do all trivial merge operations for you directly in the3130index file, and you can just write the result out with3131`git-write-tree`.313231333134[[merging-multiple-trees-2]]3135Merging multiple trees, continued3136---------------------------------31373138Sadly, many merges aren't trivial. If there are files that have3139been added.moved or removed, or if both branches have modified the3140same file, you will be left with an index tree that contains "merge3141entries" in it. Such an index tree can 'NOT' be written out to a tree3142object, and you will have to resolve any such merge clashes using3143other tools before you can write out the result.31443145You can examine such index state with `git-ls-files --unmerged`3146command. An example:31473148------------------------------------------------3149$ git-read-tree -m $orig HEAD $target3150$ git-ls-files --unmerged3151100644 263414f423d0e4d70dae8fe53fa34614ff3e2860 1 hello.c3152100644 06fa6a24256dc7e560efa5687fa84b51f0263c3a 2 hello.c3153100644 cc44c73eb783565da5831b4d820c962954019b69 3 hello.c3154------------------------------------------------31553156Each line of the `git-ls-files --unmerged` output begins with3157the blob mode bits, blob SHA1, 'stage number', and the3158filename. The 'stage number' is git's way to say which tree it3159came from: stage 1 corresponds to `$orig` tree, stage 2 `HEAD`3160tree, and stage3 `$target` tree.31613162Earlier we said that trivial merges are done inside3163`git-read-tree -m`. For example, if the file did not change3164from `$orig` to `HEAD` nor `$target`, or if the file changed3165from `$orig` to `HEAD` and `$orig` to `$target` the same way,3166obviously the final outcome is what is in `HEAD`. What the3167above example shows is that file `hello.c` was changed from3168`$orig` to `HEAD` and `$orig` to `$target` in a different way.3169You could resolve this by running your favorite 3-way merge3170program, e.g. `diff3`, `merge`, or git's own merge-file, on3171the blob objects from these three stages yourself, like this:31723173------------------------------------------------3174$ git-cat-file blob 263414f... >hello.c~13175$ git-cat-file blob 06fa6a2... >hello.c~23176$ git-cat-file blob cc44c73... >hello.c~33177$ git merge-file hello.c~2 hello.c~1 hello.c~33178------------------------------------------------31793180This would leave the merge result in `hello.c~2` file, along3181with conflict markers if there are conflicts. After verifying3182the merge result makes sense, you can tell git what the final3183merge result for this file is by:31843185-------------------------------------------------3186$ mv -f hello.c~2 hello.c3187$ git-update-index hello.c3188-------------------------------------------------31893190When a path is in unmerged state, running `git-update-index` for3191that path tells git to mark the path resolved.31923193The above is the description of a git merge at the lowest level,3194to help you understand what conceptually happens under the hood.3195In practice, nobody, not even git itself, uses three `git-cat-file`3196for this. There is `git-merge-index` program that extracts the3197stages to temporary files and calls a "merge" script on it:31983199-------------------------------------------------3200$ git-merge-index git-merge-one-file hello.c3201-------------------------------------------------32023203and that is what higher level `git merge -s resolve` is implemented with.32043205[[pack-files]]3206How git stores objects efficiently: pack files3207----------------------------------------------32083209We've seen how git stores each object in a file named after the3210object's SHA1 hash.32113212Unfortunately this system becomes inefficient once a project has a3213lot of objects. Try this on an old project:32143215------------------------------------------------3216$ git count-objects32176930 objects, 47620 kilobytes3218------------------------------------------------32193220The first number is the number of objects which are kept in3221individual files. The second is the amount of space taken up by3222those "loose" objects.32233224You can save space and make git faster by moving these loose objects in3225to a "pack file", which stores a group of objects in an efficient3226compressed format; the details of how pack files are formatted can be3227found in link:technical/pack-format.txt[technical/pack-format.txt].32283229To put the loose objects into a pack, just run git repack:32303231------------------------------------------------3232$ git repack3233Generating pack...3234Done counting 6020 objects.3235Deltifying 6020 objects.3236 100% (6020/6020) done3237Writing 6020 objects.3238 100% (6020/6020) done3239Total 6020, written 6020 (delta 4070), reused 0 (delta 0)3240Pack pack-3e54ad29d5b2e05838c75df582c65257b8d08e1c created.3241------------------------------------------------32423243You can then run32443245------------------------------------------------3246$ git prune3247------------------------------------------------32483249to remove any of the "loose" objects that are now contained in the3250pack. This will also remove any unreferenced objects (which may be3251created when, for example, you use "git reset" to remove a commit).3252You can verify that the loose objects are gone by looking at the3253.git/objects directory or by running32543255------------------------------------------------3256$ git count-objects32570 objects, 0 kilobytes3258------------------------------------------------32593260Although the object files are gone, any commands that refer to those3261objects will work exactly as they did before.32623263The gitlink:git-gc[1] command performs packing, pruning, and more for3264you, so is normally the only high-level command you need.32653266[[dangling-objects]]3267Dangling objects3268----------------32693270The gitlink:git-fsck[1] command will sometimes complain about dangling3271objects. They are not a problem.32723273The most common cause of dangling objects is that you've rebased a3274branch, or you have pulled from somebody else who rebased a branch--see3275<<cleaning-up-history>>. In that case, the old head of the original3276branch still exists, as does everything it pointed to. The branch3277pointer itself just doesn't, since you replaced it with another one.32783279There are also other situations that cause dangling objects. For3280example, a "dangling blob" may arise because you did a "git add" of a3281file, but then, before you actually committed it and made it part of the3282bigger picture, you changed something else in that file and committed3283that *updated* thing - the old state that you added originally ends up3284not being pointed to by any commit or tree, so it's now a dangling blob3285object.32863287Similarly, when the "recursive" merge strategy runs, and finds that3288there are criss-cross merges and thus more than one merge base (which is3289fairly unusual, but it does happen), it will generate one temporary3290midway tree (or possibly even more, if you had lots of criss-crossing3291merges and more than two merge bases) as a temporary internal merge3292base, and again, those are real objects, but the end result will not end3293up pointing to them, so they end up "dangling" in your repository.32943295Generally, dangling objects aren't anything to worry about. They can3296even be very useful: if you screw something up, the dangling objects can3297be how you recover your old tree (say, you did a rebase, and realized3298that you really didn't want to - you can look at what dangling objects3299you have, and decide to reset your head to some old dangling state).33003301For commits, you can just use:33023303------------------------------------------------3304$ gitk <dangling-commit-sha-goes-here> --not --all3305------------------------------------------------33063307This asks for all the history reachable from the given commit but not3308from any branch, tag, or other reference. If you decide it's something3309you want, you can always create a new reference to it, e.g.,33103311------------------------------------------------3312$ git branch recovered-branch <dangling-commit-sha-goes-here>3313------------------------------------------------33143315For blobs and trees, you can't do the same, but you can still examine3316them. You can just do33173318------------------------------------------------3319$ git show <dangling-blob/tree-sha-goes-here>3320------------------------------------------------33213322to show what the contents of the blob were (or, for a tree, basically3323what the "ls" for that directory was), and that may give you some idea3324of what the operation was that left that dangling object.33253326Usually, dangling blobs and trees aren't very interesting. They're3327almost always the result of either being a half-way mergebase (the blob3328will often even have the conflict markers from a merge in it, if you3329have had conflicting merges that you fixed up by hand), or simply3330because you interrupted a "git fetch" with ^C or something like that,3331leaving _some_ of the new objects in the object database, but just3332dangling and useless.33333334Anyway, once you are sure that you're not interested in any dangling 3335state, you can just prune all unreachable objects:33363337------------------------------------------------3338$ git prune3339------------------------------------------------33403341and they'll be gone. But you should only run "git prune" on a quiescent3342repository - it's kind of like doing a filesystem fsck recovery: you3343don't want to do that while the filesystem is mounted.33443345(The same is true of "git-fsck" itself, btw - but since 3346git-fsck never actually *changes* the repository, it just reports 3347on what it found, git-fsck itself is never "dangerous" to run. 3348Running it while somebody is actually changing the repository can cause 3349confusing and scary messages, but it won't actually do anything bad. In 3350contrast, running "git prune" while somebody is actively changing the 3351repository is a *BAD* idea).33523353[[birdview-on-the-source-code]]3354A birds-eye view of Git's source code3355-------------------------------------33563357It is not always easy for new developers to find their way through Git's3358source code. This section gives you a little guidance to show where to3359start.33603361A good place to start is with the contents of the initial commit, with:33623363----------------------------------------------------3364$ git checkout e83c51633365----------------------------------------------------33663367The initial revision lays the foundation for almost everything git has3368today, but is small enough to read in one sitting.33693370Note that terminology has changed since that revision. For example, the3371README in that revision uses the word "changeset" to describe what we3372now call a <<def_commit_object,commit>>.33733374Also, we do not call it "cache" any more, but "index", however, the3375file is still called `cache.h`. Remark: Not much reason to change it now,3376especially since there is no good single name for it anyway, because it is3377basically _the_ header file which is included by _all_ of Git's C sources.33783379If you grasp the ideas in that initial commit, you should check out a3380more recent version and skim `cache.h`, `object.h` and `commit.h`.33813382In the early days, Git (in the tradition of UNIX) was a bunch of programs3383which were extremely simple, and which you used in scripts, piping the3384output of one into another. This turned out to be good for initial3385development, since it was easier to test new things. However, recently3386many of these parts have become builtins, and some of the core has been3387"libified", i.e. put into libgit.a for performance, portability reasons,3388and to avoid code duplication.33893390By now, you know what the index is (and find the corresponding data3391structures in `cache.h`), and that there are just a couple of object types3392(blobs, trees, commits and tags) which inherit their common structure from3393`struct object`, which is their first member (and thus, you can cast e.g.3394`(struct object *)commit` to achieve the _same_ as `&commit->object`, i.e.3395get at the object name and flags).33963397Now is a good point to take a break to let this information sink in.33983399Next step: get familiar with the object naming. Read <<naming-commits>>.3400There are quite a few ways to name an object (and not only revisions!).3401All of these are handled in `sha1_name.c`. Just have a quick look at3402the function `get_sha1()`. A lot of the special handling is done by3403functions like `get_sha1_basic()` or the likes.34043405This is just to get you into the groove for the most libified part of Git:3406the revision walker.34073408Basically, the initial version of `git log` was a shell script:34093410----------------------------------------------------------------3411$ git-rev-list --pretty $(git-rev-parse --default HEAD "$@") | \3412 LESS=-S ${PAGER:-less}3413----------------------------------------------------------------34143415What does this mean?34163417`git-rev-list` is the original version of the revision walker, which3418_always_ printed a list of revisions to stdout. It is still functional,3419and needs to, since most new Git programs start out as scripts using3420`git-rev-list`.34213422`git-rev-parse` is not as important any more; it was only used to filter out3423options that were relevant for the different plumbing commands that were3424called by the script.34253426Most of what `git-rev-list` did is contained in `revision.c` and3427`revision.h`. It wraps the options in a struct named `rev_info`, which3428controls how and what revisions are walked, and more.34293430The original job of `git-rev-parse` is now taken by the function3431`setup_revisions()`, which parses the revisions and the common command line3432options for the revision walker. This information is stored in the struct3433`rev_info` for later consumption. You can do your own command line option3434parsing after calling `setup_revisions()`. After that, you have to call3435`prepare_revision_walk()` for initialization, and then you can get the3436commits one by one with the function `get_revision()`.34373438If you are interested in more details of the revision walking process,3439just have a look at the first implementation of `cmd_log()`; call3440`git-show v1.3.0~155^2~4` and scroll down to that function (note that you3441no longer need to call `setup_pager()` directly).34423443Nowadays, `git log` is a builtin, which means that it is _contained_ in the3444command `git`. The source side of a builtin is34453446- a function called `cmd_<bla>`, typically defined in `builtin-<bla>.c`,3447 and declared in `builtin.h`,34483449- an entry in the `commands[]` array in `git.c`, and34503451- an entry in `BUILTIN_OBJECTS` in the `Makefile`.34523453Sometimes, more than one builtin is contained in one source file. For3454example, `cmd_whatchanged()` and `cmd_log()` both reside in `builtin-log.c`,3455since they share quite a bit of code. In that case, the commands which are3456_not_ named like the `.c` file in which they live have to be listed in3457`BUILT_INS` in the `Makefile`.34583459`git log` looks more complicated in C than it does in the original script,3460but that allows for a much greater flexibility and performance.34613462Here again it is a good point to take a pause.34633464Lesson three is: study the code. Really, it is the best way to learn about3465the organization of Git (after you know the basic concepts).34663467So, think about something which you are interested in, say, "how can I3468access a blob just knowing the object name of it?". The first step is to3469find a Git command with which you can do it. In this example, it is either3470`git show` or `git cat-file`.34713472For the sake of clarity, let's stay with `git cat-file`, because it34733474- is plumbing, and34753476- was around even in the initial commit (it literally went only through3477 some 20 revisions as `cat-file.c`, was renamed to `builtin-cat-file.c`3478 when made a builtin, and then saw less than 10 versions).34793480So, look into `builtin-cat-file.c`, search for `cmd_cat_file()` and look what3481it does.34823483------------------------------------------------------------------3484 git_config(git_default_config);3485 if (argc != 3)3486 usage("git-cat-file [-t|-s|-e|-p|<type>] <sha1>");3487 if (get_sha1(argv[2], sha1))3488 die("Not a valid object name %s", argv[2]);3489------------------------------------------------------------------34903491Let's skip over the obvious details; the only really interesting part3492here is the call to `get_sha1()`. It tries to interpret `argv[2]` as an3493object name, and if it refers to an object which is present in the current3494repository, it writes the resulting SHA-1 into the variable `sha1`.34953496Two things are interesting here:34973498- `get_sha1()` returns 0 on _success_. This might surprise some new3499 Git hackers, but there is a long tradition in UNIX to return different3500 negative numbers in case of different errors -- and 0 on success.35013502- the variable `sha1` in the function signature of `get_sha1()` is `unsigned3503 char \*`, but is actually expected to be a pointer to `unsigned3504 char[20]`. This variable will contain the 160-bit SHA-1 of the given3505 commit. Note that whenever a SHA-1 is passed as `unsigned char \*`, it3506 is the binary representation, as opposed to the ASCII representation in3507 hex characters, which is passed as `char *`.35083509You will see both of these things throughout the code.35103511Now, for the meat:35123513-----------------------------------------------------------------------------3514 case 0:3515 buf = read_object_with_reference(sha1, argv[1], &size, NULL);3516-----------------------------------------------------------------------------35173518This is how you read a blob (actually, not only a blob, but any type of3519object). To know how the function `read_object_with_reference()` actually3520works, find the source code for it (something like `git grep3521read_object_with | grep ":[a-z]"` in the git repository), and read3522the source.35233524To find out how the result can be used, just read on in `cmd_cat_file()`:35253526-----------------------------------3527 write_or_die(1, buf, size);3528-----------------------------------35293530Sometimes, you do not know where to look for a feature. In many such cases,3531it helps to search through the output of `git log`, and then `git show` the3532corresponding commit.35333534Example: If you know that there was some test case for `git bundle`, but3535do not remember where it was (yes, you _could_ `git grep bundle t/`, but that3536does not illustrate the point!):35373538------------------------3539$ git log --no-merges t/3540------------------------35413542In the pager (`less`), just search for "bundle", go a few lines back,3543and see that it is in commit 18449ab0... Now just copy this object name,3544and paste it into the command line35453546-------------------3547$ git show 18449ab03548-------------------35493550Voila.35513552Another example: Find out what to do in order to make some script a3553builtin:35543555-------------------------------------------------3556$ git log --no-merges --diff-filter=A builtin-*.c3557-------------------------------------------------35583559You see, Git is actually the best tool to find out about the source of Git3560itself!35613562[[glossary]]3563include::glossary.txt[]35643565[[git-quick-start]]3566Appendix A: Git Quick Start3567===========================35683569This is a quick summary of the major commands; the following chapters3570will explain how these work in more detail.35713572[[quick-creating-a-new-repository]]3573Creating a new repository3574-------------------------35753576From a tarball:35773578-----------------------------------------------3579$ tar xzf project.tar.gz3580$ cd project3581$ git init3582Initialized empty Git repository in .git/3583$ git add .3584$ git commit3585-----------------------------------------------35863587From a remote repository:35883589-----------------------------------------------3590$ git clone git://example.com/pub/project.git3591$ cd project3592-----------------------------------------------35933594[[managing-branches]]3595Managing branches3596-----------------35973598-----------------------------------------------3599$ git branch # list all local branches in this repo3600$ git checkout test # switch working directory to branch "test"3601$ git branch new # create branch "new" starting at current HEAD3602$ git branch -d new # delete branch "new"3603-----------------------------------------------36043605Instead of basing new branch on current HEAD (the default), use:36063607-----------------------------------------------3608$ git branch new test # branch named "test"3609$ git branch new v2.6.15 # tag named v2.6.153610$ git branch new HEAD^ # commit before the most recent3611$ git branch new HEAD^^ # commit before that3612$ git branch new test~10 # ten commits before tip of branch "test"3613-----------------------------------------------36143615Create and switch to a new branch at the same time:36163617-----------------------------------------------3618$ git checkout -b new v2.6.153619-----------------------------------------------36203621Update and examine branches from the repository you cloned from:36223623-----------------------------------------------3624$ git fetch # update3625$ git branch -r # list3626 origin/master3627 origin/next3628 ...3629$ git checkout -b masterwork origin/master3630-----------------------------------------------36313632Fetch a branch from a different repository, and give it a new3633name in your repository:36343635-----------------------------------------------3636$ git fetch git://example.com/project.git theirbranch:mybranch3637$ git fetch git://example.com/project.git v2.6.15:mybranch3638-----------------------------------------------36393640Keep a list of repositories you work with regularly:36413642-----------------------------------------------3643$ git remote add example git://example.com/project.git3644$ git remote # list remote repositories3645example3646origin3647$ git remote show example # get details3648* remote example3649 URL: git://example.com/project.git3650 Tracked remote branches3651 master next ...3652$ git fetch example # update branches from example3653$ git branch -r # list all remote branches3654-----------------------------------------------365536563657[[exploring-history]]3658Exploring history3659-----------------36603661-----------------------------------------------3662$ gitk # visualize and browse history3663$ git log # list all commits3664$ git log src/ # ...modifying src/3665$ git log v2.6.15..v2.6.16 # ...in v2.6.16, not in v2.6.153666$ git log master..test # ...in branch test, not in branch master3667$ git log test..master # ...in branch master, but not in test3668$ git log test...master # ...in one branch, not in both3669$ git log -S'foo()' # ...where difference contain "foo()"3670$ git log --since="2 weeks ago"3671$ git log -p # show patches as well3672$ git show # most recent commit3673$ git diff v2.6.15..v2.6.16 # diff between two tagged versions3674$ git diff v2.6.15..HEAD # diff with current head3675$ git grep "foo()" # search working directory for "foo()"3676$ git grep v2.6.15 "foo()" # search old tree for "foo()"3677$ git show v2.6.15:a.txt # look at old version of a.txt3678-----------------------------------------------36793680Search for regressions:36813682-----------------------------------------------3683$ git bisect start3684$ git bisect bad # current version is bad3685$ git bisect good v2.6.13-rc2 # last known good revision3686Bisecting: 675 revisions left to test after this3687 # test here, then:3688$ git bisect good # if this revision is good, or3689$ git bisect bad # if this revision is bad.3690 # repeat until done.3691-----------------------------------------------36923693[[making-changes]]3694Making changes3695--------------36963697Make sure git knows who to blame:36983699------------------------------------------------3700$ cat >>~/.gitconfig <<\EOF3701[user]3702 name = Your Name Comes Here3703 email = you@yourdomain.example.com3704EOF3705------------------------------------------------37063707Select file contents to include in the next commit, then make the3708commit:37093710-----------------------------------------------3711$ git add a.txt # updated file3712$ git add b.txt # new file3713$ git rm c.txt # old file3714$ git commit3715-----------------------------------------------37163717Or, prepare and create the commit in one step:37183719-----------------------------------------------3720$ git commit d.txt # use latest content only of d.txt3721$ git commit -a # use latest content of all tracked files3722-----------------------------------------------37233724[[merging]]3725Merging3726-------37273728-----------------------------------------------3729$ git merge test # merge branch "test" into the current branch3730$ git pull git://example.com/project.git master3731 # fetch and merge in remote branch3732$ git pull . test # equivalent to git merge test3733-----------------------------------------------37343735[[sharing-your-changes]]3736Sharing your changes3737--------------------37383739Importing or exporting patches:37403741-----------------------------------------------3742$ git format-patch origin..HEAD # format a patch for each commit3743 # in HEAD but not in origin3744$ git am mbox # import patches from the mailbox "mbox"3745-----------------------------------------------37463747Fetch a branch in a different git repository, then merge into the3748current branch:37493750-----------------------------------------------3751$ git pull git://example.com/project.git theirbranch3752-----------------------------------------------37533754Store the fetched branch into a local branch before merging into the3755current branch:37563757-----------------------------------------------3758$ git pull git://example.com/project.git theirbranch:mybranch3759-----------------------------------------------37603761After creating commits on a local branch, update the remote3762branch with your commits:37633764-----------------------------------------------3765$ git push ssh://example.com/project.git mybranch:theirbranch3766-----------------------------------------------37673768When remote and local branch are both named "test":37693770-----------------------------------------------3771$ git push ssh://example.com/project.git test3772-----------------------------------------------37733774Shortcut version for a frequently used remote repository:37753776-----------------------------------------------3777$ git remote add example ssh://example.com/project.git3778$ git push example test3779-----------------------------------------------37803781[[repository-maintenance]]3782Repository maintenance3783----------------------37843785Check for corruption:37863787-----------------------------------------------3788$ git fsck3789-----------------------------------------------37903791Recompress, remove unused cruft:37923793-----------------------------------------------3794$ git gc3795-----------------------------------------------379637973798[[todo]]3799Appendix B: Notes and todo list for this manual3800===============================================38013802This is a work in progress.38033804The basic requirements:3805 - It must be readable in order, from beginning to end, by3806 someone intelligent with a basic grasp of the unix3807 commandline, but without any special knowledge of git. If3808 necessary, any other prerequisites should be specifically3809 mentioned as they arise.3810 - Whenever possible, section headings should clearly describe3811 the task they explain how to do, in language that requires3812 no more knowledge than necessary: for example, "importing3813 patches into a project" rather than "the git-am command"38143815Think about how to create a clear chapter dependency graph that will3816allow people to get to important topics without necessarily reading3817everything in between.38183819Say something about .gitignore.38203821Scan Documentation/ for other stuff left out; in particular:3822 howto's3823 some of technical/?3824 hooks3825 list of commands in gitlink:git[1]38263827Scan email archives for other stuff left out38283829Scan man pages to see if any assume more background than this manual3830provides.38313832Simplify beginning by suggesting disconnected head instead of3833temporary branch creation?38343835Add more good examples. Entire sections of just cookbook examples3836might be a good idea; maybe make an "advanced examples" section a3837standard end-of-chapter section?38383839Include cross-references to the glossary, where appropriate.38403841Document shallow clones? See draft 1.5.0 release notes for some3842documentation.38433844Add a section on working with other version control systems, including3845CVS, Subversion, and just imports of series of release tarballs.38463847More details on gitweb?38483849Write a chapter on using plumbing and writing scripts.