my_activity.py 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  1. #!/usr/bin/env vpython3
  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. """Get stats about your activity.
  6. Example:
  7. - my_activity.py for stats for the current week (last week on mondays).
  8. - my_activity.py -Q for stats for last quarter.
  9. - my_activity.py -Y for stats for this year.
  10. - my_activity.py -b 4/24/19 for stats since April 24th 2019.
  11. - my_activity.py -b 4/24/19 -e 6/16/19 stats between April 24th and June 16th.
  12. - my_activity.py -jd to output stats for the week to json with deltas data.
  13. To add additional gerrit instances, one can pass a JSON file as parameter:
  14. - my_activity.py -F config.json
  15. {
  16. "gerrit_instances": {
  17. "team-internal-review.googlesource.com": {
  18. "shorturl": "go/teamcl",
  19. "short_url_protocol": "http"
  20. },
  21. "team-external-review.googlesource.com": {}
  22. }
  23. }
  24. """
  25. # These services typically only provide a created time and a last modified time
  26. # for each item for general queries. This is not enough to determine if there
  27. # was activity in a given time period. So, we first query for all things created
  28. # before end and modified after begin. Then, we get the details of each item and
  29. # check those details to determine if there was activity in the given period.
  30. # This means that query time scales mostly with (today() - begin).
  31. import collections
  32. import contextlib
  33. from datetime import datetime
  34. from datetime import timedelta
  35. import httplib2
  36. import itertools
  37. import json
  38. import logging
  39. from multiprocessing.pool import ThreadPool
  40. import optparse
  41. import os
  42. from string import Formatter
  43. import sys
  44. import urllib
  45. import re
  46. import auth
  47. import fix_encoding
  48. import gclient_utils
  49. import gerrit_util
  50. if sys.version_info.major == 2:
  51. logging.critical(
  52. 'Python 2 is not supported. Run my_activity.py using vpython3.')
  53. try:
  54. import dateutil # pylint: disable=import-error
  55. import dateutil.parser
  56. from dateutil.relativedelta import relativedelta
  57. except ImportError:
  58. logging.error('python-dateutil package required')
  59. sys.exit(1)
  60. class DefaultFormatter(Formatter):
  61. def __init__(self, default=''):
  62. super(DefaultFormatter, self).__init__()
  63. self.default = default
  64. def get_value(self, key, args, kwargs):
  65. if isinstance(key, str) and key not in kwargs:
  66. return self.default
  67. return Formatter.get_value(self, key, args, kwargs)
  68. gerrit_instances = [
  69. {
  70. 'url': 'android-review.googlesource.com',
  71. 'shorturl': 'r.android.com',
  72. 'short_url_protocol': 'https',
  73. },
  74. {
  75. 'url': 'gerrit-review.googlesource.com',
  76. },
  77. {
  78. 'url': 'chrome-internal-review.googlesource.com',
  79. 'shorturl': 'crrev.com/i',
  80. 'short_url_protocol': 'https',
  81. },
  82. {
  83. 'url': 'chromium-review.googlesource.com',
  84. 'shorturl': 'crrev.com/c',
  85. 'short_url_protocol': 'https',
  86. },
  87. {
  88. 'url': 'dawn-review.googlesource.com',
  89. },
  90. {
  91. 'url': 'pdfium-review.googlesource.com',
  92. },
  93. {
  94. 'url': 'skia-review.googlesource.com',
  95. },
  96. {
  97. 'url': 'review.coreboot.org',
  98. },
  99. ]
  100. monorail_projects = {
  101. 'angleproject': {
  102. 'shorturl': 'anglebug.com',
  103. 'short_url_protocol': 'http',
  104. },
  105. 'chromium': {
  106. 'shorturl': 'crbug.com',
  107. 'short_url_protocol': 'https',
  108. },
  109. 'dawn': {},
  110. 'google-breakpad': {},
  111. 'gyp': {},
  112. 'pdfium': {
  113. 'shorturl': 'crbug.com/pdfium',
  114. 'short_url_protocol': 'https',
  115. },
  116. 'skia': {},
  117. 'tint': {},
  118. 'v8': {
  119. 'shorturl': 'crbug.com/v8',
  120. 'short_url_protocol': 'https',
  121. },
  122. }
  123. def username(email):
  124. """Keeps the username of an email address."""
  125. return email and email.split('@', 1)[0]
  126. def datetime_to_midnight(date):
  127. return date - timedelta(hours=date.hour,
  128. minutes=date.minute,
  129. seconds=date.second,
  130. microseconds=date.microsecond)
  131. def get_quarter_of(date):
  132. begin = (datetime_to_midnight(date) -
  133. relativedelta(months=(date.month - 1) % 3, days=(date.day - 1)))
  134. return begin, begin + relativedelta(months=3)
  135. def get_year_of(date):
  136. begin = (datetime_to_midnight(date) -
  137. relativedelta(months=(date.month - 1), days=(date.day - 1)))
  138. return begin, begin + relativedelta(years=1)
  139. def get_week_of(date):
  140. begin = (datetime_to_midnight(date) - timedelta(days=date.weekday()))
  141. return begin, begin + timedelta(days=7)
  142. def get_yes_or_no(msg):
  143. while True:
  144. response = gclient_utils.AskForData(msg + ' yes/no [no] ')
  145. if response in ('y', 'yes'):
  146. return True
  147. if not response or response in ('n', 'no'):
  148. return False
  149. def datetime_from_gerrit(date_string):
  150. return datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S.%f000')
  151. def datetime_from_monorail(date_string):
  152. return datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S')
  153. def extract_bug_numbers_from_description(issue):
  154. # Getting the description for REST Gerrit
  155. revision = issue['revisions'][issue['current_revision']]
  156. description = revision['commit']['message']
  157. bugs = []
  158. # Handle both "Bug: 99999" and "BUG=99999" bug notations
  159. # Multiple bugs can be noted on a single line or in multiple ones.
  160. matches = re.findall(
  161. r'^(BUG=|(Bug|Fixed):\s*)((((?:[a-zA-Z0-9-]+:)?\d+)(,\s?)?)+)',
  162. description,
  163. flags=re.IGNORECASE | re.MULTILINE)
  164. if matches:
  165. for match in matches:
  166. bugs.extend(match[2].replace(' ', '').split(','))
  167. # Add default chromium: prefix if none specified.
  168. bugs = [bug if ':' in bug else 'chromium:%s' % bug for bug in bugs]
  169. return sorted(set(bugs))
  170. class MyActivity(object):
  171. def __init__(self, options):
  172. self.options = options
  173. self.modified_after = options.begin
  174. self.modified_before = options.end
  175. self.user = options.user
  176. self.changes = []
  177. self.reviews = []
  178. self.issues = []
  179. self.referenced_issues = []
  180. self.google_code_auth_token = None
  181. self.access_errors = set()
  182. self.skip_servers = (options.skip_servers.split(','))
  183. def show_progress(self, how='.'):
  184. if sys.stdout.isatty():
  185. sys.stdout.write(how)
  186. sys.stdout.flush()
  187. def gerrit_changes_over_rest(self, instance, filters):
  188. # Convert the "key:value" filter to a list of (key, value) pairs.
  189. req = list(f.split(':', 1) for f in filters)
  190. try:
  191. # Instantiate the generator to force all the requests now and catch
  192. # the errors here.
  193. return list(
  194. gerrit_util.GenerateAllChanges(instance['url'],
  195. req,
  196. o_params=[
  197. 'MESSAGES', 'LABELS',
  198. 'DETAILED_ACCOUNTS',
  199. 'CURRENT_REVISION',
  200. 'CURRENT_COMMIT'
  201. ]))
  202. except gerrit_util.GerritError as e:
  203. error_message = 'Looking up %r: %s' % (instance['url'], e)
  204. if error_message not in self.access_errors:
  205. self.access_errors.add(error_message)
  206. return []
  207. def gerrit_search(self, instance, owner=None, reviewer=None):
  208. if instance['url'] in self.skip_servers:
  209. return []
  210. max_age = datetime.today() - self.modified_after
  211. filters = ['-age:%ss' % (max_age.days * 24 * 3600 + max_age.seconds)]
  212. if owner:
  213. assert not reviewer
  214. filters.append('owner:%s' % owner)
  215. else:
  216. filters.extend(('-owner:%s' % reviewer, 'reviewer:%s' % reviewer))
  217. # TODO(cjhopman): Should abandoned changes be filtered out when
  218. # merged_only is not enabled?
  219. if self.options.merged_only:
  220. filters.append('status:merged')
  221. issues = self.gerrit_changes_over_rest(instance, filters)
  222. self.show_progress()
  223. issues = [
  224. self.process_gerrit_issue(instance, issue) for issue in issues
  225. ]
  226. issues = filter(self.filter_issue, issues)
  227. issues = sorted(issues, key=lambda i: i['modified'], reverse=True)
  228. return issues
  229. def process_gerrit_issue(self, instance, issue):
  230. ret = {}
  231. if self.options.deltas:
  232. ret['delta'] = DefaultFormatter().format(
  233. '+{insertions},-{deletions}', **issue)
  234. ret['status'] = issue['status']
  235. if 'shorturl' in instance:
  236. protocol = instance.get('short_url_protocol', 'http')
  237. url = instance['shorturl']
  238. else:
  239. protocol = 'https'
  240. url = instance['url']
  241. ret['review_url'] = '%s://%s/%s' % (protocol, url, issue['_number'])
  242. ret['header'] = issue['subject']
  243. ret['owner'] = issue['owner'].get('email', '')
  244. ret['author'] = ret['owner']
  245. ret['created'] = datetime_from_gerrit(issue['created'])
  246. ret['modified'] = datetime_from_gerrit(issue['updated'])
  247. if 'messages' in issue:
  248. ret['replies'] = self.process_gerrit_issue_replies(
  249. issue['messages'])
  250. else:
  251. ret['replies'] = []
  252. ret['reviewers'] = set(r['author'] for r in ret['replies'])
  253. ret['reviewers'].discard(ret['author'])
  254. ret['bugs'] = extract_bug_numbers_from_description(issue)
  255. return ret
  256. @staticmethod
  257. def process_gerrit_issue_replies(replies):
  258. ret = []
  259. replies = filter(lambda r: 'author' in r and 'email' in r['author'],
  260. replies)
  261. for reply in replies:
  262. ret.append({
  263. 'author': reply['author']['email'],
  264. 'created': datetime_from_gerrit(reply['date']),
  265. 'content': reply['message'],
  266. })
  267. return ret
  268. def monorail_get_auth_http(self):
  269. # Manually use a long timeout (10m); for some users who have a
  270. # long history on the issue tracker, whatever the default timeout
  271. # is is reached.
  272. return auth.Authenticator().authorize(httplib2.Http(timeout=600))
  273. def filter_modified_monorail_issue(self, issue):
  274. """Precisely checks if an issue has been modified in the time range.
  275. This fetches all issue comments to check if the issue has been modified in
  276. the time range specified by user. This is needed because monorail only
  277. allows filtering by last updated and published dates, which is not
  278. sufficient to tell whether a given issue has been modified at some specific
  279. time range. Any update to the issue is a reported as comment on Monorail.
  280. Args:
  281. issue: Issue dict as returned by monorail_query_issues method. In
  282. particular, must have a key 'uid' formatted as 'project:issue_id'.
  283. Returns:
  284. Passed issue if modified, None otherwise.
  285. """
  286. http = self.monorail_get_auth_http()
  287. project, issue_id = issue['uid'].split(':')
  288. url = ('https://monorail-prod.appspot.com/_ah/api/monorail/v1/projects'
  289. '/%s/issues/%s/comments?maxResults=10000') % (project, issue_id)
  290. _, body = http.request(url)
  291. self.show_progress()
  292. content = json.loads(body)
  293. if not content:
  294. logging.error('Unable to parse %s response from monorail.', project)
  295. return issue
  296. for item in content.get('items', []):
  297. comment_published = datetime_from_monorail(item['published'])
  298. if self.filter_modified(comment_published):
  299. return issue
  300. return None
  301. def monorail_query_issues(self, project, query):
  302. http = self.monorail_get_auth_http()
  303. url = ('https://monorail-prod.appspot.com/_ah/api/monorail/v1/projects'
  304. '/%s/issues') % project
  305. query_data = urllib.parse.urlencode(query)
  306. url = url + '?' + query_data
  307. _, body = http.request(url)
  308. self.show_progress()
  309. content = json.loads(body)
  310. if not content:
  311. logging.error('Unable to parse %s response from monorail.', project)
  312. return []
  313. issues = []
  314. project_config = monorail_projects.get(project, {})
  315. for item in content.get('items', []):
  316. if project_config.get('shorturl'):
  317. protocol = project_config.get('short_url_protocol', 'http')
  318. item_url = '%s://%s/%d' % (protocol, project_config['shorturl'],
  319. item['id'])
  320. else:
  321. item_url = (
  322. 'https://bugs.chromium.org/p/%s/issues/detail?id=%d' %
  323. (project, item['id']))
  324. issue = {
  325. 'uid': '%s:%s' % (project, item['id']),
  326. 'header': item['title'],
  327. 'created': datetime_from_monorail(item['published']),
  328. 'modified': datetime_from_monorail(item['updated']),
  329. 'author': item['author']['name'],
  330. 'url': item_url,
  331. 'comments': [],
  332. 'status': item['status'],
  333. 'labels': [],
  334. 'components': []
  335. }
  336. if 'owner' in item:
  337. issue['owner'] = item['owner']['name']
  338. else:
  339. issue['owner'] = 'None'
  340. if 'labels' in item:
  341. issue['labels'] = item['labels']
  342. if 'components' in item:
  343. issue['components'] = item['components']
  344. issues.append(issue)
  345. return issues
  346. def monorail_issue_search(self, project):
  347. epoch = datetime.utcfromtimestamp(0)
  348. # Defaults to @chromium.org email if one wasn't provided on -u option.
  349. user_str = (self.options.email if self.options.email.find('@') >= 0 else
  350. '%s@chromium.org' % self.user)
  351. issues = self.monorail_query_issues(
  352. project, {
  353. 'maxResults':
  354. 10000,
  355. 'q':
  356. user_str,
  357. 'publishedMax':
  358. '%d' % (self.modified_before - epoch).total_seconds(),
  359. 'updatedMin':
  360. '%d' % (self.modified_after - epoch).total_seconds(),
  361. })
  362. if self.options.completed_issues:
  363. return [
  364. issue for issue in issues
  365. if (self.match(issue['owner']) and issue['status'].lower() in (
  366. 'verified', 'fixed'))
  367. ]
  368. return [
  369. issue for issue in issues
  370. if user_str in (issue['author'], issue['owner'])
  371. ]
  372. def monorail_get_issues(self, project, issue_ids):
  373. return self.monorail_query_issues(project, {
  374. 'maxResults': 10000,
  375. 'q': 'id:%s' % ','.join(issue_ids)
  376. })
  377. def print_heading(self, heading):
  378. print()
  379. print(self.options.output_format_heading.format(heading=heading))
  380. def match(self, author):
  381. if '@' in self.user:
  382. return author == self.user
  383. return author.startswith(self.user + '@')
  384. def print_change(self, change):
  385. activity = len([
  386. reply for reply in change['replies'] if self.match(reply['author'])
  387. ])
  388. optional_values = {
  389. 'created': change['created'].date().isoformat(),
  390. 'modified': change['modified'].date().isoformat(),
  391. 'reviewers': ', '.join(change['reviewers']),
  392. 'status': change['status'],
  393. 'activity': activity,
  394. }
  395. if self.options.deltas:
  396. optional_values['delta'] = change['delta']
  397. self.print_generic(self.options.output_format,
  398. self.options.output_format_changes, change['header'],
  399. change['review_url'], change['author'],
  400. change['created'], change['modified'],
  401. optional_values)
  402. def print_issue(self, issue):
  403. optional_values = {
  404. 'created': issue['created'].date().isoformat(),
  405. 'modified': issue['modified'].date().isoformat(),
  406. 'owner': issue['owner'],
  407. 'status': issue['status'],
  408. }
  409. self.print_generic(self.options.output_format,
  410. self.options.output_format_issues, issue['header'],
  411. issue['url'], issue['author'], issue['created'],
  412. issue['modified'], optional_values)
  413. def print_review(self, review):
  414. activity = len([
  415. reply for reply in review['replies'] if self.match(reply['author'])
  416. ])
  417. optional_values = {
  418. 'created': review['created'].date().isoformat(),
  419. 'modified': review['modified'].date().isoformat(),
  420. 'status': review['status'],
  421. 'activity': activity,
  422. }
  423. if self.options.deltas:
  424. optional_values['delta'] = review['delta']
  425. self.print_generic(self.options.output_format,
  426. self.options.output_format_reviews, review['header'],
  427. review['review_url'], review['author'],
  428. review['created'], review['modified'],
  429. optional_values)
  430. @staticmethod
  431. def print_generic(default_fmt,
  432. specific_fmt,
  433. title,
  434. url,
  435. author,
  436. created,
  437. modified,
  438. optional_values=None):
  439. output_format = (specific_fmt
  440. if specific_fmt is not None else default_fmt)
  441. values = {
  442. 'title': title,
  443. 'url': url,
  444. 'author': author,
  445. 'created': created,
  446. 'modified': modified,
  447. }
  448. if optional_values is not None:
  449. values.update(optional_values)
  450. print(DefaultFormatter().format(output_format, **values))
  451. def filter_issue(self, issue, should_filter_by_user=True):
  452. def maybe_filter_username(email):
  453. return not should_filter_by_user or username(email) == self.user
  454. if (maybe_filter_username(issue['author'])
  455. and self.filter_modified(issue['created'])):
  456. return True
  457. if (maybe_filter_username(issue['owner'])
  458. and (self.filter_modified(issue['created'])
  459. or self.filter_modified(issue['modified']))):
  460. return True
  461. for reply in issue['replies']:
  462. if self.filter_modified(reply['created']):
  463. if not should_filter_by_user:
  464. break
  465. if (username(reply['author']) == self.user
  466. or (self.user + '@') in reply['content']):
  467. break
  468. else:
  469. return False
  470. return True
  471. def filter_modified(self, modified):
  472. return self.modified_after < modified < self.modified_before
  473. def auth_for_changes(self):
  474. #TODO(cjhopman): Move authentication check for getting changes here.
  475. pass
  476. def auth_for_reviews(self):
  477. # Reviews use all the same instances as changes so no authentication is
  478. # required.
  479. pass
  480. def get_changes(self):
  481. num_instances = len(gerrit_instances)
  482. with contextlib.closing(ThreadPool(num_instances)) as pool:
  483. gerrit_changes = pool.map_async(
  484. lambda instance: self.gerrit_search(instance, owner=self.user),
  485. gerrit_instances)
  486. gerrit_changes = itertools.chain.from_iterable(gerrit_changes.get())
  487. self.changes = list(gerrit_changes)
  488. def print_changes(self):
  489. if self.changes:
  490. self.print_heading('Changes')
  491. for change in self.changes:
  492. self.print_change(change)
  493. def print_access_errors(self):
  494. if self.access_errors:
  495. logging.error('Access Errors:')
  496. for error in self.access_errors:
  497. logging.error(error.rstrip())
  498. def get_reviews(self):
  499. num_instances = len(gerrit_instances)
  500. with contextlib.closing(ThreadPool(num_instances)) as pool:
  501. gerrit_reviews = pool.map_async(
  502. lambda instance: self.gerrit_search(instance,
  503. reviewer=self.user),
  504. gerrit_instances)
  505. gerrit_reviews = itertools.chain.from_iterable(gerrit_reviews.get())
  506. self.reviews = list(gerrit_reviews)
  507. def print_reviews(self):
  508. if self.reviews:
  509. self.print_heading('Reviews')
  510. for review in self.reviews:
  511. self.print_review(review)
  512. def get_issues(self):
  513. with contextlib.closing(ThreadPool(len(monorail_projects))) as pool:
  514. monorail_issues = pool.map(self.monorail_issue_search,
  515. monorail_projects.keys())
  516. monorail_issues = list(
  517. itertools.chain.from_iterable(monorail_issues))
  518. if not monorail_issues:
  519. return
  520. with contextlib.closing(ThreadPool(len(monorail_issues))) as pool:
  521. filtered_issues = pool.map(self.filter_modified_monorail_issue,
  522. monorail_issues)
  523. self.issues = [issue for issue in filtered_issues if issue]
  524. def get_referenced_issues(self):
  525. if not self.issues:
  526. self.get_issues()
  527. if not self.changes:
  528. self.get_changes()
  529. referenced_issue_uids = set(
  530. itertools.chain.from_iterable(change['bugs']
  531. for change in self.changes))
  532. fetched_issue_uids = set(issue['uid'] for issue in self.issues)
  533. missing_issue_uids = referenced_issue_uids - fetched_issue_uids
  534. missing_issues_by_project = collections.defaultdict(list)
  535. for issue_uid in missing_issue_uids:
  536. project, issue_id = issue_uid.split(':')
  537. missing_issues_by_project[project].append(issue_id)
  538. for project, issue_ids in missing_issues_by_project.items():
  539. self.referenced_issues += self.monorail_get_issues(
  540. project, issue_ids)
  541. def print_issues(self):
  542. if self.issues:
  543. self.print_heading('Issues')
  544. for issue in self.issues:
  545. self.print_issue(issue)
  546. def print_changes_by_issue(self, skip_empty_own):
  547. if not self.issues or not self.changes:
  548. return
  549. self.print_heading('Changes by referenced issue(s)')
  550. issues = {issue['uid']: issue for issue in self.issues}
  551. ref_issues = {issue['uid']: issue for issue in self.referenced_issues}
  552. changes_by_issue_uid = collections.defaultdict(list)
  553. changes_by_ref_issue_uid = collections.defaultdict(list)
  554. changes_without_issue = []
  555. for change in self.changes:
  556. added = False
  557. for issue_uid in change['bugs']:
  558. if issue_uid in issues:
  559. changes_by_issue_uid[issue_uid].append(change)
  560. added = True
  561. if issue_uid in ref_issues:
  562. changes_by_ref_issue_uid[issue_uid].append(change)
  563. added = True
  564. if not added:
  565. changes_without_issue.append(change)
  566. # Changes referencing own issues.
  567. for issue_uid in issues:
  568. if changes_by_issue_uid[issue_uid] or not skip_empty_own:
  569. self.print_issue(issues[issue_uid])
  570. if changes_by_issue_uid[issue_uid]:
  571. print()
  572. for change in changes_by_issue_uid[issue_uid]:
  573. print(' ', end='') # this prints no newline
  574. self.print_change(change)
  575. print()
  576. # Changes referencing others' issues.
  577. for issue_uid in ref_issues:
  578. assert changes_by_ref_issue_uid[issue_uid]
  579. self.print_issue(ref_issues[issue_uid])
  580. for change in changes_by_ref_issue_uid[issue_uid]:
  581. print('', end=' '
  582. ) # this prints one space due to comma, but no newline
  583. self.print_change(change)
  584. # Changes referencing no issues.
  585. if changes_without_issue:
  586. print(
  587. self.options.output_format_no_url.format(title='Other changes'))
  588. for change in changes_without_issue:
  589. print('', end=' '
  590. ) # this prints one space due to comma, but no newline
  591. self.print_change(change)
  592. def print_activity(self):
  593. self.print_changes()
  594. self.print_reviews()
  595. self.print_issues()
  596. def dump_json(self, ignore_keys=None):
  597. if ignore_keys is None:
  598. ignore_keys = ['replies']
  599. def format_for_json_dump(in_array):
  600. output = {}
  601. for item in in_array:
  602. url = item.get('url') or item.get('review_url')
  603. if not url:
  604. raise Exception('Dumped item %s does not specify url' %
  605. item)
  606. output[url] = dict(
  607. (k, v) for k, v in item.items() if k not in ignore_keys)
  608. return output
  609. class PythonObjectEncoder(json.JSONEncoder):
  610. def default(self, o): # pylint: disable=method-hidden
  611. if isinstance(o, datetime):
  612. return o.isoformat()
  613. if isinstance(o, set):
  614. return list(o)
  615. return json.JSONEncoder.default(self, o)
  616. output = {
  617. 'reviews': format_for_json_dump(self.reviews),
  618. 'changes': format_for_json_dump(self.changes),
  619. 'issues': format_for_json_dump(self.issues)
  620. }
  621. print(json.dumps(output, indent=2, cls=PythonObjectEncoder))
  622. def main():
  623. parser = optparse.OptionParser(description=sys.modules[__name__].__doc__)
  624. parser.add_option(
  625. '-u',
  626. '--user',
  627. metavar='<email>',
  628. # Look for USER and USERNAME (Windows) environment variables.
  629. default=os.environ.get('USER', os.environ.get('USERNAME')),
  630. help='Filter on user, default=%default')
  631. parser.add_option('-b',
  632. '--begin',
  633. metavar='<date>',
  634. help='Filter issues created after the date (mm/dd/yy)')
  635. parser.add_option('-e',
  636. '--end',
  637. metavar='<date>',
  638. help='Filter issues created before the date (mm/dd/yy)')
  639. quarter_begin, quarter_end = get_quarter_of(datetime.today() -
  640. relativedelta(months=2))
  641. parser.add_option(
  642. '-Q',
  643. '--last_quarter',
  644. action='store_true',
  645. help='Use last quarter\'s dates, i.e. %s to %s' %
  646. (quarter_begin.strftime('%Y-%m-%d'), quarter_end.strftime('%Y-%m-%d')))
  647. parser.add_option('-Y',
  648. '--this_year',
  649. action='store_true',
  650. help='Use this year\'s dates')
  651. parser.add_option('-w',
  652. '--week_of',
  653. metavar='<date>',
  654. help='Show issues for week of the date (mm/dd/yy)')
  655. parser.add_option(
  656. '-W',
  657. '--last_week',
  658. action='count',
  659. help='Show last week\'s issues. Use more times for more weeks.')
  660. parser.add_option(
  661. '-a',
  662. '--auth',
  663. action='store_true',
  664. help='Ask to authenticate for instances with no auth cookie')
  665. parser.add_option('-d',
  666. '--deltas',
  667. action='store_true',
  668. help='Fetch deltas for changes.')
  669. parser.add_option(
  670. '--no-referenced-issues',
  671. action='store_true',
  672. help='Do not fetch issues referenced by owned changes. Useful in '
  673. 'combination with --changes-by-issue when you only want to list '
  674. 'issues that have also been modified in the same time period.')
  675. parser.add_option(
  676. '--skip_servers',
  677. action='store',
  678. default='',
  679. help='A comma separated list of gerrit and rietveld servers to ignore')
  680. parser.add_option(
  681. '--skip-own-issues-without-changes',
  682. action='store_true',
  683. help='Skips listing own issues without changes when showing changes '
  684. 'grouped by referenced issue(s). See --changes-by-issue for more '
  685. 'details.')
  686. parser.add_option(
  687. '-F',
  688. '--config_file',
  689. metavar='<config_file>',
  690. help='Configuration file in JSON format, used to add additional gerrit '
  691. 'instances (see source code for an example).')
  692. activity_types_group = optparse.OptionGroup(
  693. parser, 'Activity Types',
  694. 'By default, all activity will be looked up and '
  695. 'printed. If any of these are specified, only '
  696. 'those specified will be searched.')
  697. activity_types_group.add_option('-c',
  698. '--changes',
  699. action='store_true',
  700. help='Show changes.')
  701. activity_types_group.add_option('-i',
  702. '--issues',
  703. action='store_true',
  704. help='Show issues.')
  705. activity_types_group.add_option('-r',
  706. '--reviews',
  707. action='store_true',
  708. help='Show reviews.')
  709. activity_types_group.add_option(
  710. '--changes-by-issue',
  711. action='store_true',
  712. help='Show changes grouped by referenced issue(s).')
  713. parser.add_option_group(activity_types_group)
  714. output_format_group = optparse.OptionGroup(
  715. parser, 'Output Format',
  716. 'By default, all activity will be printed in the '
  717. 'following format: {url} {title}. This can be '
  718. 'changed for either all activity types or '
  719. 'individually for each activity type. The format '
  720. 'is defined as documented for '
  721. 'string.format(...). The variables available for '
  722. 'all activity types are url, title, author, '
  723. 'created and modified. Format options for '
  724. 'specific activity types will override the '
  725. 'generic format.')
  726. output_format_group.add_option(
  727. '-f',
  728. '--output-format',
  729. metavar='<format>',
  730. default=u'{url} {title}',
  731. help='Specifies the format to use when printing all your activity.')
  732. output_format_group.add_option(
  733. '--output-format-changes',
  734. metavar='<format>',
  735. default=None,
  736. help='Specifies the format to use when printing changes. Supports the '
  737. 'additional variable {reviewers}')
  738. output_format_group.add_option(
  739. '--output-format-issues',
  740. metavar='<format>',
  741. default=None,
  742. help='Specifies the format to use when printing issues. Supports the '
  743. 'additional variable {owner}.')
  744. output_format_group.add_option(
  745. '--output-format-reviews',
  746. metavar='<format>',
  747. default=None,
  748. help='Specifies the format to use when printing reviews.')
  749. output_format_group.add_option(
  750. '--output-format-heading',
  751. metavar='<format>',
  752. default=u'{heading}:',
  753. help='Specifies the format to use when printing headings. '
  754. 'Supports the variable {heading}.')
  755. output_format_group.add_option(
  756. '--output-format-no-url',
  757. default='{title}',
  758. help='Specifies the format to use when printing activity without url.')
  759. output_format_group.add_option(
  760. '-m',
  761. '--markdown',
  762. action='store_true',
  763. help='Use markdown-friendly output (overrides --output-format '
  764. 'and --output-format-heading)')
  765. output_format_group.add_option(
  766. '-j',
  767. '--json',
  768. action='store_true',
  769. help='Output json data (overrides other format options)')
  770. parser.add_option_group(output_format_group)
  771. parser.add_option('-v',
  772. '--verbose',
  773. action='store_const',
  774. dest='verbosity',
  775. default=logging.WARN,
  776. const=logging.INFO,
  777. help='Output extra informational messages.')
  778. parser.add_option('-q',
  779. '--quiet',
  780. action='store_const',
  781. dest='verbosity',
  782. const=logging.ERROR,
  783. help='Suppress non-error messages.')
  784. parser.add_option('-M',
  785. '--merged-only',
  786. action='store_true',
  787. dest='merged_only',
  788. default=False,
  789. help='Shows only changes that have been merged.')
  790. parser.add_option(
  791. '-C',
  792. '--completed-issues',
  793. action='store_true',
  794. dest='completed_issues',
  795. default=False,
  796. help='Shows only monorail issues that have completed (Fixed|Verified) '
  797. 'by the user.')
  798. parser.add_option(
  799. '-o',
  800. '--output',
  801. metavar='<file>',
  802. help='Where to output the results. By default prints to stdout.')
  803. # Remove description formatting
  804. parser.format_description = (lambda _: parser.description) # pylint: disable=no-member
  805. options, args = parser.parse_args()
  806. options.local_user = os.environ.get('USER')
  807. if args:
  808. parser.error('Args unsupported')
  809. if not options.user:
  810. parser.error('USER/USERNAME is not set, please use -u')
  811. # Retains the original -u option as the email address.
  812. options.email = options.user
  813. options.user = username(options.email)
  814. logging.basicConfig(level=options.verbosity)
  815. # python-keyring provides easy access to the system keyring.
  816. try:
  817. import keyring # pylint: disable=unused-import,unused-variable,F0401
  818. except ImportError:
  819. logging.warning('Consider installing python-keyring')
  820. if not options.begin:
  821. if options.last_quarter:
  822. begin, end = quarter_begin, quarter_end
  823. elif options.this_year:
  824. begin, end = get_year_of(datetime.today())
  825. elif options.week_of:
  826. begin, end = (get_week_of(
  827. datetime.strptime(options.week_of, '%m/%d/%y')))
  828. elif options.last_week:
  829. begin, end = (
  830. get_week_of(datetime.today() -
  831. timedelta(days=1 + 7 * options.last_week)))
  832. else:
  833. begin, end = (get_week_of(datetime.today() - timedelta(days=1)))
  834. else:
  835. begin = dateutil.parser.parse(options.begin)
  836. if options.end:
  837. end = dateutil.parser.parse(options.end)
  838. else:
  839. end = datetime.today()
  840. options.begin, options.end = begin, end
  841. if begin >= end:
  842. # The queries fail in peculiar ways when the begin date is in the
  843. # future. Give a descriptive error message instead.
  844. logging.error(
  845. 'Start date (%s) is the same or later than end date (%s)' %
  846. (begin, end))
  847. return 1
  848. if options.markdown:
  849. options.output_format_heading = '### {heading}\n'
  850. options.output_format = ' * [{title}]({url})'
  851. options.output_format_no_url = ' * {title}'
  852. logging.info('Searching for activity by %s', options.user)
  853. logging.info('Using range %s to %s', options.begin, options.end)
  854. if options.config_file:
  855. with open(options.config_file) as f:
  856. config = json.load(f)
  857. for item, entries in config.items():
  858. if item == 'gerrit_instances':
  859. for repo, dic in entries.items():
  860. # Use property name as URL
  861. dic['url'] = repo
  862. gerrit_instances.append(dic)
  863. elif item == 'monorail_projects':
  864. monorail_projects.append(entries)
  865. else:
  866. logging.error('Invalid entry in config file.')
  867. return 1
  868. my_activity = MyActivity(options)
  869. my_activity.show_progress('Loading data')
  870. if not (options.changes or options.reviews or options.issues
  871. or options.changes_by_issue):
  872. options.changes = True
  873. options.issues = True
  874. options.reviews = True
  875. # First do any required authentication so none of the user interaction has
  876. # to wait for actual work.
  877. if options.changes or options.changes_by_issue:
  878. my_activity.auth_for_changes()
  879. if options.reviews:
  880. my_activity.auth_for_reviews()
  881. logging.info('Looking up activity.....')
  882. try:
  883. if options.changes or options.changes_by_issue:
  884. my_activity.get_changes()
  885. if options.reviews:
  886. my_activity.get_reviews()
  887. if options.issues or options.changes_by_issue:
  888. my_activity.get_issues()
  889. if not options.no_referenced_issues:
  890. my_activity.get_referenced_issues()
  891. except auth.LoginRequiredError as e:
  892. logging.error('auth.LoginRequiredError: %s', e)
  893. my_activity.show_progress('\n')
  894. my_activity.print_access_errors()
  895. output_file = None
  896. try:
  897. if options.output:
  898. output_file = open(options.output, 'w')
  899. logging.info('Printing output to "%s"', options.output)
  900. sys.stdout = output_file
  901. except (IOError, OSError) as e:
  902. logging.error('Unable to write output: %s', e)
  903. else:
  904. if options.json:
  905. my_activity.dump_json()
  906. else:
  907. if options.changes:
  908. my_activity.print_changes()
  909. if options.reviews:
  910. my_activity.print_reviews()
  911. if options.issues:
  912. my_activity.print_issues()
  913. if options.changes_by_issue:
  914. my_activity.print_changes_by_issue(
  915. options.skip_own_issues_without_changes)
  916. finally:
  917. if output_file:
  918. logging.info('Done printing to file.')
  919. sys.stdout = sys.__stdout__
  920. output_file.close()
  921. return 0
  922. if __name__ == '__main__':
  923. # Fix encoding to support non-ascii issue titles.
  924. fix_encoding.fix_encoding()
  925. try:
  926. sys.exit(main())
  927. except KeyboardInterrupt:
  928. sys.stderr.write('interrupted\n')
  929. sys.exit(1)