-
Notifications
You must be signed in to change notification settings - Fork 0
/
to_csv.py
284 lines (202 loc) · 6.69 KB
/
to_csv.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
"""
Fetch Github issues and Zenhub metadata and write to CSV.
"""
import argparse
import csv
from multiprocessing.dummy import Pool
import pdb
from pprint import pprint
import time
import requests
from config.secrets import ZENHUB_ACCESS_TOKEN, GITHUB_PASSWORD, GITHUB_USER
from config.repos import REPO_LIST
FIELDNAMES = [
"id",
"number",
"title",
"pipeline",
"workgroup",
"type",
"project",
"body",
"repo_name",
"estimate",
"milestone",
"created_at",
"closed_at",
"updated_at",
"url",
]
def cli_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"-f",
"--filter",
type=str,
choices=["projects"],
required=False,
help="Filter issues by `projects` or `features`",
)
args = parser.parse_args()
return args
def get_github_issues(url, auth, labels=None, state="all", per_page=100):
data = []
page = 1
while True:
res = requests.get(
url,
auth=auth,
params={
"labels": labels,
"state": state,
"per_page": per_page,
"page": page,
},
)
res.raise_for_status()
data.extend(res.json())
# pagination logic
if len(res.json()) == per_page:
page += 1
else:
break
return data
def async_get_zenhub_issues(issue):
"""
async wrapper to get zenhub issues. after creating this method i learned that
zenhub limits requests to 100/min. so async is basically pointless. hence we
wait 3 seconds between each request.
20 requests/minute * 4 workers = 80 requests/minute
"""
# rate limited to 100 requests per second
print(issue["number"])
time.sleep(3)
zenhub_endpoint = (
f"https://api.zenhub.io/p1/repositories/{issue['repo_id']}/issues/"
)
# fetch zenhub issue data
zenhub_issue = get_zenhub_issue(
zenhub_endpoint, ZENHUB_ACCESS_TOKEN, issue["number"]
)
if not zenhub_issue:
# some zenhub issues are mysteriously not found
print("NO ZENHUB")
issue["pipeline"] = "Unknown"
issue["estimate"] = None
return issue
# add zenhub pipeline to github issue object
# see: https://stackoverflow.com/questions/25833613/python-safe-method-to-get-value-of-nested-dictionary
issue["pipeline"] = zenhub_issue.get("pipeline", {}).get("name")
if not issue.get("pipeline"):
# closed issues do not have a zenhub pipeline :(
issue["pipeline"] = "Closed"
# add estimate to github issue object
issue["estimate"] = zenhub_issue.get("estimate", {}).get("value")
return issue
def get_zenhub_issue(url, token, issue_no):
url = f"{url}{issue_no}"
params = {"access_token": token}
try:
# handle exceptions for timeouts, connection, etc.
res = requests.get(url, params=params)
except requests.exceptions.Timeout:
print("timeout")
return None
except:
print("unknwon error")
return None
try:
# handle status code errors
res.raise_for_status()
except Exception as e:
# handle an edge case where an issue is not found in zenub
if res.status_code == 404:
print(f"not found: {issue_no}")
return None
if res.status_code == 403:
print(res.text)
return None
else:
print(e)
return none
return res.json()
def parse_issue(issue):
# parse/format elements from github issue
# drop the Project: xxx convention from project titles
issue["title"] = issue.get("title").replace("Project: ", "")
issue["labels"] = [label["name"] for label in issue.get("labels")]
issue["milestone"] = (
issue.get("milestone").get("title") if issue.get("milestone") else None
)
return issue
def parse_labels(labels):
# extract issue type, workgroup, and project flag from issue labels
issue_type = None
project = "No"
workgroup = None
for label in labels:
if "workgroup" in label.lower():
workgroup = drop_prefix(label, "Workgroup: ")
if "type" in label.lower():
issue_type = drop_prefix(label, "Type: ")
if "index" in label.lower():
project = "Yes"
return {"project": project, "workgroup": workgroup, "type": issue_type}
def drop_prefix(val, prefix):
# helper for parsing DTS github labels
return val.replace(prefix, "")
def main():
args = cli_args()
issues = []
csv_data = []
for repo in REPO_LIST:
# iterate through all the repos to get issuse of interest
repo_name = repo.get("name")
repo_id = repo.get("id")
github_endpoint = (
f"https://api.github.com/repos/cityofaustin/{repo_name}/issues"
)
print(repo.get("name"))
"""
nixing this index-specific query for now. if we want closed Index issues, we'll need to do this
and also remove dupes from the existing query
if repo.get("name") == "atd-data-tech":
# this is the only repo that should have "Index" issues (aka, Projects),
# and we want all of them (including closed)
issues.extend(get_github_issues(github_endpoint, labels="Index", state="all"))
"""
# get all open issues
if args.filter:
if args.filter == "projects":
append_issues = get_github_issues(
github_endpoint, (GITHUB_USER, GITHUB_PASSWORD), labels=["Index"]
)
else:
raise Exception(
f"Filtering by `{args.filter}` is not supported by this script."
)
else:
append_issues = get_github_issues(
github_endpoint, (GITHUB_USER, GITHUB_PASSWORD)
)
# and repo info to each issue
for issue in append_issues:
issue["repo_name"] = repo_name
issue["repo_id"] = repo_id
issues.extend(append_issues)
with Pool(processes=4) as pool:
# async get zenhub pipeline attributes
issues = pool.map(async_get_zenhub_issues, issues)
for issue in issues:
# prepare issue object for csv output
issue = parse_issue(issue)
issue.update(parse_labels(issue["labels"]))
issue = {k: issue[k] for k in FIELDNAMES}
csv_data.append(issue)
with open("projects.csv", "w") as fout:
writer = csv.DictWriter(fout, fieldnames=FIELDNAMES)
writer.writeheader()
for row in csv_data:
writer.writerow(row)
if __name__ == "__main__":
main()