upload.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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. # pylint:disable=W0622
  26. if not is_python3():
  27. input = raw_input
  28. else:
  29. unicode = str
  30. # pylint:enable=W0622
  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. -------------
  74. review.URL.autoupload:
  75. To disable the "Upload ... (y/N)?" prompt, you can set a per-project
  76. or global Git configuration option. If review.URL.autoupload is set
  77. to "true" then repo will assume you always answer "y" at the prompt,
  78. and will not prompt you further. If it is set to "false" then repo
  79. will assume you always answer "n", and will abort.
  80. review.URL.autoreviewer:
  81. To automatically append a user or mailing list to reviews, you can set
  82. a per-project or global Git option to do so.
  83. review.URL.autocopy:
  84. To automatically copy a user or mailing list to all uploaded reviews,
  85. you can set a per-project or global Git option to do so. Specifically,
  86. review.URL.autocopy can be set to a comma separated list of reviewers
  87. who you always want copied on all uploads with a non-empty --re
  88. argument.
  89. review.URL.username:
  90. Override the username used to connect to Gerrit Code Review.
  91. By default the local part of the email address is used.
  92. The URL must match the review URL listed in the manifest XML file,
  93. or in the .git/config within the project. For example:
  94. [remote "origin"]
  95. url = git://git.example.com/project.git
  96. review = http://review.example.com/
  97. [review "http://review.example.com/"]
  98. autoupload = true
  99. autocopy = johndoe@company.com,my-team-alias@company.com
  100. review.URL.uploadtopic:
  101. To add a topic branch whenever uploading a commit, you can set a
  102. per-project or global Git option to do so. If review.URL.uploadtopic
  103. is set to "true" then repo will assume you always want the equivalent
  104. of the -t option to the repo command. If unset or set to "false" then
  105. repo will make use of only the command line option.
  106. References
  107. ----------
  108. Gerrit Code Review: http://code.google.com/p/gerrit/
  109. """
  110. def _Options(self, p):
  111. p.add_option('-t',
  112. dest='auto_topic', action='store_true',
  113. help='Send local branch name to Gerrit Code Review')
  114. p.add_option('--re', '--reviewers',
  115. type='string', action='append', dest='reviewers',
  116. help='Request reviews from these people.')
  117. p.add_option('--cc',
  118. type='string', action='append', dest='cc',
  119. help='Also send email to these email addresses.')
  120. p.add_option('--br',
  121. type='string', action='store', dest='branch',
  122. help='Branch to upload.')
  123. p.add_option('--cbr', '--current-branch',
  124. dest='current_branch', action='store_true',
  125. help='Upload current git branch.')
  126. p.add_option('-d', '--draft',
  127. action='store_true', dest='draft', default=False,
  128. help='If specified, upload as a draft.')
  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. # Options relating to upload hook. Note that verify and no-verify are NOT
  144. # opposites of each other, which is why they store to different locations.
  145. # We are using them to match 'git commit' syntax.
  146. #
  147. # Combinations:
  148. # - no-verify=False, verify=False (DEFAULT):
  149. # If stdout is a tty, can prompt about running upload hooks if needed.
  150. # If user denies running hooks, the upload is cancelled. If stdout is
  151. # not a tty and we would need to prompt about upload hooks, upload is
  152. # cancelled.
  153. # - no-verify=False, verify=True:
  154. # Always run upload hooks with no prompt.
  155. # - no-verify=True, verify=False:
  156. # Never run upload hooks, but upload anyway (AKA bypass hooks).
  157. # - no-verify=True, verify=True:
  158. # Invalid
  159. p.add_option('--no-cert-checks',
  160. dest='validate_certs', action='store_false', default=True,
  161. help='Disable verifying ssl certs (unsafe).')
  162. p.add_option('--no-verify',
  163. dest='bypass_hooks', action='store_true',
  164. help='Do not run the upload hook.')
  165. p.add_option('--verify',
  166. dest='allow_all_hooks', action='store_true',
  167. help='Run the upload hook without prompting.')
  168. def _SingleBranch(self, opt, branch, people):
  169. project = branch.project
  170. name = branch.name
  171. remote = project.GetBranch(name).remote
  172. key = 'review.%s.autoupload' % remote.review
  173. answer = project.config.GetBoolean(key)
  174. if answer is False:
  175. _die("upload blocked by %s = false" % key)
  176. if answer is None:
  177. date = branch.date
  178. commit_list = branch.commits
  179. destination = opt.dest_branch or project.dest_branch or project.revisionExpr
  180. print('Upload project %s/ to remote branch %s%s:' %
  181. (project.relpath, destination, ' (draft)' if opt.draft else ''))
  182. print(' branch %s (%2d commit%s, %s):' % (
  183. name,
  184. len(commit_list),
  185. len(commit_list) != 1 and 's' or '',
  186. date))
  187. for commit in commit_list:
  188. print(' %s' % commit)
  189. sys.stdout.write('to %s (y/N)? ' % remote.review)
  190. answer = sys.stdin.readline().strip().lower()
  191. answer = answer in ('y', 'yes', '1', 'true', 't')
  192. if answer:
  193. if len(branch.commits) > UNUSUAL_COMMIT_THRESHOLD:
  194. answer = _ConfirmManyUploads()
  195. if answer:
  196. self._UploadAndReport(opt, [branch], people)
  197. else:
  198. _die("upload aborted by user")
  199. def _MultipleBranches(self, opt, pending, people):
  200. projects = {}
  201. branches = {}
  202. script = []
  203. script.append('# Uncomment the branches to upload:')
  204. for project, avail in pending:
  205. script.append('#')
  206. script.append('# project %s/:' % project.relpath)
  207. b = {}
  208. for branch in avail:
  209. if branch is None:
  210. continue
  211. name = branch.name
  212. date = branch.date
  213. commit_list = branch.commits
  214. if b:
  215. script.append('#')
  216. destination = opt.dest_branch or project.dest_branch or project.revisionExpr
  217. script.append('# branch %s (%2d commit%s, %s) to remote branch %s:' % (
  218. name,
  219. len(commit_list),
  220. len(commit_list) != 1 and 's' or '',
  221. date,
  222. destination))
  223. for commit in commit_list:
  224. script.append('# %s' % commit)
  225. b[name] = branch
  226. projects[project.relpath] = project
  227. branches[project.name] = b
  228. script.append('')
  229. script = [ x.encode('utf-8')
  230. if issubclass(type(x), unicode)
  231. else x
  232. for x in script ]
  233. script = Editor.EditString("\n".join(script)).split("\n")
  234. project_re = re.compile(r'^#?\s*project\s*([^\s]+)/:$')
  235. branch_re = re.compile(r'^\s*branch\s*([^\s(]+)\s*\(.*')
  236. project = None
  237. todo = []
  238. for line in script:
  239. m = project_re.match(line)
  240. if m:
  241. name = m.group(1)
  242. project = projects.get(name)
  243. if not project:
  244. _die('project %s not available for upload', name)
  245. continue
  246. m = branch_re.match(line)
  247. if m:
  248. name = m.group(1)
  249. if not project:
  250. _die('project for branch %s not in script', name)
  251. branch = branches[project.name].get(name)
  252. if not branch:
  253. _die('branch %s not in %s', name, project.relpath)
  254. todo.append(branch)
  255. if not todo:
  256. _die("nothing uncommented for upload")
  257. many_commits = False
  258. for branch in todo:
  259. if len(branch.commits) > UNUSUAL_COMMIT_THRESHOLD:
  260. many_commits = True
  261. break
  262. if many_commits:
  263. if not _ConfirmManyUploads(multiple_branches=True):
  264. _die("upload aborted by user")
  265. self._UploadAndReport(opt, todo, people)
  266. def _AppendAutoList(self, branch, people):
  267. """
  268. Appends the list of reviewers in the git project's config.
  269. Appends the list of users in the CC list in the git project's config if a
  270. non-empty reviewer list was found.
  271. """
  272. name = branch.name
  273. project = branch.project
  274. key = 'review.%s.autoreviewer' % project.GetBranch(name).remote.review
  275. raw_list = project.config.GetString(key)
  276. if not raw_list is None:
  277. people[0].extend([entry.strip() for entry in raw_list.split(',')])
  278. key = 'review.%s.autocopy' % project.GetBranch(name).remote.review
  279. raw_list = project.config.GetString(key)
  280. if not raw_list is None and len(people[0]) > 0:
  281. people[1].extend([entry.strip() for entry in raw_list.split(',')])
  282. def _FindGerritChange(self, branch):
  283. last_pub = branch.project.WasPublished(branch.name)
  284. if last_pub is None:
  285. return ""
  286. refs = branch.GetPublishedRefs()
  287. try:
  288. # refs/changes/XYZ/N --> XYZ
  289. return refs.get(last_pub).split('/')[-2]
  290. except (AttributeError, IndexError):
  291. return ""
  292. def _UploadAndReport(self, opt, todo, original_people):
  293. have_errors = False
  294. for branch in todo:
  295. try:
  296. people = copy.deepcopy(original_people)
  297. self._AppendAutoList(branch, people)
  298. # Check if there are local changes that may have been forgotten
  299. changes = branch.project.UncommitedFiles()
  300. if changes:
  301. key = 'review.%s.autoupload' % branch.project.remote.review
  302. answer = branch.project.config.GetBoolean(key)
  303. # if they want to auto upload, let's not ask because it could be automated
  304. if answer is None:
  305. sys.stdout.write('Uncommitted changes in ' + branch.project.name)
  306. sys.stdout.write(' (did you forget to amend?):\n')
  307. sys.stdout.write('\n'.join(changes) + '\n')
  308. sys.stdout.write('Continue uploading? (y/N) ')
  309. a = sys.stdin.readline().strip().lower()
  310. if a not in ('y', 'yes', 't', 'true', 'on'):
  311. print("skipping upload", file=sys.stderr)
  312. branch.uploaded = False
  313. branch.error = 'User aborted'
  314. continue
  315. # Check if topic branches should be sent to the server during upload
  316. if opt.auto_topic is not True:
  317. key = 'review.%s.uploadtopic' % branch.project.remote.review
  318. opt.auto_topic = branch.project.config.GetBoolean(key)
  319. destination = opt.dest_branch or branch.project.dest_branch
  320. # Make sure our local branch is not setup to track a different remote branch
  321. merge_branch = self._GetMergeBranch(branch.project)
  322. if destination:
  323. full_dest = 'refs/heads/%s' % destination
  324. if not opt.dest_branch and merge_branch and merge_branch != full_dest:
  325. print('merge branch %s does not match destination branch %s'
  326. % (merge_branch, full_dest))
  327. print('skipping upload.')
  328. print('Please use `--destination %s` if this is intentional'
  329. % destination)
  330. branch.uploaded = False
  331. continue
  332. branch.UploadForReview(people,
  333. auto_topic=opt.auto_topic,
  334. draft=opt.draft,
  335. private=opt.private,
  336. wip=opt.wip,
  337. dest_branch=destination,
  338. validate_certs=opt.validate_certs,
  339. push_options=opt.push_options)
  340. branch.uploaded = True
  341. except UploadError as e:
  342. branch.error = e
  343. branch.uploaded = False
  344. have_errors = True
  345. print(file=sys.stderr)
  346. print('----------------------------------------------------------------------', file=sys.stderr)
  347. if have_errors:
  348. for branch in todo:
  349. if not branch.uploaded:
  350. if len(str(branch.error)) <= 30:
  351. fmt = ' (%s)'
  352. else:
  353. fmt = '\n (%s)'
  354. print(('[FAILED] %-15s %-15s' + fmt) % (
  355. branch.project.relpath + '/', \
  356. branch.name, \
  357. str(branch.error)),
  358. file=sys.stderr)
  359. print()
  360. for branch in todo:
  361. if branch.uploaded:
  362. print('[OK ] %-15s %s' % (
  363. branch.project.relpath + '/',
  364. branch.name),
  365. file=sys.stderr)
  366. if have_errors:
  367. sys.exit(1)
  368. def _GetMergeBranch(self, project):
  369. p = GitCommand(project,
  370. ['rev-parse', '--abbrev-ref', 'HEAD'],
  371. capture_stdout = True,
  372. capture_stderr = True)
  373. p.Wait()
  374. local_branch = p.stdout.strip()
  375. p = GitCommand(project,
  376. ['config', '--get', 'branch.%s.merge' % local_branch],
  377. capture_stdout = True,
  378. capture_stderr = True)
  379. p.Wait()
  380. merge_branch = p.stdout.strip()
  381. return merge_branch
  382. def Execute(self, opt, args):
  383. project_list = self.GetProjects(args)
  384. pending = []
  385. reviewers = []
  386. cc = []
  387. branch = None
  388. if opt.branch:
  389. branch = opt.branch
  390. for project in project_list:
  391. if opt.current_branch:
  392. cbr = project.CurrentBranch
  393. up_branch = project.GetUploadableBranch(cbr)
  394. if up_branch:
  395. avail = [up_branch]
  396. else:
  397. avail = None
  398. print('ERROR: Current branch (%s) not uploadable. '
  399. 'You may be able to type '
  400. '"git branch --set-upstream-to m/master" to fix '
  401. 'your branch.' % str(cbr),
  402. file=sys.stderr)
  403. else:
  404. avail = project.GetUploadableBranches(branch)
  405. if avail:
  406. pending.append((project, avail))
  407. if not pending:
  408. print("no branches ready for upload", file=sys.stderr)
  409. return
  410. if not opt.bypass_hooks:
  411. hook = RepoHook('pre-upload', self.manifest.repo_hooks_project,
  412. self.manifest.topdir,
  413. self.manifest.manifestProject.GetRemote('origin').url,
  414. abort_if_user_denies=True)
  415. pending_proj_names = [project.name for (project, available) in pending]
  416. pending_worktrees = [project.worktree for (project, available) in pending]
  417. try:
  418. hook.Run(opt.allow_all_hooks, project_list=pending_proj_names,
  419. worktree_list=pending_worktrees)
  420. except HookError as e:
  421. print("ERROR: %s" % str(e), file=sys.stderr)
  422. return
  423. if opt.reviewers:
  424. reviewers = _SplitEmails(opt.reviewers)
  425. if opt.cc:
  426. cc = _SplitEmails(opt.cc)
  427. people = (reviewers, cc)
  428. if len(pending) == 1 and len(pending[0][1]) == 1:
  429. self._SingleBranch(opt, pending[0][1][0], people)
  430. else:
  431. self._MultipleBranches(opt, pending, people)