/
main.go
241 lines (209 loc) · 5.28 KB
/
main.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
package main
import (
"context"
"encoding/csv"
"fmt"
"os"
"path/filepath"
"strconv"
"time"
"github.com/google/go-github/github"
"github.com/joho/godotenv"
"golang.org/x/oauth2"
"gopkg.in/yaml.v3"
)
const (
DefaultConfigFileName = "config.yml"
DefaultEnvFileName = ".env"
DefaultResultFileName = "result.csv"
)
type ConfigElement struct {
SourceOwner string `yaml:"source_owner"`
SourceRepo string `yaml:"source_repo"`
BaseBranch string `yaml:"base_branch"`
}
type Config struct {
Elements []ConfigElement `yaml:"elements"`
}
type PullRequest struct {
Title string
CreatedAt time.Time
MergedAt time.Time
Merged bool
}
func main() {
fmt.Println(">> Start GitHub Pull Request Aggregation!")
exec, err := os.Executable()
if err != nil {
fmt.Println(err)
return
}
// Load config file
config, err := loadConfig(filepath.Join(filepath.Dir(exec), DefaultConfigFileName))
if err != nil {
fmt.Println(err)
return
}
// Let the user select the config
fmt.Println("Select the config:")
for i, element := range config.Elements {
fmt.Println(i, ":", element.SourceOwner, "/", element.SourceRepo, ":", element.BaseBranch)
}
var selected int
fmt.Scan(&selected)
if selected < 0 || selected >= len(config.Elements) {
fmt.Println("Invalid selection")
return
}
sourceOwner := config.Elements[selected].SourceOwner
sourceRepo := config.Elements[selected].SourceRepo
baseBranch := config.Elements[selected].BaseBranch
// Load .env file
err = godotenv.Load(filepath.Join(filepath.Dir(exec), DefaultEnvFileName))
if err != nil {
fmt.Println("Error loading .env file")
return
}
ght := os.Getenv("GITHUB_ACCESS_TOKEN")
// Authentication
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{
AccessToken: ght,
},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
// get my user
user, _, err := client.Users.Get(ctx, "")
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Authenticated user:", *user.Login)
// list recent pull requests for the authenticated user
prs, _, err := listClosedPullRequestsByClient(ctx, client, sourceOwner, sourceRepo, baseBranch, *user.Login)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Pull Requests of the authenticated user (", len(prs), ") :")
for _, pr := range prs {
fmt.Println(*pr.Title)
}
// Write to a file
outputFilePath := filepath.Join(filepath.Dir(exec), DefaultResultFileName)
fmt.Println("Writing to a file:", outputFilePath)
err = writeResultCSV(outputFilePath, prs)
if err != nil {
fmt.Println(err)
return
}
// // list all repositories for the authenticated user
// repos, _, err := listRepos(ctx, client)
// if err != nil {
// fmt.Println(err)
// return
// }
// fmt.Println("Repositories of the authenticated user:")
// for _, repo := range repos {
// fmt.Println(*repo.Name)
// }
}
func loadConfig(path string) (*Config, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
var config Config
decoder := yaml.NewDecoder(f)
err = decoder.Decode(&config)
if err != nil {
return nil, err
}
return &config, nil
}
func listClosedPullRequestsByClient(ctx context.Context, client *github.Client, owner, repo, baseBranch, username string) ([]*github.PullRequest, *github.Response, error) {
// Create PullRequestListOptions
// https://godoc.org/github.com/google/go-github/github#PullRequestListOptions
opt := &github.PullRequestListOptions{
State: "closed",
ListOptions: github.ListOptions{
PerPage: 30,
},
Base: baseBranch,
// Head: username + ":" + "develop",
}
// list all pull requests
var prs []*github.PullRequest
for {
curprs, res, err := client.PullRequests.List(ctx, owner, repo, opt)
if err != nil {
return nil, res, err
}
prs = append(prs, curprs...)
fmt.Print("*")
if res.NextPage == 0 {
fmt.Println("")
break
}
opt.ListOptions.Page = res.NextPage
}
// extract pull requests which owned by the authenticated user
var myprs []*github.PullRequest
for _, pr := range prs {
if *pr.User.Login == username {
myprs = append(myprs, pr)
}
}
return myprs, nil, nil
}
func listRepos(ctx context.Context, client *github.Client) ([]*github.Repository, *github.Response, error) {
repos, res, err := client.Repositories.List(ctx, "", nil)
if err != nil {
return nil, nil, err
}
return repos, res, nil
}
func writeResultCSV(path string, prs []*github.PullRequest) error {
var records []*PullRequest
for _, pr := range prs {
// [Note]
// pr.MergedAt is nil if the pull request has not been merged.
// And, pr.Merged is always nil. This is probably a bug.
// We need to check pr.MergedAt is nil or not.
mergedAt := time.Time{}
merged := false
if pr.MergedAt != nil {
mergedAt = *pr.MergedAt
merged = true
}
record := &PullRequest{
Title: *pr.Title,
CreatedAt: *pr.CreatedAt,
MergedAt: mergedAt,
Merged: merged,
}
records = append(records, record)
}
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
writer := csv.NewWriter(file)
defer writer.Flush()
for _, record := range records {
err := writer.Write([]string{
record.Title,
record.CreatedAt.String(),
record.MergedAt.String(),
strconv.FormatBool(record.Merged),
})
if err != nil {
return err
}
}
return nil
}