-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgithub.py
More file actions
256 lines (220 loc) · 9.1 KB
/
Copy pathgithub.py
File metadata and controls
256 lines (220 loc) · 9.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
import config
import datetime
import Queue
import requests
import threading
import time
import traceback
from collections import defaultdict
class Github:
def __init__(self, credentials, plugin):
self.credentials = credentials
self.total_threads = 0
self.total_requests = 0
self.remaining_rl = None
self.plugin = plugin
self.plugin.github = self
self.check_unicodes = {
'queued': '9685',
'in_progress': '9685',
'action_required': '65794',
'canceled': '65794',
'timed_out': '65794',
'failed': '65794',
'neutral': '9685',
'success': '10003',
'failure': '65794'
}
def user(self):
if not self.credentials.user:
self.__request_user()
return self.credentials.user
def name(self):
if not self.credentials.name:
self.__request_user()
return self.credentials.name
def list_org_repos(self, org):
url = 'https://api.github.com/orgs/%s/repos' % org
return [repo['url'] for repo in self.get(url)]
def list_user_repos(self, user):
url = 'https://api.github.com/users/%s/repos' % user
return [repo['url'] for repo in self.get(url)]
def search_pulls(self):
threads = []
results = Queue.Queue()
if config.THREADED:
for repo_url in self.plugin.repos:
try:
repo = self.get(repo_url)
t = threading.Thread(target=self._analyze_repo,
args=(repo, results,))
threads.append(t)
t.start()
except:
print "Could not analyze repository: %s" % repo_url
traceback.print_exc()
self.__incr_threads(len(threads))
for thread in threads:
thread.join()
else:
for repo_url in self.plugin.repos:
try:
repo = self.get(repo_url)
self._analyze_repo(repo, results)
except:
print "Could not analyze repository: %s" % repo_url
traceback.print_exc()
pulls = []
while not results.empty():
pulls.append(results.get())
return {
"pulls": pulls,
"total-threads": self.total_threads,
"total-requests": self.total_requests,
"rate-limit": self.remaining_rl
}
def _analyze_repo(self, repo, results):
payload = {"state": "open"}
pulls = self.get(repo["pulls_url"].replace("{/number}", ""), payload)
threads = []
if config.THREADED:
for pull_head in pulls:
try:
t = threading.Thread(target=self._analyze_pull,
args=(repo, pull_head, results,))
threads.append(t)
t.start()
except:
if config.DEBUG:
print "Could not analyze pull request: %s" % pull_head["url"]
self.__incr_threads(len(threads))
for thread in threads:
thread.join()
else:
for pull_head in pulls:
try:
self._analyze_pull(repo, pull_head, results)
except:
if config.DEBUG:
print "Could not analyze pull request: %s" % pull_head["url"]
return pulls
def _analyze_pull(self, repo, pull_head, results):
pull = self.get(pull_head["url"])
summary = {}
summary['name'] = pull["title"]
summary['url'] = pull["html_url"]
summary['repo_name'] = repo["name"]
summary['repo_url'] = repo["html_url"]
summary['author'] = pull["user"]["login"]
summary['old'] = self.get_days_old(pull)
summary['target_branch'] = pull["base"]["ref"]
summary['build_status'] = self._get_build_status(pull)
summary['likes'] = 0
summary['dislikes'] = 0
summary['checks'] = self._get_check_status(pull, repo)
self.plugin.parse_pull(pull, summary)
self._analyze_reviews(pull, summary)
self._analyze_comments(pull, summary)
results.put(summary)
def _get_check_status(self, pull, repo):
commits = self.get(pull["commits_url"])
last = commits[len(commits)-1]
check_suites = self.get('https://api.github.com/repos/%s/%s/commits/%s/check-runs'
% ('abiquo', repo["name"], last["sha"]),
accept='application/vnd.github.antiope-preview+json')['check_runs']
checks = {}
for cs in check_suites:
conclusion = cs["conclusion"] if cs["status"] == "completed" else cs["status"]
if conclusion in checks:
check = checks[conclusion]
check['num'] = check['num'] + 1
else:
check = {}
check['num'] = 1
check['unicode'] = self.check_unicodes[conclusion]
checks[conclusion] = check
return checks
def _get_build_status(self, pull):
statuses = self.get(pull['statuses_url'])
return statuses[0]['state'] if statuses else "unknown"
def _analyze_comments(self, pull, summary):
following = False
comments = self.get(pull["comments_url"])
comments.extend(self.get(pull["review_comments_url"]))
for comment in comments:
if comment["user"]["login"] == self.user():
following = True
self.plugin.parse_comment(comment, summary)
summary['comments'] = pull["comments"] + pull["review_comments"]
summary['following'] = following
def _analyze_reviews(self, pull, summary):
reviews = self.get_reviews(pull)
# Index by author, taking only into account approvals or rejections
review_map = defaultdict(list)
for r in filter(lambda r: r['state'] != 'COMMENTED', reviews):
review_map[r['user']['login']].append(r)
for author, author_reviews in review_map.iteritems():
# Get the last review for each author
review = max(author_reviews, key=lambda r: r['id'])
if review['state'] == 'APPROVED':
summary['likes'] = summary['likes'] + 1
elif review['state'] == 'CHANGES_REQUESTED':
summary['dislikes'] = summary['dislikes'] + 1
def get_days_old(self, pull):
last_updated = pull['updated_at']
dt = datetime.datetime.strptime(last_updated, '%Y-%m-%dT%H:%M:%SZ')
today = datetime.datetime.today()
return (today - dt).days
def get_reviews(self, pull):
return self.get(pull['url'] + '/reviews',
accept='application/vnd.github.black-cat-preview+json')
def get(self, url, params=None, delay=config.DELAY,
retries=config.MAX_RETRIES, backoff=config.BACKOFF,
accept='application/json'):
if config.DEBUG:
print "GET %s" % url
headers={'Accept': accept, 'Authorization': 'token ' + self.credentials.token}
while retries > 1:
response = requests.get(url, params=params, headers=headers)
self.__incr_requests()
self.__update_rl(response)
if response.status_code == requests.codes.ok:
json = response.json()
if "next" in response.links:
json.extend(self.get(response.links['next']["url"]))
return json
elif response.status_code >= 400 and response.status_code < 500:
response.raise_for_status()
elif response.status_code >= 500:
if config.DEBUG:
print "Request failed. Retrying in %s seconds" % delay
time.sleep(delay)
return self.get(url, params, delay * backoff,
retries - 1, backoff)
else:
json = response.json()
if "next" in response.links:
json.extend(self.get(response.links['next']["url"]))
return json
raise Exception("Request failed after %s retries" % config.MAX_RETRIES)
def __incr_requests(self):
rlock = threading.RLock()
with rlock:
self.total_requests += 1
def __update_rl(self, response):
rate_remaining = response.headers['X-RateLimit-Remaining']
if rate_remaining is not None:
new_rl = int(rate_remaining)
rlock = threading.RLock()
with rlock:
if self.remaining_rl is None or new_rl < self.remaining_rl:
self.remaining_rl = new_rl
def __incr_threads(self, num_threads):
rlock = threading.RLock()
with rlock:
self.total_threads += num_threads
def __request_user(self):
url = 'https://api.github.com/user'
r = self.get(url)
self.credentials.user = r['login']
self.credentials.name = r['name']