-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathgraphql.go
More file actions
346 lines (311 loc) · 8.67 KB
/
Copy pathgraphql.go
File metadata and controls
346 lines (311 loc) · 8.67 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
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
package github
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"regexp"
"strings"
"time"
"github.com/Masterminds/semver/v3"
"github.com/google/go-github/v74/github"
)
type GQLOutput struct {
Data GQLData `json:"data"`
}
type GQLData struct {
Repository GQLRepo `json:"repository"`
}
type GQLPageInfo struct {
HasNextPage bool `json:"hasNextPage"`
EndCursor string `json:"endCursor"`
}
type GQLRepo struct {
Ref GQLRef `json:"ref"`
Object GQLObjectRepo `json:"object"`
Releases GQLObjectRelease `json:"releases"`
}
type GQLObjectRelease struct {
Nodes []GQLRelease `json:"nodes"`
PageInfo GQLPageInfo `json:"pageInfo"`
}
type GQLRelease struct {
Name string `json:"name"`
CreatedAt time.Time `json:"createdAt"`
PublishedAt time.Time `json:"publishedAt"`
IsDraft bool `json:"isDraft"`
IsPrerelease bool `json:"isPrerelease"`
Description string `json:"description"`
Id int `json:"databaseId"`
IsLatest bool `json:"isLatest"`
}
func (r GQLRelease) SemVer() *semver.Version {
return semver.MustParse(strings.TrimPrefix(r.Name, "v"))
}
// IsReleased returns if the release in not prerelease not a draft
func (r GQLRelease) IsReleased() bool {
return !r.IsDraft && !r.IsPrerelease
}
var releasedOnRegexp = regexp.MustCompile("^> Released on ([0-9]{4}/[0-9]{2}/[0-9]{2})")
// ExtractReleaseDate returns the date this was published, if there's a `> Released on YYYY/MM/DD` in the description it uses this,
// otherwise it uses the PublishedAt data from Github.
func (r GQLRelease) ExtractReleaseDate() (time.Time, error) {
res := releasedOnRegexp.FindStringSubmatch(r.Description)
if len(res) == 2 {
return time.Parse("2006/01/02", res[1])
}
return r.PublishedAt, nil
}
func (r GQLRelease) IsLTS() bool {
return regexp.MustCompile("^> LTS").MatchString(r.Description)
}
// Branch branch that this release was first on
func (r GQLRelease) Branch() string {
// In theory we could extract this from the tag but let's keep this simple
v := r.SemVer()
return fmt.Sprintf("release-%d.%d", v.Major(), v.Minor())
}
type GQLObjectRepo struct {
History GQLHistoryRepo `json:"history"`
}
type GQLHistoryRepo struct {
PageInfo GQLPageInfo `json:"pageInfo"`
Nodes []GQLCommit `json:"nodes"`
}
type GQLAssociatedPRs struct {
Nodes []GQLPRNode `json:"nodes"`
}
type GQLAuthor struct {
Login string `json:"login"`
}
type GQLPRNode struct {
Author GQLAuthor `json:"author"`
Number int `json:"number"`
Title string `json:"title"`
Body string `json:"body"`
Merged bool `json:"merged"`
MergeCommit GQLCommit `json:"mergeCommit"`
}
type GQLRef struct {
Target GQLRefTarget `json:"target"`
}
type GQLCommit struct {
Oid string `json:"oid"`
Message string `json:"message,omitempty"`
AssociatedPullRequests GQLAssociatedPRs `json:"associatedPullRequests,omitempty"`
}
type GQLRefTarget struct {
CommitUrl string `json:"commitUrl"`
Oid string `json:"oid"`
}
func (r GQLRefTarget) Commit() string {
return r.CommitUrl[strings.LastIndex(r.CommitUrl, "/")+1:]
}
type GQLClient struct {
Token string
Cl *github.Client
}
func SplitRepo(repo string) (string, string) {
r := strings.Split(repo, "/")
return r[0], r[1]
}
func GqlClientFromEnv() *GQLClient {
token := os.Getenv("GITHUB_TOKEN")
if token == "" {
token = os.Getenv("GITHUB_API_TOKEN")
if token == "" {
panic("need to set at least env GITHUB_TOKEN or GITHUB_API_TOKEN")
}
}
cl := github.NewTokenClient(context.Background(), token)
return &GQLClient{Token: token, Cl: cl}
}
func (c GQLClient) ReleaseGraphQL(repo string) ([]GQLRelease, error) {
owner, name := SplitRepo(repo)
var all []GQLRelease
var res GQLOutput
var err error
for {
cursorStr := ""
if res.Data.Repository.Releases.PageInfo.EndCursor != "" {
cursorStr = fmt.Sprintf(`after: "%s",`, res.Data.Repository.Releases.PageInfo.EndCursor)
}
query := fmt.Sprintf(`
query($name: String!, $owner: String!) {
repository(owner: $owner, name: $name) {
releases(first: 100, %s orderBy: {field: CREATED_AT, direction: DESC}) {
nodes {
name
createdAt
publishedAt
isDraft
isPrerelease
description
databaseId
isLatest
}
pageInfo {
endCursor
hasNextPage
hasPreviousPage
}
}
}
}
`, cursorStr)
res, err = c.graphqlQuery(query, map[string]interface{}{"owner": owner, "name": name})
if err != nil {
return nil, err
}
all = append(all, res.Data.Repository.Releases.Nodes...)
if !res.Data.Repository.Releases.PageInfo.HasNextPage {
break
}
}
return all, nil
}
func (c GQLClient) HistoryGraphQl(repo, branch, commitLimit string) ([]GQLCommit, error) {
owner, name := SplitRepo(repo)
var out []GQLCommit
var err error
var res GQLOutput
for {
cursorStr := ""
if res.Data.Repository.Object.History.PageInfo.EndCursor != "" {
cursorStr = fmt.Sprintf(`(after: "%s")`, res.Data.Repository.Object.History.PageInfo.EndCursor)
}
res, err = c.graphqlQuery(fmt.Sprintf(`
query($name: String!, $owner: String!, $branch: String!) {
repository(owner: $owner, name: $name) {
object(expression: $branch) {
... on Commit {
history%s {
pageInfo {
hasNextPage
endCursor
}
nodes {
oid
message
associatedPullRequests(first: 100) {
nodes {
author {
login
}
number
title
body
merged
mergeCommit {
oid
}
}
}
}
}
}
}
}
}
`, cursorStr), map[string]interface{}{"owner": owner, "name": name, "branch": branch})
if err != nil {
return out, err
}
for _, r := range res.Data.Repository.Object.History.Nodes {
if commitLimit != "" && strings.HasPrefix(r.Oid, commitLimit) {
return out, err
}
out = append(out, r)
}
if !res.Data.Repository.Object.History.PageInfo.HasNextPage {
return out, err
}
}
}
func (c GQLClient) CommitByRef(repo, tag string) (string, error) {
owner, name := SplitRepo(repo)
res, err := c.graphqlQuery(`
query ($owner: String!, $name: String!, $ref: String!) {
repository(name: $name, owner: $owner) {
ref(qualifiedName: $ref) {
target {
commitUrl
oid
}
}
}
}
`, map[string]interface{}{"owner": owner, "name": name, "ref": fmt.Sprintf("refs/tags/%s", tag)})
if err != nil {
return "", err
}
// In some cases the oid doesn't match the github commit so let's extract the commit from the url.
return res.Data.Repository.Ref.Target.Commit(), nil
}
func (c GQLClient) graphqlQuery(query string, variables map[string]interface{}) (GQLOutput, error) {
var out GQLOutput
var err error
b2 := bytes.Buffer{}
err = json.NewEncoder(&b2).Encode(map[string]interface{}{"query": query, "variables": variables})
if err != nil {
return out, err
}
var r *http.Request
r, err = http.NewRequest(http.MethodPost, "https://api.github.com/graphql", &b2)
if err != nil {
return out, err
}
r.Header.Set("Authorization", fmt.Sprintf("bearer %s", c.Token))
r.Header.Set("Content-Type", "application/json")
var res *http.Response
res, err = http.DefaultClient.Do(r)
if err != nil {
return out, err
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(res.Body)
if res.StatusCode != 200 {
b, _ := io.ReadAll(res.Body)
err = fmt.Errorf("got status: %d body:%s", res.StatusCode, b)
return out, err
}
err = json.NewDecoder(res.Body).Decode(&out)
return out, err
}
func (c GQLClient) UpsertRelease(ctx context.Context, repo string, release string, contentModifier func(repositoryRelease *github.RepositoryRelease) error) error {
releases, err := c.ReleaseGraphQL(repo)
if err != nil {
return err
}
var existingRelease *GQLRelease
for _, r := range releases {
if r.Name == release {
existingRelease = &r
break
}
}
owner, name := SplitRepo(repo)
if existingRelease == nil {
releasePayload := &github.RepositoryRelease{Name: &release, Draft: github.Ptr(true), TagName: &release}
err := contentModifier(releasePayload)
if err != nil {
return err
}
_, _, err = c.Cl.Repositories.CreateRelease(ctx, owner, name, releasePayload)
return err
}
releasePayload, _, err := c.Cl.Repositories.GetRelease(ctx, owner, name, int64(existingRelease.Id))
if err != nil {
return err
}
err = contentModifier(releasePayload)
if err != nil {
return err
}
_, _, err = c.Cl.Repositories.EditRelease(ctx, owner, name, int64(existingRelease.Id), releasePayload)
return err
}