Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
283 lines (240 loc) · 7.16 KB
/
Copy pathmain.go
File metadata and controls
283 lines (240 loc) · 7.16 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
package main
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"sync"
"time"
"github.com/alexflint/go-arg"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/bradleyfalzon/ghinstallation"
"github.com/google/go-github/v26/github"
"github.com/kelseyhightower/envconfig"
"github.com/thoas/go-funk"
"golang.org/x/oauth2"
)
type commit struct {
date time.Time
sha string
}
type env struct {
Token string `envconfig:"GITHUB_ACCESS_TOKEN" required:"false"`
Key string `envconfig:"GITHUB_KEY" required:"false"`
IntegrationId int64 `envconfig:"GITHUB_INTEGRATION_ID" required:"false"`
InstallationId int64 `envconfig:"GITHUB_INSTALLATION_ID" required:"false"`
ConfigURL string `envconfig:"CONFIG_URL" required:"false"`
ConfigURLToken string `envconfig:"CONFIG_URL_TOKEN" required:"false"`
ConfigS3Bucket string `envconfig:"CONFIG_S3_BUCKET" required:"false"`
ConfigS3Key string `envconfig:"CONFIG_S3_KEY" required:"false"`
}
type options struct {
DryRun bool `arg:"--dry-run" help:"dry run mode"`
}
type config struct {
Owner string `json:"owner"`
Repo string `json:"repo"`
Head string `json:"head"`
Base string `json:"base"`
Reviewers []string `json:"reviewers"`
}
func parseJsonConfig(filename string, config *[]config) error {
jsonFile, err := os.Open(filename)
if err != nil {
return err
}
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
json.Unmarshal(byteValue, config)
return nil
}
func parseJsonConfigFromURL(url string, token string, config *[]config) error {
client := &http.Client{
Timeout: 20 * time.Second,
}
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/json")
if token != "" {
authzHeader := fmt.Sprintf("Bearer %s", token)
request.Header.Set("Authorization", authzHeader)
}
res, err := client.Do(request)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return errors.New(fmt.Sprintf("HTTP Error: %d", res.StatusCode))
}
if err := json.NewDecoder(res.Body).Decode(config); err != nil {
return err
}
return nil
}
func parseJsonConfigFromS3(bucket string, key string, config *[]config) error {
svc := s3.New(session.New(), &aws.Config{})
obj, err := svc.GetObject(&s3.GetObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
})
defer obj.Body.Close()
if err != nil {
return err
}
body, err := ioutil.ReadAll(obj.Body)
if err != nil {
return err
}
err = json.Unmarshal(body, config)
if err != nil {
return err
}
return nil
}
func latestCommit(client *github.Client, config *config, branch string) (*commit, error) {
b, _, err := client.Repositories.GetBranch(context.Background(), config.Owner, config.Repo, branch)
if err != nil {
return &commit{}, err
}
c, _, err := client.Git.GetCommit(context.Background(), config.Owner, config.Repo, *b.Commit.SHA)
if err != nil {
return &commit{}, err
}
return &commit{date: *c.Author.Date, sha: *c.SHA}, nil
}
func needPR(client *github.Client, config *config, headSHA string, baseSHA string) (bool, error) {
pulls, _, err := client.PullRequests.List(context.Background(), config.Owner, config.Repo, nil)
if err != nil {
return false, err
}
releasePulls := funk.Filter(pulls, func(pull *github.PullRequest) bool {
return *pull.Base.SHA == baseSHA && strings.Contains(*pull.Title, "[NEW RELEASE]")
})
if len(releasePulls.([]*github.PullRequest)) > 0 {
return false, nil
}
return true, nil
}
func createPR(client *github.Client, config *config) error {
title := fmt.Sprintf("[NEW RELEASE] %s <- %s (%s)", config.Base, config.Head, time.Now().Format("2006/01/02"))
pr := github.NewPullRequest{Title: &title, Head: &config.Head, Base: &config.Base}
pull, _, err := client.PullRequests.Create(context.Background(), config.Owner, config.Repo, &pr)
if err != nil {
return err
}
reviewers := github.ReviewersRequest{Reviewers: config.Reviewers}
_, _, err = client.PullRequests.RequestReviewers(context.Background(), config.Owner, config.Repo, *pull.Number, reviewers)
if err != nil {
return err
}
return nil
}
func newPR(client *github.Client, config config, options *options, wg *sync.WaitGroup) {
defer wg.Done()
log.Printf("Config: %+v", config)
headCommit, err := latestCommit(client, &config, config.Head)
if err != nil {
log.Fatal(err)
}
log.Printf("Head branch found: %+v", headCommit)
baseCommit, err := latestCommit(client, &config, config.Base)
if err != nil {
log.Fatal(err)
}
log.Printf("Base branch found: %+v", baseCommit)
if baseCommit.date.Before(headCommit.date) {
needNewPR, err := needPR(client, &config, headCommit.sha, baseCommit.sha)
if err != nil {
log.Fatal(err)
}
if needNewPR {
if !options.DryRun {
err := createPR(client, &config)
if err != nil {
log.Fatal(err)
}
}
log.Printf("New PR (%s <- %s) created.", config.Base, config.Head)
}
}
}
func main() {
// Parse environ variables
var goenv env
err := envconfig.Process("env", &goenv)
if err != nil {
log.Fatal(err.Error())
}
// Parse arg
var opt options
arg.MustParse(&opt)
// Parse config
configFile := "app.config.json"
var myConfig []config
if goenv.ConfigURL != "" {
err = parseJsonConfigFromURL(goenv.ConfigURL, goenv.ConfigURLToken, &myConfig)
if err != nil {
log.Fatal("Failed to parse the config file: ", err)
}
} else if goenv.ConfigS3Bucket != "" && goenv.ConfigS3Key != "" {
err = parseJsonConfigFromS3(goenv.ConfigS3Bucket, goenv.ConfigS3Key, &myConfig)
if err != nil {
log.Fatal("Failed to parse the config file from S3: ", err)
}
} else {
err = parseJsonConfig(configFile, &myConfig)
if err != nil {
log.Fatal("Failed to parse the config file: ", err)
}
}
// Create new client
ctx := context.Background()
var client *github.Client
if goenv.Token != "" {
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: goenv.Token})
tc := oauth2.NewClient(ctx, ts)
client = github.NewClient(tc)
log.Println("Create client with token")
} else if goenv.Key != "" {
// Validate environment variables
if goenv.IntegrationId == 0 || goenv.InstallationId == 0 {
log.Fatal("`GITHUB_INTEGRATION_ID` and `GITHUB_INSTALLATION_ID` is required.")
}
if goenv.IntegrationId < 0 || goenv.InstallationId < 0 {
log.Fatal("`GITHUB_INTEGRATION_ID` or `GITHUB_INSTALLATION_ID` is invalid.")
}
// Decode base64 env
dec, err := base64.StdEncoding.DecodeString(goenv.Key)
if err != nil {
log.Fatal("Failed to decode key", err.Error())
}
// Create new github client
itr, err := ghinstallation.New(http.DefaultTransport, goenv.IntegrationId, goenv.InstallationId, dec)
if err != nil {
log.Fatal("Failed to get key file: ", err)
}
client = github.NewClient(&http.Client{Transport: itr})
log.Println("Create client with key")
} else {
client = github.NewClient(nil)
log.Println("Create client with no config")
}
// Run create new PR func
var wg sync.WaitGroup
for _, v := range myConfig {
wg.Add(1)
go newPR(client, v, &opt, &wg)
}
wg.Wait()
}