upload.py 18 KB

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