upload.py 51 KB

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