forked from release-engineering/Sync2Jira
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintermediary.py
More file actions
343 lines (293 loc) · 10.1 KB
/
Copy pathintermediary.py
File metadata and controls
343 lines (293 loc) · 10.1 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# This file is part of sync2jira.
# Copyright (C) 2016 Red Hat, Inc.
#
# sync2jira is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# sync2jira is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with sync2jira; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110.15.0 USA
#
# Authors: Ralph Bean <rbean@redhat.com>
import re
from typing import Optional
class Issue(object):
"""Issue Intermediary object"""
def __init__(
self,
source,
title,
url,
upstream,
comments,
config,
tags,
fixVersion,
priority,
content,
reporter,
assignee,
status,
id_,
storypoints,
upstream_id,
issue_type,
downstream=None,
):
self.source = source
self._title = title[:254]
self.url = url
self.upstream = upstream
self.comments = comments
self.tags = tags
self.fixVersion = fixVersion
self.priority = priority
self.storypoints = storypoints
# First trim the size of the content
self.content = trim_string(content)
# JIRA treats utf-8 characters in ways we don't totally understand, so scrub content down to
# simple ascii characters right from the start.
self.content = self.content.encode("ascii", errors="replace").decode("ascii")
# We also apply this content in regexs to pattern match, so remove any escape characters
self.content = self.content.replace("\\", "")
self.reporter = reporter
self.assignee = assignee
self.status = status
self.id = str(id_)
self.upstream_id = upstream_id
self.issue_type = issue_type
if not downstream:
self.downstream = config["sync2jira"]["map"][self.source][upstream]
else:
self.downstream = downstream
@property
def title(self):
_title = "[%s] %s" % (self.upstream, self._title)
return _title[:254].strip()
@property
def upstream_title(self):
return self._title
@classmethod
def from_github(cls, upstream, issue, config):
"""Helper function to create an intermediary Issue object."""
upstream_source = "github"
comments = reformat_github_comments(issue)
# Reformat the state field
if issue["state"]:
if issue["state"] == "open":
issue["state"] = "Open"
elif issue["state"] == "closed":
issue["state"] = "Closed"
# Get the issue type if any
issue_type = issue.get("type")
if isinstance(issue_type, dict):
issue_type = issue_type.get("name")
# Perform any mapping
mapping = config["sync2jira"]["map"][upstream_source][upstream].get(
"mapping", []
)
# Check for fixVersion
if any("fixVersion" in item for item in mapping):
map_fixVersion(mapping, issue)
return cls(
source=upstream_source,
title=issue["title"],
url=issue["html_url"],
upstream=upstream,
config=config,
comments=comments,
tags=issue["labels"],
fixVersion=[issue["milestone"]],
priority=issue.get("priority"),
content=issue["body"] or "",
reporter=issue["user"],
assignee=issue["assignees"],
status=issue["state"],
id_=issue["id"],
storypoints=issue.get("storypoints"),
upstream_id=issue["number"],
issue_type=issue_type,
)
def __repr__(self):
return f"<Issue {self.url} >"
class PR(object):
"""PR intermediary object"""
def __init__(
self,
source,
jira_key,
title,
url,
upstream,
config,
comments,
priority,
content,
reporter,
assignee,
status,
id_,
suffix,
match,
base_branch=None,
downstream=None,
):
self.source = source
self.jira_key = jira_key
self._title = title[:254]
self.url = url
self.upstream = upstream
self.comments = comments
# self.tags = tags
# self.fixVersion = fixVersion
self.priority = priority
self.base_branch = base_branch
# JIRA treats utf-8 characters in ways we don't totally understand, so scrub content down to
# simple ascii characters right from the start.
if content:
# First trim the size of the content
self.content = trim_string(content)
self.content = self.content.encode("ascii", errors="replace").decode(
"ascii"
)
# We also apply this content in regexs to pattern match, so remove any escape characters
self.content = self.content.replace("\\", "")
else:
self.content = None
self.reporter = reporter
self.assignee = assignee
self.status = status
self.id = str(id_)
self.suffix = suffix
self.match = match
# self.upstream_id = upstream_id
if not downstream:
self.downstream = config["sync2jira"]["map"][self.source][upstream]
else:
self.downstream = downstream
return
@property
def title(self):
return "[%s] %s" % (self.upstream, self._title)
@classmethod
def from_github(cls, upstream, pr, suffix, config, action=None):
"""Helper function to create an intermediary PR object."""
# Set our upstream source
upstream_source = "github"
# Format our comments
comments = reformat_github_comments(pr)
# Build our URL
url = pr["html_url"]
# Match to a JIRA
match = matcher(pr.get("body"), comments)
lifecycle = frozenset({"open", "merged", "closed", "reopened"})
if action:
if action == "reopened":
suffix = "reopened"
elif action == "closed":
suffix = "merged" if pr.get("merged") else "closed"
else:
suffix = "open"
elif suffix not in lifecycle:
suffix = "open"
base_branch = (
pr["base"].get("ref") if isinstance(pr.get("base"), dict) else None
)
# Return our PR object
return cls(
source=upstream_source,
jira_key=match,
title=pr["title"],
url=url,
upstream=upstream,
config=config,
comments=comments,
# tags=issue['labels'],
# fixVersion=[issue['milestone']],
priority=None,
content=pr.get("body"),
reporter=pr["user"]["fullname"],
assignee=pr["assignee"],
# GitHub PRs do not have status
status=None,
id_=pr["number"],
# upstream_id=issue['number'],
suffix=suffix,
match=match,
base_branch=base_branch,
)
def reformat_github_comments(issue):
return [
{
"author": comment["author"],
"name": comment["name"],
"body": trim_string(comment["body"]),
"id": comment["id"],
"date_created": comment["date_created"],
"changed": None,
}
for comment in issue["comments"]
]
def map_fixVersion(mapping, issue):
"""
Helper function to perform any fixVersion mapping.
Supports two formats:
- String template: ``"Product XXX"`` — replaces ``XXX`` with the milestone value
- Dict lookup: ``{"0.9.0": "Product 8.1", ...}`` — maps milestone to a
specific fixVersion; unmapped milestones are left unchanged
:param Dict mapping: Mapping dict we are given
:param Dict issue: Upstream issue object
"""
fixVersion_map = next(filter(lambda d: "fixVersion" in d, mapping))["fixVersion"]
if issue["milestone"]:
if isinstance(fixVersion_map, dict):
issue["milestone"] = fixVersion_map.get(
issue["milestone"], issue["milestone"]
)
else:
issue["milestone"] = fixVersion_map.replace("XXX", issue["milestone"])
JIRA_REFERENCE = re.compile(r"\bJIRA:\s*([A-Z][A-Z0-9]*-\d+)\b")
def matcher(content: Optional[str], comments: list[dict[str, str]]) -> str:
"""
Helper function to match to a JIRA
Extract the Jira ticket reference from the first instance of the magic
cookie (e.g., "JIRA: FACTORY-1234") found when searching
through the comments in reverse order. If no reference is found in the
comments, then look in the PR description. This ordering allows later
comments to override earlier ones as well as any reference in the
description.
:param String content: PR description
:param List comments: Comments
:return: JIRA match or None
:rtype: Bool
"""
def find_it(input_str: str) -> Optional[str]:
if not input_str:
return None
match = JIRA_REFERENCE.search(input_str)
return match.group(1) if match else None
for comment in reversed(comments):
match_str = find_it(comment["body"])
if match_str:
break
else:
match_str = find_it(content)
return match_str
def trim_string(content):
"""
Helper function to trim a string to ensure it is not over 50,000 char
Ref: https://github.com/release-engineering/Sync2Jira/issues/123
:param String content: Comment content
:rtype: String
"""
if len(content) > 50000:
return content[:50000]
else:
return content