-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommit.go
More file actions
49 lines (41 loc) · 1.25 KB
/
commit.go
File metadata and controls
49 lines (41 loc) · 1.25 KB
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
package main
import (
"fmt"
"log"
"os"
"strings"
)
func gitCommit(message string) {
headData, err := os.ReadFile(".git/HEAD")
if err != nil {
log.Fatal("Could not read HEAD:", err)
}
// ref: refs/heads/master
ref := strings.TrimSpace(string(headData))
parentHash := ""
if strings.HasPrefix(ref, "ref: ") {
refPath := strings.TrimPrefix(ref, "ref: ")
// Try to read the hash inside .git/refs/heads/master
hashData, err := os.ReadFile(".git/" + refPath)
if err == nil {
parentHash = strings.TrimSpace(string(hashData))
}
// If err != nil, it means this is the FIRST commit (parent remains empty)
} else {
log.Fatal("Detached HEAD state not supported for simple commit yet")
}
// 2. WRITE TREE (Take a snapshot)
treeHash := writeTree()
fmt.Println("Tree created:", treeHash)
// 3. COMMIT TREE (Create the object)
commitHash := commitTree(treeHash, message, parentHash)
fmt.Println("Commit created:", commitHash)
// 4. UPDATE HEAD (Move the branch pointer)
// We need to write 'commitHash' into .git/refs/heads/master
refPath := strings.TrimPrefix(ref, "ref: ")
err = os.WriteFile(".git/"+refPath, []byte(commitHash), 0644)
if err != nil {
log.Fatal("Could not update branch ref:", err)
}
fmt.Printf("Committed to %s\n", refPath)
}