upload.py 16 KB

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