diff options
| author | jet2tlf <jet2tlf@gmail.com> | 2024-06-01 04:28:12 +0000 |
|---|---|---|
| committer | jet2tlf <jet2tlf@gmail.com> | 2024-06-01 04:28:12 +0000 |
| commit | 1028bb5cf5b3cddce0582bdabbf520facbaf2f9b (patch) | |
| tree | 346f77a9c185a1afde23ef7ae03d6543fb0e9454 /cmd/mygit | |
| parent | 4fcb99ab9a5fa08116f7bce0499f123c39facc32 (diff) | |
| download | git-go-1028bb5cf5b3cddce0582bdabbf520facbaf2f9b.tar.gz git-go-1028bb5cf5b3cddce0582bdabbf520facbaf2f9b.zip | |
codecrafters submit [skip ci]
Diffstat (limited to 'cmd/mygit')
| -rw-r--r-- | cmd/mygit/main.go | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/cmd/mygit/main.go b/cmd/mygit/main.go index bbdb4a9..52312b2 100644 --- a/cmd/mygit/main.go +++ b/cmd/mygit/main.go @@ -3,9 +3,11 @@ package main import ( "bytes" "compress/zlib" + "crypto/sha1" "fmt" "io" "os" + "path/filepath" ) func main() { @@ -60,6 +62,56 @@ func main() { 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) |