1Git User's Manual (for version 1.5.1 or newer) 2______________________________________________ 3 4This manual is designed to be readable by someone with basic unix 5command-line skills, but no previous knowledge of git. 6 7<<repositories-and-branches>> and <<exploring-git-history>> explain how 8to fetch and study a project using git--read these chapters to learn how 9to build and test a particular version of a software project, search for 10regressions, and so on. 11 12People needing to do actual development will also want to read 13<<Developing-with-git>> and <<sharing-development>>. 14 15Further chapters cover more specialized topics. 16 17Comprehensive reference documentation is available through the man 18pages. For a command such as "git clone", just use 19 20------------------------------------------------ 21$ man git-clone 22------------------------------------------------ 23 24See also <<git-quick-start>> for a brief overview of git commands, 25without any explanation. 26 27Also, see <<todo>> for ways that you can help make this manual more 28complete. 29 30 31[[repositories-and-branches]] 32Repositories and Branches 33========================= 34 35[[how-to-get-a-git-repository]] 36How to get a git repository 37--------------------------- 38 39It will be useful to have a git repository to experiment with as you 40read this manual. 41 42The best way to get one is by using the gitlink:git-clone[1] command 43to download a copy of an existing repository for a project that you 44are interested in. If you don't already have a project in mind, here 45are some interesting examples: 46 47------------------------------------------------ 48 # git itself (approx. 10MB download): 49$ git clone git://git.kernel.org/pub/scm/git/git.git 50 # the linux kernel (approx. 150MB download): 51$ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git 52------------------------------------------------ 53 54The initial clone may be time-consuming for a large project, but you 55will only need to clone once. 56 57The clone command creates a new directory named after the project 58("git" or "linux-2.6" in the examples above). After you cd into this 59directory, you will see that it contains a copy of the project files, 60together with a special top-level directory named ".git", which 61contains all the information about the history of the project. 62 63In most of the following, examples will be taken from one of the two 64repositories above. 65 66[[how-to-check-out]] 67How to check out a different version of a project 68------------------------------------------------- 69 70Git is best thought of as a tool for storing the history of a 71collection of files. It stores the history as a compressed 72collection of interrelated snapshots (versions) of the project's 73contents. 74 75A single git repository may contain multiple branches. It keeps track 76of them by keeping a list of <<def_head,heads>> which reference the 77latest version on each branch; the gitlink:git-branch[1] command shows 78you the list of branch heads: 79 80------------------------------------------------ 81$ git branch 82* master 83------------------------------------------------ 84 85A freshly cloned repository contains a single branch head, by default 86named "master", with the working directory initialized to the state of 87the project referred to by that branch head. 88 89Most projects also use <<def_tag,tags>>. Tags, like heads, are 90references into the project's history, and can be listed using the 91gitlink:git-tag[1] command: 92 93------------------------------------------------ 94$ git tag -l 95v2.6.11 96v2.6.11-tree 97v2.6.12 98v2.6.12-rc2 99v2.6.12-rc3 100v2.6.12-rc4 101v2.6.12-rc5 102v2.6.12-rc6 103v2.6.13 104... 105------------------------------------------------ 106 107Tags are expected to always point at the same version of a project, 108while heads are expected to advance as development progresses. 109 110Create a new branch head pointing to one of these versions and check it 111out using gitlink:git-checkout[1]: 112 113------------------------------------------------ 114$ git checkout -b new v2.6.13 115------------------------------------------------ 116 117The working directory then reflects the contents that the project had 118when it was tagged v2.6.13, and gitlink:git-branch[1] shows two 119branches, with an asterisk marking the currently checked-out branch: 120 121------------------------------------------------ 122$ git branch 123 master 124* new 125------------------------------------------------ 126 127If you decide that you'd rather see version 2.6.17, you can modify 128the current branch to point at v2.6.17 instead, with 129 130------------------------------------------------ 131$ git reset --hard v2.6.17 132------------------------------------------------ 133 134Note that if the current branch head was your only reference to a 135particular point in history, then resetting that branch may leave you 136with no way to find the history it used to point to; so use this command 137carefully. 138 139[[understanding-commits]] 140Understanding History: Commits 141------------------------------ 142 143Every change in the history of a project is represented by a commit. 144The gitlink:git-show[1] command shows the most recent commit on the 145current branch: 146 147------------------------------------------------ 148$ git show 149commit 2b5f6dcce5bf94b9b119e9ed8d537098ec61c3d2 150Author: Jamal Hadi Salim <hadi@cyberus.ca> 151Date: Sat Dec 2 22:22:25 2006 -0800 152 153 [XFRM]: Fix aevent structuring to be more complete. 154 155 aevents can not uniquely identify an SA. We break the ABI with this 156 patch, but consensus is that since it is not yet utilized by any 157 (known) application then it is fine (better do it now than later). 158 159 Signed-off-by: Jamal Hadi Salim <hadi@cyberus.ca> 160 Signed-off-by: David S. Miller <davem@davemloft.net> 161 162diff --git a/Documentation/networking/xfrm_sync.txt b/Documentation/networking/xfrm_sync.txt 163index 8be626f..d7aac9d 100644 164--- a/Documentation/networking/xfrm_sync.txt 165+++ b/Documentation/networking/xfrm_sync.txt 166@@ -47,10 +47,13 @@ aevent_id structure looks like: 167 168 struct xfrm_aevent_id { 169 struct xfrm_usersa_id sa_id; 170+ xfrm_address_t saddr; 171 __u32 flags; 172+ __u32 reqid; 173 }; 174... 175------------------------------------------------ 176 177As you can see, a commit shows who made the latest change, what they 178did, and why. 179 180Every commit has a 40-hexdigit id, sometimes called the "object name" or the 181"SHA1 id", shown on the first line of the "git show" output. You can usually 182refer to a commit by a shorter name, such as a tag or a branch name, but this 183longer name can also be useful. Most importantly, it is a globally unique 184name for this commit: so if you tell somebody else the object name (for 185example in email), then you are guaranteed that name will refer to the same 186commit in their repository that it does in yours (assuming their repository 187has that commit at all). Since the object name is computed as a hash over the 188contents of the commit, you are guaranteed that the commit can never change 189without its name also changing. 190 191In fact, in <<git-internals>> we shall see that everything stored in git 192history, including file data and directory contents, is stored in an object 193with a name that is a hash of its contents. 194 195[[understanding-reachability]] 196Understanding history: commits, parents, and reachability 197~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 198 199Every commit (except the very first commit in a project) also has a 200parent commit which shows what happened before this commit. 201Following the chain of parents will eventually take you back to the 202beginning of the project. 203 204However, the commits do not form a simple list; git allows lines of 205development to diverge and then reconverge, and the point where two 206lines of development reconverge is called a "merge". The commit 207representing a merge can therefore have more than one parent, with 208each parent representing the most recent commit on one of the lines 209of development leading to that point. 210 211The best way to see how this works is using the gitlink:gitk[1] 212command; running gitk now on a git repository and looking for merge 213commits will help understand how the git organizes history. 214 215In the following, we say that commit X is "reachable" from commit Y 216if commit X is an ancestor of commit Y. Equivalently, you could say 217that Y is a descendent of X, or that there is a chain of parents 218leading from commit Y to commit X. 219 220[[history-diagrams]] 221Understanding history: History diagrams 222~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 223 224We will sometimes represent git history using diagrams like the one 225below. Commits are shown as "o", and the links between them with 226lines drawn with - / and \. Time goes left to right: 227 228 229................................................ 230 o--o--o <-- Branch A 231 / 232 o--o--o <-- master 233 \ 234 o--o--o <-- Branch B 235................................................ 236 237If we need to talk about a particular commit, the character "o" may 238be replaced with another letter or number. 239 240[[what-is-a-branch]] 241Understanding history: What is a branch? 242~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 243 244When we need to be precise, we will use the word "branch" to mean a line 245of development, and "branch head" (or just "head") to mean a reference 246to the most recent commit on a branch. In the example above, the branch 247head named "A" is a pointer to one particular commit, but we refer to 248the line of three commits leading up to that point as all being part of 249"branch A". 250 251However, when no confusion will result, we often just use the term 252"branch" both for branches and for branch heads. 253 254[[manipulating-branches]] 255Manipulating branches 256--------------------- 257 258Creating, deleting, and modifying branches is quick and easy; here's 259a summary of the commands: 260 261git branch:: 262 list all branches 263git branch <branch>:: 264 create a new branch named <branch>, referencing the same 265 point in history as the current branch 266git branch <branch> <start-point>:: 267 create a new branch named <branch>, referencing 268 <start-point>, which may be specified any way you like, 269 including using a branch name or a tag name 270git branch -d <branch>:: 271 delete the branch <branch>; if the branch you are deleting 272 points to a commit which is not reachable from the current 273 branch, this command will fail with a warning. 274git branch -D <branch>:: 275 even if the branch points to a commit not reachable 276 from the current branch, you may know that that commit 277 is still reachable from some other branch or tag. In that 278 case it is safe to use this command to force git to delete 279 the branch. 280git checkout <branch>:: 281 make the current branch <branch>, updating the working 282 directory to reflect the version referenced by <branch> 283git checkout -b <new> <start-point>:: 284 create a new branch <new> referencing <start-point>, and 285 check it out. 286 287The special symbol "HEAD" can always be used to refer to the current 288branch. In fact, git uses a file named "HEAD" in the .git directory to 289remember which branch is current: 290 291------------------------------------------------ 292$ cat .git/HEAD 293ref: refs/heads/master 294------------------------------------------------ 295 296[[detached-head]] 297Examining an old version without creating a new branch 298------------------------------------------------------ 299 300The git-checkout command normally expects a branch head, but will also 301accept an arbitrary commit; for example, you can check out the commit 302referenced by a tag: 303 304------------------------------------------------ 305$ git checkout v2.6.17 306Note: moving to "v2.6.17" which isn't a local branch 307If you want to create a new branch from this checkout, you may do so 308(now or later) by using -b with the checkout command again. Example: 309 git checkout -b <new_branch_name> 310HEAD is now at 427abfa... Linux v2.6.17 311------------------------------------------------ 312 313The HEAD then refers to the SHA1 of the commit instead of to a branch, 314and git branch shows that you are no longer on a branch: 315 316------------------------------------------------ 317$ cat .git/HEAD 318427abfa28afedffadfca9dd8b067eb6d36bac53f 319$ git branch 320* (no branch) 321 master 322------------------------------------------------ 323 324In this case we say that the HEAD is "detached". 325 326This is an easy way to check out a particular version without having to 327make up a name for the new branch. You can still create a new branch 328(or tag) for this version later if you decide to. 329 330[[examining-remote-branches]] 331Examining branches from a remote repository 332------------------------------------------- 333 334The "master" branch that was created at the time you cloned is a copy 335of the HEAD in the repository that you cloned from. That repository 336may also have had other branches, though, and your local repository 337keeps branches which track each of those remote branches, which you 338can view using the "-r" option to gitlink:git-branch[1]: 339 340------------------------------------------------ 341$ git branch -r 342 origin/HEAD 343 origin/html 344 origin/maint 345 origin/man 346 origin/master 347 origin/next 348 origin/pu 349 origin/todo 350------------------------------------------------ 351 352You cannot check out these remote-tracking branches, but you can 353examine them on a branch of your own, just as you would a tag: 354 355------------------------------------------------ 356$ git checkout -b my-todo-copy origin/todo 357------------------------------------------------ 358 359Note that the name "origin" is just the name that git uses by default 360to refer to the repository that you cloned from. 361 362[[how-git-stores-references]] 363Naming branches, tags, and other references 364------------------------------------------- 365 366Branches, remote-tracking branches, and tags are all references to 367commits. All references are named with a slash-separated path name 368starting with "refs"; the names we've been using so far are actually 369shorthand: 370 371 - The branch "test" is short for "refs/heads/test". 372 - The tag "v2.6.18" is short for "refs/tags/v2.6.18". 373 - "origin/master" is short for "refs/remotes/origin/master". 374 375The full name is occasionally useful if, for example, there ever 376exists a tag and a branch with the same name. 377 378As another useful shortcut, the "HEAD" of a repository can be referred 379to just using the name of that repository. So, for example, "origin" 380is usually a shortcut for the HEAD branch in the repository "origin". 381 382For the complete list of paths which git checks for references, and 383the order it uses to decide which to choose when there are multiple 384references with the same shorthand name, see the "SPECIFYING 385REVISIONS" section of gitlink:git-rev-parse[1]. 386 387[[Updating-a-repository-with-git-fetch]] 388Updating a repository with git fetch 389------------------------------------ 390 391Eventually the developer cloned from will do additional work in her 392repository, creating new commits and advancing the branches to point 393at the new commits. 394 395The command "git fetch", with no arguments, will update all of the 396remote-tracking branches to the latest version found in her 397repository. It will not touch any of your own branches--not even the 398"master" branch that was created for you on clone. 399 400[[fetching-branches]] 401Fetching branches from other repositories 402----------------------------------------- 403 404You can also track branches from repositories other than the one you 405cloned from, using gitlink:git-remote[1]: 406 407------------------------------------------------- 408$ git remote add linux-nfs git://linux-nfs.org/pub/nfs-2.6.git 409$ git fetch linux-nfs 410* refs/remotes/linux-nfs/master: storing branch 'master' ... 411 commit: bf81b46 412------------------------------------------------- 413 414New remote-tracking branches will be stored under the shorthand name 415that you gave "git remote add", in this case linux-nfs: 416 417------------------------------------------------- 418$ git branch -r 419linux-nfs/master 420origin/master 421------------------------------------------------- 422 423If you run "git fetch <remote>" later, the tracking branches for the 424named <remote> will be updated. 425 426If you examine the file .git/config, you will see that git has added 427a new stanza: 428 429------------------------------------------------- 430$ cat .git/config 431... 432[remote "linux-nfs"] 433 url = git://linux-nfs.org/pub/nfs-2.6.git 434 fetch = +refs/heads/*:refs/remotes/linux-nfs/* 435... 436------------------------------------------------- 437 438This is what causes git to track the remote's branches; you may modify 439or delete these configuration options by editing .git/config with a 440text editor. (See the "CONFIGURATION FILE" section of 441gitlink:git-config[1] for details.) 442 443[[exploring-git-history]] 444Exploring git history 445===================== 446 447Git is best thought of as a tool for storing the history of a 448collection of files. It does this by storing compressed snapshots of 449the contents of a file heirarchy, together with "commits" which show 450the relationships between these snapshots. 451 452Git provides extremely flexible and fast tools for exploring the 453history of a project. 454 455We start with one specialized tool that is useful for finding the 456commit that introduced a bug into a project. 457 458[[using-bisect]] 459How to use bisect to find a regression 460-------------------------------------- 461 462Suppose version 2.6.18 of your project worked, but the version at 463"master" crashes. Sometimes the best way to find the cause of such a 464regression is to perform a brute-force search through the project's 465history to find the particular commit that caused the problem. The 466gitlink:git-bisect[1] command can help you do this: 467 468------------------------------------------------- 469$ git bisect start 470$ git bisect good v2.6.18 471$ git bisect bad master 472Bisecting: 3537 revisions left to test after this 473[65934a9a028b88e83e2b0f8b36618fe503349f8e] BLOCK: Make USB storage depend on SCSI rather than selecting it [try #6] 474------------------------------------------------- 475 476If you run "git branch" at this point, you'll see that git has 477temporarily moved you to a new branch named "bisect". This branch 478points to a commit (with commit id 65934...) that is reachable from 479v2.6.19 but not from v2.6.18. Compile and test it, and see whether 480it crashes. Assume it does crash. Then: 481 482------------------------------------------------- 483$ git bisect bad 484Bisecting: 1769 revisions left to test after this 485[7eff82c8b1511017ae605f0c99ac275a7e21b867] i2c-core: Drop useless bitmaskings 486------------------------------------------------- 487 488checks out an older version. Continue like this, telling git at each 489stage whether the version it gives you is good or bad, and notice 490that the number of revisions left to test is cut approximately in 491half each time. 492 493After about 13 tests (in this case), it will output the commit id of 494the guilty commit. You can then examine the commit with 495gitlink:git-show[1], find out who wrote it, and mail them your bug 496report with the commit id. Finally, run 497 498------------------------------------------------- 499$ git bisect reset 500------------------------------------------------- 501 502to return you to the branch you were on before and delete the 503temporary "bisect" branch. 504 505Note that the version which git-bisect checks out for you at each 506point is just a suggestion, and you're free to try a different 507version if you think it would be a good idea. For example, 508occasionally you may land on a commit that broke something unrelated; 509run 510 511------------------------------------------------- 512$ git bisect visualize 513------------------------------------------------- 514 515which will run gitk and label the commit it chose with a marker that 516says "bisect". Chose a safe-looking commit nearby, note its commit 517id, and check it out with: 518 519------------------------------------------------- 520$ git reset --hard fb47ddb2db... 521------------------------------------------------- 522 523then test, run "bisect good" or "bisect bad" as appropriate, and 524continue. 525 526[[naming-commits]] 527Naming commits 528-------------- 529 530We have seen several ways of naming commits already: 531 532 - 40-hexdigit object name 533 - branch name: refers to the commit at the head of the given 534 branch 535 - tag name: refers to the commit pointed to by the given tag 536 (we've seen branches and tags are special cases of 537 <<how-git-stores-references,references>>). 538 - HEAD: refers to the head of the current branch 539 540There are many more; see the "SPECIFYING REVISIONS" section of the 541gitlink:git-rev-parse[1] man page for the complete list of ways to 542name revisions. Some examples: 543 544------------------------------------------------- 545$ git show fb47ddb2 # the first few characters of the object name 546 # are usually enough to specify it uniquely 547$ git show HEAD^ # the parent of the HEAD commit 548$ git show HEAD^^ # the grandparent 549$ git show HEAD~4 # the great-great-grandparent 550------------------------------------------------- 551 552Recall that merge commits may have more than one parent; by default, 553^ and ~ follow the first parent listed in the commit, but you can 554also choose: 555 556------------------------------------------------- 557$ git show HEAD^1 # show the first parent of HEAD 558$ git show HEAD^2 # show the second parent of HEAD 559------------------------------------------------- 560 561In addition to HEAD, there are several other special names for 562commits: 563 564Merges (to be discussed later), as well as operations such as 565git-reset, which change the currently checked-out commit, generally 566set ORIG_HEAD to the value HEAD had before the current operation. 567 568The git-fetch operation always stores the head of the last fetched 569branch in FETCH_HEAD. For example, if you run git fetch without 570specifying a local branch as the target of the operation 571 572------------------------------------------------- 573$ git fetch git://example.com/proj.git theirbranch 574------------------------------------------------- 575 576the fetched commits will still be available from FETCH_HEAD. 577 578When we discuss merges we'll also see the special name MERGE_HEAD, 579which refers to the other branch that we're merging in to the current 580branch. 581 582The gitlink:git-rev-parse[1] command is a low-level command that is 583occasionally useful for translating some name for a commit to the object 584name for that commit: 585 586------------------------------------------------- 587$ git rev-parse origin 588e05db0fd4f31dde7005f075a84f96b360d05984b 589------------------------------------------------- 590 591[[creating-tags]] 592Creating tags 593------------- 594 595We can also create a tag to refer to a particular commit; after 596running 597 598------------------------------------------------- 599$ git tag stable-1 1b2e1d63ff 600------------------------------------------------- 601 602You can use stable-1 to refer to the commit 1b2e1d63ff. 603 604This creates a "lightweight" tag. If you would also like to include a 605comment with the tag, and possibly sign it cryptographically, then you 606should create a tag object instead; see the gitlink:git-tag[1] man page 607for details. 608 609[[browsing-revisions]] 610Browsing revisions 611------------------ 612 613The gitlink:git-log[1] command can show lists of commits. On its 614own, it shows all commits reachable from the parent commit; but you 615can also make more specific requests: 616 617------------------------------------------------- 618$ git log v2.5.. # commits since (not reachable from) v2.5 619$ git log test..master # commits reachable from master but not test 620$ git log master..test # ...reachable from test but not master 621$ git log master...test # ...reachable from either test or master, 622 # but not both 623$ git log --since="2 weeks ago" # commits from the last 2 weeks 624$ git log Makefile # commits which modify Makefile 625$ git log fs/ # ... which modify any file under fs/ 626$ git log -S'foo()' # commits which add or remove any file data 627 # matching the string 'foo()' 628------------------------------------------------- 629 630And of course you can combine all of these; the following finds 631commits since v2.5 which touch the Makefile or any file under fs: 632 633------------------------------------------------- 634$ git log v2.5.. Makefile fs/ 635------------------------------------------------- 636 637You can also ask git log to show patches: 638 639------------------------------------------------- 640$ git log -p 641------------------------------------------------- 642 643See the "--pretty" option in the gitlink:git-log[1] man page for more 644display options. 645 646Note that git log starts with the most recent commit and works 647backwards through the parents; however, since git history can contain 648multiple independent lines of development, the particular order that 649commits are listed in may be somewhat arbitrary. 650 651[[generating-diffs]] 652Generating diffs 653---------------- 654 655You can generate diffs between any two versions using 656gitlink:git-diff[1]: 657 658------------------------------------------------- 659$ git diff master..test 660------------------------------------------------- 661 662Sometimes what you want instead is a set of patches: 663 664------------------------------------------------- 665$ git format-patch master..test 666------------------------------------------------- 667 668will generate a file with a patch for each commit reachable from test 669but not from master. Note that if master also has commits which are 670not reachable from test, then the combined result of these patches 671will not be the same as the diff produced by the git-diff example. 672 673[[viewing-old-file-versions]] 674Viewing old file versions 675------------------------- 676 677You can always view an old version of a file by just checking out the 678correct revision first. But sometimes it is more convenient to be 679able to view an old version of a single file without checking 680anything out; this command does that: 681 682------------------------------------------------- 683$ git show v2.5:fs/locks.c 684------------------------------------------------- 685 686Before the colon may be anything that names a commit, and after it 687may be any path to a file tracked by git. 688 689[[history-examples]] 690Examples 691-------- 692 693[[counting-commits-on-a-branch]] 694Counting the number of commits on a branch 695~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 696 697Suppose you want to know how many commits you've made on "mybranch" 698since it diverged from "origin": 699 700------------------------------------------------- 701$ git log --pretty=oneline origin..mybranch | wc -l 702------------------------------------------------- 703 704Alternatively, you may often see this sort of thing done with the 705lower-level command gitlink:git-rev-list[1], which just lists the SHA1's 706of all the given commits: 707 708------------------------------------------------- 709$ git rev-list origin..mybranch | wc -l 710------------------------------------------------- 711 712[[checking-for-equal-branches]] 713Check whether two branches point at the same history 714~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 715 716Suppose you want to check whether two branches point at the same point 717in history. 718 719------------------------------------------------- 720$ git diff origin..master 721------------------------------------------------- 722 723will tell you whether the contents of the project are the same at the 724two branches; in theory, however, it's possible that the same project 725contents could have been arrived at by two different historical 726routes. You could compare the object names: 727 728------------------------------------------------- 729$ git rev-list origin 730e05db0fd4f31dde7005f075a84f96b360d05984b 731$ git rev-list master 732e05db0fd4f31dde7005f075a84f96b360d05984b 733------------------------------------------------- 734 735Or you could recall that the ... operator selects all commits 736contained reachable from either one reference or the other but not 737both: so 738 739------------------------------------------------- 740$ git log origin...master 741------------------------------------------------- 742 743will return no commits when the two branches are equal. 744 745[[finding-tagged-descendants]] 746Find first tagged version including a given fix 747~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 748 749Suppose you know that the commit e05db0fd fixed a certain problem. 750You'd like to find the earliest tagged release that contains that 751fix. 752 753Of course, there may be more than one answer--if the history branched 754after commit e05db0fd, then there could be multiple "earliest" tagged 755releases. 756 757You could just visually inspect the commits since e05db0fd: 758 759------------------------------------------------- 760$ gitk e05db0fd.. 761------------------------------------------------- 762 763Or you can use gitlink:git-name-rev[1], which will give the commit a 764name based on any tag it finds pointing to one of the commit's 765descendants: 766 767------------------------------------------------- 768$ git name-rev --tags e05db0fd 769e05db0fd tags/v1.5.0-rc1^0~23 770------------------------------------------------- 771 772The gitlink:git-describe[1] command does the opposite, naming the 773revision using a tag on which the given commit is based: 774 775------------------------------------------------- 776$ git describe e05db0fd 777v1.5.0-rc0-260-ge05db0f 778------------------------------------------------- 779 780but that may sometimes help you guess which tags might come after the 781given commit. 782 783If you just want to verify whether a given tagged version contains a 784given commit, you could use gitlink:git-merge-base[1]: 785 786------------------------------------------------- 787$ git merge-base e05db0fd v1.5.0-rc1 788e05db0fd4f31dde7005f075a84f96b360d05984b 789------------------------------------------------- 790 791The merge-base command finds a common ancestor of the given commits, 792and always returns one or the other in the case where one is a 793descendant of the other; so the above output shows that e05db0fd 794actually is an ancestor of v1.5.0-rc1. 795 796Alternatively, note that 797 798------------------------------------------------- 799$ git log v1.5.0-rc1..e05db0fd 800------------------------------------------------- 801 802will produce empty output if and only if v1.5.0-rc1 includes e05db0fd, 803because it outputs only commits that are not reachable from v1.5.0-rc1. 804 805As yet another alternative, the gitlink:git-show-branch[1] command lists 806the commits reachable from its arguments with a display on the left-hand 807side that indicates which arguments that commit is reachable from. So, 808you can run something like 809 810------------------------------------------------- 811$ git show-branch e05db0fd v1.5.0-rc0 v1.5.0-rc1 v1.5.0-rc2 812! [e05db0fd] Fix warnings in sha1_file.c - use C99 printf format if 813available 814 ! [v1.5.0-rc0] GIT v1.5.0 preview 815 ! [v1.5.0-rc1] GIT v1.5.0-rc1 816 ! [v1.5.0-rc2] GIT v1.5.0-rc2 817... 818------------------------------------------------- 819 820then search for a line that looks like 821 822------------------------------------------------- 823+ ++ [e05db0fd] Fix warnings in sha1_file.c - use C99 printf format if 824available 825------------------------------------------------- 826 827Which shows that e05db0fd is reachable from itself, from v1.5.0-rc1, and 828from v1.5.0-rc2, but not from v1.5.0-rc0. 829 830[[making-a-release]] 831Creating a changelog and tarball for a software release 832~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 833 834The gitlink:git-archive[1] command can create a tar or zip archive from 835any version of a project; for example: 836 837------------------------------------------------- 838$ git archive --format=tar --prefix=project/ HEAD | gzip >latest.tar.gz 839------------------------------------------------- 840 841will use HEAD to produce a tar archive in which each filename is 842preceded by "prefix/". 843 844If you're releasing a new version of a software project, you may want 845to simultaneously make a changelog to include in the release 846announcement. 847 848Linus Torvalds, for example, makes new kernel releases by tagging them, 849then running: 850 851------------------------------------------------- 852$ release-script 2.6.12 2.6.13-rc6 2.6.13-rc7 853------------------------------------------------- 854 855where release-script is a shell script that looks like: 856 857------------------------------------------------- 858#!/bin/sh 859stable="$1" 860last="$2" 861new="$3" 862echo "# git tag v$new" 863echo "git archive --prefix=linux-$new/ v$new | gzip -9 > ../linux-$new.tar.gz" 864echo "git diff v$stable v$new | gzip -9 > ../patch-$new.gz" 865echo "git log --no-merges v$new ^v$last > ../ChangeLog-$new" 866echo "git shortlog --no-merges v$new ^v$last > ../ShortLog" 867echo "git diff --stat --summary -M v$last v$new > ../diffstat-$new" 868------------------------------------------------- 869 870and then he just cut-and-pastes the output commands after verifying that 871they look OK. 872 873[[Developing-with-git]] 874Developing with git 875=================== 876 877[[telling-git-your-name]] 878Telling git your name 879--------------------- 880 881Before creating any commits, you should introduce yourself to git. The 882easiest way to do so is to make sure the following lines appear in a 883file named .gitconfig in your home directory: 884 885------------------------------------------------ 886[user] 887 name = Your Name Comes Here 888 email = you@yourdomain.example.com 889------------------------------------------------ 890 891(See the "CONFIGURATION FILE" section of gitlink:git-config[1] for 892details on the configuration file.) 893 894 895[[creating-a-new-repository]] 896Creating a new repository 897------------------------- 898 899Creating a new repository from scratch is very easy: 900 901------------------------------------------------- 902$ mkdir project 903$ cd project 904$ git init 905------------------------------------------------- 906 907If you have some initial content (say, a tarball): 908 909------------------------------------------------- 910$ tar -xzvf project.tar.gz 911$ cd project 912$ git init 913$ git add . # include everything below ./ in the first commit: 914$ git commit 915------------------------------------------------- 916 917[[how-to-make-a-commit]] 918How to make a commit 919-------------------- 920 921Creating a new commit takes three steps: 922 923 1. Making some changes to the working directory using your 924 favorite editor. 925 2. Telling git about your changes. 926 3. Creating the commit using the content you told git about 927 in step 2. 928 929In practice, you can interleave and repeat steps 1 and 2 as many 930times as you want: in order to keep track of what you want committed 931at step 3, git maintains a snapshot of the tree's contents in a 932special staging area called "the index." 933 934At the beginning, the content of the index will be identical to 935that of the HEAD. The command "git diff --cached", which shows 936the difference between the HEAD and the index, should therefore 937produce no output at that point. 938 939Modifying the index is easy: 940 941To update the index with the new contents of a modified file, use 942 943------------------------------------------------- 944$ git add path/to/file 945------------------------------------------------- 946 947To add the contents of a new file to the index, use 948 949------------------------------------------------- 950$ git add path/to/file 951------------------------------------------------- 952 953To remove a file from the index and from the working tree, 954 955------------------------------------------------- 956$ git rm path/to/file 957------------------------------------------------- 958 959After each step you can verify that 960 961------------------------------------------------- 962$ git diff --cached 963------------------------------------------------- 964 965always shows the difference between the HEAD and the index file--this 966is what you'd commit if you created the commit now--and that 967 968------------------------------------------------- 969$ git diff 970------------------------------------------------- 971 972shows the difference between the working tree and the index file. 973 974Note that "git add" always adds just the current contents of a file 975to the index; further changes to the same file will be ignored unless 976you run git-add on the file again. 977 978When you're ready, just run 979 980------------------------------------------------- 981$ git commit 982------------------------------------------------- 983 984and git will prompt you for a commit message and then create the new 985commit. Check to make sure it looks like what you expected with 986 987------------------------------------------------- 988$ git show 989------------------------------------------------- 990 991As a special shortcut, 992 993------------------------------------------------- 994$ git commit -a 995------------------------------------------------- 996 997will update the index with any files that you've modified or removed 998and create a commit, all in one step. 9991000A number of commands are useful for keeping track of what you're1001about to commit:10021003-------------------------------------------------1004$ git diff --cached # difference between HEAD and the index; what1005 # would be commited if you ran "commit" now.1006$ git diff # difference between the index file and your1007 # working directory; changes that would not1008 # be included if you ran "commit" now.1009$ git diff HEAD # difference between HEAD and working tree; what1010 # would be committed if you ran "commit -a" now.1011$ git status # a brief per-file summary of the above.1012-------------------------------------------------10131014[[creating-good-commit-messages]]1015Creating good commit messages1016-----------------------------10171018Though not required, it's a good idea to begin the commit message1019with a single short (less than 50 character) line summarizing the1020change, followed by a blank line and then a more thorough1021description. Tools that turn commits into email, for example, use1022the first line on the Subject line and the rest of the commit in the1023body.10241025[[how-to-merge]]1026How to merge1027------------10281029You can rejoin two diverging branches of development using1030gitlink:git-merge[1]:10311032-------------------------------------------------1033$ git merge branchname1034-------------------------------------------------10351036merges the development in the branch "branchname" into the current1037branch. If there are conflicts--for example, if the same file is1038modified in two different ways in the remote branch and the local1039branch--then you are warned; the output may look something like this:10401041-------------------------------------------------1042$ git merge next1043 100% (4/4) done1044Auto-merged file.txt1045CONFLICT (content): Merge conflict in file.txt1046Automatic merge failed; fix conflicts and then commit the result.1047-------------------------------------------------10481049Conflict markers are left in the problematic files, and after1050you resolve the conflicts manually, you can update the index1051with the contents and run git commit, as you normally would when1052creating a new file.10531054If you examine the resulting commit using gitk, you will see that it1055has two parents, one pointing to the top of the current branch, and1056one to the top of the other branch.10571058[[resolving-a-merge]]1059Resolving a merge1060-----------------10611062When a merge isn't resolved automatically, git leaves the index and1063the working tree in a special state that gives you all the1064information you need to help resolve the merge.10651066Files with conflicts are marked specially in the index, so until you1067resolve the problem and update the index, gitlink:git-commit[1] will1068fail:10691070-------------------------------------------------1071$ git commit1072file.txt: needs merge1073-------------------------------------------------10741075Also, gitlink:git-status[1] will list those files as "unmerged", and the1076files with conflicts will have conflict markers added, like this:10771078-------------------------------------------------1079<<<<<<< HEAD:file.txt1080Hello world1081=======1082Goodbye1083>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt1084-------------------------------------------------10851086All you need to do is edit the files to resolve the conflicts, and then10871088-------------------------------------------------1089$ git add file.txt1090$ git commit1091-------------------------------------------------10921093Note that the commit message will already be filled in for you with1094some information about the merge. Normally you can just use this1095default message unchanged, but you may add additional commentary of1096your own if desired.10971098The above is all you need to know to resolve a simple merge. But git1099also provides more information to help resolve conflicts:11001101[[conflict-resolution]]1102Getting conflict-resolution help during a merge1103~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~11041105All of the changes that git was able to merge automatically are1106already added to the index file, so gitlink:git-diff[1] shows only1107the conflicts. It uses an unusual syntax:11081109-------------------------------------------------1110$ git diff1111diff --cc file.txt1112index 802992c,2b60207..00000001113--- a/file.txt1114+++ b/file.txt1115@@@ -1,1 -1,1 +1,5 @@@1116++<<<<<<< HEAD:file.txt1117 +Hello world1118++=======1119+ Goodbye1120++>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt1121-------------------------------------------------11221123Recall that the commit which will be commited after we resolve this1124conflict will have two parents instead of the usual one: one parent1125will be HEAD, the tip of the current branch; the other will be the1126tip of the other branch, which is stored temporarily in MERGE_HEAD.11271128During the merge, the index holds three versions of each file. Each of1129these three "file stages" represents a different version of the file:11301131-------------------------------------------------1132$ git show :1:file.txt # the file in a common ancestor of both branches1133$ git show :2:file.txt # the version from HEAD, but including any1134 # nonconflicting changes from MERGE_HEAD1135$ git show :3:file.txt # the version from MERGE_HEAD, but including any1136 # nonconflicting changes from HEAD.1137-------------------------------------------------11381139Since the stage 2 and stage 3 versions have already been updated with1140nonconflicting changes, the only remaining differences between them are1141the important ones; thus gitlink:git-diff[1] can use the information in1142the index to show only those conflicts.11431144The diff above shows the differences between the working-tree version of1145file.txt and the stage 2 and stage 3 versions. So instead of preceding1146each line by a single "+" or "-", it now uses two columns: the first1147column is used for differences between the first parent and the working1148directory copy, and the second for differences between the second parent1149and the working directory copy. (See the "COMBINED DIFF FORMAT" section1150of gitlink:git-diff-files[1] for a details of the format.)11511152After resolving the conflict in the obvious way (but before updating the1153index), the diff will look like:11541155-------------------------------------------------1156$ git diff1157diff --cc file.txt1158index 802992c,2b60207..00000001159--- a/file.txt1160+++ b/file.txt1161@@@ -1,1 -1,1 +1,1 @@@1162- Hello world1163 -Goodbye1164++Goodbye world1165-------------------------------------------------11661167This shows that our resolved version deleted "Hello world" from the1168first parent, deleted "Goodbye" from the second parent, and added1169"Goodbye world", which was previously absent from both.11701171Some special diff options allow diffing the working directory against1172any of these stages:11731174-------------------------------------------------1175$ git diff -1 file.txt # diff against stage 11176$ git diff --base file.txt # same as the above1177$ git diff -2 file.txt # diff against stage 21178$ git diff --ours file.txt # same as the above1179$ git diff -3 file.txt # diff against stage 31180$ git diff --theirs file.txt # same as the above.1181-------------------------------------------------11821183The gitlink:git-log[1] and gitk[1] commands also provide special help1184for merges:11851186-------------------------------------------------1187$ git log --merge1188$ gitk --merge1189-------------------------------------------------11901191These will display all commits which exist only on HEAD or on1192MERGE_HEAD, and which touch an unmerged file.11931194You may also use gitlink:git-mergetool[1], which lets you merge the1195unmerged files using external tools such as emacs or kdiff3.11961197Each time you resolve the conflicts in a file and update the index:11981199-------------------------------------------------1200$ git add file.txt1201-------------------------------------------------12021203the different stages of that file will be "collapsed", after which1204git-diff will (by default) no longer show diffs for that file.12051206[[undoing-a-merge]]1207Undoing a merge1208---------------12091210If you get stuck and decide to just give up and throw the whole mess1211away, you can always return to the pre-merge state with12121213-------------------------------------------------1214$ git reset --hard HEAD1215-------------------------------------------------12161217Or, if you've already commited the merge that you want to throw away,12181219-------------------------------------------------1220$ git reset --hard ORIG_HEAD1221-------------------------------------------------12221223However, this last command can be dangerous in some cases--never1224throw away a commit you have already committed if that commit may1225itself have been merged into another branch, as doing so may confuse1226further merges.12271228[[fast-forwards]]1229Fast-forward merges1230-------------------12311232There is one special case not mentioned above, which is treated1233differently. Normally, a merge results in a merge commit, with two1234parents, one pointing at each of the two lines of development that1235were merged.12361237However, if the current branch is a descendant of the other--so every1238commit present in the one is already contained in the other--then git1239just performs a "fast forward"; the head of the current branch is moved1240forward to point at the head of the merged-in branch, without any new1241commits being created.12421243[[fixing-mistakes]]1244Fixing mistakes1245---------------12461247If you've messed up the working tree, but haven't yet committed your1248mistake, you can return the entire working tree to the last committed1249state with12501251-------------------------------------------------1252$ git reset --hard HEAD1253-------------------------------------------------12541255If you make a commit that you later wish you hadn't, there are two1256fundamentally different ways to fix the problem:12571258 1. You can create a new commit that undoes whatever was done1259 by the previous commit. This is the correct thing if your1260 mistake has already been made public.12611262 2. You can go back and modify the old commit. You should1263 never do this if you have already made the history public;1264 git does not normally expect the "history" of a project to1265 change, and cannot correctly perform repeated merges from1266 a branch that has had its history changed.12671268[[reverting-a-commit]]1269Fixing a mistake with a new commit1270~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~12711272Creating a new commit that reverts an earlier change is very easy;1273just pass the gitlink:git-revert[1] command a reference to the bad1274commit; for example, to revert the most recent commit:12751276-------------------------------------------------1277$ git revert HEAD1278-------------------------------------------------12791280This will create a new commit which undoes the change in HEAD. You1281will be given a chance to edit the commit message for the new commit.12821283You can also revert an earlier change, for example, the next-to-last:12841285-------------------------------------------------1286$ git revert HEAD^1287-------------------------------------------------12881289In this case git will attempt to undo the old change while leaving1290intact any changes made since then. If more recent changes overlap1291with the changes to be reverted, then you will be asked to fix1292conflicts manually, just as in the case of <<resolving-a-merge,1293resolving a merge>>.12941295[[fixing-a-mistake-by-editing-history]]1296Fixing a mistake by editing history1297~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~12981299If the problematic commit is the most recent commit, and you have not1300yet made that commit public, then you may just1301<<undoing-a-merge,destroy it using git-reset>>.13021303Alternatively, you1304can edit the working directory and update the index to fix your1305mistake, just as if you were going to <<how-to-make-a-commit,create a1306new commit>>, then run13071308-------------------------------------------------1309$ git commit --amend1310-------------------------------------------------13111312which will replace the old commit by a new commit incorporating your1313changes, giving you a chance to edit the old commit message first.13141315Again, you should never do this to a commit that may already have1316been merged into another branch; use gitlink:git-revert[1] instead in1317that case.13181319It is also possible to edit commits further back in the history, but1320this is an advanced topic to be left for1321<<cleaning-up-history,another chapter>>.13221323[[checkout-of-path]]1324Checking out an old version of a file1325~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~13261327In the process of undoing a previous bad change, you may find it1328useful to check out an older version of a particular file using1329gitlink:git-checkout[1]. We've used git checkout before to switch1330branches, but it has quite different behavior if it is given a path1331name: the command13321333-------------------------------------------------1334$ git checkout HEAD^ path/to/file1335-------------------------------------------------13361337replaces path/to/file by the contents it had in the commit HEAD^, and1338also updates the index to match. It does not change branches.13391340If you just want to look at an old version of the file, without1341modifying the working directory, you can do that with1342gitlink:git-show[1]:13431344-------------------------------------------------1345$ git show HEAD^:path/to/file1346-------------------------------------------------13471348which will display the given version of the file.13491350[[ensuring-good-performance]]1351Ensuring good performance1352-------------------------13531354On large repositories, git depends on compression to keep the history1355information from taking up to much space on disk or in memory.13561357This compression is not performed automatically. Therefore you1358should occasionally run gitlink:git-gc[1]:13591360-------------------------------------------------1361$ git gc1362-------------------------------------------------13631364to recompress the archive. This can be very time-consuming, so1365you may prefer to run git-gc when you are not doing other work.136613671368[[ensuring-reliability]]1369Ensuring reliability1370--------------------13711372[[checking-for-corruption]]1373Checking the repository for corruption1374~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~13751376The gitlink:git-fsck[1] command runs a number of self-consistency checks1377on the repository, and reports on any problems. This may take some1378time. The most common warning by far is about "dangling" objects:13791380-------------------------------------------------1381$ git fsck1382dangling commit 7281251ddd2a61e38657c827739c57015671a6b31383dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a631384dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b51385dangling blob 218761f9d90712d37a9c5e36f406f92202db07eb1386dangling commit bf093535a34a4d35731aa2bd90fe6b176302f14f1387dangling commit 8e4bec7f2ddaa268bef999853c25755452100f8e1388dangling tree d50bb86186bf27b681d25af89d3b5b68382e40851389dangling tree b24c2473f1fd3d91352a624795be026d64c8841f1390...1391-------------------------------------------------13921393Dangling objects are not a problem. At worst they may take up a little1394extra disk space. They can sometimes provide a last-resort method of1395recovery lost work--see <<dangling-objects>> for details. However, if1396you want, you may remove them with gitlink:git-prune[1] or the --prune1397option to gitlink:git-gc[1]:13981399-------------------------------------------------1400$ git gc --prune1401-------------------------------------------------14021403This may be time-consuming. Unlike most other git operations (including1404git-gc when run without any options), it is not safe to prune while1405other git operations are in progress in the same repository.14061407[[recovering-lost-changes]]1408Recovering lost changes1409~~~~~~~~~~~~~~~~~~~~~~~14101411[[reflogs]]1412Reflogs1413^^^^^^^14141415Say you modify a branch with gitlink:git-reset[1] --hard, and then1416realize that the branch was the only reference you had to that point in1417history.14181419Fortunately, git also keeps a log, called a "reflog", of all the1420previous values of each branch. So in this case you can still find the1421old history using, for example, 14221423-------------------------------------------------1424$ git log master@{1}1425-------------------------------------------------14261427This lists the commits reachable from the previous version of the head.1428This syntax can be used to with any git command that accepts a commit,1429not just with git log. Some other examples:14301431-------------------------------------------------1432$ git show master@{2} # See where the branch pointed 2,1433$ git show master@{3} # 3, ... changes ago.1434$ gitk master@{yesterday} # See where it pointed yesterday,1435$ gitk master@{"1 week ago"} # ... or last week1436$ git log --walk-reflogs master # show reflog entries for master1437-------------------------------------------------14381439A separate reflog is kept for the HEAD, so14401441-------------------------------------------------1442$ git show HEAD@{"1 week ago"}1443-------------------------------------------------14441445will show what HEAD pointed to one week ago, not what the current branch1446pointed to one week ago. This allows you to see the history of what1447you've checked out.14481449The reflogs are kept by default for 30 days, after which they may be1450pruned. See gitlink:git-reflog[1] and gitlink:git-gc[1] to learn1451how to control this pruning, and see the "SPECIFYING REVISIONS"1452section of gitlink:git-rev-parse[1] for details.14531454Note that the reflog history is very different from normal git history.1455While normal history is shared by every repository that works on the1456same project, the reflog history is not shared: it tells you only about1457how the branches in your local repository have changed over time.14581459[[dangling-object-recovery]]1460Examining dangling objects1461^^^^^^^^^^^^^^^^^^^^^^^^^^14621463In some situations the reflog may not be able to save you. For example,1464suppose you delete a branch, then realize you need the history it1465contained. The reflog is also deleted; however, if you have not yet1466pruned the repository, then you may still be able to find the lost1467commits in the dangling objects that git-fsck reports. See1468<<dangling-objects>> for the details.14691470-------------------------------------------------1471$ git fsck1472dangling commit 7281251ddd2a61e38657c827739c57015671a6b31473dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a631474dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b51475...1476-------------------------------------------------14771478You can examine1479one of those dangling commits with, for example,14801481------------------------------------------------1482$ gitk 7281251ddd --not --all1483------------------------------------------------14841485which does what it sounds like: it says that you want to see the commit1486history that is described by the dangling commit(s), but not the1487history that is described by all your existing branches and tags. Thus1488you get exactly the history reachable from that commit that is lost.1489(And notice that it might not be just one commit: we only report the1490"tip of the line" as being dangling, but there might be a whole deep1491and complex commit history that was dropped.)14921493If you decide you want the history back, you can always create a new1494reference pointing to it, for example, a new branch:14951496------------------------------------------------1497$ git branch recovered-branch 7281251ddd 1498------------------------------------------------14991500Other types of dangling objects (blobs and trees) are also possible, and1501dangling objects can arise in other situations.150215031504[[sharing-development]]1505Sharing development with others1506===============================15071508[[getting-updates-with-git-pull]]1509Getting updates with git pull1510-----------------------------15111512After you clone a repository and make a few changes of your own, you1513may wish to check the original repository for updates and merge them1514into your own work.15151516We have already seen <<Updating-a-repository-with-git-fetch,how to1517keep remote tracking branches up to date>> with gitlink:git-fetch[1],1518and how to merge two branches. So you can merge in changes from the1519original repository's master branch with:15201521-------------------------------------------------1522$ git fetch1523$ git merge origin/master1524-------------------------------------------------15251526However, the gitlink:git-pull[1] command provides a way to do this in1527one step:15281529-------------------------------------------------1530$ git pull origin master1531-------------------------------------------------15321533In fact, "origin" is normally the default repository to pull from,1534and the default branch is normally the HEAD of the remote repository,1535so often you can accomplish the above with just15361537-------------------------------------------------1538$ git pull1539-------------------------------------------------15401541See the descriptions of the branch.<name>.remote and branch.<name>.merge1542options in gitlink:git-config[1] to learn how to control these defaults1543depending on the current branch. Also note that the --track option to1544gitlink:git-branch[1] and gitlink:git-checkout[1] can be used to1545automatically set the default remote branch to pull from at the time1546that a branch is created:15471548-------------------------------------------------1549$ git checkout --track -b origin/maint maint1550-------------------------------------------------15511552In addition to saving you keystrokes, "git pull" also helps you by1553producing a default commit message documenting the branch and1554repository that you pulled from.15551556(But note that no such commit will be created in the case of a1557<<fast-forwards,fast forward>>; instead, your branch will just be1558updated to point to the latest commit from the upstream branch.)15591560The git-pull command can also be given "." as the "remote" repository,1561in which case it just merges in a branch from the current repository; so1562the commands15631564-------------------------------------------------1565$ git pull . branch1566$ git merge branch1567-------------------------------------------------15681569are roughly equivalent. The former is actually very commonly used.15701571[[submitting-patches]]1572Submitting patches to a project1573-------------------------------15741575If you just have a few changes, the simplest way to submit them may1576just be to send them as patches in email:15771578First, use gitlink:git-format-patch[1]; for example:15791580-------------------------------------------------1581$ git format-patch origin1582-------------------------------------------------15831584will produce a numbered series of files in the current directory, one1585for each patch in the current branch but not in origin/HEAD.15861587You can then import these into your mail client and send them by1588hand. However, if you have a lot to send at once, you may prefer to1589use the gitlink:git-send-email[1] script to automate the process.1590Consult the mailing list for your project first to determine how they1591prefer such patches be handled.15921593[[importing-patches]]1594Importing patches to a project1595------------------------------15961597Git also provides a tool called gitlink:git-am[1] (am stands for1598"apply mailbox"), for importing such an emailed series of patches.1599Just save all of the patch-containing messages, in order, into a1600single mailbox file, say "patches.mbox", then run16011602-------------------------------------------------1603$ git am -3 patches.mbox1604-------------------------------------------------16051606Git will apply each patch in order; if any conflicts are found, it1607will stop, and you can fix the conflicts as described in1608"<<resolving-a-merge,Resolving a merge>>". (The "-3" option tells1609git to perform a merge; if you would prefer it just to abort and1610leave your tree and index untouched, you may omit that option.)16111612Once the index is updated with the results of the conflict1613resolution, instead of creating a new commit, just run16141615-------------------------------------------------1616$ git am --resolved1617-------------------------------------------------16181619and git will create the commit for you and continue applying the1620remaining patches from the mailbox.16211622The final result will be a series of commits, one for each patch in1623the original mailbox, with authorship and commit log message each1624taken from the message containing each patch.16251626[[setting-up-a-public-repository]]1627Setting up a public repository1628------------------------------16291630Another way to submit changes to a project is to simply tell the1631maintainer of that project to pull from your repository, exactly as1632you did in the section "<<getting-updates-with-git-pull, Getting1633updates with git pull>>".16341635If you and maintainer both have accounts on the same machine, then1636then you can just pull changes from each other's repositories1637directly; note that all of the commands (gitlink:git-clone[1],1638git-fetch[1], git-pull[1], etc.) that accept a URL as an argument1639will also accept a local directory name; so, for example, you can1640use16411642-------------------------------------------------1643$ git clone /path/to/repository1644$ git pull /path/to/other/repository1645-------------------------------------------------16461647If this sort of setup is inconvenient or impossible, another (more1648common) option is to set up a public repository on a public server.1649This also allows you to cleanly separate private work in progress1650from publicly visible work.16511652You will continue to do your day-to-day work in your personal1653repository, but periodically "push" changes from your personal1654repository into your public repository, allowing other developers to1655pull from that repository. So the flow of changes, in a situation1656where there is one other developer with a public repository, looks1657like this:16581659 you push1660 your personal repo ------------------> your public repo1661 ^ |1662 | |1663 | you pull | they pull1664 | |1665 | |1666 | they push V1667 their public repo <------------------- their repo16681669Now, assume your personal repository is in the directory ~/proj. We1670first create a new clone of the repository:16711672-------------------------------------------------1673$ git clone --bare ~/proj proj.git1674-------------------------------------------------16751676The resulting directory proj.git contains a "bare" git repository--it is1677just the contents of the ".git" directory, without a checked-out copy of1678a working directory.16791680Next, copy proj.git to the server where you plan to host the1681public repository. You can use scp, rsync, or whatever is most1682convenient.16831684If somebody else maintains the public server, they may already have1685set up a git service for you, and you may skip to the section1686"<<pushing-changes-to-a-public-repository,Pushing changes to a public1687repository>>", below.16881689Otherwise, the following sections explain how to export your newly1690created public repository:16911692[[exporting-via-http]]1693Exporting a git repository via http1694-----------------------------------16951696The git protocol gives better performance and reliability, but on a1697host with a web server set up, http exports may be simpler to set up.16981699All you need to do is place the newly created bare git repository in1700a directory that is exported by the web server, and make some1701adjustments to give web clients some extra information they need:17021703-------------------------------------------------1704$ mv proj.git /home/you/public_html/proj.git1705$ cd proj.git1706$ git --bare update-server-info1707$ chmod a+x hooks/post-update1708-------------------------------------------------17091710(For an explanation of the last two lines, see1711gitlink:git-update-server-info[1], and the documentation1712link:hooks.txt[Hooks used by git].)17131714Advertise the url of proj.git. Anybody else should then be able to1715clone or pull from that url, for example with a commandline like:17161717-------------------------------------------------1718$ git clone http://yourserver.com/~you/proj.git1719-------------------------------------------------17201721(See also1722link:howto/setup-git-server-over-http.txt[setup-git-server-over-http]1723for a slightly more sophisticated setup using WebDAV which also1724allows pushing over http.)17251726[[exporting-via-git]]1727Exporting a git repository via the git protocol1728-----------------------------------------------17291730This is the preferred method.17311732For now, we refer you to the gitlink:git-daemon[1] man page for1733instructions. (See especially the examples section.)17341735[[pushing-changes-to-a-public-repository]]1736Pushing changes to a public repository1737--------------------------------------17381739Note that the two techniques outline above (exporting via1740<<exporting-via-http,http>> or <<exporting-via-git,git>>) allow other1741maintainers to fetch your latest changes, but they do not allow write1742access, which you will need to update the public repository with the1743latest changes created in your private repository.17441745The simplest way to do this is using gitlink:git-push[1] and ssh; to1746update the remote branch named "master" with the latest state of your1747branch named "master", run17481749-------------------------------------------------1750$ git push ssh://yourserver.com/~you/proj.git master:master1751-------------------------------------------------17521753or just17541755-------------------------------------------------1756$ git push ssh://yourserver.com/~you/proj.git master1757-------------------------------------------------17581759As with git-fetch, git-push will complain if this does not result in1760a <<fast-forwards,fast forward>>. Normally this is a sign of1761something wrong. However, if you are sure you know what you're1762doing, you may force git-push to perform the update anyway by1763proceeding the branch name by a plus sign:17641765-------------------------------------------------1766$ git push ssh://yourserver.com/~you/proj.git +master1767-------------------------------------------------17681769As with git-fetch, you may also set up configuration options to1770save typing; so, for example, after17711772-------------------------------------------------1773$ cat >>.git/config <<EOF1774[remote "public-repo"]1775 url = ssh://yourserver.com/~you/proj.git1776EOF1777-------------------------------------------------17781779you should be able to perform the above push with just17801781-------------------------------------------------1782$ git push public-repo master1783-------------------------------------------------17841785See the explanations of the remote.<name>.url, branch.<name>.remote,1786and remote.<name>.push options in gitlink:git-config[1] for1787details.17881789[[setting-up-a-shared-repository]]1790Setting up a shared repository1791------------------------------17921793Another way to collaborate is by using a model similar to that1794commonly used in CVS, where several developers with special rights1795all push to and pull from a single shared repository. See1796link:cvs-migration.txt[git for CVS users] for instructions on how to1797set this up.17981799[[setting-up-gitweb]]1800Allow web browsing of a repository1801----------------------------------18021803The gitweb cgi script provides users an easy way to browse your1804project's files and history without having to install git; see the file1805gitweb/INSTALL in the git source tree for instructions on setting it up.18061807[[sharing-development-examples]]1808Examples1809--------18101811[[maintaining-topic-branches]]1812Maintaining topic branches for a Linux subsystem maintainer1813~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~18141815This describes how Tony Luck uses git in his role as maintainer of the1816IA64 architecture for the Linux kernel.18171818He uses two public branches:18191820 - A "test" tree into which patches are initially placed so that they1821 can get some exposure when integrated with other ongoing development.1822 This tree is available to Andrew for pulling into -mm whenever he1823 wants.18241825 - A "release" tree into which tested patches are moved for final sanity1826 checking, and as a vehicle to send them upstream to Linus (by sending1827 him a "please pull" request.)18281829He also uses a set of temporary branches ("topic branches"), each1830containing a logical grouping of patches.18311832To set this up, first create your work tree by cloning Linus's public1833tree:18341835-------------------------------------------------1836$ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git work1837$ cd work1838-------------------------------------------------18391840Linus's tree will be stored in the remote branch named origin/master,1841and can be updated using gitlink:git-fetch[1]; you can track other1842public trees using gitlink:git-remote[1] to set up a "remote" and1843git-fetch[1] to keep them up-to-date; see <<repositories-and-branches>>.18441845Now create the branches in which you are going to work; these start out1846at the current tip of origin/master branch, and should be set up (using1847the --track option to gitlink:git-branch[1]) to merge changes in from1848Linus by default.18491850-------------------------------------------------1851$ git branch --track test origin/master1852$ git branch --track release origin/master1853-------------------------------------------------18541855These can be easily kept up to date using gitlink:git-pull[1]18561857-------------------------------------------------1858$ git checkout test && git pull1859$ git checkout release && git pull1860-------------------------------------------------18611862Important note! If you have any local changes in these branches, then1863this merge will create a commit object in the history (with no local1864changes git will simply do a "Fast forward" merge). Many people dislike1865the "noise" that this creates in the Linux history, so you should avoid1866doing this capriciously in the "release" branch, as these noisy commits1867will become part of the permanent history when you ask Linus to pull1868from the release branch.18691870A few configuration variables (see gitlink:git-config[1]) can1871make it easy to push both branches to your public tree. (See1872<<setting-up-a-public-repository>>.)18731874-------------------------------------------------1875$ cat >> .git/config <<EOF1876[remote "mytree"]1877 url = master.kernel.org:/pub/scm/linux/kernel/git/aegl/linux-2.6.git1878 push = release1879 push = test1880EOF1881-------------------------------------------------18821883Then you can push both the test and release trees using1884gitlink:git-push[1]:18851886-------------------------------------------------1887$ git push mytree1888-------------------------------------------------18891890or push just one of the test and release branches using:18911892-------------------------------------------------1893$ git push mytree test1894-------------------------------------------------18951896or18971898-------------------------------------------------1899$ git push mytree release1900-------------------------------------------------19011902Now to apply some patches from the community. Think of a short1903snappy name for a branch to hold this patch (or related group of1904patches), and create a new branch from the current tip of Linus's1905branch:19061907-------------------------------------------------1908$ git checkout -b speed-up-spinlocks origin1909-------------------------------------------------19101911Now you apply the patch(es), run some tests, and commit the change(s). If1912the patch is a multi-part series, then you should apply each as a separate1913commit to this branch.19141915-------------------------------------------------1916$ ... patch ... test ... commit [ ... patch ... test ... commit ]*1917-------------------------------------------------19181919When you are happy with the state of this change, you can pull it into the1920"test" branch in preparation to make it public:19211922-------------------------------------------------1923$ git checkout test && git pull . speed-up-spinlocks1924-------------------------------------------------19251926It is unlikely that you would have any conflicts here ... but you might if you1927spent a while on this step and had also pulled new versions from upstream.19281929Some time later when enough time has passed and testing done, you can pull the1930same branch into the "release" tree ready to go upstream. This is where you1931see the value of keeping each patch (or patch series) in its own branch. It1932means that the patches can be moved into the "release" tree in any order.19331934-------------------------------------------------1935$ git checkout release && git pull . speed-up-spinlocks1936-------------------------------------------------19371938After a while, you will have a number of branches, and despite the1939well chosen names you picked for each of them, you may forget what1940they are for, or what status they are in. To get a reminder of what1941changes are in a specific branch, use:19421943-------------------------------------------------1944$ git log linux..branchname | git-shortlog1945-------------------------------------------------19461947To see whether it has already been merged into the test or release branches1948use:19491950-------------------------------------------------1951$ git log test..branchname1952-------------------------------------------------19531954or19551956-------------------------------------------------1957$ git log release..branchname1958-------------------------------------------------19591960(If this branch has not yet been merged you will see some log entries.1961If it has been merged, then there will be no output.)19621963Once a patch completes the great cycle (moving from test to release,1964then pulled by Linus, and finally coming back into your local1965"origin/master" branch) the branch for this change is no longer needed.1966You detect this when the output from:19671968-------------------------------------------------1969$ git log origin..branchname1970-------------------------------------------------19711972is empty. At this point the branch can be deleted:19731974-------------------------------------------------1975$ git branch -d branchname1976-------------------------------------------------19771978Some changes are so trivial that it is not necessary to create a separate1979branch and then merge into each of the test and release branches. For1980these changes, just apply directly to the "release" branch, and then1981merge that into the "test" branch.19821983To create diffstat and shortlog summaries of changes to include in a "please1984pull" request to Linus you can use:19851986-------------------------------------------------1987$ git diff --stat origin..release1988-------------------------------------------------19891990and19911992-------------------------------------------------1993$ git log -p origin..release | git shortlog1994-------------------------------------------------19951996Here are some of the scripts that simplify all this even further.19971998-------------------------------------------------1999==== update script ====2000# Update a branch in my GIT tree. If the branch to be updated2001# is origin, then pull from kernel.org. Otherwise merge2002# origin/master branch into test|release branch20032004case "$1" in2005test|release)2006 git checkout $1 && git pull . origin2007 ;;2008origin)2009 before=$(cat .git/refs/remotes/origin/master)2010 git fetch origin2011 after=$(cat .git/refs/remotes/origin/master)2012 if [ $before != $after ]2013 then2014 git log $before..$after | git shortlog2015 fi2016 ;;2017*)2018 echo "Usage: $0 origin|test|release" 1>&22019 exit 12020 ;;2021esac2022-------------------------------------------------20232024-------------------------------------------------2025==== merge script ====2026# Merge a branch into either the test or release branch20272028pname=$020292030usage()2031{2032 echo "Usage: $pname branch test|release" 1>&22033 exit 12034}20352036if [ ! -f .git/refs/heads/"$1" ]2037then2038 echo "Can't see branch <$1>" 1>&22039 usage2040fi20412042case "$2" in2043test|release)2044 if [ $(git log $2..$1 | wc -c) -eq 0 ]2045 then2046 echo $1 already merged into $2 1>&22047 exit 12048 fi2049 git checkout $2 && git pull . $12050 ;;2051*)2052 usage2053 ;;2054esac2055-------------------------------------------------20562057-------------------------------------------------2058==== status script ====2059# report on status of my ia64 GIT tree20602061gb=$(tput setab 2)2062rb=$(tput setab 1)2063restore=$(tput setab 9)20642065if [ `git rev-list test..release | wc -c` -gt 0 ]2066then2067 echo $rb Warning: commits in release that are not in test $restore2068 git log test..release2069fi20702071for branch in `ls .git/refs/heads`2072do2073 if [ $branch = test -o $branch = release ]2074 then2075 continue2076 fi20772078 echo -n $gb ======= $branch ====== $restore " "2079 status=2080 for ref in test release origin/master2081 do2082 if [ `git rev-list $ref..$branch | wc -c` -gt 0 ]2083 then2084 status=$status${ref:0:1}2085 fi2086 done2087 case $status in2088 trl)2089 echo $rb Need to pull into test $restore2090 ;;2091 rl)2092 echo "In test"2093 ;;2094 l)2095 echo "Waiting for linus"2096 ;;2097 "")2098 echo $rb All done $restore2099 ;;2100 *)2101 echo $rb "<$status>" $restore2102 ;;2103 esac2104 git log origin/master..$branch | git shortlog2105done2106-------------------------------------------------210721082109[[cleaning-up-history]]2110Rewriting history and maintaining patch series2111==============================================21122113Normally commits are only added to a project, never taken away or2114replaced. Git is designed with this assumption, and violating it will2115cause git's merge machinery (for example) to do the wrong thing.21162117However, there is a situation in which it can be useful to violate this2118assumption.21192120[[patch-series]]2121Creating the perfect patch series2122---------------------------------21232124Suppose you are a contributor to a large project, and you want to add a2125complicated feature, and to present it to the other developers in a way2126that makes it easy for them to read your changes, verify that they are2127correct, and understand why you made each change.21282129If you present all of your changes as a single patch (or commit), they2130may find that it is too much to digest all at once.21312132If you present them with the entire history of your work, complete with2133mistakes, corrections, and dead ends, they may be overwhelmed.21342135So the ideal is usually to produce a series of patches such that:21362137 1. Each patch can be applied in order.21382139 2. Each patch includes a single logical change, together with a2140 message explaining the change.21412142 3. No patch introduces a regression: after applying any initial2143 part of the series, the resulting project still compiles and2144 works, and has no bugs that it didn't have before.21452146 4. The complete series produces the same end result as your own2147 (probably much messier!) development process did.21482149We will introduce some tools that can help you do this, explain how to2150use them, and then explain some of the problems that can arise because2151you are rewriting history.21522153[[using-git-rebase]]2154Keeping a patch series up to date using git-rebase2155--------------------------------------------------21562157Suppose that you create a branch "mywork" on a remote-tracking branch2158"origin", and create some commits on top of it:21592160-------------------------------------------------2161$ git checkout -b mywork origin2162$ vi file.txt2163$ git commit2164$ vi otherfile.txt2165$ git commit2166...2167-------------------------------------------------21682169You have performed no merges into mywork, so it is just a simple linear2170sequence of patches on top of "origin":21712172................................................2173 o--o--o <-- origin2174 \2175 o--o--o <-- mywork2176................................................21772178Some more interesting work has been done in the upstream project, and2179"origin" has advanced:21802181................................................2182 o--o--O--o--o--o <-- origin2183 \2184 a--b--c <-- mywork2185................................................21862187At this point, you could use "pull" to merge your changes back in;2188the result would create a new merge commit, like this:21892190................................................2191 o--o--O--o--o--o <-- origin2192 \ \2193 a--b--c--m <-- mywork2194................................................21952196However, if you prefer to keep the history in mywork a simple series of2197commits without any merges, you may instead choose to use2198gitlink:git-rebase[1]:21992200-------------------------------------------------2201$ git checkout mywork2202$ git rebase origin2203-------------------------------------------------22042205This will remove each of your commits from mywork, temporarily saving2206them as patches (in a directory named ".dotest"), update mywork to2207point at the latest version of origin, then apply each of the saved2208patches to the new mywork. The result will look like:220922102211................................................2212 o--o--O--o--o--o <-- origin2213 \2214 a'--b'--c' <-- mywork2215................................................22162217In the process, it may discover conflicts. In that case it will stop2218and allow you to fix the conflicts; after fixing conflicts, use "git2219add" to update the index with those contents, and then, instead of2220running git-commit, just run22212222-------------------------------------------------2223$ git rebase --continue2224-------------------------------------------------22252226and git will continue applying the rest of the patches.22272228At any point you may use the --abort option to abort this process and2229return mywork to the state it had before you started the rebase:22302231-------------------------------------------------2232$ git rebase --abort2233-------------------------------------------------22342235[[modifying-one-commit]]2236Modifying a single commit2237-------------------------22382239We saw in <<fixing-a-mistake-by-editing-history>> that you can replace the2240most recent commit using22412242-------------------------------------------------2243$ git commit --amend2244-------------------------------------------------22452246which will replace the old commit by a new commit incorporating your2247changes, giving you a chance to edit the old commit message first.22482249You can also use a combination of this and gitlink:git-rebase[1] to edit2250commits further back in your history. First, tag the problematic commit with22512252-------------------------------------------------2253$ git tag bad mywork~52254-------------------------------------------------22552256(Either gitk or git-log may be useful for finding the commit.)22572258Then check out that commit, edit it, and rebase the rest of the series2259on top of it (note that we could check out the commit on a temporary2260branch, but instead we're using a <<detached-head,detached head>>):22612262-------------------------------------------------2263$ git checkout bad2264$ # make changes here and update the index2265$ git commit --amend2266$ git rebase --onto HEAD bad mywork2267-------------------------------------------------22682269When you're done, you'll be left with mywork checked out, with the top2270patches on mywork reapplied on top of your modified commit. You can2271then clean up with22722273-------------------------------------------------2274$ git tag -d bad2275-------------------------------------------------22762277Note that the immutable nature of git history means that you haven't really2278"modified" existing commits; instead, you have replaced the old commits with2279new commits having new object names.22802281[[reordering-patch-series]]2282Reordering or selecting from a patch series2283-------------------------------------------22842285Given one existing commit, the gitlink:git-cherry-pick[1] command2286allows you to apply the change introduced by that commit and create a2287new commit that records it. So, for example, if "mywork" points to a2288series of patches on top of "origin", you might do something like:22892290-------------------------------------------------2291$ git checkout -b mywork-new origin2292$ gitk origin..mywork &2293-------------------------------------------------22942295And browse through the list of patches in the mywork branch using gitk,2296applying them (possibly in a different order) to mywork-new using2297cherry-pick, and possibly modifying them as you go using commit2298--amend.22992300Another technique is to use git-format-patch to create a series of2301patches, then reset the state to before the patches:23022303-------------------------------------------------2304$ git format-patch origin2305$ git reset --hard origin2306-------------------------------------------------23072308Then modify, reorder, or eliminate patches as preferred before applying2309them again with gitlink:git-am[1].23102311[[patch-series-tools]]2312Other tools2313-----------23142315There are numerous other tools, such as stgit, which exist for the2316purpose of maintaining a patch series. These are outside of the scope of2317this manual.23182319[[problems-with-rewriting-history]]2320Problems with rewriting history2321-------------------------------23222323The primary problem with rewriting the history of a branch has to do2324with merging. Suppose somebody fetches your branch and merges it into2325their branch, with a result something like this:23262327................................................2328 o--o--O--o--o--o <-- origin2329 \ \2330 t--t--t--m <-- their branch:2331................................................23322333Then suppose you modify the last three commits:23342335................................................2336 o--o--o <-- new head of origin2337 /2338 o--o--O--o--o--o <-- old head of origin2339................................................23402341If we examined all this history together in one repository, it will2342look like:23432344................................................2345 o--o--o <-- new head of origin2346 /2347 o--o--O--o--o--o <-- old head of origin2348 \ \2349 t--t--t--m <-- their branch:2350................................................23512352Git has no way of knowing that the new head is an updated version of2353the old head; it treats this situation exactly the same as it would if2354two developers had independently done the work on the old and new heads2355in parallel. At this point, if someone attempts to merge the new head2356in to their branch, git will attempt to merge together the two (old and2357new) lines of development, instead of trying to replace the old by the2358new. The results are likely to be unexpected.23592360You may still choose to publish branches whose history is rewritten,2361and it may be useful for others to be able to fetch those branches in2362order to examine or test them, but they should not attempt to pull such2363branches into their own work.23642365For true distributed development that supports proper merging,2366published branches should never be rewritten.23672368[[advanced-branch-management]]2369Advanced branch management2370==========================23712372[[fetching-individual-branches]]2373Fetching individual branches2374----------------------------23752376Instead of using gitlink:git-remote[1], you can also choose just2377to update one branch at a time, and to store it locally under an2378arbitrary name:23792380-------------------------------------------------2381$ git fetch origin todo:my-todo-work2382-------------------------------------------------23832384The first argument, "origin", just tells git to fetch from the2385repository you originally cloned from. The second argument tells git2386to fetch the branch named "todo" from the remote repository, and to2387store it locally under the name refs/heads/my-todo-work.23882389You can also fetch branches from other repositories; so23902391-------------------------------------------------2392$ git fetch git://example.com/proj.git master:example-master2393-------------------------------------------------23942395will create a new branch named "example-master" and store in it the2396branch named "master" from the repository at the given URL. If you2397already have a branch named example-master, it will attempt to2398<<fast-forwards,fast-forward>> to the commit given by example.com's2399master branch. In more detail:24002401[[fetch-fast-forwards]]2402git fetch and fast-forwards2403---------------------------24042405In the previous example, when updating an existing branch, "git2406fetch" checks to make sure that the most recent commit on the remote2407branch is a descendant of the most recent commit on your copy of the2408branch before updating your copy of the branch to point at the new2409commit. Git calls this process a <<fast-forwards,fast forward>>.24102411A fast forward looks something like this:24122413................................................2414 o--o--o--o <-- old head of the branch2415 \2416 o--o--o <-- new head of the branch2417................................................241824192420In some cases it is possible that the new head will *not* actually be2421a descendant of the old head. For example, the developer may have2422realized she made a serious mistake, and decided to backtrack,2423resulting in a situation like:24242425................................................2426 o--o--o--o--a--b <-- old head of the branch2427 \2428 o--o--o <-- new head of the branch2429................................................24302431In this case, "git fetch" will fail, and print out a warning.24322433In that case, you can still force git to update to the new head, as2434described in the following section. However, note that in the2435situation above this may mean losing the commits labeled "a" and "b",2436unless you've already created a reference of your own pointing to2437them.24382439[[forcing-fetch]]2440Forcing git fetch to do non-fast-forward updates2441------------------------------------------------24422443If git fetch fails because the new head of a branch is not a2444descendant of the old head, you may force the update with:24452446-------------------------------------------------2447$ git fetch git://example.com/proj.git +master:refs/remotes/example/master2448-------------------------------------------------24492450Note the addition of the "+" sign. Alternatively, you can use the "-f"2451flag to force updates of all the fetched branches, as in:24522453-------------------------------------------------2454$ git fetch -f origin2455-------------------------------------------------24562457Be aware that commits that the old version of example/master pointed at2458may be lost, as we saw in the previous section.24592460[[remote-branch-configuration]]2461Configuring remote branches2462---------------------------24632464We saw above that "origin" is just a shortcut to refer to the2465repository that you originally cloned from. This information is2466stored in git configuration variables, which you can see using2467gitlink:git-config[1]:24682469-------------------------------------------------2470$ git config -l2471core.repositoryformatversion=02472core.filemode=true2473core.logallrefupdates=true2474remote.origin.url=git://git.kernel.org/pub/scm/git/git.git2475remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*2476branch.master.remote=origin2477branch.master.merge=refs/heads/master2478-------------------------------------------------24792480If there are other repositories that you also use frequently, you can2481create similar configuration options to save typing; for example,2482after24832484-------------------------------------------------2485$ git config remote.example.url git://example.com/proj.git2486-------------------------------------------------24872488then the following two commands will do the same thing:24892490-------------------------------------------------2491$ git fetch git://example.com/proj.git master:refs/remotes/example/master2492$ git fetch example master:refs/remotes/example/master2493-------------------------------------------------24942495Even better, if you add one more option:24962497-------------------------------------------------2498$ git config remote.example.fetch master:refs/remotes/example/master2499-------------------------------------------------25002501then the following commands will all do the same thing:25022503-------------------------------------------------2504$ git fetch git://example.com/proj.git master:refs/remotes/example/master2505$ git fetch example master:refs/remotes/example/master2506$ git fetch example2507-------------------------------------------------25082509You can also add a "+" to force the update each time:25102511-------------------------------------------------2512$ git config remote.example.fetch +master:ref/remotes/example/master2513-------------------------------------------------25142515Don't do this unless you're sure you won't mind "git fetch" possibly2516throwing away commits on mybranch.25172518Also note that all of the above configuration can be performed by2519directly editing the file .git/config instead of using2520gitlink:git-config[1].25212522See gitlink:git-config[1] for more details on the configuration2523options mentioned above.252425252526[[git-internals]]2527Git internals2528=============25292530Git depends on two fundamental abstractions: the "object database", and2531the "current directory cache" aka "index".25322533[[the-object-database]]2534The Object Database2535-------------------25362537The object database is literally just a content-addressable collection2538of objects. All objects are named by their content, which is2539approximated by the SHA1 hash of the object itself. Objects may refer2540to other objects (by referencing their SHA1 hash), and so you can2541build up a hierarchy of objects.25422543All objects have a statically determined "type" which is2544determined at object creation time, and which identifies the format of2545the object (i.e. how it is used, and how it can refer to other2546objects). There are currently four different object types: "blob",2547"tree", "commit", and "tag".25482549A <<def_blob_object,"blob" object>> cannot refer to any other object,2550and is, as the name implies, a pure storage object containing some2551user data. It is used to actually store the file data, i.e. a blob2552object is associated with some particular version of some file.25532554A <<def_tree_object,"tree" object>> is an object that ties one or more2555"blob" objects into a directory structure. In addition, a tree object2556can refer to other tree objects, thus creating a directory hierarchy.25572558A <<def_commit_object,"commit" object>> ties such directory hierarchies2559together into a <<def_DAG,directed acyclic graph>> of revisions - each2560"commit" is associated with exactly one tree (the directory hierarchy at2561the time of the commit). In addition, a "commit" refers to one or more2562"parent" commit objects that describe the history of how we arrived at2563that directory hierarchy.25642565As a special case, a commit object with no parents is called the "root"2566commit, and is the point of an initial project commit. Each project2567must have at least one root, and while you can tie several different2568root objects together into one project by creating a commit object which2569has two or more separate roots as its ultimate parents, that's probably2570just going to confuse people. So aim for the notion of "one root object2571per project", even if git itself does not enforce that. 25722573A <<def_tag_object,"tag" object>> symbolically identifies and can be2574used to sign other objects. It contains the identifier and type of2575another object, a symbolic name (of course!) and, optionally, a2576signature.25772578Regardless of object type, all objects share the following2579characteristics: they are all deflated with zlib, and have a header2580that not only specifies their type, but also provides size information2581about the data in the object. It's worth noting that the SHA1 hash2582that is used to name the object is the hash of the original data2583plus this header, so `sha1sum` 'file' does not match the object name2584for 'file'.2585(Historical note: in the dawn of the age of git the hash2586was the sha1 of the 'compressed' object.)25872588As a result, the general consistency of an object can always be tested2589independently of the contents or the type of the object: all objects can2590be validated by verifying that (a) their hashes match the content of the2591file and (b) the object successfully inflates to a stream of bytes that2592forms a sequence of <ascii type without space> + <space> + <ascii decimal2593size> + <byte\0> + <binary object data>. 25942595The structured objects can further have their structure and2596connectivity to other objects verified. This is generally done with2597the `git-fsck` program, which generates a full dependency graph2598of all objects, and verifies their internal consistency (in addition2599to just verifying their superficial consistency through the hash).26002601The object types in some more detail:26022603[[blob-object]]2604Blob Object2605-----------26062607A "blob" object is nothing but a binary blob of data, and doesn't2608refer to anything else. There is no signature or any other2609verification of the data, so while the object is consistent (it 'is'2610indexed by its sha1 hash, so the data itself is certainly correct), it2611has absolutely no other attributes. No name associations, no2612permissions. It is purely a blob of data (i.e. normally "file2613contents").26142615In particular, since the blob is entirely defined by its data, if two2616files in a directory tree (or in multiple different versions of the2617repository) have the same contents, they will share the same blob2618object. The object is totally independent of its location in the2619directory tree, and renaming a file does not change the object that2620file is associated with in any way.26212622A blob is typically created when gitlink:git-update-index[1]2623is run, and its data can be accessed by gitlink:git-cat-file[1].26242625[[tree-object]]2626Tree Object2627-----------26282629The next hierarchical object type is the "tree" object. A tree object2630is a list of mode/name/blob data, sorted by name. Alternatively, the2631mode data may specify a directory mode, in which case instead of2632naming a blob, that name is associated with another TREE object.26332634Like the "blob" object, a tree object is uniquely determined by the2635set contents, and so two separate but identical trees will always2636share the exact same object. This is true at all levels, i.e. it's2637true for a "leaf" tree (which does not refer to any other trees, only2638blobs) as well as for a whole subdirectory.26392640For that reason a "tree" object is just a pure data abstraction: it2641has no history, no signatures, no verification of validity, except2642that since the contents are again protected by the hash itself, we can2643trust that the tree is immutable and its contents never change.26442645So you can trust the contents of a tree to be valid, the same way you2646can trust the contents of a blob, but you don't know where those2647contents 'came' from.26482649Side note on trees: since a "tree" object is a sorted list of2650"filename+content", you can create a diff between two trees without2651actually having to unpack two trees. Just ignore all common parts,2652and your diff will look right. In other words, you can effectively2653(and efficiently) tell the difference between any two random trees by2654O(n) where "n" is the size of the difference, rather than the size of2655the tree.26562657Side note 2 on trees: since the name of a "blob" depends entirely and2658exclusively on its contents (i.e. there are no names or permissions2659involved), you can see trivial renames or permission changes by2660noticing that the blob stayed the same. However, renames with data2661changes need a smarter "diff" implementation.26622663A tree is created with gitlink:git-write-tree[1] and2664its data can be accessed by gitlink:git-ls-tree[1].2665Two trees can be compared with gitlink:git-diff-tree[1].26662667[[commit-object]]2668Commit Object2669-------------26702671The "commit" object is an object that introduces the notion of2672history into the picture. In contrast to the other objects, it2673doesn't just describe the physical state of a tree, it describes how2674we got there, and why.26752676A "commit" is defined by the tree-object that it results in, the2677parent commits (zero, one or more) that led up to that point, and a2678comment on what happened. Again, a commit is not trusted per se:2679the contents are well-defined and "safe" due to the cryptographically2680strong signatures at all levels, but there is no reason to believe2681that the tree is "good" or that the merge information makes sense.2682The parents do not have to actually have any relationship with the2683result, for example.26842685Note on commits: unlike some SCM's, commits do not contain2686rename information or file mode change information. All of that is2687implicit in the trees involved (the result tree, and the result trees2688of the parents), and describing that makes no sense in this idiotic2689file manager.26902691A commit is created with gitlink:git-commit-tree[1] and2692its data can be accessed by gitlink:git-cat-file[1].26932694[[trust]]2695Trust2696-----26972698An aside on the notion of "trust". Trust is really outside the scope2699of "git", but it's worth noting a few things. First off, since2700everything is hashed with SHA1, you 'can' trust that an object is2701intact and has not been messed with by external sources. So the name2702of an object uniquely identifies a known state - just not a state that2703you may want to trust.27042705Furthermore, since the SHA1 signature of a commit refers to the2706SHA1 signatures of the tree it is associated with and the signatures2707of the parent, a single named commit specifies uniquely a whole set2708of history, with full contents. You can't later fake any step of the2709way once you have the name of a commit.27102711So to introduce some real trust in the system, the only thing you need2712to do is to digitally sign just 'one' special note, which includes the2713name of a top-level commit. Your digital signature shows others2714that you trust that commit, and the immutability of the history of2715commits tells others that they can trust the whole history.27162717In other words, you can easily validate a whole archive by just2718sending out a single email that tells the people the name (SHA1 hash)2719of the top commit, and digitally sign that email using something2720like GPG/PGP.27212722To assist in this, git also provides the tag object...27232724[[tag-object]]2725Tag Object2726----------27272728Git provides the "tag" object to simplify creating, managing and2729exchanging symbolic and signed tokens. The "tag" object at its2730simplest simply symbolically identifies another object by containing2731the sha1, type and symbolic name.27322733However it can optionally contain additional signature information2734(which git doesn't care about as long as there's less than 8k of2735it). This can then be verified externally to git.27362737Note that despite the tag features, "git" itself only handles content2738integrity; the trust framework (and signature provision and2739verification) has to come from outside.27402741A tag is created with gitlink:git-mktag[1],2742its data can be accessed by gitlink:git-cat-file[1],2743and the signature can be verified by2744gitlink:git-verify-tag[1].274527462747[[the-index]]2748The "index" aka "Current Directory Cache"2749-----------------------------------------27502751The index is a simple binary file, which contains an efficient2752representation of the contents of a virtual directory. It2753does so by a simple array that associates a set of names, dates,2754permissions and content (aka "blob") objects together. The cache is2755always kept ordered by name, and names are unique (with a few very2756specific rules) at any point in time, but the cache has no long-term2757meaning, and can be partially updated at any time.27582759In particular, the index certainly does not need to be consistent with2760the current directory contents (in fact, most operations will depend on2761different ways to make the index 'not' be consistent with the directory2762hierarchy), but it has three very important attributes:27632764'(a) it can re-generate the full state it caches (not just the2765directory structure: it contains pointers to the "blob" objects so2766that it can regenerate the data too)'27672768As a special case, there is a clear and unambiguous one-way mapping2769from a current directory cache to a "tree object", which can be2770efficiently created from just the current directory cache without2771actually looking at any other data. So a directory cache at any one2772time uniquely specifies one and only one "tree" object (but has2773additional data to make it easy to match up that tree object with what2774has happened in the directory)27752776'(b) it has efficient methods for finding inconsistencies between that2777cached state ("tree object waiting to be instantiated") and the2778current state.'27792780'(c) it can additionally efficiently represent information about merge2781conflicts between different tree objects, allowing each pathname to be2782associated with sufficient information about the trees involved that2783you can create a three-way merge between them.'27842785Those are the ONLY three things that the directory cache does. It's a2786cache, and the normal operation is to re-generate it completely from a2787known tree object, or update/compare it with a live tree that is being2788developed. If you blow the directory cache away entirely, you generally2789haven't lost any information as long as you have the name of the tree2790that it described. 27912792At the same time, the index is at the same time also the2793staging area for creating new trees, and creating a new tree always2794involves a controlled modification of the index file. In particular,2795the index file can have the representation of an intermediate tree that2796has not yet been instantiated. So the index can be thought of as a2797write-back cache, which can contain dirty information that has not yet2798been written back to the backing store.2799280028012802[[the-workflow]]2803The Workflow2804------------28052806Generally, all "git" operations work on the index file. Some operations2807work *purely* on the index file (showing the current state of the2808index), but most operations move data to and from the index file. Either2809from the database or from the working directory. Thus there are four2810main combinations: 28112812[[working-directory-to-index]]2813working directory -> index2814~~~~~~~~~~~~~~~~~~~~~~~~~~28152816You update the index with information from the working directory with2817the gitlink:git-update-index[1] command. You2818generally update the index information by just specifying the filename2819you want to update, like so:28202821-------------------------------------------------2822$ git-update-index filename2823-------------------------------------------------28242825but to avoid common mistakes with filename globbing etc, the command2826will not normally add totally new entries or remove old entries,2827i.e. it will normally just update existing cache entries.28282829To tell git that yes, you really do realize that certain files no2830longer exist, or that new files should be added, you2831should use the `--remove` and `--add` flags respectively.28322833NOTE! A `--remove` flag does 'not' mean that subsequent filenames will2834necessarily be removed: if the files still exist in your directory2835structure, the index will be updated with their new status, not2836removed. The only thing `--remove` means is that update-cache will be2837considering a removed file to be a valid thing, and if the file really2838does not exist any more, it will update the index accordingly.28392840As a special case, you can also do `git-update-index --refresh`, which2841will refresh the "stat" information of each index to match the current2842stat information. It will 'not' update the object status itself, and2843it will only update the fields that are used to quickly test whether2844an object still matches its old backing store object.28452846[[index-to-object-database]]2847index -> object database2848~~~~~~~~~~~~~~~~~~~~~~~~28492850You write your current index file to a "tree" object with the program28512852-------------------------------------------------2853$ git-write-tree2854-------------------------------------------------28552856that doesn't come with any options - it will just write out the2857current index into the set of tree objects that describe that state,2858and it will return the name of the resulting top-level tree. You can2859use that tree to re-generate the index at any time by going in the2860other direction:28612862[[object-database-to-index]]2863object database -> index2864~~~~~~~~~~~~~~~~~~~~~~~~28652866You read a "tree" file from the object database, and use that to2867populate (and overwrite - don't do this if your index contains any2868unsaved state that you might want to restore later!) your current2869index. Normal operation is just28702871-------------------------------------------------2872$ git-read-tree <sha1 of tree>2873-------------------------------------------------28742875and your index file will now be equivalent to the tree that you saved2876earlier. However, that is only your 'index' file: your working2877directory contents have not been modified.28782879[[index-to-working-directory]]2880index -> working directory2881~~~~~~~~~~~~~~~~~~~~~~~~~~28822883You update your working directory from the index by "checking out"2884files. This is not a very common operation, since normally you'd just2885keep your files updated, and rather than write to your working2886directory, you'd tell the index files about the changes in your2887working directory (i.e. `git-update-index`).28882889However, if you decide to jump to a new version, or check out somebody2890else's version, or just restore a previous tree, you'd populate your2891index file with read-tree, and then you need to check out the result2892with28932894-------------------------------------------------2895$ git-checkout-index filename2896-------------------------------------------------28972898or, if you want to check out all of the index, use `-a`.28992900NOTE! git-checkout-index normally refuses to overwrite old files, so2901if you have an old version of the tree already checked out, you will2902need to use the "-f" flag ('before' the "-a" flag or the filename) to2903'force' the checkout.290429052906Finally, there are a few odds and ends which are not purely moving2907from one representation to the other:29082909[[tying-it-all-together]]2910Tying it all together2911~~~~~~~~~~~~~~~~~~~~~29122913To commit a tree you have instantiated with "git-write-tree", you'd2914create a "commit" object that refers to that tree and the history2915behind it - most notably the "parent" commits that preceded it in2916history.29172918Normally a "commit" has one parent: the previous state of the tree2919before a certain change was made. However, sometimes it can have two2920or more parent commits, in which case we call it a "merge", due to the2921fact that such a commit brings together ("merges") two or more2922previous states represented by other commits.29232924In other words, while a "tree" represents a particular directory state2925of a working directory, a "commit" represents that state in "time",2926and explains how we got there.29272928You create a commit object by giving it the tree that describes the2929state at the time of the commit, and a list of parents:29302931-------------------------------------------------2932$ git-commit-tree <tree> -p <parent> [-p <parent2> ..]2933-------------------------------------------------29342935and then giving the reason for the commit on stdin (either through2936redirection from a pipe or file, or by just typing it at the tty).29372938git-commit-tree will return the name of the object that represents2939that commit, and you should save it away for later use. Normally,2940you'd commit a new `HEAD` state, and while git doesn't care where you2941save the note about that state, in practice we tend to just write the2942result to the file pointed at by `.git/HEAD`, so that we can always see2943what the last committed state was.29442945Here is an ASCII art by Jon Loeliger that illustrates how2946various pieces fit together.29472948------------29492950 commit-tree2951 commit obj2952 +----+2953 | |2954 | |2955 V V2956 +-----------+2957 | Object DB |2958 | Backing |2959 | Store |2960 +-----------+2961 ^2962 write-tree | |2963 tree obj | |2964 | | read-tree2965 | | tree obj2966 V2967 +-----------+2968 | Index |2969 | "cache" |2970 +-----------+2971 update-index ^2972 blob obj | |2973 | |2974 checkout-index -u | | checkout-index2975 stat | | blob obj2976 V2977 +-----------+2978 | Working |2979 | Directory |2980 +-----------+29812982------------298329842985[[examining-the-data]]2986Examining the data2987------------------29882989You can examine the data represented in the object database and the2990index with various helper tools. For every object, you can use2991gitlink:git-cat-file[1] to examine details about the2992object:29932994-------------------------------------------------2995$ git-cat-file -t <objectname>2996-------------------------------------------------29972998shows the type of the object, and once you have the type (which is2999usually implicit in where you find the object), you can use30003001-------------------------------------------------3002$ git-cat-file blob|tree|commit|tag <objectname>3003-------------------------------------------------30043005to show its contents. NOTE! Trees have binary content, and as a result3006there is a special helper for showing that content, called3007`git-ls-tree`, which turns the binary content into a more easily3008readable form.30093010It's especially instructive to look at "commit" objects, since those3011tend to be small and fairly self-explanatory. In particular, if you3012follow the convention of having the top commit name in `.git/HEAD`,3013you can do30143015-------------------------------------------------3016$ git-cat-file commit HEAD3017-------------------------------------------------30183019to see what the top commit was.30203021[[merging-multiple-trees]]3022Merging multiple trees3023----------------------30243025Git helps you do a three-way merge, which you can expand to n-way by3026repeating the merge procedure arbitrary times until you finally3027"commit" the state. The normal situation is that you'd only do one3028three-way merge (two parents), and commit it, but if you like to, you3029can do multiple parents in one go.30303031To do a three-way merge, you need the two sets of "commit" objects3032that you want to merge, use those to find the closest common parent (a3033third "commit" object), and then use those commit objects to find the3034state of the directory ("tree" object) at these points.30353036To get the "base" for the merge, you first look up the common parent3037of two commits with30383039-------------------------------------------------3040$ git-merge-base <commit1> <commit2>3041-------------------------------------------------30423043which will return you the commit they are both based on. You should3044now look up the "tree" objects of those commits, which you can easily3045do with (for example)30463047-------------------------------------------------3048$ git-cat-file commit <commitname> | head -13049-------------------------------------------------30503051since the tree object information is always the first line in a commit3052object.30533054Once you know the three trees you are going to merge (the one "original"3055tree, aka the common tree, and the two "result" trees, aka the branches3056you want to merge), you do a "merge" read into the index. This will3057complain if it has to throw away your old index contents, so you should3058make sure that you've committed those - in fact you would normally3059always do a merge against your last commit (which should thus match what3060you have in your current index anyway).30613062To do the merge, do30633064-------------------------------------------------3065$ git-read-tree -m -u <origtree> <yourtree> <targettree>3066-------------------------------------------------30673068which will do all trivial merge operations for you directly in the3069index file, and you can just write the result out with3070`git-write-tree`.307130723073[[merging-multiple-trees-2]]3074Merging multiple trees, continued3075---------------------------------30763077Sadly, many merges aren't trivial. If there are files that have3078been added.moved or removed, or if both branches have modified the3079same file, you will be left with an index tree that contains "merge3080entries" in it. Such an index tree can 'NOT' be written out to a tree3081object, and you will have to resolve any such merge clashes using3082other tools before you can write out the result.30833084You can examine such index state with `git-ls-files --unmerged`3085command. An example:30863087------------------------------------------------3088$ git-read-tree -m $orig HEAD $target3089$ git-ls-files --unmerged3090100644 263414f423d0e4d70dae8fe53fa34614ff3e2860 1 hello.c3091100644 06fa6a24256dc7e560efa5687fa84b51f0263c3a 2 hello.c3092100644 cc44c73eb783565da5831b4d820c962954019b69 3 hello.c3093------------------------------------------------30943095Each line of the `git-ls-files --unmerged` output begins with3096the blob mode bits, blob SHA1, 'stage number', and the3097filename. The 'stage number' is git's way to say which tree it3098came from: stage 1 corresponds to `$orig` tree, stage 2 `HEAD`3099tree, and stage3 `$target` tree.31003101Earlier we said that trivial merges are done inside3102`git-read-tree -m`. For example, if the file did not change3103from `$orig` to `HEAD` nor `$target`, or if the file changed3104from `$orig` to `HEAD` and `$orig` to `$target` the same way,3105obviously the final outcome is what is in `HEAD`. What the3106above example shows is that file `hello.c` was changed from3107`$orig` to `HEAD` and `$orig` to `$target` in a different way.3108You could resolve this by running your favorite 3-way merge3109program, e.g. `diff3`, `merge`, or git's own merge-file, on3110the blob objects from these three stages yourself, like this:31113112------------------------------------------------3113$ git-cat-file blob 263414f... >hello.c~13114$ git-cat-file blob 06fa6a2... >hello.c~23115$ git-cat-file blob cc44c73... >hello.c~33116$ git merge-file hello.c~2 hello.c~1 hello.c~33117------------------------------------------------31183119This would leave the merge result in `hello.c~2` file, along3120with conflict markers if there are conflicts. After verifying3121the merge result makes sense, you can tell git what the final3122merge result for this file is by:31233124-------------------------------------------------3125$ mv -f hello.c~2 hello.c3126$ git-update-index hello.c3127-------------------------------------------------31283129When a path is in unmerged state, running `git-update-index` for3130that path tells git to mark the path resolved.31313132The above is the description of a git merge at the lowest level,3133to help you understand what conceptually happens under the hood.3134In practice, nobody, not even git itself, uses three `git-cat-file`3135for this. There is `git-merge-index` program that extracts the3136stages to temporary files and calls a "merge" script on it:31373138-------------------------------------------------3139$ git-merge-index git-merge-one-file hello.c3140-------------------------------------------------31413142and that is what higher level `git merge -s resolve` is implemented with.31433144[[pack-files]]3145How git stores objects efficiently: pack files3146----------------------------------------------31473148We've seen how git stores each object in a file named after the3149object's SHA1 hash.31503151Unfortunately this system becomes inefficient once a project has a3152lot of objects. Try this on an old project:31533154------------------------------------------------3155$ git count-objects31566930 objects, 47620 kilobytes3157------------------------------------------------31583159The first number is the number of objects which are kept in3160individual files. The second is the amount of space taken up by3161those "loose" objects.31623163You can save space and make git faster by moving these loose objects in3164to a "pack file", which stores a group of objects in an efficient3165compressed format; the details of how pack files are formatted can be3166found in link:technical/pack-format.txt[technical/pack-format.txt].31673168To put the loose objects into a pack, just run git repack:31693170------------------------------------------------3171$ git repack3172Generating pack...3173Done counting 6020 objects.3174Deltifying 6020 objects.3175 100% (6020/6020) done3176Writing 6020 objects.3177 100% (6020/6020) done3178Total 6020, written 6020 (delta 4070), reused 0 (delta 0)3179Pack pack-3e54ad29d5b2e05838c75df582c65257b8d08e1c created.3180------------------------------------------------31813182You can then run31833184------------------------------------------------3185$ git prune3186------------------------------------------------31873188to remove any of the "loose" objects that are now contained in the3189pack. This will also remove any unreferenced objects (which may be3190created when, for example, you use "git reset" to remove a commit).3191You can verify that the loose objects are gone by looking at the3192.git/objects directory or by running31933194------------------------------------------------3195$ git count-objects31960 objects, 0 kilobytes3197------------------------------------------------31983199Although the object files are gone, any commands that refer to those3200objects will work exactly as they did before.32013202The gitlink:git-gc[1] command performs packing, pruning, and more for3203you, so is normally the only high-level command you need.32043205[[dangling-objects]]3206Dangling objects3207----------------32083209The gitlink:git-fsck[1] command will sometimes complain about dangling3210objects. They are not a problem.32113212The most common cause of dangling objects is that you've rebased a3213branch, or you have pulled from somebody else who rebased a branch--see3214<<cleaning-up-history>>. In that case, the old head of the original3215branch still exists, as does everything it pointed to. The branch3216pointer itself just doesn't, since you replaced it with another one.32173218There are also other situations that cause dangling objects. For3219example, a "dangling blob" may arise because you did a "git add" of a3220file, but then, before you actually committed it and made it part of the3221bigger picture, you changed something else in that file and committed3222that *updated* thing - the old state that you added originally ends up3223not being pointed to by any commit or tree, so it's now a dangling blob3224object.32253226Similarly, when the "recursive" merge strategy runs, and finds that3227there are criss-cross merges and thus more than one merge base (which is3228fairly unusual, but it does happen), it will generate one temporary3229midway tree (or possibly even more, if you had lots of criss-crossing3230merges and more than two merge bases) as a temporary internal merge3231base, and again, those are real objects, but the end result will not end3232up pointing to them, so they end up "dangling" in your repository.32333234Generally, dangling objects aren't anything to worry about. They can3235even be very useful: if you screw something up, the dangling objects can3236be how you recover your old tree (say, you did a rebase, and realized3237that you really didn't want to - you can look at what dangling objects3238you have, and decide to reset your head to some old dangling state).32393240For commits, you can just use:32413242------------------------------------------------3243$ gitk <dangling-commit-sha-goes-here> --not --all3244------------------------------------------------32453246This asks for all the history reachable from the given commit but not3247from any branch, tag, or other reference. If you decide it's something3248you want, you can always create a new reference to it, e.g.,32493250------------------------------------------------3251$ git branch recovered-branch <dangling-commit-sha-goes-here>3252------------------------------------------------32533254For blobs and trees, you can't do the same, but you can still examine3255them. You can just do32563257------------------------------------------------3258$ git show <dangling-blob/tree-sha-goes-here>3259------------------------------------------------32603261to show what the contents of the blob were (or, for a tree, basically3262what the "ls" for that directory was), and that may give you some idea3263of what the operation was that left that dangling object.32643265Usually, dangling blobs and trees aren't very interesting. They're3266almost always the result of either being a half-way mergebase (the blob3267will often even have the conflict markers from a merge in it, if you3268have had conflicting merges that you fixed up by hand), or simply3269because you interrupted a "git fetch" with ^C or something like that,3270leaving _some_ of the new objects in the object database, but just3271dangling and useless.32723273Anyway, once you are sure that you're not interested in any dangling 3274state, you can just prune all unreachable objects:32753276------------------------------------------------3277$ git prune3278------------------------------------------------32793280and they'll be gone. But you should only run "git prune" on a quiescent3281repository - it's kind of like doing a filesystem fsck recovery: you3282don't want to do that while the filesystem is mounted.32833284(The same is true of "git-fsck" itself, btw - but since 3285git-fsck never actually *changes* the repository, it just reports 3286on what it found, git-fsck itself is never "dangerous" to run. 3287Running it while somebody is actually changing the repository can cause 3288confusing and scary messages, but it won't actually do anything bad. In 3289contrast, running "git prune" while somebody is actively changing the 3290repository is a *BAD* idea).32913292[[birdview-on-the-source-code]]3293A birds-eye view of Git's source code3294-------------------------------------32953296It is not always easy for new developers to find their way through Git's3297source code. This section gives you a little guidance to show where to3298start.32993300A good place to start is with the contents of the initial commit, with:33013302----------------------------------------------------3303$ git checkout e83c51633304----------------------------------------------------33053306The initial revision lays the foundation for almost everything git has3307today, but is small enough to read in one sitting.33083309Note that terminology has changed since that revision. For example, the3310README in that revision uses the word "changeset" to describe what we3311now call a <<def_commit_object,commit>>.33123313Also, we do not call it "cache" any more, but "index", however, the3314file is still called `cache.h`. Remark: Not much reason to change it now,3315especially since there is no good single name for it anyway, because it is3316basically _the_ header file which is included by _all_ of Git's C sources.33173318If you grasp the ideas in that initial commit, you should check out a3319more recent version and skim `cache.h`, `object.h` and `commit.h`.33203321In the early days, Git (in the tradition of UNIX) was a bunch of programs3322which were extremely simple, and which you used in scripts, piping the3323output of one into another. This turned out to be good for initial3324development, since it was easier to test new things. However, recently3325many of these parts have become builtins, and some of the core has been3326"libified", i.e. put into libgit.a for performance, portability reasons,3327and to avoid code duplication.33283329By now, you know what the index is (and find the corresponding data3330structures in `cache.h`), and that there are just a couple of object types3331(blobs, trees, commits and tags) which inherit their common structure from3332`struct object`, which is their first member (and thus, you can cast e.g.3333`(struct object *)commit` to achieve the _same_ as `&commit->object`, i.e.3334get at the object name and flags).33353336Now is a good point to take a break to let this information sink in.33373338Next step: get familiar with the object naming. Read <<naming-commits>>.3339There are quite a few ways to name an object (and not only revisions!).3340All of these are handled in `sha1_name.c`. Just have a quick look at3341the function `get_sha1()`. A lot of the special handling is done by3342functions like `get_sha1_basic()` or the likes.33433344This is just to get you into the groove for the most libified part of Git:3345the revision walker.33463347Basically, the initial version of `git log` was a shell script:33483349----------------------------------------------------------------3350$ git-rev-list --pretty $(git-rev-parse --default HEAD "$@") | \3351 LESS=-S ${PAGER:-less}3352----------------------------------------------------------------33533354What does this mean?33553356`git-rev-list` is the original version of the revision walker, which3357_always_ printed a list of revisions to stdout. It is still functional,3358and needs to, since most new Git programs start out as scripts using3359`git-rev-list`.33603361`git-rev-parse` is not as important any more; it was only used to filter out3362options that were relevant for the different plumbing commands that were3363called by the script.33643365Most of what `git-rev-list` did is contained in `revision.c` and3366`revision.h`. It wraps the options in a struct named `rev_info`, which3367controls how and what revisions are walked, and more.33683369The original job of `git-rev-parse` is now taken by the function3370`setup_revisions()`, which parses the revisions and the common command line3371options for the revision walker. This information is stored in the struct3372`rev_info` for later consumption. You can do your own command line option3373parsing after calling `setup_revisions()`. After that, you have to call3374`prepare_revision_walk()` for initialization, and then you can get the3375commits one by one with the function `get_revision()`.33763377If you are interested in more details of the revision walking process,3378just have a look at the first implementation of `cmd_log()`; call3379`git-show v1.3.0~155^2~4` and scroll down to that function (note that you3380no longer need to call `setup_pager()` directly).33813382Nowadays, `git log` is a builtin, which means that it is _contained_ in the3383command `git`. The source side of a builtin is33843385- a function called `cmd_<bla>`, typically defined in `builtin-<bla>.c`,3386 and declared in `builtin.h`,33873388- an entry in the `commands[]` array in `git.c`, and33893390- an entry in `BUILTIN_OBJECTS` in the `Makefile`.33913392Sometimes, more than one builtin is contained in one source file. For3393example, `cmd_whatchanged()` and `cmd_log()` both reside in `builtin-log.c`,3394since they share quite a bit of code. In that case, the commands which are3395_not_ named like the `.c` file in which they live have to be listed in3396`BUILT_INS` in the `Makefile`.33973398`git log` looks more complicated in C than it does in the original script,3399but that allows for a much greater flexibility and performance.34003401Here again it is a good point to take a pause.34023403Lesson three is: study the code. Really, it is the best way to learn about3404the organization of Git (after you know the basic concepts).34053406So, think about something which you are interested in, say, "how can I3407access a blob just knowing the object name of it?". The first step is to3408find a Git command with which you can do it. In this example, it is either3409`git show` or `git cat-file`.34103411For the sake of clarity, let's stay with `git cat-file`, because it34123413- is plumbing, and34143415- was around even in the initial commit (it literally went only through3416 some 20 revisions as `cat-file.c`, was renamed to `builtin-cat-file.c`3417 when made a builtin, and then saw less than 10 versions).34183419So, look into `builtin-cat-file.c`, search for `cmd_cat_file()` and look what3420it does.34213422------------------------------------------------------------------3423 git_config(git_default_config);3424 if (argc != 3)3425 usage("git-cat-file [-t|-s|-e|-p|<type>] <sha1>");3426 if (get_sha1(argv[2], sha1))3427 die("Not a valid object name %s", argv[2]);3428------------------------------------------------------------------34293430Let's skip over the obvious details; the only really interesting part3431here is the call to `get_sha1()`. It tries to interpret `argv[2]` as an3432object name, and if it refers to an object which is present in the current3433repository, it writes the resulting SHA-1 into the variable `sha1`.34343435Two things are interesting here:34363437- `get_sha1()` returns 0 on _success_. This might surprise some new3438 Git hackers, but there is a long tradition in UNIX to return different3439 negative numbers in case of different errors -- and 0 on success.34403441- the variable `sha1` in the function signature of `get_sha1()` is `unsigned3442 char \*`, but is actually expected to be a pointer to `unsigned3443 char[20]`. This variable will contain the 160-bit SHA-1 of the given3444 commit. Note that whenever a SHA-1 is passed as `unsigned char \*`, it3445 is the binary representation, as opposed to the ASCII representation in3446 hex characters, which is passed as `char *`.34473448You will see both of these things throughout the code.34493450Now, for the meat:34513452-----------------------------------------------------------------------------3453 case 0:3454 buf = read_object_with_reference(sha1, argv[1], &size, NULL);3455-----------------------------------------------------------------------------34563457This is how you read a blob (actually, not only a blob, but any type of3458object). To know how the function `read_object_with_reference()` actually3459works, find the source code for it (something like `git grep3460read_object_with | grep ":[a-z]"` in the git repository), and read3461the source.34623463To find out how the result can be used, just read on in `cmd_cat_file()`:34643465-----------------------------------3466 write_or_die(1, buf, size);3467-----------------------------------34683469Sometimes, you do not know where to look for a feature. In many such cases,3470it helps to search through the output of `git log`, and then `git show` the3471corresponding commit.34723473Example: If you know that there was some test case for `git bundle`, but3474do not remember where it was (yes, you _could_ `git grep bundle t/`, but that3475does not illustrate the point!):34763477------------------------3478$ git log --no-merges t/3479------------------------34803481In the pager (`less`), just search for "bundle", go a few lines back,3482and see that it is in commit 18449ab0... Now just copy this object name,3483and paste it into the command line34843485-------------------3486$ git show 18449ab03487-------------------34883489Voila.34903491Another example: Find out what to do in order to make some script a3492builtin:34933494-------------------------------------------------3495$ git log --no-merges --diff-filter=A builtin-*.c3496-------------------------------------------------34973498You see, Git is actually the best tool to find out about the source of Git3499itself!35003501[[glossary]]3502include::glossary.txt[]35033504[[git-quick-start]]3505Appendix A: Git Quick Start3506===========================35073508This is a quick summary of the major commands; the following chapters3509will explain how these work in more detail.35103511[[quick-creating-a-new-repository]]3512Creating a new repository3513-------------------------35143515From a tarball:35163517-----------------------------------------------3518$ tar xzf project.tar.gz3519$ cd project3520$ git init3521Initialized empty Git repository in .git/3522$ git add .3523$ git commit3524-----------------------------------------------35253526From a remote repository:35273528-----------------------------------------------3529$ git clone git://example.com/pub/project.git3530$ cd project3531-----------------------------------------------35323533[[managing-branches]]3534Managing branches3535-----------------35363537-----------------------------------------------3538$ git branch # list all local branches in this repo3539$ git checkout test # switch working directory to branch "test"3540$ git branch new # create branch "new" starting at current HEAD3541$ git branch -d new # delete branch "new"3542-----------------------------------------------35433544Instead of basing new branch on current HEAD (the default), use:35453546-----------------------------------------------3547$ git branch new test # branch named "test"3548$ git branch new v2.6.15 # tag named v2.6.153549$ git branch new HEAD^ # commit before the most recent3550$ git branch new HEAD^^ # commit before that3551$ git branch new test~10 # ten commits before tip of branch "test"3552-----------------------------------------------35533554Create and switch to a new branch at the same time:35553556-----------------------------------------------3557$ git checkout -b new v2.6.153558-----------------------------------------------35593560Update and examine branches from the repository you cloned from:35613562-----------------------------------------------3563$ git fetch # update3564$ git branch -r # list3565 origin/master3566 origin/next3567 ...3568$ git checkout -b masterwork origin/master3569-----------------------------------------------35703571Fetch a branch from a different repository, and give it a new3572name in your repository:35733574-----------------------------------------------3575$ git fetch git://example.com/project.git theirbranch:mybranch3576$ git fetch git://example.com/project.git v2.6.15:mybranch3577-----------------------------------------------35783579Keep a list of repositories you work with regularly:35803581-----------------------------------------------3582$ git remote add example git://example.com/project.git3583$ git remote # list remote repositories3584example3585origin3586$ git remote show example # get details3587* remote example3588 URL: git://example.com/project.git3589 Tracked remote branches3590 master next ...3591$ git fetch example # update branches from example3592$ git branch -r # list all remote branches3593-----------------------------------------------359435953596[[exploring-history]]3597Exploring history3598-----------------35993600-----------------------------------------------3601$ gitk # visualize and browse history3602$ git log # list all commits3603$ git log src/ # ...modifying src/3604$ git log v2.6.15..v2.6.16 # ...in v2.6.16, not in v2.6.153605$ git log master..test # ...in branch test, not in branch master3606$ git log test..master # ...in branch master, but not in test3607$ git log test...master # ...in one branch, not in both3608$ git log -S'foo()' # ...where difference contain "foo()"3609$ git log --since="2 weeks ago"3610$ git log -p # show patches as well3611$ git show # most recent commit3612$ git diff v2.6.15..v2.6.16 # diff between two tagged versions3613$ git diff v2.6.15..HEAD # diff with current head3614$ git grep "foo()" # search working directory for "foo()"3615$ git grep v2.6.15 "foo()" # search old tree for "foo()"3616$ git show v2.6.15:a.txt # look at old version of a.txt3617-----------------------------------------------36183619Search for regressions:36203621-----------------------------------------------3622$ git bisect start3623$ git bisect bad # current version is bad3624$ git bisect good v2.6.13-rc2 # last known good revision3625Bisecting: 675 revisions left to test after this3626 # test here, then:3627$ git bisect good # if this revision is good, or3628$ git bisect bad # if this revision is bad.3629 # repeat until done.3630-----------------------------------------------36313632[[making-changes]]3633Making changes3634--------------36353636Make sure git knows who to blame:36373638------------------------------------------------3639$ cat >>~/.gitconfig <<\EOF3640[user]3641 name = Your Name Comes Here3642 email = you@yourdomain.example.com3643EOF3644------------------------------------------------36453646Select file contents to include in the next commit, then make the3647commit:36483649-----------------------------------------------3650$ git add a.txt # updated file3651$ git add b.txt # new file3652$ git rm c.txt # old file3653$ git commit3654-----------------------------------------------36553656Or, prepare and create the commit in one step:36573658-----------------------------------------------3659$ git commit d.txt # use latest content only of d.txt3660$ git commit -a # use latest content of all tracked files3661-----------------------------------------------36623663[[merging]]3664Merging3665-------36663667-----------------------------------------------3668$ git merge test # merge branch "test" into the current branch3669$ git pull git://example.com/project.git master3670 # fetch and merge in remote branch3671$ git pull . test # equivalent to git merge test3672-----------------------------------------------36733674[[sharing-your-changes]]3675Sharing your changes3676--------------------36773678Importing or exporting patches:36793680-----------------------------------------------3681$ git format-patch origin..HEAD # format a patch for each commit3682 # in HEAD but not in origin3683$ git am mbox # import patches from the mailbox "mbox"3684-----------------------------------------------36853686Fetch a branch in a different git repository, then merge into the3687current branch:36883689-----------------------------------------------3690$ git pull git://example.com/project.git theirbranch3691-----------------------------------------------36923693Store the fetched branch into a local branch before merging into the3694current branch:36953696-----------------------------------------------3697$ git pull git://example.com/project.git theirbranch:mybranch3698-----------------------------------------------36993700After creating commits on a local branch, update the remote3701branch with your commits:37023703-----------------------------------------------3704$ git push ssh://example.com/project.git mybranch:theirbranch3705-----------------------------------------------37063707When remote and local branch are both named "test":37083709-----------------------------------------------3710$ git push ssh://example.com/project.git test3711-----------------------------------------------37123713Shortcut version for a frequently used remote repository:37143715-----------------------------------------------3716$ git remote add example ssh://example.com/project.git3717$ git push example test3718-----------------------------------------------37193720[[repository-maintenance]]3721Repository maintenance3722----------------------37233724Check for corruption:37253726-----------------------------------------------3727$ git fsck3728-----------------------------------------------37293730Recompress, remove unused cruft:37313732-----------------------------------------------3733$ git gc3734-----------------------------------------------373537363737[[todo]]3738Appendix B: Notes and todo list for this manual3739===============================================37403741This is a work in progress.37423743The basic requirements:3744 - It must be readable in order, from beginning to end, by3745 someone intelligent with a basic grasp of the unix3746 commandline, but without any special knowledge of git. If3747 necessary, any other prerequisites should be specifically3748 mentioned as they arise.3749 - Whenever possible, section headings should clearly describe3750 the task they explain how to do, in language that requires3751 no more knowledge than necessary: for example, "importing3752 patches into a project" rather than "the git-am command"37533754Think about how to create a clear chapter dependency graph that will3755allow people to get to important topics without necessarily reading3756everything in between.37573758Say something about .gitignore.37593760Scan Documentation/ for other stuff left out; in particular:3761 howto's3762 some of technical/?3763 hooks3764 list of commands in gitlink:git[1]37653766Scan email archives for other stuff left out37673768Scan man pages to see if any assume more background than this manual3769provides.37703771Simplify beginning by suggesting disconnected head instead of3772temporary branch creation?37733774Add more good examples. Entire sections of just cookbook examples3775might be a good idea; maybe make an "advanced examples" section a3776standard end-of-chapter section?37773778Include cross-references to the glossary, where appropriate.37793780Document shallow clones? See draft 1.5.0 release notes for some3781documentation.37823783Add a section on working with other version control systems, including3784CVS, Subversion, and just imports of series of release tarballs.37853786More details on gitweb?37873788Write a chapter on using plumbing and writing scripts.