1Git User's Manual (for version 1.5.3 or newer) 2______________________________________________ 3 4 5Git is a fast distributed revision control system. 6 7This manual is designed to be readable by someone with basic unix 8command-line skills, but no previous knowledge of git. 9 10<<repositories-and-branches>> and <<exploring-git-history>> explain how 11to fetch and study a project using git--read these chapters to learn how 12to build and test a particular version of a software project, search for 13regressions, and so on. 14 15People needing to do actual development will also want to read 16<<Developing-with-git>> and <<sharing-development>>. 17 18Further chapters cover more specialized topics. 19 20Comprehensive reference documentation is available through the man 21pages. For a command such as "git clone", just use 22 23------------------------------------------------ 24$ man git-clone 25------------------------------------------------ 26 27See also <<git-quick-start>> for a brief overview of git commands, 28without any explanation. 29 30Finally, see <<todo>> for ways that you can help make this manual more 31complete. 32 33 34[[repositories-and-branches]] 35Repositories and Branches 36========================= 37 38[[how-to-get-a-git-repository]] 39How to get a git repository 40--------------------------- 41 42It will be useful to have a git repository to experiment with as you 43read this manual. 44 45The best way to get one is by using the gitlink:git-clone[1] command 46to download a copy of an existing repository for a project that you 47are interested in. If you don't already have a project in mind, here 48are some interesting examples: 49 50------------------------------------------------ 51 # git itself (approx. 10MB download): 52$ git clone git://git.kernel.org/pub/scm/git/git.git 53 # the linux kernel (approx. 150MB download): 54$ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git 55------------------------------------------------ 56 57The initial clone may be time-consuming for a large project, but you 58will only need to clone once. 59 60The clone command creates a new directory named after the project 61("git" or "linux-2.6" in the examples above). After you cd into this 62directory, you will see that it contains a copy of the project files, 63together with a special top-level directory named ".git", which 64contains all the information about the history of the project. 65 66In most of the following, examples will be taken from one of the two 67repositories above. 68 69[[how-to-check-out]] 70How to check out a different version of a project 71------------------------------------------------- 72 73Git is best thought of as a tool for storing the history of a 74collection of files. It stores the history as a compressed 75collection of interrelated snapshots (versions) of the project's 76contents. 77 78A single git repository may contain multiple branches. It keeps track 79of them by keeping a list of <<def_head,heads>> which reference the 80latest version on each branch; the gitlink:git-branch[1] command shows 81you the list of branch heads: 82 83------------------------------------------------ 84$ git branch 85* master 86------------------------------------------------ 87 88A freshly cloned repository contains a single branch head, by default 89named "master", with the working directory initialized to the state of 90the project referred to by that branch head. 91 92Most projects also use <<def_tag,tags>>. Tags, like heads, are 93references into the project's history, and can be listed using the 94gitlink:git-tag[1] command: 95 96------------------------------------------------ 97$ git tag -l 98v2.6.11 99v2.6.11-tree 100v2.6.12 101v2.6.12-rc2 102v2.6.12-rc3 103v2.6.12-rc4 104v2.6.12-rc5 105v2.6.12-rc6 106v2.6.13 107... 108------------------------------------------------ 109 110Tags are expected to always point at the same version of a project, 111while heads are expected to advance as development progresses. 112 113Create a new branch head pointing to one of these versions and check it 114out using gitlink:git-checkout[1]: 115 116------------------------------------------------ 117$ git checkout -b new v2.6.13 118------------------------------------------------ 119 120The working directory then reflects the contents that the project had 121when it was tagged v2.6.13, and gitlink:git-branch[1] shows two 122branches, with an asterisk marking the currently checked-out branch: 123 124------------------------------------------------ 125$ git branch 126 master 127* new 128------------------------------------------------ 129 130If you decide that you'd rather see version 2.6.17, you can modify 131the current branch to point at v2.6.17 instead, with 132 133------------------------------------------------ 134$ git reset --hard v2.6.17 135------------------------------------------------ 136 137Note that if the current branch head was your only reference to a 138particular point in history, then resetting that branch may leave you 139with no way to find the history it used to point to; so use this command 140carefully. 141 142[[understanding-commits]] 143Understanding History: Commits 144------------------------------ 145 146Every change in the history of a project is represented by a commit. 147The gitlink:git-show[1] command shows the most recent commit on the 148current branch: 149 150------------------------------------------------ 151$ git show 152commit 2b5f6dcce5bf94b9b119e9ed8d537098ec61c3d2 153Author: Jamal Hadi Salim <hadi@cyberus.ca> 154Date: Sat Dec 2 22:22:25 2006 -0800 155 156 [XFRM]: Fix aevent structuring to be more complete. 157 158 aevents can not uniquely identify an SA. We break the ABI with this 159 patch, but consensus is that since it is not yet utilized by any 160 (known) application then it is fine (better do it now than later). 161 162 Signed-off-by: Jamal Hadi Salim <hadi@cyberus.ca> 163 Signed-off-by: David S. Miller <davem@davemloft.net> 164 165diff --git a/Documentation/networking/xfrm_sync.txt b/Documentation/networking/xfrm_sync.txt 166index 8be626f..d7aac9d 100644 167--- a/Documentation/networking/xfrm_sync.txt 168+++ b/Documentation/networking/xfrm_sync.txt 169@@ -47,10 +47,13 @@ aevent_id structure looks like: 170 171 struct xfrm_aevent_id { 172 struct xfrm_usersa_id sa_id; 173+ xfrm_address_t saddr; 174 __u32 flags; 175+ __u32 reqid; 176 }; 177... 178------------------------------------------------ 179 180As you can see, a commit shows who made the latest change, what they 181did, and why. 182 183Every commit has a 40-hexdigit id, sometimes called the "object name" or the 184"SHA1 id", shown on the first line of the "git show" output. You can usually 185refer to a commit by a shorter name, such as a tag or a branch name, but this 186longer name can also be useful. Most importantly, it is a globally unique 187name for this commit: so if you tell somebody else the object name (for 188example in email), then you are guaranteed that name will refer to the same 189commit in their repository that it does in yours (assuming their repository 190has that commit at all). Since the object name is computed as a hash over the 191contents of the commit, you are guaranteed that the commit can never change 192without its name also changing. 193 194In fact, in <<git-internals>> we shall see that everything stored in git 195history, including file data and directory contents, is stored in an object 196with a name that is a hash of its contents. 197 198[[understanding-reachability]] 199Understanding history: commits, parents, and reachability 200~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 201 202Every commit (except the very first commit in a project) also has a 203parent commit which shows what happened before this commit. 204Following the chain of parents will eventually take you back to the 205beginning of the project. 206 207However, the commits do not form a simple list; git allows lines of 208development to diverge and then reconverge, and the point where two 209lines of development reconverge is called a "merge". The commit 210representing a merge can therefore have more than one parent, with 211each parent representing the most recent commit on one of the lines 212of development leading to that point. 213 214The best way to see how this works is using the gitlink:gitk[1] 215command; running gitk now on a git repository and looking for merge 216commits will help understand how the git organizes history. 217 218In the following, we say that commit X is "reachable" from commit Y 219if commit X is an ancestor of commit Y. Equivalently, you could say 220that Y is a descendent of X, or that there is a chain of parents 221leading from commit Y to commit X. 222 223[[history-diagrams]] 224Understanding history: History diagrams 225~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 226 227We will sometimes represent git history using diagrams like the one 228below. Commits are shown as "o", and the links between them with 229lines drawn with - / and \. Time goes left to right: 230 231 232................................................ 233 o--o--o <-- Branch A 234 / 235 o--o--o <-- master 236 \ 237 o--o--o <-- Branch B 238................................................ 239 240If we need to talk about a particular commit, the character "o" may 241be replaced with another letter or number. 242 243[[what-is-a-branch]] 244Understanding history: What is a branch? 245~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 246 247When we need to be precise, we will use the word "branch" to mean a line 248of development, and "branch head" (or just "head") to mean a reference 249to the most recent commit on a branch. In the example above, the branch 250head named "A" is a pointer to one particular commit, but we refer to 251the line of three commits leading up to that point as all being part of 252"branch A". 253 254However, when no confusion will result, we often just use the term 255"branch" both for branches and for branch heads. 256 257[[manipulating-branches]] 258Manipulating branches 259--------------------- 260 261Creating, deleting, and modifying branches is quick and easy; here's 262a summary of the commands: 263 264git branch:: 265 list all branches 266git branch <branch>:: 267 create a new branch named <branch>, referencing the same 268 point in history as the current branch 269git branch <branch> <start-point>:: 270 create a new branch named <branch>, referencing 271 <start-point>, which may be specified any way you like, 272 including using a branch name or a tag name 273git branch -d <branch>:: 274 delete the branch <branch>; if the branch you are deleting 275 points to a commit which is not reachable from the current 276 branch, this command will fail with a warning. 277git branch -D <branch>:: 278 even if the branch points to a commit not reachable 279 from the current branch, you may know that that commit 280 is still reachable from some other branch or tag. In that 281 case it is safe to use this command to force git to delete 282 the branch. 283git checkout <branch>:: 284 make the current branch <branch>, updating the working 285 directory to reflect the version referenced by <branch> 286git checkout -b <new> <start-point>:: 287 create a new branch <new> referencing <start-point>, and 288 check it out. 289 290The special symbol "HEAD" can always be used to refer to the current 291branch. In fact, git uses a file named "HEAD" in the .git directory to 292remember which branch is current: 293 294------------------------------------------------ 295$ cat .git/HEAD 296ref: refs/heads/master 297------------------------------------------------ 298 299[[detached-head]] 300Examining an old version without creating a new branch 301------------------------------------------------------ 302 303The git-checkout command normally expects a branch head, but will also 304accept an arbitrary commit; for example, you can check out the commit 305referenced by a tag: 306 307------------------------------------------------ 308$ git checkout v2.6.17 309Note: moving to "v2.6.17" which isn't a local branch 310If you want to create a new branch from this checkout, you may do so 311(now or later) by using -b with the checkout command again. Example: 312 git checkout -b <new_branch_name> 313HEAD is now at 427abfa... Linux v2.6.17 314------------------------------------------------ 315 316The HEAD then refers to the SHA1 of the commit instead of to a branch, 317and git branch shows that you are no longer on a branch: 318 319------------------------------------------------ 320$ cat .git/HEAD 321427abfa28afedffadfca9dd8b067eb6d36bac53f 322$ git branch 323* (no branch) 324 master 325------------------------------------------------ 326 327In this case we say that the HEAD is "detached". 328 329This is an easy way to check out a particular version without having to 330make up a name for the new branch. You can still create a new branch 331(or tag) for this version later if you decide to. 332 333[[examining-remote-branches]] 334Examining branches from a remote repository 335------------------------------------------- 336 337The "master" branch that was created at the time you cloned is a copy 338of the HEAD in the repository that you cloned from. That repository 339may also have had other branches, though, and your local repository 340keeps branches which track each of those remote branches, which you 341can view using the "-r" option to gitlink:git-branch[1]: 342 343------------------------------------------------ 344$ git branch -r 345 origin/HEAD 346 origin/html 347 origin/maint 348 origin/man 349 origin/master 350 origin/next 351 origin/pu 352 origin/todo 353------------------------------------------------ 354 355You cannot check out these remote-tracking branches, but you can 356examine them on a branch of your own, just as you would a tag: 357 358------------------------------------------------ 359$ git checkout -b my-todo-copy origin/todo 360------------------------------------------------ 361 362Note that the name "origin" is just the name that git uses by default 363to refer to the repository that you cloned from. 364 365[[how-git-stores-references]] 366Naming branches, tags, and other references 367------------------------------------------- 368 369Branches, remote-tracking branches, and tags are all references to 370commits. All references are named with a slash-separated path name 371starting with "refs"; the names we've been using so far are actually 372shorthand: 373 374 - The branch "test" is short for "refs/heads/test". 375 - The tag "v2.6.18" is short for "refs/tags/v2.6.18". 376 - "origin/master" is short for "refs/remotes/origin/master". 377 378The full name is occasionally useful if, for example, there ever 379exists a tag and a branch with the same name. 380 381As another useful shortcut, the "HEAD" of a repository can be referred 382to just using the name of that repository. So, for example, "origin" 383is usually a shortcut for the HEAD branch in the repository "origin". 384 385For the complete list of paths which git checks for references, and 386the order it uses to decide which to choose when there are multiple 387references with the same shorthand name, see the "SPECIFYING 388REVISIONS" section of gitlink:git-rev-parse[1]. 389 390[[Updating-a-repository-with-git-fetch]] 391Updating a repository with git fetch 392------------------------------------ 393 394Eventually the developer cloned from will do additional work in her 395repository, creating new commits and advancing the branches to point 396at the new commits. 397 398The command "git fetch", with no arguments, will update all of the 399remote-tracking branches to the latest version found in her 400repository. It will not touch any of your own branches--not even the 401"master" branch that was created for you on clone. 402 403[[fetching-branches]] 404Fetching branches from other repositories 405----------------------------------------- 406 407You can also track branches from repositories other than the one you 408cloned from, using gitlink:git-remote[1]: 409 410------------------------------------------------- 411$ git remote add linux-nfs git://linux-nfs.org/pub/nfs-2.6.git 412$ git fetch linux-nfs 413* refs/remotes/linux-nfs/master: storing branch 'master' ... 414 commit: bf81b46 415------------------------------------------------- 416 417New remote-tracking branches will be stored under the shorthand name 418that you gave "git remote add", in this case linux-nfs: 419 420------------------------------------------------- 421$ git branch -r 422linux-nfs/master 423origin/master 424------------------------------------------------- 425 426If you run "git fetch <remote>" later, the tracking branches for the 427named <remote> will be updated. 428 429If you examine the file .git/config, you will see that git has added 430a new stanza: 431 432------------------------------------------------- 433$ cat .git/config 434... 435[remote "linux-nfs"] 436 url = git://linux-nfs.org/pub/nfs-2.6.git 437 fetch = +refs/heads/*:refs/remotes/linux-nfs/* 438... 439------------------------------------------------- 440 441This is what causes git to track the remote's branches; you may modify 442or delete these configuration options by editing .git/config with a 443text editor. (See the "CONFIGURATION FILE" section of 444gitlink:git-config[1] for details.) 445 446[[exploring-git-history]] 447Exploring git history 448===================== 449 450Git is best thought of as a tool for storing the history of a 451collection of files. It does this by storing compressed snapshots of 452the contents of a file hierarchy, together with "commits" which show 453the relationships between these snapshots. 454 455Git provides extremely flexible and fast tools for exploring the 456history of a project. 457 458We start with one specialized tool that is useful for finding the 459commit that introduced a bug into a project. 460 461[[using-bisect]] 462How to use bisect to find a regression 463-------------------------------------- 464 465Suppose version 2.6.18 of your project worked, but the version at 466"master" crashes. Sometimes the best way to find the cause of such a 467regression is to perform a brute-force search through the project's 468history to find the particular commit that caused the problem. The 469gitlink:git-bisect[1] command can help you do this: 470 471------------------------------------------------- 472$ git bisect start 473$ git bisect good v2.6.18 474$ git bisect bad master 475Bisecting: 3537 revisions left to test after this 476[65934a9a028b88e83e2b0f8b36618fe503349f8e] BLOCK: Make USB storage depend on SCSI rather than selecting it [try #6] 477------------------------------------------------- 478 479If you run "git branch" at this point, you'll see that git has 480temporarily moved you to a new branch named "bisect". This branch 481points to a commit (with commit id 65934...) that is reachable from 482v2.6.19 but not from v2.6.18. Compile and test it, and see whether 483it crashes. Assume it does crash. Then: 484 485------------------------------------------------- 486$ git bisect bad 487Bisecting: 1769 revisions left to test after this 488[7eff82c8b1511017ae605f0c99ac275a7e21b867] i2c-core: Drop useless bitmaskings 489------------------------------------------------- 490 491checks out an older version. Continue like this, telling git at each 492stage whether the version it gives you is good or bad, and notice 493that the number of revisions left to test is cut approximately in 494half each time. 495 496After about 13 tests (in this case), it will output the commit id of 497the guilty commit. You can then examine the commit with 498gitlink:git-show[1], find out who wrote it, and mail them your bug 499report with the commit id. Finally, run 500 501------------------------------------------------- 502$ git bisect reset 503------------------------------------------------- 504 505to return you to the branch you were on before and delete the 506temporary "bisect" branch. 507 508Note that the version which git-bisect checks out for you at each 509point is just a suggestion, and you're free to try a different 510version if you think it would be a good idea. For example, 511occasionally you may land on a commit that broke something unrelated; 512run 513 514------------------------------------------------- 515$ git bisect visualize 516------------------------------------------------- 517 518which will run gitk and label the commit it chose with a marker that 519says "bisect". Chose a safe-looking commit nearby, note its commit 520id, and check it out with: 521 522------------------------------------------------- 523$ git reset --hard fb47ddb2db... 524------------------------------------------------- 525 526then test, run "bisect good" or "bisect bad" as appropriate, and 527continue. 528 529[[naming-commits]] 530Naming commits 531-------------- 532 533We have seen several ways of naming commits already: 534 535 - 40-hexdigit object name 536 - branch name: refers to the commit at the head of the given 537 branch 538 - tag name: refers to the commit pointed to by the given tag 539 (we've seen branches and tags are special cases of 540 <<how-git-stores-references,references>>). 541 - HEAD: refers to the head of the current branch 542 543There are many more; see the "SPECIFYING REVISIONS" section of the 544gitlink:git-rev-parse[1] man page for the complete list of ways to 545name revisions. Some examples: 546 547------------------------------------------------- 548$ git show fb47ddb2 # the first few characters of the object name 549 # are usually enough to specify it uniquely 550$ git show HEAD^ # the parent of the HEAD commit 551$ git show HEAD^^ # the grandparent 552$ git show HEAD~4 # the great-great-grandparent 553------------------------------------------------- 554 555Recall that merge commits may have more than one parent; by default, 556^ and ~ follow the first parent listed in the commit, but you can 557also choose: 558 559------------------------------------------------- 560$ git show HEAD^1 # show the first parent of HEAD 561$ git show HEAD^2 # show the second parent of HEAD 562------------------------------------------------- 563 564In addition to HEAD, there are several other special names for 565commits: 566 567Merges (to be discussed later), as well as operations such as 568git-reset, which change the currently checked-out commit, generally 569set ORIG_HEAD to the value HEAD had before the current operation. 570 571The git-fetch operation always stores the head of the last fetched 572branch in FETCH_HEAD. For example, if you run git fetch without 573specifying a local branch as the target of the operation 574 575------------------------------------------------- 576$ git fetch git://example.com/proj.git theirbranch 577------------------------------------------------- 578 579the fetched commits will still be available from FETCH_HEAD. 580 581When we discuss merges we'll also see the special name MERGE_HEAD, 582which refers to the other branch that we're merging in to the current 583branch. 584 585The gitlink:git-rev-parse[1] command is a low-level command that is 586occasionally useful for translating some name for a commit to the object 587name for that commit: 588 589------------------------------------------------- 590$ git rev-parse origin 591e05db0fd4f31dde7005f075a84f96b360d05984b 592------------------------------------------------- 593 594[[creating-tags]] 595Creating tags 596------------- 597 598We can also create a tag to refer to a particular commit; after 599running 600 601------------------------------------------------- 602$ git tag stable-1 1b2e1d63ff 603------------------------------------------------- 604 605You can use stable-1 to refer to the commit 1b2e1d63ff. 606 607This creates a "lightweight" tag. If you would also like to include a 608comment with the tag, and possibly sign it cryptographically, then you 609should create a tag object instead; see the gitlink:git-tag[1] man page 610for details. 611 612[[browsing-revisions]] 613Browsing revisions 614------------------ 615 616The gitlink:git-log[1] command can show lists of commits. On its 617own, it shows all commits reachable from the parent commit; but you 618can also make more specific requests: 619 620------------------------------------------------- 621$ git log v2.5.. # commits since (not reachable from) v2.5 622$ git log test..master # commits reachable from master but not test 623$ git log master..test # ...reachable from test but not master 624$ git log master...test # ...reachable from either test or master, 625 # but not both 626$ git log --since="2 weeks ago" # commits from the last 2 weeks 627$ git log Makefile # commits which modify Makefile 628$ git log fs/ # ... which modify any file under fs/ 629$ git log -S'foo()' # commits which add or remove any file data 630 # matching the string 'foo()' 631------------------------------------------------- 632 633And of course you can combine all of these; the following finds 634commits since v2.5 which touch the Makefile or any file under fs: 635 636------------------------------------------------- 637$ git log v2.5.. Makefile fs/ 638------------------------------------------------- 639 640You can also ask git log to show patches: 641 642------------------------------------------------- 643$ git log -p 644------------------------------------------------- 645 646See the "--pretty" option in the gitlink:git-log[1] man page for more 647display options. 648 649Note that git log starts with the most recent commit and works 650backwards through the parents; however, since git history can contain 651multiple independent lines of development, the particular order that 652commits are listed in may be somewhat arbitrary. 653 654[[generating-diffs]] 655Generating diffs 656---------------- 657 658You can generate diffs between any two versions using 659gitlink:git-diff[1]: 660 661------------------------------------------------- 662$ git diff master..test 663------------------------------------------------- 664 665Sometimes what you want instead is a set of patches: 666 667------------------------------------------------- 668$ git format-patch master..test 669------------------------------------------------- 670 671will generate a file with a patch for each commit reachable from test 672but not from master. Note that if master also has commits which are 673not reachable from test, then the combined result of these patches 674will not be the same as the diff produced by the git-diff example. 675 676[[viewing-old-file-versions]] 677Viewing old file versions 678------------------------- 679 680You can always view an old version of a file by just checking out the 681correct revision first. But sometimes it is more convenient to be 682able to view an old version of a single file without checking 683anything out; this command does that: 684 685------------------------------------------------- 686$ git show v2.5:fs/locks.c 687------------------------------------------------- 688 689Before the colon may be anything that names a commit, and after it 690may be any path to a file tracked by git. 691 692[[history-examples]] 693Examples 694-------- 695 696[[counting-commits-on-a-branch]] 697Counting the number of commits on a branch 698~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 699 700Suppose you want to know how many commits you've made on "mybranch" 701since it diverged from "origin": 702 703------------------------------------------------- 704$ git log --pretty=oneline origin..mybranch | wc -l 705------------------------------------------------- 706 707Alternatively, you may often see this sort of thing done with the 708lower-level command gitlink:git-rev-list[1], which just lists the SHA1's 709of all the given commits: 710 711------------------------------------------------- 712$ git rev-list origin..mybranch | wc -l 713------------------------------------------------- 714 715[[checking-for-equal-branches]] 716Check whether two branches point at the same history 717~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 718 719Suppose you want to check whether two branches point at the same point 720in history. 721 722------------------------------------------------- 723$ git diff origin..master 724------------------------------------------------- 725 726will tell you whether the contents of the project are the same at the 727two branches; in theory, however, it's possible that the same project 728contents could have been arrived at by two different historical 729routes. You could compare the object names: 730 731------------------------------------------------- 732$ git rev-list origin 733e05db0fd4f31dde7005f075a84f96b360d05984b 734$ git rev-list master 735e05db0fd4f31dde7005f075a84f96b360d05984b 736------------------------------------------------- 737 738Or you could recall that the ... operator selects all commits 739contained reachable from either one reference or the other but not 740both: so 741 742------------------------------------------------- 743$ git log origin...master 744------------------------------------------------- 745 746will return no commits when the two branches are equal. 747 748[[finding-tagged-descendants]] 749Find first tagged version including a given fix 750~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 751 752Suppose you know that the commit e05db0fd fixed a certain problem. 753You'd like to find the earliest tagged release that contains that 754fix. 755 756Of course, there may be more than one answer--if the history branched 757after commit e05db0fd, then there could be multiple "earliest" tagged 758releases. 759 760You could just visually inspect the commits since e05db0fd: 761 762------------------------------------------------- 763$ gitk e05db0fd.. 764------------------------------------------------- 765 766Or you can use gitlink:git-name-rev[1], which will give the commit a 767name based on any tag it finds pointing to one of the commit's 768descendants: 769 770------------------------------------------------- 771$ git name-rev --tags e05db0fd 772e05db0fd tags/v1.5.0-rc1^0~23 773------------------------------------------------- 774 775The gitlink:git-describe[1] command does the opposite, naming the 776revision using a tag on which the given commit is based: 777 778------------------------------------------------- 779$ git describe e05db0fd 780v1.5.0-rc0-260-ge05db0f 781------------------------------------------------- 782 783but that may sometimes help you guess which tags might come after the 784given commit. 785 786If you just want to verify whether a given tagged version contains a 787given commit, you could use gitlink:git-merge-base[1]: 788 789------------------------------------------------- 790$ git merge-base e05db0fd v1.5.0-rc1 791e05db0fd4f31dde7005f075a84f96b360d05984b 792------------------------------------------------- 793 794The merge-base command finds a common ancestor of the given commits, 795and always returns one or the other in the case where one is a 796descendant of the other; so the above output shows that e05db0fd 797actually is an ancestor of v1.5.0-rc1. 798 799Alternatively, note that 800 801------------------------------------------------- 802$ git log v1.5.0-rc1..e05db0fd 803------------------------------------------------- 804 805will produce empty output if and only if v1.5.0-rc1 includes e05db0fd, 806because it outputs only commits that are not reachable from v1.5.0-rc1. 807 808As yet another alternative, the gitlink:git-show-branch[1] command lists 809the commits reachable from its arguments with a display on the left-hand 810side that indicates which arguments that commit is reachable from. So, 811you can run something like 812 813------------------------------------------------- 814$ git show-branch e05db0fd v1.5.0-rc0 v1.5.0-rc1 v1.5.0-rc2 815! [e05db0fd] Fix warnings in sha1_file.c - use C99 printf format if 816available 817 ! [v1.5.0-rc0] GIT v1.5.0 preview 818 ! [v1.5.0-rc1] GIT v1.5.0-rc1 819 ! [v1.5.0-rc2] GIT v1.5.0-rc2 820... 821------------------------------------------------- 822 823then search for a line that looks like 824 825------------------------------------------------- 826+ ++ [e05db0fd] Fix warnings in sha1_file.c - use C99 printf format if 827available 828------------------------------------------------- 829 830Which shows that e05db0fd is reachable from itself, from v1.5.0-rc1, and 831from v1.5.0-rc2, but not from v1.5.0-rc0. 832 833[[showing-commits-unique-to-a-branch]] 834Showing commits unique to a given branch 835~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 836 837Suppose you would like to see all the commits reachable from the branch 838head named "master" but not from any other head in your repository. 839 840We can list all the heads in this repository with 841gitlink:git-show-ref[1]: 842 843------------------------------------------------- 844$ git show-ref --heads 845bf62196b5e363d73353a9dcf094c59595f3153b7 refs/heads/core-tutorial 846db768d5504c1bb46f63ee9d6e1772bd047e05bf9 refs/heads/maint 847a07157ac624b2524a059a3414e99f6f44bebc1e7 refs/heads/master 84824dbc180ea14dc1aebe09f14c8ecf32010690627 refs/heads/tutorial-2 8491e87486ae06626c2f31eaa63d26fc0fd646c8af2 refs/heads/tutorial-fixes 850------------------------------------------------- 851 852We can get just the branch-head names, and remove "master", with 853the help of the standard utilities cut and grep: 854 855------------------------------------------------- 856$ git show-ref --heads | cut -d' ' -f2 | grep -v '^refs/heads/master' 857refs/heads/core-tutorial 858refs/heads/maint 859refs/heads/tutorial-2 860refs/heads/tutorial-fixes 861------------------------------------------------- 862 863And then we can ask to see all the commits reachable from master 864but not from these other heads: 865 866------------------------------------------------- 867$ gitk master --not $( git show-ref --heads | cut -d' ' -f2 | 868 grep -v '^refs/heads/master' ) 869------------------------------------------------- 870 871Obviously, endless variations are possible; for example, to see all 872commits reachable from some head but not from any tag in the repository: 873 874------------------------------------------------- 875$ gitk $( git show-ref --heads ) --not $( git show-ref --tags ) 876------------------------------------------------- 877 878(See gitlink:git-rev-parse[1] for explanations of commit-selecting 879syntax such as `--not`.) 880 881[[making-a-release]] 882Creating a changelog and tarball for a software release 883~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 884 885The gitlink:git-archive[1] command can create a tar or zip archive from 886any version of a project; for example: 887 888------------------------------------------------- 889$ git archive --format=tar --prefix=project/ HEAD | gzip >latest.tar.gz 890------------------------------------------------- 891 892will use HEAD to produce a tar archive in which each filename is 893preceded by "project/". 894 895If you're releasing a new version of a software project, you may want 896to simultaneously make a changelog to include in the release 897announcement. 898 899Linus Torvalds, for example, makes new kernel releases by tagging them, 900then running: 901 902------------------------------------------------- 903$ release-script 2.6.12 2.6.13-rc6 2.6.13-rc7 904------------------------------------------------- 905 906where release-script is a shell script that looks like: 907 908------------------------------------------------- 909#!/bin/sh 910stable="$1" 911last="$2" 912new="$3" 913echo "# git tag v$new" 914echo "git archive --prefix=linux-$new/ v$new | gzip -9 > ../linux-$new.tar.gz" 915echo "git diff v$stable v$new | gzip -9 > ../patch-$new.gz" 916echo "git log --no-merges v$new ^v$last > ../ChangeLog-$new" 917echo "git shortlog --no-merges v$new ^v$last > ../ShortLog" 918echo "git diff --stat --summary -M v$last v$new > ../diffstat-$new" 919------------------------------------------------- 920 921and then he just cut-and-pastes the output commands after verifying that 922they look OK. 923 924[[Finding-comments-with-given-content]] 925Finding commits referencing a file with given content 926----------------------------------------------------- 927 928Somebody hands you a copy of a file, and asks which commits modified a 929file such that it contained the given content either before or after the 930commit. You can find out with this: 931 932------------------------------------------------- 933$ git log --raw -r --abbrev=40 --pretty=oneline -- filename | 934 grep -B 1 `git hash-object filename` 935------------------------------------------------- 936 937Figuring out why this works is left as an exercise to the (advanced) 938student. The gitlink:git-log[1], gitlink:git-diff-tree[1], and 939gitlink:git-hash-object[1] man pages may prove helpful. 940 941[[Developing-with-git]] 942Developing with git 943=================== 944 945[[telling-git-your-name]] 946Telling git your name 947--------------------- 948 949Before creating any commits, you should introduce yourself to git. The 950easiest way to do so is to make sure the following lines appear in a 951file named .gitconfig in your home directory: 952 953------------------------------------------------ 954[user] 955 name = Your Name Comes Here 956 email = you@yourdomain.example.com 957------------------------------------------------ 958 959(See the "CONFIGURATION FILE" section of gitlink:git-config[1] for 960details on the configuration file.) 961 962 963[[creating-a-new-repository]] 964Creating a new repository 965------------------------- 966 967Creating a new repository from scratch is very easy: 968 969------------------------------------------------- 970$ mkdir project 971$ cd project 972$ git init 973------------------------------------------------- 974 975If you have some initial content (say, a tarball): 976 977------------------------------------------------- 978$ tar -xzvf project.tar.gz 979$ cd project 980$ git init 981$ git add . # include everything below ./ in the first commit: 982$ git commit 983------------------------------------------------- 984 985[[how-to-make-a-commit]] 986How to make a commit 987-------------------- 988 989Creating a new commit takes three steps: 990 991 1. Making some changes to the working directory using your 992 favorite editor. 993 2. Telling git about your changes. 994 3. Creating the commit using the content you told git about 995 in step 2. 996 997In practice, you can interleave and repeat steps 1 and 2 as many 998times as you want: in order to keep track of what you want committed 999at step 3, git maintains a snapshot of the tree's contents in a1000special staging area called "the index."10011002At the beginning, the content of the index will be identical to1003that of the HEAD. The command "git diff --cached", which shows1004the difference between the HEAD and the index, should therefore1005produce no output at that point.10061007Modifying the index is easy:10081009To update the index with the new contents of a modified file, use10101011-------------------------------------------------1012$ git add path/to/file1013-------------------------------------------------10141015To add the contents of a new file to the index, use10161017-------------------------------------------------1018$ git add path/to/file1019-------------------------------------------------10201021To remove a file from the index and from the working tree,10221023-------------------------------------------------1024$ git rm path/to/file1025-------------------------------------------------10261027After each step you can verify that10281029-------------------------------------------------1030$ git diff --cached1031-------------------------------------------------10321033always shows the difference between the HEAD and the index file--this1034is what you'd commit if you created the commit now--and that10351036-------------------------------------------------1037$ git diff1038-------------------------------------------------10391040shows the difference between the working tree and the index file.10411042Note that "git add" always adds just the current contents of a file1043to the index; further changes to the same file will be ignored unless1044you run git-add on the file again.10451046When you're ready, just run10471048-------------------------------------------------1049$ git commit1050-------------------------------------------------10511052and git will prompt you for a commit message and then create the new1053commit. Check to make sure it looks like what you expected with10541055-------------------------------------------------1056$ git show1057-------------------------------------------------10581059As a special shortcut,10601061-------------------------------------------------1062$ git commit -a1063-------------------------------------------------10641065will update the index with any files that you've modified or removed1066and create a commit, all in one step.10671068A number of commands are useful for keeping track of what you're1069about to commit:10701071-------------------------------------------------1072$ git diff --cached # difference between HEAD and the index; what1073 # would be committed if you ran "commit" now.1074$ git diff # difference between the index file and your1075 # working directory; changes that would not1076 # be included if you ran "commit" now.1077$ git diff HEAD # difference between HEAD and working tree; what1078 # would be committed if you ran "commit -a" now.1079$ git status # a brief per-file summary of the above.1080-------------------------------------------------10811082You can also use gitlink:git-gui[1] to create commits, view changes in1083the index and the working tree files, and individually select diff hunks1084for inclusion in the index (by right-clicking on the diff hunk and1085choosing "Stage Hunk For Commit").10861087[[creating-good-commit-messages]]1088Creating good commit messages1089-----------------------------10901091Though not required, it's a good idea to begin the commit message1092with a single short (less than 50 character) line summarizing the1093change, followed by a blank line and then a more thorough1094description. Tools that turn commits into email, for example, use1095the first line on the Subject line and the rest of the commit in the1096body.10971098[[ignoring-files]]1099Ignoring files1100--------------11011102A project will often generate files that you do 'not' want to track with git.1103This typically includes files generated by a build process or temporary1104backup files made by your editor. Of course, 'not' tracking files with git1105is just a matter of 'not' calling "`git add`" on them. But it quickly becomes1106annoying to have these untracked files lying around; e.g. they make1107"`git add .`" and "`git commit -a`" practically useless, and they keep1108showing up in the output of "`git status`", etc.11091110Git therefore provides "exclude patterns" for telling git which files to1111actively ignore. Exclude patterns are thoroughly explained in the1112gitlink:gitignore[5] manual page, but the heart of the concept is simply1113a list of files which git should ignore. Entries in the list may contain1114globs to specify multiple files, or may be prefixed by "`!`" to1115explicitly include (un-ignore) a previously excluded (ignored) file1116(i.e. later exclude patterns override earlier ones). The following1117example should illustrate such patterns:11181119-------------------------------------------------1120# Lines starting with '#' are considered comments.1121# Ignore foo.txt.1122foo.txt1123# Ignore (generated) html files,1124*.html1125# except foo.html which is maintained by hand.1126!foo.html1127# Ignore objects and archives.1128*.[oa]1129-------------------------------------------------11301131The next question is where to put these exclude patterns so that git can1132find them. Git looks for exclude patterns in the following files:11331134`.gitignore` files in your working tree:::1135 You may store multiple `.gitignore` files at various locations in your1136 working tree. Each `.gitignore` file is applied to the directory where1137 it's located, including its subdirectories. Furthermore, the1138 `.gitignore` files can be tracked like any other files in your working1139 tree; just do a "`git add .gitignore`" and commit. `.gitignore` is1140 therefore the right place to put exclude patterns that are meant to1141 be shared between all project participants, such as build output files1142 (e.g. `\*.o`), etc.1143`.git/info/exclude` in your repo:::1144 Exclude patterns in this file are applied to the working tree as a1145 whole. Since the file is not located in your working tree, it does1146 not follow push/pull/clone like `.gitignore` can do. This is therefore1147 the place to put exclude patterns that are local to your copy of the1148 repo (i.e. 'not' shared between project participants), such as1149 temporary backup files made by your editor (e.g. `\*~`), etc.1150The file specified by the `core.excludesfile` config directive:::1151 By setting the `core.excludesfile` config directive you can tell git1152 where to find more exclude patterns (see gitlink:git-config[1] for1153 more information on configuration options). This config directive1154 can be set in the per-repo `.git/config` file, in which case the1155 exclude patterns will apply to that repo only. Alternatively, you1156 can set the directive in the global `~/.gitconfig` file to apply1157 the exclude pattern to all your git repos. As with the above1158 `.git/info/exclude` (and, indeed, with git config directives in1159 general), this directive does not follow push/pull/clone, but remain1160 local to your repo(s).11611162[NOTE]1163In addition to the above alternatives, there are git commands that can take1164exclude patterns directly on the command line. See gitlink:git-ls-files[1]1165for an example of this.11661167[[how-to-merge]]1168How to merge1169------------11701171You can rejoin two diverging branches of development using1172gitlink:git-merge[1]:11731174-------------------------------------------------1175$ git merge branchname1176-------------------------------------------------11771178merges the development in the branch "branchname" into the current1179branch. If there are conflicts--for example, if the same file is1180modified in two different ways in the remote branch and the local1181branch--then you are warned; the output may look something like this:11821183-------------------------------------------------1184$ git merge next1185 100% (4/4) done1186Auto-merged file.txt1187CONFLICT (content): Merge conflict in file.txt1188Automatic merge failed; fix conflicts and then commit the result.1189-------------------------------------------------11901191Conflict markers are left in the problematic files, and after1192you resolve the conflicts manually, you can update the index1193with the contents and run git commit, as you normally would when1194creating a new file.11951196If you examine the resulting commit using gitk, you will see that it1197has two parents, one pointing to the top of the current branch, and1198one to the top of the other branch.11991200[[resolving-a-merge]]1201Resolving a merge1202-----------------12031204When a merge isn't resolved automatically, git leaves the index and1205the working tree in a special state that gives you all the1206information you need to help resolve the merge.12071208Files with conflicts are marked specially in the index, so until you1209resolve the problem and update the index, gitlink:git-commit[1] will1210fail:12111212-------------------------------------------------1213$ git commit1214file.txt: needs merge1215-------------------------------------------------12161217Also, gitlink:git-status[1] will list those files as "unmerged", and the1218files with conflicts will have conflict markers added, like this:12191220-------------------------------------------------1221<<<<<<< HEAD:file.txt1222Hello world1223=======1224Goodbye1225>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt1226-------------------------------------------------12271228All you need to do is edit the files to resolve the conflicts, and then12291230-------------------------------------------------1231$ git add file.txt1232$ git commit1233-------------------------------------------------12341235Note that the commit message will already be filled in for you with1236some information about the merge. Normally you can just use this1237default message unchanged, but you may add additional commentary of1238your own if desired.12391240The above is all you need to know to resolve a simple merge. But git1241also provides more information to help resolve conflicts:12421243[[conflict-resolution]]1244Getting conflict-resolution help during a merge1245~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~12461247All of the changes that git was able to merge automatically are1248already added to the index file, so gitlink:git-diff[1] shows only1249the conflicts. It uses an unusual syntax:12501251-------------------------------------------------1252$ git diff1253diff --cc file.txt1254index 802992c,2b60207..00000001255--- a/file.txt1256+++ b/file.txt1257@@@ -1,1 -1,1 +1,5 @@@1258++<<<<<<< HEAD:file.txt1259 +Hello world1260++=======1261+ Goodbye1262++>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt1263-------------------------------------------------12641265Recall that the commit which will be committed after we resolve this1266conflict will have two parents instead of the usual one: one parent1267will be HEAD, the tip of the current branch; the other will be the1268tip of the other branch, which is stored temporarily in MERGE_HEAD.12691270During the merge, the index holds three versions of each file. Each of1271these three "file stages" represents a different version of the file:12721273-------------------------------------------------1274$ git show :1:file.txt # the file in a common ancestor of both branches1275$ git show :2:file.txt # the version from HEAD, but including any1276 # nonconflicting changes from MERGE_HEAD1277$ git show :3:file.txt # the version from MERGE_HEAD, but including any1278 # nonconflicting changes from HEAD.1279-------------------------------------------------12801281Since the stage 2 and stage 3 versions have already been updated with1282nonconflicting changes, the only remaining differences between them are1283the important ones; thus gitlink:git-diff[1] can use the information in1284the index to show only those conflicts.12851286The diff above shows the differences between the working-tree version of1287file.txt and the stage 2 and stage 3 versions. So instead of preceding1288each line by a single "+" or "-", it now uses two columns: the first1289column is used for differences between the first parent and the working1290directory copy, and the second for differences between the second parent1291and the working directory copy. (See the "COMBINED DIFF FORMAT" section1292of gitlink:git-diff-files[1] for a details of the format.)12931294After resolving the conflict in the obvious way (but before updating the1295index), the diff will look like:12961297-------------------------------------------------1298$ git diff1299diff --cc file.txt1300index 802992c,2b60207..00000001301--- a/file.txt1302+++ b/file.txt1303@@@ -1,1 -1,1 +1,1 @@@1304- Hello world1305 -Goodbye1306++Goodbye world1307-------------------------------------------------13081309This shows that our resolved version deleted "Hello world" from the1310first parent, deleted "Goodbye" from the second parent, and added1311"Goodbye world", which was previously absent from both.13121313Some special diff options allow diffing the working directory against1314any of these stages:13151316-------------------------------------------------1317$ git diff -1 file.txt # diff against stage 11318$ git diff --base file.txt # same as the above1319$ git diff -2 file.txt # diff against stage 21320$ git diff --ours file.txt # same as the above1321$ git diff -3 file.txt # diff against stage 31322$ git diff --theirs file.txt # same as the above.1323-------------------------------------------------13241325The gitlink:git-log[1] and gitk[1] commands also provide special help1326for merges:13271328-------------------------------------------------1329$ git log --merge1330$ gitk --merge1331-------------------------------------------------13321333These will display all commits which exist only on HEAD or on1334MERGE_HEAD, and which touch an unmerged file.13351336You may also use gitlink:git-mergetool[1], which lets you merge the1337unmerged files using external tools such as emacs or kdiff3.13381339Each time you resolve the conflicts in a file and update the index:13401341-------------------------------------------------1342$ git add file.txt1343-------------------------------------------------13441345the different stages of that file will be "collapsed", after which1346git-diff will (by default) no longer show diffs for that file.13471348[[undoing-a-merge]]1349Undoing a merge1350---------------13511352If you get stuck and decide to just give up and throw the whole mess1353away, you can always return to the pre-merge state with13541355-------------------------------------------------1356$ git reset --hard HEAD1357-------------------------------------------------13581359Or, if you've already committed the merge that you want to throw away,13601361-------------------------------------------------1362$ git reset --hard ORIG_HEAD1363-------------------------------------------------13641365However, this last command can be dangerous in some cases--never1366throw away a commit you have already committed if that commit may1367itself have been merged into another branch, as doing so may confuse1368further merges.13691370[[fast-forwards]]1371Fast-forward merges1372-------------------13731374There is one special case not mentioned above, which is treated1375differently. Normally, a merge results in a merge commit, with two1376parents, one pointing at each of the two lines of development that1377were merged.13781379However, if the current branch is a descendant of the other--so every1380commit present in the one is already contained in the other--then git1381just performs a "fast forward"; the head of the current branch is moved1382forward to point at the head of the merged-in branch, without any new1383commits being created.13841385[[fixing-mistakes]]1386Fixing mistakes1387---------------13881389If you've messed up the working tree, but haven't yet committed your1390mistake, you can return the entire working tree to the last committed1391state with13921393-------------------------------------------------1394$ git reset --hard HEAD1395-------------------------------------------------13961397If you make a commit that you later wish you hadn't, there are two1398fundamentally different ways to fix the problem:13991400 1. You can create a new commit that undoes whatever was done1401 by the previous commit. This is the correct thing if your1402 mistake has already been made public.14031404 2. You can go back and modify the old commit. You should1405 never do this if you have already made the history public;1406 git does not normally expect the "history" of a project to1407 change, and cannot correctly perform repeated merges from1408 a branch that has had its history changed.14091410[[reverting-a-commit]]1411Fixing a mistake with a new commit1412~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~14131414Creating a new commit that reverts an earlier change is very easy;1415just pass the gitlink:git-revert[1] command a reference to the bad1416commit; for example, to revert the most recent commit:14171418-------------------------------------------------1419$ git revert HEAD1420-------------------------------------------------14211422This will create a new commit which undoes the change in HEAD. You1423will be given a chance to edit the commit message for the new commit.14241425You can also revert an earlier change, for example, the next-to-last:14261427-------------------------------------------------1428$ git revert HEAD^1429-------------------------------------------------14301431In this case git will attempt to undo the old change while leaving1432intact any changes made since then. If more recent changes overlap1433with the changes to be reverted, then you will be asked to fix1434conflicts manually, just as in the case of <<resolving-a-merge,1435resolving a merge>>.14361437[[fixing-a-mistake-by-editing-history]]1438Fixing a mistake by editing history1439~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~14401441If the problematic commit is the most recent commit, and you have not1442yet made that commit public, then you may just1443<<undoing-a-merge,destroy it using git-reset>>.14441445Alternatively, you1446can edit the working directory and update the index to fix your1447mistake, just as if you were going to <<how-to-make-a-commit,create a1448new commit>>, then run14491450-------------------------------------------------1451$ git commit --amend1452-------------------------------------------------14531454which will replace the old commit by a new commit incorporating your1455changes, giving you a chance to edit the old commit message first.14561457Again, you should never do this to a commit that may already have1458been merged into another branch; use gitlink:git-revert[1] instead in1459that case.14601461It is also possible to edit commits further back in the history, but1462this is an advanced topic to be left for1463<<cleaning-up-history,another chapter>>.14641465[[checkout-of-path]]1466Checking out an old version of a file1467~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~14681469In the process of undoing a previous bad change, you may find it1470useful to check out an older version of a particular file using1471gitlink:git-checkout[1]. We've used git checkout before to switch1472branches, but it has quite different behavior if it is given a path1473name: the command14741475-------------------------------------------------1476$ git checkout HEAD^ path/to/file1477-------------------------------------------------14781479replaces path/to/file by the contents it had in the commit HEAD^, and1480also updates the index to match. It does not change branches.14811482If you just want to look at an old version of the file, without1483modifying the working directory, you can do that with1484gitlink:git-show[1]:14851486-------------------------------------------------1487$ git show HEAD^:path/to/file1488-------------------------------------------------14891490which will display the given version of the file.14911492[[interrupted-work]]1493Temporarily setting aside work in progress1494~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~14951496While you are in the middle of working on something complicated, you1497find an unrelated but obvious and trivial bug. You would like to fix it1498before continuing. You can use gitlink:git-stash[1] to save the current1499state of your work, and after fixing the bug (or, optionally after doing1500so on a different branch and then coming back), unstash the1501work-in-progress changes.15021503------------------------------------------------1504$ git stash "work in progress for foo feature"1505------------------------------------------------15061507This command will save your changes away to the `stash`, and1508reset your working tree and the index to match the tip of your1509current branch. Then you can make your fix as usual.15101511------------------------------------------------1512... edit and test ...1513$ git commit -a -m "blorpl: typofix"1514------------------------------------------------15151516After that, you can go back to what you were working on with1517`git stash apply`:15181519------------------------------------------------1520$ git stash apply1521------------------------------------------------152215231524[[ensuring-good-performance]]1525Ensuring good performance1526-------------------------15271528On large repositories, git depends on compression to keep the history1529information from taking up to much space on disk or in memory.15301531This compression is not performed automatically. Therefore you1532should occasionally run gitlink:git-gc[1]:15331534-------------------------------------------------1535$ git gc1536-------------------------------------------------15371538to recompress the archive. This can be very time-consuming, so1539you may prefer to run git-gc when you are not doing other work.154015411542[[ensuring-reliability]]1543Ensuring reliability1544--------------------15451546[[checking-for-corruption]]1547Checking the repository for corruption1548~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~15491550The gitlink:git-fsck[1] command runs a number of self-consistency checks1551on the repository, and reports on any problems. This may take some1552time. The most common warning by far is about "dangling" objects:15531554-------------------------------------------------1555$ git fsck1556dangling commit 7281251ddd2a61e38657c827739c57015671a6b31557dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a631558dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b51559dangling blob 218761f9d90712d37a9c5e36f406f92202db07eb1560dangling commit bf093535a34a4d35731aa2bd90fe6b176302f14f1561dangling commit 8e4bec7f2ddaa268bef999853c25755452100f8e1562dangling tree d50bb86186bf27b681d25af89d3b5b68382e40851563dangling tree b24c2473f1fd3d91352a624795be026d64c8841f1564...1565-------------------------------------------------15661567Dangling objects are not a problem. At worst they may take up a little1568extra disk space. They can sometimes provide a last-resort method for1569recovering lost work--see <<dangling-objects>> for details. However, if1570you wish, you can remove them with gitlink:git-prune[1] or the --prune1571option to gitlink:git-gc[1]:15721573-------------------------------------------------1574$ git gc --prune1575-------------------------------------------------15761577This may be time-consuming. Unlike most other git operations (including1578git-gc when run without any options), it is not safe to prune while1579other git operations are in progress in the same repository.15801581[[recovering-lost-changes]]1582Recovering lost changes1583~~~~~~~~~~~~~~~~~~~~~~~15841585[[reflogs]]1586Reflogs1587^^^^^^^15881589Say you modify a branch with gitlink:git-reset[1] --hard, and then1590realize that the branch was the only reference you had to that point in1591history.15921593Fortunately, git also keeps a log, called a "reflog", of all the1594previous values of each branch. So in this case you can still find the1595old history using, for example,15961597-------------------------------------------------1598$ git log master@{1}1599-------------------------------------------------16001601This lists the commits reachable from the previous version of the head.1602This syntax can be used to with any git command that accepts a commit,1603not just with git log. Some other examples:16041605-------------------------------------------------1606$ git show master@{2} # See where the branch pointed 2,1607$ git show master@{3} # 3, ... changes ago.1608$ gitk master@{yesterday} # See where it pointed yesterday,1609$ gitk master@{"1 week ago"} # ... or last week1610$ git log --walk-reflogs master # show reflog entries for master1611-------------------------------------------------16121613A separate reflog is kept for the HEAD, so16141615-------------------------------------------------1616$ git show HEAD@{"1 week ago"}1617-------------------------------------------------16181619will show what HEAD pointed to one week ago, not what the current branch1620pointed to one week ago. This allows you to see the history of what1621you've checked out.16221623The reflogs are kept by default for 30 days, after which they may be1624pruned. See gitlink:git-reflog[1] and gitlink:git-gc[1] to learn1625how to control this pruning, and see the "SPECIFYING REVISIONS"1626section of gitlink:git-rev-parse[1] for details.16271628Note that the reflog history is very different from normal git history.1629While normal history is shared by every repository that works on the1630same project, the reflog history is not shared: it tells you only about1631how the branches in your local repository have changed over time.16321633[[dangling-object-recovery]]1634Examining dangling objects1635^^^^^^^^^^^^^^^^^^^^^^^^^^16361637In some situations the reflog may not be able to save you. For example,1638suppose you delete a branch, then realize you need the history it1639contained. The reflog is also deleted; however, if you have not yet1640pruned the repository, then you may still be able to find the lost1641commits in the dangling objects that git-fsck reports. See1642<<dangling-objects>> for the details.16431644-------------------------------------------------1645$ git fsck1646dangling commit 7281251ddd2a61e38657c827739c57015671a6b31647dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a631648dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b51649...1650-------------------------------------------------16511652You can examine1653one of those dangling commits with, for example,16541655------------------------------------------------1656$ gitk 7281251ddd --not --all1657------------------------------------------------16581659which does what it sounds like: it says that you want to see the commit1660history that is described by the dangling commit(s), but not the1661history that is described by all your existing branches and tags. Thus1662you get exactly the history reachable from that commit that is lost.1663(And notice that it might not be just one commit: we only report the1664"tip of the line" as being dangling, but there might be a whole deep1665and complex commit history that was dropped.)16661667If you decide you want the history back, you can always create a new1668reference pointing to it, for example, a new branch:16691670------------------------------------------------1671$ git branch recovered-branch 7281251ddd1672------------------------------------------------16731674Other types of dangling objects (blobs and trees) are also possible, and1675dangling objects can arise in other situations.167616771678[[sharing-development]]1679Sharing development with others1680===============================16811682[[getting-updates-with-git-pull]]1683Getting updates with git pull1684-----------------------------16851686After you clone a repository and make a few changes of your own, you1687may wish to check the original repository for updates and merge them1688into your own work.16891690We have already seen <<Updating-a-repository-with-git-fetch,how to1691keep remote tracking branches up to date>> with gitlink:git-fetch[1],1692and how to merge two branches. So you can merge in changes from the1693original repository's master branch with:16941695-------------------------------------------------1696$ git fetch1697$ git merge origin/master1698-------------------------------------------------16991700However, the gitlink:git-pull[1] command provides a way to do this in1701one step:17021703-------------------------------------------------1704$ git pull origin master1705-------------------------------------------------17061707In fact, if you have "master" checked out, then by default "git pull"1708merges from the HEAD branch of the origin repository. So often you can1709accomplish the above with just a simple17101711-------------------------------------------------1712$ git pull1713-------------------------------------------------17141715More generally, a branch that is created from a remote branch will pull1716by default from that branch. See the descriptions of the1717branch.<name>.remote and branch.<name>.merge options in1718gitlink:git-config[1], and the discussion of the --track option in1719gitlink:git-checkout[1], to learn how to control these defaults.17201721In addition to saving you keystrokes, "git pull" also helps you by1722producing a default commit message documenting the branch and1723repository that you pulled from.17241725(But note that no such commit will be created in the case of a1726<<fast-forwards,fast forward>>; instead, your branch will just be1727updated to point to the latest commit from the upstream branch.)17281729The git-pull command can also be given "." as the "remote" repository,1730in which case it just merges in a branch from the current repository; so1731the commands17321733-------------------------------------------------1734$ git pull . branch1735$ git merge branch1736-------------------------------------------------17371738are roughly equivalent. The former is actually very commonly used.17391740[[submitting-patches]]1741Submitting patches to a project1742-------------------------------17431744If you just have a few changes, the simplest way to submit them may1745just be to send them as patches in email:17461747First, use gitlink:git-format-patch[1]; for example:17481749-------------------------------------------------1750$ git format-patch origin1751-------------------------------------------------17521753will produce a numbered series of files in the current directory, one1754for each patch in the current branch but not in origin/HEAD.17551756You can then import these into your mail client and send them by1757hand. However, if you have a lot to send at once, you may prefer to1758use the gitlink:git-send-email[1] script to automate the process.1759Consult the mailing list for your project first to determine how they1760prefer such patches be handled.17611762[[importing-patches]]1763Importing patches to a project1764------------------------------17651766Git also provides a tool called gitlink:git-am[1] (am stands for1767"apply mailbox"), for importing such an emailed series of patches.1768Just save all of the patch-containing messages, in order, into a1769single mailbox file, say "patches.mbox", then run17701771-------------------------------------------------1772$ git am -3 patches.mbox1773-------------------------------------------------17741775Git will apply each patch in order; if any conflicts are found, it1776will stop, and you can fix the conflicts as described in1777"<<resolving-a-merge,Resolving a merge>>". (The "-3" option tells1778git to perform a merge; if you would prefer it just to abort and1779leave your tree and index untouched, you may omit that option.)17801781Once the index is updated with the results of the conflict1782resolution, instead of creating a new commit, just run17831784-------------------------------------------------1785$ git am --resolved1786-------------------------------------------------17871788and git will create the commit for you and continue applying the1789remaining patches from the mailbox.17901791The final result will be a series of commits, one for each patch in1792the original mailbox, with authorship and commit log message each1793taken from the message containing each patch.17941795[[public-repositories]]1796Public git repositories1797-----------------------17981799Another way to submit changes to a project is to tell the maintainer of1800that project to pull the changes from your repository using git-pull[1].1801In the section "<<getting-updates-with-git-pull, Getting updates with1802git pull>>" we described this as a way to get updates from the "main"1803repository, but it works just as well in the other direction.18041805If you and the maintainer both have accounts on the same machine, then1806you can just pull changes from each other's repositories directly;1807commands that accept repository URLs as arguments will also accept a1808local directory name:18091810-------------------------------------------------1811$ git clone /path/to/repository1812$ git pull /path/to/other/repository1813-------------------------------------------------18141815or an ssh url:18161817-------------------------------------------------1818$ git clone ssh://yourhost/~you/repository1819-------------------------------------------------18201821For projects with few developers, or for synchronizing a few private1822repositories, this may be all you need.18231824However, the more common way to do this is to maintain a separate public1825repository (usually on a different host) for others to pull changes1826from. This is usually more convenient, and allows you to cleanly1827separate private work in progress from publicly visible work.18281829You will continue to do your day-to-day work in your personal1830repository, but periodically "push" changes from your personal1831repository into your public repository, allowing other developers to1832pull from that repository. So the flow of changes, in a situation1833where there is one other developer with a public repository, looks1834like this:18351836 you push1837 your personal repo ------------------> your public repo1838 ^ |1839 | |1840 | you pull | they pull1841 | |1842 | |1843 | they push V1844 their public repo <------------------- their repo18451846We explain how to do this in the following sections.18471848[[setting-up-a-public-repository]]1849Setting up a public repository1850~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~18511852Assume your personal repository is in the directory ~/proj. We1853first create a new clone of the repository and tell git-daemon that it1854is meant to be public:18551856-------------------------------------------------1857$ git clone --bare ~/proj proj.git1858$ touch proj.git/git-daemon-export-ok1859-------------------------------------------------18601861The resulting directory proj.git contains a "bare" git repository--it is1862just the contents of the ".git" directory, without any files checked out1863around it.18641865Next, copy proj.git to the server where you plan to host the1866public repository. You can use scp, rsync, or whatever is most1867convenient.18681869[[exporting-via-git]]1870Exporting a git repository via the git protocol1871~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~18721873This is the preferred method.18741875If someone else administers the server, they should tell you what1876directory to put the repository in, and what git:// url it will appear1877at. You can then skip to the section1878"<<pushing-changes-to-a-public-repository,Pushing changes to a public1879repository>>", below.18801881Otherwise, all you need to do is start gitlink:git-daemon[1]; it will1882listen on port 9418. By default, it will allow access to any directory1883that looks like a git directory and contains the magic file1884git-daemon-export-ok. Passing some directory paths as git-daemon1885arguments will further restrict the exports to those paths.18861887You can also run git-daemon as an inetd service; see the1888gitlink:git-daemon[1] man page for details. (See especially the1889examples section.)18901891[[exporting-via-http]]1892Exporting a git repository via http1893~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~18941895The git protocol gives better performance and reliability, but on a1896host with a web server set up, http exports may be simpler to set up.18971898All you need to do is place the newly created bare git repository in1899a directory that is exported by the web server, and make some1900adjustments to give web clients some extra information they need:19011902-------------------------------------------------1903$ mv proj.git /home/you/public_html/proj.git1904$ cd proj.git1905$ git --bare update-server-info1906$ chmod a+x hooks/post-update1907-------------------------------------------------19081909(For an explanation of the last two lines, see1910gitlink:git-update-server-info[1], and the documentation1911link:hooks.html[Hooks used by git].)19121913Advertise the url of proj.git. Anybody else should then be able to1914clone or pull from that url, for example with a commandline like:19151916-------------------------------------------------1917$ git clone http://yourserver.com/~you/proj.git1918-------------------------------------------------19191920(See also1921link:howto/setup-git-server-over-http.txt[setup-git-server-over-http]1922for a slightly more sophisticated setup using WebDAV which also1923allows pushing over http.)19241925[[pushing-changes-to-a-public-repository]]1926Pushing changes to a public repository1927~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~19281929Note that the two techniques outlined above (exporting via1930<<exporting-via-http,http>> or <<exporting-via-git,git>>) allow other1931maintainers to fetch your latest changes, but they do not allow write1932access, which you will need to update the public repository with the1933latest changes created in your private repository.19341935The simplest way to do this is using gitlink:git-push[1] and ssh; to1936update the remote branch named "master" with the latest state of your1937branch named "master", run19381939-------------------------------------------------1940$ git push ssh://yourserver.com/~you/proj.git master:master1941-------------------------------------------------19421943or just19441945-------------------------------------------------1946$ git push ssh://yourserver.com/~you/proj.git master1947-------------------------------------------------19481949As with git-fetch, git-push will complain if this does not result in1950a <<fast-forwards,fast forward>>. Normally this is a sign of1951something wrong. However, if you are sure you know what you're1952doing, you may force git-push to perform the update anyway by1953proceeding the branch name by a plus sign:19541955-------------------------------------------------1956$ git push ssh://yourserver.com/~you/proj.git +master1957-------------------------------------------------19581959Note that the target of a "push" is normally a1960<<def_bare_repository,bare>> repository. You can also push to a1961repository that has a checked-out working tree, but the working tree1962will not be updated by the push. This may lead to unexpected results if1963the branch you push to is the currently checked-out branch!19641965As with git-fetch, you may also set up configuration options to1966save typing; so, for example, after19671968-------------------------------------------------1969$ cat >>.git/config <<EOF1970[remote "public-repo"]1971 url = ssh://yourserver.com/~you/proj.git1972EOF1973-------------------------------------------------19741975you should be able to perform the above push with just19761977-------------------------------------------------1978$ git push public-repo master1979-------------------------------------------------19801981See the explanations of the remote.<name>.url, branch.<name>.remote,1982and remote.<name>.push options in gitlink:git-config[1] for1983details.19841985[[setting-up-a-shared-repository]]1986Setting up a shared repository1987~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~19881989Another way to collaborate is by using a model similar to that1990commonly used in CVS, where several developers with special rights1991all push to and pull from a single shared repository. See1992link:cvs-migration.html[git for CVS users] for instructions on how to1993set this up.19941995However, while there is nothing wrong with git's support for shared1996repositories, this mode of operation is not generally recommended,1997simply because the mode of collaboration that git supports--by1998exchanging patches and pulling from public repositories--has so many1999advantages over the central shared repository:20002001 - Git's ability to quickly import and merge patches allows a2002 single maintainer to process incoming changes even at very2003 high rates. And when that becomes too much, git-pull provides2004 an easy way for that maintainer to delegate this job to other2005 maintainers while still allowing optional review of incoming2006 changes.2007 - Since every developer's repository has the same complete copy2008 of the project history, no repository is special, and it is2009 trivial for another developer to take over maintenance of a2010 project, either by mutual agreement, or because a maintainer2011 becomes unresponsive or difficult to work with.2012 - The lack of a central group of "committers" means there is2013 less need for formal decisions about who is "in" and who is2014 "out".20152016[[setting-up-gitweb]]2017Allowing web browsing of a repository2018~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~20192020The gitweb cgi script provides users an easy way to browse your2021project's files and history without having to install git; see the file2022gitweb/INSTALL in the git source tree for instructions on setting it up.20232024[[sharing-development-examples]]2025Examples2026--------20272028[[maintaining-topic-branches]]2029Maintaining topic branches for a Linux subsystem maintainer2030~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~20312032This describes how Tony Luck uses git in his role as maintainer of the2033IA64 architecture for the Linux kernel.20342035He uses two public branches:20362037 - A "test" tree into which patches are initially placed so that they2038 can get some exposure when integrated with other ongoing development.2039 This tree is available to Andrew for pulling into -mm whenever he2040 wants.20412042 - A "release" tree into which tested patches are moved for final sanity2043 checking, and as a vehicle to send them upstream to Linus (by sending2044 him a "please pull" request.)20452046He also uses a set of temporary branches ("topic branches"), each2047containing a logical grouping of patches.20482049To set this up, first create your work tree by cloning Linus's public2050tree:20512052-------------------------------------------------2053$ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git work2054$ cd work2055-------------------------------------------------20562057Linus's tree will be stored in the remote branch named origin/master,2058and can be updated using gitlink:git-fetch[1]; you can track other2059public trees using gitlink:git-remote[1] to set up a "remote" and2060git-fetch[1] to keep them up-to-date; see <<repositories-and-branches>>.20612062Now create the branches in which you are going to work; these start out2063at the current tip of origin/master branch, and should be set up (using2064the --track option to gitlink:git-branch[1]) to merge changes in from2065Linus by default.20662067-------------------------------------------------2068$ git branch --track test origin/master2069$ git branch --track release origin/master2070-------------------------------------------------20712072These can be easily kept up to date using gitlink:git-pull[1]20732074-------------------------------------------------2075$ git checkout test && git pull2076$ git checkout release && git pull2077-------------------------------------------------20782079Important note! If you have any local changes in these branches, then2080this merge will create a commit object in the history (with no local2081changes git will simply do a "Fast forward" merge). Many people dislike2082the "noise" that this creates in the Linux history, so you should avoid2083doing this capriciously in the "release" branch, as these noisy commits2084will become part of the permanent history when you ask Linus to pull2085from the release branch.20862087A few configuration variables (see gitlink:git-config[1]) can2088make it easy to push both branches to your public tree. (See2089<<setting-up-a-public-repository>>.)20902091-------------------------------------------------2092$ cat >> .git/config <<EOF2093[remote "mytree"]2094 url = master.kernel.org:/pub/scm/linux/kernel/git/aegl/linux-2.6.git2095 push = release2096 push = test2097EOF2098-------------------------------------------------20992100Then you can push both the test and release trees using2101gitlink:git-push[1]:21022103-------------------------------------------------2104$ git push mytree2105-------------------------------------------------21062107or push just one of the test and release branches using:21082109-------------------------------------------------2110$ git push mytree test2111-------------------------------------------------21122113or21142115-------------------------------------------------2116$ git push mytree release2117-------------------------------------------------21182119Now to apply some patches from the community. Think of a short2120snappy name for a branch to hold this patch (or related group of2121patches), and create a new branch from the current tip of Linus's2122branch:21232124-------------------------------------------------2125$ git checkout -b speed-up-spinlocks origin2126-------------------------------------------------21272128Now you apply the patch(es), run some tests, and commit the change(s). If2129the patch is a multi-part series, then you should apply each as a separate2130commit to this branch.21312132-------------------------------------------------2133$ ... patch ... test ... commit [ ... patch ... test ... commit ]*2134-------------------------------------------------21352136When you are happy with the state of this change, you can pull it into the2137"test" branch in preparation to make it public:21382139-------------------------------------------------2140$ git checkout test && git pull . speed-up-spinlocks2141-------------------------------------------------21422143It is unlikely that you would have any conflicts here ... but you might if you2144spent a while on this step and had also pulled new versions from upstream.21452146Some time later when enough time has passed and testing done, you can pull the2147same branch into the "release" tree ready to go upstream. This is where you2148see the value of keeping each patch (or patch series) in its own branch. It2149means that the patches can be moved into the "release" tree in any order.21502151-------------------------------------------------2152$ git checkout release && git pull . speed-up-spinlocks2153-------------------------------------------------21542155After a while, you will have a number of branches, and despite the2156well chosen names you picked for each of them, you may forget what2157they are for, or what status they are in. To get a reminder of what2158changes are in a specific branch, use:21592160-------------------------------------------------2161$ git log linux..branchname | git-shortlog2162-------------------------------------------------21632164To see whether it has already been merged into the test or release branches2165use:21662167-------------------------------------------------2168$ git log test..branchname2169-------------------------------------------------21702171or21722173-------------------------------------------------2174$ git log release..branchname2175-------------------------------------------------21762177(If this branch has not yet been merged you will see some log entries.2178If it has been merged, then there will be no output.)21792180Once a patch completes the great cycle (moving from test to release,2181then pulled by Linus, and finally coming back into your local2182"origin/master" branch) the branch for this change is no longer needed.2183You detect this when the output from:21842185-------------------------------------------------2186$ git log origin..branchname2187-------------------------------------------------21882189is empty. At this point the branch can be deleted:21902191-------------------------------------------------2192$ git branch -d branchname2193-------------------------------------------------21942195Some changes are so trivial that it is not necessary to create a separate2196branch and then merge into each of the test and release branches. For2197these changes, just apply directly to the "release" branch, and then2198merge that into the "test" branch.21992200To create diffstat and shortlog summaries of changes to include in a "please2201pull" request to Linus you can use:22022203-------------------------------------------------2204$ git diff --stat origin..release2205-------------------------------------------------22062207and22082209-------------------------------------------------2210$ git log -p origin..release | git shortlog2211-------------------------------------------------22122213Here are some of the scripts that simplify all this even further.22142215-------------------------------------------------2216==== update script ====2217# Update a branch in my GIT tree. If the branch to be updated2218# is origin, then pull from kernel.org. Otherwise merge2219# origin/master branch into test|release branch22202221case "$1" in2222test|release)2223 git checkout $1 && git pull . origin2224 ;;2225origin)2226 before=$(cat .git/refs/remotes/origin/master)2227 git fetch origin2228 after=$(cat .git/refs/remotes/origin/master)2229 if [ $before != $after ]2230 then2231 git log $before..$after | git shortlog2232 fi2233 ;;2234*)2235 echo "Usage: $0 origin|test|release" 1>&22236 exit 12237 ;;2238esac2239-------------------------------------------------22402241-------------------------------------------------2242==== merge script ====2243# Merge a branch into either the test or release branch22442245pname=$022462247usage()2248{2249 echo "Usage: $pname branch test|release" 1>&22250 exit 12251}22522253if [ ! -f .git/refs/heads/"$1" ]2254then2255 echo "Can't see branch <$1>" 1>&22256 usage2257fi22582259case "$2" in2260test|release)2261 if [ $(git log $2..$1 | wc -c) -eq 0 ]2262 then2263 echo $1 already merged into $2 1>&22264 exit 12265 fi2266 git checkout $2 && git pull . $12267 ;;2268*)2269 usage2270 ;;2271esac2272-------------------------------------------------22732274-------------------------------------------------2275==== status script ====2276# report on status of my ia64 GIT tree22772278gb=$(tput setab 2)2279rb=$(tput setab 1)2280restore=$(tput setab 9)22812282if [ `git rev-list test..release | wc -c` -gt 0 ]2283then2284 echo $rb Warning: commits in release that are not in test $restore2285 git log test..release2286fi22872288for branch in `ls .git/refs/heads`2289do2290 if [ $branch = test -o $branch = release ]2291 then2292 continue2293 fi22942295 echo -n $gb ======= $branch ====== $restore " "2296 status=2297 for ref in test release origin/master2298 do2299 if [ `git rev-list $ref..$branch | wc -c` -gt 0 ]2300 then2301 status=$status${ref:0:1}2302 fi2303 done2304 case $status in2305 trl)2306 echo $rb Need to pull into test $restore2307 ;;2308 rl)2309 echo "In test"2310 ;;2311 l)2312 echo "Waiting for linus"2313 ;;2314 "")2315 echo $rb All done $restore2316 ;;2317 *)2318 echo $rb "<$status>" $restore2319 ;;2320 esac2321 git log origin/master..$branch | git shortlog2322done2323-------------------------------------------------232423252326[[cleaning-up-history]]2327Rewriting history and maintaining patch series2328==============================================23292330Normally commits are only added to a project, never taken away or2331replaced. Git is designed with this assumption, and violating it will2332cause git's merge machinery (for example) to do the wrong thing.23332334However, there is a situation in which it can be useful to violate this2335assumption.23362337[[patch-series]]2338Creating the perfect patch series2339---------------------------------23402341Suppose you are a contributor to a large project, and you want to add a2342complicated feature, and to present it to the other developers in a way2343that makes it easy for them to read your changes, verify that they are2344correct, and understand why you made each change.23452346If you present all of your changes as a single patch (or commit), they2347may find that it is too much to digest all at once.23482349If you present them with the entire history of your work, complete with2350mistakes, corrections, and dead ends, they may be overwhelmed.23512352So the ideal is usually to produce a series of patches such that:23532354 1. Each patch can be applied in order.23552356 2. Each patch includes a single logical change, together with a2357 message explaining the change.23582359 3. No patch introduces a regression: after applying any initial2360 part of the series, the resulting project still compiles and2361 works, and has no bugs that it didn't have before.23622363 4. The complete series produces the same end result as your own2364 (probably much messier!) development process did.23652366We will introduce some tools that can help you do this, explain how to2367use them, and then explain some of the problems that can arise because2368you are rewriting history.23692370[[using-git-rebase]]2371Keeping a patch series up to date using git-rebase2372--------------------------------------------------23732374Suppose that you create a branch "mywork" on a remote-tracking branch2375"origin", and create some commits on top of it:23762377-------------------------------------------------2378$ git checkout -b mywork origin2379$ vi file.txt2380$ git commit2381$ vi otherfile.txt2382$ git commit2383...2384-------------------------------------------------23852386You have performed no merges into mywork, so it is just a simple linear2387sequence of patches on top of "origin":23882389................................................2390 o--o--o <-- origin2391 \2392 o--o--o <-- mywork2393................................................23942395Some more interesting work has been done in the upstream project, and2396"origin" has advanced:23972398................................................2399 o--o--O--o--o--o <-- origin2400 \2401 a--b--c <-- mywork2402................................................24032404At this point, you could use "pull" to merge your changes back in;2405the result would create a new merge commit, like this:24062407................................................2408 o--o--O--o--o--o <-- origin2409 \ \2410 a--b--c--m <-- mywork2411................................................24122413However, if you prefer to keep the history in mywork a simple series of2414commits without any merges, you may instead choose to use2415gitlink:git-rebase[1]:24162417-------------------------------------------------2418$ git checkout mywork2419$ git rebase origin2420-------------------------------------------------24212422This will remove each of your commits from mywork, temporarily saving2423them as patches (in a directory named ".dotest"), update mywork to2424point at the latest version of origin, then apply each of the saved2425patches to the new mywork. The result will look like:242624272428................................................2429 o--o--O--o--o--o <-- origin2430 \2431 a'--b'--c' <-- mywork2432................................................24332434In the process, it may discover conflicts. In that case it will stop2435and allow you to fix the conflicts; after fixing conflicts, use "git2436add" to update the index with those contents, and then, instead of2437running git-commit, just run24382439-------------------------------------------------2440$ git rebase --continue2441-------------------------------------------------24422443and git will continue applying the rest of the patches.24442445At any point you may use the --abort option to abort this process and2446return mywork to the state it had before you started the rebase:24472448-------------------------------------------------2449$ git rebase --abort2450-------------------------------------------------24512452[[modifying-one-commit]]2453Modifying a single commit2454-------------------------24552456We saw in <<fixing-a-mistake-by-editing-history>> that you can replace the2457most recent commit using24582459-------------------------------------------------2460$ git commit --amend2461-------------------------------------------------24622463which will replace the old commit by a new commit incorporating your2464changes, giving you a chance to edit the old commit message first.24652466You can also use a combination of this and gitlink:git-rebase[1] to edit2467commits further back in your history. First, tag the problematic commit with24682469-------------------------------------------------2470$ git tag bad mywork~52471-------------------------------------------------24722473(Either gitk or git-log may be useful for finding the commit.)24742475Then check out that commit, edit it, and rebase the rest of the series2476on top of it (note that we could check out the commit on a temporary2477branch, but instead we're using a <<detached-head,detached head>>):24782479-------------------------------------------------2480$ git checkout bad2481$ # make changes here and update the index2482$ git commit --amend2483$ git rebase --onto HEAD bad mywork2484-------------------------------------------------24852486When you're done, you'll be left with mywork checked out, with the top2487patches on mywork reapplied on top of your modified commit. You can2488then clean up with24892490-------------------------------------------------2491$ git tag -d bad2492-------------------------------------------------24932494Note that the immutable nature of git history means that you haven't really2495"modified" existing commits; instead, you have replaced the old commits with2496new commits having new object names.24972498[[reordering-patch-series]]2499Reordering or selecting from a patch series2500-------------------------------------------25012502Given one existing commit, the gitlink:git-cherry-pick[1] command2503allows you to apply the change introduced by that commit and create a2504new commit that records it. So, for example, if "mywork" points to a2505series of patches on top of "origin", you might do something like:25062507-------------------------------------------------2508$ git checkout -b mywork-new origin2509$ gitk origin..mywork &2510-------------------------------------------------25112512And browse through the list of patches in the mywork branch using gitk,2513applying them (possibly in a different order) to mywork-new using2514cherry-pick, and possibly modifying them as you go using commit --amend.2515The git-gui[1] command may also help as it allows you to individually2516select diff hunks for inclusion in the index (by right-clicking on the2517diff hunk and choosing "Stage Hunk for Commit").25182519Another technique is to use git-format-patch to create a series of2520patches, then reset the state to before the patches:25212522-------------------------------------------------2523$ git format-patch origin2524$ git reset --hard origin2525-------------------------------------------------25262527Then modify, reorder, or eliminate patches as preferred before applying2528them again with gitlink:git-am[1].25292530[[patch-series-tools]]2531Other tools2532-----------25332534There are numerous other tools, such as stgit, which exist for the2535purpose of maintaining a patch series. These are outside of the scope of2536this manual.25372538[[problems-with-rewriting-history]]2539Problems with rewriting history2540-------------------------------25412542The primary problem with rewriting the history of a branch has to do2543with merging. Suppose somebody fetches your branch and merges it into2544their branch, with a result something like this:25452546................................................2547 o--o--O--o--o--o <-- origin2548 \ \2549 t--t--t--m <-- their branch:2550................................................25512552Then suppose you modify the last three commits:25532554................................................2555 o--o--o <-- new head of origin2556 /2557 o--o--O--o--o--o <-- old head of origin2558................................................25592560If we examined all this history together in one repository, it will2561look like:25622563................................................2564 o--o--o <-- new head of origin2565 /2566 o--o--O--o--o--o <-- old head of origin2567 \ \2568 t--t--t--m <-- their branch:2569................................................25702571Git has no way of knowing that the new head is an updated version of2572the old head; it treats this situation exactly the same as it would if2573two developers had independently done the work on the old and new heads2574in parallel. At this point, if someone attempts to merge the new head2575in to their branch, git will attempt to merge together the two (old and2576new) lines of development, instead of trying to replace the old by the2577new. The results are likely to be unexpected.25782579You may still choose to publish branches whose history is rewritten,2580and it may be useful for others to be able to fetch those branches in2581order to examine or test them, but they should not attempt to pull such2582branches into their own work.25832584For true distributed development that supports proper merging,2585published branches should never be rewritten.25862587[[advanced-branch-management]]2588Advanced branch management2589==========================25902591[[fetching-individual-branches]]2592Fetching individual branches2593----------------------------25942595Instead of using gitlink:git-remote[1], you can also choose just2596to update one branch at a time, and to store it locally under an2597arbitrary name:25982599-------------------------------------------------2600$ git fetch origin todo:my-todo-work2601-------------------------------------------------26022603The first argument, "origin", just tells git to fetch from the2604repository you originally cloned from. The second argument tells git2605to fetch the branch named "todo" from the remote repository, and to2606store it locally under the name refs/heads/my-todo-work.26072608You can also fetch branches from other repositories; so26092610-------------------------------------------------2611$ git fetch git://example.com/proj.git master:example-master2612-------------------------------------------------26132614will create a new branch named "example-master" and store in it the2615branch named "master" from the repository at the given URL. If you2616already have a branch named example-master, it will attempt to2617<<fast-forwards,fast-forward>> to the commit given by example.com's2618master branch. In more detail:26192620[[fetch-fast-forwards]]2621git fetch and fast-forwards2622---------------------------26232624In the previous example, when updating an existing branch, "git2625fetch" checks to make sure that the most recent commit on the remote2626branch is a descendant of the most recent commit on your copy of the2627branch before updating your copy of the branch to point at the new2628commit. Git calls this process a <<fast-forwards,fast forward>>.26292630A fast forward looks something like this:26312632................................................2633 o--o--o--o <-- old head of the branch2634 \2635 o--o--o <-- new head of the branch2636................................................263726382639In some cases it is possible that the new head will *not* actually be2640a descendant of the old head. For example, the developer may have2641realized she made a serious mistake, and decided to backtrack,2642resulting in a situation like:26432644................................................2645 o--o--o--o--a--b <-- old head of the branch2646 \2647 o--o--o <-- new head of the branch2648................................................26492650In this case, "git fetch" will fail, and print out a warning.26512652In that case, you can still force git to update to the new head, as2653described in the following section. However, note that in the2654situation above this may mean losing the commits labeled "a" and "b",2655unless you've already created a reference of your own pointing to2656them.26572658[[forcing-fetch]]2659Forcing git fetch to do non-fast-forward updates2660------------------------------------------------26612662If git fetch fails because the new head of a branch is not a2663descendant of the old head, you may force the update with:26642665-------------------------------------------------2666$ git fetch git://example.com/proj.git +master:refs/remotes/example/master2667-------------------------------------------------26682669Note the addition of the "+" sign. Alternatively, you can use the "-f"2670flag to force updates of all the fetched branches, as in:26712672-------------------------------------------------2673$ git fetch -f origin2674-------------------------------------------------26752676Be aware that commits that the old version of example/master pointed at2677may be lost, as we saw in the previous section.26782679[[remote-branch-configuration]]2680Configuring remote branches2681---------------------------26822683We saw above that "origin" is just a shortcut to refer to the2684repository that you originally cloned from. This information is2685stored in git configuration variables, which you can see using2686gitlink:git-config[1]:26872688-------------------------------------------------2689$ git config -l2690core.repositoryformatversion=02691core.filemode=true2692core.logallrefupdates=true2693remote.origin.url=git://git.kernel.org/pub/scm/git/git.git2694remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*2695branch.master.remote=origin2696branch.master.merge=refs/heads/master2697-------------------------------------------------26982699If there are other repositories that you also use frequently, you can2700create similar configuration options to save typing; for example,2701after27022703-------------------------------------------------2704$ git config remote.example.url git://example.com/proj.git2705-------------------------------------------------27062707then the following two commands will do the same thing:27082709-------------------------------------------------2710$ git fetch git://example.com/proj.git master:refs/remotes/example/master2711$ git fetch example master:refs/remotes/example/master2712-------------------------------------------------27132714Even better, if you add one more option:27152716-------------------------------------------------2717$ git config remote.example.fetch master:refs/remotes/example/master2718-------------------------------------------------27192720then the following commands will all do the same thing:27212722-------------------------------------------------2723$ git fetch git://example.com/proj.git master:refs/remotes/example/master2724$ git fetch example master:refs/remotes/example/master2725$ git fetch example2726-------------------------------------------------27272728You can also add a "+" to force the update each time:27292730-------------------------------------------------2731$ git config remote.example.fetch +master:ref/remotes/example/master2732-------------------------------------------------27332734Don't do this unless you're sure you won't mind "git fetch" possibly2735throwing away commits on mybranch.27362737Also note that all of the above configuration can be performed by2738directly editing the file .git/config instead of using2739gitlink:git-config[1].27402741See gitlink:git-config[1] for more details on the configuration2742options mentioned above.274327442745[[git-internals]]2746Git internals2747=============27482749Git depends on two fundamental abstractions: the "object database", and2750the "current directory cache" aka "index".27512752[[the-object-database]]2753The Object Database2754-------------------27552756The object database is literally just a content-addressable collection2757of objects. All objects are named by their content, which is2758approximated by the SHA1 hash of the object itself. Objects may refer2759to other objects (by referencing their SHA1 hash), and so you can2760build up a hierarchy of objects.27612762All objects have a statically determined "type" which is2763determined at object creation time, and which identifies the format of2764the object (i.e. how it is used, and how it can refer to other2765objects). There are currently four different object types: "blob",2766"tree", "commit", and "tag".27672768A <<def_blob_object,"blob" object>> cannot refer to any other object,2769and is, as the name implies, a pure storage object containing some2770user data. It is used to actually store the file data, i.e. a blob2771object is associated with some particular version of some file.27722773A <<def_tree_object,"tree" object>> is an object that ties one or more2774"blob" objects into a directory structure. In addition, a tree object2775can refer to other tree objects, thus creating a directory hierarchy.27762777A <<def_commit_object,"commit" object>> ties such directory hierarchies2778together into a <<def_DAG,directed acyclic graph>> of revisions - each2779"commit" is associated with exactly one tree (the directory hierarchy at2780the time of the commit). In addition, a "commit" refers to one or more2781"parent" commit objects that describe the history of how we arrived at2782that directory hierarchy.27832784As a special case, a commit object with no parents is called the "root"2785commit, and is the point of an initial project commit. Each project2786must have at least one root, and while you can tie several different2787root objects together into one project by creating a commit object which2788has two or more separate roots as its ultimate parents, that's probably2789just going to confuse people. So aim for the notion of "one root object2790per project", even if git itself does not enforce that.27912792A <<def_tag_object,"tag" object>> symbolically identifies and can be2793used to sign other objects. It contains the identifier and type of2794another object, a symbolic name (of course!) and, optionally, a2795signature.27962797Regardless of object type, all objects share the following2798characteristics: they are all deflated with zlib, and have a header2799that not only specifies their type, but also provides size information2800about the data in the object. It's worth noting that the SHA1 hash2801that is used to name the object is the hash of the original data2802plus this header, so `sha1sum` 'file' does not match the object name2803for 'file'.2804(Historical note: in the dawn of the age of git the hash2805was the sha1 of the 'compressed' object.)28062807As a result, the general consistency of an object can always be tested2808independently of the contents or the type of the object: all objects can2809be validated by verifying that (a) their hashes match the content of the2810file and (b) the object successfully inflates to a stream of bytes that2811forms a sequence of <ascii type without space> {plus} <space> {plus} <ascii decimal2812size> {plus} <byte\0> {plus} <binary object data>.28132814The structured objects can further have their structure and2815connectivity to other objects verified. This is generally done with2816the `git-fsck` program, which generates a full dependency graph2817of all objects, and verifies their internal consistency (in addition2818to just verifying their superficial consistency through the hash).28192820The object types in some more detail:28212822[[blob-object]]2823Blob Object2824-----------28252826A "blob" object is nothing but a binary blob of data, and doesn't2827refer to anything else. There is no signature or any other2828verification of the data, so while the object is consistent (it 'is'2829indexed by its sha1 hash, so the data itself is certainly correct), it2830has absolutely no other attributes. No name associations, no2831permissions. It is purely a blob of data (i.e. normally "file2832contents").28332834In particular, since the blob is entirely defined by its data, if two2835files in a directory tree (or in multiple different versions of the2836repository) have the same contents, they will share the same blob2837object. The object is totally independent of its location in the2838directory tree, and renaming a file does not change the object that2839file is associated with in any way.28402841A blob is typically created when gitlink:git-update-index[1]2842is run, and its data can be accessed by gitlink:git-cat-file[1].28432844[[tree-object]]2845Tree Object2846-----------28472848The next hierarchical object type is the "tree" object. A tree object2849is a list of mode/name/blob data, sorted by name. Alternatively, the2850mode data may specify a directory mode, in which case instead of2851naming a blob, that name is associated with another TREE object.28522853Like the "blob" object, a tree object is uniquely determined by the2854set contents, and so two separate but identical trees will always2855share the exact same object. This is true at all levels, i.e. it's2856true for a "leaf" tree (which does not refer to any other trees, only2857blobs) as well as for a whole subdirectory.28582859For that reason a "tree" object is just a pure data abstraction: it2860has no history, no signatures, no verification of validity, except2861that since the contents are again protected by the hash itself, we can2862trust that the tree is immutable and its contents never change.28632864So you can trust the contents of a tree to be valid, the same way you2865can trust the contents of a blob, but you don't know where those2866contents 'came' from.28672868Side note on trees: since a "tree" object is a sorted list of2869"filename+content", you can create a diff between two trees without2870actually having to unpack two trees. Just ignore all common parts,2871and your diff will look right. In other words, you can effectively2872(and efficiently) tell the difference between any two random trees by2873O(n) where "n" is the size of the difference, rather than the size of2874the tree.28752876Side note 2 on trees: since the name of a "blob" depends entirely and2877exclusively on its contents (i.e. there are no names or permissions2878involved), you can see trivial renames or permission changes by2879noticing that the blob stayed the same. However, renames with data2880changes need a smarter "diff" implementation.28812882A tree is created with gitlink:git-write-tree[1] and2883its data can be accessed by gitlink:git-ls-tree[1].2884Two trees can be compared with gitlink:git-diff-tree[1].28852886[[commit-object]]2887Commit Object2888-------------28892890The "commit" object is an object that introduces the notion of2891history into the picture. In contrast to the other objects, it2892doesn't just describe the physical state of a tree, it describes how2893we got there, and why.28942895A "commit" is defined by the tree-object that it results in, the2896parent commits (zero, one or more) that led up to that point, and a2897comment on what happened. Again, a commit is not trusted per se:2898the contents are well-defined and "safe" due to the cryptographically2899strong signatures at all levels, but there is no reason to believe2900that the tree is "good" or that the merge information makes sense.2901The parents do not have to actually have any relationship with the2902result, for example.29032904Note on commits: unlike some SCM's, commits do not contain2905rename information or file mode change information. All of that is2906implicit in the trees involved (the result tree, and the result trees2907of the parents), and describing that makes no sense in this idiotic2908file manager.29092910A commit is created with gitlink:git-commit-tree[1] and2911its data can be accessed by gitlink:git-cat-file[1].29122913[[trust]]2914Trust2915-----29162917An aside on the notion of "trust". Trust is really outside the scope2918of "git", but it's worth noting a few things. First off, since2919everything is hashed with SHA1, you 'can' trust that an object is2920intact and has not been messed with by external sources. So the name2921of an object uniquely identifies a known state - just not a state that2922you may want to trust.29232924Furthermore, since the SHA1 signature of a commit refers to the2925SHA1 signatures of the tree it is associated with and the signatures2926of the parent, a single named commit specifies uniquely a whole set2927of history, with full contents. You can't later fake any step of the2928way once you have the name of a commit.29292930So to introduce some real trust in the system, the only thing you need2931to do is to digitally sign just 'one' special note, which includes the2932name of a top-level commit. Your digital signature shows others2933that you trust that commit, and the immutability of the history of2934commits tells others that they can trust the whole history.29352936In other words, you can easily validate a whole archive by just2937sending out a single email that tells the people the name (SHA1 hash)2938of the top commit, and digitally sign that email using something2939like GPG/PGP.29402941To assist in this, git also provides the tag object...29422943[[tag-object]]2944Tag Object2945----------29462947Git provides the "tag" object to simplify creating, managing and2948exchanging symbolic and signed tokens. The "tag" object at its2949simplest simply symbolically identifies another object by containing2950the sha1, type and symbolic name.29512952However it can optionally contain additional signature information2953(which git doesn't care about as long as there's less than 8k of2954it). This can then be verified externally to git.29552956Note that despite the tag features, "git" itself only handles content2957integrity; the trust framework (and signature provision and2958verification) has to come from outside.29592960A tag is created with gitlink:git-mktag[1],2961its data can be accessed by gitlink:git-cat-file[1],2962and the signature can be verified by2963gitlink:git-verify-tag[1].296429652966[[the-index]]2967The "index" aka "Current Directory Cache"2968-----------------------------------------29692970The index is a simple binary file, which contains an efficient2971representation of the contents of a virtual directory. It2972does so by a simple array that associates a set of names, dates,2973permissions and content (aka "blob") objects together. The cache is2974always kept ordered by name, and names are unique (with a few very2975specific rules) at any point in time, but the cache has no long-term2976meaning, and can be partially updated at any time.29772978In particular, the index certainly does not need to be consistent with2979the current directory contents (in fact, most operations will depend on2980different ways to make the index 'not' be consistent with the directory2981hierarchy), but it has three very important attributes:29822983'(a) it can re-generate the full state it caches (not just the2984directory structure: it contains pointers to the "blob" objects so2985that it can regenerate the data too)'29862987As a special case, there is a clear and unambiguous one-way mapping2988from a current directory cache to a "tree object", which can be2989efficiently created from just the current directory cache without2990actually looking at any other data. So a directory cache at any one2991time uniquely specifies one and only one "tree" object (but has2992additional data to make it easy to match up that tree object with what2993has happened in the directory)29942995'(b) it has efficient methods for finding inconsistencies between that2996cached state ("tree object waiting to be instantiated") and the2997current state.'29982999'(c) it can additionally efficiently represent information about merge3000conflicts between different tree objects, allowing each pathname to be3001associated with sufficient information about the trees involved that3002you can create a three-way merge between them.'30033004Those are the ONLY three things that the directory cache does. It's a3005cache, and the normal operation is to re-generate it completely from a3006known tree object, or update/compare it with a live tree that is being3007developed. If you blow the directory cache away entirely, you generally3008haven't lost any information as long as you have the name of the tree3009that it described.30103011At the same time, the index is also the staging area for creating3012new trees, and creating a new tree always involves a controlled3013modification of the index file. In particular, the index file can3014have the representation of an intermediate tree that has not yet been3015instantiated. So the index can be thought of as a write-back cache,3016which can contain dirty information that has not yet been written back3017to the backing store.3018301930203021[[the-workflow]]3022The Workflow3023------------30243025Generally, all "git" operations work on the index file. Some operations3026work *purely* on the index file (showing the current state of the3027index), but most operations move data to and from the index file. Either3028from the database or from the working directory. Thus there are four3029main combinations:30303031[[working-directory-to-index]]3032working directory -> index3033~~~~~~~~~~~~~~~~~~~~~~~~~~30343035You update the index with information from the working directory with3036the gitlink:git-update-index[1] command. You3037generally update the index information by just specifying the filename3038you want to update, like so:30393040-------------------------------------------------3041$ git-update-index filename3042-------------------------------------------------30433044but to avoid common mistakes with filename globbing etc, the command3045will not normally add totally new entries or remove old entries,3046i.e. it will normally just update existing cache entries.30473048To tell git that yes, you really do realize that certain files no3049longer exist, or that new files should be added, you3050should use the `--remove` and `--add` flags respectively.30513052NOTE! A `--remove` flag does 'not' mean that subsequent filenames will3053necessarily be removed: if the files still exist in your directory3054structure, the index will be updated with their new status, not3055removed. The only thing `--remove` means is that update-cache will be3056considering a removed file to be a valid thing, and if the file really3057does not exist any more, it will update the index accordingly.30583059As a special case, you can also do `git-update-index --refresh`, which3060will refresh the "stat" information of each index to match the current3061stat information. It will 'not' update the object status itself, and3062it will only update the fields that are used to quickly test whether3063an object still matches its old backing store object.30643065[[index-to-object-database]]3066index -> object database3067~~~~~~~~~~~~~~~~~~~~~~~~30683069You write your current index file to a "tree" object with the program30703071-------------------------------------------------3072$ git-write-tree3073-------------------------------------------------30743075that doesn't come with any options - it will just write out the3076current index into the set of tree objects that describe that state,3077and it will return the name of the resulting top-level tree. You can3078use that tree to re-generate the index at any time by going in the3079other direction:30803081[[object-database-to-index]]3082object database -> index3083~~~~~~~~~~~~~~~~~~~~~~~~30843085You read a "tree" file from the object database, and use that to3086populate (and overwrite - don't do this if your index contains any3087unsaved state that you might want to restore later!) your current3088index. Normal operation is just30893090-------------------------------------------------3091$ git-read-tree <sha1 of tree>3092-------------------------------------------------30933094and your index file will now be equivalent to the tree that you saved3095earlier. However, that is only your 'index' file: your working3096directory contents have not been modified.30973098[[index-to-working-directory]]3099index -> working directory3100~~~~~~~~~~~~~~~~~~~~~~~~~~31013102You update your working directory from the index by "checking out"3103files. This is not a very common operation, since normally you'd just3104keep your files updated, and rather than write to your working3105directory, you'd tell the index files about the changes in your3106working directory (i.e. `git-update-index`).31073108However, if you decide to jump to a new version, or check out somebody3109else's version, or just restore a previous tree, you'd populate your3110index file with read-tree, and then you need to check out the result3111with31123113-------------------------------------------------3114$ git-checkout-index filename3115-------------------------------------------------31163117or, if you want to check out all of the index, use `-a`.31183119NOTE! git-checkout-index normally refuses to overwrite old files, so3120if you have an old version of the tree already checked out, you will3121need to use the "-f" flag ('before' the "-a" flag or the filename) to3122'force' the checkout.312331243125Finally, there are a few odds and ends which are not purely moving3126from one representation to the other:31273128[[tying-it-all-together]]3129Tying it all together3130~~~~~~~~~~~~~~~~~~~~~31313132To commit a tree you have instantiated with "git-write-tree", you'd3133create a "commit" object that refers to that tree and the history3134behind it - most notably the "parent" commits that preceded it in3135history.31363137Normally a "commit" has one parent: the previous state of the tree3138before a certain change was made. However, sometimes it can have two3139or more parent commits, in which case we call it a "merge", due to the3140fact that such a commit brings together ("merges") two or more3141previous states represented by other commits.31423143In other words, while a "tree" represents a particular directory state3144of a working directory, a "commit" represents that state in "time",3145and explains how we got there.31463147You create a commit object by giving it the tree that describes the3148state at the time of the commit, and a list of parents:31493150-------------------------------------------------3151$ git-commit-tree <tree> -p <parent> [-p <parent2> ..]3152-------------------------------------------------31533154and then giving the reason for the commit on stdin (either through3155redirection from a pipe or file, or by just typing it at the tty).31563157git-commit-tree will return the name of the object that represents3158that commit, and you should save it away for later use. Normally,3159you'd commit a new `HEAD` state, and while git doesn't care where you3160save the note about that state, in practice we tend to just write the3161result to the file pointed at by `.git/HEAD`, so that we can always see3162what the last committed state was.31633164Here is an ASCII art by Jon Loeliger that illustrates how3165various pieces fit together.31663167------------31683169 commit-tree3170 commit obj3171 +----+3172 | |3173 | |3174 V V3175 +-----------+3176 | Object DB |3177 | Backing |3178 | Store |3179 +-----------+3180 ^3181 write-tree | |3182 tree obj | |3183 | | read-tree3184 | | tree obj3185 V3186 +-----------+3187 | Index |3188 | "cache" |3189 +-----------+3190 update-index ^3191 blob obj | |3192 | |3193 checkout-index -u | | checkout-index3194 stat | | blob obj3195 V3196 +-----------+3197 | Working |3198 | Directory |3199 +-----------+32003201------------320232033204[[examining-the-data]]3205Examining the data3206------------------32073208You can examine the data represented in the object database and the3209index with various helper tools. For every object, you can use3210gitlink:git-cat-file[1] to examine details about the3211object:32123213-------------------------------------------------3214$ git-cat-file -t <objectname>3215-------------------------------------------------32163217shows the type of the object, and once you have the type (which is3218usually implicit in where you find the object), you can use32193220-------------------------------------------------3221$ git-cat-file blob|tree|commit|tag <objectname>3222-------------------------------------------------32233224to show its contents. NOTE! Trees have binary content, and as a result3225there is a special helper for showing that content, called3226`git-ls-tree`, which turns the binary content into a more easily3227readable form.32283229It's especially instructive to look at "commit" objects, since those3230tend to be small and fairly self-explanatory. In particular, if you3231follow the convention of having the top commit name in `.git/HEAD`,3232you can do32333234-------------------------------------------------3235$ git-cat-file commit HEAD3236-------------------------------------------------32373238to see what the top commit was.32393240[[merging-multiple-trees]]3241Merging multiple trees3242----------------------32433244Git helps you do a three-way merge, which you can expand to n-way by3245repeating the merge procedure arbitrary times until you finally3246"commit" the state. The normal situation is that you'd only do one3247three-way merge (two parents), and commit it, but if you like to, you3248can do multiple parents in one go.32493250To do a three-way merge, you need the two sets of "commit" objects3251that you want to merge, use those to find the closest common parent (a3252third "commit" object), and then use those commit objects to find the3253state of the directory ("tree" object) at these points.32543255To get the "base" for the merge, you first look up the common parent3256of two commits with32573258-------------------------------------------------3259$ git-merge-base <commit1> <commit2>3260-------------------------------------------------32613262which will return you the commit they are both based on. You should3263now look up the "tree" objects of those commits, which you can easily3264do with (for example)32653266-------------------------------------------------3267$ git-cat-file commit <commitname> | head -13268-------------------------------------------------32693270since the tree object information is always the first line in a commit3271object.32723273Once you know the three trees you are going to merge (the one "original"3274tree, aka the common tree, and the two "result" trees, aka the branches3275you want to merge), you do a "merge" read into the index. This will3276complain if it has to throw away your old index contents, so you should3277make sure that you've committed those - in fact you would normally3278always do a merge against your last commit (which should thus match what3279you have in your current index anyway).32803281To do the merge, do32823283-------------------------------------------------3284$ git-read-tree -m -u <origtree> <yourtree> <targettree>3285-------------------------------------------------32863287which will do all trivial merge operations for you directly in the3288index file, and you can just write the result out with3289`git-write-tree`.329032913292[[merging-multiple-trees-2]]3293Merging multiple trees, continued3294---------------------------------32953296Sadly, many merges aren't trivial. If there are files that have3297been added.moved or removed, or if both branches have modified the3298same file, you will be left with an index tree that contains "merge3299entries" in it. Such an index tree can 'NOT' be written out to a tree3300object, and you will have to resolve any such merge clashes using3301other tools before you can write out the result.33023303You can examine such index state with `git-ls-files --unmerged`3304command. An example:33053306------------------------------------------------3307$ git-read-tree -m $orig HEAD $target3308$ git-ls-files --unmerged3309100644 263414f423d0e4d70dae8fe53fa34614ff3e2860 1 hello.c3310100644 06fa6a24256dc7e560efa5687fa84b51f0263c3a 2 hello.c3311100644 cc44c73eb783565da5831b4d820c962954019b69 3 hello.c3312------------------------------------------------33133314Each line of the `git-ls-files --unmerged` output begins with3315the blob mode bits, blob SHA1, 'stage number', and the3316filename. The 'stage number' is git's way to say which tree it3317came from: stage 1 corresponds to `$orig` tree, stage 2 `HEAD`3318tree, and stage3 `$target` tree.33193320Earlier we said that trivial merges are done inside3321`git-read-tree -m`. For example, if the file did not change3322from `$orig` to `HEAD` nor `$target`, or if the file changed3323from `$orig` to `HEAD` and `$orig` to `$target` the same way,3324obviously the final outcome is what is in `HEAD`. What the3325above example shows is that file `hello.c` was changed from3326`$orig` to `HEAD` and `$orig` to `$target` in a different way.3327You could resolve this by running your favorite 3-way merge3328program, e.g. `diff3`, `merge`, or git's own merge-file, on3329the blob objects from these three stages yourself, like this:33303331------------------------------------------------3332$ git-cat-file blob 263414f... >hello.c~13333$ git-cat-file blob 06fa6a2... >hello.c~23334$ git-cat-file blob cc44c73... >hello.c~33335$ git merge-file hello.c~2 hello.c~1 hello.c~33336------------------------------------------------33373338This would leave the merge result in `hello.c~2` file, along3339with conflict markers if there are conflicts. After verifying3340the merge result makes sense, you can tell git what the final3341merge result for this file is by:33423343-------------------------------------------------3344$ mv -f hello.c~2 hello.c3345$ git-update-index hello.c3346-------------------------------------------------33473348When a path is in unmerged state, running `git-update-index` for3349that path tells git to mark the path resolved.33503351The above is the description of a git merge at the lowest level,3352to help you understand what conceptually happens under the hood.3353In practice, nobody, not even git itself, uses three `git-cat-file`3354for this. There is `git-merge-index` program that extracts the3355stages to temporary files and calls a "merge" script on it:33563357-------------------------------------------------3358$ git-merge-index git-merge-one-file hello.c3359-------------------------------------------------33603361and that is what higher level `git merge -s resolve` is implemented with.33623363[[pack-files]]3364How git stores objects efficiently: pack files3365----------------------------------------------33663367We've seen how git stores each object in a file named after the3368object's SHA1 hash.33693370Unfortunately this system becomes inefficient once a project has a3371lot of objects. Try this on an old project:33723373------------------------------------------------3374$ git count-objects33756930 objects, 47620 kilobytes3376------------------------------------------------33773378The first number is the number of objects which are kept in3379individual files. The second is the amount of space taken up by3380those "loose" objects.33813382You can save space and make git faster by moving these loose objects in3383to a "pack file", which stores a group of objects in an efficient3384compressed format; the details of how pack files are formatted can be3385found in link:technical/pack-format.txt[technical/pack-format.txt].33863387To put the loose objects into a pack, just run git repack:33883389------------------------------------------------3390$ git repack3391Generating pack...3392Done counting 6020 objects.3393Deltifying 6020 objects.3394 100% (6020/6020) done3395Writing 6020 objects.3396 100% (6020/6020) done3397Total 6020, written 6020 (delta 4070), reused 0 (delta 0)3398Pack pack-3e54ad29d5b2e05838c75df582c65257b8d08e1c created.3399------------------------------------------------34003401You can then run34023403------------------------------------------------3404$ git prune3405------------------------------------------------34063407to remove any of the "loose" objects that are now contained in the3408pack. This will also remove any unreferenced objects (which may be3409created when, for example, you use "git reset" to remove a commit).3410You can verify that the loose objects are gone by looking at the3411.git/objects directory or by running34123413------------------------------------------------3414$ git count-objects34150 objects, 0 kilobytes3416------------------------------------------------34173418Although the object files are gone, any commands that refer to those3419objects will work exactly as they did before.34203421The gitlink:git-gc[1] command performs packing, pruning, and more for3422you, so is normally the only high-level command you need.34233424[[dangling-objects]]3425Dangling objects3426----------------34273428The gitlink:git-fsck[1] command will sometimes complain about dangling3429objects. They are not a problem.34303431The most common cause of dangling objects is that you've rebased a3432branch, or you have pulled from somebody else who rebased a branch--see3433<<cleaning-up-history>>. In that case, the old head of the original3434branch still exists, as does everything it pointed to. The branch3435pointer itself just doesn't, since you replaced it with another one.34363437There are also other situations that cause dangling objects. For3438example, a "dangling blob" may arise because you did a "git add" of a3439file, but then, before you actually committed it and made it part of the3440bigger picture, you changed something else in that file and committed3441that *updated* thing - the old state that you added originally ends up3442not being pointed to by any commit or tree, so it's now a dangling blob3443object.34443445Similarly, when the "recursive" merge strategy runs, and finds that3446there are criss-cross merges and thus more than one merge base (which is3447fairly unusual, but it does happen), it will generate one temporary3448midway tree (or possibly even more, if you had lots of criss-crossing3449merges and more than two merge bases) as a temporary internal merge3450base, and again, those are real objects, but the end result will not end3451up pointing to them, so they end up "dangling" in your repository.34523453Generally, dangling objects aren't anything to worry about. They can3454even be very useful: if you screw something up, the dangling objects can3455be how you recover your old tree (say, you did a rebase, and realized3456that you really didn't want to - you can look at what dangling objects3457you have, and decide to reset your head to some old dangling state).34583459For commits, you can just use:34603461------------------------------------------------3462$ gitk <dangling-commit-sha-goes-here> --not --all3463------------------------------------------------34643465This asks for all the history reachable from the given commit but not3466from any branch, tag, or other reference. If you decide it's something3467you want, you can always create a new reference to it, e.g.,34683469------------------------------------------------3470$ git branch recovered-branch <dangling-commit-sha-goes-here>3471------------------------------------------------34723473For blobs and trees, you can't do the same, but you can still examine3474them. You can just do34753476------------------------------------------------3477$ git show <dangling-blob/tree-sha-goes-here>3478------------------------------------------------34793480to show what the contents of the blob were (or, for a tree, basically3481what the "ls" for that directory was), and that may give you some idea3482of what the operation was that left that dangling object.34833484Usually, dangling blobs and trees aren't very interesting. They're3485almost always the result of either being a half-way mergebase (the blob3486will often even have the conflict markers from a merge in it, if you3487have had conflicting merges that you fixed up by hand), or simply3488because you interrupted a "git fetch" with ^C or something like that,3489leaving _some_ of the new objects in the object database, but just3490dangling and useless.34913492Anyway, once you are sure that you're not interested in any dangling3493state, you can just prune all unreachable objects:34943495------------------------------------------------3496$ git prune3497------------------------------------------------34983499and they'll be gone. But you should only run "git prune" on a quiescent3500repository - it's kind of like doing a filesystem fsck recovery: you3501don't want to do that while the filesystem is mounted.35023503(The same is true of "git-fsck" itself, btw - but since3504git-fsck never actually *changes* the repository, it just reports3505on what it found, git-fsck itself is never "dangerous" to run.3506Running it while somebody is actually changing the repository can cause3507confusing and scary messages, but it won't actually do anything bad. In3508contrast, running "git prune" while somebody is actively changing the3509repository is a *BAD* idea).35103511[[birdview-on-the-source-code]]3512A birds-eye view of Git's source code3513-------------------------------------35143515It is not always easy for new developers to find their way through Git's3516source code. This section gives you a little guidance to show where to3517start.35183519A good place to start is with the contents of the initial commit, with:35203521----------------------------------------------------3522$ git checkout e83c51633523----------------------------------------------------35243525The initial revision lays the foundation for almost everything git has3526today, but is small enough to read in one sitting.35273528Note that terminology has changed since that revision. For example, the3529README in that revision uses the word "changeset" to describe what we3530now call a <<def_commit_object,commit>>.35313532Also, we do not call it "cache" any more, but "index", however, the3533file is still called `cache.h`. Remark: Not much reason to change it now,3534especially since there is no good single name for it anyway, because it is3535basically _the_ header file which is included by _all_ of Git's C sources.35363537If you grasp the ideas in that initial commit, you should check out a3538more recent version and skim `cache.h`, `object.h` and `commit.h`.35393540In the early days, Git (in the tradition of UNIX) was a bunch of programs3541which were extremely simple, and which you used in scripts, piping the3542output of one into another. This turned out to be good for initial3543development, since it was easier to test new things. However, recently3544many of these parts have become builtins, and some of the core has been3545"libified", i.e. put into libgit.a for performance, portability reasons,3546and to avoid code duplication.35473548By now, you know what the index is (and find the corresponding data3549structures in `cache.h`), and that there are just a couple of object types3550(blobs, trees, commits and tags) which inherit their common structure from3551`struct object`, which is their first member (and thus, you can cast e.g.3552`(struct object *)commit` to achieve the _same_ as `&commit->object`, i.e.3553get at the object name and flags).35543555Now is a good point to take a break to let this information sink in.35563557Next step: get familiar with the object naming. Read <<naming-commits>>.3558There are quite a few ways to name an object (and not only revisions!).3559All of these are handled in `sha1_name.c`. Just have a quick look at3560the function `get_sha1()`. A lot of the special handling is done by3561functions like `get_sha1_basic()` or the likes.35623563This is just to get you into the groove for the most libified part of Git:3564the revision walker.35653566Basically, the initial version of `git log` was a shell script:35673568----------------------------------------------------------------3569$ git-rev-list --pretty $(git-rev-parse --default HEAD "$@") | \3570 LESS=-S ${PAGER:-less}3571----------------------------------------------------------------35723573What does this mean?35743575`git-rev-list` is the original version of the revision walker, which3576_always_ printed a list of revisions to stdout. It is still functional,3577and needs to, since most new Git programs start out as scripts using3578`git-rev-list`.35793580`git-rev-parse` is not as important any more; it was only used to filter out3581options that were relevant for the different plumbing commands that were3582called by the script.35833584Most of what `git-rev-list` did is contained in `revision.c` and3585`revision.h`. It wraps the options in a struct named `rev_info`, which3586controls how and what revisions are walked, and more.35873588The original job of `git-rev-parse` is now taken by the function3589`setup_revisions()`, which parses the revisions and the common command line3590options for the revision walker. This information is stored in the struct3591`rev_info` for later consumption. You can do your own command line option3592parsing after calling `setup_revisions()`. After that, you have to call3593`prepare_revision_walk()` for initialization, and then you can get the3594commits one by one with the function `get_revision()`.35953596If you are interested in more details of the revision walking process,3597just have a look at the first implementation of `cmd_log()`; call3598`git-show v1.3.0~155^2~4` and scroll down to that function (note that you3599no longer need to call `setup_pager()` directly).36003601Nowadays, `git log` is a builtin, which means that it is _contained_ in the3602command `git`. The source side of a builtin is36033604- a function called `cmd_<bla>`, typically defined in `builtin-<bla>.c`,3605 and declared in `builtin.h`,36063607- an entry in the `commands[]` array in `git.c`, and36083609- an entry in `BUILTIN_OBJECTS` in the `Makefile`.36103611Sometimes, more than one builtin is contained in one source file. For3612example, `cmd_whatchanged()` and `cmd_log()` both reside in `builtin-log.c`,3613since they share quite a bit of code. In that case, the commands which are3614_not_ named like the `.c` file in which they live have to be listed in3615`BUILT_INS` in the `Makefile`.36163617`git log` looks more complicated in C than it does in the original script,3618but that allows for a much greater flexibility and performance.36193620Here again it is a good point to take a pause.36213622Lesson three is: study the code. Really, it is the best way to learn about3623the organization of Git (after you know the basic concepts).36243625So, think about something which you are interested in, say, "how can I3626access a blob just knowing the object name of it?". The first step is to3627find a Git command with which you can do it. In this example, it is either3628`git show` or `git cat-file`.36293630For the sake of clarity, let's stay with `git cat-file`, because it36313632- is plumbing, and36333634- was around even in the initial commit (it literally went only through3635 some 20 revisions as `cat-file.c`, was renamed to `builtin-cat-file.c`3636 when made a builtin, and then saw less than 10 versions).36373638So, look into `builtin-cat-file.c`, search for `cmd_cat_file()` and look what3639it does.36403641------------------------------------------------------------------3642 git_config(git_default_config);3643 if (argc != 3)3644 usage("git-cat-file [-t|-s|-e|-p|<type>] <sha1>");3645 if (get_sha1(argv[2], sha1))3646 die("Not a valid object name %s", argv[2]);3647------------------------------------------------------------------36483649Let's skip over the obvious details; the only really interesting part3650here is the call to `get_sha1()`. It tries to interpret `argv[2]` as an3651object name, and if it refers to an object which is present in the current3652repository, it writes the resulting SHA-1 into the variable `sha1`.36533654Two things are interesting here:36553656- `get_sha1()` returns 0 on _success_. This might surprise some new3657 Git hackers, but there is a long tradition in UNIX to return different3658 negative numbers in case of different errors -- and 0 on success.36593660- the variable `sha1` in the function signature of `get_sha1()` is `unsigned3661 char \*`, but is actually expected to be a pointer to `unsigned3662 char[20]`. This variable will contain the 160-bit SHA-1 of the given3663 commit. Note that whenever a SHA-1 is passed as `unsigned char \*`, it3664 is the binary representation, as opposed to the ASCII representation in3665 hex characters, which is passed as `char *`.36663667You will see both of these things throughout the code.36683669Now, for the meat:36703671-----------------------------------------------------------------------------3672 case 0:3673 buf = read_object_with_reference(sha1, argv[1], &size, NULL);3674-----------------------------------------------------------------------------36753676This is how you read a blob (actually, not only a blob, but any type of3677object). To know how the function `read_object_with_reference()` actually3678works, find the source code for it (something like `git grep3679read_object_with | grep ":[a-z]"` in the git repository), and read3680the source.36813682To find out how the result can be used, just read on in `cmd_cat_file()`:36833684-----------------------------------3685 write_or_die(1, buf, size);3686-----------------------------------36873688Sometimes, you do not know where to look for a feature. In many such cases,3689it helps to search through the output of `git log`, and then `git show` the3690corresponding commit.36913692Example: If you know that there was some test case for `git bundle`, but3693do not remember where it was (yes, you _could_ `git grep bundle t/`, but that3694does not illustrate the point!):36953696------------------------3697$ git log --no-merges t/3698------------------------36993700In the pager (`less`), just search for "bundle", go a few lines back,3701and see that it is in commit 18449ab0... Now just copy this object name,3702and paste it into the command line37033704-------------------3705$ git show 18449ab03706-------------------37073708Voila.37093710Another example: Find out what to do in order to make some script a3711builtin:37123713-------------------------------------------------3714$ git log --no-merges --diff-filter=A builtin-*.c3715-------------------------------------------------37163717You see, Git is actually the best tool to find out about the source of Git3718itself!37193720[[glossary]]3721include::glossary.txt[]37223723[[git-quick-start]]3724Appendix A: Git Quick Reference3725===============================37263727This is a quick summary of the major commands; the previous chapters3728explain how these work in more detail.37293730[[quick-creating-a-new-repository]]3731Creating a new repository3732-------------------------37333734From a tarball:37353736-----------------------------------------------3737$ tar xzf project.tar.gz3738$ cd project3739$ git init3740Initialized empty Git repository in .git/3741$ git add .3742$ git commit3743-----------------------------------------------37443745From a remote repository:37463747-----------------------------------------------3748$ git clone git://example.com/pub/project.git3749$ cd project3750-----------------------------------------------37513752[[managing-branches]]3753Managing branches3754-----------------37553756-----------------------------------------------3757$ git branch # list all local branches in this repo3758$ git checkout test # switch working directory to branch "test"3759$ git branch new # create branch "new" starting at current HEAD3760$ git branch -d new # delete branch "new"3761-----------------------------------------------37623763Instead of basing new branch on current HEAD (the default), use:37643765-----------------------------------------------3766$ git branch new test # branch named "test"3767$ git branch new v2.6.15 # tag named v2.6.153768$ git branch new HEAD^ # commit before the most recent3769$ git branch new HEAD^^ # commit before that3770$ git branch new test~10 # ten commits before tip of branch "test"3771-----------------------------------------------37723773Create and switch to a new branch at the same time:37743775-----------------------------------------------3776$ git checkout -b new v2.6.153777-----------------------------------------------37783779Update and examine branches from the repository you cloned from:37803781-----------------------------------------------3782$ git fetch # update3783$ git branch -r # list3784 origin/master3785 origin/next3786 ...3787$ git checkout -b masterwork origin/master3788-----------------------------------------------37893790Fetch a branch from a different repository, and give it a new3791name in your repository:37923793-----------------------------------------------3794$ git fetch git://example.com/project.git theirbranch:mybranch3795$ git fetch git://example.com/project.git v2.6.15:mybranch3796-----------------------------------------------37973798Keep a list of repositories you work with regularly:37993800-----------------------------------------------3801$ git remote add example git://example.com/project.git3802$ git remote # list remote repositories3803example3804origin3805$ git remote show example # get details3806* remote example3807 URL: git://example.com/project.git3808 Tracked remote branches3809 master next ...3810$ git fetch example # update branches from example3811$ git branch -r # list all remote branches3812-----------------------------------------------381338143815[[exploring-history]]3816Exploring history3817-----------------38183819-----------------------------------------------3820$ gitk # visualize and browse history3821$ git log # list all commits3822$ git log src/ # ...modifying src/3823$ git log v2.6.15..v2.6.16 # ...in v2.6.16, not in v2.6.153824$ git log master..test # ...in branch test, not in branch master3825$ git log test..master # ...in branch master, but not in test3826$ git log test...master # ...in one branch, not in both3827$ git log -S'foo()' # ...where difference contain "foo()"3828$ git log --since="2 weeks ago"3829$ git log -p # show patches as well3830$ git show # most recent commit3831$ git diff v2.6.15..v2.6.16 # diff between two tagged versions3832$ git diff v2.6.15..HEAD # diff with current head3833$ git grep "foo()" # search working directory for "foo()"3834$ git grep v2.6.15 "foo()" # search old tree for "foo()"3835$ git show v2.6.15:a.txt # look at old version of a.txt3836-----------------------------------------------38373838Search for regressions:38393840-----------------------------------------------3841$ git bisect start3842$ git bisect bad # current version is bad3843$ git bisect good v2.6.13-rc2 # last known good revision3844Bisecting: 675 revisions left to test after this3845 # test here, then:3846$ git bisect good # if this revision is good, or3847$ git bisect bad # if this revision is bad.3848 # repeat until done.3849-----------------------------------------------38503851[[making-changes]]3852Making changes3853--------------38543855Make sure git knows who to blame:38563857------------------------------------------------3858$ cat >>~/.gitconfig <<\EOF3859[user]3860 name = Your Name Comes Here3861 email = you@yourdomain.example.com3862EOF3863------------------------------------------------38643865Select file contents to include in the next commit, then make the3866commit:38673868-----------------------------------------------3869$ git add a.txt # updated file3870$ git add b.txt # new file3871$ git rm c.txt # old file3872$ git commit3873-----------------------------------------------38743875Or, prepare and create the commit in one step:38763877-----------------------------------------------3878$ git commit d.txt # use latest content only of d.txt3879$ git commit -a # use latest content of all tracked files3880-----------------------------------------------38813882[[merging]]3883Merging3884-------38853886-----------------------------------------------3887$ git merge test # merge branch "test" into the current branch3888$ git pull git://example.com/project.git master3889 # fetch and merge in remote branch3890$ git pull . test # equivalent to git merge test3891-----------------------------------------------38923893[[sharing-your-changes]]3894Sharing your changes3895--------------------38963897Importing or exporting patches:38983899-----------------------------------------------3900$ git format-patch origin..HEAD # format a patch for each commit3901 # in HEAD but not in origin3902$ git am mbox # import patches from the mailbox "mbox"3903-----------------------------------------------39043905Fetch a branch in a different git repository, then merge into the3906current branch:39073908-----------------------------------------------3909$ git pull git://example.com/project.git theirbranch3910-----------------------------------------------39113912Store the fetched branch into a local branch before merging into the3913current branch:39143915-----------------------------------------------3916$ git pull git://example.com/project.git theirbranch:mybranch3917-----------------------------------------------39183919After creating commits on a local branch, update the remote3920branch with your commits:39213922-----------------------------------------------3923$ git push ssh://example.com/project.git mybranch:theirbranch3924-----------------------------------------------39253926When remote and local branch are both named "test":39273928-----------------------------------------------3929$ git push ssh://example.com/project.git test3930-----------------------------------------------39313932Shortcut version for a frequently used remote repository:39333934-----------------------------------------------3935$ git remote add example ssh://example.com/project.git3936$ git push example test3937-----------------------------------------------39383939[[repository-maintenance]]3940Repository maintenance3941----------------------39423943Check for corruption:39443945-----------------------------------------------3946$ git fsck3947-----------------------------------------------39483949Recompress, remove unused cruft:39503951-----------------------------------------------3952$ git gc3953-----------------------------------------------395439553956[[todo]]3957Appendix B: Notes and todo list for this manual3958===============================================39593960This is a work in progress.39613962The basic requirements:3963 - It must be readable in order, from beginning to end, by3964 someone intelligent with a basic grasp of the unix3965 commandline, but without any special knowledge of git. If3966 necessary, any other prerequisites should be specifically3967 mentioned as they arise.3968 - Whenever possible, section headings should clearly describe3969 the task they explain how to do, in language that requires3970 no more knowledge than necessary: for example, "importing3971 patches into a project" rather than "the git-am command"39723973Think about how to create a clear chapter dependency graph that will3974allow people to get to important topics without necessarily reading3975everything in between.39763977Scan Documentation/ for other stuff left out; in particular:3978 howto's3979 some of technical/?3980 hooks3981 list of commands in gitlink:git[1]39823983Scan email archives for other stuff left out39843985Scan man pages to see if any assume more background than this manual3986provides.39873988Simplify beginning by suggesting disconnected head instead of3989temporary branch creation?39903991Add more good examples. Entire sections of just cookbook examples3992might be a good idea; maybe make an "advanced examples" section a3993standard end-of-chapter section?39943995Include cross-references to the glossary, where appropriate.39963997Document shallow clones? See draft 1.5.0 release notes for some3998documentation.39994000Add a section on working with other version control systems, including4001CVS, Subversion, and just imports of series of release tarballs.40024003More details on gitweb?40044005Write a chapter on using plumbing and writing scripts.40064007Alternates, clone -reference, etc.40084009git unpack-objects -r for recovery