/
git_object.go
272 lines (242 loc) · 5.54 KB
/
git_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
package repository
import (
"bufio"
"bytes"
"compress/zlib"
"crypto/sha1"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"strconv"
"strings"
)
type GitObjectType string
const (
BLOB GitObjectType = "blob"
TREE = "tree"
COMMIT = "commit"
)
type (
ObjectReader func(
path string,
formatter GitFileFormatter,
) (*DeserializedGitObject, error)
FileReader func(path string) ([]byte, error)
)
var (
//reader to read a raw content from given path
Reader FileReader = func(path string) ([]byte, error) {
return ioutil.ReadFile(path)
}
//reader to read raw content as git obj
ObjReader ObjectReader = func(path string, formatter GitFileFormatter) (*DeserializedGitObject, error) {
content, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
return formatter.Deserialize(content)
}
)
type GitFileFormatter interface {
Serialize(data []byte, objType GitObjectType) (*SerializedGitObject, error)
Deserialize(data []byte) (*DeserializedGitObject, error)
Save(serialized *SerializedGitObject, path string) error
}
type TreeAlreadyExistError struct {
message string
}
type DefaultGitFileFormatter struct {
}
type DeserializedGitObject struct {
ObjType GitObjectType
Content string
}
type SerializedGitObject struct {
Hash Hash
Content []byte
}
type Hash string
func NewHash(hash string) (Hash, error) {
if len(hash) != sha1.Size*2 {
return "",
errors.New(
fmt.Sprintf(
"Wrong hash length ,should be %d, got %d",
sha1.Size*2,
len(hash),
),
)
}
return Hash(hash), nil
}
func (h Hash) Dir() string {
return string(h)[0:2]
}
//returns the whole directory to the file with given hash
func (h Hash) Path(objPath string) string {
return objPath + h.Dir() + "/" + h.FileName()
}
func (h Hash) FileName() string {
return string(h)[2:]
}
func (err *TreeAlreadyExistError) Error() string {
return err.message
}
func NewTreeAlreadyExistError(message string) *TreeAlreadyExistError {
return &TreeAlreadyExistError{
message: message,
}
}
func (obj *DefaultGitFileFormatter) Deserialize(data []byte) (*DeserializedGitObject, error) {
unzipped, err := unzipped(data)
unzippedContent := string(unzipped)
if err != nil {
return nil, err
}
return newDeserializedObj(unzippedContent)
}
func (obj *DefaultGitFileFormatter) Serialize(data []byte, objType GitObjectType) (*SerializedGitObject, error) {
header := header(data, objType)
result := append(header, data...)
hash, err := GenerateHash(result)
if err != nil {
return nil, err
}
zipped, err := zipped(result)
if err != nil {
return nil, err
}
return &SerializedGitObject{
Hash: Hash(hash),
Content: zipped,
}, nil
}
func (obj *DefaultGitFileFormatter) Save(serialized *SerializedGitObject, objPath string) error {
fullPath := objPath + serialized.Hash.Dir()
//dir may already exist
if _, err := os.Stat(fullPath); os.IsNotExist(err) {
os.Mkdir(fullPath, 0755)
}
file, err := os.Create(fullPath + "/" + serialized.Hash.FileName())
if err != nil {
return err
}
defer file.Close()
writer := bufio.NewWriter(file)
_, err = writer.Write(serialized.Content)
if err != nil {
return err
}
return writer.Flush()
}
//Get type of a object by given hash
func TypeByHash(
objPath string,
hash Hash,
reader FileReader,
fileFormatter GitFileFormatter,
) (GitObjectType, error) {
if !Exists(objPath + hash.Dir() + "/" + hash.FileName()) {
return "", errors.New(fmt.Sprintf("Object with hash %s doesn't exist", hash))
}
data, err := reader(objPath + hash.Dir() + "/" + hash.FileName())
if err != nil {
return "", err
}
deser, err := fileFormatter.Deserialize(data)
if err != nil {
return "", err
}
return deser.ObjType, nil
}
func newDeserializedObj(content string) (*DeserializedGitObject, error) {
spaceIndex := strings.Index(content, " ")
objType, err := AsGitObjectType(content[0:spaceIndex])
if err != nil {
return nil, err
}
nullIndex := strings.Index(content, "\x00")
length, err := strconv.Atoi(content[spaceIndex+1 : nullIndex])
if err != nil {
return nil, err
}
if length != len(content)-nullIndex-1 {
return nil,
errors.New(
fmt.Sprintf(
`Invalid git object for deserialization ,
the length in the head is %d , expected %d\n`,
length,
len(content)-nullIndex-1,
),
)
}
return &DeserializedGitObject{
ObjType: objType,
Content: content[nullIndex+1:],
}, nil
}
func unzipped(data []byte) ([]byte, error) {
buffer := bytes.NewReader(data)
reader, err := zlib.NewReader(buffer)
if err != nil {
return nil, err
}
defer reader.Close()
var out bytes.Buffer
_, err = io.Copy(&out, reader)
if err != nil {
return nil, err
}
return out.Bytes(), nil
}
func zipped(data []byte) ([]byte, error) {
var buffer bytes.Buffer
w := zlib.NewWriter(&buffer)
_, err := w.Write(data)
if err != nil {
return nil, err
}
w.Close()
return buffer.Bytes(), nil
}
func GenerateHash(data []byte) (string, error) {
hash := sha1.New()
_, err := hash.Write(data)
if err != nil {
return "", err
}
hashStr := fmt.Sprintf("%x", hash.Sum(nil))
return hashStr, nil
}
//[type] [length][null]
func header(data []byte, objType GitObjectType) []byte {
return []byte(
fmt.Sprintf(
"%s %d\x00",
objType,
len(data),
),
)
}
//convert given string to git object type
func AsGitObjectType(str string) (GitObjectType, error) {
switch str {
case "blob":
return BLOB, nil
case "tree":
return TREE, nil
case "commit":
return COMMIT, nil
default:
return "",
errors.New(
fmt.Sprintf(
"%s is not a valid git object type",
str,
),
)
}
}