-
Notifications
You must be signed in to change notification settings - Fork 25
/
object.go
462 lines (399 loc) · 10.1 KB
/
object.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
package gitgo
import (
"bufio"
"bytes"
"compress/zlib"
"encoding/hex"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"time"
)
const (
RFC2822 = "Mon Jan 2 15:04:05 2006 -0700"
)
// GitObject represents a commit, tree, or blob.
// Under the hood, these may be objects stored directly
// or through packfiles
type GitObject interface {
Type() string
//Contents() string
}
type gitObject struct {
Type string
// Commit fields
Tree string
Parents []string
Author string
Committer string
Message []byte
Size string
// Tree
Blobs []objectMeta
Trees []objectMeta
// Blob
Contents []byte
}
// A Blob compresses content from a file
type Blob struct {
_type string
size string
Contents []byte
rawData []byte
}
func (b Blob) Type() string {
return b._type
}
type Commit struct {
_type string
Name SHA
Tree string
Parents []SHA
Author string
AuthorDate time.Time
Committer string
CommitterDate time.Time
Message []byte
size string
rawData []byte
}
func (c Commit) Type() string {
return c._type
}
type Tree struct {
_type string
Blobs []objectMeta
Trees []objectMeta
size string
}
func (t Tree) Type() string {
return t._type
}
// objectMeta contains the metadata
// (hash, permissions, and filename)
// corresponding either to a blob (leaf) or another tree
type objectMeta struct {
Hash SHA
Perms string
filename string
}
func NewObject(input SHA, basedir os.File) (obj GitObject, err error) {
repo := Repository{Basedir: basedir}
return repo.Object(input)
}
func newObject(input SHA, basedir *os.File, packfiles []*packfile) (obj GitObject, err error) {
if filepath.Base(basedir.Name()) != ".git" {
defer basedir.Close()
basedir, err = os.Open(filepath.Join(basedir.Name(), ".git"))
if err != nil {
return nil, err
}
}
candidateName := basedir.Name()
for {
candidate, err := os.Open(candidateName)
if err == nil {
basedir = candidate
break
}
if !os.IsNotExist(err) {
return nil, err
}
// This should not be the main condition of the for loop
// just in case the filesystem root directory contains
// a .git subdirectory
// TODO check for mountpoint
if candidateName == "/" {
return nil, fmt.Errorf("not a git repository (or any parent up to root /")
}
candidateName = filepath.Join(candidate.Name(), "..", "..", ".git")
}
if len(input) < 4 {
return nil, fmt.Errorf("input SHA must be at least 4 characters")
}
filename := filepath.Join(basedir.Name(), "objects", string(input[:2]), string(input[2:]))
_, err = os.Stat(filename)
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
// check the directory for a file with the SHA as a prefix
_, err = os.Stat(filepath.Join(basedir.Name(), "objects", string(input[:2])))
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
} else {
dirname := filepath.Join(basedir.Name(), "objects", string(input[:2]))
files, err := ioutil.ReadDir(dirname)
if err != nil {
return nil, err
}
for _, file := range files {
if strings.HasPrefix(file.Name(), string(input[2:])) {
return objectFromFile(filepath.Join(dirname, file.Name()), input, *basedir)
}
}
}
// try the packfile
for _, pack := range packfiles {
if p, ok := pack.objects[input]; ok {
return p.normalize(*basedir)
}
for _, object := range pack.objects {
if strings.HasPrefix(string(object.Name), string(input)) {
return object.normalize(*basedir)
}
}
}
return nil, fmt.Errorf("object not in any packfile: %s", input)
}
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
r, err := zlib.NewReader(f)
if err != nil {
return nil, err
}
return parseObj(r, input, *basedir)
}
func objectFromFile(filename string, name SHA, basedir os.File) (GitObject, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
r, err := zlib.NewReader(f)
if err != nil {
return nil, err
}
return parseObj(r, name, basedir)
}
func normalizePerms(perms string) string {
// TODO don't store permissions as a string
for len(perms) < 6 {
perms = "0" + perms
}
return perms
}
func parseObj(r io.Reader, name SHA, basedir os.File) (result GitObject, err error) {
var resultType string
var resultSize string
scnr := scanner{r, nil, nil}
for scnr.scan() {
txt := string(scnr.data)
if txt == " " {
break
}
resultType += txt
}
for scnr.scan() {
txt := string(scnr.data)
if txt == "\x00" {
break
}
resultSize += txt
}
if scnr.Err() != nil {
return nil, scnr.Err()
}
switch resultType {
case "commit":
return parseCommit(r, resultSize, name)
case "tree":
return parseTree(r, resultSize, basedir)
case "blob":
return parseBlob(r, resultSize)
default:
err = fmt.Errorf("Received unknown object type %s", resultType)
}
return
}
func parseCommit(r io.Reader, resultSize string, name SHA) (Commit, error) {
var commit = Commit{_type: "commit", size: resultSize}
scnr := bufio.NewScanner(r)
scnr.Split(ScanLinesNoTrim)
var commitMessageLines [][]byte
for scnr.Scan() {
line := scnr.Bytes()
trimmedLine := bytes.TrimRight(line, "\r\n")
if commitMessageLines == nil && len(bytes.Fields(trimmedLine)) == 0 {
// Everything after the first empty line is the commit message
commitMessageLines = [][]byte{}
continue
}
if commitMessageLines != nil {
// We have already seen an empty line
commitMessageLines = append(commitMessageLines, line)
continue
}
parts := bytes.Fields(trimmedLine)
key := parts[0]
switch keyType(key) {
case treeKey:
commit.Tree = string(parts[1])
case parentKey:
commit.Parents = append(commit.Parents, SHA(string(parts[1])))
case authorKey:
authorline := string(bytes.Join(parts[1:], []byte(" ")))
author, date, err := parseAuthorString(authorline)
if err != nil {
return commit, err
}
commit.Author = author
commit.AuthorDate = date
case committerKey:
committerline := string(bytes.Join(parts[1:], []byte(" ")))
committer, date, err := parseCommitterString(committerline)
if err != nil {
return commit, err
}
commit.Committer = committer
commit.CommitterDate = date
default:
err := fmt.Errorf("encountered unknown field in commit: %s", key)
return commit, err
}
}
commit.Name = name
commit.Message = bytes.Join(commitMessageLines, []byte("\n"))
return commit, nil
}
func parseTree(r io.Reader, resultSize string, basedir os.File) (Tree, error) {
var tree = Tree{_type: "tree", size: resultSize}
scanner := bufio.NewScanner(r)
scanner.Split(ScanNullLines)
var tmp objectMeta
var resultObjs []objectMeta
for count := 0; ; count++ {
done := !scanner.Scan()
if done {
break
}
txt := scanner.Text()
if count == 0 {
// the first time through, scanner.Text() will be
// <perms> <filename>
// separated by a space
fields := strings.Fields(txt)
tmp.Perms = normalizePerms(fields[0])
tmp.filename = fields[1]
continue
}
// after the first time through, scanner.Text() will be
// <sha><perms2> <file2>
// where perms2 and file2 refer to the permissions and filename (respectively)
// of the NEXT object, and <sha> is the first 20 bytes exactly.
// If there is no next object (this is the last object)
// then scanner.Text() will yield exactly 20 bytes.
// decode the next 20 bytes to get the SHA
tmp.Hash = SHA(hex.EncodeToString([]byte(txt[:20])))
resultObjs = append(resultObjs, tmp)
if len(txt) <= 20 {
// We've read the last line
break
}
// Now, tmp points to the next object in the tree listing
tmp = objectMeta{}
remainder := txt[20:]
fields := strings.Fields(remainder)
tmp.Perms = normalizePerms(fields[0])
tmp.filename = fields[1]
}
if err := scanner.Err(); err != nil && err != io.EOF {
return tree, err
}
for _, part := range resultObjs {
obj, err := NewObject(part.Hash, basedir)
if err != nil {
return tree, err
}
if o, ok := obj.(*packObject); ok {
obj, err = o.normalize(basedir)
if err != nil {
return tree, err
}
}
switch obj.Type() {
case "tree":
tree.Trees = append(tree.Trees, part)
case "blob":
tree.Blobs = append(tree.Blobs, part)
default:
return tree, fmt.Errorf("Unknown type found: %s", obj.Type())
}
}
return tree, nil
}
func parseBlob(r io.Reader, resultSize string) (Blob, error) {
var blob = Blob{_type: "blob", size: resultSize}
bts, err := ioutil.ReadAll(r)
blob.Contents = bts
return blob, err
}
func findUniquePrefix(prefix SHA, files []os.FileInfo) (os.FileInfo, error) {
var result os.FileInfo
for _, file := range files {
if file.IsDir() {
continue
}
if strings.HasPrefix(file.Name(), string(prefix)) {
if result != nil {
return nil, fmt.Errorf("prefix is not unique: %s", prefix)
}
result = file
}
}
if result == nil {
return nil, os.ErrNotExist
}
return result, nil
}
// The ommitter string is in the same format as
// the author string, and oftentimes shares
// the same value as the author string.
func parseCommitterString(str string) (committer string, date time.Time, err error) {
return parseAuthorString(str)
}
// parseAuthorString parses the author string.
func parseAuthorString(str string) (author string, date time.Time, err error) {
const layout = "Mon Jan _2 15:04:05 2006 -0700"
const layout2 = "Mon Jan _2 15:04:05 2006"
var authorW bytes.Buffer
var dateW bytes.Buffer
s := bufio.NewScanner(strings.NewReader(str))
s.Split(bufio.ScanBytes)
// git will ignore '<' if it appears in an author's name
// so we can safely use it as a delimiter
for s.Scan() {
authorW.Write(s.Bytes())
if s.Text() == ">" {
break
}
}
for s.Scan() {
dateW.Write(s.Bytes())
}
if s.Err() != nil {
err = s.Err()
return
}
timestamp, err := strconv.Atoi(strings.Fields(dateW.String())[0])
if err != nil {
return
}
timezone := strings.Fields(dateW.String())[1]
hours, err := strconv.Atoi(timezone)
if err != nil {
return
}
t := time.Unix(int64(timestamp), 0).In(time.FixedZone("", hours*60*60/100))
date, err = time.Parse(layout, fmt.Sprintf("%s %s", t.Format(layout2), timezone))
return strings.TrimSpace(authorW.String()), date, err
}