2 A tour of git: the basics
6 This document is a modified version of a document originally titled
7 "Distributed revision control with Mercurial" and originally authored
8 by Bryan O’Sullivan. The original document was obtained from
9 <http://hgbook.red-bean.com/>.
11 Copyright © 2006, 2007 Bryan O’Sullivan.
13 This material may be distributed only subject to the terms and
14 conditions set forth in version 1.0 of the Open Publication
15 License. Please refer to Appendix D for the license text.
17 As this is a modified version, the name of Bryan O'Sullivan is used
18 only to properly credit him with the original text. The appearance of
19 his name here explicitly does not assert or imply his endorsement of
20 this modified document.
22 Portions Copyright © 2007 Carl Worth.
24 Changes made by Carl include the following:
27 * Convert from HTML to markdown source syntax
28 * Eliminate all content except Chapter 2 and Appendix D
29 * Eliminate line numbers from examples
30 * Modified to describe git instead of mercurial
32 The source of this modified version can be obtained via git:
34 git clone git://cworth.org/git/hgbook-git
38 git clone http://cworth.org/git/hgbook-git
40 and can be [browsed online](http://git.cworth.org/git/hgbook-git)
42 ### 2.1 Installing git on your system
44 Prebuilt binary packages of git are available for many popular
45 operating systems. These make it easy to start using git on your
50 Because each Linux distribution has its own packaging tools, policies,
51 and rate of development, it’s difficult to give a comprehensive set of
52 instructions on how to install git binaries. The version of
53 git that you will end up with can vary depending on how active
54 the person is who maintains the package for your distribution.
56 To keep things simple, I will focus on installing git from the
57 command line under the most popular Linux distributions. Most of these
58 distributions provide graphical package managers that will let you
59 install git with a single click. The package name to look for is
60 often git, but is sometimes git-core, (due to an unfortunate name
61 with git, meaning GNU Interactive Tools).
65 apt-get install git-core
81 apt-get install git-core
85 A git-core package is available through
86 [macports](http://macports.org). Once macports is enabled, the command
93 Git has long been available as part of cygwin, and works reasonably
94 well in that environment. Some people find cygwin a particularly
95 inelegant approach to running git and would prefer a "native"
96 solution. To this end, the [msysgit
97 project](http://code.google.com/p/msysgit/) is rapidly putting
98 together a solution including various packages with full
99 installers. These include GitMe, a package to install the entire
100 development environment necessary to work on improving the msysgit
101 port of git, and WinGit, a package for installing just git itself
102 without the development environment, (still in Alpha as of September
105 ### 2.2 Getting started
107 To begin, we’ll use the “git version” command to find out whether git
108 is actually installed properly. Versions 1.5 and newer of git are much
109 more friendly to new users than versions 1.4 and older. If you aren't
110 yet running version 1.5 or newer, it's highly recommended that you
116 #### 2.2.1 Built-in help
118 Git provides a built-in help system. This is invaluable for those
119 times when you find yourself stuck trying to remember how to run a
120 command. If you are completely stuck, simply run “git help”; it will
121 print a brief list of commonly-used commands, along with a description
122 of what each does. If you ask for help on a specific command (such as
123 "git help init"), it prints more detailed information. [XXX: Does "git
124 help \<foo\>" work universally as a built-in or does it expect man to be
125 present and just call out to "man git-\<foo\>"?]
127 [XXX: The original hgbook includes the complete output of "hg
128 help init" at this point. I'm not including the corresponding
129 "git help init" output as it would be excessively long. The
130 description alone is quite reasonable, (other than a
131 not-too-helpful aside about the obsolete git-init-db command),
132 but it only comes after a full screen's worth of options
133 details. Might it make sense to have a more summarized help
134 output for "git help <foo>" than all of the documentation
135 available for git-<foo>? And perhaps alos provide a "git -v
136 help" similar to "hg -v help" for more?]
138 ### 2.3 Working with a repository
140 In git, everything happens inside a repository. The repository
141 for a project contains all of the files that “belong to” that project,
142 along with a historical record of the project’s files.
144 There’s nothing particularly magical about a repository; it is simply
145 a directory tree in your filesystem that git treats as
146 special. You can rename or delete a repository any time you like,
147 using either the command line or your file browser.
149 #### 2.3.1 Creating a copy of a remote repository
151 The "git clone" command is used to create a local copy of a remote
152 repository. This is generally the first git operation you will use
153 when beginning to work with an existing project.
155 We've assembled a simple repository that will be used in the examples
156 throughout this chapter. Go ahead and clone this repository now so
157 that you will be able to follow along:
159 $ git clone git://cworth.org/git/hello
160 Initialized empty Git repository in /tmp/hello/.git/
161 remote: Generating pack...
162 remote: Done counting 15 objects.
163 remote: Deltifying 15 objects...
164 remote: 100% (15/15) done
165 remote: Total 15 (delta 2), reused 15 (delta remote: 2)
166 Indexing 15 objects...
168 Resolving 2 deltas...
171 If for some reason you are prevented from talking on the git: port,
172 then there is also the capability to clone a repository (less
173 efficiently) over http:
175 $ git clone http://cworth.org/git/hello
176 Initialized empty Git repository in /tmp/hello/.git/
177 Getting alternates list for http://cworth.org/git/hello
178 Getting pack list for http://cworth.org/git/hello
179 Getting index for pack 04ecb061314ecbd60fa0610ecf55a1cbf85ea294
180 Getting pack 04ecb061314ecbd60fa0610ecf55a1cbf85ea294
181 which contains a1a0e8b392b17caf50325498df54802fe3c03710
182 walk a1a0e8b392b17caf50325498df54802fe3c03710
183 walk 72d4f10e4a27dbb09ace1503c20dbac1912ee451
184 walk 13ed136b983a9c439eddeea8a1c2076cffbb685f
185 walk 0a633bf58b45fcf1a8299d3c82cd1fd26d3f48f2
186 walk db7117a9dd9a6e57e8632ea5848e1101eee0fbde
188 If our clone succeeded, we should now have a local directory called
189 hello. This directory will contain some files.
193 drwxr-xr-x 3 cworth cworth 4096 2007-09-27 16:40 hello
197 These files have the same contents and history in our repository as
198 they do in the repository we cloned.
200 Every git repository is complete, self-contained, and
201 independent. It contains its own private copy of a project’s files and
202 history. A cloned repository remembers the location of the repository
203 it was cloned from, but it does not communicate with that repository,
204 or any other, unless you tell it to.
206 What this means for now is that we’re free to experiment with our
207 repository, safe in the knowledge that it’s a private “sandbox” that
208 won’t affect anyone else.
210 #### 2.3.2 Creating copy of a local repository
212 As mentioned above, a repository can be copied through normal
213 file-copying commands. But it's useful to use "git clone" even when
214 just making a local copy of a repository. Using "git clone" will be
215 much faster and will use much less space than a normal copy. In fact,
216 local clones are impressively fast. Go ahead and make a local clone
219 $ git clone hello hello-clone
220 Initialized empty Git repository in /tmp/hello-clone/.git/
223 [XXX Git says "empty" here, (presumably from the git-init
224 part), but shouldn't the command also report the succesful
225 clone which makes it non-empty? And what the heck does "0
226 blocks" mean? This is not friendly output.]
228 In fact, let's make a couple more clones at the same time. This isn't
229 just to drive home the speed and storage benefits of local clones, but
230 we'll use each of these cloned repositories in Section 2.8 when
231 discussing how to move commits between repositories:
233 $ git clone hello hello-pull
234 $ git clone hello hello-fetch
235 $ git clone hello hello-remote
237 #### 2.3.2 What’s in a repository?
239 When we take a more detailed look inside a repository, we can see that
240 it contains a directory named .git. This is where git keeps all
241 of its metadata for the repository.
245 . .. .git hello.c Makefile
247 The contents of the .git directory and its subdirectories are private
248 to git. Every other file and directory in the repository is
249 yours to do with as you please.
251 To introduce a little terminology, the .git directory is the “real”
252 repository, and all of the files and directories that coexist with it
253 are said to live in the working directory. An easy way to remember the
254 distinction is that the repository contains the history of your
255 project, while the working directory contains a snapshot of your
256 project at a particular point in history.
258 ### 2.4 A tour through history
260 One of the first things we might want to do with a new, unfamiliar
261 repository is understand its history. The “git log” command gives us a
265 commit a1a0e8b392b17caf50325498df54802fe3c03710
266 Author: Bryan O'Sullivan <bos@serpentine.com>
267 Date: Tue Sep 6 15:43:07 2005 -0700
271 commit 72d4f10e4a27dbb09ace1503c20dbac1912ee451
272 Author: Bryan O'Sullivan <bos@serpentine.com>
273 Date: Tue Sep 6 13:15:58 2005 -0700
275 Get make to generate the final binary from a .o file.
277 commit 13ed136b983a9c439eddeea8a1c2076cffbb685f
278 Author: Bryan O'Sullivan <bos@serpentine.com>
279 Date: Tue Sep 6 13:15:43 2005 -0700
281 Introduce a typo into hello.c.
283 commit 0a633bf58b45fcf1a8299d3c82cd1fd26d3f48f2
284 Author: Bryan O'Sullivan <mpm@selenic.com>
285 Date: Fri Aug 26 01:21:28 2005 -0700
289 commit db7117a9dd9a6e57e8632ea5848e1101eee0fbde
290 Author: Bryan O'Sullivan <mpm@selenic.com>
291 Date: Fri Aug 26 01:20:50 2005 -0700
293 Create a standard "hello, world" program
295 By default, this command prints a brief paragraph of output for each
296 change to the project that was recorded. In git terminology, we
297 call each of these recorded events a commit.
299 The fields in a record of output from “git log” are as follows.
301 * commit This field consists of a string of 40 hexadecimal characters.
302 This is a unique identifier for referring to particular commits.
303 * Author The identity of the person who authored the commit. This
304 field consist of two sub-fields for the user's name and email
305 address, (or at least an email-like idenitifer). Note that git
306 stores a separate "Committer" field for the person who commited
307 the change, (since often an author will email a change to a
308 maintainer that commits it). The "git log" command doesn't display
309 the Committer, but other git tools do.
310 * Date The date and time on which the commit was authored, (again
311 stored separately from the date the change was committed).
312 timezone in which it was created. (The date and time are displayed
313 in the timezone of the person who created the commit.)
314 * commit message The text message that the creator of the commit
315 entered to describe the commit, (generally a one-line summary
316 followed by more supporting text).
318 The default output printed by “git log” is purely a summary; it is
319 missing a lot of detail.
321 #### 2.4.1 Commits, revisions, and talking to other people
323 As English is a notoriously sloppy language, and computer science has
324 a hallowed history of terminological confusion (why use one term when
325 four will do?), revision control has a variety of words and phrases
326 that mean the same thing. If you are talking about git history
327 with other people, you will find that what we have called a “commit”
328 is often called a "revision". In other systems, a similar notion
329 is referred to as a "changeset". You might even see abbreviations of
330 these terms such as "rev", "change", or even "cset".
332 While it may not matter much what word you use to refer to the concept
333 of “a commit”, it's important to know how to name “a specific
334 commit”. We have already seen one means of referring to a particular
335 commit, the 40-character hexadecimal string shown by "git log". These
336 commit identifiers are powerful because they are permanent, unique
337 identifiers that always identify the same commit in any copy of a
338 repository. If two users are examining a working directory associated
339 with the same commit identifier, then those two users have precisely
340 the same contents in all files, and exactly the same history leading
343 So there are places where it is often important to archive the
344 complete commit identifier, (perhaps in bug-tracking systems to
345 indicate a specific commit that fixes a bug, for example). But often,
346 in more casual settings, it's more convenient to use abbreviated
347 commit identifiers. Git accept any unique prefix of a commit
348 identifier, (and for reasonably-sized project the first 8 or 10
349 characters are almost always unique).
351 And unlike the permanent commit identifiers, git also provides
352 transient means of identifying commits. In fact, in day-to-day use of
353 git, you will probably use these names more than commit
354 identifiers. One example is branch names, (such as the default
355 "master" branch in any git repository), or any project-specific branch
356 names such as "stable", "experimental", or "crazy-insane-changes". Git
357 also provides a special name "HEAD" which always refers to the current
360 #### 2.4.2 Naming related commits
362 Git offers simple ways to name revisions that are related to
363 particular revisions in the history. One syntax is the ~ suffix which
364 refers to the parent of a commit, or if followed by a number, to the
365 Nth parent. For example, since "HEAD" refers to the most recent commit
366 in the current branch, "HEAD~", refers to the previous commit, and
367 "HEAD~2" refers to two commits back in the history.
369 Another useful syntax is .. which can be used to specify a range of
370 commits. So "origin..master" specifies everything that has been
371 committed to master since it diverged from origin.
373 #### 2.4.3 Viewing specific revisions
375 You can use "git log" to explore the range syntax just introduced. For
376 example, to see a list of the most recent 3 revisions you can use
377 "HEAD~3..", (the destination of the range is implicitly HEAD in this
381 commit a1a0e8b392b17caf50325498df54802fe3c03710
382 Author: Bryan O'Sullivan <bos@serpentine.com>
383 Date: Tue Sep 6 15:43:07 2005 -0700
387 commit 72d4f10e4a27dbb09ace1503c20dbac1912ee451
388 Author: Bryan O'Sullivan <bos@serpentine.com>
389 Date: Tue Sep 6 13:15:58 2005 -0700
391 Get make to generate the final binary from a .o file.
393 commit 13ed136b983a9c439eddeea8a1c2076cffbb685f
394 Author: Bryan O'Sullivan <bos@serpentine.com>
395 Date: Tue Sep 6 13:15:43 2005 -0700
397 Introduce a typo into hello.c.
399 #### 2.4.4 Other log filters
401 Besides filtering by commit identifiers, git allows you to easily
402 filter the log output according to which files (or directories) are
403 modified by listing them after "--" which is necessary to distinguish
404 commit names from file names:
406 $ git log -- Makefile
407 commit 72d4f10e4a27dbb09ace1503c20dbac1912ee451
408 Author: Bryan O'Sullivan <bos@serpentine.com>
409 Date: Tue Sep 6 13:15:58 2005 -0700
411 Get make to generate the final binary from a .o file.
413 commit 0a633bf58b45fcf1a8299d3c82cd1fd26d3f48f2
414 Author: Bryan O'Sullivan <mpm@selenic.com>
415 Date: Fri Aug 26 01:21:28 2005 -0700
419 And "git log" can also filter based on the dates at which commits were
422 $ git log --since="2 weeks ago" --until="yesterday"
424 [XXX: By default, "git log" displays author dates as "Date"
425 but then uses commit dates when given a --since option. That
426 seems like broken defaults to me. Why the inconsistency?]
428 Another useful option is -n or --max-count which, unsurprisingly,
429 limits the maximum number of commits to be displayed.
431 #### 2.4.5 More detailed information
433 While the default information printed by “git log” is useful if you
434 already know what you’re looking for, you may need to see more details
435 of the change, such as the "diffstat" information with --stat:
437 $ git log --stat --max-count=3
438 commit a1a0e8b392b17caf50325498df54802fe3c03710
439 Author: Bryan O'Sullivan <bos@serpentine.com>
440 Date: Tue Sep 6 15:43:07 2005 -0700
445 1 files changed, 2 insertions(+), 6 deletions(-)
447 commit 72d4f10e4a27dbb09ace1503c20dbac1912ee451
448 Author: Bryan O'Sullivan <bos@serpentine.com>
449 Date: Tue Sep 6 13:15:58 2005 -0700
451 Get make to generate the final binary from a .o file.
454 1 files changed, 2 insertions(+), 0 deletions(-)
456 commit 13ed136b983a9c439eddeea8a1c2076cffbb685f
457 Author: Bryan O'Sullivan <bos@serpentine.com>
458 Date: Tue Sep 6 13:15:43 2005 -0700
460 Introduce a typo into hello.c.
463 1 files changed, 1 insertions(+), 1 deletions(-)
465 Or perhaps you'd like to see the actual patch content of each change,
466 which you can get with -p. That commit with the word typo in its name
467 looks suspicous, so let's tak a closer look. Remember that we can name
468 it as master~3, HEAD~3, or any prefix of its commit identifier, (such
471 $ git log -p -n 1 13ed136b
472 commit 13ed136b983a9c439eddeea8a1c2076cffbb685f
473 Author: Bryan O'Sullivan <bos@serpentine.com>
474 Date: Tue Sep 6 13:15:43 2005 -0700
476 Introduce a typo into hello.c.
478 diff --git a/hello.c b/hello.c
479 index ed55ec0..80b260c 100644
484 int main(int argc, char **argv)
486 - printf("hello, world!\n");
487 + printf("hello, world!\");
491 Of course, wanting to see all this information for a single commit is
492 such a common operation that it's given its own name in git, "git
493 show". So "git show 13ed136b" is a much easier way to get exactly the
497 commit 13ed136b983a9c439eddeea8a1c2076cffbb685f
498 Author: Bryan O'Sullivan <bos@serpentine.com>
499 Date: Tue Sep 6 13:15:43 2005 -0700
501 Introduce a typo into hello.c.
503 diff --git a/hello.c b/hello.c
504 index ed55ec0..80b260c 100644
509 int main(int argc, char **argv)
511 - printf("hello, world!\n");
512 + printf("hello, world!\");
516 ### 2.5 All about command options
518 Let’s take a brief break from exploring git commands to discuss
519 a pattern in the way that they work; you may find this useful to keep
520 in mind as we continue our tour.
522 Git has a consistent and straightforward approach to dealing
523 with the options that you can pass to commands. It follows the
524 conventions for options that are common to modern Linux and Unix
527 * Most options have long names. For example, as we’ve already seen,
528 the “git log" command accepts a --max-count=\<number\> option.
529 * Some options have short, single-character names. Often these are
530 aliases for long commands, (such as "-n \<number\>" instead of
531 --max-count=\<number\>), but sometimes the option exists in
532 short-form with no long-form equivalent, (such as -p). [XXX: It
533 wouldn't hurt to fix this by adding --patch, etc. right?]
534 * Long options start with two dashes (e.g. --max-count), while short
535 options start with one (e.g. -n).
537 * Option naming and usage is consistent across commands. For
538 example, every command that lets you specify a commit identifier
539 or range will accept the same expressions, (HEAD~3,
540 origin..master, 72d4f10e, etc), while any command that can be
541 limited by paths will accept the same expressions ("-- doc/
544 Many commands that print output of some kind can be made more quiet by
545 passing the -q or --quiet options.
547 ### 2.6 Making and reviewing changes
549 Now that we have a grasp of viewing history in git, let’s take a look
550 at making some changes and examining them. You should be working
551 within the "hello" directory that we originally cloned.
553 In the repository, we have a file hello.c that contains the classic
554 “hello, world” program. But this program currently has a syntax error
555 and won't compile, (there's a missing 'n' between the '\' and the '"'
556 on the line containing printf). Let's fix that now. You can use a text
557 editor to correct the file, or you can copy-and-paste the sed command
560 $ sed -i '/printf/s/\\"/\\n"/' hello.c
562 After you've made that change, the “git status” command will tell you
563 what git knows about the files in the repository.
569 # Changed but not updated:
570 # (use "git add <file>..." to update what will be committed)
574 no changes added to commit (use "git add" and/or "git commit -a")
576 First "git status" tells us that the current branch is "master". This
577 means that the master branch is what will be updated when we create a
580 Note: In git a branch is a very simple notion---it's simply a name
581 that points to a particular commit, (literally nothing more than a
582 pointer---look at the contents of .git/refs/heads/master if you're
583 curious). The fact that a branch is so light is what makes the
584 creation of new branches an instantaneous operation in git. Together
585 with the ease of merging, git makes branches a joy to work with. But
586 we'll delay talk of branching and merging to a future chapter.
588 Next “git status” prints a line with "modified" for each modified
589 file---in this case just hello.c. The “git status” command will not
590 print any output for files that have not been modified.
592 Notice that we didn’t need to inform git that we were going to modify
593 the file before we started, or that we had modified the file after we
594 were done; it was able to figure this out itself.
596 It’s a little bit helpful to know that we’ve modified hello.c, but we
597 might prefer to know exactly what changes we’ve made to it. To do
598 this, we use the “git diff” command.
601 diff --git a/hello.c b/hello.c
602 index 9a3ff79..ea364d3 100644
607 int main(int argc, char **argv)
609 - printf("hello, world!\");
610 + printf("hello, world!\n");
614 ### 2.7 Recording changes in a new commit
616 We can modify files, build and test our changes, and use “git status”
617 and “git diff” to review our changes, until we’re satisfied with what
618 we’ve done and arrive at a natural stopping point where we want to
619 record our work in a new commit.
621 If you'd like, go ahead and build the program now with "make" and run
622 it to ensure it works. Everything should look good so we're just about
623 ready to make a commit. Unsurprisingly, we'll be using "git commit" to
626 #### 2.7.1 Introducing yourself to git
628 Before you run "git commit" though, you should introduce yourself to
629 git. Git records your name and email address with each change that
630 you commit, (as both author and committer unless you tell it
631 otherwise), so that you and others will later be able to tell who made
634 Git tries to automatically figure out a sensible name and address to
635 attribute to both author and committer if you haven't explicitly told
636 it a name and address. And it tries a lot, (detailed below). If you're
637 not interested in these details, you might want to skip to the next
638 section which explains how to avoid all this guesswork and tell git
639 what your name and email address are.
641 Here is a list of all the guessing that git will attempt. It will
642 attempt each of the following methods, in order, (stopping for each of
643 the author and committer name and email as soon as a value is found):
645 1. If you specify a --author option to the “git commit” command on
646 the command line, followed by a "Real Name \<email@example.com\>"
647 string, then this name and addresss will be used for the author
648 fields. The committer fields will still be determined as
649 below. This option is very helpful for when applying a commit
650 originally authored by someone other than yourself.
651 2. If any of the `GIT_AUTHOR_NAME`, `GIT_AUTHOR_EMAIL`,
652 `GIT_COMMITTER`_NAME, or `GIT_COMMITER_EMAIL` environment variables
653 are set, then those values will be used for the corresponding
655 3. If you have a file in your home directory called .gitconfig, with
656 name or email settings in the [user] section, then these values
657 will be used to set any remaining author and committer
658 fields. For more details on the contents of this file, refer to
660 4. If you have a file in the local repository called .git/config,
661 again with name or email settings in the [user] section, then
662 these values will be used to set any remaining author and
664 5. If you have set the `EMAIL` environment variable, this will be used
665 to set author and committer email addresses if still unset.
666 6. git will query your system to find out your real name from
667 available GECOS field and your username, hostname, and domain to
668 construct an email address, (or at least an identifier resembling
671 If all of these mechanisms fail, "git commit" will fail, printing an
672 error message instructing you how to use "git config" to tell git your
673 name and email address.
675 You should think of the `GIT_AUTHOR`/`COMMITER_NAME`/`EMAIL` environment
676 variables and the --author option to the “git commit” command as ways
677 to override git’s default selection. For normal use, the simplest and
678 most robust way to set your information is by creating a .gitconfig
679 file, (either manually or with the "git config" command); see below
682 ##### Creating a git configuration file
684 To set your name and email address, just use the following commands:
686 git config --global user.name "Your Name"
687 git config --global user.email "you@example.com"
689 The --global option means that this command will set global
690 information, (affecting all repositories on this machine), in the
691 .gitconfig file in your home directory. Alternately, you could omit
692 the --global which would make the change take effect only in the local
693 repository. This is convenient if you want to have different email
694 addresses associated with different projects, for example.
696 Of course, git's configuration file is a simple-to-edit plain-text
697 file, so instead of using the above commands, you can also just edit
698 the files directly. Use your favorite editor to create a file called
699 .gitconfig in your home directory, (or if you ran the above commands
700 then it will be there already). The initial contents of your
701 .gitconfig should look like this.
703 # This is a git configuration file.
706 email = you@example.com
708 Similarly, you can make a repository-specific configuration by editing
709 .git/config in the local repository. It will already have some
710 sections present, (created by the "git clone"), just add a [user]
713 The “[user]” line begins a section of the config file, so you can read
714 the “name = ...” line as meaning “set the value of the name item in
715 the user section”. This is the same notion expressed with the
716 "user.name" syntax on the git-config command line. A section
717 continues until a new section begins, or the end of the file. Git
718 ignores empty lines and treats any text from “#” to the end of a line
721 ##### Choosing your name and email
723 You can use any text you like as the value of the name and email
724 configuration items, since this information is for reading by other
725 people, not for interpreting by git. It is conventional to use your
726 actual name as well as a valid email address. But some poepl, (notably
727 Linus Torvalds, the original author of git), actually like the default
728 username@hostname convention that git falls back on without any
729 additional information about an email address. There's no requirement
730 that the email address actually be valid, and perhaps it's useful to
731 be reminded which machine was used to create particular commits. So
732 choose the name and email you wish, or follow a particular project's
735 #### 2.7.2 Writing a commit message
737 When we commit a change, git drops us into a text editor to
738 enter a message that will describe the modifications we’ve made in
739 this commit. This is called the commit message. It will be a record
740 for readers of what we did and why, and it will be printed by “git log”
741 after we’ve finished committing.
745 Note: The -a on the command-line instructs git to commit the new
746 content of *all* tracked files that have been modified. This is a
747 convenience over explicitly listing filenames to be committed on the
748 "git commit" command line. It is useful to use "git commit \<files\>"
749 when there is a need to commit only some subset of the files that have
752 If new files need to be committed for the first time, just use "git
753 add \<file\>" before "git commit -a". If a file needs to be removed,
754 just remove it as normal before committing and "git commit -a" will
755 notice that---it does not need to be explicitly told about the
758 The editor that the “git commit” command drops us into will contain an
759 empty line, followed by a number of lines starting with “#”. These
760 lines contain the same information as seen in "git status" before:
763 # Please enter the commit message for your changes.
764 # (Comment lines starting with '#' will not be included)
766 # Changes to be committed:
767 # (use "git reset HEAD <file>..." to unstage)
772 # (use "git add <file>..." to include in what will be committed)
777 Notice that two untracked files (hello and hello.o) have now appeared
778 from the build process. Git is reminding us of these in case we
779 intended to commit them as well, (in which case we would need to "git
780 add" them). We don't actually want to commit these files so we will
781 ignore them for now, (and we could tell git to ignore them as well by
782 listing them in a .gitignore file).
784 Git will ignore all lines in the commit message that start with “#”;
785 it uses them only to give us information on the commit. Modifying or
786 deleting these lines has no effect.
788 #### 2.7.3 Writing a good commit message
790 A good commit message will generally have a single line that
791 summarizes the commit, a blank line, and then one or more pargraphs
792 with supporting detail. Since many tools only print the first line of
793 a commit message by default, it’s important that the first line stands
796 One example of a first-line-only viewer is "git log
797 --pretty=short". Other examples include graphical history viewers such
798 as gitk and gitview, and web-based viewers such as gitweb and cgit.
800 Here’s a real example of a commit message that doesn’t follow
801 this guideline, and hence has a summary that is not readable.
803 $ git log --pretty=short
804 commit 3ef5535144da88a854f7930503845cd44506c2e2
805 Author: Censored Person <censored.person@example.org>
807 include buildmeister/commondefs. Add an exports and install
809 As far as the remainder of the contents of the commit message are
810 concerned, there are no hard-and-fast rules. git itself doesn’t
811 interpret or care about the contents of the commit message, though
812 your project may have policies that dictate a certain kind of
815 My personal preference is for short, but informative, commit messages
816 that tell me something that I can’t figure out with a quick glance at
817 the output of "git log --stat" or “git log -p", (so repeating the list
818 of all modified files is not useful, for example).
820 #### 2.7.4 Aborting a commit
822 If you decide that you don’t want to commit while in the middle of
823 editing a commit message, simply exit from your editor without saving
824 the file that it’s editing. This will cause nothing to happen to
825 either the repository or the working directory.
827 #### 2.7.5 Admiring our new handiwork
829 Once we’ve finished the commit, we can use the “git show” command to
830 display the commit we just created. As discussed previously, this
831 command produces output that is identical to “git log -p”, but for
832 only a single revision, (and the most recent revision by default):
835 commit fd21e5d6c5eedee70137229ebf348c25181812ab
836 Author: Carl Worth <cworth@cworth.org>
837 Date: Fri Sep 28 12:50:16 2007 -0700
839 Fixed the typo so the program actuall complies now.
841 diff --git a/hello.c b/hello.c
842 index 9a3ff79..ea364d3 100644
847 int main(int argc, char **argv)
849 - printf("hello, world!\");
850 + printf("hello, world!\n");
854 Note that you will not see the same commit identifier for your commit,
855 even if the change you made is identical to mine. The commit
856 identifier incorporates not only the contents of the files, but commit
857 message, the author and committer names and emails, and the author and
858 commit dates. (OK, so now you probably know enough to be able to guess
859 the right command to produce a commit with exactly the commit
860 identifier shown above. Can you do it?)
862 #### 2.7.6 Fixing up a broken commit (before anyone else sees it)
864 So now that we've cloned a local repository, made a change to the
865 code, setup our name and email address, and made a careful commit,
866 we're just about ready to share our change with the world. But wait,
867 that commit message has some really embarrassing misspellings in
868 it. Wouldn't it be nice to touch those up before I post this commit
869 with a never-to-be-changed again commit identifier?
871 This is the exact situation for which "git commit --amend" was
873 So I can just run that now and fix the broken commit message:
877 Here's the final result:
880 commit 3c54ac672ec1130b36837f1b708054a7a1d402de
881 Author: Carl Worth <cworth@cworth.org>
882 Date: Fri Sep 28 12:50:16 2007 -0700
884 Fixed the typo so the program actually compiles now.
886 diff --git a/hello.c b/hello.c
887 index 9a3ff79..ea364d3 100644
892 int main(int argc, char **argv)
894 - printf("hello, world!\");
895 + printf("hello, world!\n");
899 Note that we didn't use "commit -a" this time. This means that "git
900 commit --amend" will amend only the commit message and not any of the
901 actual files being tracked, (even if some of them had been modified
902 between the commits).
904 It's also possible to use "git commit -a --amend" to similarly fix up
905 mistakes noticed in code. That will replace the most recent commit
906 with a different commit based on any new changes to files.
908 I do feel a little hesitant to mention "git commit -a --amend". It's a
909 handy command for fixing up something like a misspelling in a comment
910 in the code. But if there is anything more significant than that, then
911 it would generally be better to create an additional commit rather
912 than amending an existing commit. This is important for several
915 * The amend operation will destroy a state that was previously saved
916 in a commit. If it's just the commit message being changed, then
917 that's no big deal. But if the contents are being amended, then a
918 mistake could eliminate something valuable.
920 * All commits should be logically independent and as small as
921 possible. Abusing "git commit -a --amend" can cause a small commit
922 to grow and acquire unrelated changes.
924 It's worth emphasizing the value of minimal, independent commits. The
925 smaller the changes are the more useful the history will be when
926 actually using the history, not just viewing it. This is particularly
927 important when doing "git bisect"---that's a powerful tool for
928 isolating a single commit that introduces a bug. And it's much more
929 helpful when the commit it isolates is as small as possible.
931 One advantage of using git over some other systems is that the commit
932 speed is blazingly fast. The tool doesn't punish you at all for
933 committing as often as you get our project into a state that is worth
934 saving. "Commit early, commit often" is a well-supported mode of
937 ### 2.8 Sharing changes
939 We mentioned earlier that repositories in git are
940 self-contained. This means that the commit we just created exists
941 only in our hello repository. Let’s look at a few ways that we can
942 propagate this change into other repositories.
944 #### 2.8.1 Pulling changes from the original repository
946 Recall that in Section 2.3.2 we made several local clones of the hello
947 repository before we made any commits. This allows us to simulate what
948 happens when upstream changes have been committed after you originally
951 The simplest, (and quite common), scenario is that you inherently
952 trust any changes in the original repository and you want to pull
953 these directly into your clone. This might be the case if you are
954 using git simply to track the progress of a project without making any
957 In this case, the operation is as simple as just calling "git pull":
961 remote: Generating pack...
962 Unpacking 3 objects...
964 remote: Done counting 5 objects.
965 Result has 3 objects.
966 Deltifying 3 objects...
967 100% remote: (3/3) done
968 Total 3 (delta 1), reused 0 (delta 0)
969 * refs/remotes/origin/master: fast forward to branch 'master' of /tmp/hello
970 old..new: a1a0e8b..3c54ac6
971 Updating a1a0e8b..3c54ac6
974 1 files changed, 1 insertions(+), 1 deletions(-)
976 XXX: Git is fairly noisy here, but a user has little need to care
977 about the several stages of operation involved here. As a tutorial
978 writer I'd like to say "ignore all that progress stuff, and look at
979 where the stat information starts" but it's hard for a new user to
980 even be able to understand that. I think it would be ideal if all of
981 the progress-tracking spew were reduced to a single line. Something
982 like "Computing (100%) Transferring (100%)" or whatever.
984 After (lots!) of progresss indication, git gives a report of which
985 files were modified, (which is very useful for getting a quick feel
986 for what happened). If you would like more details on what changes
987 came in, git provides a range that is perfect for examining. Let's
988 take a look (again, the commit identifiers will be different for you
989 --- just copy-and-paste the range that git prints):
991 $ git log a1a0e8b..3c54ac6
992 commit 3c54ac672ec1130b36837f1b708054a7a1d402de
993 Author: Carl Worth <cworth@cworth.org>
994 Date: Fri Sep 28 12:50:16 2007 -0700
996 Fixed the typo so the program actually compiles now.
998 As expected, we received just the one commit.
1000 So that's all that's needed in the common case. Just run "git pull"
1001 everytime you want to pull in new changes that have landed in the
1002 upstream repository.
1004 Note: Mercurial users who are reading this might wonder if there's a
1005 need for the equivalent of "hg update" after doing a "git pull". And
1006 the answer is no. Unlike mercurial, "git pull", (and "git merge") will
1007 automatically update the working-directory files as necessary.
1009 #### 2.8.2 Using fetch and merge separately to pull
1011 Sometimes you may not know if you want to pull in the changes from the
1012 remote repository or not. It's useful to be able to examine them
1013 before accepting them into our branch. The "git pull" command shown in
1014 the previous section is conceptually the combination of two command,
1015 "git fetch" and "git merge". We can use these commands separately to
1016 examine the change before accepting it.
1018 So let's do that within the hello-fetch clone we made earlier. First
1019 we will do the fetch:
1023 remote: Generating pack...
1024 Unpacking 3 objects...
1025 remote: Done counting 5 objects.
1026 Result has 3 objects.
1027 Deltifying 3 objects...
1028 100% remote: (3/3) done
1029 Total 3 (delta 1), reused 0 (delta 0)
1031 * refs/remotes/origin/master: fast forward to branch 'master' of /tmp/hello/
1032 old..new: a1a0e8b..3c54ac6
1034 You may notice that the output here looks very much like the first
1035 portion of the output from "git pull". This is no coincidence. The
1036 new changes have been "fetched" into the current repository and are
1037 stored into "origin/master" and have not been into the current
1038 "master" branch. Remember that "master" is our current branch. So now,
1039 "origin/master" is the state of the master branch that exists in the
1040 "origin" repository, (the one we cloned from).
1042 The most convenient way to examine the fetched changes is with the
1043 "master..origin" range notation:
1045 $ git log master..origin
1046 commit 3c54ac672ec1130b36837f1b708054a7a1d402de
1047 Author: Carl Worth <cworth@cworth.org>
1048 Date: Fri Sep 28 12:50:16 2007 -0700
1050 Fixed the typo so the program actually compiles now.
1052 Another helpful way of visualizing what happened with "git fetch" here
1053 is to run "gitk --all", which gives a graphical representation of all
1054 branches. Here is what it would look like:
1056 [[img gitk-fetch.png]]
1058 Notice that origin/master points to a single commit that was committed
1059 on top of the state pointed to by the "master" branch.
1061 Let's assume we are happy with the changes and we want to include them
1062 into our master branch. To do this we simply run "git merge origin":
1065 Updating a1a0e8b..3c54ac6
1068 1 files changed, 1 insertions(+), 1 deletions(-)
1070 Again, you'll see that this precisely matches the final portion of the
1071 output from "git pull". Using "git fetch" and "git merge" let us
1072 achieve exactly what "git pull" did, but we were able to stop in the
1073 middle to examine the situation, (and we could have decided to reject
1074 the changes and not merge them---leaving our master branch unchanged).
1076 ##### On merges and "fast forward"
1078 You'll notice that we've been seeing the phrase "fast forward" several
1079 times. This is a special-case operation performed by "git merge" where
1080 a branch can be advanced along a linear sequence. This happens
1081 whenever you pull changes that build directly on top of the same
1082 commit you have as your most recent commit. In other words, there was
1083 never any divergence or simultaneous commits created in parallel in
1084 multiple repositories. If there had been parallel commits, then "git
1085 merge" would actually introduce a new merge commit to tie the two
1088 When a non-fast-forward merge occurs, there is always the possibility
1089 that a conflict occurs. In this case, "git merge" will leave conflict
1090 markers in the files and instruct you to resolve the conflicts. When
1091 you are finished, you would issue a "git commit -a" to create the
1094 #### 2.8.3 Using "git remote" to pull changes other repositories
1096 We've already described how "git pull" will pull in changes from the
1097 repository which was the origin of the clone operation. Git also
1098 provides excellent support for pulling changes from any other
1099 repository as well, (distributed, rather than centralized
1102 If you have a situation where you want to pull a single time from some
1103 repository, then you can simply give the path or URL of the repository
1104 on the "git pull" command line. However, it's often the case that if
1105 you want to pull changes from a repository once, you'll want to pull
1106 changes from that same repository again in the future. This is where
1107 the "git remote" notion is extremely useful---it allows you to
1108 associate simple names, (and behaviors), with remote repository URLs
1110 We've already seen one instance of "git remote" which is the creation
1111 of the "origin" remote which happens automatically during "git
1112 clone". Let's now create another. Let's assume you are going to be
1113 working in the hello-remote repository and you'd like to pull changes
1114 from the hello-pull repository, where your friend "fred" has been
1115 making changes. Here's how to setup the new remote:
1117 $ cd ../hello-remote
1118 $ git remote add fred ../hello-pull
1120 So that's a "git remote add" command line followed by an arbitrary
1121 name you'd like for the new remote (fred) and the URL of the remote
1122 (../hello-pull). Obviously, the URL could be a git:// URL or any other
1123 git-supported URL in addition to a local path.
1125 The "git remote" command is really just a helper for adding some
1126 entries to the .git/config file. You might find it more convenient to
1127 edit that file directly once you get comfortable with things.
1129 At this point the name "fred" will work much like the name "origin"
1130 has worked in previous examples. For example, we can fetch the changes
1131 fred has made with "git fetch fred":
1134 remote: Generating pack...
1135 Unpacking 3 objects...
1136 remote: Done counting 5 objects.
1137 Result has 3 objects.
1138 Deltifying 3 objects...
1139 100% remote: (3/3) done
1140 Total 3 (delta 1), reused 0 (delta 0)
1142 * refs/remotes/fred/master: storing branch 'master' of ../hello-pull
1145 Notice that this command-line only differs from the "git fetch" we did
1146 previously by explicitly naming which remote should be fetched. We
1147 could have explicitly said "git fetch origin" earlier.
1149 We can also list all known remote-tracking branches with "git branch
1157 These remote-tracking branches make it very easy to collaborate with
1158 people as they are working on experimental features not yet ready for
1159 upstream inclusion. For example, if fred's latest code is still
1160 trashing filesystems then he might not want to push it out the the
1161 project's primary repository. But he may still want my help with
1162 it. So he can push it to a branch in his own repository for which I've
1163 got a remote. Then on my next "git fetch fred" I might notice a new
1164 branch called fred/trashes-filesystems and I can examine his code with
1165 a command such as "git log ..fred/trashed-filesystems".
1167 So lots of side collaboration can go on easily, and people working
1168 only with the primary repository never even have to see this dangerous
1169 code. It's distributed development at its finest.
1171 #### 2.8.4 Checking out previous revisions
1173 It's often useful to examine the working-tree state of some specific
1174 revision other than the tip of some branch. For example, maybe you
1175 would like to build a particular tagged version, or maybe you'd like
1176 to test the behavior of the code before a particular change was
1177 introduced. To do this, use "git checkout" and pass it the name of any
1178 revision, (with a branch name, a tag name, or any other commit
1179 identifier). For example, to examine our project before the original
1180 typo was introduced:
1182 $ git checkout 0a633bf5
1183 Note: moving to "0a633bf5" which isn't a local branch
1184 If you want to create a new branch from this checkout, you may do so
1185 (now or later) by using -b with the checkout command again. Example:
1186 git checkout -b <new_branch_name>
1187 HEAD is now at 0a633bf... Create a makefile
1189 The note that git gives us is to indicate that we are checking out a
1190 non-branch revision. This is perfectly fine if we are just exploring
1191 history, but if we actually wanted to use this revision as the basis
1192 for new commits, we would first have to create a new branch name as it
1195 If we were to use "git checkout" with a branch name, then that would
1196 change the current branch, (meaning that any new commits would advance
1197 that branch pointer).
1199 For now, let's return back to the tip of the master branch by just
1200 checking it out again:
1202 $ git checkout master
1203 Previous HEAD position was 0a633bf... Create a makefile
1204 Switched to branch "master"
1206 #### 2.8.5 Pushing changes to another repository
1208 As an unsurprising parallel to "git pull", git also provides "git
1209 push" for pushing changes to another repository. Now, generally the
1210 purpose of pushing to a repository is to have some "collaboration
1211 point" where potentially multiple people might be pushing or
1212 pulling. Because there might be multiple people pushing into the
1213 repository at any point, it wouldn't make sense to have a
1214 working-directory associated with this repository.
1216 For this, git has the notion of a "bare" repository, which is simply a
1217 repository with no working directory. Let's create a new bare
1218 repository and push some changes into it:
1223 $ git --bare init --shared
1225 The --shared option sets up the necessary group file permissions so
1226 that other users in my group will be able to push into this repository
1229 Now lets return to our hello repository and push some changes to this
1230 new repository. Since this is our very first push into this repository
1231 we need to tell git which branches to push. The easiest way to do this
1232 is to use --all to indicate all branches:
1235 $ git push ../hello-bare --all
1236 updating 'refs/heads/master'
1237 from 0000000000000000000000000000000000000000
1238 to 3c54ac672ec1130b36837f1b708054a7a1d402de
1240 Done counting 18 objects.
1241 Deltifying 18 objects...
1243 Writing 18 objects...
1245 Total 18 (delta 3), reused 15 (delta 2)
1246 Unpacking 18 objects...
1248 refs/heads/master: 0000000000000000000000000000000000000000 -> 3c54ac672ec1130b36837f1b708054a7a1d402de
1250 For subsequent pushes we don't need to specify --all as "git push" by
1251 default pushes all branches that exist in both the local and remote
1252 repositories. Also, as with pull, instead of explicitly specifying a
1253 URL, you may also specify a remote to push to. And by default, after
1254 cloning a repository, "git push" with no other arguments will attempt
1255 to push back to the same origin repository. As this is often exactly
1256 what is wanted, you may find that "git push" alone is often exactly
1259 What happens if we try to pull or push changes and the receiving
1260 repository already has those changes? Nothing too exciting.
1262 $ git push ../hello-bare
1263 Everything up-to-date
1266 Open Publication License
1268 Version 1.0, 8 June 1999
1270 ### D.1 Requirements on both unmodified and modified versions
1272 The Open Publication works may be reproduced and distributed in whole
1273 or in part, in any medium physical or electronic, provided that the
1274 terms of this license are adhered to, and that this license or an
1275 incorporation of it by reference (with any options elected by the
1276 author(s) and/or publisher) is displayed in the reproduction.
1278 Proper form for an incorporation by reference is as follows:
1280 Copyright (c) year by author’s name or designee. This material may be
1281 distributed only subject to the terms and conditions set forth in the
1282 Open Publication License, vx.y or later (the latest version is
1283 presently available at
1284 [http://www.opencontent.org/openpub/][http://www.opencontent.org/openpub/]).
1286 The reference must be immediately followed with any options elected by
1287 the author(s) and/or publisher of the document (see section D.6).
1289 Commercial redistribution of Open Publication-licensed material is
1292 Any publication in standard (paper) book form shall require the
1293 citation of the original publisher and author. The publisher and
1294 author’s names shall appear on all outer surfaces of the book. On all
1295 outer surfaces of the book the original publisher’s name shall be as
1296 large as the title of the work and cited as possessive with respect to
1301 The copyright to each Open Publication is owned by its author(s) or
1304 ### D.3 Scope of license
1306 The following license terms apply to all Open Publication works,
1307 unless otherwise explicitly stated in the document.
1309 Mere aggregation of Open Publication works or a portion of an Open
1310 Publication work with other works or programs on the same media shall
1311 not cause this license to apply to those other works. The aggregate
1312 work shall contain a notice specifying the inclusion of the Open
1313 Publication material and appropriate copyright notice.
1315 Severability. If any part of this license is found to be unenforceable
1316 in any jurisdiction, the remaining portions of the license remain in
1319 No warranty. Open Publication works are licensed and provided “as is”
1320 without warranty of any kind, express or implied, including, but not
1321 limited to, the implied warranties of merchantability and fitness for
1322 a particular purpose or a warranty of non-infringement.
1324 ### D.4 Requirements on modified works
1326 All modified versions of documents covered by this license, including
1327 translations, anthologies, compilations and partial documents, must
1328 meet the following requirements:
1330 1. The modified version must be labeled as such.
1331 2. The person making the modifications must be identified and the
1332 modifications dated.
1333 3. Acknowledgement of the original author and publisher if
1334 applicable must be retained according to normal academic citation
1336 4. The location of the original unmodified document must be identified.
1337 5. The original author’s (or authors’) name(s) may not be used to
1338 assert or imply endorsement of the resulting document without the
1339 original author’s (or authors’) permission.
1341 ### D.5 Good-practice recommendations
1343 In addition to the requirements of this license, it is requested from
1344 and strongly recommended of redistributors that:
1346 1. If you are distributing Open Publication works on hardcopy or
1347 CD-ROM, you provide email notification to the authors of your
1348 intent to redistribute at least thirty days before your
1349 manuscript or media freeze, to give the authors time to provide
1350 updated documents. This notification should describe
1351 modifications, if any, made to the document.
1352 2. All substantive modifications (including deletions) be either
1353 clearly marked up in the document or else described in an
1354 attachment to the document.
1355 3. Finally, while it is not mandatory under this license, it is
1356 considered good form to offer a free copy of any hardcopy and
1357 CD-ROM expression of an Open Publication-licensed work to its
1360 ### D.6 License options
1362 The author(s) and/or publisher of an Open Publication-licensed
1363 document may elect certain options by appending language to the
1364 reference to or copy of the license. These options are considered part
1365 of the license instance and must be included with the license (or its
1366 incorporation by reference) in derived works.
1368 1. To prohibit distribution of substantively modified versions
1369 without the explicit permission of the author(s). “Substantive
1370 modification” is defined as a change to the semantic content of
1371 the document, and excludes mere changes in format or
1372 typographical corrections.
1374 To accomplish this, add the phrase “Distribution of substantively
1375 modified versions of this document is prohibited without the
1376 explicit permission of the copyright holder.” to the license
1379 2. To prohibit any publication of this work or derivative works in
1380 whole or in part in standard (paper) book form for commercial
1381 purposes is prohibited unless prior permission is obtained from
1382 the copyright holder.
1384 To accomplish this, add the phrase “Distribution of the work or
1385 derivative of the work in any standard (paper) book form is
1386 prohibited unless prior permission is obtained from the copyright
1387 holder.” to the license reference or copy.