upload.py 19 KB

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