upload.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. #
  2. # Copyright (C) 2008 The Android Open Source Project
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import copy
  16. import re
  17. import sys
  18. from command import InteractiveCommand
  19. from editor import Editor
  20. from error import UploadError
  21. UNUSUAL_COMMIT_THRESHOLD = 5
  22. def _ConfirmManyUploads(multiple_branches=False):
  23. if multiple_branches:
  24. print "ATTENTION: One or more branches has an unusually high number of commits."
  25. else:
  26. print "ATTENTION: You are uploading an unusually high number of commits."
  27. print "YOU PROBABLY DO NOT MEAN TO DO THIS. (Did you rebase across branches?)"
  28. answer = raw_input("If you are sure you intend to do this, type 'yes': ").strip()
  29. return answer == "yes"
  30. def _die(fmt, *args):
  31. msg = fmt % args
  32. print >>sys.stderr, 'error: %s' % msg
  33. sys.exit(1)
  34. def _SplitEmails(values):
  35. result = []
  36. for str in values:
  37. result.extend([s.strip() for s in str.split(',')])
  38. return result
  39. class Upload(InteractiveCommand):
  40. common = True
  41. helpSummary = "Upload changes for code review"
  42. helpUsage="""
  43. %prog [--re --cc] [<project>]...
  44. """
  45. helpDescription = """
  46. The '%prog' command is used to send changes to the Gerrit Code
  47. Review system. It searches for topic branches in local projects
  48. that have not yet been published for review. If multiple topic
  49. branches are found, '%prog' opens an editor to allow the user to
  50. select which branches to upload.
  51. '%prog' searches for uploadable changes in all projects listed at
  52. the command line. Projects can be specified either by name, or by
  53. a relative or absolute path to the project's local directory. If no
  54. projects are specified, '%prog' will search for uploadable changes
  55. in all projects listed in the manifest.
  56. If the --reviewers or --cc options are passed, those emails are
  57. added to the respective list of users, and emails are sent to any
  58. new users. Users passed as --reviewers must already be registered
  59. with the code review system, or the upload will fail.
  60. Configuration
  61. -------------
  62. review.URL.autoupload:
  63. To disable the "Upload ... (y/n)?" prompt, you can set a per-project
  64. or global Git configuration option. If review.URL.autoupload is set
  65. to "true" then repo will assume you always answer "y" at the prompt,
  66. and will not prompt you further. If it is set to "false" then repo
  67. will assume you always answer "n", and will abort.
  68. review.URL.autocopy:
  69. To automatically copy a user or mailing list to all uploaded reviews,
  70. you can set a per-project or global Git option to do so. Specifically,
  71. review.URL.autocopy can be set to a comma separated list of reviewers
  72. who you always want copied on all uploads with a non-empty --re
  73. argument.
  74. review.URL.username:
  75. Override the username used to connect to Gerrit Code Review.
  76. By default the local part of the email address is used.
  77. The URL must match the review URL listed in the manifest XML file,
  78. or in the .git/config within the project. For example:
  79. [remote "origin"]
  80. url = git://git.example.com/project.git
  81. review = http://review.example.com/
  82. [review "http://review.example.com/"]
  83. autoupload = true
  84. autocopy = johndoe@company.com,my-team-alias@company.com
  85. References
  86. ----------
  87. Gerrit Code Review: http://code.google.com/p/gerrit/
  88. """
  89. def _Options(self, p):
  90. p.add_option('-t',
  91. dest='auto_topic', action='store_true',
  92. help='Send local branch name to Gerrit Code Review')
  93. p.add_option('--re', '--reviewers',
  94. type='string', action='append', dest='reviewers',
  95. help='Request reviews from these people.')
  96. p.add_option('--cc',
  97. type='string', action='append', dest='cc',
  98. help='Also send email to these email addresses.')
  99. def _SingleBranch(self, opt, branch, people):
  100. project = branch.project
  101. name = branch.name
  102. remote = project.GetBranch(name).remote
  103. key = 'review.%s.autoupload' % remote.review
  104. answer = project.config.GetBoolean(key)
  105. if answer is False:
  106. _die("upload blocked by %s = false" % key)
  107. if answer is None:
  108. date = branch.date
  109. list = branch.commits
  110. print 'Upload project %s/:' % project.relpath
  111. print ' branch %s (%2d commit%s, %s):' % (
  112. name,
  113. len(list),
  114. len(list) != 1 and 's' or '',
  115. date)
  116. for commit in list:
  117. print ' %s' % commit
  118. sys.stdout.write('to %s (y/n)? ' % remote.review)
  119. answer = sys.stdin.readline().strip()
  120. answer = answer in ('y', 'Y', 'yes', '1', 'true', 't')
  121. if answer:
  122. if len(branch.commits) > UNUSUAL_COMMIT_THRESHOLD:
  123. answer = _ConfirmManyUploads()
  124. if answer:
  125. self._UploadAndReport(opt, [branch], people)
  126. else:
  127. _die("upload aborted by user")
  128. def _MultipleBranches(self, opt, pending, people):
  129. projects = {}
  130. branches = {}
  131. script = []
  132. script.append('# Uncomment the branches to upload:')
  133. for project, avail in pending:
  134. script.append('#')
  135. script.append('# project %s/:' % project.relpath)
  136. b = {}
  137. for branch in avail:
  138. name = branch.name
  139. date = branch.date
  140. list = branch.commits
  141. if b:
  142. script.append('#')
  143. script.append('# branch %s (%2d commit%s, %s):' % (
  144. name,
  145. len(list),
  146. len(list) != 1 and 's' or '',
  147. date))
  148. for commit in list:
  149. script.append('# %s' % commit)
  150. b[name] = branch
  151. projects[project.relpath] = project
  152. branches[project.name] = b
  153. script.append('')
  154. script = Editor.EditString("\n".join(script)).split("\n")
  155. project_re = re.compile(r'^#?\s*project\s*([^\s]+)/:$')
  156. branch_re = re.compile(r'^\s*branch\s*([^\s(]+)\s*\(.*')
  157. project = None
  158. todo = []
  159. for line in script:
  160. m = project_re.match(line)
  161. if m:
  162. name = m.group(1)
  163. project = projects.get(name)
  164. if not project:
  165. _die('project %s not available for upload', name)
  166. continue
  167. m = branch_re.match(line)
  168. if m:
  169. name = m.group(1)
  170. if not project:
  171. _die('project for branch %s not in script', name)
  172. branch = branches[project.name].get(name)
  173. if not branch:
  174. _die('branch %s not in %s', name, project.relpath)
  175. todo.append(branch)
  176. if not todo:
  177. _die("nothing uncommented for upload")
  178. many_commits = False
  179. for branch in todo:
  180. if len(branch.commits) > UNUSUAL_COMMIT_THRESHOLD:
  181. many_commits = True
  182. break
  183. if many_commits:
  184. if not _ConfirmManyUploads(multiple_branches=True):
  185. _die("upload aborted by user")
  186. self._UploadAndReport(opt, todo, people)
  187. def _AppendAutoCcList(self, branch, people):
  188. """
  189. Appends the list of users in the CC list in the git project's config if a
  190. non-empty reviewer list was found.
  191. """
  192. name = branch.name
  193. project = branch.project
  194. key = 'review.%s.autocopy' % project.GetBranch(name).remote.review
  195. raw_list = project.config.GetString(key)
  196. if not raw_list is None and len(people[0]) > 0:
  197. people[1].extend([entry.strip() for entry in raw_list.split(',')])
  198. def _FindGerritChange(self, branch):
  199. last_pub = branch.project.WasPublished(branch.name)
  200. if last_pub is None:
  201. return ""
  202. refs = branch.GetPublishedRefs()
  203. try:
  204. # refs/changes/XYZ/N --> XYZ
  205. return refs.get(last_pub).split('/')[-2]
  206. except:
  207. return ""
  208. def _UploadAndReport(self, opt, todo, original_people):
  209. have_errors = False
  210. for branch in todo:
  211. try:
  212. people = copy.deepcopy(original_people)
  213. self._AppendAutoCcList(branch, people)
  214. # Check if there are local changes that may have been forgotten
  215. if branch.project.HasChanges():
  216. key = 'review.%s.autoupload' % branch.project.remote.review
  217. answer = branch.project.config.GetBoolean(key)
  218. # if they want to auto upload, let's not ask because it could be automated
  219. if answer is None:
  220. sys.stdout.write('Uncommitted changes in ' + branch.project.name + ' (did you forget to amend?). Continue uploading? (y/n) ')
  221. a = sys.stdin.readline().strip().lower()
  222. if a not in ('y', 'yes', 't', 'true', 'on'):
  223. print >>sys.stderr, "skipping upload"
  224. branch.uploaded = False
  225. branch.error = 'User aborted'
  226. continue
  227. branch.UploadForReview(people, auto_topic=opt.auto_topic)
  228. branch.uploaded = True
  229. except UploadError, e:
  230. branch.error = e
  231. branch.uploaded = False
  232. have_errors = True
  233. print >>sys.stderr, ''
  234. print >>sys.stderr, '----------------------------------------------------------------------'
  235. if have_errors:
  236. for branch in todo:
  237. if not branch.uploaded:
  238. if len(str(branch.error)) <= 30:
  239. fmt = ' (%s)'
  240. else:
  241. fmt = '\n (%s)'
  242. print >>sys.stderr, ('[FAILED] %-15s %-15s' + fmt) % (
  243. branch.project.relpath + '/', \
  244. branch.name, \
  245. str(branch.error))
  246. print >>sys.stderr, ''
  247. for branch in todo:
  248. if branch.uploaded:
  249. print >>sys.stderr, '[OK ] %-15s %s' % (
  250. branch.project.relpath + '/',
  251. branch.name)
  252. if have_errors:
  253. sys.exit(1)
  254. def Execute(self, opt, args):
  255. project_list = self.GetProjects(args)
  256. pending = []
  257. reviewers = []
  258. cc = []
  259. if opt.reviewers:
  260. reviewers = _SplitEmails(opt.reviewers)
  261. if opt.cc:
  262. cc = _SplitEmails(opt.cc)
  263. people = (reviewers,cc)
  264. for project in project_list:
  265. avail = project.GetUploadableBranches()
  266. if avail:
  267. pending.append((project, avail))
  268. if not pending:
  269. print >>sys.stdout, "no branches ready for upload"
  270. elif len(pending) == 1 and len(pending[0][1]) == 1:
  271. self._SingleBranch(opt, pending[0][1][0], people)
  272. else:
  273. self._MultipleBranches(opt, pending, people)