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
|
package main
import (
"bytes"
"compress/zlib"
"crypto/sha1"
"fmt"
"io"
"os"
"path/filepath"
)
func main() {
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, "usage: mygit <command> [<args>...]\n")
os.Exit(1)
}
switch command := os.Args[1]; command {
case "init":
for _, dir := range []string{".git", ".git/objects", ".git/refs"} {
if err := os.MkdirAll(dir, 0755); err != nil {
fmt.Fprintf(os.Stderr, "Error creating directory: %s\n", err)
}
}
headFileContents := []byte("ref: refs/heads/main\n")
if err := os.WriteFile(".git/HEAD", headFileContents, 0644); err != nil {
fmt.Fprintf(os.Stderr, "Error writing file: %s\n", err)
}
fmt.Println("Initialized git directory")
case "cat-file":
object := os.Args[3]
filePath := fmt.Sprintf(".git/objects/%s/%s", object[:2], object[2:])
file, err := os.Open(filePath)
if err != nil {
fmt.Fprintf(os.Stderr, "Error opening file: %s\n", err)
os.Exit(1)
}
defer file.Close()
r, err := zlib.NewReader(file)
if err != nil {
fmt.Fprintf(os.Stderr, "Error creating zlib reader: %s\n", err)
os.Exit(1)
}
defer r.Close()
w, err := io.ReadAll(r)
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading zlib data: %s\n", err)
os.Exit(1)
}
parts := bytes.Split(w, []byte("\x00"))
if len(parts) < 2 {
fmt.Fprintf(os.Stderr, "Invalid zlib data\n")
os.Exit(1)
}
fmt.Print(string(parts[1]))
case "hash-object":
object := os.Args[3]
file, err := os.ReadFile(object)
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading file: %s\n", err)
os.Exit(1)
}
stats, err := os.Stat(object)
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting file stats: %s\n", err)
os.Exit(1)
}
content := string(file)
contentAndHeader := fmt.Sprintf("blob %d\x00%s", stats.Size(), content)
sha := sha1.Sum([]byte(contentAndHeader))
hash := fmt.Sprintf("%x", sha)
blobName := []rune(hash)
blobPath := ".git/objects/"
for i, v := range blobName {
blobPath += string(v)
if i == 1 {
blobPath += "/"
}
}
var buffer bytes.Buffer
z := zlib.NewWriter(&buffer)
z.Write([]byte(contentAndHeader))
z.Close()
if err := os.MkdirAll(filepath.Dir(blobPath), os.ModePerm); err != nil {
fmt.Fprintf(os.Stderr, "Error creating directory: %s\n", err)
os.Exit(1)
}
f, err := os.Create(blobPath)
if err != nil {
fmt.Fprintf(os.Stderr, "Error creating file: %s\n", err)
os.Exit(1)
}
defer f.Close()
if _, err := f.Write(buffer.Bytes()); err != nil {
fmt.Fprintf(os.Stderr, "Error writing to file: %s\n", err)
os.Exit(1)
}
fmt.Print(hash)
default:
fmt.Fprintf(os.Stderr, "Unknown command %s\n", command)
os.Exit(1)
}
}
|