-
Notifications
You must be signed in to change notification settings - Fork 157
/
github.go
364 lines (295 loc) · 8.95 KB
/
github.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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
package github
import (
"context"
"errors"
"fmt"
"io"
"net/url"
githubsdk "github.com/google/go-github/v57/github"
"github.com/hatchet-dev/hatchet/internal/encryption"
"github.com/hatchet-dev/hatchet/internal/integrations/vcs"
"github.com/hatchet-dev/hatchet/internal/repository"
"github.com/hatchet-dev/hatchet/internal/repository/prisma/db"
)
type GithubVCSProvider struct {
repo repository.APIRepository
appConf *GithubAppConf
serverURL string
enc encryption.EncryptionService
}
func NewGithubVCSProvider(appConf *GithubAppConf, repo repository.APIRepository, serverURL string, enc encryption.EncryptionService) GithubVCSProvider {
return GithubVCSProvider{
appConf: appConf,
repo: repo,
serverURL: serverURL,
enc: enc,
}
}
func ToGithubVCSProvider(provider vcs.VCSProvider) (res GithubVCSProvider, err error) {
res, ok := provider.(GithubVCSProvider)
if !ok {
return res, fmt.Errorf("could not convert VCS provider to Github VCS provider: %w", err)
}
return res, nil
}
func (g GithubVCSProvider) GetGithubAppConfig() *GithubAppConf {
return g.appConf
}
func (g GithubVCSProvider) GetVCSRepositoryFromWorkflow(workflow *db.WorkflowModel) (vcs.VCSRepository, error) {
var installationId string
var deploymentConf *db.WorkflowDeploymentConfigModel
var ok bool
if deploymentConf, ok = workflow.DeploymentConfig(); ok {
if installationId, ok = deploymentConf.GithubAppInstallationID(); !ok {
return nil, fmt.Errorf("module does not have github app installation id param set")
}
}
gai, err := g.repo.Github().ReadGithubAppInstallationByID(installationId)
if err != nil {
return nil, err
}
client, err := g.appConf.GetGithubClient(int64(gai.InstallationID))
if err != nil {
return nil, err
}
return &GithubVCSRepository{
repoOwner: deploymentConf.GitRepoOwner,
repoName: deploymentConf.GitRepoName,
serverURL: g.serverURL,
webhookURL: g.appConf.GetWebhookURL(),
client: client,
repo: g.repo,
enc: g.enc,
}, nil
}
type GithubVCSRepository struct {
repoOwner, repoName string
client *githubsdk.Client
repo repository.APIRepository
serverURL string
webhookURL string
enc encryption.EncryptionService
}
// GetKind returns the kind of VCS provider -- used for downstream integrations
func (g *GithubVCSRepository) GetKind() vcs.VCSRepositoryKind {
return vcs.VCSRepositoryKindGithub
}
func (g *GithubVCSRepository) GetRepoOwner() string {
return g.repoOwner
}
func (g *GithubVCSRepository) GetRepoName() string {
return g.repoName
}
// SetupRepository sets up a VCS repository on Hatchet.
func (g *GithubVCSRepository) SetupRepository(tenantId string) error {
repoOwner := g.GetRepoOwner()
repoName := g.GetRepoName()
_, err := g.repo.Github().ReadGithubWebhook(tenantId, repoOwner, repoName)
if err != nil && !errors.Is(err, db.ErrNotFound) {
return err
} else if err != nil {
opts, signingSecret, err := repository.NewGithubWebhookCreateOpts(g.enc, repoOwner, repoName)
if err != nil {
return err
}
gw, err := g.repo.Github().CreateGithubWebhook(tenantId, opts)
if err != nil {
return err
}
webhookURL := fmt.Sprintf("%s/api/v1/github/webhook/%s", g.webhookURL, gw.ID)
_, _, err = g.client.Repositories.CreateHook(
context.Background(), repoOwner, repoName, &githubsdk.Hook{
Config: map[string]interface{}{
"url": webhookURL,
"content_type": "json",
"secret": signingSecret,
},
Events: []string{"pull_request", "push"},
Active: githubsdk.Bool(true),
},
)
return err
}
return nil
}
// GetArchiveLink returns an archive link for a specific repo SHA
func (g *GithubVCSRepository) GetArchiveLink(ref string) (*url.URL, error) {
gURL, _, err := g.client.Repositories.GetArchiveLink(
context.TODO(),
g.GetRepoOwner(),
g.GetRepoName(),
githubsdk.Zipball,
&githubsdk.RepositoryContentGetOptions{
Ref: ref,
},
2,
)
return gURL, err
}
// GetBranch gets a full branch (name and sha)
func (g *GithubVCSRepository) GetBranch(name string) (vcs.VCSBranch, error) {
branchResp, _, err := g.client.Repositories.GetBranch(
context.TODO(),
g.GetRepoOwner(),
g.GetRepoName(),
name,
2,
)
if err != nil {
return nil, err
}
return &GithubBranch{branchResp}, nil
}
// ReadFile returns a file by a SHA reference or path
func (g *GithubVCSRepository) ReadFile(ref, path string) (io.ReadCloser, error) {
file, _, err := g.client.Repositories.DownloadContents(
context.Background(),
g.GetRepoOwner(),
g.GetRepoName(),
path,
&githubsdk.RepositoryContentGetOptions{
Ref: ref,
},
)
return file, err
}
func (g *GithubVCSRepository) ReadDirectory(ref, path string) ([]vcs.DirectoryItem, error) {
_, dirs, _, err := g.client.Repositories.GetContents(
context.Background(),
g.GetRepoOwner(),
g.GetRepoName(),
path,
&githubsdk.RepositoryContentGetOptions{
Ref: ref,
},
)
if err != nil {
return nil, err
}
res := []vcs.DirectoryItem{}
for _, item := range dirs {
if item.Type != nil && item.Name != nil {
res = append(res, vcs.DirectoryItem{
Type: *item.Type,
Name: *item.Name,
})
}
}
return res, nil
}
func (g *GithubVCSRepository) CreateOrUpdatePullRequest(tenantId, workflowRunId string, opts *vcs.CreatePullRequestOpts) (*db.GithubPullRequestModel, error) {
// determine if there's an open pull request for this workflow run
prs, err := g.repo.WorkflowRun().ListPullRequestsForWorkflowRun(tenantId, workflowRunId, &repository.ListPullRequestsForWorkflowRunOpts{
State: repository.StringPtr("open"),
})
if err != nil {
return nil, err
}
if len(prs) > 0 {
// double check that the PR is still open, cycle through PRs to find the first open one
for _, pr := range prs {
prCp := pr
ghPR, err := g.getPullRequest(tenantId, workflowRunId, &prCp)
if err != nil {
return nil, err
}
if prCp.PullRequestState != ghPR.GetState() {
defer g.repo.Github().UpdatePullRequest(tenantId, prCp.ID, &repository.UpdatePullRequestOpts{ // nolint: errcheck
State: repository.StringPtr(ghPR.GetState()),
})
}
if ghPR.GetState() == "open" {
return g.updatePullRequest(tenantId, workflowRunId, &prCp, opts)
}
}
}
// if we get here, we need to create a new PR
return g.createPullRequest(tenantId, workflowRunId, opts)
}
func (g *GithubVCSRepository) getPullRequest(tenantId, workflowRunId string, pr *db.GithubPullRequestModel) (*githubsdk.PullRequest, error) {
ghPR, _, err := g.client.PullRequests.Get(
context.Background(),
pr.RepositoryOwner,
pr.RepositoryName,
pr.PullRequestNumber,
)
return ghPR, err
}
func (g *GithubVCSRepository) updatePullRequest(tenantId, workflowRunId string, pr *db.GithubPullRequestModel, opts *vcs.CreatePullRequestOpts) (*db.GithubPullRequestModel, error) {
err := commitFiles(
g.client,
opts.Files,
opts.GitRepoOwner,
opts.GitRepoName,
opts.HeadBranchName,
)
if err != nil {
return nil, fmt.Errorf("Could not commit files: %w", err)
}
return pr, nil
}
func (g *GithubVCSRepository) createPullRequest(tenantId, workflowRunId string, opts *vcs.CreatePullRequestOpts) (*db.GithubPullRequestModel, error) {
var baseBranch string
if opts.BaseBranch == nil {
repo, _, err := g.client.Repositories.Get(
context.TODO(),
opts.GitRepoOwner,
opts.GitRepoName,
)
if err != nil {
return nil, err
}
baseBranch = repo.GetDefaultBranch()
} else {
baseBranch = *opts.BaseBranch
}
err := createNewBranch(g.client, opts.GitRepoOwner, opts.GitRepoName, baseBranch, opts.HeadBranchName)
if err != nil {
return nil, fmt.Errorf("Could not create PR: %w", err)
}
err = commitFiles(
g.client,
opts.Files,
opts.GitRepoOwner,
opts.GitRepoName,
opts.HeadBranchName,
)
if err != nil {
return nil, fmt.Errorf("Could not commit files: %w", err)
}
pr, _, err := g.client.PullRequests.Create(
context.Background(), opts.GitRepoOwner, opts.GitRepoName, &githubsdk.NewPullRequest{
Title: githubsdk.String(opts.Title),
Base: githubsdk.String(baseBranch),
Head: githubsdk.String(opts.HeadBranchName),
},
)
if err != nil {
return nil, err
}
return g.repo.WorkflowRun().CreateWorkflowRunPullRequest(tenantId, workflowRunId, &repository.CreateWorkflowRunPullRequestOpts{
RepositoryOwner: opts.GitRepoOwner,
RepositoryName: opts.GitRepoName,
PullRequestID: int(pr.GetID()),
PullRequestTitle: opts.Title,
PullRequestNumber: pr.GetNumber(),
PullRequestHeadBranch: opts.HeadBranchName,
PullRequestBaseBranch: baseBranch,
PullRequestState: pr.GetState(),
})
}
// CompareCommits compares a base commit with a head commit
func (g *GithubVCSRepository) CompareCommits(base, head string) (vcs.VCSCommitsComparison, error) {
commitsRes, _, err := g.client.Repositories.CompareCommits(
context.Background(),
g.GetRepoOwner(),
g.GetRepoName(),
base,
head,
&githubsdk.ListOptions{},
)
if err != nil {
return nil, err
}
return &GithubCommitsComparison{commitsRes}, nil
}