upload.py 13 KB

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