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/object"
12)
13
14// Basic example of how to commit changes to the current branch to an existing
15// repository.
16func main() {
17 CheckArgs("<directory>")
18 directory := os.Args[1]
19
20 // Opens an already existing repository.
21 r, err := git.PlainOpen(directory)
22 CheckIfError(err)
23
24 w, err := r.Worktree()
25 CheckIfError(err)
26
27 // ... we need a file to commit so let's create a new file inside of the
28 // worktree of the project using the go standard library.
29 Info("echo \"hello world!\" > example-git-file")
30 filename := filepath.Join(directory, "example-git-file")
31 err = os.WriteFile(filename, []byte("hello world!"), 0644)
32 CheckIfError(err)
33
34 // Adds the new file to the staging area.
35 Info("git add example-git-file")
36 _, err = w.Add("example-git-file")
37 CheckIfError(err)
38
39 // We can verify the current status of the worktree using the method Status.
40 Info("git status --porcelain")
41 status, err := w.Status()
42 CheckIfError(err)
43
44 fmt.Println(status)
45
46 // Commits the current staging area to the repository, with the new file
47 // just created. We should provide the object.Signature of Author of the
48 // commit Since version 5.0.1, we can omit the Author signature, being read
49 // from the git config files.
50 Info("git commit -m \"example go-git commit\"")
51 commit, err := w.Commit("example go-git commit", &git.CommitOptions{
52 Author: &object.Signature{
53 Name: "John Doe",
54 Email: "john@doe.org",
55 When: time.Now(),
56 },
57 })
58
59 CheckIfError(err)
60
61 // Prints the current HEAD to verify that all worked well.
62 Info("git show -s")
63 obj, err := r.CommitObject(commit)
64 CheckIfError(err)
65
66 fmt.Println(obj)
67}