1package main
2
3import (
4 "fmt"
5 "os"
6 "path/filepath"
7 "time"
8
9 "github.com/go-git/go-git/v5"
10 . "github.com/go-git/go-git/v5/_examples"
11 "github.com/go-git/go-git/v5/plumbing/format/config"
12 "github.com/go-git/go-git/v5/plumbing/object"
13)
14
15// This example requires building with the sha256 tag for it to work:
16// go run -tags sha256 main.go /tmp/repository
17
18// Basic example of how to initialise a repository using sha256 as the hashing algorithm.
19func main() {
20 CheckArgs("<directory>")
21 directory := os.Args[1]
22
23 os.RemoveAll(directory)
24
25 // Init a new repository using the ObjectFormat SHA256.
26 r, err := git.PlainInitWithOptions(directory, &git.PlainInitOptions{ObjectFormat: config.SHA256})
27 CheckIfError(err)
28
29 w, err := r.Worktree()
30 CheckIfError(err)
31
32 // ... we need a file to commit so let's create a new file inside of the
33 // worktree of the project using the go standard library.
34 Info("echo \"hello world!\" > example-git-file")
35 filename := filepath.Join(directory, "example-git-file")
36 err = os.WriteFile(filename, []byte("hello world!"), 0644)
37 CheckIfError(err)
38
39 // Adds the new file to the staging area.
40 Info("git add example-git-file")
41 _, err = w.Add("example-git-file")
42 CheckIfError(err)
43
44 // Commits the current staging area to the repository, with the new file
45 // just created. We should provide the object.Signature of Author of the
46 // commit Since version 5.0.1, we can omit the Author signature, being read
47 // from the git config files.
48 Info("git commit -m \"example go-git commit\"")
49 commit, err := w.Commit("example go-git commit", &git.CommitOptions{
50 Author: &object.Signature{
51 Name: "John Doe",
52 Email: "john@doe.org",
53 When: time.Now(),
54 },
55 })
56
57 CheckIfError(err)
58
59 // Prints the current HEAD to verify that all worked well.
60 Info("git show -s")
61 obj, err := r.CommitObject(commit)
62 CheckIfError(err)
63
64 fmt.Println(obj)
65}