blob: ac68a23a58de36bb6be6ee24c2e8c475f6003a03 [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")
576 ret.append(self.process_git_commit(instance, author, date, output[2:]))
577
578 ret = sorted(ret, key=lambda i: i['modified'], reverse=True)
579 return ret
580
581 @staticmethod
582 def process_git_commit(instance, author, date, log):
583 ret = {}
584 ret['owner'] = author
585 ret['author'] = author
586 ret['modified'] = date
587 ret['created'] = date
588 ret['header'] = log[0]
589
590 reviews = []
591 reviewers = []
592 changes = []
593
594 for line in log:
595 match = re.match(r'Reviewed by ([^.]*)', line)
596 if match:
597 reviewers.append(match.group(1))
598 if instance['review_re']:
599 match = re.match(instance['review_re'], line)
600 if match:
601 reviews.append(int(match.group(1)))
602 if instance['change_re']:
603 match = re.match(instance['change_re'], line)
604 if match:
605 changes.append(int(match.group(1)))
606
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000607 committer_list = webkitpy.common.config.committers.CommitterList()
608 ret['reviewers'] = set(
609 (committer_list.contributor_by_name(r).emails[0] for r in reviewers))
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000610
611 # Reviews more useful than change link itself, but tricky if multiple
612 # Reviews == bugs for WebKit changes
613 if len(reviews) == 1:
614 url = 'http://%s/%d' % (instance['review_url'], reviews[0])
615 if instance['review_prop']:
616 ret[instance['review_prop']] = reviews[0]
617 else:
618 url = 'http://%s/%d' % (instance['change_url'], changes[0])
619 ret['review_url'] = url
620
621 return ret
622
623 def bugzilla_issues(self, instance, user):
624 if instance['user_func']:
625 user = instance['user_func'](user)
626 if not user:
627 return []
628
629 # This search is a little iffy, as it returns any bug that has been
630 # modified over a time period in any way and that a user has ever commented
631 # on, but that's the best that Bugzilla can get us. Oops.
632 commented = { 'emaillongdesc1': 1 }
633 issues = self.bugzilla_search(instance, user, commented)
634 issues = filter(lambda issue: issue['owner'] != user, issues)
635
636 reported = { 'emailreporter1': 1, 'chfield': '[Bug creation]' }
637 issues.extend(self.bugzilla_search(instance, user, reported))
638
639 # Remove duplicates by bug id
640 seen = {}
641 pruned = []
642 for issue in issues:
643 bug_id = issue['webkit_bug_id']
644 if bug_id in seen:
645 continue
646 seen[bug_id] = True
647 pruned.append(issue)
648
649 # Bugzilla has no modified time, so sort by id?
650 pruned = sorted(pruned, key=lambda i: i['webkit_bug_id'])
651 return issues
652
653 def bugzilla_search(self, instance, user, params):
654 time_format = '%Y-%m-%d'
655 values = {
656 'chfieldfrom': self.modified_after.strftime(time_format),
657 'chfieldto': self.modified_before.strftime(time_format),
658 'ctype': 'csv',
659 'emailtype1': 'substring',
660 'email1': '%s' % user,
661 }
662 values.update(params)
663
664 # Must be GET not POST
665 data = urllib.urlencode(values)
666 req = urllib2.Request("%s?%s" % (instance['search_url'], data))
667 response = urllib2.urlopen(req)
668 reader = csv.reader(response)
669 reader.next() # skip the header line
670
671 issues = map(partial(self.process_bugzilla_issue, instance), reader)
672 return issues
673
674 @staticmethod
675 def process_bugzilla_issue(instance, issue):
676 bug_id, owner, desc = int(issue[0]), issue[4], issue[7]
677
678 ret = {}
679 ret['owner'] = owner
680 ret['author'] = owner
681 ret['review_url'] = 'http://%s/%d' % (instance['url'], bug_id)
682 ret['url'] = ret['review_url']
683 ret['header'] = desc
684 ret['webkit_bug_id'] = bug_id
685 return ret
686
687 def setup_webkit_info(self):
688 assert(self.webkit_repo)
689 git_dir = os.path.normpath(self.webkit_repo + "/.git")
690 if not os.path.exists(git_dir):
scheib@chromium.orgb299e7c2012-11-13 21:34:34 +0000691 print "%s doesn't exist, skipping WebKit checks." % git_dir
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000692 self.webkit_repo = None
693 return
694
695 try:
696 self.git_cmd(self.webkit_repo, "fetch", "origin")
697 except subprocess.CalledProcessError:
scheib@chromium.orgb299e7c2012-11-13 21:34:34 +0000698 print "Failed to update WebKit repo, skipping WebKit checks."
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000699 self.webkit_repo = None
700 return
701
702 path = "Tools/Scripts"
703 full_path = os.path.normpath("%s/%s" % (self.options.webkit_repo, path))
704 sys.path.append(full_path)
705
706 try:
707 global webkitpy
708 webkitpy = __import__('webkitpy.common.config.committers')
709 except ImportError:
scheib@chromium.orgb299e7c2012-11-13 21:34:34 +0000710 print "Failed to import WebKit committer list, skipping WebKit checks."
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000711 self.webkit_repo = None
712 return
713
714 if not webkit_account(self.user):
715 email = self.user + "@chromium.org"
scheib@chromium.orgb299e7c2012-11-13 21:34:34 +0000716 print "No %s in committers.py, skipping WebKit checks." % email
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000717 self.webkit_repo = None
718
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000719 def print_change(self, change):
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000720 optional_values = {
721 'reviewers': ', '.join(change['reviewers'])
722 }
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000723 self.print_generic(self.options.output_format,
724 self.options.output_format_changes,
725 change['header'],
726 change['review_url'],
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000727 change['author'],
728 optional_values)
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000729
730 def print_issue(self, issue):
731 optional_values = {
732 'owner': issue['owner'],
733 }
734 self.print_generic(self.options.output_format,
735 self.options.output_format_issues,
736 issue['header'],
737 issue['url'],
738 issue['author'],
739 optional_values)
740
741 def print_review(self, review):
742 self.print_generic(self.options.output_format,
743 self.options.output_format_reviews,
744 review['header'],
745 review['review_url'],
746 review['author'])
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000747
748 @staticmethod
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000749 def print_generic(default_fmt, specific_fmt,
750 title, url, author,
751 optional_values=None):
752 output_format = specific_fmt if specific_fmt is not None else default_fmt
753 output_format = unicode(output_format)
754 required_values = {
755 'title': title,
756 'url': url,
757 'author': author,
758 }
759 # Merge required and optional values.
760 if optional_values is not None:
761 values = dict(required_values.items() + optional_values.items())
762 else:
763 values = required_values
764 print output_format.format(**values)
765
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000766
767 def filter_issue(self, issue, should_filter_by_user=True):
768 def maybe_filter_username(email):
769 return not should_filter_by_user or username(email) == self.user
770 if (maybe_filter_username(issue['author']) and
771 self.filter_modified(issue['created'])):
772 return True
773 if (maybe_filter_username(issue['owner']) and
774 (self.filter_modified(issue['created']) or
775 self.filter_modified(issue['modified']))):
776 return True
777 for reply in issue['replies']:
778 if self.filter_modified(reply['created']):
779 if not should_filter_by_user:
780 break
781 if (username(reply['author']) == self.user
782 or (self.user + '@') in reply['content']):
783 break
784 else:
785 return False
786 return True
787
788 def filter_modified(self, modified):
789 return self.modified_after < modified and modified < self.modified_before
790
791 def auth_for_changes(self):
792 #TODO(cjhopman): Move authentication check for getting changes here.
793 pass
794
795 def auth_for_reviews(self):
796 # Reviews use all the same instances as changes so no authentication is
797 # required.
798 pass
799
800 def auth_for_issues(self):
801 self.google_code_auth_token = (
802 get_auth_token(self.options.local_user + '@chromium.org'))
803
804 def get_changes(self):
805 for instance in rietveld_instances:
806 self.changes += self.rietveld_search(instance, owner=self.user)
807
808 for instance in gerrit_instances:
809 self.changes += self.gerrit_search(instance, owner=self.user)
810
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000811 for instance in git_instances:
812 self.changes += self.git_search(instance, owner=self.user)
813
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000814 def print_changes(self):
815 if self.changes:
816 print '\nChanges:'
817 for change in self.changes:
818 self.print_change(change)
819
820 def get_reviews(self):
821 for instance in rietveld_instances:
822 self.reviews += self.rietveld_search(instance, reviewer=self.user)
823
824 for instance in gerrit_instances:
825 reviews = self.gerrit_search(instance, reviewer=self.user)
826 reviews = filter(lambda r: not username(r['owner']) == self.user, reviews)
827 self.reviews += reviews
828
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000829 for instance in git_instances:
830 self.reviews += self.git_search(instance, reviewer=self.user)
831
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000832 def print_reviews(self):
833 if self.reviews:
834 print '\nReviews:'
835 for review in self.reviews:
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000836 self.print_review(review)
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000837
838 def get_issues(self):
839 for project in google_code_projects:
840 self.issues += self.google_code_issue_search(project)
841
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000842 for instance in bugzilla_instances:
843 self.issues += self.bugzilla_issues(instance, self.user)
844
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000845 def print_issues(self):
846 if self.issues:
847 print '\nIssues:'
848 for issue in self.issues:
849 self.print_issue(issue)
850
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000851 def process_activities(self):
852 # If a webkit bug was a review, don't list it as an issue.
853 ids = {}
854 for review in self.reviews + self.changes:
855 if 'webkit_bug_id' in review:
856 ids[review['webkit_bug_id']] = True
857
858 def duplicate_issue(issue):
859 if 'webkit_bug_id' not in issue:
860 return False
861 return issue['webkit_bug_id'] in ids
862
863 self.issues = filter(lambda issue: not duplicate_issue(issue), self.issues)
864
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000865 def print_activity(self):
866 self.print_changes()
867 self.print_reviews()
868 self.print_issues()
869
870
871def main():
872 # Silence upload.py.
873 rietveld.upload.verbosity = 0
874
875 parser = optparse.OptionParser(description=sys.modules[__name__].__doc__)
876 parser.add_option(
877 '-u', '--user', metavar='<email>',
878 default=os.environ.get('USER'),
879 help='Filter on user, default=%default')
880 parser.add_option(
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000881 '--webkit_repo', metavar='<dir>',
882 default='%s' % os.environ.get('WEBKIT_DIR'),
883 help='Local path to WebKit repository, default=%default')
884 parser.add_option(
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000885 '-b', '--begin', metavar='<date>',
886 help='Filter issues created after the date')
887 parser.add_option(
888 '-e', '--end', metavar='<date>',
889 help='Filter issues created before the date')
890 quarter_begin, quarter_end = get_quarter_of(datetime.today() -
891 relativedelta(months=2))
892 parser.add_option(
893 '-Q', '--last_quarter', action='store_true',
894 help='Use last quarter\'s dates, e.g. %s to %s' % (
895 quarter_begin.strftime('%Y-%m-%d'), quarter_end.strftime('%Y-%m-%d')))
896 parser.add_option(
897 '-Y', '--this_year', action='store_true',
898 help='Use this year\'s dates')
899 parser.add_option(
900 '-w', '--week_of', metavar='<date>',
901 help='Show issues for week of the date')
902 parser.add_option(
903 '-a', '--auth',
904 action='store_true',
905 help='Ask to authenticate for instances with no auth cookie')
906
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000907 activity_types_group = optparse.OptionGroup(parser, 'Activity Types',
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000908 'By default, all activity will be looked up and '
909 'printed. If any of these are specified, only '
910 'those specified will be searched.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000911 activity_types_group.add_option(
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000912 '-c', '--changes',
913 action='store_true',
914 help='Show changes.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000915 activity_types_group.add_option(
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000916 '-i', '--issues',
917 action='store_true',
918 help='Show issues.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000919 activity_types_group.add_option(
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000920 '-r', '--reviews',
921 action='store_true',
922 help='Show reviews.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000923 parser.add_option_group(activity_types_group)
924
925 output_format_group = optparse.OptionGroup(parser, 'Output Format',
926 'By default, all activity will be printed in the '
927 'following format: {url} {title}. This can be '
928 'changed for either all activity types or '
929 'individually for each activity type. The format '
930 'is defined as documented for '
931 'string.format(...). The variables available for '
932 'all activity types are url, title and author. '
933 'Format options for specific activity types will '
934 'override the generic format.')
935 output_format_group.add_option(
936 '-f', '--output-format', metavar='<format>',
937 default=u'{url} {title}',
938 help='Specifies the format to use when printing all your activity.')
939 output_format_group.add_option(
940 '--output-format-changes', metavar='<format>',
941 default=None,
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000942 help='Specifies the format to use when printing changes. Supports the '
943 'additional variable {reviewers}')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000944 output_format_group.add_option(
945 '--output-format-issues', metavar='<format>',
946 default=None,
cjhopman@chromium.org53c1e562013-03-11 20:02:38 +0000947 help='Specifies the format to use when printing issues. Supports the '
948 'additional variable {owner}.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000949 output_format_group.add_option(
950 '--output-format-reviews', metavar='<format>',
951 default=None,
952 help='Specifies the format to use when printing reviews.')
953 parser.add_option_group(output_format_group)
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000954
955 # Remove description formatting
956 parser.format_description = (
957 lambda _: parser.description) # pylint: disable=E1101
958
959 options, args = parser.parse_args()
960 options.local_user = os.environ.get('USER')
961 if args:
962 parser.error('Args unsupported')
963 if not options.user:
964 parser.error('USER is not set, please use -u')
965
966 options.user = username(options.user)
967
968 if not options.begin:
969 if options.last_quarter:
970 begin, end = quarter_begin, quarter_end
971 elif options.this_year:
972 begin, end = get_year_of(datetime.today())
973 elif options.week_of:
974 begin, end = (get_week_of(datetime.strptime(options.week_of, '%m/%d/%y')))
975 else:
976 begin, end = (get_week_of(datetime.today() - timedelta(days=1)))
977 else:
978 begin = datetime.strptime(options.begin, '%m/%d/%y')
979 if options.end:
980 end = datetime.strptime(options.end, '%m/%d/%y')
981 else:
982 end = datetime.today()
983 options.begin, options.end = begin, end
984
985 print 'Searching for activity by %s' % options.user
986 print 'Using range %s to %s' % (options.begin, options.end)
987
988 my_activity = MyActivity(options)
989
990 if not (options.changes or options.reviews or options.issues):
991 options.changes = True
992 options.issues = True
993 options.reviews = True
994
995 # First do any required authentication so none of the user interaction has to
996 # wait for actual work.
997 if options.changes:
998 my_activity.auth_for_changes()
999 if options.reviews:
1000 my_activity.auth_for_reviews()
1001 if options.issues:
1002 my_activity.auth_for_issues()
1003
1004 print 'Looking up activity.....'
1005
1006 if options.changes:
1007 my_activity.get_changes()
1008 if options.reviews:
1009 my_activity.get_reviews()
1010 if options.issues:
1011 my_activity.get_issues()
1012
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +00001013 my_activity.process_activities()
1014
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +00001015 print '\n\n\n'
1016
1017 my_activity.print_changes()
1018 my_activity.print_reviews()
1019 my_activity.print_issues()
1020 return 0
1021
1022
1023if __name__ == '__main__':
1024 sys.exit(main())