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[[checking-for-equal-branches]] 694Check whether two branches point at the same history 695~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 696 697Suppose you want to check whether two branches point at the same point 698in history. 699 700------------------------------------------------- 701$ git diff origin..master 702------------------------------------------------- 703 704will tell you whether the contents of the project are the same at the 705two branches; in theory, however, it's possible that the same project 706contents could have been arrived at by two different historical 707routes. You could compare the object names: 708 709------------------------------------------------- 710$ git rev-list origin 711e05db0fd4f31dde7005f075a84f96b360d05984b 712$ git rev-list master 713e05db0fd4f31dde7005f075a84f96b360d05984b 714------------------------------------------------- 715 716Or you could recall that the ... operator selects all commits 717contained reachable from either one reference or the other but not 718both: so 719 720------------------------------------------------- 721$ git log origin...master 722------------------------------------------------- 723 724will return no commits when the two branches are equal. 725 726[[finding-tagged-descendants]] 727Find first tagged version including a given fix 728~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 729 730Suppose you know that the commit e05db0fd fixed a certain problem. 731You'd like to find the earliest tagged release that contains that 732fix. 733 734Of course, there may be more than one answer--if the history branched 735after commit e05db0fd, then there could be multiple "earliest" tagged 736releases. 737 738You could just visually inspect the commits since e05db0fd: 739 740------------------------------------------------- 741$ gitk e05db0fd.. 742------------------------------------------------- 743 744Or you can use gitlink:git-name-rev[1], which will give the commit a 745name based on any tag it finds pointing to one of the commit's 746descendants: 747 748------------------------------------------------- 749$ git name-rev --tags e05db0fd 750e05db0fd tags/v1.5.0-rc1^0~23 751------------------------------------------------- 752 753The gitlink:git-describe[1] command does the opposite, naming the 754revision using a tag on which the given commit is based: 755 756------------------------------------------------- 757$ git describe e05db0fd 758v1.5.0-rc0-260-ge05db0f 759------------------------------------------------- 760 761but that may sometimes help you guess which tags might come after the 762given commit. 763 764If you just want to verify whether a given tagged version contains a 765given commit, you could use gitlink:git-merge-base[1]: 766 767------------------------------------------------- 768$ git merge-base e05db0fd v1.5.0-rc1 769e05db0fd4f31dde7005f075a84f96b360d05984b 770------------------------------------------------- 771 772The merge-base command finds a common ancestor of the given commits, 773and always returns one or the other in the case where one is a 774descendant of the other; so the above output shows that e05db0fd 775actually is an ancestor of v1.5.0-rc1. 776 777Alternatively, note that 778 779------------------------------------------------- 780$ git log v1.5.0-rc1..e05db0fd 781------------------------------------------------- 782 783will produce empty output if and only if v1.5.0-rc1 includes e05db0fd, 784because it outputs only commits that are not reachable from v1.5.0-rc1. 785 786As yet another alternative, the gitlink:git-show-branch[1] command lists 787the commits reachable from its arguments with a display on the left-hand 788side that indicates which arguments that commit is reachable from. So, 789you can run something like 790 791------------------------------------------------- 792$ git show-branch e05db0fd v1.5.0-rc0 v1.5.0-rc1 v1.5.0-rc2 793! [e05db0fd] Fix warnings in sha1_file.c - use C99 printf format if 794available 795 ! [v1.5.0-rc0] GIT v1.5.0 preview 796 ! [v1.5.0-rc1] GIT v1.5.0-rc1 797 ! [v1.5.0-rc2] GIT v1.5.0-rc2 798... 799------------------------------------------------- 800 801then search for a line that looks like 802 803------------------------------------------------- 804+ ++ [e05db0fd] Fix warnings in sha1_file.c - use C99 printf format if 805available 806------------------------------------------------- 807 808Which shows that e05db0fd is reachable from itself, from v1.5.0-rc1, and 809from v1.5.0-rc2, but not from v1.5.0-rc0. 810 811[[making-a-release]] 812Creating a changelog and tarball for a software release 813~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 814 815The gitlink:git-archive[1] command can create a tar or zip archive from 816any version of a project; for example: 817 818------------------------------------------------- 819$ git archive --format=tar --prefix=project/ HEAD | gzip >latest.tar.gz 820------------------------------------------------- 821 822will use HEAD to produce a tar archive in which each filename is 823preceded by "prefix/". 824 825If you're releasing a new version of a software project, you may want 826to simultaneously make a changelog to include in the release 827announcement. 828 829Linus Torvalds, for example, makes new kernel releases by tagging them, 830then running: 831 832------------------------------------------------- 833$ release-script 2.6.12 2.6.13-rc6 2.6.13-rc7 834------------------------------------------------- 835 836where release-script is a shell script that looks like: 837 838------------------------------------------------- 839#!/bin/sh 840stable="$1" 841last="$2" 842new="$3" 843echo "# git tag v$new" 844echo "git archive --prefix=linux-$new/ v$new | gzip -9 > ../linux-$new.tar.gz" 845echo "git diff v$stable v$new | gzip -9 > ../patch-$new.gz" 846echo "git log --no-merges v$new ^v$last > ../ChangeLog-$new" 847echo "git shortlog --no-merges v$new ^v$last > ../ShortLog" 848echo "git diff --stat --summary -M v$last v$new > ../diffstat-$new" 849------------------------------------------------- 850 851and then he just cut-and-pastes the output commands after verifying that 852they look OK. 853 854[[Developing-with-git]] 855Developing with git 856=================== 857 858[[telling-git-your-name]] 859Telling git your name 860--------------------- 861 862Before creating any commits, you should introduce yourself to git. The 863easiest way to do so is to make sure the following lines appear in a 864file named .gitconfig in your home directory: 865 866------------------------------------------------ 867[user] 868 name = Your Name Comes Here 869 email = you@yourdomain.example.com 870------------------------------------------------ 871 872(See the "CONFIGURATION FILE" section of gitlink:git-config[1] for 873details on the configuration file.) 874 875 876[[creating-a-new-repository]] 877Creating a new repository 878------------------------- 879 880Creating a new repository from scratch is very easy: 881 882------------------------------------------------- 883$ mkdir project 884$ cd project 885$ git init 886------------------------------------------------- 887 888If you have some initial content (say, a tarball): 889 890------------------------------------------------- 891$ tar -xzvf project.tar.gz 892$ cd project 893$ git init 894$ git add . # include everything below ./ in the first commit: 895$ git commit 896------------------------------------------------- 897 898[[how-to-make-a-commit]] 899How to make a commit 900-------------------- 901 902Creating a new commit takes three steps: 903 904 1. Making some changes to the working directory using your 905 favorite editor. 906 2. Telling git about your changes. 907 3. Creating the commit using the content you told git about 908 in step 2. 909 910In practice, you can interleave and repeat steps 1 and 2 as many 911times as you want: in order to keep track of what you want committed 912at step 3, git maintains a snapshot of the tree's contents in a 913special staging area called "the index." 914 915At the beginning, the content of the index will be identical to 916that of the HEAD. The command "git diff --cached", which shows 917the difference between the HEAD and the index, should therefore 918produce no output at that point. 919 920Modifying the index is easy: 921 922To update the index with the new contents of a modified file, use 923 924------------------------------------------------- 925$ git add path/to/file 926------------------------------------------------- 927 928To add the contents of a new file to the index, use 929 930------------------------------------------------- 931$ git add path/to/file 932------------------------------------------------- 933 934To remove a file from the index and from the working tree, 935 936------------------------------------------------- 937$ git rm path/to/file 938------------------------------------------------- 939 940After each step you can verify that 941 942------------------------------------------------- 943$ git diff --cached 944------------------------------------------------- 945 946always shows the difference between the HEAD and the index file--this 947is what you'd commit if you created the commit now--and that 948 949------------------------------------------------- 950$ git diff 951------------------------------------------------- 952 953shows the difference between the working tree and the index file. 954 955Note that "git add" always adds just the current contents of a file 956to the index; further changes to the same file will be ignored unless 957you run git-add on the file again. 958 959When you're ready, just run 960 961------------------------------------------------- 962$ git commit 963------------------------------------------------- 964 965and git will prompt you for a commit message and then create the new 966commit. Check to make sure it looks like what you expected with 967 968------------------------------------------------- 969$ git show 970------------------------------------------------- 971 972As a special shortcut, 973 974------------------------------------------------- 975$ git commit -a 976------------------------------------------------- 977 978will update the index with any files that you've modified or removed 979and create a commit, all in one step. 980 981A number of commands are useful for keeping track of what you're 982about to commit: 983 984------------------------------------------------- 985$ git diff --cached # difference between HEAD and the index; what 986 # would be commited if you ran "commit" now. 987$ git diff # difference between the index file and your 988 # working directory; changes that would not 989 # be included if you ran "commit" now. 990$ git diff HEAD # difference between HEAD and working tree; what 991 # would be committed if you ran "commit -a" now. 992$ git status # a brief per-file summary of the above. 993------------------------------------------------- 994 995[[creating-good-commit-messages]] 996Creating good commit messages 997----------------------------- 998 999Though not required, it's a good idea to begin the commit message1000with a single short (less than 50 character) line summarizing the1001change, followed by a blank line and then a more thorough1002description. Tools that turn commits into email, for example, use1003the first line on the Subject line and the rest of the commit in the1004body.10051006[[how-to-merge]]1007How to merge1008------------10091010You can rejoin two diverging branches of development using1011gitlink:git-merge[1]:10121013-------------------------------------------------1014$ git merge branchname1015-------------------------------------------------10161017merges the development in the branch "branchname" into the current1018branch. If there are conflicts--for example, if the same file is1019modified in two different ways in the remote branch and the local1020branch--then you are warned; the output may look something like this:10211022-------------------------------------------------1023$ git merge next1024 100% (4/4) done1025Auto-merged file.txt1026CONFLICT (content): Merge conflict in file.txt1027Automatic merge failed; fix conflicts and then commit the result.1028-------------------------------------------------10291030Conflict markers are left in the problematic files, and after1031you resolve the conflicts manually, you can update the index1032with the contents and run git commit, as you normally would when1033creating a new file.10341035If you examine the resulting commit using gitk, you will see that it1036has two parents, one pointing to the top of the current branch, and1037one to the top of the other branch.10381039[[resolving-a-merge]]1040Resolving a merge1041-----------------10421043When a merge isn't resolved automatically, git leaves the index and1044the working tree in a special state that gives you all the1045information you need to help resolve the merge.10461047Files with conflicts are marked specially in the index, so until you1048resolve the problem and update the index, gitlink:git-commit[1] will1049fail:10501051-------------------------------------------------1052$ git commit1053file.txt: needs merge1054-------------------------------------------------10551056Also, gitlink:git-status[1] will list those files as "unmerged", and the1057files with conflicts will have conflict markers added, like this:10581059-------------------------------------------------1060<<<<<<< HEAD:file.txt1061Hello world1062=======1063Goodbye1064>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt1065-------------------------------------------------10661067All you need to do is edit the files to resolve the conflicts, and then10681069-------------------------------------------------1070$ git add file.txt1071$ git commit1072-------------------------------------------------10731074Note that the commit message will already be filled in for you with1075some information about the merge. Normally you can just use this1076default message unchanged, but you may add additional commentary of1077your own if desired.10781079The above is all you need to know to resolve a simple merge. But git1080also provides more information to help resolve conflicts:10811082[[conflict-resolution]]1083Getting conflict-resolution help during a merge1084~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~10851086All of the changes that git was able to merge automatically are1087already added to the index file, so gitlink:git-diff[1] shows only1088the conflicts. It uses an unusual syntax:10891090-------------------------------------------------1091$ git diff1092diff --cc file.txt1093index 802992c,2b60207..00000001094--- a/file.txt1095+++ b/file.txt1096@@@ -1,1 -1,1 +1,5 @@@1097++<<<<<<< HEAD:file.txt1098 +Hello world1099++=======1100+ Goodbye1101++>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt1102-------------------------------------------------11031104Recall that the commit which will be commited after we resolve this1105conflict will have two parents instead of the usual one: one parent1106will be HEAD, the tip of the current branch; the other will be the1107tip of the other branch, which is stored temporarily in MERGE_HEAD.11081109During the merge, the index holds three versions of each file. Each of1110these three "file stages" represents a different version of the file:11111112-------------------------------------------------1113$ git show :1:file.txt # the file in a common ancestor of both branches1114$ git show :2:file.txt # the version from HEAD, but including any1115 # nonconflicting changes from MERGE_HEAD1116$ git show :3:file.txt # the version from MERGE_HEAD, but including any1117 # nonconflicting changes from HEAD.1118-------------------------------------------------11191120Since the stage 2 and stage 3 versions have already been updated with1121nonconflicting changes, the only remaining differences between them are1122the important ones; thus gitlink:git-diff[1] can use the information in1123the index to show only those conflicts.11241125The diff above shows the differences between the working-tree version of1126file.txt and the stage 2 and stage 3 versions. So instead of preceding1127each line by a single "+" or "-", it now uses two columns: the first1128column is used for differences between the first parent and the working1129directory copy, and the second for differences between the second parent1130and the working directory copy. (See the "COMBINED DIFF FORMAT" section1131of gitlink:git-diff-files[1] for a details of the format.)11321133After resolving the conflict in the obvious way (but before updating the1134index), the diff will look like:11351136-------------------------------------------------1137$ git diff1138diff --cc file.txt1139index 802992c,2b60207..00000001140--- a/file.txt1141+++ b/file.txt1142@@@ -1,1 -1,1 +1,1 @@@1143- Hello world1144 -Goodbye1145++Goodbye world1146-------------------------------------------------11471148This shows that our resolved version deleted "Hello world" from the1149first parent, deleted "Goodbye" from the second parent, and added1150"Goodbye world", which was previously absent from both.11511152Some special diff options allow diffing the working directory against1153any of these stages:11541155-------------------------------------------------1156$ git diff -1 file.txt # diff against stage 11157$ git diff --base file.txt # same as the above1158$ git diff -2 file.txt # diff against stage 21159$ git diff --ours file.txt # same as the above1160$ git diff -3 file.txt # diff against stage 31161$ git diff --theirs file.txt # same as the above.1162-------------------------------------------------11631164The gitlink:git-log[1] and gitk[1] commands also provide special help1165for merges:11661167-------------------------------------------------1168$ git log --merge1169$ gitk --merge1170-------------------------------------------------11711172These will display all commits which exist only on HEAD or on1173MERGE_HEAD, and which touch an unmerged file.11741175You may also use gitlink:git-mergetool[1], which lets you merge the1176unmerged files using external tools such as emacs or kdiff3.11771178Each time you resolve the conflicts in a file and update the index:11791180-------------------------------------------------1181$ git add file.txt1182-------------------------------------------------11831184the different stages of that file will be "collapsed", after which1185git-diff will (by default) no longer show diffs for that file.11861187[[undoing-a-merge]]1188Undoing a merge1189---------------11901191If you get stuck and decide to just give up and throw the whole mess1192away, you can always return to the pre-merge state with11931194-------------------------------------------------1195$ git reset --hard HEAD1196-------------------------------------------------11971198Or, if you've already commited the merge that you want to throw away,11991200-------------------------------------------------1201$ git reset --hard ORIG_HEAD1202-------------------------------------------------12031204However, this last command can be dangerous in some cases--never1205throw away a commit you have already committed if that commit may1206itself have been merged into another branch, as doing so may confuse1207further merges.12081209[[fast-forwards]]1210Fast-forward merges1211-------------------12121213There is one special case not mentioned above, which is treated1214differently. Normally, a merge results in a merge commit, with two1215parents, one pointing at each of the two lines of development that1216were merged.12171218However, if the current branch is a descendant of the other--so every1219commit present in the one is already contained in the other--then git1220just performs a "fast forward"; the head of the current branch is moved1221forward to point at the head of the merged-in branch, without any new1222commits being created.12231224[[fixing-mistakes]]1225Fixing mistakes1226---------------12271228If you've messed up the working tree, but haven't yet committed your1229mistake, you can return the entire working tree to the last committed1230state with12311232-------------------------------------------------1233$ git reset --hard HEAD1234-------------------------------------------------12351236If you make a commit that you later wish you hadn't, there are two1237fundamentally different ways to fix the problem:12381239 1. You can create a new commit that undoes whatever was done1240 by the previous commit. This is the correct thing if your1241 mistake has already been made public.12421243 2. You can go back and modify the old commit. You should1244 never do this if you have already made the history public;1245 git does not normally expect the "history" of a project to1246 change, and cannot correctly perform repeated merges from1247 a branch that has had its history changed.12481249[[reverting-a-commit]]1250Fixing a mistake with a new commit1251~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~12521253Creating a new commit that reverts an earlier change is very easy;1254just pass the gitlink:git-revert[1] command a reference to the bad1255commit; for example, to revert the most recent commit:12561257-------------------------------------------------1258$ git revert HEAD1259-------------------------------------------------12601261This will create a new commit which undoes the change in HEAD. You1262will be given a chance to edit the commit message for the new commit.12631264You can also revert an earlier change, for example, the next-to-last:12651266-------------------------------------------------1267$ git revert HEAD^1268-------------------------------------------------12691270In this case git will attempt to undo the old change while leaving1271intact any changes made since then. If more recent changes overlap1272with the changes to be reverted, then you will be asked to fix1273conflicts manually, just as in the case of <<resolving-a-merge,1274resolving a merge>>.12751276[[fixing-a-mistake-by-editing-history]]1277Fixing a mistake by editing history1278~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~12791280If the problematic commit is the most recent commit, and you have not1281yet made that commit public, then you may just1282<<undoing-a-merge,destroy it using git-reset>>.12831284Alternatively, you1285can edit the working directory and update the index to fix your1286mistake, just as if you were going to <<how-to-make-a-commit,create a1287new commit>>, then run12881289-------------------------------------------------1290$ git commit --amend1291-------------------------------------------------12921293which will replace the old commit by a new commit incorporating your1294changes, giving you a chance to edit the old commit message first.12951296Again, you should never do this to a commit that may already have1297been merged into another branch; use gitlink:git-revert[1] instead in1298that case.12991300It is also possible to edit commits further back in the history, but1301this is an advanced topic to be left for1302<<cleaning-up-history,another chapter>>.13031304[[checkout-of-path]]1305Checking out an old version of a file1306~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~13071308In the process of undoing a previous bad change, you may find it1309useful to check out an older version of a particular file using1310gitlink:git-checkout[1]. We've used git checkout before to switch1311branches, but it has quite different behavior if it is given a path1312name: the command13131314-------------------------------------------------1315$ git checkout HEAD^ path/to/file1316-------------------------------------------------13171318replaces path/to/file by the contents it had in the commit HEAD^, and1319also updates the index to match. It does not change branches.13201321If you just want to look at an old version of the file, without1322modifying the working directory, you can do that with1323gitlink:git-show[1]:13241325-------------------------------------------------1326$ git show HEAD^:path/to/file1327-------------------------------------------------13281329which will display the given version of the file.13301331[[ensuring-good-performance]]1332Ensuring good performance1333-------------------------13341335On large repositories, git depends on compression to keep the history1336information from taking up to much space on disk or in memory.13371338This compression is not performed automatically. Therefore you1339should occasionally run gitlink:git-gc[1]:13401341-------------------------------------------------1342$ git gc1343-------------------------------------------------13441345to recompress the archive. This can be very time-consuming, so1346you may prefer to run git-gc when you are not doing other work.134713481349[[ensuring-reliability]]1350Ensuring reliability1351--------------------13521353[[checking-for-corruption]]1354Checking the repository for corruption1355~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~13561357The gitlink:git-fsck[1] command runs a number of self-consistency checks1358on the repository, and reports on any problems. This may take some1359time. The most common warning by far is about "dangling" objects:13601361-------------------------------------------------1362$ git fsck1363dangling commit 7281251ddd2a61e38657c827739c57015671a6b31364dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a631365dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b51366dangling blob 218761f9d90712d37a9c5e36f406f92202db07eb1367dangling commit bf093535a34a4d35731aa2bd90fe6b176302f14f1368dangling commit 8e4bec7f2ddaa268bef999853c25755452100f8e1369dangling tree d50bb86186bf27b681d25af89d3b5b68382e40851370dangling tree b24c2473f1fd3d91352a624795be026d64c8841f1371...1372-------------------------------------------------13731374Dangling objects are not a problem. At worst they may take up a little1375extra disk space. They can sometimes provide a last-resort method of1376recovery lost work--see <<dangling-objects>> for details. However, if1377you want, you may remove them with gitlink:git-prune[1] or the --prune1378option to gitlink:git-gc[1]:13791380-------------------------------------------------1381$ git gc --prune1382-------------------------------------------------13831384This may be time-consuming. Unlike most other git operations (including1385git-gc when run without any options), it is not safe to prune while1386other git operations are in progress in the same repository.13871388[[recovering-lost-changes]]1389Recovering lost changes1390~~~~~~~~~~~~~~~~~~~~~~~13911392[[reflogs]]1393Reflogs1394^^^^^^^13951396Say you modify a branch with gitlink:git-reset[1] --hard, and then1397realize that the branch was the only reference you had to that point in1398history.13991400Fortunately, git also keeps a log, called a "reflog", of all the1401previous values of each branch. So in this case you can still find the1402old history using, for example, 14031404-------------------------------------------------1405$ git log master@{1}1406-------------------------------------------------14071408This lists the commits reachable from the previous version of the head.1409This syntax can be used to with any git command that accepts a commit,1410not just with git log. Some other examples:14111412-------------------------------------------------1413$ git show master@{2} # See where the branch pointed 2,1414$ git show master@{3} # 3, ... changes ago.1415$ gitk master@{yesterday} # See where it pointed yesterday,1416$ gitk master@{"1 week ago"} # ... or last week1417$ git log --walk-reflogs master # show reflog entries for master1418-------------------------------------------------14191420A separate reflog is kept for the HEAD, so14211422-------------------------------------------------1423$ git show HEAD@{"1 week ago"}1424-------------------------------------------------14251426will show what HEAD pointed to one week ago, not what the current branch1427pointed to one week ago. This allows you to see the history of what1428you've checked out.14291430The reflogs are kept by default for 30 days, after which they may be1431pruned. See gitlink:git-reflog[1] and gitlink:git-gc[1] to learn1432how to control this pruning, and see the "SPECIFYING REVISIONS"1433section of gitlink:git-rev-parse[1] for details.14341435Note that the reflog history is very different from normal git history.1436While normal history is shared by every repository that works on the1437same project, the reflog history is not shared: it tells you only about1438how the branches in your local repository have changed over time.14391440[[dangling-object-recovery]]1441Examining dangling objects1442^^^^^^^^^^^^^^^^^^^^^^^^^^14431444In some situations the reflog may not be able to save you. For example,1445suppose you delete a branch, then realize you need the history it1446contained. The reflog is also deleted; however, if you have not yet1447pruned the repository, then you may still be able to find the lost1448commits in the dangling objects that git-fsck reports. See1449<<dangling-objects>> for the details.14501451-------------------------------------------------1452$ git fsck1453dangling commit 7281251ddd2a61e38657c827739c57015671a6b31454dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a631455dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b51456...1457-------------------------------------------------14581459You can examine1460one of those dangling commits with, for example,14611462------------------------------------------------1463$ gitk 7281251ddd --not --all1464------------------------------------------------14651466which does what it sounds like: it says that you want to see the commit1467history that is described by the dangling commit(s), but not the1468history that is described by all your existing branches and tags. Thus1469you get exactly the history reachable from that commit that is lost.1470(And notice that it might not be just one commit: we only report the1471"tip of the line" as being dangling, but there might be a whole deep1472and complex commit history that was dropped.)14731474If you decide you want the history back, you can always create a new1475reference pointing to it, for example, a new branch:14761477------------------------------------------------1478$ git branch recovered-branch 7281251ddd 1479------------------------------------------------14801481Other types of dangling objects (blobs and trees) are also possible, and1482dangling objects can arise in other situations.148314841485[[sharing-development]]1486Sharing development with others1487===============================14881489[[getting-updates-with-git-pull]]1490Getting updates with git pull1491-----------------------------14921493After you clone a repository and make a few changes of your own, you1494may wish to check the original repository for updates and merge them1495into your own work.14961497We have already seen <<Updating-a-repository-with-git-fetch,how to1498keep remote tracking branches up to date>> with gitlink:git-fetch[1],1499and how to merge two branches. So you can merge in changes from the1500original repository's master branch with:15011502-------------------------------------------------1503$ git fetch1504$ git merge origin/master1505-------------------------------------------------15061507However, the gitlink:git-pull[1] command provides a way to do this in1508one step:15091510-------------------------------------------------1511$ git pull origin master1512-------------------------------------------------15131514In fact, "origin" is normally the default repository to pull from,1515and the default branch is normally the HEAD of the remote repository,1516so often you can accomplish the above with just15171518-------------------------------------------------1519$ git pull1520-------------------------------------------------15211522See the descriptions of the branch.<name>.remote and branch.<name>.merge1523options in gitlink:git-config[1] to learn how to control these defaults1524depending on the current branch. Also note that the --track option to1525gitlink:git-branch[1] and gitlink:git-checkout[1] can be used to1526automatically set the default remote branch to pull from at the time1527that a branch is created:15281529-------------------------------------------------1530$ git checkout --track -b origin/maint maint1531-------------------------------------------------15321533In addition to saving you keystrokes, "git pull" also helps you by1534producing a default commit message documenting the branch and1535repository that you pulled from.15361537(But note that no such commit will be created in the case of a1538<<fast-forwards,fast forward>>; instead, your branch will just be1539updated to point to the latest commit from the upstream branch.)15401541The git-pull command can also be given "." as the "remote" repository,1542in which case it just merges in a branch from the current repository; so1543the commands15441545-------------------------------------------------1546$ git pull . branch1547$ git merge branch1548-------------------------------------------------15491550are roughly equivalent. The former is actually very commonly used.15511552[[submitting-patches]]1553Submitting patches to a project1554-------------------------------15551556If you just have a few changes, the simplest way to submit them may1557just be to send them as patches in email:15581559First, use gitlink:git-format-patch[1]; for example:15601561-------------------------------------------------1562$ git format-patch origin1563-------------------------------------------------15641565will produce a numbered series of files in the current directory, one1566for each patch in the current branch but not in origin/HEAD.15671568You can then import these into your mail client and send them by1569hand. However, if you have a lot to send at once, you may prefer to1570use the gitlink:git-send-email[1] script to automate the process.1571Consult the mailing list for your project first to determine how they1572prefer such patches be handled.15731574[[importing-patches]]1575Importing patches to a project1576------------------------------15771578Git also provides a tool called gitlink:git-am[1] (am stands for1579"apply mailbox"), for importing such an emailed series of patches.1580Just save all of the patch-containing messages, in order, into a1581single mailbox file, say "patches.mbox", then run15821583-------------------------------------------------1584$ git am -3 patches.mbox1585-------------------------------------------------15861587Git will apply each patch in order; if any conflicts are found, it1588will stop, and you can fix the conflicts as described in1589"<<resolving-a-merge,Resolving a merge>>". (The "-3" option tells1590git to perform a merge; if you would prefer it just to abort and1591leave your tree and index untouched, you may omit that option.)15921593Once the index is updated with the results of the conflict1594resolution, instead of creating a new commit, just run15951596-------------------------------------------------1597$ git am --resolved1598-------------------------------------------------15991600and git will create the commit for you and continue applying the1601remaining patches from the mailbox.16021603The final result will be a series of commits, one for each patch in1604the original mailbox, with authorship and commit log message each1605taken from the message containing each patch.16061607[[setting-up-a-public-repository]]1608Setting up a public repository1609------------------------------16101611Another way to submit changes to a project is to simply tell the1612maintainer of that project to pull from your repository, exactly as1613you did in the section "<<getting-updates-with-git-pull, Getting1614updates with git pull>>".16151616If you and maintainer both have accounts on the same machine, then1617then you can just pull changes from each other's repositories1618directly; note that all of the commands (gitlink:git-clone[1],1619git-fetch[1], git-pull[1], etc.) that accept a URL as an argument1620will also accept a local directory name; so, for example, you can1621use16221623-------------------------------------------------1624$ git clone /path/to/repository1625$ git pull /path/to/other/repository1626-------------------------------------------------16271628If this sort of setup is inconvenient or impossible, another (more1629common) option is to set up a public repository on a public server.1630This also allows you to cleanly separate private work in progress1631from publicly visible work.16321633You will continue to do your day-to-day work in your personal1634repository, but periodically "push" changes from your personal1635repository into your public repository, allowing other developers to1636pull from that repository. So the flow of changes, in a situation1637where there is one other developer with a public repository, looks1638like this:16391640 you push1641 your personal repo ------------------> your public repo1642 ^ |1643 | |1644 | you pull | they pull1645 | |1646 | |1647 | they push V1648 their public repo <------------------- their repo16491650Now, assume your personal repository is in the directory ~/proj. We1651first create a new clone of the repository:16521653-------------------------------------------------1654$ git clone --bare ~/proj proj.git1655-------------------------------------------------16561657The resulting directory proj.git contains a "bare" git repository--it is1658just the contents of the ".git" directory, without a checked-out copy of1659a working directory.16601661Next, copy proj.git to the server where you plan to host the1662public repository. You can use scp, rsync, or whatever is most1663convenient.16641665If somebody else maintains the public server, they may already have1666set up a git service for you, and you may skip to the section1667"<<pushing-changes-to-a-public-repository,Pushing changes to a public1668repository>>", below.16691670Otherwise, the following sections explain how to export your newly1671created public repository:16721673[[exporting-via-http]]1674Exporting a git repository via http1675-----------------------------------16761677The git protocol gives better performance and reliability, but on a1678host with a web server set up, http exports may be simpler to set up.16791680All you need to do is place the newly created bare git repository in1681a directory that is exported by the web server, and make some1682adjustments to give web clients some extra information they need:16831684-------------------------------------------------1685$ mv proj.git /home/you/public_html/proj.git1686$ cd proj.git1687$ git --bare update-server-info1688$ chmod a+x hooks/post-update1689-------------------------------------------------16901691(For an explanation of the last two lines, see1692gitlink:git-update-server-info[1], and the documentation1693link:hooks.txt[Hooks used by git].)16941695Advertise the url of proj.git. Anybody else should then be able to1696clone or pull from that url, for example with a commandline like:16971698-------------------------------------------------1699$ git clone http://yourserver.com/~you/proj.git1700-------------------------------------------------17011702(See also1703link:howto/setup-git-server-over-http.txt[setup-git-server-over-http]1704for a slightly more sophisticated setup using WebDAV which also1705allows pushing over http.)17061707[[exporting-via-git]]1708Exporting a git repository via the git protocol1709-----------------------------------------------17101711This is the preferred method.17121713For now, we refer you to the gitlink:git-daemon[1] man page for1714instructions. (See especially the examples section.)17151716[[pushing-changes-to-a-public-repository]]1717Pushing changes to a public repository1718--------------------------------------17191720Note that the two techniques outline above (exporting via1721<<exporting-via-http,http>> or <<exporting-via-git,git>>) allow other1722maintainers to fetch your latest changes, but they do not allow write1723access, which you will need to update the public repository with the1724latest changes created in your private repository.17251726The simplest way to do this is using gitlink:git-push[1] and ssh; to1727update the remote branch named "master" with the latest state of your1728branch named "master", run17291730-------------------------------------------------1731$ git push ssh://yourserver.com/~you/proj.git master:master1732-------------------------------------------------17331734or just17351736-------------------------------------------------1737$ git push ssh://yourserver.com/~you/proj.git master1738-------------------------------------------------17391740As with git-fetch, git-push will complain if this does not result in1741a <<fast-forwards,fast forward>>. Normally this is a sign of1742something wrong. However, if you are sure you know what you're1743doing, you may force git-push to perform the update anyway by1744proceeding the branch name by a plus sign:17451746-------------------------------------------------1747$ git push ssh://yourserver.com/~you/proj.git +master1748-------------------------------------------------17491750As with git-fetch, you may also set up configuration options to1751save typing; so, for example, after17521753-------------------------------------------------1754$ cat >>.git/config <<EOF1755[remote "public-repo"]1756 url = ssh://yourserver.com/~you/proj.git1757EOF1758-------------------------------------------------17591760you should be able to perform the above push with just17611762-------------------------------------------------1763$ git push public-repo master1764-------------------------------------------------17651766See the explanations of the remote.<name>.url, branch.<name>.remote,1767and remote.<name>.push options in gitlink:git-config[1] for1768details.17691770[[setting-up-a-shared-repository]]1771Setting up a shared repository1772------------------------------17731774Another way to collaborate is by using a model similar to that1775commonly used in CVS, where several developers with special rights1776all push to and pull from a single shared repository. See1777link:cvs-migration.txt[git for CVS users] for instructions on how to1778set this up.17791780[[setting-up-gitweb]]1781Allow web browsing of a repository1782----------------------------------17831784The gitweb cgi script provides users an easy way to browse your1785project's files and history without having to install git; see the file1786gitweb/INSTALL in the git source tree for instructions on setting it up.17871788[[sharing-development-examples]]1789Examples1790--------17911792[[maintaining-topic-branches]]1793Maintaining topic branches for a Linux subsystem maintainer1794~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~17951796This describes how Tony Luck uses git in his role as maintainer of the1797IA64 architecture for the Linux kernel.17981799He uses two public branches:18001801 - A "test" tree into which patches are initially placed so that they1802 can get some exposure when integrated with other ongoing development.1803 This tree is available to Andrew for pulling into -mm whenever he1804 wants.18051806 - A "release" tree into which tested patches are moved for final sanity1807 checking, and as a vehicle to send them upstream to Linus (by sending1808 him a "please pull" request.)18091810He also uses a set of temporary branches ("topic branches"), each1811containing a logical grouping of patches.18121813To set this up, first create your work tree by cloning Linus's public1814tree:18151816-------------------------------------------------1817$ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git work1818$ cd work1819-------------------------------------------------18201821Linus's tree will be stored in the remote branch named origin/master,1822and can be updated using gitlink:git-fetch[1]; you can track other1823public trees using gitlink:git-remote[1] to set up a "remote" and1824git-fetch[1] to keep them up-to-date; see <<repositories-and-branches>>.18251826Now create the branches in which you are going to work; these start out1827at the current tip of origin/master branch, and should be set up (using1828the --track option to gitlink:git-branch[1]) to merge changes in from1829Linus by default.18301831-------------------------------------------------1832$ git branch --track test origin/master1833$ git branch --track release origin/master1834-------------------------------------------------18351836These can be easily kept up to date using gitlink:git-pull[1]18371838-------------------------------------------------1839$ git checkout test && git pull1840$ git checkout release && git pull1841-------------------------------------------------18421843Important note! If you have any local changes in these branches, then1844this merge will create a commit object in the history (with no local1845changes git will simply do a "Fast forward" merge). Many people dislike1846the "noise" that this creates in the Linux history, so you should avoid1847doing this capriciously in the "release" branch, as these noisy commits1848will become part of the permanent history when you ask Linus to pull1849from the release branch.18501851A few configuration variables (see gitlink:git-config[1]) can1852make it easy to push both branches to your public tree. (See1853<<setting-up-a-public-repository>>.)18541855-------------------------------------------------1856$ cat >> .git/config <<EOF1857[remote "mytree"]1858 url = master.kernel.org:/pub/scm/linux/kernel/git/aegl/linux-2.6.git1859 push = release1860 push = test1861EOF1862-------------------------------------------------18631864Then you can push both the test and release trees using1865gitlink:git-push[1]:18661867-------------------------------------------------1868$ git push mytree1869-------------------------------------------------18701871or push just one of the test and release branches using:18721873-------------------------------------------------1874$ git push mytree test1875-------------------------------------------------18761877or18781879-------------------------------------------------1880$ git push mytree release1881-------------------------------------------------18821883Now to apply some patches from the community. Think of a short1884snappy name for a branch to hold this patch (or related group of1885patches), and create a new branch from the current tip of Linus's1886branch:18871888-------------------------------------------------1889$ git checkout -b speed-up-spinlocks origin1890-------------------------------------------------18911892Now you apply the patch(es), run some tests, and commit the change(s). If1893the patch is a multi-part series, then you should apply each as a separate1894commit to this branch.18951896-------------------------------------------------1897$ ... patch ... test ... commit [ ... patch ... test ... commit ]*1898-------------------------------------------------18991900When you are happy with the state of this change, you can pull it into the1901"test" branch in preparation to make it public:19021903-------------------------------------------------1904$ git checkout test && git pull . speed-up-spinlocks1905-------------------------------------------------19061907It is unlikely that you would have any conflicts here ... but you might if you1908spent a while on this step and had also pulled new versions from upstream.19091910Some time later when enough time has passed and testing done, you can pull the1911same branch into the "release" tree ready to go upstream. This is where you1912see the value of keeping each patch (or patch series) in its own branch. It1913means that the patches can be moved into the "release" tree in any order.19141915-------------------------------------------------1916$ git checkout release && git pull . speed-up-spinlocks1917-------------------------------------------------19181919After a while, you will have a number of branches, and despite the1920well chosen names you picked for each of them, you may forget what1921they are for, or what status they are in. To get a reminder of what1922changes are in a specific branch, use:19231924-------------------------------------------------1925$ git log linux..branchname | git-shortlog1926-------------------------------------------------19271928To see whether it has already been merged into the test or release branches1929use:19301931-------------------------------------------------1932$ git log test..branchname1933-------------------------------------------------19341935or19361937-------------------------------------------------1938$ git log release..branchname1939-------------------------------------------------19401941(If this branch has not yet been merged you will see some log entries.1942If it has been merged, then there will be no output.)19431944Once a patch completes the great cycle (moving from test to release,1945then pulled by Linus, and finally coming back into your local1946"origin/master" branch) the branch for this change is no longer needed.1947You detect this when the output from:19481949-------------------------------------------------1950$ git log origin..branchname1951-------------------------------------------------19521953is empty. At this point the branch can be deleted:19541955-------------------------------------------------1956$ git branch -d branchname1957-------------------------------------------------19581959Some changes are so trivial that it is not necessary to create a separate1960branch and then merge into each of the test and release branches. For1961these changes, just apply directly to the "release" branch, and then1962merge that into the "test" branch.19631964To create diffstat and shortlog summaries of changes to include in a "please1965pull" request to Linus you can use:19661967-------------------------------------------------1968$ git diff --stat origin..release1969-------------------------------------------------19701971and19721973-------------------------------------------------1974$ git log -p origin..release | git shortlog1975-------------------------------------------------19761977Here are some of the scripts that simplify all this even further.19781979-------------------------------------------------1980==== update script ====1981# Update a branch in my GIT tree. If the branch to be updated1982# is origin, then pull from kernel.org. Otherwise merge1983# origin/master branch into test|release branch19841985case "$1" in1986test|release)1987 git checkout $1 && git pull . origin1988 ;;1989origin)1990 before=$(cat .git/refs/remotes/origin/master)1991 git fetch origin1992 after=$(cat .git/refs/remotes/origin/master)1993 if [ $before != $after ]1994 then1995 git log $before..$after | git shortlog1996 fi1997 ;;1998*)1999 echo "Usage: $0 origin|test|release" 1>&22000 exit 12001 ;;2002esac2003-------------------------------------------------20042005-------------------------------------------------2006==== merge script ====2007# Merge a branch into either the test or release branch20082009pname=$020102011usage()2012{2013 echo "Usage: $pname branch test|release" 1>&22014 exit 12015}20162017if [ ! -f .git/refs/heads/"$1" ]2018then2019 echo "Can't see branch <$1>" 1>&22020 usage2021fi20222023case "$2" in2024test|release)2025 if [ $(git log $2..$1 | wc -c) -eq 0 ]2026 then2027 echo $1 already merged into $2 1>&22028 exit 12029 fi2030 git checkout $2 && git pull . $12031 ;;2032*)2033 usage2034 ;;2035esac2036-------------------------------------------------20372038-------------------------------------------------2039==== status script ====2040# report on status of my ia64 GIT tree20412042gb=$(tput setab 2)2043rb=$(tput setab 1)2044restore=$(tput setab 9)20452046if [ `git rev-list test..release | wc -c` -gt 0 ]2047then2048 echo $rb Warning: commits in release that are not in test $restore2049 git log test..release2050fi20512052for branch in `ls .git/refs/heads`2053do2054 if [ $branch = test -o $branch = release ]2055 then2056 continue2057 fi20582059 echo -n $gb ======= $branch ====== $restore " "2060 status=2061 for ref in test release origin/master2062 do2063 if [ `git rev-list $ref..$branch | wc -c` -gt 0 ]2064 then2065 status=$status${ref:0:1}2066 fi2067 done2068 case $status in2069 trl)2070 echo $rb Need to pull into test $restore2071 ;;2072 rl)2073 echo "In test"2074 ;;2075 l)2076 echo "Waiting for linus"2077 ;;2078 "")2079 echo $rb All done $restore2080 ;;2081 *)2082 echo $rb "<$status>" $restore2083 ;;2084 esac2085 git log origin/master..$branch | git shortlog2086done2087-------------------------------------------------208820892090[[cleaning-up-history]]2091Rewriting history and maintaining patch series2092==============================================20932094Normally commits are only added to a project, never taken away or2095replaced. Git is designed with this assumption, and violating it will2096cause git's merge machinery (for example) to do the wrong thing.20972098However, there is a situation in which it can be useful to violate this2099assumption.21002101[[patch-series]]2102Creating the perfect patch series2103---------------------------------21042105Suppose you are a contributor to a large project, and you want to add a2106complicated feature, and to present it to the other developers in a way2107that makes it easy for them to read your changes, verify that they are2108correct, and understand why you made each change.21092110If you present all of your changes as a single patch (or commit), they2111may find that it is too much to digest all at once.21122113If you present them with the entire history of your work, complete with2114mistakes, corrections, and dead ends, they may be overwhelmed.21152116So the ideal is usually to produce a series of patches such that:21172118 1. Each patch can be applied in order.21192120 2. Each patch includes a single logical change, together with a2121 message explaining the change.21222123 3. No patch introduces a regression: after applying any initial2124 part of the series, the resulting project still compiles and2125 works, and has no bugs that it didn't have before.21262127 4. The complete series produces the same end result as your own2128 (probably much messier!) development process did.21292130We will introduce some tools that can help you do this, explain how to2131use them, and then explain some of the problems that can arise because2132you are rewriting history.21332134[[using-git-rebase]]2135Keeping a patch series up to date using git-rebase2136--------------------------------------------------21372138Suppose that you create a branch "mywork" on a remote-tracking branch2139"origin", and create some commits on top of it:21402141-------------------------------------------------2142$ git checkout -b mywork origin2143$ vi file.txt2144$ git commit2145$ vi otherfile.txt2146$ git commit2147...2148-------------------------------------------------21492150You have performed no merges into mywork, so it is just a simple linear2151sequence of patches on top of "origin":21522153................................................2154 o--o--o <-- origin2155 \2156 o--o--o <-- mywork2157................................................21582159Some more interesting work has been done in the upstream project, and2160"origin" has advanced:21612162................................................2163 o--o--O--o--o--o <-- origin2164 \2165 a--b--c <-- mywork2166................................................21672168At this point, you could use "pull" to merge your changes back in;2169the result would create a new merge commit, like this:21702171................................................2172 o--o--O--o--o--o <-- origin2173 \ \2174 a--b--c--m <-- mywork2175................................................21762177However, if you prefer to keep the history in mywork a simple series of2178commits without any merges, you may instead choose to use2179gitlink:git-rebase[1]:21802181-------------------------------------------------2182$ git checkout mywork2183$ git rebase origin2184-------------------------------------------------21852186This will remove each of your commits from mywork, temporarily saving2187them as patches (in a directory named ".dotest"), update mywork to2188point at the latest version of origin, then apply each of the saved2189patches to the new mywork. The result will look like:219021912192................................................2193 o--o--O--o--o--o <-- origin2194 \2195 a'--b'--c' <-- mywork2196................................................21972198In the process, it may discover conflicts. In that case it will stop2199and allow you to fix the conflicts; after fixing conflicts, use "git2200add" to update the index with those contents, and then, instead of2201running git-commit, just run22022203-------------------------------------------------2204$ git rebase --continue2205-------------------------------------------------22062207and git will continue applying the rest of the patches.22082209At any point you may use the --abort option to abort this process and2210return mywork to the state it had before you started the rebase:22112212-------------------------------------------------2213$ git rebase --abort2214-------------------------------------------------22152216[[modifying-one-commit]]2217Modifying a single commit2218-------------------------22192220We saw in <<fixing-a-mistake-by-editing-history>> that you can replace the2221most recent commit using22222223-------------------------------------------------2224$ git commit --amend2225-------------------------------------------------22262227which will replace the old commit by a new commit incorporating your2228changes, giving you a chance to edit the old commit message first.22292230You can also use a combination of this and gitlink:git-rebase[1] to edit2231commits further back in your history. First, tag the problematic commit with22322233-------------------------------------------------2234$ git tag bad mywork~52235-------------------------------------------------22362237(Either gitk or git-log may be useful for finding the commit.)22382239Then check out that commit, edit it, and rebase the rest of the series2240on top of it (note that we could check out the commit on a temporary2241branch, but instead we're using a <<detached-head,detached head>>):22422243-------------------------------------------------2244$ git checkout bad2245$ # make changes here and update the index2246$ git commit --amend2247$ git rebase --onto HEAD bad mywork2248-------------------------------------------------22492250When you're done, you'll be left with mywork checked out, with the top2251patches on mywork reapplied on top of your modified commit. You can2252then clean up with22532254-------------------------------------------------2255$ git tag -d bad2256-------------------------------------------------22572258Note that the immutable nature of git history means that you haven't really2259"modified" existing commits; instead, you have replaced the old commits with2260new commits having new object names.22612262[[reordering-patch-series]]2263Reordering or selecting from a patch series2264-------------------------------------------22652266Given one existing commit, the gitlink:git-cherry-pick[1] command2267allows you to apply the change introduced by that commit and create a2268new commit that records it. So, for example, if "mywork" points to a2269series of patches on top of "origin", you might do something like:22702271-------------------------------------------------2272$ git checkout -b mywork-new origin2273$ gitk origin..mywork &2274-------------------------------------------------22752276And browse through the list of patches in the mywork branch using gitk,2277applying them (possibly in a different order) to mywork-new using2278cherry-pick, and possibly modifying them as you go using commit2279--amend.22802281Another technique is to use git-format-patch to create a series of2282patches, then reset the state to before the patches:22832284-------------------------------------------------2285$ git format-patch origin2286$ git reset --hard origin2287-------------------------------------------------22882289Then modify, reorder, or eliminate patches as preferred before applying2290them again with gitlink:git-am[1].22912292[[patch-series-tools]]2293Other tools2294-----------22952296There are numerous other tools, such as stgit, which exist for the2297purpose of maintaining a patch series. These are outside of the scope of2298this manual.22992300[[problems-with-rewriting-history]]2301Problems with rewriting history2302-------------------------------23032304The primary problem with rewriting the history of a branch has to do2305with merging. Suppose somebody fetches your branch and merges it into2306their branch, with a result something like this:23072308................................................2309 o--o--O--o--o--o <-- origin2310 \ \2311 t--t--t--m <-- their branch:2312................................................23132314Then suppose you modify the last three commits:23152316................................................2317 o--o--o <-- new head of origin2318 /2319 o--o--O--o--o--o <-- old head of origin2320................................................23212322If we examined all this history together in one repository, it will2323look like:23242325................................................2326 o--o--o <-- new head of origin2327 /2328 o--o--O--o--o--o <-- old head of origin2329 \ \2330 t--t--t--m <-- their branch:2331................................................23322333Git has no way of knowing that the new head is an updated version of2334the old head; it treats this situation exactly the same as it would if2335two developers had independently done the work on the old and new heads2336in parallel. At this point, if someone attempts to merge the new head2337in to their branch, git will attempt to merge together the two (old and2338new) lines of development, instead of trying to replace the old by the2339new. The results are likely to be unexpected.23402341You may still choose to publish branches whose history is rewritten,2342and it may be useful for others to be able to fetch those branches in2343order to examine or test them, but they should not attempt to pull such2344branches into their own work.23452346For true distributed development that supports proper merging,2347published branches should never be rewritten.23482349[[advanced-branch-management]]2350Advanced branch management2351==========================23522353[[fetching-individual-branches]]2354Fetching individual branches2355----------------------------23562357Instead of using gitlink:git-remote[1], you can also choose just2358to update one branch at a time, and to store it locally under an2359arbitrary name:23602361-------------------------------------------------2362$ git fetch origin todo:my-todo-work2363-------------------------------------------------23642365The first argument, "origin", just tells git to fetch from the2366repository you originally cloned from. The second argument tells git2367to fetch the branch named "todo" from the remote repository, and to2368store it locally under the name refs/heads/my-todo-work.23692370You can also fetch branches from other repositories; so23712372-------------------------------------------------2373$ git fetch git://example.com/proj.git master:example-master2374-------------------------------------------------23752376will create a new branch named "example-master" and store in it the2377branch named "master" from the repository at the given URL. If you2378already have a branch named example-master, it will attempt to2379<<fast-forwards,fast-forward>> to the commit given by example.com's2380master branch. In more detail:23812382[[fetch-fast-forwards]]2383git fetch and fast-forwards2384---------------------------23852386In the previous example, when updating an existing branch, "git2387fetch" checks to make sure that the most recent commit on the remote2388branch is a descendant of the most recent commit on your copy of the2389branch before updating your copy of the branch to point at the new2390commit. Git calls this process a <<fast-forwards,fast forward>>.23912392A fast forward looks something like this:23932394................................................2395 o--o--o--o <-- old head of the branch2396 \2397 o--o--o <-- new head of the branch2398................................................239924002401In some cases it is possible that the new head will *not* actually be2402a descendant of the old head. For example, the developer may have2403realized she made a serious mistake, and decided to backtrack,2404resulting in a situation like:24052406................................................2407 o--o--o--o--a--b <-- old head of the branch2408 \2409 o--o--o <-- new head of the branch2410................................................24112412In this case, "git fetch" will fail, and print out a warning.24132414In that case, you can still force git to update to the new head, as2415described in the following section. However, note that in the2416situation above this may mean losing the commits labeled "a" and "b",2417unless you've already created a reference of your own pointing to2418them.24192420[[forcing-fetch]]2421Forcing git fetch to do non-fast-forward updates2422------------------------------------------------24232424If git fetch fails because the new head of a branch is not a2425descendant of the old head, you may force the update with:24262427-------------------------------------------------2428$ git fetch git://example.com/proj.git +master:refs/remotes/example/master2429-------------------------------------------------24302431Note the addition of the "+" sign. Alternatively, you can use the "-f"2432flag to force updates of all the fetched branches, as in:24332434-------------------------------------------------2435$ git fetch -f origin2436-------------------------------------------------24372438Be aware that commits that the old version of example/master pointed at2439may be lost, as we saw in the previous section.24402441[[remote-branch-configuration]]2442Configuring remote branches2443---------------------------24442445We saw above that "origin" is just a shortcut to refer to the2446repository that you originally cloned from. This information is2447stored in git configuration variables, which you can see using2448gitlink:git-config[1]:24492450-------------------------------------------------2451$ git config -l2452core.repositoryformatversion=02453core.filemode=true2454core.logallrefupdates=true2455remote.origin.url=git://git.kernel.org/pub/scm/git/git.git2456remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*2457branch.master.remote=origin2458branch.master.merge=refs/heads/master2459-------------------------------------------------24602461If there are other repositories that you also use frequently, you can2462create similar configuration options to save typing; for example,2463after24642465-------------------------------------------------2466$ git config remote.example.url git://example.com/proj.git2467-------------------------------------------------24682469then the following two commands will do the same thing:24702471-------------------------------------------------2472$ git fetch git://example.com/proj.git master:refs/remotes/example/master2473$ git fetch example master:refs/remotes/example/master2474-------------------------------------------------24752476Even better, if you add one more option:24772478-------------------------------------------------2479$ git config remote.example.fetch master:refs/remotes/example/master2480-------------------------------------------------24812482then the following commands will all do the same thing:24832484-------------------------------------------------2485$ git fetch git://example.com/proj.git master:refs/remotes/example/master2486$ git fetch example master:refs/remotes/example/master2487$ git fetch example2488-------------------------------------------------24892490You can also add a "+" to force the update each time:24912492-------------------------------------------------2493$ git config remote.example.fetch +master:ref/remotes/example/master2494-------------------------------------------------24952496Don't do this unless you're sure you won't mind "git fetch" possibly2497throwing away commits on mybranch.24982499Also note that all of the above configuration can be performed by2500directly editing the file .git/config instead of using2501gitlink:git-config[1].25022503See gitlink:git-config[1] for more details on the configuration2504options mentioned above.250525062507[[git-internals]]2508Git internals2509=============25102511Git depends on two fundamental abstractions: the "object database", and2512the "current directory cache" aka "index".25132514[[the-object-database]]2515The Object Database2516-------------------25172518The object database is literally just a content-addressable collection2519of objects. All objects are named by their content, which is2520approximated by the SHA1 hash of the object itself. Objects may refer2521to other objects (by referencing their SHA1 hash), and so you can2522build up a hierarchy of objects.25232524All objects have a statically determined "type" which is2525determined at object creation time, and which identifies the format of2526the object (i.e. how it is used, and how it can refer to other2527objects). There are currently four different object types: "blob",2528"tree", "commit", and "tag".25292530A <<def_blob_object,"blob" object>> cannot refer to any other object,2531and is, as the name implies, a pure storage object containing some2532user data. It is used to actually store the file data, i.e. a blob2533object is associated with some particular version of some file.25342535A <<def_tree_object,"tree" object>> is an object that ties one or more2536"blob" objects into a directory structure. In addition, a tree object2537can refer to other tree objects, thus creating a directory hierarchy.25382539A <<def_commit_object,"commit" object>> ties such directory hierarchies2540together into a <<def_DAG,directed acyclic graph>> of revisions - each2541"commit" is associated with exactly one tree (the directory hierarchy at2542the time of the commit). In addition, a "commit" refers to one or more2543"parent" commit objects that describe the history of how we arrived at2544that directory hierarchy.25452546As a special case, a commit object with no parents is called the "root"2547commit, and is the point of an initial project commit. Each project2548must have at least one root, and while you can tie several different2549root objects together into one project by creating a commit object which2550has two or more separate roots as its ultimate parents, that's probably2551just going to confuse people. So aim for the notion of "one root object2552per project", even if git itself does not enforce that. 25532554A <<def_tag_object,"tag" object>> symbolically identifies and can be2555used to sign other objects. It contains the identifier and type of2556another object, a symbolic name (of course!) and, optionally, a2557signature.25582559Regardless of object type, all objects share the following2560characteristics: they are all deflated with zlib, and have a header2561that not only specifies their type, but also provides size information2562about the data in the object. It's worth noting that the SHA1 hash2563that is used to name the object is the hash of the original data2564plus this header, so `sha1sum` 'file' does not match the object name2565for 'file'.2566(Historical note: in the dawn of the age of git the hash2567was the sha1 of the 'compressed' object.)25682569As a result, the general consistency of an object can always be tested2570independently of the contents or the type of the object: all objects can2571be validated by verifying that (a) their hashes match the content of the2572file and (b) the object successfully inflates to a stream of bytes that2573forms a sequence of <ascii type without space> + <space> + <ascii decimal2574size> + <byte\0> + <binary object data>. 25752576The structured objects can further have their structure and2577connectivity to other objects verified. This is generally done with2578the `git-fsck` program, which generates a full dependency graph2579of all objects, and verifies their internal consistency (in addition2580to just verifying their superficial consistency through the hash).25812582The object types in some more detail:25832584[[blob-object]]2585Blob Object2586-----------25872588A "blob" object is nothing but a binary blob of data, and doesn't2589refer to anything else. There is no signature or any other2590verification of the data, so while the object is consistent (it 'is'2591indexed by its sha1 hash, so the data itself is certainly correct), it2592has absolutely no other attributes. No name associations, no2593permissions. It is purely a blob of data (i.e. normally "file2594contents").25952596In particular, since the blob is entirely defined by its data, if two2597files in a directory tree (or in multiple different versions of the2598repository) have the same contents, they will share the same blob2599object. The object is totally independent of its location in the2600directory tree, and renaming a file does not change the object that2601file is associated with in any way.26022603A blob is typically created when gitlink:git-update-index[1]2604is run, and its data can be accessed by gitlink:git-cat-file[1].26052606[[tree-object]]2607Tree Object2608-----------26092610The next hierarchical object type is the "tree" object. A tree object2611is a list of mode/name/blob data, sorted by name. Alternatively, the2612mode data may specify a directory mode, in which case instead of2613naming a blob, that name is associated with another TREE object.26142615Like the "blob" object, a tree object is uniquely determined by the2616set contents, and so two separate but identical trees will always2617share the exact same object. This is true at all levels, i.e. it's2618true for a "leaf" tree (which does not refer to any other trees, only2619blobs) as well as for a whole subdirectory.26202621For that reason a "tree" object is just a pure data abstraction: it2622has no history, no signatures, no verification of validity, except2623that since the contents are again protected by the hash itself, we can2624trust that the tree is immutable and its contents never change.26252626So you can trust the contents of a tree to be valid, the same way you2627can trust the contents of a blob, but you don't know where those2628contents 'came' from.26292630Side note on trees: since a "tree" object is a sorted list of2631"filename+content", you can create a diff between two trees without2632actually having to unpack two trees. Just ignore all common parts,2633and your diff will look right. In other words, you can effectively2634(and efficiently) tell the difference between any two random trees by2635O(n) where "n" is the size of the difference, rather than the size of2636the tree.26372638Side note 2 on trees: since the name of a "blob" depends entirely and2639exclusively on its contents (i.e. there are no names or permissions2640involved), you can see trivial renames or permission changes by2641noticing that the blob stayed the same. However, renames with data2642changes need a smarter "diff" implementation.26432644A tree is created with gitlink:git-write-tree[1] and2645its data can be accessed by gitlink:git-ls-tree[1].2646Two trees can be compared with gitlink:git-diff-tree[1].26472648[[commit-object]]2649Commit Object2650-------------26512652The "commit" object is an object that introduces the notion of2653history into the picture. In contrast to the other objects, it2654doesn't just describe the physical state of a tree, it describes how2655we got there, and why.26562657A "commit" is defined by the tree-object that it results in, the2658parent commits (zero, one or more) that led up to that point, and a2659comment on what happened. Again, a commit is not trusted per se:2660the contents are well-defined and "safe" due to the cryptographically2661strong signatures at all levels, but there is no reason to believe2662that the tree is "good" or that the merge information makes sense.2663The parents do not have to actually have any relationship with the2664result, for example.26652666Note on commits: unlike some SCM's, commits do not contain2667rename information or file mode change information. All of that is2668implicit in the trees involved (the result tree, and the result trees2669of the parents), and describing that makes no sense in this idiotic2670file manager.26712672A commit is created with gitlink:git-commit-tree[1] and2673its data can be accessed by gitlink:git-cat-file[1].26742675[[trust]]2676Trust2677-----26782679An aside on the notion of "trust". Trust is really outside the scope2680of "git", but it's worth noting a few things. First off, since2681everything is hashed with SHA1, you 'can' trust that an object is2682intact and has not been messed with by external sources. So the name2683of an object uniquely identifies a known state - just not a state that2684you may want to trust.26852686Furthermore, since the SHA1 signature of a commit refers to the2687SHA1 signatures of the tree it is associated with and the signatures2688of the parent, a single named commit specifies uniquely a whole set2689of history, with full contents. You can't later fake any step of the2690way once you have the name of a commit.26912692So to introduce some real trust in the system, the only thing you need2693to do is to digitally sign just 'one' special note, which includes the2694name of a top-level commit. Your digital signature shows others2695that you trust that commit, and the immutability of the history of2696commits tells others that they can trust the whole history.26972698In other words, you can easily validate a whole archive by just2699sending out a single email that tells the people the name (SHA1 hash)2700of the top commit, and digitally sign that email using something2701like GPG/PGP.27022703To assist in this, git also provides the tag object...27042705[[tag-object]]2706Tag Object2707----------27082709Git provides the "tag" object to simplify creating, managing and2710exchanging symbolic and signed tokens. The "tag" object at its2711simplest simply symbolically identifies another object by containing2712the sha1, type and symbolic name.27132714However it can optionally contain additional signature information2715(which git doesn't care about as long as there's less than 8k of2716it). This can then be verified externally to git.27172718Note that despite the tag features, "git" itself only handles content2719integrity; the trust framework (and signature provision and2720verification) has to come from outside.27212722A tag is created with gitlink:git-mktag[1],2723its data can be accessed by gitlink:git-cat-file[1],2724and the signature can be verified by2725gitlink:git-verify-tag[1].272627272728[[the-index]]2729The "index" aka "Current Directory Cache"2730-----------------------------------------27312732The index is a simple binary file, which contains an efficient2733representation of the contents of a virtual directory. It2734does so by a simple array that associates a set of names, dates,2735permissions and content (aka "blob") objects together. The cache is2736always kept ordered by name, and names are unique (with a few very2737specific rules) at any point in time, but the cache has no long-term2738meaning, and can be partially updated at any time.27392740In particular, the index certainly does not need to be consistent with2741the current directory contents (in fact, most operations will depend on2742different ways to make the index 'not' be consistent with the directory2743hierarchy), but it has three very important attributes:27442745'(a) it can re-generate the full state it caches (not just the2746directory structure: it contains pointers to the "blob" objects so2747that it can regenerate the data too)'27482749As a special case, there is a clear and unambiguous one-way mapping2750from a current directory cache to a "tree object", which can be2751efficiently created from just the current directory cache without2752actually looking at any other data. So a directory cache at any one2753time uniquely specifies one and only one "tree" object (but has2754additional data to make it easy to match up that tree object with what2755has happened in the directory)27562757'(b) it has efficient methods for finding inconsistencies between that2758cached state ("tree object waiting to be instantiated") and the2759current state.'27602761'(c) it can additionally efficiently represent information about merge2762conflicts between different tree objects, allowing each pathname to be2763associated with sufficient information about the trees involved that2764you can create a three-way merge between them.'27652766Those are the ONLY three things that the directory cache does. It's a2767cache, and the normal operation is to re-generate it completely from a2768known tree object, or update/compare it with a live tree that is being2769developed. If you blow the directory cache away entirely, you generally2770haven't lost any information as long as you have the name of the tree2771that it described. 27722773At the same time, the index is at the same time also the2774staging area for creating new trees, and creating a new tree always2775involves a controlled modification of the index file. In particular,2776the index file can have the representation of an intermediate tree that2777has not yet been instantiated. So the index can be thought of as a2778write-back cache, which can contain dirty information that has not yet2779been written back to the backing store.2780278127822783[[the-workflow]]2784The Workflow2785------------27862787Generally, all "git" operations work on the index file. Some operations2788work *purely* on the index file (showing the current state of the2789index), but most operations move data to and from the index file. Either2790from the database or from the working directory. Thus there are four2791main combinations: 27922793[[working-directory-to-index]]2794working directory -> index2795~~~~~~~~~~~~~~~~~~~~~~~~~~27962797You update the index with information from the working directory with2798the gitlink:git-update-index[1] command. You2799generally update the index information by just specifying the filename2800you want to update, like so:28012802-------------------------------------------------2803$ git-update-index filename2804-------------------------------------------------28052806but to avoid common mistakes with filename globbing etc, the command2807will not normally add totally new entries or remove old entries,2808i.e. it will normally just update existing cache entries.28092810To tell git that yes, you really do realize that certain files no2811longer exist, or that new files should be added, you2812should use the `--remove` and `--add` flags respectively.28132814NOTE! A `--remove` flag does 'not' mean that subsequent filenames will2815necessarily be removed: if the files still exist in your directory2816structure, the index will be updated with their new status, not2817removed. The only thing `--remove` means is that update-cache will be2818considering a removed file to be a valid thing, and if the file really2819does not exist any more, it will update the index accordingly.28202821As a special case, you can also do `git-update-index --refresh`, which2822will refresh the "stat" information of each index to match the current2823stat information. It will 'not' update the object status itself, and2824it will only update the fields that are used to quickly test whether2825an object still matches its old backing store object.28262827[[index-to-object-database]]2828index -> object database2829~~~~~~~~~~~~~~~~~~~~~~~~28302831You write your current index file to a "tree" object with the program28322833-------------------------------------------------2834$ git-write-tree2835-------------------------------------------------28362837that doesn't come with any options - it will just write out the2838current index into the set of tree objects that describe that state,2839and it will return the name of the resulting top-level tree. You can2840use that tree to re-generate the index at any time by going in the2841other direction:28422843[[object-database-to-index]]2844object database -> index2845~~~~~~~~~~~~~~~~~~~~~~~~28462847You read a "tree" file from the object database, and use that to2848populate (and overwrite - don't do this if your index contains any2849unsaved state that you might want to restore later!) your current2850index. Normal operation is just28512852-------------------------------------------------2853$ git-read-tree <sha1 of tree>2854-------------------------------------------------28552856and your index file will now be equivalent to the tree that you saved2857earlier. However, that is only your 'index' file: your working2858directory contents have not been modified.28592860[[index-to-working-directory]]2861index -> working directory2862~~~~~~~~~~~~~~~~~~~~~~~~~~28632864You update your working directory from the index by "checking out"2865files. This is not a very common operation, since normally you'd just2866keep your files updated, and rather than write to your working2867directory, you'd tell the index files about the changes in your2868working directory (i.e. `git-update-index`).28692870However, if you decide to jump to a new version, or check out somebody2871else's version, or just restore a previous tree, you'd populate your2872index file with read-tree, and then you need to check out the result2873with28742875-------------------------------------------------2876$ git-checkout-index filename2877-------------------------------------------------28782879or, if you want to check out all of the index, use `-a`.28802881NOTE! git-checkout-index normally refuses to overwrite old files, so2882if you have an old version of the tree already checked out, you will2883need to use the "-f" flag ('before' the "-a" flag or the filename) to2884'force' the checkout.288528862887Finally, there are a few odds and ends which are not purely moving2888from one representation to the other:28892890[[tying-it-all-together]]2891Tying it all together2892~~~~~~~~~~~~~~~~~~~~~28932894To commit a tree you have instantiated with "git-write-tree", you'd2895create a "commit" object that refers to that tree and the history2896behind it - most notably the "parent" commits that preceded it in2897history.28982899Normally a "commit" has one parent: the previous state of the tree2900before a certain change was made. However, sometimes it can have two2901or more parent commits, in which case we call it a "merge", due to the2902fact that such a commit brings together ("merges") two or more2903previous states represented by other commits.29042905In other words, while a "tree" represents a particular directory state2906of a working directory, a "commit" represents that state in "time",2907and explains how we got there.29082909You create a commit object by giving it the tree that describes the2910state at the time of the commit, and a list of parents:29112912-------------------------------------------------2913$ git-commit-tree <tree> -p <parent> [-p <parent2> ..]2914-------------------------------------------------29152916and then giving the reason for the commit on stdin (either through2917redirection from a pipe or file, or by just typing it at the tty).29182919git-commit-tree will return the name of the object that represents2920that commit, and you should save it away for later use. Normally,2921you'd commit a new `HEAD` state, and while git doesn't care where you2922save the note about that state, in practice we tend to just write the2923result to the file pointed at by `.git/HEAD`, so that we can always see2924what the last committed state was.29252926Here is an ASCII art by Jon Loeliger that illustrates how2927various pieces fit together.29282929------------29302931 commit-tree2932 commit obj2933 +----+2934 | |2935 | |2936 V V2937 +-----------+2938 | Object DB |2939 | Backing |2940 | Store |2941 +-----------+2942 ^2943 write-tree | |2944 tree obj | |2945 | | read-tree2946 | | tree obj2947 V2948 +-----------+2949 | Index |2950 | "cache" |2951 +-----------+2952 update-index ^2953 blob obj | |2954 | |2955 checkout-index -u | | checkout-index2956 stat | | blob obj2957 V2958 +-----------+2959 | Working |2960 | Directory |2961 +-----------+29622963------------296429652966[[examining-the-data]]2967Examining the data2968------------------29692970You can examine the data represented in the object database and the2971index with various helper tools. For every object, you can use2972gitlink:git-cat-file[1] to examine details about the2973object:29742975-------------------------------------------------2976$ git-cat-file -t <objectname>2977-------------------------------------------------29782979shows the type of the object, and once you have the type (which is2980usually implicit in where you find the object), you can use29812982-------------------------------------------------2983$ git-cat-file blob|tree|commit|tag <objectname>2984-------------------------------------------------29852986to show its contents. NOTE! Trees have binary content, and as a result2987there is a special helper for showing that content, called2988`git-ls-tree`, which turns the binary content into a more easily2989readable form.29902991It's especially instructive to look at "commit" objects, since those2992tend to be small and fairly self-explanatory. In particular, if you2993follow the convention of having the top commit name in `.git/HEAD`,2994you can do29952996-------------------------------------------------2997$ git-cat-file commit HEAD2998-------------------------------------------------29993000to see what the top commit was.30013002[[merging-multiple-trees]]3003Merging multiple trees3004----------------------30053006Git helps you do a three-way merge, which you can expand to n-way by3007repeating the merge procedure arbitrary times until you finally3008"commit" the state. The normal situation is that you'd only do one3009three-way merge (two parents), and commit it, but if you like to, you3010can do multiple parents in one go.30113012To do a three-way merge, you need the two sets of "commit" objects3013that you want to merge, use those to find the closest common parent (a3014third "commit" object), and then use those commit objects to find the3015state of the directory ("tree" object) at these points.30163017To get the "base" for the merge, you first look up the common parent3018of two commits with30193020-------------------------------------------------3021$ git-merge-base <commit1> <commit2>3022-------------------------------------------------30233024which will return you the commit they are both based on. You should3025now look up the "tree" objects of those commits, which you can easily3026do with (for example)30273028-------------------------------------------------3029$ git-cat-file commit <commitname> | head -13030-------------------------------------------------30313032since the tree object information is always the first line in a commit3033object.30343035Once you know the three trees you are going to merge (the one "original"3036tree, aka the common tree, and the two "result" trees, aka the branches3037you want to merge), you do a "merge" read into the index. This will3038complain if it has to throw away your old index contents, so you should3039make sure that you've committed those - in fact you would normally3040always do a merge against your last commit (which should thus match what3041you have in your current index anyway).30423043To do the merge, do30443045-------------------------------------------------3046$ git-read-tree -m -u <origtree> <yourtree> <targettree>3047-------------------------------------------------30483049which will do all trivial merge operations for you directly in the3050index file, and you can just write the result out with3051`git-write-tree`.305230533054[[merging-multiple-trees-2]]3055Merging multiple trees, continued3056---------------------------------30573058Sadly, many merges aren't trivial. If there are files that have3059been added.moved or removed, or if both branches have modified the3060same file, you will be left with an index tree that contains "merge3061entries" in it. Such an index tree can 'NOT' be written out to a tree3062object, and you will have to resolve any such merge clashes using3063other tools before you can write out the result.30643065You can examine such index state with `git-ls-files --unmerged`3066command. An example:30673068------------------------------------------------3069$ git-read-tree -m $orig HEAD $target3070$ git-ls-files --unmerged3071100644 263414f423d0e4d70dae8fe53fa34614ff3e2860 1 hello.c3072100644 06fa6a24256dc7e560efa5687fa84b51f0263c3a 2 hello.c3073100644 cc44c73eb783565da5831b4d820c962954019b69 3 hello.c3074------------------------------------------------30753076Each line of the `git-ls-files --unmerged` output begins with3077the blob mode bits, blob SHA1, 'stage number', and the3078filename. The 'stage number' is git's way to say which tree it3079came from: stage 1 corresponds to `$orig` tree, stage 2 `HEAD`3080tree, and stage3 `$target` tree.30813082Earlier we said that trivial merges are done inside3083`git-read-tree -m`. For example, if the file did not change3084from `$orig` to `HEAD` nor `$target`, or if the file changed3085from `$orig` to `HEAD` and `$orig` to `$target` the same way,3086obviously the final outcome is what is in `HEAD`. What the3087above example shows is that file `hello.c` was changed from3088`$orig` to `HEAD` and `$orig` to `$target` in a different way.3089You could resolve this by running your favorite 3-way merge3090program, e.g. `diff3`, `merge`, or git's own merge-file, on3091the blob objects from these three stages yourself, like this:30923093------------------------------------------------3094$ git-cat-file blob 263414f... >hello.c~13095$ git-cat-file blob 06fa6a2... >hello.c~23096$ git-cat-file blob cc44c73... >hello.c~33097$ git merge-file hello.c~2 hello.c~1 hello.c~33098------------------------------------------------30993100This would leave the merge result in `hello.c~2` file, along3101with conflict markers if there are conflicts. After verifying3102the merge result makes sense, you can tell git what the final3103merge result for this file is by:31043105-------------------------------------------------3106$ mv -f hello.c~2 hello.c3107$ git-update-index hello.c3108-------------------------------------------------31093110When a path is in unmerged state, running `git-update-index` for3111that path tells git to mark the path resolved.31123113The above is the description of a git merge at the lowest level,3114to help you understand what conceptually happens under the hood.3115In practice, nobody, not even git itself, uses three `git-cat-file`3116for this. There is `git-merge-index` program that extracts the3117stages to temporary files and calls a "merge" script on it:31183119-------------------------------------------------3120$ git-merge-index git-merge-one-file hello.c3121-------------------------------------------------31223123and that is what higher level `git merge -s resolve` is implemented with.31243125[[pack-files]]3126How git stores objects efficiently: pack files3127----------------------------------------------31283129We've seen how git stores each object in a file named after the3130object's SHA1 hash.31313132Unfortunately this system becomes inefficient once a project has a3133lot of objects. Try this on an old project:31343135------------------------------------------------3136$ git count-objects31376930 objects, 47620 kilobytes3138------------------------------------------------31393140The first number is the number of objects which are kept in3141individual files. The second is the amount of space taken up by3142those "loose" objects.31433144You can save space and make git faster by moving these loose objects in3145to a "pack file", which stores a group of objects in an efficient3146compressed format; the details of how pack files are formatted can be3147found in link:technical/pack-format.txt[technical/pack-format.txt].31483149To put the loose objects into a pack, just run git repack:31503151------------------------------------------------3152$ git repack3153Generating pack...3154Done counting 6020 objects.3155Deltifying 6020 objects.3156 100% (6020/6020) done3157Writing 6020 objects.3158 100% (6020/6020) done3159Total 6020, written 6020 (delta 4070), reused 0 (delta 0)3160Pack pack-3e54ad29d5b2e05838c75df582c65257b8d08e1c created.3161------------------------------------------------31623163You can then run31643165------------------------------------------------3166$ git prune3167------------------------------------------------31683169to remove any of the "loose" objects that are now contained in the3170pack. This will also remove any unreferenced objects (which may be3171created when, for example, you use "git reset" to remove a commit).3172You can verify that the loose objects are gone by looking at the3173.git/objects directory or by running31743175------------------------------------------------3176$ git count-objects31770 objects, 0 kilobytes3178------------------------------------------------31793180Although the object files are gone, any commands that refer to those3181objects will work exactly as they did before.31823183The gitlink:git-gc[1] command performs packing, pruning, and more for3184you, so is normally the only high-level command you need.31853186[[dangling-objects]]3187Dangling objects3188----------------31893190The gitlink:git-fsck[1] command will sometimes complain about dangling3191objects. They are not a problem.31923193The most common cause of dangling objects is that you've rebased a3194branch, or you have pulled from somebody else who rebased a branch--see3195<<cleaning-up-history>>. In that case, the old head of the original3196branch still exists, as does everything it pointed to. The branch3197pointer itself just doesn't, since you replaced it with another one.31983199There are also other situations that cause dangling objects. For3200example, a "dangling blob" may arise because you did a "git add" of a3201file, but then, before you actually committed it and made it part of the3202bigger picture, you changed something else in that file and committed3203that *updated* thing - the old state that you added originally ends up3204not being pointed to by any commit or tree, so it's now a dangling blob3205object.32063207Similarly, when the "recursive" merge strategy runs, and finds that3208there are criss-cross merges and thus more than one merge base (which is3209fairly unusual, but it does happen), it will generate one temporary3210midway tree (or possibly even more, if you had lots of criss-crossing3211merges and more than two merge bases) as a temporary internal merge3212base, and again, those are real objects, but the end result will not end3213up pointing to them, so they end up "dangling" in your repository.32143215Generally, dangling objects aren't anything to worry about. They can3216even be very useful: if you screw something up, the dangling objects can3217be how you recover your old tree (say, you did a rebase, and realized3218that you really didn't want to - you can look at what dangling objects3219you have, and decide to reset your head to some old dangling state).32203221For commits, you can just use:32223223------------------------------------------------3224$ gitk <dangling-commit-sha-goes-here> --not --all3225------------------------------------------------32263227This asks for all the history reachable from the given commit but not3228from any branch, tag, or other reference. If you decide it's something3229you want, you can always create a new reference to it, e.g.,32303231------------------------------------------------3232$ git branch recovered-branch <dangling-commit-sha-goes-here>3233------------------------------------------------32343235For blobs and trees, you can't do the same, but you can still examine3236them. You can just do32373238------------------------------------------------3239$ git show <dangling-blob/tree-sha-goes-here>3240------------------------------------------------32413242to show what the contents of the blob were (or, for a tree, basically3243what the "ls" for that directory was), and that may give you some idea3244of what the operation was that left that dangling object.32453246Usually, dangling blobs and trees aren't very interesting. They're3247almost always the result of either being a half-way mergebase (the blob3248will often even have the conflict markers from a merge in it, if you3249have had conflicting merges that you fixed up by hand), or simply3250because you interrupted a "git fetch" with ^C or something like that,3251leaving _some_ of the new objects in the object database, but just3252dangling and useless.32533254Anyway, once you are sure that you're not interested in any dangling 3255state, you can just prune all unreachable objects:32563257------------------------------------------------3258$ git prune3259------------------------------------------------32603261and they'll be gone. But you should only run "git prune" on a quiescent3262repository - it's kind of like doing a filesystem fsck recovery: you3263don't want to do that while the filesystem is mounted.32643265(The same is true of "git-fsck" itself, btw - but since 3266git-fsck never actually *changes* the repository, it just reports 3267on what it found, git-fsck itself is never "dangerous" to run. 3268Running it while somebody is actually changing the repository can cause 3269confusing and scary messages, but it won't actually do anything bad. In 3270contrast, running "git prune" while somebody is actively changing the 3271repository is a *BAD* idea).32723273[[birdview-on-the-source-code]]3274A birds-eye view of Git's source code3275-------------------------------------32763277It is not always easy for new developers to find their way through Git's3278source code. This section gives you a little guidance to show where to3279start.32803281A good place to start is with the contents of the initial commit, with:32823283----------------------------------------------------3284$ git checkout e83c51633285----------------------------------------------------32863287The initial revision lays the foundation for almost everything git has3288today, but is small enough to read in one sitting.32893290Note that terminology has changed since that revision. For example, the3291README in that revision uses the word "changeset" to describe what we3292now call a <<def_commit_object,commit>>.32933294Also, we do not call it "cache" any more, but "index", however, the3295file is still called `cache.h`. Remark: Not much reason to change it now,3296especially since there is no good single name for it anyway, because it is3297basically _the_ header file which is included by _all_ of Git's C sources.32983299If you grasp the ideas in that initial commit, you should check out a3300more recent version and skim `cache.h`, `object.h` and `commit.h`.33013302In the early days, Git (in the tradition of UNIX) was a bunch of programs3303which were extremely simple, and which you used in scripts, piping the3304output of one into another. This turned out to be good for initial3305development, since it was easier to test new things. However, recently3306many of these parts have become builtins, and some of the core has been3307"libified", i.e. put into libgit.a for performance, portability reasons,3308and to avoid code duplication.33093310By now, you know what the index is (and find the corresponding data3311structures in `cache.h`), and that there are just a couple of object types3312(blobs, trees, commits and tags) which inherit their common structure from3313`struct object`, which is their first member (and thus, you can cast e.g.3314`(struct object *)commit` to achieve the _same_ as `&commit->object`, i.e.3315get at the object name and flags).33163317Now is a good point to take a break to let this information sink in.33183319Next step: get familiar with the object naming. Read <<naming-commits>>.3320There are quite a few ways to name an object (and not only revisions!).3321All of these are handled in `sha1_name.c`. Just have a quick look at3322the function `get_sha1()`. A lot of the special handling is done by3323functions like `get_sha1_basic()` or the likes.33243325This is just to get you into the groove for the most libified part of Git:3326the revision walker.33273328Basically, the initial version of `git log` was a shell script:33293330----------------------------------------------------------------3331$ git-rev-list --pretty $(git-rev-parse --default HEAD "$@") | \3332 LESS=-S ${PAGER:-less}3333----------------------------------------------------------------33343335What does this mean?33363337`git-rev-list` is the original version of the revision walker, which3338_always_ printed a list of revisions to stdout. It is still functional,3339and needs to, since most new Git programs start out as scripts using3340`git-rev-list`.33413342`git-rev-parse` is not as important any more; it was only used to filter out3343options that were relevant for the different plumbing commands that were3344called by the script.33453346Most of what `git-rev-list` did is contained in `revision.c` and3347`revision.h`. It wraps the options in a struct named `rev_info`, which3348controls how and what revisions are walked, and more.33493350The original job of `git-rev-parse` is now taken by the function3351`setup_revisions()`, which parses the revisions and the common command line3352options for the revision walker. This information is stored in the struct3353`rev_info` for later consumption. You can do your own command line option3354parsing after calling `setup_revisions()`. After that, you have to call3355`prepare_revision_walk()` for initialization, and then you can get the3356commits one by one with the function `get_revision()`.33573358If you are interested in more details of the revision walking process,3359just have a look at the first implementation of `cmd_log()`; call3360`git-show v1.3.0~155^2~4` and scroll down to that function (note that you3361no longer need to call `setup_pager()` directly).33623363Nowadays, `git log` is a builtin, which means that it is _contained_ in the3364command `git`. The source side of a builtin is33653366- a function called `cmd_<bla>`, typically defined in `builtin-<bla>.c`,3367 and declared in `builtin.h`,33683369- an entry in the `commands[]` array in `git.c`, and33703371- an entry in `BUILTIN_OBJECTS` in the `Makefile`.33723373Sometimes, more than one builtin is contained in one source file. For3374example, `cmd_whatchanged()` and `cmd_log()` both reside in `builtin-log.c`,3375since they share quite a bit of code. In that case, the commands which are3376_not_ named like the `.c` file in which they live have to be listed in3377`BUILT_INS` in the `Makefile`.33783379`git log` looks more complicated in C than it does in the original script,3380but that allows for a much greater flexibility and performance.33813382Here again it is a good point to take a pause.33833384Lesson three is: study the code. Really, it is the best way to learn about3385the organization of Git (after you know the basic concepts).33863387So, think about something which you are interested in, say, "how can I3388access a blob just knowing the object name of it?". The first step is to3389find a Git command with which you can do it. In this example, it is either3390`git show` or `git cat-file`.33913392For the sake of clarity, let's stay with `git cat-file`, because it33933394- is plumbing, and33953396- was around even in the initial commit (it literally went only through3397 some 20 revisions as `cat-file.c`, was renamed to `builtin-cat-file.c`3398 when made a builtin, and then saw less than 10 versions).33993400So, look into `builtin-cat-file.c`, search for `cmd_cat_file()` and look what3401it does.34023403------------------------------------------------------------------3404 git_config(git_default_config);3405 if (argc != 3)3406 usage("git-cat-file [-t|-s|-e|-p|<type>] <sha1>");3407 if (get_sha1(argv[2], sha1))3408 die("Not a valid object name %s", argv[2]);3409------------------------------------------------------------------34103411Let's skip over the obvious details; the only really interesting part3412here is the call to `get_sha1()`. It tries to interpret `argv[2]` as an3413object name, and if it refers to an object which is present in the current3414repository, it writes the resulting SHA-1 into the variable `sha1`.34153416Two things are interesting here:34173418- `get_sha1()` returns 0 on _success_. This might surprise some new3419 Git hackers, but there is a long tradition in UNIX to return different3420 negative numbers in case of different errors -- and 0 on success.34213422- the variable `sha1` in the function signature of `get_sha1()` is `unsigned3423 char \*`, but is actually expected to be a pointer to `unsigned3424 char[20]`. This variable will contain the 160-bit SHA-1 of the given3425 commit. Note that whenever a SHA-1 is passed as `unsigned char \*`, it3426 is the binary representation, as opposed to the ASCII representation in3427 hex characters, which is passed as `char *`.34283429You will see both of these things throughout the code.34303431Now, for the meat:34323433-----------------------------------------------------------------------------3434 case 0:3435 buf = read_object_with_reference(sha1, argv[1], &size, NULL);3436-----------------------------------------------------------------------------34373438This is how you read a blob (actually, not only a blob, but any type of3439object). To know how the function `read_object_with_reference()` actually3440works, find the source code for it (something like `git grep3441read_object_with | grep ":[a-z]"` in the git repository), and read3442the source.34433444To find out how the result can be used, just read on in `cmd_cat_file()`:34453446-----------------------------------3447 write_or_die(1, buf, size);3448-----------------------------------34493450Sometimes, you do not know where to look for a feature. In many such cases,3451it helps to search through the output of `git log`, and then `git show` the3452corresponding commit.34533454Example: If you know that there was some test case for `git bundle`, but3455do not remember where it was (yes, you _could_ `git grep bundle t/`, but that3456does not illustrate the point!):34573458------------------------3459$ git log --no-merges t/3460------------------------34613462In the pager (`less`), just search for "bundle", go a few lines back,3463and see that it is in commit 18449ab0... Now just copy this object name,3464and paste it into the command line34653466-------------------3467$ git show 18449ab03468-------------------34693470Voila.34713472Another example: Find out what to do in order to make some script a3473builtin:34743475-------------------------------------------------3476$ git log --no-merges --diff-filter=A builtin-*.c3477-------------------------------------------------34783479You see, Git is actually the best tool to find out about the source of Git3480itself!34813482[[glossary]]3483include::glossary.txt[]34843485[[git-quick-start]]3486Appendix A: Git Quick Start3487===========================34883489This is a quick summary of the major commands; the following chapters3490will explain how these work in more detail.34913492[[quick-creating-a-new-repository]]3493Creating a new repository3494-------------------------34953496From a tarball:34973498-----------------------------------------------3499$ tar xzf project.tar.gz3500$ cd project3501$ git init3502Initialized empty Git repository in .git/3503$ git add .3504$ git commit3505-----------------------------------------------35063507From a remote repository:35083509-----------------------------------------------3510$ git clone git://example.com/pub/project.git3511$ cd project3512-----------------------------------------------35133514[[managing-branches]]3515Managing branches3516-----------------35173518-----------------------------------------------3519$ git branch # list all local branches in this repo3520$ git checkout test # switch working directory to branch "test"3521$ git branch new # create branch "new" starting at current HEAD3522$ git branch -d new # delete branch "new"3523-----------------------------------------------35243525Instead of basing new branch on current HEAD (the default), use:35263527-----------------------------------------------3528$ git branch new test # branch named "test"3529$ git branch new v2.6.15 # tag named v2.6.153530$ git branch new HEAD^ # commit before the most recent3531$ git branch new HEAD^^ # commit before that3532$ git branch new test~10 # ten commits before tip of branch "test"3533-----------------------------------------------35343535Create and switch to a new branch at the same time:35363537-----------------------------------------------3538$ git checkout -b new v2.6.153539-----------------------------------------------35403541Update and examine branches from the repository you cloned from:35423543-----------------------------------------------3544$ git fetch # update3545$ git branch -r # list3546 origin/master3547 origin/next3548 ...3549$ git checkout -b masterwork origin/master3550-----------------------------------------------35513552Fetch a branch from a different repository, and give it a new3553name in your repository:35543555-----------------------------------------------3556$ git fetch git://example.com/project.git theirbranch:mybranch3557$ git fetch git://example.com/project.git v2.6.15:mybranch3558-----------------------------------------------35593560Keep a list of repositories you work with regularly:35613562-----------------------------------------------3563$ git remote add example git://example.com/project.git3564$ git remote # list remote repositories3565example3566origin3567$ git remote show example # get details3568* remote example3569 URL: git://example.com/project.git3570 Tracked remote branches3571 master next ...3572$ git fetch example # update branches from example3573$ git branch -r # list all remote branches3574-----------------------------------------------357535763577[[exploring-history]]3578Exploring history3579-----------------35803581-----------------------------------------------3582$ gitk # visualize and browse history3583$ git log # list all commits3584$ git log src/ # ...modifying src/3585$ git log v2.6.15..v2.6.16 # ...in v2.6.16, not in v2.6.153586$ git log master..test # ...in branch test, not in branch master3587$ git log test..master # ...in branch master, but not in test3588$ git log test...master # ...in one branch, not in both3589$ git log -S'foo()' # ...where difference contain "foo()"3590$ git log --since="2 weeks ago"3591$ git log -p # show patches as well3592$ git show # most recent commit3593$ git diff v2.6.15..v2.6.16 # diff between two tagged versions3594$ git diff v2.6.15..HEAD # diff with current head3595$ git grep "foo()" # search working directory for "foo()"3596$ git grep v2.6.15 "foo()" # search old tree for "foo()"3597$ git show v2.6.15:a.txt # look at old version of a.txt3598-----------------------------------------------35993600Search for regressions:36013602-----------------------------------------------3603$ git bisect start3604$ git bisect bad # current version is bad3605$ git bisect good v2.6.13-rc2 # last known good revision3606Bisecting: 675 revisions left to test after this3607 # test here, then:3608$ git bisect good # if this revision is good, or3609$ git bisect bad # if this revision is bad.3610 # repeat until done.3611-----------------------------------------------36123613[[making-changes]]3614Making changes3615--------------36163617Make sure git knows who to blame:36183619------------------------------------------------3620$ cat >>~/.gitconfig <<\EOF3621[user]3622 name = Your Name Comes Here3623 email = you@yourdomain.example.com3624EOF3625------------------------------------------------36263627Select file contents to include in the next commit, then make the3628commit:36293630-----------------------------------------------3631$ git add a.txt # updated file3632$ git add b.txt # new file3633$ git rm c.txt # old file3634$ git commit3635-----------------------------------------------36363637Or, prepare and create the commit in one step:36383639-----------------------------------------------3640$ git commit d.txt # use latest content only of d.txt3641$ git commit -a # use latest content of all tracked files3642-----------------------------------------------36433644[[merging]]3645Merging3646-------36473648-----------------------------------------------3649$ git merge test # merge branch "test" into the current branch3650$ git pull git://example.com/project.git master3651 # fetch and merge in remote branch3652$ git pull . test # equivalent to git merge test3653-----------------------------------------------36543655[[sharing-your-changes]]3656Sharing your changes3657--------------------36583659Importing or exporting patches:36603661-----------------------------------------------3662$ git format-patch origin..HEAD # format a patch for each commit3663 # in HEAD but not in origin3664$ git am mbox # import patches from the mailbox "mbox"3665-----------------------------------------------36663667Fetch a branch in a different git repository, then merge into the3668current branch:36693670-----------------------------------------------3671$ git pull git://example.com/project.git theirbranch3672-----------------------------------------------36733674Store the fetched branch into a local branch before merging into the3675current branch:36763677-----------------------------------------------3678$ git pull git://example.com/project.git theirbranch:mybranch3679-----------------------------------------------36803681After creating commits on a local branch, update the remote3682branch with your commits:36833684-----------------------------------------------3685$ git push ssh://example.com/project.git mybranch:theirbranch3686-----------------------------------------------36873688When remote and local branch are both named "test":36893690-----------------------------------------------3691$ git push ssh://example.com/project.git test3692-----------------------------------------------36933694Shortcut version for a frequently used remote repository:36953696-----------------------------------------------3697$ git remote add example ssh://example.com/project.git3698$ git push example test3699-----------------------------------------------37003701[[repository-maintenance]]3702Repository maintenance3703----------------------37043705Check for corruption:37063707-----------------------------------------------3708$ git fsck3709-----------------------------------------------37103711Recompress, remove unused cruft:37123713-----------------------------------------------3714$ git gc3715-----------------------------------------------371637173718[[todo]]3719Appendix B: Notes and todo list for this manual3720===============================================37213722This is a work in progress.37233724The basic requirements:3725 - It must be readable in order, from beginning to end, by3726 someone intelligent with a basic grasp of the unix3727 commandline, but without any special knowledge of git. If3728 necessary, any other prerequisites should be specifically3729 mentioned as they arise.3730 - Whenever possible, section headings should clearly describe3731 the task they explain how to do, in language that requires3732 no more knowledge than necessary: for example, "importing3733 patches into a project" rather than "the git-am command"37343735Think about how to create a clear chapter dependency graph that will3736allow people to get to important topics without necessarily reading3737everything in between.37383739Say something about .gitignore.37403741Scan Documentation/ for other stuff left out; in particular:3742 howto's3743 some of technical/?3744 hooks3745 list of commands in gitlink:git[1]37463747Scan email archives for other stuff left out37483749Scan man pages to see if any assume more background than this manual3750provides.37513752Simplify beginning by suggesting disconnected head instead of3753temporary branch creation?37543755Add more good examples. Entire sections of just cookbook examples3756might be a good idea; maybe make an "advanced examples" section a3757standard end-of-chapter section?37583759Include cross-references to the glossary, where appropriate.37603761Document shallow clones? See draft 1.5.0 release notes for some3762documentation.37633764Add a section on working with other version control systems, including3765CVS, Subversion, and just imports of series of release tarballs.37663767More details on gitweb?37683769Write a chapter on using plumbing and writing scripts.