upload.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. # -*- coding:utf-8 -*-
  2. #
  3. # Copyright (C) 2008 The Android Open Source Project
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. from __future__ import print_function
  17. import copy
  18. import re
  19. import sys
  20. from command import InteractiveCommand
  21. from editor import Editor
  22. from error import HookError, UploadError
  23. from git_command import GitCommand
  24. from project import RepoHook
  25. from pyversion import is_python3
  26. if not is_python3():
  27. input = raw_input # noqa: F821
  28. else:
  29. unicode = str
  30. UNUSUAL_COMMIT_THRESHOLD = 5
  31. def _ConfirmManyUploads(multiple_branches=False):
  32. if multiple_branches:
  33. print('ATTENTION: One or more branches has an unusually high number '
  34. 'of commits.')
  35. else:
  36. print('ATTENTION: You are uploading an unusually high number of commits.')
  37. print('YOU PROBABLY DO NOT MEAN TO DO THIS. (Did you rebase across '
  38. 'branches?)')
  39. answer = input("If you are sure you intend to do this, type 'yes': ").strip()
  40. return answer == "yes"
  41. def _die(fmt, *args):
  42. msg = fmt % args
  43. print('error: %s' % msg, file=sys.stderr)
  44. sys.exit(1)
  45. def _SplitEmails(values):
  46. result = []
  47. for value in values:
  48. result.extend([s.strip() for s in value.split(',')])
  49. return result
  50. class Upload(InteractiveCommand):
  51. common = True
  52. helpSummary = "Upload changes for code review"
  53. helpUsage = """
  54. %prog [--re --cc] [<project>]...
  55. """
  56. helpDescription = """
  57. The '%prog' command is used to send changes to the Gerrit Code
  58. Review system. It searches for topic branches in local projects
  59. that have not yet been published for review. If multiple topic
  60. branches are found, '%prog' opens an editor to allow the user to
  61. select which branches to upload.
  62. '%prog' searches for uploadable changes in all projects listed at
  63. the command line. Projects can be specified either by name, or by
  64. a relative or absolute path to the project's local directory. If no
  65. projects are specified, '%prog' will search for uploadable changes
  66. in all projects listed in the manifest.
  67. If the --reviewers or --cc options are passed, those emails are
  68. added to the respective list of users, and emails are sent to any
  69. new users. Users passed as --reviewers must already be registered
  70. with the code review system, or the upload will fail.
  71. # Configuration
  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.autoreviewer:
  79. To automatically append a user or mailing list to reviews, you can set
  80. a per-project or global Git option to do so.
  81. review.URL.autocopy:
  82. To automatically copy a user or mailing list to all uploaded reviews,
  83. you can set a per-project or global Git option to do so. Specifically,
  84. review.URL.autocopy can be set to a comma separated list of reviewers
  85. who you always want copied on all uploads with a non-empty --re
  86. argument.
  87. review.URL.username:
  88. Override the username used to connect to Gerrit Code Review.
  89. By default the local part of the email address is used.
  90. The URL must match the review URL listed in the manifest XML file,
  91. or in the .git/config within the project. For example:
  92. [remote "origin"]
  93. url = git://git.example.com/project.git
  94. review = http://review.example.com/
  95. [review "http://review.example.com/"]
  96. autoupload = true
  97. autocopy = johndoe@company.com,my-team-alias@company.com
  98. review.URL.uploadtopic:
  99. To add a topic branch whenever uploading a commit, you can set a
  100. per-project or global Git option to do so. If review.URL.uploadtopic
  101. is set to "true" then repo will assume you always want the equivalent
  102. of the -t option to the repo command. If unset or set to "false" then
  103. repo will make use of only the command line option.
  104. # References
  105. Gerrit Code Review: https://www.gerritcodereview.com/
  106. """
  107. def _Options(self, p):
  108. p.add_option('-t',
  109. dest='auto_topic', action='store_true',
  110. help='Send local branch name to Gerrit Code Review')
  111. p.add_option('--re', '--reviewers',
  112. type='string', action='append', dest='reviewers',
  113. help='Request reviews from these people.')
  114. p.add_option('--cc',
  115. type='string', action='append', dest='cc',
  116. help='Also send email to these email addresses.')
  117. p.add_option('--br',
  118. type='string', action='store', dest='branch',
  119. help='Branch to upload.')
  120. p.add_option('--cbr', '--current-branch',
  121. dest='current_branch', action='store_true',
  122. help='Upload current git branch.')
  123. p.add_option('-d', '--draft',
  124. action='store_true', dest='draft', default=False,
  125. help='If specified, upload as a draft.')
  126. p.add_option('--ne', '--no-emails',
  127. action='store_false', dest='notify', default=True,
  128. help='If specified, do not send emails on upload.')
  129. p.add_option('-p', '--private',
  130. action='store_true', dest='private', default=False,
  131. help='If specified, upload as a private change.')
  132. p.add_option('-w', '--wip',
  133. action='store_true', dest='wip', default=False,
  134. help='If specified, upload as a work-in-progress change.')
  135. p.add_option('-o', '--push-option',
  136. type='string', action='append', dest='push_options',
  137. default=[],
  138. help='Additional push options to transmit')
  139. p.add_option('-D', '--destination', '--dest',
  140. type='string', action='store', dest='dest_branch',
  141. metavar='BRANCH',
  142. help='Submit for review on this target branch.')
  143. p.add_option('--no-cert-checks',
  144. dest='validate_certs', action='store_false', default=True,
  145. help='Disable verifying ssl certs (unsafe).')
  146. # Options relating to upload hook. Note that verify and no-verify are NOT
  147. # opposites of each other, which is why they store to different locations.
  148. # We are using them to match 'git commit' syntax.
  149. #
  150. # Combinations:
  151. # - no-verify=False, verify=False (DEFAULT):
  152. # If stdout is a tty, can prompt about running upload hooks if needed.
  153. # If user denies running hooks, the upload is cancelled. If stdout is
  154. # not a tty and we would need to prompt about upload hooks, upload is
  155. # cancelled.
  156. # - no-verify=False, verify=True:
  157. # Always run upload hooks with no prompt.
  158. # - no-verify=True, verify=False:
  159. # Never run upload hooks, but upload anyway (AKA bypass hooks).
  160. # - no-verify=True, verify=True:
  161. # Invalid
  162. g = p.add_option_group('Upload hooks')
  163. g.add_option('--no-verify',
  164. dest='bypass_hooks', action='store_true',
  165. help='Do not run the upload hook.')
  166. g.add_option('--verify',
  167. dest='allow_all_hooks', action='store_true',
  168. help='Run the upload hook without prompting.')
  169. g.add_option('--ignore-hooks',
  170. dest='ignore_hooks', action='store_true',
  171. help='Do not abort uploading if upload hooks fail.')
  172. def _SingleBranch(self, opt, branch, people):
  173. project = branch.project
  174. name = branch.name
  175. remote = project.GetBranch(name).remote
  176. key = 'review.%s.autoupload' % remote.review
  177. answer = project.config.GetBoolean(key)
  178. if answer is False:
  179. _die("upload blocked by %s = false" % key)
  180. if answer is None:
  181. date = branch.date
  182. commit_list = branch.commits
  183. destination = opt.dest_branch or project.dest_branch or project.revisionExpr
  184. print('Upload project %s/ to remote branch %s%s:' %
  185. (project.relpath, destination, ' (draft)' if opt.draft else ''))
  186. print(' branch %s (%2d commit%s, %s):' % (
  187. name,
  188. len(commit_list),
  189. len(commit_list) != 1 and 's' or '',
  190. date))
  191. for commit in commit_list:
  192. print(' %s' % commit)
  193. print('to %s (y/N)? ' % remote.review, end='')
  194. # TODO: When we require Python 3, use flush=True w/print above.
  195. sys.stdout.flush()
  196. answer = sys.stdin.readline().strip().lower()
  197. answer = answer in ('y', 'yes', '1', 'true', 't')
  198. if answer:
  199. if len(branch.commits) > UNUSUAL_COMMIT_THRESHOLD:
  200. answer = _ConfirmManyUploads()
  201. if answer:
  202. self._UploadAndReport(opt, [branch], people)
  203. else:
  204. _die("upload aborted by user")
  205. def _MultipleBranches(self, opt, pending, people):
  206. projects = {}
  207. branches = {}
  208. script = []
  209. script.append('# Uncomment the branches to upload:')
  210. for project, avail in pending:
  211. script.append('#')
  212. script.append('# project %s/:' % project.relpath)
  213. b = {}
  214. for branch in avail:
  215. if branch is None:
  216. continue
  217. name = branch.name
  218. date = branch.date
  219. commit_list = branch.commits
  220. if b:
  221. script.append('#')
  222. destination = opt.dest_branch or project.dest_branch or project.revisionExpr
  223. script.append('# branch %s (%2d commit%s, %s) to remote branch %s:' % (
  224. name,
  225. len(commit_list),
  226. len(commit_list) != 1 and 's' or '',
  227. date,
  228. destination))
  229. for commit in commit_list:
  230. script.append('# %s' % commit)
  231. b[name] = branch
  232. projects[project.relpath] = project
  233. branches[project.name] = b
  234. script.append('')
  235. script = Editor.EditString("\n".join(script)).split("\n")
  236. project_re = re.compile(r'^#?\s*project\s*([^\s]+)/:$')
  237. branch_re = re.compile(r'^\s*branch\s*([^\s(]+)\s*\(.*')
  238. project = None
  239. todo = []
  240. for line in script:
  241. m = project_re.match(line)
  242. if m:
  243. name = m.group(1)
  244. project = projects.get(name)
  245. if not project:
  246. _die('project %s not available for upload', name)
  247. continue
  248. m = branch_re.match(line)
  249. if m:
  250. name = m.group(1)
  251. if not project:
  252. _die('project for branch %s not in script', name)
  253. branch = branches[project.name].get(name)
  254. if not branch:
  255. _die('branch %s not in %s', name, project.relpath)
  256. todo.append(branch)
  257. if not todo:
  258. _die("nothing uncommented for upload")
  259. many_commits = False
  260. for branch in todo:
  261. if len(branch.commits) > UNUSUAL_COMMIT_THRESHOLD:
  262. many_commits = True
  263. break
  264. if many_commits:
  265. if not _ConfirmManyUploads(multiple_branches=True):
  266. _die("upload aborted by user")
  267. self._UploadAndReport(opt, todo, people)
  268. def _AppendAutoList(self, branch, people):
  269. """
  270. Appends the list of reviewers in the git project's config.
  271. Appends the list of users in the CC list in the git project's config if a
  272. non-empty reviewer list was found.
  273. """
  274. name = branch.name
  275. project = branch.project
  276. key = 'review.%s.autoreviewer' % project.GetBranch(name).remote.review
  277. raw_list = project.config.GetString(key)
  278. if raw_list is not None:
  279. people[0].extend([entry.strip() for entry in raw_list.split(',')])
  280. key = 'review.%s.autocopy' % project.GetBranch(name).remote.review
  281. raw_list = project.config.GetString(key)
  282. if raw_list is not None and len(people[0]) > 0:
  283. people[1].extend([entry.strip() for entry in raw_list.split(',')])
  284. def _FindGerritChange(self, branch):
  285. last_pub = branch.project.WasPublished(branch.name)
  286. if last_pub is None:
  287. return ""
  288. refs = branch.GetPublishedRefs()
  289. try:
  290. # refs/changes/XYZ/N --> XYZ
  291. return refs.get(last_pub).split('/')[-2]
  292. except (AttributeError, IndexError):
  293. return ""
  294. def _UploadAndReport(self, opt, todo, original_people):
  295. have_errors = False
  296. for branch in todo:
  297. try:
  298. people = copy.deepcopy(original_people)
  299. self._AppendAutoList(branch, people)
  300. # Check if there are local changes that may have been forgotten
  301. changes = branch.project.UncommitedFiles()
  302. if changes:
  303. key = 'review.%s.autoupload' % branch.project.remote.review
  304. answer = branch.project.config.GetBoolean(key)
  305. # if they want to auto upload, let's not ask because it could be automated
  306. if answer is None:
  307. print()
  308. print('Uncommitted changes in %s (did you forget to amend?):'
  309. % branch.project.name)
  310. print('\n'.join(changes))
  311. print('Continue uploading? (y/N) ', end='')
  312. # TODO: When we require Python 3, use flush=True w/print above.
  313. sys.stdout.flush()
  314. a = sys.stdin.readline().strip().lower()
  315. if a not in ('y', 'yes', 't', 'true', 'on'):
  316. print("skipping upload", file=sys.stderr)
  317. branch.uploaded = False
  318. branch.error = 'User aborted'
  319. continue
  320. # Check if topic branches should be sent to the server during upload
  321. if opt.auto_topic is not True:
  322. key = 'review.%s.uploadtopic' % branch.project.remote.review
  323. opt.auto_topic = branch.project.config.GetBoolean(key)
  324. destination = opt.dest_branch or branch.project.dest_branch
  325. # Make sure our local branch is not setup to track a different remote branch
  326. merge_branch = self._GetMergeBranch(branch.project)
  327. if destination:
  328. full_dest = 'refs/heads/%s' % destination
  329. if not opt.dest_branch and merge_branch and merge_branch != full_dest:
  330. print('merge branch %s does not match destination branch %s'
  331. % (merge_branch, full_dest))
  332. print('skipping upload.')
  333. print('Please use `--destination %s` if this is intentional'
  334. % destination)
  335. branch.uploaded = False
  336. continue
  337. branch.UploadForReview(people,
  338. auto_topic=opt.auto_topic,
  339. draft=opt.draft,
  340. private=opt.private,
  341. notify=None if opt.notify else 'NONE',
  342. wip=opt.wip,
  343. dest_branch=destination,
  344. validate_certs=opt.validate_certs,
  345. push_options=opt.push_options)
  346. branch.uploaded = True
  347. except UploadError as e:
  348. branch.error = e
  349. branch.uploaded = False
  350. have_errors = True
  351. print(file=sys.stderr)
  352. print('----------------------------------------------------------------------', file=sys.stderr)
  353. if have_errors:
  354. for branch in todo:
  355. if not branch.uploaded:
  356. if len(str(branch.error)) <= 30:
  357. fmt = ' (%s)'
  358. else:
  359. fmt = '\n (%s)'
  360. print(('[FAILED] %-15s %-15s' + fmt) % (
  361. branch.project.relpath + '/',
  362. branch.name,
  363. str(branch.error)),
  364. file=sys.stderr)
  365. print()
  366. for branch in todo:
  367. if branch.uploaded:
  368. print('[OK ] %-15s %s' % (
  369. branch.project.relpath + '/',
  370. branch.name),
  371. file=sys.stderr)
  372. if have_errors:
  373. sys.exit(1)
  374. def _GetMergeBranch(self, project):
  375. p = GitCommand(project,
  376. ['rev-parse', '--abbrev-ref', 'HEAD'],
  377. capture_stdout=True,
  378. capture_stderr=True)
  379. p.Wait()
  380. local_branch = p.stdout.strip()
  381. p = GitCommand(project,
  382. ['config', '--get', 'branch.%s.merge' % local_branch],
  383. capture_stdout=True,
  384. capture_stderr=True)
  385. p.Wait()
  386. merge_branch = p.stdout.strip()
  387. return merge_branch
  388. def Execute(self, opt, args):
  389. project_list = self.GetProjects(args)
  390. pending = []
  391. reviewers = []
  392. cc = []
  393. branch = None
  394. if opt.branch:
  395. branch = opt.branch
  396. for project in project_list:
  397. if opt.current_branch:
  398. cbr = project.CurrentBranch
  399. up_branch = project.GetUploadableBranch(cbr)
  400. if up_branch:
  401. avail = [up_branch]
  402. else:
  403. avail = None
  404. print('ERROR: Current branch (%s) not uploadable. '
  405. 'You may be able to type '
  406. '"git branch --set-upstream-to m/master" to fix '
  407. 'your branch.' % str(cbr),
  408. file=sys.stderr)
  409. else:
  410. avail = project.GetUploadableBranches(branch)
  411. if avail:
  412. pending.append((project, avail))
  413. if not pending:
  414. print("no branches ready for upload", file=sys.stderr)
  415. return
  416. if not opt.bypass_hooks:
  417. hook = RepoHook('pre-upload', self.manifest.repo_hooks_project,
  418. self.manifest.topdir,
  419. self.manifest.manifestProject.GetRemote('origin').url,
  420. abort_if_user_denies=True)
  421. pending_proj_names = [project.name for (project, available) in pending]
  422. pending_worktrees = [project.worktree for (project, available) in pending]
  423. passed = True
  424. try:
  425. hook.Run(opt.allow_all_hooks, project_list=pending_proj_names,
  426. worktree_list=pending_worktrees)
  427. except SystemExit:
  428. passed = False
  429. if not opt.ignore_hooks:
  430. raise
  431. except HookError as e:
  432. passed = False
  433. print("ERROR: %s" % str(e), file=sys.stderr)
  434. if not passed:
  435. if opt.ignore_hooks:
  436. print('\nWARNING: pre-upload hooks failed, but uploading anyways.',
  437. file=sys.stderr)
  438. else:
  439. return
  440. if opt.reviewers:
  441. reviewers = _SplitEmails(opt.reviewers)
  442. if opt.cc:
  443. cc = _SplitEmails(opt.cc)
  444. people = (reviewers, cc)
  445. if len(pending) == 1 and len(pending[0][1]) == 1:
  446. self._SingleBranch(opt, pending[0][1][0], people)
  447. else:
  448. self._MultipleBranches(opt, pending, people)