trychange.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. #!/usr/bin/python
  2. # Copyright (c) 2009 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Client-side script to send a try job to the try server. It communicates to
  6. the try server by either writting to a svn repository or by directly connecting
  7. to the server by HTTP.
  8. """
  9. import datetime
  10. import getpass
  11. import logging
  12. import optparse
  13. import os
  14. import shutil
  15. import sys
  16. import tempfile
  17. import traceback
  18. import urllib
  19. import gcl
  20. __version__ = '1.1'
  21. # Constants
  22. HELP_STRING = "Sorry, Tryserver is not available."
  23. SCRIPT_PATH = os.path.join('tools', 'tryserver', 'tryserver.py')
  24. USAGE = r"""%prog [options]
  25. Client-side script to send a try job to the try server. It communicates to
  26. the try server by either writting to a svn repository or by directly connecting
  27. to the server by HTTP.
  28. Examples:
  29. A git patch off a web site (git inserts a/ and b/) and fix the base dir:
  30. %prog --url http://url/to/patch.diff --patchlevel 1 --root src
  31. Use svn to store the try job, specify an alternate email address and use a
  32. premade diff file on the local drive:
  33. %prog --email user@example.com
  34. --svn_repo svn://svn.chromium.org/chrome-try/try --diff foo.diff
  35. Running only on a 'mac' slave with revision src@123 and clobber first; specify
  36. manually the 3 source files to use for the try job:
  37. %prog --bot mac --revision src@123 --clobber -f src/a.cc -f src/a.h
  38. -f include/b.h
  39. """
  40. class InvalidScript(Exception):
  41. def __str__(self):
  42. return self.args[0] + '\n' + HELP_STRING
  43. class NoTryServerAccess(Exception):
  44. def __str__(self):
  45. return self.args[0] + '\n' + HELP_STRING
  46. def PathDifference(root, subpath):
  47. """Returns the difference subpath minus root."""
  48. if subpath.find(root) != 0:
  49. return None
  50. # The + 1 is for the trailing / or \.
  51. return subpath[len(root) + len(os.sep):]
  52. def GetSourceRoot():
  53. """Returns the absolute directory one level up from the repository root."""
  54. return os.path.abspath(os.path.join(gcl.GetRepositoryRoot(), '..'))
  55. def ExecuteTryServerScript():
  56. """Locates the tryserver script, executes it and returns its dictionary.
  57. The try server script contains the repository-specific try server commands."""
  58. script_locals = {}
  59. try:
  60. # gcl.GetRepositoryRoot() may throw an exception.
  61. script_path = os.path.join(gcl.GetRepositoryRoot(), SCRIPT_PATH)
  62. except Exception:
  63. return script_locals
  64. if os.path.exists(script_path):
  65. try:
  66. exec(gcl.ReadFile(script_path), script_locals)
  67. except Exception, e:
  68. # TODO(maruel): Need to specialize the exception trapper.
  69. traceback.print_exc()
  70. raise InvalidScript('%s is invalid.' % script_path)
  71. return script_locals
  72. def EscapeDot(name):
  73. return name.replace('.', '-')
  74. def RunCommand(command):
  75. output, retcode = gcl.RunShellWithReturnCode(command)
  76. if retcode:
  77. raise NoTryServerAccess(' '.join(command) + '\nOuput:\n' + output)
  78. return output
  79. class SCM(object):
  80. """Simplistic base class to implement one function: ProcessOptions."""
  81. def __init__(self, options):
  82. self.options = options
  83. def ProcessOptions(self):
  84. raise Unimplemented
  85. class SVN(SCM):
  86. """Gathers the options and diff for a subversion checkout."""
  87. def GenerateDiff(self, files, root):
  88. """Returns a string containing the diff for the given file list.
  89. The files in the list should either be absolute paths or relative to the
  90. given root. If no root directory is provided, the repository root will be
  91. used.
  92. """
  93. previous_cwd = os.getcwd()
  94. if root is None:
  95. os.chdir(gcl.GetRepositoryRoot())
  96. else:
  97. os.chdir(root)
  98. diff = []
  99. for file in files:
  100. # Use svn info output instead of os.path.isdir because the latter fails
  101. # when the file is deleted.
  102. if gcl.GetSVNFileInfo(file).get("Node Kind") == "directory":
  103. continue
  104. # If the user specified a custom diff command in their svn config file,
  105. # then it'll be used when we do svn diff, which we don't want to happen
  106. # since we want the unified diff. Using --diff-cmd=diff doesn't always
  107. # work, since they can have another diff executable in their path that
  108. # gives different line endings. So we use a bogus temp directory as the
  109. # config directory, which gets around these problems.
  110. if sys.platform.startswith("win"):
  111. parent_dir = tempfile.gettempdir()
  112. else:
  113. parent_dir = sys.path[0] # tempdir is not secure.
  114. bogus_dir = os.path.join(parent_dir, "temp_svn_config")
  115. if not os.path.exists(bogus_dir):
  116. os.mkdir(bogus_dir)
  117. # Grabs the diff data.
  118. data = gcl.RunShell(["svn", "diff", "--config-dir", bogus_dir, file])
  119. # We know the diff will be incorrectly formatted. Fix it.
  120. if gcl.IsSVNMoved(file):
  121. # The file is "new" in the patch sense. Generate a homebrew diff.
  122. # We can't use ReadFile() since it's not using binary mode.
  123. file_handle = open(file, 'rb')
  124. file_content = file_handle.read()
  125. file_handle.close()
  126. # Prepend '+ ' to every lines.
  127. file_content = ['+ ' + i for i in file_content.splitlines(True)]
  128. nb_lines = len(file_content)
  129. # We need to use / since patch on unix will fail otherwise.
  130. file = file.replace('\\', '/')
  131. data = "Index: %s\n" % file
  132. data += ("============================================================="
  133. "======\n")
  134. # Note: Should we use /dev/null instead?
  135. data += "--- %s\n" % file
  136. data += "+++ %s\n" % file
  137. data += "@@ -0,0 +1,%d @@\n" % nb_lines
  138. data += ''.join(file_content)
  139. diff.append(data)
  140. os.chdir(previous_cwd)
  141. return "".join(diff)
  142. def ProcessOptions(self):
  143. if not self.options.diff:
  144. # Generate the diff with svn and write it to the submit queue path. The
  145. # files are relative to the repository root, but we need patches relative
  146. # to one level up from there (i.e., 'src'), so adjust both the file
  147. # paths and the root of the diff.
  148. source_root = GetSourceRoot()
  149. prefix = PathDifference(source_root, gcl.GetRepositoryRoot())
  150. adjusted_paths = [os.path.join(prefix, x) for x in self.options.files]
  151. self.options.diff = self.GenerateDiff(adjusted_paths, root=source_root)
  152. class GIT(SCM):
  153. """Gathers the options and diff for a git checkout."""
  154. def GenerateDiff(self):
  155. """Get the diff we'll send to the try server. We ignore the files list."""
  156. branch = upload.RunShell(['git', 'cl', 'upstream']).strip()
  157. diff = upload.RunShell(['git', 'diff-tree', '-p', '--no-prefix',
  158. branch, 'HEAD']).splitlines(True)
  159. for i in range(len(diff)):
  160. # In the case of added files, replace /dev/null with the path to the
  161. # file being added.
  162. if diff[i].startswith('--- /dev/null'):
  163. diff[i] = '--- %s' % diff[i+1][4:]
  164. return ''.join(diff)
  165. def GetEmail(self):
  166. # TODO: check for errors here?
  167. return upload.RunShell(['git', 'config', 'user.email']).strip()
  168. def GetPatchName(self):
  169. """Construct a name for this patch."""
  170. # TODO: perhaps include the hash of the current commit, to distinguish
  171. # patches?
  172. branch = upload.RunShell(['git', 'symbolic-ref', 'HEAD']).strip()
  173. if not branch.startswith('refs/heads/'):
  174. raise "Couldn't figure out branch name"
  175. branch = branch[len('refs/heads/'):]
  176. return branch
  177. def ProcessOptions(self):
  178. if not self.options.diff:
  179. self.options.diff = self.GenerateDiff()
  180. if not self.options.name:
  181. self.options.name = self.GetPatchName()
  182. if not self.options.email:
  183. self.options.email = self.GetEmail()
  184. def _ParseSendChangeOptions(options):
  185. """Parse common options passed to _SendChangeHTTP and _SendChangeSVN."""
  186. values = {}
  187. if options.email:
  188. values['email'] = options.email
  189. values['user'] = options.user
  190. values['name'] = options.name
  191. if options.bot:
  192. values['bot'] = ','.join(options.bot)
  193. if options.revision:
  194. values['revision'] = options.revision
  195. if options.clobber:
  196. values['clobber'] = 'true'
  197. if options.tests:
  198. values['tests'] = ','.join(options.tests)
  199. if options.root:
  200. values['root'] = options.root
  201. if options.patchlevel:
  202. values['patchlevel'] = options.patchlevel
  203. if options.issue:
  204. values['issue'] = options.issue
  205. if options.patchset:
  206. values['patchset'] = options.patchset
  207. return values
  208. def _SendChangeHTTP(options):
  209. """Send a change to the try server using the HTTP protocol."""
  210. script_locals = ExecuteTryServerScript()
  211. if not options.host:
  212. options.host = script_locals.get('try_server_http_host', None)
  213. if not options.host:
  214. raise NoTryServerAccess('Please use the --host option to specify the try '
  215. 'server host to connect to.')
  216. if not options.port:
  217. options.port = script_locals.get('try_server_http_port', None)
  218. if not options.port:
  219. raise NoTryServerAccess('Please use the --port option to specify the try '
  220. 'server port to connect to.')
  221. values = _ParseSendChangeOptions(options)
  222. values['patch'] = options.diff
  223. url = 'http://%s:%s/send_try_patch' % (options.host, options.port)
  224. proxies = None
  225. if options.proxy:
  226. if options.proxy.lower() == 'none':
  227. # Effectively disable HTTP_PROXY or Internet settings proxy setup.
  228. proxies = {}
  229. else:
  230. proxies = {'http': options.proxy, 'https': options.proxy}
  231. try:
  232. connection = urllib.urlopen(url, urllib.urlencode(values), proxies=proxies)
  233. except IOError, e:
  234. # TODO(thestig) this probably isn't quite right.
  235. if values.get('bot') and e[2] == 'got a bad status line':
  236. raise NoTryServerAccess('%s is unaccessible. Bad --bot argument?' % url)
  237. else:
  238. raise NoTryServerAccess('%s is unaccessible.' % url)
  239. if not connection:
  240. raise NoTryServerAccess('%s is unaccessible.' % url)
  241. if connection.read() != 'OK':
  242. raise NoTryServerAccess('%s is unaccessible.' % url)
  243. return options.name
  244. def _SendChangeSVN(options):
  245. """Send a change to the try server by committing a diff file on a subversion
  246. server."""
  247. script_locals = ExecuteTryServerScript()
  248. if not options.svn_repo:
  249. options.svn_repo = script_locals.get('try_server_svn', None)
  250. if not options.svn_repo:
  251. raise NoTryServerAccess('Please use the --svn_repo option to specify the'
  252. ' try server svn repository to connect to.')
  253. values = _ParseSendChangeOptions(options)
  254. description = ''
  255. for (k,v) in values.iteritems():
  256. description += "%s=%s\n" % (k,v)
  257. # Do an empty checkout.
  258. temp_dir = tempfile.mkdtemp()
  259. temp_file = tempfile.NamedTemporaryFile()
  260. temp_file_name = temp_file.name
  261. try:
  262. RunCommand(['svn', 'checkout', '--depth', 'empty', '--non-interactive',
  263. options.svn_repo, temp_dir])
  264. # TODO(maruel): Use a subdirectory per user?
  265. current_time = str(datetime.datetime.now()).replace(':', '.')
  266. file_name = (EscapeDot(options.user) + '.' + EscapeDot(options.name) +
  267. '.%s.diff' % current_time)
  268. full_path = os.path.join(temp_dir, file_name)
  269. full_url = options.svn_repo + '/' + file_name
  270. file_found = False
  271. try:
  272. RunCommand(['svn', 'ls', '--non-interactive', full_url])
  273. file_found = True
  274. except NoTryServerAccess:
  275. pass
  276. if file_found:
  277. # The file already exists in the repo. Note that commiting a file is a
  278. # no-op if the file's content (the diff) is not modified. This is why the
  279. # file name contains the date and time.
  280. RunCommand(['svn', 'update', '--non-interactive', full_path])
  281. file = open(full_path, 'wb')
  282. file.write(options.diff)
  283. file.close()
  284. else:
  285. # Add the file to the repo
  286. file = open(full_path, 'wb')
  287. file.write(options.diff)
  288. file.close()
  289. RunCommand(["svn", "add", '--non-interactive', full_path])
  290. temp_file.write(description)
  291. temp_file.flush()
  292. RunCommand(["svn", "commit", '--non-interactive', full_path, '--file',
  293. temp_file_name])
  294. finally:
  295. temp_file.close()
  296. shutil.rmtree(temp_dir, True)
  297. return options.name
  298. def GuessVCS(options):
  299. """Helper to guess the version control system.
  300. NOTE: Very similar to upload.GuessVCS. Doesn't look for hg since we don't
  301. support it yet.
  302. This examines the current directory, guesses which SCM we're using, and
  303. returns an instance of the appropriate class. Exit with an error if we can't
  304. figure it out.
  305. Returns:
  306. A SCM instance. Exits if the SCM can't be guessed.
  307. """
  308. # Subversion has a .svn in all working directories.
  309. if os.path.isdir('.svn'):
  310. logging.info("Guessed VCS = Subversion")
  311. return SVN(options)
  312. # Git has a command to test if you're in a git tree.
  313. # Try running it, but don't die if we don't have git installed.
  314. try:
  315. out, returncode = gcl.RunShellWithReturnCode(["git", "rev-parse",
  316. "--is-inside-work-tree"])
  317. if returncode == 0:
  318. logging.info("Guessed VCS = Git")
  319. return GIT(options)
  320. except OSError, (errno, message):
  321. if errno != 2: # ENOENT -- they don't have git installed.
  322. raise
  323. raise NoTryServerAccess("Could not guess version control system. "
  324. "Are you in a working copy directory?")
  325. def TryChange(argv,
  326. file_list,
  327. swallow_exception,
  328. prog=None):
  329. # Parse argv
  330. parser = optparse.OptionParser(usage=USAGE,
  331. version=__version__,
  332. prog=prog)
  333. group = optparse.OptionGroup(parser, "Result and status")
  334. group.add_option("-u", "--user", default=getpass.getuser(),
  335. help="Owner user name [default: %default]")
  336. group.add_option("-e", "--email", default=os.environ.get('EMAIL_ADDRESS'),
  337. help="Email address where to send the results. Use the "
  338. "EMAIL_ADDRESS environment variable to set the default "
  339. "email address [default: %default]")
  340. group.add_option("-n", "--name", default='Unnamed',
  341. help="Descriptive name of the try job")
  342. group.add_option("--issue", type='int',
  343. help="Update rietveld issue try job status")
  344. group.add_option("--patchset", type='int',
  345. help="Update rietveld issue try job status")
  346. parser.add_option_group(group)
  347. group = optparse.OptionGroup(parser, "Try job options")
  348. group.add_option("-b", "--bot", action="append",
  349. help="Only use specifics build slaves, ex: '--bot win' to "
  350. "run the try job only on the 'win' slave; see the try "
  351. "server watefall for the slave's name")
  352. group.add_option("-r", "--revision",
  353. help="Revision to use for the try job; default: the "
  354. "revision will be determined by the try server; see "
  355. "its waterfall for more info")
  356. group.add_option("-c", "--clobber", action="store_true",
  357. help="Force a clobber before building; e.g. don't do an "
  358. "incremental build")
  359. # Override the list of tests to run, use multiple times to list many tests
  360. # (or comma separated)
  361. group.add_option("-t", "--tests", action="append",
  362. help=optparse.SUPPRESS_HELP)
  363. parser.add_option_group(group)
  364. group = optparse.OptionGroup(parser, "Patch to run")
  365. group.add_option("-f", "--file", default=file_list, dest="files",
  366. metavar="FILE", action="append",
  367. help="Use many times to list the files to include in the "
  368. "try, relative to the repository root")
  369. group.add_option("--diff",
  370. help="File containing the diff to try")
  371. group.add_option("--url",
  372. help="Url where to grab a patch")
  373. group.add_option("--root",
  374. help="Root to use for the patch; base subdirectory for "
  375. "patch created in a subdirectory")
  376. group.add_option("--patchlevel", type='int', metavar="LEVEL",
  377. help="Used as -pN parameter to patch")
  378. parser.add_option_group(group)
  379. group = optparse.OptionGroup(parser, "Access the try server by HTTP")
  380. group.add_option("--use_http", action="store_const", const=_SendChangeHTTP,
  381. dest="send_patch", default=_SendChangeHTTP,
  382. help="Use HTTP to talk to the try server [default]")
  383. group.add_option("--host",
  384. help="Host address")
  385. group.add_option("--port",
  386. help="HTTP port")
  387. group.add_option("--proxy",
  388. help="HTTP proxy")
  389. parser.add_option_group(group)
  390. group = optparse.OptionGroup(parser, "Access the try server with SVN")
  391. group.add_option("--use_svn", action="store_const", const=_SendChangeSVN,
  392. dest="send_patch",
  393. help="Use SVN to talk to the try server")
  394. group.add_option("--svn_repo", metavar="SVN_URL",
  395. help="SVN url to use to write the changes in; --use_svn is "
  396. "implied when using --svn_repo")
  397. parser.add_option_group(group)
  398. options, args = parser.parse_args(argv)
  399. # Switch the default accordingly.
  400. if options.svn_repo:
  401. options.send_patch = _SendChangeSVN
  402. if len(args) == 1 and args[0] == 'help':
  403. parser.print_help()
  404. if (not options.files and (not options.issue and options.patchset) and
  405. not options.diff and not options.url):
  406. # TODO(maruel): It should just try the modified files showing up in a
  407. # svn status.
  408. print "Nothing to try, changelist is empty."
  409. return
  410. try:
  411. # Convert options.diff into the content of the diff.
  412. if options.url:
  413. options.diff = urllib.urlopen(options.url).read()
  414. elif options.diff:
  415. options.diff = gcl.ReadFile(options.diff)
  416. # Process the VCS in any case at least to retrieve the email address.
  417. try:
  418. options.scm = GuessVCS(options)
  419. options.scm.ProcessOptions()
  420. except NoTryServerAccess, e:
  421. # If we got the diff, we don't care.
  422. if not options.diff:
  423. raise
  424. # Send the patch.
  425. patch_name = options.send_patch(options)
  426. print 'Patch \'%s\' sent to try server.' % patch_name
  427. if patch_name == 'Unnamed':
  428. print "Note: use --name NAME to change the try's name."
  429. except (InvalidScript, NoTryServerAccess), e:
  430. if swallow_exception:
  431. return
  432. print e
  433. if __name__ == "__main__":
  434. TryChange(None, None, False)