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 661Sometimes what you want instead is a set of patches: 662 663------------------------------------------------- 664$ git format-patch master..test 665------------------------------------------------- 666 667will generate a file with a patch for each commit reachable from test 668but not from master. Note that if master also has commits which are 669not reachable from test, then the combined result of these patches 670will not be the same as the diff produced by the git-diff example. 671 672[[viewing-old-file-versions]] 673Viewing old file versions 674------------------------- 675 676You can always view an old version of a file by just checking out the 677correct revision first. But sometimes it is more convenient to be 678able to view an old version of a single file without checking 679anything out; this command does that: 680 681------------------------------------------------- 682$ git show v2.5:fs/locks.c 683------------------------------------------------- 684 685Before the colon may be anything that names a commit, and after it 686may be any path to a file tracked by git. 687 688[[history-examples]] 689Examples 690-------- 691 692[[counting-commits-on-a-branch]] 693Counting the number of commits on a branch 694~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 695 696Suppose you want to know how many commits you've made on "mybranch" 697since it diverged from "origin": 698 699------------------------------------------------- 700$ git log --pretty=oneline origin..mybranch | wc -l 701------------------------------------------------- 702 703Alternatively, you may often see this sort of thing done with the 704lower-level command gitlink:git-rev-list[1], which just lists the SHA1's 705of all the given commits: 706 707------------------------------------------------- 708$ git rev-list origin..mybranch | wc -l 709------------------------------------------------- 710 711[[checking-for-equal-branches]] 712Check whether two branches point at the same history 713~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 714 715Suppose you want to check whether two branches point at the same point 716in history. 717 718------------------------------------------------- 719$ git diff origin..master 720------------------------------------------------- 721 722will tell you whether the contents of the project are the same at the 723two branches; in theory, however, it's possible that the same project 724contents could have been arrived at by two different historical 725routes. You could compare the object names: 726 727------------------------------------------------- 728$ git rev-list origin 729e05db0fd4f31dde7005f075a84f96b360d05984b 730$ git rev-list master 731e05db0fd4f31dde7005f075a84f96b360d05984b 732------------------------------------------------- 733 734Or you could recall that the ... operator selects all commits 735contained reachable from either one reference or the other but not 736both: so 737 738------------------------------------------------- 739$ git log origin...master 740------------------------------------------------- 741 742will return no commits when the two branches are equal. 743 744[[finding-tagged-descendants]] 745Find first tagged version including a given fix 746~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 747 748Suppose you know that the commit e05db0fd fixed a certain problem. 749You'd like to find the earliest tagged release that contains that 750fix. 751 752Of course, there may be more than one answer--if the history branched 753after commit e05db0fd, then there could be multiple "earliest" tagged 754releases. 755 756You could just visually inspect the commits since e05db0fd: 757 758------------------------------------------------- 759$ gitk e05db0fd.. 760------------------------------------------------- 761 762Or you can use gitlink:git-name-rev[1], which will give the commit a 763name based on any tag it finds pointing to one of the commit's 764descendants: 765 766------------------------------------------------- 767$ git name-rev --tags e05db0fd 768e05db0fd tags/v1.5.0-rc1^0~23 769------------------------------------------------- 770 771The gitlink:git-describe[1] command does the opposite, naming the 772revision using a tag on which the given commit is based: 773 774------------------------------------------------- 775$ git describe e05db0fd 776v1.5.0-rc0-260-ge05db0f 777------------------------------------------------- 778 779but that may sometimes help you guess which tags might come after the 780given commit. 781 782If you just want to verify whether a given tagged version contains a 783given commit, you could use gitlink:git-merge-base[1]: 784 785------------------------------------------------- 786$ git merge-base e05db0fd v1.5.0-rc1 787e05db0fd4f31dde7005f075a84f96b360d05984b 788------------------------------------------------- 789 790The merge-base command finds a common ancestor of the given commits, 791and always returns one or the other in the case where one is a 792descendant of the other; so the above output shows that e05db0fd 793actually is an ancestor of v1.5.0-rc1. 794 795Alternatively, note that 796 797------------------------------------------------- 798$ git log v1.5.0-rc1..e05db0fd 799------------------------------------------------- 800 801will produce empty output if and only if v1.5.0-rc1 includes e05db0fd, 802because it outputs only commits that are not reachable from v1.5.0-rc1. 803 804As yet another alternative, the gitlink:git-show-branch[1] command lists 805the commits reachable from its arguments with a display on the left-hand 806side that indicates which arguments that commit is reachable from. So, 807you can run something like 808 809------------------------------------------------- 810$ git show-branch e05db0fd v1.5.0-rc0 v1.5.0-rc1 v1.5.0-rc2 811! [e05db0fd] Fix warnings in sha1_file.c - use C99 printf format if 812available 813 ! [v1.5.0-rc0] GIT v1.5.0 preview 814 ! [v1.5.0-rc1] GIT v1.5.0-rc1 815 ! [v1.5.0-rc2] GIT v1.5.0-rc2 816... 817------------------------------------------------- 818 819then search for a line that looks like 820 821------------------------------------------------- 822+ ++ [e05db0fd] Fix warnings in sha1_file.c - use C99 printf format if 823available 824------------------------------------------------- 825 826Which shows that e05db0fd is reachable from itself, from v1.5.0-rc1, and 827from v1.5.0-rc2, but not from v1.5.0-rc0. 828 829[[showing-commits-unique-to-a-branch]] 830Showing commits unique to a given branch 831~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 832 833Suppose you would like to see all the commits reachable from the branch 834head named "master" but not from any other head in your repository. 835 836We can list all the heads in this repository with 837gitlink:git-show-ref[1]: 838 839------------------------------------------------- 840$ git show-ref --heads 841bf62196b5e363d73353a9dcf094c59595f3153b7 refs/heads/core-tutorial 842db768d5504c1bb46f63ee9d6e1772bd047e05bf9 refs/heads/maint 843a07157ac624b2524a059a3414e99f6f44bebc1e7 refs/heads/master 84424dbc180ea14dc1aebe09f14c8ecf32010690627 refs/heads/tutorial-2 8451e87486ae06626c2f31eaa63d26fc0fd646c8af2 refs/heads/tutorial-fixes 846------------------------------------------------- 847 848We can get just the branch-head names, and remove "master", with 849the help of the standard utilities cut and grep: 850 851------------------------------------------------- 852$ git show-ref --heads | cut -d' ' -f2 | grep -v '^refs/heads/master' 853refs/heads/core-tutorial 854refs/heads/maint 855refs/heads/tutorial-2 856refs/heads/tutorial-fixes 857------------------------------------------------- 858 859And then we can ask to see all the commits reachable from master 860but not from these other heads: 861 862------------------------------------------------- 863$ gitk master --not $( git show-ref --heads | cut -d' ' -f2 | 864 grep -v '^refs/heads/master' ) 865------------------------------------------------- 866 867Obviously, endless variations are possible; for example, to see all 868commits reachable from some head but not from any tag in the repository: 869 870------------------------------------------------- 871$ gitk $( git show-ref --heads ) --not $( git show-ref --tags ) 872------------------------------------------------- 873 874(See gitlink:git-rev-parse[1] for explanations of commit-selecting 875syntax such as `--not`.) 876 877[[making-a-release]] 878Creating a changelog and tarball for a software release 879~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 880 881The gitlink:git-archive[1] command can create a tar or zip archive from 882any version of a project; for example: 883 884------------------------------------------------- 885$ git archive --format=tar --prefix=project/ HEAD | gzip >latest.tar.gz 886------------------------------------------------- 887 888will use HEAD to produce a tar archive in which each filename is 889preceded by "project/". 890 891If you're releasing a new version of a software project, you may want 892to simultaneously make a changelog to include in the release 893announcement. 894 895Linus Torvalds, for example, makes new kernel releases by tagging them, 896then running: 897 898------------------------------------------------- 899$ release-script 2.6.12 2.6.13-rc6 2.6.13-rc7 900------------------------------------------------- 901 902where release-script is a shell script that looks like: 903 904------------------------------------------------- 905#!/bin/sh 906stable="$1" 907last="$2" 908new="$3" 909echo "# git tag v$new" 910echo "git archive --prefix=linux-$new/ v$new | gzip -9 > ../linux-$new.tar.gz" 911echo "git diff v$stable v$new | gzip -9 > ../patch-$new.gz" 912echo "git log --no-merges v$new ^v$last > ../ChangeLog-$new" 913echo "git shortlog --no-merges v$new ^v$last > ../ShortLog" 914echo "git diff --stat --summary -M v$last v$new > ../diffstat-$new" 915------------------------------------------------- 916 917and then he just cut-and-pastes the output commands after verifying that 918they look OK. 919 920[[Finding-comments-with-given-content]] 921Finding commits referencing a file with given content 922~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 923 924Somebody hands you a copy of a file, and asks which commits modified a 925file such that it contained the given content either before or after the 926commit. You can find out with this: 927 928------------------------------------------------- 929$ git log --raw --abbrev=40 --pretty=oneline | 930 grep -B 1 `git hash-object filename` 931------------------------------------------------- 932 933Figuring out why this works is left as an exercise to the (advanced) 934student. The gitlink:git-log[1], gitlink:git-diff-tree[1], and 935gitlink:git-hash-object[1] man pages may prove helpful. 936 937[[Developing-with-git]] 938Developing with git 939=================== 940 941[[telling-git-your-name]] 942Telling git your name 943--------------------- 944 945Before creating any commits, you should introduce yourself to git. The 946easiest way to do so is to make sure the following lines appear in a 947file named .gitconfig in your home directory: 948 949------------------------------------------------ 950[user] 951 name = Your Name Comes Here 952 email = you@yourdomain.example.com 953------------------------------------------------ 954 955(See the "CONFIGURATION FILE" section of gitlink:git-config[1] for 956details on the configuration file.) 957 958 959[[creating-a-new-repository]] 960Creating a new repository 961------------------------- 962 963Creating a new repository from scratch is very easy: 964 965------------------------------------------------- 966$ mkdir project 967$ cd project 968$ git init 969------------------------------------------------- 970 971If you have some initial content (say, a tarball): 972 973------------------------------------------------- 974$ tar -xzvf project.tar.gz 975$ cd project 976$ git init 977$ git add . # include everything below ./ in the first commit: 978$ git commit 979------------------------------------------------- 980 981[[how-to-make-a-commit]] 982How to make a commit 983-------------------- 984 985Creating a new commit takes three steps: 986 987 1. Making some changes to the working directory using your 988 favorite editor. 989 2. Telling git about your changes. 990 3. Creating the commit using the content you told git about 991 in step 2. 992 993In practice, you can interleave and repeat steps 1 and 2 as many 994times as you want: in order to keep track of what you want committed 995at step 3, git maintains a snapshot of the tree's contents in a 996special staging area called "the index." 997 998At the beginning, the content of the index will be identical to 999that of the HEAD. The command "git diff --cached", which shows1000the difference between the HEAD and the index, should therefore1001produce no output at that point.10021003Modifying the index is easy:10041005To update the index with the new contents of a modified file, use10061007-------------------------------------------------1008$ git add path/to/file1009-------------------------------------------------10101011To add the contents of a new file to the index, use10121013-------------------------------------------------1014$ git add path/to/file1015-------------------------------------------------10161017To remove a file from the index and from the working tree,10181019-------------------------------------------------1020$ git rm path/to/file1021-------------------------------------------------10221023After each step you can verify that10241025-------------------------------------------------1026$ git diff --cached1027-------------------------------------------------10281029always shows the difference between the HEAD and the index file--this1030is what you'd commit if you created the commit now--and that10311032-------------------------------------------------1033$ git diff1034-------------------------------------------------10351036shows the difference between the working tree and the index file.10371038Note that "git add" always adds just the current contents of a file1039to the index; further changes to the same file will be ignored unless1040you run git-add on the file again.10411042When you're ready, just run10431044-------------------------------------------------1045$ git commit1046-------------------------------------------------10471048and git will prompt you for a commit message and then create the new1049commit. Check to make sure it looks like what you expected with10501051-------------------------------------------------1052$ git show1053-------------------------------------------------10541055As a special shortcut,10561057-------------------------------------------------1058$ git commit -a1059-------------------------------------------------10601061will update the index with any files that you've modified or removed1062and create a commit, all in one step.10631064A number of commands are useful for keeping track of what you're1065about to commit:10661067-------------------------------------------------1068$ git diff --cached # difference between HEAD and the index; what1069 # would be committed if you ran "commit" now.1070$ git diff # difference between the index file and your1071 # working directory; changes that would not1072 # be included if you ran "commit" now.1073$ git diff HEAD # difference between HEAD and working tree; what1074 # would be committed if you ran "commit -a" now.1075$ git status # a brief per-file summary of the above.1076-------------------------------------------------10771078You can also use gitlink:git-gui[1] to create commits, view changes in1079the index and the working tree files, and individually select diff hunks1080for inclusion in the index (by right-clicking on the diff hunk and1081choosing "Stage Hunk For Commit").10821083[[creating-good-commit-messages]]1084Creating good commit messages1085-----------------------------10861087Though not required, it's a good idea to begin the commit message1088with a single short (less than 50 character) line summarizing the1089change, followed by a blank line and then a more thorough1090description. Tools that turn commits into email, for example, use1091the first line on the Subject line and the rest of the commit in the1092body.10931094[[ignoring-files]]1095Ignoring files1096--------------10971098A project will often generate files that you do 'not' want to track with git.1099This typically includes files generated by a build process or temporary1100backup files made by your editor. Of course, 'not' tracking files with git1101is just a matter of 'not' calling "`git add`" on them. But it quickly becomes1102annoying to have these untracked files lying around; e.g. they make1103"`git add .`" and "`git commit -a`" practically useless, and they keep1104showing up in the output of "`git status`".11051106You can tell git to ignore certain files by creating a file called .gitignore1107in the top level of your working directory, with contents such as:11081109-------------------------------------------------1110# Lines starting with '#' are considered comments.1111# Ignore any file named foo.txt.1112foo.txt1113# Ignore (generated) html files,1114*.html1115# except foo.html which is maintained by hand.1116!foo.html1117# Ignore objects and archives.1118*.[oa]1119-------------------------------------------------11201121See gitlink:gitignore[5] for a detailed explanation of the syntax. You can1122also place .gitignore files in other directories in your working tree, and they1123will apply to those directories and their subdirectories. The `.gitignore`1124files can be added to your repository like any other files (just run `git add1125.gitignore` and `git commit`, as usual), which is convenient when the exclude1126patterns (such as patterns matching build output files) would also make sense1127for other users who clone your repository.11281129If you wish the exclude patterns to affect only certain repositories1130(instead of every repository for a given project), you may instead put1131them in a file in your repository named .git/info/exclude, or in any file1132specified by the `core.excludesfile` configuration variable. Some git1133commands can also take exclude patterns directly on the command line.1134See gitlink:gitignore[5] for the details.11351136[[how-to-merge]]1137How to merge1138------------11391140You can rejoin two diverging branches of development using1141gitlink:git-merge[1]:11421143-------------------------------------------------1144$ git merge branchname1145-------------------------------------------------11461147merges the development in the branch "branchname" into the current1148branch. If there are conflicts--for example, if the same file is1149modified in two different ways in the remote branch and the local1150branch--then you are warned; the output may look something like this:11511152-------------------------------------------------1153$ git merge next1154 100% (4/4) done1155Auto-merged file.txt1156CONFLICT (content): Merge conflict in file.txt1157Automatic merge failed; fix conflicts and then commit the result.1158-------------------------------------------------11591160Conflict markers are left in the problematic files, and after1161you resolve the conflicts manually, you can update the index1162with the contents and run git commit, as you normally would when1163creating a new file.11641165If you examine the resulting commit using gitk, you will see that it1166has two parents, one pointing to the top of the current branch, and1167one to the top of the other branch.11681169[[resolving-a-merge]]1170Resolving a merge1171-----------------11721173When a merge isn't resolved automatically, git leaves the index and1174the working tree in a special state that gives you all the1175information you need to help resolve the merge.11761177Files with conflicts are marked specially in the index, so until you1178resolve the problem and update the index, gitlink:git-commit[1] will1179fail:11801181-------------------------------------------------1182$ git commit1183file.txt: needs merge1184-------------------------------------------------11851186Also, gitlink:git-status[1] will list those files as "unmerged", and the1187files with conflicts will have conflict markers added, like this:11881189-------------------------------------------------1190<<<<<<< HEAD:file.txt1191Hello world1192=======1193Goodbye1194>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt1195-------------------------------------------------11961197All you need to do is edit the files to resolve the conflicts, and then11981199-------------------------------------------------1200$ git add file.txt1201$ git commit1202-------------------------------------------------12031204Note that the commit message will already be filled in for you with1205some information about the merge. Normally you can just use this1206default message unchanged, but you may add additional commentary of1207your own if desired.12081209The above is all you need to know to resolve a simple merge. But git1210also provides more information to help resolve conflicts:12111212[[conflict-resolution]]1213Getting conflict-resolution help during a merge1214~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~12151216All of the changes that git was able to merge automatically are1217already added to the index file, so gitlink:git-diff[1] shows only1218the conflicts. It uses an unusual syntax:12191220-------------------------------------------------1221$ git diff1222diff --cc file.txt1223index 802992c,2b60207..00000001224--- a/file.txt1225+++ b/file.txt1226@@@ -1,1 -1,1 +1,5 @@@1227++<<<<<<< HEAD:file.txt1228 +Hello world1229++=======1230+ Goodbye1231++>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt1232-------------------------------------------------12331234Recall that the commit which will be committed after we resolve this1235conflict will have two parents instead of the usual one: one parent1236will be HEAD, the tip of the current branch; the other will be the1237tip of the other branch, which is stored temporarily in MERGE_HEAD.12381239During the merge, the index holds three versions of each file. Each of1240these three "file stages" represents a different version of the file:12411242-------------------------------------------------1243$ git show :1:file.txt # the file in a common ancestor of both branches1244$ git show :2:file.txt # the version from HEAD, but including any1245 # nonconflicting changes from MERGE_HEAD1246$ git show :3:file.txt # the version from MERGE_HEAD, but including any1247 # nonconflicting changes from HEAD.1248-------------------------------------------------12491250Since the stage 2 and stage 3 versions have already been updated with1251nonconflicting changes, the only remaining differences between them are1252the important ones; thus gitlink:git-diff[1] can use the information in1253the index to show only those conflicts.12541255The diff above shows the differences between the working-tree version of1256file.txt and the stage 2 and stage 3 versions. So instead of preceding1257each line by a single "+" or "-", it now uses two columns: the first1258column is used for differences between the first parent and the working1259directory copy, and the second for differences between the second parent1260and the working directory copy. (See the "COMBINED DIFF FORMAT" section1261of gitlink:git-diff-files[1] for a details of the format.)12621263After resolving the conflict in the obvious way (but before updating the1264index), the diff will look like:12651266-------------------------------------------------1267$ git diff1268diff --cc file.txt1269index 802992c,2b60207..00000001270--- a/file.txt1271+++ b/file.txt1272@@@ -1,1 -1,1 +1,1 @@@1273- Hello world1274 -Goodbye1275++Goodbye world1276-------------------------------------------------12771278This shows that our resolved version deleted "Hello world" from the1279first parent, deleted "Goodbye" from the second parent, and added1280"Goodbye world", which was previously absent from both.12811282Some special diff options allow diffing the working directory against1283any of these stages:12841285-------------------------------------------------1286$ git diff -1 file.txt # diff against stage 11287$ git diff --base file.txt # same as the above1288$ git diff -2 file.txt # diff against stage 21289$ git diff --ours file.txt # same as the above1290$ git diff -3 file.txt # diff against stage 31291$ git diff --theirs file.txt # same as the above.1292-------------------------------------------------12931294The gitlink:git-log[1] and gitk[1] commands also provide special help1295for merges:12961297-------------------------------------------------1298$ git log --merge1299$ gitk --merge1300-------------------------------------------------13011302These will display all commits which exist only on HEAD or on1303MERGE_HEAD, and which touch an unmerged file.13041305You may also use gitlink:git-mergetool[1], which lets you merge the1306unmerged files using external tools such as emacs or kdiff3.13071308Each time you resolve the conflicts in a file and update the index:13091310-------------------------------------------------1311$ git add file.txt1312-------------------------------------------------13131314the different stages of that file will be "collapsed", after which1315git-diff will (by default) no longer show diffs for that file.13161317[[undoing-a-merge]]1318Undoing a merge1319---------------13201321If you get stuck and decide to just give up and throw the whole mess1322away, you can always return to the pre-merge state with13231324-------------------------------------------------1325$ git reset --hard HEAD1326-------------------------------------------------13271328Or, if you've already committed the merge that you want to throw away,13291330-------------------------------------------------1331$ git reset --hard ORIG_HEAD1332-------------------------------------------------13331334However, this last command can be dangerous in some cases--never1335throw away a commit you have already committed if that commit may1336itself have been merged into another branch, as doing so may confuse1337further merges.13381339[[fast-forwards]]1340Fast-forward merges1341-------------------13421343There is one special case not mentioned above, which is treated1344differently. Normally, a merge results in a merge commit, with two1345parents, one pointing at each of the two lines of development that1346were merged.13471348However, if the current branch is a descendant of the other--so every1349commit present in the one is already contained in the other--then git1350just performs a "fast forward"; the head of the current branch is moved1351forward to point at the head of the merged-in branch, without any new1352commits being created.13531354[[fixing-mistakes]]1355Fixing mistakes1356---------------13571358If you've messed up the working tree, but haven't yet committed your1359mistake, you can return the entire working tree to the last committed1360state with13611362-------------------------------------------------1363$ git reset --hard HEAD1364-------------------------------------------------13651366If you make a commit that you later wish you hadn't, there are two1367fundamentally different ways to fix the problem:13681369 1. You can create a new commit that undoes whatever was done1370 by the old commit. This is the correct thing if your1371 mistake has already been made public.13721373 2. You can go back and modify the old commit. You should1374 never do this if you have already made the history public;1375 git does not normally expect the "history" of a project to1376 change, and cannot correctly perform repeated merges from1377 a branch that has had its history changed.13781379[[reverting-a-commit]]1380Fixing a mistake with a new commit1381~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~13821383Creating a new commit that reverts an earlier change is very easy;1384just pass the gitlink:git-revert[1] command a reference to the bad1385commit; for example, to revert the most recent commit:13861387-------------------------------------------------1388$ git revert HEAD1389-------------------------------------------------13901391This will create a new commit which undoes the change in HEAD. You1392will be given a chance to edit the commit message for the new commit.13931394You can also revert an earlier change, for example, the next-to-last:13951396-------------------------------------------------1397$ git revert HEAD^1398-------------------------------------------------13991400In this case git will attempt to undo the old change while leaving1401intact any changes made since then. If more recent changes overlap1402with the changes to be reverted, then you will be asked to fix1403conflicts manually, just as in the case of <<resolving-a-merge,1404resolving a merge>>.14051406[[fixing-a-mistake-by-editing-history]]1407Fixing a mistake by editing history1408~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~14091410If the problematic commit is the most recent commit, and you have not1411yet made that commit public, then you may just1412<<undoing-a-merge,destroy it using git-reset>>.14131414Alternatively, you1415can edit the working directory and update the index to fix your1416mistake, just as if you were going to <<how-to-make-a-commit,create a1417new commit>>, then run14181419-------------------------------------------------1420$ git commit --amend1421-------------------------------------------------14221423which will replace the old commit by a new commit incorporating your1424changes, giving you a chance to edit the old commit message first.14251426Again, you should never do this to a commit that may already have1427been merged into another branch; use gitlink:git-revert[1] instead in1428that case.14291430It is also possible to edit commits further back in the history, but1431this is an advanced topic to be left for1432<<cleaning-up-history,another chapter>>.14331434[[checkout-of-path]]1435Checking out an old version of a file1436~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~14371438In the process of undoing a previous bad change, you may find it1439useful to check out an older version of a particular file using1440gitlink:git-checkout[1]. We've used git checkout before to switch1441branches, but it has quite different behavior if it is given a path1442name: the command14431444-------------------------------------------------1445$ git checkout HEAD^ path/to/file1446-------------------------------------------------14471448replaces path/to/file by the contents it had in the commit HEAD^, and1449also updates the index to match. It does not change branches.14501451If you just want to look at an old version of the file, without1452modifying the working directory, you can do that with1453gitlink:git-show[1]:14541455-------------------------------------------------1456$ git show HEAD^:path/to/file1457-------------------------------------------------14581459which will display the given version of the file.14601461[[interrupted-work]]1462Temporarily setting aside work in progress1463~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~14641465While you are in the middle of working on something complicated, you1466find an unrelated but obvious and trivial bug. You would like to fix it1467before continuing. You can use gitlink:git-stash[1] to save the current1468state of your work, and after fixing the bug (or, optionally after doing1469so on a different branch and then coming back), unstash the1470work-in-progress changes.14711472------------------------------------------------1473$ git stash "work in progress for foo feature"1474------------------------------------------------14751476This command will save your changes away to the `stash`, and1477reset your working tree and the index to match the tip of your1478current branch. Then you can make your fix as usual.14791480------------------------------------------------1481... edit and test ...1482$ git commit -a -m "blorpl: typofix"1483------------------------------------------------14841485After that, you can go back to what you were working on with1486`git stash apply`:14871488------------------------------------------------1489$ git stash apply1490------------------------------------------------149114921493[[ensuring-good-performance]]1494Ensuring good performance1495-------------------------14961497On large repositories, git depends on compression to keep the history1498information from taking up too much space on disk or in memory.14991500This compression is not performed automatically. Therefore you1501should occasionally run gitlink:git-gc[1]:15021503-------------------------------------------------1504$ git gc1505-------------------------------------------------15061507to recompress the archive. This can be very time-consuming, so1508you may prefer to run git-gc when you are not doing other work.150915101511[[ensuring-reliability]]1512Ensuring reliability1513--------------------15141515[[checking-for-corruption]]1516Checking the repository for corruption1517~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~15181519The gitlink:git-fsck[1] command runs a number of self-consistency checks1520on the repository, and reports on any problems. This may take some1521time. The most common warning by far is about "dangling" objects:15221523-------------------------------------------------1524$ git fsck1525dangling commit 7281251ddd2a61e38657c827739c57015671a6b31526dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a631527dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b51528dangling blob 218761f9d90712d37a9c5e36f406f92202db07eb1529dangling commit bf093535a34a4d35731aa2bd90fe6b176302f14f1530dangling commit 8e4bec7f2ddaa268bef999853c25755452100f8e1531dangling tree d50bb86186bf27b681d25af89d3b5b68382e40851532dangling tree b24c2473f1fd3d91352a624795be026d64c8841f1533...1534-------------------------------------------------15351536Dangling objects are not a problem. At worst they may take up a little1537extra disk space. They can sometimes provide a last-resort method for1538recovering lost work--see <<dangling-objects>> for details. However, if1539you wish, you can remove them with gitlink:git-prune[1] or the `--prune`1540option to gitlink:git-gc[1]:15411542-------------------------------------------------1543$ git gc --prune1544-------------------------------------------------15451546This may be time-consuming. Unlike most other git operations (including1547git-gc when run without any options), it is not safe to prune while1548other git operations are in progress in the same repository.15491550[[recovering-lost-changes]]1551Recovering lost changes1552~~~~~~~~~~~~~~~~~~~~~~~15531554[[reflogs]]1555Reflogs1556^^^^^^^15571558Say you modify a branch with `gitlink:git-reset[1] --hard`, and then1559realize that the branch was the only reference you had to that point in1560history.15611562Fortunately, git also keeps a log, called a "reflog", of all the1563previous values of each branch. So in this case you can still find the1564old history using, for example,15651566-------------------------------------------------1567$ git log master@{1}1568-------------------------------------------------15691570This lists the commits reachable from the previous version of the head.1571This syntax can be used with any git command that accepts a commit,1572not just with git log. Some other examples:15731574-------------------------------------------------1575$ git show master@{2} # See where the branch pointed 2,1576$ git show master@{3} # 3, ... changes ago.1577$ gitk master@{yesterday} # See where it pointed yesterday,1578$ gitk master@{"1 week ago"} # ... or last week1579$ git log --walk-reflogs master # show reflog entries for master1580-------------------------------------------------15811582A separate reflog is kept for the HEAD, so15831584-------------------------------------------------1585$ git show HEAD@{"1 week ago"}1586-------------------------------------------------15871588will show what HEAD pointed to one week ago, not what the current branch1589pointed to one week ago. This allows you to see the history of what1590you've checked out.15911592The reflogs are kept by default for 30 days, after which they may be1593pruned. See gitlink:git-reflog[1] and gitlink:git-gc[1] to learn1594how to control this pruning, and see the "SPECIFYING REVISIONS"1595section of gitlink:git-rev-parse[1] for details.15961597Note that the reflog history is very different from normal git history.1598While normal history is shared by every repository that works on the1599same project, the reflog history is not shared: it tells you only about1600how the branches in your local repository have changed over time.16011602[[dangling-object-recovery]]1603Examining dangling objects1604^^^^^^^^^^^^^^^^^^^^^^^^^^16051606In some situations the reflog may not be able to save you. For example,1607suppose you delete a branch, then realize you need the history it1608contained. The reflog is also deleted; however, if you have not yet1609pruned the repository, then you may still be able to find the lost1610commits in the dangling objects that git-fsck reports. See1611<<dangling-objects>> for the details.16121613-------------------------------------------------1614$ git fsck1615dangling commit 7281251ddd2a61e38657c827739c57015671a6b31616dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a631617dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b51618...1619-------------------------------------------------16201621You can examine1622one of those dangling commits with, for example,16231624------------------------------------------------1625$ gitk 7281251ddd --not --all1626------------------------------------------------16271628which does what it sounds like: it says that you want to see the commit1629history that is described by the dangling commit(s), but not the1630history that is described by all your existing branches and tags. Thus1631you get exactly the history reachable from that commit that is lost.1632(And notice that it might not be just one commit: we only report the1633"tip of the line" as being dangling, but there might be a whole deep1634and complex commit history that was dropped.)16351636If you decide you want the history back, you can always create a new1637reference pointing to it, for example, a new branch:16381639------------------------------------------------1640$ git branch recovered-branch 7281251ddd1641------------------------------------------------16421643Other types of dangling objects (blobs and trees) are also possible, and1644dangling objects can arise in other situations.164516461647[[sharing-development]]1648Sharing development with others1649===============================16501651[[getting-updates-with-git-pull]]1652Getting updates with git pull1653-----------------------------16541655After you clone a repository and make a few changes of your own, you1656may wish to check the original repository for updates and merge them1657into your own work.16581659We have already seen <<Updating-a-repository-with-git-fetch,how to1660keep remote tracking branches up to date>> with gitlink:git-fetch[1],1661and how to merge two branches. So you can merge in changes from the1662original repository's master branch with:16631664-------------------------------------------------1665$ git fetch1666$ git merge origin/master1667-------------------------------------------------16681669However, the gitlink:git-pull[1] command provides a way to do this in1670one step:16711672-------------------------------------------------1673$ git pull origin master1674-------------------------------------------------16751676In fact, if you have "master" checked out, then by default "git pull"1677merges from the HEAD branch of the origin repository. So often you can1678accomplish the above with just a simple16791680-------------------------------------------------1681$ git pull1682-------------------------------------------------16831684More generally, a branch that is created from a remote branch will pull1685by default from that branch. See the descriptions of the1686branch.<name>.remote and branch.<name>.merge options in1687gitlink:git-config[1], and the discussion of the `--track` option in1688gitlink:git-checkout[1], to learn how to control these defaults.16891690In addition to saving you keystrokes, "git pull" also helps you by1691producing a default commit message documenting the branch and1692repository that you pulled from.16931694(But note that no such commit will be created in the case of a1695<<fast-forwards,fast forward>>; instead, your branch will just be1696updated to point to the latest commit from the upstream branch.)16971698The git-pull command can also be given "." as the "remote" repository,1699in which case it just merges in a branch from the current repository; so1700the commands17011702-------------------------------------------------1703$ git pull . branch1704$ git merge branch1705-------------------------------------------------17061707are roughly equivalent. The former is actually very commonly used.17081709[[submitting-patches]]1710Submitting patches to a project1711-------------------------------17121713If you just have a few changes, the simplest way to submit them may1714just be to send them as patches in email:17151716First, use gitlink:git-format-patch[1]; for example:17171718-------------------------------------------------1719$ git format-patch origin1720-------------------------------------------------17211722will produce a numbered series of files in the current directory, one1723for each patch in the current branch but not in origin/HEAD.17241725You can then import these into your mail client and send them by1726hand. However, if you have a lot to send at once, you may prefer to1727use the gitlink:git-send-email[1] script to automate the process.1728Consult the mailing list for your project first to determine how they1729prefer such patches be handled.17301731[[importing-patches]]1732Importing patches to a project1733------------------------------17341735Git also provides a tool called gitlink:git-am[1] (am stands for1736"apply mailbox"), for importing such an emailed series of patches.1737Just save all of the patch-containing messages, in order, into a1738single mailbox file, say "patches.mbox", then run17391740-------------------------------------------------1741$ git am -3 patches.mbox1742-------------------------------------------------17431744Git will apply each patch in order; if any conflicts are found, it1745will stop, and you can fix the conflicts as described in1746"<<resolving-a-merge,Resolving a merge>>". (The "-3" option tells1747git to perform a merge; if you would prefer it just to abort and1748leave your tree and index untouched, you may omit that option.)17491750Once the index is updated with the results of the conflict1751resolution, instead of creating a new commit, just run17521753-------------------------------------------------1754$ git am --resolved1755-------------------------------------------------17561757and git will create the commit for you and continue applying the1758remaining patches from the mailbox.17591760The final result will be a series of commits, one for each patch in1761the original mailbox, with authorship and commit log message each1762taken from the message containing each patch.17631764[[public-repositories]]1765Public git repositories1766-----------------------17671768Another way to submit changes to a project is to tell the maintainer1769of that project to pull the changes from your repository using1770gitlink:git-pull[1]. In the section "<<getting-updates-with-git-pull,1771Getting updates with git pull>>" we described this as a way to get1772updates from the "main" repository, but it works just as well in the1773other direction.17741775If you and the maintainer both have accounts on the same machine, then1776you can just pull changes from each other's repositories directly;1777commands that accept repository URLs as arguments will also accept a1778local directory name:17791780-------------------------------------------------1781$ git clone /path/to/repository1782$ git pull /path/to/other/repository1783-------------------------------------------------17841785or an ssh URL:17861787-------------------------------------------------1788$ git clone ssh://yourhost/~you/repository1789-------------------------------------------------17901791For projects with few developers, or for synchronizing a few private1792repositories, this may be all you need.17931794However, the more common way to do this is to maintain a separate public1795repository (usually on a different host) for others to pull changes1796from. This is usually more convenient, and allows you to cleanly1797separate private work in progress from publicly visible work.17981799You will continue to do your day-to-day work in your personal1800repository, but periodically "push" changes from your personal1801repository into your public repository, allowing other developers to1802pull from that repository. So the flow of changes, in a situation1803where there is one other developer with a public repository, looks1804like this:18051806 you push1807 your personal repo ------------------> your public repo1808 ^ |1809 | |1810 | you pull | they pull1811 | |1812 | |1813 | they push V1814 their public repo <------------------- their repo18151816We explain how to do this in the following sections.18171818[[setting-up-a-public-repository]]1819Setting up a public repository1820~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~18211822Assume your personal repository is in the directory ~/proj. We1823first create a new clone of the repository and tell git-daemon that it1824is meant to be public:18251826-------------------------------------------------1827$ git clone --bare ~/proj proj.git1828$ touch proj.git/git-daemon-export-ok1829-------------------------------------------------18301831The resulting directory proj.git contains a "bare" git repository--it is1832just the contents of the ".git" directory, without any files checked out1833around it.18341835Next, copy proj.git to the server where you plan to host the1836public repository. You can use scp, rsync, or whatever is most1837convenient.18381839[[exporting-via-git]]1840Exporting a git repository via the git protocol1841~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~18421843This is the preferred method.18441845If someone else administers the server, they should tell you what1846directory to put the repository in, and what git:// URL it will appear1847at. You can then skip to the section1848"<<pushing-changes-to-a-public-repository,Pushing changes to a public1849repository>>", below.18501851Otherwise, all you need to do is start gitlink:git-daemon[1]; it will1852listen on port 9418. By default, it will allow access to any directory1853that looks like a git directory and contains the magic file1854git-daemon-export-ok. Passing some directory paths as git-daemon1855arguments will further restrict the exports to those paths.18561857You can also run git-daemon as an inetd service; see the1858gitlink:git-daemon[1] man page for details. (See especially the1859examples section.)18601861[[exporting-via-http]]1862Exporting a git repository via http1863~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~18641865The git protocol gives better performance and reliability, but on a1866host with a web server set up, http exports may be simpler to set up.18671868All you need to do is place the newly created bare git repository in1869a directory that is exported by the web server, and make some1870adjustments to give web clients some extra information they need:18711872-------------------------------------------------1873$ mv proj.git /home/you/public_html/proj.git1874$ cd proj.git1875$ git --bare update-server-info1876$ chmod a+x hooks/post-update1877-------------------------------------------------18781879(For an explanation of the last two lines, see1880gitlink:git-update-server-info[1], and the documentation1881link:hooks.html[Hooks used by git].)18821883Advertise the URL of proj.git. Anybody else should then be able to1884clone or pull from that URL, for example with a command line like:18851886-------------------------------------------------1887$ git clone http://yourserver.com/~you/proj.git1888-------------------------------------------------18891890(See also1891link:howto/setup-git-server-over-http.txt[setup-git-server-over-http]1892for a slightly more sophisticated setup using WebDAV which also1893allows pushing over http.)18941895[[pushing-changes-to-a-public-repository]]1896Pushing changes to a public repository1897~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~18981899Note that the two techniques outlined above (exporting via1900<<exporting-via-http,http>> or <<exporting-via-git,git>>) allow other1901maintainers to fetch your latest changes, but they do not allow write1902access, which you will need to update the public repository with the1903latest changes created in your private repository.19041905The simplest way to do this is using gitlink:git-push[1] and ssh; to1906update the remote branch named "master" with the latest state of your1907branch named "master", run19081909-------------------------------------------------1910$ git push ssh://yourserver.com/~you/proj.git master:master1911-------------------------------------------------19121913or just19141915-------------------------------------------------1916$ git push ssh://yourserver.com/~you/proj.git master1917-------------------------------------------------19181919As with git-fetch, git-push will complain if this does not result in1920a <<fast-forwards,fast forward>>. Normally this is a sign of1921something wrong. However, if you are sure you know what you're1922doing, you may force git-push to perform the update anyway by1923preceding the branch name by a plus sign:19241925-------------------------------------------------1926$ git push ssh://yourserver.com/~you/proj.git +master1927-------------------------------------------------19281929Note that the target of a "push" is normally a1930<<def_bare_repository,bare>> repository. You can also push to a1931repository that has a checked-out working tree, but the working tree1932will not be updated by the push. This may lead to unexpected results if1933the branch you push to is the currently checked-out branch!19341935As with git-fetch, you may also set up configuration options to1936save typing; so, for example, after19371938-------------------------------------------------1939$ cat >>.git/config <<EOF1940[remote "public-repo"]1941 url = ssh://yourserver.com/~you/proj.git1942EOF1943-------------------------------------------------19441945you should be able to perform the above push with just19461947-------------------------------------------------1948$ git push public-repo master1949-------------------------------------------------19501951See the explanations of the remote.<name>.url, branch.<name>.remote,1952and remote.<name>.push options in gitlink:git-config[1] for1953details.19541955[[setting-up-a-shared-repository]]1956Setting up a shared repository1957~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~19581959Another way to collaborate is by using a model similar to that1960commonly used in CVS, where several developers with special rights1961all push to and pull from a single shared repository. See1962link:cvs-migration.html[git for CVS users] for instructions on how to1963set this up.19641965However, while there is nothing wrong with git's support for shared1966repositories, this mode of operation is not generally recommended,1967simply because the mode of collaboration that git supports--by1968exchanging patches and pulling from public repositories--has so many1969advantages over the central shared repository:19701971 - Git's ability to quickly import and merge patches allows a1972 single maintainer to process incoming changes even at very1973 high rates. And when that becomes too much, git-pull provides1974 an easy way for that maintainer to delegate this job to other1975 maintainers while still allowing optional review of incoming1976 changes.1977 - Since every developer's repository has the same complete copy1978 of the project history, no repository is special, and it is1979 trivial for another developer to take over maintenance of a1980 project, either by mutual agreement, or because a maintainer1981 becomes unresponsive or difficult to work with.1982 - The lack of a central group of "committers" means there is1983 less need for formal decisions about who is "in" and who is1984 "out".19851986[[setting-up-gitweb]]1987Allowing web browsing of a repository1988~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~19891990The gitweb cgi script provides users an easy way to browse your1991project's files and history without having to install git; see the file1992gitweb/INSTALL in the git source tree for instructions on setting it up.19931994[[sharing-development-examples]]1995Examples1996--------19971998[[maintaining-topic-branches]]1999Maintaining topic branches for a Linux subsystem maintainer2000~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~20012002This describes how Tony Luck uses git in his role as maintainer of the2003IA64 architecture for the Linux kernel.20042005He uses two public branches:20062007 - A "test" tree into which patches are initially placed so that they2008 can get some exposure when integrated with other ongoing development.2009 This tree is available to Andrew for pulling into -mm whenever he2010 wants.20112012 - A "release" tree into which tested patches are moved for final sanity2013 checking, and as a vehicle to send them upstream to Linus (by sending2014 him a "please pull" request.)20152016He also uses a set of temporary branches ("topic branches"), each2017containing a logical grouping of patches.20182019To set this up, first create your work tree by cloning Linus's public2020tree:20212022-------------------------------------------------2023$ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git work2024$ cd work2025-------------------------------------------------20262027Linus's tree will be stored in the remote branch named origin/master,2028and can be updated using gitlink:git-fetch[1]; you can track other2029public trees using gitlink:git-remote[1] to set up a "remote" and2030gitlink:git-fetch[1] to keep them up-to-date; see2031<<repositories-and-branches>>.20322033Now create the branches in which you are going to work; these start out2034at the current tip of origin/master branch, and should be set up (using2035the --track option to gitlink:git-branch[1]) to merge changes in from2036Linus by default.20372038-------------------------------------------------2039$ git branch --track test origin/master2040$ git branch --track release origin/master2041-------------------------------------------------20422043These can be easily kept up to date using gitlink:git-pull[1].20442045-------------------------------------------------2046$ git checkout test && git pull2047$ git checkout release && git pull2048-------------------------------------------------20492050Important note! If you have any local changes in these branches, then2051this merge will create a commit object in the history (with no local2052changes git will simply do a "Fast forward" merge). Many people dislike2053the "noise" that this creates in the Linux history, so you should avoid2054doing this capriciously in the "release" branch, as these noisy commits2055will become part of the permanent history when you ask Linus to pull2056from the release branch.20572058A few configuration variables (see gitlink:git-config[1]) can2059make it easy to push both branches to your public tree. (See2060<<setting-up-a-public-repository>>.)20612062-------------------------------------------------2063$ cat >> .git/config <<EOF2064[remote "mytree"]2065 url = master.kernel.org:/pub/scm/linux/kernel/git/aegl/linux-2.6.git2066 push = release2067 push = test2068EOF2069-------------------------------------------------20702071Then you can push both the test and release trees using2072gitlink:git-push[1]:20732074-------------------------------------------------2075$ git push mytree2076-------------------------------------------------20772078or push just one of the test and release branches using:20792080-------------------------------------------------2081$ git push mytree test2082-------------------------------------------------20832084or20852086-------------------------------------------------2087$ git push mytree release2088-------------------------------------------------20892090Now to apply some patches from the community. Think of a short2091snappy name for a branch to hold this patch (or related group of2092patches), and create a new branch from the current tip of Linus's2093branch:20942095-------------------------------------------------2096$ git checkout -b speed-up-spinlocks origin2097-------------------------------------------------20982099Now you apply the patch(es), run some tests, and commit the change(s). If2100the patch is a multi-part series, then you should apply each as a separate2101commit to this branch.21022103-------------------------------------------------2104$ ... patch ... test ... commit [ ... patch ... test ... commit ]*2105-------------------------------------------------21062107When you are happy with the state of this change, you can pull it into the2108"test" branch in preparation to make it public:21092110-------------------------------------------------2111$ git checkout test && git pull . speed-up-spinlocks2112-------------------------------------------------21132114It is unlikely that you would have any conflicts here ... but you might if you2115spent a while on this step and had also pulled new versions from upstream.21162117Some time later when enough time has passed and testing done, you can pull the2118same branch into the "release" tree ready to go upstream. This is where you2119see the value of keeping each patch (or patch series) in its own branch. It2120means that the patches can be moved into the "release" tree in any order.21212122-------------------------------------------------2123$ git checkout release && git pull . speed-up-spinlocks2124-------------------------------------------------21252126After a while, you will have a number of branches, and despite the2127well chosen names you picked for each of them, you may forget what2128they are for, or what status they are in. To get a reminder of what2129changes are in a specific branch, use:21302131-------------------------------------------------2132$ git log linux..branchname | git-shortlog2133-------------------------------------------------21342135To see whether it has already been merged into the test or release branches,2136use:21372138-------------------------------------------------2139$ git log test..branchname2140-------------------------------------------------21412142or21432144-------------------------------------------------2145$ git log release..branchname2146-------------------------------------------------21472148(If this branch has not yet been merged, you will see some log entries.2149If it has been merged, then there will be no output.)21502151Once a patch completes the great cycle (moving from test to release,2152then pulled by Linus, and finally coming back into your local2153"origin/master" branch), the branch for this change is no longer needed.2154You detect this when the output from:21552156-------------------------------------------------2157$ git log origin..branchname2158-------------------------------------------------21592160is empty. At this point the branch can be deleted:21612162-------------------------------------------------2163$ git branch -d branchname2164-------------------------------------------------21652166Some changes are so trivial that it is not necessary to create a separate2167branch and then merge into each of the test and release branches. For2168these changes, just apply directly to the "release" branch, and then2169merge that into the "test" branch.21702171To create diffstat and shortlog summaries of changes to include in a "please2172pull" request to Linus you can use:21732174-------------------------------------------------2175$ git diff --stat origin..release2176-------------------------------------------------21772178and21792180-------------------------------------------------2181$ git log -p origin..release | git shortlog2182-------------------------------------------------21832184Here are some of the scripts that simplify all this even further.21852186-------------------------------------------------2187==== update script ====2188# Update a branch in my GIT tree. If the branch to be updated2189# is origin, then pull from kernel.org. Otherwise merge2190# origin/master branch into test|release branch21912192case "$1" in2193test|release)2194 git checkout $1 && git pull . origin2195 ;;2196origin)2197 before=$(git rev-parse refs/remotes/origin/master)2198 git fetch origin2199 after=$(git rev-parse refs/remotes/origin/master)2200 if [ $before != $after ]2201 then2202 git log $before..$after | git shortlog2203 fi2204 ;;2205*)2206 echo "Usage: $0 origin|test|release" 1>&22207 exit 12208 ;;2209esac2210-------------------------------------------------22112212-------------------------------------------------2213==== merge script ====2214# Merge a branch into either the test or release branch22152216pname=$022172218usage()2219{2220 echo "Usage: $pname branch test|release" 1>&22221 exit 12222}22232224git show-ref -q --verify -- refs/heads/"$1" || {2225 echo "Can't see branch <$1>" 1>&22226 usage2227}22282229case "$2" in2230test|release)2231 if [ $(git log $2..$1 | wc -c) -eq 0 ]2232 then2233 echo $1 already merged into $2 1>&22234 exit 12235 fi2236 git checkout $2 && git pull . $12237 ;;2238*)2239 usage2240 ;;2241esac2242-------------------------------------------------22432244-------------------------------------------------2245==== status script ====2246# report on status of my ia64 GIT tree22472248gb=$(tput setab 2)2249rb=$(tput setab 1)2250restore=$(tput setab 9)22512252if [ `git rev-list test..release | wc -c` -gt 0 ]2253then2254 echo $rb Warning: commits in release that are not in test $restore2255 git log test..release2256fi22572258for branch in `git show-ref --heads | sed 's|^.*/||'`2259do2260 if [ $branch = test -o $branch = release ]2261 then2262 continue2263 fi22642265 echo -n $gb ======= $branch ====== $restore " "2266 status=2267 for ref in test release origin/master2268 do2269 if [ `git rev-list $ref..$branch | wc -c` -gt 0 ]2270 then2271 status=$status${ref:0:1}2272 fi2273 done2274 case $status in2275 trl)2276 echo $rb Need to pull into test $restore2277 ;;2278 rl)2279 echo "In test"2280 ;;2281 l)2282 echo "Waiting for linus"2283 ;;2284 "")2285 echo $rb All done $restore2286 ;;2287 *)2288 echo $rb "<$status>" $restore2289 ;;2290 esac2291 git log origin/master..$branch | git shortlog2292done2293-------------------------------------------------229422952296[[cleaning-up-history]]2297Rewriting history and maintaining patch series2298==============================================22992300Normally commits are only added to a project, never taken away or2301replaced. Git is designed with this assumption, and violating it will2302cause git's merge machinery (for example) to do the wrong thing.23032304However, there is a situation in which it can be useful to violate this2305assumption.23062307[[patch-series]]2308Creating the perfect patch series2309---------------------------------23102311Suppose you are a contributor to a large project, and you want to add a2312complicated feature, and to present it to the other developers in a way2313that makes it easy for them to read your changes, verify that they are2314correct, and understand why you made each change.23152316If you present all of your changes as a single patch (or commit), they2317may find that it is too much to digest all at once.23182319If you present them with the entire history of your work, complete with2320mistakes, corrections, and dead ends, they may be overwhelmed.23212322So the ideal is usually to produce a series of patches such that:23232324 1. Each patch can be applied in order.23252326 2. Each patch includes a single logical change, together with a2327 message explaining the change.23282329 3. No patch introduces a regression: after applying any initial2330 part of the series, the resulting project still compiles and2331 works, and has no bugs that it didn't have before.23322333 4. The complete series produces the same end result as your own2334 (probably much messier!) development process did.23352336We will introduce some tools that can help you do this, explain how to2337use them, and then explain some of the problems that can arise because2338you are rewriting history.23392340[[using-git-rebase]]2341Keeping a patch series up to date using git-rebase2342--------------------------------------------------23432344Suppose that you create a branch "mywork" on a remote-tracking branch2345"origin", and create some commits on top of it:23462347-------------------------------------------------2348$ git checkout -b mywork origin2349$ vi file.txt2350$ git commit2351$ vi otherfile.txt2352$ git commit2353...2354-------------------------------------------------23552356You have performed no merges into mywork, so it is just a simple linear2357sequence of patches on top of "origin":23582359................................................2360 o--o--o <-- origin2361 \2362 o--o--o <-- mywork2363................................................23642365Some more interesting work has been done in the upstream project, and2366"origin" has advanced:23672368................................................2369 o--o--O--o--o--o <-- origin2370 \2371 a--b--c <-- mywork2372................................................23732374At this point, you could use "pull" to merge your changes back in;2375the result would create a new merge commit, like this:23762377................................................2378 o--o--O--o--o--o <-- origin2379 \ \2380 a--b--c--m <-- mywork2381................................................23822383However, if you prefer to keep the history in mywork a simple series of2384commits without any merges, you may instead choose to use2385gitlink:git-rebase[1]:23862387-------------------------------------------------2388$ git checkout mywork2389$ git rebase origin2390-------------------------------------------------23912392This will remove each of your commits from mywork, temporarily saving2393them as patches (in a directory named ".dotest"), update mywork to2394point at the latest version of origin, then apply each of the saved2395patches to the new mywork. The result will look like:239623972398................................................2399 o--o--O--o--o--o <-- origin2400 \2401 a'--b'--c' <-- mywork2402................................................24032404In the process, it may discover conflicts. In that case it will stop2405and allow you to fix the conflicts; after fixing conflicts, use "git2406add" to update the index with those contents, and then, instead of2407running git-commit, just run24082409-------------------------------------------------2410$ git rebase --continue2411-------------------------------------------------24122413and git will continue applying the rest of the patches.24142415At any point you may use the `--abort` option to abort this process and2416return mywork to the state it had before you started the rebase:24172418-------------------------------------------------2419$ git rebase --abort2420-------------------------------------------------24212422[[modifying-one-commit]]2423Modifying a single commit2424-------------------------24252426We saw in <<fixing-a-mistake-by-editing-history>> that you can replace the2427most recent commit using24282429-------------------------------------------------2430$ git commit --amend2431-------------------------------------------------24322433which will replace the old commit by a new commit incorporating your2434changes, giving you a chance to edit the old commit message first.24352436You can also use a combination of this and gitlink:git-rebase[1] to edit2437commits further back in your history. First, tag the problematic commit with24382439-------------------------------------------------2440$ git tag bad mywork~52441-------------------------------------------------24422443(Either gitk or git-log may be useful for finding the commit.)24442445Then check out that commit, edit it, and rebase the rest of the series2446on top of it (note that we could check out the commit on a temporary2447branch, but instead we're using a <<detached-head,detached head>>):24482449-------------------------------------------------2450$ git checkout bad2451$ # make changes here and update the index2452$ git commit --amend2453$ git rebase --onto HEAD bad mywork2454-------------------------------------------------24552456When you're done, you'll be left with mywork checked out, with the top2457patches on mywork reapplied on top of your modified commit. You can2458then clean up with24592460-------------------------------------------------2461$ git tag -d bad2462-------------------------------------------------24632464Note that the immutable nature of git history means that you haven't really2465"modified" existing commits; instead, you have replaced the old commits with2466new commits having new object names.24672468[[reordering-patch-series]]2469Reordering or selecting from a patch series2470-------------------------------------------24712472Given one existing commit, the gitlink:git-cherry-pick[1] command2473allows you to apply the change introduced by that commit and create a2474new commit that records it. So, for example, if "mywork" points to a2475series of patches on top of "origin", you might do something like:24762477-------------------------------------------------2478$ git checkout -b mywork-new origin2479$ gitk origin..mywork &2480-------------------------------------------------24812482and browse through the list of patches in the mywork branch using gitk,2483applying them (possibly in a different order) to mywork-new using2484cherry-pick, and possibly modifying them as you go using `commit --amend`.2485The gitlink:git-gui[1] command may also help as it allows you to2486individually select diff hunks for inclusion in the index (by2487right-clicking on the diff hunk and choosing "Stage Hunk for Commit").24882489Another technique is to use git-format-patch to create a series of2490patches, then reset the state to before the patches:24912492-------------------------------------------------2493$ git format-patch origin2494$ git reset --hard origin2495-------------------------------------------------24962497Then modify, reorder, or eliminate patches as preferred before applying2498them again with gitlink:git-am[1].24992500[[patch-series-tools]]2501Other tools2502-----------25032504There are numerous other tools, such as StGIT, which exist for the2505purpose of maintaining a patch series. These are outside of the scope of2506this manual.25072508[[problems-with-rewriting-history]]2509Problems with rewriting history2510-------------------------------25112512The primary problem with rewriting the history of a branch has to do2513with merging. Suppose somebody fetches your branch and merges it into2514their branch, with a result something like this:25152516................................................2517 o--o--O--o--o--o <-- origin2518 \ \2519 t--t--t--m <-- their branch:2520................................................25212522Then suppose you modify the last three commits:25232524................................................2525 o--o--o <-- new head of origin2526 /2527 o--o--O--o--o--o <-- old head of origin2528................................................25292530If we examined all this history together in one repository, it will2531look like:25322533................................................2534 o--o--o <-- new head of origin2535 /2536 o--o--O--o--o--o <-- old head of origin2537 \ \2538 t--t--t--m <-- their branch:2539................................................25402541Git has no way of knowing that the new head is an updated version of2542the old head; it treats this situation exactly the same as it would if2543two developers had independently done the work on the old and new heads2544in parallel. At this point, if someone attempts to merge the new head2545in to their branch, git will attempt to merge together the two (old and2546new) lines of development, instead of trying to replace the old by the2547new. The results are likely to be unexpected.25482549You may still choose to publish branches whose history is rewritten,2550and it may be useful for others to be able to fetch those branches in2551order to examine or test them, but they should not attempt to pull such2552branches into their own work.25532554For true distributed development that supports proper merging,2555published branches should never be rewritten.25562557[[advanced-branch-management]]2558Advanced branch management2559==========================25602561[[fetching-individual-branches]]2562Fetching individual branches2563----------------------------25642565Instead of using gitlink:git-remote[1], you can also choose just2566to update one branch at a time, and to store it locally under an2567arbitrary name:25682569-------------------------------------------------2570$ git fetch origin todo:my-todo-work2571-------------------------------------------------25722573The first argument, "origin", just tells git to fetch from the2574repository you originally cloned from. The second argument tells git2575to fetch the branch named "todo" from the remote repository, and to2576store it locally under the name refs/heads/my-todo-work.25772578You can also fetch branches from other repositories; so25792580-------------------------------------------------2581$ git fetch git://example.com/proj.git master:example-master2582-------------------------------------------------25832584will create a new branch named "example-master" and store in it the2585branch named "master" from the repository at the given URL. If you2586already have a branch named example-master, it will attempt to2587<<fast-forwards,fast-forward>> to the commit given by example.com's2588master branch. In more detail:25892590[[fetch-fast-forwards]]2591git fetch and fast-forwards2592---------------------------25932594In the previous example, when updating an existing branch, "git2595fetch" checks to make sure that the most recent commit on the remote2596branch is a descendant of the most recent commit on your copy of the2597branch before updating your copy of the branch to point at the new2598commit. Git calls this process a <<fast-forwards,fast forward>>.25992600A fast forward looks something like this:26012602................................................2603 o--o--o--o <-- old head of the branch2604 \2605 o--o--o <-- new head of the branch2606................................................260726082609In some cases it is possible that the new head will *not* actually be2610a descendant of the old head. For example, the developer may have2611realized she made a serious mistake, and decided to backtrack,2612resulting in a situation like:26132614................................................2615 o--o--o--o--a--b <-- old head of the branch2616 \2617 o--o--o <-- new head of the branch2618................................................26192620In this case, "git fetch" will fail, and print out a warning.26212622In that case, you can still force git to update to the new head, as2623described in the following section. However, note that in the2624situation above this may mean losing the commits labeled "a" and "b",2625unless you've already created a reference of your own pointing to2626them.26272628[[forcing-fetch]]2629Forcing git fetch to do non-fast-forward updates2630------------------------------------------------26312632If git fetch fails because the new head of a branch is not a2633descendant of the old head, you may force the update with:26342635-------------------------------------------------2636$ git fetch git://example.com/proj.git +master:refs/remotes/example/master2637-------------------------------------------------26382639Note the addition of the "+" sign. Alternatively, you can use the "-f"2640flag to force updates of all the fetched branches, as in:26412642-------------------------------------------------2643$ git fetch -f origin2644-------------------------------------------------26452646Be aware that commits that the old version of example/master pointed at2647may be lost, as we saw in the previous section.26482649[[remote-branch-configuration]]2650Configuring remote branches2651---------------------------26522653We saw above that "origin" is just a shortcut to refer to the2654repository that you originally cloned from. This information is2655stored in git configuration variables, which you can see using2656gitlink:git-config[1]:26572658-------------------------------------------------2659$ git config -l2660core.repositoryformatversion=02661core.filemode=true2662core.logallrefupdates=true2663remote.origin.url=git://git.kernel.org/pub/scm/git/git.git2664remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*2665branch.master.remote=origin2666branch.master.merge=refs/heads/master2667-------------------------------------------------26682669If there are other repositories that you also use frequently, you can2670create similar configuration options to save typing; for example,2671after26722673-------------------------------------------------2674$ git config remote.example.url git://example.com/proj.git2675-------------------------------------------------26762677then the following two commands will do the same thing:26782679-------------------------------------------------2680$ git fetch git://example.com/proj.git master:refs/remotes/example/master2681$ git fetch example master:refs/remotes/example/master2682-------------------------------------------------26832684Even better, if you add one more option:26852686-------------------------------------------------2687$ git config remote.example.fetch master:refs/remotes/example/master2688-------------------------------------------------26892690then the following commands will all do the same thing:26912692-------------------------------------------------2693$ git fetch git://example.com/proj.git master:refs/remotes/example/master2694$ git fetch example master:refs/remotes/example/master2695$ git fetch example2696-------------------------------------------------26972698You can also add a "+" to force the update each time:26992700-------------------------------------------------2701$ git config remote.example.fetch +master:ref/remotes/example/master2702-------------------------------------------------27032704Don't do this unless you're sure you won't mind "git fetch" possibly2705throwing away commits on mybranch.27062707Also note that all of the above configuration can be performed by2708directly editing the file .git/config instead of using2709gitlink:git-config[1].27102711See gitlink:git-config[1] for more details on the configuration2712options mentioned above.271327142715[[git-concepts]]2716Git concepts2717============27182719Git is built on a small number of simple but powerful ideas. While it2720is possible to get things done without understanding them, you will find2721git much more intuitive if you do.27222723We start with the most important, the <<def_object_database,object2724database>> and the <<def_index,index>>.27252726[[the-object-database]]2727The Object Database2728-------------------272927302731We already saw in <<understanding-commits>> that all commits are stored2732under a 40-digit "object name". In fact, all the information needed to2733represent the history of a project is stored in objects with such names.2734In each case the name is calculated by taking the SHA1 hash of the2735contents of the object. The SHA1 hash is a cryptographic hash function.2736What that means to us is that it is impossible to find two different2737objects with the same name. This has a number of advantages; among2738others:27392740- Git can quickly determine whether two objects are identical or not,2741 just by comparing names.2742- Since object names are computed the same way in every repository, the2743 same content stored in two repositories will always be stored under2744 the same name.2745- Git can detect errors when it reads an object, by checking that the2746 object's name is still the SHA1 hash of its contents.27472748(See <<object-details>> for the details of the object formatting and2749SHA1 calculation.)27502751There are four different types of objects: "blob", "tree", "commit", and2752"tag".27532754- A <<def_blob_object,"blob" object>> is used to store file data.2755- A <<def_tree_object,"tree" object>> is an object that ties one or more2756 "blob" objects into a directory structure. In addition, a tree object2757 can refer to other tree objects, thus creating a directory hierarchy.2758- A <<def_commit_object,"commit" object>> ties such directory hierarchies2759 together into a <<def_DAG,directed acyclic graph>> of revisions--each2760 commit contains the object name of exactly one tree designating the2761 directory hierarchy at the time of the commit. In addition, a commit2762 refers to "parent" commit objects that describe the history of how we2763 arrived at that directory hierarchy.2764- A <<def_tag_object,"tag" object>> symbolically identifies and can be2765 used to sign other objects. It contains the object name and type of2766 another object, a symbolic name (of course!) and, optionally, a2767 signature.27682769The object types in some more detail:27702771[[commit-object]]2772Commit Object2773~~~~~~~~~~~~~27742775The "commit" object links a physical state of a tree with a description2776of how we got there and why. Use the --pretty=raw option to2777gitlink:git-show[1] or gitlink:git-log[1] to examine your favorite2778commit:27792780------------------------------------------------2781$ git show -s --pretty=raw 2be7fcb4762782commit 2be7fcb4764f2dbcee52635b91fedb1b3dcf7ab42783tree fb3a8bdd0ceddd019615af4d57a53f43d8cee2bf2784parent 257a84d9d02e90447b149af58b271c19405edb6a2785author Dave Watson <dwatson@mimvista.com> 1187576872 -04002786committer Junio C Hamano <gitster@pobox.com> 1187591163 -070027872788 Fix misspelling of 'suppress' in docs27892790 Signed-off-by: Junio C Hamano <gitster@pobox.com>2791------------------------------------------------27922793As you can see, a commit is defined by:27942795- a tree: The SHA1 name of a tree object (as defined below), representing2796 the contents of a directory at a certain point in time.2797- parent(s): The SHA1 name of some number of commits which represent the2798 immediately prevoius step(s) in the history of the project. The2799 example above has one parent; merge commits may have more than2800 one. A commit with no parents is called a "root" commit, and2801 represents the initial revision of a project. Each project must have2802 at least one root. A project can also have multiple roots, though2803 that isn't common (or necessarily a good idea).2804- an author: The name of the person responsible for this change, together2805 with its date.2806- a committer: The name of the person who actually created the commit,2807 with the date it was done. This may be different from the author, for2808 example, if the author was someone who wrote a patch and emailed it2809 to the person who used it to create the commit.2810- a comment describing this commit.28112812Note that a commit does not itself contain any information about what2813actually changed; all changes are calculated by comparing the contents2814of the tree referred to by this commit with the trees associated with2815its parents. In particular, git does not attempt to record file renames2816explicitly, though it can identify cases where the existence of the same2817file data at changing paths suggests a rename. (See, for example, the2818-M option to gitlink:git-diff[1]).28192820A commit is usually created by gitlink:git-commit[1], which creates a2821commit whose parent is normally the current HEAD, and whose tree is2822taken from the content currently stored in the index.28232824[[tree-object]]2825Tree Object2826~~~~~~~~~~~28272828The ever-versatile gitlink:git-show[1] command can also be used to2829examine tree objects, but gitlink:git-ls-tree[1] will give you more2830details:28312832------------------------------------------------2833$ git ls-tree fb3a8bdd0ce2834100644 blob 63c918c667fa005ff12ad89437f2fdc80926e21c .gitignore2835100644 blob 5529b198e8d14decbe4ad99db3f7fb632de0439d .mailmap2836100644 blob 6ff87c4664981e4397625791c8ea3bbb5f2279a3 COPYING2837040000 tree 2fb783e477100ce076f6bf57e4a6f026013dc745 Documentation2838100755 blob 3c0032cec592a765692234f1cba47dfdcc3a9200 GIT-VERSION-GEN2839100644 blob 289b046a443c0647624607d471289b2c7dcd470b INSTALL2840100644 blob 4eb463797adc693dc168b926b6932ff53f17d0b1 Makefile2841100644 blob 548142c327a6790ff8821d67c2ee1eff7a656b52 README2842...2843------------------------------------------------28442845As you can see, a tree object contains a list of entries, each with a2846mode, object type, SHA1 name, and name, sorted by name. It represents2847the contents of a single directory tree.28482849The object type may be a blob, representing the contents of a file, or2850another tree, representing the contents of a subdirectory. Since trees2851and blobs, like all other objects, are named by the SHA1 hash of their2852contents, two trees have the same SHA1 name if and only if their2853contents (including, recursively, the contents of all subdirectories)2854are identical. This allows git to quickly determine the differences2855between two related tree objects, since it can ignore any entries with2856identical object names.28572858(Note: in the presence of submodules, trees may also have commits as2859entries. See <<submodules>> for documentation.)28602861Note that the files all have mode 644 or 755: git actually only pays2862attention to the executable bit.28632864[[blob-object]]2865Blob Object2866~~~~~~~~~~~28672868You can use gitlink:git-show[1] to examine the contents of a blob; take,2869for example, the blob in the entry for "COPYING" from the tree above:28702871------------------------------------------------2872$ git show 6ff87c466428732874 Note that the only valid version of the GPL as far as this project2875 is concerned is _this_ particular version of the license (ie v2, not2876 v2.2 or v3.x or whatever), unless explicitly otherwise stated.2877...2878------------------------------------------------28792880A "blob" object is nothing but a binary blob of data. It doesn't refer2881to anything else or have attributes of any kind.28822883Since the blob is entirely defined by its data, if two files in a2884directory tree (or in multiple different versions of the repository)2885have the same contents, they will share the same blob object. The object2886is totally independent of its location in the directory tree, and2887renaming a file does not change the object that file is associated with.28882889Note that any tree or blob object can be examined using2890gitlink:git-show[1] with the <revision>:<path> syntax. This can2891sometimes be useful for browsing the contents of a tree that is not2892currently checked out.28932894[[trust]]2895Trust2896~~~~~28972898If you receive the SHA1 name of a blob from one source, and its contents2899from another (possibly untrusted) source, you can still trust that those2900contents are correct as long as the SHA1 name agrees. This is because2901the SHA1 is designed so that it is infeasible to find different contents2902that produce the same hash.29032904Similarly, you need only trust the SHA1 name of a top-level tree object2905to trust the contents of the entire directory that it refers to, and if2906you receive the SHA1 name of a commit from a trusted source, then you2907can easily verify the entire history of commits reachable through2908parents of that commit, and all of those contents of the trees referred2909to by those commits.29102911So to introduce some real trust in the system, the only thing you need2912to do is to digitally sign just 'one' special note, which includes the2913name of a top-level commit. Your digital signature shows others2914that you trust that commit, and the immutability of the history of2915commits tells others that they can trust the whole history.29162917In other words, you can easily validate a whole archive by just2918sending out a single email that tells the people the name (SHA1 hash)2919of the top commit, and digitally sign that email using something2920like GPG/PGP.29212922To assist in this, git also provides the tag object...29232924[[tag-object]]2925Tag Object2926~~~~~~~~~~29272928A tag object contains an object, object type, tag name, the name of the2929person ("tagger") who created the tag, and a message, which may contain2930a signature, as can be seen using the gitlink:git-cat-file[1]:29312932------------------------------------------------2933$ git cat-file tag v1.5.02934object 437b1b20df4b356c9342dac8d38849f24ef44f272935type commit2936tag v1.5.02937tagger Junio C Hamano <junkio@cox.net> 1171411200 +000029382939GIT 1.5.02940-----BEGIN PGP SIGNATURE-----2941Version: GnuPG v1.4.6 (GNU/Linux)29422943iD8DBQBF0lGqwMbZpPMRm5oRAuRiAJ9ohBLd7s2kqjkKlq1qqC57SbnmzQCdG4ui2944nLE/L9aUXdWeTFPron96DLA=2945=2E+02946-----END PGP SIGNATURE-----2947------------------------------------------------29482949See the gitlink:git-tag[1] command to learn how to create and verify tag2950objects. (Note that gitlink:git-tag[1] can also be used to create2951"lightweight tags", which are not tag objects at all, but just simple2952references whose names begin with "refs/tags/").29532954[[pack-files]]2955How git stores objects efficiently: pack files2956~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~29572958Newly created objects are initially created in a file named after the2959object's SHA1 hash (stored in .git/objects).29602961Unfortunately this system becomes inefficient once a project has a2962lot of objects. Try this on an old project:29632964------------------------------------------------2965$ git count-objects29666930 objects, 47620 kilobytes2967------------------------------------------------29682969The first number is the number of objects which are kept in2970individual files. The second is the amount of space taken up by2971those "loose" objects.29722973You can save space and make git faster by moving these loose objects in2974to a "pack file", which stores a group of objects in an efficient2975compressed format; the details of how pack files are formatted can be2976found in link:technical/pack-format.txt[technical/pack-format.txt].29772978To put the loose objects into a pack, just run git repack:29792980------------------------------------------------2981$ git repack2982Generating pack...2983Done counting 6020 objects.2984Deltifying 6020 objects.2985 100% (6020/6020) done2986Writing 6020 objects.2987 100% (6020/6020) done2988Total 6020, written 6020 (delta 4070), reused 0 (delta 0)2989Pack pack-3e54ad29d5b2e05838c75df582c65257b8d08e1c created.2990------------------------------------------------29912992You can then run29932994------------------------------------------------2995$ git prune2996------------------------------------------------29972998to remove any of the "loose" objects that are now contained in the2999pack. This will also remove any unreferenced objects (which may be3000created when, for example, you use "git reset" to remove a commit).3001You can verify that the loose objects are gone by looking at the3002.git/objects directory or by running30033004------------------------------------------------3005$ git count-objects30060 objects, 0 kilobytes3007------------------------------------------------30083009Although the object files are gone, any commands that refer to those3010objects will work exactly as they did before.30113012The gitlink:git-gc[1] command performs packing, pruning, and more for3013you, so is normally the only high-level command you need.30143015[[dangling-objects]]3016Dangling objects3017~~~~~~~~~~~~~~~~30183019The gitlink:git-fsck[1] command will sometimes complain about dangling3020objects. They are not a problem.30213022The most common cause of dangling objects is that you've rebased a3023branch, or you have pulled from somebody else who rebased a branch--see3024<<cleaning-up-history>>. In that case, the old head of the original3025branch still exists, as does everything it pointed to. The branch3026pointer itself just doesn't, since you replaced it with another one.30273028There are also other situations that cause dangling objects. For3029example, a "dangling blob" may arise because you did a "git add" of a3030file, but then, before you actually committed it and made it part of the3031bigger picture, you changed something else in that file and committed3032that *updated* thing--the old state that you added originally ends up3033not being pointed to by any commit or tree, so it's now a dangling blob3034object.30353036Similarly, when the "recursive" merge strategy runs, and finds that3037there are criss-cross merges and thus more than one merge base (which is3038fairly unusual, but it does happen), it will generate one temporary3039midway tree (or possibly even more, if you had lots of criss-crossing3040merges and more than two merge bases) as a temporary internal merge3041base, and again, those are real objects, but the end result will not end3042up pointing to them, so they end up "dangling" in your repository.30433044Generally, dangling objects aren't anything to worry about. They can3045even be very useful: if you screw something up, the dangling objects can3046be how you recover your old tree (say, you did a rebase, and realized3047that you really didn't want to--you can look at what dangling objects3048you have, and decide to reset your head to some old dangling state).30493050For commits, you can just use:30513052------------------------------------------------3053$ gitk <dangling-commit-sha-goes-here> --not --all3054------------------------------------------------30553056This asks for all the history reachable from the given commit but not3057from any branch, tag, or other reference. If you decide it's something3058you want, you can always create a new reference to it, e.g.,30593060------------------------------------------------3061$ git branch recovered-branch <dangling-commit-sha-goes-here>3062------------------------------------------------30633064For blobs and trees, you can't do the same, but you can still examine3065them. You can just do30663067------------------------------------------------3068$ git show <dangling-blob/tree-sha-goes-here>3069------------------------------------------------30703071to show what the contents of the blob were (or, for a tree, basically3072what the "ls" for that directory was), and that may give you some idea3073of what the operation was that left that dangling object.30743075Usually, dangling blobs and trees aren't very interesting. They're3076almost always the result of either being a half-way mergebase (the blob3077will often even have the conflict markers from a merge in it, if you3078have had conflicting merges that you fixed up by hand), or simply3079because you interrupted a "git fetch" with ^C or something like that,3080leaving _some_ of the new objects in the object database, but just3081dangling and useless.30823083Anyway, once you are sure that you're not interested in any dangling3084state, you can just prune all unreachable objects:30853086------------------------------------------------3087$ git prune3088------------------------------------------------30893090and they'll be gone. But you should only run "git prune" on a quiescent3091repository--it's kind of like doing a filesystem fsck recovery: you3092don't want to do that while the filesystem is mounted.30933094(The same is true of "git-fsck" itself, btw, but since3095git-fsck never actually *changes* the repository, it just reports3096on what it found, git-fsck itself is never "dangerous" to run.3097Running it while somebody is actually changing the repository can cause3098confusing and scary messages, but it won't actually do anything bad. In3099contrast, running "git prune" while somebody is actively changing the3100repository is a *BAD* idea).31013102[[the-index]]3103The index3104-----------31053106The index is a binary file (generally kept in .git/index) containing a3107sorted list of path names, each with permissions and the SHA1 of a blob3108object; gitlink:git-ls-files[1] can show you the contents of the index:31093110-------------------------------------------------3111$ git ls-files --stage3112100644 63c918c667fa005ff12ad89437f2fdc80926e21c 0 .gitignore3113100644 5529b198e8d14decbe4ad99db3f7fb632de0439d 0 .mailmap3114100644 6ff87c4664981e4397625791c8ea3bbb5f2279a3 0 COPYING3115100644 a37b2152bd26be2c2289e1f57a292534a51a93c7 0 Documentation/.gitignore3116100644 fbefe9a45b00a54b58d94d06eca48b03d40a50e0 0 Documentation/Makefile3117...3118100644 2511aef8d89ab52be5ec6a5e46236b4b6bcd07ea 0 xdiff/xtypes.h3119100644 2ade97b2574a9f77e7ae4002a4e07a6a38e46d07 0 xdiff/xutils.c3120100644 d5de8292e05e7c36c4b68857c1cf9855e3d2f70a 0 xdiff/xutils.h3121-------------------------------------------------31223123Note that in older documentation you may see the index called the3124"current directory cache" or just the "cache". It has three important3125properties:312631271. The index contains all the information necessary to generate a single3128(uniquely determined) tree object.3129+3130For example, running gitlink:git-commit[1] generates this tree object3131from the index, stores it in the object database, and uses it as the3132tree object associated with the new commit.313331342. The index enables fast comparisons between the tree object it defines3135and the working tree.3136+3137It does this by storing some additional data for each entry (such as3138the last modified time). This data is not displayed above, and is not3139stored in the created tree object, but it can be used to determine3140quickly which files in the working directory differ from what was3141stored in the index, and thus save git from having to read all of the3142data from such files to look for changes.314331443. It can efficiently represent information about merge conflicts3145between different tree objects, allowing each pathname to be3146associated with sufficient information about the trees involved that3147you can create a three-way merge between them.3148+3149We saw in <<conflict-resolution>> that during a merge the index can3150store multiple versions of a single file (called "stages"). The third3151column in the gitlink:git-ls-files[1] output above is the stage3152number, and will take on values other than 0 for files with merge3153conflicts.31543155The index is thus a sort of temporary staging area, which is filled with3156a tree which you are in the process of working on.31573158If you blow the index away entirely, you generally haven't lost any3159information as long as you have the name of the tree that it described.31603161[[submodules]]3162Submodules3163==========31643165Large projects are often composed of smaller, self-contained modules. For3166example, an embedded Linux distribution's source tree would include every3167piece of software in the distribution with some local modifications; a movie3168player might need to build against a specific, known-working version of a3169decompression library; several independent programs might all share the same3170build scripts.31713172With centralized revision control systems this is often accomplished by3173including every module in one single repository. Developers can check out3174all modules or only the modules they need to work with. They can even modify3175files across several modules in a single commit while moving things around3176or updating APIs and translations.31773178Git does not allow partial checkouts, so duplicating this approach in Git3179would force developers to keep a local copy of modules they are not3180interested in touching. Commits in an enormous checkout would be slower3181than you'd expect as Git would have to scan every directory for changes.3182If modules have a lot of local history, clones would take forever.31833184On the plus side, distributed revision control systems can much better3185integrate with external sources. In a centralized model, a single arbitrary3186snapshot of the external project is exported from its own revision control3187and then imported into the local revision control on a vendor branch. All3188the history is hidden. With distributed revision control you can clone the3189entire external history and much more easily follow development and re-merge3190local changes.31913192Git's submodule support allows a repository to contain, as a subdirectory, a3193checkout of an external project. Submodules maintain their own identity;3194the submodule support just stores the submodule repository location and3195commit ID, so other developers who clone the containing project3196("superproject") can easily clone all the submodules at the same revision.3197Partial checkouts of the superproject are possible: you can tell Git to3198clone none, some or all of the submodules.31993200The gitlink:git-submodule[1] command is available since Git 1.5.3. Users3201with Git 1.5.2 can look up the submodule commits in the repository and3202manually check them out; earlier versions won't recognize the submodules at3203all.32043205To see how submodule support works, create (for example) four example3206repositories that can be used later as a submodule:32073208-------------------------------------------------3209$ mkdir ~/git3210$ cd ~/git3211$ for i in a b c d3212do3213 mkdir $i3214 cd $i3215 git init3216 echo "module $i" > $i.txt3217 git add $i.txt3218 git commit -m "Initial commit, submodule $i"3219 cd ..3220done3221-------------------------------------------------32223223Now create the superproject and add all the submodules:32243225-------------------------------------------------3226$ mkdir super3227$ cd super3228$ git init3229$ for i in a b c d3230do3231 git submodule add ~/git/$i3232done3233-------------------------------------------------32343235NOTE: Do not use local URLs here if you plan to publish your superproject!32363237See what files `git submodule` created:32383239-------------------------------------------------3240$ ls -a3241. .. .git .gitmodules a b c d3242-------------------------------------------------32433244The `git submodule add` command does a couple of things:32453246- It clones the submodule under the current directory and by default checks out3247 the master branch.3248- It adds the submodule's clone path to the gitlink:gitmodules[5] file and3249 adds this file to the index, ready to be committed.3250- It adds the submodule's current commit ID to the index, ready to be3251 committed.32523253Commit the superproject:32543255-------------------------------------------------3256$ git commit -m "Add submodules a, b, c and d."3257-------------------------------------------------32583259Now clone the superproject:32603261-------------------------------------------------3262$ cd ..3263$ git clone super cloned3264$ cd cloned3265-------------------------------------------------32663267The submodule directories are there, but they're empty:32683269-------------------------------------------------3270$ ls -a a3271. ..3272$ git submodule status3273-d266b9873ad50488163457f025db7cdd9683d88b a3274-e81d457da15309b4fef4249aba9b50187999670d b3275-c1536a972b9affea0f16e0680ba87332dc059146 c3276-d96249ff5d57de5de093e6baff9e0aafa5276a74 d3277-------------------------------------------------32783279NOTE: The commit object names shown above would be different for you, but they3280should match the HEAD commit object names of your repositories. You can check3281it by running `git ls-remote ../a`.32823283Pulling down the submodules is a two-step process. First run `git submodule3284init` to add the submodule repository URLs to `.git/config`:32853286-------------------------------------------------3287$ git submodule init3288-------------------------------------------------32893290Now use `git submodule update` to clone the repositories and check out the3291commits specified in the superproject:32923293-------------------------------------------------3294$ git submodule update3295$ cd a3296$ ls -a3297. .. .git a.txt3298-------------------------------------------------32993300One major difference between `git submodule update` and `git submodule add` is3301that `git submodule update` checks out a specific commit, rather than the tip3302of a branch. It's like checking out a tag: the head is detached, so you're not3303working on a branch.33043305-------------------------------------------------3306$ git branch3307* (no branch)3308 master3309-------------------------------------------------33103311If you want to make a change within a submodule and you have a detached head,3312then you should create or checkout a branch, make your changes, publish the3313change within the submodule, and then update the superproject to reference the3314new commit:33153316-------------------------------------------------3317$ git checkout master3318-------------------------------------------------33193320or33213322-------------------------------------------------3323$ git checkout -b fix-up3324-------------------------------------------------33253326then33273328-------------------------------------------------3329$ echo "adding a line again" >> a.txt3330$ git commit -a -m "Updated the submodule from within the superproject."3331$ git push3332$ cd ..3333$ git diff3334diff --git a/a b/a3335index d266b98..261dfac 1600003336--- a/a3337+++ b/a3338@@ -1 +1 @@3339-Subproject commit d266b9873ad50488163457f025db7cdd9683d88b3340+Subproject commit 261dfac35cb99d380eb966e102c1197139f7fa243341$ git add a3342$ git commit -m "Updated submodule a."3343$ git push3344-------------------------------------------------33453346You have to run `git submodule update` after `git pull` if you want to update3347submodules, too.33483349Pitfalls with submodules3350------------------------33513352Always publish the submodule change before publishing the change to the3353superproject that references it. If you forget to publish the submodule change,3354others won't be able to clone the repository:33553356-------------------------------------------------3357$ cd ~/git/super/a3358$ echo i added another line to this file >> a.txt3359$ git commit -a -m "doing it wrong this time"3360$ cd ..3361$ git add a3362$ git commit -m "Updated submodule a again."3363$ git push3364$ cd ~/git/cloned3365$ git pull3366$ git submodule update3367error: pathspec '261dfac35cb99d380eb966e102c1197139f7fa24' did not match any file(s) known to git.3368Did you forget to 'git add'?3369Unable to checkout '261dfac35cb99d380eb966e102c1197139f7fa24' in submodule path 'a'3370-------------------------------------------------33713372You also should not rewind branches in a submodule beyond commits that were3373ever recorded in any superproject.33743375It's not safe to run `git submodule update` if you've made and committed3376changes within a submodule without checking out a branch first. They will be3377silently overwritten:33783379-------------------------------------------------3380$ cat a.txt3381module a3382$ echo line added from private2 >> a.txt3383$ git commit -a -m "line added inside private2"3384$ cd ..3385$ git submodule update3386Submodule path 'a': checked out 'd266b9873ad50488163457f025db7cdd9683d88b'3387$ cd a3388$ cat a.txt3389module a3390-------------------------------------------------33913392NOTE: The changes are still visible in the submodule's reflog.33933394This is not the case if you did not commit your changes.33953396[[low-level-operations]]3397Low-level git operations3398========================33993400Many of the higher-level commands were originally implemented as shell3401scripts using a smaller core of low-level git commands. These can still3402be useful when doing unusual things with git, or just as a way to3403understand its inner workings.34043405[[object-manipulation]]3406Object access and manipulation3407------------------------------34083409The gitlink:git-cat-file[1] command can show the contents of any object,3410though the higher-level gitlink:git-show[1] is usually more useful.34113412The gitlink:git-commit-tree[1] command allows constructing commits with3413arbitrary parents and trees.34143415A tree can be created with gitlink:git-write-tree[1] and its data can be3416accessed by gitlink:git-ls-tree[1]. Two trees can be compared with3417gitlink:git-diff-tree[1].34183419A tag is created with gitlink:git-mktag[1], and the signature can be3420verified by gitlink:git-verify-tag[1], though it is normally simpler to3421use gitlink:git-tag[1] for both.34223423[[the-workflow]]3424The Workflow3425------------34263427High-level operations such as gitlink:git-commit[1],3428gitlink:git-checkout[1] and gitlink:git-reset[1] work by moving data3429between the working tree, the index, and the object database. Git3430provides low-level operations which perform each of these steps3431individually.34323433Generally, all "git" operations work on the index file. Some operations3434work *purely* on the index file (showing the current state of the3435index), but most operations move data between the index file and either3436the database or the working directory. Thus there are four main3437combinations:34383439[[working-directory-to-index]]3440working directory -> index3441~~~~~~~~~~~~~~~~~~~~~~~~~~34423443The gitlink:git-update-index[1] command updates the index with3444information from the working directory. You generally update the3445index information by just specifying the filename you want to update,3446like so:34473448-------------------------------------------------3449$ git update-index filename3450-------------------------------------------------34513452but to avoid common mistakes with filename globbing etc, the command3453will not normally add totally new entries or remove old entries,3454i.e. it will normally just update existing cache entries.34553456To tell git that yes, you really do realize that certain files no3457longer exist, or that new files should be added, you3458should use the `--remove` and `--add` flags respectively.34593460NOTE! A `--remove` flag does 'not' mean that subsequent filenames will3461necessarily be removed: if the files still exist in your directory3462structure, the index will be updated with their new status, not3463removed. The only thing `--remove` means is that update-cache will be3464considering a removed file to be a valid thing, and if the file really3465does not exist any more, it will update the index accordingly.34663467As a special case, you can also do `git-update-index --refresh`, which3468will refresh the "stat" information of each index to match the current3469stat information. It will 'not' update the object status itself, and3470it will only update the fields that are used to quickly test whether3471an object still matches its old backing store object.34723473The previously introduced gitlink:git-add[1] is just a wrapper for3474gitlink:git-update-index[1].34753476[[index-to-object-database]]3477index -> object database3478~~~~~~~~~~~~~~~~~~~~~~~~34793480You write your current index file to a "tree" object with the program34813482-------------------------------------------------3483$ git write-tree3484-------------------------------------------------34853486that doesn't come with any options--it will just write out the3487current index into the set of tree objects that describe that state,3488and it will return the name of the resulting top-level tree. You can3489use that tree to re-generate the index at any time by going in the3490other direction:34913492[[object-database-to-index]]3493object database -> index3494~~~~~~~~~~~~~~~~~~~~~~~~34953496You read a "tree" file from the object database, and use that to3497populate (and overwrite--don't do this if your index contains any3498unsaved state that you might want to restore later!) your current3499index. Normal operation is just35003501-------------------------------------------------3502$ git-read-tree <sha1 of tree>3503-------------------------------------------------35043505and your index file will now be equivalent to the tree that you saved3506earlier. However, that is only your 'index' file: your working3507directory contents have not been modified.35083509[[index-to-working-directory]]3510index -> working directory3511~~~~~~~~~~~~~~~~~~~~~~~~~~35123513You update your working directory from the index by "checking out"3514files. This is not a very common operation, since normally you'd just3515keep your files updated, and rather than write to your working3516directory, you'd tell the index files about the changes in your3517working directory (i.e. `git-update-index`).35183519However, if you decide to jump to a new version, or check out somebody3520else's version, or just restore a previous tree, you'd populate your3521index file with read-tree, and then you need to check out the result3522with35233524-------------------------------------------------3525$ git-checkout-index filename3526-------------------------------------------------35273528or, if you want to check out all of the index, use `-a`.35293530NOTE! git-checkout-index normally refuses to overwrite old files, so3531if you have an old version of the tree already checked out, you will3532need to use the "-f" flag ('before' the "-a" flag or the filename) to3533'force' the checkout.353435353536Finally, there are a few odds and ends which are not purely moving3537from one representation to the other:35383539[[tying-it-all-together]]3540Tying it all together3541~~~~~~~~~~~~~~~~~~~~~35423543To commit a tree you have instantiated with "git-write-tree", you'd3544create a "commit" object that refers to that tree and the history3545behind it--most notably the "parent" commits that preceded it in3546history.35473548Normally a "commit" has one parent: the previous state of the tree3549before a certain change was made. However, sometimes it can have two3550or more parent commits, in which case we call it a "merge", due to the3551fact that such a commit brings together ("merges") two or more3552previous states represented by other commits.35533554In other words, while a "tree" represents a particular directory state3555of a working directory, a "commit" represents that state in "time",3556and explains how we got there.35573558You create a commit object by giving it the tree that describes the3559state at the time of the commit, and a list of parents:35603561-------------------------------------------------3562$ git-commit-tree <tree> -p <parent> [-p <parent2> ..]3563-------------------------------------------------35643565and then giving the reason for the commit on stdin (either through3566redirection from a pipe or file, or by just typing it at the tty).35673568git-commit-tree will return the name of the object that represents3569that commit, and you should save it away for later use. Normally,3570you'd commit a new `HEAD` state, and while git doesn't care where you3571save the note about that state, in practice we tend to just write the3572result to the file pointed at by `.git/HEAD`, so that we can always see3573what the last committed state was.35743575Here is an ASCII art by Jon Loeliger that illustrates how3576various pieces fit together.35773578------------35793580 commit-tree3581 commit obj3582 +----+3583 | |3584 | |3585 V V3586 +-----------+3587 | Object DB |3588 | Backing |3589 | Store |3590 +-----------+3591 ^3592 write-tree | |3593 tree obj | |3594 | | read-tree3595 | | tree obj3596 V3597 +-----------+3598 | Index |3599 | "cache" |3600 +-----------+3601 update-index ^3602 blob obj | |3603 | |3604 checkout-index -u | | checkout-index3605 stat | | blob obj3606 V3607 +-----------+3608 | Working |3609 | Directory |3610 +-----------+36113612------------361336143615[[examining-the-data]]3616Examining the data3617------------------36183619You can examine the data represented in the object database and the3620index with various helper tools. For every object, you can use3621gitlink:git-cat-file[1] to examine details about the3622object:36233624-------------------------------------------------3625$ git-cat-file -t <objectname>3626-------------------------------------------------36273628shows the type of the object, and once you have the type (which is3629usually implicit in where you find the object), you can use36303631-------------------------------------------------3632$ git-cat-file blob|tree|commit|tag <objectname>3633-------------------------------------------------36343635to show its contents. NOTE! Trees have binary content, and as a result3636there is a special helper for showing that content, called3637`git-ls-tree`, which turns the binary content into a more easily3638readable form.36393640It's especially instructive to look at "commit" objects, since those3641tend to be small and fairly self-explanatory. In particular, if you3642follow the convention of having the top commit name in `.git/HEAD`,3643you can do36443645-------------------------------------------------3646$ git-cat-file commit HEAD3647-------------------------------------------------36483649to see what the top commit was.36503651[[merging-multiple-trees]]3652Merging multiple trees3653----------------------36543655Git helps you do a three-way merge, which you can expand to n-way by3656repeating the merge procedure arbitrary times until you finally3657"commit" the state. The normal situation is that you'd only do one3658three-way merge (two parents), and commit it, but if you like to, you3659can do multiple parents in one go.36603661To do a three-way merge, you need the two sets of "commit" objects3662that you want to merge, use those to find the closest common parent (a3663third "commit" object), and then use those commit objects to find the3664state of the directory ("tree" object) at these points.36653666To get the "base" for the merge, you first look up the common parent3667of two commits with36683669-------------------------------------------------3670$ git-merge-base <commit1> <commit2>3671-------------------------------------------------36723673which will return you the commit they are both based on. You should3674now look up the "tree" objects of those commits, which you can easily3675do with (for example)36763677-------------------------------------------------3678$ git-cat-file commit <commitname> | head -13679-------------------------------------------------36803681since the tree object information is always the first line in a commit3682object.36833684Once you know the three trees you are going to merge (the one "original"3685tree, aka the common tree, and the two "result" trees, aka the branches3686you want to merge), you do a "merge" read into the index. This will3687complain if it has to throw away your old index contents, so you should3688make sure that you've committed those--in fact you would normally3689always do a merge against your last commit (which should thus match what3690you have in your current index anyway).36913692To do the merge, do36933694-------------------------------------------------3695$ git-read-tree -m -u <origtree> <yourtree> <targettree>3696-------------------------------------------------36973698which will do all trivial merge operations for you directly in the3699index file, and you can just write the result out with3700`git-write-tree`.370137023703[[merging-multiple-trees-2]]3704Merging multiple trees, continued3705---------------------------------37063707Sadly, many merges aren't trivial. If there are files that have3708been added, moved or removed, or if both branches have modified the3709same file, you will be left with an index tree that contains "merge3710entries" in it. Such an index tree can 'NOT' be written out to a tree3711object, and you will have to resolve any such merge clashes using3712other tools before you can write out the result.37133714You can examine such index state with `git-ls-files --unmerged`3715command. An example:37163717------------------------------------------------3718$ git-read-tree -m $orig HEAD $target3719$ git-ls-files --unmerged3720100644 263414f423d0e4d70dae8fe53fa34614ff3e2860 1 hello.c3721100644 06fa6a24256dc7e560efa5687fa84b51f0263c3a 2 hello.c3722100644 cc44c73eb783565da5831b4d820c962954019b69 3 hello.c3723------------------------------------------------37243725Each line of the `git-ls-files --unmerged` output begins with3726the blob mode bits, blob SHA1, 'stage number', and the3727filename. The 'stage number' is git's way to say which tree it3728came from: stage 1 corresponds to `$orig` tree, stage 2 `HEAD`3729tree, and stage3 `$target` tree.37303731Earlier we said that trivial merges are done inside3732`git-read-tree -m`. For example, if the file did not change3733from `$orig` to `HEAD` nor `$target`, or if the file changed3734from `$orig` to `HEAD` and `$orig` to `$target` the same way,3735obviously the final outcome is what is in `HEAD`. What the3736above example shows is that file `hello.c` was changed from3737`$orig` to `HEAD` and `$orig` to `$target` in a different way.3738You could resolve this by running your favorite 3-way merge3739program, e.g. `diff3`, `merge`, or git's own merge-file, on3740the blob objects from these three stages yourself, like this:37413742------------------------------------------------3743$ git-cat-file blob 263414f... >hello.c~13744$ git-cat-file blob 06fa6a2... >hello.c~23745$ git-cat-file blob cc44c73... >hello.c~33746$ git merge-file hello.c~2 hello.c~1 hello.c~33747------------------------------------------------37483749This would leave the merge result in `hello.c~2` file, along3750with conflict markers if there are conflicts. After verifying3751the merge result makes sense, you can tell git what the final3752merge result for this file is by:37533754-------------------------------------------------3755$ mv -f hello.c~2 hello.c3756$ git-update-index hello.c3757-------------------------------------------------37583759When a path is in unmerged state, running `git-update-index` for3760that path tells git to mark the path resolved.37613762The above is the description of a git merge at the lowest level,3763to help you understand what conceptually happens under the hood.3764In practice, nobody, not even git itself, uses three `git-cat-file`3765for this. There is `git-merge-index` program that extracts the3766stages to temporary files and calls a "merge" script on it:37673768-------------------------------------------------3769$ git-merge-index git-merge-one-file hello.c3770-------------------------------------------------37713772and that is what higher level `git merge -s resolve` is implemented with.37733774[[hacking-git]]3775Hacking git3776===========37773778This chapter covers internal details of the git implementation which3779probably only git developers need to understand.37803781[[object-details]]3782Object storage format3783---------------------37843785All objects have a statically determined "type" which identifies the3786format of the object (i.e. how it is used, and how it can refer to other3787objects). There are currently four different object types: "blob",3788"tree", "commit", and "tag".37893790Regardless of object type, all objects share the following3791characteristics: they are all deflated with zlib, and have a header3792that not only specifies their type, but also provides size information3793about the data in the object. It's worth noting that the SHA1 hash3794that is used to name the object is the hash of the original data3795plus this header, so `sha1sum` 'file' does not match the object name3796for 'file'.3797(Historical note: in the dawn of the age of git the hash3798was the sha1 of the 'compressed' object.)37993800As a result, the general consistency of an object can always be tested3801independently of the contents or the type of the object: all objects can3802be validated by verifying that (a) their hashes match the content of the3803file and (b) the object successfully inflates to a stream of bytes that3804forms a sequence of <ascii type without space> {plus} <space> {plus} <ascii decimal3805size> {plus} <byte\0> {plus} <binary object data>.38063807The structured objects can further have their structure and3808connectivity to other objects verified. This is generally done with3809the `git-fsck` program, which generates a full dependency graph3810of all objects, and verifies their internal consistency (in addition3811to just verifying their superficial consistency through the hash).38123813[[birdview-on-the-source-code]]3814A birds-eye view of Git's source code3815-------------------------------------38163817It is not always easy for new developers to find their way through Git's3818source code. This section gives you a little guidance to show where to3819start.38203821A good place to start is with the contents of the initial commit, with:38223823----------------------------------------------------3824$ git checkout e83c51633825----------------------------------------------------38263827The initial revision lays the foundation for almost everything git has3828today, but is small enough to read in one sitting.38293830Note that terminology has changed since that revision. For example, the3831README in that revision uses the word "changeset" to describe what we3832now call a <<def_commit_object,commit>>.38333834Also, we do not call it "cache" any more, but "index", however, the3835file is still called `cache.h`. Remark: Not much reason to change it now,3836especially since there is no good single name for it anyway, because it is3837basically _the_ header file which is included by _all_ of Git's C sources.38383839If you grasp the ideas in that initial commit, you should check out a3840more recent version and skim `cache.h`, `object.h` and `commit.h`.38413842In the early days, Git (in the tradition of UNIX) was a bunch of programs3843which were extremely simple, and which you used in scripts, piping the3844output of one into another. This turned out to be good for initial3845development, since it was easier to test new things. However, recently3846many of these parts have become builtins, and some of the core has been3847"libified", i.e. put into libgit.a for performance, portability reasons,3848and to avoid code duplication.38493850By now, you know what the index is (and find the corresponding data3851structures in `cache.h`), and that there are just a couple of object types3852(blobs, trees, commits and tags) which inherit their common structure from3853`struct object`, which is their first member (and thus, you can cast e.g.3854`(struct object *)commit` to achieve the _same_ as `&commit->object`, i.e.3855get at the object name and flags).38563857Now is a good point to take a break to let this information sink in.38583859Next step: get familiar with the object naming. Read <<naming-commits>>.3860There are quite a few ways to name an object (and not only revisions!).3861All of these are handled in `sha1_name.c`. Just have a quick look at3862the function `get_sha1()`. A lot of the special handling is done by3863functions like `get_sha1_basic()` or the likes.38643865This is just to get you into the groove for the most libified part of Git:3866the revision walker.38673868Basically, the initial version of `git log` was a shell script:38693870----------------------------------------------------------------3871$ git-rev-list --pretty $(git-rev-parse --default HEAD "$@") | \3872 LESS=-S ${PAGER:-less}3873----------------------------------------------------------------38743875What does this mean?38763877`git-rev-list` is the original version of the revision walker, which3878_always_ printed a list of revisions to stdout. It is still functional,3879and needs to, since most new Git programs start out as scripts using3880`git-rev-list`.38813882`git-rev-parse` is not as important any more; it was only used to filter out3883options that were relevant for the different plumbing commands that were3884called by the script.38853886Most of what `git-rev-list` did is contained in `revision.c` and3887`revision.h`. It wraps the options in a struct named `rev_info`, which3888controls how and what revisions are walked, and more.38893890The original job of `git-rev-parse` is now taken by the function3891`setup_revisions()`, which parses the revisions and the common command line3892options for the revision walker. This information is stored in the struct3893`rev_info` for later consumption. You can do your own command line option3894parsing after calling `setup_revisions()`. After that, you have to call3895`prepare_revision_walk()` for initialization, and then you can get the3896commits one by one with the function `get_revision()`.38973898If you are interested in more details of the revision walking process,3899just have a look at the first implementation of `cmd_log()`; call3900`git-show v1.3.0~155^2~4` and scroll down to that function (note that you3901no longer need to call `setup_pager()` directly).39023903Nowadays, `git log` is a builtin, which means that it is _contained_ in the3904command `git`. The source side of a builtin is39053906- a function called `cmd_<bla>`, typically defined in `builtin-<bla>.c`,3907 and declared in `builtin.h`,39083909- an entry in the `commands[]` array in `git.c`, and39103911- an entry in `BUILTIN_OBJECTS` in the `Makefile`.39123913Sometimes, more than one builtin is contained in one source file. For3914example, `cmd_whatchanged()` and `cmd_log()` both reside in `builtin-log.c`,3915since they share quite a bit of code. In that case, the commands which are3916_not_ named like the `.c` file in which they live have to be listed in3917`BUILT_INS` in the `Makefile`.39183919`git log` looks more complicated in C than it does in the original script,3920but that allows for a much greater flexibility and performance.39213922Here again it is a good point to take a pause.39233924Lesson three is: study the code. Really, it is the best way to learn about3925the organization of Git (after you know the basic concepts).39263927So, think about something which you are interested in, say, "how can I3928access a blob just knowing the object name of it?". The first step is to3929find a Git command with which you can do it. In this example, it is either3930`git show` or `git cat-file`.39313932For the sake of clarity, let's stay with `git cat-file`, because it39333934- is plumbing, and39353936- was around even in the initial commit (it literally went only through3937 some 20 revisions as `cat-file.c`, was renamed to `builtin-cat-file.c`3938 when made a builtin, and then saw less than 10 versions).39393940So, look into `builtin-cat-file.c`, search for `cmd_cat_file()` and look what3941it does.39423943------------------------------------------------------------------3944 git_config(git_default_config);3945 if (argc != 3)3946 usage("git-cat-file [-t|-s|-e|-p|<type>] <sha1>");3947 if (get_sha1(argv[2], sha1))3948 die("Not a valid object name %s", argv[2]);3949------------------------------------------------------------------39503951Let's skip over the obvious details; the only really interesting part3952here is the call to `get_sha1()`. It tries to interpret `argv[2]` as an3953object name, and if it refers to an object which is present in the current3954repository, it writes the resulting SHA-1 into the variable `sha1`.39553956Two things are interesting here:39573958- `get_sha1()` returns 0 on _success_. This might surprise some new3959 Git hackers, but there is a long tradition in UNIX to return different3960 negative numbers in case of different errors--and 0 on success.39613962- the variable `sha1` in the function signature of `get_sha1()` is `unsigned3963 char \*`, but is actually expected to be a pointer to `unsigned3964 char[20]`. This variable will contain the 160-bit SHA-1 of the given3965 commit. Note that whenever a SHA-1 is passed as `unsigned char \*`, it3966 is the binary representation, as opposed to the ASCII representation in3967 hex characters, which is passed as `char *`.39683969You will see both of these things throughout the code.39703971Now, for the meat:39723973-----------------------------------------------------------------------------3974 case 0:3975 buf = read_object_with_reference(sha1, argv[1], &size, NULL);3976-----------------------------------------------------------------------------39773978This is how you read a blob (actually, not only a blob, but any type of3979object). To know how the function `read_object_with_reference()` actually3980works, find the source code for it (something like `git grep3981read_object_with | grep ":[a-z]"` in the git repository), and read3982the source.39833984To find out how the result can be used, just read on in `cmd_cat_file()`:39853986-----------------------------------3987 write_or_die(1, buf, size);3988-----------------------------------39893990Sometimes, you do not know where to look for a feature. In many such cases,3991it helps to search through the output of `git log`, and then `git show` the3992corresponding commit.39933994Example: If you know that there was some test case for `git bundle`, but3995do not remember where it was (yes, you _could_ `git grep bundle t/`, but that3996does not illustrate the point!):39973998------------------------3999$ git log --no-merges t/4000------------------------40014002In the pager (`less`), just search for "bundle", go a few lines back,4003and see that it is in commit 18449ab0... Now just copy this object name,4004and paste it into the command line40054006-------------------4007$ git show 18449ab04008-------------------40094010Voila.40114012Another example: Find out what to do in order to make some script a4013builtin:40144015-------------------------------------------------4016$ git log --no-merges --diff-filter=A builtin-*.c4017-------------------------------------------------40184019You see, Git is actually the best tool to find out about the source of Git4020itself!40214022[[glossary]]4023include::glossary.txt[]40244025[[git-quick-start]]4026Appendix A: Git Quick Reference4027===============================40284029This is a quick summary of the major commands; the previous chapters4030explain how these work in more detail.40314032[[quick-creating-a-new-repository]]4033Creating a new repository4034-------------------------40354036From a tarball:40374038-----------------------------------------------4039$ tar xzf project.tar.gz4040$ cd project4041$ git init4042Initialized empty Git repository in .git/4043$ git add .4044$ git commit4045-----------------------------------------------40464047From a remote repository:40484049-----------------------------------------------4050$ git clone git://example.com/pub/project.git4051$ cd project4052-----------------------------------------------40534054[[managing-branches]]4055Managing branches4056-----------------40574058-----------------------------------------------4059$ git branch # list all local branches in this repo4060$ git checkout test # switch working directory to branch "test"4061$ git branch new # create branch "new" starting at current HEAD4062$ git branch -d new # delete branch "new"4063-----------------------------------------------40644065Instead of basing a new branch on current HEAD (the default), use:40664067-----------------------------------------------4068$ git branch new test # branch named "test"4069$ git branch new v2.6.15 # tag named v2.6.154070$ git branch new HEAD^ # commit before the most recent4071$ git branch new HEAD^^ # commit before that4072$ git branch new test~10 # ten commits before tip of branch "test"4073-----------------------------------------------40744075Create and switch to a new branch at the same time:40764077-----------------------------------------------4078$ git checkout -b new v2.6.154079-----------------------------------------------40804081Update and examine branches from the repository you cloned from:40824083-----------------------------------------------4084$ git fetch # update4085$ git branch -r # list4086 origin/master4087 origin/next4088 ...4089$ git checkout -b masterwork origin/master4090-----------------------------------------------40914092Fetch a branch from a different repository, and give it a new4093name in your repository:40944095-----------------------------------------------4096$ git fetch git://example.com/project.git theirbranch:mybranch4097$ git fetch git://example.com/project.git v2.6.15:mybranch4098-----------------------------------------------40994100Keep a list of repositories you work with regularly:41014102-----------------------------------------------4103$ git remote add example git://example.com/project.git4104$ git remote # list remote repositories4105example4106origin4107$ git remote show example # get details4108* remote example4109 URL: git://example.com/project.git4110 Tracked remote branches4111 master next ...4112$ git fetch example # update branches from example4113$ git branch -r # list all remote branches4114-----------------------------------------------411541164117[[exploring-history]]4118Exploring history4119-----------------41204121-----------------------------------------------4122$ gitk # visualize and browse history4123$ git log # list all commits4124$ git log src/ # ...modifying src/4125$ git log v2.6.15..v2.6.16 # ...in v2.6.16, not in v2.6.154126$ git log master..test # ...in branch test, not in branch master4127$ git log test..master # ...in branch master, but not in test4128$ git log test...master # ...in one branch, not in both4129$ git log -S'foo()' # ...where difference contain "foo()"4130$ git log --since="2 weeks ago"4131$ git log -p # show patches as well4132$ git show # most recent commit4133$ git diff v2.6.15..v2.6.16 # diff between two tagged versions4134$ git diff v2.6.15..HEAD # diff with current head4135$ git grep "foo()" # search working directory for "foo()"4136$ git grep v2.6.15 "foo()" # search old tree for "foo()"4137$ git show v2.6.15:a.txt # look at old version of a.txt4138-----------------------------------------------41394140Search for regressions:41414142-----------------------------------------------4143$ git bisect start4144$ git bisect bad # current version is bad4145$ git bisect good v2.6.13-rc2 # last known good revision4146Bisecting: 675 revisions left to test after this4147 # test here, then:4148$ git bisect good # if this revision is good, or4149$ git bisect bad # if this revision is bad.4150 # repeat until done.4151-----------------------------------------------41524153[[making-changes]]4154Making changes4155--------------41564157Make sure git knows who to blame:41584159------------------------------------------------4160$ cat >>~/.gitconfig <<\EOF4161[user]4162 name = Your Name Comes Here4163 email = you@yourdomain.example.com4164EOF4165------------------------------------------------41664167Select file contents to include in the next commit, then make the4168commit:41694170-----------------------------------------------4171$ git add a.txt # updated file4172$ git add b.txt # new file4173$ git rm c.txt # old file4174$ git commit4175-----------------------------------------------41764177Or, prepare and create the commit in one step:41784179-----------------------------------------------4180$ git commit d.txt # use latest content only of d.txt4181$ git commit -a # use latest content of all tracked files4182-----------------------------------------------41834184[[merging]]4185Merging4186-------41874188-----------------------------------------------4189$ git merge test # merge branch "test" into the current branch4190$ git pull git://example.com/project.git master4191 # fetch and merge in remote branch4192$ git pull . test # equivalent to git merge test4193-----------------------------------------------41944195[[sharing-your-changes]]4196Sharing your changes4197--------------------41984199Importing or exporting patches:42004201-----------------------------------------------4202$ git format-patch origin..HEAD # format a patch for each commit4203 # in HEAD but not in origin4204$ git am mbox # import patches from the mailbox "mbox"4205-----------------------------------------------42064207Fetch a branch in a different git repository, then merge into the4208current branch:42094210-----------------------------------------------4211$ git pull git://example.com/project.git theirbranch4212-----------------------------------------------42134214Store the fetched branch into a local branch before merging into the4215current branch:42164217-----------------------------------------------4218$ git pull git://example.com/project.git theirbranch:mybranch4219-----------------------------------------------42204221After creating commits on a local branch, update the remote4222branch with your commits:42234224-----------------------------------------------4225$ git push ssh://example.com/project.git mybranch:theirbranch4226-----------------------------------------------42274228When remote and local branch are both named "test":42294230-----------------------------------------------4231$ git push ssh://example.com/project.git test4232-----------------------------------------------42334234Shortcut version for a frequently used remote repository:42354236-----------------------------------------------4237$ git remote add example ssh://example.com/project.git4238$ git push example test4239-----------------------------------------------42404241[[repository-maintenance]]4242Repository maintenance4243----------------------42444245Check for corruption:42464247-----------------------------------------------4248$ git fsck4249-----------------------------------------------42504251Recompress, remove unused cruft:42524253-----------------------------------------------4254$ git gc4255-----------------------------------------------425642574258[[todo]]4259Appendix B: Notes and todo list for this manual4260===============================================42614262This is a work in progress.42634264The basic requirements:42654266- It must be readable in order, from beginning to end, by someone4267 intelligent with a basic grasp of the UNIX command line, but without4268 any special knowledge of git. If necessary, any other prerequisites4269 should be specifically mentioned as they arise.4270- Whenever possible, section headings should clearly describe the task4271 they explain how to do, in language that requires no more knowledge4272 than necessary: for example, "importing patches into a project" rather4273 than "the git-am command"42744275Think about how to create a clear chapter dependency graph that will4276allow people to get to important topics without necessarily reading4277everything in between.42784279Scan Documentation/ for other stuff left out; in particular:42804281- howto's4282- some of technical/?4283- hooks4284- list of commands in gitlink:git[1]42854286Scan email archives for other stuff left out42874288Scan man pages to see if any assume more background than this manual4289provides.42904291Simplify beginning by suggesting disconnected head instead of4292temporary branch creation?42934294Add more good examples. Entire sections of just cookbook examples4295might be a good idea; maybe make an "advanced examples" section a4296standard end-of-chapter section?42974298Include cross-references to the glossary, where appropriate.42994300Document shallow clones? See draft 1.5.0 release notes for some4301documentation.43024303Add a section on working with other version control systems, including4304CVS, Subversion, and just imports of series of release tarballs.43054306More details on gitweb?43074308Write a chapter on using plumbing and writing scripts.43094310Alternates, clone -reference, etc.43114312git unpack-objects -r for recovery