-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
293 lines (255 loc) · 7.43 KB
/
main.go
File metadata and controls
293 lines (255 loc) · 7.43 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
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
jira "github.com/andygrunwald/go-jira"
"github.com/shiftstack/bugwatcher/pkg/jiraclient"
"github.com/shiftstack/bugwatcher/pkg/query"
"github.com/shiftstack/bugwatcher/pkg/team"
)
const (
githubRepository = "k-orc/openstack-resource-controller"
shiftStackQuery = `project = "OSASINFRA" AND (component in ("ORC"))`
)
var (
GITHUB_TOKEN = os.Getenv("GITHUB_TOKEN")
JIRA_TOKEN = os.Getenv("JIRA_TOKEN")
PEOPLE = os.Getenv("PEOPLE")
ghIssueNumberRegex = regexp.MustCompile(`GH-orc-(\d+): `)
linkHeaderRegex = regexp.MustCompile(`<(\S+)>; rel="next"`)
)
type GithubIssue struct {
Title string `json:"title"`
Body string `json:"body_text"`
URL string `json:"html_url"`
Number int `json:"number"`
Author struct {
Handle string `json:"login"`
JiraUsername string `json:"-"`
} `json:"user"`
Assignee struct {
Handle string `json:"login"`
JiraUsername string `json:"-"`
} `json:"assignee"`
Status string `json:"state"`
IsPR any `json:"pull_request"`
}
// ResolveNames resolves Github handles to Jira usernames.
func ResolveNames(issues <-chan GithubIssue, teamMembers []team.Person) <-chan GithubIssue {
out := make(chan GithubIssue)
go func() {
defer close(out)
for i := range issues {
if i.Author.Handle != "" {
if author, ok := team.PersonByGithubHandle(teamMembers, i.Author.Handle); ok {
i.Author.JiraUsername = author.Jira
}
}
if i.Assignee.Handle != "" {
if assignee, ok := team.PersonByGithubHandle(teamMembers, i.Assignee.Handle); ok {
i.Assignee.JiraUsername = assignee.Jira
}
}
out <- i
}
}()
return out
}
func fetchGitHubIssues(ctx context.Context, token string) <-chan GithubIssue {
issueCh := make(chan GithubIssue)
go func() {
defer close(issueCh)
// https://docs.github.com/en/rest/issues/issues?apiVersion=2022-11-28#list-repository-issues
client := &http.Client{}
url := fmt.Sprintf("https://api.github.com/repos/%s/issues", githubRepository)
for url != "" {
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
log.Fatalf("error fetching issues: %v", err)
return
}
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
req.Header.Set("Accept", "application/vnd.github.text+json") // Don't need the Markdown version
}
{
q := req.URL.Query()
q.Add("state", "all")
req.URL.RawQuery = q.Encode()
}
res, err := client.Do(req)
if err != nil {
log.Fatalf("error fetching issues: %v", err)
return
}
defer func() {
io.Copy(io.Discard, res.Body)
res.Body.Close()
}()
if statusCode := res.StatusCode; statusCode != 200 {
body, err := io.ReadAll(res.Body)
if err != nil {
log.Fatalf("Status code %d from Github. Additionally, reading the body errored with: %v", statusCode, err)
return
}
log.Fatalf("Status code %d from Github: %s", statusCode, body)
return
}
var issueBatch []GithubIssue
err = json.NewDecoder(res.Body).Decode(&issueBatch)
if err != nil {
log.Fatalf("error decoding Github issues: %v", err)
return
}
for _, issue := range issueBatch {
if issue.IsPR == nil {
issueCh <- issue
}
}
url = ""
if linkHeader := res.Header.Get("link"); linkHeader != "" {
if s := linkHeaderRegex.FindStringSubmatch(linkHeader); len(s) > 1 {
url = s[1]
}
}
}
}()
return issueCh
}
func createJiraIssue(jiraClient *jira.Client, issue GithubIssue) (*jira.Issue, error) {
i := jira.Issue{
Fields: &jira.IssueFields{
Description: fmt.Sprintf("Originally posted on Github: %s\n\n%s", issue.URL, issue.Body),
Type: jira.IssueType{
Name: "Task",
},
Project: jira.Project{
Key: "OSASINFRA",
},
Summary: "GH-orc-" + strconv.Itoa(issue.Number) + ": " + issue.Title,
Components: []*jira.Component{{Name: "ORC"}},
},
}
if assignee := issue.Assignee.JiraUsername; assignee != "" {
i.Fields.Assignee = &jira.User{
Name: assignee,
}
}
if author := issue.Author.JiraUsername; author != "" {
i.Fields.Reporter = &jira.User{
Name: author,
}
}
jiraIssue, response, err := jiraClient.Issue.Create(&i)
if err != nil {
io.Copy(os.Stderr, response.Body)
log.Println()
return nil, err
}
return jiraIssue, nil
}
type knownIssue struct {
Key string
Status *jira.Status
}
func main() {
ctx := context.Background()
people, err := team.Load(strings.NewReader(PEOPLE))
if err != nil {
log.Fatalf("error fetching team information: %v", err)
}
jiraClient, err := jiraclient.NewWithToken(query.JiraBaseURL, JIRA_TOKEN)
if err != nil {
log.Fatalf("error building a Jira client: %v", err)
}
issues := fetchGitHubIssues(ctx, GITHUB_TOKEN)
alreadyKnown := make(map[int]knownIssue)
for issue := range query.SearchIssues(ctx, jiraClient, shiftStackQuery) {
if s := ghIssueNumberRegex.FindStringSubmatch(issue.Fields.Summary); len(s) > 1 {
n, err := strconv.Atoi(s[1])
if err != nil {
panic("unexpected error: could not parse the issue number: " + err.Error())
}
alreadyKnown[n] = knownIssue{
Key: issue.Key,
Status: issue.Fields.Status,
}
}
}
{
alreadyKnownNumbers := make([]string, 0, len(alreadyKnown))
for k := range alreadyKnown {
alreadyKnownNumbers = append(alreadyKnownNumbers, strconv.Itoa(k))
}
log.Printf("Known issues: %v", alreadyKnownNumbers)
}
for issue := range ResolveNames(issues, people) {
jiraIssue, issueExistsInJira := alreadyKnown[issue.Number]
log.Printf("Now processing Github issue number %d, assigned to %s, status %q (Jira: %q)", issue.Number, issue.Author.Handle, issue.Status, jiraIssue.Key)
if issueExistsInJira {
var transitionTodo, transitionClosed string
{
possibleTransitions, _, _ := jiraClient.Issue.GetTransitions(jiraIssue.Key)
for _, v := range possibleTransitions {
switch v.Name {
case "Closed":
transitionClosed = v.ID
case "To Do":
transitionTodo = v.ID
}
}
}
switch {
case issue.Status == "closed" && jiraIssue.Status.Name != "Closed":
if _, err := jiraClient.Issue.DoTransition(jiraIssue.Key, transitionClosed); err != nil {
log.Printf("ERROR: Unable to transition issue %s to Closed: %v", jiraIssue.Key, err)
} else {
log.Printf("Transitioned issue %s to Closed", jiraIssue.Key)
}
case issue.Status == "open" && jiraIssue.Status.Name == "Closed":
if _, err := jiraClient.Issue.DoTransition(jiraIssue.Key, transitionTodo); err != nil {
log.Printf("ERROR: Unable to transition issue %s to To Do: %v", jiraIssue.Key, err)
} else {
log.Printf("Transitioned issue %s to To Do", jiraIssue.Key)
}
}
} else {
jiraIssue, err := createJiraIssue(jiraClient, issue)
if err != nil {
fmt.Println("Error creating Jira issue:", err)
}
if jiraIssue != nil {
log.Printf("Created Jira task with key: %s", jiraIssue.Key)
}
}
}
}
func init() {
log.SetFlags(log.Ldate | log.Ltime | log.LUTC)
ex_usage := false
if GITHUB_TOKEN == "" {
ex_usage = true
log.Print("Required environment variable not found: GITHUB_TOKEN")
}
if JIRA_TOKEN == "" {
ex_usage = true
log.Print("Required environment variable not found: JIRA_TOKEN")
}
if PEOPLE == "" {
ex_usage = true
log.Print("Required environment variable not found: PEOPLE")
}
if ex_usage {
log.Print("Exiting.")
os.Exit(64)
}
}