-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgit.go
106 lines (96 loc) · 2.24 KB
/
git.go
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
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/go-git/go-billy/v5"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/storage/memory"
)
type gitClient struct {
repository *git.Repository
worktree *git.Worktree
file billy.Filesystem
token string
config gitConfig
}
type gitConfig struct {
userName string
userEmail string
}
func newGitClient(ctx context.Context, token, repository string, config gitConfig) (*gitClient, error) {
fs := memfs.New()
// https://<GITHUB_TOKEN>@github.com/<REPO>.git
repo, err := git.CloneContext(ctx, memory.NewStorage(), fs, &git.CloneOptions{
URL: fmt.Sprintf("https://%[email protected]/%s.git", token, repository),
})
if err != nil {
fmt.Printf("failed to clone repository %s\n", repository)
return nil, err
}
w, err := repo.Worktree()
if err != nil {
fmt.Println("failed to get worktree")
return nil, err
}
return &gitClient{
repository: repo,
worktree: w,
file: fs,
token: token,
config: config,
}, nil
}
// Checkout new branch
func (g *gitClient) Checkout(refName string) (string, error) {
branch := plumbing.ReferenceName(refName)
if err := g.worktree.Checkout(&git.CheckoutOptions{
Create: true,
Branch: branch,
}); err != nil {
return "", nil
}
return branch.String(), nil
}
func (g *gitClient) Add(filePath string) error {
if _, err := g.worktree.Add(filePath); err != nil {
fmt.Printf("failed to git add file %s\n", filePath)
return err
}
return nil
}
func (g *gitClient) Commit(msg string) error {
commitHash, err := g.worktree.Commit(
msg,
&git.CommitOptions{
Author: &object.Signature{
Name: g.config.userName,
Email: g.config.userEmail,
When: time.Now(),
},
},
)
if err != nil {
fmt.Println("failed to git commit")
return err
}
fmt.Printf("commit %s has been created\n", commitHash.String())
return nil
}
func (g *gitClient) Push(ctx context.Context) error {
if err := g.repository.PushContext(
ctx,
&git.PushOptions{
Progress: os.Stdout,
RemoteName: "origin",
},
); err != nil {
fmt.Println("failed to git push")
return err
}
return nil
}