-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgithubactivity.py
More file actions
271 lines (218 loc) · 7.52 KB
/
githubactivity.py
File metadata and controls
271 lines (218 loc) · 7.52 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
import datetime
import argparse
from github import Github
from mako.template import Template
# ahem hack to cope with printing utf8
# http://stackoverflow.com/a/1169209/54056
import sys
import codecs
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
dateStamp = '%Y-%m-%d'
class Commit(object):
def __init__(self, commit):
self._commit = commit
@property
def author(self):
if self._commit.author is None:
return 'None?'
return self._commit.author.login
@property
def message(self):
lines = [l.strip() for l in self._commit.commit.message.split('\n')]
lines = [l for l in lines if l]
return lines[0]
@property
def timestamp(self):
return self._commit.commit.author.date.strftime(dateStamp)
class PullRequest(object):
def __init__(self, pull):
self._pull = pull
self._closer = '?'
@property
def closedTimestamp(self):
return self._pull.closed_at.strftime(dateStamp)
@property
def closer(self):
return self._closer
def addCloser(self, closer):
if closer:
self._closer = closer
@property
def author(self):
return self._pull.user.login
@property
def title(self):
return self._pull.title
@property
def number(self):
return self._pull.number
class Issue(object):
def __init__(self, issue):
self._issue = issue
@property
def url(self):
return self._issue.html_url
@property
def assignee(self):
if self._issue.assignee:
return self._issue.assignee.login
return 'no'
@property
def author(self):
return self._issue.user.login
@property
def number(self):
return self._issue.number
@property
def title(self):
return self._issue.title
@property
def timestamp(self):
if self.created == self.updated:
return 'new {}'.format(self.created)
return 'updated {}'.format(self.updated)
@property
def created(self):
return self._issue.created_at.strftime(dateStamp)
@property
def updated(self):
return self._issue.updated_at.strftime(dateStamp)
@property
def closer(self):
return self._issue.closed_by.login
@property
def closed(self):
return self._issue.closed_at.strftime(dateStamp)
@property
def comments(self):
return list(self._issue.get_comments())
@property
def commentSummary(self):
totalComments = len(self.comments)
if totalComments == 0:
return 'No comments'
if totalComments == 1:
return '1 comment'
else:
return '{} comments'.format(totalComments)
def getRecentCommits(repo, start):
"""
@param repo: a GitRepo object
@return: string
"""
commits = repo.get_commits()
recentCommits = []
for commit in commits:
# I think we're iterating through these basically backwards??
ts = commit.commit.author.date
if ts < start:
break
# end might be specified, i.e. in the past
recentCommits.append(Commit(commit))
return recentCommits
def getPullRequestsOpen(repo):
pulls = repo.get_pulls('open')
pulls = [PullRequest(p) for p in pulls]
return pulls
def getPullRequestsClosed(repo, start):
pulls = repo.get_pulls('closed')
pulls = [PullRequest(p) for p in pulls if start < p.closed_at]
closingevents = getPullRequestClosingEvents(repo, start)
for pull in pulls:
closer = findCloser(pull, closingevents)
pull.addCloser(closer)
return pulls
def findCloser(pull, closingevents):
closes = [e for e in closingevents if e.payload['number'] == pull.number]
if closes == []:
# somehow couldn't find one
return None
# can be more than one if a pull request is reopened
lastClose = max(closes, key=lambda e: e.created_at)
return lastClose.actor.login
def getPullRequestClosingEvents(repo, start):
closingevents = []
for event in repo.get_events():
if event.created_at < start:
break
if event.type != 'PullRequestEvent':
continue
if event.payload['action'] != 'closed':
continue
closingevents.append(event)
return closingevents
def getIssuesUpdated(repo, start):
if not repo.has_issues:
return False
issues = [Issue(i) for i in repo.get_issues(state='open', sort='updated', since=start)]
return issues
def getIssuesClosed(repo, start):
if not repo.has_issues:
return False
issues = [Issue(i) for i in repo.get_issues(state='closed', sort='updated', since=start)]
return issues
def getRepoActivity(org, repo, days=None, reportNoActivity=True, username=None, password=None):
"""
@param org: a string representing an organization
@param repo: a string representing a repo
@param days: optional, int
@param end: optional, datetime object
@param reportNoActivity: bool, explicitly report when there has been no activity?
@return: string
"""
if not days:
days = 7
end = datetime.datetime.today()
period = datetime.timedelta(days=days)
start = end - period
if username and password:
g = Github(login_or_token=username, password=password)
else:
g = Github()
repository = g.get_organization(org).get_repo(repo)
commits = getRecentCommits(repository, start)
pullReqOpen = getPullRequestsOpen(repository)
pullReqClosed = getPullRequestsClosed(repository, start)
hasIssues = repository.has_issues
contents = {
'repo': repo,
'org': org,
'period': period.days,
'end': end.strftime('%Y-%m-%d'),
'commits': commits,
'pullrequestsopen': pullReqOpen,
'pullrequestsclosed': pullReqClosed,
'hasIssues': hasIssues,
'issuessubmitted': None,
'issuesactivity': None,
'issuesclosed': None,
}
if hasIssues:
issuesUpdated = getIssuesUpdated(repository, start)
issuesClosed = getIssuesClosed(repository, start)
contents.update({
'issuesupdated': issuesUpdated,
'issuesclosed': issuesClosed
})
template = Template(filename='template.txt')
result = template.render(**contents)
return result
def dateObject(s):
try:
d = datetime.datetime.strptime(s, dateStamp)
except ValueError:
msg = "'{}' is not a timestamp of the form '{}'".format(s, dateStamp)
raise argparse.ArgumentTypeError(msg)
return d
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Print out a summary of Github activity")
parser.add_argument("-o", dest="org", required=True, help="Name of an organization")
parser.add_argument("-r", dest="repo", required=True, help="Name of a repository")
parser.add_argument("-d", dest="days", default=None, type=int, help="Number of days to summarise")
# parser.add_argument("-e", dest="end", default=None, type=dateObject, help="End date (in format '{}'".format(dateStamp))
parser.add_argument('--reportNoActivity', '-n', action="store_true", default=False, help="Report explicitly if there is no activity")
parser.add_argument("-u", dest="username", required=False, help="Github username (authenticating increases the rate limit for hitting the Github API)")
parser.add_argument("-p", dest="password", required=False, help="Github password")
args = parser.parse_args()
r = getRepoActivity(**vars(args))
print r