upload.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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 re
  16. import sys
  17. from command import InteractiveCommand
  18. from editor import Editor
  19. from error import UploadError
  20. UNUSUAL_COMMIT_THRESHOLD = 5
  21. def _ConfirmManyUploads(multiple_branches=False):
  22. if multiple_branches:
  23. print "ATTENTION: One or more branches has an unusually high number of commits."
  24. else:
  25. print "ATTENTION: You are uploading an unusually high number of commits."
  26. print "YOU PROBABLY DO NOT MEAN TO DO THIS. (Did you rebase across branches?)"
  27. answer = raw_input("If you are sure you intend to do this, type 'yes': ").strip()
  28. return answer == "yes"
  29. def _die(fmt, *args):
  30. msg = fmt % args
  31. print >>sys.stderr, 'error: %s' % msg
  32. sys.exit(1)
  33. def _SplitEmails(values):
  34. result = []
  35. for str in values:
  36. result.extend([s.strip() for s in str.split(',')])
  37. return result
  38. class Upload(InteractiveCommand):
  39. common = True
  40. helpSummary = "Upload changes for code review"
  41. helpUsage="""
  42. %prog [--re --cc] {[<project>]... | --replace <project>}
  43. """
  44. helpDescription = """
  45. The '%prog' command is used to send changes to the Gerrit Code
  46. Review system. It searches for topic branches in local projects
  47. that have not yet been published for review. If multiple topic
  48. branches are found, '%prog' opens an editor to allow the user to
  49. select which branches to upload.
  50. '%prog' searches for uploadable changes in all projects listed at
  51. the command line. Projects can be specified either by name, or by
  52. a relative or absolute path to the project's local directory. If no
  53. projects are specified, '%prog' will search for uploadable changes
  54. in all projects listed in the manifest.
  55. If the --reviewers or --cc options are passed, those emails are
  56. added to the respective list of users, and emails are sent to any
  57. new users. Users passed as --reviewers must already be registered
  58. with the code review system, or the upload will fail.
  59. If the --replace option is passed the user can designate which
  60. existing change(s) in Gerrit match up to the commits in the branch
  61. being uploaded. For each matched pair of change,commit the commit
  62. will be added as a new patch set, completely replacing the set of
  63. files and description associated with the change in Gerrit.
  64. Configuration
  65. -------------
  66. review.URL.autoupload:
  67. To disable the "Upload ... (y/n)?" prompt, you can set a per-project
  68. or global Git configuration option. If review.URL.autoupload is set
  69. to "true" then repo will assume you always answer "y" at the prompt,
  70. and will not prompt you further. If it is set to "false" then repo
  71. will assume you always answer "n", and will abort.
  72. The URL must match the review URL listed in the manifest XML file,
  73. or in the .git/config within the project. For example:
  74. [remote "origin"]
  75. url = git://git.example.com/project.git
  76. review = http://review.example.com/
  77. [review "http://review.example.com/"]
  78. autoupload = true
  79. References
  80. ----------
  81. Gerrit Code Review: http://code.google.com/p/gerrit/
  82. """
  83. def _Options(self, p):
  84. p.add_option('--replace',
  85. dest='replace', action='store_true',
  86. help='Upload replacement patchesets from this branch')
  87. p.add_option('--re', '--reviewers',
  88. type='string', action='append', dest='reviewers',
  89. help='Request reviews from these people.')
  90. p.add_option('--cc',
  91. type='string', action='append', dest='cc',
  92. help='Also send email to these email addresses.')
  93. def _SingleBranch(self, branch, people):
  94. project = branch.project
  95. name = branch.name
  96. remote = project.GetBranch(name).remote
  97. key = 'review.%s.autoupload' % remote.review
  98. answer = project.config.GetBoolean(key)
  99. if answer is False:
  100. _die("upload blocked by %s = false" % key)
  101. if answer is None:
  102. date = branch.date
  103. list = branch.commits
  104. print 'Upload project %s/:' % project.relpath
  105. print ' branch %s (%2d commit%s, %s):' % (
  106. name,
  107. len(list),
  108. len(list) != 1 and 's' or '',
  109. date)
  110. for commit in list:
  111. print ' %s' % commit
  112. sys.stdout.write('to %s (y/n)? ' % remote.review)
  113. answer = sys.stdin.readline().strip()
  114. answer = answer in ('y', 'Y', 'yes', '1', 'true', 't')
  115. if answer:
  116. if len(branch.commits) > UNUSUAL_COMMIT_THRESHOLD:
  117. answer = _ConfirmManyUploads()
  118. if answer:
  119. self._UploadAndReport([branch], people)
  120. else:
  121. _die("upload aborted by user")
  122. def _MultipleBranches(self, pending, people):
  123. projects = {}
  124. branches = {}
  125. script = []
  126. script.append('# Uncomment the branches to upload:')
  127. for project, avail in pending:
  128. script.append('#')
  129. script.append('# project %s/:' % project.relpath)
  130. b = {}
  131. for branch in avail:
  132. name = branch.name
  133. date = branch.date
  134. list = branch.commits
  135. if b:
  136. script.append('#')
  137. script.append('# branch %s (%2d commit%s, %s):' % (
  138. name,
  139. len(list),
  140. len(list) != 1 and 's' or '',
  141. date))
  142. for commit in list:
  143. script.append('# %s' % commit)
  144. b[name] = branch
  145. projects[project.relpath] = project
  146. branches[project.name] = b
  147. script.append('')
  148. script = Editor.EditString("\n".join(script)).split("\n")
  149. project_re = re.compile(r'^#?\s*project\s*([^\s]+)/:$')
  150. branch_re = re.compile(r'^\s*branch\s*([^\s(]+)\s*\(.*')
  151. project = None
  152. todo = []
  153. for line in script:
  154. m = project_re.match(line)
  155. if m:
  156. name = m.group(1)
  157. project = projects.get(name)
  158. if not project:
  159. _die('project %s not available for upload', name)
  160. continue
  161. m = branch_re.match(line)
  162. if m:
  163. name = m.group(1)
  164. if not project:
  165. _die('project for branch %s not in script', name)
  166. branch = branches[project.name].get(name)
  167. if not branch:
  168. _die('branch %s not in %s', name, project.relpath)
  169. todo.append(branch)
  170. if not todo:
  171. _die("nothing uncommented for upload")
  172. many_commits = False
  173. for branch in todo:
  174. if len(branch.commits) > UNUSUAL_COMMIT_THRESHOLD:
  175. many_commits = True
  176. break
  177. if many_commits:
  178. if not _ConfirmManyUploads(multiple_branches=True):
  179. _die("upload aborted by user")
  180. self._UploadAndReport(todo, people)
  181. def _FindGerritChange(self, branch):
  182. last_pub = branch.project.WasPublished(branch.name)
  183. if last_pub is None:
  184. return ""
  185. refs = branch.GetPublishedRefs()
  186. try:
  187. # refs/changes/XYZ/N --> XYZ
  188. return refs.get(last_pub).split('/')[-2]
  189. except:
  190. return ""
  191. def _ReplaceBranch(self, project, people):
  192. branch = project.CurrentBranch
  193. if not branch:
  194. print >>sys.stdout, "no branches ready for upload"
  195. return
  196. branch = project.GetUploadableBranch(branch)
  197. if not branch:
  198. print >>sys.stdout, "no branches ready for upload"
  199. return
  200. script = []
  201. script.append('# Replacing from branch %s' % branch.name)
  202. if len(branch.commits) == 1:
  203. change = self._FindGerritChange(branch)
  204. script.append('[%-6s] %s' % (change, branch.commits[0]))
  205. else:
  206. for commit in branch.commits:
  207. script.append('[ ] %s' % commit)
  208. script.append('')
  209. script.append('# Insert change numbers in the brackets to add a new patch set.')
  210. script.append('# To create a new change record, leave the brackets empty.')
  211. script = Editor.EditString("\n".join(script)).split("\n")
  212. change_re = re.compile(r'^\[\s*(\d{1,})\s*\]\s*([0-9a-f]{1,}) .*$')
  213. to_replace = dict()
  214. full_hashes = branch.unabbrev_commits
  215. for line in script:
  216. m = change_re.match(line)
  217. if m:
  218. c = m.group(1)
  219. f = m.group(2)
  220. try:
  221. f = full_hashes[f]
  222. except KeyError:
  223. print 'fh = %s' % full_hashes
  224. print >>sys.stderr, "error: commit %s not found" % f
  225. sys.exit(1)
  226. if c in to_replace:
  227. print >>sys.stderr,\
  228. "error: change %s cannot accept multiple commits" % c
  229. sys.exit(1)
  230. to_replace[c] = f
  231. if not to_replace:
  232. print >>sys.stderr, "error: no replacements specified"
  233. print >>sys.stderr, " use 'repo upload' without --replace"
  234. sys.exit(1)
  235. if len(branch.commits) > UNUSUAL_COMMIT_THRESHOLD:
  236. if not _ConfirmManyUploads(multiple_branches=True):
  237. _die("upload aborted by user")
  238. branch.replace_changes = to_replace
  239. self._UploadAndReport([branch], people)
  240. def _UploadAndReport(self, todo, people):
  241. have_errors = False
  242. for branch in todo:
  243. try:
  244. branch.UploadForReview(people)
  245. branch.uploaded = True
  246. except UploadError, e:
  247. branch.error = e
  248. branch.uploaded = False
  249. have_errors = True
  250. print >>sys.stderr, ''
  251. print >>sys.stderr, '--------------------------------------------'
  252. if have_errors:
  253. for branch in todo:
  254. if not branch.uploaded:
  255. print >>sys.stderr, '[FAILED] %-15s %-15s (%s)' % (
  256. branch.project.relpath + '/', \
  257. branch.name, \
  258. branch.error)
  259. print >>sys.stderr, ''
  260. for branch in todo:
  261. if branch.uploaded:
  262. print >>sys.stderr, '[OK ] %-15s %s' % (
  263. branch.project.relpath + '/',
  264. branch.name)
  265. if have_errors:
  266. sys.exit(1)
  267. def Execute(self, opt, args):
  268. project_list = self.GetProjects(args)
  269. pending = []
  270. reviewers = []
  271. cc = []
  272. if opt.reviewers:
  273. reviewers = _SplitEmails(opt.reviewers)
  274. if opt.cc:
  275. cc = _SplitEmails(opt.cc)
  276. people = (reviewers,cc)
  277. if opt.replace:
  278. if len(project_list) != 1:
  279. print >>sys.stderr, \
  280. 'error: --replace requires exactly one project'
  281. sys.exit(1)
  282. self._ReplaceBranch(project_list[0], people)
  283. return
  284. for project in project_list:
  285. avail = project.GetUploadableBranches()
  286. if avail:
  287. pending.append((project, avail))
  288. if not pending:
  289. print >>sys.stdout, "no branches ready for upload"
  290. elif len(pending) == 1 and len(pending[0][1]) == 1:
  291. self._SingleBranch(pending[0][1][0], people)
  292. else:
  293. self._MultipleBranches(pending, people)