blob: d8a093a81fcfa980a926d83c5c6405f51260562d [file] [log] [blame]
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +00001#!/usr/bin/env python
2# Copyright (c) 2012 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Get stats about your activity.
7
8Example:
9 - my_activity.py for stats for the current week (last week on mondays).
10 - my_activity.py -Q for stats for last quarter.
11 - my_activity.py -Y for stats for this year.
12 - my_activity.py -b 4/5/12 for stats since 4/5/12.
13 - my_activity.py -b 4/5/12 -e 6/7/12 for stats between 4/5/12 and 6/7/12.
14"""
15
16# These services typically only provide a created time and a last modified time
17# for each item for general queries. This is not enough to determine if there
18# was activity in a given time period. So, we first query for all things created
19# before end and modified after begin. Then, we get the details of each item and
20# check those details to determine if there was activity in the given period.
21# This means that query time scales mostly with (today() - begin).
22
23import cookielib
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +000024import csv
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +000025import datetime
26from datetime import datetime
27from datetime import timedelta
28from functools import partial
29import json
30import optparse
31import os
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +000032import re
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +000033import subprocess
34import sys
35import urllib
36import urllib2
37
deymo@chromium.orgf8be2762013-11-06 01:01:59 +000038import gerrit_util
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +000039import rietveld
40from third_party import upload
41
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +000042# Imported later, once options are set.
43webkitpy = None
44
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +000045try:
46 from dateutil.relativedelta import relativedelta # pylint: disable=F0401
47except ImportError:
48 print 'python-dateutil package required'
49 exit(1)
50
51# python-keyring provides easy access to the system keyring.
52try:
53 import keyring # pylint: disable=W0611,F0401
54except ImportError:
55 print 'Consider installing python-keyring'
56
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +000057def webkit_account(user):
58 if not webkitpy:
59 return None
60 committer_list = webkitpy.common.config.committers.CommitterList()
61 email = user + "@chromium.org"
62 return committer_list.account_by_email(email)
63
64def user_to_webkit_email(user):
65 account = webkit_account(user)
66 if not account:
67 return None
68 return account.emails[0]
69
70def user_to_webkit_owner_search(user):
71 account = webkit_account(user)
72 if not account:
73 return ['--author=%s@chromium.org' % user]
74 search = []
75 for email in account.emails:
76 search.append('--author=' + email)
77 # commit-bot is author for contributors who are not committers.
78 search.append('--grep=Patch by ' + account.full_name)
79 return search
80
81def user_to_webkit_reviewer_search(user):
82 committer_list = webkitpy.common.config.committers.CommitterList()
83 email = user + "@chromium.org"
84 account = committer_list.reviewer_by_email(email)
85 if not account:
86 return []
87 return ['--grep=Reviewed by ' + account.full_name]
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +000088
89rietveld_instances = [
90 {
91 'url': 'codereview.chromium.org',
92 'shorturl': 'crrev.com',
93 'supports_owner_modified_query': True,
94 'requires_auth': False,
95 'email_domain': 'chromium.org',
96 },
97 {
98 'url': 'chromereviews.googleplex.com',
99 'shorturl': 'go/chromerev',
100 'supports_owner_modified_query': True,
101 'requires_auth': True,
102 'email_domain': 'google.com',
103 },
104 {
105 'url': 'codereview.appspot.com',
106 'supports_owner_modified_query': True,
107 'requires_auth': False,
108 'email_domain': 'chromium.org',
109 },
110 {
111 'url': 'breakpad.appspot.com',
112 'supports_owner_modified_query': False,
113 'requires_auth': False,
114 'email_domain': 'chromium.org',
115 },
116]
117
118gerrit_instances = [
119 {
deymo@chromium.org6c039202013-09-12 12:28:12 +0000120 'url': 'chromium-review.googlesource.com',
deymo@chromium.orge52bd5a2013-08-29 18:05:21 +0000121 'shorturl': 'crosreview.com',
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000122 },
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000123 {
124 'url': 'chrome-internal-review.googlesource.com',
125 'shorturl': 'crosreview.com/i',
126 },
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000127 {
deymo@chromium.org6c039202013-09-12 12:28:12 +0000128 'host': 'gerrit.chromium.org',
129 'port': 29418,
130 },
131 {
132 'host': 'gerrit-int.chromium.org',
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000133 'port': 29419,
134 },
135]
136
137google_code_projects = [
138 {
139 'name': 'chromium',
140 'shorturl': 'crbug.com',
141 },
142 {
143 'name': 'chromium-os',
deymo@chromium.orgc840e212013-02-13 20:40:22 +0000144 'shorturl': 'crosbug.com',
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000145 },
146 {
147 'name': 'chrome-os-partner',
148 },
149 {
150 'name': 'google-breakpad',
151 },
152 {
153 'name': 'gyp',
enne@chromium.orgf01fad32012-11-26 18:09:38 +0000154 },
155 {
156 'name': 'skia',
157 },
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000158]
159
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000160bugzilla_instances = [
161 {
162 'search_url': 'http://bugs.webkit.org/buglist.cgi',
163 'url': 'wkb.ug',
164 'user_func': user_to_webkit_email,
165 },
166]
167
168git_instances = [
169 {
170 'option': 'webkit_repo',
171 'change_re':
172 r'git-svn-id: http://svn\.webkit\.org/repository/webkit/trunk@(\d*)',
173 'change_url': 'trac.webkit.org/changeset',
174 'review_re': r'https://bugs\.webkit\.org/show_bug\.cgi\?id\=(\d*)',
175 'review_url': 'wkb.ug',
176 'review_prop': 'webkit_bug_id',
177
178 'owner_search_func': user_to_webkit_owner_search,
179 'reviewer_search_func': user_to_webkit_reviewer_search,
180 },
181]
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000182
183# Uses ClientLogin to authenticate the user for Google Code issue trackers.
184def get_auth_token(email):
cjhopman@chromium.org3365f2d2012-11-01 18:53:13 +0000185 # KeyringCreds will use the system keyring on the first try, and prompt for
186 # a password on the next ones.
187 creds = upload.KeyringCreds('code.google.com', 'code.google.com', email)
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000188 for _ in xrange(3):
cjhopman@chromium.org3365f2d2012-11-01 18:53:13 +0000189 email, password = creds.GetUserCredentials()
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000190 url = 'https://www.google.com/accounts/ClientLogin'
191 data = urllib.urlencode({
192 'Email': email,
193 'Passwd': password,
194 'service': 'code',
195 'source': 'chrome-my-activity',
196 'accountType': 'GOOGLE',
197 })
198 req = urllib2.Request(url, data=data, headers={'Accept': 'text/plain'})
199 try:
200 response = urllib2.urlopen(req)
201 response_body = response.read()
202 response_dict = dict(x.split('=')
203 for x in response_body.split('\n') if x)
204 return response_dict['Auth']
205 except urllib2.HTTPError, e:
cjhopman@chromium.org3365f2d2012-11-01 18:53:13 +0000206 print e
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000207
cjhopman@chromium.org3365f2d2012-11-01 18:53:13 +0000208 print 'Unable to authenticate to code.google.com.'
209 print 'Some issues may be missing.'
210 return None
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000211
212
213def username(email):
214 """Keeps the username of an email address."""
215 return email and email.split('@', 1)[0]
216
217
cjhopman@chromium.org426557a2012-10-22 20:18:52 +0000218def datetime_to_midnight(date):
219 return date - timedelta(hours=date.hour, minutes=date.minute,
220 seconds=date.second, microseconds=date.microsecond)
221
222
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000223def get_quarter_of(date):
cjhopman@chromium.org426557a2012-10-22 20:18:52 +0000224 begin = (datetime_to_midnight(date) -
225 relativedelta(months=(date.month % 3) - 1, days=(date.day - 1)))
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000226 return begin, begin + relativedelta(months=3)
227
228
229def get_year_of(date):
cjhopman@chromium.org426557a2012-10-22 20:18:52 +0000230 begin = (datetime_to_midnight(date) -
231 relativedelta(months=(date.month - 1), days=(date.day - 1)))
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000232 return begin, begin + relativedelta(years=1)
233
234
235def get_week_of(date):
cjhopman@chromium.org426557a2012-10-22 20:18:52 +0000236 begin = (datetime_to_midnight(date) - timedelta(days=date.weekday()))
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000237 return begin, begin + timedelta(days=7)
238
239
240def get_yes_or_no(msg):
241 while True:
242 response = raw_input(msg + ' yes/no [no] ')
243 if response == 'y' or response == 'yes':
244 return True
245 elif not response or response == 'n' or response == 'no':
246 return False
247
248
deymo@chromium.org6c039202013-09-12 12:28:12 +0000249def datetime_from_gerrit(date_string):
250 return datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f000')
251
252
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000253def datetime_from_rietveld(date_string):
254 return datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
255
256
257def datetime_from_google_code(date_string):
258 return datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%fZ')
259
260
261class MyActivity(object):
262 def __init__(self, options):
263 self.options = options
264 self.modified_after = options.begin
265 self.modified_before = options.end
266 self.user = options.user
267 self.changes = []
268 self.reviews = []
269 self.issues = []
270 self.check_cookies()
271 self.google_code_auth_token = None
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000272 self.webkit_repo = options.webkit_repo
273 if self.webkit_repo:
274 self.setup_webkit_info()
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000275
276 # Check the codereview cookie jar to determine which Rietveld instances to
277 # authenticate to.
278 def check_cookies(self):
279 cookie_file = os.path.expanduser('~/.codereview_upload_cookies')
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000280 if not os.path.exists(cookie_file):
deymo@chromium.org8aee4862013-11-13 19:33:27 +0000281 print 'No Rietveld cookie file found.'
282 cookie_jar = []
283 else:
284 cookie_jar = cookielib.MozillaCookieJar(cookie_file)
285 try:
286 cookie_jar.load()
287 print 'Found cookie file: %s' % cookie_file
288 except (cookielib.LoadError, IOError):
289 print 'Error loading Rietveld cookie file: %s' % cookie_file
290 cookie_jar = []
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000291
292 filtered_instances = []
293
294 def has_cookie(instance):
295 for cookie in cookie_jar:
296 if cookie.name == 'SACSID' and cookie.domain == instance['url']:
297 return True
298 if self.options.auth:
299 return get_yes_or_no('No cookie found for %s. Authorize for this '
300 'instance? (may require application-specific '
301 'password)' % instance['url'])
302 filtered_instances.append(instance)
303 return False
304
305 for instance in rietveld_instances:
306 instance['auth'] = has_cookie(instance)
307
308 if filtered_instances:
309 print ('No cookie found for the following Rietveld instance%s:' %
310 ('s' if len(filtered_instances) > 1 else ''))
311 for instance in filtered_instances:
312 print '\t' + instance['url']
313 print 'Use --auth if you would like to authenticate to them.\n'
314
315 def rietveld_search(self, instance, owner=None, reviewer=None):
316 if instance['requires_auth'] and not instance['auth']:
317 return []
318
319
320 email = None if instance['auth'] else ''
321 remote = rietveld.Rietveld('https://' + instance['url'], email, None)
322
323 # See def search() in rietveld.py to see all the filters you can use.
324 query_modified_after = None
325
326 if instance['supports_owner_modified_query']:
327 query_modified_after = self.modified_after.strftime('%Y-%m-%d')
328
329 # Rietveld does not allow search by both created_before and modified_after.
330 # (And some instances don't allow search by both owner and modified_after)
331 owner_email = None
332 reviewer_email = None
333 if owner:
334 owner_email = owner + '@' + instance['email_domain']
335 if reviewer:
336 reviewer_email = reviewer + '@' + instance['email_domain']
337 issues = remote.search(
338 owner=owner_email,
339 reviewer=reviewer_email,
340 modified_after=query_modified_after,
341 with_messages=True)
342
343 issues = filter(
344 lambda i: (datetime_from_rietveld(i['created']) < self.modified_before),
345 issues)
346 issues = filter(
347 lambda i: (datetime_from_rietveld(i['modified']) > self.modified_after),
348 issues)
349
350 should_filter_by_user = True
351 issues = map(partial(self.process_rietveld_issue, instance), issues)
352 issues = filter(
353 partial(self.filter_issue, should_filter_by_user=should_filter_by_user),
354 issues)
355 issues = sorted(issues, key=lambda i: i['modified'], reverse=True)
356
357 return issues
358
359 def process_rietveld_issue(self, instance, issue):
360 ret = {}
361 ret['owner'] = issue['owner_email']
362 ret['author'] = ret['owner']
363
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000364 ret['reviewers'] = set(issue['reviewers'])
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000365
366 shorturl = instance['url']
367 if 'shorturl' in instance:
368 shorturl = instance['shorturl']
369
370 ret['review_url'] = 'http://%s/%d' % (shorturl, issue['issue'])
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000371
372 # Rietveld sometimes has '\r\n' instead of '\n'.
373 ret['header'] = issue['description'].replace('\r', '').split('\n')[0]
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000374
375 ret['modified'] = datetime_from_rietveld(issue['modified'])
376 ret['created'] = datetime_from_rietveld(issue['created'])
377 ret['replies'] = self.process_rietveld_replies(issue['messages'])
378
379 return ret
380
381 @staticmethod
382 def process_rietveld_replies(replies):
383 ret = []
384 for reply in replies:
385 r = {}
386 r['author'] = reply['sender']
387 r['created'] = datetime_from_rietveld(reply['date'])
388 r['content'] = ''
389 ret.append(r)
390 return ret
391
deymo@chromium.org6c039202013-09-12 12:28:12 +0000392 @staticmethod
393 def gerrit_changes_over_ssh(instance, filters):
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000394 # See https://review.openstack.org/Documentation/cmd-query.html
395 # Gerrit doesn't allow filtering by created time, only modified time.
deymo@chromium.org6c039202013-09-12 12:28:12 +0000396 gquery_cmd = ['ssh', '-p', str(instance['port']), instance['host'],
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000397 'gerrit', 'query',
398 '--format', 'JSON',
399 '--comments',
deymo@chromium.org6c039202013-09-12 12:28:12 +0000400 '--'] + filters
401 (stdout, _) = subprocess.Popen(gquery_cmd, stdout=subprocess.PIPE,
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000402 stderr=subprocess.PIPE).communicate()
deymo@chromium.org6c039202013-09-12 12:28:12 +0000403 # Drop the last line of the output with the stats.
404 issues = stdout.splitlines()[:-1]
405 return map(json.loads, issues)
406
407 @staticmethod
408 def gerrit_changes_over_rest(instance, filters):
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000409 # Convert the "key:value" filter to a dictionary.
410 req = dict(f.split(':', 1) for f in filters)
deymo@chromium.org6c039202013-09-12 12:28:12 +0000411 try:
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000412 # Instantiate the generator to force all the requests now and catch the
413 # errors here.
414 return list(gerrit_util.GenerateAllChanges(instance['url'], req,
415 o_params=['MESSAGES', 'LABELS', 'DETAILED_ACCOUNTS']))
416 except gerrit_util.GerritError, e:
417 print 'ERROR: Looking up %r: %s' % (instance['url'], e)
deymo@chromium.org6c039202013-09-12 12:28:12 +0000418 return []
419
deymo@chromium.org6c039202013-09-12 12:28:12 +0000420 def gerrit_search(self, instance, owner=None, reviewer=None):
421 max_age = datetime.today() - self.modified_after
422 max_age = max_age.days * 24 * 3600 + max_age.seconds
423 user_filter = 'owner:%s' % owner if owner else 'reviewer:%s' % reviewer
424 filters = ['-age:%ss' % max_age, user_filter]
425
426 # Determine the gerrit interface to use: SSH or REST API:
427 if 'host' in instance:
428 issues = self.gerrit_changes_over_ssh(instance, filters)
429 issues = [self.process_gerrit_ssh_issue(instance, issue)
430 for issue in issues]
431 elif 'url' in instance:
432 issues = self.gerrit_changes_over_rest(instance, filters)
433 issues = [self.process_gerrit_rest_issue(instance, issue)
434 for issue in issues]
435 else:
436 raise Exception('Invalid gerrit_instances configuration.')
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000437
438 # TODO(cjhopman): should we filter abandoned changes?
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000439 issues = filter(self.filter_issue, issues)
440 issues = sorted(issues, key=lambda i: i['modified'], reverse=True)
441
442 return issues
443
deymo@chromium.org6c039202013-09-12 12:28:12 +0000444 def process_gerrit_ssh_issue(self, instance, issue):
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000445 ret = {}
446 ret['review_url'] = issue['url']
deymo@chromium.orge52bd5a2013-08-29 18:05:21 +0000447 if 'shorturl' in instance:
448 ret['review_url'] = 'http://%s/%s' % (instance['shorturl'],
449 issue['number'])
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000450 ret['header'] = issue['subject']
451 ret['owner'] = issue['owner']['email']
452 ret['author'] = ret['owner']
453 ret['created'] = datetime.fromtimestamp(issue['createdOn'])
454 ret['modified'] = datetime.fromtimestamp(issue['lastUpdated'])
455 if 'comments' in issue:
deymo@chromium.org6c039202013-09-12 12:28:12 +0000456 ret['replies'] = self.process_gerrit_ssh_issue_replies(issue['comments'])
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000457 else:
458 ret['replies'] = []
deymo@chromium.org6c039202013-09-12 12:28:12 +0000459 ret['reviewers'] = set(r['author'] for r in ret['replies'])
460 ret['reviewers'].discard(ret['author'])
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000461 return ret
462
463 @staticmethod
deymo@chromium.org6c039202013-09-12 12:28:12 +0000464 def process_gerrit_ssh_issue_replies(replies):
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000465 ret = []
466 replies = filter(lambda r: 'email' in r['reviewer'], replies)
467 for reply in replies:
deymo@chromium.org6c039202013-09-12 12:28:12 +0000468 ret.append({
469 'author': reply['reviewer']['email'],
470 'created': datetime.fromtimestamp(reply['timestamp']),
471 'content': '',
472 })
473 return ret
474
475 def process_gerrit_rest_issue(self, instance, issue):
476 ret = {}
477 ret['review_url'] = 'https://%s/%s' % (instance['url'], issue['_number'])
478 if 'shorturl' in instance:
479 # TODO(deymo): Move this short link to https once crosreview.com supports
480 # it.
481 ret['review_url'] = 'http://%s/%s' % (instance['shorturl'],
482 issue['_number'])
483 ret['header'] = issue['subject']
484 ret['owner'] = issue['owner']['email']
485 ret['author'] = ret['owner']
486 ret['created'] = datetime_from_gerrit(issue['created'])
487 ret['modified'] = datetime_from_gerrit(issue['updated'])
488 if 'messages' in issue:
489 ret['replies'] = self.process_gerrit_rest_issue_replies(issue['messages'])
490 else:
491 ret['replies'] = []
492 ret['reviewers'] = set(r['author'] for r in ret['replies'])
493 ret['reviewers'].discard(ret['author'])
494 return ret
495
496 @staticmethod
497 def process_gerrit_rest_issue_replies(replies):
498 ret = []
deymo@chromium.orgf8be2762013-11-06 01:01:59 +0000499 replies = filter(lambda r: 'author' in r and 'email' in r['author'],
500 replies)
deymo@chromium.org6c039202013-09-12 12:28:12 +0000501 for reply in replies:
502 ret.append({
503 'author': reply['author']['email'],
504 'created': datetime_from_gerrit(reply['date']),
505 'content': reply['message'],
506 })
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000507 return ret
508
509 def google_code_issue_search(self, instance):
510 time_format = '%Y-%m-%dT%T'
511 # See http://code.google.com/p/support/wiki/IssueTrackerAPI
512 # q=<owner>@chromium.org does a full text search for <owner>@chromium.org.
513 # This will accept the issue if owner is the owner or in the cc list. Might
514 # have some false positives, though.
515
516 # Don't filter normally on modified_before because it can filter out things
517 # that were modified in the time period and then modified again after it.
518 gcode_url = ('https://code.google.com/feeds/issues/p/%s/issues/full' %
519 instance['name'])
520
521 gcode_data = urllib.urlencode({
522 'alt': 'json',
523 'max-results': '100000',
524 'q': '%s' % self.user,
525 'published-max': self.modified_before.strftime(time_format),
526 'updated-min': self.modified_after.strftime(time_format),
527 })
528
529 opener = urllib2.build_opener()
cjhopman@chromium.org3365f2d2012-11-01 18:53:13 +0000530 if self.google_code_auth_token:
531 opener.addheaders = [('Authorization', 'GoogleLogin auth=%s' %
532 self.google_code_auth_token)]
533 gcode_json = None
534 try:
535 gcode_get = opener.open(gcode_url + '?' + gcode_data)
536 gcode_json = json.load(gcode_get)
537 gcode_get.close()
538 except urllib2.HTTPError, _:
539 print 'Unable to access ' + instance['name'] + ' issue tracker.'
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000540
cjhopman@chromium.org3365f2d2012-11-01 18:53:13 +0000541 if not gcode_json or 'entry' not in gcode_json['feed']:
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000542 return []
543
544 issues = gcode_json['feed']['entry']
545 issues = map(partial(self.process_google_code_issue, instance), issues)
546 issues = filter(self.filter_issue, issues)
547 issues = sorted(issues, key=lambda i: i['modified'], reverse=True)
548 return issues
549
550 def process_google_code_issue(self, project, issue):
551 ret = {}
552 ret['created'] = datetime_from_google_code(issue['published']['$t'])
553 ret['modified'] = datetime_from_google_code(issue['updated']['$t'])
554
555 ret['owner'] = ''
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000556 if 'issues$owner' in issue:
557 ret['owner'] = issue['issues$owner']['issues$username']['$t']
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000558 ret['author'] = issue['author'][0]['name']['$t']
559
560 if 'shorturl' in project:
561 issue_id = issue['id']['$t']
562 issue_id = issue_id[issue_id.rfind('/') + 1:]
563 ret['url'] = 'http://%s/%d' % (project['shorturl'], int(issue_id))
564 else:
565 issue_url = issue['link'][1]
566 if issue_url['rel'] != 'alternate':
567 raise RuntimeError
568 ret['url'] = issue_url['href']
569 ret['header'] = issue['title']['$t']
570
571 ret['replies'] = self.get_google_code_issue_replies(issue)
572 return ret
573
574 def get_google_code_issue_replies(self, issue):
575 """Get all the comments on the issue."""
576 replies_url = issue['link'][0]
577 if replies_url['rel'] != 'replies':
578 raise RuntimeError
579
580 replies_data = urllib.urlencode({
581 'alt': 'json',
582 'fields': 'entry(published,author,content)',
583 })
584
585 opener = urllib2.build_opener()
586 opener.addheaders = [('Authorization', 'GoogleLogin auth=%s' %
587 self.google_code_auth_token)]
588 try:
589 replies_get = opener.open(replies_url['href'] + '?' + replies_data)
590 except urllib2.HTTPError, _:
591 return []
592
593 replies_json = json.load(replies_get)
594 replies_get.close()
595 return self.process_google_code_issue_replies(replies_json)
596
597 @staticmethod
598 def process_google_code_issue_replies(replies):
599 if 'entry' not in replies['feed']:
600 return []
601
602 ret = []
603 for entry in replies['feed']['entry']:
604 e = {}
605 e['created'] = datetime_from_google_code(entry['published']['$t'])
606 e['content'] = entry['content']['$t']
607 e['author'] = entry['author'][0]['name']['$t']
608 ret.append(e)
609 return ret
610
611 @staticmethod
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000612 def git_cmd(repo, *args):
613 cmd = ['git', '--git-dir=%s/.git' % repo]
614 cmd.extend(args)
615 [stdout, _] = subprocess.Popen(cmd, stdout=subprocess.PIPE,
616 stderr=subprocess.PIPE).communicate()
617 lines = str(stdout).split('\n')[:-1]
618 return lines
619
620 def git_search(self, instance, owner=None, reviewer=None):
621 repo = getattr(self, instance['option'])
622 if not repo:
623 return []
624
625 search = []
626 if owner:
627 search.extend(instance['owner_search_func'](owner))
628 if reviewer:
629 search.extend(instance['reviewer_search_func'](reviewer))
630 if not len(search):
631 return []
632
633 self.git_cmd(repo, 'fetch', 'origin')
634
635 time_format = '%Y-%m-%d %H:%M:%S'
636 log_args = [
637 '--after=' + self.modified_after.strftime(time_format),
638 '--before=' + self.modified_before.strftime(time_format),
639 '--format=%H'
640 ]
641 commits = set()
642 for query in search:
643 query_args = [query]
644 query_args.extend(log_args)
645 commits |= set(self.git_cmd(repo, 'log', 'origin/master', *query_args))
646
647 ret = []
648 for commit in commits:
649 output = self.git_cmd(repo, 'log', commit + "^!", "--format=%cn%n%cd%n%B")
650 author = output[0]
651 date = datetime.strptime(output[1], "%a %b %d %H:%M:%S %Y +0000")
enne@chromium.orgd69dab92013-06-10 20:19:56 +0000652 processed = self.process_git_commit(instance, author, date, output[2:])
653 if processed:
654 ret.append(processed)
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000655
656 ret = sorted(ret, key=lambda i: i['modified'], reverse=True)
657 return ret
658
659 @staticmethod
660 def process_git_commit(instance, author, date, log):
661 ret = {}
662 ret['owner'] = author
663 ret['author'] = author
664 ret['modified'] = date
665 ret['created'] = date
666 ret['header'] = log[0]
667
668 reviews = []
669 reviewers = []
670 changes = []
671
672 for line in log:
673 match = re.match(r'Reviewed by ([^.]*)', line)
674 if match:
675 reviewers.append(match.group(1))
676 if instance['review_re']:
677 match = re.match(instance['review_re'], line)
678 if match:
679 reviews.append(int(match.group(1)))
680 if instance['change_re']:
681 match = re.match(instance['change_re'], line)
682 if match:
683 changes.append(int(match.group(1)))
684
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000685 committer_list = webkitpy.common.config.committers.CommitterList()
686 ret['reviewers'] = set(
687 (committer_list.contributor_by_name(r).emails[0] for r in reviewers))
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000688
689 # Reviews more useful than change link itself, but tricky if multiple
690 # Reviews == bugs for WebKit changes
691 if len(reviews) == 1:
692 url = 'http://%s/%d' % (instance['review_url'], reviews[0])
693 if instance['review_prop']:
694 ret[instance['review_prop']] = reviews[0]
enne@chromium.orgd69dab92013-06-10 20:19:56 +0000695 elif len(changes) == 1:
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000696 url = 'http://%s/%d' % (instance['change_url'], changes[0])
enne@chromium.orgd69dab92013-06-10 20:19:56 +0000697 else:
698 # Couldn't find anything.
699 return None
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000700 ret['review_url'] = url
701
702 return ret
703
704 def bugzilla_issues(self, instance, user):
705 if instance['user_func']:
706 user = instance['user_func'](user)
707 if not user:
708 return []
709
710 # This search is a little iffy, as it returns any bug that has been
711 # modified over a time period in any way and that a user has ever commented
712 # on, but that's the best that Bugzilla can get us. Oops.
713 commented = { 'emaillongdesc1': 1 }
714 issues = self.bugzilla_search(instance, user, commented)
715 issues = filter(lambda issue: issue['owner'] != user, issues)
716
717 reported = { 'emailreporter1': 1, 'chfield': '[Bug creation]' }
718 issues.extend(self.bugzilla_search(instance, user, reported))
719
720 # Remove duplicates by bug id
721 seen = {}
722 pruned = []
723 for issue in issues:
724 bug_id = issue['webkit_bug_id']
725 if bug_id in seen:
726 continue
727 seen[bug_id] = True
728 pruned.append(issue)
729
730 # Bugzilla has no modified time, so sort by id?
731 pruned = sorted(pruned, key=lambda i: i['webkit_bug_id'])
732 return issues
733
734 def bugzilla_search(self, instance, user, params):
735 time_format = '%Y-%m-%d'
736 values = {
737 'chfieldfrom': self.modified_after.strftime(time_format),
738 'chfieldto': self.modified_before.strftime(time_format),
739 'ctype': 'csv',
740 'emailtype1': 'substring',
741 'email1': '%s' % user,
742 }
743 values.update(params)
744
745 # Must be GET not POST
746 data = urllib.urlencode(values)
747 req = urllib2.Request("%s?%s" % (instance['search_url'], data))
748 response = urllib2.urlopen(req)
749 reader = csv.reader(response)
750 reader.next() # skip the header line
751
752 issues = map(partial(self.process_bugzilla_issue, instance), reader)
753 return issues
754
755 @staticmethod
756 def process_bugzilla_issue(instance, issue):
757 bug_id, owner, desc = int(issue[0]), issue[4], issue[7]
758
759 ret = {}
760 ret['owner'] = owner
761 ret['author'] = owner
762 ret['review_url'] = 'http://%s/%d' % (instance['url'], bug_id)
763 ret['url'] = ret['review_url']
764 ret['header'] = desc
765 ret['webkit_bug_id'] = bug_id
766 return ret
767
768 def setup_webkit_info(self):
769 assert(self.webkit_repo)
770 git_dir = os.path.normpath(self.webkit_repo + "/.git")
771 if not os.path.exists(git_dir):
scheib@chromium.orgb299e7c2012-11-13 21:34:34 +0000772 print "%s doesn't exist, skipping WebKit checks." % git_dir
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000773 self.webkit_repo = None
774 return
775
776 try:
777 self.git_cmd(self.webkit_repo, "fetch", "origin")
778 except subprocess.CalledProcessError:
scheib@chromium.orgb299e7c2012-11-13 21:34:34 +0000779 print "Failed to update WebKit repo, skipping WebKit checks."
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000780 self.webkit_repo = None
781 return
782
783 path = "Tools/Scripts"
784 full_path = os.path.normpath("%s/%s" % (self.options.webkit_repo, path))
785 sys.path.append(full_path)
786
787 try:
788 global webkitpy
789 webkitpy = __import__('webkitpy.common.config.committers')
790 except ImportError:
scheib@chromium.orgb299e7c2012-11-13 21:34:34 +0000791 print "Failed to import WebKit committer list, skipping WebKit checks."
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000792 self.webkit_repo = None
793 return
794
795 if not webkit_account(self.user):
796 email = self.user + "@chromium.org"
scheib@chromium.orgb299e7c2012-11-13 21:34:34 +0000797 print "No %s in committers.py, skipping WebKit checks." % email
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000798 self.webkit_repo = None
799
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000800 def print_change(self, change):
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000801 optional_values = {
802 'reviewers': ', '.join(change['reviewers'])
803 }
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000804 self.print_generic(self.options.output_format,
805 self.options.output_format_changes,
806 change['header'],
807 change['review_url'],
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000808 change['author'],
809 optional_values)
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000810
811 def print_issue(self, issue):
812 optional_values = {
813 'owner': issue['owner'],
814 }
815 self.print_generic(self.options.output_format,
816 self.options.output_format_issues,
817 issue['header'],
818 issue['url'],
819 issue['author'],
820 optional_values)
821
822 def print_review(self, review):
823 self.print_generic(self.options.output_format,
824 self.options.output_format_reviews,
825 review['header'],
826 review['review_url'],
827 review['author'])
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000828
829 @staticmethod
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000830 def print_generic(default_fmt, specific_fmt,
831 title, url, author,
832 optional_values=None):
833 output_format = specific_fmt if specific_fmt is not None else default_fmt
834 output_format = unicode(output_format)
835 required_values = {
836 'title': title,
837 'url': url,
838 'author': author,
839 }
840 # Merge required and optional values.
841 if optional_values is not None:
842 values = dict(required_values.items() + optional_values.items())
843 else:
844 values = required_values
845 print output_format.format(**values)
846
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000847
848 def filter_issue(self, issue, should_filter_by_user=True):
849 def maybe_filter_username(email):
850 return not should_filter_by_user or username(email) == self.user
851 if (maybe_filter_username(issue['author']) and
852 self.filter_modified(issue['created'])):
853 return True
854 if (maybe_filter_username(issue['owner']) and
855 (self.filter_modified(issue['created']) or
856 self.filter_modified(issue['modified']))):
857 return True
858 for reply in issue['replies']:
859 if self.filter_modified(reply['created']):
860 if not should_filter_by_user:
861 break
862 if (username(reply['author']) == self.user
863 or (self.user + '@') in reply['content']):
864 break
865 else:
866 return False
867 return True
868
869 def filter_modified(self, modified):
870 return self.modified_after < modified and modified < self.modified_before
871
872 def auth_for_changes(self):
873 #TODO(cjhopman): Move authentication check for getting changes here.
874 pass
875
876 def auth_for_reviews(self):
877 # Reviews use all the same instances as changes so no authentication is
878 # required.
879 pass
880
881 def auth_for_issues(self):
882 self.google_code_auth_token = (
883 get_auth_token(self.options.local_user + '@chromium.org'))
884
885 def get_changes(self):
886 for instance in rietveld_instances:
887 self.changes += self.rietveld_search(instance, owner=self.user)
888
889 for instance in gerrit_instances:
890 self.changes += self.gerrit_search(instance, owner=self.user)
891
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000892 for instance in git_instances:
893 self.changes += self.git_search(instance, owner=self.user)
894
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000895 def print_changes(self):
896 if self.changes:
897 print '\nChanges:'
898 for change in self.changes:
899 self.print_change(change)
900
901 def get_reviews(self):
902 for instance in rietveld_instances:
903 self.reviews += self.rietveld_search(instance, reviewer=self.user)
904
905 for instance in gerrit_instances:
906 reviews = self.gerrit_search(instance, reviewer=self.user)
907 reviews = filter(lambda r: not username(r['owner']) == self.user, reviews)
908 self.reviews += reviews
909
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000910 for instance in git_instances:
911 self.reviews += self.git_search(instance, reviewer=self.user)
912
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000913 def print_reviews(self):
914 if self.reviews:
915 print '\nReviews:'
916 for review in self.reviews:
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000917 self.print_review(review)
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000918
919 def get_issues(self):
920 for project in google_code_projects:
921 self.issues += self.google_code_issue_search(project)
922
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000923 for instance in bugzilla_instances:
924 self.issues += self.bugzilla_issues(instance, self.user)
925
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000926 def print_issues(self):
927 if self.issues:
928 print '\nIssues:'
929 for issue in self.issues:
930 self.print_issue(issue)
931
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000932 def process_activities(self):
933 # If a webkit bug was a review, don't list it as an issue.
934 ids = {}
935 for review in self.reviews + self.changes:
936 if 'webkit_bug_id' in review:
937 ids[review['webkit_bug_id']] = True
938
939 def duplicate_issue(issue):
940 if 'webkit_bug_id' not in issue:
941 return False
942 return issue['webkit_bug_id'] in ids
943
944 self.issues = filter(lambda issue: not duplicate_issue(issue), self.issues)
945
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000946 def print_activity(self):
947 self.print_changes()
948 self.print_reviews()
949 self.print_issues()
950
951
952def main():
953 # Silence upload.py.
954 rietveld.upload.verbosity = 0
955
956 parser = optparse.OptionParser(description=sys.modules[__name__].__doc__)
957 parser.add_option(
958 '-u', '--user', metavar='<email>',
959 default=os.environ.get('USER'),
960 help='Filter on user, default=%default')
961 parser.add_option(
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000962 '--webkit_repo', metavar='<dir>',
963 default='%s' % os.environ.get('WEBKIT_DIR'),
964 help='Local path to WebKit repository, default=%default')
965 parser.add_option(
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000966 '-b', '--begin', metavar='<date>',
967 help='Filter issues created after the date')
968 parser.add_option(
969 '-e', '--end', metavar='<date>',
970 help='Filter issues created before the date')
971 quarter_begin, quarter_end = get_quarter_of(datetime.today() -
972 relativedelta(months=2))
973 parser.add_option(
974 '-Q', '--last_quarter', action='store_true',
975 help='Use last quarter\'s dates, e.g. %s to %s' % (
976 quarter_begin.strftime('%Y-%m-%d'), quarter_end.strftime('%Y-%m-%d')))
977 parser.add_option(
978 '-Y', '--this_year', action='store_true',
979 help='Use this year\'s dates')
980 parser.add_option(
981 '-w', '--week_of', metavar='<date>',
982 help='Show issues for week of the date')
983 parser.add_option(
984 '-a', '--auth',
985 action='store_true',
986 help='Ask to authenticate for instances with no auth cookie')
987
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000988 activity_types_group = optparse.OptionGroup(parser, 'Activity Types',
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000989 'By default, all activity will be looked up and '
990 'printed. If any of these are specified, only '
991 'those specified will be searched.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000992 activity_types_group.add_option(
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000993 '-c', '--changes',
994 action='store_true',
995 help='Show changes.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000996 activity_types_group.add_option(
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000997 '-i', '--issues',
998 action='store_true',
999 help='Show issues.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +00001000 activity_types_group.add_option(
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +00001001 '-r', '--reviews',
1002 action='store_true',
1003 help='Show reviews.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +00001004 parser.add_option_group(activity_types_group)
1005
1006 output_format_group = optparse.OptionGroup(parser, 'Output Format',
1007 'By default, all activity will be printed in the '
1008 'following format: {url} {title}. This can be '
1009 'changed for either all activity types or '
1010 'individually for each activity type. The format '
1011 'is defined as documented for '
1012 'string.format(...). The variables available for '
1013 'all activity types are url, title and author. '
1014 'Format options for specific activity types will '
1015 'override the generic format.')
1016 output_format_group.add_option(
1017 '-f', '--output-format', metavar='<format>',
1018 default=u'{url} {title}',
1019 help='Specifies the format to use when printing all your activity.')
1020 output_format_group.add_option(
1021 '--output-format-changes', metavar='<format>',
1022 default=None,
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +00001023 help='Specifies the format to use when printing changes. Supports the '
1024 'additional variable {reviewers}')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +00001025 output_format_group.add_option(
1026 '--output-format-issues', metavar='<format>',
1027 default=None,
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +00001028 help='Specifies the format to use when printing issues. Supports the '
1029 'additional variable {owner}.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +00001030 output_format_group.add_option(
1031 '--output-format-reviews', metavar='<format>',
1032 default=None,
1033 help='Specifies the format to use when printing reviews.')
1034 parser.add_option_group(output_format_group)
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +00001035
1036 # Remove description formatting
1037 parser.format_description = (
1038 lambda _: parser.description) # pylint: disable=E1101
1039
1040 options, args = parser.parse_args()
1041 options.local_user = os.environ.get('USER')
1042 if args:
1043 parser.error('Args unsupported')
1044 if not options.user:
1045 parser.error('USER is not set, please use -u')
1046
1047 options.user = username(options.user)
1048
1049 if not options.begin:
1050 if options.last_quarter:
1051 begin, end = quarter_begin, quarter_end
1052 elif options.this_year:
1053 begin, end = get_year_of(datetime.today())
1054 elif options.week_of:
1055 begin, end = (get_week_of(datetime.strptime(options.week_of, '%m/%d/%y')))
1056 else:
1057 begin, end = (get_week_of(datetime.today() - timedelta(days=1)))
1058 else:
1059 begin = datetime.strptime(options.begin, '%m/%d/%y')
1060 if options.end:
1061 end = datetime.strptime(options.end, '%m/%d/%y')
1062 else:
1063 end = datetime.today()
1064 options.begin, options.end = begin, end
1065
1066 print 'Searching for activity by %s' % options.user
1067 print 'Using range %s to %s' % (options.begin, options.end)
1068
1069 my_activity = MyActivity(options)
1070
1071 if not (options.changes or options.reviews or options.issues):
1072 options.changes = True
1073 options.issues = True
1074 options.reviews = True
1075
1076 # First do any required authentication so none of the user interaction has to
1077 # wait for actual work.
1078 if options.changes:
1079 my_activity.auth_for_changes()
1080 if options.reviews:
1081 my_activity.auth_for_reviews()
1082 if options.issues:
1083 my_activity.auth_for_issues()
1084
1085 print 'Looking up activity.....'
1086
1087 if options.changes:
1088 my_activity.get_changes()
1089 if options.reviews:
1090 my_activity.get_reviews()
1091 if options.issues:
1092 my_activity.get_issues()
1093
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +00001094 my_activity.process_activities()
1095
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +00001096 print '\n\n\n'
1097
1098 my_activity.print_changes()
1099 my_activity.print_reviews()
1100 my_activity.print_issues()
1101 return 0
1102
1103
1104if __name__ == '__main__':
1105 sys.exit(main())