upload.py 21 KB

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