PageRenderTime 55ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/upload.py

http://testability-explorer.googlecode.com/
Python | 1389 lines | 1267 code | 23 blank | 99 comment | 49 complexity | dc3d71fd2b2a0afce7cc961fc85fe1b9 MD5 | raw file
Possible License(s): Apache-2.0
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2007 Google Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """Tool for uploading diffs from a version control system to the codereview app.
  17. Usage summary: upload.py [options] [-- diff_options]
  18. Diff options are passed to the diff command of the underlying system.
  19. Supported version control systems:
  20. Git
  21. Mercurial
  22. Subversion
  23. It is important for Git/Mercurial users to specify a tree/node/branch to diff
  24. against by using the '--rev' option.
  25. """
  26. # This code is derived from appcfg.py in the App Engine SDK (open source),
  27. # and from ASPN recipe #146306.
  28. # Defaults edited by alexeagle@google.com (Alex Eagle)
  29. import cookielib
  30. import getpass
  31. import logging
  32. import md5
  33. import mimetypes
  34. import optparse
  35. import os
  36. import re
  37. import socket
  38. import subprocess
  39. import sys
  40. import urllib
  41. import urllib2
  42. import urlparse
  43. try:
  44. import readline
  45. except ImportError:
  46. pass
  47. # The logging verbosity:
  48. # 0: Errors only.
  49. # 1: Status messages.
  50. # 2: Info logs.
  51. # 3: Debug logs.
  52. verbosity = 1
  53. # Max size of patch or base file.
  54. MAX_UPLOAD_SIZE = 900 * 1024
  55. def GetEmail(prompt):
  56. """Prompts the user for their email address and returns it.
  57. The last used email address is saved to a file and offered up as a suggestion
  58. to the user. If the user presses enter without typing in anything the last
  59. used email address is used. If the user enters a new address, it is saved
  60. for next time we prompt.
  61. """
  62. last_email_file_name = os.path.expanduser("~/.last_codereview_email_address")
  63. last_email = ""
  64. if os.path.exists(last_email_file_name):
  65. try:
  66. last_email_file = open(last_email_file_name, "r")
  67. last_email = last_email_file.readline().strip("\n")
  68. last_email_file.close()
  69. prompt += " [%s]" % last_email
  70. except IOError, e:
  71. pass
  72. email = raw_input(prompt + ": ").strip()
  73. if email:
  74. try:
  75. last_email_file = open(last_email_file_name, "w")
  76. last_email_file.write(email)
  77. last_email_file.close()
  78. except IOError, e:
  79. pass
  80. else:
  81. email = last_email
  82. return email
  83. def StatusUpdate(msg):
  84. """Print a status message to stdout.
  85. If 'verbosity' is greater than 0, print the message.
  86. Args:
  87. msg: The string to print.
  88. """
  89. if verbosity > 0:
  90. print msg
  91. def ErrorExit(msg):
  92. """Print an error message to stderr and exit."""
  93. print >>sys.stderr, msg
  94. sys.exit(1)
  95. class ClientLoginError(urllib2.HTTPError):
  96. """Raised to indicate there was an error authenticating with ClientLogin."""
  97. def __init__(self, url, code, msg, headers, args):
  98. urllib2.HTTPError.__init__(self, url, code, msg, headers, None)
  99. self.args = args
  100. self.reason = args["Error"]
  101. class AbstractRpcServer(object):
  102. """Provides a common interface for a simple RPC server."""
  103. def __init__(self, host, auth_function, host_override=None, extra_headers={},
  104. save_cookies=False):
  105. """Creates a new HttpRpcServer.
  106. Args:
  107. host: The host to send requests to.
  108. auth_function: A function that takes no arguments and returns an
  109. (email, password) tuple when called. Will be called if authentication
  110. is required.
  111. host_override: The host header to send to the server (defaults to host).
  112. extra_headers: A dict of extra headers to append to every request.
  113. save_cookies: If True, save the authentication cookies to local disk.
  114. If False, use an in-memory cookiejar instead. Subclasses must
  115. implement this functionality. Defaults to False.
  116. """
  117. self.host = host
  118. self.host_override = host_override
  119. self.auth_function = auth_function
  120. self.authenticated = False
  121. self.extra_headers = extra_headers
  122. self.save_cookies = save_cookies
  123. self.opener = self._GetOpener()
  124. if self.host_override:
  125. logging.info("Server: %s; Host: %s", self.host, self.host_override)
  126. else:
  127. logging.info("Server: %s", self.host)
  128. def _GetOpener(self):
  129. """Returns an OpenerDirector for making HTTP requests.
  130. Returns:
  131. A urllib2.OpenerDirector object.
  132. """
  133. raise NotImplementedError()
  134. def _CreateRequest(self, url, data=None):
  135. """Creates a new urllib request."""
  136. logging.debug("Creating request for: '%s' with payload:\n%s", url, data)
  137. req = urllib2.Request(url, data=data)
  138. if self.host_override:
  139. req.add_header("Host", self.host_override)
  140. for key, value in self.extra_headers.iteritems():
  141. req.add_header(key, value)
  142. return req
  143. def _GetAuthToken(self, email, password):
  144. """Uses ClientLogin to authenticate the user, returning an auth token.
  145. Args:
  146. email: The user's email address
  147. password: The user's password
  148. Raises:
  149. ClientLoginError: If there was an error authenticating with ClientLogin.
  150. HTTPError: If there was some other form of HTTP error.
  151. Returns:
  152. The authentication token returned by ClientLogin.
  153. """
  154. account_type = "GOOGLE"
  155. if self.host.endswith(".google.com"):
  156. # Needed for use inside Google.
  157. account_type = "HOSTED"
  158. req = self._CreateRequest(
  159. url="https://www.google.com/accounts/ClientLogin",
  160. data=urllib.urlencode({
  161. "Email": email,
  162. "Passwd": password,
  163. "service": "ah",
  164. "source": "rietveld-codereview-upload",
  165. "accountType": account_type,
  166. }),
  167. )
  168. try:
  169. response = self.opener.open(req)
  170. response_body = response.read()
  171. response_dict = dict(x.split("=")
  172. for x in response_body.split("\n") if x)
  173. return response_dict["Auth"]
  174. except urllib2.HTTPError, e:
  175. if e.code == 403:
  176. body = e.read()
  177. response_dict = dict(x.split("=", 1) for x in body.split("\n") if x)
  178. raise ClientLoginError(req.get_full_url(), e.code, e.msg,
  179. e.headers, response_dict)
  180. else:
  181. raise
  182. def _GetAuthCookie(self, auth_token):
  183. """Fetches authentication cookies for an authentication token.
  184. Args:
  185. auth_token: The authentication token returned by ClientLogin.
  186. Raises:
  187. HTTPError: If there was an error fetching the authentication cookies.
  188. """
  189. # This is a dummy value to allow us to identify when we're successful.
  190. continue_location = "http://localhost/"
  191. args = {"continue": continue_location, "auth": auth_token}
  192. req = self._CreateRequest("http://%s/_ah/login?%s" %
  193. (self.host, urllib.urlencode(args)))
  194. try:
  195. response = self.opener.open(req)
  196. except urllib2.HTTPError, e:
  197. response = e
  198. if (response.code != 302 or
  199. response.info()["location"] != continue_location):
  200. raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg,
  201. response.headers, response.fp)
  202. self.authenticated = True
  203. def _Authenticate(self):
  204. """Authenticates the user.
  205. The authentication process works as follows:
  206. 1) We get a username and password from the user
  207. 2) We use ClientLogin to obtain an AUTH token for the user
  208. (see http://code.google.com/apis/accounts/AuthForInstalledApps.html).
  209. 3) We pass the auth token to /_ah/login on the server to obtain an
  210. authentication cookie. If login was successful, it tries to redirect
  211. us to the URL we provided.
  212. If we attempt to access the upload API without first obtaining an
  213. authentication cookie, it returns a 401 response and directs us to
  214. authenticate ourselves with ClientLogin.
  215. """
  216. for i in range(3):
  217. credentials = self.auth_function()
  218. try:
  219. auth_token = self._GetAuthToken(credentials[0], credentials[1])
  220. except ClientLoginError, e:
  221. if e.reason == "BadAuthentication":
  222. print >>sys.stderr, "Invalid username or password."
  223. continue
  224. if e.reason == "CaptchaRequired":
  225. print >>sys.stderr, (
  226. "Please go to\n"
  227. "https://www.google.com/accounts/DisplayUnlockCaptcha\n"
  228. "and verify you are a human. Then try again.")
  229. break
  230. if e.reason == "NotVerified":
  231. print >>sys.stderr, "Account not verified."
  232. break
  233. if e.reason == "TermsNotAgreed":
  234. print >>sys.stderr, "User has not agreed to TOS."
  235. break
  236. if e.reason == "AccountDeleted":
  237. print >>sys.stderr, "The user account has been deleted."
  238. break
  239. if e.reason == "AccountDisabled":
  240. print >>sys.stderr, "The user account has been disabled."
  241. break
  242. if e.reason == "ServiceDisabled":
  243. print >>sys.stderr, ("The user's access to the service has been "
  244. "disabled.")
  245. break
  246. if e.reason == "ServiceUnavailable":
  247. print >>sys.stderr, "The service is not available; try again later."
  248. break
  249. raise
  250. self._GetAuthCookie(auth_token)
  251. return
  252. def Send(self, request_path, payload=None,
  253. content_type="application/octet-stream",
  254. timeout=None,
  255. **kwargs):
  256. """Sends an RPC and returns the response.
  257. Args:
  258. request_path: The path to send the request to, eg /api/appversion/create.
  259. payload: The body of the request, or None to send an empty request.
  260. content_type: The Content-Type header to use.
  261. timeout: timeout in seconds; default None i.e. no timeout.
  262. (Note: for large requests on OS X, the timeout doesn't work right.)
  263. kwargs: Any keyword arguments are converted into query string parameters.
  264. Returns:
  265. The response body, as a string.
  266. """
  267. # TODO: Don't require authentication. Let the server say
  268. # whether it is necessary.
  269. if not self.authenticated:
  270. self._Authenticate()
  271. old_timeout = socket.getdefaulttimeout()
  272. socket.setdefaulttimeout(timeout)
  273. try:
  274. tries = 0
  275. while True:
  276. tries += 1
  277. args = dict(kwargs)
  278. url = "http://%s%s" % (self.host, request_path)
  279. if args:
  280. url += "?" + urllib.urlencode(args)
  281. req = self._CreateRequest(url=url, data=payload)
  282. req.add_header("Content-Type", content_type)
  283. try:
  284. f = self.opener.open(req)
  285. response = f.read()
  286. f.close()
  287. return response
  288. except urllib2.HTTPError, e:
  289. if tries > 3:
  290. raise
  291. elif e.code == 401:
  292. self._Authenticate()
  293. ## elif e.code >= 500 and e.code < 600:
  294. ## # Server Error - try again.
  295. ## continue
  296. else:
  297. raise
  298. finally:
  299. socket.setdefaulttimeout(old_timeout)
  300. class HttpRpcServer(AbstractRpcServer):
  301. """Provides a simplified RPC-style interface for HTTP requests."""
  302. def _Authenticate(self):
  303. """Save the cookie jar after authentication."""
  304. super(HttpRpcServer, self)._Authenticate()
  305. if self.save_cookies:
  306. StatusUpdate("Saving authentication cookies to %s" % self.cookie_file)
  307. self.cookie_jar.save()
  308. def _GetOpener(self):
  309. """Returns an OpenerDirector that supports cookies and ignores redirects.
  310. Returns:
  311. A urllib2.OpenerDirector object.
  312. """
  313. opener = urllib2.OpenerDirector()
  314. opener.add_handler(urllib2.ProxyHandler())
  315. opener.add_handler(urllib2.UnknownHandler())
  316. opener.add_handler(urllib2.HTTPHandler())
  317. opener.add_handler(urllib2.HTTPDefaultErrorHandler())
  318. opener.add_handler(urllib2.HTTPSHandler())
  319. opener.add_handler(urllib2.HTTPErrorProcessor())
  320. if self.save_cookies:
  321. self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies")
  322. self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file)
  323. if os.path.exists(self.cookie_file):
  324. try:
  325. self.cookie_jar.load()
  326. self.authenticated = True
  327. StatusUpdate("Loaded authentication cookies from %s" %
  328. self.cookie_file)
  329. except (cookielib.LoadError, IOError):
  330. # Failed to load cookies - just ignore them.
  331. pass
  332. else:
  333. # Create an empty cookie file with mode 600
  334. fd = os.open(self.cookie_file, os.O_CREAT, 0600)
  335. os.close(fd)
  336. # Always chmod the cookie file
  337. os.chmod(self.cookie_file, 0600)
  338. else:
  339. # Don't save cookies across runs of update.py.
  340. self.cookie_jar = cookielib.CookieJar()
  341. opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar))
  342. return opener
  343. parser = optparse.OptionParser(usage="%prog [options] [-- diff_options]")
  344. parser.add_option("-y", "--assume_yes", action="store_true",
  345. dest="assume_yes", default=False,
  346. help="Assume that the answer to yes/no questions is 'yes'.")
  347. # Logging
  348. group = parser.add_option_group("Logging options")
  349. group.add_option("-q", "--quiet", action="store_const", const=0,
  350. dest="verbose", help="Print errors only.")
  351. group.add_option("-v", "--verbose", action="store_const", const=2,
  352. dest="verbose", default=1,
  353. help="Print info level logs (default).")
  354. group.add_option("--noisy", action="store_const", const=3,
  355. dest="verbose", help="Print all logs.")
  356. # Review server
  357. group = parser.add_option_group("Review server options")
  358. group.add_option("-s", "--server", action="store", dest="server",
  359. default="codereview.appspot.com",
  360. metavar="SERVER",
  361. help=("The server to upload to. The format is host[:port]. "
  362. "Defaults to '%default'."))
  363. group.add_option("-e", "--email", action="store", dest="email",
  364. metavar="EMAIL", default=None,
  365. help="The username to use. Will prompt if omitted.")
  366. group.add_option("-H", "--host", action="store", dest="host",
  367. metavar="HOST", default=None,
  368. help="Overrides the Host header sent with all RPCs.")
  369. group.add_option("--no_cookies", action="store_false",
  370. dest="save_cookies", default=True,
  371. help="Do not save authentication cookies to local disk.")
  372. # Issue
  373. group = parser.add_option_group("Issue options")
  374. group.add_option("-d", "--description", action="store", dest="description",
  375. metavar="DESCRIPTION", default=None,
  376. help="Optional description when creating an issue.")
  377. group.add_option("-f", "--description_file", action="store",
  378. dest="description_file", metavar="DESCRIPTION_FILE",
  379. default=None,
  380. help="Optional path of a file that contains "
  381. "the description when creating an issue.")
  382. group.add_option("-r", "--reviewers", action="store", dest="reviewers",
  383. metavar="REVIEWERS", default="aeagle22206@gmail.com",
  384. help="Add reviewers (comma separated email addresses).")
  385. group.add_option("--cc", action="store", dest="cc",
  386. metavar="CC", default="testability-explorer-dev@googlegroups.com",
  387. help="Add CC (comma separated email addresses).")
  388. # Upload options
  389. group = parser.add_option_group("Patch options")
  390. group.add_option("-m", "--message", action="store", dest="message",
  391. metavar="MESSAGE", default=None,
  392. help="A message to identify the patch. "
  393. "Will prompt if omitted.")
  394. group.add_option("-i", "--issue", type="int", action="store",
  395. metavar="ISSUE", default=None,
  396. help="Issue number to which to add. Defaults to new issue.")
  397. group.add_option("--download_base", action="store_true",
  398. dest="download_base", default=False,
  399. help="Base files will be downloaded by the server "
  400. "(side-by-side diffs may not work on files with CRs).")
  401. group.add_option("--rev", action="store", dest="revision",
  402. metavar="REV", default=None,
  403. help="Branch/tree/revision to diff against (used by DVCS).")
  404. group.add_option("--send_mail", action="store_true",
  405. dest="send_mail", default=False,
  406. help="Send notification email to reviewers.")
  407. def GetRpcServer(options):
  408. """Returns an instance of an AbstractRpcServer.
  409. Returns:
  410. A new AbstractRpcServer, on which RPC calls can be made.
  411. """
  412. rpc_server_class = HttpRpcServer
  413. def GetUserCredentials():
  414. """Prompts the user for a username and password."""
  415. email = options.email
  416. if email is None:
  417. email = GetEmail("Email (login for uploading to %s)" % options.server)
  418. password = getpass.getpass("Password for %s: " % email)
  419. return (email, password)
  420. # If this is the dev_appserver, use fake authentication.
  421. host = (options.host or options.server).lower()
  422. if host == "localhost" or host.startswith("localhost:"):
  423. email = options.email
  424. if email is None:
  425. email = "test@example.com"
  426. logging.info("Using debug user %s. Override with --email" % email)
  427. server = rpc_server_class(
  428. options.server,
  429. lambda: (email, "password"),
  430. host_override=options.host,
  431. extra_headers={"Cookie":
  432. 'dev_appserver_login="%s:False"' % email},
  433. save_cookies=options.save_cookies)
  434. # Don't try to talk to ClientLogin.
  435. server.authenticated = True
  436. return server
  437. return rpc_server_class(options.server, GetUserCredentials,
  438. host_override=options.host,
  439. save_cookies=options.save_cookies)
  440. def EncodeMultipartFormData(fields, files):
  441. """Encode form fields for multipart/form-data.
  442. Args:
  443. fields: A sequence of (name, value) elements for regular form fields.
  444. files: A sequence of (name, filename, value) elements for data to be
  445. uploaded as files.
  446. Returns:
  447. (content_type, body) ready for httplib.HTTP instance.
  448. Source:
  449. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
  450. """
  451. BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-'
  452. CRLF = '\r\n'
  453. lines = []
  454. for (key, value) in fields:
  455. lines.append('--' + BOUNDARY)
  456. lines.append('Content-Disposition: form-data; name="%s"' % key)
  457. lines.append('')
  458. lines.append(value)
  459. for (key, filename, value) in files:
  460. lines.append('--' + BOUNDARY)
  461. lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' %
  462. (key, filename))
  463. lines.append('Content-Type: %s' % GetContentType(filename))
  464. lines.append('')
  465. lines.append(value)
  466. lines.append('--' + BOUNDARY + '--')
  467. lines.append('')
  468. body = CRLF.join(lines)
  469. content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
  470. return content_type, body
  471. def GetContentType(filename):
  472. """Helper to guess the content-type from the filename."""
  473. return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
  474. # Use a shell for subcommands on Windows to get a PATH search.
  475. use_shell = sys.platform.startswith("win")
  476. def RunShellWithReturnCode(command, print_output=False,
  477. universal_newlines=True):
  478. """Executes a command and returns the output from stdout and the return code.
  479. Args:
  480. command: Command to execute.
  481. print_output: If True, the output is printed to stdout.
  482. If False, both stdout and stderr are ignored.
  483. universal_newlines: Use universal_newlines flag (default: True).
  484. Returns:
  485. Tuple (output, return code)
  486. """
  487. logging.info("Running %s", command)
  488. p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  489. shell=use_shell, universal_newlines=universal_newlines)
  490. if print_output:
  491. output_array = []
  492. while True:
  493. line = p.stdout.readline()
  494. if not line:
  495. break
  496. print line.strip("\n")
  497. output_array.append(line)
  498. output = "".join(output_array)
  499. else:
  500. output = p.stdout.read()
  501. p.wait()
  502. errout = p.stderr.read()
  503. if print_output and errout:
  504. print >>sys.stderr, errout
  505. p.stdout.close()
  506. p.stderr.close()
  507. return output, p.returncode
  508. def RunShell(command, silent_ok=False, universal_newlines=True,
  509. print_output=False):
  510. data, retcode = RunShellWithReturnCode(command, print_output,
  511. universal_newlines)
  512. if retcode:
  513. ErrorExit("Got error status from %s:\n%s" % (command, data))
  514. if not silent_ok and not data:
  515. ErrorExit("No output from %s" % command)
  516. return data
  517. class VersionControlSystem(object):
  518. """Abstract base class providing an interface to the VCS."""
  519. def __init__(self, options):
  520. """Constructor.
  521. Args:
  522. options: Command line options.
  523. """
  524. self.options = options
  525. def GenerateDiff(self, args):
  526. """Return the current diff as a string.
  527. Args:
  528. args: Extra arguments to pass to the diff command.
  529. """
  530. raise NotImplementedError(
  531. "abstract method -- subclass %s must override" % self.__class__)
  532. def GetUnknownFiles(self):
  533. """Return a list of files unknown to the VCS."""
  534. raise NotImplementedError(
  535. "abstract method -- subclass %s must override" % self.__class__)
  536. def CheckForUnknownFiles(self):
  537. """Show an "are you sure?" prompt if there are unknown files."""
  538. unknown_files = self.GetUnknownFiles()
  539. if unknown_files:
  540. print "The following files are not added to version control:"
  541. for line in unknown_files:
  542. print line
  543. prompt = "Are you sure to continue?(y/N) "
  544. answer = raw_input(prompt).strip()
  545. if answer != "y":
  546. ErrorExit("User aborted")
  547. def GetBaseFile(self, filename):
  548. """Get the content of the upstream version of a file.
  549. Returns:
  550. A tuple (base_content, new_content, is_binary, status)
  551. base_content: The contents of the base file.
  552. new_content: For text files, this is empty. For binary files, this is
  553. the contents of the new file, since the diff output won't contain
  554. information to reconstruct the current file.
  555. is_binary: True iff the file is binary.
  556. status: The status of the file.
  557. """
  558. raise NotImplementedError(
  559. "abstract method -- subclass %s must override" % self.__class__)
  560. def GetBaseFiles(self, diff):
  561. """Helper that calls GetBase file for each file in the patch.
  562. Returns:
  563. A dictionary that maps from filename to GetBaseFile's tuple. Filenames
  564. are retrieved based on lines that start with "Index:" or
  565. "Property changes on:".
  566. """
  567. files = {}
  568. for line in diff.splitlines(True):
  569. if line.startswith('Index:') or line.startswith('Property changes on:'):
  570. unused, filename = line.split(':', 1)
  571. # On Windows if a file has property changes its filename uses '\'
  572. # instead of '/'.
  573. filename = filename.strip().replace('\\', '/')
  574. files[filename] = self.GetBaseFile(filename)
  575. return files
  576. def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options,
  577. files):
  578. """Uploads the base files (and if necessary, the current ones as well)."""
  579. def UploadFile(filename, file_id, content, is_binary, status, is_base):
  580. """Uploads a file to the server."""
  581. file_too_large = False
  582. if is_base:
  583. type = "base"
  584. else:
  585. type = "current"
  586. if len(content) > MAX_UPLOAD_SIZE:
  587. print ("Not uploading the %s file for %s because it's too large." %
  588. (type, filename))
  589. file_too_large = True
  590. content = ""
  591. checksum = md5.new(content).hexdigest()
  592. if options.verbose > 0 and not file_too_large:
  593. print "Uploading %s file for %s" % (type, filename)
  594. url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id)
  595. form_fields = [("filename", filename),
  596. ("status", status),
  597. ("checksum", checksum),
  598. ("is_binary", str(is_binary)),
  599. ("is_current", str(not is_base)),
  600. ]
  601. if file_too_large:
  602. form_fields.append(("file_too_large", "1"))
  603. if options.email:
  604. form_fields.append(("user", options.email))
  605. ctype, body = EncodeMultipartFormData(form_fields,
  606. [("data", filename, content)])
  607. response_body = rpc_server.Send(url, body,
  608. content_type=ctype)
  609. if not response_body.startswith("OK"):
  610. StatusUpdate(" --> %s" % response_body)
  611. sys.exit(1)
  612. patches = dict()
  613. [patches.setdefault(v, k) for k, v in patch_list]
  614. for filename in patches.keys():
  615. base_content, new_content, is_binary, status = files[filename]
  616. file_id_str = patches.get(filename)
  617. if file_id_str.find("nobase") != -1:
  618. base_content = None
  619. file_id_str = file_id_str[file_id_str.rfind("_") + 1:]
  620. file_id = int(file_id_str)
  621. if base_content != None:
  622. UploadFile(filename, file_id, base_content, is_binary, status, True)
  623. if new_content != None:
  624. UploadFile(filename, file_id, new_content, is_binary, status, False)
  625. def IsImage(self, filename):
  626. """Returns true if the filename has an image extension."""
  627. mimetype = mimetypes.guess_type(filename)[0]
  628. if not mimetype:
  629. return False
  630. return mimetype.startswith("image/")
  631. class SubversionVCS(VersionControlSystem):
  632. """Implementation of the VersionControlSystem interface for Subversion."""
  633. def __init__(self, options):
  634. super(SubversionVCS, self).__init__(options)
  635. if self.options.revision:
  636. match = re.match(r"(\d+)(:(\d+))?", self.options.revision)
  637. if not match:
  638. ErrorExit("Invalid Subversion revision %s." % self.options.revision)
  639. self.rev_start = match.group(1)
  640. self.rev_end = match.group(3)
  641. else:
  642. self.rev_start = self.rev_end = None
  643. # Cache output from "svn list -r REVNO dirname".
  644. # Keys: dirname, Values: 2-tuple (ouput for start rev and end rev).
  645. self.svnls_cache = {}
  646. # SVN base URL is required to fetch files deleted in an older revision.
  647. # Result is cached to not guess it over and over again in GetBaseFile().
  648. required = self.options.download_base or self.options.revision is not None
  649. self.svn_base = self._GuessBase(required)
  650. def GuessBase(self, required):
  651. """Wrapper for _GuessBase."""
  652. return self.svn_base
  653. def _GuessBase(self, required):
  654. """Returns the SVN base URL.
  655. Args:
  656. required: If true, exits if the url can't be guessed, otherwise None is
  657. returned.
  658. """
  659. info = RunShell(["svn", "info"])
  660. for line in info.splitlines():
  661. words = line.split()
  662. if len(words) == 2 and words[0] == "URL:":
  663. url = words[1]
  664. scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
  665. username, netloc = urllib.splituser(netloc)
  666. if username:
  667. logging.info("Removed username from base URL")
  668. if netloc.endswith("svn.python.org"):
  669. if netloc == "svn.python.org":
  670. if path.startswith("/projects/"):
  671. path = path[9:]
  672. elif netloc != "pythondev@svn.python.org":
  673. ErrorExit("Unrecognized Python URL: %s" % url)
  674. base = "http://svn.python.org/view/*checkout*%s/" % path
  675. logging.info("Guessed Python base = %s", base)
  676. elif netloc.endswith("svn.collab.net"):
  677. if path.startswith("/repos/"):
  678. path = path[6:]
  679. base = "http://svn.collab.net/viewvc/*checkout*%s/" % path
  680. logging.info("Guessed CollabNet base = %s", base)
  681. elif netloc.endswith(".googlecode.com"):
  682. path = path + "/"
  683. base = urlparse.urlunparse(("http", netloc, path, params,
  684. query, fragment))
  685. logging.info("Guessed Google Code base = %s", base)
  686. else:
  687. path = path + "/"
  688. base = urlparse.urlunparse((scheme, netloc, path, params,
  689. query, fragment))
  690. logging.info("Guessed base = %s", base)
  691. return base
  692. if required:
  693. ErrorExit("Can't find URL in output from svn info")
  694. return None
  695. def GenerateDiff(self, args):
  696. cmd = ["svn", "diff"]
  697. if self.options.revision:
  698. cmd += ["-r", self.options.revision]
  699. cmd.extend(args)
  700. data = RunShell(cmd)
  701. count = 0
  702. for line in data.splitlines():
  703. if line.startswith("Index:") or line.startswith("Property changes on:"):
  704. count += 1
  705. logging.info(line)
  706. if not count:
  707. ErrorExit("No valid patches found in output from svn diff")
  708. return data
  709. def _CollapseKeywords(self, content, keyword_str):
  710. """Collapses SVN keywords."""
  711. # svn cat translates keywords but svn diff doesn't. As a result of this
  712. # behavior patching.PatchChunks() fails with a chunk mismatch error.
  713. # This part was originally written by the Review Board development team
  714. # who had the same problem (http://reviews.review-board.org/r/276/).
  715. # Mapping of keywords to known aliases
  716. svn_keywords = {
  717. # Standard keywords
  718. 'Date': ['Date', 'LastChangedDate'],
  719. 'Revision': ['Revision', 'LastChangedRevision', 'Rev'],
  720. 'Author': ['Author', 'LastChangedBy'],
  721. 'HeadURL': ['HeadURL', 'URL'],
  722. 'Id': ['Id'],
  723. # Aliases
  724. 'LastChangedDate': ['LastChangedDate', 'Date'],
  725. 'LastChangedRevision': ['LastChangedRevision', 'Rev', 'Revision'],
  726. 'LastChangedBy': ['LastChangedBy', 'Author'],
  727. 'URL': ['URL', 'HeadURL'],
  728. }
  729. def repl(m):
  730. if m.group(2):
  731. return "$%s::%s$" % (m.group(1), " " * len(m.group(3)))
  732. return "$%s$" % m.group(1)
  733. keywords = [keyword
  734. for name in keyword_str.split(" ")
  735. for keyword in svn_keywords.get(name, [])]
  736. return re.sub(r"\$(%s):(:?)([^\$]+)\$" % '|'.join(keywords), repl, content)
  737. def GetUnknownFiles(self):
  738. status = RunShell(["svn", "status", "--ignore-externals"], silent_ok=True)
  739. unknown_files = []
  740. for line in status.split("\n"):
  741. if line and line[0] == "?":
  742. unknown_files.append(line)
  743. return unknown_files
  744. def ReadFile(self, filename):
  745. """Returns the contents of a file."""
  746. file = open(filename, 'rb')
  747. result = ""
  748. try:
  749. result = file.read()
  750. finally:
  751. file.close()
  752. return result
  753. def GetStatus(self, filename):
  754. """Returns the status of a file."""
  755. if not self.options.revision:
  756. status = RunShell(["svn", "status", "--ignore-externals", filename])
  757. if not status:
  758. ErrorExit("svn status returned no output for %s" % filename)
  759. status_lines = status.splitlines()
  760. # If file is in a cl, the output will begin with
  761. # "\n--- Changelist 'cl_name':\n". See
  762. # http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt
  763. if (len(status_lines) == 3 and
  764. not status_lines[0] and
  765. status_lines[1].startswith("--- Changelist")):
  766. status = status_lines[2]
  767. else:
  768. status = status_lines[0]
  769. # If we have a revision to diff against we need to run "svn list"
  770. # for the old and the new revision and compare the results to get
  771. # the correct status for a file.
  772. else:
  773. dirname, relfilename = os.path.split(filename)
  774. if dirname not in self.svnls_cache:
  775. cmd = ["svn", "list", "-r", self.rev_start, dirname or "."]
  776. out, returncode = RunShellWithReturnCode(cmd)
  777. if returncode:
  778. ErrorExit("Failed to get status for %s." % filename)
  779. old_files = out.splitlines()
  780. args = ["svn", "list"]
  781. if self.rev_end:
  782. args += ["-r", self.rev_end]
  783. cmd = args + [dirname or "."]
  784. out, returncode = RunShellWithReturnCode(cmd)
  785. if returncode:
  786. ErrorExit("Failed to run command %s" % cmd)
  787. self.svnls_cache[dirname] = (old_files, out.splitlines())
  788. old_files, new_files = self.svnls_cache[dirname]
  789. if relfilename in old_files and relfilename not in new_files:
  790. status = "D "
  791. elif relfilename in old_files and relfilename in new_files:
  792. status = "M "
  793. else:
  794. status = "A "
  795. return status
  796. def GetBaseFile(self, filename):
  797. status = self.GetStatus(filename)
  798. base_content = None
  799. new_content = None
  800. # If a file is copied its status will be "A +", which signifies
  801. # "addition-with-history". See "svn st" for more information. We need to
  802. # upload the original file or else diff parsing will fail if the file was
  803. # edited.
  804. if status[0] == "A" and status[3] != "+":
  805. # We'll need to upload the new content if we're adding a binary file
  806. # since diff's output won't contain it.
  807. mimetype = RunShell(["svn", "propget", "svn:mime-type", filename],
  808. silent_ok=True)
  809. base_content = ""
  810. is_binary = bool(mimetype) and not mimetype.startswith("text/")
  811. if is_binary and self.IsImage(filename):
  812. new_content = self.ReadFile(filename)
  813. elif (status[0] in ("M", "D", "R") or
  814. (status[0] == "A" and status[3] == "+") or # Copied file.
  815. (status[0] == " " and status[1] == "M")): # Property change.
  816. args = []
  817. if self.options.revision:
  818. url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
  819. else:
  820. # Don't change filename, it's needed later.
  821. url = filename
  822. args += ["-r", "BASE"]
  823. cmd = ["svn"] + args + ["propget", "svn:mime-type", url]
  824. mimetype, returncode = RunShellWithReturnCode(cmd)
  825. if returncode:
  826. # File does not exist in the requested revision.
  827. # Reset mimetype, it contains an error message.
  828. mimetype = ""
  829. get_base = False
  830. is_binary = bool(mimetype) and not mimetype.startswith("text/")
  831. if status[0] == " ":
  832. # Empty base content just to force an upload.
  833. base_content = ""
  834. elif is_binary:
  835. if self.IsImage(filename):
  836. get_base = True
  837. if status[0] == "M":
  838. if not self.rev_end:
  839. new_content = self.ReadFile(filename)
  840. else:
  841. url = "%s/%s@%s" % (self.svn_base, filename, self.rev_end)
  842. new_content = RunShell(["svn", "cat", url],
  843. universal_newlines=True, silent_ok=True)
  844. else:
  845. base_content = ""
  846. else:
  847. get_base = True
  848. if get_base:
  849. if is_binary:
  850. universal_newlines = False
  851. else:
  852. universal_newlines = True
  853. if self.rev_start:
  854. # "svn cat -r REV delete_file.txt" doesn't work. cat requires
  855. # the full URL with "@REV" appended instead of using "-r" option.
  856. url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
  857. base_content = RunShell(["svn", "cat", url],
  858. universal_newlines=universal_newlines,
  859. silent_ok=True)
  860. else:
  861. base_content = RunShell(["svn", "cat", filename],
  862. universal_newlines=universal_newlines,
  863. silent_ok=True)
  864. if not is_binary:
  865. args = []
  866. if self.rev_start:
  867. url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
  868. else:
  869. url = filename
  870. args += ["-r", "BASE"]
  871. cmd = ["svn"] + args + ["propget", "svn:keywords", url]
  872. keywords, returncode = RunShellWithReturnCode(cmd)
  873. if keywords and not returncode:
  874. base_content = self._CollapseKeywords(base_content, keywords)
  875. else:
  876. StatusUpdate("svn status returned unexpected output: %s" % status)
  877. sys.exit(1)
  878. return base_content, new_content, is_binary, status[0:5]
  879. class GitVCS(VersionControlSystem):
  880. """Implementation of the VersionControlSystem interface for Git."""
  881. def __init__(self, options):
  882. super(GitVCS, self).__init__(options)
  883. # Map of filename -> hash of base file.
  884. self.base_hashes = {}
  885. def GenerateDiff(self, extra_args):
  886. # This is more complicated than svn's GenerateDiff because we must convert
  887. # the diff output to include an svn-style "Index:" line as well as record
  888. # the hashes of the base files, so we can upload them along with our diff.
  889. if self.options.revision:
  890. extra_args = [self.options.revision] + extra_args
  891. gitdiff = RunShell(["git", "diff", "--full-index"] + extra_args)
  892. svndiff = []
  893. filecount = 0
  894. filename = None
  895. for line in gitdiff.splitlines():
  896. match = re.match(r"diff --git a/(.*) b/.*$", line)
  897. if match:
  898. filecount += 1
  899. filename = match.group(1)
  900. svndiff.append("Index: %s\n" % filename)
  901. else:
  902. # The "index" line in a git diff looks like this (long hashes elided):
  903. # index 82c0d44..b2cee3f 100755
  904. # We want to save the left hash, as that identifies the base file.
  905. match = re.match(r"index (\w+)\.\.", line)
  906. if match:
  907. self.base_hashes[filename] = match.group(1)
  908. svndiff.append(line + "\n")
  909. if not filecount:
  910. ErrorExit("No valid patches found in output from git diff")
  911. return "".join(svndiff)
  912. def GetUnknownFiles(self):
  913. status = RunShell(["git", "ls-files", "--exclude-standard", "--others"],
  914. silent_ok=True)
  915. return status.splitlines()
  916. def GetBaseFile(self, filename):
  917. hash = self.base_hashes[filename]
  918. base_content = None
  919. new_content = None
  920. is_binary = False
  921. if hash == "0" * 40: # All-zero hash indicates no base file.
  922. status = "A"
  923. base_content = ""
  924. else:
  925. status = "M"
  926. base_content, returncode = RunShellWithReturnCode(["git", "show", hash])
  927. if returncode:
  928. ErrorExit("Got error status from 'git show %s'" % hash)
  929. return (base_content, new_content, is_binary, status)
  930. class MercurialVCS(VersionControlSystem):
  931. """Implementation of the VersionControlSystem interface for Mercurial."""
  932. def __init__(self, options, repo_dir):
  933. super(MercurialVCS, self).__init__(options)
  934. # Absolute path to repository (we can be in a subdir)
  935. self.repo_dir = os.path.normpath(repo_dir)
  936. # Compute the subdir
  937. cwd = os.path.normpath(os.getcwd())
  938. assert cwd.startswith(self.repo_dir)
  939. self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/")
  940. if self.options.revision:
  941. self.base_rev = self.options.revision
  942. else:
  943. self.base_rev = RunShell(["hg", "parent", "-q"]).split(':')[1].strip()
  944. def _GetRelPath(self, filename):
  945. """Get relative path of a file according to the current directory,
  946. given its logical path in the repo."""
  947. assert filename.startswith(self.subdir), filename
  948. return filename[len(self.subdir):].lstrip(r"\/")
  949. def GenerateDiff(self, extra_args):
  950. # If no file specified, restrict to the current subdir
  951. extra_args = extra_args or ["."]
  952. cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args
  953. data = RunShell(cmd, silent_ok=True)
  954. svndiff = []
  955. filecount = 0
  956. for line in data.splitlines():
  957. m = re.match("diff --git a/(\S+) b/(\S+)", line)
  958. if m:
  959. # Modify line to make it look like as it comes from svn diff.
  960. # With this modification no changes on the server side are required
  961. # to make upload.py work with Mercurial repos.
  962. # NOTE: for proper handling of moved/copied files, we have to use
  963. # the second filename.
  964. filename = m.group(2)
  965. svndiff.append("Index: %s" % filename)
  966. svndiff.append("=" * 67)
  967. filecount += 1
  968. logging.info(line)
  969. else:
  970. svndiff.append(line)
  971. if not filecount:
  972. ErrorExit("No valid patches found in output from hg diff")
  973. return "\n".join(svndiff) + "\n"
  974. def GetUnknownFiles(self):
  975. """Return a list of files unknown to the VCS."""
  976. args = []
  977. status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."],
  978. silent_ok=True)
  979. unknown_files = []
  980. for line in status.splitlines():
  981. st, fn = line.split(" ", 1)
  982. if st == "?":
  983. unknown_files.append(fn)
  984. return unknown_files
  985. def GetBaseFile(self, filename):
  986. # "hg status" and "hg cat" both take a path relative to the current subdir
  987. # rather than to the repo root, but "hg diff" has given us the full path
  988. # to the repo root.
  989. base_content = ""
  990. new_content = None
  991. is_binary = False
  992. oldrelpath = relpath = self._GetRelPath(filename)
  993. # "hg status -C" returns two lines for moved/copied files, one otherwise
  994. out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath])
  995. out = out.splitlines()
  996. # HACK: strip error message about missing file/directory if it isn't in
  997. # the working copy
  998. if out[0].startswith('%s: ' % relpath):
  999. out = out[1:]
  1000. if len(out) > 1:
  1001. # Moved/copied => considered as modified, use old filename to
  1002. # retrieve base contents
  1003. oldrelpath = out[1].strip()
  1004. status = "M"
  1005. else:
  1006. status, _ = out[0].split(' ', 1)
  1007. if status != "A":
  1008. base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath],
  1009. silent_ok=True)
  1010. is_binary = "\0" in base_content # Mercurial's heuristic
  1011. if status != "R":
  1012. new_content = open(relpath, "rb").read()
  1013. is_binary = is_binary or "\0" in new_content
  1014. if is_binary and base_content:
  1015. # Fetch again without converting newlines
  1016. base_content = RunShell(["hg", "cat", "-r", self.base_rev, oldrelpath],
  1017. silent_ok=True, universal_newlines=False)
  1018. if not is_binary or not self.IsImage(relpath):
  1019. new_content = None
  1020. return base_content, new_content, is_binary, status
  1021. # NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync.
  1022. def SplitPatch(data):
  1023. """Splits a patch into separate pieces for each file.
  1024. Args:
  1025. data: A string containing the output of svn diff.
  1026. Returns:
  1027. A list of 2-tuple (filename, text) where text is the svn diff output
  1028. pertaining to filename.
  1029. """
  1030. patches = []
  1031. filename = None
  1032. diff = []
  1033. for line in data.splitlines(True):
  1034. new_filename = None
  1035. if line.startswith('Index:'):
  1036. unused, new_filename = line.split(':', 1)
  1037. new_filename = new_filename.strip()
  1038. elif line.startswith('Property changes on:'):
  1039. unused, temp_filename = line.split(':', 1)
  1040. # When a file is modified, paths use '/' between directories, however
  1041. # when a property is modified '\' is used on Windows. Make them the same
  1042. # otherwise the file shows up twice.
  1043. temp_filename = temp_filename.strip().replace('\\', '/')
  1044. if temp_filename != filename:
  1045. # File has property changes but no modifications, create a new diff.
  1046. new_filename = temp_filename
  1047. if new_filename:
  1048. if filename and diff:
  1049. patches.append((filename, ''.join(diff)))
  1050. filename = new_filename
  1051. diff = [line]
  1052. continue
  1053. if diff is not None:
  1054. diff.append(line)
  1055. if filename and diff:
  1056. patches.append((filename, ''.join(diff)))
  1057. return patches
  1058. def UploadSeparatePatches(issue, rpc_server, patchset, data, options):
  1059. """Uploads a separate patch for each file in the diff output.
  1060. Returns a list of [patch_key, filename] for each file.
  1061. """
  1062. patches = SplitPatch(data)
  1063. rv = []
  1064. for patch in patches:
  1065. if len(patch[1]) > MAX_UPLOAD_SIZE:
  1066. print ("Not uploading the patch for " + patch[0] +
  1067. " because the file is too large.")
  1068. continue
  1069. form_fields = [("filename", patch[0])]
  1070. if not options.download_base:
  1071. form_fields.append(("content_upload", "1"))
  1072. files = [("data", "data.diff", patch[1])]
  1073. ctype, body = EncodeMultipartFormData(form_fields, files)
  1074. url = "/%d/upload_patch/%d" % (int(issue), int(patchset))
  1075. print "Uploading patch for " + patch[0]
  1076. response_body = rpc_server.Send(url, body, content_type=ctype)
  1077. lines = response_body.splitlines()
  1078. if not lines or lines[0] != "OK":
  1079. StatusUpdate(" --> %s" % response_body)
  1080. sys.exit(1)
  1081. rv.append([lines[1], patch[0]])
  1082. return rv
  1083. def GuessVCS(options):
  1084. """Helper to guess the version control system.
  1085. This examines the current directory, guesses which VersionControlSystem
  1086. we're using, and returns an instance of the appropriate class. Exit with an
  1087. error if we can't figure it out.
  1088. Returns:
  1089. A VersionControlSystem instance. Exits if the VCS can't be guessed.
  1090. """
  1091. # Mercurial has a command to get the base directory of a repository
  1092. # Try running it, but don't die if we don't have hg installed.
  1093. # NOTE: we try Mercurial first as it can sit on top of an SVN working copy.
  1094. try:
  1095. out, returncode = RunShellWithReturnCode(["hg", "root"])
  1096. if returncode == 0:
  1097. return MercurialVCS(options, out.strip())
  1098. except OSError, (errno, message):
  1099. if errno != 2: # ENOENT -- they don't have hg installed.
  1100. raise
  1101. # Subversion has a .svn in all working directories.
  1102. if os.path.isdir('.svn'):
  1103. logging.info("Guessed VCS = Subversion")
  1104. return SubversionVCS(options)
  1105. # Git has a command to test if you're in a git tree.
  1106. # Try running it, but don't die if we don't have git installed.
  1107. try:
  1108. out, returncode = RunShellWithReturnCode(["git", "rev-parse",
  1109. "--is-inside-work-tree"])
  1110. if returncode == 0:
  1111. return GitVCS(options)
  1112. except OSError, (errno, message):
  1113. if errno != 2: # ENOENT -- they don't have git installed.
  1114. raise
  1115. ErrorExit(("Could not guess version control system. "
  1116. "Are you in a working copy directory?"))
  1117. def RealMain(argv, data=None):
  1118. """The real main function.
  1119. Args:
  1120. argv: Command line arguments.
  1121. data: Diff contents. If None (default) the diff is generated by
  1122. the VersionControlSystem implementation returned by GuessVCS().
  1123. Returns:
  1124. A 2-tuple (issue id, patchset id).
  1125. The patchset id is None if the base files are not uploaded by this
  1126. script (applies only to SVN checkouts).
  1127. """
  1128. logging.basicConfig(format=("%(asctime).19s %(levelname)s %(filename)s:"
  1129. "%(lineno)s %(message)s "))
  1130. os.environ['LC_ALL'] = 'C'
  1131. options, args = parser.parse_args(argv[1:])
  1132. global verbosity
  1133. verbosity = options.verbose
  1134. if verbosity >= 3:
  1135. logging.getLogger().setLevel(logging.DEBUG)
  1136. elif verbosity >= 2:
  1137. logging.getLogger().setLevel(logging.INFO)
  1138. vcs = GuessVCS(options)
  1139. if isinstance(vcs, SubversionVCS):
  1140. # base field is only allowed for Subversion.
  1141. # Note: Fetching base files may become deprecated in future releases.
  1142. base = vcs.GuessBase(options.download_base)
  1143. else:
  1144. base = None
  1145. if not base and options.download_base:
  1146. options.download_base = True
  1147. logging.info("Enabled upload of base file")
  1148. if not options.assume_yes:
  1149. vcs.CheckForUnknownFiles()
  1150. if data is None:
  1151. data = vcs.GenerateDiff(args)
  1152. files = vcs.GetBaseFiles(data)
  1153. if verbosity >= 1:
  1154. print "Upload server:", options.server, "(change with -s/--server)"
  1155. if options.issue:
  1156. prompt = "Message describing this patch set: "
  1157. else:
  1158. prompt = "New issue subject: "
  1159. message = options.message or raw_input(prompt).strip()
  1160. if not message:
  1161. ErrorExit("A non-empty message is required")
  1162. rpc_server = GetRpcServer(options)
  1163. form_fields = [("subject", message)]
  1164. if base:
  1165. form_fields.append(("base", base))
  1166. if options.issue:
  1167. form_fields.append(("issue", str(options.issue)))
  1168. if options.email:
  1169. form_fields.append(("user", options.email))
  1170. if options.reviewers:
  1171. for reviewer in options.reviewers.split(','):
  1172. if "@" in reviewer and not reviewer.split("@")[1].count(".") == 1:
  1173. ErrorExit("Invalid email address: %s" % reviewer)
  1174. form_fields.append(("reviewers", options.reviewers))
  1175. if options.cc:
  1176. for cc in options.cc.split(','):
  1177. if "@" in cc and not cc.split("@")[1].count(".") == 1:
  1178. ErrorExit("Invalid email address: %s" % cc)
  1179. form_fields.append(("cc", options.cc))
  1180. description = options.description
  1181. if options.description_file:
  1182. if options.description:
  1183. ErrorExit("Can't specify description and description_file")
  1184. file = open(options.description_file, 'r')
  1185. description = file.read()
  1186. file.close()
  1187. if description:
  1188. form_fields.append(("description", description))
  1189. # Send a hash of all the base file so the server can determine if a copy
  1190. # already exists in an earlier patchset.
  1191. base_hashes = ""
  1192. for file, info in files.iteritems():
  1193. if not info[0] is None:
  1194. checksum = md5.new(info[0]).hexdigest()
  1195. if base_hashes:
  1196. base_hashes += "|"
  1197. base_hashes += checksum + ":" + file
  1198. form_fields.append(("base_hashes", base_hashes))
  1199. # If we're uploading base files, don't send the email before the uploads, so
  1200. # that it contains the file status.
  1201. if options.send_mail and options.download_base:
  1202. form_fields.append(("send_mail", "1"))
  1203. if not options.download_base:
  1204. form_fields.append(("content_upload", "1"))
  1205. if len(data) > MAX_UPLOAD_SIZE:
  1206. print "Patch is large, so uploading file patches separately."
  1207. uploaded_diff_file = []
  1208. form_fields.append(("separate_patches", "1"))
  1209. else:
  1210. uploaded_diff_file = [("data", "data.diff", data)]
  1211. ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file)
  1212. response_body = rpc_server.Send("/upload", body, content_type=ctype)
  1213. patchset = None
  1214. if not options.download_base or not uploaded_diff_file:
  1215. lines = response_body.splitlines()
  1216. if len(lines) >= 2:
  1217. msg = lines[0]
  1218. patchset = lines[1].strip()
  1219. patches = [x.split(" ", 1) for x in lines[2:]]
  1220. else:
  1221. msg = response_body
  1222. else:
  1223. msg = response_body
  1224. StatusUpdate(msg)
  1225. if not response_body.startswith("Issue created.") and \
  1226. not response_body.startswith("Issue updated."):
  1227. sys.exit(0)
  1228. issue = msg[msg.rfind("/")+1:]
  1229. if not uploaded_diff_file:
  1230. result = UploadSeparatePatches(issue, rpc_server, patchset, data, options)
  1231. if not options.download_base:
  1232. patches = result
  1233. if not options.download_base:
  1234. vcs.UploadBaseFiles(issue, rpc_server, patches, patchset, options, files)
  1235. if options.send_mail:
  1236. rpc_server.Send("/" + issue + "/mail", payload="")
  1237. return issue, patchset
  1238. def main():
  1239. try:
  1240. RealMain(sys.argv)
  1241. except KeyboardInterrupt:
  1242. print
  1243. StatusUpdate("Interrupted.")
  1244. sys.exit(1)
  1245. if __name__ == "__main__":
  1246. main()