-
Notifications
You must be signed in to change notification settings - Fork 10
/
main.go
243 lines (201 loc) · 6.1 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
/*
Copyright 2022 Guilhem Lettron ([email protected]).
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"bytes"
"context"
"fmt"
"os"
"regexp"
"strconv"
"strings"
"text/template"
"time"
"github.com/akrennmair/slice"
"github.com/google/go-github/v33/github"
"golang.org/x/oauth2"
funk "github.com/thoas/go-funk"
"github.com/mmcdole/gofeed"
gha "github.com/sethvargo/go-githubactions"
md "github.com/JohannesKaufmann/html-to-markdown"
)
const (
lastTimeInput = "lastTime"
labelsInput = "labels"
repoTokenInput = "repo-token"
feedInput = "feed"
prefixInput = "prefix"
aggregateInput = "aggregate"
dryRunInput = "dry-run"
titleFilterInput = "titleFilter"
contentFilterInput = "contentFilter"
)
func main() {
a := gha.New()
a.AddPath("main.go")
// Parse repository in form owner/name
repo := strings.Split(os.Getenv("GITHUB_REPOSITORY"), "/")
// Parse limit time option
var limitTime time.Time
if d, err := time.ParseDuration(a.GetInput(lastTimeInput)); err == nil {
// Make duration negative
if d > 0 {
d = -d
}
limitTime = time.Now().Add(d)
} else {
a.Debugf("Fail to parse last time %s", a.GetInput(lastTimeInput))
}
a.Debugf("limitTime %s", limitTime)
// Parse Labels
labels := strings.Split(a.GetInput(labelsInput), ",")
a.Debugf("labels %v", labels)
ctx := context.Background()
// Instanciate GitHub client
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: a.GetInput(repoTokenInput)},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
// Instanciate feed parser
fp := gofeed.NewParser()
feed, err := fp.ParseURLWithContext(a.GetInput(feedInput), ctx)
if err != nil {
a.Errorf("Cannot parse feed '%s': '%s'", a.GetInput(feedInput), err)
os.Exit(1)
}
a.Infof("%s", feed.Title)
// Instanciate HTML to markdown
converter := md.NewConverter("", true, nil)
// Remove old items in feed
feed.Items = funk.Filter(feed.Items, func(x *gofeed.Item) bool {
if x.PublishedParsed != nil {
return x.PublishedParsed.After(limitTime)
}
a.Infof("Item don't have a publish date, skip limitTime")
return true
}).([]*gofeed.Item)
// Get all issues
IssueListByRepoOption := &github.IssueListByRepoOptions{
State: "all",
Labels: labels,
}
issues, _, err := client.Issues.ListByRepo(ctx, repo[0], repo[1], IssueListByRepoOption)
if err != nil {
a.Fatalf("%v", err)
}
a.Debugf("%d issues", len(issues))
var issuesToCreate []*github.IssueRequest
var createdIssues []*github.Issue
// Iterate
for _, item := range feed.Items {
title := strings.Join([]string{a.GetInput(prefixInput), item.Title}, " ")
a.Debugf("Issue '%s'", title)
if issue := funk.Find(issues, func(x *github.Issue) bool {
return *x.Title == title
}); issue != nil {
a.Warningf("Issue already exists")
continue
}
// Issue Content
content := item.Content
if content == "" {
content = item.Description
}
filter := a.GetInput(titleFilterInput)
if filter != "" {
matched, _ := regexp.MatchString(filter, item.Title)
if matched {
a.Debugf("No issue created due to title filter")
continue
}
}
filter = a.GetInput(contentFilterInput)
if filter != "" {
matched, _ := regexp.MatchString(filter, content)
if matched {
a.Debugf("No issue created due to content filter")
continue
}
}
markdown, err := converter.ConvertString(content)
if err != nil {
a.Errorf("Fail to convert HTML to markdown: '%s'", err)
continue
}
// truncate if characterLimit >0
characterLimit := a.GetInput("characterLimit")
if characterLimit != "" {
cl, err := strconv.Atoi(characterLimit)
if err != nil {
a.Errorf("fail to convert 'characterLimit': '%s'", err)
continue
}
if len(markdown) > cl {
markdown = markdown[:cl] + "…"
markdown += "\n\n---\n## Would you like to know more?\nRead the full article on the following website:"
}
}
// Execute the template with a map as context
context := map[string]string{
"Link": item.Link,
"Content": markdown,
}
const issue = `
{{if .Content}}
{{ .Content }}
{{end}}
{{if .Link}}
<{{ .Link }}>
{{end}}
`
var tpl bytes.Buffer
if err := template.Must(template.New("issue").Parse(issue)).Execute(&tpl, context); err != nil {
a.Warningf("Cannot render issue: '%s'", err)
continue
}
body := tpl.String()
// Default to creating an issue per item
// Create first issue if aggregate
if aggregate, err := strconv.ParseBool(a.GetInput(aggregateInput)); err != nil || !aggregate || len(issuesToCreate) == 0 {
// Create Issue
issueRequest := &github.IssueRequest{
Title: &title,
Body: &body,
}
if len(labels) != 0 {
issueRequest.Labels = &labels
}
issuesToCreate = append(issuesToCreate, issueRequest)
} else {
title = strings.Join([]string{a.GetInput(prefixInput), time.Now().Format(time.RFC822)}, " ")
issuesToCreate[0].Title = &title
body = fmt.Sprintf("%s\n\n%s", *issuesToCreate[0].Body, body)
issuesToCreate[0].Body = &body
}
}
for _, issueRequest := range issuesToCreate {
if dr, err := strconv.ParseBool(a.GetInput(dryRunInput)); err != nil || !dr {
issue, _, err := client.Issues.Create(ctx, repo[0], repo[1], issueRequest)
if err != nil {
a.Warningf("Fail create issue %s: %s", *issueRequest.Title, err)
continue
}
createdIssues = append(createdIssues, issue)
} else {
a.Debugf("Creating Issue '%s' with content '%s'", *issueRequest.Title, *issueRequest.Body)
}
}
createdIssuesString := slice.Map(createdIssues, func(ci *github.Issue) string { return strconv.Itoa(*ci.Number) })
gha.SetOutput("issues", strings.Join(createdIssuesString, ","))
}