3 We take a peek under the hood and explain how Git performs its miracles. I will skimp over details. For in-depth descriptions refer to http://www.kernel.org/pub/software/scm/git/docs/user-manual.html[the user manual].
7 How can Git be so unobtrusive? Aside from occasional commits and merges, you can work as if you were unaware that version control exists. That is, until you need it, and that's when you're glad Git was watching over you the whole time.
9 Other version control systems don't let you forget about them. Permissions of files may be read-only unless you explicitly tell the server which files you intend to edit. The central server might be keeping track of who's checked out which code, and when. When the network goes down, you'll soon suffer. Developers constantly struggle with virtual red tape and bureaucracy.
11 The secret is the `.git` directory in your working directory. Git keeps the history of your project here. The initial "." stops it showing up in `ls` listings. Except when you're pushing and pulling changes, all version control operations operate within this directory.
13 You have total control over the fate of your files because Git doesn't care what you do to them. Git can easily recreate a saved state from `.git` at any time.
17 Most people associate cryptography with keeping information secret, but another equally important goal is keeping information safe. Proper use of cryptographic hash functions can prevent accidental or malicious data corruption.
19 A SHA1 hash can be thought of as a unique 160-bit ID number for every string of bytes you'll encounter in your life. Actually more than that: every string of bytes that any human will ever use over many lifetimes.
21 As a SHA1 hash is itself a string of bytes, we can hash strings of bytes containing other hashes. This simple observation is surprisingly useful: look up 'hash chains'. We'll later see how Git uses it to efficiently guarantee data integrity.
23 Briefly, Git keeps your data in the ".git/objects" subdirectory, where instead of normal filenames, you'll find only IDs. By using IDs as filenames, as well as a few lockfiles and timestamping tricks, Git transforms any humble filesystem into an efficient and robust database.
27 How does Git know you renamed a file, even though you never mentioned the fact explicitly? Sure, you may have run *git mv*, but that is exactly the same as a *git rm* followed by a *git add*.
29 Git heuristically ferrets out renames and copies between successive versions. In fact, it can detect chunks of code being moved or copied around between files! Though it cannot cover all cases, it does a decent job, and this feature is always improving. If it fails to work for you, try options enabling more expensive copy detection, and consider upgrading.
33 For every tracked file, Git records information such as its size, creation time and last modification time in a file known as the 'index'. To determine whether a file has changed, Git compares its current stats with that held the index. If they match, then Git can skip reading the file again.
35 Since stat calls are considerably faster than file reads, if you only edit a
36 few files, Git can update its state in almost no time.
38 === Bare Repositories ===
40 You may have been wondering what format those online Git repositories use.
41 They're plain Git repositories, just like your `.git` directory, except they've got names like `proj.git`, and they have no working directory associated with them.
43 Most Git commands expect the Git index to live in `.git`, and will fail on these bare repositories. Fix this by setting the `GIT_DIR` environment variable to the path of the bare repository, or running Git within the directory itself with the `--bare` option.
47 This http://lkml.org/lkml/2005/4/6/121[Linux Kernel Mailing List post] describes the chain of events that led to Git. The entire thread is a fascinating archaeological site for Git historians.
49 === The Object Database ===
51 Here's how to write a Git-like system from scratch in a few hours.
55 First, a magic trick. Pick a filename, any filename. In an empty directory:
57 $ echo sweet > YOUR_FILENAME
60 $ find .git/objects -type f
62 You'll see +.git/objects/aa/823728ea7d592acc69b36875a482cdf3fd5c8d+.
64 How do I know this without knowing the filename? It's because the
67 "blob" SP "6" NUL "sweet" LF
69 is aa823728ea7d592acc69b36875a482cdf3fd5c8d,
70 where SP is a space, NUL is a zero byte and LF is a linefeed. You can verify
73 $ printf "blob 6\000sweet\n" | sha1sum
75 Git is 'content-addressable': files are not stored according to their filename,
76 but rather by the hash of the data they contain, in a file we call a 'blob
77 object'. We can think of the hash as a unique ID for a file's contents, so
78 in a sense we are addressing files by their content. The initial "blob 6" is
79 merely a header consisting of the object type and its length in bytes; it
80 simplifies internal bookkeeping.
82 Thus I could easily predict what you would see. The file's name is irrelevant:
83 only the data inside is used to construct the blob object.
85 You may be wondering what happens to identical files. Try adding copies of
86 your file, with any filenames whatsoever. The contents of +.git/objects+ stay
87 the same no matter how many you add. Git only stores the data once.
89 By the way, the files within +.git/objects+ are compressed with zlib so you
90 should not stare at them directly. Filter them through
91 http://www.zlib.net/zpipe.c[zpipe -d], or type:
93 $ git cat-file -p aa823728ea7d592acc69b36875a482cdf3fd5c8d
95 which pretty-prints the given object.
99 But where are the filenames? They must be stored somewhere at some stage.
100 Git gets around to the filenames during a commit:
102 $ git commit # Type some message.
103 $ find .git/objects -type f
105 You should now see 3 objects. This time I cannot tell you what the 2 new files are, as it partly depends on the filename you picked. We'll proceed assuming you chose "rose". If you didn't, you can rewrite history to make it look like you did:
107 $ git filter-branch --tree-filter 'mv YOUR_FILENAME rose'
108 $ find .git/objects -type f
110 Now you should see the file
111 +.git/objects/05/b217bb859794d08bb9e4f7f04cbda4b207fbe9+, because this is the
112 SHA1 hash of its contents:
114 "tree" SP "32" NUL "100644 rose" NUL 0xaa823728ea7d592acc69b36875a482cdf3fd5c8d
116 Check this file does indeed contain the above by typing:
118 $ echo 05b217bb859794d08bb9e4f7f04cbda4b207fbe9 | git cat-file --batch
120 With zpipe, it's easy to verify the hash:
122 $ zpipe -d < .git/objects/05/b217bb859794d08bb9e4f7f04cbda4b207fbe9 | sha1sum
124 Hash verification is trickier via cat-file because its output contains more
125 than the raw uncompressed object file.
127 This file is a 'tree' object: a list of tuples consisting of a file
128 type, a filename, and a hash. In our example, the file type is "100644", which
129 means "rose" is a normal file, and the hash is the blob object that contains
130 the contents of "rose". Other possible file types are executables, symlinks or
131 directories. In the last case, the hash points to a tree object.
133 If you ran filter-branch, you'll have old objects you no longer need. Although
134 they will be jettisoned automatically once the grace period expires, we'll
135 delete them now to make our toy example easier to follow:
137 $ rm -r .git/refs/original
138 $ git reflog expire --expire=now --all
141 For real projects you should typically avoid commands like this, as you are
142 destroying backups. If you want a clean repository, it is usually best to make
143 a fresh clone. Also, take care when directly manipulating +.git+: what if a Git
144 command is running at the same time, or a sudden power outage occurs?
145 In general, refs should be deleted with *git update-ref -d*,
146 though usually it's safe to remove +refs/original+ by hand.
150 We've explained 2 of the 3 objects. The third is a 'commit' object. Its
151 contents depend on the commit message as well as the date and time it was
152 created. To match what we have here, we'll have to tweak it a little:
154 $ git commit --amend -m Shakespeare # Change the commit message.
155 $ git filter-branch --env-filter 'export
156 GIT_AUTHOR_DATE="Fri 13 Feb 2009 15:31:30 -0800"
157 GIT_AUTHOR_NAME="Alice"
158 GIT_AUTHOR_EMAIL="alice@example.com"
159 GIT_COMMITTER_DATE="Fri, 13 Feb 2009 15:31:30 -0800"
160 GIT_COMMITTER_NAME="Bob"
161 GIT_COMMITTER_EMAIL="bob@example.com"' # Rig timestamps and authors.
162 $ find .git/objects -type f
165 +.git/objects/49/993fe130c4b3bf24857a15d7969c396b7bc187+
166 which is the SHA1 hash of its contents:
169 "tree 05b217bb859794d08bb9e4f7f04cbda4b207fbe9" LF
170 "author Alice <alice@example.com> 1234567890 -0800" LF
171 "committer Bob <bob@example.com> 1234567890 -0800" LF
175 As before, you can run zpipe or cat-file to see for yourself.
177 This is the first commit, so there are no parent commits, but later commits
178 will always contain at least one line identifying a parent commit.
180 ==== Indistinguishable From Magic ====
182 There's little else to say. We have just exposed the secret behind Git's
183 powers. It seems too simple: it looks like you could mix together a few shell
184 scripts and add a dash of C code to cook up the above in a matter of hours,
185 mixing in lock files and fsyncs for robustness. In fact, this accurately
186 describes the earliest versions of Git. Nonetheless, apart from ingenious
187 packing tricks to save space, and ingenious indexing tricks to save time, we
188 now know how Git deftly changes a filesystem into a database perfect for
191 For example, if any file within the object database is corrupted by a disk
192 error, then its hash will no longer match, alerting us to the problem. By
193 hashing hashes of other objects, we maintain integrity at all levels. Commits
194 are atomic, that is, a commit can never only partially record changes: we can
195 only compute the hash of a commit and store it in the database after we already
196 have stored all relevant trees, blobs and parent commits. The object
197 database is immune to unexpected interruptions such as power outages.
199 We defeat even the most devious adversaries. Suppose somebody attempts to
200 stealthily modify the contents of a file in an ancient version of a project. To
201 keep the object database looking healthy, they must also change the hash of the
202 corresponding blob object since it's now a different string of bytes. This
203 means they'll have to change the hash of any tree object referencing the file,
204 and in turn change the hash of all commit objects involving such a tree, in
205 addition to the hashes of all the descendants of these commits. This implies the
206 hash of the official head differs to that of the bad repository. By
207 following the trail of mismatching hashes we can pinpoint the mutilated file,
208 as well as the commit where it was first corrupted.
210 In short, so long as the 20 bytes representing the last commit are safe,
211 it's impossible to tamper with a Git repository.
213 What about Git's famous features? Branching? Merging? Tags?
214 Mere details. The current head is kept in the file +.git/HEAD+,
215 which contains a hash of a commit object. The hash gets updated during a commit
216 as well as many other commands. Branches are almost the same: they are files in
217 +.git/refs/heads+. Tags too: they live in +.git/refs/tags+ but they
218 are updated by a different set of commands.