-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.go
More file actions
97 lines (80 loc) · 2.01 KB
/
Copy pathgit.go
File metadata and controls
97 lines (80 loc) · 2.01 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
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
package gitops
import (
"fmt"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/transport/ssh"
"os"
"time"
)
type GitOptions struct {
WorkingDirectory string
Keys *ssh.PublicKeys
Branch string
Email string
Name string
}
func NewGitOptions(keys *ssh.PublicKeys) (*GitOptions, func(), error) {
dir, err := os.MkdirTemp("/tmp", "prefix")
if err != nil {
return nil, nil, err
}
return &GitOptions{
WorkingDirectory: dir,
Keys: keys,
Branch: "master",
Name: "gitops-commit-bot",
Email: "gitops-commit@example.com",
}, func() {
err := os.RemoveAll(dir)
if err != nil {
return
}
}, nil
}
func PushVersion(r *git.Repository, options *GitOptions, file string, message string) error {
tree, err := r.Worktree()
if err != nil {
return err
}
_, err = tree.Add(file)
if err != nil {
return fmt.Errorf("failed to stage file for comit:%w", err)
}
commit, err := tree.Commit(message, &git.CommitOptions{
Author: &object.Signature{
Name: options.Name,
Email: options.Email,
When: time.Now(),
},
})
if err != nil {
return fmt.Errorf("failed to commit: %w", err)
}
_, err = r.CommitObject(commit)
if err != nil {
return fmt.Errorf("failed to commit: %w", err)
}
err = r.Push(&git.PushOptions{
Auth: options.Keys,
})
if err != nil {
return fmt.Errorf("failed to push change to the repo: %w", err)
}
return nil
}
func GetPasswordlessKey(key string) (*ssh.PublicKeys, error) {
publicKeys, err := ssh.NewPublicKeysFromFile("git", key, "")
if err != nil {
return nil, fmt.Errorf("private/public key invalid: %w", err)
}
return publicKeys, nil
}
func cloneRepository(o *GitOptions, r string) (*git.Repository, error) {
return git.PlainClone(o.WorkingDirectory, false, &git.CloneOptions{
Auth: o.Keys,
URL: fmt.Sprintf("git@github.com:%s.git", r),
SingleBranch: true,
Depth: 1,
})
}