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