upload.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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>]... | --replace <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. If the --replace option is passed the user can designate which
  61. existing change(s) in Gerrit match up to the commits in the branch
  62. being uploaded. For each matched pair of change,commit the commit
  63. will be added as a new patch set, completely replacing the set of
  64. files and description associated with the change in Gerrit.
  65. Configuration
  66. -------------
  67. review.URL.autoupload:
  68. To disable the "Upload ... (y/n)?" prompt, you can set a per-project
  69. or global Git configuration option. If review.URL.autoupload is set
  70. to "true" then repo will assume you always answer "y" at the prompt,
  71. and will not prompt you further. If it is set to "false" then repo
  72. will assume you always answer "n", and will abort.
  73. review.URL.autocopy:
  74. To automatically copy a user or mailing list to all uploaded reviews,
  75. you can set a per-project or global Git option to do so. Specifically,
  76. review.URL.autocopy can be set to a comma separated list of reviewers
  77. who you always want copied on all uploads with a non-empty --re
  78. argument.
  79. The URL must match the review URL listed in the manifest XML file,
  80. or in the .git/config within the project. For example:
  81. [remote "origin"]
  82. url = git://git.example.com/project.git
  83. review = http://review.example.com/
  84. [review "http://review.example.com/"]
  85. autoupload = true
  86. autocopy = johndoe@company.com,my-team-alias@company.com
  87. References
  88. ----------
  89. Gerrit Code Review: http://code.google.com/p/gerrit/
  90. """
  91. def _Options(self, p):
  92. p.add_option('-t',
  93. dest='auto_topic', action='store_true',
  94. help='Send local branch name to Gerrit Code Review')
  95. p.add_option('--replace',
  96. dest='replace', action='store_true',
  97. help='Upload replacement patchesets from this branch')
  98. p.add_option('--re', '--reviewers',
  99. type='string', action='append', dest='reviewers',
  100. help='Request reviews from these people.')
  101. p.add_option('--cc',
  102. type='string', action='append', dest='cc',
  103. help='Also send email to these email addresses.')
  104. def _SingleBranch(self, opt, branch, people):
  105. project = branch.project
  106. name = branch.name
  107. remote = project.GetBranch(name).remote
  108. key = 'review.%s.autoupload' % remote.review
  109. answer = project.config.GetBoolean(key)
  110. if answer is False:
  111. _die("upload blocked by %s = false" % key)
  112. if answer is None:
  113. date = branch.date
  114. list = branch.commits
  115. print 'Upload project %s/:' % project.relpath
  116. print ' branch %s (%2d commit%s, %s):' % (
  117. name,
  118. len(list),
  119. len(list) != 1 and 's' or '',
  120. date)
  121. for commit in list:
  122. print ' %s' % commit
  123. sys.stdout.write('to %s (y/n)? ' % remote.review)
  124. answer = sys.stdin.readline().strip()
  125. answer = answer in ('y', 'Y', 'yes', '1', 'true', 't')
  126. if answer:
  127. if len(branch.commits) > UNUSUAL_COMMIT_THRESHOLD:
  128. answer = _ConfirmManyUploads()
  129. if answer:
  130. self._UploadAndReport(opt, [branch], people)
  131. else:
  132. _die("upload aborted by user")
  133. def _MultipleBranches(self, opt, pending, people):
  134. projects = {}
  135. branches = {}
  136. script = []
  137. script.append('# Uncomment the branches to upload:')
  138. for project, avail in pending:
  139. script.append('#')
  140. script.append('# project %s/:' % project.relpath)
  141. b = {}
  142. for branch in avail:
  143. name = branch.name
  144. date = branch.date
  145. list = branch.commits
  146. if b:
  147. script.append('#')
  148. script.append('# branch %s (%2d commit%s, %s):' % (
  149. name,
  150. len(list),
  151. len(list) != 1 and 's' or '',
  152. date))
  153. for commit in list:
  154. script.append('# %s' % commit)
  155. b[name] = branch
  156. projects[project.relpath] = project
  157. branches[project.name] = b
  158. script.append('')
  159. script = Editor.EditString("\n".join(script)).split("\n")
  160. project_re = re.compile(r'^#?\s*project\s*([^\s]+)/:$')
  161. branch_re = re.compile(r'^\s*branch\s*([^\s(]+)\s*\(.*')
  162. project = None
  163. todo = []
  164. for line in script:
  165. m = project_re.match(line)
  166. if m:
  167. name = m.group(1)
  168. project = projects.get(name)
  169. if not project:
  170. _die('project %s not available for upload', name)
  171. continue
  172. m = branch_re.match(line)
  173. if m:
  174. name = m.group(1)
  175. if not project:
  176. _die('project for branch %s not in script', name)
  177. branch = branches[project.name].get(name)
  178. if not branch:
  179. _die('branch %s not in %s', name, project.relpath)
  180. todo.append(branch)
  181. if not todo:
  182. _die("nothing uncommented for upload")
  183. many_commits = False
  184. for branch in todo:
  185. if len(branch.commits) > UNUSUAL_COMMIT_THRESHOLD:
  186. many_commits = True
  187. break
  188. if many_commits:
  189. if not _ConfirmManyUploads(multiple_branches=True):
  190. _die("upload aborted by user")
  191. self._UploadAndReport(opt, todo, people)
  192. def _AppendAutoCcList(self, branch, people):
  193. """
  194. Appends the list of users in the CC list in the git project's config if a
  195. non-empty reviewer list was found.
  196. """
  197. name = branch.name
  198. project = branch.project
  199. key = 'review.%s.autocopy' % project.GetBranch(name).remote.review
  200. raw_list = project.config.GetString(key)
  201. if not raw_list is None and len(people[0]) > 0:
  202. people[1].extend([entry.strip() for entry in raw_list.split(',')])
  203. def _FindGerritChange(self, branch):
  204. last_pub = branch.project.WasPublished(branch.name)
  205. if last_pub is None:
  206. return ""
  207. refs = branch.GetPublishedRefs()
  208. try:
  209. # refs/changes/XYZ/N --> XYZ
  210. return refs.get(last_pub).split('/')[-2]
  211. except:
  212. return ""
  213. def _ReplaceBranch(self, project, people):
  214. branch = project.CurrentBranch
  215. if not branch:
  216. print >>sys.stdout, "no branches ready for upload"
  217. return
  218. branch = project.GetUploadableBranch(branch)
  219. if not branch:
  220. print >>sys.stdout, "no branches ready for upload"
  221. return
  222. script = []
  223. script.append('# Replacing from branch %s' % branch.name)
  224. if len(branch.commits) == 1:
  225. change = self._FindGerritChange(branch)
  226. script.append('[%-6s] %s' % (change, branch.commits[0]))
  227. else:
  228. for commit in branch.commits:
  229. script.append('[ ] %s' % commit)
  230. script.append('')
  231. script.append('# Insert change numbers in the brackets to add a new patch set.')
  232. script.append('# To create a new change record, leave the brackets empty.')
  233. script = Editor.EditString("\n".join(script)).split("\n")
  234. change_re = re.compile(r'^\[\s*(\d{1,})\s*\]\s*([0-9a-f]{1,}) .*$')
  235. to_replace = dict()
  236. full_hashes = branch.unabbrev_commits
  237. for line in script:
  238. m = change_re.match(line)
  239. if m:
  240. c = m.group(1)
  241. f = m.group(2)
  242. try:
  243. f = full_hashes[f]
  244. except KeyError:
  245. print 'fh = %s' % full_hashes
  246. print >>sys.stderr, "error: commit %s not found" % f
  247. sys.exit(1)
  248. if c in to_replace:
  249. print >>sys.stderr,\
  250. "error: change %s cannot accept multiple commits" % c
  251. sys.exit(1)
  252. to_replace[c] = f
  253. if not to_replace:
  254. print >>sys.stderr, "error: no replacements specified"
  255. print >>sys.stderr, " use 'repo upload' without --replace"
  256. sys.exit(1)
  257. if len(branch.commits) > UNUSUAL_COMMIT_THRESHOLD:
  258. if not _ConfirmManyUploads(multiple_branches=True):
  259. _die("upload aborted by user")
  260. branch.replace_changes = to_replace
  261. self._UploadAndReport(opt, [branch], people)
  262. def _UploadAndReport(self, opt, todo, original_people):
  263. have_errors = False
  264. for branch in todo:
  265. try:
  266. people = copy.deepcopy(original_people)
  267. self._AppendAutoCcList(branch, people)
  268. # Check if there are local changes that may have been forgotten
  269. if branch.project.HasChanges():
  270. key = 'review.%s.autoupload' % branch.project.remote.review
  271. answer = branch.project.config.GetBoolean(key)
  272. # if they want to auto upload, let's not ask because it could be automated
  273. if answer is None:
  274. sys.stdout.write('Uncommitted changes in ' + branch.project.name + ' (did you forget to amend?). Continue uploading? (y/n) ')
  275. a = sys.stdin.readline().strip().lower()
  276. if a not in ('y', 'yes', 't', 'true', 'on'):
  277. print >>sys.stderr, "skipping upload"
  278. branch.uploaded = False
  279. branch.error = 'User aborted'
  280. continue
  281. branch.UploadForReview(people, auto_topic=opt.auto_topic)
  282. branch.uploaded = True
  283. except UploadError, e:
  284. branch.error = e
  285. branch.uploaded = False
  286. have_errors = True
  287. print >>sys.stderr, ''
  288. print >>sys.stderr, '--------------------------------------------'
  289. if have_errors:
  290. for branch in todo:
  291. if not branch.uploaded:
  292. print >>sys.stderr, '[FAILED] %-15s %-15s (%s)' % (
  293. branch.project.relpath + '/', \
  294. branch.name, \
  295. branch.error)
  296. print >>sys.stderr, ''
  297. for branch in todo:
  298. if branch.uploaded:
  299. print >>sys.stderr, '[OK ] %-15s %s' % (
  300. branch.project.relpath + '/',
  301. branch.name)
  302. if have_errors:
  303. sys.exit(1)
  304. def Execute(self, opt, args):
  305. project_list = self.GetProjects(args)
  306. pending = []
  307. reviewers = []
  308. cc = []
  309. if opt.reviewers:
  310. reviewers = _SplitEmails(opt.reviewers)
  311. if opt.cc:
  312. cc = _SplitEmails(opt.cc)
  313. people = (reviewers,cc)
  314. if opt.replace:
  315. if len(project_list) != 1:
  316. print >>sys.stderr, \
  317. 'error: --replace requires exactly one project'
  318. sys.exit(1)
  319. self._ReplaceBranch(project_list[0], people)
  320. return
  321. for project in project_list:
  322. avail = project.GetUploadableBranches()
  323. if avail:
  324. pending.append((project, avail))
  325. if not pending:
  326. print >>sys.stdout, "no branches ready for upload"
  327. elif len(pending) == 1 and len(pending[0][1]) == 1:
  328. self._SingleBranch(opt, pending[0][1][0], people)
  329. else:
  330. self._MultipleBranches(opt, pending, people)