upload.py 14 KB

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