PageRenderTime 61ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/upload-diffs.py

http://googlecl.googlecode.com/
Python | 1784 lines | 1695 code | 17 blank | 72 comment | 41 complexity | 1589180e0197a5f44945f980888474be MD5 | raw file
  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] [path...]
  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. # Taken from rietveld trunk (http://code.google.com/p/rietveld), r579
  27. # This code is derived from appcfg.py in the App Engine SDK (open source),
  28. # and from ASPN recipe #146306.
  29. import ConfigParser
  30. import cookielib
  31. import fnmatch
  32. import getpass
  33. import logging
  34. import mimetypes
  35. import optparse
  36. import os
  37. import re
  38. import socket
  39. import subprocess
  40. import sys
  41. import urllib
  42. import urllib2
  43. import urlparse
  44. # The md5 module was deprecated in Python 2.5.
  45. try:
  46. from hashlib import md5
  47. except ImportError:
  48. from md5 import md5
  49. try:
  50. import readline
  51. except ImportError:
  52. pass
  53. try:
  54. import keyring
  55. except ImportError:
  56. keyring = None
  57. # Constants for GoogleCL.
  58. DEFAULT_REVIEWER = 'tom.h.miller@gmail.com'
  59. DEFAULT_CC = 'googlecl-dev@googlegroups.com'
  60. # The logging verbosity:
  61. # 0: Errors only.
  62. # 1: Status messages.
  63. # 2: Info logs.
  64. # 3: Debug logs.
  65. verbosity = 1
  66. # The account type used for authentication.
  67. # This line could be changed by the review server (see handler for
  68. # upload.py).
  69. AUTH_ACCOUNT_TYPE = "GOOGLE"
  70. # URL of the default review server. As for AUTH_ACCOUNT_TYPE, this line could be
  71. # changed by the review server (see handler for upload.py).
  72. DEFAULT_REVIEW_SERVER = "codereview.appspot.com"
  73. # Max size of patch or base file.
  74. MAX_UPLOAD_SIZE = 900 * 1024
  75. # Constants for version control names. Used by GuessVCSName.
  76. VCS_GIT = "Git"
  77. VCS_MERCURIAL = "Mercurial"
  78. VCS_SUBVERSION = "Subversion"
  79. VCS_UNKNOWN = "Unknown"
  80. # whitelist for non-binary filetypes which do not start with "text/"
  81. # .mm (Objective-C) shows up as application/x-freemind on my Linux box.
  82. TEXT_MIMETYPES = ['application/javascript', 'application/x-javascript',
  83. 'application/xml', 'application/x-freemind',
  84. 'application/x-sh']
  85. VCS_ABBREVIATIONS = {
  86. VCS_MERCURIAL.lower(): VCS_MERCURIAL,
  87. "hg": VCS_MERCURIAL,
  88. VCS_SUBVERSION.lower(): VCS_SUBVERSION,
  89. "svn": VCS_SUBVERSION,
  90. VCS_GIT.lower(): VCS_GIT,
  91. }
  92. # The result of parsing Subversion's [auto-props] setting.
  93. svn_auto_props_map = None
  94. def GetEmail(prompt):
  95. """Prompts the user for their email address and returns it.
  96. The last used email address is saved to a file and offered up as a suggestion
  97. to the user. If the user presses enter without typing in anything the last
  98. used email address is used. If the user enters a new address, it is saved
  99. for next time we prompt.
  100. """
  101. last_email_file_name = os.path.expanduser("~/.last_codereview_email_address")
  102. last_email = ""
  103. if os.path.exists(last_email_file_name):
  104. try:
  105. last_email_file = open(last_email_file_name, "r")
  106. last_email = last_email_file.readline().strip("\n")
  107. last_email_file.close()
  108. prompt += " [%s]" % last_email
  109. except IOError, e:
  110. pass
  111. email = raw_input(prompt + ": ").strip()
  112. if email:
  113. try:
  114. last_email_file = open(last_email_file_name, "w")
  115. last_email_file.write(email)
  116. last_email_file.close()
  117. except IOError, e:
  118. pass
  119. else:
  120. email = last_email
  121. return email
  122. def StatusUpdate(msg):
  123. """Print a status message to stdout.
  124. If 'verbosity' is greater than 0, print the message.
  125. Args:
  126. msg: The string to print.
  127. """
  128. if verbosity > 0:
  129. print msg
  130. def ErrorExit(msg):
  131. """Print an error message to stderr and exit."""
  132. print >>sys.stderr, msg
  133. sys.exit(1)
  134. class ClientLoginError(urllib2.HTTPError):
  135. """Raised to indicate there was an error authenticating with ClientLogin."""
  136. def __init__(self, url, code, msg, headers, args):
  137. urllib2.HTTPError.__init__(self, url, code, msg, headers, None)
  138. self.args = args
  139. self.reason = args["Error"]
  140. class AbstractRpcServer(object):
  141. """Provides a common interface for a simple RPC server."""
  142. def __init__(self, host, auth_function, host_override=None, extra_headers={},
  143. save_cookies=False, account_type=AUTH_ACCOUNT_TYPE):
  144. """Creates a new HttpRpcServer.
  145. Args:
  146. host: The host to send requests to.
  147. auth_function: A function that takes no arguments and returns an
  148. (email, password) tuple when called. Will be called if authentication
  149. is required.
  150. host_override: The host header to send to the server (defaults to host).
  151. extra_headers: A dict of extra headers to append to every request.
  152. save_cookies: If True, save the authentication cookies to local disk.
  153. If False, use an in-memory cookiejar instead. Subclasses must
  154. implement this functionality. Defaults to False.
  155. account_type: Account type used for authentication. Defaults to
  156. AUTH_ACCOUNT_TYPE.
  157. """
  158. self.host = host
  159. if (not self.host.startswith("http://") and
  160. not self.host.startswith("https://")):
  161. self.host = "http://" + self.host
  162. self.host_override = host_override
  163. self.auth_function = auth_function
  164. self.authenticated = False
  165. self.extra_headers = extra_headers
  166. self.save_cookies = save_cookies
  167. self.account_type = account_type
  168. self.opener = self._GetOpener()
  169. if self.host_override:
  170. logging.info("Server: %s; Host: %s", self.host, self.host_override)
  171. else:
  172. logging.info("Server: %s", self.host)
  173. def _GetOpener(self):
  174. """Returns an OpenerDirector for making HTTP requests.
  175. Returns:
  176. A urllib2.OpenerDirector object.
  177. """
  178. raise NotImplementedError()
  179. def _CreateRequest(self, url, data=None):
  180. """Creates a new urllib request."""
  181. logging.debug("Creating request for: '%s' with payload:\n%s", url, data)
  182. req = urllib2.Request(url, data=data)
  183. if self.host_override:
  184. req.add_header("Host", self.host_override)
  185. for key, value in self.extra_headers.iteritems():
  186. req.add_header(key, value)
  187. return req
  188. def _GetAuthToken(self, email, password):
  189. """Uses ClientLogin to authenticate the user, returning an auth token.
  190. Args:
  191. email: The user's email address
  192. password: The user's password
  193. Raises:
  194. ClientLoginError: If there was an error authenticating with ClientLogin.
  195. HTTPError: If there was some other form of HTTP error.
  196. Returns:
  197. The authentication token returned by ClientLogin.
  198. """
  199. account_type = self.account_type
  200. if self.host.endswith(".google.com"):
  201. # Needed for use inside Google.
  202. account_type = "HOSTED"
  203. req = self._CreateRequest(
  204. url="https://www.google.com/accounts/ClientLogin",
  205. data=urllib.urlencode({
  206. "Email": email,
  207. "Passwd": password,
  208. "service": "ah",
  209. "source": "rietveld-codereview-upload",
  210. "accountType": account_type,
  211. }),
  212. )
  213. try:
  214. response = self.opener.open(req)
  215. response_body = response.read()
  216. response_dict = dict(x.split("=")
  217. for x in response_body.split("\n") if x)
  218. return response_dict["Auth"]
  219. except urllib2.HTTPError, e:
  220. if e.code == 403:
  221. body = e.read()
  222. response_dict = dict(x.split("=", 1) for x in body.split("\n") if x)
  223. raise ClientLoginError(req.get_full_url(), e.code, e.msg,
  224. e.headers, response_dict)
  225. else:
  226. raise
  227. def _GetAuthCookie(self, auth_token):
  228. """Fetches authentication cookies for an authentication token.
  229. Args:
  230. auth_token: The authentication token returned by ClientLogin.
  231. Raises:
  232. HTTPError: If there was an error fetching the authentication cookies.
  233. """
  234. # This is a dummy value to allow us to identify when we're successful.
  235. continue_location = "http://localhost/"
  236. args = {"continue": continue_location, "auth": auth_token}
  237. req = self._CreateRequest("%s/_ah/login?%s" %
  238. (self.host, urllib.urlencode(args)))
  239. try:
  240. response = self.opener.open(req)
  241. except urllib2.HTTPError, e:
  242. response = e
  243. if (response.code != 302 or
  244. response.info()["location"] != continue_location):
  245. raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg,
  246. response.headers, response.fp)
  247. self.authenticated = True
  248. def _Authenticate(self):
  249. """Authenticates the user.
  250. The authentication process works as follows:
  251. 1) We get a username and password from the user
  252. 2) We use ClientLogin to obtain an AUTH token for the user
  253. (see http://code.google.com/apis/accounts/AuthForInstalledApps.html).
  254. 3) We pass the auth token to /_ah/login on the server to obtain an
  255. authentication cookie. If login was successful, it tries to redirect
  256. us to the URL we provided.
  257. If we attempt to access the upload API without first obtaining an
  258. authentication cookie, it returns a 401 response (or a 302) and
  259. directs us to authenticate ourselves with ClientLogin.
  260. """
  261. for i in range(3):
  262. credentials = self.auth_function()
  263. try:
  264. auth_token = self._GetAuthToken(credentials[0], credentials[1])
  265. except ClientLoginError, e:
  266. if e.reason == "BadAuthentication":
  267. print >>sys.stderr, "Invalid username or password."
  268. continue
  269. if e.reason == "CaptchaRequired":
  270. print >>sys.stderr, (
  271. "Please go to\n"
  272. "https://www.google.com/accounts/DisplayUnlockCaptcha\n"
  273. "and verify you are a human. Then try again.\n"
  274. "If you are using a Google Apps account the URL is:\n"
  275. "https://www.google.com/a/yourdomain.com/UnlockCaptcha")
  276. break
  277. if e.reason == "NotVerified":
  278. print >>sys.stderr, "Account not verified."
  279. break
  280. if e.reason == "TermsNotAgreed":
  281. print >>sys.stderr, "User has not agreed to TOS."
  282. break
  283. if e.reason == "AccountDeleted":
  284. print >>sys.stderr, "The user account has been deleted."
  285. break
  286. if e.reason == "AccountDisabled":
  287. print >>sys.stderr, "The user account has been disabled."
  288. break
  289. if e.reason == "ServiceDisabled":
  290. print >>sys.stderr, ("The user's access to the service has been "
  291. "disabled.")
  292. break
  293. if e.reason == "ServiceUnavailable":
  294. print >>sys.stderr, "The service is not available; try again later."
  295. break
  296. raise
  297. self._GetAuthCookie(auth_token)
  298. return
  299. def Send(self, request_path, payload=None,
  300. content_type="application/octet-stream",
  301. timeout=None,
  302. extra_headers=None,
  303. **kwargs):
  304. """Sends an RPC and returns the response.
  305. Args:
  306. request_path: The path to send the request to, eg /api/appversion/create.
  307. payload: The body of the request, or None to send an empty request.
  308. content_type: The Content-Type header to use.
  309. timeout: timeout in seconds; default None i.e. no timeout.
  310. (Note: for large requests on OS X, the timeout doesn't work right.)
  311. extra_headers: Dict containing additional HTTP headers that should be
  312. included in the request (string header names mapped to their values),
  313. or None to not include any additional headers.
  314. kwargs: Any keyword arguments are converted into query string parameters.
  315. Returns:
  316. The response body, as a string.
  317. """
  318. # TODO: Don't require authentication. Let the server say
  319. # whether it is necessary.
  320. if not self.authenticated:
  321. self._Authenticate()
  322. old_timeout = socket.getdefaulttimeout()
  323. socket.setdefaulttimeout(timeout)
  324. try:
  325. tries = 0
  326. while True:
  327. tries += 1
  328. args = dict(kwargs)
  329. url = "%s%s" % (self.host, request_path)
  330. if args:
  331. url += "?" + urllib.urlencode(args)
  332. req = self._CreateRequest(url=url, data=payload)
  333. req.add_header("Content-Type", content_type)
  334. if extra_headers:
  335. for header, value in extra_headers.items():
  336. req.add_header(header, value)
  337. try:
  338. f = self.opener.open(req)
  339. response = f.read()
  340. f.close()
  341. return response
  342. except urllib2.HTTPError, e:
  343. if tries > 3:
  344. raise
  345. elif e.code == 401 or e.code == 302:
  346. self._Authenticate()
  347. ## elif e.code >= 500 and e.code < 600:
  348. ## # Server Error - try again.
  349. ## continue
  350. else:
  351. raise
  352. finally:
  353. socket.setdefaulttimeout(old_timeout)
  354. class HttpRpcServer(AbstractRpcServer):
  355. """Provides a simplified RPC-style interface for HTTP requests."""
  356. def _Authenticate(self):
  357. """Save the cookie jar after authentication."""
  358. super(HttpRpcServer, self)._Authenticate()
  359. if self.save_cookies:
  360. StatusUpdate("Saving authentication cookies to %s" % self.cookie_file)
  361. self.cookie_jar.save()
  362. def _GetOpener(self):
  363. """Returns an OpenerDirector that supports cookies and ignores redirects.
  364. Returns:
  365. A urllib2.OpenerDirector object.
  366. """
  367. opener = urllib2.OpenerDirector()
  368. opener.add_handler(urllib2.ProxyHandler())
  369. opener.add_handler(urllib2.UnknownHandler())
  370. opener.add_handler(urllib2.HTTPHandler())
  371. opener.add_handler(urllib2.HTTPDefaultErrorHandler())
  372. opener.add_handler(urllib2.HTTPSHandler())
  373. opener.add_handler(urllib2.HTTPErrorProcessor())
  374. if self.save_cookies:
  375. self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies")
  376. self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file)
  377. if os.path.exists(self.cookie_file):
  378. try:
  379. self.cookie_jar.load()
  380. self.authenticated = True
  381. StatusUpdate("Loaded authentication cookies from %s" %
  382. self.cookie_file)
  383. except (cookielib.LoadError, IOError):
  384. # Failed to load cookies - just ignore them.
  385. pass
  386. else:
  387. # Create an empty cookie file with mode 600
  388. fd = os.open(self.cookie_file, os.O_CREAT, 0600)
  389. os.close(fd)
  390. # Always chmod the cookie file
  391. os.chmod(self.cookie_file, 0600)
  392. else:
  393. # Don't save cookies across runs of update.py.
  394. self.cookie_jar = cookielib.CookieJar()
  395. opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar))
  396. return opener
  397. parser = optparse.OptionParser(
  398. usage="%prog [options] [-- diff_options] [path...]")
  399. parser.add_option("-y", "--assume_yes", action="store_true",
  400. dest="assume_yes", default=False,
  401. help="Assume that the answer to yes/no questions is 'yes'.")
  402. # Logging
  403. group = parser.add_option_group("Logging options")
  404. group.add_option("-q", "--quiet", action="store_const", const=0,
  405. dest="verbose", help="Print errors only.")
  406. group.add_option("-v", "--verbose", action="store_const", const=2,
  407. dest="verbose", default=1,
  408. help="Print info level logs.")
  409. group.add_option("--noisy", action="store_const", const=3,
  410. dest="verbose", help="Print all logs.")
  411. # Review server
  412. group = parser.add_option_group("Review server options")
  413. group.add_option("-s", "--server", action="store", dest="server",
  414. default=DEFAULT_REVIEW_SERVER,
  415. metavar="SERVER",
  416. help=("The server to upload to. The format is host[:port]. "
  417. "Defaults to '%default'."))
  418. group.add_option("-e", "--email", action="store", dest="email",
  419. metavar="EMAIL", default=None,
  420. help="The username to use. Will prompt if omitted.")
  421. group.add_option("-H", "--host", action="store", dest="host",
  422. metavar="HOST", default=None,
  423. help="Overrides the Host header sent with all RPCs.")
  424. group.add_option("--no_cookies", action="store_false",
  425. dest="save_cookies", default=True,
  426. help="Do not save authentication cookies to local disk.")
  427. group.add_option("--account_type", action="store", dest="account_type",
  428. metavar="TYPE", default=AUTH_ACCOUNT_TYPE,
  429. choices=["GOOGLE", "HOSTED"],
  430. help=("Override the default account type "
  431. "(defaults to '%default', "
  432. "valid choices are 'GOOGLE' and 'HOSTED')."))
  433. # Issue
  434. group = parser.add_option_group("Issue options")
  435. group.add_option("-d", "--description", action="store", dest="description",
  436. metavar="DESCRIPTION", default=None,
  437. help="Optional description when creating an issue.")
  438. group.add_option("-f", "--description_file", action="store",
  439. dest="description_file", metavar="DESCRIPTION_FILE",
  440. default=None,
  441. help="Optional path of a file that contains "
  442. "the description when creating an issue.")
  443. group.add_option("-r", "--reviewers", action="store", dest="reviewers",
  444. metavar="REVIEWERS", default=DEFAULT_REVIEWER,
  445. help="Add reviewers (comma separated email addresses).")
  446. group.add_option("--cc", action="store", dest="cc",
  447. metavar="CC", default=DEFAULT_CC,
  448. help="Add CC (comma separated email addresses).")
  449. group.add_option("--private", action="store_true", dest="private",
  450. default=False,
  451. help="Make the issue restricted to reviewers and those CCed")
  452. # Upload options
  453. group = parser.add_option_group("Patch options")
  454. group.add_option("-m", "--message", action="store", dest="message",
  455. metavar="MESSAGE", default=None,
  456. help="A message to identify the patch. "
  457. "Will prompt if omitted.")
  458. group.add_option("-i", "--issue", type="int", action="store",
  459. metavar="ISSUE", default=None,
  460. help="Issue number to which to add. Defaults to new issue.")
  461. group.add_option("--base_url", action="store", dest="base_url", default=None,
  462. help="Base repository URL (listed as \"Base URL\" when "
  463. "viewing issue). If omitted, will be guessed automatically "
  464. "for SVN repos and left blank for others.")
  465. group.add_option("--download_base", action="store_true",
  466. dest="download_base", default=False,
  467. help="Base files will be downloaded by the server "
  468. "(side-by-side diffs may not work on files with CRs).")
  469. group.add_option("--rev", action="store", dest="revision",
  470. metavar="REV", default=None,
  471. help="Base revision/branch/tree to diff against. Use "
  472. "rev1:rev2 range to review already committed changeset.")
  473. group.add_option("--send_mail", action="store_true",
  474. dest="send_mail", default=False,
  475. help="Send notification email to reviewers.")
  476. group.add_option("--vcs", action="store", dest="vcs",
  477. metavar="VCS", default=None,
  478. help=("Version control system (optional, usually upload.py "
  479. "already guesses the right VCS)."))
  480. group.add_option("--emulate_svn_auto_props", action="store_true",
  481. dest="emulate_svn_auto_props", default=False,
  482. help=("Emulate Subversion's auto properties feature."))
  483. def GetRpcServer(server, email=None, host_override=None, save_cookies=True,
  484. account_type=AUTH_ACCOUNT_TYPE):
  485. """Returns an instance of an AbstractRpcServer.
  486. Args:
  487. server: String containing the review server URL.
  488. email: String containing user's email address.
  489. host_override: If not None, string containing an alternate hostname to use
  490. in the host header.
  491. save_cookies: Whether authentication cookies should be saved to disk.
  492. account_type: Account type for authentication, either 'GOOGLE'
  493. or 'HOSTED'. Defaults to AUTH_ACCOUNT_TYPE.
  494. Returns:
  495. A new AbstractRpcServer, on which RPC calls can be made.
  496. """
  497. rpc_server_class = HttpRpcServer
  498. # If this is the dev_appserver, use fake authentication.
  499. host = (host_override or server).lower()
  500. if host == "localhost" or host.startswith("localhost:"):
  501. if email is None:
  502. email = "test@example.com"
  503. logging.info("Using debug user %s. Override with --email" % email)
  504. server = rpc_server_class(
  505. server,
  506. lambda: (email, "password"),
  507. host_override=host_override,
  508. extra_headers={"Cookie":
  509. 'dev_appserver_login="%s:False"' % email},
  510. save_cookies=save_cookies,
  511. account_type=account_type)
  512. # Don't try to talk to ClientLogin.
  513. server.authenticated = True
  514. return server
  515. def GetUserCredentials():
  516. """Prompts the user for a username and password."""
  517. # Create a local alias to the email variable to avoid Python's crazy
  518. # scoping rules.
  519. local_email = email
  520. if local_email is None:
  521. local_email = GetEmail("Email (login for uploading to %s)" % server)
  522. password = None
  523. if keyring:
  524. password = keyring.get_password(host, local_email)
  525. if password is not None:
  526. print "Using password from system keyring."
  527. else:
  528. password = getpass.getpass("Password for %s: " % local_email)
  529. if keyring:
  530. answer = raw_input("Store password in system keyring?(y/N) ").strip()
  531. if answer == "y":
  532. keyring.set_password(host, local_email, password)
  533. return (local_email, password)
  534. return rpc_server_class(server,
  535. GetUserCredentials,
  536. host_override=host_override,
  537. save_cookies=save_cookies)
  538. def EncodeMultipartFormData(fields, files):
  539. """Encode form fields for multipart/form-data.
  540. Args:
  541. fields: A sequence of (name, value) elements for regular form fields.
  542. files: A sequence of (name, filename, value) elements for data to be
  543. uploaded as files.
  544. Returns:
  545. (content_type, body) ready for httplib.HTTP instance.
  546. Source:
  547. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
  548. """
  549. BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-'
  550. CRLF = '\r\n'
  551. lines = []
  552. for (key, value) in fields:
  553. lines.append('--' + BOUNDARY)
  554. lines.append('Content-Disposition: form-data; name="%s"' % key)
  555. lines.append('')
  556. if isinstance(value, unicode):
  557. value = value.encode('utf-8')
  558. lines.append(value)
  559. for (key, filename, value) in files:
  560. lines.append('--' + BOUNDARY)
  561. lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' %
  562. (key, filename))
  563. lines.append('Content-Type: %s' % GetContentType(filename))
  564. lines.append('')
  565. if isinstance(value, unicode):
  566. value = value.encode('utf-8')
  567. lines.append(value)
  568. lines.append('--' + BOUNDARY + '--')
  569. lines.append('')
  570. body = CRLF.join(lines)
  571. content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
  572. return content_type, body
  573. def GetContentType(filename):
  574. """Helper to guess the content-type from the filename."""
  575. return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
  576. # Use a shell for subcommands on Windows to get a PATH search.
  577. use_shell = sys.platform.startswith("win")
  578. def RunShellWithReturnCode(command, print_output=False,
  579. universal_newlines=True,
  580. env=os.environ):
  581. """Executes a command and returns the output from stdout and the return code.
  582. Args:
  583. command: Command to execute.
  584. print_output: If True, the output is printed to stdout.
  585. If False, both stdout and stderr are ignored.
  586. universal_newlines: Use universal_newlines flag (default: True).
  587. Returns:
  588. Tuple (output, return code)
  589. """
  590. logging.info("Running %s", command)
  591. p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  592. shell=use_shell, universal_newlines=universal_newlines,
  593. env=env)
  594. if print_output:
  595. output_array = []
  596. while True:
  597. line = p.stdout.readline()
  598. if not line:
  599. break
  600. print line.strip("\n")
  601. output_array.append(line)
  602. output = "".join(output_array)
  603. else:
  604. output = p.stdout.read()
  605. p.wait()
  606. errout = p.stderr.read()
  607. if print_output and errout:
  608. print >>sys.stderr, errout
  609. p.stdout.close()
  610. p.stderr.close()
  611. return output, p.returncode
  612. def RunShell(command, silent_ok=False, universal_newlines=True,
  613. print_output=False, env=os.environ):
  614. data, retcode = RunShellWithReturnCode(command, print_output,
  615. universal_newlines, env)
  616. if retcode:
  617. ErrorExit("Got error status from %s:\n%s" % (command, data))
  618. if not silent_ok and not data:
  619. ErrorExit("No output from %s" % command)
  620. return data
  621. class VersionControlSystem(object):
  622. """Abstract base class providing an interface to the VCS."""
  623. def __init__(self, options):
  624. """Constructor.
  625. Args:
  626. options: Command line options.
  627. """
  628. self.options = options
  629. def PostProcessDiff(self, diff):
  630. """Return the diff with any special post processing this VCS needs, e.g.
  631. to include an svn-style "Index:"."""
  632. return diff
  633. def GenerateDiff(self, args):
  634. """Return the current diff as a string.
  635. Args:
  636. args: Extra arguments to pass to the diff command.
  637. """
  638. raise NotImplementedError(
  639. "abstract method -- subclass %s must override" % self.__class__)
  640. def GetUnknownFiles(self):
  641. """Return a list of files unknown to the VCS."""
  642. raise NotImplementedError(
  643. "abstract method -- subclass %s must override" % self.__class__)
  644. def CheckForUnknownFiles(self):
  645. """Show an "are you sure?" prompt if there are unknown files."""
  646. unknown_files = self.GetUnknownFiles()
  647. if unknown_files:
  648. print "The following files are not added to version control:"
  649. for line in unknown_files:
  650. print line
  651. prompt = "Are you sure to continue?(y/N) "
  652. answer = raw_input(prompt).strip()
  653. if answer != "y":
  654. ErrorExit("User aborted")
  655. def GetBaseFile(self, filename):
  656. """Get the content of the upstream version of a file.
  657. Returns:
  658. A tuple (base_content, new_content, is_binary, status)
  659. base_content: The contents of the base file.
  660. new_content: For text files, this is empty. For binary files, this is
  661. the contents of the new file, since the diff output won't contain
  662. information to reconstruct the current file.
  663. is_binary: True iff the file is binary.
  664. status: The status of the file.
  665. """
  666. raise NotImplementedError(
  667. "abstract method -- subclass %s must override" % self.__class__)
  668. def GetBaseFiles(self, diff):
  669. """Helper that calls GetBase file for each file in the patch.
  670. Returns:
  671. A dictionary that maps from filename to GetBaseFile's tuple. Filenames
  672. are retrieved based on lines that start with "Index:" or
  673. "Property changes on:".
  674. """
  675. files = {}
  676. for line in diff.splitlines(True):
  677. if line.startswith('Index:') or line.startswith('Property changes on:'):
  678. unused, filename = line.split(':', 1)
  679. # On Windows if a file has property changes its filename uses '\'
  680. # instead of '/'.
  681. filename = filename.strip().replace('\\', '/')
  682. files[filename] = self.GetBaseFile(filename)
  683. return files
  684. def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options,
  685. files):
  686. """Uploads the base files (and if necessary, the current ones as well)."""
  687. def UploadFile(filename, file_id, content, is_binary, status, is_base):
  688. """Uploads a file to the server."""
  689. file_too_large = False
  690. if is_base:
  691. type = "base"
  692. else:
  693. type = "current"
  694. if len(content) > MAX_UPLOAD_SIZE:
  695. print ("Not uploading the %s file for %s because it's too large." %
  696. (type, filename))
  697. file_too_large = True
  698. content = ""
  699. checksum = md5(content).hexdigest()
  700. if options.verbose > 0 and not file_too_large:
  701. print "Uploading %s file for %s" % (type, filename)
  702. url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id)
  703. form_fields = [("filename", filename),
  704. ("status", status),
  705. ("checksum", checksum),
  706. ("is_binary", str(is_binary)),
  707. ("is_current", str(not is_base)),
  708. ]
  709. if file_too_large:
  710. form_fields.append(("file_too_large", "1"))
  711. if options.email:
  712. form_fields.append(("user", options.email))
  713. ctype, body = EncodeMultipartFormData(form_fields,
  714. [("data", filename, content)])
  715. response_body = rpc_server.Send(url, body,
  716. content_type=ctype)
  717. if not response_body.startswith("OK"):
  718. StatusUpdate(" --> %s" % response_body)
  719. sys.exit(1)
  720. patches = dict()
  721. [patches.setdefault(v, k) for k, v in patch_list]
  722. for filename in patches.keys():
  723. base_content, new_content, is_binary, status = files[filename]
  724. file_id_str = patches.get(filename)
  725. if file_id_str.find("nobase") != -1:
  726. base_content = None
  727. file_id_str = file_id_str[file_id_str.rfind("_") + 1:]
  728. file_id = int(file_id_str)
  729. if base_content != None:
  730. UploadFile(filename, file_id, base_content, is_binary, status, True)
  731. if new_content != None:
  732. UploadFile(filename, file_id, new_content, is_binary, status, False)
  733. def IsImage(self, filename):
  734. """Returns true if the filename has an image extension."""
  735. mimetype = mimetypes.guess_type(filename)[0]
  736. if not mimetype:
  737. return False
  738. return mimetype.startswith("image/")
  739. def IsBinary(self, filename):
  740. """Returns true if the guessed mimetyped isnt't in text group."""
  741. mimetype = mimetypes.guess_type(filename)[0]
  742. if not mimetype:
  743. return False # e.g. README, "real" binaries usually have an extension
  744. # special case for text files which don't start with text/
  745. if mimetype in TEXT_MIMETYPES:
  746. return False
  747. return not mimetype.startswith("text/")
  748. class SubversionVCS(VersionControlSystem):
  749. """Implementation of the VersionControlSystem interface for Subversion."""
  750. def __init__(self, options):
  751. super(SubversionVCS, self).__init__(options)
  752. if self.options.revision:
  753. match = re.match(r"(\d+)(:(\d+))?", self.options.revision)
  754. if not match:
  755. ErrorExit("Invalid Subversion revision %s." % self.options.revision)
  756. self.rev_start = match.group(1)
  757. self.rev_end = match.group(3)
  758. else:
  759. self.rev_start = self.rev_end = None
  760. # Cache output from "svn list -r REVNO dirname".
  761. # Keys: dirname, Values: 2-tuple (ouput for start rev and end rev).
  762. self.svnls_cache = {}
  763. # Base URL is required to fetch files deleted in an older revision.
  764. # Result is cached to not guess it over and over again in GetBaseFile().
  765. required = self.options.download_base or self.options.revision is not None
  766. self.svn_base = self._GuessBase(required)
  767. def GuessBase(self, required):
  768. """Wrapper for _GuessBase."""
  769. return self.svn_base
  770. def _GuessBase(self, required):
  771. """Returns the SVN base URL.
  772. Args:
  773. required: If true, exits if the url can't be guessed, otherwise None is
  774. returned.
  775. """
  776. info = RunShell(["svn", "info"])
  777. for line in info.splitlines():
  778. words = line.split()
  779. if len(words) == 2 and words[0] == "URL:":
  780. url = words[1]
  781. scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
  782. username, netloc = urllib.splituser(netloc)
  783. if username:
  784. logging.info("Removed username from base URL")
  785. if netloc.endswith("svn.python.org"):
  786. if netloc == "svn.python.org":
  787. if path.startswith("/projects/"):
  788. path = path[9:]
  789. elif netloc != "pythondev@svn.python.org":
  790. ErrorExit("Unrecognized Python URL: %s" % url)
  791. base = "http://svn.python.org/view/*checkout*%s/" % path
  792. logging.info("Guessed Python base = %s", base)
  793. elif netloc.endswith("svn.collab.net"):
  794. if path.startswith("/repos/"):
  795. path = path[6:]
  796. base = "http://svn.collab.net/viewvc/*checkout*%s/" % path
  797. logging.info("Guessed CollabNet base = %s", base)
  798. elif netloc.endswith(".googlecode.com"):
  799. path = path + "/"
  800. base = urlparse.urlunparse(("http", netloc, path, params,
  801. query, fragment))
  802. logging.info("Guessed Google Code base = %s", base)
  803. else:
  804. path = path + "/"
  805. base = urlparse.urlunparse((scheme, netloc, path, params,
  806. query, fragment))
  807. logging.info("Guessed base = %s", base)
  808. return base
  809. if required:
  810. ErrorExit("Can't find URL in output from svn info")
  811. return None
  812. def GenerateDiff(self, args):
  813. cmd = ["svn", "diff"]
  814. if self.options.revision:
  815. cmd += ["-r", self.options.revision]
  816. cmd.extend(args)
  817. data = RunShell(cmd)
  818. count = 0
  819. for line in data.splitlines():
  820. if line.startswith("Index:") or line.startswith("Property changes on:"):
  821. count += 1
  822. logging.info(line)
  823. if not count:
  824. ErrorExit("No valid patches found in output from svn diff")
  825. return data
  826. def _CollapseKeywords(self, content, keyword_str):
  827. """Collapses SVN keywords."""
  828. # svn cat translates keywords but svn diff doesn't. As a result of this
  829. # behavior patching.PatchChunks() fails with a chunk mismatch error.
  830. # This part was originally written by the Review Board development team
  831. # who had the same problem (http://reviews.review-board.org/r/276/).
  832. # Mapping of keywords to known aliases
  833. svn_keywords = {
  834. # Standard keywords
  835. 'Date': ['Date', 'LastChangedDate'],
  836. 'Revision': ['Revision', 'LastChangedRevision', 'Rev'],
  837. 'Author': ['Author', 'LastChangedBy'],
  838. 'HeadURL': ['HeadURL', 'URL'],
  839. 'Id': ['Id'],
  840. # Aliases
  841. 'LastChangedDate': ['LastChangedDate', 'Date'],
  842. 'LastChangedRevision': ['LastChangedRevision', 'Rev', 'Revision'],
  843. 'LastChangedBy': ['LastChangedBy', 'Author'],
  844. 'URL': ['URL', 'HeadURL'],
  845. }
  846. def repl(m):
  847. if m.group(2):
  848. return "$%s::%s$" % (m.group(1), " " * len(m.group(3)))
  849. return "$%s$" % m.group(1)
  850. keywords = [keyword
  851. for name in keyword_str.split(" ")
  852. for keyword in svn_keywords.get(name, [])]
  853. return re.sub(r"\$(%s):(:?)([^\$]+)\$" % '|'.join(keywords), repl, content)
  854. def GetUnknownFiles(self):
  855. status = RunShell(["svn", "status", "--ignore-externals"], silent_ok=True)
  856. unknown_files = []
  857. for line in status.split("\n"):
  858. if line and line[0] == "?":
  859. unknown_files.append(line)
  860. return unknown_files
  861. def ReadFile(self, filename):
  862. """Returns the contents of a file."""
  863. file = open(filename, 'rb')
  864. result = ""
  865. try:
  866. result = file.read()
  867. finally:
  868. file.close()
  869. return result
  870. def GetStatus(self, filename):
  871. """Returns the status of a file."""
  872. if not self.options.revision:
  873. status = RunShell(["svn", "status", "--ignore-externals", filename])
  874. if not status:
  875. ErrorExit("svn status returned no output for %s" % filename)
  876. status_lines = status.splitlines()
  877. # If file is in a cl, the output will begin with
  878. # "\n--- Changelist 'cl_name':\n". See
  879. # http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt
  880. if (len(status_lines) == 3 and
  881. not status_lines[0] and
  882. status_lines[1].startswith("--- Changelist")):
  883. status = status_lines[2]
  884. else:
  885. status = status_lines[0]
  886. # If we have a revision to diff against we need to run "svn list"
  887. # for the old and the new revision and compare the results to get
  888. # the correct status for a file.
  889. else:
  890. dirname, relfilename = os.path.split(filename)
  891. if dirname not in self.svnls_cache:
  892. cmd = ["svn", "list", "-r", self.rev_start, dirname or "."]
  893. out, returncode = RunShellWithReturnCode(cmd)
  894. if returncode:
  895. ErrorExit("Failed to get status for %s." % filename)
  896. old_files = out.splitlines()
  897. args = ["svn", "list"]
  898. if self.rev_end:
  899. args += ["-r", self.rev_end]
  900. cmd = args + [dirname or "."]
  901. out, returncode = RunShellWithReturnCode(cmd)
  902. if returncode:
  903. ErrorExit("Failed to run command %s" % cmd)
  904. self.svnls_cache[dirname] = (old_files, out.splitlines())
  905. old_files, new_files = self.svnls_cache[dirname]
  906. if relfilename in old_files and relfilename not in new_files:
  907. status = "D "
  908. elif relfilename in old_files and relfilename in new_files:
  909. status = "M "
  910. else:
  911. status = "A "
  912. return status
  913. def GetBaseFile(self, filename):
  914. status = self.GetStatus(filename)
  915. base_content = None
  916. new_content = None
  917. # If a file is copied its status will be "A +", which signifies
  918. # "addition-with-history". See "svn st" for more information. We need to
  919. # upload the original file or else diff parsing will fail if the file was
  920. # edited.
  921. if status[0] == "A" and status[3] != "+":
  922. # We'll need to upload the new content if we're adding a binary file
  923. # since diff's output won't contain it.
  924. mimetype = RunShell(["svn", "propget", "svn:mime-type", filename],
  925. silent_ok=True)
  926. base_content = ""
  927. is_binary = bool(mimetype) and not mimetype.startswith("text/")
  928. if is_binary and self.IsImage(filename):
  929. new_content = self.ReadFile(filename)
  930. elif (status[0] in ("M", "D", "R") or
  931. (status[0] == "A" and status[3] == "+") or # Copied file.
  932. (status[0] == " " and status[1] == "M")): # Property change.
  933. args = []
  934. if self.options.revision:
  935. url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
  936. else:
  937. # Don't change filename, it's needed later.
  938. url = filename
  939. args += ["-r", "BASE"]
  940. cmd = ["svn"] + args + ["propget", "svn:mime-type", url]
  941. mimetype, returncode = RunShellWithReturnCode(cmd)
  942. if returncode:
  943. # File does not exist in the requested revision.
  944. # Reset mimetype, it contains an error message.
  945. mimetype = ""
  946. get_base = False
  947. is_binary = bool(mimetype) and not mimetype.startswith("text/")
  948. if status[0] == " ":
  949. # Empty base content just to force an upload.
  950. base_content = ""
  951. elif is_binary:
  952. if self.IsImage(filename):
  953. get_base = True
  954. if status[0] == "M":
  955. if not self.rev_end:
  956. new_content = self.ReadFile(filename)
  957. else:
  958. url = "%s/%s@%s" % (self.svn_base, filename, self.rev_end)
  959. new_content = RunShell(["svn", "cat", url],
  960. universal_newlines=True, silent_ok=True)
  961. else:
  962. base_content = ""
  963. else:
  964. get_base = True
  965. if get_base:
  966. if is_binary:
  967. universal_newlines = False
  968. else:
  969. universal_newlines = True
  970. if self.rev_start:
  971. # "svn cat -r REV delete_file.txt" doesn't work. cat requires
  972. # the full URL with "@REV" appended instead of using "-r" option.
  973. url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
  974. base_content = RunShell(["svn", "cat", url],
  975. universal_newlines=universal_newlines,
  976. silent_ok=True)
  977. else:
  978. base_content, ret_code = RunShellWithReturnCode(
  979. ["svn", "cat", filename], universal_newlines=universal_newlines)
  980. if ret_code and status[0] == "R":
  981. # It's a replaced file without local history (see issue208).
  982. # The base file needs to be fetched from the server.
  983. url = "%s/%s" % (self.svn_base, filename)
  984. base_content = RunShell(["svn", "cat", url],
  985. universal_newlines=universal_newlines,
  986. silent_ok=True)
  987. elif ret_code:
  988. ErrorExit("Got error status from 'svn cat %s'" % filename)
  989. if not is_binary:
  990. args = []
  991. if self.rev_start:
  992. url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
  993. else:
  994. url = filename
  995. args += ["-r", "BASE"]
  996. cmd = ["svn"] + args + ["propget", "svn:keywords", url]
  997. keywords, returncode = RunShellWithReturnCode(cmd)
  998. if keywords and not returncode:
  999. base_content = self._CollapseKeywords(base_content, keywords)
  1000. else:
  1001. StatusUpdate("svn status returned unexpected output: %s" % status)
  1002. sys.exit(1)
  1003. return base_content, new_content, is_binary, status[0:5]
  1004. class GitVCS(VersionControlSystem):
  1005. """Implementation of the VersionControlSystem interface for Git."""
  1006. def __init__(self, options):
  1007. super(GitVCS, self).__init__(options)
  1008. # Map of filename -> (hash before, hash after) of base file.
  1009. # Hashes for "no such file" are represented as None.
  1010. self.hashes = {}
  1011. # Map of new filename -> old filename for renames.
  1012. self.renames = {}
  1013. def PostProcessDiff(self, gitdiff):
  1014. """Converts the diff output to include an svn-style "Index:" line as well
  1015. as record the hashes of the files, so we can upload them along with our
  1016. diff."""
  1017. # Special used by git to indicate "no such content".
  1018. NULL_HASH = "0"*40
  1019. def IsFileNew(filename):
  1020. return filename in self.hashes and self.hashes[filename][0] is None
  1021. def AddSubversionPropertyChange(filename):
  1022. """Add svn's property change information into the patch if given file is
  1023. new file.
  1024. We use Subversion's auto-props setting to retrieve its property.
  1025. See http://svnbook.red-bean.com/en/1.1/ch07.html#svn-ch-7-sect-1.3.2 for
  1026. Subversion's [auto-props] setting.
  1027. """
  1028. if self.options.emulate_svn_auto_props and IsFileNew(filename):
  1029. svnprops = GetSubversionPropertyChanges(filename)
  1030. if svnprops:
  1031. svndiff.append("\n" + svnprops + "\n")
  1032. svndiff = []
  1033. filecount = 0
  1034. filename = None
  1035. for line in gitdiff.splitlines():
  1036. match = re.match(r"diff --git a/(.*) b/(.*)$", line)
  1037. if match:
  1038. # Add auto property here for previously seen file.
  1039. if filename is not None:
  1040. AddSubversionPropertyChange(filename)
  1041. filecount += 1
  1042. # Intentionally use the "after" filename so we can show renames.
  1043. filename = match.group(2)
  1044. svndiff.append("Index: %s\n" % filename)
  1045. if match.group(1) != match.group(2):
  1046. self.renames[match.group(2)] = match.group(1)
  1047. else:
  1048. # The "index" line in a git diff looks like this (long hashes elided):
  1049. # index 82c0d44..b2cee3f 100755
  1050. # We want to save the left hash, as that identifies the base file.
  1051. match = re.match(r"index (\w+)\.\.(\w+)", line)
  1052. if match:
  1053. before, after = (match.group(1), match.group(2))
  1054. if before == NULL_HASH:
  1055. before = None
  1056. if after == NULL_HASH:
  1057. after = None
  1058. self.hashes[filename] = (before, after)
  1059. svndiff.append(line + "\n")
  1060. if not filecount:
  1061. ErrorExit("No valid patches found in output from git diff")
  1062. # Add auto property for the last seen file.
  1063. assert filename is not None
  1064. AddSubversionPropertyChange(filename)
  1065. return "".join(svndiff)
  1066. def GenerateDiff(self, extra_args):
  1067. extra_args = extra_args[:]
  1068. if self.options.revision:
  1069. if ":" in self.options.revision:
  1070. extra_args = self.options.revision.split(":", 1) + extra_args
  1071. else:
  1072. extra_args = [self.options.revision] + extra_args
  1073. # --no-ext-diff is broken in some versions of Git, so try to work around
  1074. # this by overriding the environment (but there is still a problem if the
  1075. # git config key "diff.external" is used).
  1076. env = os.environ.copy()
  1077. if 'GIT_EXTERNAL_DIFF' in env: del env['GIT_EXTERNAL_DIFF']
  1078. return RunShell(["git", "diff", "--no-ext-diff", "--full-index", "-M"]
  1079. + extra_args, env=env)
  1080. def GetUnknownFiles(self):
  1081. status = RunShell(["git", "ls-files", "--exclude-standard", "--others"],
  1082. silent_ok=True)
  1083. return status.splitlines()
  1084. def GetFileContent(self, file_hash, is_binary):
  1085. """Returns the content of a file identified by its git hash."""
  1086. data, retcode = RunShellWithReturnCode(["git", "show", file_hash],
  1087. universal_newlines=not is_binary)
  1088. if retcode:
  1089. ErrorExit("Got error status from 'git show %s'" % file_hash)
  1090. return data
  1091. def GetBaseFile(self, filename):
  1092. hash_before, hash_after = self.hashes.get(filename, (None,None))
  1093. base_content = None
  1094. new_content = None
  1095. is_binary = self.IsBinary(filename)
  1096. status = None
  1097. if filename in self.renames:
  1098. status = "A +" # Match svn attribute name for renames.
  1099. if filename not in self.hashes:
  1100. # If a rename doesn't change the content, we never get a hash.
  1101. base_content = RunShell(["git", "show", "HEAD:" + filename])
  1102. elif not hash_before:
  1103. status = "A"
  1104. base_content = ""
  1105. elif not hash_after:
  1106. status = "D"
  1107. else:
  1108. status = "M"
  1109. is_image = self.IsImage(filename)
  1110. # Grab the before/after content if we need it.
  1111. # We should include file contents if it's text or it's an image.
  1112. if not is_binary or is_image:
  1113. # Grab the base content if we don't have it already.
  1114. if base_content is None and hash_before:
  1115. base_content = self.GetFileContent(hash_before, is_binary)
  1116. # Only include the "after" file if it's an image; otherwise it
  1117. # it is reconstructed from the diff.
  1118. if is_image and hash_after:
  1119. new_content = self.GetFileContent(hash_after, is_binary)
  1120. return (base_content, new_content, is_binary, status)
  1121. class MercurialVCS(VersionControlSystem):
  1122. """Implementation of the VersionControlSystem interface for Mercurial."""
  1123. def __init__(self, options, repo_dir):
  1124. super(MercurialVCS, self).__init__(options)
  1125. # Absolute path to repository (we can be in a subdir)
  1126. self.repo_dir = os.path.normpath(repo_dir)
  1127. # Compute the subdir
  1128. cwd = os.path.normpath(os.getcwd())
  1129. assert cwd.startswith(self.repo_dir)
  1130. self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/")
  1131. if self.options.revision:
  1132. self.base_rev = self.options.revision
  1133. else:
  1134. self.base_rev = RunShell(["hg", "parent", "-q"]).split(':')[1].strip()
  1135. def _GetRelPath(self, filename):
  1136. """Get relative path of a file according to the current directory,
  1137. given its logical path in the repo."""
  1138. assert filename.startswith(self.subdir), (filename, self.subdir)
  1139. return filename[len(self.subdir):].lstrip(r"\/")
  1140. def GenerateDiff(self, extra_args):
  1141. cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args
  1142. data = RunShell(cmd, silent_ok=True)
  1143. svndiff = []
  1144. filecount = 0
  1145. for line in data.splitlines():
  1146. m = re.match("diff --git a/(\S+) b/(\S+)", line)
  1147. if m:
  1148. # Modify line to make it look like as it comes from svn diff.
  1149. # With this modification no changes on the server side are required
  1150. # to make upload.py work with Mercurial repos.
  1151. # NOTE: for proper handling of moved/copied files, we have to use
  1152. # the second filename.
  1153. filename = m.group(2)
  1154. svndiff.append("Index: %s" % filename)
  1155. svndiff.append("=" * 67)
  1156. filecount += 1
  1157. logging.info(line)
  1158. else:
  1159. svndiff.append(line)
  1160. if not filecount:
  1161. ErrorExit("No valid patches found in output from hg diff")
  1162. return "\n".join(svndiff) + "\n"
  1163. def GetUnknownFiles(self):
  1164. """Return a list of files unknown to the VCS."""
  1165. args = []
  1166. status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."],
  1167. silent_ok=True)
  1168. unknown_files = []
  1169. for line in status.splitlines():
  1170. st, fn = line.split(" ", 1)
  1171. if st == "?":
  1172. unknown_files.append(fn)
  1173. return unknown_files
  1174. def GetBaseFile(self, filename):
  1175. # "hg status" and "hg cat" both take a path relative to the current subdir
  1176. # rather than to the repo root, but "hg diff" has given us the full path
  1177. # to the repo root.
  1178. base_content = ""
  1179. new_content = None
  1180. is_binary = False
  1181. oldrelpath = relpath = self._GetRelPath(filename)
  1182. # "hg status -C" returns two lines for moved/copied files, one otherwise
  1183. out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath])
  1184. out = out.splitlines()
  1185. # HACK: strip error message about missing file/directory if it isn't in
  1186. # the working copy
  1187. if out[0].startswith('%s: ' % relpath):
  1188. out = out[1:]
  1189. if len(out) > 1:
  1190. # Moved/copied => considered as modified, use old filename to
  1191. # retrieve base contents
  1192. oldrelpath = out[1].strip()
  1193. status = "M"
  1194. else:
  1195. status, _ = out[0].split(' ', 1)
  1196. if ":" in self.base_rev:
  1197. base_rev = self.base_rev.split(":", 1)[0]
  1198. else:
  1199. base_rev = self.base_rev
  1200. if status != "A":
  1201. base_content = RunShell(["hg", "cat", "-r", base_rev, oldrelpath],
  1202. silent_ok=True)
  1203. is_binary = "\0" in base_content # Mercurial's heuristic
  1204. if status != "R":
  1205. new_content = open(relpath, "rb").read()
  1206. is_binary = is_binary or "\0" in new_content
  1207. if is_binary and base_content:
  1208. # Fetch again without converting newlines
  1209. base_content = RunShell(["hg", "cat", "-r", base_rev, oldrelpath],
  1210. silent_ok=True, universal_newlines=False)
  1211. if not is_binary or not self.IsImage(relpath):
  1212. new_content = None
  1213. return base_content, new_content, is_binary, status
  1214. # NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync.
  1215. def SplitPatch(data):
  1216. """Splits a patch into separate pieces for each file.
  1217. Args:
  1218. data: A string containing the output of svn diff.
  1219. Returns:
  1220. A list of 2-tuple (filename, text) where text is the svn diff output
  1221. pertaining to filename.
  1222. """
  1223. patches = []
  1224. filename = None
  1225. diff = []
  1226. for line in data.splitlines(True):
  1227. new_filename = None
  1228. if line.startswith('Index:'):
  1229. unused, new_filename = line.split(':', 1)
  1230. new_filename = new_filename.strip()
  1231. elif line.startswith('Property changes on:'):
  1232. unused, temp_filename = line.split(':', 1)
  1233. # When a file is modified, paths use '/' between directories, however
  1234. # when a property is modified '\' is used on Windows. Make them the same
  1235. # otherwise the file shows up twice.
  1236. temp_filename = temp_filename.strip().replace('\\', '/')
  1237. if temp_filename != filename:
  1238. # File has property changes but no modifications, create a new diff.
  1239. new_filename = temp_filename
  1240. if new_filename:
  1241. if filename and diff:
  1242. patches.append((filename, ''.join(diff)))
  1243. filename = new_filename
  1244. diff = [line]
  1245. continue
  1246. if diff is not None:
  1247. diff.append(line)
  1248. if filename and diff:
  1249. patches.append((filename, ''.join(diff)))
  1250. return patches
  1251. def UploadSeparatePatches(issue, rpc_server, patchset, data, options):
  1252. """Uploads a separate patch for each file in the diff output.
  1253. Returns a list of [patch_key, filename] for each file.
  1254. """
  1255. patches = SplitPatch(data)
  1256. rv = []
  1257. for patch in patches:
  1258. if len(patch[1]) > MAX_UPLOAD_SIZE:
  1259. print ("Not uploading the patch for " + patch[0] +
  1260. " because the file is too large.")
  1261. continue
  1262. form_fields = [("filename", patch[0])]
  1263. if not options.download_base:
  1264. form_fields.append(("content_upload", "1"))
  1265. files = [("data", "data.diff", patch[1])]
  1266. ctype, body = EncodeMultipartFormData(form_fields, files)
  1267. url = "/%d/upload_patch/%d" % (int(issue), int(patchset))
  1268. print "Uploading patch for " + patch[0]
  1269. response_body = rpc_server.Send(url, body, content_type=ctype)
  1270. lines = response_body.splitlines()
  1271. if not lines or lines[0] != "OK":
  1272. StatusUpdate(" --> %s" % response_body)
  1273. sys.exit(1)
  1274. rv.append([lines[1], patch[0]])
  1275. return rv
  1276. def GuessVCSName():
  1277. """Helper to guess the version control system.
  1278. This examines the current directory, guesses which VersionControlSystem
  1279. we're using, and returns an string indicating which VCS is detected.
  1280. Returns:
  1281. A pair (vcs, output). vcs is a string indicating which VCS was detected
  1282. and is one of VCS_GIT, VCS_MERCURIAL, VCS_SUBVERSION, or VCS_UNKNOWN.
  1283. output is a string containing any interesting output from the vcs
  1284. detection routine, or None if there is nothing interesting.
  1285. """
  1286. # Mercurial has a command to get the base directory of a repository
  1287. # Try running it, but don't die if we don't have hg installed.
  1288. # NOTE: we try Mercurial first as it can sit on top of an SVN working copy.
  1289. try:
  1290. out, returncode = RunShellWithReturnCode(["hg", "root"])
  1291. if returncode == 0:
  1292. return (VCS_MERCURIAL, out.strip())
  1293. except OSError, (errno, message):
  1294. if errno != 2: # ENOENT -- they don't have hg installed.
  1295. raise
  1296. # Subversion has a .svn in all working directories.
  1297. if os.path.isdir('.svn'):
  1298. logging.info("Guessed VCS = Subversion")
  1299. return (VCS_SUBVERSION, None)
  1300. # Git has a command to test if you're in a git tree.
  1301. # Try running it, but don't die if we don't have git installed.
  1302. try:
  1303. out, returncode = RunShellWithReturnCode(["git", "rev-parse",
  1304. "--is-inside-work-tree"])
  1305. if returncode == 0:
  1306. return (VCS_GIT, None)
  1307. except OSError, (errno, message):
  1308. if errno != 2: # ENOENT -- they don't have git installed.
  1309. raise
  1310. return (VCS_UNKNOWN, None)
  1311. def GuessVCS(options):
  1312. """Helper to guess the version control system.
  1313. This verifies any user-specified VersionControlSystem (by command line
  1314. or environment variable). If the user didn't specify one, this examines
  1315. the current directory, guesses which VersionControlSystem we're using,
  1316. and returns an instance of the appropriate class. Exit with an error
  1317. if we can't figure it out.
  1318. Returns:
  1319. A VersionControlSystem instance. Exits if the VCS can't be guessed.
  1320. """
  1321. vcs = options.vcs
  1322. if not vcs:
  1323. vcs = os.environ.get("CODEREVIEW_VCS")
  1324. if vcs:
  1325. v = VCS_ABBREVIATIONS.get(vcs.lower())
  1326. if v is None:
  1327. ErrorExit("Unknown version control system %r specified." % vcs)
  1328. (vcs, extra_output) = (v, None)
  1329. else:
  1330. (vcs, extra_output) = GuessVCSName()
  1331. if vcs == VCS_MERCURIAL:
  1332. if extra_output is None:
  1333. extra_output = RunShell(["hg", "root"]).strip()
  1334. return MercurialVCS(options, extra_output)
  1335. elif vcs == VCS_SUBVERSION:
  1336. return SubversionVCS(options)
  1337. elif vcs == VCS_GIT:
  1338. return GitVCS(options)
  1339. ErrorExit(("Could not guess version control system. "
  1340. "Are you in a working copy directory?"))
  1341. def CheckReviewer(reviewer):
  1342. """Validate a reviewer -- either a nickname or an email addres.
  1343. Args:
  1344. reviewer: A nickname or an email address.
  1345. Calls ErrorExit() if it is an invalid email address.
  1346. """
  1347. if "@" not in reviewer:
  1348. return # Assume nickname
  1349. parts = reviewer.split("@")
  1350. if len(parts) > 2:
  1351. ErrorExit("Invalid email address: %r" % reviewer)
  1352. assert len(parts) == 2
  1353. if "." not in parts[1]:
  1354. ErrorExit("Invalid email address: %r" % reviewer)
  1355. def LoadSubversionAutoProperties():
  1356. """Returns the content of [auto-props] section of Subversion's config file as
  1357. a dictionary.
  1358. Returns:
  1359. A dictionary whose key-value pair corresponds the [auto-props] section's
  1360. key-value pair.
  1361. In following cases, returns empty dictionary:
  1362. - config file doesn't exist, or
  1363. - 'enable-auto-props' is not set to 'true-like-value' in [miscellany].
  1364. """
  1365. if os.name == 'nt':
  1366. subversion_config = os.environ.get("APPDATA") + "\\Subversion\\config"
  1367. else:
  1368. subversion_config = os.path.expanduser("~/.subversion/config")
  1369. if not os.path.exists(subversion_config):
  1370. return {}
  1371. config = ConfigParser.ConfigParser()
  1372. config.read(subversion_config)
  1373. if (config.has_section("miscellany") and
  1374. config.has_option("miscellany", "enable-auto-props") and
  1375. config.getboolean("miscellany", "enable-auto-props") and
  1376. config.has_section("auto-props")):
  1377. props = {}
  1378. for file_pattern in config.options("auto-props"):
  1379. props[file_pattern] = ParseSubversionPropertyValues(
  1380. config.get("auto-props", file_pattern))
  1381. return props
  1382. else:
  1383. return {}
  1384. def ParseSubversionPropertyValues(props):
  1385. """Parse the given property value which comes from [auto-props] section and
  1386. returns a list whose element is a (svn_prop_key, svn_prop_value) pair.
  1387. See the following doctest for example.
  1388. >>> ParseSubversionPropertyValues('svn:eol-style=LF')
  1389. [('svn:eol-style', 'LF')]
  1390. >>> ParseSubversionPropertyValues('svn:mime-type=image/jpeg')
  1391. [('svn:mime-type', 'image/jpeg')]
  1392. >>> ParseSubversionPropertyValues('svn:eol-style=LF;svn:executable')
  1393. [('svn:eol-style', 'LF'), ('svn:executable', '*')]
  1394. """
  1395. key_value_pairs = []
  1396. for prop in props.split(";"):
  1397. key_value = prop.split("=")
  1398. assert len(key_value) <= 2
  1399. if len(key_value) == 1:
  1400. # If value is not given, use '*' as a Subversion's convention.
  1401. key_value_pairs.append((key_value[0], "*"))
  1402. else:
  1403. key_value_pairs.append((key_value[0], key_value[1]))
  1404. return key_value_pairs
  1405. def GetSubversionPropertyChanges(filename):
  1406. """Return a Subversion's 'Property changes on ...' string, which is used in
  1407. the patch file.
  1408. Args:
  1409. filename: filename whose property might be set by [auto-props] config.
  1410. Returns:
  1411. A string like 'Property changes on |filename| ...' if given |filename|
  1412. matches any entries in [auto-props] section. None, otherwise.
  1413. """
  1414. global svn_auto_props_map
  1415. if svn_auto_props_map is None:
  1416. svn_auto_props_map = LoadSubversionAutoProperties()
  1417. all_props = []
  1418. for file_pattern, props in svn_auto_props_map.items():
  1419. if fnmatch.fnmatch(filename, file_pattern):
  1420. all_props.extend(props)
  1421. if all_props:
  1422. return FormatSubversionPropertyChanges(filename, all_props)
  1423. return None
  1424. def FormatSubversionPropertyChanges(filename, props):
  1425. """Returns Subversion's 'Property changes on ...' strings using given filename
  1426. and properties.
  1427. Args:
  1428. filename: filename
  1429. props: A list whose element is a (svn_prop_key, svn_prop_value) pair.
  1430. Returns:
  1431. A string which can be used in the patch file for Subversion.
  1432. See the following doctest for example.
  1433. >>> print FormatSubversionPropertyChanges('foo.cc', [('svn:eol-style', 'LF')])
  1434. Property changes on: foo.cc
  1435. ___________________________________________________________________
  1436. Added: svn:eol-style
  1437. + LF
  1438. <BLANKLINE>
  1439. """
  1440. prop_changes_lines = [
  1441. "Property changes on: %s" % filename,
  1442. "___________________________________________________________________"]
  1443. for key, value in props:
  1444. prop_changes_lines.append("Added: " + key)
  1445. prop_changes_lines.append(" + " + value)
  1446. return "\n".join(prop_changes_lines) + "\n"
  1447. def RealMain(argv, data=None):
  1448. """The real main function.
  1449. Args:
  1450. argv: Command line arguments.
  1451. data: Diff contents. If None (default) the diff is generated by
  1452. the VersionControlSystem implementation returned by GuessVCS().
  1453. Returns:
  1454. A 2-tuple (issue id, patchset id).
  1455. The patchset id is None if the base files are not uploaded by this
  1456. script (applies only to SVN checkouts).
  1457. """
  1458. logging.basicConfig(format=("%(asctime).19s %(levelname)s %(filename)s:"
  1459. "%(lineno)s %(message)s "))
  1460. os.environ['LC_ALL'] = 'C'
  1461. options, args = parser.parse_args(argv[1:])
  1462. global verbosity
  1463. verbosity = options.verbose
  1464. if verbosity >= 3:
  1465. logging.getLogger().setLevel(logging.DEBUG)
  1466. elif verbosity >= 2:
  1467. logging.getLogger().setLevel(logging.INFO)
  1468. vcs = GuessVCS(options)
  1469. base = options.base_url
  1470. if isinstance(vcs, SubversionVCS):
  1471. # Guessing the base field is only supported for Subversion.
  1472. # Note: Fetching base files may become deprecated in future releases.
  1473. guessed_base = vcs.GuessBase(options.download_base)
  1474. if base:
  1475. if guessed_base and base != guessed_base:
  1476. print "Using base URL \"%s\" from --base_url instead of \"%s\"" % \
  1477. (base, guessed_base)
  1478. else:
  1479. base = guessed_base
  1480. if not base and options.download_base:
  1481. options.download_base = True
  1482. logging.info("Enabled upload of base file")
  1483. if not options.assume_yes:
  1484. vcs.CheckForUnknownFiles()
  1485. if data is None:
  1486. data = vcs.GenerateDiff(args)
  1487. data = vcs.PostProcessDiff(data)
  1488. files = vcs.GetBaseFiles(data)
  1489. if verbosity >= 1:
  1490. print "Upload server:", options.server, "(change with -s/--server)"
  1491. if options.issue:
  1492. prompt = "Message describing this patch set: "
  1493. else:
  1494. prompt = "New issue subject: "
  1495. message = options.message or raw_input(prompt).strip()
  1496. if not message:
  1497. ErrorExit("A non-empty message is required")
  1498. rpc_server = GetRpcServer(options.server,
  1499. options.email,
  1500. options.host,
  1501. options.save_cookies,
  1502. options.account_type)
  1503. form_fields = [("subject", message)]
  1504. if base:
  1505. form_fields.append(("base", base))
  1506. if options.issue:
  1507. form_fields.append(("issue", str(options.issue)))
  1508. if options.email:
  1509. form_fields.append(("user", options.email))
  1510. if options.reviewers:
  1511. for reviewer in options.reviewers.split(','):
  1512. CheckReviewer(reviewer)
  1513. form_fields.append(("reviewers", options.reviewers))
  1514. if options.cc:
  1515. for cc in options.cc.split(','):
  1516. CheckReviewer(cc)
  1517. form_fields.append(("cc", options.cc))
  1518. description = options.description
  1519. if options.description_file:
  1520. if options.description:
  1521. ErrorExit("Can't specify description and description_file")
  1522. file = open(options.description_file, 'r')
  1523. description = file.read()
  1524. file.close()
  1525. if description:
  1526. form_fields.append(("description", description))
  1527. # Send a hash of all the base file so the server can determine if a copy
  1528. # already exists in an earlier patchset.
  1529. base_hashes = ""
  1530. for file, info in files.iteritems():
  1531. if not info[0] is None:
  1532. checksum = md5(info[0]).hexdigest()
  1533. if base_hashes:
  1534. base_hashes += "|"
  1535. base_hashes += checksum + ":" + file
  1536. form_fields.append(("base_hashes", base_hashes))
  1537. if options.private:
  1538. if options.issue:
  1539. print "Warning: Private flag ignored when updating an existing issue."
  1540. else:
  1541. form_fields.append(("private", "1"))
  1542. # If we're uploading base files, don't send the email before the uploads, so
  1543. # that it contains the file status.
  1544. if options.send_mail and options.download_base:
  1545. form_fields.append(("send_mail", "1"))
  1546. if not options.download_base:
  1547. form_fields.append(("content_upload", "1"))
  1548. if len(data) > MAX_UPLOAD_SIZE:
  1549. print "Patch is large, so uploading file patches separately."
  1550. uploaded_diff_file = []
  1551. form_fields.append(("separate_patches", "1"))
  1552. else:
  1553. uploaded_diff_file = [("data", "data.diff", data)]
  1554. ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file)
  1555. response_body = rpc_server.Send("/upload", body, content_type=ctype)
  1556. patchset = None
  1557. if not options.download_base or not uploaded_diff_file:
  1558. lines = response_body.splitlines()
  1559. if len(lines) >= 2:
  1560. msg = lines[0]
  1561. patchset = lines[1].strip()
  1562. patches = [x.split(" ", 1) for x in lines[2:]]
  1563. else:
  1564. msg = response_body
  1565. else:
  1566. msg = response_body
  1567. StatusUpdate(msg)
  1568. if not response_body.startswith("Issue created.") and \
  1569. not response_body.startswith("Issue updated."):
  1570. sys.exit(0)
  1571. issue = msg[msg.rfind("/")+1:]
  1572. if not uploaded_diff_file:
  1573. result = UploadSeparatePatches(issue, rpc_server, patchset, data, options)
  1574. if not options.download_base:
  1575. patches = result
  1576. if not options.download_base:
  1577. vcs.UploadBaseFiles(issue, rpc_server, patches, patchset, options, files)
  1578. if options.send_mail:
  1579. rpc_server.Send("/" + issue + "/mail", payload="")
  1580. return issue, patchset
  1581. def main():
  1582. try:
  1583. RealMain(sys.argv)
  1584. except KeyboardInterrupt:
  1585. print
  1586. StatusUpdate("Interrupted.")
  1587. sys.exit(1)
  1588. if __name__ == "__main__":
  1589. main()