upload.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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. # pylint:disable=W0622
  27. input = raw_input
  28. # pylint:enable=W0622
  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('-D', '--destination', '--dest',
  128. type='string', action='store', dest='dest_branch',
  129. metavar='BRANCH',
  130. help='Submit for review on this target branch.')
  131. # Options relating to upload hook. Note that verify and no-verify are NOT
  132. # opposites of each other, which is why they store to different locations.
  133. # We are using them to match 'git commit' syntax.
  134. #
  135. # Combinations:
  136. # - no-verify=False, verify=False (DEFAULT):
  137. # If stdout is a tty, can prompt about running upload hooks if needed.
  138. # If user denies running hooks, the upload is cancelled. If stdout is
  139. # not a tty and we would need to prompt about upload hooks, upload is
  140. # cancelled.
  141. # - no-verify=False, verify=True:
  142. # Always run upload hooks with no prompt.
  143. # - no-verify=True, verify=False:
  144. # Never run upload hooks, but upload anyway (AKA bypass hooks).
  145. # - no-verify=True, verify=True:
  146. # Invalid
  147. p.add_option('--no-verify',
  148. dest='bypass_hooks', action='store_true',
  149. help='Do not run the upload hook.')
  150. p.add_option('--verify',
  151. dest='allow_all_hooks', action='store_true',
  152. help='Run the upload hook without prompting.')
  153. def _SingleBranch(self, opt, branch, people):
  154. project = branch.project
  155. name = branch.name
  156. remote = project.GetBranch(name).remote
  157. key = 'review.%s.autoupload' % remote.review
  158. answer = project.config.GetBoolean(key)
  159. if answer is False:
  160. _die("upload blocked by %s = false" % key)
  161. if answer is None:
  162. date = branch.date
  163. commit_list = branch.commits
  164. destination = opt.dest_branch or project.dest_branch or project.revisionExpr
  165. print('Upload project %s/ to remote branch %s:' % (project.relpath, destination))
  166. print(' branch %s (%2d commit%s, %s):' % (
  167. name,
  168. len(commit_list),
  169. len(commit_list) != 1 and 's' or '',
  170. date))
  171. for commit in commit_list:
  172. print(' %s' % commit)
  173. sys.stdout.write('to %s (y/N)? ' % remote.review)
  174. answer = sys.stdin.readline().strip().lower()
  175. answer = answer in ('y', 'yes', '1', 'true', 't')
  176. if answer:
  177. if len(branch.commits) > UNUSUAL_COMMIT_THRESHOLD:
  178. answer = _ConfirmManyUploads()
  179. if answer:
  180. self._UploadAndReport(opt, [branch], people)
  181. else:
  182. _die("upload aborted by user")
  183. def _MultipleBranches(self, opt, pending, people):
  184. projects = {}
  185. branches = {}
  186. script = []
  187. script.append('# Uncomment the branches to upload:')
  188. for project, avail in pending:
  189. script.append('#')
  190. script.append('# project %s/:' % project.relpath)
  191. b = {}
  192. for branch in avail:
  193. if branch is None:
  194. continue
  195. name = branch.name
  196. date = branch.date
  197. commit_list = branch.commits
  198. if b:
  199. script.append('#')
  200. destination = opt.dest_branch or project.dest_branch or project.revisionExpr
  201. script.append('# branch %s (%2d commit%s, %s) to remote branch %s:' % (
  202. name,
  203. len(commit_list),
  204. len(commit_list) != 1 and 's' or '',
  205. date,
  206. destination))
  207. for commit in commit_list:
  208. script.append('# %s' % commit)
  209. b[name] = branch
  210. projects[project.relpath] = project
  211. branches[project.name] = b
  212. script.append('')
  213. script = [ x.encode('utf-8')
  214. if issubclass(type(x), unicode)
  215. else x
  216. for x in script ]
  217. script = Editor.EditString("\n".join(script)).split("\n")
  218. project_re = re.compile(r'^#?\s*project\s*([^\s]+)/:$')
  219. branch_re = re.compile(r'^\s*branch\s*([^\s(]+)\s*\(.*')
  220. project = None
  221. todo = []
  222. for line in script:
  223. m = project_re.match(line)
  224. if m:
  225. name = m.group(1)
  226. project = projects.get(name)
  227. if not project:
  228. _die('project %s not available for upload', name)
  229. continue
  230. m = branch_re.match(line)
  231. if m:
  232. name = m.group(1)
  233. if not project:
  234. _die('project for branch %s not in script', name)
  235. branch = branches[project.name].get(name)
  236. if not branch:
  237. _die('branch %s not in %s', name, project.relpath)
  238. todo.append(branch)
  239. if not todo:
  240. _die("nothing uncommented for upload")
  241. many_commits = False
  242. for branch in todo:
  243. if len(branch.commits) > UNUSUAL_COMMIT_THRESHOLD:
  244. many_commits = True
  245. break
  246. if many_commits:
  247. if not _ConfirmManyUploads(multiple_branches=True):
  248. _die("upload aborted by user")
  249. self._UploadAndReport(opt, todo, people)
  250. def _AppendAutoList(self, branch, people):
  251. """
  252. Appends the list of reviewers in the git project's config.
  253. Appends the list of users in the CC list in the git project's config if a
  254. non-empty reviewer list was found.
  255. """
  256. name = branch.name
  257. project = branch.project
  258. key = 'review.%s.autoreviewer' % project.GetBranch(name).remote.review
  259. raw_list = project.config.GetString(key)
  260. if not raw_list is None:
  261. people[0].extend([entry.strip() for entry in raw_list.split(',')])
  262. key = 'review.%s.autocopy' % project.GetBranch(name).remote.review
  263. raw_list = project.config.GetString(key)
  264. if not raw_list is None and len(people[0]) > 0:
  265. people[1].extend([entry.strip() for entry in raw_list.split(',')])
  266. def _FindGerritChange(self, branch):
  267. last_pub = branch.project.WasPublished(branch.name)
  268. if last_pub is None:
  269. return ""
  270. refs = branch.GetPublishedRefs()
  271. try:
  272. # refs/changes/XYZ/N --> XYZ
  273. return refs.get(last_pub).split('/')[-2]
  274. except (AttributeError, IndexError):
  275. return ""
  276. def _UploadAndReport(self, opt, todo, original_people):
  277. have_errors = False
  278. for branch in todo:
  279. try:
  280. people = copy.deepcopy(original_people)
  281. self._AppendAutoList(branch, people)
  282. # Check if there are local changes that may have been forgotten
  283. if branch.project.HasChanges():
  284. key = 'review.%s.autoupload' % branch.project.remote.review
  285. answer = branch.project.config.GetBoolean(key)
  286. # if they want to auto upload, let's not ask because it could be automated
  287. if answer is None:
  288. sys.stdout.write('Uncommitted changes in ' + branch.project.name + ' (did you forget to amend?). Continue uploading? (y/N) ')
  289. a = sys.stdin.readline().strip().lower()
  290. if a not in ('y', 'yes', 't', 'true', 'on'):
  291. print("skipping upload", file=sys.stderr)
  292. branch.uploaded = False
  293. branch.error = 'User aborted'
  294. continue
  295. # Check if topic branches should be sent to the server during upload
  296. if opt.auto_topic is not True:
  297. key = 'review.%s.uploadtopic' % branch.project.remote.review
  298. opt.auto_topic = branch.project.config.GetBoolean(key)
  299. destination = opt.dest_branch or branch.project.dest_branch
  300. # Make sure our local branch is not setup to track a different remote branch
  301. merge_branch = self._GetMergeBranch(branch.project)
  302. if destination:
  303. full_dest = 'refs/heads/%s' % destination
  304. if not opt.dest_branch and merge_branch and merge_branch != full_dest:
  305. print('merge branch %s does not match destination branch %s'
  306. % (merge_branch, full_dest))
  307. print('skipping upload.')
  308. print('Please use `--destination %s` if this is intentional'
  309. % destination)
  310. branch.uploaded = False
  311. continue
  312. branch.UploadForReview(people, auto_topic=opt.auto_topic, draft=opt.draft, dest_branch=destination)
  313. branch.uploaded = True
  314. except UploadError as e:
  315. branch.error = e
  316. branch.uploaded = False
  317. have_errors = True
  318. print(file=sys.stderr)
  319. print('----------------------------------------------------------------------', file=sys.stderr)
  320. if have_errors:
  321. for branch in todo:
  322. if not branch.uploaded:
  323. if len(str(branch.error)) <= 30:
  324. fmt = ' (%s)'
  325. else:
  326. fmt = '\n (%s)'
  327. print(('[FAILED] %-15s %-15s' + fmt) % (
  328. branch.project.relpath + '/', \
  329. branch.name, \
  330. str(branch.error)),
  331. file=sys.stderr)
  332. print()
  333. for branch in todo:
  334. if branch.uploaded:
  335. print('[OK ] %-15s %s' % (
  336. branch.project.relpath + '/',
  337. branch.name),
  338. file=sys.stderr)
  339. if have_errors:
  340. sys.exit(1)
  341. def _GetMergeBranch(self, project):
  342. p = GitCommand(project,
  343. ['rev-parse', '--abbrev-ref', 'HEAD'],
  344. capture_stdout = True,
  345. capture_stderr = True)
  346. p.Wait()
  347. local_branch = p.stdout.strip()
  348. p = GitCommand(project,
  349. ['config', '--get', 'branch.%s.merge' % local_branch],
  350. capture_stdout = True,
  351. capture_stderr = True)
  352. p.Wait()
  353. merge_branch = p.stdout.strip()
  354. return merge_branch
  355. def Execute(self, opt, args):
  356. project_list = self.GetProjects(args)
  357. pending = []
  358. reviewers = []
  359. cc = []
  360. branch = None
  361. if opt.branch:
  362. branch = opt.branch
  363. for project in project_list:
  364. if opt.current_branch:
  365. cbr = project.CurrentBranch
  366. up_branch = project.GetUploadableBranch(cbr)
  367. if up_branch:
  368. avail = [up_branch]
  369. else:
  370. avail = None
  371. print('ERROR: Current branch (%s) not uploadable. '
  372. 'You may be able to type '
  373. '"git branch --set-upstream-to m/master" to fix '
  374. 'your branch.' % str(cbr),
  375. file=sys.stderr)
  376. else:
  377. avail = project.GetUploadableBranches(branch)
  378. if avail:
  379. pending.append((project, avail))
  380. if pending and (not opt.bypass_hooks):
  381. hook = RepoHook('pre-upload', self.manifest.repo_hooks_project,
  382. self.manifest.topdir, abort_if_user_denies=True)
  383. pending_proj_names = [project.name for (project, avail) in pending]
  384. pending_worktrees = [project.worktree for (project, avail) in pending]
  385. try:
  386. hook.Run(opt.allow_all_hooks, project_list=pending_proj_names,
  387. worktree_list=pending_worktrees)
  388. except HookError as e:
  389. print("ERROR: %s" % str(e), file=sys.stderr)
  390. return
  391. if opt.reviewers:
  392. reviewers = _SplitEmails(opt.reviewers)
  393. if opt.cc:
  394. cc = _SplitEmails(opt.cc)
  395. people = (reviewers, cc)
  396. if not pending:
  397. print("no branches ready for upload", file=sys.stderr)
  398. elif len(pending) == 1 and len(pending[0][1]) == 1:
  399. self._SingleBranch(opt, pending[0][1][0], people)
  400. else:
  401. self._MultipleBranches(opt, pending, people)