/
git.go
223 lines (207 loc) · 5 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package plugin
import (
"context"
"fmt"
"log"
"os"
"os/user"
"path/filepath"
"strings"
"time"
"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/plumbing/transport"
"github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/go-git/go-git/v5/plumbing/transport/ssh"
"github.com/jrcichra/image-gatherer/pkg/registry"
)
type Git struct {
State
}
var _ InputPlugin = &Git{}
func getTempDir() (string, error) {
return os.MkdirTemp("", "")
}
func buildAuth(username, password, sshStr string) (transport.AuthMethod, error) {
var auth transport.AuthMethod
if username != "" && password != "" {
auth = &http.BasicAuth{
Username: username,
Password: password,
}
} else if sshStr == "true" {
user, err := user.Current()
if err != nil {
return auth, err
}
// TODO make SSH more configurable
homedir := fmt.Sprintf("%s/.ssh/id_rsa", user.HomeDir)
auth, err = ssh.NewPublicKeysFromFile("git", homedir, "")
if err != nil {
return auth, err
}
}
return auth, nil
}
func (g *Git) GetTag(ctx context.Context, container string, options map[string]string) (string, error) {
username, _ := os.LookupEnv(options["username_env"])
password, _ := os.LookupEnv(options["password_env"])
ssh := options["ssh"]
branch := options["branch"]
url := options["url"]
tempDir, err := getTempDir()
defer func() {
err = os.RemoveAll(tempDir)
if err != nil {
panic(err)
}
}()
if err != nil {
return "", err
}
// get tags from registry
r, err := registry.NewRegistry(container)
if err != nil {
return "", err
}
tags, err := r.GetAllTags(ctx, container)
if err != nil {
return "", err
}
// parse git commits
fullBranchName := fmt.Sprintf("refs/heads/%s", branch)
auth, err := buildAuth(username, password, ssh)
if err != nil {
return "", err
}
_, err = git.PlainCloneContext(ctx, tempDir, false, &git.CloneOptions{
URL: url,
ReferenceName: plumbing.ReferenceName(fullBranchName),
SingleBranch: true,
Auth: auth,
})
if err != nil {
return "", err
}
repo, err := git.PlainOpen(tempDir)
if err != nil {
return "", err
}
ref, err := repo.Reference(plumbing.ReferenceName(fullBranchName), true)
if err != nil {
return "", err
}
commit, err := repo.CommitObject(ref.Hash())
var matchedTag string
for matchedTag == "" {
if err != nil {
return "", err
}
if commit == nil {
return "", fmt.Errorf("commit returned was nil")
}
fullHash := commit.Hash.String()
// loop through the tags and see if the hash is in there
// TODO improve regex for matching tags to hashes, or expose it
for _, tag := range tags {
// clean up the tag
trimmedTag := strings.TrimPrefix(tag, "sha-")
// is this tag part of the latest hash?
if strings.HasPrefix(fullHash, trimmedTag) || strings.HasSuffix(fullHash, trimmedTag) {
// found it
matchedTag = tag
break
}
}
// if we didn't match, check the next parent
if matchedTag == "" {
log.Printf("%s: container image for %s not found. Checking parent...", container, fullHash)
commit, err = commit.Parents().Next()
if err != nil {
return "", err
}
}
}
// the response should be the full output
result := fmt.Sprintf("%s:%s", container, matchedTag)
return result, nil
}
var _ OutputPlugin = &Git{}
func (g *Git) Synth(ctx context.Context, options map[string]string) error {
filename := options["filename"]
username, _ := os.LookupEnv(options["username_env"])
password, _ := os.LookupEnv(options["password_env"])
ssh := options["ssh"]
branch := options["branch"]
url := options["url"]
tempDir, err := getTempDir()
defer func() {
err = os.RemoveAll(tempDir)
if err != nil {
panic(err)
}
}()
auth, err := buildAuth(username, password, ssh)
if err != nil {
return err
}
fullBranchName := fmt.Sprintf("refs/heads/%s", branch)
repo, err := git.PlainCloneContext(ctx, tempDir, false, &git.CloneOptions{
URL: url,
ReferenceName: plumbing.ReferenceName(fullBranchName),
SingleBranch: true,
Auth: auth,
Depth: 1,
})
if err != nil {
return err
}
fullPath := filepath.Join(tempDir, filename)
file, err := os.Create(fullPath)
if err != nil {
return err
}
defer file.Close()
content, err := g.Marshal()
if err != nil {
return err
}
if _, err := file.Write(content); err != nil {
return err
}
w, err := repo.Worktree()
if err != nil {
return err
}
status, err := w.Status()
if err != nil {
return err
}
// do nothing if there's no change
if status.IsClean() {
return nil
}
if _, err := w.Add(filename); err != nil {
return err
}
message := fmt.Sprintf("chore: update %s", filename)
_, err = w.Commit(message, &git.CommitOptions{
Author: &object.Signature{
Name: "Image Gatherer",
Email: "imagegatherer@jrcichra.dev",
When: time.Now(),
},
AllowEmptyCommits: false,
})
if err != nil {
return err
}
err = repo.PushContext(ctx, &git.PushOptions{
Auth: auth,
})
if err != nil {
return err
}
return nil
}