commit_queue.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. #!/usr/bin/env python
  2. # Copyright (c) 2011 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. """Access the commit queue from the command line.
  6. """
  7. __version__ = '0.1'
  8. import functools
  9. import json
  10. import logging
  11. import optparse
  12. import os
  13. import sys
  14. import urllib2
  15. import breakpad # pylint: disable=W0611
  16. import auth
  17. import fix_encoding
  18. import rietveld
  19. THIRD_PARTY_DIR = os.path.join(os.path.dirname(__file__), 'third_party')
  20. sys.path.insert(0, THIRD_PARTY_DIR)
  21. from cq_client import cq_pb2
  22. from protobuf26 import text_format
  23. def usage(more):
  24. def hook(fn):
  25. fn.func_usage_more = more
  26. return fn
  27. return hook
  28. def need_issue(fn):
  29. """Post-parse args to create a Rietveld object."""
  30. @functools.wraps(fn)
  31. def hook(parser, args, *extra_args, **kwargs):
  32. old_parse_args = parser.parse_args
  33. def new_parse_args(args=None, values=None):
  34. options, args = old_parse_args(args, values)
  35. auth_config = auth.extract_auth_config_from_options(options)
  36. if not options.issue:
  37. parser.error('Require --issue')
  38. obj = rietveld.Rietveld(options.server, auth_config, options.user)
  39. return options, args, obj
  40. parser.parse_args = new_parse_args
  41. parser.add_option(
  42. '-u', '--user',
  43. metavar='U',
  44. default=os.environ.get('EMAIL_ADDRESS', None),
  45. help='Email address, default: %default')
  46. parser.add_option(
  47. '-i', '--issue',
  48. metavar='I',
  49. type='int',
  50. help='Rietveld issue number')
  51. parser.add_option(
  52. '-s',
  53. '--server',
  54. metavar='S',
  55. default='http://codereview.chromium.org',
  56. help='Rietveld server, default: %default')
  57. auth.add_auth_options(parser)
  58. # Call the original function with the modified parser.
  59. return fn(parser, args, *extra_args, **kwargs)
  60. hook.func_usage_more = '[options]'
  61. return hook
  62. def _apply_on_issue(fun, obj, issue):
  63. """Applies function 'fun' on an issue."""
  64. try:
  65. return fun(obj.get_issue_properties(issue, False))
  66. except urllib2.HTTPError, e:
  67. if e.code == 404:
  68. print >> sys.stderr, 'Issue %d doesn\'t exist.' % issue
  69. elif e.code == 403:
  70. print >> sys.stderr, 'Access denied to issue %d.' % issue
  71. else:
  72. raise
  73. return 1
  74. def get_commit(obj, issue):
  75. """Gets the commit bit flag of an issue."""
  76. def _get_commit(properties):
  77. print int(properties['commit'])
  78. return 0
  79. _apply_on_issue(_get_commit, obj, issue)
  80. def set_commit(obj, issue, flag):
  81. """Sets the commit bit flag on an issue."""
  82. def _set_commit(properties):
  83. print obj.set_flag(issue, properties['patchsets'][-1], 'commit', flag)
  84. return 0
  85. _apply_on_issue(_set_commit, obj, issue)
  86. def get_master_builder_map(
  87. config_path, include_experimental=True, include_triggered=True):
  88. """Returns a map of master -> [builders] from cq config."""
  89. with open(config_path) as config_file:
  90. cq_config = config_file.read()
  91. config = cq_pb2.Config()
  92. text_format.Merge(cq_config, config)
  93. masters = {}
  94. if config.HasField('verifiers') and config.verifiers.HasField('try_job'):
  95. for bucket in config.verifiers.try_job.buckets:
  96. masters.setdefault(bucket.name, [])
  97. for builder in bucket.builders:
  98. if (not include_experimental and
  99. builder.HasField('experiment_percentage')):
  100. continue
  101. if (not include_triggered and
  102. builder.HasField('triggered_by')):
  103. continue
  104. masters[bucket.name].append(builder.name)
  105. return masters
  106. @need_issue
  107. def CMDset(parser, args):
  108. """Sets the commit bit."""
  109. options, args, obj = parser.parse_args(args)
  110. if args:
  111. parser.error('Unrecognized args: %s' % ' '.join(args))
  112. return set_commit(obj, options.issue, '1')
  113. @need_issue
  114. def CMDget(parser, args):
  115. """Gets the commit bit."""
  116. options, args, obj = parser.parse_args(args)
  117. if args:
  118. parser.error('Unrecognized args: %s' % ' '.join(args))
  119. return get_commit(obj, options.issue)
  120. @need_issue
  121. def CMDclear(parser, args):
  122. """Clears the commit bit."""
  123. options, args, obj = parser.parse_args(args)
  124. if args:
  125. parser.error('Unrecognized args: %s' % ' '.join(args))
  126. return set_commit(obj, options.issue, '0')
  127. def CMDbuilders(parser, args):
  128. """Prints json-formatted list of builders given a path to cq.cfg file.
  129. The output is a dictionary in the following format:
  130. {
  131. 'master_name': [
  132. 'builder_name',
  133. 'another_builder'
  134. ],
  135. 'another_master': [
  136. 'third_builder'
  137. ]
  138. }
  139. """
  140. parser.add_option('--include-experimental', action='store_true')
  141. parser.add_option('--exclude-experimental', action='store_false',
  142. dest='include_experimental')
  143. parser.add_option('--include-triggered', action='store_true')
  144. parser.add_option('--exclude-triggered', action='store_false',
  145. dest='include_triggered')
  146. # The defaults have been chosen because of backward compatbility.
  147. parser.set_defaults(include_experimental=True, include_triggered=True)
  148. options, args = parser.parse_args(args)
  149. if len(args) != 1:
  150. parser.error('Expected a single path to CQ config. Got: %s' %
  151. ' '.join(args))
  152. print json.dumps(get_master_builder_map(
  153. args[0],
  154. include_experimental=options.include_experimental,
  155. include_triggered=options.include_triggered))
  156. CMDbuilders.func_usage_more = '<path-to-cq-config>'
  157. def CMDvalidate(parser, args):
  158. """Validates a CQ config, returns 0 on valid config.
  159. BUGS: this doesn't do semantic validation, only verifies validity of protobuf.
  160. But don't worry - bad cq.cfg won't cause outages, luci-config service will
  161. not accept them, will send warning email, and continue using previous
  162. version.
  163. """
  164. _, args = parser.parse_args(args)
  165. if len(args) != 1:
  166. parser.error('Expected a single path to CQ config. Got: %s' %
  167. ' '.join(args))
  168. config = cq_pb2.Config()
  169. try:
  170. with open(args[0]) as config_file:
  171. text_config = config_file.read()
  172. text_format.Merge(text_config, config)
  173. # TODO(tandrii): provide an option to actually validate semantics of CQ
  174. # config.
  175. return 0
  176. except text_format.ParseError as e:
  177. print 'failed to parse cq.cfg: %s' % e
  178. return 1
  179. CMDvalidate.func_usage_more = '<path-to-cq-config>'
  180. ###############################################################################
  181. ## Boilerplate code
  182. class OptionParser(optparse.OptionParser):
  183. """An OptionParser instance with default options.
  184. It should be then processed with gen_usage() before being used.
  185. """
  186. def __init__(self, *args, **kwargs):
  187. optparse.OptionParser.__init__(self, *args, **kwargs)
  188. self.add_option(
  189. '-v', '--verbose', action='count', default=0,
  190. help='Use multiple times to increase logging level')
  191. def parse_args(self, args=None, values=None):
  192. options, args = optparse.OptionParser.parse_args(self, args, values)
  193. levels = [logging.WARNING, logging.INFO, logging.DEBUG]
  194. logging.basicConfig(
  195. level=levels[min(len(levels) - 1, options.verbose)],
  196. format='%(levelname)s %(filename)s(%(lineno)d): %(message)s')
  197. return options, args
  198. def format_description(self, _):
  199. """Removes description formatting."""
  200. return self.description.rstrip() + '\n'
  201. def Command(name):
  202. return getattr(sys.modules[__name__], 'CMD' + name, None)
  203. @usage('<command>')
  204. def CMDhelp(parser, args):
  205. """Print list of commands or use 'help <command>'."""
  206. # Strip out the help command description and replace it with the module
  207. # docstring.
  208. parser.description = sys.modules[__name__].__doc__
  209. parser.description += '\nCommands are:\n' + '\n'.join(
  210. ' %-12s %s' % (
  211. fn[3:], Command(fn[3:]).__doc__.split('\n', 1)[0].rstrip('.'))
  212. for fn in dir(sys.modules[__name__]) if fn.startswith('CMD'))
  213. _, args = parser.parse_args(args)
  214. if len(args) == 1 and args[0] != 'help':
  215. return main(args + ['--help'])
  216. parser.print_help()
  217. return 0
  218. def gen_usage(parser, command):
  219. """Modifies an OptionParser object with the command's documentation.
  220. The documentation is taken from the function's docstring.
  221. """
  222. obj = Command(command)
  223. more = getattr(obj, 'func_usage_more')
  224. # OptParser.description prefer nicely non-formatted strings.
  225. parser.description = obj.__doc__ + '\n'
  226. parser.set_usage('usage: %%prog %s %s' % (command, more))
  227. def main(args=None):
  228. # Do it late so all commands are listed.
  229. # pylint: disable=E1101
  230. parser = OptionParser(version=__version__)
  231. if args is None:
  232. args = sys.argv[1:]
  233. if args:
  234. command = Command(args[0])
  235. if command:
  236. # "fix" the usage and the description now that we know the subcommand.
  237. gen_usage(parser, args[0])
  238. return command(parser, args[1:])
  239. # Not a known command. Default to help.
  240. gen_usage(parser, 'help')
  241. return CMDhelp(parser, args)
  242. if __name__ == "__main__":
  243. fix_encoding.fix_encoding()
  244. try:
  245. sys.exit(main())
  246. except KeyboardInterrupt:
  247. sys.stderr.write('interrupted\n')
  248. sys.exit(1)