upload.py 13 KB

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