upload.py 15 KB

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