upload.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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 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. RepoHook.AddOptionGroup(p, 'pre-upload')
  171. def _SingleBranch(self, opt, branch, people):
  172. project = branch.project
  173. name = branch.name
  174. remote = project.GetBranch(name).remote
  175. key = 'review.%s.autoupload' % remote.review
  176. answer = project.config.GetBoolean(key)
  177. if answer is False:
  178. _die("upload blocked by %s = false" % key)
  179. if answer is None:
  180. date = branch.date
  181. commit_list = branch.commits
  182. destination = opt.dest_branch or project.dest_branch or project.revisionExpr
  183. print('Upload project %s/ to remote branch %s%s:' %
  184. (project.relpath, destination, ' (private)' if opt.private else ''))
  185. print(' branch %s (%2d commit%s, %s):' % (
  186. name,
  187. len(commit_list),
  188. len(commit_list) != 1 and 's' or '',
  189. date))
  190. for commit in commit_list:
  191. print(' %s' % commit)
  192. print('to %s (y/N)? ' % remote.review, end='')
  193. # TODO: When we require Python 3, use flush=True w/print above.
  194. sys.stdout.flush()
  195. if opt.yes:
  196. print('<--yes>')
  197. answer = True
  198. else:
  199. answer = sys.stdin.readline().strip().lower()
  200. answer = answer in ('y', 'yes', '1', 'true', 't')
  201. if answer:
  202. if len(branch.commits) > UNUSUAL_COMMIT_THRESHOLD:
  203. answer = _ConfirmManyUploads()
  204. if answer:
  205. self._UploadAndReport(opt, [branch], people)
  206. else:
  207. _die("upload aborted by user")
  208. def _MultipleBranches(self, opt, pending, people):
  209. projects = {}
  210. branches = {}
  211. script = []
  212. script.append('# Uncomment the branches to upload:')
  213. for project, avail in pending:
  214. script.append('#')
  215. script.append('# project %s/:' % project.relpath)
  216. b = {}
  217. for branch in avail:
  218. if branch is None:
  219. continue
  220. name = branch.name
  221. date = branch.date
  222. commit_list = branch.commits
  223. if b:
  224. script.append('#')
  225. destination = opt.dest_branch or project.dest_branch or project.revisionExpr
  226. script.append('# branch %s (%2d commit%s, %s) to remote branch %s:' % (
  227. name,
  228. len(commit_list),
  229. len(commit_list) != 1 and 's' or '',
  230. date,
  231. destination))
  232. for commit in commit_list:
  233. script.append('# %s' % commit)
  234. b[name] = branch
  235. projects[project.relpath] = project
  236. branches[project.name] = b
  237. script.append('')
  238. script = Editor.EditString("\n".join(script)).split("\n")
  239. project_re = re.compile(r'^#?\s*project\s*([^\s]+)/:$')
  240. branch_re = re.compile(r'^\s*branch\s*([^\s(]+)\s*\(.*')
  241. project = None
  242. todo = []
  243. for line in script:
  244. m = project_re.match(line)
  245. if m:
  246. name = m.group(1)
  247. project = projects.get(name)
  248. if not project:
  249. _die('project %s not available for upload', name)
  250. continue
  251. m = branch_re.match(line)
  252. if m:
  253. name = m.group(1)
  254. if not project:
  255. _die('project for branch %s not in script', name)
  256. branch = branches[project.name].get(name)
  257. if not branch:
  258. _die('branch %s not in %s', name, project.relpath)
  259. todo.append(branch)
  260. if not todo:
  261. _die("nothing uncommented for upload")
  262. many_commits = False
  263. for branch in todo:
  264. if len(branch.commits) > UNUSUAL_COMMIT_THRESHOLD:
  265. many_commits = True
  266. break
  267. if many_commits:
  268. if not _ConfirmManyUploads(multiple_branches=True):
  269. _die("upload aborted by user")
  270. self._UploadAndReport(opt, todo, people)
  271. def _AppendAutoList(self, branch, people):
  272. """
  273. Appends the list of reviewers in the git project's config.
  274. Appends the list of users in the CC list in the git project's config if a
  275. non-empty reviewer list was found.
  276. """
  277. name = branch.name
  278. project = branch.project
  279. key = 'review.%s.autoreviewer' % project.GetBranch(name).remote.review
  280. raw_list = project.config.GetString(key)
  281. if raw_list is not None:
  282. people[0].extend([entry.strip() for entry in raw_list.split(',')])
  283. key = 'review.%s.autocopy' % project.GetBranch(name).remote.review
  284. raw_list = project.config.GetString(key)
  285. if raw_list is not None and len(people[0]) > 0:
  286. people[1].extend([entry.strip() for entry in raw_list.split(',')])
  287. def _FindGerritChange(self, branch):
  288. last_pub = branch.project.WasPublished(branch.name)
  289. if last_pub is None:
  290. return ""
  291. refs = branch.GetPublishedRefs()
  292. try:
  293. # refs/changes/XYZ/N --> XYZ
  294. return refs.get(last_pub).split('/')[-2]
  295. except (AttributeError, IndexError):
  296. return ""
  297. def _UploadAndReport(self, opt, todo, original_people):
  298. have_errors = False
  299. for branch in todo:
  300. try:
  301. people = copy.deepcopy(original_people)
  302. self._AppendAutoList(branch, people)
  303. # Check if there are local changes that may have been forgotten
  304. changes = branch.project.UncommitedFiles()
  305. if changes:
  306. key = 'review.%s.autoupload' % branch.project.remote.review
  307. answer = branch.project.config.GetBoolean(key)
  308. # if they want to auto upload, let's not ask because it could be automated
  309. if answer is None:
  310. print()
  311. print('Uncommitted changes in %s (did you forget to amend?):'
  312. % branch.project.name)
  313. print('\n'.join(changes))
  314. print('Continue uploading? (y/N) ', end='')
  315. # TODO: When we require Python 3, use flush=True w/print above.
  316. sys.stdout.flush()
  317. if opt.yes:
  318. print('<--yes>')
  319. a = 'yes'
  320. else:
  321. a = sys.stdin.readline().strip().lower()
  322. if a not in ('y', 'yes', 't', 'true', 'on'):
  323. print("skipping upload", file=sys.stderr)
  324. branch.uploaded = False
  325. branch.error = 'User aborted'
  326. continue
  327. # Check if topic branches should be sent to the server during upload
  328. if opt.auto_topic is not True:
  329. key = 'review.%s.uploadtopic' % branch.project.remote.review
  330. opt.auto_topic = branch.project.config.GetBoolean(key)
  331. def _ExpandCommaList(value):
  332. """Split |value| up into comma delimited entries."""
  333. if not value:
  334. return
  335. for ret in value.split(','):
  336. ret = ret.strip()
  337. if ret:
  338. yield ret
  339. # Check if hashtags should be included.
  340. key = 'review.%s.uploadhashtags' % branch.project.remote.review
  341. hashtags = set(_ExpandCommaList(branch.project.config.GetString(key)))
  342. for tag in opt.hashtags:
  343. hashtags.update(_ExpandCommaList(tag))
  344. if opt.hashtag_branch:
  345. hashtags.add(branch.name)
  346. # Check if labels should be included.
  347. key = 'review.%s.uploadlabels' % branch.project.remote.review
  348. labels = set(_ExpandCommaList(branch.project.config.GetString(key)))
  349. for label in opt.labels:
  350. labels.update(_ExpandCommaList(label))
  351. # Basic sanity check on label syntax.
  352. for label in labels:
  353. if not re.match(r'^.+[+-][0-9]+$', label):
  354. print('repo: error: invalid label syntax "%s": labels use forms '
  355. 'like CodeReview+1 or Verified-1' % (label,), file=sys.stderr)
  356. sys.exit(1)
  357. # Handle e-mail notifications.
  358. if opt.notify is False:
  359. notify = 'NONE'
  360. else:
  361. key = 'review.%s.uploadnotify' % branch.project.remote.review
  362. notify = branch.project.config.GetString(key)
  363. destination = opt.dest_branch or branch.project.dest_branch
  364. # Make sure our local branch is not setup to track a different remote branch
  365. merge_branch = self._GetMergeBranch(branch.project)
  366. if destination:
  367. full_dest = destination
  368. if not full_dest.startswith(R_HEADS):
  369. full_dest = R_HEADS + full_dest
  370. if not opt.dest_branch and merge_branch and merge_branch != full_dest:
  371. print('merge branch %s does not match destination branch %s'
  372. % (merge_branch, full_dest))
  373. print('skipping upload.')
  374. print('Please use `--destination %s` if this is intentional'
  375. % destination)
  376. branch.uploaded = False
  377. continue
  378. branch.UploadForReview(people,
  379. dryrun=opt.dryrun,
  380. auto_topic=opt.auto_topic,
  381. hashtags=hashtags,
  382. labels=labels,
  383. private=opt.private,
  384. notify=notify,
  385. wip=opt.wip,
  386. dest_branch=destination,
  387. validate_certs=opt.validate_certs,
  388. push_options=opt.push_options)
  389. branch.uploaded = True
  390. except UploadError as e:
  391. branch.error = e
  392. branch.uploaded = False
  393. have_errors = True
  394. print(file=sys.stderr)
  395. print('----------------------------------------------------------------------', file=sys.stderr)
  396. if have_errors:
  397. for branch in todo:
  398. if not branch.uploaded:
  399. if len(str(branch.error)) <= 30:
  400. fmt = ' (%s)'
  401. else:
  402. fmt = '\n (%s)'
  403. print(('[FAILED] %-15s %-15s' + fmt) % (
  404. branch.project.relpath + '/',
  405. branch.name,
  406. str(branch.error)),
  407. file=sys.stderr)
  408. print()
  409. for branch in todo:
  410. if branch.uploaded:
  411. print('[OK ] %-15s %s' % (
  412. branch.project.relpath + '/',
  413. branch.name),
  414. file=sys.stderr)
  415. if have_errors:
  416. sys.exit(1)
  417. def _GetMergeBranch(self, project):
  418. p = GitCommand(project,
  419. ['rev-parse', '--abbrev-ref', 'HEAD'],
  420. capture_stdout=True,
  421. capture_stderr=True)
  422. p.Wait()
  423. local_branch = p.stdout.strip()
  424. p = GitCommand(project,
  425. ['config', '--get', 'branch.%s.merge' % local_branch],
  426. capture_stdout=True,
  427. capture_stderr=True)
  428. p.Wait()
  429. merge_branch = p.stdout.strip()
  430. return merge_branch
  431. def Execute(self, opt, args):
  432. project_list = self.GetProjects(args)
  433. pending = []
  434. reviewers = []
  435. cc = []
  436. branch = None
  437. if opt.branch:
  438. branch = opt.branch
  439. for project in project_list:
  440. if opt.current_branch:
  441. cbr = project.CurrentBranch
  442. up_branch = project.GetUploadableBranch(cbr)
  443. if up_branch:
  444. avail = [up_branch]
  445. else:
  446. avail = None
  447. print('repo: error: Unable to upload branch "%s". '
  448. 'You might be able to fix the branch by running:\n'
  449. ' git branch --set-upstream-to m/%s' %
  450. (str(cbr), self.manifest.branch),
  451. file=sys.stderr)
  452. else:
  453. avail = project.GetUploadableBranches(branch)
  454. if avail:
  455. pending.append((project, avail))
  456. if not pending:
  457. if branch is None:
  458. print('repo: error: no branches ready for upload', file=sys.stderr)
  459. else:
  460. print('repo: error: no branches named "%s" ready for upload' %
  461. (branch,), file=sys.stderr)
  462. return 1
  463. pending_proj_names = [project.name for (project, available) in pending]
  464. pending_worktrees = [project.worktree for (project, available) in pending]
  465. hook = RepoHook.FromSubcmd(
  466. hook_type='pre-upload', manifest=self.manifest,
  467. opt=opt, abort_if_user_denies=True)
  468. if not hook.Run(
  469. project_list=pending_proj_names,
  470. worktree_list=pending_worktrees):
  471. return 1
  472. if opt.reviewers:
  473. reviewers = _SplitEmails(opt.reviewers)
  474. if opt.cc:
  475. cc = _SplitEmails(opt.cc)
  476. people = (reviewers, cc)
  477. if len(pending) == 1 and len(pending[0][1]) == 1:
  478. self._SingleBranch(opt, pending[0][1][0], people)
  479. else:
  480. self._MultipleBranches(opt, pending, people)