-
Notifications
You must be signed in to change notification settings - Fork 0
/
git-jira-history.py
executable file
·383 lines (344 loc) · 16.2 KB
/
git-jira-history.py
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
#!/usr/bin/python
import jira
import json
import sys
import urlparse
import pytz
import datetime
import dateutil.parser
from optparse import OptionParser
import unittest
DEBUG = False
def logDebug(msg):
if DEBUG:
for line in msg.split('\n'):
sys.stderr.write("[DEBUG] " + line + "\n")
def printIssues(issues, reachables):
reachablesJSON = []
for key, rev, repo in reachables:
issue = [i for i in issues if i['key'] == key][0]
reachablesJSON.append({
'key': key,
'endpoint': jiraEndpoint,
'summary': issue['fields']['summary'],
'resolution': issue['fields']['resolution']['name'],
'revision': rev,
'repository': repo})
print json.dumps(reachablesJSON)
def resolveEndpointAddress(endpoint):
endp = urlparse.urlparse(endpoint)
if not endp.netloc: # simple host definition will be interpreted as path, not as host name
endpoint = '//' + endpoint
if not endp.scheme:
endpoint = 'https:' + endpoint
return endpoint
def parseUserCredentials(credentialsString):
credentials = credentialsString.split(":", 1)
return (credentials[0], credentials[1] if len(credentials) > 1 else None)
def buildHistoryChart(client, query):
chart = []
issues = client.search(query, fields=["timeestimate", "created"], expand=["changelog"])
for issue in issues["issues"]:
chartEntry = {}
chartIssue = {
"key": issue["key"],
"created": issue["fields"]["created"],
}
chartEntry["issue"] = chartIssue
# timings
for update in issue["changelog"]["histories"]:
for entry in update["items"]:
if entry.get("toString") == "In Progress":
chartIssue["started"] = update["created"]
if entry.get("toString") == "Resolved":
chartIssue["completed"] = update["created"]
if chartIssue.get("started"):
estimatedDuration = issue["fields"]["timeestimate"]
chartIssue["estimate"] = estimatedDuration
if issue["fields"].get("timeestimate"):
startedDate = dateutil.parser.parse(chartIssue.get("started"))
estimatedEndDate = startedDate + datetime.timedelta(seconds=estimatedDuration)
chartIssue["estimatedCompletion"] = estimatedEndDate.strftime('%Y-%m-%dT%H:%M:%S.%f%z')
# commits
commits = [commit for repository in client.getCommits(issue["id"]) for commit in repository["commits"]]
chartEntry["commits"] = commits
# responsible resource
assignee = None
for update in issue["changelog"]["histories"]:
for entry in update["items"]:
if entry.get("toString") == "In Progress":
assignee = update["author"]["name"]
committers = [commit["author"]["name"] for commit in commits]
committer = max(set(committers), key=committers.count)
if committer or assignee:
chartEntry["resource"] = committer or assignee
chart.append(chartEntry)
return sorted(chart, key=lambda x: x["issue"].get("started"))
class Tests(unittest.TestCase):
def test_parseUserCredentials(self):
self.assertEqual(parseUserCredentials("user:password"), ("user", "password"))
self.assertEqual(parseUserCredentials("user"), ("user", None))
self.assertEqual(parseUserCredentials("user:"), ("user", ""))
self.assertEqual(parseUserCredentials("user:password:xxx"), ("user", "password:xxx"))
def test_resolveEndpointAddress(self):
self.assertEqual(resolveEndpointAddress("jira.com"), "https://jira.com")
self.assertEqual(resolveEndpointAddress("http://jira.com"), "http://jira.com")
self.assertEqual(resolveEndpointAddress("https://jira.com/path"), "https://jira.com/path")
def test_WorkingHours_addWorkTime(self):
workHours = WorkingHours(dayLength=28800, dayEnd=64800)
self.assertEqual(
workHours.addWorkTime(dateutil.parser.parse("2017-01-01T12:00:00"), datetime.timedelta(hours=4)),
dateutil.parser.parse("2017-01-01T16:00:00")
)
self.assertEqual(
workHours.addWorkTime(dateutil.parser.parse("2017-01-01T16:00:00"), datetime.timedelta(hours=3)),
dateutil.parser.parse("2017-01-02T11:00:00")
)
self.assertEqual(
workHours.addWorkTime(dateutil.parser.parse("2017-01-01T12:00:00"), datetime.timedelta(hours=8)),
dateutil.parser.parse("2017-01-02T12:00:00")
)
self.assertEqual(
workHours.addWorkTime(dateutil.parser.parse("2017-01-01T00:00:00"), datetime.timedelta(hours=8)),
dateutil.parser.parse("2017-01-01T18:00:00")
)
def test_buildHistoryChart(self):
class MockJira:
def search(self, jql, offset=None, limit=None, fields=None, expand=None):
return {
# The second issue was created later than the first. But the second issue was started earlier.
"issues": [
{
"id": "1234",
"key": "TEST-1",
"fields": {
"timeestimate": 28800,
"created": "2017-01-01T00:00:01.000+0000",
},
"changelog": {
"histories": [
{
"created": "2017-01-04T00:00:01.000+0000",
"author": {
"name": "developer2",
},
"items": [
{
"field": "status",
"fromString": "Open",
"toString": "In Progress"
}
]
},
{
"created": "2017-01-04T01:00:01.000+0000",
"author": {
"name": "developer2",
},
"items": [
{
"field": "status",
"fromString": "In Progress",
"toString": "In Review"
}
]
},
{
"created": "2017-01-04T02:00:01.000+0000",
"author": {
"name": "developer1",
},
"items": [
{
"field": "status",
"fromString": "In Review",
"toString": "Resolved"
}
]
},
{
"created": "2017-01-04T03:00:01.000+0000",
"author": {
"name": "tester1",
},
"items": [
{
"field": "status",
"fromString": "Resolved",
"toString": "Closed"
}
]
},
]
}
},
{
"id": "5678",
"key": "TEST-2",
"fields": {
"timeestimate": 28800,
"created": "2017-01-02T00:00:01.000+0000",
},
"changelog": {
"histories": [
{
"created": "2017-01-03T00:00:01.000+0000",
"author": {
"name": "developer1",
},
"items": [
{
"field": "status",
"fromString": "Open",
"toString": "In Progress"
}
]
},
{
"created": "2017-01-03T01:00:01.000+0000",
"author": {
"name": "developer1",
},
"items": [
{
"field": "status",
"fromString": "In Progress",
"toString": "In Review"
}
]
},
{
"created": "2017-01-03T02:00:01.000+0000",
"author": {
"name": "developer2",
},
"items": [
{
"field": "status",
"fromString": "In Review",
"toString": "Resolved"
}
]
},
{
"created": "2017-01-03T03:00:01.000+0000",
"author": {
"name": "tester1",
},
"items": [
{
"field": "status",
"fromString": "Resolved",
"toString": "Closed"
}
]
},
]
}
}
]
}
def getCommits(self, issueId):
if issueId == "1234":
return [
{
"url": "https://test.test/test-repo",
"commits": [
{
"id": "39c6ba96cdfc4ce348ca88a13913a0fde3556f07",
"author": {
"name": "developer2"
},
"authorTimestamp": "2017-01-04T00:50:01.000+0000"
}
]
}
]
elif issueId == "5678":
return [
{
"url": "https://test.test/test-repo",
"commits": [
{
"id": "5c8e9bc64fa00ce304fb65a75b2ab4d30be68436",
"author": {
"name": "developer1"
},
"authorTimestamp": "2017-01-03T00:50:01.000+0000"
}
]
}
]
else:
return []
historyChart = buildHistoryChart(MockJira(), "jql = test")
self.maxDiff = None
self.assertEqual(historyChart, [
{
"resource": "developer1",
"issue": {
"key": "TEST-2",
"created": "2017-01-02T00:00:01.000+0000",
"estimate": 28800,
"estimatedCompletion": "2017-01-04T00:00:01.000+0000",
"started": "2017-01-03T00:00:01.000+0000",
"completed": "2017-01-03T02:00:01.000+0000",
},
"commits": [
{
"id": "5c8e9bc64fa00ce304fb65a75b2ab4d30be68436",
"author": {
"name": "developer1"
},
"authorTimestamp": "2017-01-03T00:50:01.000+0000"
}
],
},
{
"resource": "developer2",
"issue": {
"key": "TEST-1",
"created": "2017-01-01T00:00:01.000+0000",
"estimate": 28800,
"estimatedCompletion": "2017-01-05T00:00:01.000+0000",
"started": "2017-01-04T00:00:01.000+0000",
"completed": "2017-01-04T02:00:01.000+0000",
},
"commits": [
{
"id": "39c6ba96cdfc4ce348ca88a13913a0fde3556f07",
"author": {
"name": "developer2"
},
"authorTimestamp": "2017-01-04T00:50:01.000+0000"
}
],
}
])
# TODO: entries without issues
# TODO: group subtasks in some way
if __name__ == '__main__':
opt_parser = OptionParser(usage="%prog [options] JIRA_ENDPOINT JIRA_QUERY [GIT_REPO_PATH]",
description="")
opt_parser.add_option("--user", action="store", default=None, metavar="USER:PWD", help="Login credentials.")
opt_parser.add_option("--test", action="store_true", default=False,
help="Run self-testing & diagnostics.")
opts, args = opt_parser.parse_args()
if opts.test:
suite = unittest.TestLoader().loadTestsFromTestCase(Tests)
unittest.TextTestRunner(verbosity=2).run(suite)
elif len(args) >= 2:
DEBUG = opts.debug
jiraEndpoint = resolveEndpointAddress(args[0])
jiraQuery = args[1]
username, password = parseUserCredentials(opts.user) if opts.user else (None, None)
jiraClient = jira.JIRA(jiraEndpoint, username, password)
fields = getFieldIDs(jiraClient, opts.search_in)
issues = getAllIssues(jiraClient, jiraQuery, set(['summary', 'resolution'] + fields))
revisions = findRevisionsSpecified(jiraClient, issues, fields)
gitModules = getGitModules(repoRootPath, opts.revision)
verifiedRevisions = verifyRevisions(revisions, gitModules)
reachables = findReachables(verifiedRevisions)
printIssues(issues, reachables)
else:
opt_parser.print_help()