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