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 <repo>", 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 linkgit: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 ("git" 60or "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, 62called the <<def_working_tree,working tree>>, together with a special 63top-level directory named ".git", which contains all the information 64about the history of the project. 65 66[[how-to-check-out]] 67How to check out a different version of a project 68------------------------------------------------- 69 70Git is best thought of as a tool for storing the history of a collection 71of files. It stores the history as a compressed collection of 72interrelated snapshots of the project's contents. In git each such 73version is called a <<def_commit,commit>>. 74 75Those snapshots aren't necessarily all arranged in a single line from 76oldest to newest; instead, work may simultaneously proceed along 77parallel lines of development, called <<def_branch,branches>>, which may 78merge and diverge. 79 80A single git repository can track development on multiple branches. It 81does this by keeping a list of <<def_head,heads>> which reference the 82latest commit on each branch; the linkgit:git-branch[1] command shows 83you the list of branch heads: 84 85------------------------------------------------ 86$ git branch 87* master 88------------------------------------------------ 89 90A freshly cloned repository contains a single branch head, by default 91named "master", with the working directory initialized to the state of 92the project referred to by that branch head. 93 94Most projects also use <<def_tag,tags>>. Tags, like heads, are 95references into the project's history, and can be listed using the 96linkgit:git-tag[1] command: 97 98------------------------------------------------ 99$ git tag -l 100v2.6.11 101v2.6.11-tree 102v2.6.12 103v2.6.12-rc2 104v2.6.12-rc3 105v2.6.12-rc4 106v2.6.12-rc5 107v2.6.12-rc6 108v2.6.13 109... 110------------------------------------------------ 111 112Tags are expected to always point at the same version of a project, 113while heads are expected to advance as development progresses. 114 115Create a new branch head pointing to one of these versions and check it 116out using linkgit:git-checkout[1]: 117 118------------------------------------------------ 119$ git checkout -b new v2.6.13 120------------------------------------------------ 121 122The working directory then reflects the contents that the project had 123when it was tagged v2.6.13, and linkgit:git-branch[1] shows two 124branches, with an asterisk marking the currently checked-out branch: 125 126------------------------------------------------ 127$ git branch 128 master 129* new 130------------------------------------------------ 131 132If you decide that you'd rather see version 2.6.17, you can modify 133the current branch to point at v2.6.17 instead, with 134 135------------------------------------------------ 136$ git reset --hard v2.6.17 137------------------------------------------------ 138 139Note that if the current branch head was your only reference to a 140particular point in history, then resetting that branch may leave you 141with no way to find the history it used to point to; so use this command 142carefully. 143 144[[understanding-commits]] 145Understanding History: Commits 146------------------------------ 147 148Every change in the history of a project is represented by a commit. 149The linkgit:git-show[1] command shows the most recent commit on the 150current branch: 151 152------------------------------------------------ 153$ git show 154commit 17cf781661e6d38f737f15f53ab552f1e95960d7 155Author: Linus Torvalds <torvalds@ppc970.osdl.org.(none)> 156Date: Tue Apr 19 14:11:06 2005 -0700 157 158 Remove duplicate getenv(DB_ENVIRONMENT) call 159 160 Noted by Tony Luck. 161 162diff --git a/init-db.c b/init-db.c 163index 65898fa..b002dc6 100644 164--- a/init-db.c 165+++ b/init-db.c 166@@ -7,7 +7,7 @@ 167 168 int main(int argc, char **argv) 169 { 170- char *sha1_dir = getenv(DB_ENVIRONMENT), *path; 171+ char *sha1_dir, *path; 172 int len, i; 173 174 if (mkdir(".git", 0755) < 0) { 175------------------------------------------------ 176 177As you can see, a commit shows who made the latest change, what they 178did, and why. 179 180Every commit has a 40-hexdigit id, sometimes called the "object name" or the 181"SHA1 id", shown on the first line of the "git-show" output. You can usually 182refer to a commit by a shorter name, such as a tag or a branch name, but this 183longer name can also be useful. Most importantly, it is a globally unique 184name for this commit: so if you tell somebody else the object name (for 185example in email), then you are guaranteed that name will refer to the same 186commit in their repository that it does in yours (assuming their repository 187has that commit at all). Since the object name is computed as a hash over the 188contents of the commit, you are guaranteed that the commit can never change 189without its name also changing. 190 191In fact, in <<git-concepts>> we shall see that everything stored in git 192history, including file data and directory contents, is stored in an object 193with a name that is a hash of its contents. 194 195[[understanding-reachability]] 196Understanding history: commits, parents, and reachability 197~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 198 199Every commit (except the very first commit in a project) also has a 200parent commit which shows what happened before this commit. 201Following the chain of parents will eventually take you back to the 202beginning of the project. 203 204However, the commits do not form a simple list; git allows lines of 205development to diverge and then reconverge, and the point where two 206lines of development reconverge is called a "merge". The commit 207representing a merge can therefore have more than one parent, with 208each parent representing the most recent commit on one of the lines 209of development leading to that point. 210 211The best way to see how this works is using the linkgit:gitk[1] 212command; running gitk now on a git repository and looking for merge 213commits will help understand how the git organizes history. 214 215In the following, we say that commit X is "reachable" from commit Y 216if commit X is an ancestor of commit Y. Equivalently, you could say 217that Y is a descendant of X, or that there is a chain of parents 218leading from commit Y to commit X. 219 220[[history-diagrams]] 221Understanding history: History diagrams 222~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 223 224We will sometimes represent git history using diagrams like the one 225below. Commits are shown as "o", and the links between them with 226lines drawn with - / and \. Time goes left to right: 227 228 229................................................ 230 o--o--o <-- Branch A 231 / 232 o--o--o <-- master 233 \ 234 o--o--o <-- Branch B 235................................................ 236 237If we need to talk about a particular commit, the character "o" may 238be replaced with another letter or number. 239 240[[what-is-a-branch]] 241Understanding history: What is a branch? 242~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 243 244When we need to be precise, we will use the word "branch" to mean a line 245of development, and "branch head" (or just "head") to mean a reference 246to the most recent commit on a branch. In the example above, the branch 247head named "A" is a pointer to one particular commit, but we refer to 248the line of three commits leading up to that point as all being part of 249"branch A". 250 251However, when no confusion will result, we often just use the term 252"branch" both for branches and for branch heads. 253 254[[manipulating-branches]] 255Manipulating branches 256--------------------- 257 258Creating, deleting, and modifying branches is quick and easy; here's 259a summary of the commands: 260 261git branch:: 262 list all branches 263git branch <branch>:: 264 create a new branch named <branch>, referencing the same 265 point in history as the current branch 266git branch <branch> <start-point>:: 267 create a new branch named <branch>, referencing 268 <start-point>, which may be specified any way you like, 269 including using a branch name or a tag name 270git branch -d <branch>:: 271 delete the branch <branch>; if the branch you are deleting 272 points to a commit which is not reachable from the current 273 branch, this command will fail with a warning. 274git branch -D <branch>:: 275 even if the branch points to a commit not reachable 276 from the current branch, you may know that that commit 277 is still reachable from some other branch or tag. In that 278 case it is safe to use this command to force git to delete 279 the branch. 280git checkout <branch>:: 281 make the current branch <branch>, updating the working 282 directory to reflect the version referenced by <branch> 283git checkout -b <new> <start-point>:: 284 create a new branch <new> referencing <start-point>, and 285 check it out. 286 287The special symbol "HEAD" can always be used to refer to the current 288branch. In fact, git uses a file named "HEAD" in the .git directory to 289remember which branch is current: 290 291------------------------------------------------ 292$ cat .git/HEAD 293ref: refs/heads/master 294------------------------------------------------ 295 296[[detached-head]] 297Examining an old version without creating a new branch 298------------------------------------------------------ 299 300The git-checkout command normally expects a branch head, but will also 301accept an arbitrary commit; for example, you can check out the commit 302referenced by a tag: 303 304------------------------------------------------ 305$ git checkout v2.6.17 306Note: moving to "v2.6.17" which isn't a local branch 307If you want to create a new branch from this checkout, you may do so 308(now or later) by using -b with the checkout command again. Example: 309 git checkout -b <new_branch_name> 310HEAD is now at 427abfa... Linux v2.6.17 311------------------------------------------------ 312 313The HEAD then refers to the SHA1 of the commit instead of to a branch, 314and git branch shows that you are no longer on a branch: 315 316------------------------------------------------ 317$ cat .git/HEAD 318427abfa28afedffadfca9dd8b067eb6d36bac53f 319$ git branch 320* (no branch) 321 master 322------------------------------------------------ 323 324In this case we say that the HEAD is "detached". 325 326This is an easy way to check out a particular version without having to 327make up a name for the new branch. You can still create a new branch 328(or tag) for this version later if you decide to. 329 330[[examining-remote-branches]] 331Examining branches from a remote repository 332------------------------------------------- 333 334The "master" branch that was created at the time you cloned is a copy 335of the HEAD in the repository that you cloned from. That repository 336may also have had other branches, though, and your local repository 337keeps branches which track each of those remote branches, which you 338can view using the "-r" option to linkgit:git-branch[1]: 339 340------------------------------------------------ 341$ git branch -r 342 origin/HEAD 343 origin/html 344 origin/maint 345 origin/man 346 origin/master 347 origin/next 348 origin/pu 349 origin/todo 350------------------------------------------------ 351 352You cannot check out these remote-tracking branches, but you can 353examine them on a branch of your own, just as you would a tag: 354 355------------------------------------------------ 356$ git checkout -b my-todo-copy origin/todo 357------------------------------------------------ 358 359Note that the name "origin" is just the name that git uses by default 360to refer to the repository that you cloned from. 361 362[[how-git-stores-references]] 363Naming branches, tags, and other references 364------------------------------------------- 365 366Branches, remote-tracking branches, and tags are all references to 367commits. All references are named with a slash-separated path name 368starting with "refs"; the names we've been using so far are actually 369shorthand: 370 371 - The branch "test" is short for "refs/heads/test". 372 - The tag "v2.6.18" is short for "refs/tags/v2.6.18". 373 - "origin/master" is short for "refs/remotes/origin/master". 374 375The full name is occasionally useful if, for example, there ever 376exists a tag and a branch with the same name. 377 378(Newly created refs are actually stored in the .git/refs directory, 379under the path given by their name. However, for efficiency reasons 380they may also be packed together in a single file; see 381linkgit:git-pack-refs[1]). 382 383As another useful shortcut, the "HEAD" of a repository can be referred 384to just using the name of that repository. So, for example, "origin" 385is usually a shortcut for the HEAD branch in the repository "origin". 386 387For the complete list of paths which git checks for references, and 388the order it uses to decide which to choose when there are multiple 389references with the same shorthand name, see the "SPECIFYING 390REVISIONS" section of linkgit:git-rev-parse[1]. 391 392[[Updating-a-repository-With-git-fetch]] 393Updating a repository with git-fetch 394------------------------------------ 395 396Eventually the developer cloned from will do additional work in her 397repository, creating new commits and advancing the branches to point 398at the new commits. 399 400The command "git fetch", with no arguments, will update all of the 401remote-tracking branches to the latest version found in her 402repository. It will not touch any of your own branches--not even the 403"master" branch that was created for you on clone. 404 405[[fetching-branches]] 406Fetching branches from other repositories 407----------------------------------------- 408 409You can also track branches from repositories other than the one you 410cloned from, using linkgit:git-remote[1]: 411 412------------------------------------------------- 413$ git remote add linux-nfs git://linux-nfs.org/pub/nfs-2.6.git 414$ git fetch linux-nfs 415* refs/remotes/linux-nfs/master: storing branch 'master' ... 416 commit: bf81b46 417------------------------------------------------- 418 419New remote-tracking branches will be stored under the shorthand name 420that you gave "git-remote add", in this case linux-nfs: 421 422------------------------------------------------- 423$ git branch -r 424linux-nfs/master 425origin/master 426------------------------------------------------- 427 428If you run "git fetch <remote>" later, the tracking branches for the 429named <remote> will be updated. 430 431If you examine the file .git/config, you will see that git has added 432a new stanza: 433 434------------------------------------------------- 435$ cat .git/config 436... 437[remote "linux-nfs"] 438 url = git://linux-nfs.org/pub/nfs-2.6.git 439 fetch = +refs/heads/*:refs/remotes/linux-nfs/* 440... 441------------------------------------------------- 442 443This is what causes git to track the remote's branches; you may modify 444or delete these configuration options by editing .git/config with a 445text editor. (See the "CONFIGURATION FILE" section of 446linkgit:git-config[1] for details.) 447 448[[exploring-git-history]] 449Exploring git history 450===================== 451 452Git is best thought of as a tool for storing the history of a 453collection of files. It does this by storing compressed snapshots of 454the contents of a file hierarchy, together with "commits" which show 455the relationships between these snapshots. 456 457Git provides extremely flexible and fast tools for exploring the 458history of a project. 459 460We start with one specialized tool that is useful for finding the 461commit that introduced a bug into a project. 462 463[[using-bisect]] 464How to use bisect to find a regression 465-------------------------------------- 466 467Suppose version 2.6.18 of your project worked, but the version at 468"master" crashes. Sometimes the best way to find the cause of such a 469regression is to perform a brute-force search through the project's 470history to find the particular commit that caused the problem. The 471linkgit:git-bisect[1] command can help you do this: 472 473------------------------------------------------- 474$ git bisect start 475$ git bisect good v2.6.18 476$ git bisect bad master 477Bisecting: 3537 revisions left to test after this 478[65934a9a028b88e83e2b0f8b36618fe503349f8e] BLOCK: Make USB storage depend on SCSI rather than selecting it [try #6] 479------------------------------------------------- 480 481If you run "git branch" at this point, you'll see that git has 482temporarily moved you in "(no branch)". HEAD is now detached from any 483branch and points directly to a commit (with commit id 65934...) that 484is reachable from "master" but not from v2.6.18. Compile and test it, 485and see whether it crashes. Assume it does crash. Then: 486 487------------------------------------------------- 488$ git bisect bad 489Bisecting: 1769 revisions left to test after this 490[7eff82c8b1511017ae605f0c99ac275a7e21b867] i2c-core: Drop useless bitmaskings 491------------------------------------------------- 492 493checks out an older version. Continue like this, telling git at each 494stage whether the version it gives you is good or bad, and notice 495that the number of revisions left to test is cut approximately in 496half each time. 497 498After about 13 tests (in this case), it will output the commit id of 499the guilty commit. You can then examine the commit with 500linkgit:git-show[1], find out who wrote it, and mail them your bug 501report with the commit id. Finally, run 502 503------------------------------------------------- 504$ git bisect reset 505------------------------------------------------- 506 507to return you to the branch you were on before. 508 509Note that the version which git-bisect checks out for you at each 510point is just a suggestion, and you're free to try a different 511version if you think it would be a good idea. For example, 512occasionally you may land on a commit that broke something unrelated; 513run 514 515------------------------------------------------- 516$ git bisect visualize 517------------------------------------------------- 518 519which will run gitk and label the commit it chose with a marker that 520says "bisect". Choose a safe-looking commit nearby, note its commit 521id, and check it out with: 522 523------------------------------------------------- 524$ git reset --hard fb47ddb2db... 525------------------------------------------------- 526 527then test, run "bisect good" or "bisect bad" as appropriate, and 528continue. 529 530Instead of "git bisect visualize" and then "git reset --hard 531fb47ddb2db...", you might just want to tell git that you want to skip 532the current commit: 533 534------------------------------------------------- 535$ git bisect skip 536------------------------------------------------- 537 538In this case, though, git may not eventually be able to tell the first 539bad one between some first skipped commits and a later bad commit. 540 541There are also ways to automate the bisecting process if you have a 542test script that can tell a good from a bad commit. See 543linkgit:git-bisect[1] for more information about this and other "git 544bisect" features. 545 546[[naming-commits]] 547Naming commits 548-------------- 549 550We have seen several ways of naming commits already: 551 552 - 40-hexdigit object name 553 - branch name: refers to the commit at the head of the given 554 branch 555 - tag name: refers to the commit pointed to by the given tag 556 (we've seen branches and tags are special cases of 557 <<how-git-stores-references,references>>). 558 - HEAD: refers to the head of the current branch 559 560There are many more; see the "SPECIFYING REVISIONS" section of the 561linkgit:git-rev-parse[1] man page for the complete list of ways to 562name revisions. Some examples: 563 564------------------------------------------------- 565$ git show fb47ddb2 # the first few characters of the object name 566 # are usually enough to specify it uniquely 567$ git show HEAD^ # the parent of the HEAD commit 568$ git show HEAD^^ # the grandparent 569$ git show HEAD~4 # the great-great-grandparent 570------------------------------------------------- 571 572Recall that merge commits may have more than one parent; by default, 573^ and ~ follow the first parent listed in the commit, but you can 574also choose: 575 576------------------------------------------------- 577$ git show HEAD^1 # show the first parent of HEAD 578$ git show HEAD^2 # show the second parent of HEAD 579------------------------------------------------- 580 581In addition to HEAD, there are several other special names for 582commits: 583 584Merges (to be discussed later), as well as operations such as 585git-reset, which change the currently checked-out commit, generally 586set ORIG_HEAD to the value HEAD had before the current operation. 587 588The git-fetch operation always stores the head of the last fetched 589branch in FETCH_HEAD. For example, if you run git fetch without 590specifying a local branch as the target of the operation 591 592------------------------------------------------- 593$ git fetch git://example.com/proj.git theirbranch 594------------------------------------------------- 595 596the fetched commits will still be available from FETCH_HEAD. 597 598When we discuss merges we'll also see the special name MERGE_HEAD, 599which refers to the other branch that we're merging in to the current 600branch. 601 602The linkgit:git-rev-parse[1] command is a low-level command that is 603occasionally useful for translating some name for a commit to the object 604name for that commit: 605 606------------------------------------------------- 607$ git rev-parse origin 608e05db0fd4f31dde7005f075a84f96b360d05984b 609------------------------------------------------- 610 611[[creating-tags]] 612Creating tags 613------------- 614 615We can also create a tag to refer to a particular commit; after 616running 617 618------------------------------------------------- 619$ git tag stable-1 1b2e1d63ff 620------------------------------------------------- 621 622You can use stable-1 to refer to the commit 1b2e1d63ff. 623 624This creates a "lightweight" tag. If you would also like to include a 625comment with the tag, and possibly sign it cryptographically, then you 626should create a tag object instead; see the linkgit:git-tag[1] man page 627for details. 628 629[[browsing-revisions]] 630Browsing revisions 631------------------ 632 633The linkgit:git-log[1] command can show lists of commits. On its 634own, it shows all commits reachable from the parent commit; but you 635can also make more specific requests: 636 637------------------------------------------------- 638$ git log v2.5.. # commits since (not reachable from) v2.5 639$ git log test..master # commits reachable from master but not test 640$ git log master..test # ...reachable from test but not master 641$ git log master...test # ...reachable from either test or master, 642 # but not both 643$ git log --since="2 weeks ago" # commits from the last 2 weeks 644$ git log Makefile # commits which modify Makefile 645$ git log fs/ # ... which modify any file under fs/ 646$ git log -S'foo()' # commits which add or remove any file data 647 # matching the string 'foo()' 648------------------------------------------------- 649 650And of course you can combine all of these; the following finds 651commits since v2.5 which touch the Makefile or any file under fs: 652 653------------------------------------------------- 654$ git log v2.5.. Makefile fs/ 655------------------------------------------------- 656 657You can also ask git log to show patches: 658 659------------------------------------------------- 660$ git log -p 661------------------------------------------------- 662 663See the "--pretty" option in the linkgit:git-log[1] man page for more 664display options. 665 666Note that git log starts with the most recent commit and works 667backwards through the parents; however, since git history can contain 668multiple independent lines of development, the particular order that 669commits are listed in may be somewhat arbitrary. 670 671[[generating-diffs]] 672Generating diffs 673---------------- 674 675You can generate diffs between any two versions using 676linkgit:git-diff[1]: 677 678------------------------------------------------- 679$ git diff master..test 680------------------------------------------------- 681 682That will produce the diff between the tips of the two branches. If 683you'd prefer to find the diff from their common ancestor to test, you 684can use three dots instead of two: 685 686------------------------------------------------- 687$ git diff master...test 688------------------------------------------------- 689 690Sometimes what you want instead is a set of patches; for this you can 691use linkgit:git-format-patch[1]: 692 693------------------------------------------------- 694$ git format-patch master..test 695------------------------------------------------- 696 697will generate a file with a patch for each commit reachable from test 698but not from master. 699 700[[viewing-old-file-versions]] 701Viewing old file versions 702------------------------- 703 704You can always view an old version of a file by just checking out the 705correct revision first. But sometimes it is more convenient to be 706able to view an old version of a single file without checking 707anything out; this command does that: 708 709------------------------------------------------- 710$ git show v2.5:fs/locks.c 711------------------------------------------------- 712 713Before the colon may be anything that names a commit, and after it 714may be any path to a file tracked by git. 715 716[[history-examples]] 717Examples 718-------- 719 720[[counting-commits-on-a-branch]] 721Counting the number of commits on a branch 722~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 723 724Suppose you want to know how many commits you've made on "mybranch" 725since it diverged from "origin": 726 727------------------------------------------------- 728$ git log --pretty=oneline origin..mybranch | wc -l 729------------------------------------------------- 730 731Alternatively, you may often see this sort of thing done with the 732lower-level command linkgit:git-rev-list[1], which just lists the SHA1's 733of all the given commits: 734 735------------------------------------------------- 736$ git rev-list origin..mybranch | wc -l 737------------------------------------------------- 738 739[[checking-for-equal-branches]] 740Check whether two branches point at the same history 741~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 742 743Suppose you want to check whether two branches point at the same point 744in history. 745 746------------------------------------------------- 747$ git diff origin..master 748------------------------------------------------- 749 750will tell you whether the contents of the project are the same at the 751two branches; in theory, however, it's possible that the same project 752contents could have been arrived at by two different historical 753routes. You could compare the object names: 754 755------------------------------------------------- 756$ git rev-list origin 757e05db0fd4f31dde7005f075a84f96b360d05984b 758$ git rev-list master 759e05db0fd4f31dde7005f075a84f96b360d05984b 760------------------------------------------------- 761 762Or you could recall that the ... operator selects all commits 763contained reachable from either one reference or the other but not 764both: so 765 766------------------------------------------------- 767$ git log origin...master 768------------------------------------------------- 769 770will return no commits when the two branches are equal. 771 772[[finding-tagged-descendants]] 773Find first tagged version including a given fix 774~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 775 776Suppose you know that the commit e05db0fd fixed a certain problem. 777You'd like to find the earliest tagged release that contains that 778fix. 779 780Of course, there may be more than one answer--if the history branched 781after commit e05db0fd, then there could be multiple "earliest" tagged 782releases. 783 784You could just visually inspect the commits since e05db0fd: 785 786------------------------------------------------- 787$ gitk e05db0fd.. 788------------------------------------------------- 789 790Or you can use linkgit:git-name-rev[1], which will give the commit a 791name based on any tag it finds pointing to one of the commit's 792descendants: 793 794------------------------------------------------- 795$ git name-rev --tags e05db0fd 796e05db0fd tags/v1.5.0-rc1^0~23 797------------------------------------------------- 798 799The linkgit:git-describe[1] command does the opposite, naming the 800revision using a tag on which the given commit is based: 801 802------------------------------------------------- 803$ git describe e05db0fd 804v1.5.0-rc0-260-ge05db0f 805------------------------------------------------- 806 807but that may sometimes help you guess which tags might come after the 808given commit. 809 810If you just want to verify whether a given tagged version contains a 811given commit, you could use linkgit:git-merge-base[1]: 812 813------------------------------------------------- 814$ git merge-base e05db0fd v1.5.0-rc1 815e05db0fd4f31dde7005f075a84f96b360d05984b 816------------------------------------------------- 817 818The merge-base command finds a common ancestor of the given commits, 819and always returns one or the other in the case where one is a 820descendant of the other; so the above output shows that e05db0fd 821actually is an ancestor of v1.5.0-rc1. 822 823Alternatively, note that 824 825------------------------------------------------- 826$ git log v1.5.0-rc1..e05db0fd 827------------------------------------------------- 828 829will produce empty output if and only if v1.5.0-rc1 includes e05db0fd, 830because it outputs only commits that are not reachable from v1.5.0-rc1. 831 832As yet another alternative, the linkgit:git-show-branch[1] command lists 833the commits reachable from its arguments with a display on the left-hand 834side that indicates which arguments that commit is reachable from. So, 835you can run something like 836 837------------------------------------------------- 838$ git show-branch e05db0fd v1.5.0-rc0 v1.5.0-rc1 v1.5.0-rc2 839! [e05db0fd] Fix warnings in sha1_file.c - use C99 printf format if 840available 841 ! [v1.5.0-rc0] GIT v1.5.0 preview 842 ! [v1.5.0-rc1] GIT v1.5.0-rc1 843 ! [v1.5.0-rc2] GIT v1.5.0-rc2 844... 845------------------------------------------------- 846 847then search for a line that looks like 848 849------------------------------------------------- 850+ ++ [e05db0fd] Fix warnings in sha1_file.c - use C99 printf format if 851available 852------------------------------------------------- 853 854Which shows that e05db0fd is reachable from itself, from v1.5.0-rc1, and 855from v1.5.0-rc2, but not from v1.5.0-rc0. 856 857[[showing-commits-unique-to-a-branch]] 858Showing commits unique to a given branch 859~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 860 861Suppose you would like to see all the commits reachable from the branch 862head named "master" but not from any other head in your repository. 863 864We can list all the heads in this repository with 865linkgit:git-show-ref[1]: 866 867------------------------------------------------- 868$ git show-ref --heads 869bf62196b5e363d73353a9dcf094c59595f3153b7 refs/heads/core-tutorial 870db768d5504c1bb46f63ee9d6e1772bd047e05bf9 refs/heads/maint 871a07157ac624b2524a059a3414e99f6f44bebc1e7 refs/heads/master 87224dbc180ea14dc1aebe09f14c8ecf32010690627 refs/heads/tutorial-2 8731e87486ae06626c2f31eaa63d26fc0fd646c8af2 refs/heads/tutorial-fixes 874------------------------------------------------- 875 876We can get just the branch-head names, and remove "master", with 877the help of the standard utilities cut and grep: 878 879------------------------------------------------- 880$ git show-ref --heads | cut -d' ' -f2 | grep -v '^refs/heads/master' 881refs/heads/core-tutorial 882refs/heads/maint 883refs/heads/tutorial-2 884refs/heads/tutorial-fixes 885------------------------------------------------- 886 887And then we can ask to see all the commits reachable from master 888but not from these other heads: 889 890------------------------------------------------- 891$ gitk master --not $( git show-ref --heads | cut -d' ' -f2 | 892 grep -v '^refs/heads/master' ) 893------------------------------------------------- 894 895Obviously, endless variations are possible; for example, to see all 896commits reachable from some head but not from any tag in the repository: 897 898------------------------------------------------- 899$ gitk $( git show-ref --heads ) --not $( git show-ref --tags ) 900------------------------------------------------- 901 902(See linkgit:git-rev-parse[1] for explanations of commit-selecting 903syntax such as `--not`.) 904 905[[making-a-release]] 906Creating a changelog and tarball for a software release 907~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 908 909The linkgit:git-archive[1] command can create a tar or zip archive from 910any version of a project; for example: 911 912------------------------------------------------- 913$ git archive --format=tar --prefix=project/ HEAD | gzip >latest.tar.gz 914------------------------------------------------- 915 916will use HEAD to produce a tar archive in which each filename is 917preceded by "project/". 918 919If you're releasing a new version of a software project, you may want 920to simultaneously make a changelog to include in the release 921announcement. 922 923Linus Torvalds, for example, makes new kernel releases by tagging them, 924then running: 925 926------------------------------------------------- 927$ release-script 2.6.12 2.6.13-rc6 2.6.13-rc7 928------------------------------------------------- 929 930where release-script is a shell script that looks like: 931 932------------------------------------------------- 933#!/bin/sh 934stable="$1" 935last="$2" 936new="$3" 937echo "# git tag v$new" 938echo "git archive --prefix=linux-$new/ v$new | gzip -9 > ../linux-$new.tar.gz" 939echo "git diff v$stable v$new | gzip -9 > ../patch-$new.gz" 940echo "git log --no-merges v$new ^v$last > ../ChangeLog-$new" 941echo "git shortlog --no-merges v$new ^v$last > ../ShortLog" 942echo "git diff --stat --summary -M v$last v$new > ../diffstat-$new" 943------------------------------------------------- 944 945and then he just cut-and-pastes the output commands after verifying that 946they look OK. 947 948[[Finding-comments-With-given-Content]] 949Finding commits referencing a file with given content 950~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 951 952Somebody hands you a copy of a file, and asks which commits modified a 953file such that it contained the given content either before or after the 954commit. You can find out with this: 955 956------------------------------------------------- 957$ git log --raw --abbrev=40 --pretty=oneline | 958 grep -B 1 `git hash-object filename` 959------------------------------------------------- 960 961Figuring out why this works is left as an exercise to the (advanced) 962student. The linkgit:git-log[1], linkgit:git-diff-tree[1], and 963linkgit:git-hash-object[1] man pages may prove helpful. 964 965[[Developing-With-git]] 966Developing with git 967=================== 968 969[[telling-git-your-name]] 970Telling git your name 971--------------------- 972 973Before creating any commits, you should introduce yourself to git. The 974easiest way to do so is to make sure the following lines appear in a 975file named .gitconfig in your home directory: 976 977------------------------------------------------ 978[user] 979 name = Your Name Comes Here 980 email = you@yourdomain.example.com 981------------------------------------------------ 982 983(See the "CONFIGURATION FILE" section of linkgit:git-config[1] for 984details on the configuration file.) 985 986 987[[creating-a-new-repository]] 988Creating a new repository 989------------------------- 990 991Creating a new repository from scratch is very easy: 992 993------------------------------------------------- 994$ mkdir project 995$ cd project 996$ git init 997------------------------------------------------- 998 999If you have some initial content (say, a tarball):10001001-------------------------------------------------1002$ tar -xzvf project.tar.gz1003$ cd project1004$ git init1005$ git add . # include everything below ./ in the first commit:1006$ git commit1007-------------------------------------------------10081009[[how-to-make-a-commit]]1010How to make a commit1011--------------------10121013Creating a new commit takes three steps:10141015 1. Making some changes to the working directory using your1016 favorite editor.1017 2. Telling git about your changes.1018 3. Creating the commit using the content you told git about1019 in step 2.10201021In practice, you can interleave and repeat steps 1 and 2 as many1022times as you want: in order to keep track of what you want committed1023at step 3, git maintains a snapshot of the tree's contents in a1024special staging area called "the index."10251026At the beginning, the content of the index will be identical to1027that of the HEAD. The command "git diff --cached", which shows1028the difference between the HEAD and the index, should therefore1029produce no output at that point.10301031Modifying the index is easy:10321033To update the index with the new contents of a modified file, use10341035-------------------------------------------------1036$ git add path/to/file1037-------------------------------------------------10381039To add the contents of a new file to the index, use10401041-------------------------------------------------1042$ git add path/to/file1043-------------------------------------------------10441045To remove a file from the index and from the working tree,10461047-------------------------------------------------1048$ git rm path/to/file1049-------------------------------------------------10501051After each step you can verify that10521053-------------------------------------------------1054$ git diff --cached1055-------------------------------------------------10561057always shows the difference between the HEAD and the index file--this1058is what you'd commit if you created the commit now--and that10591060-------------------------------------------------1061$ git diff1062-------------------------------------------------10631064shows the difference between the working tree and the index file.10651066Note that "git-add" always adds just the current contents of a file1067to the index; further changes to the same file will be ignored unless1068you run git-add on the file again.10691070When you're ready, just run10711072-------------------------------------------------1073$ git commit1074-------------------------------------------------10751076and git will prompt you for a commit message and then create the new1077commit. Check to make sure it looks like what you expected with10781079-------------------------------------------------1080$ git show1081-------------------------------------------------10821083As a special shortcut,10841085-------------------------------------------------1086$ git commit -a1087-------------------------------------------------10881089will update the index with any files that you've modified or removed1090and create a commit, all in one step.10911092A number of commands are useful for keeping track of what you're1093about to commit:10941095-------------------------------------------------1096$ git diff --cached # difference between HEAD and the index; what1097 # would be committed if you ran "commit" now.1098$ git diff # difference between the index file and your1099 # working directory; changes that would not1100 # be included if you ran "commit" now.1101$ git diff HEAD # difference between HEAD and working tree; what1102 # would be committed if you ran "commit -a" now.1103$ git status # a brief per-file summary of the above.1104-------------------------------------------------11051106You can also use linkgit:git-gui[1] to create commits, view changes in1107the index and the working tree files, and individually select diff hunks1108for inclusion in the index (by right-clicking on the diff hunk and1109choosing "Stage Hunk For Commit").11101111[[creating-good-commit-messages]]1112Creating good commit messages1113-----------------------------11141115Though not required, it's a good idea to begin the commit message1116with a single short (less than 50 character) line summarizing the1117change, followed by a blank line and then a more thorough1118description. Tools that turn commits into email, for example, use1119the first line on the Subject line and the rest of the commit in the1120body.11211122[[ignoring-files]]1123Ignoring files1124--------------11251126A project will often generate files that you do 'not' want to track with git.1127This typically includes files generated by a build process or temporary1128backup files made by your editor. Of course, 'not' tracking files with git1129is just a matter of 'not' calling "`git-add`" on them. But it quickly becomes1130annoying to have these untracked files lying around; e.g. they make1131"`git add .`" practically useless, and they keep showing up in the output of1132"`git status`".11331134You can tell git to ignore certain files by creating a file called .gitignore1135in the top level of your working directory, with contents such as:11361137-------------------------------------------------1138# Lines starting with '#' are considered comments.1139# Ignore any file named foo.txt.1140foo.txt1141# Ignore (generated) html files,1142*.html1143# except foo.html which is maintained by hand.1144!foo.html1145# Ignore objects and archives.1146*.[oa]1147-------------------------------------------------11481149See linkgit:gitignore[5] for a detailed explanation of the syntax. You can1150also place .gitignore files in other directories in your working tree, and they1151will apply to those directories and their subdirectories. The `.gitignore`1152files can be added to your repository like any other files (just run `git add1153.gitignore` and `git commit`, as usual), which is convenient when the exclude1154patterns (such as patterns matching build output files) would also make sense1155for other users who clone your repository.11561157If you wish the exclude patterns to affect only certain repositories1158(instead of every repository for a given project), you may instead put1159them in a file in your repository named .git/info/exclude, or in any file1160specified by the `core.excludesfile` configuration variable. Some git1161commands can also take exclude patterns directly on the command line.1162See linkgit:gitignore[5] for the details.11631164[[how-to-merge]]1165How to merge1166------------11671168You can rejoin two diverging branches of development using1169linkgit:git-merge[1]:11701171-------------------------------------------------1172$ git merge branchname1173-------------------------------------------------11741175merges the development in the branch "branchname" into the current1176branch. If there are conflicts--for example, if the same file is1177modified in two different ways in the remote branch and the local1178branch--then you are warned; the output may look something like this:11791180-------------------------------------------------1181$ git merge next1182 100% (4/4) done1183Auto-merged file.txt1184CONFLICT (content): Merge conflict in file.txt1185Automatic merge failed; fix conflicts and then commit the result.1186-------------------------------------------------11871188Conflict markers are left in the problematic files, and after1189you resolve the conflicts manually, you can update the index1190with the contents and run git commit, as you normally would when1191creating a new file.11921193If you examine the resulting commit using gitk, you will see that it1194has two parents, one pointing to the top of the current branch, and1195one to the top of the other branch.11961197[[resolving-a-merge]]1198Resolving a merge1199-----------------12001201When a merge isn't resolved automatically, git leaves the index and1202the working tree in a special state that gives you all the1203information you need to help resolve the merge.12041205Files with conflicts are marked specially in the index, so until you1206resolve the problem and update the index, linkgit:git-commit[1] will1207fail:12081209-------------------------------------------------1210$ git commit1211file.txt: needs merge1212-------------------------------------------------12131214Also, linkgit:git-status[1] will list those files as "unmerged", and the1215files with conflicts will have conflict markers added, like this:12161217-------------------------------------------------1218<<<<<<< HEAD:file.txt1219Hello world1220=======1221Goodbye1222>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt1223-------------------------------------------------12241225All you need to do is edit the files to resolve the conflicts, and then12261227-------------------------------------------------1228$ git add file.txt1229$ git commit1230-------------------------------------------------12311232Note that the commit message will already be filled in for you with1233some information about the merge. Normally you can just use this1234default message unchanged, but you may add additional commentary of1235your own if desired.12361237The above is all you need to know to resolve a simple merge. But git1238also provides more information to help resolve conflicts:12391240[[conflict-resolution]]1241Getting conflict-resolution help during a merge1242~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~12431244All of the changes that git was able to merge automatically are1245already added to the index file, so linkgit:git-diff[1] shows only1246the conflicts. It uses an unusual syntax:12471248-------------------------------------------------1249$ git diff1250diff --cc file.txt1251index 802992c,2b60207..00000001252--- a/file.txt1253+++ b/file.txt1254@@@ -1,1 -1,1 +1,5 @@@1255++<<<<<<< HEAD:file.txt1256 +Hello world1257++=======1258+ Goodbye1259++>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt1260-------------------------------------------------12611262Recall that the commit which will be committed after we resolve this1263conflict will have two parents instead of the usual one: one parent1264will be HEAD, the tip of the current branch; the other will be the1265tip of the other branch, which is stored temporarily in MERGE_HEAD.12661267During the merge, the index holds three versions of each file. Each of1268these three "file stages" represents a different version of the file:12691270-------------------------------------------------1271$ git show :1:file.txt # the file in a common ancestor of both branches1272$ git show :2:file.txt # the version from HEAD.1273$ git show :3:file.txt # the version from MERGE_HEAD.1274-------------------------------------------------12751276When you ask linkgit:git-diff[1] to show the conflicts, it runs a1277three-way diff between the conflicted merge results in the work tree with1278stages 2 and 3 to show only hunks whose contents come from both sides,1279mixed (in other words, when a hunk's merge results come only from stage 2,1280that part is not conflicting and is not shown. Same for stage 3).12811282The diff above shows the differences between the working-tree version of1283file.txt and the stage 2 and stage 3 versions. So instead of preceding1284each line by a single "+" or "-", it now uses two columns: the first1285column is used for differences between the first parent and the working1286directory copy, and the second for differences between the second parent1287and the working directory copy. (See the "COMBINED DIFF FORMAT" section1288of linkgit:git-diff-files[1] for a details of the format.)12891290After resolving the conflict in the obvious way (but before updating the1291index), the diff will look like:12921293-------------------------------------------------1294$ git diff1295diff --cc file.txt1296index 802992c,2b60207..00000001297--- a/file.txt1298+++ b/file.txt1299@@@ -1,1 -1,1 +1,1 @@@1300- Hello world1301 -Goodbye1302++Goodbye world1303-------------------------------------------------13041305This shows that our resolved version deleted "Hello world" from the1306first parent, deleted "Goodbye" from the second parent, and added1307"Goodbye world", which was previously absent from both.13081309Some special diff options allow diffing the working directory against1310any of these stages:13111312-------------------------------------------------1313$ git diff -1 file.txt # diff against stage 11314$ git diff --base file.txt # same as the above1315$ git diff -2 file.txt # diff against stage 21316$ git diff --ours file.txt # same as the above1317$ git diff -3 file.txt # diff against stage 31318$ git diff --theirs file.txt # same as the above.1319-------------------------------------------------13201321The linkgit:git-log[1] and linkgit:gitk[1] commands also provide special help1322for merges:13231324-------------------------------------------------1325$ git log --merge1326$ gitk --merge1327-------------------------------------------------13281329These will display all commits which exist only on HEAD or on1330MERGE_HEAD, and which touch an unmerged file.13311332You may also use linkgit:git-mergetool[1], which lets you merge the1333unmerged files using external tools such as emacs or kdiff3.13341335Each time you resolve the conflicts in a file and update the index:13361337-------------------------------------------------1338$ git add file.txt1339-------------------------------------------------13401341the different stages of that file will be "collapsed", after which1342git-diff will (by default) no longer show diffs for that file.13431344[[undoing-a-merge]]1345Undoing a merge1346---------------13471348If you get stuck and decide to just give up and throw the whole mess1349away, you can always return to the pre-merge state with13501351-------------------------------------------------1352$ git reset --hard HEAD1353-------------------------------------------------13541355Or, if you've already committed the merge that you want to throw away,13561357-------------------------------------------------1358$ git reset --hard ORIG_HEAD1359-------------------------------------------------13601361However, this last command can be dangerous in some cases--never1362throw away a commit you have already committed if that commit may1363itself have been merged into another branch, as doing so may confuse1364further merges.13651366[[fast-forwards]]1367Fast-forward merges1368-------------------13691370There is one special case not mentioned above, which is treated1371differently. Normally, a merge results in a merge commit, with two1372parents, one pointing at each of the two lines of development that1373were merged.13741375However, if the current branch is a descendant of the other--so every1376commit present in the one is already contained in the other--then git1377just performs a "fast forward"; the head of the current branch is moved1378forward to point at the head of the merged-in branch, without any new1379commits being created.13801381[[fixing-mistakes]]1382Fixing mistakes1383---------------13841385If you've messed up the working tree, but haven't yet committed your1386mistake, you can return the entire working tree to the last committed1387state with13881389-------------------------------------------------1390$ git reset --hard HEAD1391-------------------------------------------------13921393If you make a commit that you later wish you hadn't, there are two1394fundamentally different ways to fix the problem:13951396 1. You can create a new commit that undoes whatever was done1397 by the old commit. This is the correct thing if your1398 mistake has already been made public.13991400 2. You can go back and modify the old commit. You should1401 never do this if you have already made the history public;1402 git does not normally expect the "history" of a project to1403 change, and cannot correctly perform repeated merges from1404 a branch that has had its history changed.14051406[[reverting-a-commit]]1407Fixing a mistake with a new commit1408~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~14091410Creating a new commit that reverts an earlier change is very easy;1411just pass the linkgit:git-revert[1] command a reference to the bad1412commit; for example, to revert the most recent commit:14131414-------------------------------------------------1415$ git revert HEAD1416-------------------------------------------------14171418This will create a new commit which undoes the change in HEAD. You1419will be given a chance to edit the commit message for the new commit.14201421You can also revert an earlier change, for example, the next-to-last:14221423-------------------------------------------------1424$ git revert HEAD^1425-------------------------------------------------14261427In this case git will attempt to undo the old change while leaving1428intact any changes made since then. If more recent changes overlap1429with the changes to be reverted, then you will be asked to fix1430conflicts manually, just as in the case of <<resolving-a-merge,1431resolving a merge>>.14321433[[fixing-a-mistake-by-rewriting-history]]1434Fixing a mistake by rewriting history1435~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~14361437If the problematic commit is the most recent commit, and you have not1438yet made that commit public, then you may just1439<<undoing-a-merge,destroy it using git-reset>>.14401441Alternatively, you1442can edit the working directory and update the index to fix your1443mistake, just as if you were going to <<how-to-make-a-commit,create a1444new commit>>, then run14451446-------------------------------------------------1447$ git commit --amend1448-------------------------------------------------14491450which will replace the old commit by a new commit incorporating your1451changes, giving you a chance to edit the old commit message first.14521453Again, you should never do this to a commit that may already have1454been merged into another branch; use linkgit:git-revert[1] instead in1455that case.14561457It is also possible to replace commits further back in the history, but1458this is an advanced topic to be left for1459<<cleaning-up-history,another chapter>>.14601461[[checkout-of-path]]1462Checking out an old version of a file1463~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~14641465In the process of undoing a previous bad change, you may find it1466useful to check out an older version of a particular file using1467linkgit:git-checkout[1]. We've used git-checkout before to switch1468branches, but it has quite different behavior if it is given a path1469name: the command14701471-------------------------------------------------1472$ git checkout HEAD^ path/to/file1473-------------------------------------------------14741475replaces path/to/file by the contents it had in the commit HEAD^, and1476also updates the index to match. It does not change branches.14771478If you just want to look at an old version of the file, without1479modifying the working directory, you can do that with1480linkgit:git-show[1]:14811482-------------------------------------------------1483$ git show HEAD^:path/to/file1484-------------------------------------------------14851486which will display the given version of the file.14871488[[interrupted-work]]1489Temporarily setting aside work in progress1490~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~14911492While you are in the middle of working on something complicated, you1493find an unrelated but obvious and trivial bug. You would like to fix it1494before continuing. You can use linkgit:git-stash[1] to save the current1495state of your work, and after fixing the bug (or, optionally after doing1496so on a different branch and then coming back), unstash the1497work-in-progress changes.14981499------------------------------------------------1500$ git stash save "work in progress for foo feature"1501------------------------------------------------15021503This command will save your changes away to the `stash`, and1504reset your working tree and the index to match the tip of your1505current branch. Then you can make your fix as usual.15061507------------------------------------------------1508... edit and test ...1509$ git commit -a -m "blorpl: typofix"1510------------------------------------------------15111512After that, you can go back to what you were working on with1513`git stash apply`:15141515------------------------------------------------1516$ git stash apply1517------------------------------------------------151815191520[[ensuring-good-performance]]1521Ensuring good performance1522-------------------------15231524On large repositories, git depends on compression to keep the history1525information from taking up too much space on disk or in memory.15261527This compression is not performed automatically. Therefore you1528should occasionally run linkgit:git-gc[1]:15291530-------------------------------------------------1531$ git gc1532-------------------------------------------------15331534to recompress the archive. This can be very time-consuming, so1535you may prefer to run git-gc when you are not doing other work.153615371538[[ensuring-reliability]]1539Ensuring reliability1540--------------------15411542[[checking-for-corruption]]1543Checking the repository for corruption1544~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~15451546The linkgit:git-fsck[1] command runs a number of self-consistency checks1547on the repository, and reports on any problems. This may take some1548time. The most common warning by far is about "dangling" objects:15491550-------------------------------------------------1551$ git fsck1552dangling commit 7281251ddd2a61e38657c827739c57015671a6b31553dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a631554dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b51555dangling blob 218761f9d90712d37a9c5e36f406f92202db07eb1556dangling commit bf093535a34a4d35731aa2bd90fe6b176302f14f1557dangling commit 8e4bec7f2ddaa268bef999853c25755452100f8e1558dangling tree d50bb86186bf27b681d25af89d3b5b68382e40851559dangling tree b24c2473f1fd3d91352a624795be026d64c8841f1560...1561-------------------------------------------------15621563Dangling objects are not a problem. At worst they may take up a little1564extra disk space. They can sometimes provide a last-resort method for1565recovering lost work--see <<dangling-objects>> for details.15661567[[recovering-lost-changes]]1568Recovering lost changes1569~~~~~~~~~~~~~~~~~~~~~~~15701571[[reflogs]]1572Reflogs1573^^^^^^^15741575Say you modify a branch with `linkgit:git-reset[1] --hard`, and then1576realize that the branch was the only reference you had to that point in1577history.15781579Fortunately, git also keeps a log, called a "reflog", of all the1580previous values of each branch. So in this case you can still find the1581old history using, for example,15821583-------------------------------------------------1584$ git log master@{1}1585-------------------------------------------------15861587This lists the commits reachable from the previous version of the1588"master" branch head. This syntax can be used with any git command1589that accepts a commit, not just with git log. Some other examples:15901591-------------------------------------------------1592$ git show master@{2} # See where the branch pointed 2,1593$ git show master@{3} # 3, ... changes ago.1594$ gitk master@{yesterday} # See where it pointed yesterday,1595$ gitk master@{"1 week ago"} # ... or last week1596$ git log --walk-reflogs master # show reflog entries for master1597-------------------------------------------------15981599A separate reflog is kept for the HEAD, so16001601-------------------------------------------------1602$ git show HEAD@{"1 week ago"}1603-------------------------------------------------16041605will show what HEAD pointed to one week ago, not what the current branch1606pointed to one week ago. This allows you to see the history of what1607you've checked out.16081609The reflogs are kept by default for 30 days, after which they may be1610pruned. See linkgit:git-reflog[1] and linkgit:git-gc[1] to learn1611how to control this pruning, and see the "SPECIFYING REVISIONS"1612section of linkgit:git-rev-parse[1] for details.16131614Note that the reflog history is very different from normal git history.1615While normal history is shared by every repository that works on the1616same project, the reflog history is not shared: it tells you only about1617how the branches in your local repository have changed over time.16181619[[dangling-object-recovery]]1620Examining dangling objects1621^^^^^^^^^^^^^^^^^^^^^^^^^^16221623In some situations the reflog may not be able to save you. For example,1624suppose you delete a branch, then realize you need the history it1625contained. The reflog is also deleted; however, if you have not yet1626pruned the repository, then you may still be able to find the lost1627commits in the dangling objects that git-fsck reports. See1628<<dangling-objects>> for the details.16291630-------------------------------------------------1631$ git fsck1632dangling commit 7281251ddd2a61e38657c827739c57015671a6b31633dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a631634dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b51635...1636-------------------------------------------------16371638You can examine1639one of those dangling commits with, for example,16401641------------------------------------------------1642$ gitk 7281251ddd --not --all1643------------------------------------------------16441645which does what it sounds like: it says that you want to see the commit1646history that is described by the dangling commit(s), but not the1647history that is described by all your existing branches and tags. Thus1648you get exactly the history reachable from that commit that is lost.1649(And notice that it might not be just one commit: we only report the1650"tip of the line" as being dangling, but there might be a whole deep1651and complex commit history that was dropped.)16521653If you decide you want the history back, you can always create a new1654reference pointing to it, for example, a new branch:16551656------------------------------------------------1657$ git branch recovered-branch 7281251ddd1658------------------------------------------------16591660Other types of dangling objects (blobs and trees) are also possible, and1661dangling objects can arise in other situations.166216631664[[sharing-development]]1665Sharing development with others1666===============================16671668[[getting-updates-With-git-pull]]1669Getting updates with git-pull1670-----------------------------16711672After you clone a repository and make a few changes of your own, you1673may wish to check the original repository for updates and merge them1674into your own work.16751676We have already seen <<Updating-a-repository-With-git-fetch,how to1677keep remote tracking branches up to date>> with linkgit:git-fetch[1],1678and how to merge two branches. So you can merge in changes from the1679original repository's master branch with:16801681-------------------------------------------------1682$ git fetch1683$ git merge origin/master1684-------------------------------------------------16851686However, the linkgit:git-pull[1] command provides a way to do this in1687one step:16881689-------------------------------------------------1690$ git pull origin master1691-------------------------------------------------16921693In fact, if you have "master" checked out, then by default "git pull"1694merges from the HEAD branch of the origin repository. So often you can1695accomplish the above with just a simple16961697-------------------------------------------------1698$ git pull1699-------------------------------------------------17001701More generally, a branch that is created from a remote branch will pull1702by default from that branch. See the descriptions of the1703branch.<name>.remote and branch.<name>.merge options in1704linkgit:git-config[1], and the discussion of the `--track` option in1705linkgit:git-checkout[1], to learn how to control these defaults.17061707In addition to saving you keystrokes, "git pull" also helps you by1708producing a default commit message documenting the branch and1709repository that you pulled from.17101711(But note that no such commit will be created in the case of a1712<<fast-forwards,fast forward>>; instead, your branch will just be1713updated to point to the latest commit from the upstream branch.)17141715The git-pull command can also be given "." as the "remote" repository,1716in which case it just merges in a branch from the current repository; so1717the commands17181719-------------------------------------------------1720$ git pull . branch1721$ git merge branch1722-------------------------------------------------17231724are roughly equivalent. The former is actually very commonly used.17251726[[submitting-patches]]1727Submitting patches to a project1728-------------------------------17291730If you just have a few changes, the simplest way to submit them may1731just be to send them as patches in email:17321733First, use linkgit:git-format-patch[1]; for example:17341735-------------------------------------------------1736$ git format-patch origin1737-------------------------------------------------17381739will produce a numbered series of files in the current directory, one1740for each patch in the current branch but not in origin/HEAD.17411742You can then import these into your mail client and send them by1743hand. However, if you have a lot to send at once, you may prefer to1744use the linkgit:git-send-email[1] script to automate the process.1745Consult the mailing list for your project first to determine how they1746prefer such patches be handled.17471748[[importing-patches]]1749Importing patches to a project1750------------------------------17511752Git also provides a tool called linkgit:git-am[1] (am stands for1753"apply mailbox"), for importing such an emailed series of patches.1754Just save all of the patch-containing messages, in order, into a1755single mailbox file, say "patches.mbox", then run17561757-------------------------------------------------1758$ git am -3 patches.mbox1759-------------------------------------------------17601761Git will apply each patch in order; if any conflicts are found, it1762will stop, and you can fix the conflicts as described in1763"<<resolving-a-merge,Resolving a merge>>". (The "-3" option tells1764git to perform a merge; if you would prefer it just to abort and1765leave your tree and index untouched, you may omit that option.)17661767Once the index is updated with the results of the conflict1768resolution, instead of creating a new commit, just run17691770-------------------------------------------------1771$ git am --resolved1772-------------------------------------------------17731774and git will create the commit for you and continue applying the1775remaining patches from the mailbox.17761777The final result will be a series of commits, one for each patch in1778the original mailbox, with authorship and commit log message each1779taken from the message containing each patch.17801781[[public-repositories]]1782Public git repositories1783-----------------------17841785Another way to submit changes to a project is to tell the maintainer1786of that project to pull the changes from your repository using1787linkgit:git-pull[1]. In the section "<<getting-updates-With-git-pull,1788Getting updates with git-pull>>" we described this as a way to get1789updates from the "main" repository, but it works just as well in the1790other direction.17911792If you and the maintainer both have accounts on the same machine, then1793you can just pull changes from each other's repositories directly;1794commands that accept repository URLs as arguments will also accept a1795local directory name:17961797-------------------------------------------------1798$ git clone /path/to/repository1799$ git pull /path/to/other/repository1800-------------------------------------------------18011802or an ssh URL:18031804-------------------------------------------------1805$ git clone ssh://yourhost/~you/repository1806-------------------------------------------------18071808For projects with few developers, or for synchronizing a few private1809repositories, this may be all you need.18101811However, the more common way to do this is to maintain a separate public1812repository (usually on a different host) for others to pull changes1813from. This is usually more convenient, and allows you to cleanly1814separate private work in progress from publicly visible work.18151816You will continue to do your day-to-day work in your personal1817repository, but periodically "push" changes from your personal1818repository into your public repository, allowing other developers to1819pull from that repository. So the flow of changes, in a situation1820where there is one other developer with a public repository, looks1821like this:18221823 you push1824 your personal repo ------------------> your public repo1825 ^ |1826 | |1827 | you pull | they pull1828 | |1829 | |1830 | they push V1831 their public repo <------------------- their repo18321833We explain how to do this in the following sections.18341835[[setting-up-a-public-repository]]1836Setting up a public repository1837~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~18381839Assume your personal repository is in the directory ~/proj. We1840first create a new clone of the repository and tell git-daemon that it1841is meant to be public:18421843-------------------------------------------------1844$ git clone --bare ~/proj proj.git1845$ touch proj.git/git-daemon-export-ok1846-------------------------------------------------18471848The resulting directory proj.git contains a "bare" git repository--it is1849just the contents of the ".git" directory, without any files checked out1850around it.18511852Next, copy proj.git to the server where you plan to host the1853public repository. You can use scp, rsync, or whatever is most1854convenient.18551856[[exporting-via-git]]1857Exporting a git repository via the git protocol1858~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~18591860This is the preferred method.18611862If someone else administers the server, they should tell you what1863directory to put the repository in, and what git:// URL it will appear1864at. You can then skip to the section1865"<<pushing-changes-to-a-public-repository,Pushing changes to a public1866repository>>", below.18671868Otherwise, all you need to do is start linkgit:git-daemon[1]; it will1869listen on port 9418. By default, it will allow access to any directory1870that looks like a git directory and contains the magic file1871git-daemon-export-ok. Passing some directory paths as git-daemon1872arguments will further restrict the exports to those paths.18731874You can also run git-daemon as an inetd service; see the1875linkgit:git-daemon[1] man page for details. (See especially the1876examples section.)18771878[[exporting-via-http]]1879Exporting a git repository via http1880~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~18811882The git protocol gives better performance and reliability, but on a1883host with a web server set up, http exports may be simpler to set up.18841885All you need to do is place the newly created bare git repository in1886a directory that is exported by the web server, and make some1887adjustments to give web clients some extra information they need:18881889-------------------------------------------------1890$ mv proj.git /home/you/public_html/proj.git1891$ cd proj.git1892$ git --bare update-server-info1893$ mv hooks/post-update.sample hooks/post-update1894-------------------------------------------------18951896(For an explanation of the last two lines, see1897linkgit:git-update-server-info[1] and linkgit:githooks[5].)18981899Advertise the URL of proj.git. Anybody else should then be able to1900clone or pull from that URL, for example with a command line like:19011902-------------------------------------------------1903$ git clone http://yourserver.com/~you/proj.git1904-------------------------------------------------19051906(See also1907link:howto/setup-git-server-over-http.txt[setup-git-server-over-http]1908for a slightly more sophisticated setup using WebDAV which also1909allows pushing over http.)19101911[[pushing-changes-to-a-public-repository]]1912Pushing changes to a public repository1913~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~19141915Note that the two techniques outlined above (exporting via1916<<exporting-via-http,http>> or <<exporting-via-git,git>>) allow other1917maintainers to fetch your latest changes, but they do not allow write1918access, which you will need to update the public repository with the1919latest changes created in your private repository.19201921The simplest way to do this is using linkgit:git-push[1] and ssh; to1922update the remote branch named "master" with the latest state of your1923branch named "master", run19241925-------------------------------------------------1926$ git push ssh://yourserver.com/~you/proj.git master:master1927-------------------------------------------------19281929or just19301931-------------------------------------------------1932$ git push ssh://yourserver.com/~you/proj.git master1933-------------------------------------------------19341935As with git-fetch, git-push will complain if this does not result in a1936<<fast-forwards,fast forward>>; see the following section for details on1937handling this case.19381939Note that the target of a "push" is normally a1940<<def_bare_repository,bare>> repository. You can also push to a1941repository that has a checked-out working tree, but the working tree1942will not be updated by the push. This may lead to unexpected results if1943the branch you push to is the currently checked-out branch!19441945As with git-fetch, you may also set up configuration options to1946save typing; so, for example, after19471948-------------------------------------------------1949$ cat >>.git/config <<EOF1950[remote "public-repo"]1951 url = ssh://yourserver.com/~you/proj.git1952EOF1953-------------------------------------------------19541955you should be able to perform the above push with just19561957-------------------------------------------------1958$ git push public-repo master1959-------------------------------------------------19601961See the explanations of the remote.<name>.url, branch.<name>.remote,1962and remote.<name>.push options in linkgit:git-config[1] for1963details.19641965[[forcing-push]]1966What to do when a push fails1967~~~~~~~~~~~~~~~~~~~~~~~~~~~~19681969If a push would not result in a <<fast-forwards,fast forward>> of the1970remote branch, then it will fail with an error like:19711972-------------------------------------------------1973error: remote 'refs/heads/master' is not an ancestor of1974 local 'refs/heads/master'.1975 Maybe you are not up-to-date and need to pull first?1976error: failed to push to 'ssh://yourserver.com/~you/proj.git'1977-------------------------------------------------19781979This can happen, for example, if you:19801981 - use `git-reset --hard` to remove already-published commits, or1982 - use `git-commit --amend` to replace already-published commits1983 (as in <<fixing-a-mistake-by-rewriting-history>>), or1984 - use `git-rebase` to rebase any already-published commits (as1985 in <<using-git-rebase>>).19861987You may force git-push to perform the update anyway by preceding the1988branch name with a plus sign:19891990-------------------------------------------------1991$ git push ssh://yourserver.com/~you/proj.git +master1992-------------------------------------------------19931994Normally whenever a branch head in a public repository is modified, it1995is modified to point to a descendant of the commit that it pointed to1996before. By forcing a push in this situation, you break that convention.1997(See <<problems-With-rewriting-history>>.)19981999Nevertheless, this is a common practice for people that need a simple2000way to publish a work-in-progress patch series, and it is an acceptable2001compromise as long as you warn other developers that this is how you2002intend to manage the branch.20032004It's also possible for a push to fail in this way when other people have2005the right to push to the same repository. In that case, the correct2006solution is to retry the push after first updating your work: either by a2007pull, or by a fetch followed by a rebase; see the2008<<setting-up-a-shared-repository,next section>> and2009linkgit:gitcvs-migration[7] for more.20102011[[setting-up-a-shared-repository]]2012Setting up a shared repository2013~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~20142015Another way to collaborate is by using a model similar to that2016commonly used in CVS, where several developers with special rights2017all push to and pull from a single shared repository. See2018linkgit:gitcvs-migration[7] for instructions on how to2019set this up.20202021However, while there is nothing wrong with git's support for shared2022repositories, this mode of operation is not generally recommended,2023simply because the mode of collaboration that git supports--by2024exchanging patches and pulling from public repositories--has so many2025advantages over the central shared repository:20262027 - Git's ability to quickly import and merge patches allows a2028 single maintainer to process incoming changes even at very2029 high rates. And when that becomes too much, git-pull provides2030 an easy way for that maintainer to delegate this job to other2031 maintainers while still allowing optional review of incoming2032 changes.2033 - Since every developer's repository has the same complete copy2034 of the project history, no repository is special, and it is2035 trivial for another developer to take over maintenance of a2036 project, either by mutual agreement, or because a maintainer2037 becomes unresponsive or difficult to work with.2038 - The lack of a central group of "committers" means there is2039 less need for formal decisions about who is "in" and who is2040 "out".20412042[[setting-up-gitweb]]2043Allowing web browsing of a repository2044~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~20452046The gitweb cgi script provides users an easy way to browse your2047project's files and history without having to install git; see the file2048gitweb/INSTALL in the git source tree for instructions on setting it up.20492050[[sharing-development-examples]]2051Examples2052--------20532054[[maintaining-topic-branches]]2055Maintaining topic branches for a Linux subsystem maintainer2056~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~20572058This describes how Tony Luck uses git in his role as maintainer of the2059IA64 architecture for the Linux kernel.20602061He uses two public branches:20622063 - A "test" tree into which patches are initially placed so that they2064 can get some exposure when integrated with other ongoing development.2065 This tree is available to Andrew for pulling into -mm whenever he2066 wants.20672068 - A "release" tree into which tested patches are moved for final sanity2069 checking, and as a vehicle to send them upstream to Linus (by sending2070 him a "please pull" request.)20712072He also uses a set of temporary branches ("topic branches"), each2073containing a logical grouping of patches.20742075To set this up, first create your work tree by cloning Linus's public2076tree:20772078-------------------------------------------------2079$ git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git work2080$ cd work2081-------------------------------------------------20822083Linus's tree will be stored in the remote branch named origin/master,2084and can be updated using linkgit:git-fetch[1]; you can track other2085public trees using linkgit:git-remote[1] to set up a "remote" and2086linkgit:git-fetch[1] to keep them up-to-date; see2087<<repositories-and-branches>>.20882089Now create the branches in which you are going to work; these start out2090at the current tip of origin/master branch, and should be set up (using2091the --track option to linkgit:git-branch[1]) to merge changes in from2092Linus by default.20932094-------------------------------------------------2095$ git branch --track test origin/master2096$ git branch --track release origin/master2097-------------------------------------------------20982099These can be easily kept up to date using linkgit:git-pull[1].21002101-------------------------------------------------2102$ git checkout test && git pull2103$ git checkout release && git pull2104-------------------------------------------------21052106Important note! If you have any local changes in these branches, then2107this merge will create a commit object in the history (with no local2108changes git will simply do a "Fast forward" merge). Many people dislike2109the "noise" that this creates in the Linux history, so you should avoid2110doing this capriciously in the "release" branch, as these noisy commits2111will become part of the permanent history when you ask Linus to pull2112from the release branch.21132114A few configuration variables (see linkgit:git-config[1]) can2115make it easy to push both branches to your public tree. (See2116<<setting-up-a-public-repository>>.)21172118-------------------------------------------------2119$ cat >> .git/config <<EOF2120[remote "mytree"]2121 url = master.kernel.org:/pub/scm/linux/kernel/git/aegl/linux-2.6.git2122 push = release2123 push = test2124EOF2125-------------------------------------------------21262127Then you can push both the test and release trees using2128linkgit:git-push[1]:21292130-------------------------------------------------2131$ git push mytree2132-------------------------------------------------21332134or push just one of the test and release branches using:21352136-------------------------------------------------2137$ git push mytree test2138-------------------------------------------------21392140or21412142-------------------------------------------------2143$ git push mytree release2144-------------------------------------------------21452146Now to apply some patches from the community. Think of a short2147snappy name for a branch to hold this patch (or related group of2148patches), and create a new branch from the current tip of Linus's2149branch:21502151-------------------------------------------------2152$ git checkout -b speed-up-spinlocks origin2153-------------------------------------------------21542155Now you apply the patch(es), run some tests, and commit the change(s). If2156the patch is a multi-part series, then you should apply each as a separate2157commit to this branch.21582159-------------------------------------------------2160$ ... patch ... test ... commit [ ... patch ... test ... commit ]*2161-------------------------------------------------21622163When you are happy with the state of this change, you can pull it into the2164"test" branch in preparation to make it public:21652166-------------------------------------------------2167$ git checkout test && git pull . speed-up-spinlocks2168-------------------------------------------------21692170It is unlikely that you would have any conflicts here ... but you might if you2171spent a while on this step and had also pulled new versions from upstream.21722173Some time later when enough time has passed and testing done, you can pull the2174same branch into the "release" tree ready to go upstream. This is where you2175see the value of keeping each patch (or patch series) in its own branch. It2176means that the patches can be moved into the "release" tree in any order.21772178-------------------------------------------------2179$ git checkout release && git pull . speed-up-spinlocks2180-------------------------------------------------21812182After a while, you will have a number of branches, and despite the2183well chosen names you picked for each of them, you may forget what2184they are for, or what status they are in. To get a reminder of what2185changes are in a specific branch, use:21862187-------------------------------------------------2188$ git log linux..branchname | git shortlog2189-------------------------------------------------21902191To see whether it has already been merged into the test or release branches,2192use:21932194-------------------------------------------------2195$ git log test..branchname2196-------------------------------------------------21972198or21992200-------------------------------------------------2201$ git log release..branchname2202-------------------------------------------------22032204(If this branch has not yet been merged, you will see some log entries.2205If it has been merged, then there will be no output.)22062207Once a patch completes the great cycle (moving from test to release,2208then pulled by Linus, and finally coming back into your local2209"origin/master" branch), the branch for this change is no longer needed.2210You detect this when the output from:22112212-------------------------------------------------2213$ git log origin..branchname2214-------------------------------------------------22152216is empty. At this point the branch can be deleted:22172218-------------------------------------------------2219$ git branch -d branchname2220-------------------------------------------------22212222Some changes are so trivial that it is not necessary to create a separate2223branch and then merge into each of the test and release branches. For2224these changes, just apply directly to the "release" branch, and then2225merge that into the "test" branch.22262227To create diffstat and shortlog summaries of changes to include in a "please2228pull" request to Linus you can use:22292230-------------------------------------------------2231$ git diff --stat origin..release2232-------------------------------------------------22332234and22352236-------------------------------------------------2237$ git log -p origin..release | git shortlog2238-------------------------------------------------22392240Here are some of the scripts that simplify all this even further.22412242-------------------------------------------------2243==== update script ====2244# Update a branch in my GIT tree. If the branch to be updated2245# is origin, then pull from kernel.org. Otherwise merge2246# origin/master branch into test|release branch22472248case "$1" in2249test|release)2250 git checkout $1 && git pull . origin2251 ;;2252origin)2253 before=$(git rev-parse refs/remotes/origin/master)2254 git fetch origin2255 after=$(git rev-parse refs/remotes/origin/master)2256 if [ $before != $after ]2257 then2258 git log $before..$after | git shortlog2259 fi2260 ;;2261*)2262 echo "Usage: $0 origin|test|release" 1>&22263 exit 12264 ;;2265esac2266-------------------------------------------------22672268-------------------------------------------------2269==== merge script ====2270# Merge a branch into either the test or release branch22712272pname=$022732274usage()2275{2276 echo "Usage: $pname branch test|release" 1>&22277 exit 12278}22792280git show-ref -q --verify -- refs/heads/"$1" || {2281 echo "Can't see branch <$1>" 1>&22282 usage2283}22842285case "$2" in2286test|release)2287 if [ $(git log $2..$1 | wc -c) -eq 0 ]2288 then2289 echo $1 already merged into $2 1>&22290 exit 12291 fi2292 git checkout $2 && git pull . $12293 ;;2294*)2295 usage2296 ;;2297esac2298-------------------------------------------------22992300-------------------------------------------------2301==== status script ====2302# report on status of my ia64 GIT tree23032304gb=$(tput setab 2)2305rb=$(tput setab 1)2306restore=$(tput setab 9)23072308if [ `git rev-list test..release | wc -c` -gt 0 ]2309then2310 echo $rb Warning: commits in release that are not in test $restore2311 git log test..release2312fi23132314for branch in `git show-ref --heads | sed 's|^.*/||'`2315do2316 if [ $branch = test -o $branch = release ]2317 then2318 continue2319 fi23202321 echo -n $gb ======= $branch ====== $restore " "2322 status=2323 for ref in test release origin/master2324 do2325 if [ `git rev-list $ref..$branch | wc -c` -gt 0 ]2326 then2327 status=$status${ref:0:1}2328 fi2329 done2330 case $status in2331 trl)2332 echo $rb Need to pull into test $restore2333 ;;2334 rl)2335 echo "In test"2336 ;;2337 l)2338 echo "Waiting for linus"2339 ;;2340 "")2341 echo $rb All done $restore2342 ;;2343 *)2344 echo $rb "<$status>" $restore2345 ;;2346 esac2347 git log origin/master..$branch | git shortlog2348done2349-------------------------------------------------235023512352[[cleaning-up-history]]2353Rewriting history and maintaining patch series2354==============================================23552356Normally commits are only added to a project, never taken away or2357replaced. Git is designed with this assumption, and violating it will2358cause git's merge machinery (for example) to do the wrong thing.23592360However, there is a situation in which it can be useful to violate this2361assumption.23622363[[patch-series]]2364Creating the perfect patch series2365---------------------------------23662367Suppose you are a contributor to a large project, and you want to add a2368complicated feature, and to present it to the other developers in a way2369that makes it easy for them to read your changes, verify that they are2370correct, and understand why you made each change.23712372If you present all of your changes as a single patch (or commit), they2373may find that it is too much to digest all at once.23742375If you present them with the entire history of your work, complete with2376mistakes, corrections, and dead ends, they may be overwhelmed.23772378So the ideal is usually to produce a series of patches such that:23792380 1. Each patch can be applied in order.23812382 2. Each patch includes a single logical change, together with a2383 message explaining the change.23842385 3. No patch introduces a regression: after applying any initial2386 part of the series, the resulting project still compiles and2387 works, and has no bugs that it didn't have before.23882389 4. The complete series produces the same end result as your own2390 (probably much messier!) development process did.23912392We will introduce some tools that can help you do this, explain how to2393use them, and then explain some of the problems that can arise because2394you are rewriting history.23952396[[using-git-rebase]]2397Keeping a patch series up to date using git-rebase2398--------------------------------------------------23992400Suppose that you create a branch "mywork" on a remote-tracking branch2401"origin", and create some commits on top of it:24022403-------------------------------------------------2404$ git checkout -b mywork origin2405$ vi file.txt2406$ git commit2407$ vi otherfile.txt2408$ git commit2409...2410-------------------------------------------------24112412You have performed no merges into mywork, so it is just a simple linear2413sequence of patches on top of "origin":24142415................................................2416 o--o--o <-- origin2417 \2418 o--o--o <-- mywork2419................................................24202421Some more interesting work has been done in the upstream project, and2422"origin" has advanced:24232424................................................2425 o--o--O--o--o--o <-- origin2426 \2427 a--b--c <-- mywork2428................................................24292430At this point, you could use "pull" to merge your changes back in;2431the result would create a new merge commit, like this:24322433................................................2434 o--o--O--o--o--o <-- origin2435 \ \2436 a--b--c--m <-- mywork2437................................................24382439However, if you prefer to keep the history in mywork a simple series of2440commits without any merges, you may instead choose to use2441linkgit:git-rebase[1]:24422443-------------------------------------------------2444$ git checkout mywork2445$ git rebase origin2446-------------------------------------------------24472448This will remove each of your commits from mywork, temporarily saving2449them as patches (in a directory named ".git/rebase-apply"), update mywork to2450point at the latest version of origin, then apply each of the saved2451patches to the new mywork. The result will look like:245224532454................................................2455 o--o--O--o--o--o <-- origin2456 \2457 a'--b'--c' <-- mywork2458................................................24592460In the process, it may discover conflicts. In that case it will stop2461and allow you to fix the conflicts; after fixing conflicts, use "git-add"2462to update the index with those contents, and then, instead of2463running git-commit, just run24642465-------------------------------------------------2466$ git rebase --continue2467-------------------------------------------------24682469and git will continue applying the rest of the patches.24702471At any point you may use the `--abort` option to abort this process and2472return mywork to the state it had before you started the rebase:24732474-------------------------------------------------2475$ git rebase --abort2476-------------------------------------------------24772478[[rewriting-one-commit]]2479Rewriting a single commit2480-------------------------24812482We saw in <<fixing-a-mistake-by-rewriting-history>> that you can replace the2483most recent commit using24842485-------------------------------------------------2486$ git commit --amend2487-------------------------------------------------24882489which will replace the old commit by a new commit incorporating your2490changes, giving you a chance to edit the old commit message first.24912492You can also use a combination of this and linkgit:git-rebase[1] to2493replace a commit further back in your history and recreate the2494intervening changes on top of it. First, tag the problematic commit2495with24962497-------------------------------------------------2498$ git tag bad mywork~52499-------------------------------------------------25002501(Either gitk or git-log may be useful for finding the commit.)25022503Then check out that commit, edit it, and rebase the rest of the series2504on top of it (note that we could check out the commit on a temporary2505branch, but instead we're using a <<detached-head,detached head>>):25062507-------------------------------------------------2508$ git checkout bad2509$ # make changes here and update the index2510$ git commit --amend2511$ git rebase --onto HEAD bad mywork2512-------------------------------------------------25132514When you're done, you'll be left with mywork checked out, with the top2515patches on mywork reapplied on top of your modified commit. You can2516then clean up with25172518-------------------------------------------------2519$ git tag -d bad2520-------------------------------------------------25212522Note that the immutable nature of git history means that you haven't really2523"modified" existing commits; instead, you have replaced the old commits with2524new commits having new object names.25252526[[reordering-patch-series]]2527Reordering or selecting from a patch series2528-------------------------------------------25292530Given one existing commit, the linkgit:git-cherry-pick[1] command2531allows you to apply the change introduced by that commit and create a2532new commit that records it. So, for example, if "mywork" points to a2533series of patches on top of "origin", you might do something like:25342535-------------------------------------------------2536$ git checkout -b mywork-new origin2537$ gitk origin..mywork &2538-------------------------------------------------25392540and browse through the list of patches in the mywork branch using gitk,2541applying them (possibly in a different order) to mywork-new using2542cherry-pick, and possibly modifying them as you go using `commit --amend`.2543The linkgit:git-gui[1] command may also help as it allows you to2544individually select diff hunks for inclusion in the index (by2545right-clicking on the diff hunk and choosing "Stage Hunk for Commit").25462547Another technique is to use git-format-patch to create a series of2548patches, then reset the state to before the patches:25492550-------------------------------------------------2551$ git format-patch origin2552$ git reset --hard origin2553-------------------------------------------------25542555Then modify, reorder, or eliminate patches as preferred before applying2556them again with linkgit:git-am[1].25572558[[patch-series-tools]]2559Other tools2560-----------25612562There are numerous other tools, such as StGIT, which exist for the2563purpose of maintaining a patch series. These are outside of the scope of2564this manual.25652566[[problems-With-rewriting-history]]2567Problems with rewriting history2568-------------------------------25692570The primary problem with rewriting the history of a branch has to do2571with merging. Suppose somebody fetches your branch and merges it into2572their branch, with a result something like this:25732574................................................2575 o--o--O--o--o--o <-- origin2576 \ \2577 t--t--t--m <-- their branch:2578................................................25792580Then suppose you modify the last three commits:25812582................................................2583 o--o--o <-- new head of origin2584 /2585 o--o--O--o--o--o <-- old head of origin2586................................................25872588If we examined all this history together in one repository, it will2589look like:25902591................................................2592 o--o--o <-- new head of origin2593 /2594 o--o--O--o--o--o <-- old head of origin2595 \ \2596 t--t--t--m <-- their branch:2597................................................25982599Git has no way of knowing that the new head is an updated version of2600the old head; it treats this situation exactly the same as it would if2601two developers had independently done the work on the old and new heads2602in parallel. At this point, if someone attempts to merge the new head2603in to their branch, git will attempt to merge together the two (old and2604new) lines of development, instead of trying to replace the old by the2605new. The results are likely to be unexpected.26062607You may still choose to publish branches whose history is rewritten,2608and it may be useful for others to be able to fetch those branches in2609order to examine or test them, but they should not attempt to pull such2610branches into their own work.26112612For true distributed development that supports proper merging,2613published branches should never be rewritten.26142615[[bisect-merges]]2616Why bisecting merge commits can be harder than bisecting linear history2617-----------------------------------------------------------------------26182619The linkgit:git-bisect[1] command correctly handles history that2620includes merge commits. However, when the commit that it finds is a2621merge commit, the user may need to work harder than usual to figure out2622why that commit introduced a problem.26232624Imagine this history:26252626................................................2627 ---Z---o---X---...---o---A---C---D2628 \ /2629 o---o---Y---...---o---B2630................................................26312632Suppose that on the upper line of development, the meaning of one2633of the functions that exists at Z is changed at commit X. The2634commits from Z leading to A change both the function's2635implementation and all calling sites that exist at Z, as well2636as new calling sites they add, to be consistent. There is no2637bug at A.26382639Suppose that in the meantime on the lower line of development somebody2640adds a new calling site for that function at commit Y. The2641commits from Z leading to B all assume the old semantics of that2642function and the callers and the callee are consistent with each2643other. There is no bug at B, either.26442645Suppose further that the two development lines merge cleanly at C,2646so no conflict resolution is required.26472648Nevertheless, the code at C is broken, because the callers added2649on the lower line of development have not been converted to the new2650semantics introduced on the upper line of development. So if all2651you know is that D is bad, that Z is good, and that2652linkgit:git-bisect[1] identifies C as the culprit, how will you2653figure out that the problem is due to this change in semantics?26542655When the result of a git-bisect is a non-merge commit, you should2656normally be able to discover the problem by examining just that commit.2657Developers can make this easy by breaking their changes into small2658self-contained commits. That won't help in the case above, however,2659because the problem isn't obvious from examination of any single2660commit; instead, a global view of the development is required. To2661make matters worse, the change in semantics in the problematic2662function may be just one small part of the changes in the upper2663line of development.26642665On the other hand, if instead of merging at C you had rebased the2666history between Z to B on top of A, you would have gotten this2667linear history:26682669................................................................2670 ---Z---o---X--...---o---A---o---o---Y*--...---o---B*--D*2671................................................................26722673Bisecting between Z and D* would hit a single culprit commit Y*,2674and understanding why Y* was broken would probably be easier.26752676Partly for this reason, many experienced git users, even when2677working on an otherwise merge-heavy project, keep the history2678linear by rebasing against the latest upstream version before2679publishing.26802681[[advanced-branch-management]]2682Advanced branch management2683==========================26842685[[fetching-individual-branches]]2686Fetching individual branches2687----------------------------26882689Instead of using linkgit:git-remote[1], you can also choose just2690to update one branch at a time, and to store it locally under an2691arbitrary name:26922693-------------------------------------------------2694$ git fetch origin todo:my-todo-work2695-------------------------------------------------26962697The first argument, "origin", just tells git to fetch from the2698repository you originally cloned from. The second argument tells git2699to fetch the branch named "todo" from the remote repository, and to2700store it locally under the name refs/heads/my-todo-work.27012702You can also fetch branches from other repositories; so27032704-------------------------------------------------2705$ git fetch git://example.com/proj.git master:example-master2706-------------------------------------------------27072708will create a new branch named "example-master" and store in it the2709branch named "master" from the repository at the given URL. If you2710already have a branch named example-master, it will attempt to2711<<fast-forwards,fast-forward>> to the commit given by example.com's2712master branch. In more detail:27132714[[fetch-fast-forwards]]2715git fetch and fast-forwards2716---------------------------27172718In the previous example, when updating an existing branch, "git-fetch"2719checks to make sure that the most recent commit on the remote2720branch is a descendant of the most recent commit on your copy of the2721branch before updating your copy of the branch to point at the new2722commit. Git calls this process a <<fast-forwards,fast forward>>.27232724A fast forward looks something like this:27252726................................................2727 o--o--o--o <-- old head of the branch2728 \2729 o--o--o <-- new head of the branch2730................................................273127322733In some cases it is possible that the new head will *not* actually be2734a descendant of the old head. For example, the developer may have2735realized she made a serious mistake, and decided to backtrack,2736resulting in a situation like:27372738................................................2739 o--o--o--o--a--b <-- old head of the branch2740 \2741 o--o--o <-- new head of the branch2742................................................27432744In this case, "git-fetch" will fail, and print out a warning.27452746In that case, you can still force git to update to the new head, as2747described in the following section. However, note that in the2748situation above this may mean losing the commits labeled "a" and "b",2749unless you've already created a reference of your own pointing to2750them.27512752[[forcing-fetch]]2753Forcing git-fetch to do non-fast-forward updates2754------------------------------------------------27552756If git fetch fails because the new head of a branch is not a2757descendant of the old head, you may force the update with:27582759-------------------------------------------------2760$ git fetch git://example.com/proj.git +master:refs/remotes/example/master2761-------------------------------------------------27622763Note the addition of the "+" sign. Alternatively, you can use the "-f"2764flag to force updates of all the fetched branches, as in:27652766-------------------------------------------------2767$ git fetch -f origin2768-------------------------------------------------27692770Be aware that commits that the old version of example/master pointed at2771may be lost, as we saw in the previous section.27722773[[remote-branch-configuration]]2774Configuring remote branches2775---------------------------27762777We saw above that "origin" is just a shortcut to refer to the2778repository that you originally cloned from. This information is2779stored in git configuration variables, which you can see using2780linkgit:git-config[1]:27812782-------------------------------------------------2783$ git config -l2784core.repositoryformatversion=02785core.filemode=true2786core.logallrefupdates=true2787remote.origin.url=git://git.kernel.org/pub/scm/git/git.git2788remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*2789branch.master.remote=origin2790branch.master.merge=refs/heads/master2791-------------------------------------------------27922793If there are other repositories that you also use frequently, you can2794create similar configuration options to save typing; for example,2795after27962797-------------------------------------------------2798$ git config remote.example.url git://example.com/proj.git2799-------------------------------------------------28002801then the following two commands will do the same thing:28022803-------------------------------------------------2804$ git fetch git://example.com/proj.git master:refs/remotes/example/master2805$ git fetch example master:refs/remotes/example/master2806-------------------------------------------------28072808Even better, if you add one more option:28092810-------------------------------------------------2811$ git config remote.example.fetch master:refs/remotes/example/master2812-------------------------------------------------28132814then the following commands will all do the same thing:28152816-------------------------------------------------2817$ git fetch git://example.com/proj.git master:refs/remotes/example/master2818$ git fetch example master:refs/remotes/example/master2819$ git fetch example2820-------------------------------------------------28212822You can also add a "+" to force the update each time:28232824-------------------------------------------------2825$ git config remote.example.fetch +master:ref/remotes/example/master2826-------------------------------------------------28272828Don't do this unless you're sure you won't mind "git fetch" possibly2829throwing away commits on 'example/master'.28302831Also note that all of the above configuration can be performed by2832directly editing the file .git/config instead of using2833linkgit:git-config[1].28342835See linkgit:git-config[1] for more details on the configuration2836options mentioned above.283728382839[[git-concepts]]2840Git concepts2841============28422843Git is built on a small number of simple but powerful ideas. While it2844is possible to get things done without understanding them, you will find2845git much more intuitive if you do.28462847We start with the most important, the <<def_object_database,object2848database>> and the <<def_index,index>>.28492850[[the-object-database]]2851The Object Database2852-------------------285328542855We already saw in <<understanding-commits>> that all commits are stored2856under a 40-digit "object name". In fact, all the information needed to2857represent the history of a project is stored in objects with such names.2858In each case the name is calculated by taking the SHA1 hash of the2859contents of the object. The SHA1 hash is a cryptographic hash function.2860What that means to us is that it is impossible to find two different2861objects with the same name. This has a number of advantages; among2862others:28632864- Git can quickly determine whether two objects are identical or not,2865 just by comparing names.2866- Since object names are computed the same way in every repository, the2867 same content stored in two repositories will always be stored under2868 the same name.2869- Git can detect errors when it reads an object, by checking that the2870 object's name is still the SHA1 hash of its contents.28712872(See <<object-details>> for the details of the object formatting and2873SHA1 calculation.)28742875There are four different types of objects: "blob", "tree", "commit", and2876"tag".28772878- A <<def_blob_object,"blob" object>> is used to store file data.2879- A <<def_tree_object,"tree" object>> ties one or more2880 "blob" objects into a directory structure. In addition, a tree object2881 can refer to other tree objects, thus creating a directory hierarchy.2882- A <<def_commit_object,"commit" object>> ties such directory hierarchies2883 together into a <<def_DAG,directed acyclic graph>> of revisions--each2884 commit contains the object name of exactly one tree designating the2885 directory hierarchy at the time of the commit. In addition, a commit2886 refers to "parent" commit objects that describe the history of how we2887 arrived at that directory hierarchy.2888- A <<def_tag_object,"tag" object>> symbolically identifies and can be2889 used to sign other objects. It contains the object name and type of2890 another object, a symbolic name (of course!) and, optionally, a2891 signature.28922893The object types in some more detail:28942895[[commit-object]]2896Commit Object2897~~~~~~~~~~~~~28982899The "commit" object links a physical state of a tree with a description2900of how we got there and why. Use the --pretty=raw option to2901linkgit:git-show[1] or linkgit:git-log[1] to examine your favorite2902commit:29032904------------------------------------------------2905$ git show -s --pretty=raw 2be7fcb4762906commit 2be7fcb4764f2dbcee52635b91fedb1b3dcf7ab42907tree fb3a8bdd0ceddd019615af4d57a53f43d8cee2bf2908parent 257a84d9d02e90447b149af58b271c19405edb6a2909author Dave Watson <dwatson@mimvista.com> 1187576872 -04002910committer Junio C Hamano <gitster@pobox.com> 1187591163 -070029112912 Fix misspelling of 'suppress' in docs29132914 Signed-off-by: Junio C Hamano <gitster@pobox.com>2915------------------------------------------------29162917As you can see, a commit is defined by:29182919- a tree: The SHA1 name of a tree object (as defined below), representing2920 the contents of a directory at a certain point in time.2921- parent(s): The SHA1 name of some number of commits which represent the2922 immediately previous step(s) in the history of the project. The2923 example above has one parent; merge commits may have more than2924 one. A commit with no parents is called a "root" commit, and2925 represents the initial revision of a project. Each project must have2926 at least one root. A project can also have multiple roots, though2927 that isn't common (or necessarily a good idea).2928- an author: The name of the person responsible for this change, together2929 with its date.2930- a committer: The name of the person who actually created the commit,2931 with the date it was done. This may be different from the author, for2932 example, if the author was someone who wrote a patch and emailed it2933 to the person who used it to create the commit.2934- a comment describing this commit.29352936Note that a commit does not itself contain any information about what2937actually changed; all changes are calculated by comparing the contents2938of the tree referred to by this commit with the trees associated with2939its parents. In particular, git does not attempt to record file renames2940explicitly, though it can identify cases where the existence of the same2941file data at changing paths suggests a rename. (See, for example, the2942-M option to linkgit:git-diff[1]).29432944A commit is usually created by linkgit:git-commit[1], which creates a2945commit whose parent is normally the current HEAD, and whose tree is2946taken from the content currently stored in the index.29472948[[tree-object]]2949Tree Object2950~~~~~~~~~~~29512952The ever-versatile linkgit:git-show[1] command can also be used to2953examine tree objects, but linkgit:git-ls-tree[1] will give you more2954details:29552956------------------------------------------------2957$ git ls-tree fb3a8bdd0ce2958100644 blob 63c918c667fa005ff12ad89437f2fdc80926e21c .gitignore2959100644 blob 5529b198e8d14decbe4ad99db3f7fb632de0439d .mailmap2960100644 blob 6ff87c4664981e4397625791c8ea3bbb5f2279a3 COPYING2961040000 tree 2fb783e477100ce076f6bf57e4a6f026013dc745 Documentation2962100755 blob 3c0032cec592a765692234f1cba47dfdcc3a9200 GIT-VERSION-GEN2963100644 blob 289b046a443c0647624607d471289b2c7dcd470b INSTALL2964100644 blob 4eb463797adc693dc168b926b6932ff53f17d0b1 Makefile2965100644 blob 548142c327a6790ff8821d67c2ee1eff7a656b52 README2966...2967------------------------------------------------29682969As you can see, a tree object contains a list of entries, each with a2970mode, object type, SHA1 name, and name, sorted by name. It represents2971the contents of a single directory tree.29722973The object type may be a blob, representing the contents of a file, or2974another tree, representing the contents of a subdirectory. Since trees2975and blobs, like all other objects, are named by the SHA1 hash of their2976contents, two trees have the same SHA1 name if and only if their2977contents (including, recursively, the contents of all subdirectories)2978are identical. This allows git to quickly determine the differences2979between two related tree objects, since it can ignore any entries with2980identical object names.29812982(Note: in the presence of submodules, trees may also have commits as2983entries. See <<submodules>> for documentation.)29842985Note that the files all have mode 644 or 755: git actually only pays2986attention to the executable bit.29872988[[blob-object]]2989Blob Object2990~~~~~~~~~~~29912992You can use linkgit:git-show[1] to examine the contents of a blob; take,2993for example, the blob in the entry for "COPYING" from the tree above:29942995------------------------------------------------2996$ git show 6ff87c466429972998 Note that the only valid version of the GPL as far as this project2999 is concerned is _this_ particular version of the license (ie v2, not3000 v2.2 or v3.x or whatever), unless explicitly otherwise stated.3001...3002------------------------------------------------30033004A "blob" object is nothing but a binary blob of data. It doesn't refer3005to anything else or have attributes of any kind.30063007Since the blob is entirely defined by its data, if two files in a3008directory tree (or in multiple different versions of the repository)3009have the same contents, they will share the same blob object. The object3010is totally independent of its location in the directory tree, and3011renaming a file does not change the object that file is associated with.30123013Note that any tree or blob object can be examined using3014linkgit:git-show[1] with the <revision>:<path> syntax. This can3015sometimes be useful for browsing the contents of a tree that is not3016currently checked out.30173018[[trust]]3019Trust3020~~~~~30213022If you receive the SHA1 name of a blob from one source, and its contents3023from another (possibly untrusted) source, you can still trust that those3024contents are correct as long as the SHA1 name agrees. This is because3025the SHA1 is designed so that it is infeasible to find different contents3026that produce the same hash.30273028Similarly, you need only trust the SHA1 name of a top-level tree object3029to trust the contents of the entire directory that it refers to, and if3030you receive the SHA1 name of a commit from a trusted source, then you3031can easily verify the entire history of commits reachable through3032parents of that commit, and all of those contents of the trees referred3033to by those commits.30343035So to introduce some real trust in the system, the only thing you need3036to do is to digitally sign just 'one' special note, which includes the3037name of a top-level commit. Your digital signature shows others3038that you trust that commit, and the immutability of the history of3039commits tells others that they can trust the whole history.30403041In other words, you can easily validate a whole archive by just3042sending out a single email that tells the people the name (SHA1 hash)3043of the top commit, and digitally sign that email using something3044like GPG/PGP.30453046To assist in this, git also provides the tag object...30473048[[tag-object]]3049Tag Object3050~~~~~~~~~~30513052A tag object contains an object, object type, tag name, the name of the3053person ("tagger") who created the tag, and a message, which may contain3054a signature, as can be seen using linkgit:git-cat-file[1]:30553056------------------------------------------------3057$ git cat-file tag v1.5.03058object 437b1b20df4b356c9342dac8d38849f24ef44f273059type commit3060tag v1.5.03061tagger Junio C Hamano <junkio@cox.net> 1171411200 +000030623063GIT 1.5.03064-----BEGIN PGP SIGNATURE-----3065Version: GnuPG v1.4.6 (GNU/Linux)30663067iD8DBQBF0lGqwMbZpPMRm5oRAuRiAJ9ohBLd7s2kqjkKlq1qqC57SbnmzQCdG4ui3068nLE/L9aUXdWeTFPron96DLA=3069=2E+03070-----END PGP SIGNATURE-----3071------------------------------------------------30723073See the linkgit:git-tag[1] command to learn how to create and verify tag3074objects. (Note that linkgit:git-tag[1] can also be used to create3075"lightweight tags", which are not tag objects at all, but just simple3076references whose names begin with "refs/tags/").30773078[[pack-files]]3079How git stores objects efficiently: pack files3080~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~30813082Newly created objects are initially created in a file named after the3083object's SHA1 hash (stored in .git/objects).30843085Unfortunately this system becomes inefficient once a project has a3086lot of objects. Try this on an old project:30873088------------------------------------------------3089$ git count-objects30906930 objects, 47620 kilobytes3091------------------------------------------------30923093The first number is the number of objects which are kept in3094individual files. The second is the amount of space taken up by3095those "loose" objects.30963097You can save space and make git faster by moving these loose objects in3098to a "pack file", which stores a group of objects in an efficient3099compressed format; the details of how pack files are formatted can be3100found in link:technical/pack-format.txt[technical/pack-format.txt].31013102To put the loose objects into a pack, just run git repack:31033104------------------------------------------------3105$ git repack3106Generating pack...3107Done counting 6020 objects.3108Deltifying 6020 objects.3109 100% (6020/6020) done3110Writing 6020 objects.3111 100% (6020/6020) done3112Total 6020, written 6020 (delta 4070), reused 0 (delta 0)3113Pack pack-3e54ad29d5b2e05838c75df582c65257b8d08e1c created.3114------------------------------------------------31153116You can then run31173118------------------------------------------------3119$ git prune3120------------------------------------------------31213122to remove any of the "loose" objects that are now contained in the3123pack. This will also remove any unreferenced objects (which may be3124created when, for example, you use "git-reset" to remove a commit).3125You can verify that the loose objects are gone by looking at the3126.git/objects directory or by running31273128------------------------------------------------3129$ git count-objects31300 objects, 0 kilobytes3131------------------------------------------------31323133Although the object files are gone, any commands that refer to those3134objects will work exactly as they did before.31353136The linkgit:git-gc[1] command performs packing, pruning, and more for3137you, so is normally the only high-level command you need.31383139[[dangling-objects]]3140Dangling objects3141~~~~~~~~~~~~~~~~31423143The linkgit:git-fsck[1] command will sometimes complain about dangling3144objects. They are not a problem.31453146The most common cause of dangling objects is that you've rebased a3147branch, or you have pulled from somebody else who rebased a branch--see3148<<cleaning-up-history>>. In that case, the old head of the original3149branch still exists, as does everything it pointed to. The branch3150pointer itself just doesn't, since you replaced it with another one.31513152There are also other situations that cause dangling objects. For3153example, a "dangling blob" may arise because you did a "git-add" of a3154file, but then, before you actually committed it and made it part of the3155bigger picture, you changed something else in that file and committed3156that *updated* thing--the old state that you added originally ends up3157not being pointed to by any commit or tree, so it's now a dangling blob3158object.31593160Similarly, when the "recursive" merge strategy runs, and finds that3161there are criss-cross merges and thus more than one merge base (which is3162fairly unusual, but it does happen), it will generate one temporary3163midway tree (or possibly even more, if you had lots of criss-crossing3164merges and more than two merge bases) as a temporary internal merge3165base, and again, those are real objects, but the end result will not end3166up pointing to them, so they end up "dangling" in your repository.31673168Generally, dangling objects aren't anything to worry about. They can3169even be very useful: if you screw something up, the dangling objects can3170be how you recover your old tree (say, you did a rebase, and realized3171that you really didn't want to--you can look at what dangling objects3172you have, and decide to reset your head to some old dangling state).31733174For commits, you can just use:31753176------------------------------------------------3177$ gitk <dangling-commit-sha-goes-here> --not --all3178------------------------------------------------31793180This asks for all the history reachable from the given commit but not3181from any branch, tag, or other reference. If you decide it's something3182you want, you can always create a new reference to it, e.g.,31833184------------------------------------------------3185$ git branch recovered-branch <dangling-commit-sha-goes-here>3186------------------------------------------------31873188For blobs and trees, you can't do the same, but you can still examine3189them. You can just do31903191------------------------------------------------3192$ git show <dangling-blob/tree-sha-goes-here>3193------------------------------------------------31943195to show what the contents of the blob were (or, for a tree, basically3196what the "ls" for that directory was), and that may give you some idea3197of what the operation was that left that dangling object.31983199Usually, dangling blobs and trees aren't very interesting. They're3200almost always the result of either being a half-way mergebase (the blob3201will often even have the conflict markers from a merge in it, if you3202have had conflicting merges that you fixed up by hand), or simply3203because you interrupted a "git-fetch" with ^C or something like that,3204leaving _some_ of the new objects in the object database, but just3205dangling and useless.32063207Anyway, once you are sure that you're not interested in any dangling3208state, you can just prune all unreachable objects:32093210------------------------------------------------3211$ git prune3212------------------------------------------------32133214and they'll be gone. But you should only run "git prune" on a quiescent3215repository--it's kind of like doing a filesystem fsck recovery: you3216don't want to do that while the filesystem is mounted.32173218(The same is true of "git-fsck" itself, btw, but since3219git-fsck never actually *changes* the repository, it just reports3220on what it found, git-fsck itself is never "dangerous" to run.3221Running it while somebody is actually changing the repository can cause3222confusing and scary messages, but it won't actually do anything bad. In3223contrast, running "git prune" while somebody is actively changing the3224repository is a *BAD* idea).32253226[[recovering-from-repository-corruption]]3227Recovering from repository corruption3228~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~32293230By design, git treats data trusted to it with caution. However, even in3231the absence of bugs in git itself, it is still possible that hardware or3232operating system errors could corrupt data.32333234The first defense against such problems is backups. You can back up a3235git directory using clone, or just using cp, tar, or any other backup3236mechanism.32373238As a last resort, you can search for the corrupted objects and attempt3239to replace them by hand. Back up your repository before attempting this3240in case you corrupt things even more in the process.32413242We'll assume that the problem is a single missing or corrupted blob,3243which is sometimes a solvable problem. (Recovering missing trees and3244especially commits is *much* harder).32453246Before starting, verify that there is corruption, and figure out where3247it is with linkgit:git-fsck[1]; this may be time-consuming.32483249Assume the output looks like this:32503251------------------------------------------------3252$ git fsck --full3253broken link from tree 2d9263c6d23595e7cb2a21e5ebbb53655278dff83254 to blob 4b9458b3786228369c63936db65827de3cc062003255missing blob 4b9458b3786228369c63936db65827de3cc062003256------------------------------------------------32573258(Typically there will be some "dangling object" messages too, but they3259aren't interesting.)32603261Now you know that blob 4b9458b3 is missing, and that the tree 2d9263c63262points to it. If you could find just one copy of that missing blob3263object, possibly in some other repository, you could move it into3264.git/objects/4b/9458b3... and be done. Suppose you can't. You can3265still examine the tree that pointed to it with linkgit:git-ls-tree[1],3266which might output something like:32673268------------------------------------------------3269$ git ls-tree 2d9263c6d23595e7cb2a21e5ebbb53655278dff83270100644 blob 8d14531846b95bfa3564b58ccfb7913a034323b8 .gitignore3271100644 blob ebf9bf84da0aab5ed944264a5db2a65fe3a3e883 .mailmap3272100644 blob ca442d313d86dc67e0a2e5d584b465bd382cbf5c COPYING3273...3274100644 blob 4b9458b3786228369c63936db65827de3cc06200 myfile3275...3276------------------------------------------------32773278So now you know that the missing blob was the data for a file named3279"myfile". And chances are you can also identify the directory--let's3280say it's in "somedirectory". If you're lucky the missing copy might be3281the same as the copy you have checked out in your working tree at3282"somedirectory/myfile"; you can test whether that's right with3283linkgit:git-hash-object[1]:32843285------------------------------------------------3286$ git hash-object -w somedirectory/myfile3287------------------------------------------------32883289which will create and store a blob object with the contents of3290somedirectory/myfile, and output the sha1 of that object. if you're3291extremely lucky it might be 4b9458b3786228369c63936db65827de3cc06200, in3292which case you've guessed right, and the corruption is fixed!32933294Otherwise, you need more information. How do you tell which version of3295the file has been lost?32963297The easiest way to do this is with:32983299------------------------------------------------3300$ git log --raw --all --full-history -- somedirectory/myfile3301------------------------------------------------33023303Because you're asking for raw output, you'll now get something like33043305------------------------------------------------3306commit abc3307Author:3308Date:3309...3310:100644 100644 4b9458b... newsha... M somedirectory/myfile331133123313commit xyz3314Author:3315Date:33163317...3318:100644 100644 oldsha... 4b9458b... M somedirectory/myfile3319------------------------------------------------33203321This tells you that the immediately preceding version of the file was3322"newsha", and that the immediately following version was "oldsha".3323You also know the commit messages that went with the change from oldsha3324to 4b9458b and with the change from 4b9458b to newsha.33253326If you've been committing small enough changes, you may now have a good3327shot at reconstructing the contents of the in-between state 4b9458b.33283329If you can do that, you can now recreate the missing object with33303331------------------------------------------------3332$ git hash-object -w <recreated-file>3333------------------------------------------------33343335and your repository is good again!33363337(Btw, you could have ignored the fsck, and started with doing a33383339------------------------------------------------3340$ git log --raw --all3341------------------------------------------------33423343and just looked for the sha of the missing object (4b9458b..) in that3344whole thing. It's up to you - git does *have* a lot of information, it is3345just missing one particular blob version.33463347[[the-index]]3348The index3349-----------33503351The index is a binary file (generally kept in .git/index) containing a3352sorted list of path names, each with permissions and the SHA1 of a blob3353object; linkgit:git-ls-files[1] can show you the contents of the index:33543355-------------------------------------------------3356$ git ls-files --stage3357100644 63c918c667fa005ff12ad89437f2fdc80926e21c 0 .gitignore3358100644 5529b198e8d14decbe4ad99db3f7fb632de0439d 0 .mailmap3359100644 6ff87c4664981e4397625791c8ea3bbb5f2279a3 0 COPYING3360100644 a37b2152bd26be2c2289e1f57a292534a51a93c7 0 Documentation/.gitignore3361100644 fbefe9a45b00a54b58d94d06eca48b03d40a50e0 0 Documentation/Makefile3362...3363100644 2511aef8d89ab52be5ec6a5e46236b4b6bcd07ea 0 xdiff/xtypes.h3364100644 2ade97b2574a9f77e7ae4002a4e07a6a38e46d07 0 xdiff/xutils.c3365100644 d5de8292e05e7c36c4b68857c1cf9855e3d2f70a 0 xdiff/xutils.h3366-------------------------------------------------33673368Note that in older documentation you may see the index called the3369"current directory cache" or just the "cache". It has three important3370properties:337133721. The index contains all the information necessary to generate a single3373(uniquely determined) tree object.3374+3375For example, running linkgit:git-commit[1] generates this tree object3376from the index, stores it in the object database, and uses it as the3377tree object associated with the new commit.337833792. The index enables fast comparisons between the tree object it defines3380and the working tree.3381+3382It does this by storing some additional data for each entry (such as3383the last modified time). This data is not displayed above, and is not3384stored in the created tree object, but it can be used to determine3385quickly which files in the working directory differ from what was3386stored in the index, and thus save git from having to read all of the3387data from such files to look for changes.338833893. It can efficiently represent information about merge conflicts3390between different tree objects, allowing each pathname to be3391associated with sufficient information about the trees involved that3392you can create a three-way merge between them.3393+3394We saw in <<conflict-resolution>> that during a merge the index can3395store multiple versions of a single file (called "stages"). The third3396column in the linkgit:git-ls-files[1] output above is the stage3397number, and will take on values other than 0 for files with merge3398conflicts.33993400The index is thus a sort of temporary staging area, which is filled with3401a tree which you are in the process of working on.34023403If you blow the index away entirely, you generally haven't lost any3404information as long as you have the name of the tree that it described.34053406[[submodules]]3407Submodules3408==========34093410Large projects are often composed of smaller, self-contained modules. For3411example, an embedded Linux distribution's source tree would include every3412piece of software in the distribution with some local modifications; a movie3413player might need to build against a specific, known-working version of a3414decompression library; several independent programs might all share the same3415build scripts.34163417With centralized revision control systems this is often accomplished by3418including every module in one single repository. Developers can check out3419all modules or only the modules they need to work with. They can even modify3420files across several modules in a single commit while moving things around3421or updating APIs and translations.34223423Git does not allow partial checkouts, so duplicating this approach in Git3424would force developers to keep a local copy of modules they are not3425interested in touching. Commits in an enormous checkout would be slower3426than you'd expect as Git would have to scan every directory for changes.3427If modules have a lot of local history, clones would take forever.34283429On the plus side, distributed revision control systems can much better3430integrate with external sources. In a centralized model, a single arbitrary3431snapshot of the external project is exported from its own revision control3432and then imported into the local revision control on a vendor branch. All3433the history is hidden. With distributed revision control you can clone the3434entire external history and much more easily follow development and re-merge3435local changes.34363437Git's submodule support allows a repository to contain, as a subdirectory, a3438checkout of an external project. Submodules maintain their own identity;3439the submodule support just stores the submodule repository location and3440commit ID, so other developers who clone the containing project3441("superproject") can easily clone all the submodules at the same revision.3442Partial checkouts of the superproject are possible: you can tell Git to3443clone none, some or all of the submodules.34443445The linkgit:git-submodule[1] command is available since Git 1.5.3. Users3446with Git 1.5.2 can look up the submodule commits in the repository and3447manually check them out; earlier versions won't recognize the submodules at3448all.34493450To see how submodule support works, create (for example) four example3451repositories that can be used later as a submodule:34523453-------------------------------------------------3454$ mkdir ~/git3455$ cd ~/git3456$ for i in a b c d3457do3458 mkdir $i3459 cd $i3460 git init3461 echo "module $i" > $i.txt3462 git add $i.txt3463 git commit -m "Initial commit, submodule $i"3464 cd ..3465done3466-------------------------------------------------34673468Now create the superproject and add all the submodules:34693470-------------------------------------------------3471$ mkdir super3472$ cd super3473$ git init3474$ for i in a b c d3475do3476 git submodule add ~/git/$i $i3477done3478-------------------------------------------------34793480NOTE: Do not use local URLs here if you plan to publish your superproject!34813482See what files `git-submodule` created:34833484-------------------------------------------------3485$ ls -a3486. .. .git .gitmodules a b c d3487-------------------------------------------------34883489The `git-submodule add <repo> <path>` command does a couple of things:34903491- It clones the submodule from <repo> to the given <path> under the3492 current directory and by default checks out the master branch.3493- It adds the submodule's clone path to the linkgit:gitmodules[5] file and3494 adds this file to the index, ready to be committed.3495- It adds the submodule's current commit ID to the index, ready to be3496 committed.34973498Commit the superproject:34993500-------------------------------------------------3501$ git commit -m "Add submodules a, b, c and d."3502-------------------------------------------------35033504Now clone the superproject:35053506-------------------------------------------------3507$ cd ..3508$ git clone super cloned3509$ cd cloned3510-------------------------------------------------35113512The submodule directories are there, but they're empty:35133514-------------------------------------------------3515$ ls -a a3516. ..3517$ git submodule status3518-d266b9873ad50488163457f025db7cdd9683d88b a3519-e81d457da15309b4fef4249aba9b50187999670d b3520-c1536a972b9affea0f16e0680ba87332dc059146 c3521-d96249ff5d57de5de093e6baff9e0aafa5276a74 d3522-------------------------------------------------35233524NOTE: The commit object names shown above would be different for you, but they3525should match the HEAD commit object names of your repositories. You can check3526it by running `git ls-remote ../a`.35273528Pulling down the submodules is a two-step process. First run `git submodule3529init` to add the submodule repository URLs to `.git/config`:35303531-------------------------------------------------3532$ git submodule init3533-------------------------------------------------35343535Now use `git-submodule update` to clone the repositories and check out the3536commits specified in the superproject:35373538-------------------------------------------------3539$ git submodule update3540$ cd a3541$ ls -a3542. .. .git a.txt3543-------------------------------------------------35443545One major difference between `git-submodule update` and `git-submodule add` is3546that `git-submodule update` checks out a specific commit, rather than the tip3547of a branch. It's like checking out a tag: the head is detached, so you're not3548working on a branch.35493550-------------------------------------------------3551$ git branch3552* (no branch)3553 master3554-------------------------------------------------35553556If you want to make a change within a submodule and you have a detached head,3557then you should create or checkout a branch, make your changes, publish the3558change within the submodule, and then update the superproject to reference the3559new commit:35603561-------------------------------------------------3562$ git checkout master3563-------------------------------------------------35643565or35663567-------------------------------------------------3568$ git checkout -b fix-up3569-------------------------------------------------35703571then35723573-------------------------------------------------3574$ echo "adding a line again" >> a.txt3575$ git commit -a -m "Updated the submodule from within the superproject."3576$ git push3577$ cd ..3578$ git diff3579diff --git a/a b/a3580index d266b98..261dfac 1600003581--- a/a3582+++ b/a3583@@ -1 +1 @@3584-Subproject commit d266b9873ad50488163457f025db7cdd9683d88b3585+Subproject commit 261dfac35cb99d380eb966e102c1197139f7fa243586$ git add a3587$ git commit -m "Updated submodule a."3588$ git push3589-------------------------------------------------35903591You have to run `git submodule update` after `git pull` if you want to update3592submodules, too.35933594Pitfalls with submodules3595------------------------35963597Always publish the submodule change before publishing the change to the3598superproject that references it. If you forget to publish the submodule change,3599others won't be able to clone the repository:36003601-------------------------------------------------3602$ cd ~/git/super/a3603$ echo i added another line to this file >> a.txt3604$ git commit -a -m "doing it wrong this time"3605$ cd ..3606$ git add a3607$ git commit -m "Updated submodule a again."3608$ git push3609$ cd ~/git/cloned3610$ git pull3611$ git submodule update3612error: pathspec '261dfac35cb99d380eb966e102c1197139f7fa24' did not match any file(s) known to git.3613Did you forget to 'git add'?3614Unable to checkout '261dfac35cb99d380eb966e102c1197139f7fa24' in submodule path 'a'3615-------------------------------------------------36163617You also should not rewind branches in a submodule beyond commits that were3618ever recorded in any superproject.36193620It's not safe to run `git submodule update` if you've made and committed3621changes within a submodule without checking out a branch first. They will be3622silently overwritten:36233624-------------------------------------------------3625$ cat a.txt3626module a3627$ echo line added from private2 >> a.txt3628$ git commit -a -m "line added inside private2"3629$ cd ..3630$ git submodule update3631Submodule path 'a': checked out 'd266b9873ad50488163457f025db7cdd9683d88b'3632$ cd a3633$ cat a.txt3634module a3635-------------------------------------------------36363637NOTE: The changes are still visible in the submodule's reflog.36383639This is not the case if you did not commit your changes.36403641[[low-level-operations]]3642Low-level git operations3643========================36443645Many of the higher-level commands were originally implemented as shell3646scripts using a smaller core of low-level git commands. These can still3647be useful when doing unusual things with git, or just as a way to3648understand its inner workings.36493650[[object-manipulation]]3651Object access and manipulation3652------------------------------36533654The linkgit:git-cat-file[1] command can show the contents of any object,3655though the higher-level linkgit:git-show[1] is usually more useful.36563657The linkgit:git-commit-tree[1] command allows constructing commits with3658arbitrary parents and trees.36593660A tree can be created with linkgit:git-write-tree[1] and its data can be3661accessed by linkgit:git-ls-tree[1]. Two trees can be compared with3662linkgit:git-diff-tree[1].36633664A tag is created with linkgit:git-mktag[1], and the signature can be3665verified by linkgit:git-verify-tag[1], though it is normally simpler to3666use linkgit:git-tag[1] for both.36673668[[the-workflow]]3669The Workflow3670------------36713672High-level operations such as linkgit:git-commit[1],3673linkgit:git-checkout[1] and linkgit:git-reset[1] work by moving data3674between the working tree, the index, and the object database. Git3675provides low-level operations which perform each of these steps3676individually.36773678Generally, all "git" operations work on the index file. Some operations3679work *purely* on the index file (showing the current state of the3680index), but most operations move data between the index file and either3681the database or the working directory. Thus there are four main3682combinations:36833684[[working-directory-to-index]]3685working directory -> index3686~~~~~~~~~~~~~~~~~~~~~~~~~~36873688The linkgit:git-update-index[1] command updates the index with3689information from the working directory. You generally update the3690index information by just specifying the filename you want to update,3691like so:36923693-------------------------------------------------3694$ git update-index filename3695-------------------------------------------------36963697but to avoid common mistakes with filename globbing etc, the command3698will not normally add totally new entries or remove old entries,3699i.e. it will normally just update existing cache entries.37003701To tell git that yes, you really do realize that certain files no3702longer exist, or that new files should be added, you3703should use the `--remove` and `--add` flags respectively.37043705NOTE! A `--remove` flag does 'not' mean that subsequent filenames will3706necessarily be removed: if the files still exist in your directory3707structure, the index will be updated with their new status, not3708removed. The only thing `--remove` means is that update-index will be3709considering a removed file to be a valid thing, and if the file really3710does not exist any more, it will update the index accordingly.37113712As a special case, you can also do `git update-index --refresh`, which3713will refresh the "stat" information of each index to match the current3714stat information. It will 'not' update the object status itself, and3715it will only update the fields that are used to quickly test whether3716an object still matches its old backing store object.37173718The previously introduced linkgit:git-add[1] is just a wrapper for3719linkgit:git-update-index[1].37203721[[index-to-object-database]]3722index -> object database3723~~~~~~~~~~~~~~~~~~~~~~~~37243725You write your current index file to a "tree" object with the program37263727-------------------------------------------------3728$ git write-tree3729-------------------------------------------------37303731that doesn't come with any options--it will just write out the3732current index into the set of tree objects that describe that state,3733and it will return the name of the resulting top-level tree. You can3734use that tree to re-generate the index at any time by going in the3735other direction:37363737[[object-database-to-index]]3738object database -> index3739~~~~~~~~~~~~~~~~~~~~~~~~37403741You read a "tree" file from the object database, and use that to3742populate (and overwrite--don't do this if your index contains any3743unsaved state that you might want to restore later!) your current3744index. Normal operation is just37453746-------------------------------------------------3747$ git read-tree <sha1 of tree>3748-------------------------------------------------37493750and your index file will now be equivalent to the tree that you saved3751earlier. However, that is only your 'index' file: your working3752directory contents have not been modified.37533754[[index-to-working-directory]]3755index -> working directory3756~~~~~~~~~~~~~~~~~~~~~~~~~~37573758You update your working directory from the index by "checking out"3759files. This is not a very common operation, since normally you'd just3760keep your files updated, and rather than write to your working3761directory, you'd tell the index files about the changes in your3762working directory (i.e. `git-update-index`).37633764However, if you decide to jump to a new version, or check out somebody3765else's version, or just restore a previous tree, you'd populate your3766index file with read-tree, and then you need to check out the result3767with37683769-------------------------------------------------3770$ git checkout-index filename3771-------------------------------------------------37723773or, if you want to check out all of the index, use `-a`.37743775NOTE! git-checkout-index normally refuses to overwrite old files, so3776if you have an old version of the tree already checked out, you will3777need to use the "-f" flag ('before' the "-a" flag or the filename) to3778'force' the checkout.377937803781Finally, there are a few odds and ends which are not purely moving3782from one representation to the other:37833784[[tying-it-all-together]]3785Tying it all together3786~~~~~~~~~~~~~~~~~~~~~37873788To commit a tree you have instantiated with "git write-tree", you'd3789create a "commit" object that refers to that tree and the history3790behind it--most notably the "parent" commits that preceded it in3791history.37923793Normally a "commit" has one parent: the previous state of the tree3794before a certain change was made. However, sometimes it can have two3795or more parent commits, in which case we call it a "merge", due to the3796fact that such a commit brings together ("merges") two or more3797previous states represented by other commits.37983799In other words, while a "tree" represents a particular directory state3800of a working directory, a "commit" represents that state in "time",3801and explains how we got there.38023803You create a commit object by giving it the tree that describes the3804state at the time of the commit, and a list of parents:38053806-------------------------------------------------3807$ git commit-tree <tree> -p <parent> [-p <parent2> ..]3808-------------------------------------------------38093810and then giving the reason for the commit on stdin (either through3811redirection from a pipe or file, or by just typing it at the tty).38123813git-commit-tree will return the name of the object that represents3814that commit, and you should save it away for later use. Normally,3815you'd commit a new `HEAD` state, and while git doesn't care where you3816save the note about that state, in practice we tend to just write the3817result to the file pointed at by `.git/HEAD`, so that we can always see3818what the last committed state was.38193820Here is an ASCII art by Jon Loeliger that illustrates how3821various pieces fit together.38223823------------38243825 commit-tree3826 commit obj3827 +----+3828 | |3829 | |3830 V V3831 +-----------+3832 | Object DB |3833 | Backing |3834 | Store |3835 +-----------+3836 ^3837 write-tree | |3838 tree obj | |3839 | | read-tree3840 | | tree obj3841 V3842 +-----------+3843 | Index |3844 | "cache" |3845 +-----------+3846 update-index ^3847 blob obj | |3848 | |3849 checkout-index -u | | checkout-index3850 stat | | blob obj3851 V3852 +-----------+3853 | Working |3854 | Directory |3855 +-----------+38563857------------385838593860[[examining-the-data]]3861Examining the data3862------------------38633864You can examine the data represented in the object database and the3865index with various helper tools. For every object, you can use3866linkgit:git-cat-file[1] to examine details about the3867object:38683869-------------------------------------------------3870$ git cat-file -t <objectname>3871-------------------------------------------------38723873shows the type of the object, and once you have the type (which is3874usually implicit in where you find the object), you can use38753876-------------------------------------------------3877$ git cat-file blob|tree|commit|tag <objectname>3878-------------------------------------------------38793880to show its contents. NOTE! Trees have binary content, and as a result3881there is a special helper for showing that content, called3882`git-ls-tree`, which turns the binary content into a more easily3883readable form.38843885It's especially instructive to look at "commit" objects, since those3886tend to be small and fairly self-explanatory. In particular, if you3887follow the convention of having the top commit name in `.git/HEAD`,3888you can do38893890-------------------------------------------------3891$ git cat-file commit HEAD3892-------------------------------------------------38933894to see what the top commit was.38953896[[merging-multiple-trees]]3897Merging multiple trees3898----------------------38993900Git helps you do a three-way merge, which you can expand to n-way by3901repeating the merge procedure arbitrary times until you finally3902"commit" the state. The normal situation is that you'd only do one3903three-way merge (two parents), and commit it, but if you like to, you3904can do multiple parents in one go.39053906To do a three-way merge, you need the two sets of "commit" objects3907that you want to merge, use those to find the closest common parent (a3908third "commit" object), and then use those commit objects to find the3909state of the directory ("tree" object) at these points.39103911To get the "base" for the merge, you first look up the common parent3912of two commits with39133914-------------------------------------------------3915$ git merge-base <commit1> <commit2>3916-------------------------------------------------39173918which will return you the commit they are both based on. You should3919now look up the "tree" objects of those commits, which you can easily3920do with (for example)39213922-------------------------------------------------3923$ git cat-file commit <commitname> | head -13924-------------------------------------------------39253926since the tree object information is always the first line in a commit3927object.39283929Once you know the three trees you are going to merge (the one "original"3930tree, aka the common tree, and the two "result" trees, aka the branches3931you want to merge), you do a "merge" read into the index. This will3932complain if it has to throw away your old index contents, so you should3933make sure that you've committed those--in fact you would normally3934always do a merge against your last commit (which should thus match what3935you have in your current index anyway).39363937To do the merge, do39383939-------------------------------------------------3940$ git read-tree -m -u <origtree> <yourtree> <targettree>3941-------------------------------------------------39423943which will do all trivial merge operations for you directly in the3944index file, and you can just write the result out with3945`git write-tree`.394639473948[[merging-multiple-trees-2]]3949Merging multiple trees, continued3950---------------------------------39513952Sadly, many merges aren't trivial. If there are files that have3953been added, moved or removed, or if both branches have modified the3954same file, you will be left with an index tree that contains "merge3955entries" in it. Such an index tree can 'NOT' be written out to a tree3956object, and you will have to resolve any such merge clashes using3957other tools before you can write out the result.39583959You can examine such index state with `git ls-files --unmerged`3960command. An example:39613962------------------------------------------------3963$ git read-tree -m $orig HEAD $target3964$ git ls-files --unmerged3965100644 263414f423d0e4d70dae8fe53fa34614ff3e2860 1 hello.c3966100644 06fa6a24256dc7e560efa5687fa84b51f0263c3a 2 hello.c3967100644 cc44c73eb783565da5831b4d820c962954019b69 3 hello.c3968------------------------------------------------39693970Each line of the `git ls-files --unmerged` output begins with3971the blob mode bits, blob SHA1, 'stage number', and the3972filename. The 'stage number' is git's way to say which tree it3973came from: stage 1 corresponds to `$orig` tree, stage 2 `HEAD`3974tree, and stage3 `$target` tree.39753976Earlier we said that trivial merges are done inside3977`git-read-tree -m`. For example, if the file did not change3978from `$orig` to `HEAD` nor `$target`, or if the file changed3979from `$orig` to `HEAD` and `$orig` to `$target` the same way,3980obviously the final outcome is what is in `HEAD`. What the3981above example shows is that file `hello.c` was changed from3982`$orig` to `HEAD` and `$orig` to `$target` in a different way.3983You could resolve this by running your favorite 3-way merge3984program, e.g. `diff3`, `merge`, or git's own merge-file, on3985the blob objects from these three stages yourself, like this:39863987------------------------------------------------3988$ git cat-file blob 263414f... >hello.c~13989$ git cat-file blob 06fa6a2... >hello.c~23990$ git cat-file blob cc44c73... >hello.c~33991$ git merge-file hello.c~2 hello.c~1 hello.c~33992------------------------------------------------39933994This would leave the merge result in `hello.c~2` file, along3995with conflict markers if there are conflicts. After verifying3996the merge result makes sense, you can tell git what the final3997merge result for this file is by:39983999-------------------------------------------------4000$ mv -f hello.c~2 hello.c4001$ git update-index hello.c4002-------------------------------------------------40034004When a path is in the "unmerged" state, running `git-update-index` for4005that path tells git to mark the path resolved.40064007The above is the description of a git merge at the lowest level,4008to help you understand what conceptually happens under the hood.4009In practice, nobody, not even git itself, runs `git-cat-file` three times4010for this. There is a `git-merge-index` program that extracts the4011stages to temporary files and calls a "merge" script on it:40124013-------------------------------------------------4014$ git merge-index git-merge-one-file hello.c4015-------------------------------------------------40164017and that is what higher level `git-merge -s resolve` is implemented with.40184019[[hacking-git]]4020Hacking git4021===========40224023This chapter covers internal details of the git implementation which4024probably only git developers need to understand.40254026[[object-details]]4027Object storage format4028---------------------40294030All objects have a statically determined "type" which identifies the4031format of the object (i.e. how it is used, and how it can refer to other4032objects). There are currently four different object types: "blob",4033"tree", "commit", and "tag".40344035Regardless of object type, all objects share the following4036characteristics: they are all deflated with zlib, and have a header4037that not only specifies their type, but also provides size information4038about the data in the object. It's worth noting that the SHA1 hash4039that is used to name the object is the hash of the original data4040plus this header, so `sha1sum` 'file' does not match the object name4041for 'file'.4042(Historical note: in the dawn of the age of git the hash4043was the sha1 of the 'compressed' object.)40444045As a result, the general consistency of an object can always be tested4046independently of the contents or the type of the object: all objects can4047be validated by verifying that (a) their hashes match the content of the4048file and (b) the object successfully inflates to a stream of bytes that4049forms a sequence of <ascii type without space> {plus} <space> {plus} <ascii decimal4050size> {plus} <byte\0> {plus} <binary object data>.40514052The structured objects can further have their structure and4053connectivity to other objects verified. This is generally done with4054the `git-fsck` program, which generates a full dependency graph4055of all objects, and verifies their internal consistency (in addition4056to just verifying their superficial consistency through the hash).40574058[[birdview-on-the-source-code]]4059A birds-eye view of Git's source code4060-------------------------------------40614062It is not always easy for new developers to find their way through Git's4063source code. This section gives you a little guidance to show where to4064start.40654066A good place to start is with the contents of the initial commit, with:40674068----------------------------------------------------4069$ git checkout e83c51634070----------------------------------------------------40714072The initial revision lays the foundation for almost everything git has4073today, but is small enough to read in one sitting.40744075Note that terminology has changed since that revision. For example, the4076README in that revision uses the word "changeset" to describe what we4077now call a <<def_commit_object,commit>>.40784079Also, we do not call it "cache" any more, but rather "index"; however, the4080file is still called `cache.h`. Remark: Not much reason to change it now,4081especially since there is no good single name for it anyway, because it is4082basically _the_ header file which is included by _all_ of Git's C sources.40834084If you grasp the ideas in that initial commit, you should check out a4085more recent version and skim `cache.h`, `object.h` and `commit.h`.40864087In the early days, Git (in the tradition of UNIX) was a bunch of programs4088which were extremely simple, and which you used in scripts, piping the4089output of one into another. This turned out to be good for initial4090development, since it was easier to test new things. However, recently4091many of these parts have become builtins, and some of the core has been4092"libified", i.e. put into libgit.a for performance, portability reasons,4093and to avoid code duplication.40944095By now, you know what the index is (and find the corresponding data4096structures in `cache.h`), and that there are just a couple of object types4097(blobs, trees, commits and tags) which inherit their common structure from4098`struct object`, which is their first member (and thus, you can cast e.g.4099`(struct object *)commit` to achieve the _same_ as `&commit->object`, i.e.4100get at the object name and flags).41014102Now is a good point to take a break to let this information sink in.41034104Next step: get familiar with the object naming. Read <<naming-commits>>.4105There are quite a few ways to name an object (and not only revisions!).4106All of these are handled in `sha1_name.c`. Just have a quick look at4107the function `get_sha1()`. A lot of the special handling is done by4108functions like `get_sha1_basic()` or the likes.41094110This is just to get you into the groove for the most libified part of Git:4111the revision walker.41124113Basically, the initial version of `git-log` was a shell script:41144115----------------------------------------------------------------4116$ git-rev-list --pretty $(git-rev-parse --default HEAD "$@") | \4117 LESS=-S ${PAGER:-less}4118----------------------------------------------------------------41194120What does this mean?41214122`git-rev-list` is the original version of the revision walker, which4123_always_ printed a list of revisions to stdout. It is still functional,4124and needs to, since most new Git programs start out as scripts using4125`git-rev-list`.41264127`git-rev-parse` is not as important any more; it was only used to filter out4128options that were relevant for the different plumbing commands that were4129called by the script.41304131Most of what `git-rev-list` did is contained in `revision.c` and4132`revision.h`. It wraps the options in a struct named `rev_info`, which4133controls how and what revisions are walked, and more.41344135The original job of `git-rev-parse` is now taken by the function4136`setup_revisions()`, which parses the revisions and the common command line4137options for the revision walker. This information is stored in the struct4138`rev_info` for later consumption. You can do your own command line option4139parsing after calling `setup_revisions()`. After that, you have to call4140`prepare_revision_walk()` for initialization, and then you can get the4141commits one by one with the function `get_revision()`.41424143If you are interested in more details of the revision walking process,4144just have a look at the first implementation of `cmd_log()`; call4145`git show v1.3.0{tilde}155^2{tilde}4` and scroll down to that function (note that you4146no longer need to call `setup_pager()` directly).41474148Nowadays, `git-log` is a builtin, which means that it is _contained_ in the4149command `git`. The source side of a builtin is41504151- a function called `cmd_<bla>`, typically defined in `builtin-<bla>.c`,4152 and declared in `builtin.h`,41534154- an entry in the `commands[]` array in `git.c`, and41554156- an entry in `BUILTIN_OBJECTS` in the `Makefile`.41574158Sometimes, more than one builtin is contained in one source file. For4159example, `cmd_whatchanged()` and `cmd_log()` both reside in `builtin-log.c`,4160since they share quite a bit of code. In that case, the commands which are4161_not_ named like the `.c` file in which they live have to be listed in4162`BUILT_INS` in the `Makefile`.41634164`git-log` looks more complicated in C than it does in the original script,4165but that allows for a much greater flexibility and performance.41664167Here again it is a good point to take a pause.41684169Lesson three is: study the code. Really, it is the best way to learn about4170the organization of Git (after you know the basic concepts).41714172So, think about something which you are interested in, say, "how can I4173access a blob just knowing the object name of it?". The first step is to4174find a Git command with which you can do it. In this example, it is either4175`git-show` or `git-cat-file`.41764177For the sake of clarity, let's stay with `git-cat-file`, because it41784179- is plumbing, and41804181- was around even in the initial commit (it literally went only through4182 some 20 revisions as `cat-file.c`, was renamed to `builtin-cat-file.c`4183 when made a builtin, and then saw less than 10 versions).41844185So, look into `builtin-cat-file.c`, search for `cmd_cat_file()` and look what4186it does.41874188------------------------------------------------------------------4189 git_config(git_default_config);4190 if (argc != 3)4191 usage("git-cat-file [-t|-s|-e|-p|<type>] <sha1>");4192 if (get_sha1(argv[2], sha1))4193 die("Not a valid object name %s", argv[2]);4194------------------------------------------------------------------41954196Let's skip over the obvious details; the only really interesting part4197here is the call to `get_sha1()`. It tries to interpret `argv[2]` as an4198object name, and if it refers to an object which is present in the current4199repository, it writes the resulting SHA-1 into the variable `sha1`.42004201Two things are interesting here:42024203- `get_sha1()` returns 0 on _success_. This might surprise some new4204 Git hackers, but there is a long tradition in UNIX to return different4205 negative numbers in case of different errors--and 0 on success.42064207- the variable `sha1` in the function signature of `get_sha1()` is `unsigned4208 char \*`, but is actually expected to be a pointer to `unsigned4209 char[20]`. This variable will contain the 160-bit SHA-1 of the given4210 commit. Note that whenever a SHA-1 is passed as `unsigned char \*`, it4211 is the binary representation, as opposed to the ASCII representation in4212 hex characters, which is passed as `char *`.42134214You will see both of these things throughout the code.42154216Now, for the meat:42174218-----------------------------------------------------------------------------4219 case 0:4220 buf = read_object_with_reference(sha1, argv[1], &size, NULL);4221-----------------------------------------------------------------------------42224223This is how you read a blob (actually, not only a blob, but any type of4224object). To know how the function `read_object_with_reference()` actually4225works, find the source code for it (something like `git grep4226read_object_with | grep ":[a-z]"` in the git repository), and read4227the source.42284229To find out how the result can be used, just read on in `cmd_cat_file()`:42304231-----------------------------------4232 write_or_die(1, buf, size);4233-----------------------------------42344235Sometimes, you do not know where to look for a feature. In many such cases,4236it helps to search through the output of `git log`, and then `git-show` the4237corresponding commit.42384239Example: If you know that there was some test case for `git-bundle`, but4240do not remember where it was (yes, you _could_ `git grep bundle t/`, but that4241does not illustrate the point!):42424243------------------------4244$ git log --no-merges t/4245------------------------42464247In the pager (`less`), just search for "bundle", go a few lines back,4248and see that it is in commit 18449ab0... Now just copy this object name,4249and paste it into the command line42504251-------------------4252$ git show 18449ab04253-------------------42544255Voila.42564257Another example: Find out what to do in order to make some script a4258builtin:42594260-------------------------------------------------4261$ git log --no-merges --diff-filter=A builtin-*.c4262-------------------------------------------------42634264You see, Git is actually the best tool to find out about the source of Git4265itself!42664267[[glossary]]4268GIT Glossary4269============42704271include::glossary-content.txt[]42724273[[git-quick-start]]4274Appendix A: Git Quick Reference4275===============================42764277This is a quick summary of the major commands; the previous chapters4278explain how these work in more detail.42794280[[quick-creating-a-new-repository]]4281Creating a new repository4282-------------------------42834284From a tarball:42854286-----------------------------------------------4287$ tar xzf project.tar.gz4288$ cd project4289$ git init4290Initialized empty Git repository in .git/4291$ git add .4292$ git commit4293-----------------------------------------------42944295From a remote repository:42964297-----------------------------------------------4298$ git clone git://example.com/pub/project.git4299$ cd project4300-----------------------------------------------43014302[[managing-branches]]4303Managing branches4304-----------------43054306-----------------------------------------------4307$ git branch # list all local branches in this repo4308$ git checkout test # switch working directory to branch "test"4309$ git branch new # create branch "new" starting at current HEAD4310$ git branch -d new # delete branch "new"4311-----------------------------------------------43124313Instead of basing a new branch on current HEAD (the default), use:43144315-----------------------------------------------4316$ git branch new test # branch named "test"4317$ git branch new v2.6.15 # tag named v2.6.154318$ git branch new HEAD^ # commit before the most recent4319$ git branch new HEAD^^ # commit before that4320$ git branch new test~10 # ten commits before tip of branch "test"4321-----------------------------------------------43224323Create and switch to a new branch at the same time:43244325-----------------------------------------------4326$ git checkout -b new v2.6.154327-----------------------------------------------43284329Update and examine branches from the repository you cloned from:43304331-----------------------------------------------4332$ git fetch # update4333$ git branch -r # list4334 origin/master4335 origin/next4336 ...4337$ git checkout -b masterwork origin/master4338-----------------------------------------------43394340Fetch a branch from a different repository, and give it a new4341name in your repository:43424343-----------------------------------------------4344$ git fetch git://example.com/project.git theirbranch:mybranch4345$ git fetch git://example.com/project.git v2.6.15:mybranch4346-----------------------------------------------43474348Keep a list of repositories you work with regularly:43494350-----------------------------------------------4351$ git remote add example git://example.com/project.git4352$ git remote # list remote repositories4353example4354origin4355$ git remote show example # get details4356* remote example4357 URL: git://example.com/project.git4358 Tracked remote branches4359 master next ...4360$ git fetch example # update branches from example4361$ git branch -r # list all remote branches4362-----------------------------------------------436343644365[[exploring-history]]4366Exploring history4367-----------------43684369-----------------------------------------------4370$ gitk # visualize and browse history4371$ git log # list all commits4372$ git log src/ # ...modifying src/4373$ git log v2.6.15..v2.6.16 # ...in v2.6.16, not in v2.6.154374$ git log master..test # ...in branch test, not in branch master4375$ git log test..master # ...in branch master, but not in test4376$ git log test...master # ...in one branch, not in both4377$ git log -S'foo()' # ...where difference contain "foo()"4378$ git log --since="2 weeks ago"4379$ git log -p # show patches as well4380$ git show # most recent commit4381$ git diff v2.6.15..v2.6.16 # diff between two tagged versions4382$ git diff v2.6.15..HEAD # diff with current head4383$ git grep "foo()" # search working directory for "foo()"4384$ git grep v2.6.15 "foo()" # search old tree for "foo()"4385$ git show v2.6.15:a.txt # look at old version of a.txt4386-----------------------------------------------43874388Search for regressions:43894390-----------------------------------------------4391$ git bisect start4392$ git bisect bad # current version is bad4393$ git bisect good v2.6.13-rc2 # last known good revision4394Bisecting: 675 revisions left to test after this4395 # test here, then:4396$ git bisect good # if this revision is good, or4397$ git bisect bad # if this revision is bad.4398 # repeat until done.4399-----------------------------------------------44004401[[making-changes]]4402Making changes4403--------------44044405Make sure git knows who to blame:44064407------------------------------------------------4408$ cat >>~/.gitconfig <<\EOF4409[user]4410 name = Your Name Comes Here4411 email = you@yourdomain.example.com4412EOF4413------------------------------------------------44144415Select file contents to include in the next commit, then make the4416commit:44174418-----------------------------------------------4419$ git add a.txt # updated file4420$ git add b.txt # new file4421$ git rm c.txt # old file4422$ git commit4423-----------------------------------------------44244425Or, prepare and create the commit in one step:44264427-----------------------------------------------4428$ git commit d.txt # use latest content only of d.txt4429$ git commit -a # use latest content of all tracked files4430-----------------------------------------------44314432[[merging]]4433Merging4434-------44354436-----------------------------------------------4437$ git merge test # merge branch "test" into the current branch4438$ git pull git://example.com/project.git master4439 # fetch and merge in remote branch4440$ git pull . test # equivalent to git merge test4441-----------------------------------------------44424443[[sharing-your-changes]]4444Sharing your changes4445--------------------44464447Importing or exporting patches:44484449-----------------------------------------------4450$ git format-patch origin..HEAD # format a patch for each commit4451 # in HEAD but not in origin4452$ git am mbox # import patches from the mailbox "mbox"4453-----------------------------------------------44544455Fetch a branch in a different git repository, then merge into the4456current branch:44574458-----------------------------------------------4459$ git pull git://example.com/project.git theirbranch4460-----------------------------------------------44614462Store the fetched branch into a local branch before merging into the4463current branch:44644465-----------------------------------------------4466$ git pull git://example.com/project.git theirbranch:mybranch4467-----------------------------------------------44684469After creating commits on a local branch, update the remote4470branch with your commits:44714472-----------------------------------------------4473$ git push ssh://example.com/project.git mybranch:theirbranch4474-----------------------------------------------44754476When remote and local branch are both named "test":44774478-----------------------------------------------4479$ git push ssh://example.com/project.git test4480-----------------------------------------------44814482Shortcut version for a frequently used remote repository:44834484-----------------------------------------------4485$ git remote add example ssh://example.com/project.git4486$ git push example test4487-----------------------------------------------44884489[[repository-maintenance]]4490Repository maintenance4491----------------------44924493Check for corruption:44944495-----------------------------------------------4496$ git fsck4497-----------------------------------------------44984499Recompress, remove unused cruft:45004501-----------------------------------------------4502$ git gc4503-----------------------------------------------450445054506[[todo]]4507Appendix B: Notes and todo list for this manual4508===============================================45094510This is a work in progress.45114512The basic requirements:45134514- It must be readable in order, from beginning to end, by someone4515 intelligent with a basic grasp of the UNIX command line, but without4516 any special knowledge of git. If necessary, any other prerequisites4517 should be specifically mentioned as they arise.4518- Whenever possible, section headings should clearly describe the task4519 they explain how to do, in language that requires no more knowledge4520 than necessary: for example, "importing patches into a project" rather4521 than "the git-am command"45224523Think about how to create a clear chapter dependency graph that will4524allow people to get to important topics without necessarily reading4525everything in between.45264527Scan Documentation/ for other stuff left out; in particular:45284529- howto's4530- some of technical/?4531- hooks4532- list of commands in linkgit:git[1]45334534Scan email archives for other stuff left out45354536Scan man pages to see if any assume more background than this manual4537provides.45384539Simplify beginning by suggesting disconnected head instead of4540temporary branch creation?45414542Add more good examples. Entire sections of just cookbook examples4543might be a good idea; maybe make an "advanced examples" section a4544standard end-of-chapter section?45454546Include cross-references to the glossary, where appropriate.45474548Document shallow clones? See draft 1.5.0 release notes for some4549documentation.45504551Add a section on working with other version control systems, including4552CVS, Subversion, and just imports of series of release tarballs.45534554More details on gitweb?45554556Write a chapter on using plumbing and writing scripts.45574558Alternates, clone -reference, etc.45594560More on recovery from repository corruption. See:4561 http://marc.theaimsgroup.com/?l=git&m=117263864820799&w=24562 http://marc.theaimsgroup.com/?l=git&m=117147855503798&w=2