Reworded Git Grandmastery intro.
[gitmagic.git] / en / secrets.txt
blob38712dbdeab4938be92c4c87318f7d0ed98bfcbf
1 == Secrets Revealed ==
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].
5 === Invisibility ===
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 force you to constantly struggle with red tape and bureaucracy. Permissions of files may be read-only unless you explicitly tell a central server which files you intend to edit. The most basic commands may slow to a crawl as the number of users increases. Work grinds to a halt when the network or the central server goes down.
11 In contrast, Git simply keeps the history of your project in the `.git` directory in your working directory. This is your own copy of the history, so you can stay offline until you want to communicate with others. You have total control over the fate of your files because Git can easily recreate a saved state from `.git` at any time.
13 === Integrity ===
15 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.
17 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.
19 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.
21 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.
23 === Intelligence ===
25 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*.
27 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.
29 === Indexing ===
31 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 those cached in the index. If they match, then Git can skip reading the file again.
33 Since stat calls are considerably faster than file reads, if you only edit a
34 few files, Git can update its state in almost no time.
36 We stated earlier that the index is a staging area. Then how can the index
37 just be a bunch of file stats?
39 The index can be thought of as a staging area because the add command puts
40 files into Git's database and updates the index accordingly, while the commit
41 command, without options, creates a commit based on the state of the index.
43 === Git's Origins ===
45 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.
47 === The Object Database ===
49 Every version of your data is kept in the 'object database', which lives in the
50 subdirectory `.git/objects`; the other residents of `.git/` hold lesser data:
51 the index, branch names, tags, configuration options, logs, the current
52 location of the head commit, and so on. The object database is elementary yet
53 elegant, and the source of Git's power.
55 Each file within `.git/objects` is an 'object'. There are 3 kinds of objects
56 that concern us: 'blob' objects, 'tree' objects, and 'commit' objects.
58 === Blobs ===
60 First, a magic trick. Pick a filename, any filename. In an empty directory:
62  $ echo sweet > YOUR_FILENAME
63  $ git init
64  $ git add .
65  $ find .git/objects -type f
67 You'll see +.git/objects/aa/823728ea7d592acc69b36875a482cdf3fd5c8d+.
69 How do I know this without knowing the filename? It's because the
70 SHA1 hash of:
72  "blob" SP "6" NUL "sweet" LF
74 is aa823728ea7d592acc69b36875a482cdf3fd5c8d,
75 where SP is a space, NUL is a zero byte and LF is a linefeed. You can verify
76 this by typing:
78   $ printf "blob 6\000sweet\n" | sha1sum
80 Git is 'content-addressable': files are not stored according to their filename,
81 but rather by the hash of the data they contain, in a file we call a 'blob
82 object'. We can think of the hash as a unique ID for a file's contents, so
83 in a sense we are addressing files by their content. The initial `blob 6` is
84 merely a header consisting of the object type and its length in bytes; it
85 simplifies internal bookkeeping.
87 Thus I could easily predict what you would see. The file's name is irrelevant:
88 only the data inside is used to construct the blob object.
90 You may be wondering what happens to identical files. Try adding copies of
91 your file, with any filenames whatsoever. The contents of +.git/objects+ stay
92 the same no matter how many you add. Git only stores the data once.
94 By the way, the files within +.git/objects+ are compressed with zlib so you
95 should not stare at them directly. Filter them through
96 http://www.zlib.net/zpipe.c[zpipe -d], or type:
98  $ git cat-file -p aa823728ea7d592acc69b36875a482cdf3fd5c8d
100 which pretty-prints the given object.
102 === Trees ===
104 But where are the filenames? They must be stored somewhere at some stage.
105 Git gets around to the filenames during a commit:
107  $ git commit  # Type some message.
108  $ find .git/objects -type f
110 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:
112  $ git filter-branch --tree-filter 'mv YOUR_FILENAME rose'
113  $ find .git/objects -type f
115 Now you should see the file
116 +.git/objects/05/b217bb859794d08bb9e4f7f04cbda4b207fbe9+, because this is the
117 SHA1 hash of its contents:
119  "tree" SP "32" NUL "100644 rose" NUL 0xaa823728ea7d592acc69b36875a482cdf3fd5c8d
121 Check this file does indeed contain the above by typing:
123  $ echo 05b217bb859794d08bb9e4f7f04cbda4b207fbe9 | git cat-file --batch
125 With zpipe, it's easy to verify the hash:
127  $ zpipe -d < .git/objects/05/b217bb859794d08bb9e4f7f04cbda4b207fbe9 | sha1sum
129 Hash verification is trickier via cat-file because its output contains more
130 than the raw uncompressed object file.
132 This file is a 'tree' object: a list of tuples consisting of a file
133 type, a filename, and a hash. In our example, the file type is 100644, which
134 means `rose` is a normal file, and the hash is the blob object that contains
135 the contents of `rose'. Other possible file types are executables, symlinks or
136 directories. In the last case, the hash points to a tree object.
138 If you ran filter-branch, you'll have old objects you no longer need. Although
139 they will be jettisoned automatically once the grace period expires, we'll
140 delete them now to make our toy example easier to follow:
142  $ rm -r .git/refs/original
143  $ git reflog expire --expire=now --all
144  $ git prune
146 For real projects you should typically avoid commands like this, as you are
147 destroying backups. If you want a clean repository, it is usually best to make
148 a fresh clone. Also, take care when directly manipulating +.git+: what if a Git
149 command is running at the same time, or a sudden power outage occurs?
150 In general, refs should be deleted with *git update-ref -d*,
151 though usually it's safe to remove +refs/original+ by hand.
153 === Commits ===
155 We've explained 2 of the 3 objects. The third is a 'commit' object. Its
156 contents depend on the commit message as well as the date and time it was
157 created. To match what we have here, we'll have to tweak it a little:
159  $ git commit --amend -m Shakespeare  # Change the commit message.
160  $ git filter-branch --env-filter 'export
161      GIT_AUTHOR_DATE="Fri 13 Feb 2009 15:31:30 -0800"
162      GIT_AUTHOR_NAME="Alice"
163      GIT_AUTHOR_EMAIL="alice@example.com"
164      GIT_COMMITTER_DATE="Fri, 13 Feb 2009 15:31:30 -0800"
165      GIT_COMMITTER_NAME="Bob"
166      GIT_COMMITTER_EMAIL="bob@example.com"'  # Rig timestamps and authors.
167  $ find .git/objects -type f
169 You should now see
170 +.git/objects/49/993fe130c4b3bf24857a15d7969c396b7bc187+
171 which is the SHA1 hash of its contents:
173  "commit 158" NUL
174  "tree 05b217bb859794d08bb9e4f7f04cbda4b207fbe9" LF
175  "author Alice <alice@example.com> 1234567890 -0800" LF
176  "committer Bob <bob@example.com> 1234567890 -0800" LF
177  LF
178  "Shakespeare" LF
180 As before, you can run zpipe or cat-file to see for yourself.
182 This is the first commit, so there are no parent commits, but later commits
183 will always contain at least one line identifying a parent commit.
185 === Indistinguishable From Magic ===
187 Git's secrets seem too simple. It looks like you could mix together a few shell scripts and add a dash of C code to cook it up in a matter of hours: a melange of basic filesystem operations and SHA1 hashing, garnished with lock files and fsyncs for robustness. In fact, this accurately describes the earliest versions of Git. Nonetheless, apart from ingenious packing tricks to save space, and ingenious indexing tricks to save time, we now know how Git deftly changes a filesystem into a database perfect for version control.
189 For example, if any file within the object database is corrupted by a disk
190 error, then its hash will no longer match, alerting us to the problem. By
191 hashing hashes of other objects, we maintain integrity at all levels. Commits
192 are atomic, that is, a commit can never only partially record changes: we can
193 only compute the hash of a commit and store it in the database after we already
194 have stored all relevant trees, blobs and parent commits. The object
195 database is immune to unexpected interruptions such as power outages.
197 We defeat even the most devious adversaries. Suppose somebody attempts to
198 stealthily modify the contents of a file in an ancient version of a project. To
199 keep the object database looking healthy, they must also change the hash of the
200 corresponding blob object since it's now a different string of bytes. This
201 means they'll have to change the hash of any tree object referencing the file,
202 and in turn change the hash of all commit objects involving such a tree, in
203 addition to the hashes of all the descendants of these commits. This implies the
204 hash of the official head differs to that of the bad repository. By
205 following the trail of mismatching hashes we can pinpoint the mutilated file,
206 as well as the commit where it was first corrupted.
208 In short, so long as the 20 bytes representing the last commit are safe,
209 it's impossible to tamper with a Git repository.
211 What about Git's famous features? Branching? Merging? Tags?
212 Mere details. The current head is kept in the file +.git/HEAD+,
213 which contains a hash of a commit object. The hash gets updated during a commit
214 as well as many other commands. Branches are almost the same: they are files in
215 +.git/refs/heads+. Tags too: they live in +.git/refs/tags+ but they
216 are updated by a different set of commands.