upload.py 14 KB

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