<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN" "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">

<article lang="en" id="gitcore-tutorial(7)">
<articleinfo>
    <title>gitcore-tutorial(7)</title>
        <indexterm>
                <primary>gitcore-tutorial(7)</primary>
        </indexterm>
</articleinfo>
<simplesect id="_name">
<title>NAME</title>
<simpara>gitcore-tutorial - A git core tutorial for developers</simpara>
</simplesect>
<simplesect id="_synopsis">
<title>SYNOPSIS</title>
<simpara>git *</simpara>
</simplesect>
<simplesect id="_description">
<title>DESCRIPTION</title>
<simpara>This tutorial explains how to use the "core" git programs to set up and
work with a git repository.</simpara>
<simpara>If you just need to use git as a revision control system you may prefer
to start with "A Tutorial Introduction to GIT" (<xref linkend="gittutorial(7)"/>) or
<ulink url="user-manual.html">the GIT User Manual</ulink>.</simpara>
<simpara>However, an understanding of these low-level tools can be helpful if
you want to understand git&#8217;s internals.</simpara>
<simpara>The core git is often called "plumbing", with the prettier user
interfaces on top of it called "porcelain". You may not want to use the
plumbing directly very often, but it can be good to know what the
plumbing does for when the porcelain isn&#8217;t flushing.</simpara>
<note><simpara>Deeper technical details are often marked as Notes, which you can
skip on your first reading.</simpara></note>
</simplesect>
<simplesect id="_creating_a_git_repository">
<title>Creating a git repository</title>
<simpara>Creating a new git repository couldn&#8217;t be easier: all git repositories start
out empty, and the only thing you need to do is find yourself a
subdirectory that you want to use as a working tree - either an empty
one for a totally new project, or an existing working tree that you want
to import into git.</simpara>
<simpara>For our first example, we&#8217;re going to start a totally new repository from
scratch, with no pre-existing files, and we&#8217;ll call it <emphasis>git-tutorial</emphasis>.
To start up, create a subdirectory for it, change into that
subdirectory, and initialize the git infrastructure with <emphasis>git-init</emphasis>:</simpara>
<literallayout>$ mkdir git-tutorial
$ cd git-tutorial
$ git init</literallayout>
<simpara>to which git will reply</simpara>
<literallayout>Initialized empty Git repository in .git/</literallayout>
<simpara>which is just git&#8217;s way of saying that you haven&#8217;t been doing anything
strange, and that it will have created a local <literal>.git</literal> directory setup for
your new project. You will now have a <literal>.git</literal> directory, and you can
inspect that with <emphasis>ls</emphasis>. For your new empty project, it should show you
three entries, among other things:</simpara>
<itemizedlist>
<listitem>
<simpara>
a file called <literal>HEAD</literal>, that has <literal>ref: refs/heads/master</literal> in it.
   This is similar to a symbolic link and points at
   <literal>refs/heads/master</literal> relative to the <literal>HEAD</literal> file.
</simpara>
<simpara>Don&#8217;t worry about the fact that the file that the <literal>HEAD</literal> link points to
doesn&#8217;t even exist yet&#8201;&#8212;&#8201;you haven&#8217;t created the commit that will
start your <literal>HEAD</literal> development branch yet.</simpara>
</listitem>
<listitem>
<simpara>
a subdirectory called <literal>objects</literal>, which will contain all the
   objects of your project. You should never have any real reason to
   look at the objects directly, but you might want to know that these
   objects are what contains all the real <emphasis>data</emphasis> in your repository.
</simpara>
</listitem>
<listitem>
<simpara>
a subdirectory called <literal>refs</literal>, which contains references to objects.
</simpara>
</listitem>
</itemizedlist>
<simpara>In particular, the <literal>refs</literal> subdirectory will contain two other
subdirectories, named <literal>heads</literal> and <literal>tags</literal> respectively. They do
exactly what their names imply: they contain references to any number
of different <emphasis>heads</emphasis> of development (aka <emphasis>branches</emphasis>), and to any
<emphasis>tags</emphasis> that you have created to name specific versions in your
repository.</simpara>
<simpara>One note: the special <literal>master</literal> head is the default branch, which is
why the <literal>.git/HEAD</literal> file was created points to it even if it
doesn&#8217;t yet exist. Basically, the <literal>HEAD</literal> link is supposed to always
point to the branch you are working on right now, and you always
start out expecting to work on the <literal>master</literal> branch.</simpara>
<simpara>However, this is only a convention, and you can name your branches
anything you want, and don&#8217;t have to ever even <emphasis>have</emphasis> a <literal>master</literal>
branch. A number of the git tools will assume that <literal>.git/HEAD</literal> is
valid, though.</simpara>
<note><simpara>An <emphasis>object</emphasis> is identified by its 160-bit SHA1 hash, aka <emphasis>object name</emphasis>,
and a reference to an object is always the 40-byte hex
representation of that SHA1 name. The files in the &#8216;refs`
subdirectory are expected to contain these hex references
(usually with a final <literal>&#8217;\n\'</literal> at the end), and you should thus
expect to see a number of 41-byte files containing these
references in these <literal>refs</literal> subdirectories when you actually start
populating your tree.</simpara></note>
<note><simpara>An advanced user may want to take a look at <xref linkend="gitrepository-layout(5)"/>
after finishing this tutorial.</simpara></note>
<simpara>You have now created your first git repository. Of course, since it&#8217;s
empty, that&#8217;s not very useful, so let&#8217;s start populating it with data.</simpara>
</simplesect>
<simplesect id="_populating_a_git_repository">
<title>Populating a git repository</title>
<simpara>We&#8217;ll keep this simple and stupid, so we&#8217;ll start off with populating a
few trivial files just to get a feel for it.</simpara>
<simpara>Start off with just creating any random files that you want to maintain
in your git repository. We&#8217;ll start off with a few bad examples, just to
get a feel for how this works:</simpara>
<literallayout>$ echo "Hello World" &gt;hello
$ echo "Silly example" &gt;example</literallayout>
<simpara>you have now created two files in your working tree (aka <emphasis>working directory</emphasis>),
but to actually check in your hard work, you will have to go through two steps:</simpara>
<itemizedlist>
<listitem>
<simpara>
fill in the <emphasis>index</emphasis> file (aka <emphasis>cache</emphasis>) with the information about your
   working tree state.
</simpara>
</listitem>
<listitem>
<simpara>
commit that index file as an object.
</simpara>
</listitem>
</itemizedlist>
<simpara>The first step is trivial: when you want to tell git about any changes
to your working tree, you use the <emphasis>git-update-index</emphasis> program. That
program normally just takes a list of filenames you want to update, but
to avoid trivial mistakes, it refuses to add new entries to the index
(or remove existing ones) unless you explicitly tell it that you&#8217;re
adding a new entry with the <literal>--add</literal> flag (or removing an entry with the
<literal>--remove</literal>) flag.</simpara>
<simpara>So to populate the index with the two files you just created, you can do</simpara>
<literallayout>$ git update-index --add hello example</literallayout>
<simpara>and you have now told git to track those two files.</simpara>
<simpara>In fact, as you did that, if you now look into your object directory,
you&#8217;ll notice that git will have added two new objects to the object
database. If you did exactly the steps above, you should now be able to do</simpara>
<literallayout>$ ls .git/objects/??/*</literallayout>
<simpara>and see two files:</simpara>
<literallayout>.git/objects/55/7db03de997c86a4a028e1ebd3a1ceb225be238
.git/objects/f2/4c74a2e500f5ee1332c86b94199f52b1d1d962</literallayout>
<simpara>which correspond with the objects with names of <literal>557db&#8230;</literal> and
<literal>f24c7&#8230;</literal> respectively.</simpara>
<simpara>If you want to, you can use <emphasis>git-cat-file</emphasis> to look at those objects, but
you&#8217;ll have to use the object name, not the filename of the object:</simpara>
<literallayout>$ git cat-file -t 557db03de997c86a4a028e1ebd3a1ceb225be238</literallayout>
<simpara>where the <literal>-t</literal> tells <emphasis>git-cat-file</emphasis> to tell you what the "type" of the
object is. git will tell you that you have a "blob" object (i.e., just a
regular file), and you can see the contents with</simpara>
<literallayout>$ git cat-file "blob" 557db03</literallayout>
<simpara>which will print out "Hello World". The object <literal>557db03</literal> is nothing
more than the contents of your file <literal>hello</literal>.</simpara>
<note><simpara>Don&#8217;t confuse that object with the file <literal>hello</literal> itself. The
object is literally just those specific <emphasis role="strong">contents</emphasis> of the file, and
however much you later change the contents in file <literal>hello</literal>, the object
we just looked at will never change. Objects are immutable.</simpara></note>
<note><simpara>The second example demonstrates that you can
abbreviate the object name to only the first several
hexadecimal digits in most places.</simpara></note>
<simpara>Anyway, as we mentioned previously, you normally never actually take a
look at the objects themselves, and typing long 40-character hex
names is not something you&#8217;d normally want to do. The above digression
was just to show that <emphasis>git-update-index</emphasis> did something magical, and
actually saved away the contents of your files into the git object
database.</simpara>
<simpara>Updating the index did something else too: it created a <literal>.git/index</literal>
file. This is the index that describes your current working tree, and
something you should be very aware of. Again, you normally never worry
about the index file itself, but you should be aware of the fact that
you have not actually really "checked in" your files into git so far,
you&#8217;ve only <emphasis role="strong">told</emphasis> git about them.</simpara>
<simpara>However, since git knows about them, you can now start using some of the
most basic git commands to manipulate the files or look at their status.</simpara>
<simpara>In particular, let&#8217;s not even check in the two files into git yet, we&#8217;ll
start off by adding another line to <literal>hello</literal> first:</simpara>
<literallayout>$ echo "It's a new day for git" &gt;&gt;hello</literallayout>
<simpara>and you can now, since you told git about the previous state of <literal>hello</literal>, ask
git what has changed in the tree compared to your old index, using the
<emphasis>git-diff-files</emphasis> command:</simpara>
<literallayout>$ git diff-files</literallayout>
<simpara>Oops. That wasn&#8217;t very readable. It just spit out its own internal
version of a <emphasis>diff</emphasis>, but that internal version really just tells you
that it has noticed that "hello" has been modified, and that the old object
contents it had have been replaced with something else.</simpara>
<simpara>To make it readable, we can tell <emphasis>git-diff-files</emphasis> to output the
differences as a patch, using the <literal>-p</literal> flag:</simpara>
<literallayout>$ git diff-files -p
diff --git a/hello b/hello
index 557db03..263414f 100644
--- a/hello
+++ b/hello
@@ -1 +1,2 @@
 Hello World
+It's a new day for git</literallayout>
<simpara>i.e. the diff of the change we caused by adding another line to <literal>hello</literal>.</simpara>
<simpara>In other words, <emphasis>git-diff-files</emphasis> always shows us the difference between
what is recorded in the index, and what is currently in the working
tree. That&#8217;s very useful.</simpara>
<simpara>A common shorthand for <literal>git diff-files -p</literal> is to just write <literal>git
diff</literal>, which will do the same thing.</simpara>
<literallayout>$ git diff
diff --git a/hello b/hello
index 557db03..263414f 100644
--- a/hello
+++ b/hello
@@ -1 +1,2 @@
 Hello World
+It's a new day for git</literallayout>
</simplesect>
<simplesect id="_committing_git_state">
<title>Committing git state</title>
<simpara>Now, we want to go to the next stage in git, which is to take the files
that git knows about in the index, and commit them as a real tree. We do
that in two phases: creating a <emphasis>tree</emphasis> object, and committing that <emphasis>tree</emphasis>
object as a <emphasis>commit</emphasis> object together with an explanation of what the
tree was all about, along with information of how we came to that state.</simpara>
<simpara>Creating a tree object is trivial, and is done with <emphasis>git-write-tree</emphasis>.
There are no options or other input: <literal>git write-tree</literal> will take the
current index state, and write an object that describes that whole
index. In other words, we&#8217;re now tying together all the different
filenames with their contents (and their permissions), and we&#8217;re
creating the equivalent of a git "directory" object:</simpara>
<literallayout>$ git write-tree</literallayout>
<simpara>and this will just output the name of the resulting tree, in this case
(if you have done exactly as I&#8217;ve described) it should be</simpara>
<literallayout>8988da15d077d4829fc51d8544c097def6644dbb</literallayout>
<simpara>which is another incomprehensible object name. Again, if you want to,
you can use <literal>git cat-file -t 8988d...</literal> to see that this time the object
is not a "blob" object, but a "tree" object (you can also use
<literal>git cat-file</literal> to actually output the raw object contents, but you&#8217;ll see
mainly a binary mess, so that&#8217;s less interesting).</simpara>
<simpara>However&#8201;&#8212;&#8201;normally you&#8217;d never use <emphasis>git-write-tree</emphasis> on its own, because
normally you always commit a tree into a commit object using the
<emphasis>git-commit-tree</emphasis> command. In fact, it&#8217;s easier to not actually use
<emphasis>git-write-tree</emphasis> on its own at all, but to just pass its result in as an
argument to <emphasis>git-commit-tree</emphasis>.</simpara>
<simpara><emphasis>git-commit-tree</emphasis> normally takes several arguments&#8201;&#8212;&#8201;it wants to know
what the <emphasis>parent</emphasis> of a commit was, but since this is the first commit
ever in this new repository, and it has no parents, we only need to pass in
the object name of the tree. However, <emphasis>git-commit-tree</emphasis> also wants to get a
commit message on its standard input, and it will write out the resulting
object name for the commit to its standard output.</simpara>
<simpara>And this is where we create the <literal>.git/refs/heads/master</literal> file
which is pointed at by <literal>HEAD</literal>. This file is supposed to contain
the reference to the top-of-tree of the master branch, and since
that&#8217;s exactly what <emphasis>git-commit-tree</emphasis> spits out, we can do this
all with a sequence of simple shell commands:</simpara>
<literallayout>$ tree=$(git write-tree)
$ commit=$(echo 'Initial commit' | git commit-tree $tree)
$ git update-ref HEAD $commit</literallayout>
<simpara>In this case this creates a totally new commit that is not related to
anything else. Normally you do this only <emphasis role="strong">once</emphasis> for a project ever, and
all later commits will be parented on top of an earlier commit.</simpara>
<simpara>Again, normally you&#8217;d never actually do this by hand. There is a
helpful script called <literal>git commit</literal> that will do all of this for you. So
you could have just written <literal>git commit</literal>
instead, and it would have done the above magic scripting for you.</simpara>
</simplesect>
<simplesect id="_making_a_change">
<title>Making a change</title>
<simpara>Remember how we did the <emphasis>git-update-index</emphasis> on file <literal>hello</literal> and then we
changed <literal>hello</literal> afterward, and could compare the new state of <literal>hello</literal> with the
state we saved in the index file?</simpara>
<simpara>Further, remember how I said that <emphasis>git-write-tree</emphasis> writes the contents
of the <emphasis role="strong">index</emphasis> file to the tree, and thus what we just committed was in
fact the <emphasis role="strong">original</emphasis> contents of the file <literal>hello</literal>, not the new ones. We did
that on purpose, to show the difference between the index state, and the
state in the working tree, and how they don&#8217;t have to match, even
when we commit things.</simpara>
<simpara>As before, if we do <literal>git diff-files -p</literal> in our git-tutorial project,
we&#8217;ll still see the same difference we saw last time: the index file
hasn&#8217;t changed by the act of committing anything. However, now that we
have committed something, we can also learn to use a new command:
<emphasis>git-diff-index</emphasis>.</simpara>
<simpara>Unlike <emphasis>git-diff-files</emphasis>, which showed the difference between the index
file and the working tree, <emphasis>git-diff-index</emphasis> shows the differences
between a committed <emphasis role="strong">tree</emphasis> and either the index file or the working
tree. In other words, <emphasis>git-diff-index</emphasis> wants a tree to be diffed
against, and before we did the commit, we couldn&#8217;t do that, because we
didn&#8217;t have anything to diff against.</simpara>
<simpara>But now we can do</simpara>
<literallayout>$ git diff-index -p HEAD</literallayout>
<simpara>(where <literal>-p</literal> has the same meaning as it did in <emphasis>git-diff-files</emphasis>), and it
will show us the same difference, but for a totally different reason.
Now we&#8217;re comparing the working tree not against the index file,
but against the tree we just wrote. It just so happens that those two
are obviously the same, so we get the same result.</simpara>
<simpara>Again, because this is a common operation, you can also just shorthand
it with</simpara>
<literallayout>$ git diff HEAD</literallayout>
<simpara>which ends up doing the above for you.</simpara>
<simpara>In other words, <emphasis>git-diff-index</emphasis> normally compares a tree against the
working tree, but when given the <literal>--cached</literal> flag, it is told to
instead compare against just the index cache contents, and ignore the
current working tree state entirely. Since we just wrote the index
file to HEAD, doing <literal>git diff-index --cached -p HEAD</literal> should thus return
an empty set of differences, and that&#8217;s exactly what it does.</simpara>
<note>
<simpara><emphasis>git-diff-index</emphasis> really always uses the index for its
comparisons, and saying that it compares a tree against the working
tree is thus not strictly accurate. In particular, the list of
files to compare (the "meta-data") <emphasis role="strong">always</emphasis> comes from the index file,
regardless of whether the <literal>--cached</literal> flag is used or not. The <literal>--cached</literal>
flag really only determines whether the file <emphasis role="strong">contents</emphasis> to be compared
come from the working tree or not.</simpara>
<simpara>This is not hard to understand, as soon as you realize that git simply
never knows (or cares) about files that it is not told about
explicitly. git will never go <emphasis role="strong">looking</emphasis> for files to compare, it
expects you to tell it what the files are, and that&#8217;s what the index
is there for.</simpara>
</note>
<simpara>However, our next step is to commit the <emphasis role="strong">change</emphasis> we did, and again, to
understand what&#8217;s going on, keep in mind the difference between "working
tree contents", "index file" and "committed tree". We have changes
in the working tree that we want to commit, and we always have to
work through the index file, so the first thing we need to do is to
update the index cache:</simpara>
<literallayout>$ git update-index hello</literallayout>
<simpara>(note how we didn&#8217;t need the <literal>--add</literal> flag this time, since git knew
about the file already).</simpara>
<simpara>Note what happens to the different <emphasis>git-diff-*</emphasis> versions here. After
we&#8217;ve updated <literal>hello</literal> in the index, <literal>git diff-files -p</literal> now shows no
differences, but <literal>git diff-index -p HEAD</literal> still <emphasis role="strong">does</emphasis> show that the
current state is different from the state we committed. In fact, now
<emphasis>git-diff-index</emphasis> shows the same difference whether we use the <literal>--cached</literal>
flag or not, since now the index is coherent with the working tree.</simpara>
<simpara>Now, since we&#8217;ve updated <literal>hello</literal> in the index, we can commit the new
version. We could do it by writing the tree by hand again, and
committing the tree (this time we&#8217;d have to use the <literal>-p HEAD</literal> flag to
tell commit that the HEAD was the <emphasis role="strong">parent</emphasis> of the new commit, and that
this wasn&#8217;t an initial commit any more), but you&#8217;ve done that once
already, so let&#8217;s just use the helpful script this time:</simpara>
<literallayout>$ git commit</literallayout>
<simpara>which starts an editor for you to write the commit message and tells you
a bit about what you have done.</simpara>
<simpara>Write whatever message you want, and all the lines that start with <emphasis>#</emphasis>
will be pruned out, and the rest will be used as the commit message for
the change. If you decide you don&#8217;t want to commit anything after all at
this point (you can continue to edit things and update the index), you
can just leave an empty message. Otherwise <literal>git commit</literal> will commit
the change for you.</simpara>
<simpara>You&#8217;ve now made your first real git commit. And if you&#8217;re interested in
looking at what <literal>git commit</literal> really does, feel free to investigate:
it&#8217;s a few very simple shell scripts to generate the helpful (?) commit
message headers, and a few one-liners that actually do the
commit itself (<emphasis>git-commit</emphasis>).</simpara>
</simplesect>
<simplesect id="_inspecting_changes">
<title>Inspecting Changes</title>
<simpara>While creating changes is useful, it&#8217;s even more useful if you can tell
later what changed. The most useful command for this is another of the
<emphasis>diff</emphasis> family, namely <emphasis>git-diff-tree</emphasis>.</simpara>
<simpara><emphasis>git-diff-tree</emphasis> can be given two arbitrary trees, and it will tell you the
differences between them. Perhaps even more commonly, though, you can
give it just a single commit object, and it will figure out the parent
of that commit itself, and show the difference directly. Thus, to get
the same diff that we&#8217;ve already seen several times, we can now do</simpara>
<literallayout>$ git diff-tree -p HEAD</literallayout>
<simpara>(again, <literal>-p</literal> means to show the difference as a human-readable patch),
and it will show what the last commit (in <literal>HEAD</literal>) actually changed.</simpara>
<note>
<simpara>Here is an ASCII art by Jon Loeliger that illustrates how
various diff-\* commands compare things.</simpara>
<literallayout class="monospaced">            diff-tree
             +----+
             |    |
             |    |
             V    V
          +-----------+
          | Object DB |
          |  Backing  |
          |   Store   |
          +-----------+
            ^    ^
            |    |
            |    |  diff-index --cached
            |    |
diff-index  |    V
            |  +-----------+
            |  |   Index   |
            |  |  "cache"  |
            |  +-----------+
            |    ^
            |    |
            |    |  diff-files
            |    |
            V    V
          +-----------+
          |  Working  |
          | Directory |
          +-----------+</literallayout>
</note>
<simpara>More interestingly, you can also give <emphasis>git-diff-tree</emphasis> the <literal>--pretty</literal> flag,
which tells it to also show the commit message and author and date of the
commit, and you can tell it to show a whole series of diffs.
Alternatively, you can tell it to be "silent", and not show the diffs at
all, but just show the actual commit message.</simpara>
<simpara>In fact, together with the <emphasis>git-rev-list</emphasis> program (which generates a
list of revisions), <emphasis>git-diff-tree</emphasis> ends up being a veritable fount of
changes. A trivial (but very useful) script called <emphasis>git-whatchanged</emphasis> is
included with git which does exactly this, and shows a log of recent
activities.</simpara>
<simpara>To see the whole history of our pitiful little git-tutorial project, you
can do</simpara>
<literallayout>$ git log</literallayout>
<simpara>which shows just the log messages, or if we want to see the log together
with the associated patches use the more complex (and much more
powerful)</simpara>
<literallayout>$ git whatchanged -p</literallayout>
<simpara>and you will see exactly what has changed in the repository over its
short history.</simpara>
<note><simpara>When using the above two commands, the initial commit will be shown.
If this is a problem because it is huge, you can hide it by setting
the log.showroot configuration variable to false. Having this, you
can still show it for each command just adding the <literal>--root</literal> option,
which is a flag for <emphasis>git-diff-tree</emphasis> accepted by both commands.</simpara></note>
<simpara>With that, you should now be having some inkling of what git does, and
can explore on your own.</simpara>
<note><simpara>Most likely, you are not directly using the core
git Plumbing commands, but using Porcelain such as <emphasis>git-add</emphasis>, &#8216;git-rm&#8217;
and &#8216;git-commit&#8217;.</simpara></note>
</simplesect>
<simplesect id="_tagging_a_version">
<title>Tagging a version</title>
<simpara>In git, there are two kinds of tags, a "light" one, and an "annotated tag".</simpara>
<simpara>A "light" tag is technically nothing more than a branch, except we put
it in the <literal>.git/refs/tags/</literal> subdirectory instead of calling it a <literal>head</literal>.
So the simplest form of tag involves nothing more than</simpara>
<literallayout>$ git tag my-first-tag</literallayout>
<simpara>which just writes the current <literal>HEAD</literal> into the <literal>.git/refs/tags/my-first-tag</literal>
file, after which point you can then use this symbolic name for that
particular state. You can, for example, do</simpara>
<literallayout>$ git diff my-first-tag</literallayout>
<simpara>to diff your current state against that tag which at this point will
obviously be an empty diff, but if you continue to develop and commit
stuff, you can use your tag as an "anchor-point" to see what has changed
since you tagged it.</simpara>
<simpara>An "annotated tag" is actually a real git object, and contains not only a
pointer to the state you want to tag, but also a small tag name and
message, along with optionally a PGP signature that says that yes,
you really did
that tag. You create these annotated tags with either the <literal>-a</literal> or
<literal>-s</literal> flag to <emphasis>git-tag</emphasis>:</simpara>
<literallayout>$ git tag -s &lt;tagname&gt;</literallayout>
<simpara>which will sign the current <literal>HEAD</literal> (but you can also give it another
argument that specifies the thing to tag, i.e., you could have tagged the
current <literal>mybranch</literal> point by using <literal>git tag &lt;tagname&gt; mybranch</literal>).</simpara>
<simpara>You normally only do signed tags for major releases or things
like that, while the light-weight tags are useful for any marking you
want to do&#8201;&#8212;&#8201;any time you decide that you want to remember a certain
point, just create a private tag for it, and you have a nice symbolic
name for the state at that point.</simpara>
</simplesect>
<simplesect id="_copying_repositories">
<title>Copying repositories</title>
<simpara>git repositories are normally totally self-sufficient and relocatable.
Unlike CVS, for example, there is no separate notion of
"repository" and "working tree". A git repository normally <emphasis role="strong">is</emphasis> the
working tree, with the local git information hidden in the <literal>.git</literal>
subdirectory. There is nothing else. What you see is what you got.</simpara>
<note><simpara>You can tell git to split the git internal information from
the directory that it tracks, but we&#8217;ll ignore that for now: it&#8217;s not
how normal projects work, and it&#8217;s really only meant for special uses.
So the mental model of "the git information is always tied directly to
the working tree that it describes" may not be technically 100%
accurate, but it&#8217;s a good model for all normal use.</simpara></note>
<simpara>This has two implications:</simpara>
<itemizedlist>
<listitem>
<simpara>
if you grow bored with the tutorial repository you created (or you&#8217;ve
   made a mistake and want to start all over), you can just do simple
</simpara>
<literallayout>$ rm -rf git-tutorial</literallayout>
<simpara>and it will be gone. There&#8217;s no external repository, and there&#8217;s no
history outside the project you created.</simpara>
</listitem>
<listitem>
<simpara>
if you want to move or duplicate a git repository, you can do so. There
   is <emphasis>git-clone</emphasis> command, but if all you want to do is just to
   create a copy of your repository (with all the full history that
   went along with it), you can do so with a regular
   <literal>cp -a git-tutorial new-git-tutorial</literal>.
</simpara>
<simpara>Note that when you&#8217;ve moved or copied a git repository, your git index
file (which caches various information, notably some of the "stat"
information for the files involved) will likely need to be refreshed.
So after you do a <literal>cp -a</literal> to create a new copy, you&#8217;ll want to do</simpara>
<literallayout>$ git update-index --refresh</literallayout>
<simpara>in the new repository to make sure that the index file is up-to-date.</simpara>
</listitem>
</itemizedlist>
<simpara>Note that the second point is true even across machines. You can
duplicate a remote git repository with <emphasis role="strong">any</emphasis> regular copy mechanism, be it
<emphasis>scp</emphasis>, <emphasis>rsync</emphasis> or <emphasis>wget</emphasis>.</simpara>
<simpara>When copying a remote repository, you&#8217;ll want to at a minimum update the
index cache when you do this, and especially with other peoples'
repositories you often want to make sure that the index cache is in some
known state (you don&#8217;t know <emphasis role="strong">what</emphasis> they&#8217;ve done and not yet checked in),
so usually you&#8217;ll precede the <emphasis>git-update-index</emphasis> with a</simpara>
<literallayout>$ git read-tree --reset HEAD
$ git update-index --refresh</literallayout>
<simpara>which will force a total index re-build from the tree pointed to by <literal>HEAD</literal>.
It resets the index contents to <literal>HEAD</literal>, and then the <emphasis>git-update-index</emphasis>
makes sure to match up all index entries with the checked-out files.
If the original repository had uncommitted changes in its
working tree, <literal>git update-index --refresh</literal> notices them and
tells you they need to be updated.</simpara>
<simpara>The above can also be written as simply</simpara>
<literallayout>$ git reset</literallayout>
<simpara>and in fact a lot of the common git command combinations can be scripted
with the <literal>git xyz</literal> interfaces.  You can learn things by just looking
at what the various git scripts do.  For example, <literal>git reset</literal> used to be
the above two lines implemented in <emphasis>git-reset</emphasis>, but some things like
<emphasis>git-status</emphasis> and <emphasis>git-commit</emphasis> are slightly more complex scripts around
the basic git commands.</simpara>
<simpara>Many (most?) public remote repositories will not contain any of
the checked out files or even an index file, and will <emphasis role="strong">only</emphasis> contain the
actual core git files. Such a repository usually doesn&#8217;t even have the
<literal>.git</literal> subdirectory, but has all the git files directly in the
repository.</simpara>
<simpara>To create your own local live copy of such a "raw" git repository, you&#8217;d
first create your own subdirectory for the project, and then copy the
raw repository contents into the <literal>.git</literal> directory. For example, to
create your own copy of the git repository, you&#8217;d do the following</simpara>
<literallayout>$ mkdir my-git
$ cd my-git
$ rsync -rL rsync://rsync.kernel.org/pub/scm/git/git.git/ .git</literallayout>
<simpara>followed by</simpara>
<literallayout>$ git read-tree HEAD</literallayout>
<simpara>to populate the index. However, now you have populated the index, and
you have all the git internal files, but you will notice that you don&#8217;t
actually have any of the working tree files to work on. To get
those, you&#8217;d check them out with</simpara>
<literallayout>$ git checkout-index -u -a</literallayout>
<simpara>where the <literal>-u</literal> flag means that you want the checkout to keep the index
up-to-date (so that you don&#8217;t have to refresh it afterward), and the
<literal>-a</literal> flag means "check out all files" (if you have a stale copy or an
older version of a checked out tree you may also need to add the <literal>-f</literal>
flag first, to tell <emphasis>git-checkout-index</emphasis> to <emphasis role="strong">force</emphasis> overwriting of any old
files).</simpara>
<simpara>Again, this can all be simplified with</simpara>
<literallayout>$ git clone rsync://rsync.kernel.org/pub/scm/git/git.git/ my-git
$ cd my-git
$ git checkout</literallayout>
<simpara>which will end up doing all of the above for you.</simpara>
<simpara>You have now successfully copied somebody else&#8217;s (mine) remote
repository, and checked it out.</simpara>
</simplesect>
<simplesect id="_creating_a_new_branch">
<title>Creating a new branch</title>
<simpara>Branches in git are really nothing more than pointers into the git
object database from within the <literal>.git/refs/</literal> subdirectory, and as we
already discussed, the <literal>HEAD</literal> branch is nothing but a symlink to one of
these object pointers.</simpara>
<simpara>You can at any time create a new branch by just picking an arbitrary
point in the project history, and just writing the SHA1 name of that
object into a file under <literal>.git/refs/heads/</literal>. You can use any filename you
want (and indeed, subdirectories), but the convention is that the
"normal" branch is called <literal>master</literal>. That&#8217;s just a convention, though,
and nothing enforces it.</simpara>
<simpara>To show that as an example, let&#8217;s go back to the git-tutorial repository we
used earlier, and create a branch in it. You do that by simply just
saying that you want to check out a new branch:</simpara>
<literallayout>$ git checkout -b mybranch</literallayout>
<simpara>will create a new branch based at the current <literal>HEAD</literal> position, and switch
to it.</simpara>
<note>
<simpara>If you make the decision to start your new branch at some
other point in the history than the current <literal>HEAD</literal>, you can do so by
just telling <emphasis>git-checkout</emphasis> what the base of the checkout would be.
In other words, if you have an earlier tag or branch, you&#8217;d just do</simpara>
<literallayout>$ git checkout -b mybranch earlier-commit</literallayout>
<simpara>and it would create the new branch <literal>mybranch</literal> at the earlier commit,
and check out the state at that time.</simpara>
</note>
<simpara>You can always just jump back to your original <literal>master</literal> branch by doing</simpara>
<literallayout>$ git checkout master</literallayout>
<simpara>(or any other branch-name, for that matter) and if you forget which
branch you happen to be on, a simple</simpara>
<literallayout>$ cat .git/HEAD</literallayout>
<simpara>will tell you where it&#8217;s pointing.  To get the list of branches
you have, you can say</simpara>
<literallayout>$ git branch</literallayout>
<simpara>which used to be nothing more than a simple script around <literal>ls .git/refs/heads</literal>.
There will be an asterisk in front of the branch you are currently on.</simpara>
<simpara>Sometimes you may wish to create a new branch <emphasis>without</emphasis> actually
checking it out and switching to it. If so, just use the command</simpara>
<literallayout>$ git branch &lt;branchname&gt; [startingpoint]</literallayout>
<simpara>which will simply <emphasis>create</emphasis> the branch, but will not do anything further.
You can then later&#8201;&#8212;&#8201;once you decide that you want to actually develop
on that branch&#8201;&#8212;&#8201;switch to that branch with a regular <emphasis>git-checkout</emphasis>
with the branchname as the argument.</simpara>
</simplesect>
<simplesect id="_merging_two_branches">
<title>Merging two branches</title>
<simpara>One of the ideas of having a branch is that you do some (possibly
experimental) work in it, and eventually merge it back to the main
branch. So assuming you created the above <literal>mybranch</literal> that started out
being the same as the original <literal>master</literal> branch, let&#8217;s make sure we&#8217;re in
that branch, and do some work there.</simpara>
<literallayout>$ git checkout mybranch
$ echo "Work, work, work" &gt;&gt;hello
$ git commit -m "Some work." -i hello</literallayout>
<simpara>Here, we just added another line to <literal>hello</literal>, and we used a shorthand for
doing both <literal>git update-index hello</literal> and <literal>git commit</literal> by just giving the
filename directly to <literal>git commit</literal>, with an <literal>-i</literal> flag (it tells
git to <emphasis>include</emphasis> that file in addition to what you have done to
the index file so far when making the commit).  The <literal>-m</literal> flag is to give the
commit log message from the command line.</simpara>
<simpara>Now, to make it a bit more interesting, let&#8217;s assume that somebody else
does some work in the original branch, and simulate that by going back
to the master branch, and editing the same file differently there:</simpara>
<literallayout>$ git checkout master</literallayout>
<simpara>Here, take a moment to look at the contents of <literal>hello</literal>, and notice how they
don&#8217;t contain the work we just did in <literal>mybranch</literal>&#8201;&#8212;&#8201;because that work
hasn&#8217;t happened in the <literal>master</literal> branch at all. Then do</simpara>
<literallayout>$ echo "Play, play, play" &gt;&gt;hello
$ echo "Lots of fun" &gt;&gt;example
$ git commit -m "Some fun." -i hello example</literallayout>
<simpara>since the master branch is obviously in a much better mood.</simpara>
<simpara>Now, you&#8217;ve got two branches, and you decide that you want to merge the
work done. Before we do that, let&#8217;s introduce a cool graphical tool that
helps you view what&#8217;s going on:</simpara>
<literallayout>$ gitk --all</literallayout>
<simpara>will show you graphically both of your branches (that&#8217;s what the <literal>--all</literal>
means: normally it will just show you your current <literal>HEAD</literal>) and their
histories. You can also see exactly how they came to be from a common
source.</simpara>
<simpara>Anyway, let&#8217;s exit <emphasis>gitk</emphasis> (<literal>^Q</literal> or the File menu), and decide that we want
to merge the work we did on the <literal>mybranch</literal> branch into the <literal>master</literal>
branch (which is currently our <literal>HEAD</literal> too). To do that, there&#8217;s a nice
script called <emphasis>git-merge</emphasis>, which wants to know which branches you want
to resolve and what the merge is all about:</simpara>
<literallayout>$ git merge -m "Merge work in mybranch" mybranch</literallayout>
<simpara>where the first argument is going to be used as the commit message if
the merge can be resolved automatically.</simpara>
<simpara>Now, in this case we&#8217;ve intentionally created a situation where the
merge will need to be fixed up by hand, though, so git will do as much
of it as it can automatically (which in this case is just merge the <literal>example</literal>
file, which had no differences in the <literal>mybranch</literal> branch), and say:</simpara>
<literallayout>        Auto-merging hello
        CONFLICT (content): Merge conflict in hello
        Automatic merge failed; fix conflicts and then commit the result.</literallayout>
<simpara>It tells you that it did an "Automatic merge", which
failed due to conflicts in <literal>hello</literal>.</simpara>
<simpara>Not to worry. It left the (trivial) conflict in <literal>hello</literal> in the same form you
should already be well used to if you&#8217;ve ever used CVS, so let&#8217;s just
open <literal>hello</literal> in our editor (whatever that may be), and fix it up somehow.
I&#8217;d suggest just making it so that <literal>hello</literal> contains all four lines:</simpara>
<literallayout>Hello World
It's a new day for git
Play, play, play
Work, work, work</literallayout>
<simpara>and once you&#8217;re happy with your manual merge, just do a</simpara>
<literallayout>$ git commit -i hello</literallayout>
<simpara>which will very loudly warn you that you&#8217;re now committing a merge
(which is correct, so never mind), and you can write a small merge
message about your adventures in <emphasis>git-merge</emphasis>-land.</simpara>
<simpara>After you&#8217;re done, start up <literal>gitk --all</literal> to see graphically what the
history looks like. Notice that <literal>mybranch</literal> still exists, and you can
switch to it, and continue to work with it if you want to. The
<literal>mybranch</literal> branch will not contain the merge, but next time you merge it
from the <literal>master</literal> branch, git will know how you merged it, so you&#8217;ll not
have to do <emphasis>that</emphasis> merge again.</simpara>
<simpara>Another useful tool, especially if you do not always work in X-Window
environment, is <literal>git show-branch</literal>.</simpara>
<literallayout>$ git show-branch --topo-order --more=1 master mybranch
* [master] Merge work in mybranch
 ! [mybranch] Some work.
--
-  [master] Merge work in mybranch
*+ [mybranch] Some work.
*  [master^] Some fun.</literallayout>
<simpara>The first two lines indicate that it is showing the two branches
and the first line of the commit log message from their
top-of-the-tree commits, you are currently on <literal>master</literal> branch
(notice the asterisk <literal>*</literal> character), and the first column for
the later output lines is used to show commits contained in the
<literal>master</literal> branch, and the second column for the <literal>mybranch</literal>
branch. Three commits are shown along with their log messages.
All of them have non blank characters in the first column (<literal>*</literal>
shows an ordinary commit on the current branch, <literal>-</literal> is a merge commit), which
means they are now part of the <literal>master</literal> branch. Only the "Some
work" commit has the plus <literal>+</literal> character in the second column,
because <literal>mybranch</literal> has not been merged to incorporate these
commits from the master branch.  The string inside brackets
before the commit log message is a short name you can use to
name the commit.  In the above example, <emphasis>master</emphasis> and <emphasis>mybranch</emphasis>
are branch heads.  <emphasis>master^</emphasis> is the first parent of <emphasis>master</emphasis>
branch head.  Please see <xref linkend="git-rev-parse(1)"/> if you want to
see more complex cases.</simpara>
<note><simpara>Without the <emphasis>--more=1</emphasis> option, <emphasis>git-show-branch</emphasis> would not output the
<emphasis>[master^]</emphasis> commit, as <emphasis>[mybranch]</emphasis> commit is a common ancestor of
both <emphasis>master</emphasis> and <emphasis>mybranch</emphasis> tips.  Please see <xref linkend="git-show-branch(1)"/>
for details.</simpara></note>
<note><simpara>If there were more commits on the <emphasis>master</emphasis> branch after the merge, the
merge commit itself would not be shown by <emphasis>git-show-branch</emphasis> by
default.  You would need to provide <emphasis>--sparse</emphasis> option to make the
merge commit visible in this case.</simpara></note>
<simpara>Now, let&#8217;s pretend you are the one who did all the work in
<literal>mybranch</literal>, and the fruit of your hard work has finally been merged
to the <literal>master</literal> branch. Let&#8217;s go back to <literal>mybranch</literal>, and run
<emphasis>git-merge</emphasis> to get the "upstream changes" back to your branch.</simpara>
<literallayout>$ git checkout mybranch
$ git merge -m "Merge upstream changes." master</literallayout>
<simpara>This outputs something like this (the actual commit object names
would be different)</simpara>
<literallayout>Updating from ae3a2da... to a80b4aa....
Fast forward (no commit created; -m option ignored)
 example |    1 +
 hello   |    1 +
 2 files changed, 2 insertions(+), 0 deletions(-)</literallayout>
<simpara>Because your branch did not contain anything more than what had
already been merged into the <literal>master</literal> branch, the merge operation did
not actually do a merge. Instead, it just updated the top of
the tree of your branch to that of the <literal>master</literal> branch. This is
often called <emphasis>fast forward</emphasis> merge.</simpara>
<simpara>You can run <literal>gitk --all</literal> again to see how the commit ancestry
looks like, or run <emphasis>show-branch</emphasis>, which tells you this.</simpara>
<literallayout>$ git show-branch master mybranch
! [master] Merge work in mybranch
 * [mybranch] Merge work in mybranch
--
-- [master] Merge work in mybranch</literallayout>
</simplesect>
<simplesect id="_merging_external_work">
<title>Merging external work</title>
<simpara>It&#8217;s usually much more common that you merge with somebody else than
merging with your own branches, so it&#8217;s worth pointing out that git
makes that very easy too, and in fact, it&#8217;s not that different from
doing a <emphasis>git-merge</emphasis>. In fact, a remote merge ends up being nothing
more than "fetch the work from a remote repository into a temporary tag"
followed by a <emphasis>git-merge</emphasis>.</simpara>
<simpara>Fetching from a remote repository is done by, unsurprisingly,
<emphasis>git-fetch</emphasis>:</simpara>
<literallayout>$ git fetch &lt;remote-repository&gt;</literallayout>
<simpara>One of the following transports can be used to name the
repository to download from:</simpara>
<variablelist>
<varlistentry>
<term>
Rsync
</term>
<listitem>
<simpara>
        <literal>rsync://remote.machine/path/to/repo.git/</literal>
</simpara>
<simpara>Rsync transport is usable for both uploading and downloading,
but is completely unaware of what git does, and can produce
unexpected results when you download from the public repository
while the repository owner is uploading into it via <literal>rsync</literal>
transport.  Most notably, it could update the files under
<literal>refs/</literal> which holds the object name of the topmost commits
before uploading the files in <literal>objects/</literal>&#8201;&#8212;&#8201;the downloader would
obtain head commit object name while that object itself is still
not available in the repository.  For this reason, it is
considered deprecated.</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>
SSH
</term>
<listitem>
<simpara>
        <literal>remote.machine:/path/to/repo.git/</literal> or
</simpara>
<simpara><literal>ssh://remote.machine/path/to/repo.git/</literal></simpara>
<simpara>This transport can be used for both uploading and downloading,
and requires you to have a log-in privilege over <literal>ssh</literal> to the
remote machine.  It finds out the set of objects the other side
lacks by exchanging the head commits both ends have and
transfers (close to) minimum set of objects.  It is by far the
most efficient way to exchange git objects between repositories.</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>
Local directory
</term>
<listitem>
<simpara>
        <literal>/path/to/repo.git/</literal>
</simpara>
<simpara>This transport is the same as SSH transport but uses <emphasis>sh</emphasis> to run
both ends on the local machine instead of running other end on
the remote machine via <emphasis>ssh</emphasis>.</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>
git Native
</term>
<listitem>
<simpara>
        <literal>git://remote.machine/path/to/repo.git/</literal>
</simpara>
<simpara>This transport was designed for anonymous downloading.  Like SSH
transport, it finds out the set of objects the downstream side
lacks and transfers (close to) minimum set of objects.</simpara>
</listitem>
</varlistentry>
<varlistentry>
<term>
HTTP(S)
</term>
<listitem>
<simpara>
        <literal>http://remote.machine/path/to/repo.git/</literal>
</simpara>
<simpara>Downloader from http and https URL
first obtains the topmost commit object name from the remote site
by looking at the specified refname under <literal>repo.git/refs/</literal> directory,
and then tries to obtain the
commit object by downloading from <literal>repo.git/objects/xx/xxx...</literal>
using the object name of that commit object.  Then it reads the
commit object to find out its parent commits and the associate
tree object; it repeats this process until it gets all the
necessary objects.  Because of this behavior, they are
sometimes also called <emphasis>commit walkers</emphasis>.</simpara>
<simpara>The <emphasis>commit walkers</emphasis> are sometimes also called <emphasis>dumb
transports</emphasis>, because they do not require any git aware smart
server like git Native transport does.  Any stock HTTP server
that does not even support directory index would suffice.  But
you must prepare your repository with <emphasis>git-update-server-info</emphasis>
to help dumb transport downloaders.</simpara>
</listitem>
</varlistentry>
</variablelist>
<simpara>Once you fetch from the remote repository, you <literal>merge</literal> that
with your current branch.</simpara>
<simpara>However&#8201;&#8212;&#8201;it&#8217;s such a common thing to <literal>fetch</literal> and then
immediately <literal>merge</literal>, that it&#8217;s called <literal>git pull</literal>, and you can
simply do</simpara>
<literallayout>$ git pull &lt;remote-repository&gt;</literallayout>
<simpara>and optionally give a branch-name for the remote end as a second
argument.</simpara>
<note><simpara>You could do without using any branches at all, by
keeping as many local repositories as you would like to have
branches, and merging between them with <emphasis>git-pull</emphasis>, just like
you merge between branches. The advantage of this approach is
that it lets you keep a set of files for each <literal>branch</literal> checked
out and you may find it easier to switch back and forth if you
juggle multiple lines of development simultaneously. Of
course, you will pay the price of more disk usage to hold
multiple working trees, but disk space is cheap these days.</simpara></note>
<simpara>It is likely that you will be pulling from the same remote
repository from time to time. As a short hand, you can store
the remote repository URL in the local repository&#8217;s config file
like this:</simpara>
<literallayout>$ git config remote.linus.url http://www.kernel.org/pub/scm/git/git.git/</literallayout>
<simpara>and use the "linus" keyword with <emphasis>git-pull</emphasis> instead of the full URL.</simpara>
<simpara>Examples.</simpara>
<orderedlist numeration="arabic">
<listitem>
<simpara>
<literal>git pull linus</literal>
</simpara>
</listitem>
<listitem>
<simpara>
<literal>git pull linus tag v0.99.1</literal>
</simpara>
</listitem>
</orderedlist>
<simpara>the above are equivalent to:</simpara>
<orderedlist numeration="arabic">
<listitem>
<simpara>
<literal>git pull <ulink url="http://www.kernel.org/pub/scm/git/git.git/">http://www.kernel.org/pub/scm/git/git.git/</ulink> HEAD</literal>
</simpara>
</listitem>
<listitem>
<simpara>
<literal>git pull <ulink url="http://www.kernel.org/pub/scm/git/git.git/">http://www.kernel.org/pub/scm/git/git.git/</ulink> tag v0.99.1</literal>
</simpara>
</listitem>
</orderedlist>
</simplesect>
<simplesect id="_how_does_the_merge_work">
<title>How does the merge work?</title>
<simpara>We said this tutorial shows what plumbing does to help you cope
with the porcelain that isn&#8217;t flushing, but we so far did not
talk about how the merge really works.  If you are following
this tutorial the first time, I&#8217;d suggest to skip to "Publishing
your work" section and come back here later.</simpara>
<simpara>OK, still with me?  To give us an example to look at, let&#8217;s go
back to the earlier repository with "hello" and "example" file,
and bring ourselves back to the pre-merge state:</simpara>
<literallayout>$ git show-branch --more=2 master mybranch
! [master] Merge work in mybranch
 * [mybranch] Merge work in mybranch
--
-- [master] Merge work in mybranch
+* [master^2] Some work.
+* [master^] Some fun.</literallayout>
<simpara>Remember, before running <emphasis>git-merge</emphasis>, our <literal>master</literal> head was at
"Some fun." commit, while our <literal>mybranch</literal> head was at "Some
work." commit.</simpara>
<literallayout>$ git checkout mybranch
$ git reset --hard master^2
$ git checkout master
$ git reset --hard master^</literallayout>
<simpara>After rewinding, the commit structure should look like this:</simpara>
<literallayout>$ git show-branch
* [master] Some fun.
 ! [mybranch] Some work.
--
 + [mybranch] Some work.
*  [master] Some fun.
*+ [mybranch^] New day.</literallayout>
<simpara>Now we are ready to experiment with the merge by hand.</simpara>
<simpara><literal>git merge</literal> command, when merging two branches, uses 3-way merge
algorithm.  First, it finds the common ancestor between them.
The command it uses is <emphasis>git-merge-base</emphasis>:</simpara>
<literallayout>$ mb=$(git merge-base HEAD mybranch)</literallayout>
<simpara>The command writes the commit object name of the common ancestor
to the standard output, so we captured its output to a variable,
because we will be using it in the next step.  By the way, the common
ancestor commit is the "New day." commit in this case.  You can
tell it by:</simpara>
<literallayout>$ git name-rev $mb
my-first-tag</literallayout>
<simpara>After finding out a common ancestor commit, the second step is
this:</simpara>
<literallayout>$ git read-tree -m -u $mb HEAD mybranch</literallayout>
<simpara>This is the same <emphasis>git-read-tree</emphasis> command we have already seen,
but it takes three trees, unlike previous examples.  This reads
the contents of each tree into different <emphasis>stage</emphasis> in the index
file (the first tree goes to stage 1, the second to stage 2,
etc.).  After reading three trees into three stages, the paths
that are the same in all three stages are <emphasis>collapsed</emphasis> into stage
0.  Also paths that are the same in two of three stages are
collapsed into stage 0, taking the SHA1 from either stage 2 or
stage 3, whichever is different from stage 1 (i.e. only one side
changed from the common ancestor).</simpara>
<simpara>After <emphasis>collapsing</emphasis> operation, paths that are different in three
trees are left in non-zero stages.  At this point, you can
inspect the index file with this command:</simpara>
<literallayout>$ git ls-files --stage
100644 7f8b141b65fdcee47321e399a2598a235a032422 0       example
100644 263414f423d0e4d70dae8fe53fa34614ff3e2860 1       hello
100644 06fa6a24256dc7e560efa5687fa84b51f0263c3a 2       hello
100644 cc44c73eb783565da5831b4d820c962954019b69 3       hello</literallayout>
<simpara>In our example of only two files, we did not have unchanged
files so only <emphasis>example</emphasis> resulted in collapsing.  But in real-life
large projects, when only a small number of files change in one commit,
this <emphasis>collapsing</emphasis> tends to trivially merge most of the paths
fairly quickly, leaving only a handful of real changes in non-zero
stages.</simpara>
<simpara>To look at only non-zero stages, use <literal>--unmerged</literal> flag:</simpara>
<literallayout>$ git ls-files --unmerged
100644 263414f423d0e4d70dae8fe53fa34614ff3e2860 1       hello
100644 06fa6a24256dc7e560efa5687fa84b51f0263c3a 2       hello
100644 cc44c73eb783565da5831b4d820c962954019b69 3       hello</literallayout>
<simpara>The next step of merging is to merge these three versions of the
file, using 3-way merge.  This is done by giving
<emphasis>git-merge-one-file</emphasis> command as one of the arguments to
<emphasis>git-merge-index</emphasis> command:</simpara>
<literallayout>$ git merge-index git-merge-one-file hello
Auto-merging hello
ERROR: Merge conflict in hello
fatal: merge program failed</literallayout>
<simpara><emphasis>git-merge-one-file</emphasis> script is called with parameters to
describe those three versions, and is responsible to leave the
merge results in the working tree.
It is a fairly straightforward shell script, and
eventually calls <emphasis>merge</emphasis> program from RCS suite to perform a
file-level 3-way merge.  In this case, <emphasis>merge</emphasis> detects
conflicts, and the merge result with conflict marks is left in
the working tree..  This can be seen if you run <literal>ls-files
--stage</literal> again at this point:</simpara>
<literallayout>$ git ls-files --stage
100644 7f8b141b65fdcee47321e399a2598a235a032422 0       example
100644 263414f423d0e4d70dae8fe53fa34614ff3e2860 1       hello
100644 06fa6a24256dc7e560efa5687fa84b51f0263c3a 2       hello
100644 cc44c73eb783565da5831b4d820c962954019b69 3       hello</literallayout>
<simpara>This is the state of the index file and the working file after
<emphasis>git-merge</emphasis> returns control back to you, leaving the conflicting
merge for you to resolve.  Notice that the path <literal>hello</literal> is still
unmerged, and what you see with <emphasis>git-diff</emphasis> at this point is
differences since stage 2 (i.e. your version).</simpara>
</simplesect>
<simplesect id="_publishing_your_work">
<title>Publishing your work</title>
<simpara>So, we can use somebody else&#8217;s work from a remote repository, but
how can <emphasis role="strong">you</emphasis> prepare a repository to let other people pull from
it?</simpara>
<simpara>You do your real work in your working tree that has your
primary repository hanging under it as its <literal>.git</literal> subdirectory.
You <emphasis role="strong">could</emphasis> make that repository accessible remotely and ask
people to pull from it, but in practice that is not the way
things are usually done. A recommended way is to have a public
repository, make it reachable by other people, and when the
changes you made in your primary working tree are in good shape,
update the public repository from it. This is often called
<emphasis>pushing</emphasis>.</simpara>
<note><simpara>This public repository could further be mirrored, and that is
how git repositories at <literal>kernel.org</literal> are managed.</simpara></note>
<simpara>Publishing the changes from your local (private) repository to
your remote (public) repository requires a write privilege on
the remote machine. You need to have an SSH account there to
run a single command, <emphasis>git-receive-pack</emphasis>.</simpara>
<simpara>First, you need to create an empty repository on the remote
machine that will house your public repository. This empty
repository will be populated and be kept up-to-date by pushing
into it later. Obviously, this repository creation needs to be
done only once.</simpara>
<note><simpara><emphasis>git-push</emphasis> uses a pair of programs,
<emphasis>git-send-pack</emphasis> on your local machine, and <emphasis>git-receive-pack</emphasis>
on the remote machine. The communication between the two over
the network internally uses an SSH connection.</simpara></note>
<simpara>Your private repository&#8217;s git directory is usually <literal>.git</literal>, but
your public repository is often named after the project name,
i.e. <literal>&lt;project&gt;.git</literal>. Let&#8217;s create such a public repository for
project <literal>my-git</literal>. After logging into the remote machine, create
an empty directory:</simpara>
<literallayout>$ mkdir my-git.git</literallayout>
<simpara>Then, make that directory into a git repository by running
<emphasis>git-init</emphasis>, but this time, since its name is not the usual
<literal>.git</literal>, we do things slightly differently:</simpara>
<literallayout>$ GIT_DIR=my-git.git git init</literallayout>
<simpara>Make sure this directory is available for others you want your
changes to be pulled via the transport of your choice. Also
you need to make sure that you have the <emphasis>git-receive-pack</emphasis>
program on the <literal>$PATH</literal>.</simpara>
<note><simpara>Many installations of sshd do not invoke your shell as the login
shell when you directly run programs; what this means is that if
your login shell is <emphasis>bash</emphasis>, only <literal>.bashrc</literal> is read and not
<literal>.bash_profile</literal>. As a workaround, make sure <literal>.bashrc</literal> sets up
<literal>$PATH</literal> so that you can run <emphasis>git-receive-pack</emphasis> program.</simpara></note>
<note><simpara>If you plan to publish this repository to be accessed over http,
you should do <literal>mv my-git.git/hooks/post-update.sample
my-git.git/hooks/post-update</literal> at this point.
This makes sure that every time you push into this
repository, <literal>git update-server-info</literal> is run.</simpara></note>
<simpara>Your "public repository" is now ready to accept your changes.
Come back to the machine you have your private repository. From
there, run this command:</simpara>
<literallayout>$ git push &lt;public-host&gt;:/path/to/my-git.git master</literallayout>
<simpara>This synchronizes your public repository to match the named
branch head (i.e. <literal>master</literal> in this case) and objects reachable
from them in your current repository.</simpara>
<simpara>As a real example, this is how I update my public git
repository. Kernel.org mirror network takes care of the
propagation to other publicly visible machines:</simpara>
<literallayout>$ git push master.kernel.org:/pub/scm/git/git.git/</literallayout>
</simplesect>
<simplesect id="_packing_your_repository">
<title>Packing your repository</title>
<simpara>Earlier, we saw that one file under <literal>.git/objects/??/</literal> directory
is stored for each git object you create. This representation
is efficient to create atomically and safely, but
not so convenient to transport over the network. Since git objects are
immutable once they are created, there is a way to optimize the
storage by "packing them together". The command</simpara>
<literallayout>$ git repack</literallayout>
<simpara>will do it for you. If you followed the tutorial examples, you
would have accumulated about 17 objects in <literal>.git/objects/??/</literal>
directories by now. <emphasis>git-repack</emphasis> tells you how many objects it
packed, and stores the packed file in <literal>.git/objects/pack</literal>
directory.</simpara>
<note><simpara>You will see two files, <literal>pack-*.pack</literal> and <literal>pack-\*.idx</literal>,
in <literal>.git/objects/pack</literal> directory. They are closely related to
each other, and if you ever copy them by hand to a different
repository for whatever reason, you should make sure you copy
them together. The former holds all the data from the objects
in the pack, and the latter holds the index for random
access.</simpara></note>
<simpara>If you are paranoid, running <emphasis>git-verify-pack</emphasis> command would
detect if you have a corrupt pack, but do not worry too much.
Our programs are always perfect ;-).</simpara>
<simpara>Once you have packed objects, you do not need to leave the
unpacked objects that are contained in the pack file anymore.</simpara>
<literallayout>$ git prune-packed</literallayout>
<simpara>would remove them for you.</simpara>
<simpara>You can try running <literal>find .git/objects -type f</literal> before and after
you run <literal>git prune-packed</literal> if you are curious.  Also <literal>git
count-objects</literal> would tell you how many unpacked objects are in
your repository and how much space they are consuming.</simpara>
<note><simpara><literal>git pull</literal> is slightly cumbersome for HTTP transport, as a
packed repository may contain relatively few objects in a
relatively large pack. If you expect many HTTP pulls from your
public repository you might want to repack &amp; prune often, or
never.</simpara></note>
<simpara>If you run <literal>git repack</literal> again at this point, it will say
"Nothing new to pack.". Once you continue your development and
accumulate the changes, running <literal>git repack</literal> again will create a
new pack, that contains objects created since you packed your
repository the last time. We recommend that you pack your project
soon after the initial import (unless you are starting your
project from scratch), and then run <literal>git repack</literal> every once in a
while, depending on how active your project is.</simpara>
<simpara>When a repository is synchronized via <literal>git push</literal> and <literal>git pull</literal>
objects packed in the source repository are usually stored
unpacked in the destination, unless rsync transport is used.
While this allows you to use different packing strategies on
both ends, it also means you may need to repack both
repositories every once in a while.</simpara>
</simplesect>
<simplesect id="_working_with_others">
<title>Working with Others</title>
<simpara>Although git is a truly distributed system, it is often
convenient to organize your project with an informal hierarchy
of developers. Linux kernel development is run this way. There
is a nice illustration (page 17, "Merges to Mainline") in
<ulink url="http://www.xenotime.net/linux/mentor/linux-mentoring-2006.pdf">Randy Dunlap&#8217;s presentation</ulink>.</simpara>
<simpara>It should be stressed that this hierarchy is purely <emphasis role="strong">informal</emphasis>.
There is nothing fundamental in git that enforces the "chain of
patch flow" this hierarchy implies. You do not have to pull
from only one remote repository.</simpara>
<simpara>A recommended workflow for a "project lead" goes like this:</simpara>
<orderedlist numeration="arabic">
<listitem>
<simpara>
Prepare your primary repository on your local machine. Your
   work is done there.
</simpara>
</listitem>
<listitem>
<simpara>
Prepare a public repository accessible to others.
</simpara>
<simpara>If other people are pulling from your repository over dumb
transport protocols (HTTP), you need to keep this repository
<emphasis>dumb transport friendly</emphasis>.  After <literal>git init</literal>,
<literal>$GIT_DIR/hooks/post-update.sample</literal> copied from the standard templates
would contain a call to <emphasis>git-update-server-info</emphasis>
but you need to manually enable the hook with
<literal>mv post-update.sample post-update</literal>.  This makes sure
<emphasis>git-update-server-info</emphasis> keeps the necessary files up-to-date.</simpara>
</listitem>
<listitem>
<simpara>
Push into the public repository from your primary
   repository.
</simpara>
</listitem>
<listitem>
<simpara>
<emphasis>git-repack</emphasis> the public repository. This establishes a big
   pack that contains the initial set of objects as the
   baseline, and possibly <emphasis>git-prune</emphasis> if the transport
   used for pulling from your repository supports packed
   repositories.
</simpara>
</listitem>
<listitem>
<simpara>
Keep working in your primary repository. Your changes
   include modifications of your own, patches you receive via
   e-mails, and merges resulting from pulling the "public"
   repositories of your "subsystem maintainers".
</simpara>
<simpara>You can repack this private repository whenever you feel like.</simpara>
</listitem>
<listitem>
<simpara>
Push your changes to the public repository, and announce it
   to the public.
</simpara>
</listitem>
<listitem>
<simpara>
Every once in a while, <emphasis>git-repack</emphasis> the public repository.
   Go back to step 5. and continue working.
</simpara>
</listitem>
</orderedlist>
<simpara>A recommended work cycle for a "subsystem maintainer" who works
on that project and has an own "public repository" goes like this:</simpara>
<orderedlist numeration="arabic">
<listitem>
<simpara>
Prepare your work repository, by <emphasis>git-clone</emphasis> the public
   repository of the "project lead". The URL used for the
   initial cloning is stored in the remote.origin.url
   configuration variable.
</simpara>
</listitem>
<listitem>
<simpara>
Prepare a public repository accessible to others, just like
   the "project lead" person does.
</simpara>
</listitem>
<listitem>
<simpara>
Copy over the packed files from "project lead" public
   repository to your public repository, unless the "project
   lead" repository lives on the same machine as yours.  In the
   latter case, you can use <literal>objects/info/alternates</literal> file to
   point at the repository you are borrowing from.
</simpara>
</listitem>
<listitem>
<simpara>
Push into the public repository from your primary
   repository. Run <emphasis>git-repack</emphasis>, and possibly <emphasis>git-prune</emphasis> if the
   transport used for pulling from your repository supports
   packed repositories.
</simpara>
</listitem>
<listitem>
<simpara>
Keep working in your primary repository. Your changes
   include modifications of your own, patches you receive via
   e-mails, and merges resulting from pulling the "public"
   repositories of your "project lead" and possibly your
   "sub-subsystem maintainers".
</simpara>
<simpara>You can repack this private repository whenever you feel
like.</simpara>
</listitem>
<listitem>
<simpara>
Push your changes to your public repository, and ask your
   "project lead" and possibly your "sub-subsystem
   maintainers" to pull from it.
</simpara>
</listitem>
<listitem>
<simpara>
Every once in a while, <emphasis>git-repack</emphasis> the public repository.
   Go back to step 5. and continue working.
</simpara>
</listitem>
</orderedlist>
<simpara>A recommended work cycle for an "individual developer" who does
not have a "public" repository is somewhat different. It goes
like this:</simpara>
<orderedlist numeration="arabic">
<listitem>
<simpara>
Prepare your work repository, by <emphasis>git-clone</emphasis> the public
   repository of the "project lead" (or a "subsystem
   maintainer", if you work on a subsystem). The URL used for
   the initial cloning is stored in the remote.origin.url
   configuration variable.
</simpara>
</listitem>
<listitem>
<simpara>
Do your work in your repository on <emphasis>master</emphasis> branch.
</simpara>
</listitem>
<listitem>
<simpara>
Run <literal>git fetch origin</literal> from the public repository of your
   upstream every once in a while. This does only the first
   half of <literal>git pull</literal> but does not merge. The head of the
   public repository is stored in <literal>.git/refs/remotes/origin/master</literal>.
</simpara>
</listitem>
<listitem>
<simpara>
Use <literal>git cherry origin</literal> to see which ones of your patches
   were accepted, and/or use <literal>git rebase origin</literal> to port your
   unmerged changes forward to the updated upstream.
</simpara>
</listitem>
<listitem>
<simpara>
Use <literal>git format-patch origin</literal> to prepare patches for e-mail
   submission to your upstream and send it out. Go back to
   step 2. and continue.
</simpara>
</listitem>
</orderedlist>
</simplesect>
<simplesect id="_working_with_others_shared_repository_style">
<title>Working with Others, Shared Repository Style</title>
<simpara>If you are coming from CVS background, the style of cooperation
suggested in the previous section may be new to you. You do not
have to worry. git supports "shared public repository" style of
cooperation you are probably more familiar with as well.</simpara>
<simpara>See <xref linkend="gitcvs-migration(7)"/> for the details.</simpara>
</simplesect>
<simplesect id="_bundling_your_work_together">
<title>Bundling your work together</title>
<simpara>It is likely that you will be working on more than one thing at
a time.  It is easy to manage those more-or-less independent tasks
using branches with git.</simpara>
<simpara>We have already seen how branches work previously,
with "fun and work" example using two branches.  The idea is the
same if there are more than two branches.  Let&#8217;s say you started
out from "master" head, and have some new code in the "master"
branch, and two independent fixes in the "commit-fix" and
"diff-fix" branches:</simpara>
<literallayout>$ git show-branch
! [commit-fix] Fix commit message normalization.
 ! [diff-fix] Fix rename detection.
  * [master] Release candidate #1
---
 +  [diff-fix] Fix rename detection.
 +  [diff-fix~1] Better common substring algorithm.
+   [commit-fix] Fix commit message normalization.
  * [master] Release candidate #1
++* [diff-fix~2] Pretty-print messages.</literallayout>
<simpara>Both fixes are tested well, and at this point, you want to merge
in both of them.  You could merge in <emphasis>diff-fix</emphasis> first and then
<emphasis>commit-fix</emphasis> next, like this:</simpara>
<literallayout>$ git merge -m "Merge fix in diff-fix" diff-fix
$ git merge -m "Merge fix in commit-fix" commit-fix</literallayout>
<simpara>Which would result in:</simpara>
<literallayout>$ git show-branch
! [commit-fix] Fix commit message normalization.
 ! [diff-fix] Fix rename detection.
  * [master] Merge fix in commit-fix
---
  - [master] Merge fix in commit-fix
+ * [commit-fix] Fix commit message normalization.
  - [master~1] Merge fix in diff-fix
 +* [diff-fix] Fix rename detection.
 +* [diff-fix~1] Better common substring algorithm.
  * [master~2] Release candidate #1
++* [master~3] Pretty-print messages.</literallayout>
<simpara>However, there is no particular reason to merge in one branch
first and the other next, when what you have are a set of truly
independent changes (if the order mattered, then they are not
independent by definition).  You could instead merge those two
branches into the current branch at once.  First let&#8217;s undo what
we just did and start over.  We would want to get the master
branch before these two merges by resetting it to <emphasis>master~2</emphasis>:</simpara>
<literallayout>$ git reset --hard master~2</literallayout>
<simpara>You can make sure <literal>git show-branch</literal> matches the state before
those two <emphasis>git-merge</emphasis> you just did.  Then, instead of running
two <emphasis>git-merge</emphasis> commands in a row, you would merge these two
branch heads (this is known as <emphasis>making an Octopus</emphasis>):</simpara>
<literallayout>$ git merge commit-fix diff-fix
$ git show-branch
! [commit-fix] Fix commit message normalization.
 ! [diff-fix] Fix rename detection.
  * [master] Octopus merge of branches 'diff-fix' and 'commit-fix'
---
  - [master] Octopus merge of branches 'diff-fix' and 'commit-fix'
+ * [commit-fix] Fix commit message normalization.
 +* [diff-fix] Fix rename detection.
 +* [diff-fix~1] Better common substring algorithm.
  * [master~1] Release candidate #1
++* [master~2] Pretty-print messages.</literallayout>
<simpara>Note that you should not do Octopus because you can.  An octopus
is a valid thing to do and often makes it easier to view the
commit history if you are merging more than two independent
changes at the same time.  However, if you have merge conflicts
with any of the branches you are merging in and need to hand
resolve, that is an indication that the development happened in
those branches were not independent after all, and you should
merge two at a time, documenting how you resolved the conflicts,
and the reason why you preferred changes made in one side over
the other.  Otherwise it would make the project history harder
to follow, not easier.</simpara>
</simplesect>
<simplesect id="_see_also">
<title>SEE ALSO</title>
<simpara><xref linkend="gittutorial(7)"/>,
<xref linkend="gittutorial-2(7)"/>,
<xref linkend="gitcvs-migration(7)"/>,
<xref linkend="git-help(1)"/>,
<ulink url="everyday.html">Everyday git</ulink>,
<ulink url="user-manual.html">The Git User&#8217;s Manual</ulink></simpara>
</simplesect>
<simplesect id="_git">
<title>GIT</title>
<simpara>Part of the <xref linkend="git(1)"/> suite.</simpara>
</simplesect>
</article>
