upload.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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 HookError, UploadError
  21. from project import RepoHook
  22. UNUSUAL_COMMIT_THRESHOLD = 5
  23. def _ConfirmManyUploads(multiple_branches=False):
  24. if multiple_branches:
  25. print "ATTENTION: One or more branches has an unusually high number of commits."
  26. else:
  27. print "ATTENTION: You are uploading an unusually high number of commits."
  28. print "YOU PROBABLY DO NOT MEAN TO DO THIS. (Did you rebase across branches?)"
  29. answer = raw_input("If you are sure you intend to do this, type 'yes': ").strip()
  30. return answer == "yes"
  31. def _die(fmt, *args):
  32. msg = fmt % args
  33. print >>sys.stderr, 'error: %s' % msg
  34. sys.exit(1)
  35. def _SplitEmails(values):
  36. result = []
  37. for value in values:
  38. result.extend([s.strip() for s in value.split(',')])
  39. return result
  40. class Upload(InteractiveCommand):
  41. common = True
  42. helpSummary = "Upload changes for code review"
  43. helpUsage="""
  44. %prog [--re --cc] [<project>]...
  45. """
  46. helpDescription = """
  47. The '%prog' command is used to send changes to the Gerrit Code
  48. Review system. It searches for topic branches in local projects
  49. that have not yet been published for review. If multiple topic
  50. branches are found, '%prog' opens an editor to allow the user to
  51. select which branches to upload.
  52. '%prog' searches for uploadable changes in all projects listed at
  53. the command line. Projects can be specified either by name, or by
  54. a relative or absolute path to the project's local directory. If no
  55. projects are specified, '%prog' will search for uploadable changes
  56. in all projects listed in the manifest.
  57. If the --reviewers or --cc options are passed, those emails are
  58. added to the respective list of users, and emails are sent to any
  59. new users. Users passed as --reviewers must already be registered
  60. with the code review system, or the upload will fail.
  61. Configuration
  62. -------------
  63. review.URL.autoupload:
  64. To disable the "Upload ... (y/N)?" prompt, you can set a per-project
  65. or global Git configuration option. If review.URL.autoupload is set
  66. to "true" then repo will assume you always answer "y" at the prompt,
  67. and will not prompt you further. If it is set to "false" then repo
  68. will assume you always answer "n", and will abort.
  69. review.URL.autocopy:
  70. To automatically copy a user or mailing list to all uploaded reviews,
  71. you can set a per-project or global Git option to do so. Specifically,
  72. review.URL.autocopy can be set to a comma separated list of reviewers
  73. who you always want copied on all uploads with a non-empty --re
  74. argument.
  75. review.URL.username:
  76. Override the username used to connect to Gerrit Code Review.
  77. By default the local part of the email address is used.
  78. The URL must match the review URL listed in the manifest XML file,
  79. or in the .git/config within the project. For example:
  80. [remote "origin"]
  81. url = git://git.example.com/project.git
  82. review = http://review.example.com/
  83. [review "http://review.example.com/"]
  84. autoupload = true
  85. autocopy = johndoe@company.com,my-team-alias@company.com
  86. review.URL.uploadtopic:
  87. To add a topic branch whenever uploading a commit, you can set a
  88. per-project or global Git option to do so. If review.URL.uploadtopic
  89. is set to "true" then repo will assume you always want the equivalent
  90. of the -t option to the repo command. If unset or set to "false" then
  91. repo will make use of only the command line option.
  92. References
  93. ----------
  94. Gerrit Code Review: http://code.google.com/p/gerrit/
  95. """
  96. def _Options(self, p):
  97. p.add_option('-t',
  98. dest='auto_topic', action='store_true',
  99. help='Send local branch name to Gerrit Code Review')
  100. p.add_option('--re', '--reviewers',
  101. type='string', action='append', dest='reviewers',
  102. help='Request reviews from these people.')
  103. p.add_option('--cc',
  104. type='string', action='append', dest='cc',
  105. help='Also send email to these email addresses.')
  106. p.add_option('--br',
  107. type='string', action='store', dest='branch',
  108. help='Branch to upload.')
  109. p.add_option('--cbr', '--current-branch',
  110. dest='current_branch', action='store_true',
  111. help='Upload current git branch.')
  112. p.add_option('-d', '--draft',
  113. action='store_true', dest='draft', default=False,
  114. help='If specified, upload as a draft.')
  115. # Options relating to upload hook. Note that verify and no-verify are NOT
  116. # opposites of each other, which is why they store to different locations.
  117. # We are using them to match 'git commit' syntax.
  118. #
  119. # Combinations:
  120. # - no-verify=False, verify=False (DEFAULT):
  121. # If stdout is a tty, can prompt about running upload hooks if needed.
  122. # If user denies running hooks, the upload is cancelled. If stdout is
  123. # not a tty and we would need to prompt about upload hooks, upload is
  124. # cancelled.
  125. # - no-verify=False, verify=True:
  126. # Always run upload hooks with no prompt.
  127. # - no-verify=True, verify=False:
  128. # Never run upload hooks, but upload anyway (AKA bypass hooks).
  129. # - no-verify=True, verify=True:
  130. # Invalid
  131. p.add_option('--no-verify',
  132. dest='bypass_hooks', action='store_true',
  133. help='Do not run the upload hook.')
  134. p.add_option('--verify',
  135. dest='allow_all_hooks', action='store_true',
  136. help='Run the upload hook without prompting.')
  137. def _SingleBranch(self, opt, branch, people):
  138. project = branch.project
  139. name = branch.name
  140. remote = project.GetBranch(name).remote
  141. key = 'review.%s.autoupload' % remote.review
  142. answer = project.config.GetBoolean(key)
  143. if answer is False:
  144. _die("upload blocked by %s = false" % key)
  145. if answer is None:
  146. date = branch.date
  147. commit_list = branch.commits
  148. print 'Upload project %s/ to remote branch %s:' % (project.relpath, project.revisionExpr)
  149. print ' branch %s (%2d commit%s, %s):' % (
  150. name,
  151. len(commit_list),
  152. len(commit_list) != 1 and 's' or '',
  153. date)
  154. for commit in commit_list:
  155. print ' %s' % commit
  156. sys.stdout.write('to %s (y/N)? ' % remote.review)
  157. answer = sys.stdin.readline().strip()
  158. answer = answer in ('y', 'Y', 'yes', '1', 'true', 't')
  159. if answer:
  160. if len(branch.commits) > UNUSUAL_COMMIT_THRESHOLD:
  161. answer = _ConfirmManyUploads()
  162. if answer:
  163. self._UploadAndReport(opt, [branch], people)
  164. else:
  165. _die("upload aborted by user")
  166. def _MultipleBranches(self, opt, pending, people):
  167. projects = {}
  168. branches = {}
  169. script = []
  170. script.append('# Uncomment the branches to upload:')
  171. for project, avail in pending:
  172. script.append('#')
  173. script.append('# project %s/:' % project.relpath)
  174. b = {}
  175. for branch in avail:
  176. name = branch.name
  177. date = branch.date
  178. commit_list = branch.commits
  179. if b:
  180. script.append('#')
  181. script.append('# branch %s (%2d commit%s, %s) to remote branch %s:' % (
  182. name,
  183. len(commit_list),
  184. len(commit_list) != 1 and 's' or '',
  185. date,
  186. project.revisionExpr))
  187. for commit in commit_list:
  188. script.append('# %s' % commit)
  189. b[name] = branch
  190. projects[project.relpath] = project
  191. branches[project.name] = b
  192. script.append('')
  193. script = [ x.encode('utf-8')
  194. if issubclass(type(x), unicode)
  195. else x
  196. for x in script ]
  197. script = Editor.EditString("\n".join(script)).split("\n")
  198. project_re = re.compile(r'^#?\s*project\s*([^\s]+)/:$')
  199. branch_re = re.compile(r'^\s*branch\s*([^\s(]+)\s*\(.*')
  200. project = None
  201. todo = []
  202. for line in script:
  203. m = project_re.match(line)
  204. if m:
  205. name = m.group(1)
  206. project = projects.get(name)
  207. if not project:
  208. _die('project %s not available for upload', name)
  209. continue
  210. m = branch_re.match(line)
  211. if m:
  212. name = m.group(1)
  213. if not project:
  214. _die('project for branch %s not in script', name)
  215. branch = branches[project.name].get(name)
  216. if not branch:
  217. _die('branch %s not in %s', name, project.relpath)
  218. todo.append(branch)
  219. if not todo:
  220. _die("nothing uncommented for upload")
  221. many_commits = False
  222. for branch in todo:
  223. if len(branch.commits) > UNUSUAL_COMMIT_THRESHOLD:
  224. many_commits = True
  225. break
  226. if many_commits:
  227. if not _ConfirmManyUploads(multiple_branches=True):
  228. _die("upload aborted by user")
  229. self._UploadAndReport(opt, todo, people)
  230. def _AppendAutoCcList(self, branch, people):
  231. """
  232. Appends the list of users in the CC list in the git project's config if a
  233. non-empty reviewer list was found.
  234. """
  235. name = branch.name
  236. project = branch.project
  237. key = 'review.%s.autocopy' % project.GetBranch(name).remote.review
  238. raw_list = project.config.GetString(key)
  239. if not raw_list is None and len(people[0]) > 0:
  240. people[1].extend([entry.strip() for entry in raw_list.split(',')])
  241. def _FindGerritChange(self, branch):
  242. last_pub = branch.project.WasPublished(branch.name)
  243. if last_pub is None:
  244. return ""
  245. refs = branch.GetPublishedRefs()
  246. try:
  247. # refs/changes/XYZ/N --> XYZ
  248. return refs.get(last_pub).split('/')[-2]
  249. except:
  250. return ""
  251. def _UploadAndReport(self, opt, todo, original_people):
  252. have_errors = False
  253. for branch in todo:
  254. try:
  255. people = copy.deepcopy(original_people)
  256. self._AppendAutoCcList(branch, people)
  257. # Check if there are local changes that may have been forgotten
  258. if branch.project.HasChanges():
  259. key = 'review.%s.autoupload' % branch.project.remote.review
  260. answer = branch.project.config.GetBoolean(key)
  261. # if they want to auto upload, let's not ask because it could be automated
  262. if answer is None:
  263. sys.stdout.write('Uncommitted changes in ' + branch.project.name + ' (did you forget to amend?). Continue uploading? (y/N) ')
  264. a = sys.stdin.readline().strip().lower()
  265. if a not in ('y', 'yes', 't', 'true', 'on'):
  266. print >>sys.stderr, "skipping upload"
  267. branch.uploaded = False
  268. branch.error = 'User aborted'
  269. continue
  270. # Check if topic branches should be sent to the server during upload
  271. if opt.auto_topic is not True:
  272. key = 'review.%s.uploadtopic' % branch.project.remote.review
  273. opt.auto_topic = branch.project.config.GetBoolean(key)
  274. branch.UploadForReview(people, auto_topic=opt.auto_topic, draft=opt.draft)
  275. branch.uploaded = True
  276. except UploadError, e:
  277. branch.error = e
  278. branch.uploaded = False
  279. have_errors = True
  280. print >>sys.stderr, ''
  281. print >>sys.stderr, '----------------------------------------------------------------------'
  282. if have_errors:
  283. for branch in todo:
  284. if not branch.uploaded:
  285. if len(str(branch.error)) <= 30:
  286. fmt = ' (%s)'
  287. else:
  288. fmt = '\n (%s)'
  289. print >>sys.stderr, ('[FAILED] %-15s %-15s' + fmt) % (
  290. branch.project.relpath + '/', \
  291. branch.name, \
  292. str(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. branch = None
  307. if opt.branch:
  308. branch = opt.branch
  309. for project in project_list:
  310. if opt.current_branch:
  311. cbr = project.CurrentBranch
  312. avail = [project.GetUploadableBranch(cbr)] if cbr else None
  313. else:
  314. avail = project.GetUploadableBranches(branch)
  315. if avail:
  316. pending.append((project, avail))
  317. if pending and (not opt.bypass_hooks):
  318. hook = RepoHook('pre-upload', self.manifest.repo_hooks_project,
  319. self.manifest.topdir, abort_if_user_denies=True)
  320. pending_proj_names = [project.name for (project, avail) in pending]
  321. try:
  322. hook.Run(opt.allow_all_hooks, project_list=pending_proj_names)
  323. except HookError, e:
  324. print >>sys.stderr, "ERROR: %s" % str(e)
  325. return
  326. if opt.reviewers:
  327. reviewers = _SplitEmails(opt.reviewers)
  328. if opt.cc:
  329. cc = _SplitEmails(opt.cc)
  330. people = (reviewers,cc)
  331. if not pending:
  332. print >>sys.stdout, "no branches ready for upload"
  333. elif len(pending) == 1 and len(pending[0][1]) == 1:
  334. self._SingleBranch(opt, pending[0][1][0], people)
  335. else:
  336. self._MultipleBranches(opt, pending, people)