my_activity.py 33 KB

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