1Git User's Manual (for version 1.5.3 or newer) 2______________________________________________ 3 4 5Git is a fast distributed revision control system. 6 7This manual is designed to be readable by someone with basic UNIX 8command-line skills, but no previous knowledge of git. 9 10<<repositories-and-branches>> and <<exploring-git-history>> explain how 11to fetch and study a project using git--read these chapters to learn how 12to build and test a particular version of a software project, search for 13regressions, and so on. 14 15People needing to do actual development will also want to read 16<<Developing-with-git>> and <<sharing-development>>. 17 18Further chapters cover more specialized topics. 19 20Comprehensive reference documentation is available through the man 21pages. For a command such as "git clone", just use 22 23------------------------------------------------ 24$ man git-clone 25------------------------------------------------ 26 27See also <<git-quick-start>> for a brief overview of git commands, 28without any explanation. 29 30Finally, see <<todo>> for ways that you can help make this manual more 31complete. 32 33 34[[repositories-and-branches]] 35Repositories and Branches 36========================= 37 38[[how-to-get-a-git-repository]] 39How to get a git repository 40--------------------------- 41 42It will be useful to have a git repository to experiment with as you 43read this manual. 44 45The best way to get one is by using the gitlink:git-clone[1] command to 46download a copy of an existing repository. If you don't already have a 47project in mind, here are some interesting examples: 48 49------------------------------------------------ 50 # git itself (approx. 10MB download): 51$ git clone git://git.kernel.org/pub/scm/git/git.git 52 # the linux kernel (approx. 150MB download): 53$ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git 54------------------------------------------------ 55 56The initial clone may be time-consuming for a large project, but you 57will only need to clone once. 58 59The clone command creates a new directory named after the project 60("git" or "linux-2.6" in the examples above). After you cd into this 61directory, you will see that it contains a copy of the project files, 62together with a special top-level directory named ".git", which 63contains all the information about the history of the project. 64 65[[how-to-check-out]] 66How to check out a different version of a project 67------------------------------------------------- 68 69Git is best thought of as a tool for storing the history of a collection 70of files. It stores the history as a compressed collection of 71interrelated snapshots of the project's contents. In git each such 72version is called a <<def_commit,commit>>. 73 74A single git repository may contain multiple branches. It keeps track 75of them by keeping a list of <<def_head,heads>> which reference the 76latest commit on each branch; the gitlink:git-branch[1] command shows 77you the list of branch heads: 78 79------------------------------------------------ 80$ git branch 81* master 82------------------------------------------------ 83 84A freshly cloned repository contains a single branch head, by default 85named "master", with the working directory initialized to the state of 86the project referred to by that branch head. 87 88Most projects also use <<def_tag,tags>>. Tags, like heads, are 89references into the project's history, and can be listed using the 90gitlink:git-tag[1] command: 91 92------------------------------------------------ 93$ git tag -l 94v2.6.11 95v2.6.11-tree 96v2.6.12 97v2.6.12-rc2 98v2.6.12-rc3 99v2.6.12-rc4 100v2.6.12-rc5 101v2.6.12-rc6 102v2.6.13 103... 104------------------------------------------------ 105 106Tags are expected to always point at the same version of a project, 107while heads are expected to advance as development progresses. 108 109Create a new branch head pointing to one of these versions and check it 110out using gitlink:git-checkout[1]: 111 112------------------------------------------------ 113$ git checkout -b new v2.6.13 114------------------------------------------------ 115 116The working directory then reflects the contents that the project had 117when it was tagged v2.6.13, and gitlink:git-branch[1] shows two 118branches, with an asterisk marking the currently checked-out branch: 119 120------------------------------------------------ 121$ git branch 122 master 123* new 124------------------------------------------------ 125 126If you decide that you'd rather see version 2.6.17, you can modify 127the current branch to point at v2.6.17 instead, with 128 129------------------------------------------------ 130$ git reset --hard v2.6.17 131------------------------------------------------ 132 133Note that if the current branch head was your only reference to a 134particular point in history, then resetting that branch may leave you 135with no way to find the history it used to point to; so use this command 136carefully. 137 138[[understanding-commits]] 139Understanding History: Commits 140------------------------------ 141 142Every change in the history of a project is represented by a commit. 143The gitlink:git-show[1] command shows the most recent commit on the 144current branch: 145 146------------------------------------------------ 147$ git show 148commit 17cf781661e6d38f737f15f53ab552f1e95960d7 149Author: Linus Torvalds <torvalds@ppc970.osdl.org.(none)> 150Date: Tue Apr 19 14:11:06 2005 -0700 151 152 Remove duplicate getenv(DB_ENVIRONMENT) call 153 154 Noted by Tony Luck. 155 156diff --git a/init-db.c b/init-db.c 157index 65898fa..b002dc6 100644 158--- a/init-db.c 159+++ b/init-db.c 160@@ -7,7 +7,7 @@ 161 162 int main(int argc, char **argv) 163 { 164- char *sha1_dir = getenv(DB_ENVIRONMENT), *path; 165+ char *sha1_dir, *path; 166 int len, i; 167 168 if (mkdir(".git", 0755) < 0) { 169------------------------------------------------ 170 171As you can see, a commit shows who made the latest change, what they 172did, and why. 173 174Every commit has a 40-hexdigit id, sometimes called the "object name" or the 175"SHA1 id", shown on the first line of the "git show" output. You can usually 176refer to a commit by a shorter name, such as a tag or a branch name, but this 177longer name can also be useful. Most importantly, it is a globally unique 178name for this commit: so if you tell somebody else the object name (for 179example in email), then you are guaranteed that name will refer to the same 180commit in their repository that it does in yours (assuming their repository 181has that commit at all). Since the object name is computed as a hash over the 182contents of the commit, you are guaranteed that the commit can never change 183without its name also changing. 184 185In fact, in <<git-concepts>> we shall see that everything stored in git 186history, including file data and directory contents, is stored in an object 187with a name that is a hash of its contents. 188 189[[understanding-reachability]] 190Understanding history: commits, parents, and reachability 191~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 192 193Every commit (except the very first commit in a project) also has a 194parent commit which shows what happened before this commit. 195Following the chain of parents will eventually take you back to the 196beginning of the project. 197 198However, the commits do not form a simple list; git allows lines of 199development to diverge and then reconverge, and the point where two 200lines of development reconverge is called a "merge". The commit 201representing a merge can therefore have more than one parent, with 202each parent representing the most recent commit on one of the lines 203of development leading to that point. 204 205The best way to see how this works is using the gitlink:gitk[1] 206command; running gitk now on a git repository and looking for merge 207commits will help understand how the git organizes history. 208 209In the following, we say that commit X is "reachable" from commit Y 210if commit X is an ancestor of commit Y. Equivalently, you could say 211that Y is a descendant of X, or that there is a chain of parents 212leading from commit Y to commit X. 213 214[[history-diagrams]] 215Understanding history: History diagrams 216~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 217 218We will sometimes represent git history using diagrams like the one 219below. Commits are shown as "o", and the links between them with 220lines drawn with - / and \. Time goes left to right: 221 222 223................................................ 224 o--o--o <-- Branch A 225 / 226 o--o--o <-- master 227 \ 228 o--o--o <-- Branch B 229................................................ 230 231If we need to talk about a particular commit, the character "o" may 232be replaced with another letter or number. 233 234[[what-is-a-branch]] 235Understanding history: What is a branch? 236~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 237 238When we need to be precise, we will use the word "branch" to mean a line 239of development, and "branch head" (or just "head") to mean a reference 240to the most recent commit on a branch. In the example above, the branch 241head named "A" is a pointer to one particular commit, but we refer to 242the line of three commits leading up to that point as all being part of 243"branch A". 244 245However, when no confusion will result, we often just use the term 246"branch" both for branches and for branch heads. 247 248[[manipulating-branches]] 249Manipulating branches 250--------------------- 251 252Creating, deleting, and modifying branches is quick and easy; here's 253a summary of the commands: 254 255git branch:: 256 list all branches 257git branch <branch>:: 258 create a new branch named <branch>, referencing the same 259 point in history as the current branch 260git branch <branch> <start-point>:: 261 create a new branch named <branch>, referencing 262 <start-point>, which may be specified any way you like, 263 including using a branch name or a tag name 264git branch -d <branch>:: 265 delete the branch <branch>; if the branch you are deleting 266 points to a commit which is not reachable from the current 267 branch, this command will fail with a warning. 268git branch -D <branch>:: 269 even if the branch points to a commit not reachable 270 from the current branch, you may know that that commit 271 is still reachable from some other branch or tag. In that 272 case it is safe to use this command to force git to delete 273 the branch. 274git checkout <branch>:: 275 make the current branch <branch>, updating the working 276 directory to reflect the version referenced by <branch> 277git checkout -b <new> <start-point>:: 278 create a new branch <new> referencing <start-point>, and 279 check it out. 280 281The special symbol "HEAD" can always be used to refer to the current 282branch. In fact, git uses a file named "HEAD" in the .git directory to 283remember which branch is current: 284 285------------------------------------------------ 286$ cat .git/HEAD 287ref: refs/heads/master 288------------------------------------------------ 289 290[[detached-head]] 291Examining an old version without creating a new branch 292------------------------------------------------------ 293 294The git-checkout command normally expects a branch head, but will also 295accept an arbitrary commit; for example, you can check out the commit 296referenced by a tag: 297 298------------------------------------------------ 299$ git checkout v2.6.17 300Note: moving to "v2.6.17" which isn't a local branch 301If you want to create a new branch from this checkout, you may do so 302(now or later) by using -b with the checkout command again. Example: 303 git checkout -b <new_branch_name> 304HEAD is now at 427abfa... Linux v2.6.17 305------------------------------------------------ 306 307The HEAD then refers to the SHA1 of the commit instead of to a branch, 308and git branch shows that you are no longer on a branch: 309 310------------------------------------------------ 311$ cat .git/HEAD 312427abfa28afedffadfca9dd8b067eb6d36bac53f 313$ git branch 314* (no branch) 315 master 316------------------------------------------------ 317 318In this case we say that the HEAD is "detached". 319 320This is an easy way to check out a particular version without having to 321make up a name for the new branch. You can still create a new branch 322(or tag) for this version later if you decide to. 323 324[[examining-remote-branches]] 325Examining branches from a remote repository 326------------------------------------------- 327 328The "master" branch that was created at the time you cloned is a copy 329of the HEAD in the repository that you cloned from. That repository 330may also have had other branches, though, and your local repository 331keeps branches which track each of those remote branches, which you 332can view using the "-r" option to gitlink:git-branch[1]: 333 334------------------------------------------------ 335$ git branch -r 336 origin/HEAD 337 origin/html 338 origin/maint 339 origin/man 340 origin/master 341 origin/next 342 origin/pu 343 origin/todo 344------------------------------------------------ 345 346You cannot check out these remote-tracking branches, but you can 347examine them on a branch of your own, just as you would a tag: 348 349------------------------------------------------ 350$ git checkout -b my-todo-copy origin/todo 351------------------------------------------------ 352 353Note that the name "origin" is just the name that git uses by default 354to refer to the repository that you cloned from. 355 356[[how-git-stores-references]] 357Naming branches, tags, and other references 358------------------------------------------- 359 360Branches, remote-tracking branches, and tags are all references to 361commits. All references are named with a slash-separated path name 362starting with "refs"; the names we've been using so far are actually 363shorthand: 364 365 - The branch "test" is short for "refs/heads/test". 366 - The tag "v2.6.18" is short for "refs/tags/v2.6.18". 367 - "origin/master" is short for "refs/remotes/origin/master". 368 369The full name is occasionally useful if, for example, there ever 370exists a tag and a branch with the same name. 371 372(Newly created refs are actually stored in the .git/refs directory, 373under the path given by their name. However, for efficiency reasons 374they may also be packed together in a single file; see 375gitlink:git-pack-refs[1]). 376 377As another useful shortcut, the "HEAD" of a repository can be referred 378to just using the name of that repository. So, for example, "origin" 379is usually a shortcut for the HEAD branch in the repository "origin". 380 381For the complete list of paths which git checks for references, and 382the order it uses to decide which to choose when there are multiple 383references with the same shorthand name, see the "SPECIFYING 384REVISIONS" section of gitlink:git-rev-parse[1]. 385 386[[Updating-a-repository-with-git-fetch]] 387Updating a repository with git fetch 388------------------------------------ 389 390Eventually the developer cloned from will do additional work in her 391repository, creating new commits and advancing the branches to point 392at the new commits. 393 394The command "git fetch", with no arguments, will update all of the 395remote-tracking branches to the latest version found in her 396repository. It will not touch any of your own branches--not even the 397"master" branch that was created for you on clone. 398 399[[fetching-branches]] 400Fetching branches from other repositories 401----------------------------------------- 402 403You can also track branches from repositories other than the one you 404cloned from, using gitlink:git-remote[1]: 405 406------------------------------------------------- 407$ git remote add linux-nfs git://linux-nfs.org/pub/nfs-2.6.git 408$ git fetch linux-nfs 409* refs/remotes/linux-nfs/master: storing branch 'master' ... 410 commit: bf81b46 411------------------------------------------------- 412 413New remote-tracking branches will be stored under the shorthand name 414that you gave "git remote add", in this case linux-nfs: 415 416------------------------------------------------- 417$ git branch -r 418linux-nfs/master 419origin/master 420------------------------------------------------- 421 422If you run "git fetch <remote>" later, the tracking branches for the 423named <remote> will be updated. 424 425If you examine the file .git/config, you will see that git has added 426a new stanza: 427 428------------------------------------------------- 429$ cat .git/config 430... 431[remote "linux-nfs"] 432 url = git://linux-nfs.org/pub/nfs-2.6.git 433 fetch = +refs/heads/*:refs/remotes/linux-nfs/* 434... 435------------------------------------------------- 436 437This is what causes git to track the remote's branches; you may modify 438or delete these configuration options by editing .git/config with a 439text editor. (See the "CONFIGURATION FILE" section of 440gitlink:git-config[1] for details.) 441 442[[exploring-git-history]] 443Exploring git history 444===================== 445 446Git is best thought of as a tool for storing the history of a 447collection of files. It does this by storing compressed snapshots of 448the contents of a file hierarchy, together with "commits" which show 449the relationships between these snapshots. 450 451Git provides extremely flexible and fast tools for exploring the 452history of a project. 453 454We start with one specialized tool that is useful for finding the 455commit that introduced a bug into a project. 456 457[[using-bisect]] 458How to use bisect to find a regression 459-------------------------------------- 460 461Suppose version 2.6.18 of your project worked, but the version at 462"master" crashes. Sometimes the best way to find the cause of such a 463regression is to perform a brute-force search through the project's 464history to find the particular commit that caused the problem. The 465gitlink:git-bisect[1] command can help you do this: 466 467------------------------------------------------- 468$ git bisect start 469$ git bisect good v2.6.18 470$ git bisect bad master 471Bisecting: 3537 revisions left to test after this 472[65934a9a028b88e83e2b0f8b36618fe503349f8e] BLOCK: Make USB storage depend on SCSI rather than selecting it [try #6] 473------------------------------------------------- 474 475If you run "git branch" at this point, you'll see that git has 476temporarily moved you to a new branch named "bisect". This branch 477points to a commit (with commit id 65934...) that is reachable from 478"master" but not from v2.6.18. Compile and test it, and see whether 479it crashes. Assume it does crash. Then: 480 481------------------------------------------------- 482$ git bisect bad 483Bisecting: 1769 revisions left to test after this 484[7eff82c8b1511017ae605f0c99ac275a7e21b867] i2c-core: Drop useless bitmaskings 485------------------------------------------------- 486 487checks out an older version. Continue like this, telling git at each 488stage whether the version it gives you is good or bad, and notice 489that the number of revisions left to test is cut approximately in 490half each time. 491 492After about 13 tests (in this case), it will output the commit id of 493the guilty commit. You can then examine the commit with 494gitlink:git-show[1], find out who wrote it, and mail them your bug 495report with the commit id. Finally, run 496 497------------------------------------------------- 498$ git bisect reset 499------------------------------------------------- 500 501to return you to the branch you were on before and delete the 502temporary "bisect" branch. 503 504Note that the version which git-bisect checks out for you at each 505point is just a suggestion, and you're free to try a different 506version if you think it would be a good idea. For example, 507occasionally you may land on a commit that broke something unrelated; 508run 509 510------------------------------------------------- 511$ git bisect visualize 512------------------------------------------------- 513 514which will run gitk and label the commit it chose with a marker that 515says "bisect". Chose a safe-looking commit nearby, note its commit 516id, and check it out with: 517 518------------------------------------------------- 519$ git reset --hard fb47ddb2db... 520------------------------------------------------- 521 522then test, run "bisect good" or "bisect bad" as appropriate, and 523continue. 524 525[[naming-commits]] 526Naming commits 527-------------- 528 529We have seen several ways of naming commits already: 530 531 - 40-hexdigit object name 532 - branch name: refers to the commit at the head of the given 533 branch 534 - tag name: refers to the commit pointed to by the given tag 535 (we've seen branches and tags are special cases of 536 <<how-git-stores-references,references>>). 537 - HEAD: refers to the head of the current branch 538 539There are many more; see the "SPECIFYING REVISIONS" section of the 540gitlink:git-rev-parse[1] man page for the complete list of ways to 541name revisions. Some examples: 542 543------------------------------------------------- 544$ git show fb47ddb2 # the first few characters of the object name 545 # are usually enough to specify it uniquely 546$ git show HEAD^ # the parent of the HEAD commit 547$ git show HEAD^^ # the grandparent 548$ git show HEAD~4 # the great-great-grandparent 549------------------------------------------------- 550 551Recall that merge commits may have more than one parent; by default, 552^ and ~ follow the first parent listed in the commit, but you can 553also choose: 554 555------------------------------------------------- 556$ git show HEAD^1 # show the first parent of HEAD 557$ git show HEAD^2 # show the second parent of HEAD 558------------------------------------------------- 559 560In addition to HEAD, there are several other special names for 561commits: 562 563Merges (to be discussed later), as well as operations such as 564git-reset, which change the currently checked-out commit, generally 565set ORIG_HEAD to the value HEAD had before the current operation. 566 567The git-fetch operation always stores the head of the last fetched 568branch in FETCH_HEAD. For example, if you run git fetch without 569specifying a local branch as the target of the operation 570 571------------------------------------------------- 572$ git fetch git://example.com/proj.git theirbranch 573------------------------------------------------- 574 575the fetched commits will still be available from FETCH_HEAD. 576 577When we discuss merges we'll also see the special name MERGE_HEAD, 578which refers to the other branch that we're merging in to the current 579branch. 580 581The gitlink:git-rev-parse[1] command is a low-level command that is 582occasionally useful for translating some name for a commit to the object 583name for that commit: 584 585------------------------------------------------- 586$ git rev-parse origin 587e05db0fd4f31dde7005f075a84f96b360d05984b 588------------------------------------------------- 589 590[[creating-tags]] 591Creating tags 592------------- 593 594We can also create a tag to refer to a particular commit; after 595running 596 597------------------------------------------------- 598$ git tag stable-1 1b2e1d63ff 599------------------------------------------------- 600 601You can use stable-1 to refer to the commit 1b2e1d63ff. 602 603This creates a "lightweight" tag. If you would also like to include a 604comment with the tag, and possibly sign it cryptographically, then you 605should create a tag object instead; see the gitlink:git-tag[1] man page 606for details. 607 608[[browsing-revisions]] 609Browsing revisions 610------------------ 611 612The gitlink:git-log[1] command can show lists of commits. On its 613own, it shows all commits reachable from the parent commit; but you 614can also make more specific requests: 615 616------------------------------------------------- 617$ git log v2.5.. # commits since (not reachable from) v2.5 618$ git log test..master # commits reachable from master but not test 619$ git log master..test # ...reachable from test but not master 620$ git log master...test # ...reachable from either test or master, 621 # but not both 622$ git log --since="2 weeks ago" # commits from the last 2 weeks 623$ git log Makefile # commits which modify Makefile 624$ git log fs/ # ... which modify any file under fs/ 625$ git log -S'foo()' # commits which add or remove any file data 626 # matching the string 'foo()' 627------------------------------------------------- 628 629And of course you can combine all of these; the following finds 630commits since v2.5 which touch the Makefile or any file under fs: 631 632------------------------------------------------- 633$ git log v2.5.. Makefile fs/ 634------------------------------------------------- 635 636You can also ask git log to show patches: 637 638------------------------------------------------- 639$ git log -p 640------------------------------------------------- 641 642See the "--pretty" option in the gitlink:git-log[1] man page for more 643display options. 644 645Note that git log starts with the most recent commit and works 646backwards through the parents; however, since git history can contain 647multiple independent lines of development, the particular order that 648commits are listed in may be somewhat arbitrary. 649 650[[generating-diffs]] 651Generating diffs 652---------------- 653 654You can generate diffs between any two versions using 655gitlink:git-diff[1]: 656 657------------------------------------------------- 658$ git diff master..test 659------------------------------------------------- 660 661That will produce the diff between the tips of the two branches. If 662you'd prefer to find the diff from their common ancestor to test, you 663can use three dots instead of two: 664 665------------------------------------------------- 666$ git diff master...test 667------------------------------------------------- 668 669Sometimes what you want instead is a set of patches; for this you can 670use gitlink:git-format-patch[1]: 671 672------------------------------------------------- 673$ git format-patch master..test 674------------------------------------------------- 675 676will generate a file with a patch for each commit reachable from test 677but not from master. 678 679[[viewing-old-file-versions]] 680Viewing old file versions 681------------------------- 682 683You can always view an old version of a file by just checking out the 684correct revision first. But sometimes it is more convenient to be 685able to view an old version of a single file without checking 686anything out; this command does that: 687 688------------------------------------------------- 689$ git show v2.5:fs/locks.c 690------------------------------------------------- 691 692Before the colon may be anything that names a commit, and after it 693may be any path to a file tracked by git. 694 695[[history-examples]] 696Examples 697-------- 698 699[[counting-commits-on-a-branch]] 700Counting the number of commits on a branch 701~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 702 703Suppose you want to know how many commits you've made on "mybranch" 704since it diverged from "origin": 705 706------------------------------------------------- 707$ git log --pretty=oneline origin..mybranch | wc -l 708------------------------------------------------- 709 710Alternatively, you may often see this sort of thing done with the 711lower-level command gitlink:git-rev-list[1], which just lists the SHA1's 712of all the given commits: 713 714------------------------------------------------- 715$ git rev-list origin..mybranch | wc -l 716------------------------------------------------- 717 718[[checking-for-equal-branches]] 719Check whether two branches point at the same history 720~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 721 722Suppose you want to check whether two branches point at the same point 723in history. 724 725------------------------------------------------- 726$ git diff origin..master 727------------------------------------------------- 728 729will tell you whether the contents of the project are the same at the 730two branches; in theory, however, it's possible that the same project 731contents could have been arrived at by two different historical 732routes. You could compare the object names: 733 734------------------------------------------------- 735$ git rev-list origin 736e05db0fd4f31dde7005f075a84f96b360d05984b 737$ git rev-list master 738e05db0fd4f31dde7005f075a84f96b360d05984b 739------------------------------------------------- 740 741Or you could recall that the ... operator selects all commits 742contained reachable from either one reference or the other but not 743both: so 744 745------------------------------------------------- 746$ git log origin...master 747------------------------------------------------- 748 749will return no commits when the two branches are equal. 750 751[[finding-tagged-descendants]] 752Find first tagged version including a given fix 753~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 754 755Suppose you know that the commit e05db0fd fixed a certain problem. 756You'd like to find the earliest tagged release that contains that 757fix. 758 759Of course, there may be more than one answer--if the history branched 760after commit e05db0fd, then there could be multiple "earliest" tagged 761releases. 762 763You could just visually inspect the commits since e05db0fd: 764 765------------------------------------------------- 766$ gitk e05db0fd.. 767------------------------------------------------- 768 769Or you can use gitlink:git-name-rev[1], which will give the commit a 770name based on any tag it finds pointing to one of the commit's 771descendants: 772 773------------------------------------------------- 774$ git name-rev --tags e05db0fd 775e05db0fd tags/v1.5.0-rc1^0~23 776------------------------------------------------- 777 778The gitlink:git-describe[1] command does the opposite, naming the 779revision using a tag on which the given commit is based: 780 781------------------------------------------------- 782$ git describe e05db0fd 783v1.5.0-rc0-260-ge05db0f 784------------------------------------------------- 785 786but that may sometimes help you guess which tags might come after the 787given commit. 788 789If you just want to verify whether a given tagged version contains a 790given commit, you could use gitlink:git-merge-base[1]: 791 792------------------------------------------------- 793$ git merge-base e05db0fd v1.5.0-rc1 794e05db0fd4f31dde7005f075a84f96b360d05984b 795------------------------------------------------- 796 797The merge-base command finds a common ancestor of the given commits, 798and always returns one or the other in the case where one is a 799descendant of the other; so the above output shows that e05db0fd 800actually is an ancestor of v1.5.0-rc1. 801 802Alternatively, note that 803 804------------------------------------------------- 805$ git log v1.5.0-rc1..e05db0fd 806------------------------------------------------- 807 808will produce empty output if and only if v1.5.0-rc1 includes e05db0fd, 809because it outputs only commits that are not reachable from v1.5.0-rc1. 810 811As yet another alternative, the gitlink:git-show-branch[1] command lists 812the commits reachable from its arguments with a display on the left-hand 813side that indicates which arguments that commit is reachable from. So, 814you can run something like 815 816------------------------------------------------- 817$ git show-branch e05db0fd v1.5.0-rc0 v1.5.0-rc1 v1.5.0-rc2 818! [e05db0fd] Fix warnings in sha1_file.c - use C99 printf format if 819available 820 ! [v1.5.0-rc0] GIT v1.5.0 preview 821 ! [v1.5.0-rc1] GIT v1.5.0-rc1 822 ! [v1.5.0-rc2] GIT v1.5.0-rc2 823... 824------------------------------------------------- 825 826then search for a line that looks like 827 828------------------------------------------------- 829+ ++ [e05db0fd] Fix warnings in sha1_file.c - use C99 printf format if 830available 831------------------------------------------------- 832 833Which shows that e05db0fd is reachable from itself, from v1.5.0-rc1, and 834from v1.5.0-rc2, but not from v1.5.0-rc0. 835 836[[showing-commits-unique-to-a-branch]] 837Showing commits unique to a given branch 838~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 839 840Suppose you would like to see all the commits reachable from the branch 841head named "master" but not from any other head in your repository. 842 843We can list all the heads in this repository with 844gitlink:git-show-ref[1]: 845 846------------------------------------------------- 847$ git show-ref --heads 848bf62196b5e363d73353a9dcf094c59595f3153b7 refs/heads/core-tutorial 849db768d5504c1bb46f63ee9d6e1772bd047e05bf9 refs/heads/maint 850a07157ac624b2524a059a3414e99f6f44bebc1e7 refs/heads/master 85124dbc180ea14dc1aebe09f14c8ecf32010690627 refs/heads/tutorial-2 8521e87486ae06626c2f31eaa63d26fc0fd646c8af2 refs/heads/tutorial-fixes 853------------------------------------------------- 854 855We can get just the branch-head names, and remove "master", with 856the help of the standard utilities cut and grep: 857 858------------------------------------------------- 859$ git show-ref --heads | cut -d' ' -f2 | grep -v '^refs/heads/master' 860refs/heads/core-tutorial 861refs/heads/maint 862refs/heads/tutorial-2 863refs/heads/tutorial-fixes 864------------------------------------------------- 865 866And then we can ask to see all the commits reachable from master 867but not from these other heads: 868 869------------------------------------------------- 870$ gitk master --not $( git show-ref --heads | cut -d' ' -f2 | 871 grep -v '^refs/heads/master' ) 872------------------------------------------------- 873 874Obviously, endless variations are possible; for example, to see all 875commits reachable from some head but not from any tag in the repository: 876 877------------------------------------------------- 878$ gitk $( git show-ref --heads ) --not $( git show-ref --tags ) 879------------------------------------------------- 880 881(See gitlink:git-rev-parse[1] for explanations of commit-selecting 882syntax such as `--not`.) 883 884[[making-a-release]] 885Creating a changelog and tarball for a software release 886~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 887 888The gitlink:git-archive[1] command can create a tar or zip archive from 889any version of a project; for example: 890 891------------------------------------------------- 892$ git archive --format=tar --prefix=project/ HEAD | gzip >latest.tar.gz 893------------------------------------------------- 894 895will use HEAD to produce a tar archive in which each filename is 896preceded by "project/". 897 898If you're releasing a new version of a software project, you may want 899to simultaneously make a changelog to include in the release 900announcement. 901 902Linus Torvalds, for example, makes new kernel releases by tagging them, 903then running: 904 905------------------------------------------------- 906$ release-script 2.6.12 2.6.13-rc6 2.6.13-rc7 907------------------------------------------------- 908 909where release-script is a shell script that looks like: 910 911------------------------------------------------- 912#!/bin/sh 913stable="$1" 914last="$2" 915new="$3" 916echo "# git tag v$new" 917echo "git archive --prefix=linux-$new/ v$new | gzip -9 > ../linux-$new.tar.gz" 918echo "git diff v$stable v$new | gzip -9 > ../patch-$new.gz" 919echo "git log --no-merges v$new ^v$last > ../ChangeLog-$new" 920echo "git shortlog --no-merges v$new ^v$last > ../ShortLog" 921echo "git diff --stat --summary -M v$last v$new > ../diffstat-$new" 922------------------------------------------------- 923 924and then he just cut-and-pastes the output commands after verifying that 925they look OK. 926 927[[Finding-comments-with-given-content]] 928Finding commits referencing a file with given content 929~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 930 931Somebody hands you a copy of a file, and asks which commits modified a 932file such that it contained the given content either before or after the 933commit. You can find out with this: 934 935------------------------------------------------- 936$ git log --raw --abbrev=40 --pretty=oneline | 937 grep -B 1 `git hash-object filename` 938------------------------------------------------- 939 940Figuring out why this works is left as an exercise to the (advanced) 941student. The gitlink:git-log[1], gitlink:git-diff-tree[1], and 942gitlink:git-hash-object[1] man pages may prove helpful. 943 944[[Developing-with-git]] 945Developing with git 946=================== 947 948[[telling-git-your-name]] 949Telling git your name 950--------------------- 951 952Before creating any commits, you should introduce yourself to git. The 953easiest way to do so is to make sure the following lines appear in a 954file named .gitconfig in your home directory: 955 956------------------------------------------------ 957[user] 958 name = Your Name Comes Here 959 email = you@yourdomain.example.com 960------------------------------------------------ 961 962(See the "CONFIGURATION FILE" section of gitlink:git-config[1] for 963details on the configuration file.) 964 965 966[[creating-a-new-repository]] 967Creating a new repository 968------------------------- 969 970Creating a new repository from scratch is very easy: 971 972------------------------------------------------- 973$ mkdir project 974$ cd project 975$ git init 976------------------------------------------------- 977 978If you have some initial content (say, a tarball): 979 980------------------------------------------------- 981$ tar -xzvf project.tar.gz 982$ cd project 983$ git init 984$ git add . # include everything below ./ in the first commit: 985$ git commit 986------------------------------------------------- 987 988[[how-to-make-a-commit]] 989How to make a commit 990-------------------- 991 992Creating a new commit takes three steps: 993 994 1. Making some changes to the working directory using your 995 favorite editor. 996 2. Telling git about your changes. 997 3. Creating the commit using the content you told git about 998 in step 2. 9991000In practice, you can interleave and repeat steps 1 and 2 as many1001times as you want: in order to keep track of what you want committed1002at step 3, git maintains a snapshot of the tree's contents in a1003special staging area called "the index."10041005At the beginning, the content of the index will be identical to1006that of the HEAD. The command "git diff --cached", which shows1007the difference between the HEAD and the index, should therefore1008produce no output at that point.10091010Modifying the index is easy:10111012To update the index with the new contents of a modified file, use10131014-------------------------------------------------1015$ git add path/to/file1016-------------------------------------------------10171018To add the contents of a new file to the index, use10191020-------------------------------------------------1021$ git add path/to/file1022-------------------------------------------------10231024To remove a file from the index and from the working tree,10251026-------------------------------------------------1027$ git rm path/to/file1028-------------------------------------------------10291030After each step you can verify that10311032-------------------------------------------------1033$ git diff --cached1034-------------------------------------------------10351036always shows the difference between the HEAD and the index file--this1037is what you'd commit if you created the commit now--and that10381039-------------------------------------------------1040$ git diff1041-------------------------------------------------10421043shows the difference between the working tree and the index file.10441045Note that "git add" always adds just the current contents of a file1046to the index; further changes to the same file will be ignored unless1047you run git-add on the file again.10481049When you're ready, just run10501051-------------------------------------------------1052$ git commit1053-------------------------------------------------10541055and git will prompt you for a commit message and then create the new1056commit. Check to make sure it looks like what you expected with10571058-------------------------------------------------1059$ git show1060-------------------------------------------------10611062As a special shortcut,10631064-------------------------------------------------1065$ git commit -a1066-------------------------------------------------10671068will update the index with any files that you've modified or removed1069and create a commit, all in one step.10701071A number of commands are useful for keeping track of what you're1072about to commit:10731074-------------------------------------------------1075$ git diff --cached # difference between HEAD and the index; what1076 # would be committed if you ran "commit" now.1077$ git diff # difference between the index file and your1078 # working directory; changes that would not1079 # be included if you ran "commit" now.1080$ git diff HEAD # difference between HEAD and working tree; what1081 # would be committed if you ran "commit -a" now.1082$ git status # a brief per-file summary of the above.1083-------------------------------------------------10841085You can also use gitlink:git-gui[1] to create commits, view changes in1086the index and the working tree files, and individually select diff hunks1087for inclusion in the index (by right-clicking on the diff hunk and1088choosing "Stage Hunk For Commit").10891090[[creating-good-commit-messages]]1091Creating good commit messages1092-----------------------------10931094Though not required, it's a good idea to begin the commit message1095with a single short (less than 50 character) line summarizing the1096change, followed by a blank line and then a more thorough1097description. Tools that turn commits into email, for example, use1098the first line on the Subject line and the rest of the commit in the1099body.11001101[[ignoring-files]]1102Ignoring files1103--------------11041105A project will often generate files that you do 'not' want to track with git.1106This typically includes files generated by a build process or temporary1107backup files made by your editor. Of course, 'not' tracking files with git1108is just a matter of 'not' calling "`git add`" on them. But it quickly becomes1109annoying to have these untracked files lying around; e.g. they make1110"`git add .`" and "`git commit -a`" practically useless, and they keep1111showing up in the output of "`git status`".11121113You can tell git to ignore certain files by creating a file called .gitignore1114in the top level of your working directory, with contents such as:11151116-------------------------------------------------1117# Lines starting with '#' are considered comments.1118# Ignore any file named foo.txt.1119foo.txt1120# Ignore (generated) html files,1121*.html1122# except foo.html which is maintained by hand.1123!foo.html1124# Ignore objects and archives.1125*.[oa]1126-------------------------------------------------11271128See gitlink:gitignore[5] for a detailed explanation of the syntax. You can1129also place .gitignore files in other directories in your working tree, and they1130will apply to those directories and their subdirectories. The `.gitignore`1131files can be added to your repository like any other files (just run `git add1132.gitignore` and `git commit`, as usual), which is convenient when the exclude1133patterns (such as patterns matching build output files) would also make sense1134for other users who clone your repository.11351136If you wish the exclude patterns to affect only certain repositories1137(instead of every repository for a given project), you may instead put1138them in a file in your repository named .git/info/exclude, or in any file1139specified by the `core.excludesfile` configuration variable. Some git1140commands can also take exclude patterns directly on the command line.1141See gitlink:gitignore[5] for the details.11421143[[how-to-merge]]1144How to merge1145------------11461147You can rejoin two diverging branches of development using1148gitlink:git-merge[1]:11491150-------------------------------------------------1151$ git merge branchname1152-------------------------------------------------11531154merges the development in the branch "branchname" into the current1155branch. If there are conflicts--for example, if the same file is1156modified in two different ways in the remote branch and the local1157branch--then you are warned; the output may look something like this:11581159-------------------------------------------------1160$ git merge next1161 100% (4/4) done1162Auto-merged file.txt1163CONFLICT (content): Merge conflict in file.txt1164Automatic merge failed; fix conflicts and then commit the result.1165-------------------------------------------------11661167Conflict markers are left in the problematic files, and after1168you resolve the conflicts manually, you can update the index1169with the contents and run git commit, as you normally would when1170creating a new file.11711172If you examine the resulting commit using gitk, you will see that it1173has two parents, one pointing to the top of the current branch, and1174one to the top of the other branch.11751176[[resolving-a-merge]]1177Resolving a merge1178-----------------11791180When a merge isn't resolved automatically, git leaves the index and1181the working tree in a special state that gives you all the1182information you need to help resolve the merge.11831184Files with conflicts are marked specially in the index, so until you1185resolve the problem and update the index, gitlink:git-commit[1] will1186fail:11871188-------------------------------------------------1189$ git commit1190file.txt: needs merge1191-------------------------------------------------11921193Also, gitlink:git-status[1] will list those files as "unmerged", and the1194files with conflicts will have conflict markers added, like this:11951196-------------------------------------------------1197<<<<<<< HEAD:file.txt1198Hello world1199=======1200Goodbye1201>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt1202-------------------------------------------------12031204All you need to do is edit the files to resolve the conflicts, and then12051206-------------------------------------------------1207$ git add file.txt1208$ git commit1209-------------------------------------------------12101211Note that the commit message will already be filled in for you with1212some information about the merge. Normally you can just use this1213default message unchanged, but you may add additional commentary of1214your own if desired.12151216The above is all you need to know to resolve a simple merge. But git1217also provides more information to help resolve conflicts:12181219[[conflict-resolution]]1220Getting conflict-resolution help during a merge1221~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~12221223All of the changes that git was able to merge automatically are1224already added to the index file, so gitlink:git-diff[1] shows only1225the conflicts. It uses an unusual syntax:12261227-------------------------------------------------1228$ git diff1229diff --cc file.txt1230index 802992c,2b60207..00000001231--- a/file.txt1232+++ b/file.txt1233@@@ -1,1 -1,1 +1,5 @@@1234++<<<<<<< HEAD:file.txt1235 +Hello world1236++=======1237+ Goodbye1238++>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt1239-------------------------------------------------12401241Recall that the commit which will be committed after we resolve this1242conflict will have two parents instead of the usual one: one parent1243will be HEAD, the tip of the current branch; the other will be the1244tip of the other branch, which is stored temporarily in MERGE_HEAD.12451246During the merge, the index holds three versions of each file. Each of1247these three "file stages" represents a different version of the file:12481249-------------------------------------------------1250$ git show :1:file.txt # the file in a common ancestor of both branches1251$ git show :2:file.txt # the version from HEAD, but including any1252 # nonconflicting changes from MERGE_HEAD1253$ git show :3:file.txt # the version from MERGE_HEAD, but including any1254 # nonconflicting changes from HEAD.1255-------------------------------------------------12561257Since the stage 2 and stage 3 versions have already been updated with1258nonconflicting changes, the only remaining differences between them are1259the important ones; thus gitlink:git-diff[1] can use the information in1260the index to show only those conflicts.12611262The diff above shows the differences between the working-tree version of1263file.txt and the stage 2 and stage 3 versions. So instead of preceding1264each line by a single "+" or "-", it now uses two columns: the first1265column is used for differences between the first parent and the working1266directory copy, and the second for differences between the second parent1267and the working directory copy. (See the "COMBINED DIFF FORMAT" section1268of gitlink:git-diff-files[1] for a details of the format.)12691270After resolving the conflict in the obvious way (but before updating the1271index), the diff will look like:12721273-------------------------------------------------1274$ git diff1275diff --cc file.txt1276index 802992c,2b60207..00000001277--- a/file.txt1278+++ b/file.txt1279@@@ -1,1 -1,1 +1,1 @@@1280- Hello world1281 -Goodbye1282++Goodbye world1283-------------------------------------------------12841285This shows that our resolved version deleted "Hello world" from the1286first parent, deleted "Goodbye" from the second parent, and added1287"Goodbye world", which was previously absent from both.12881289Some special diff options allow diffing the working directory against1290any of these stages:12911292-------------------------------------------------1293$ git diff -1 file.txt # diff against stage 11294$ git diff --base file.txt # same as the above1295$ git diff -2 file.txt # diff against stage 21296$ git diff --ours file.txt # same as the above1297$ git diff -3 file.txt # diff against stage 31298$ git diff --theirs file.txt # same as the above.1299-------------------------------------------------13001301The gitlink:git-log[1] and gitk[1] commands also provide special help1302for merges:13031304-------------------------------------------------1305$ git log --merge1306$ gitk --merge1307-------------------------------------------------13081309These will display all commits which exist only on HEAD or on1310MERGE_HEAD, and which touch an unmerged file.13111312You may also use gitlink:git-mergetool[1], which lets you merge the1313unmerged files using external tools such as emacs or kdiff3.13141315Each time you resolve the conflicts in a file and update the index:13161317-------------------------------------------------1318$ git add file.txt1319-------------------------------------------------13201321the different stages of that file will be "collapsed", after which1322git-diff will (by default) no longer show diffs for that file.13231324[[undoing-a-merge]]1325Undoing a merge1326---------------13271328If you get stuck and decide to just give up and throw the whole mess1329away, you can always return to the pre-merge state with13301331-------------------------------------------------1332$ git reset --hard HEAD1333-------------------------------------------------13341335Or, if you've already committed the merge that you want to throw away,13361337-------------------------------------------------1338$ git reset --hard ORIG_HEAD1339-------------------------------------------------13401341However, this last command can be dangerous in some cases--never1342throw away a commit you have already committed if that commit may1343itself have been merged into another branch, as doing so may confuse1344further merges.13451346[[fast-forwards]]1347Fast-forward merges1348-------------------13491350There is one special case not mentioned above, which is treated1351differently. Normally, a merge results in a merge commit, with two1352parents, one pointing at each of the two lines of development that1353were merged.13541355However, if the current branch is a descendant of the other--so every1356commit present in the one is already contained in the other--then git1357just performs a "fast forward"; the head of the current branch is moved1358forward to point at the head of the merged-in branch, without any new1359commits being created.13601361[[fixing-mistakes]]1362Fixing mistakes1363---------------13641365If you've messed up the working tree, but haven't yet committed your1366mistake, you can return the entire working tree to the last committed1367state with13681369-------------------------------------------------1370$ git reset --hard HEAD1371-------------------------------------------------13721373If you make a commit that you later wish you hadn't, there are two1374fundamentally different ways to fix the problem:13751376 1. You can create a new commit that undoes whatever was done1377 by the old commit. This is the correct thing if your1378 mistake has already been made public.13791380 2. You can go back and modify the old commit. You should1381 never do this if you have already made the history public;1382 git does not normally expect the "history" of a project to1383 change, and cannot correctly perform repeated merges from1384 a branch that has had its history changed.13851386[[reverting-a-commit]]1387Fixing a mistake with a new commit1388~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~13891390Creating a new commit that reverts an earlier change is very easy;1391just pass the gitlink:git-revert[1] command a reference to the bad1392commit; for example, to revert the most recent commit:13931394-------------------------------------------------1395$ git revert HEAD1396-------------------------------------------------13971398This will create a new commit which undoes the change in HEAD. You1399will be given a chance to edit the commit message for the new commit.14001401You can also revert an earlier change, for example, the next-to-last:14021403-------------------------------------------------1404$ git revert HEAD^1405-------------------------------------------------14061407In this case git will attempt to undo the old change while leaving1408intact any changes made since then. If more recent changes overlap1409with the changes to be reverted, then you will be asked to fix1410conflicts manually, just as in the case of <<resolving-a-merge,1411resolving a merge>>.14121413[[fixing-a-mistake-by-editing-history]]1414Fixing a mistake by editing history1415~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~14161417If the problematic commit is the most recent commit, and you have not1418yet made that commit public, then you may just1419<<undoing-a-merge,destroy it using git-reset>>.14201421Alternatively, you1422can edit the working directory and update the index to fix your1423mistake, just as if you were going to <<how-to-make-a-commit,create a1424new commit>>, then run14251426-------------------------------------------------1427$ git commit --amend1428-------------------------------------------------14291430which will replace the old commit by a new commit incorporating your1431changes, giving you a chance to edit the old commit message first.14321433Again, you should never do this to a commit that may already have1434been merged into another branch; use gitlink:git-revert[1] instead in1435that case.14361437It is also possible to edit commits further back in the history, but1438this is an advanced topic to be left for1439<<cleaning-up-history,another chapter>>.14401441[[checkout-of-path]]1442Checking out an old version of a file1443~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~14441445In the process of undoing a previous bad change, you may find it1446useful to check out an older version of a particular file using1447gitlink:git-checkout[1]. We've used git checkout before to switch1448branches, but it has quite different behavior if it is given a path1449name: the command14501451-------------------------------------------------1452$ git checkout HEAD^ path/to/file1453-------------------------------------------------14541455replaces path/to/file by the contents it had in the commit HEAD^, and1456also updates the index to match. It does not change branches.14571458If you just want to look at an old version of the file, without1459modifying the working directory, you can do that with1460gitlink:git-show[1]:14611462-------------------------------------------------1463$ git show HEAD^:path/to/file1464-------------------------------------------------14651466which will display the given version of the file.14671468[[interrupted-work]]1469Temporarily setting aside work in progress1470~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~14711472While you are in the middle of working on something complicated, you1473find an unrelated but obvious and trivial bug. You would like to fix it1474before continuing. You can use gitlink:git-stash[1] to save the current1475state of your work, and after fixing the bug (or, optionally after doing1476so on a different branch and then coming back), unstash the1477work-in-progress changes.14781479------------------------------------------------1480$ git stash "work in progress for foo feature"1481------------------------------------------------14821483This command will save your changes away to the `stash`, and1484reset your working tree and the index to match the tip of your1485current branch. Then you can make your fix as usual.14861487------------------------------------------------1488... edit and test ...1489$ git commit -a -m "blorpl: typofix"1490------------------------------------------------14911492After that, you can go back to what you were working on with1493`git stash apply`:14941495------------------------------------------------1496$ git stash apply1497------------------------------------------------149814991500[[ensuring-good-performance]]1501Ensuring good performance1502-------------------------15031504On large repositories, git depends on compression to keep the history1505information from taking up too much space on disk or in memory.15061507This compression is not performed automatically. Therefore you1508should occasionally run gitlink:git-gc[1]:15091510-------------------------------------------------1511$ git gc1512-------------------------------------------------15131514to recompress the archive. This can be very time-consuming, so1515you may prefer to run git-gc when you are not doing other work.151615171518[[ensuring-reliability]]1519Ensuring reliability1520--------------------15211522[[checking-for-corruption]]1523Checking the repository for corruption1524~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~15251526The gitlink:git-fsck[1] command runs a number of self-consistency checks1527on the repository, and reports on any problems. This may take some1528time. The most common warning by far is about "dangling" objects:15291530-------------------------------------------------1531$ git fsck1532dangling commit 7281251ddd2a61e38657c827739c57015671a6b31533dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a631534dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b51535dangling blob 218761f9d90712d37a9c5e36f406f92202db07eb1536dangling commit bf093535a34a4d35731aa2bd90fe6b176302f14f1537dangling commit 8e4bec7f2ddaa268bef999853c25755452100f8e1538dangling tree d50bb86186bf27b681d25af89d3b5b68382e40851539dangling tree b24c2473f1fd3d91352a624795be026d64c8841f1540...1541-------------------------------------------------15421543Dangling objects are not a problem. At worst they may take up a little1544extra disk space. They can sometimes provide a last-resort method for1545recovering lost work--see <<dangling-objects>> for details. However, if1546you wish, you can remove them with gitlink:git-prune[1] or the `--prune`1547option to gitlink:git-gc[1]:15481549-------------------------------------------------1550$ git gc --prune1551-------------------------------------------------15521553This may be time-consuming. Unlike most other git operations (including1554git-gc when run without any options), it is not safe to prune while1555other git operations are in progress in the same repository.15561557[[recovering-lost-changes]]1558Recovering lost changes1559~~~~~~~~~~~~~~~~~~~~~~~15601561[[reflogs]]1562Reflogs1563^^^^^^^15641565Say you modify a branch with `gitlink:git-reset[1] --hard`, and then1566realize that the branch was the only reference you had to that point in1567history.15681569Fortunately, git also keeps a log, called a "reflog", of all the1570previous values of each branch. So in this case you can still find the1571old history using, for example,15721573-------------------------------------------------1574$ git log master@{1}1575-------------------------------------------------15761577This lists the commits reachable from the previous version of the1578"master" branch head. This syntax can be used with any git command1579that accepts a commit, not just with git log. Some other examples:15801581-------------------------------------------------1582$ git show master@{2} # See where the branch pointed 2,1583$ git show master@{3} # 3, ... changes ago.1584$ gitk master@{yesterday} # See where it pointed yesterday,1585$ gitk master@{"1 week ago"} # ... or last week1586$ git log --walk-reflogs master # show reflog entries for master1587-------------------------------------------------15881589A separate reflog is kept for the HEAD, so15901591-------------------------------------------------1592$ git show HEAD@{"1 week ago"}1593-------------------------------------------------15941595will show what HEAD pointed to one week ago, not what the current branch1596pointed to one week ago. This allows you to see the history of what1597you've checked out.15981599The reflogs are kept by default for 30 days, after which they may be1600pruned. See gitlink:git-reflog[1] and gitlink:git-gc[1] to learn1601how to control this pruning, and see the "SPECIFYING REVISIONS"1602section of gitlink:git-rev-parse[1] for details.16031604Note that the reflog history is very different from normal git history.1605While normal history is shared by every repository that works on the1606same project, the reflog history is not shared: it tells you only about1607how the branches in your local repository have changed over time.16081609[[dangling-object-recovery]]1610Examining dangling objects1611^^^^^^^^^^^^^^^^^^^^^^^^^^16121613In some situations the reflog may not be able to save you. For example,1614suppose you delete a branch, then realize you need the history it1615contained. The reflog is also deleted; however, if you have not yet1616pruned the repository, then you may still be able to find the lost1617commits in the dangling objects that git-fsck reports. See1618<<dangling-objects>> for the details.16191620-------------------------------------------------1621$ git fsck1622dangling commit 7281251ddd2a61e38657c827739c57015671a6b31623dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a631624dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b51625...1626-------------------------------------------------16271628You can examine1629one of those dangling commits with, for example,16301631------------------------------------------------1632$ gitk 7281251ddd --not --all1633------------------------------------------------16341635which does what it sounds like: it says that you want to see the commit1636history that is described by the dangling commit(s), but not the1637history that is described by all your existing branches and tags. Thus1638you get exactly the history reachable from that commit that is lost.1639(And notice that it might not be just one commit: we only report the1640"tip of the line" as being dangling, but there might be a whole deep1641and complex commit history that was dropped.)16421643If you decide you want the history back, you can always create a new1644reference pointing to it, for example, a new branch:16451646------------------------------------------------1647$ git branch recovered-branch 7281251ddd1648------------------------------------------------16491650Other types of dangling objects (blobs and trees) are also possible, and1651dangling objects can arise in other situations.165216531654[[sharing-development]]1655Sharing development with others1656===============================16571658[[getting-updates-with-git-pull]]1659Getting updates with git pull1660-----------------------------16611662After you clone a repository and make a few changes of your own, you1663may wish to check the original repository for updates and merge them1664into your own work.16651666We have already seen <<Updating-a-repository-with-git-fetch,how to1667keep remote tracking branches up to date>> with gitlink:git-fetch[1],1668and how to merge two branches. So you can merge in changes from the1669original repository's master branch with:16701671-------------------------------------------------1672$ git fetch1673$ git merge origin/master1674-------------------------------------------------16751676However, the gitlink:git-pull[1] command provides a way to do this in1677one step:16781679-------------------------------------------------1680$ git pull origin master1681-------------------------------------------------16821683In fact, if you have "master" checked out, then by default "git pull"1684merges from the HEAD branch of the origin repository. So often you can1685accomplish the above with just a simple16861687-------------------------------------------------1688$ git pull1689-------------------------------------------------16901691More generally, a branch that is created from a remote branch will pull1692by default from that branch. See the descriptions of the1693branch.<name>.remote and branch.<name>.merge options in1694gitlink:git-config[1], and the discussion of the `--track` option in1695gitlink:git-checkout[1], to learn how to control these defaults.16961697In addition to saving you keystrokes, "git pull" also helps you by1698producing a default commit message documenting the branch and1699repository that you pulled from.17001701(But note that no such commit will be created in the case of a1702<<fast-forwards,fast forward>>; instead, your branch will just be1703updated to point to the latest commit from the upstream branch.)17041705The git-pull command can also be given "." as the "remote" repository,1706in which case it just merges in a branch from the current repository; so1707the commands17081709-------------------------------------------------1710$ git pull . branch1711$ git merge branch1712-------------------------------------------------17131714are roughly equivalent. The former is actually very commonly used.17151716[[submitting-patches]]1717Submitting patches to a project1718-------------------------------17191720If you just have a few changes, the simplest way to submit them may1721just be to send them as patches in email:17221723First, use gitlink:git-format-patch[1]; for example:17241725-------------------------------------------------1726$ git format-patch origin1727-------------------------------------------------17281729will produce a numbered series of files in the current directory, one1730for each patch in the current branch but not in origin/HEAD.17311732You can then import these into your mail client and send them by1733hand. However, if you have a lot to send at once, you may prefer to1734use the gitlink:git-send-email[1] script to automate the process.1735Consult the mailing list for your project first to determine how they1736prefer such patches be handled.17371738[[importing-patches]]1739Importing patches to a project1740------------------------------17411742Git also provides a tool called gitlink:git-am[1] (am stands for1743"apply mailbox"), for importing such an emailed series of patches.1744Just save all of the patch-containing messages, in order, into a1745single mailbox file, say "patches.mbox", then run17461747-------------------------------------------------1748$ git am -3 patches.mbox1749-------------------------------------------------17501751Git will apply each patch in order; if any conflicts are found, it1752will stop, and you can fix the conflicts as described in1753"<<resolving-a-merge,Resolving a merge>>". (The "-3" option tells1754git to perform a merge; if you would prefer it just to abort and1755leave your tree and index untouched, you may omit that option.)17561757Once the index is updated with the results of the conflict1758resolution, instead of creating a new commit, just run17591760-------------------------------------------------1761$ git am --resolved1762-------------------------------------------------17631764and git will create the commit for you and continue applying the1765remaining patches from the mailbox.17661767The final result will be a series of commits, one for each patch in1768the original mailbox, with authorship and commit log message each1769taken from the message containing each patch.17701771[[public-repositories]]1772Public git repositories1773-----------------------17741775Another way to submit changes to a project is to tell the maintainer1776of that project to pull the changes from your repository using1777gitlink:git-pull[1]. In the section "<<getting-updates-with-git-pull,1778Getting updates with git pull>>" we described this as a way to get1779updates from the "main" repository, but it works just as well in the1780other direction.17811782If you and the maintainer both have accounts on the same machine, then1783you can just pull changes from each other's repositories directly;1784commands that accept repository URLs as arguments will also accept a1785local directory name:17861787-------------------------------------------------1788$ git clone /path/to/repository1789$ git pull /path/to/other/repository1790-------------------------------------------------17911792or an ssh URL:17931794-------------------------------------------------1795$ git clone ssh://yourhost/~you/repository1796-------------------------------------------------17971798For projects with few developers, or for synchronizing a few private1799repositories, this may be all you need.18001801However, the more common way to do this is to maintain a separate public1802repository (usually on a different host) for others to pull changes1803from. This is usually more convenient, and allows you to cleanly1804separate private work in progress from publicly visible work.18051806You will continue to do your day-to-day work in your personal1807repository, but periodically "push" changes from your personal1808repository into your public repository, allowing other developers to1809pull from that repository. So the flow of changes, in a situation1810where there is one other developer with a public repository, looks1811like this:18121813 you push1814 your personal repo ------------------> your public repo1815 ^ |1816 | |1817 | you pull | they pull1818 | |1819 | |1820 | they push V1821 their public repo <------------------- their repo18221823We explain how to do this in the following sections.18241825[[setting-up-a-public-repository]]1826Setting up a public repository1827~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~18281829Assume your personal repository is in the directory ~/proj. We1830first create a new clone of the repository and tell git-daemon that it1831is meant to be public:18321833-------------------------------------------------1834$ git clone --bare ~/proj proj.git1835$ touch proj.git/git-daemon-export-ok1836-------------------------------------------------18371838The resulting directory proj.git contains a "bare" git repository--it is1839just the contents of the ".git" directory, without any files checked out1840around it.18411842Next, copy proj.git to the server where you plan to host the1843public repository. You can use scp, rsync, or whatever is most1844convenient.18451846[[exporting-via-git]]1847Exporting a git repository via the git protocol1848~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~18491850This is the preferred method.18511852If someone else administers the server, they should tell you what1853directory to put the repository in, and what git:// URL it will appear1854at. You can then skip to the section1855"<<pushing-changes-to-a-public-repository,Pushing changes to a public1856repository>>", below.18571858Otherwise, all you need to do is start gitlink:git-daemon[1]; it will1859listen on port 9418. By default, it will allow access to any directory1860that looks like a git directory and contains the magic file1861git-daemon-export-ok. Passing some directory paths as git-daemon1862arguments will further restrict the exports to those paths.18631864You can also run git-daemon as an inetd service; see the1865gitlink:git-daemon[1] man page for details. (See especially the1866examples section.)18671868[[exporting-via-http]]1869Exporting a git repository via http1870~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~18711872The git protocol gives better performance and reliability, but on a1873host with a web server set up, http exports may be simpler to set up.18741875All you need to do is place the newly created bare git repository in1876a directory that is exported by the web server, and make some1877adjustments to give web clients some extra information they need:18781879-------------------------------------------------1880$ mv proj.git /home/you/public_html/proj.git1881$ cd proj.git1882$ git --bare update-server-info1883$ chmod a+x hooks/post-update1884-------------------------------------------------18851886(For an explanation of the last two lines, see1887gitlink:git-update-server-info[1], and the documentation1888link:hooks.html[Hooks used by git].)18891890Advertise the URL of proj.git. Anybody else should then be able to1891clone or pull from that URL, for example with a command line like:18921893-------------------------------------------------1894$ git clone http://yourserver.com/~you/proj.git1895-------------------------------------------------18961897(See also1898link:howto/setup-git-server-over-http.txt[setup-git-server-over-http]1899for a slightly more sophisticated setup using WebDAV which also1900allows pushing over http.)19011902[[pushing-changes-to-a-public-repository]]1903Pushing changes to a public repository1904~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~19051906Note that the two techniques outlined above (exporting via1907<<exporting-via-http,http>> or <<exporting-via-git,git>>) allow other1908maintainers to fetch your latest changes, but they do not allow write1909access, which you will need to update the public repository with the1910latest changes created in your private repository.19111912The simplest way to do this is using gitlink:git-push[1] and ssh; to1913update the remote branch named "master" with the latest state of your1914branch named "master", run19151916-------------------------------------------------1917$ git push ssh://yourserver.com/~you/proj.git master:master1918-------------------------------------------------19191920or just19211922-------------------------------------------------1923$ git push ssh://yourserver.com/~you/proj.git master1924-------------------------------------------------19251926As with git-fetch, git-push will complain if this does not result in1927a <<fast-forwards,fast forward>>. Normally this is a sign of1928something wrong. However, if you are sure you know what you're1929doing, you may force git-push to perform the update anyway by1930preceding the branch name by a plus sign:19311932-------------------------------------------------1933$ git push ssh://yourserver.com/~you/proj.git +master1934-------------------------------------------------19351936Note that the target of a "push" is normally a1937<<def_bare_repository,bare>> repository. You can also push to a1938repository that has a checked-out working tree, but the working tree1939will not be updated by the push. This may lead to unexpected results if1940the branch you push to is the currently checked-out branch!19411942As with git-fetch, you may also set up configuration options to1943save typing; so, for example, after19441945-------------------------------------------------1946$ cat >>.git/config <<EOF1947[remote "public-repo"]1948 url = ssh://yourserver.com/~you/proj.git1949EOF1950-------------------------------------------------19511952you should be able to perform the above push with just19531954-------------------------------------------------1955$ git push public-repo master1956-------------------------------------------------19571958See the explanations of the remote.<name>.url, branch.<name>.remote,1959and remote.<name>.push options in gitlink:git-config[1] for1960details.19611962[[setting-up-a-shared-repository]]1963Setting up a shared repository1964~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~19651966Another way to collaborate is by using a model similar to that1967commonly used in CVS, where several developers with special rights1968all push to and pull from a single shared repository. See1969link:cvs-migration.html[git for CVS users] for instructions on how to1970set this up.19711972However, while there is nothing wrong with git's support for shared1973repositories, this mode of operation is not generally recommended,1974simply because the mode of collaboration that git supports--by1975exchanging patches and pulling from public repositories--has so many1976advantages over the central shared repository:19771978 - Git's ability to quickly import and merge patches allows a1979 single maintainer to process incoming changes even at very1980 high rates. And when that becomes too much, git-pull provides1981 an easy way for that maintainer to delegate this job to other1982 maintainers while still allowing optional review of incoming1983 changes.1984 - Since every developer's repository has the same complete copy1985 of the project history, no repository is special, and it is1986 trivial for another developer to take over maintenance of a1987 project, either by mutual agreement, or because a maintainer1988 becomes unresponsive or difficult to work with.1989 - The lack of a central group of "committers" means there is1990 less need for formal decisions about who is "in" and who is1991 "out".19921993[[setting-up-gitweb]]1994Allowing web browsing of a repository1995~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~19961997The gitweb cgi script provides users an easy way to browse your1998project's files and history without having to install git; see the file1999gitweb/INSTALL in the git source tree for instructions on setting it up.20002001[[sharing-development-examples]]2002Examples2003--------20042005[[maintaining-topic-branches]]2006Maintaining topic branches for a Linux subsystem maintainer2007~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~20082009This describes how Tony Luck uses git in his role as maintainer of the2010IA64 architecture for the Linux kernel.20112012He uses two public branches:20132014 - A "test" tree into which patches are initially placed so that they2015 can get some exposure when integrated with other ongoing development.2016 This tree is available to Andrew for pulling into -mm whenever he2017 wants.20182019 - A "release" tree into which tested patches are moved for final sanity2020 checking, and as a vehicle to send them upstream to Linus (by sending2021 him a "please pull" request.)20222023He also uses a set of temporary branches ("topic branches"), each2024containing a logical grouping of patches.20252026To set this up, first create your work tree by cloning Linus's public2027tree:20282029-------------------------------------------------2030$ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git work2031$ cd work2032-------------------------------------------------20332034Linus's tree will be stored in the remote branch named origin/master,2035and can be updated using gitlink:git-fetch[1]; you can track other2036public trees using gitlink:git-remote[1] to set up a "remote" and2037gitlink:git-fetch[1] to keep them up-to-date; see2038<<repositories-and-branches>>.20392040Now create the branches in which you are going to work; these start out2041at the current tip of origin/master branch, and should be set up (using2042the --track option to gitlink:git-branch[1]) to merge changes in from2043Linus by default.20442045-------------------------------------------------2046$ git branch --track test origin/master2047$ git branch --track release origin/master2048-------------------------------------------------20492050These can be easily kept up to date using gitlink:git-pull[1].20512052-------------------------------------------------2053$ git checkout test && git pull2054$ git checkout release && git pull2055-------------------------------------------------20562057Important note! If you have any local changes in these branches, then2058this merge will create a commit object in the history (with no local2059changes git will simply do a "Fast forward" merge). Many people dislike2060the "noise" that this creates in the Linux history, so you should avoid2061doing this capriciously in the "release" branch, as these noisy commits2062will become part of the permanent history when you ask Linus to pull2063from the release branch.20642065A few configuration variables (see gitlink:git-config[1]) can2066make it easy to push both branches to your public tree. (See2067<<setting-up-a-public-repository>>.)20682069-------------------------------------------------2070$ cat >> .git/config <<EOF2071[remote "mytree"]2072 url = master.kernel.org:/pub/scm/linux/kernel/git/aegl/linux-2.6.git2073 push = release2074 push = test2075EOF2076-------------------------------------------------20772078Then you can push both the test and release trees using2079gitlink:git-push[1]:20802081-------------------------------------------------2082$ git push mytree2083-------------------------------------------------20842085or push just one of the test and release branches using:20862087-------------------------------------------------2088$ git push mytree test2089-------------------------------------------------20902091or20922093-------------------------------------------------2094$ git push mytree release2095-------------------------------------------------20962097Now to apply some patches from the community. Think of a short2098snappy name for a branch to hold this patch (or related group of2099patches), and create a new branch from the current tip of Linus's2100branch:21012102-------------------------------------------------2103$ git checkout -b speed-up-spinlocks origin2104-------------------------------------------------21052106Now you apply the patch(es), run some tests, and commit the change(s). If2107the patch is a multi-part series, then you should apply each as a separate2108commit to this branch.21092110-------------------------------------------------2111$ ... patch ... test ... commit [ ... patch ... test ... commit ]*2112-------------------------------------------------21132114When you are happy with the state of this change, you can pull it into the2115"test" branch in preparation to make it public:21162117-------------------------------------------------2118$ git checkout test && git pull . speed-up-spinlocks2119-------------------------------------------------21202121It is unlikely that you would have any conflicts here ... but you might if you2122spent a while on this step and had also pulled new versions from upstream.21232124Some time later when enough time has passed and testing done, you can pull the2125same branch into the "release" tree ready to go upstream. This is where you2126see the value of keeping each patch (or patch series) in its own branch. It2127means that the patches can be moved into the "release" tree in any order.21282129-------------------------------------------------2130$ git checkout release && git pull . speed-up-spinlocks2131-------------------------------------------------21322133After a while, you will have a number of branches, and despite the2134well chosen names you picked for each of them, you may forget what2135they are for, or what status they are in. To get a reminder of what2136changes are in a specific branch, use:21372138-------------------------------------------------2139$ git log linux..branchname | git-shortlog2140-------------------------------------------------21412142To see whether it has already been merged into the test or release branches,2143use:21442145-------------------------------------------------2146$ git log test..branchname2147-------------------------------------------------21482149or21502151-------------------------------------------------2152$ git log release..branchname2153-------------------------------------------------21542155(If this branch has not yet been merged, you will see some log entries.2156If it has been merged, then there will be no output.)21572158Once a patch completes the great cycle (moving from test to release,2159then pulled by Linus, and finally coming back into your local2160"origin/master" branch), the branch for this change is no longer needed.2161You detect this when the output from:21622163-------------------------------------------------2164$ git log origin..branchname2165-------------------------------------------------21662167is empty. At this point the branch can be deleted:21682169-------------------------------------------------2170$ git branch -d branchname2171-------------------------------------------------21722173Some changes are so trivial that it is not necessary to create a separate2174branch and then merge into each of the test and release branches. For2175these changes, just apply directly to the "release" branch, and then2176merge that into the "test" branch.21772178To create diffstat and shortlog summaries of changes to include in a "please2179pull" request to Linus you can use:21802181-------------------------------------------------2182$ git diff --stat origin..release2183-------------------------------------------------21842185and21862187-------------------------------------------------2188$ git log -p origin..release | git shortlog2189-------------------------------------------------21902191Here are some of the scripts that simplify all this even further.21922193-------------------------------------------------2194==== update script ====2195# Update a branch in my GIT tree. If the branch to be updated2196# is origin, then pull from kernel.org. Otherwise merge2197# origin/master branch into test|release branch21982199case "$1" in2200test|release)2201 git checkout $1 && git pull . origin2202 ;;2203origin)2204 before=$(git rev-parse refs/remotes/origin/master)2205 git fetch origin2206 after=$(git rev-parse refs/remotes/origin/master)2207 if [ $before != $after ]2208 then2209 git log $before..$after | git shortlog2210 fi2211 ;;2212*)2213 echo "Usage: $0 origin|test|release" 1>&22214 exit 12215 ;;2216esac2217-------------------------------------------------22182219-------------------------------------------------2220==== merge script ====2221# Merge a branch into either the test or release branch22222223pname=$022242225usage()2226{2227 echo "Usage: $pname branch test|release" 1>&22228 exit 12229}22302231git show-ref -q --verify -- refs/heads/"$1" || {2232 echo "Can't see branch <$1>" 1>&22233 usage2234}22352236case "$2" in2237test|release)2238 if [ $(git log $2..$1 | wc -c) -eq 0 ]2239 then2240 echo $1 already merged into $2 1>&22241 exit 12242 fi2243 git checkout $2 && git pull . $12244 ;;2245*)2246 usage2247 ;;2248esac2249-------------------------------------------------22502251-------------------------------------------------2252==== status script ====2253# report on status of my ia64 GIT tree22542255gb=$(tput setab 2)2256rb=$(tput setab 1)2257restore=$(tput setab 9)22582259if [ `git rev-list test..release | wc -c` -gt 0 ]2260then2261 echo $rb Warning: commits in release that are not in test $restore2262 git log test..release2263fi22642265for branch in `git show-ref --heads | sed 's|^.*/||'`2266do2267 if [ $branch = test -o $branch = release ]2268 then2269 continue2270 fi22712272 echo -n $gb ======= $branch ====== $restore " "2273 status=2274 for ref in test release origin/master2275 do2276 if [ `git rev-list $ref..$branch | wc -c` -gt 0 ]2277 then2278 status=$status${ref:0:1}2279 fi2280 done2281 case $status in2282 trl)2283 echo $rb Need to pull into test $restore2284 ;;2285 rl)2286 echo "In test"2287 ;;2288 l)2289 echo "Waiting for linus"2290 ;;2291 "")2292 echo $rb All done $restore2293 ;;2294 *)2295 echo $rb "<$status>" $restore2296 ;;2297 esac2298 git log origin/master..$branch | git shortlog2299done2300-------------------------------------------------230123022303[[cleaning-up-history]]2304Rewriting history and maintaining patch series2305==============================================23062307Normally commits are only added to a project, never taken away or2308replaced. Git is designed with this assumption, and violating it will2309cause git's merge machinery (for example) to do the wrong thing.23102311However, there is a situation in which it can be useful to violate this2312assumption.23132314[[patch-series]]2315Creating the perfect patch series2316---------------------------------23172318Suppose you are a contributor to a large project, and you want to add a2319complicated feature, and to present it to the other developers in a way2320that makes it easy for them to read your changes, verify that they are2321correct, and understand why you made each change.23222323If you present all of your changes as a single patch (or commit), they2324may find that it is too much to digest all at once.23252326If you present them with the entire history of your work, complete with2327mistakes, corrections, and dead ends, they may be overwhelmed.23282329So the ideal is usually to produce a series of patches such that:23302331 1. Each patch can be applied in order.23322333 2. Each patch includes a single logical change, together with a2334 message explaining the change.23352336 3. No patch introduces a regression: after applying any initial2337 part of the series, the resulting project still compiles and2338 works, and has no bugs that it didn't have before.23392340 4. The complete series produces the same end result as your own2341 (probably much messier!) development process did.23422343We will introduce some tools that can help you do this, explain how to2344use them, and then explain some of the problems that can arise because2345you are rewriting history.23462347[[using-git-rebase]]2348Keeping a patch series up to date using git-rebase2349--------------------------------------------------23502351Suppose that you create a branch "mywork" on a remote-tracking branch2352"origin", and create some commits on top of it:23532354-------------------------------------------------2355$ git checkout -b mywork origin2356$ vi file.txt2357$ git commit2358$ vi otherfile.txt2359$ git commit2360...2361-------------------------------------------------23622363You have performed no merges into mywork, so it is just a simple linear2364sequence of patches on top of "origin":23652366................................................2367 o--o--o <-- origin2368 \2369 o--o--o <-- mywork2370................................................23712372Some more interesting work has been done in the upstream project, and2373"origin" has advanced:23742375................................................2376 o--o--O--o--o--o <-- origin2377 \2378 a--b--c <-- mywork2379................................................23802381At this point, you could use "pull" to merge your changes back in;2382the result would create a new merge commit, like this:23832384................................................2385 o--o--O--o--o--o <-- origin2386 \ \2387 a--b--c--m <-- mywork2388................................................23892390However, if you prefer to keep the history in mywork a simple series of2391commits without any merges, you may instead choose to use2392gitlink:git-rebase[1]:23932394-------------------------------------------------2395$ git checkout mywork2396$ git rebase origin2397-------------------------------------------------23982399This will remove each of your commits from mywork, temporarily saving2400them as patches (in a directory named ".dotest"), update mywork to2401point at the latest version of origin, then apply each of the saved2402patches to the new mywork. The result will look like:240324042405................................................2406 o--o--O--o--o--o <-- origin2407 \2408 a'--b'--c' <-- mywork2409................................................24102411In the process, it may discover conflicts. In that case it will stop2412and allow you to fix the conflicts; after fixing conflicts, use "git2413add" to update the index with those contents, and then, instead of2414running git-commit, just run24152416-------------------------------------------------2417$ git rebase --continue2418-------------------------------------------------24192420and git will continue applying the rest of the patches.24212422At any point you may use the `--abort` option to abort this process and2423return mywork to the state it had before you started the rebase:24242425-------------------------------------------------2426$ git rebase --abort2427-------------------------------------------------24282429[[modifying-one-commit]]2430Modifying a single commit2431-------------------------24322433We saw in <<fixing-a-mistake-by-editing-history>> that you can replace the2434most recent commit using24352436-------------------------------------------------2437$ git commit --amend2438-------------------------------------------------24392440which will replace the old commit by a new commit incorporating your2441changes, giving you a chance to edit the old commit message first.24422443You can also use a combination of this and gitlink:git-rebase[1] to edit2444commits further back in your history. First, tag the problematic commit with24452446-------------------------------------------------2447$ git tag bad mywork~52448-------------------------------------------------24492450(Either gitk or git-log may be useful for finding the commit.)24512452Then check out that commit, edit it, and rebase the rest of the series2453on top of it (note that we could check out the commit on a temporary2454branch, but instead we're using a <<detached-head,detached head>>):24552456-------------------------------------------------2457$ git checkout bad2458$ # make changes here and update the index2459$ git commit --amend2460$ git rebase --onto HEAD bad mywork2461-------------------------------------------------24622463When you're done, you'll be left with mywork checked out, with the top2464patches on mywork reapplied on top of your modified commit. You can2465then clean up with24662467-------------------------------------------------2468$ git tag -d bad2469-------------------------------------------------24702471Note that the immutable nature of git history means that you haven't really2472"modified" existing commits; instead, you have replaced the old commits with2473new commits having new object names.24742475[[reordering-patch-series]]2476Reordering or selecting from a patch series2477-------------------------------------------24782479Given one existing commit, the gitlink:git-cherry-pick[1] command2480allows you to apply the change introduced by that commit and create a2481new commit that records it. So, for example, if "mywork" points to a2482series of patches on top of "origin", you might do something like:24832484-------------------------------------------------2485$ git checkout -b mywork-new origin2486$ gitk origin..mywork &2487-------------------------------------------------24882489and browse through the list of patches in the mywork branch using gitk,2490applying them (possibly in a different order) to mywork-new using2491cherry-pick, and possibly modifying them as you go using `commit --amend`.2492The gitlink:git-gui[1] command may also help as it allows you to2493individually select diff hunks for inclusion in the index (by2494right-clicking on the diff hunk and choosing "Stage Hunk for Commit").24952496Another technique is to use git-format-patch to create a series of2497patches, then reset the state to before the patches:24982499-------------------------------------------------2500$ git format-patch origin2501$ git reset --hard origin2502-------------------------------------------------25032504Then modify, reorder, or eliminate patches as preferred before applying2505them again with gitlink:git-am[1].25062507[[patch-series-tools]]2508Other tools2509-----------25102511There are numerous other tools, such as StGIT, which exist for the2512purpose of maintaining a patch series. These are outside of the scope of2513this manual.25142515[[problems-with-rewriting-history]]2516Problems with rewriting history2517-------------------------------25182519The primary problem with rewriting the history of a branch has to do2520with merging. Suppose somebody fetches your branch and merges it into2521their branch, with a result something like this:25222523................................................2524 o--o--O--o--o--o <-- origin2525 \ \2526 t--t--t--m <-- their branch:2527................................................25282529Then suppose you modify the last three commits:25302531................................................2532 o--o--o <-- new head of origin2533 /2534 o--o--O--o--o--o <-- old head of origin2535................................................25362537If we examined all this history together in one repository, it will2538look like:25392540................................................2541 o--o--o <-- new head of origin2542 /2543 o--o--O--o--o--o <-- old head of origin2544 \ \2545 t--t--t--m <-- their branch:2546................................................25472548Git has no way of knowing that the new head is an updated version of2549the old head; it treats this situation exactly the same as it would if2550two developers had independently done the work on the old and new heads2551in parallel. At this point, if someone attempts to merge the new head2552in to their branch, git will attempt to merge together the two (old and2553new) lines of development, instead of trying to replace the old by the2554new. The results are likely to be unexpected.25552556You may still choose to publish branches whose history is rewritten,2557and it may be useful for others to be able to fetch those branches in2558order to examine or test them, but they should not attempt to pull such2559branches into their own work.25602561For true distributed development that supports proper merging,2562published branches should never be rewritten.25632564[[bisect-merges]]2565Why bisecting merge commits can be harder than bisecting linear history2566-----------------------------------------------------------------------25672568The gitlink:git-bisect[1] command correctly handles history that2569includes merge commits. However, when the commit that it finds is a2570merge commit, the user may need to work harder than usual to figure out2571why that commit introduced a problem.25722573Imagine this history:25742575................................................2576 ---Z---o---X---...---o---A---C---D2577 \ /2578 o---o---Y---...---o---B2579................................................25802581Suppose that on the upper line of development, the meaning of one2582of the functions that exists at Z is changed at commit X. The2583commits from Z leading to A change both the function's2584implementation and all calling sites that exist at Z, as well2585as new calling sites they add, to be consistent. There is no2586bug at A.25872588Suppose that in the meantime on the lower line of development somebody2589adds a new calling site for that function at commit Y. The2590commits from Z leading to B all assume the old semantics of that2591function and the callers and the callee are consistent with each2592other. There is no bug at B, either.25932594Suppose further that the two development lines merge cleanly at C,2595so no conflict resolution is required.25962597Nevertheless, the code at C is broken, because the callers added2598on the lower line of development have not been converted to the new2599semantics introduced on the upper line of development. So if all2600you know is that D is bad, that Z is good, and that2601gitlink:git-bisect[1] identifies C as the culprit, how will you2602figure out that the problem is due to this change in semantics?26032604When the result of a git-bisect is a non-merge commit, you should2605normally be able to discover the problem by examining just that commit.2606Developers can make this easy by breaking their changes into small2607self-contained commits. That won't help in the case above, however,2608because the problem isn't obvious from examination of any single2609commit; instead, a global view of the development is required. To2610make matters worse, the change in semantics in the problematic2611function may be just one small part of the changes in the upper2612line of development.26132614On the other hand, if instead of merging at C you had rebased the2615history between Z to B on top of A, you would have gotten this2616linear history:26172618................................................................2619 ---Z---o---X--...---o---A---o---o---Y*--...---o---B*--D*2620................................................................26212622Bisecting between Z and D* would hit a single culprit commit Y*,2623and understanding why Y* was broken would probably be easier.26242625Partly for this reason, many experienced git users, even when2626working on an otherwise merge-heavy project, keep the history2627linear by rebasing against the latest upstream version before2628publishing.26292630[[advanced-branch-management]]2631Advanced branch management2632==========================26332634[[fetching-individual-branches]]2635Fetching individual branches2636----------------------------26372638Instead of using gitlink:git-remote[1], you can also choose just2639to update one branch at a time, and to store it locally under an2640arbitrary name:26412642-------------------------------------------------2643$ git fetch origin todo:my-todo-work2644-------------------------------------------------26452646The first argument, "origin", just tells git to fetch from the2647repository you originally cloned from. The second argument tells git2648to fetch the branch named "todo" from the remote repository, and to2649store it locally under the name refs/heads/my-todo-work.26502651You can also fetch branches from other repositories; so26522653-------------------------------------------------2654$ git fetch git://example.com/proj.git master:example-master2655-------------------------------------------------26562657will create a new branch named "example-master" and store in it the2658branch named "master" from the repository at the given URL. If you2659already have a branch named example-master, it will attempt to2660<<fast-forwards,fast-forward>> to the commit given by example.com's2661master branch. In more detail:26622663[[fetch-fast-forwards]]2664git fetch and fast-forwards2665---------------------------26662667In the previous example, when updating an existing branch, "git2668fetch" checks to make sure that the most recent commit on the remote2669branch is a descendant of the most recent commit on your copy of the2670branch before updating your copy of the branch to point at the new2671commit. Git calls this process a <<fast-forwards,fast forward>>.26722673A fast forward looks something like this:26742675................................................2676 o--o--o--o <-- old head of the branch2677 \2678 o--o--o <-- new head of the branch2679................................................268026812682In some cases it is possible that the new head will *not* actually be2683a descendant of the old head. For example, the developer may have2684realized she made a serious mistake, and decided to backtrack,2685resulting in a situation like:26862687................................................2688 o--o--o--o--a--b <-- old head of the branch2689 \2690 o--o--o <-- new head of the branch2691................................................26922693In this case, "git fetch" will fail, and print out a warning.26942695In that case, you can still force git to update to the new head, as2696described in the following section. However, note that in the2697situation above this may mean losing the commits labeled "a" and "b",2698unless you've already created a reference of your own pointing to2699them.27002701[[forcing-fetch]]2702Forcing git fetch to do non-fast-forward updates2703------------------------------------------------27042705If git fetch fails because the new head of a branch is not a2706descendant of the old head, you may force the update with:27072708-------------------------------------------------2709$ git fetch git://example.com/proj.git +master:refs/remotes/example/master2710-------------------------------------------------27112712Note the addition of the "+" sign. Alternatively, you can use the "-f"2713flag to force updates of all the fetched branches, as in:27142715-------------------------------------------------2716$ git fetch -f origin2717-------------------------------------------------27182719Be aware that commits that the old version of example/master pointed at2720may be lost, as we saw in the previous section.27212722[[remote-branch-configuration]]2723Configuring remote branches2724---------------------------27252726We saw above that "origin" is just a shortcut to refer to the2727repository that you originally cloned from. This information is2728stored in git configuration variables, which you can see using2729gitlink:git-config[1]:27302731-------------------------------------------------2732$ git config -l2733core.repositoryformatversion=02734core.filemode=true2735core.logallrefupdates=true2736remote.origin.url=git://git.kernel.org/pub/scm/git/git.git2737remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*2738branch.master.remote=origin2739branch.master.merge=refs/heads/master2740-------------------------------------------------27412742If there are other repositories that you also use frequently, you can2743create similar configuration options to save typing; for example,2744after27452746-------------------------------------------------2747$ git config remote.example.url git://example.com/proj.git2748-------------------------------------------------27492750then the following two commands will do the same thing:27512752-------------------------------------------------2753$ git fetch git://example.com/proj.git master:refs/remotes/example/master2754$ git fetch example master:refs/remotes/example/master2755-------------------------------------------------27562757Even better, if you add one more option:27582759-------------------------------------------------2760$ git config remote.example.fetch master:refs/remotes/example/master2761-------------------------------------------------27622763then the following commands will all do the same thing:27642765-------------------------------------------------2766$ git fetch git://example.com/proj.git master:refs/remotes/example/master2767$ git fetch example master:refs/remotes/example/master2768$ git fetch example2769-------------------------------------------------27702771You can also add a "+" to force the update each time:27722773-------------------------------------------------2774$ git config remote.example.fetch +master:ref/remotes/example/master2775-------------------------------------------------27762777Don't do this unless you're sure you won't mind "git fetch" possibly2778throwing away commits on mybranch.27792780Also note that all of the above configuration can be performed by2781directly editing the file .git/config instead of using2782gitlink:git-config[1].27832784See gitlink:git-config[1] for more details on the configuration2785options mentioned above.278627872788[[git-concepts]]2789Git concepts2790============27912792Git is built on a small number of simple but powerful ideas. While it2793is possible to get things done without understanding them, you will find2794git much more intuitive if you do.27952796We start with the most important, the <<def_object_database,object2797database>> and the <<def_index,index>>.27982799[[the-object-database]]2800The Object Database2801-------------------280228032804We already saw in <<understanding-commits>> that all commits are stored2805under a 40-digit "object name". In fact, all the information needed to2806represent the history of a project is stored in objects with such names.2807In each case the name is calculated by taking the SHA1 hash of the2808contents of the object. The SHA1 hash is a cryptographic hash function.2809What that means to us is that it is impossible to find two different2810objects with the same name. This has a number of advantages; among2811others:28122813- Git can quickly determine whether two objects are identical or not,2814 just by comparing names.2815- Since object names are computed the same way in every repository, the2816 same content stored in two repositories will always be stored under2817 the same name.2818- Git can detect errors when it reads an object, by checking that the2819 object's name is still the SHA1 hash of its contents.28202821(See <<object-details>> for the details of the object formatting and2822SHA1 calculation.)28232824There are four different types of objects: "blob", "tree", "commit", and2825"tag".28262827- A <<def_blob_object,"blob" object>> is used to store file data.2828- A <<def_tree_object,"tree" object>> is an object that ties one or more2829 "blob" objects into a directory structure. In addition, a tree object2830 can refer to other tree objects, thus creating a directory hierarchy.2831- A <<def_commit_object,"commit" object>> ties such directory hierarchies2832 together into a <<def_DAG,directed acyclic graph>> of revisions--each2833 commit contains the object name of exactly one tree designating the2834 directory hierarchy at the time of the commit. In addition, a commit2835 refers to "parent" commit objects that describe the history of how we2836 arrived at that directory hierarchy.2837- A <<def_tag_object,"tag" object>> symbolically identifies and can be2838 used to sign other objects. It contains the object name and type of2839 another object, a symbolic name (of course!) and, optionally, a2840 signature.28412842The object types in some more detail:28432844[[commit-object]]2845Commit Object2846~~~~~~~~~~~~~28472848The "commit" object links a physical state of a tree with a description2849of how we got there and why. Use the --pretty=raw option to2850gitlink:git-show[1] or gitlink:git-log[1] to examine your favorite2851commit:28522853------------------------------------------------2854$ git show -s --pretty=raw 2be7fcb4762855commit 2be7fcb4764f2dbcee52635b91fedb1b3dcf7ab42856tree fb3a8bdd0ceddd019615af4d57a53f43d8cee2bf2857parent 257a84d9d02e90447b149af58b271c19405edb6a2858author Dave Watson <dwatson@mimvista.com> 1187576872 -04002859committer Junio C Hamano <gitster@pobox.com> 1187591163 -070028602861 Fix misspelling of 'suppress' in docs28622863 Signed-off-by: Junio C Hamano <gitster@pobox.com>2864------------------------------------------------28652866As you can see, a commit is defined by:28672868- a tree: The SHA1 name of a tree object (as defined below), representing2869 the contents of a directory at a certain point in time.2870- parent(s): The SHA1 name of some number of commits which represent the2871 immediately prevoius step(s) in the history of the project. The2872 example above has one parent; merge commits may have more than2873 one. A commit with no parents is called a "root" commit, and2874 represents the initial revision of a project. Each project must have2875 at least one root. A project can also have multiple roots, though2876 that isn't common (or necessarily a good idea).2877- an author: The name of the person responsible for this change, together2878 with its date.2879- a committer: The name of the person who actually created the commit,2880 with the date it was done. This may be different from the author, for2881 example, if the author was someone who wrote a patch and emailed it2882 to the person who used it to create the commit.2883- a comment describing this commit.28842885Note that a commit does not itself contain any information about what2886actually changed; all changes are calculated by comparing the contents2887of the tree referred to by this commit with the trees associated with2888its parents. In particular, git does not attempt to record file renames2889explicitly, though it can identify cases where the existence of the same2890file data at changing paths suggests a rename. (See, for example, the2891-M option to gitlink:git-diff[1]).28922893A commit is usually created by gitlink:git-commit[1], which creates a2894commit whose parent is normally the current HEAD, and whose tree is2895taken from the content currently stored in the index.28962897[[tree-object]]2898Tree Object2899~~~~~~~~~~~29002901The ever-versatile gitlink:git-show[1] command can also be used to2902examine tree objects, but gitlink:git-ls-tree[1] will give you more2903details:29042905------------------------------------------------2906$ git ls-tree fb3a8bdd0ce2907100644 blob 63c918c667fa005ff12ad89437f2fdc80926e21c .gitignore2908100644 blob 5529b198e8d14decbe4ad99db3f7fb632de0439d .mailmap2909100644 blob 6ff87c4664981e4397625791c8ea3bbb5f2279a3 COPYING2910040000 tree 2fb783e477100ce076f6bf57e4a6f026013dc745 Documentation2911100755 blob 3c0032cec592a765692234f1cba47dfdcc3a9200 GIT-VERSION-GEN2912100644 blob 289b046a443c0647624607d471289b2c7dcd470b INSTALL2913100644 blob 4eb463797adc693dc168b926b6932ff53f17d0b1 Makefile2914100644 blob 548142c327a6790ff8821d67c2ee1eff7a656b52 README2915...2916------------------------------------------------29172918As you can see, a tree object contains a list of entries, each with a2919mode, object type, SHA1 name, and name, sorted by name. It represents2920the contents of a single directory tree.29212922The object type may be a blob, representing the contents of a file, or2923another tree, representing the contents of a subdirectory. Since trees2924and blobs, like all other objects, are named by the SHA1 hash of their2925contents, two trees have the same SHA1 name if and only if their2926contents (including, recursively, the contents of all subdirectories)2927are identical. This allows git to quickly determine the differences2928between two related tree objects, since it can ignore any entries with2929identical object names.29302931(Note: in the presence of submodules, trees may also have commits as2932entries. See <<submodules>> for documentation.)29332934Note that the files all have mode 644 or 755: git actually only pays2935attention to the executable bit.29362937[[blob-object]]2938Blob Object2939~~~~~~~~~~~29402941You can use gitlink:git-show[1] to examine the contents of a blob; take,2942for example, the blob in the entry for "COPYING" from the tree above:29432944------------------------------------------------2945$ git show 6ff87c466429462947 Note that the only valid version of the GPL as far as this project2948 is concerned is _this_ particular version of the license (ie v2, not2949 v2.2 or v3.x or whatever), unless explicitly otherwise stated.2950...2951------------------------------------------------29522953A "blob" object is nothing but a binary blob of data. It doesn't refer2954to anything else or have attributes of any kind.29552956Since the blob is entirely defined by its data, if two files in a2957directory tree (or in multiple different versions of the repository)2958have the same contents, they will share the same blob object. The object2959is totally independent of its location in the directory tree, and2960renaming a file does not change the object that file is associated with.29612962Note that any tree or blob object can be examined using2963gitlink:git-show[1] with the <revision>:<path> syntax. This can2964sometimes be useful for browsing the contents of a tree that is not2965currently checked out.29662967[[trust]]2968Trust2969~~~~~29702971If you receive the SHA1 name of a blob from one source, and its contents2972from another (possibly untrusted) source, you can still trust that those2973contents are correct as long as the SHA1 name agrees. This is because2974the SHA1 is designed so that it is infeasible to find different contents2975that produce the same hash.29762977Similarly, you need only trust the SHA1 name of a top-level tree object2978to trust the contents of the entire directory that it refers to, and if2979you receive the SHA1 name of a commit from a trusted source, then you2980can easily verify the entire history of commits reachable through2981parents of that commit, and all of those contents of the trees referred2982to by those commits.29832984So to introduce some real trust in the system, the only thing you need2985to do is to digitally sign just 'one' special note, which includes the2986name of a top-level commit. Your digital signature shows others2987that you trust that commit, and the immutability of the history of2988commits tells others that they can trust the whole history.29892990In other words, you can easily validate a whole archive by just2991sending out a single email that tells the people the name (SHA1 hash)2992of the top commit, and digitally sign that email using something2993like GPG/PGP.29942995To assist in this, git also provides the tag object...29962997[[tag-object]]2998Tag Object2999~~~~~~~~~~30003001A tag object contains an object, object type, tag name, the name of the3002person ("tagger") who created the tag, and a message, which may contain3003a signature, as can be seen using the gitlink:git-cat-file[1]:30043005------------------------------------------------3006$ git cat-file tag v1.5.03007object 437b1b20df4b356c9342dac8d38849f24ef44f273008type commit3009tag v1.5.03010tagger Junio C Hamano <junkio@cox.net> 1171411200 +000030113012GIT 1.5.03013-----BEGIN PGP SIGNATURE-----3014Version: GnuPG v1.4.6 (GNU/Linux)30153016iD8DBQBF0lGqwMbZpPMRm5oRAuRiAJ9ohBLd7s2kqjkKlq1qqC57SbnmzQCdG4ui3017nLE/L9aUXdWeTFPron96DLA=3018=2E+03019-----END PGP SIGNATURE-----3020------------------------------------------------30213022See the gitlink:git-tag[1] command to learn how to create and verify tag3023objects. (Note that gitlink:git-tag[1] can also be used to create3024"lightweight tags", which are not tag objects at all, but just simple3025references whose names begin with "refs/tags/").30263027[[pack-files]]3028How git stores objects efficiently: pack files3029~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~30303031Newly created objects are initially created in a file named after the3032object's SHA1 hash (stored in .git/objects).30333034Unfortunately this system becomes inefficient once a project has a3035lot of objects. Try this on an old project:30363037------------------------------------------------3038$ git count-objects30396930 objects, 47620 kilobytes3040------------------------------------------------30413042The first number is the number of objects which are kept in3043individual files. The second is the amount of space taken up by3044those "loose" objects.30453046You can save space and make git faster by moving these loose objects in3047to a "pack file", which stores a group of objects in an efficient3048compressed format; the details of how pack files are formatted can be3049found in link:technical/pack-format.txt[technical/pack-format.txt].30503051To put the loose objects into a pack, just run git repack:30523053------------------------------------------------3054$ git repack3055Generating pack...3056Done counting 6020 objects.3057Deltifying 6020 objects.3058 100% (6020/6020) done3059Writing 6020 objects.3060 100% (6020/6020) done3061Total 6020, written 6020 (delta 4070), reused 0 (delta 0)3062Pack pack-3e54ad29d5b2e05838c75df582c65257b8d08e1c created.3063------------------------------------------------30643065You can then run30663067------------------------------------------------3068$ git prune3069------------------------------------------------30703071to remove any of the "loose" objects that are now contained in the3072pack. This will also remove any unreferenced objects (which may be3073created when, for example, you use "git reset" to remove a commit).3074You can verify that the loose objects are gone by looking at the3075.git/objects directory or by running30763077------------------------------------------------3078$ git count-objects30790 objects, 0 kilobytes3080------------------------------------------------30813082Although the object files are gone, any commands that refer to those3083objects will work exactly as they did before.30843085The gitlink:git-gc[1] command performs packing, pruning, and more for3086you, so is normally the only high-level command you need.30873088[[dangling-objects]]3089Dangling objects3090~~~~~~~~~~~~~~~~30913092The gitlink:git-fsck[1] command will sometimes complain about dangling3093objects. They are not a problem.30943095The most common cause of dangling objects is that you've rebased a3096branch, or you have pulled from somebody else who rebased a branch--see3097<<cleaning-up-history>>. In that case, the old head of the original3098branch still exists, as does everything it pointed to. The branch3099pointer itself just doesn't, since you replaced it with another one.31003101There are also other situations that cause dangling objects. For3102example, a "dangling blob" may arise because you did a "git add" of a3103file, but then, before you actually committed it and made it part of the3104bigger picture, you changed something else in that file and committed3105that *updated* thing--the old state that you added originally ends up3106not being pointed to by any commit or tree, so it's now a dangling blob3107object.31083109Similarly, when the "recursive" merge strategy runs, and finds that3110there are criss-cross merges and thus more than one merge base (which is3111fairly unusual, but it does happen), it will generate one temporary3112midway tree (or possibly even more, if you had lots of criss-crossing3113merges and more than two merge bases) as a temporary internal merge3114base, and again, those are real objects, but the end result will not end3115up pointing to them, so they end up "dangling" in your repository.31163117Generally, dangling objects aren't anything to worry about. They can3118even be very useful: if you screw something up, the dangling objects can3119be how you recover your old tree (say, you did a rebase, and realized3120that you really didn't want to--you can look at what dangling objects3121you have, and decide to reset your head to some old dangling state).31223123For commits, you can just use:31243125------------------------------------------------3126$ gitk <dangling-commit-sha-goes-here> --not --all3127------------------------------------------------31283129This asks for all the history reachable from the given commit but not3130from any branch, tag, or other reference. If you decide it's something3131you want, you can always create a new reference to it, e.g.,31323133------------------------------------------------3134$ git branch recovered-branch <dangling-commit-sha-goes-here>3135------------------------------------------------31363137For blobs and trees, you can't do the same, but you can still examine3138them. You can just do31393140------------------------------------------------3141$ git show <dangling-blob/tree-sha-goes-here>3142------------------------------------------------31433144to show what the contents of the blob were (or, for a tree, basically3145what the "ls" for that directory was), and that may give you some idea3146of what the operation was that left that dangling object.31473148Usually, dangling blobs and trees aren't very interesting. They're3149almost always the result of either being a half-way mergebase (the blob3150will often even have the conflict markers from a merge in it, if you3151have had conflicting merges that you fixed up by hand), or simply3152because you interrupted a "git fetch" with ^C or something like that,3153leaving _some_ of the new objects in the object database, but just3154dangling and useless.31553156Anyway, once you are sure that you're not interested in any dangling3157state, you can just prune all unreachable objects:31583159------------------------------------------------3160$ git prune3161------------------------------------------------31623163and they'll be gone. But you should only run "git prune" on a quiescent3164repository--it's kind of like doing a filesystem fsck recovery: you3165don't want to do that while the filesystem is mounted.31663167(The same is true of "git-fsck" itself, btw, but since3168git-fsck never actually *changes* the repository, it just reports3169on what it found, git-fsck itself is never "dangerous" to run.3170Running it while somebody is actually changing the repository can cause3171confusing and scary messages, but it won't actually do anything bad. In3172contrast, running "git prune" while somebody is actively changing the3173repository is a *BAD* idea).31743175[[the-index]]3176The index3177-----------31783179The index is a binary file (generally kept in .git/index) containing a3180sorted list of path names, each with permissions and the SHA1 of a blob3181object; gitlink:git-ls-files[1] can show you the contents of the index:31823183-------------------------------------------------3184$ git ls-files --stage3185100644 63c918c667fa005ff12ad89437f2fdc80926e21c 0 .gitignore3186100644 5529b198e8d14decbe4ad99db3f7fb632de0439d 0 .mailmap3187100644 6ff87c4664981e4397625791c8ea3bbb5f2279a3 0 COPYING3188100644 a37b2152bd26be2c2289e1f57a292534a51a93c7 0 Documentation/.gitignore3189100644 fbefe9a45b00a54b58d94d06eca48b03d40a50e0 0 Documentation/Makefile3190...3191100644 2511aef8d89ab52be5ec6a5e46236b4b6bcd07ea 0 xdiff/xtypes.h3192100644 2ade97b2574a9f77e7ae4002a4e07a6a38e46d07 0 xdiff/xutils.c3193100644 d5de8292e05e7c36c4b68857c1cf9855e3d2f70a 0 xdiff/xutils.h3194-------------------------------------------------31953196Note that in older documentation you may see the index called the3197"current directory cache" or just the "cache". It has three important3198properties:319932001. The index contains all the information necessary to generate a single3201(uniquely determined) tree object.3202+3203For example, running gitlink:git-commit[1] generates this tree object3204from the index, stores it in the object database, and uses it as the3205tree object associated with the new commit.320632072. The index enables fast comparisons between the tree object it defines3208and the working tree.3209+3210It does this by storing some additional data for each entry (such as3211the last modified time). This data is not displayed above, and is not3212stored in the created tree object, but it can be used to determine3213quickly which files in the working directory differ from what was3214stored in the index, and thus save git from having to read all of the3215data from such files to look for changes.321632173. It can efficiently represent information about merge conflicts3218between different tree objects, allowing each pathname to be3219associated with sufficient information about the trees involved that3220you can create a three-way merge between them.3221+3222We saw in <<conflict-resolution>> that during a merge the index can3223store multiple versions of a single file (called "stages"). The third3224column in the gitlink:git-ls-files[1] output above is the stage3225number, and will take on values other than 0 for files with merge3226conflicts.32273228The index is thus a sort of temporary staging area, which is filled with3229a tree which you are in the process of working on.32303231If you blow the index away entirely, you generally haven't lost any3232information as long as you have the name of the tree that it described.32333234[[submodules]]3235Submodules3236==========32373238Large projects are often composed of smaller, self-contained modules. For3239example, an embedded Linux distribution's source tree would include every3240piece of software in the distribution with some local modifications; a movie3241player might need to build against a specific, known-working version of a3242decompression library; several independent programs might all share the same3243build scripts.32443245With centralized revision control systems this is often accomplished by3246including every module in one single repository. Developers can check out3247all modules or only the modules they need to work with. They can even modify3248files across several modules in a single commit while moving things around3249or updating APIs and translations.32503251Git does not allow partial checkouts, so duplicating this approach in Git3252would force developers to keep a local copy of modules they are not3253interested in touching. Commits in an enormous checkout would be slower3254than you'd expect as Git would have to scan every directory for changes.3255If modules have a lot of local history, clones would take forever.32563257On the plus side, distributed revision control systems can much better3258integrate with external sources. In a centralized model, a single arbitrary3259snapshot of the external project is exported from its own revision control3260and then imported into the local revision control on a vendor branch. All3261the history is hidden. With distributed revision control you can clone the3262entire external history and much more easily follow development and re-merge3263local changes.32643265Git's submodule support allows a repository to contain, as a subdirectory, a3266checkout of an external project. Submodules maintain their own identity;3267the submodule support just stores the submodule repository location and3268commit ID, so other developers who clone the containing project3269("superproject") can easily clone all the submodules at the same revision.3270Partial checkouts of the superproject are possible: you can tell Git to3271clone none, some or all of the submodules.32723273The gitlink:git-submodule[1] command is available since Git 1.5.3. Users3274with Git 1.5.2 can look up the submodule commits in the repository and3275manually check them out; earlier versions won't recognize the submodules at3276all.32773278To see how submodule support works, create (for example) four example3279repositories that can be used later as a submodule:32803281-------------------------------------------------3282$ mkdir ~/git3283$ cd ~/git3284$ for i in a b c d3285do3286 mkdir $i3287 cd $i3288 git init3289 echo "module $i" > $i.txt3290 git add $i.txt3291 git commit -m "Initial commit, submodule $i"3292 cd ..3293done3294-------------------------------------------------32953296Now create the superproject and add all the submodules:32973298-------------------------------------------------3299$ mkdir super3300$ cd super3301$ git init3302$ for i in a b c d3303do3304 git submodule add ~/git/$i3305done3306-------------------------------------------------33073308NOTE: Do not use local URLs here if you plan to publish your superproject!33093310See what files `git submodule` created:33113312-------------------------------------------------3313$ ls -a3314. .. .git .gitmodules a b c d3315-------------------------------------------------33163317The `git submodule add` command does a couple of things:33183319- It clones the submodule under the current directory and by default checks out3320 the master branch.3321- It adds the submodule's clone path to the gitlink:gitmodules[5] file and3322 adds this file to the index, ready to be committed.3323- It adds the submodule's current commit ID to the index, ready to be3324 committed.33253326Commit the superproject:33273328-------------------------------------------------3329$ git commit -m "Add submodules a, b, c and d."3330-------------------------------------------------33313332Now clone the superproject:33333334-------------------------------------------------3335$ cd ..3336$ git clone super cloned3337$ cd cloned3338-------------------------------------------------33393340The submodule directories are there, but they're empty:33413342-------------------------------------------------3343$ ls -a a3344. ..3345$ git submodule status3346-d266b9873ad50488163457f025db7cdd9683d88b a3347-e81d457da15309b4fef4249aba9b50187999670d b3348-c1536a972b9affea0f16e0680ba87332dc059146 c3349-d96249ff5d57de5de093e6baff9e0aafa5276a74 d3350-------------------------------------------------33513352NOTE: The commit object names shown above would be different for you, but they3353should match the HEAD commit object names of your repositories. You can check3354it by running `git ls-remote ../a`.33553356Pulling down the submodules is a two-step process. First run `git submodule3357init` to add the submodule repository URLs to `.git/config`:33583359-------------------------------------------------3360$ git submodule init3361-------------------------------------------------33623363Now use `git submodule update` to clone the repositories and check out the3364commits specified in the superproject:33653366-------------------------------------------------3367$ git submodule update3368$ cd a3369$ ls -a3370. .. .git a.txt3371-------------------------------------------------33723373One major difference between `git submodule update` and `git submodule add` is3374that `git submodule update` checks out a specific commit, rather than the tip3375of a branch. It's like checking out a tag: the head is detached, so you're not3376working on a branch.33773378-------------------------------------------------3379$ git branch3380* (no branch)3381 master3382-------------------------------------------------33833384If you want to make a change within a submodule and you have a detached head,3385then you should create or checkout a branch, make your changes, publish the3386change within the submodule, and then update the superproject to reference the3387new commit:33883389-------------------------------------------------3390$ git checkout master3391-------------------------------------------------33923393or33943395-------------------------------------------------3396$ git checkout -b fix-up3397-------------------------------------------------33983399then34003401-------------------------------------------------3402$ echo "adding a line again" >> a.txt3403$ git commit -a -m "Updated the submodule from within the superproject."3404$ git push3405$ cd ..3406$ git diff3407diff --git a/a b/a3408index d266b98..261dfac 1600003409--- a/a3410+++ b/a3411@@ -1 +1 @@3412-Subproject commit d266b9873ad50488163457f025db7cdd9683d88b3413+Subproject commit 261dfac35cb99d380eb966e102c1197139f7fa243414$ git add a3415$ git commit -m "Updated submodule a."3416$ git push3417-------------------------------------------------34183419You have to run `git submodule update` after `git pull` if you want to update3420submodules, too.34213422Pitfalls with submodules3423------------------------34243425Always publish the submodule change before publishing the change to the3426superproject that references it. If you forget to publish the submodule change,3427others won't be able to clone the repository:34283429-------------------------------------------------3430$ cd ~/git/super/a3431$ echo i added another line to this file >> a.txt3432$ git commit -a -m "doing it wrong this time"3433$ cd ..3434$ git add a3435$ git commit -m "Updated submodule a again."3436$ git push3437$ cd ~/git/cloned3438$ git pull3439$ git submodule update3440error: pathspec '261dfac35cb99d380eb966e102c1197139f7fa24' did not match any file(s) known to git.3441Did you forget to 'git add'?3442Unable to checkout '261dfac35cb99d380eb966e102c1197139f7fa24' in submodule path 'a'3443-------------------------------------------------34443445You also should not rewind branches in a submodule beyond commits that were3446ever recorded in any superproject.34473448It's not safe to run `git submodule update` if you've made and committed3449changes within a submodule without checking out a branch first. They will be3450silently overwritten:34513452-------------------------------------------------3453$ cat a.txt3454module a3455$ echo line added from private2 >> a.txt3456$ git commit -a -m "line added inside private2"3457$ cd ..3458$ git submodule update3459Submodule path 'a': checked out 'd266b9873ad50488163457f025db7cdd9683d88b'3460$ cd a3461$ cat a.txt3462module a3463-------------------------------------------------34643465NOTE: The changes are still visible in the submodule's reflog.34663467This is not the case if you did not commit your changes.34683469[[low-level-operations]]3470Low-level git operations3471========================34723473Many of the higher-level commands were originally implemented as shell3474scripts using a smaller core of low-level git commands. These can still3475be useful when doing unusual things with git, or just as a way to3476understand its inner workings.34773478[[object-manipulation]]3479Object access and manipulation3480------------------------------34813482The gitlink:git-cat-file[1] command can show the contents of any object,3483though the higher-level gitlink:git-show[1] is usually more useful.34843485The gitlink:git-commit-tree[1] command allows constructing commits with3486arbitrary parents and trees.34873488A tree can be created with gitlink:git-write-tree[1] and its data can be3489accessed by gitlink:git-ls-tree[1]. Two trees can be compared with3490gitlink:git-diff-tree[1].34913492A tag is created with gitlink:git-mktag[1], and the signature can be3493verified by gitlink:git-verify-tag[1], though it is normally simpler to3494use gitlink:git-tag[1] for both.34953496[[the-workflow]]3497The Workflow3498------------34993500High-level operations such as gitlink:git-commit[1],3501gitlink:git-checkout[1] and gitlink:git-reset[1] work by moving data3502between the working tree, the index, and the object database. Git3503provides low-level operations which perform each of these steps3504individually.35053506Generally, all "git" operations work on the index file. Some operations3507work *purely* on the index file (showing the current state of the3508index), but most operations move data between the index file and either3509the database or the working directory. Thus there are four main3510combinations:35113512[[working-directory-to-index]]3513working directory -> index3514~~~~~~~~~~~~~~~~~~~~~~~~~~35153516The gitlink:git-update-index[1] command updates the index with3517information from the working directory. You generally update the3518index information by just specifying the filename you want to update,3519like so:35203521-------------------------------------------------3522$ git update-index filename3523-------------------------------------------------35243525but to avoid common mistakes with filename globbing etc, the command3526will not normally add totally new entries or remove old entries,3527i.e. it will normally just update existing cache entries.35283529To tell git that yes, you really do realize that certain files no3530longer exist, or that new files should be added, you3531should use the `--remove` and `--add` flags respectively.35323533NOTE! A `--remove` flag does 'not' mean that subsequent filenames will3534necessarily be removed: if the files still exist in your directory3535structure, the index will be updated with their new status, not3536removed. The only thing `--remove` means is that update-cache will be3537considering a removed file to be a valid thing, and if the file really3538does not exist any more, it will update the index accordingly.35393540As a special case, you can also do `git-update-index --refresh`, which3541will refresh the "stat" information of each index to match the current3542stat information. It will 'not' update the object status itself, and3543it will only update the fields that are used to quickly test whether3544an object still matches its old backing store object.35453546The previously introduced gitlink:git-add[1] is just a wrapper for3547gitlink:git-update-index[1].35483549[[index-to-object-database]]3550index -> object database3551~~~~~~~~~~~~~~~~~~~~~~~~35523553You write your current index file to a "tree" object with the program35543555-------------------------------------------------3556$ git write-tree3557-------------------------------------------------35583559that doesn't come with any options--it will just write out the3560current index into the set of tree objects that describe that state,3561and it will return the name of the resulting top-level tree. You can3562use that tree to re-generate the index at any time by going in the3563other direction:35643565[[object-database-to-index]]3566object database -> index3567~~~~~~~~~~~~~~~~~~~~~~~~35683569You read a "tree" file from the object database, and use that to3570populate (and overwrite--don't do this if your index contains any3571unsaved state that you might want to restore later!) your current3572index. Normal operation is just35733574-------------------------------------------------3575$ git-read-tree <sha1 of tree>3576-------------------------------------------------35773578and your index file will now be equivalent to the tree that you saved3579earlier. However, that is only your 'index' file: your working3580directory contents have not been modified.35813582[[index-to-working-directory]]3583index -> working directory3584~~~~~~~~~~~~~~~~~~~~~~~~~~35853586You update your working directory from the index by "checking out"3587files. This is not a very common operation, since normally you'd just3588keep your files updated, and rather than write to your working3589directory, you'd tell the index files about the changes in your3590working directory (i.e. `git-update-index`).35913592However, if you decide to jump to a new version, or check out somebody3593else's version, or just restore a previous tree, you'd populate your3594index file with read-tree, and then you need to check out the result3595with35963597-------------------------------------------------3598$ git-checkout-index filename3599-------------------------------------------------36003601or, if you want to check out all of the index, use `-a`.36023603NOTE! git-checkout-index normally refuses to overwrite old files, so3604if you have an old version of the tree already checked out, you will3605need to use the "-f" flag ('before' the "-a" flag or the filename) to3606'force' the checkout.360736083609Finally, there are a few odds and ends which are not purely moving3610from one representation to the other:36113612[[tying-it-all-together]]3613Tying it all together3614~~~~~~~~~~~~~~~~~~~~~36153616To commit a tree you have instantiated with "git-write-tree", you'd3617create a "commit" object that refers to that tree and the history3618behind it--most notably the "parent" commits that preceded it in3619history.36203621Normally a "commit" has one parent: the previous state of the tree3622before a certain change was made. However, sometimes it can have two3623or more parent commits, in which case we call it a "merge", due to the3624fact that such a commit brings together ("merges") two or more3625previous states represented by other commits.36263627In other words, while a "tree" represents a particular directory state3628of a working directory, a "commit" represents that state in "time",3629and explains how we got there.36303631You create a commit object by giving it the tree that describes the3632state at the time of the commit, and a list of parents:36333634-------------------------------------------------3635$ git-commit-tree <tree> -p <parent> [-p <parent2> ..]3636-------------------------------------------------36373638and then giving the reason for the commit on stdin (either through3639redirection from a pipe or file, or by just typing it at the tty).36403641git-commit-tree will return the name of the object that represents3642that commit, and you should save it away for later use. Normally,3643you'd commit a new `HEAD` state, and while git doesn't care where you3644save the note about that state, in practice we tend to just write the3645result to the file pointed at by `.git/HEAD`, so that we can always see3646what the last committed state was.36473648Here is an ASCII art by Jon Loeliger that illustrates how3649various pieces fit together.36503651------------36523653 commit-tree3654 commit obj3655 +----+3656 | |3657 | |3658 V V3659 +-----------+3660 | Object DB |3661 | Backing |3662 | Store |3663 +-----------+3664 ^3665 write-tree | |3666 tree obj | |3667 | | read-tree3668 | | tree obj3669 V3670 +-----------+3671 | Index |3672 | "cache" |3673 +-----------+3674 update-index ^3675 blob obj | |3676 | |3677 checkout-index -u | | checkout-index3678 stat | | blob obj3679 V3680 +-----------+3681 | Working |3682 | Directory |3683 +-----------+36843685------------368636873688[[examining-the-data]]3689Examining the data3690------------------36913692You can examine the data represented in the object database and the3693index with various helper tools. For every object, you can use3694gitlink:git-cat-file[1] to examine details about the3695object:36963697-------------------------------------------------3698$ git-cat-file -t <objectname>3699-------------------------------------------------37003701shows the type of the object, and once you have the type (which is3702usually implicit in where you find the object), you can use37033704-------------------------------------------------3705$ git-cat-file blob|tree|commit|tag <objectname>3706-------------------------------------------------37073708to show its contents. NOTE! Trees have binary content, and as a result3709there is a special helper for showing that content, called3710`git-ls-tree`, which turns the binary content into a more easily3711readable form.37123713It's especially instructive to look at "commit" objects, since those3714tend to be small and fairly self-explanatory. In particular, if you3715follow the convention of having the top commit name in `.git/HEAD`,3716you can do37173718-------------------------------------------------3719$ git-cat-file commit HEAD3720-------------------------------------------------37213722to see what the top commit was.37233724[[merging-multiple-trees]]3725Merging multiple trees3726----------------------37273728Git helps you do a three-way merge, which you can expand to n-way by3729repeating the merge procedure arbitrary times until you finally3730"commit" the state. The normal situation is that you'd only do one3731three-way merge (two parents), and commit it, but if you like to, you3732can do multiple parents in one go.37333734To do a three-way merge, you need the two sets of "commit" objects3735that you want to merge, use those to find the closest common parent (a3736third "commit" object), and then use those commit objects to find the3737state of the directory ("tree" object) at these points.37383739To get the "base" for the merge, you first look up the common parent3740of two commits with37413742-------------------------------------------------3743$ git-merge-base <commit1> <commit2>3744-------------------------------------------------37453746which will return you the commit they are both based on. You should3747now look up the "tree" objects of those commits, which you can easily3748do with (for example)37493750-------------------------------------------------3751$ git-cat-file commit <commitname> | head -13752-------------------------------------------------37533754since the tree object information is always the first line in a commit3755object.37563757Once you know the three trees you are going to merge (the one "original"3758tree, aka the common tree, and the two "result" trees, aka the branches3759you want to merge), you do a "merge" read into the index. This will3760complain if it has to throw away your old index contents, so you should3761make sure that you've committed those--in fact you would normally3762always do a merge against your last commit (which should thus match what3763you have in your current index anyway).37643765To do the merge, do37663767-------------------------------------------------3768$ git-read-tree -m -u <origtree> <yourtree> <targettree>3769-------------------------------------------------37703771which will do all trivial merge operations for you directly in the3772index file, and you can just write the result out with3773`git-write-tree`.377437753776[[merging-multiple-trees-2]]3777Merging multiple trees, continued3778---------------------------------37793780Sadly, many merges aren't trivial. If there are files that have3781been added, moved or removed, or if both branches have modified the3782same file, you will be left with an index tree that contains "merge3783entries" in it. Such an index tree can 'NOT' be written out to a tree3784object, and you will have to resolve any such merge clashes using3785other tools before you can write out the result.37863787You can examine such index state with `git-ls-files --unmerged`3788command. An example:37893790------------------------------------------------3791$ git-read-tree -m $orig HEAD $target3792$ git-ls-files --unmerged3793100644 263414f423d0e4d70dae8fe53fa34614ff3e2860 1 hello.c3794100644 06fa6a24256dc7e560efa5687fa84b51f0263c3a 2 hello.c3795100644 cc44c73eb783565da5831b4d820c962954019b69 3 hello.c3796------------------------------------------------37973798Each line of the `git-ls-files --unmerged` output begins with3799the blob mode bits, blob SHA1, 'stage number', and the3800filename. The 'stage number' is git's way to say which tree it3801came from: stage 1 corresponds to `$orig` tree, stage 2 `HEAD`3802tree, and stage3 `$target` tree.38033804Earlier we said that trivial merges are done inside3805`git-read-tree -m`. For example, if the file did not change3806from `$orig` to `HEAD` nor `$target`, or if the file changed3807from `$orig` to `HEAD` and `$orig` to `$target` the same way,3808obviously the final outcome is what is in `HEAD`. What the3809above example shows is that file `hello.c` was changed from3810`$orig` to `HEAD` and `$orig` to `$target` in a different way.3811You could resolve this by running your favorite 3-way merge3812program, e.g. `diff3`, `merge`, or git's own merge-file, on3813the blob objects from these three stages yourself, like this:38143815------------------------------------------------3816$ git-cat-file blob 263414f... >hello.c~13817$ git-cat-file blob 06fa6a2... >hello.c~23818$ git-cat-file blob cc44c73... >hello.c~33819$ git merge-file hello.c~2 hello.c~1 hello.c~33820------------------------------------------------38213822This would leave the merge result in `hello.c~2` file, along3823with conflict markers if there are conflicts. After verifying3824the merge result makes sense, you can tell git what the final3825merge result for this file is by:38263827-------------------------------------------------3828$ mv -f hello.c~2 hello.c3829$ git-update-index hello.c3830-------------------------------------------------38313832When a path is in unmerged state, running `git-update-index` for3833that path tells git to mark the path resolved.38343835The above is the description of a git merge at the lowest level,3836to help you understand what conceptually happens under the hood.3837In practice, nobody, not even git itself, uses three `git-cat-file`3838for this. There is `git-merge-index` program that extracts the3839stages to temporary files and calls a "merge" script on it:38403841-------------------------------------------------3842$ git-merge-index git-merge-one-file hello.c3843-------------------------------------------------38443845and that is what higher level `git merge -s resolve` is implemented with.38463847[[hacking-git]]3848Hacking git3849===========38503851This chapter covers internal details of the git implementation which3852probably only git developers need to understand.38533854[[object-details]]3855Object storage format3856---------------------38573858All objects have a statically determined "type" which identifies the3859format of the object (i.e. how it is used, and how it can refer to other3860objects). There are currently four different object types: "blob",3861"tree", "commit", and "tag".38623863Regardless of object type, all objects share the following3864characteristics: they are all deflated with zlib, and have a header3865that not only specifies their type, but also provides size information3866about the data in the object. It's worth noting that the SHA1 hash3867that is used to name the object is the hash of the original data3868plus this header, so `sha1sum` 'file' does not match the object name3869for 'file'.3870(Historical note: in the dawn of the age of git the hash3871was the sha1 of the 'compressed' object.)38723873As a result, the general consistency of an object can always be tested3874independently of the contents or the type of the object: all objects can3875be validated by verifying that (a) their hashes match the content of the3876file and (b) the object successfully inflates to a stream of bytes that3877forms a sequence of <ascii type without space> {plus} <space> {plus} <ascii decimal3878size> {plus} <byte\0> {plus} <binary object data>.38793880The structured objects can further have their structure and3881connectivity to other objects verified. This is generally done with3882the `git-fsck` program, which generates a full dependency graph3883of all objects, and verifies their internal consistency (in addition3884to just verifying their superficial consistency through the hash).38853886[[birdview-on-the-source-code]]3887A birds-eye view of Git's source code3888-------------------------------------38893890It is not always easy for new developers to find their way through Git's3891source code. This section gives you a little guidance to show where to3892start.38933894A good place to start is with the contents of the initial commit, with:38953896----------------------------------------------------3897$ git checkout e83c51633898----------------------------------------------------38993900The initial revision lays the foundation for almost everything git has3901today, but is small enough to read in one sitting.39023903Note that terminology has changed since that revision. For example, the3904README in that revision uses the word "changeset" to describe what we3905now call a <<def_commit_object,commit>>.39063907Also, we do not call it "cache" any more, but "index", however, the3908file is still called `cache.h`. Remark: Not much reason to change it now,3909especially since there is no good single name for it anyway, because it is3910basically _the_ header file which is included by _all_ of Git's C sources.39113912If you grasp the ideas in that initial commit, you should check out a3913more recent version and skim `cache.h`, `object.h` and `commit.h`.39143915In the early days, Git (in the tradition of UNIX) was a bunch of programs3916which were extremely simple, and which you used in scripts, piping the3917output of one into another. This turned out to be good for initial3918development, since it was easier to test new things. However, recently3919many of these parts have become builtins, and some of the core has been3920"libified", i.e. put into libgit.a for performance, portability reasons,3921and to avoid code duplication.39223923By now, you know what the index is (and find the corresponding data3924structures in `cache.h`), and that there are just a couple of object types3925(blobs, trees, commits and tags) which inherit their common structure from3926`struct object`, which is their first member (and thus, you can cast e.g.3927`(struct object *)commit` to achieve the _same_ as `&commit->object`, i.e.3928get at the object name and flags).39293930Now is a good point to take a break to let this information sink in.39313932Next step: get familiar with the object naming. Read <<naming-commits>>.3933There are quite a few ways to name an object (and not only revisions!).3934All of these are handled in `sha1_name.c`. Just have a quick look at3935the function `get_sha1()`. A lot of the special handling is done by3936functions like `get_sha1_basic()` or the likes.39373938This is just to get you into the groove for the most libified part of Git:3939the revision walker.39403941Basically, the initial version of `git log` was a shell script:39423943----------------------------------------------------------------3944$ git-rev-list --pretty $(git-rev-parse --default HEAD "$@") | \3945 LESS=-S ${PAGER:-less}3946----------------------------------------------------------------39473948What does this mean?39493950`git-rev-list` is the original version of the revision walker, which3951_always_ printed a list of revisions to stdout. It is still functional,3952and needs to, since most new Git programs start out as scripts using3953`git-rev-list`.39543955`git-rev-parse` is not as important any more; it was only used to filter out3956options that were relevant for the different plumbing commands that were3957called by the script.39583959Most of what `git-rev-list` did is contained in `revision.c` and3960`revision.h`. It wraps the options in a struct named `rev_info`, which3961controls how and what revisions are walked, and more.39623963The original job of `git-rev-parse` is now taken by the function3964`setup_revisions()`, which parses the revisions and the common command line3965options for the revision walker. This information is stored in the struct3966`rev_info` for later consumption. You can do your own command line option3967parsing after calling `setup_revisions()`. After that, you have to call3968`prepare_revision_walk()` for initialization, and then you can get the3969commits one by one with the function `get_revision()`.39703971If you are interested in more details of the revision walking process,3972just have a look at the first implementation of `cmd_log()`; call3973`git-show v1.3.0~155^2~4` and scroll down to that function (note that you3974no longer need to call `setup_pager()` directly).39753976Nowadays, `git log` is a builtin, which means that it is _contained_ in the3977command `git`. The source side of a builtin is39783979- a function called `cmd_<bla>`, typically defined in `builtin-<bla>.c`,3980 and declared in `builtin.h`,39813982- an entry in the `commands[]` array in `git.c`, and39833984- an entry in `BUILTIN_OBJECTS` in the `Makefile`.39853986Sometimes, more than one builtin is contained in one source file. For3987example, `cmd_whatchanged()` and `cmd_log()` both reside in `builtin-log.c`,3988since they share quite a bit of code. In that case, the commands which are3989_not_ named like the `.c` file in which they live have to be listed in3990`BUILT_INS` in the `Makefile`.39913992`git log` looks more complicated in C than it does in the original script,3993but that allows for a much greater flexibility and performance.39943995Here again it is a good point to take a pause.39963997Lesson three is: study the code. Really, it is the best way to learn about3998the organization of Git (after you know the basic concepts).39994000So, think about something which you are interested in, say, "how can I4001access a blob just knowing the object name of it?". The first step is to4002find a Git command with which you can do it. In this example, it is either4003`git show` or `git cat-file`.40044005For the sake of clarity, let's stay with `git cat-file`, because it40064007- is plumbing, and40084009- was around even in the initial commit (it literally went only through4010 some 20 revisions as `cat-file.c`, was renamed to `builtin-cat-file.c`4011 when made a builtin, and then saw less than 10 versions).40124013So, look into `builtin-cat-file.c`, search for `cmd_cat_file()` and look what4014it does.40154016------------------------------------------------------------------4017 git_config(git_default_config);4018 if (argc != 3)4019 usage("git-cat-file [-t|-s|-e|-p|<type>] <sha1>");4020 if (get_sha1(argv[2], sha1))4021 die("Not a valid object name %s", argv[2]);4022------------------------------------------------------------------40234024Let's skip over the obvious details; the only really interesting part4025here is the call to `get_sha1()`. It tries to interpret `argv[2]` as an4026object name, and if it refers to an object which is present in the current4027repository, it writes the resulting SHA-1 into the variable `sha1`.40284029Two things are interesting here:40304031- `get_sha1()` returns 0 on _success_. This might surprise some new4032 Git hackers, but there is a long tradition in UNIX to return different4033 negative numbers in case of different errors--and 0 on success.40344035- the variable `sha1` in the function signature of `get_sha1()` is `unsigned4036 char \*`, but is actually expected to be a pointer to `unsigned4037 char[20]`. This variable will contain the 160-bit SHA-1 of the given4038 commit. Note that whenever a SHA-1 is passed as `unsigned char \*`, it4039 is the binary representation, as opposed to the ASCII representation in4040 hex characters, which is passed as `char *`.40414042You will see both of these things throughout the code.40434044Now, for the meat:40454046-----------------------------------------------------------------------------4047 case 0:4048 buf = read_object_with_reference(sha1, argv[1], &size, NULL);4049-----------------------------------------------------------------------------40504051This is how you read a blob (actually, not only a blob, but any type of4052object). To know how the function `read_object_with_reference()` actually4053works, find the source code for it (something like `git grep4054read_object_with | grep ":[a-z]"` in the git repository), and read4055the source.40564057To find out how the result can be used, just read on in `cmd_cat_file()`:40584059-----------------------------------4060 write_or_die(1, buf, size);4061-----------------------------------40624063Sometimes, you do not know where to look for a feature. In many such cases,4064it helps to search through the output of `git log`, and then `git show` the4065corresponding commit.40664067Example: If you know that there was some test case for `git bundle`, but4068do not remember where it was (yes, you _could_ `git grep bundle t/`, but that4069does not illustrate the point!):40704071------------------------4072$ git log --no-merges t/4073------------------------40744075In the pager (`less`), just search for "bundle", go a few lines back,4076and see that it is in commit 18449ab0... Now just copy this object name,4077and paste it into the command line40784079-------------------4080$ git show 18449ab04081-------------------40824083Voila.40844085Another example: Find out what to do in order to make some script a4086builtin:40874088-------------------------------------------------4089$ git log --no-merges --diff-filter=A builtin-*.c4090-------------------------------------------------40914092You see, Git is actually the best tool to find out about the source of Git4093itself!40944095[[glossary]]4096include::glossary.txt[]40974098[[git-quick-start]]4099Appendix A: Git Quick Reference4100===============================41014102This is a quick summary of the major commands; the previous chapters4103explain how these work in more detail.41044105[[quick-creating-a-new-repository]]4106Creating a new repository4107-------------------------41084109From a tarball:41104111-----------------------------------------------4112$ tar xzf project.tar.gz4113$ cd project4114$ git init4115Initialized empty Git repository in .git/4116$ git add .4117$ git commit4118-----------------------------------------------41194120From a remote repository:41214122-----------------------------------------------4123$ git clone git://example.com/pub/project.git4124$ cd project4125-----------------------------------------------41264127[[managing-branches]]4128Managing branches4129-----------------41304131-----------------------------------------------4132$ git branch # list all local branches in this repo4133$ git checkout test # switch working directory to branch "test"4134$ git branch new # create branch "new" starting at current HEAD4135$ git branch -d new # delete branch "new"4136-----------------------------------------------41374138Instead of basing a new branch on current HEAD (the default), use:41394140-----------------------------------------------4141$ git branch new test # branch named "test"4142$ git branch new v2.6.15 # tag named v2.6.154143$ git branch new HEAD^ # commit before the most recent4144$ git branch new HEAD^^ # commit before that4145$ git branch new test~10 # ten commits before tip of branch "test"4146-----------------------------------------------41474148Create and switch to a new branch at the same time:41494150-----------------------------------------------4151$ git checkout -b new v2.6.154152-----------------------------------------------41534154Update and examine branches from the repository you cloned from:41554156-----------------------------------------------4157$ git fetch # update4158$ git branch -r # list4159 origin/master4160 origin/next4161 ...4162$ git checkout -b masterwork origin/master4163-----------------------------------------------41644165Fetch a branch from a different repository, and give it a new4166name in your repository:41674168-----------------------------------------------4169$ git fetch git://example.com/project.git theirbranch:mybranch4170$ git fetch git://example.com/project.git v2.6.15:mybranch4171-----------------------------------------------41724173Keep a list of repositories you work with regularly:41744175-----------------------------------------------4176$ git remote add example git://example.com/project.git4177$ git remote # list remote repositories4178example4179origin4180$ git remote show example # get details4181* remote example4182 URL: git://example.com/project.git4183 Tracked remote branches4184 master next ...4185$ git fetch example # update branches from example4186$ git branch -r # list all remote branches4187-----------------------------------------------418841894190[[exploring-history]]4191Exploring history4192-----------------41934194-----------------------------------------------4195$ gitk # visualize and browse history4196$ git log # list all commits4197$ git log src/ # ...modifying src/4198$ git log v2.6.15..v2.6.16 # ...in v2.6.16, not in v2.6.154199$ git log master..test # ...in branch test, not in branch master4200$ git log test..master # ...in branch master, but not in test4201$ git log test...master # ...in one branch, not in both4202$ git log -S'foo()' # ...where difference contain "foo()"4203$ git log --since="2 weeks ago"4204$ git log -p # show patches as well4205$ git show # most recent commit4206$ git diff v2.6.15..v2.6.16 # diff between two tagged versions4207$ git diff v2.6.15..HEAD # diff with current head4208$ git grep "foo()" # search working directory for "foo()"4209$ git grep v2.6.15 "foo()" # search old tree for "foo()"4210$ git show v2.6.15:a.txt # look at old version of a.txt4211-----------------------------------------------42124213Search for regressions:42144215-----------------------------------------------4216$ git bisect start4217$ git bisect bad # current version is bad4218$ git bisect good v2.6.13-rc2 # last known good revision4219Bisecting: 675 revisions left to test after this4220 # test here, then:4221$ git bisect good # if this revision is good, or4222$ git bisect bad # if this revision is bad.4223 # repeat until done.4224-----------------------------------------------42254226[[making-changes]]4227Making changes4228--------------42294230Make sure git knows who to blame:42314232------------------------------------------------4233$ cat >>~/.gitconfig <<\EOF4234[user]4235 name = Your Name Comes Here4236 email = you@yourdomain.example.com4237EOF4238------------------------------------------------42394240Select file contents to include in the next commit, then make the4241commit:42424243-----------------------------------------------4244$ git add a.txt # updated file4245$ git add b.txt # new file4246$ git rm c.txt # old file4247$ git commit4248-----------------------------------------------42494250Or, prepare and create the commit in one step:42514252-----------------------------------------------4253$ git commit d.txt # use latest content only of d.txt4254$ git commit -a # use latest content of all tracked files4255-----------------------------------------------42564257[[merging]]4258Merging4259-------42604261-----------------------------------------------4262$ git merge test # merge branch "test" into the current branch4263$ git pull git://example.com/project.git master4264 # fetch and merge in remote branch4265$ git pull . test # equivalent to git merge test4266-----------------------------------------------42674268[[sharing-your-changes]]4269Sharing your changes4270--------------------42714272Importing or exporting patches:42734274-----------------------------------------------4275$ git format-patch origin..HEAD # format a patch for each commit4276 # in HEAD but not in origin4277$ git am mbox # import patches from the mailbox "mbox"4278-----------------------------------------------42794280Fetch a branch in a different git repository, then merge into the4281current branch:42824283-----------------------------------------------4284$ git pull git://example.com/project.git theirbranch4285-----------------------------------------------42864287Store the fetched branch into a local branch before merging into the4288current branch:42894290-----------------------------------------------4291$ git pull git://example.com/project.git theirbranch:mybranch4292-----------------------------------------------42934294After creating commits on a local branch, update the remote4295branch with your commits:42964297-----------------------------------------------4298$ git push ssh://example.com/project.git mybranch:theirbranch4299-----------------------------------------------43004301When remote and local branch are both named "test":43024303-----------------------------------------------4304$ git push ssh://example.com/project.git test4305-----------------------------------------------43064307Shortcut version for a frequently used remote repository:43084309-----------------------------------------------4310$ git remote add example ssh://example.com/project.git4311$ git push example test4312-----------------------------------------------43134314[[repository-maintenance]]4315Repository maintenance4316----------------------43174318Check for corruption:43194320-----------------------------------------------4321$ git fsck4322-----------------------------------------------43234324Recompress, remove unused cruft:43254326-----------------------------------------------4327$ git gc4328-----------------------------------------------432943304331[[todo]]4332Appendix B: Notes and todo list for this manual4333===============================================43344335This is a work in progress.43364337The basic requirements:43384339- It must be readable in order, from beginning to end, by someone4340 intelligent with a basic grasp of the UNIX command line, but without4341 any special knowledge of git. If necessary, any other prerequisites4342 should be specifically mentioned as they arise.4343- Whenever possible, section headings should clearly describe the task4344 they explain how to do, in language that requires no more knowledge4345 than necessary: for example, "importing patches into a project" rather4346 than "the git-am command"43474348Think about how to create a clear chapter dependency graph that will4349allow people to get to important topics without necessarily reading4350everything in between.43514352Scan Documentation/ for other stuff left out; in particular:43534354- howto's4355- some of technical/?4356- hooks4357- list of commands in gitlink:git[1]43584359Scan email archives for other stuff left out43604361Scan man pages to see if any assume more background than this manual4362provides.43634364Simplify beginning by suggesting disconnected head instead of4365temporary branch creation?43664367Add more good examples. Entire sections of just cookbook examples4368might be a good idea; maybe make an "advanced examples" section a4369standard end-of-chapter section?43704371Include cross-references to the glossary, where appropriate.43724373Document shallow clones? See draft 1.5.0 release notes for some4374documentation.43754376Add a section on working with other version control systems, including4377CVS, Subversion, and just imports of series of release tarballs.43784379More details on gitweb?43804381Write a chapter on using plumbing and writing scripts.43824383Alternates, clone -reference, etc.43844385git unpack-objects -r for recovery