blob: 4883cdf286517af40ddcccce94c5c2ff007400f8 [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,
121 },
122 {
123 'url': 'gerrit-int.chromium.org',
124 'port': 29419,
125 },
126]
127
128google_code_projects = [
129 {
130 'name': 'chromium',
131 'shorturl': 'crbug.com',
132 },
133 {
134 'name': 'chromium-os',
deymo@chromium.orgc840e212013-02-13 20:40:22 +0000135 'shorturl': 'crosbug.com',
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000136 },
137 {
138 'name': 'chrome-os-partner',
139 },
140 {
141 'name': 'google-breakpad',
142 },
143 {
144 'name': 'gyp',
enne@chromium.orgf01fad32012-11-26 18:09:38 +0000145 },
146 {
147 'name': 'skia',
148 },
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000149]
150
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000151bugzilla_instances = [
152 {
153 'search_url': 'http://bugs.webkit.org/buglist.cgi',
154 'url': 'wkb.ug',
155 'user_func': user_to_webkit_email,
156 },
157]
158
159git_instances = [
160 {
161 'option': 'webkit_repo',
162 'change_re':
163 r'git-svn-id: http://svn\.webkit\.org/repository/webkit/trunk@(\d*)',
164 'change_url': 'trac.webkit.org/changeset',
165 'review_re': r'https://bugs\.webkit\.org/show_bug\.cgi\?id\=(\d*)',
166 'review_url': 'wkb.ug',
167 'review_prop': 'webkit_bug_id',
168
169 'owner_search_func': user_to_webkit_owner_search,
170 'reviewer_search_func': user_to_webkit_reviewer_search,
171 },
172]
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000173
174# Uses ClientLogin to authenticate the user for Google Code issue trackers.
175def get_auth_token(email):
cjhopman@chromium.org3365f2d2012-11-01 18:53:13 +0000176 # KeyringCreds will use the system keyring on the first try, and prompt for
177 # a password on the next ones.
178 creds = upload.KeyringCreds('code.google.com', 'code.google.com', email)
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000179 for _ in xrange(3):
cjhopman@chromium.org3365f2d2012-11-01 18:53:13 +0000180 email, password = creds.GetUserCredentials()
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000181 url = 'https://www.google.com/accounts/ClientLogin'
182 data = urllib.urlencode({
183 'Email': email,
184 'Passwd': password,
185 'service': 'code',
186 'source': 'chrome-my-activity',
187 'accountType': 'GOOGLE',
188 })
189 req = urllib2.Request(url, data=data, headers={'Accept': 'text/plain'})
190 try:
191 response = urllib2.urlopen(req)
192 response_body = response.read()
193 response_dict = dict(x.split('=')
194 for x in response_body.split('\n') if x)
195 return response_dict['Auth']
196 except urllib2.HTTPError, e:
cjhopman@chromium.org3365f2d2012-11-01 18:53:13 +0000197 print e
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000198
cjhopman@chromium.org3365f2d2012-11-01 18:53:13 +0000199 print 'Unable to authenticate to code.google.com.'
200 print 'Some issues may be missing.'
201 return None
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000202
203
204def username(email):
205 """Keeps the username of an email address."""
206 return email and email.split('@', 1)[0]
207
208
cjhopman@chromium.org426557a2012-10-22 20:18:52 +0000209def datetime_to_midnight(date):
210 return date - timedelta(hours=date.hour, minutes=date.minute,
211 seconds=date.second, microseconds=date.microsecond)
212
213
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000214def get_quarter_of(date):
cjhopman@chromium.org426557a2012-10-22 20:18:52 +0000215 begin = (datetime_to_midnight(date) -
216 relativedelta(months=(date.month % 3) - 1, days=(date.day - 1)))
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000217 return begin, begin + relativedelta(months=3)
218
219
220def get_year_of(date):
cjhopman@chromium.org426557a2012-10-22 20:18:52 +0000221 begin = (datetime_to_midnight(date) -
222 relativedelta(months=(date.month - 1), days=(date.day - 1)))
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000223 return begin, begin + relativedelta(years=1)
224
225
226def get_week_of(date):
cjhopman@chromium.org426557a2012-10-22 20:18:52 +0000227 begin = (datetime_to_midnight(date) - timedelta(days=date.weekday()))
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000228 return begin, begin + timedelta(days=7)
229
230
231def get_yes_or_no(msg):
232 while True:
233 response = raw_input(msg + ' yes/no [no] ')
234 if response == 'y' or response == 'yes':
235 return True
236 elif not response or response == 'n' or response == 'no':
237 return False
238
239
240def datetime_from_rietveld(date_string):
241 return datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f')
242
243
244def datetime_from_google_code(date_string):
245 return datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%fZ')
246
247
248class MyActivity(object):
249 def __init__(self, options):
250 self.options = options
251 self.modified_after = options.begin
252 self.modified_before = options.end
253 self.user = options.user
254 self.changes = []
255 self.reviews = []
256 self.issues = []
257 self.check_cookies()
258 self.google_code_auth_token = None
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000259 self.webkit_repo = options.webkit_repo
260 if self.webkit_repo:
261 self.setup_webkit_info()
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000262
263 # Check the codereview cookie jar to determine which Rietveld instances to
264 # authenticate to.
265 def check_cookies(self):
266 cookie_file = os.path.expanduser('~/.codereview_upload_cookies')
267 cookie_jar = cookielib.MozillaCookieJar(cookie_file)
268 if not os.path.exists(cookie_file):
269 exit(1)
270
271 try:
272 cookie_jar.load()
273 print 'Found cookie file: %s' % cookie_file
274 except (cookielib.LoadError, IOError):
275 exit(1)
276
277 filtered_instances = []
278
279 def has_cookie(instance):
280 for cookie in cookie_jar:
281 if cookie.name == 'SACSID' and cookie.domain == instance['url']:
282 return True
283 if self.options.auth:
284 return get_yes_or_no('No cookie found for %s. Authorize for this '
285 'instance? (may require application-specific '
286 'password)' % instance['url'])
287 filtered_instances.append(instance)
288 return False
289
290 for instance in rietveld_instances:
291 instance['auth'] = has_cookie(instance)
292
293 if filtered_instances:
294 print ('No cookie found for the following Rietveld instance%s:' %
295 ('s' if len(filtered_instances) > 1 else ''))
296 for instance in filtered_instances:
297 print '\t' + instance['url']
298 print 'Use --auth if you would like to authenticate to them.\n'
299
300 def rietveld_search(self, instance, owner=None, reviewer=None):
301 if instance['requires_auth'] and not instance['auth']:
302 return []
303
304
305 email = None if instance['auth'] else ''
306 remote = rietveld.Rietveld('https://' + instance['url'], email, None)
307
308 # See def search() in rietveld.py to see all the filters you can use.
309 query_modified_after = None
310
311 if instance['supports_owner_modified_query']:
312 query_modified_after = self.modified_after.strftime('%Y-%m-%d')
313
314 # Rietveld does not allow search by both created_before and modified_after.
315 # (And some instances don't allow search by both owner and modified_after)
316 owner_email = None
317 reviewer_email = None
318 if owner:
319 owner_email = owner + '@' + instance['email_domain']
320 if reviewer:
321 reviewer_email = reviewer + '@' + instance['email_domain']
322 issues = remote.search(
323 owner=owner_email,
324 reviewer=reviewer_email,
325 modified_after=query_modified_after,
326 with_messages=True)
327
328 issues = filter(
329 lambda i: (datetime_from_rietveld(i['created']) < self.modified_before),
330 issues)
331 issues = filter(
332 lambda i: (datetime_from_rietveld(i['modified']) > self.modified_after),
333 issues)
334
335 should_filter_by_user = True
336 issues = map(partial(self.process_rietveld_issue, instance), issues)
337 issues = filter(
338 partial(self.filter_issue, should_filter_by_user=should_filter_by_user),
339 issues)
340 issues = sorted(issues, key=lambda i: i['modified'], reverse=True)
341
342 return issues
343
344 def process_rietveld_issue(self, instance, issue):
345 ret = {}
346 ret['owner'] = issue['owner_email']
347 ret['author'] = ret['owner']
348
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000349 ret['reviewers'] = set(issue['reviewers'])
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000350
351 shorturl = instance['url']
352 if 'shorturl' in instance:
353 shorturl = instance['shorturl']
354
355 ret['review_url'] = 'http://%s/%d' % (shorturl, issue['issue'])
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000356
357 # Rietveld sometimes has '\r\n' instead of '\n'.
358 ret['header'] = issue['description'].replace('\r', '').split('\n')[0]
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000359
360 ret['modified'] = datetime_from_rietveld(issue['modified'])
361 ret['created'] = datetime_from_rietveld(issue['created'])
362 ret['replies'] = self.process_rietveld_replies(issue['messages'])
363
364 return ret
365
366 @staticmethod
367 def process_rietveld_replies(replies):
368 ret = []
369 for reply in replies:
370 r = {}
371 r['author'] = reply['sender']
372 r['created'] = datetime_from_rietveld(reply['date'])
373 r['content'] = ''
374 ret.append(r)
375 return ret
376
377 def gerrit_search(self, instance, owner=None, reviewer=None):
378 max_age = datetime.today() - self.modified_after
379 max_age = max_age.days * 24 * 3600 + max_age.seconds
380
381 # See https://review.openstack.org/Documentation/cmd-query.html
382 # Gerrit doesn't allow filtering by created time, only modified time.
383 user_filter = 'owner:%s' % owner if owner else 'reviewer:%s' % reviewer
384 gquery_cmd = ['ssh', '-p', str(instance['port']), instance['url'],
385 'gerrit', 'query',
386 '--format', 'JSON',
387 '--comments',
388 '--',
389 '-age:%ss' % str(max_age),
390 user_filter]
391 [stdout, _] = subprocess.Popen(gquery_cmd, stdout=subprocess.PIPE,
392 stderr=subprocess.PIPE).communicate()
393 issues = str(stdout).split('\n')[:-2]
394 issues = map(json.loads, issues)
395
396 # TODO(cjhopman): should we filter abandoned changes?
397 issues = map(self.process_gerrit_issue, issues)
398 issues = filter(self.filter_issue, issues)
399 issues = sorted(issues, key=lambda i: i['modified'], reverse=True)
400
401 return issues
402
403 def process_gerrit_issue(self, issue):
404 ret = {}
405 ret['review_url'] = issue['url']
406 ret['header'] = issue['subject']
407 ret['owner'] = issue['owner']['email']
408 ret['author'] = ret['owner']
409 ret['created'] = datetime.fromtimestamp(issue['createdOn'])
410 ret['modified'] = datetime.fromtimestamp(issue['lastUpdated'])
411 if 'comments' in issue:
412 ret['replies'] = self.process_gerrit_issue_replies(issue['comments'])
413 else:
414 ret['replies'] = []
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000415 ret['reviewers'] = set()
416 for reply in ret['replies']:
417 if reply['author'] != ret['author']:
418 ret['reviewers'].add(reply['author'])
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000419 return ret
420
421 @staticmethod
422 def process_gerrit_issue_replies(replies):
423 ret = []
424 replies = filter(lambda r: 'email' in r['reviewer'], replies)
425 for reply in replies:
426 r = {}
427 r['author'] = reply['reviewer']['email']
428 r['created'] = datetime.fromtimestamp(reply['timestamp'])
429 r['content'] = ''
430 ret.append(r)
431 return ret
432
433 def google_code_issue_search(self, instance):
434 time_format = '%Y-%m-%dT%T'
435 # See http://code.google.com/p/support/wiki/IssueTrackerAPI
436 # q=<owner>@chromium.org does a full text search for <owner>@chromium.org.
437 # This will accept the issue if owner is the owner or in the cc list. Might
438 # have some false positives, though.
439
440 # Don't filter normally on modified_before because it can filter out things
441 # that were modified in the time period and then modified again after it.
442 gcode_url = ('https://code.google.com/feeds/issues/p/%s/issues/full' %
443 instance['name'])
444
445 gcode_data = urllib.urlencode({
446 'alt': 'json',
447 'max-results': '100000',
448 'q': '%s' % self.user,
449 'published-max': self.modified_before.strftime(time_format),
450 'updated-min': self.modified_after.strftime(time_format),
451 })
452
453 opener = urllib2.build_opener()
cjhopman@chromium.org3365f2d2012-11-01 18:53:13 +0000454 if self.google_code_auth_token:
455 opener.addheaders = [('Authorization', 'GoogleLogin auth=%s' %
456 self.google_code_auth_token)]
457 gcode_json = None
458 try:
459 gcode_get = opener.open(gcode_url + '?' + gcode_data)
460 gcode_json = json.load(gcode_get)
461 gcode_get.close()
462 except urllib2.HTTPError, _:
463 print 'Unable to access ' + instance['name'] + ' issue tracker.'
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000464
cjhopman@chromium.org3365f2d2012-11-01 18:53:13 +0000465 if not gcode_json or 'entry' not in gcode_json['feed']:
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000466 return []
467
468 issues = gcode_json['feed']['entry']
469 issues = map(partial(self.process_google_code_issue, instance), issues)
470 issues = filter(self.filter_issue, issues)
471 issues = sorted(issues, key=lambda i: i['modified'], reverse=True)
472 return issues
473
474 def process_google_code_issue(self, project, issue):
475 ret = {}
476 ret['created'] = datetime_from_google_code(issue['published']['$t'])
477 ret['modified'] = datetime_from_google_code(issue['updated']['$t'])
478
479 ret['owner'] = ''
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000480 if 'issues$owner' in issue:
481 ret['owner'] = issue['issues$owner']['issues$username']['$t']
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000482 ret['author'] = issue['author'][0]['name']['$t']
483
484 if 'shorturl' in project:
485 issue_id = issue['id']['$t']
486 issue_id = issue_id[issue_id.rfind('/') + 1:]
487 ret['url'] = 'http://%s/%d' % (project['shorturl'], int(issue_id))
488 else:
489 issue_url = issue['link'][1]
490 if issue_url['rel'] != 'alternate':
491 raise RuntimeError
492 ret['url'] = issue_url['href']
493 ret['header'] = issue['title']['$t']
494
495 ret['replies'] = self.get_google_code_issue_replies(issue)
496 return ret
497
498 def get_google_code_issue_replies(self, issue):
499 """Get all the comments on the issue."""
500 replies_url = issue['link'][0]
501 if replies_url['rel'] != 'replies':
502 raise RuntimeError
503
504 replies_data = urllib.urlencode({
505 'alt': 'json',
506 'fields': 'entry(published,author,content)',
507 })
508
509 opener = urllib2.build_opener()
510 opener.addheaders = [('Authorization', 'GoogleLogin auth=%s' %
511 self.google_code_auth_token)]
512 try:
513 replies_get = opener.open(replies_url['href'] + '?' + replies_data)
514 except urllib2.HTTPError, _:
515 return []
516
517 replies_json = json.load(replies_get)
518 replies_get.close()
519 return self.process_google_code_issue_replies(replies_json)
520
521 @staticmethod
522 def process_google_code_issue_replies(replies):
523 if 'entry' not in replies['feed']:
524 return []
525
526 ret = []
527 for entry in replies['feed']['entry']:
528 e = {}
529 e['created'] = datetime_from_google_code(entry['published']['$t'])
530 e['content'] = entry['content']['$t']
531 e['author'] = entry['author'][0]['name']['$t']
532 ret.append(e)
533 return ret
534
535 @staticmethod
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000536 def git_cmd(repo, *args):
537 cmd = ['git', '--git-dir=%s/.git' % repo]
538 cmd.extend(args)
539 [stdout, _] = subprocess.Popen(cmd, stdout=subprocess.PIPE,
540 stderr=subprocess.PIPE).communicate()
541 lines = str(stdout).split('\n')[:-1]
542 return lines
543
544 def git_search(self, instance, owner=None, reviewer=None):
545 repo = getattr(self, instance['option'])
546 if not repo:
547 return []
548
549 search = []
550 if owner:
551 search.extend(instance['owner_search_func'](owner))
552 if reviewer:
553 search.extend(instance['reviewer_search_func'](reviewer))
554 if not len(search):
555 return []
556
557 self.git_cmd(repo, 'fetch', 'origin')
558
559 time_format = '%Y-%m-%d %H:%M:%S'
560 log_args = [
561 '--after=' + self.modified_after.strftime(time_format),
562 '--before=' + self.modified_before.strftime(time_format),
563 '--format=%H'
564 ]
565 commits = set()
566 for query in search:
567 query_args = [query]
568 query_args.extend(log_args)
569 commits |= set(self.git_cmd(repo, 'log', 'origin/master', *query_args))
570
571 ret = []
572 for commit in commits:
573 output = self.git_cmd(repo, 'log', commit + "^!", "--format=%cn%n%cd%n%B")
574 author = output[0]
575 date = datetime.strptime(output[1], "%a %b %d %H:%M:%S %Y +0000")
enne@chromium.orgd69dab92013-06-10 20:19:56 +0000576 processed = self.process_git_commit(instance, author, date, output[2:])
577 if processed:
578 ret.append(processed)
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000579
580 ret = sorted(ret, key=lambda i: i['modified'], reverse=True)
581 return ret
582
583 @staticmethod
584 def process_git_commit(instance, author, date, log):
585 ret = {}
586 ret['owner'] = author
587 ret['author'] = author
588 ret['modified'] = date
589 ret['created'] = date
590 ret['header'] = log[0]
591
592 reviews = []
593 reviewers = []
594 changes = []
595
596 for line in log:
597 match = re.match(r'Reviewed by ([^.]*)', line)
598 if match:
599 reviewers.append(match.group(1))
600 if instance['review_re']:
601 match = re.match(instance['review_re'], line)
602 if match:
603 reviews.append(int(match.group(1)))
604 if instance['change_re']:
605 match = re.match(instance['change_re'], line)
606 if match:
607 changes.append(int(match.group(1)))
608
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000609 committer_list = webkitpy.common.config.committers.CommitterList()
610 ret['reviewers'] = set(
611 (committer_list.contributor_by_name(r).emails[0] for r in reviewers))
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000612
613 # Reviews more useful than change link itself, but tricky if multiple
614 # Reviews == bugs for WebKit changes
615 if len(reviews) == 1:
616 url = 'http://%s/%d' % (instance['review_url'], reviews[0])
617 if instance['review_prop']:
618 ret[instance['review_prop']] = reviews[0]
enne@chromium.orgd69dab92013-06-10 20:19:56 +0000619 elif len(changes) == 1:
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000620 url = 'http://%s/%d' % (instance['change_url'], changes[0])
enne@chromium.orgd69dab92013-06-10 20:19:56 +0000621 else:
622 # Couldn't find anything.
623 return None
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000624 ret['review_url'] = url
625
626 return ret
627
628 def bugzilla_issues(self, instance, user):
629 if instance['user_func']:
630 user = instance['user_func'](user)
631 if not user:
632 return []
633
634 # This search is a little iffy, as it returns any bug that has been
635 # modified over a time period in any way and that a user has ever commented
636 # on, but that's the best that Bugzilla can get us. Oops.
637 commented = { 'emaillongdesc1': 1 }
638 issues = self.bugzilla_search(instance, user, commented)
639 issues = filter(lambda issue: issue['owner'] != user, issues)
640
641 reported = { 'emailreporter1': 1, 'chfield': '[Bug creation]' }
642 issues.extend(self.bugzilla_search(instance, user, reported))
643
644 # Remove duplicates by bug id
645 seen = {}
646 pruned = []
647 for issue in issues:
648 bug_id = issue['webkit_bug_id']
649 if bug_id in seen:
650 continue
651 seen[bug_id] = True
652 pruned.append(issue)
653
654 # Bugzilla has no modified time, so sort by id?
655 pruned = sorted(pruned, key=lambda i: i['webkit_bug_id'])
656 return issues
657
658 def bugzilla_search(self, instance, user, params):
659 time_format = '%Y-%m-%d'
660 values = {
661 'chfieldfrom': self.modified_after.strftime(time_format),
662 'chfieldto': self.modified_before.strftime(time_format),
663 'ctype': 'csv',
664 'emailtype1': 'substring',
665 'email1': '%s' % user,
666 }
667 values.update(params)
668
669 # Must be GET not POST
670 data = urllib.urlencode(values)
671 req = urllib2.Request("%s?%s" % (instance['search_url'], data))
672 response = urllib2.urlopen(req)
673 reader = csv.reader(response)
674 reader.next() # skip the header line
675
676 issues = map(partial(self.process_bugzilla_issue, instance), reader)
677 return issues
678
679 @staticmethod
680 def process_bugzilla_issue(instance, issue):
681 bug_id, owner, desc = int(issue[0]), issue[4], issue[7]
682
683 ret = {}
684 ret['owner'] = owner
685 ret['author'] = owner
686 ret['review_url'] = 'http://%s/%d' % (instance['url'], bug_id)
687 ret['url'] = ret['review_url']
688 ret['header'] = desc
689 ret['webkit_bug_id'] = bug_id
690 return ret
691
692 def setup_webkit_info(self):
693 assert(self.webkit_repo)
694 git_dir = os.path.normpath(self.webkit_repo + "/.git")
695 if not os.path.exists(git_dir):
scheib@chromium.orgb299e7c2012-11-13 21:34:34 +0000696 print "%s doesn't exist, skipping WebKit checks." % git_dir
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000697 self.webkit_repo = None
698 return
699
700 try:
701 self.git_cmd(self.webkit_repo, "fetch", "origin")
702 except subprocess.CalledProcessError:
scheib@chromium.orgb299e7c2012-11-13 21:34:34 +0000703 print "Failed to update WebKit repo, skipping WebKit checks."
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000704 self.webkit_repo = None
705 return
706
707 path = "Tools/Scripts"
708 full_path = os.path.normpath("%s/%s" % (self.options.webkit_repo, path))
709 sys.path.append(full_path)
710
711 try:
712 global webkitpy
713 webkitpy = __import__('webkitpy.common.config.committers')
714 except ImportError:
scheib@chromium.orgb299e7c2012-11-13 21:34:34 +0000715 print "Failed to import WebKit committer list, skipping WebKit checks."
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000716 self.webkit_repo = None
717 return
718
719 if not webkit_account(self.user):
720 email = self.user + "@chromium.org"
scheib@chromium.orgb299e7c2012-11-13 21:34:34 +0000721 print "No %s in committers.py, skipping WebKit checks." % email
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000722 self.webkit_repo = None
723
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000724 def print_change(self, change):
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000725 optional_values = {
726 'reviewers': ', '.join(change['reviewers'])
727 }
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000728 self.print_generic(self.options.output_format,
729 self.options.output_format_changes,
730 change['header'],
731 change['review_url'],
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000732 change['author'],
733 optional_values)
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000734
735 def print_issue(self, issue):
736 optional_values = {
737 'owner': issue['owner'],
738 }
739 self.print_generic(self.options.output_format,
740 self.options.output_format_issues,
741 issue['header'],
742 issue['url'],
743 issue['author'],
744 optional_values)
745
746 def print_review(self, review):
747 self.print_generic(self.options.output_format,
748 self.options.output_format_reviews,
749 review['header'],
750 review['review_url'],
751 review['author'])
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000752
753 @staticmethod
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000754 def print_generic(default_fmt, specific_fmt,
755 title, url, author,
756 optional_values=None):
757 output_format = specific_fmt if specific_fmt is not None else default_fmt
758 output_format = unicode(output_format)
759 required_values = {
760 'title': title,
761 'url': url,
762 'author': author,
763 }
764 # Merge required and optional values.
765 if optional_values is not None:
766 values = dict(required_values.items() + optional_values.items())
767 else:
768 values = required_values
769 print output_format.format(**values)
770
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000771
772 def filter_issue(self, issue, should_filter_by_user=True):
773 def maybe_filter_username(email):
774 return not should_filter_by_user or username(email) == self.user
775 if (maybe_filter_username(issue['author']) and
776 self.filter_modified(issue['created'])):
777 return True
778 if (maybe_filter_username(issue['owner']) and
779 (self.filter_modified(issue['created']) or
780 self.filter_modified(issue['modified']))):
781 return True
782 for reply in issue['replies']:
783 if self.filter_modified(reply['created']):
784 if not should_filter_by_user:
785 break
786 if (username(reply['author']) == self.user
787 or (self.user + '@') in reply['content']):
788 break
789 else:
790 return False
791 return True
792
793 def filter_modified(self, modified):
794 return self.modified_after < modified and modified < self.modified_before
795
796 def auth_for_changes(self):
797 #TODO(cjhopman): Move authentication check for getting changes here.
798 pass
799
800 def auth_for_reviews(self):
801 # Reviews use all the same instances as changes so no authentication is
802 # required.
803 pass
804
805 def auth_for_issues(self):
806 self.google_code_auth_token = (
807 get_auth_token(self.options.local_user + '@chromium.org'))
808
809 def get_changes(self):
810 for instance in rietveld_instances:
811 self.changes += self.rietveld_search(instance, owner=self.user)
812
813 for instance in gerrit_instances:
814 self.changes += self.gerrit_search(instance, owner=self.user)
815
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000816 for instance in git_instances:
817 self.changes += self.git_search(instance, owner=self.user)
818
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000819 def print_changes(self):
820 if self.changes:
821 print '\nChanges:'
822 for change in self.changes:
823 self.print_change(change)
824
825 def get_reviews(self):
826 for instance in rietveld_instances:
827 self.reviews += self.rietveld_search(instance, reviewer=self.user)
828
829 for instance in gerrit_instances:
830 reviews = self.gerrit_search(instance, reviewer=self.user)
831 reviews = filter(lambda r: not username(r['owner']) == self.user, reviews)
832 self.reviews += reviews
833
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000834 for instance in git_instances:
835 self.reviews += self.git_search(instance, reviewer=self.user)
836
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000837 def print_reviews(self):
838 if self.reviews:
839 print '\nReviews:'
840 for review in self.reviews:
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000841 self.print_review(review)
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000842
843 def get_issues(self):
844 for project in google_code_projects:
845 self.issues += self.google_code_issue_search(project)
846
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000847 for instance in bugzilla_instances:
848 self.issues += self.bugzilla_issues(instance, self.user)
849
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000850 def print_issues(self):
851 if self.issues:
852 print '\nIssues:'
853 for issue in self.issues:
854 self.print_issue(issue)
855
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000856 def process_activities(self):
857 # If a webkit bug was a review, don't list it as an issue.
858 ids = {}
859 for review in self.reviews + self.changes:
860 if 'webkit_bug_id' in review:
861 ids[review['webkit_bug_id']] = True
862
863 def duplicate_issue(issue):
864 if 'webkit_bug_id' not in issue:
865 return False
866 return issue['webkit_bug_id'] in ids
867
868 self.issues = filter(lambda issue: not duplicate_issue(issue), self.issues)
869
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000870 def print_activity(self):
871 self.print_changes()
872 self.print_reviews()
873 self.print_issues()
874
875
876def main():
877 # Silence upload.py.
878 rietveld.upload.verbosity = 0
879
880 parser = optparse.OptionParser(description=sys.modules[__name__].__doc__)
881 parser.add_option(
882 '-u', '--user', metavar='<email>',
883 default=os.environ.get('USER'),
884 help='Filter on user, default=%default')
885 parser.add_option(
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000886 '--webkit_repo', metavar='<dir>',
887 default='%s' % os.environ.get('WEBKIT_DIR'),
888 help='Local path to WebKit repository, default=%default')
889 parser.add_option(
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000890 '-b', '--begin', metavar='<date>',
891 help='Filter issues created after the date')
892 parser.add_option(
893 '-e', '--end', metavar='<date>',
894 help='Filter issues created before the date')
895 quarter_begin, quarter_end = get_quarter_of(datetime.today() -
896 relativedelta(months=2))
897 parser.add_option(
898 '-Q', '--last_quarter', action='store_true',
899 help='Use last quarter\'s dates, e.g. %s to %s' % (
900 quarter_begin.strftime('%Y-%m-%d'), quarter_end.strftime('%Y-%m-%d')))
901 parser.add_option(
902 '-Y', '--this_year', action='store_true',
903 help='Use this year\'s dates')
904 parser.add_option(
905 '-w', '--week_of', metavar='<date>',
906 help='Show issues for week of the date')
907 parser.add_option(
908 '-a', '--auth',
909 action='store_true',
910 help='Ask to authenticate for instances with no auth cookie')
911
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000912 activity_types_group = optparse.OptionGroup(parser, 'Activity Types',
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000913 'By default, all activity will be looked up and '
914 'printed. If any of these are specified, only '
915 'those specified will be searched.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000916 activity_types_group.add_option(
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000917 '-c', '--changes',
918 action='store_true',
919 help='Show changes.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000920 activity_types_group.add_option(
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000921 '-i', '--issues',
922 action='store_true',
923 help='Show issues.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000924 activity_types_group.add_option(
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000925 '-r', '--reviews',
926 action='store_true',
927 help='Show reviews.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000928 parser.add_option_group(activity_types_group)
929
930 output_format_group = optparse.OptionGroup(parser, 'Output Format',
931 'By default, all activity will be printed in the '
932 'following format: {url} {title}. This can be '
933 'changed for either all activity types or '
934 'individually for each activity type. The format '
935 'is defined as documented for '
936 'string.format(...). The variables available for '
937 'all activity types are url, title and author. '
938 'Format options for specific activity types will '
939 'override the generic format.')
940 output_format_group.add_option(
941 '-f', '--output-format', metavar='<format>',
942 default=u'{url} {title}',
943 help='Specifies the format to use when printing all your activity.')
944 output_format_group.add_option(
945 '--output-format-changes', metavar='<format>',
946 default=None,
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000947 help='Specifies the format to use when printing changes. Supports the '
948 'additional variable {reviewers}')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000949 output_format_group.add_option(
950 '--output-format-issues', metavar='<format>',
951 default=None,
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000952 help='Specifies the format to use when printing issues. Supports the '
953 'additional variable {owner}.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000954 output_format_group.add_option(
955 '--output-format-reviews', metavar='<format>',
956 default=None,
957 help='Specifies the format to use when printing reviews.')
958 parser.add_option_group(output_format_group)
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000959
960 # Remove description formatting
961 parser.format_description = (
962 lambda _: parser.description) # pylint: disable=E1101
963
964 options, args = parser.parse_args()
965 options.local_user = os.environ.get('USER')
966 if args:
967 parser.error('Args unsupported')
968 if not options.user:
969 parser.error('USER is not set, please use -u')
970
971 options.user = username(options.user)
972
973 if not options.begin:
974 if options.last_quarter:
975 begin, end = quarter_begin, quarter_end
976 elif options.this_year:
977 begin, end = get_year_of(datetime.today())
978 elif options.week_of:
979 begin, end = (get_week_of(datetime.strptime(options.week_of, '%m/%d/%y')))
980 else:
981 begin, end = (get_week_of(datetime.today() - timedelta(days=1)))
982 else:
983 begin = datetime.strptime(options.begin, '%m/%d/%y')
984 if options.end:
985 end = datetime.strptime(options.end, '%m/%d/%y')
986 else:
987 end = datetime.today()
988 options.begin, options.end = begin, end
989
990 print 'Searching for activity by %s' % options.user
991 print 'Using range %s to %s' % (options.begin, options.end)
992
993 my_activity = MyActivity(options)
994
995 if not (options.changes or options.reviews or options.issues):
996 options.changes = True
997 options.issues = True
998 options.reviews = True
999
1000 # First do any required authentication so none of the user interaction has to
1001 # wait for actual work.
1002 if options.changes:
1003 my_activity.auth_for_changes()
1004 if options.reviews:
1005 my_activity.auth_for_reviews()
1006 if options.issues:
1007 my_activity.auth_for_issues()
1008
1009 print 'Looking up activity.....'
1010
1011 if options.changes:
1012 my_activity.get_changes()
1013 if options.reviews:
1014 my_activity.get_reviews()
1015 if options.issues:
1016 my_activity.get_issues()
1017
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +00001018 my_activity.process_activities()
1019
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +00001020 print '\n\n\n'
1021
1022 my_activity.print_changes()
1023 my_activity.print_reviews()
1024 my_activity.print_issues()
1025 return 0
1026
1027
1028if __name__ == '__main__':
1029 sys.exit(main())