upload.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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. import copy
  16. import re
  17. import sys
  18. from command import InteractiveCommand
  19. from editor import Editor
  20. from error import HookError, UploadError
  21. from project import RepoHook
  22. UNUSUAL_COMMIT_THRESHOLD = 5
  23. def _ConfirmManyUploads(multiple_branches=False):
  24. if multiple_branches:
  25. print "ATTENTION: One or more branches has an unusually high number of commits."
  26. else:
  27. print "ATTENTION: You are uploading an unusually high number of commits."
  28. print "YOU PROBABLY DO NOT MEAN TO DO THIS. (Did you rebase across branches?)"
  29. answer = raw_input("If you are sure you intend to do this, type 'yes': ").strip()
  30. return answer == "yes"
  31. def _die(fmt, *args):
  32. msg = fmt % args
  33. print >>sys.stderr, 'error: %s' % msg
  34. sys.exit(1)
  35. def _SplitEmails(values):
  36. result = []
  37. for str in values:
  38. result.extend([s.strip() for s in str.split(',')])
  39. return result
  40. class Upload(InteractiveCommand):
  41. common = True
  42. helpSummary = "Upload changes for code review"
  43. helpUsage="""
  44. %prog [--re --cc] [<project>]...
  45. """
  46. helpDescription = """
  47. The '%prog' command is used to send changes to the Gerrit Code
  48. Review system. It searches for topic branches in local projects
  49. that have not yet been published for review. If multiple topic
  50. branches are found, '%prog' opens an editor to allow the user to
  51. select which branches to upload.
  52. '%prog' searches for uploadable changes in all projects listed at
  53. the command line. Projects can be specified either by name, or by
  54. a relative or absolute path to the project's local directory. If no
  55. projects are specified, '%prog' will search for uploadable changes
  56. in all projects listed in the manifest.
  57. If the --reviewers or --cc options are passed, those emails are
  58. added to the respective list of users, and emails are sent to any
  59. new users. Users passed as --reviewers must already be registered
  60. with the code review system, or the upload will fail.
  61. Configuration
  62. -------------
  63. review.URL.autoupload:
  64. To disable the "Upload ... (y/N)?" prompt, you can set a per-project
  65. or global Git configuration option. If review.URL.autoupload is set
  66. to "true" then repo will assume you always answer "y" at the prompt,
  67. and will not prompt you further. If it is set to "false" then repo
  68. will assume you always answer "n", and will abort.
  69. review.URL.autocopy:
  70. To automatically copy a user or mailing list to all uploaded reviews,
  71. you can set a per-project or global Git option to do so. Specifically,
  72. review.URL.autocopy can be set to a comma separated list of reviewers
  73. who you always want copied on all uploads with a non-empty --re
  74. argument.
  75. review.URL.username:
  76. Override the username used to connect to Gerrit Code Review.
  77. By default the local part of the email address is used.
  78. The URL must match the review URL listed in the manifest XML file,
  79. or in the .git/config within the project. For example:
  80. [remote "origin"]
  81. url = git://git.example.com/project.git
  82. review = http://review.example.com/
  83. [review "http://review.example.com/"]
  84. autoupload = true
  85. autocopy = johndoe@company.com,my-team-alias@company.com
  86. review.URL.uploadtopic:
  87. To add a topic branch whenever uploading a commit, you can set a
  88. per-project or global Git option to do so. If review.URL.uploadtopic
  89. is set to "true" then repo will assume you always want the equivalent
  90. of the -t option to the repo command. If unset or set to "false" then
  91. repo will make use of only the command line option.
  92. References
  93. ----------
  94. Gerrit Code Review: http://code.google.com/p/gerrit/
  95. """
  96. def _Options(self, p):
  97. p.add_option('-t',
  98. dest='auto_topic', action='store_true',
  99. help='Send local branch name to Gerrit Code Review')
  100. p.add_option('--re', '--reviewers',
  101. type='string', action='append', dest='reviewers',
  102. help='Request reviews from these people.')
  103. p.add_option('--cc',
  104. type='string', action='append', dest='cc',
  105. help='Also send email to these email addresses.')
  106. p.add_option('--br',
  107. type='string', action='store', dest='branch',
  108. help='Branch to upload.')
  109. p.add_option('--cbr', '--current-branch',
  110. dest='current_branch', action='store_true',
  111. help='Upload current git branch.')
  112. # Options relating to upload hook. Note that verify and no-verify are NOT
  113. # opposites of each other, which is why they store to different locations.
  114. # We are using them to match 'git commit' syntax.
  115. #
  116. # Combinations:
  117. # - no-verify=False, verify=False (DEFAULT):
  118. # If stdout is a tty, can prompt about running upload hooks if needed.
  119. # If user denies running hooks, the upload is cancelled. If stdout is
  120. # not a tty and we would need to prompt about upload hooks, upload is
  121. # cancelled.
  122. # - no-verify=False, verify=True:
  123. # Always run upload hooks with no prompt.
  124. # - no-verify=True, verify=False:
  125. # Never run upload hooks, but upload anyway (AKA bypass hooks).
  126. # - no-verify=True, verify=True:
  127. # Invalid
  128. p.add_option('--no-verify',
  129. dest='bypass_hooks', action='store_true',
  130. help='Do not run the upload hook.')
  131. p.add_option('--verify',
  132. dest='allow_all_hooks', action='store_true',
  133. help='Run the upload hook without prompting.')
  134. def _SingleBranch(self, opt, branch, people):
  135. project = branch.project
  136. name = branch.name
  137. remote = project.GetBranch(name).remote
  138. key = 'review.%s.autoupload' % remote.review
  139. answer = project.config.GetBoolean(key)
  140. if answer is False:
  141. _die("upload blocked by %s = false" % key)
  142. if answer is None:
  143. date = branch.date
  144. list = branch.commits
  145. print 'Upload project %s/ to remote branch %s:' % (project.relpath, project.revisionExpr)
  146. print ' branch %s (%2d commit%s, %s):' % (
  147. name,
  148. len(list),
  149. len(list) != 1 and 's' or '',
  150. date)
  151. for commit in list:
  152. print ' %s' % commit
  153. sys.stdout.write('to %s (y/N)? ' % remote.review)
  154. answer = sys.stdin.readline().strip()
  155. answer = answer in ('y', 'Y', 'yes', '1', 'true', 't')
  156. if answer:
  157. if len(branch.commits) > UNUSUAL_COMMIT_THRESHOLD:
  158. answer = _ConfirmManyUploads()
  159. if answer:
  160. self._UploadAndReport(opt, [branch], people)
  161. else:
  162. _die("upload aborted by user")
  163. def _MultipleBranches(self, opt, pending, people):
  164. projects = {}
  165. branches = {}
  166. script = []
  167. script.append('# Uncomment the branches to upload:')
  168. for project, avail in pending:
  169. script.append('#')
  170. script.append('# project %s/:' % project.relpath)
  171. b = {}
  172. for branch in avail:
  173. name = branch.name
  174. date = branch.date
  175. list = branch.commits
  176. if b:
  177. script.append('#')
  178. script.append('# branch %s (%2d commit%s, %s) to remote branch %s:' % (
  179. name,
  180. len(list),
  181. len(list) != 1 and 's' or '',
  182. date,
  183. project.revisionExpr))
  184. for commit in list:
  185. script.append('# %s' % commit)
  186. b[name] = branch
  187. projects[project.relpath] = project
  188. branches[project.name] = b
  189. script.append('')
  190. script = [ x.encode('utf-8')
  191. if issubclass(type(x), unicode)
  192. else x
  193. for x in script ]
  194. script = Editor.EditString("\n".join(script)).split("\n")
  195. project_re = re.compile(r'^#?\s*project\s*([^\s]+)/:$')
  196. branch_re = re.compile(r'^\s*branch\s*([^\s(]+)\s*\(.*')
  197. project = None
  198. todo = []
  199. for line in script:
  200. m = project_re.match(line)
  201. if m:
  202. name = m.group(1)
  203. project = projects.get(name)
  204. if not project:
  205. _die('project %s not available for upload', name)
  206. continue
  207. m = branch_re.match(line)
  208. if m:
  209. name = m.group(1)
  210. if not project:
  211. _die('project for branch %s not in script', name)
  212. branch = branches[project.name].get(name)
  213. if not branch:
  214. _die('branch %s not in %s', name, project.relpath)
  215. todo.append(branch)
  216. if not todo:
  217. _die("nothing uncommented for upload")
  218. many_commits = False
  219. for branch in todo:
  220. if len(branch.commits) > UNUSUAL_COMMIT_THRESHOLD:
  221. many_commits = True
  222. break
  223. if many_commits:
  224. if not _ConfirmManyUploads(multiple_branches=True):
  225. _die("upload aborted by user")
  226. self._UploadAndReport(opt, todo, people)
  227. def _AppendAutoCcList(self, branch, people):
  228. """
  229. Appends the list of users in the CC list in the git project's config if a
  230. non-empty reviewer list was found.
  231. """
  232. name = branch.name
  233. project = branch.project
  234. key = 'review.%s.autocopy' % project.GetBranch(name).remote.review
  235. raw_list = project.config.GetString(key)
  236. if not raw_list is None and len(people[0]) > 0:
  237. people[1].extend([entry.strip() for entry in raw_list.split(',')])
  238. def _FindGerritChange(self, branch):
  239. last_pub = branch.project.WasPublished(branch.name)
  240. if last_pub is None:
  241. return ""
  242. refs = branch.GetPublishedRefs()
  243. try:
  244. # refs/changes/XYZ/N --> XYZ
  245. return refs.get(last_pub).split('/')[-2]
  246. except:
  247. return ""
  248. def _UploadAndReport(self, opt, todo, original_people):
  249. have_errors = False
  250. for branch in todo:
  251. try:
  252. people = copy.deepcopy(original_people)
  253. self._AppendAutoCcList(branch, people)
  254. # Check if there are local changes that may have been forgotten
  255. if branch.project.HasChanges():
  256. key = 'review.%s.autoupload' % branch.project.remote.review
  257. answer = branch.project.config.GetBoolean(key)
  258. # if they want to auto upload, let's not ask because it could be automated
  259. if answer is None:
  260. sys.stdout.write('Uncommitted changes in ' + branch.project.name + ' (did you forget to amend?). Continue uploading? (y/N) ')
  261. a = sys.stdin.readline().strip().lower()
  262. if a not in ('y', 'yes', 't', 'true', 'on'):
  263. print >>sys.stderr, "skipping upload"
  264. branch.uploaded = False
  265. branch.error = 'User aborted'
  266. continue
  267. # Check if topic branches should be sent to the server during upload
  268. if opt.auto_topic is not True:
  269. key = 'review.%s.uploadtopic' % branch.project.remote.review
  270. opt.auto_topic = branch.project.config.GetBoolean(key)
  271. branch.UploadForReview(people, auto_topic=opt.auto_topic)
  272. branch.uploaded = True
  273. except UploadError, e:
  274. branch.error = e
  275. branch.uploaded = False
  276. have_errors = True
  277. print >>sys.stderr, ''
  278. print >>sys.stderr, '----------------------------------------------------------------------'
  279. if have_errors:
  280. for branch in todo:
  281. if not branch.uploaded:
  282. if len(str(branch.error)) <= 30:
  283. fmt = ' (%s)'
  284. else:
  285. fmt = '\n (%s)'
  286. print >>sys.stderr, ('[FAILED] %-15s %-15s' + fmt) % (
  287. branch.project.relpath + '/', \
  288. branch.name, \
  289. str(branch.error))
  290. print >>sys.stderr, ''
  291. for branch in todo:
  292. if branch.uploaded:
  293. print >>sys.stderr, '[OK ] %-15s %s' % (
  294. branch.project.relpath + '/',
  295. branch.name)
  296. if have_errors:
  297. sys.exit(1)
  298. def Execute(self, opt, args):
  299. project_list = self.GetProjects(args)
  300. pending = []
  301. reviewers = []
  302. cc = []
  303. branch = None
  304. if opt.branch:
  305. branch = opt.branch
  306. for project in project_list:
  307. if opt.current_branch:
  308. cbr = project.CurrentBranch
  309. avail = [project.GetUploadableBranch(cbr)] if cbr else None
  310. else:
  311. avail = project.GetUploadableBranches(branch)
  312. if avail:
  313. pending.append((project, avail))
  314. if pending and (not opt.bypass_hooks):
  315. hook = RepoHook('pre-upload', self.manifest.repo_hooks_project,
  316. self.manifest.topdir, abort_if_user_denies=True)
  317. pending_proj_names = [project.name for (project, avail) in pending]
  318. try:
  319. hook.Run(opt.allow_all_hooks, project_list=pending_proj_names)
  320. except HookError, e:
  321. print >>sys.stderr, "ERROR: %s" % str(e)
  322. return
  323. if opt.reviewers:
  324. reviewers = _SplitEmails(opt.reviewers)
  325. if opt.cc:
  326. cc = _SplitEmails(opt.cc)
  327. people = (reviewers,cc)
  328. if not pending:
  329. print >>sys.stdout, "no branches ready for upload"
  330. elif len(pending) == 1 and len(pending[0][1]) == 1:
  331. self._SingleBranch(opt, pending[0][1][0], people)
  332. else:
  333. self._MultipleBranches(opt, pending, people)