blob: 16d3f7dba4770c620b381233818d5651d2bc88e8 [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
38import rietveld
39from third_party import upload
40
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +000041# Imported later, once options are set.
42webkitpy = None
43
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +000044try:
45 from dateutil.relativedelta import relativedelta # pylint: disable=F0401
46except ImportError:
47 print 'python-dateutil package required'
48 exit(1)
49
50# python-keyring provides easy access to the system keyring.
51try:
52 import keyring # pylint: disable=W0611,F0401
53except ImportError:
54 print 'Consider installing python-keyring'
55
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +000056def webkit_account(user):
57 if not webkitpy:
58 return None
59 committer_list = webkitpy.common.config.committers.CommitterList()
60 email = user + "@chromium.org"
61 return committer_list.account_by_email(email)
62
63def user_to_webkit_email(user):
64 account = webkit_account(user)
65 if not account:
66 return None
67 return account.emails[0]
68
69def user_to_webkit_owner_search(user):
70 account = webkit_account(user)
71 if not account:
72 return ['--author=%s@chromium.org' % user]
73 search = []
74 for email in account.emails:
75 search.append('--author=' + email)
76 # commit-bot is author for contributors who are not committers.
77 search.append('--grep=Patch by ' + account.full_name)
78 return search
79
80def user_to_webkit_reviewer_search(user):
81 committer_list = webkitpy.common.config.committers.CommitterList()
82 email = user + "@chromium.org"
83 account = committer_list.reviewer_by_email(email)
84 if not account:
85 return []
86 return ['--grep=Reviewed by ' + account.full_name]
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +000087
88rietveld_instances = [
89 {
90 'url': 'codereview.chromium.org',
91 'shorturl': 'crrev.com',
92 'supports_owner_modified_query': True,
93 'requires_auth': False,
94 'email_domain': 'chromium.org',
95 },
96 {
97 'url': 'chromereviews.googleplex.com',
98 'shorturl': 'go/chromerev',
99 'supports_owner_modified_query': True,
100 'requires_auth': True,
101 'email_domain': 'google.com',
102 },
103 {
104 'url': 'codereview.appspot.com',
105 'supports_owner_modified_query': True,
106 'requires_auth': False,
107 'email_domain': 'chromium.org',
108 },
109 {
110 'url': 'breakpad.appspot.com',
111 'supports_owner_modified_query': False,
112 'requires_auth': False,
113 'email_domain': 'chromium.org',
114 },
115]
116
117gerrit_instances = [
118 {
119 'url': 'gerrit.chromium.org',
120 'port': 29418,
deymo@chromium.orge52bd5a2013-08-29 18:05:21 +0000121 'shorturl': 'crosreview.com',
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000122 },
123 {
124 'url': 'gerrit-int.chromium.org',
125 'port': 29419,
deymo@chromium.orge52bd5a2013-08-29 18:05:21 +0000126 'shorturl': 'crosreview.com/i',
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000127 },
128]
129
130google_code_projects = [
131 {
132 'name': 'chromium',
133 'shorturl': 'crbug.com',
134 },
135 {
136 'name': 'chromium-os',
deymo@chromium.orgc840e212013-02-13 20:40:22 +0000137 'shorturl': 'crosbug.com',
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000138 },
139 {
140 'name': 'chrome-os-partner',
141 },
142 {
143 'name': 'google-breakpad',
144 },
145 {
146 'name': 'gyp',
enne@chromium.orgf01fad32012-11-26 18:09:38 +0000147 },
148 {
149 'name': 'skia',
150 },
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000151]
152
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000153bugzilla_instances = [
154 {
155 'search_url': 'http://bugs.webkit.org/buglist.cgi',
156 'url': 'wkb.ug',
157 'user_func': user_to_webkit_email,
158 },
159]
160
161git_instances = [
162 {
163 'option': 'webkit_repo',
164 'change_re':
165 r'git-svn-id: http://svn\.webkit\.org/repository/webkit/trunk@(\d*)',
166 'change_url': 'trac.webkit.org/changeset',
167 'review_re': r'https://bugs\.webkit\.org/show_bug\.cgi\?id\=(\d*)',
168 'review_url': 'wkb.ug',
169 'review_prop': 'webkit_bug_id',
170
171 'owner_search_func': user_to_webkit_owner_search,
172 'reviewer_search_func': user_to_webkit_reviewer_search,
173 },
174]
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000175
176# Uses ClientLogin to authenticate the user for Google Code issue trackers.
177def get_auth_token(email):
cjhopman@chromium.org3365f2d2012-11-01 18:53:13 +0000178 # KeyringCreds will use the system keyring on the first try, and prompt for
179 # a password on the next ones.
180 creds = upload.KeyringCreds('code.google.com', 'code.google.com', email)
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000181 for _ in xrange(3):
cjhopman@chromium.org3365f2d2012-11-01 18:53:13 +0000182 email, password = creds.GetUserCredentials()
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000183 url = 'https://www.google.com/accounts/ClientLogin'
184 data = urllib.urlencode({
185 'Email': email,
186 'Passwd': password,
187 'service': 'code',
188 'source': 'chrome-my-activity',
189 'accountType': 'GOOGLE',
190 })
191 req = urllib2.Request(url, data=data, headers={'Accept': 'text/plain'})
192 try:
193 response = urllib2.urlopen(req)
194 response_body = response.read()
195 response_dict = dict(x.split('=')
196 for x in response_body.split('\n') if x)
197 return response_dict['Auth']
198 except urllib2.HTTPError, e:
cjhopman@chromium.org3365f2d2012-11-01 18:53:13 +0000199 print e
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000200
cjhopman@chromium.org3365f2d2012-11-01 18:53:13 +0000201 print 'Unable to authenticate to code.google.com.'
202 print 'Some issues may be missing.'
203 return None
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000204
205
206def username(email):
207 """Keeps the username of an email address."""
208 return email and email.split('@', 1)[0]
209
210
cjhopman@chromium.org426557a2012-10-22 20:18:52 +0000211def datetime_to_midnight(date):
212 return date - timedelta(hours=date.hour, minutes=date.minute,
213 seconds=date.second, microseconds=date.microsecond)
214
215
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000216def get_quarter_of(date):
cjhopman@chromium.org426557a2012-10-22 20:18:52 +0000217 begin = (datetime_to_midnight(date) -
218 relativedelta(months=(date.month % 3) - 1, days=(date.day - 1)))
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000219 return begin, begin + relativedelta(months=3)
220
221
222def get_year_of(date):
cjhopman@chromium.org426557a2012-10-22 20:18:52 +0000223 begin = (datetime_to_midnight(date) -
224 relativedelta(months=(date.month - 1), days=(date.day - 1)))
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000225 return begin, begin + relativedelta(years=1)
226
227
228def get_week_of(date):
cjhopman@chromium.org426557a2012-10-22 20:18:52 +0000229 begin = (datetime_to_midnight(date) - timedelta(days=date.weekday()))
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000230 return begin, begin + timedelta(days=7)
231
232
233def get_yes_or_no(msg):
234 while True:
235 response = raw_input(msg + ' yes/no [no] ')
236 if response == 'y' or response == 'yes':
237 return True
238 elif not response or response == 'n' or response == 'no':
239 return False
240
241
242def datetime_from_rietveld(date_string):
243 return datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
244
245
246def datetime_from_google_code(date_string):
247 return datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%fZ')
248
249
250class MyActivity(object):
251 def __init__(self, options):
252 self.options = options
253 self.modified_after = options.begin
254 self.modified_before = options.end
255 self.user = options.user
256 self.changes = []
257 self.reviews = []
258 self.issues = []
259 self.check_cookies()
260 self.google_code_auth_token = None
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000261 self.webkit_repo = options.webkit_repo
262 if self.webkit_repo:
263 self.setup_webkit_info()
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000264
265 # Check the codereview cookie jar to determine which Rietveld instances to
266 # authenticate to.
267 def check_cookies(self):
268 cookie_file = os.path.expanduser('~/.codereview_upload_cookies')
269 cookie_jar = cookielib.MozillaCookieJar(cookie_file)
270 if not os.path.exists(cookie_file):
271 exit(1)
272
273 try:
274 cookie_jar.load()
275 print 'Found cookie file: %s' % cookie_file
276 except (cookielib.LoadError, IOError):
277 exit(1)
278
279 filtered_instances = []
280
281 def has_cookie(instance):
282 for cookie in cookie_jar:
283 if cookie.name == 'SACSID' and cookie.domain == instance['url']:
284 return True
285 if self.options.auth:
286 return get_yes_or_no('No cookie found for %s. Authorize for this '
287 'instance? (may require application-specific '
288 'password)' % instance['url'])
289 filtered_instances.append(instance)
290 return False
291
292 for instance in rietveld_instances:
293 instance['auth'] = has_cookie(instance)
294
295 if filtered_instances:
296 print ('No cookie found for the following Rietveld instance%s:' %
297 ('s' if len(filtered_instances) > 1 else ''))
298 for instance in filtered_instances:
299 print '\t' + instance['url']
300 print 'Use --auth if you would like to authenticate to them.\n'
301
302 def rietveld_search(self, instance, owner=None, reviewer=None):
303 if instance['requires_auth'] and not instance['auth']:
304 return []
305
306
307 email = None if instance['auth'] else ''
308 remote = rietveld.Rietveld('https://' + instance['url'], email, None)
309
310 # See def search() in rietveld.py to see all the filters you can use.
311 query_modified_after = None
312
313 if instance['supports_owner_modified_query']:
314 query_modified_after = self.modified_after.strftime('%Y-%m-%d')
315
316 # Rietveld does not allow search by both created_before and modified_after.
317 # (And some instances don't allow search by both owner and modified_after)
318 owner_email = None
319 reviewer_email = None
320 if owner:
321 owner_email = owner + '@' + instance['email_domain']
322 if reviewer:
323 reviewer_email = reviewer + '@' + instance['email_domain']
324 issues = remote.search(
325 owner=owner_email,
326 reviewer=reviewer_email,
327 modified_after=query_modified_after,
328 with_messages=True)
329
330 issues = filter(
331 lambda i: (datetime_from_rietveld(i['created']) < self.modified_before),
332 issues)
333 issues = filter(
334 lambda i: (datetime_from_rietveld(i['modified']) > self.modified_after),
335 issues)
336
337 should_filter_by_user = True
338 issues = map(partial(self.process_rietveld_issue, instance), issues)
339 issues = filter(
340 partial(self.filter_issue, should_filter_by_user=should_filter_by_user),
341 issues)
342 issues = sorted(issues, key=lambda i: i['modified'], reverse=True)
343
344 return issues
345
346 def process_rietveld_issue(self, instance, issue):
347 ret = {}
348 ret['owner'] = issue['owner_email']
349 ret['author'] = ret['owner']
350
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000351 ret['reviewers'] = set(issue['reviewers'])
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000352
353 shorturl = instance['url']
354 if 'shorturl' in instance:
355 shorturl = instance['shorturl']
356
357 ret['review_url'] = 'http://%s/%d' % (shorturl, issue['issue'])
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000358
359 # Rietveld sometimes has '\r\n' instead of '\n'.
360 ret['header'] = issue['description'].replace('\r', '').split('\n')[0]
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000361
362 ret['modified'] = datetime_from_rietveld(issue['modified'])
363 ret['created'] = datetime_from_rietveld(issue['created'])
364 ret['replies'] = self.process_rietveld_replies(issue['messages'])
365
366 return ret
367
368 @staticmethod
369 def process_rietveld_replies(replies):
370 ret = []
371 for reply in replies:
372 r = {}
373 r['author'] = reply['sender']
374 r['created'] = datetime_from_rietveld(reply['date'])
375 r['content'] = ''
376 ret.append(r)
377 return ret
378
379 def gerrit_search(self, instance, owner=None, reviewer=None):
380 max_age = datetime.today() - self.modified_after
381 max_age = max_age.days * 24 * 3600 + max_age.seconds
382
383 # See https://review.openstack.org/Documentation/cmd-query.html
384 # Gerrit doesn't allow filtering by created time, only modified time.
385 user_filter = 'owner:%s' % owner if owner else 'reviewer:%s' % reviewer
386 gquery_cmd = ['ssh', '-p', str(instance['port']), instance['url'],
387 'gerrit', 'query',
388 '--format', 'JSON',
389 '--comments',
390 '--',
391 '-age:%ss' % str(max_age),
392 user_filter]
393 [stdout, _] = subprocess.Popen(gquery_cmd, stdout=subprocess.PIPE,
394 stderr=subprocess.PIPE).communicate()
395 issues = str(stdout).split('\n')[:-2]
396 issues = map(json.loads, issues)
397
398 # TODO(cjhopman): should we filter abandoned changes?
deymo@chromium.orge52bd5a2013-08-29 18:05:21 +0000399 issues = [self.process_gerrit_issue(instance, issue) for issue in issues]
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000400 issues = filter(self.filter_issue, issues)
401 issues = sorted(issues, key=lambda i: i['modified'], reverse=True)
402
403 return issues
404
deymo@chromium.orge52bd5a2013-08-29 18:05:21 +0000405 def process_gerrit_issue(self, instance, issue):
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000406 ret = {}
407 ret['review_url'] = issue['url']
deymo@chromium.orge52bd5a2013-08-29 18:05:21 +0000408 if 'shorturl' in instance:
409 ret['review_url'] = 'http://%s/%s' % (instance['shorturl'],
410 issue['number'])
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000411 ret['header'] = issue['subject']
412 ret['owner'] = issue['owner']['email']
413 ret['author'] = ret['owner']
414 ret['created'] = datetime.fromtimestamp(issue['createdOn'])
415 ret['modified'] = datetime.fromtimestamp(issue['lastUpdated'])
416 if 'comments' in issue:
417 ret['replies'] = self.process_gerrit_issue_replies(issue['comments'])
418 else:
419 ret['replies'] = []
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000420 ret['reviewers'] = set()
421 for reply in ret['replies']:
422 if reply['author'] != ret['author']:
423 ret['reviewers'].add(reply['author'])
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000424 return ret
425
426 @staticmethod
427 def process_gerrit_issue_replies(replies):
428 ret = []
429 replies = filter(lambda r: 'email' in r['reviewer'], replies)
430 for reply in replies:
431 r = {}
432 r['author'] = reply['reviewer']['email']
433 r['created'] = datetime.fromtimestamp(reply['timestamp'])
434 r['content'] = ''
435 ret.append(r)
436 return ret
437
438 def google_code_issue_search(self, instance):
439 time_format = '%Y-%m-%dT%T'
440 # See http://code.google.com/p/support/wiki/IssueTrackerAPI
441 # q=<owner>@chromium.org does a full text search for <owner>@chromium.org.
442 # This will accept the issue if owner is the owner or in the cc list. Might
443 # have some false positives, though.
444
445 # Don't filter normally on modified_before because it can filter out things
446 # that were modified in the time period and then modified again after it.
447 gcode_url = ('https://code.google.com/feeds/issues/p/%s/issues/full' %
448 instance['name'])
449
450 gcode_data = urllib.urlencode({
451 'alt': 'json',
452 'max-results': '100000',
453 'q': '%s' % self.user,
454 'published-max': self.modified_before.strftime(time_format),
455 'updated-min': self.modified_after.strftime(time_format),
456 })
457
458 opener = urllib2.build_opener()
cjhopman@chromium.org3365f2d2012-11-01 18:53:13 +0000459 if self.google_code_auth_token:
460 opener.addheaders = [('Authorization', 'GoogleLogin auth=%s' %
461 self.google_code_auth_token)]
462 gcode_json = None
463 try:
464 gcode_get = opener.open(gcode_url + '?' + gcode_data)
465 gcode_json = json.load(gcode_get)
466 gcode_get.close()
467 except urllib2.HTTPError, _:
468 print 'Unable to access ' + instance['name'] + ' issue tracker.'
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000469
cjhopman@chromium.org3365f2d2012-11-01 18:53:13 +0000470 if not gcode_json or 'entry' not in gcode_json['feed']:
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000471 return []
472
473 issues = gcode_json['feed']['entry']
474 issues = map(partial(self.process_google_code_issue, instance), issues)
475 issues = filter(self.filter_issue, issues)
476 issues = sorted(issues, key=lambda i: i['modified'], reverse=True)
477 return issues
478
479 def process_google_code_issue(self, project, issue):
480 ret = {}
481 ret['created'] = datetime_from_google_code(issue['published']['$t'])
482 ret['modified'] = datetime_from_google_code(issue['updated']['$t'])
483
484 ret['owner'] = ''
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000485 if 'issues$owner' in issue:
486 ret['owner'] = issue['issues$owner']['issues$username']['$t']
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000487 ret['author'] = issue['author'][0]['name']['$t']
488
489 if 'shorturl' in project:
490 issue_id = issue['id']['$t']
491 issue_id = issue_id[issue_id.rfind('/') + 1:]
492 ret['url'] = 'http://%s/%d' % (project['shorturl'], int(issue_id))
493 else:
494 issue_url = issue['link'][1]
495 if issue_url['rel'] != 'alternate':
496 raise RuntimeError
497 ret['url'] = issue_url['href']
498 ret['header'] = issue['title']['$t']
499
500 ret['replies'] = self.get_google_code_issue_replies(issue)
501 return ret
502
503 def get_google_code_issue_replies(self, issue):
504 """Get all the comments on the issue."""
505 replies_url = issue['link'][0]
506 if replies_url['rel'] != 'replies':
507 raise RuntimeError
508
509 replies_data = urllib.urlencode({
510 'alt': 'json',
511 'fields': 'entry(published,author,content)',
512 })
513
514 opener = urllib2.build_opener()
515 opener.addheaders = [('Authorization', 'GoogleLogin auth=%s' %
516 self.google_code_auth_token)]
517 try:
518 replies_get = opener.open(replies_url['href'] + '?' + replies_data)
519 except urllib2.HTTPError, _:
520 return []
521
522 replies_json = json.load(replies_get)
523 replies_get.close()
524 return self.process_google_code_issue_replies(replies_json)
525
526 @staticmethod
527 def process_google_code_issue_replies(replies):
528 if 'entry' not in replies['feed']:
529 return []
530
531 ret = []
532 for entry in replies['feed']['entry']:
533 e = {}
534 e['created'] = datetime_from_google_code(entry['published']['$t'])
535 e['content'] = entry['content']['$t']
536 e['author'] = entry['author'][0]['name']['$t']
537 ret.append(e)
538 return ret
539
540 @staticmethod
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000541 def git_cmd(repo, *args):
542 cmd = ['git', '--git-dir=%s/.git' % repo]
543 cmd.extend(args)
544 [stdout, _] = subprocess.Popen(cmd, stdout=subprocess.PIPE,
545 stderr=subprocess.PIPE).communicate()
546 lines = str(stdout).split('\n')[:-1]
547 return lines
548
549 def git_search(self, instance, owner=None, reviewer=None):
550 repo = getattr(self, instance['option'])
551 if not repo:
552 return []
553
554 search = []
555 if owner:
556 search.extend(instance['owner_search_func'](owner))
557 if reviewer:
558 search.extend(instance['reviewer_search_func'](reviewer))
559 if not len(search):
560 return []
561
562 self.git_cmd(repo, 'fetch', 'origin')
563
564 time_format = '%Y-%m-%d %H:%M:%S'
565 log_args = [
566 '--after=' + self.modified_after.strftime(time_format),
567 '--before=' + self.modified_before.strftime(time_format),
568 '--format=%H'
569 ]
570 commits = set()
571 for query in search:
572 query_args = [query]
573 query_args.extend(log_args)
574 commits |= set(self.git_cmd(repo, 'log', 'origin/master', *query_args))
575
576 ret = []
577 for commit in commits:
578 output = self.git_cmd(repo, 'log', commit + "^!", "--format=%cn%n%cd%n%B")
579 author = output[0]
580 date = datetime.strptime(output[1], "%a %b %d %H:%M:%S %Y +0000")
enne@chromium.orgd69dab92013-06-10 20:19:56 +0000581 processed = self.process_git_commit(instance, author, date, output[2:])
582 if processed:
583 ret.append(processed)
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000584
585 ret = sorted(ret, key=lambda i: i['modified'], reverse=True)
586 return ret
587
588 @staticmethod
589 def process_git_commit(instance, author, date, log):
590 ret = {}
591 ret['owner'] = author
592 ret['author'] = author
593 ret['modified'] = date
594 ret['created'] = date
595 ret['header'] = log[0]
596
597 reviews = []
598 reviewers = []
599 changes = []
600
601 for line in log:
602 match = re.match(r'Reviewed by ([^.]*)', line)
603 if match:
604 reviewers.append(match.group(1))
605 if instance['review_re']:
606 match = re.match(instance['review_re'], line)
607 if match:
608 reviews.append(int(match.group(1)))
609 if instance['change_re']:
610 match = re.match(instance['change_re'], line)
611 if match:
612 changes.append(int(match.group(1)))
613
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000614 committer_list = webkitpy.common.config.committers.CommitterList()
615 ret['reviewers'] = set(
616 (committer_list.contributor_by_name(r).emails[0] for r in reviewers))
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000617
618 # Reviews more useful than change link itself, but tricky if multiple
619 # Reviews == bugs for WebKit changes
620 if len(reviews) == 1:
621 url = 'http://%s/%d' % (instance['review_url'], reviews[0])
622 if instance['review_prop']:
623 ret[instance['review_prop']] = reviews[0]
enne@chromium.orgd69dab92013-06-10 20:19:56 +0000624 elif len(changes) == 1:
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000625 url = 'http://%s/%d' % (instance['change_url'], changes[0])
enne@chromium.orgd69dab92013-06-10 20:19:56 +0000626 else:
627 # Couldn't find anything.
628 return None
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000629 ret['review_url'] = url
630
631 return ret
632
633 def bugzilla_issues(self, instance, user):
634 if instance['user_func']:
635 user = instance['user_func'](user)
636 if not user:
637 return []
638
639 # This search is a little iffy, as it returns any bug that has been
640 # modified over a time period in any way and that a user has ever commented
641 # on, but that's the best that Bugzilla can get us. Oops.
642 commented = { 'emaillongdesc1': 1 }
643 issues = self.bugzilla_search(instance, user, commented)
644 issues = filter(lambda issue: issue['owner'] != user, issues)
645
646 reported = { 'emailreporter1': 1, 'chfield': '[Bug creation]' }
647 issues.extend(self.bugzilla_search(instance, user, reported))
648
649 # Remove duplicates by bug id
650 seen = {}
651 pruned = []
652 for issue in issues:
653 bug_id = issue['webkit_bug_id']
654 if bug_id in seen:
655 continue
656 seen[bug_id] = True
657 pruned.append(issue)
658
659 # Bugzilla has no modified time, so sort by id?
660 pruned = sorted(pruned, key=lambda i: i['webkit_bug_id'])
661 return issues
662
663 def bugzilla_search(self, instance, user, params):
664 time_format = '%Y-%m-%d'
665 values = {
666 'chfieldfrom': self.modified_after.strftime(time_format),
667 'chfieldto': self.modified_before.strftime(time_format),
668 'ctype': 'csv',
669 'emailtype1': 'substring',
670 'email1': '%s' % user,
671 }
672 values.update(params)
673
674 # Must be GET not POST
675 data = urllib.urlencode(values)
676 req = urllib2.Request("%s?%s" % (instance['search_url'], data))
677 response = urllib2.urlopen(req)
678 reader = csv.reader(response)
679 reader.next() # skip the header line
680
681 issues = map(partial(self.process_bugzilla_issue, instance), reader)
682 return issues
683
684 @staticmethod
685 def process_bugzilla_issue(instance, issue):
686 bug_id, owner, desc = int(issue[0]), issue[4], issue[7]
687
688 ret = {}
689 ret['owner'] = owner
690 ret['author'] = owner
691 ret['review_url'] = 'http://%s/%d' % (instance['url'], bug_id)
692 ret['url'] = ret['review_url']
693 ret['header'] = desc
694 ret['webkit_bug_id'] = bug_id
695 return ret
696
697 def setup_webkit_info(self):
698 assert(self.webkit_repo)
699 git_dir = os.path.normpath(self.webkit_repo + "/.git")
700 if not os.path.exists(git_dir):
scheib@chromium.orgb299e7c2012-11-13 21:34:34 +0000701 print "%s doesn't exist, skipping WebKit checks." % git_dir
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000702 self.webkit_repo = None
703 return
704
705 try:
706 self.git_cmd(self.webkit_repo, "fetch", "origin")
707 except subprocess.CalledProcessError:
scheib@chromium.orgb299e7c2012-11-13 21:34:34 +0000708 print "Failed to update WebKit repo, skipping WebKit checks."
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000709 self.webkit_repo = None
710 return
711
712 path = "Tools/Scripts"
713 full_path = os.path.normpath("%s/%s" % (self.options.webkit_repo, path))
714 sys.path.append(full_path)
715
716 try:
717 global webkitpy
718 webkitpy = __import__('webkitpy.common.config.committers')
719 except ImportError:
scheib@chromium.orgb299e7c2012-11-13 21:34:34 +0000720 print "Failed to import WebKit committer list, skipping WebKit checks."
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000721 self.webkit_repo = None
722 return
723
724 if not webkit_account(self.user):
725 email = self.user + "@chromium.org"
scheib@chromium.orgb299e7c2012-11-13 21:34:34 +0000726 print "No %s in committers.py, skipping WebKit checks." % email
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000727 self.webkit_repo = None
728
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000729 def print_change(self, change):
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000730 optional_values = {
731 'reviewers': ', '.join(change['reviewers'])
732 }
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000733 self.print_generic(self.options.output_format,
734 self.options.output_format_changes,
735 change['header'],
736 change['review_url'],
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000737 change['author'],
738 optional_values)
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000739
740 def print_issue(self, issue):
741 optional_values = {
742 'owner': issue['owner'],
743 }
744 self.print_generic(self.options.output_format,
745 self.options.output_format_issues,
746 issue['header'],
747 issue['url'],
748 issue['author'],
749 optional_values)
750
751 def print_review(self, review):
752 self.print_generic(self.options.output_format,
753 self.options.output_format_reviews,
754 review['header'],
755 review['review_url'],
756 review['author'])
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000757
758 @staticmethod
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000759 def print_generic(default_fmt, specific_fmt,
760 title, url, author,
761 optional_values=None):
762 output_format = specific_fmt if specific_fmt is not None else default_fmt
763 output_format = unicode(output_format)
764 required_values = {
765 'title': title,
766 'url': url,
767 'author': author,
768 }
769 # Merge required and optional values.
770 if optional_values is not None:
771 values = dict(required_values.items() + optional_values.items())
772 else:
773 values = required_values
774 print output_format.format(**values)
775
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000776
777 def filter_issue(self, issue, should_filter_by_user=True):
778 def maybe_filter_username(email):
779 return not should_filter_by_user or username(email) == self.user
780 if (maybe_filter_username(issue['author']) and
781 self.filter_modified(issue['created'])):
782 return True
783 if (maybe_filter_username(issue['owner']) and
784 (self.filter_modified(issue['created']) or
785 self.filter_modified(issue['modified']))):
786 return True
787 for reply in issue['replies']:
788 if self.filter_modified(reply['created']):
789 if not should_filter_by_user:
790 break
791 if (username(reply['author']) == self.user
792 or (self.user + '@') in reply['content']):
793 break
794 else:
795 return False
796 return True
797
798 def filter_modified(self, modified):
799 return self.modified_after < modified and modified < self.modified_before
800
801 def auth_for_changes(self):
802 #TODO(cjhopman): Move authentication check for getting changes here.
803 pass
804
805 def auth_for_reviews(self):
806 # Reviews use all the same instances as changes so no authentication is
807 # required.
808 pass
809
810 def auth_for_issues(self):
811 self.google_code_auth_token = (
812 get_auth_token(self.options.local_user + '@chromium.org'))
813
814 def get_changes(self):
815 for instance in rietveld_instances:
816 self.changes += self.rietveld_search(instance, owner=self.user)
817
818 for instance in gerrit_instances:
819 self.changes += self.gerrit_search(instance, owner=self.user)
820
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000821 for instance in git_instances:
822 self.changes += self.git_search(instance, owner=self.user)
823
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000824 def print_changes(self):
825 if self.changes:
826 print '\nChanges:'
827 for change in self.changes:
828 self.print_change(change)
829
830 def get_reviews(self):
831 for instance in rietveld_instances:
832 self.reviews += self.rietveld_search(instance, reviewer=self.user)
833
834 for instance in gerrit_instances:
835 reviews = self.gerrit_search(instance, reviewer=self.user)
836 reviews = filter(lambda r: not username(r['owner']) == self.user, reviews)
837 self.reviews += reviews
838
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000839 for instance in git_instances:
840 self.reviews += self.git_search(instance, reviewer=self.user)
841
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000842 def print_reviews(self):
843 if self.reviews:
844 print '\nReviews:'
845 for review in self.reviews:
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000846 self.print_review(review)
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000847
848 def get_issues(self):
849 for project in google_code_projects:
850 self.issues += self.google_code_issue_search(project)
851
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000852 for instance in bugzilla_instances:
853 self.issues += self.bugzilla_issues(instance, self.user)
854
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000855 def print_issues(self):
856 if self.issues:
857 print '\nIssues:'
858 for issue in self.issues:
859 self.print_issue(issue)
860
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000861 def process_activities(self):
862 # If a webkit bug was a review, don't list it as an issue.
863 ids = {}
864 for review in self.reviews + self.changes:
865 if 'webkit_bug_id' in review:
866 ids[review['webkit_bug_id']] = True
867
868 def duplicate_issue(issue):
869 if 'webkit_bug_id' not in issue:
870 return False
871 return issue['webkit_bug_id'] in ids
872
873 self.issues = filter(lambda issue: not duplicate_issue(issue), self.issues)
874
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000875 def print_activity(self):
876 self.print_changes()
877 self.print_reviews()
878 self.print_issues()
879
880
881def main():
882 # Silence upload.py.
883 rietveld.upload.verbosity = 0
884
885 parser = optparse.OptionParser(description=sys.modules[__name__].__doc__)
886 parser.add_option(
887 '-u', '--user', metavar='<email>',
888 default=os.environ.get('USER'),
889 help='Filter on user, default=%default')
890 parser.add_option(
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000891 '--webkit_repo', metavar='<dir>',
892 default='%s' % os.environ.get('WEBKIT_DIR'),
893 help='Local path to WebKit repository, default=%default')
894 parser.add_option(
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000895 '-b', '--begin', metavar='<date>',
896 help='Filter issues created after the date')
897 parser.add_option(
898 '-e', '--end', metavar='<date>',
899 help='Filter issues created before the date')
900 quarter_begin, quarter_end = get_quarter_of(datetime.today() -
901 relativedelta(months=2))
902 parser.add_option(
903 '-Q', '--last_quarter', action='store_true',
904 help='Use last quarter\'s dates, e.g. %s to %s' % (
905 quarter_begin.strftime('%Y-%m-%d'), quarter_end.strftime('%Y-%m-%d')))
906 parser.add_option(
907 '-Y', '--this_year', action='store_true',
908 help='Use this year\'s dates')
909 parser.add_option(
910 '-w', '--week_of', metavar='<date>',
911 help='Show issues for week of the date')
912 parser.add_option(
913 '-a', '--auth',
914 action='store_true',
915 help='Ask to authenticate for instances with no auth cookie')
916
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000917 activity_types_group = optparse.OptionGroup(parser, 'Activity Types',
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000918 'By default, all activity will be looked up and '
919 'printed. If any of these are specified, only '
920 'those specified will be searched.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000921 activity_types_group.add_option(
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000922 '-c', '--changes',
923 action='store_true',
924 help='Show changes.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000925 activity_types_group.add_option(
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000926 '-i', '--issues',
927 action='store_true',
928 help='Show issues.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000929 activity_types_group.add_option(
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000930 '-r', '--reviews',
931 action='store_true',
932 help='Show reviews.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000933 parser.add_option_group(activity_types_group)
934
935 output_format_group = optparse.OptionGroup(parser, 'Output Format',
936 'By default, all activity will be printed in the '
937 'following format: {url} {title}. This can be '
938 'changed for either all activity types or '
939 'individually for each activity type. The format '
940 'is defined as documented for '
941 'string.format(...). The variables available for '
942 'all activity types are url, title and author. '
943 'Format options for specific activity types will '
944 'override the generic format.')
945 output_format_group.add_option(
946 '-f', '--output-format', metavar='<format>',
947 default=u'{url} {title}',
948 help='Specifies the format to use when printing all your activity.')
949 output_format_group.add_option(
950 '--output-format-changes', metavar='<format>',
951 default=None,
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000952 help='Specifies the format to use when printing changes. Supports the '
953 'additional variable {reviewers}')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000954 output_format_group.add_option(
955 '--output-format-issues', metavar='<format>',
956 default=None,
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000957 help='Specifies the format to use when printing issues. Supports the '
958 'additional variable {owner}.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000959 output_format_group.add_option(
960 '--output-format-reviews', metavar='<format>',
961 default=None,
962 help='Specifies the format to use when printing reviews.')
963 parser.add_option_group(output_format_group)
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000964
965 # Remove description formatting
966 parser.format_description = (
967 lambda _: parser.description) # pylint: disable=E1101
968
969 options, args = parser.parse_args()
970 options.local_user = os.environ.get('USER')
971 if args:
972 parser.error('Args unsupported')
973 if not options.user:
974 parser.error('USER is not set, please use -u')
975
976 options.user = username(options.user)
977
978 if not options.begin:
979 if options.last_quarter:
980 begin, end = quarter_begin, quarter_end
981 elif options.this_year:
982 begin, end = get_year_of(datetime.today())
983 elif options.week_of:
984 begin, end = (get_week_of(datetime.strptime(options.week_of, '%m/%d/%y')))
985 else:
986 begin, end = (get_week_of(datetime.today() - timedelta(days=1)))
987 else:
988 begin = datetime.strptime(options.begin, '%m/%d/%y')
989 if options.end:
990 end = datetime.strptime(options.end, '%m/%d/%y')
991 else:
992 end = datetime.today()
993 options.begin, options.end = begin, end
994
995 print 'Searching for activity by %s' % options.user
996 print 'Using range %s to %s' % (options.begin, options.end)
997
998 my_activity = MyActivity(options)
999
1000 if not (options.changes or options.reviews or options.issues):
1001 options.changes = True
1002 options.issues = True
1003 options.reviews = True
1004
1005 # First do any required authentication so none of the user interaction has to
1006 # wait for actual work.
1007 if options.changes:
1008 my_activity.auth_for_changes()
1009 if options.reviews:
1010 my_activity.auth_for_reviews()
1011 if options.issues:
1012 my_activity.auth_for_issues()
1013
1014 print 'Looking up activity.....'
1015
1016 if options.changes:
1017 my_activity.get_changes()
1018 if options.reviews:
1019 my_activity.get_reviews()
1020 if options.issues:
1021 my_activity.get_issues()
1022
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +00001023 my_activity.process_activities()
1024
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +00001025 print '\n\n\n'
1026
1027 my_activity.print_changes()
1028 my_activity.print_reviews()
1029 my_activity.print_issues()
1030 return 0
1031
1032
1033if __name__ == '__main__':
1034 sys.exit(main())