my_activity.py 38 KB

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