blob: ecce01d0ab4f3b2e5881a00dc3887450c0081802 [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
349 ret['reviewers'] = set(username(r) for r in issue['reviewers'])
350
351 shorturl = instance['url']
352 if 'shorturl' in instance:
353 shorturl = instance['shorturl']
354
355 ret['review_url'] = 'http://%s/%d' % (shorturl, issue['issue'])
356 ret['header'] = issue['description'].split('\n')[0]
357
358 ret['modified'] = datetime_from_rietveld(issue['modified'])
359 ret['created'] = datetime_from_rietveld(issue['created'])
360 ret['replies'] = self.process_rietveld_replies(issue['messages'])
361
362 return ret
363
364 @staticmethod
365 def process_rietveld_replies(replies):
366 ret = []
367 for reply in replies:
368 r = {}
369 r['author'] = reply['sender']
370 r['created'] = datetime_from_rietveld(reply['date'])
371 r['content'] = ''
372 ret.append(r)
373 return ret
374
375 def gerrit_search(self, instance, owner=None, reviewer=None):
376 max_age = datetime.today() - self.modified_after
377 max_age = max_age.days * 24 * 3600 + max_age.seconds
378
379 # See https://review.openstack.org/Documentation/cmd-query.html
380 # Gerrit doesn't allow filtering by created time, only modified time.
381 user_filter = 'owner:%s' % owner if owner else 'reviewer:%s' % reviewer
382 gquery_cmd = ['ssh', '-p', str(instance['port']), instance['url'],
383 'gerrit', 'query',
384 '--format', 'JSON',
385 '--comments',
386 '--',
387 '-age:%ss' % str(max_age),
388 user_filter]
389 [stdout, _] = subprocess.Popen(gquery_cmd, stdout=subprocess.PIPE,
390 stderr=subprocess.PIPE).communicate()
391 issues = str(stdout).split('\n')[:-2]
392 issues = map(json.loads, issues)
393
394 # TODO(cjhopman): should we filter abandoned changes?
395 issues = map(self.process_gerrit_issue, issues)
396 issues = filter(self.filter_issue, issues)
397 issues = sorted(issues, key=lambda i: i['modified'], reverse=True)
398
399 return issues
400
401 def process_gerrit_issue(self, issue):
402 ret = {}
403 ret['review_url'] = issue['url']
404 ret['header'] = issue['subject']
405 ret['owner'] = issue['owner']['email']
406 ret['author'] = ret['owner']
407 ret['created'] = datetime.fromtimestamp(issue['createdOn'])
408 ret['modified'] = datetime.fromtimestamp(issue['lastUpdated'])
409 if 'comments' in issue:
410 ret['replies'] = self.process_gerrit_issue_replies(issue['comments'])
411 else:
412 ret['replies'] = []
413 return ret
414
415 @staticmethod
416 def process_gerrit_issue_replies(replies):
417 ret = []
418 replies = filter(lambda r: 'email' in r['reviewer'], replies)
419 for reply in replies:
420 r = {}
421 r['author'] = reply['reviewer']['email']
422 r['created'] = datetime.fromtimestamp(reply['timestamp'])
423 r['content'] = ''
424 ret.append(r)
425 return ret
426
427 def google_code_issue_search(self, instance):
428 time_format = '%Y-%m-%dT%T'
429 # See http://code.google.com/p/support/wiki/IssueTrackerAPI
430 # q=<owner>@chromium.org does a full text search for <owner>@chromium.org.
431 # This will accept the issue if owner is the owner or in the cc list. Might
432 # have some false positives, though.
433
434 # Don't filter normally on modified_before because it can filter out things
435 # that were modified in the time period and then modified again after it.
436 gcode_url = ('https://code.google.com/feeds/issues/p/%s/issues/full' %
437 instance['name'])
438
439 gcode_data = urllib.urlencode({
440 'alt': 'json',
441 'max-results': '100000',
442 'q': '%s' % self.user,
443 'published-max': self.modified_before.strftime(time_format),
444 'updated-min': self.modified_after.strftime(time_format),
445 })
446
447 opener = urllib2.build_opener()
cjhopman@chromium.org3365f2d2012-11-01 18:53:13 +0000448 if self.google_code_auth_token:
449 opener.addheaders = [('Authorization', 'GoogleLogin auth=%s' %
450 self.google_code_auth_token)]
451 gcode_json = None
452 try:
453 gcode_get = opener.open(gcode_url + '?' + gcode_data)
454 gcode_json = json.load(gcode_get)
455 gcode_get.close()
456 except urllib2.HTTPError, _:
457 print 'Unable to access ' + instance['name'] + ' issue tracker.'
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000458
cjhopman@chromium.org3365f2d2012-11-01 18:53:13 +0000459 if not gcode_json or 'entry' not in gcode_json['feed']:
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000460 return []
461
462 issues = gcode_json['feed']['entry']
463 issues = map(partial(self.process_google_code_issue, instance), issues)
464 issues = filter(self.filter_issue, issues)
465 issues = sorted(issues, key=lambda i: i['modified'], reverse=True)
466 return issues
467
468 def process_google_code_issue(self, project, issue):
469 ret = {}
470 ret['created'] = datetime_from_google_code(issue['published']['$t'])
471 ret['modified'] = datetime_from_google_code(issue['updated']['$t'])
472
473 ret['owner'] = ''
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000474 if 'issues$owner' in issue:
475 ret['owner'] = issue['issues$owner']['issues$username']['$t']
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000476 ret['author'] = issue['author'][0]['name']['$t']
477
478 if 'shorturl' in project:
479 issue_id = issue['id']['$t']
480 issue_id = issue_id[issue_id.rfind('/') + 1:]
481 ret['url'] = 'http://%s/%d' % (project['shorturl'], int(issue_id))
482 else:
483 issue_url = issue['link'][1]
484 if issue_url['rel'] != 'alternate':
485 raise RuntimeError
486 ret['url'] = issue_url['href']
487 ret['header'] = issue['title']['$t']
488
489 ret['replies'] = self.get_google_code_issue_replies(issue)
490 return ret
491
492 def get_google_code_issue_replies(self, issue):
493 """Get all the comments on the issue."""
494 replies_url = issue['link'][0]
495 if replies_url['rel'] != 'replies':
496 raise RuntimeError
497
498 replies_data = urllib.urlencode({
499 'alt': 'json',
500 'fields': 'entry(published,author,content)',
501 })
502
503 opener = urllib2.build_opener()
504 opener.addheaders = [('Authorization', 'GoogleLogin auth=%s' %
505 self.google_code_auth_token)]
506 try:
507 replies_get = opener.open(replies_url['href'] + '?' + replies_data)
508 except urllib2.HTTPError, _:
509 return []
510
511 replies_json = json.load(replies_get)
512 replies_get.close()
513 return self.process_google_code_issue_replies(replies_json)
514
515 @staticmethod
516 def process_google_code_issue_replies(replies):
517 if 'entry' not in replies['feed']:
518 return []
519
520 ret = []
521 for entry in replies['feed']['entry']:
522 e = {}
523 e['created'] = datetime_from_google_code(entry['published']['$t'])
524 e['content'] = entry['content']['$t']
525 e['author'] = entry['author'][0]['name']['$t']
526 ret.append(e)
527 return ret
528
529 @staticmethod
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000530 def git_cmd(repo, *args):
531 cmd = ['git', '--git-dir=%s/.git' % repo]
532 cmd.extend(args)
533 [stdout, _] = subprocess.Popen(cmd, stdout=subprocess.PIPE,
534 stderr=subprocess.PIPE).communicate()
535 lines = str(stdout).split('\n')[:-1]
536 return lines
537
538 def git_search(self, instance, owner=None, reviewer=None):
539 repo = getattr(self, instance['option'])
540 if not repo:
541 return []
542
543 search = []
544 if owner:
545 search.extend(instance['owner_search_func'](owner))
546 if reviewer:
547 search.extend(instance['reviewer_search_func'](reviewer))
548 if not len(search):
549 return []
550
551 self.git_cmd(repo, 'fetch', 'origin')
552
553 time_format = '%Y-%m-%d %H:%M:%S'
554 log_args = [
555 '--after=' + self.modified_after.strftime(time_format),
556 '--before=' + self.modified_before.strftime(time_format),
557 '--format=%H'
558 ]
559 commits = set()
560 for query in search:
561 query_args = [query]
562 query_args.extend(log_args)
563 commits |= set(self.git_cmd(repo, 'log', 'origin/master', *query_args))
564
565 ret = []
566 for commit in commits:
567 output = self.git_cmd(repo, 'log', commit + "^!", "--format=%cn%n%cd%n%B")
568 author = output[0]
569 date = datetime.strptime(output[1], "%a %b %d %H:%M:%S %Y +0000")
570 ret.append(self.process_git_commit(instance, author, date, output[2:]))
571
572 ret = sorted(ret, key=lambda i: i['modified'], reverse=True)
573 return ret
574
575 @staticmethod
576 def process_git_commit(instance, author, date, log):
577 ret = {}
578 ret['owner'] = author
579 ret['author'] = author
580 ret['modified'] = date
581 ret['created'] = date
582 ret['header'] = log[0]
583
584 reviews = []
585 reviewers = []
586 changes = []
587
588 for line in log:
589 match = re.match(r'Reviewed by ([^.]*)', line)
590 if match:
591 reviewers.append(match.group(1))
592 if instance['review_re']:
593 match = re.match(instance['review_re'], line)
594 if match:
595 reviews.append(int(match.group(1)))
596 if instance['change_re']:
597 match = re.match(instance['change_re'], line)
598 if match:
599 changes.append(int(match.group(1)))
600
601 # TODO(enne): should convert full names to usernames via CommitterList.
602 ret['reviewers'] = set(reviewers)
603
604 # Reviews more useful than change link itself, but tricky if multiple
605 # Reviews == bugs for WebKit changes
606 if len(reviews) == 1:
607 url = 'http://%s/%d' % (instance['review_url'], reviews[0])
608 if instance['review_prop']:
609 ret[instance['review_prop']] = reviews[0]
610 else:
611 url = 'http://%s/%d' % (instance['change_url'], changes[0])
612 ret['review_url'] = url
613
614 return ret
615
616 def bugzilla_issues(self, instance, user):
617 if instance['user_func']:
618 user = instance['user_func'](user)
619 if not user:
620 return []
621
622 # This search is a little iffy, as it returns any bug that has been
623 # modified over a time period in any way and that a user has ever commented
624 # on, but that's the best that Bugzilla can get us. Oops.
625 commented = { 'emaillongdesc1': 1 }
626 issues = self.bugzilla_search(instance, user, commented)
627 issues = filter(lambda issue: issue['owner'] != user, issues)
628
629 reported = { 'emailreporter1': 1, 'chfield': '[Bug creation]' }
630 issues.extend(self.bugzilla_search(instance, user, reported))
631
632 # Remove duplicates by bug id
633 seen = {}
634 pruned = []
635 for issue in issues:
636 bug_id = issue['webkit_bug_id']
637 if bug_id in seen:
638 continue
639 seen[bug_id] = True
640 pruned.append(issue)
641
642 # Bugzilla has no modified time, so sort by id?
643 pruned = sorted(pruned, key=lambda i: i['webkit_bug_id'])
644 return issues
645
646 def bugzilla_search(self, instance, user, params):
647 time_format = '%Y-%m-%d'
648 values = {
649 'chfieldfrom': self.modified_after.strftime(time_format),
650 'chfieldto': self.modified_before.strftime(time_format),
651 'ctype': 'csv',
652 'emailtype1': 'substring',
653 'email1': '%s' % user,
654 }
655 values.update(params)
656
657 # Must be GET not POST
658 data = urllib.urlencode(values)
659 req = urllib2.Request("%s?%s" % (instance['search_url'], data))
660 response = urllib2.urlopen(req)
661 reader = csv.reader(response)
662 reader.next() # skip the header line
663
664 issues = map(partial(self.process_bugzilla_issue, instance), reader)
665 return issues
666
667 @staticmethod
668 def process_bugzilla_issue(instance, issue):
669 bug_id, owner, desc = int(issue[0]), issue[4], issue[7]
670
671 ret = {}
672 ret['owner'] = owner
673 ret['author'] = owner
674 ret['review_url'] = 'http://%s/%d' % (instance['url'], bug_id)
675 ret['url'] = ret['review_url']
676 ret['header'] = desc
677 ret['webkit_bug_id'] = bug_id
678 return ret
679
680 def setup_webkit_info(self):
681 assert(self.webkit_repo)
682 git_dir = os.path.normpath(self.webkit_repo + "/.git")
683 if not os.path.exists(git_dir):
scheib@chromium.orgb299e7c2012-11-13 21:34:34 +0000684 print "%s doesn't exist, skipping WebKit checks." % git_dir
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000685 self.webkit_repo = None
686 return
687
688 try:
689 self.git_cmd(self.webkit_repo, "fetch", "origin")
690 except subprocess.CalledProcessError:
scheib@chromium.orgb299e7c2012-11-13 21:34:34 +0000691 print "Failed to update WebKit repo, skipping WebKit checks."
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000692 self.webkit_repo = None
693 return
694
695 path = "Tools/Scripts"
696 full_path = os.path.normpath("%s/%s" % (self.options.webkit_repo, path))
697 sys.path.append(full_path)
698
699 try:
700 global webkitpy
701 webkitpy = __import__('webkitpy.common.config.committers')
702 except ImportError:
scheib@chromium.orgb299e7c2012-11-13 21:34:34 +0000703 print "Failed to import WebKit committer list, skipping WebKit checks."
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000704 self.webkit_repo = None
705 return
706
707 if not webkit_account(self.user):
708 email = self.user + "@chromium.org"
scheib@chromium.orgb299e7c2012-11-13 21:34:34 +0000709 print "No %s in committers.py, skipping WebKit checks." % email
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000710 self.webkit_repo = None
711
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000712 def print_change(self, change):
713 self.print_generic(self.options.output_format,
714 self.options.output_format_changes,
715 change['header'],
716 change['review_url'],
717 change['author'])
718
719 def print_issue(self, issue):
720 optional_values = {
721 'owner': issue['owner'],
722 }
723 self.print_generic(self.options.output_format,
724 self.options.output_format_issues,
725 issue['header'],
726 issue['url'],
727 issue['author'],
728 optional_values)
729
730 def print_review(self, review):
731 self.print_generic(self.options.output_format,
732 self.options.output_format_reviews,
733 review['header'],
734 review['review_url'],
735 review['author'])
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000736
737 @staticmethod
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000738 def print_generic(default_fmt, specific_fmt,
739 title, url, author,
740 optional_values=None):
741 output_format = specific_fmt if specific_fmt is not None else default_fmt
742 output_format = unicode(output_format)
743 required_values = {
744 'title': title,
745 'url': url,
746 'author': author,
747 }
748 # Merge required and optional values.
749 if optional_values is not None:
750 values = dict(required_values.items() + optional_values.items())
751 else:
752 values = required_values
753 print output_format.format(**values)
754
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000755
756 def filter_issue(self, issue, should_filter_by_user=True):
757 def maybe_filter_username(email):
758 return not should_filter_by_user or username(email) == self.user
759 if (maybe_filter_username(issue['author']) and
760 self.filter_modified(issue['created'])):
761 return True
762 if (maybe_filter_username(issue['owner']) and
763 (self.filter_modified(issue['created']) or
764 self.filter_modified(issue['modified']))):
765 return True
766 for reply in issue['replies']:
767 if self.filter_modified(reply['created']):
768 if not should_filter_by_user:
769 break
770 if (username(reply['author']) == self.user
771 or (self.user + '@') in reply['content']):
772 break
773 else:
774 return False
775 return True
776
777 def filter_modified(self, modified):
778 return self.modified_after < modified and modified < self.modified_before
779
780 def auth_for_changes(self):
781 #TODO(cjhopman): Move authentication check for getting changes here.
782 pass
783
784 def auth_for_reviews(self):
785 # Reviews use all the same instances as changes so no authentication is
786 # required.
787 pass
788
789 def auth_for_issues(self):
790 self.google_code_auth_token = (
791 get_auth_token(self.options.local_user + '@chromium.org'))
792
793 def get_changes(self):
794 for instance in rietveld_instances:
795 self.changes += self.rietveld_search(instance, owner=self.user)
796
797 for instance in gerrit_instances:
798 self.changes += self.gerrit_search(instance, owner=self.user)
799
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000800 for instance in git_instances:
801 self.changes += self.git_search(instance, owner=self.user)
802
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000803 def print_changes(self):
804 if self.changes:
805 print '\nChanges:'
806 for change in self.changes:
807 self.print_change(change)
808
809 def get_reviews(self):
810 for instance in rietveld_instances:
811 self.reviews += self.rietveld_search(instance, reviewer=self.user)
812
813 for instance in gerrit_instances:
814 reviews = self.gerrit_search(instance, reviewer=self.user)
815 reviews = filter(lambda r: not username(r['owner']) == self.user, reviews)
816 self.reviews += reviews
817
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000818 for instance in git_instances:
819 self.reviews += self.git_search(instance, reviewer=self.user)
820
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000821 def print_reviews(self):
822 if self.reviews:
823 print '\nReviews:'
824 for review in self.reviews:
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000825 self.print_review(review)
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000826
827 def get_issues(self):
828 for project in google_code_projects:
829 self.issues += self.google_code_issue_search(project)
830
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000831 for instance in bugzilla_instances:
832 self.issues += self.bugzilla_issues(instance, self.user)
833
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000834 def print_issues(self):
835 if self.issues:
836 print '\nIssues:'
837 for issue in self.issues:
838 self.print_issue(issue)
839
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000840 def process_activities(self):
841 # If a webkit bug was a review, don't list it as an issue.
842 ids = {}
843 for review in self.reviews + self.changes:
844 if 'webkit_bug_id' in review:
845 ids[review['webkit_bug_id']] = True
846
847 def duplicate_issue(issue):
848 if 'webkit_bug_id' not in issue:
849 return False
850 return issue['webkit_bug_id'] in ids
851
852 self.issues = filter(lambda issue: not duplicate_issue(issue), self.issues)
853
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000854 def print_activity(self):
855 self.print_changes()
856 self.print_reviews()
857 self.print_issues()
858
859
860def main():
861 # Silence upload.py.
862 rietveld.upload.verbosity = 0
863
864 parser = optparse.OptionParser(description=sys.modules[__name__].__doc__)
865 parser.add_option(
866 '-u', '--user', metavar='<email>',
867 default=os.environ.get('USER'),
868 help='Filter on user, default=%default')
869 parser.add_option(
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +0000870 '--webkit_repo', metavar='<dir>',
871 default='%s' % os.environ.get('WEBKIT_DIR'),
872 help='Local path to WebKit repository, default=%default')
873 parser.add_option(
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000874 '-b', '--begin', metavar='<date>',
875 help='Filter issues created after the date')
876 parser.add_option(
877 '-e', '--end', metavar='<date>',
878 help='Filter issues created before the date')
879 quarter_begin, quarter_end = get_quarter_of(datetime.today() -
880 relativedelta(months=2))
881 parser.add_option(
882 '-Q', '--last_quarter', action='store_true',
883 help='Use last quarter\'s dates, e.g. %s to %s' % (
884 quarter_begin.strftime('%Y-%m-%d'), quarter_end.strftime('%Y-%m-%d')))
885 parser.add_option(
886 '-Y', '--this_year', action='store_true',
887 help='Use this year\'s dates')
888 parser.add_option(
889 '-w', '--week_of', metavar='<date>',
890 help='Show issues for week of the date')
891 parser.add_option(
892 '-a', '--auth',
893 action='store_true',
894 help='Ask to authenticate for instances with no auth cookie')
895
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000896 activity_types_group = optparse.OptionGroup(parser, 'Activity Types',
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000897 'By default, all activity will be looked up and '
898 'printed. If any of these are specified, only '
899 'those specified will be searched.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000900 activity_types_group.add_option(
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000901 '-c', '--changes',
902 action='store_true',
903 help='Show changes.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000904 activity_types_group.add_option(
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000905 '-i', '--issues',
906 action='store_true',
907 help='Show issues.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000908 activity_types_group.add_option(
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000909 '-r', '--reviews',
910 action='store_true',
911 help='Show reviews.')
nyquist@chromium.org18bc90d2012-12-20 19:26:47 +0000912 parser.add_option_group(activity_types_group)
913
914 output_format_group = optparse.OptionGroup(parser, 'Output Format',
915 'By default, all activity will be printed in the '
916 'following format: {url} {title}. This can be '
917 'changed for either all activity types or '
918 'individually for each activity type. The format '
919 'is defined as documented for '
920 'string.format(...). The variables available for '
921 'all activity types are url, title and author. '
922 'Format options for specific activity types will '
923 'override the generic format.')
924 output_format_group.add_option(
925 '-f', '--output-format', metavar='<format>',
926 default=u'{url} {title}',
927 help='Specifies the format to use when printing all your activity.')
928 output_format_group.add_option(
929 '--output-format-changes', metavar='<format>',
930 default=None,
931 help='Specifies the format to use when printing changes.')
932 output_format_group.add_option(
933 '--output-format-issues', metavar='<format>',
934 default=None,
935 help='Specifies the format to use when printing issues. Has support '
936 'for the additional variable owner.')
937 output_format_group.add_option(
938 '--output-format-reviews', metavar='<format>',
939 default=None,
940 help='Specifies the format to use when printing reviews.')
941 parser.add_option_group(output_format_group)
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +0000942
943 # Remove description formatting
944 parser.format_description = (
945 lambda _: parser.description) # pylint: disable=E1101
946
947 options, args = parser.parse_args()
948 options.local_user = os.environ.get('USER')
949 if args:
950 parser.error('Args unsupported')
951 if not options.user:
952 parser.error('USER is not set, please use -u')
953
954 options.user = username(options.user)
955
956 if not options.begin:
957 if options.last_quarter:
958 begin, end = quarter_begin, quarter_end
959 elif options.this_year:
960 begin, end = get_year_of(datetime.today())
961 elif options.week_of:
962 begin, end = (get_week_of(datetime.strptime(options.week_of, '%m/%d/%y')))
963 else:
964 begin, end = (get_week_of(datetime.today() - timedelta(days=1)))
965 else:
966 begin = datetime.strptime(options.begin, '%m/%d/%y')
967 if options.end:
968 end = datetime.strptime(options.end, '%m/%d/%y')
969 else:
970 end = datetime.today()
971 options.begin, options.end = begin, end
972
973 print 'Searching for activity by %s' % options.user
974 print 'Using range %s to %s' % (options.begin, options.end)
975
976 my_activity = MyActivity(options)
977
978 if not (options.changes or options.reviews or options.issues):
979 options.changes = True
980 options.issues = True
981 options.reviews = True
982
983 # First do any required authentication so none of the user interaction has to
984 # wait for actual work.
985 if options.changes:
986 my_activity.auth_for_changes()
987 if options.reviews:
988 my_activity.auth_for_reviews()
989 if options.issues:
990 my_activity.auth_for_issues()
991
992 print 'Looking up activity.....'
993
994 if options.changes:
995 my_activity.get_changes()
996 if options.reviews:
997 my_activity.get_reviews()
998 if options.issues:
999 my_activity.get_issues()
1000
enne@chromium.orgcb55d8a2012-11-06 01:11:40 +00001001 my_activity.process_activities()
1002
cjhopman@chromium.org04d119d2012-10-17 22:41:53 +00001003 print '\n\n\n'
1004
1005 my_activity.print_changes()
1006 my_activity.print_reviews()
1007 my_activity.print_issues()
1008 return 0
1009
1010
1011if __name__ == '__main__':
1012 sys.exit(main())