-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblob.go
98 lines (75 loc) · 1.96 KB
/
blob.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
package git
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"os"
"path/filepath"
"git.codecrafters.io/0c40c1d7ba1ab4a0/object"
)
var ErrShortHash = errors.New("too short hash")
func (g *Git) CatFile(obj string) error {
path, err := g.findPath(obj)
if err != nil {
return fmt.Errorf("find object: %w", err)
}
typ, content, err := object.ReadFromFile(path)
if err != nil {
return fmt.Errorf("read file: %w", err)
}
switch typ {
case "blob", "commit":
_, err = os.Stdout.Write(content)
case "tree":
err = g.lsTree(content, false)
default:
return fmt.Errorf("unsupported object type: %v", typ)
}
if err != nil {
return fmt.Errorf("print: %w", err)
}
return nil
}
func (g *Git) HashObject(file string, write bool) (object.Hash, error) {
return g.writeObject("blob", file, write)
}
func (g *Git) writeObject(typ, file string, write bool) (object.Hash, error) {
var buf bytes.Buffer
key, err := object.WriteFile(&buf, typ, file)
if err != nil {
return object.Hash{}, fmt.Errorf("encode object: %w", err)
}
if !write {
return key, nil
}
err = g.writeToStorage(key, buf.Bytes())
if err != nil {
return object.Hash{}, fmt.Errorf("write to storage: %w", err)
}
return key, nil
}
func (g *Git) writeToStorage(key object.Hash, content []byte) error {
path := g.objectPath(key)
dir := filepath.Dir(path)
err := os.MkdirAll(dir, 0755)
if err != nil {
return fmt.Errorf("create object dir: %w", err)
}
err = os.WriteFile(path, content, 0644)
if err != nil {
return fmt.Errorf("write file: %w", err)
}
return nil
}
func (g *Git) findPath(obj string) (string, error) {
// TODO: deciding of branch names, tags and hash prefixes should be here
if len(obj) < 4 {
return "", errors.New("short object-hash")
}
return filepath.Join(g.gitRoot, "objects", obj[:2], obj[2:]), nil
}
func (g *Git) objectPath(key object.Hash) string {
hashStr := hex.EncodeToString(key[:])
return filepath.Join(g.gitRoot, "objects", hashStr[:2], hashStr[2:])
}