-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
262 lines (212 loc) · 5.44 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
package main
import (
"context"
"fmt"
"log"
"os"
"strconv"
"strings"
"sync"
"time"
"github.com/google/go-github/v31/github"
"golang.org/x/oauth2"
)
const (
defaultIssuesPerPage = 200
defaultSyncDays = 1
defaultMaxLevels = 0
)
type env struct {
token string
owner string
repo string
syncDays int
maxLevels int
addChangelog bool
dryRun bool
updateClosed bool
}
type service struct {
ctx context.Context
client *github.Client
env *env
wg sync.WaitGroup
}
func flagToBool(s string) bool {
s = strings.ToLower(s)
return s == "1" || s == "true" || s == "y" || s == "yes"
}
func environment() *env {
r := strings.Split(os.Getenv("INPUT_REPO"), "/")
e := &env{
owner: r[0],
repo: r[1],
token: os.Getenv("INPUT_TOKEN"),
dryRun: flagToBool(os.Getenv("INPUT_DRY_RUN")),
addChangelog: flagToBool(os.Getenv("INPUT_ADD_CHANGELOG")),
updateClosed: flagToBool(os.Getenv("INPUT_UPDATE_CLOSED")),
}
var err error
syncDays := os.Getenv("INPUT_SYNC_DAYS")
e.syncDays, err = strconv.Atoi(syncDays)
if err != nil {
if strings.ToLower(syncDays) == "all" {
e.syncDays = -1
} else {
e.syncDays = defaultSyncDays
}
}
e.maxLevels, err = strconv.Atoi(os.Getenv("INPUT_MAX_LEVELS"))
if err != nil {
e.maxLevels = defaultMaxLevels
}
return e
}
func (e *env) debugPrint() {
log.Printf("Repo: %v", e.repo)
log.Printf("Owner: %v", e.owner)
log.Printf("Sync days: %v", e.syncDays)
log.Printf("Max levels: %v", e.maxLevels)
log.Printf("Dry run: %v", e.dryRun)
log.Printf("Add comments: %v", e.addChangelog)
log.Printf("Update closed: %v", e.updateClosed)
}
func (s *service) fetchGithubIssues() ([]*github.Issue, error) {
var allIssues []*github.Issue
opt := &github.IssueListByRepoOptions{
State: "all",
ListOptions: github.ListOptions{PerPage: defaultIssuesPerPage},
}
if s.env.syncDays > 0 {
opt.Since = time.Now().AddDate(0 /*year*/, 0 /*month*/, -s.env.syncDays)
}
for {
issues, resp, err := s.client.Issues.ListByRepo(s.ctx, s.env.owner, s.env.repo, opt)
if err != nil {
return nil, err
}
allIssues = append(allIssues, issues...)
if resp.NextPage == 0 {
break
}
opt.Page = resp.NextPage
}
log.Printf("Fetched github issues. count=%v", len(allIssues))
return allIssues, nil
}
func (s *service) fetchIssuesByID(issues []int) ([]*github.Issue, error) {
log.Printf("Fetching issues by ID. count=%v", len(issues))
var wg sync.WaitGroup
var allIssues []*github.Issue
for _, i := range issues {
wg.Add(1)
go func(id int) {
defer wg.Done()
issue, _, err := s.client.Issues.Get(s.ctx, s.env.owner, s.env.repo, id)
if err != nil {
log.Printf("Failed to retrieve an issue. issue=%v err=%v", id, err)
return
}
allIssues = append(allIssues, issue)
}(i)
}
log.Printf("Waiting for issues to be fetched by ID...")
wg.Wait()
return allIssues, nil
}
func createComment(changelog []string) string {
if len(changelog) == 0 {
return ""
}
var str strings.Builder
str.WriteString("Issue update changelog:\n")
for _, s := range changelog {
str.WriteString(fmt.Sprintf("- %s\n", s))
}
return str.String()
}
func (s *service) updateIssue(i *Issue, body string, changelog []string) {
defer s.wg.Done()
log.Printf("About to update an issue. issue=%v", i.ID)
if s.env.dryRun {
log.Printf("Dry run mode.")
return
}
req := &github.IssueRequest{
Body: &body,
}
_, _, err := s.client.Issues.Edit(s.ctx, s.env.owner, s.env.repo, i.ID, req)
if err != nil {
log.Printf("Error while editing an issue. issue=%v err=%v", i.ID, err)
return
}
log.Printf("Updated an issue. issue=%v", i.ID)
if s.env.addChangelog && len(changelog) > 0 {
body := createComment(changelog)
comment := &github.IssueComment{
Body: &body,
}
_, _, err = s.client.Issues.CreateComment(s.ctx, s.env.owner, s.env.repo, i.ID, comment)
if err != nil {
log.Printf("Error while adding a comment. issue=%v err=%v", i.ID, err)
return
}
log.Printf("Added a comment to the issue. issue=%v", i.ID)
}
}
func main() {
log.SetOutput(os.Stdout)
env := environment()
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: env.token},
)
tc := oauth2.NewClient(ctx, ts)
svc := &service{
ctx: ctx,
client: github.NewClient(tc),
env: env,
}
env.debugPrint()
ghIssues, err := svc.fetchGithubIssues()
if err != nil {
log.Panic(err)
}
if len(ghIssues) == 0 {
fmt.Println(fmt.Sprintf(`::set-output name=updatedIssues::%s`, "1"))
return
}
tr := NewTree(ghIssues)
missing, err := svc.fetchIssuesByID(tr.missing)
if err != nil {
log.Panic(err)
}
tr.AddParentIssues(missing)
issues := tr.Issues()
e := &Editor{
MaxLevels: svc.env.maxLevels,
}
for _, i := range issues {
canProcess := i.IsOpened() || (i.IsClosed() && svc.env.updateClosed)
if !canProcess {
log.Printf("Skipping issue update. issue=%v status=%v", i.ID, i.Status)
continue
}
body, changeLog, err := e.Update(i, true /*add missing*/)
if err != nil {
log.Printf("Failed to update issue body. issue=%v err=%v", i.ID, err)
continue
}
if body == i.Body {
log.Printf("Skipping identical issue body. issue=%v", i.ID)
continue
}
svc.wg.Add(1)
go svc.updateIssue(i, body, changeLog)
}
log.Printf("Waiting for issue update to finish...")
svc.wg.Wait()
fmt.Println(fmt.Sprintf(`::set-output name=updatedIssues::%s`, "1"))
// help logger to flush
time.Sleep(1 * time.Second)
}