upload.py 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. #
  4. # Copyright 2007 Google Inc.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. """Tool for uploading diffs from a version control system to the codereview app.
  18. Usage summary: upload.py [options] [-- diff_options] [path...]
  19. Diff options are passed to the diff command of the underlying system.
  20. Supported version control systems:
  21. Git
  22. Mercurial
  23. Subversion
  24. Perforce
  25. CVS
  26. It is important for Git/Mercurial users to specify a tree/node/branch to diff
  27. against by using the '--rev' option.
  28. """
  29. # This code is derived from appcfg.py in the App Engine SDK (open source),
  30. # and from ASPN recipe #146306.
  31. import ConfigParser
  32. import cookielib
  33. import errno
  34. import fnmatch
  35. import getpass
  36. import logging
  37. import marshal
  38. import mimetypes
  39. import optparse
  40. import os
  41. import re
  42. import socket
  43. import subprocess
  44. import sys
  45. import urllib
  46. import urllib2
  47. import urlparse
  48. # The md5 module was deprecated in Python 2.5.
  49. try:
  50. from hashlib import md5
  51. except ImportError:
  52. from md5 import md5
  53. try:
  54. import readline
  55. except ImportError:
  56. pass
  57. try:
  58. import keyring
  59. except ImportError:
  60. keyring = None
  61. # The logging verbosity:
  62. # 0: Errors only.
  63. # 1: Status messages.
  64. # 2: Info logs.
  65. # 3: Debug logs.
  66. verbosity = 1
  67. # The account type used for authentication.
  68. # This line could be changed by the review server (see handler for
  69. # upload.py).
  70. AUTH_ACCOUNT_TYPE = "HOSTED"
  71. # URL of the default review server. As for AUTH_ACCOUNT_TYPE, this line could be
  72. # changed by the review server (see handler for upload.py).
  73. DEFAULT_REVIEW_SERVER = "codereview.10gen.com"
  74. # Max size of patch or base file.
  75. MAX_UPLOAD_SIZE = 900 * 1024
  76. # Constants for version control names. Used by GuessVCSName.
  77. VCS_GIT = "Git"
  78. VCS_MERCURIAL = "Mercurial"
  79. VCS_SUBVERSION = "Subversion"
  80. VCS_PERFORCE = "Perforce"
  81. VCS_CVS = "CVS"
  82. VCS_UNKNOWN = "Unknown"
  83. VCS_ABBREVIATIONS = {
  84. VCS_MERCURIAL.lower(): VCS_MERCURIAL,
  85. "hg": VCS_MERCURIAL,
  86. VCS_SUBVERSION.lower(): VCS_SUBVERSION,
  87. "svn": VCS_SUBVERSION,
  88. VCS_PERFORCE.lower(): VCS_PERFORCE,
  89. "p4": VCS_PERFORCE,
  90. VCS_GIT.lower(): VCS_GIT,
  91. VCS_CVS.lower(): VCS_CVS,
  92. }
  93. # The result of parsing Subversion's [auto-props] setting.
  94. svn_auto_props_map = None
  95. def GetEmail(prompt):
  96. """Prompts the user for their email address and returns it.
  97. The last used email address is saved to a file and offered up as a suggestion
  98. to the user. If the user presses enter without typing in anything the last
  99. used email address is used. If the user enters a new address, it is saved
  100. for next time we prompt.
  101. """
  102. last_email_file_name = os.path.expanduser("~/.last_codereview_email_address")
  103. last_email = ""
  104. if os.path.exists(last_email_file_name):
  105. try:
  106. last_email_file = open(last_email_file_name, "r")
  107. last_email = last_email_file.readline().strip("\n")
  108. last_email_file.close()
  109. prompt += " [%s]" % last_email
  110. except IOError, e:
  111. pass
  112. email = raw_input(prompt + ": ").strip()
  113. if email:
  114. try:
  115. last_email_file = open(last_email_file_name, "w")
  116. last_email_file.write(email)
  117. last_email_file.close()
  118. except IOError, e:
  119. pass
  120. else:
  121. email = last_email
  122. return email
  123. def StatusUpdate(msg):
  124. """Print a status message to stdout.
  125. If 'verbosity' is greater than 0, print the message.
  126. Args:
  127. msg: The string to print.
  128. """
  129. if verbosity > 0:
  130. print msg
  131. def ErrorExit(msg):
  132. """Print an error message to stderr and exit."""
  133. print >>sys.stderr, msg
  134. sys.exit(1)
  135. class ClientLoginError(urllib2.HTTPError):
  136. """Raised to indicate there was an error authenticating with ClientLogin."""
  137. def __init__(self, url, code, msg, headers, args):
  138. urllib2.HTTPError.__init__(self, url, code, msg, headers, None)
  139. self.args = args
  140. self.reason = args["Error"]
  141. self.info = args.get("Info", None)
  142. class AbstractRpcServer(object):
  143. """Provides a common interface for a simple RPC server."""
  144. def __init__(self, host, auth_function, host_override=None, extra_headers={},
  145. save_cookies=False, account_type=AUTH_ACCOUNT_TYPE):
  146. """Creates a new HttpRpcServer.
  147. Args:
  148. host: The host to send requests to.
  149. auth_function: A function that takes no arguments and returns an
  150. (email, password) tuple when called. Will be called if authentication
  151. is required.
  152. host_override: The host header to send to the server (defaults to host).
  153. extra_headers: A dict of extra headers to append to every request.
  154. save_cookies: If True, save the authentication cookies to local disk.
  155. If False, use an in-memory cookiejar instead. Subclasses must
  156. implement this functionality. Defaults to False.
  157. account_type: Account type used for authentication. Defaults to
  158. AUTH_ACCOUNT_TYPE.
  159. """
  160. self.host = host
  161. if (not self.host.startswith("http://") and
  162. not self.host.startswith("https://")):
  163. self.host = "http://" + self.host
  164. self.host_override = host_override
  165. self.auth_function = auth_function
  166. self.authenticated = False
  167. self.extra_headers = extra_headers
  168. self.save_cookies = save_cookies
  169. self.account_type = account_type
  170. self.opener = self._GetOpener()
  171. if self.host_override:
  172. logging.info("Server: %s; Host: %s", self.host, self.host_override)
  173. else:
  174. logging.info("Server: %s", self.host)
  175. def _GetOpener(self):
  176. """Returns an OpenerDirector for making HTTP requests.
  177. Returns:
  178. A urllib2.OpenerDirector object.
  179. """
  180. raise NotImplementedError()
  181. def _CreateRequest(self, url, data=None):
  182. """Creates a new urllib request."""
  183. logging.debug("Creating request for: '%s' with payload:\n%s", url, data)
  184. req = urllib2.Request(url, data=data, headers={"Accept": "text/plain"})
  185. if self.host_override:
  186. req.add_header("Host", self.host_override)
  187. for key, value in self.extra_headers.iteritems():
  188. req.add_header(key, value)
  189. return req
  190. def _GetAuthToken(self, email, password):
  191. """Uses ClientLogin to authenticate the user, returning an auth token.
  192. Args:
  193. email: The user's email address
  194. password: The user's password
  195. Raises:
  196. ClientLoginError: If there was an error authenticating with ClientLogin.
  197. HTTPError: If there was some other form of HTTP error.
  198. Returns:
  199. The authentication token returned by ClientLogin.
  200. """
  201. account_type = self.account_type
  202. if self.host.endswith(".google.com"):
  203. # Needed for use inside Google.
  204. account_type = "HOSTED"
  205. req = self._CreateRequest(
  206. url="https://www.google.com/accounts/ClientLogin",
  207. data=urllib.urlencode({
  208. "Email": email,
  209. "Passwd": password,
  210. "service": "ah",
  211. "source": "rietveld-codereview-upload",
  212. "accountType": account_type,
  213. }),
  214. )
  215. try:
  216. response = self.opener.open(req)
  217. response_body = response.read()
  218. response_dict = dict(x.split("=")
  219. for x in response_body.split("\n") if x)
  220. return response_dict["Auth"]
  221. except urllib2.HTTPError, e:
  222. if e.code == 403:
  223. body = e.read()
  224. response_dict = dict(x.split("=", 1) for x in body.split("\n") if x)
  225. raise ClientLoginError(req.get_full_url(), e.code, e.msg,
  226. e.headers, response_dict)
  227. else:
  228. raise
  229. def _GetAuthCookie(self, auth_token):
  230. """Fetches authentication cookies for an authentication token.
  231. Args:
  232. auth_token: The authentication token returned by ClientLogin.
  233. Raises:
  234. HTTPError: If there was an error fetching the authentication cookies.
  235. """
  236. # This is a dummy value to allow us to identify when we're successful.
  237. continue_location = "http://localhost/"
  238. args = {"continue": continue_location, "auth": auth_token}
  239. req = self._CreateRequest("%s/_ah/login?%s" %
  240. (self.host, urllib.urlencode(args)))
  241. try:
  242. response = self.opener.open(req)
  243. except urllib2.HTTPError, e:
  244. response = e
  245. if (response.code != 302 or
  246. response.info()["location"] != continue_location):
  247. raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg,
  248. response.headers, response.fp)
  249. self.authenticated = True
  250. def _Authenticate(self):
  251. """Authenticates the user.
  252. The authentication process works as follows:
  253. 1) We get a username and password from the user
  254. 2) We use ClientLogin to obtain an AUTH token for the user
  255. (see http://code.google.com/apis/accounts/AuthForInstalledApps.html).
  256. 3) We pass the auth token to /_ah/login on the server to obtain an
  257. authentication cookie. If login was successful, it tries to redirect
  258. us to the URL we provided.
  259. If we attempt to access the upload API without first obtaining an
  260. authentication cookie, it returns a 401 response (or a 302) and
  261. directs us to authenticate ourselves with ClientLogin.
  262. """
  263. for i in range(3):
  264. credentials = self.auth_function()
  265. try:
  266. auth_token = self._GetAuthToken(credentials[0], credentials[1])
  267. except ClientLoginError, e:
  268. print >>sys.stderr, ''
  269. if e.reason == "BadAuthentication":
  270. if e.info == "InvalidSecondFactor":
  271. print >>sys.stderr, (
  272. "Use an application-specific password instead "
  273. "of your regular account password.\n"
  274. "See http://www.google.com/"
  275. "support/accounts/bin/answer.py?answer=185833")
  276. else:
  277. print >>sys.stderr, "Invalid username or password."
  278. elif e.reason == "CaptchaRequired":
  279. print >>sys.stderr, (
  280. "Please go to\n"
  281. "https://www.google.com/accounts/DisplayUnlockCaptcha\n"
  282. "and verify you are a human. Then try again.\n"
  283. "If you are using a Google Apps account the URL is:\n"
  284. "https://www.google.com/a/yourdomain.com/UnlockCaptcha")
  285. elif e.reason == "NotVerified":
  286. print >>sys.stderr, "Account not verified."
  287. elif e.reason == "TermsNotAgreed":
  288. print >>sys.stderr, "User has not agreed to TOS."
  289. elif e.reason == "AccountDeleted":
  290. print >>sys.stderr, "The user account has been deleted."
  291. elif e.reason == "AccountDisabled":
  292. print >>sys.stderr, "The user account has been disabled."
  293. break
  294. elif e.reason == "ServiceDisabled":
  295. print >>sys.stderr, ("The user's access to the service has been "
  296. "disabled.")
  297. elif e.reason == "ServiceUnavailable":
  298. print >>sys.stderr, "The service is not available; try again later."
  299. else:
  300. # Unknown error.
  301. raise
  302. print >>sys.stderr, ''
  303. continue
  304. self._GetAuthCookie(auth_token)
  305. return
  306. def Send(self, request_path, payload=None,
  307. content_type="application/octet-stream",
  308. timeout=None,
  309. extra_headers=None,
  310. **kwargs):
  311. """Sends an RPC and returns the response.
  312. Args:
  313. request_path: The path to send the request to, eg /api/appversion/create.
  314. payload: The body of the request, or None to send an empty request.
  315. content_type: The Content-Type header to use.
  316. timeout: timeout in seconds; default None i.e. no timeout.
  317. (Note: for large requests on OS X, the timeout doesn't work right.)
  318. extra_headers: Dict containing additional HTTP headers that should be
  319. included in the request (string header names mapped to their values),
  320. or None to not include any additional headers.
  321. kwargs: Any keyword arguments are converted into query string parameters.
  322. Returns:
  323. The response body, as a string.
  324. """
  325. # TODO: Don't require authentication. Let the server say
  326. # whether it is necessary.
  327. if not self.authenticated:
  328. self._Authenticate()
  329. old_timeout = socket.getdefaulttimeout()
  330. socket.setdefaulttimeout(timeout)
  331. try:
  332. tries = 0
  333. while True:
  334. tries += 1
  335. args = dict(kwargs)
  336. url = "%s%s" % (self.host, request_path)
  337. if args:
  338. url += "?" + urllib.urlencode(args)
  339. req = self._CreateRequest(url=url, data=payload)
  340. req.add_header("Content-Type", content_type)
  341. if extra_headers:
  342. for header, value in extra_headers.items():
  343. req.add_header(header, value)
  344. try:
  345. f = self.opener.open(req)
  346. response = f.read()
  347. f.close()
  348. return response
  349. except urllib2.HTTPError, e:
  350. if tries > 3:
  351. raise
  352. elif e.code == 401 or e.code == 302:
  353. self._Authenticate()
  354. elif e.code == 301:
  355. # Handle permanent redirect manually.
  356. url = e.info()["location"]
  357. url_loc = urlparse.urlparse(url)
  358. self.host = '%s://%s' % (url_loc[0], url_loc[1])
  359. elif e.code >= 500:
  360. ErrorExit(e.read())
  361. else:
  362. raise
  363. finally:
  364. socket.setdefaulttimeout(old_timeout)
  365. class HttpRpcServer(AbstractRpcServer):
  366. """Provides a simplified RPC-style interface for HTTP requests."""
  367. def _Authenticate(self):
  368. """Save the cookie jar after authentication."""
  369. super(HttpRpcServer, self)._Authenticate()
  370. if self.save_cookies:
  371. StatusUpdate("Saving authentication cookies to %s" % self.cookie_file)
  372. self.cookie_jar.save()
  373. def _GetOpener(self):
  374. """Returns an OpenerDirector that supports cookies and ignores redirects.
  375. Returns:
  376. A urllib2.OpenerDirector object.
  377. """
  378. opener = urllib2.OpenerDirector()
  379. opener.add_handler(urllib2.ProxyHandler())
  380. opener.add_handler(urllib2.UnknownHandler())
  381. opener.add_handler(urllib2.HTTPHandler())
  382. opener.add_handler(urllib2.HTTPDefaultErrorHandler())
  383. opener.add_handler(urllib2.HTTPSHandler())
  384. opener.add_handler(urllib2.HTTPErrorProcessor())
  385. if self.save_cookies:
  386. self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies")
  387. self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file)
  388. if os.path.exists(self.cookie_file):
  389. try:
  390. self.cookie_jar.load()
  391. self.authenticated = True
  392. StatusUpdate("Loaded authentication cookies from %s" %
  393. self.cookie_file)
  394. except (cookielib.LoadError, IOError):
  395. # Failed to load cookies - just ignore them.
  396. pass
  397. else:
  398. # Create an empty cookie file with mode 600
  399. fd = os.open(self.cookie_file, os.O_CREAT, 0600)
  400. os.close(fd)
  401. # Always chmod the cookie file
  402. os.chmod(self.cookie_file, 0600)
  403. else:
  404. # Don't save cookies across runs of update.py.
  405. self.cookie_jar = cookielib.CookieJar()
  406. opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar))
  407. return opener
  408. class CondensedHelpFormatter(optparse.IndentedHelpFormatter):
  409. """Frees more horizontal space by removing indentation from group
  410. options and collapsing arguments between short and long, e.g.
  411. '-o ARG, --opt=ARG' to -o --opt ARG"""
  412. def format_heading(self, heading):
  413. return "%s:\n" % heading
  414. def format_option(self, option):
  415. self.dedent()
  416. res = optparse.HelpFormatter.format_option(self, option)
  417. self.indent()
  418. return res
  419. def format_option_strings(self, option):
  420. self.set_long_opt_delimiter(" ")
  421. optstr = optparse.HelpFormatter.format_option_strings(self, option)
  422. optlist = optstr.split(", ")
  423. if len(optlist) > 1:
  424. if option.takes_value():
  425. # strip METAVAR from all but the last option
  426. optlist = [x.split()[0] for x in optlist[:-1]] + optlist[-1:]
  427. optstr = " ".join(optlist)
  428. return optstr
  429. parser = optparse.OptionParser(
  430. usage="%prog [options] [-- diff_options] [path...]",
  431. add_help_option=False,
  432. formatter=CondensedHelpFormatter()
  433. )
  434. parser.add_option("-h", "--help", action="store_true",
  435. help="Show this help message and exit.")
  436. parser.add_option("-y", "--assume_yes", action="store_true",
  437. dest="assume_yes", default=False,
  438. help="Assume that the answer to yes/no questions is 'yes'.")
  439. # Logging
  440. group = parser.add_option_group("Logging options")
  441. group.add_option("-q", "--quiet", action="store_const", const=0,
  442. dest="verbose", help="Print errors only.")
  443. group.add_option("-v", "--verbose", action="store_const", const=2,
  444. dest="verbose", default=1,
  445. help="Print info level logs.")
  446. group.add_option("--noisy", action="store_const", const=3,
  447. dest="verbose", help="Print all logs.")
  448. group.add_option("--print_diffs", dest="print_diffs", action="store_true",
  449. help="Print full diffs.")
  450. # Review server
  451. group = parser.add_option_group("Review server options")
  452. group.add_option("-s", "--server", action="store", dest="server",
  453. default=DEFAULT_REVIEW_SERVER,
  454. metavar="SERVER",
  455. help=("The server to upload to. The format is host[:port]. "
  456. "Defaults to '%default'."))
  457. group.add_option("-e", "--email", action="store", dest="email",
  458. metavar="EMAIL", default=None,
  459. help="The username to use. Will prompt if omitted.")
  460. group.add_option("-H", "--host", action="store", dest="host",
  461. metavar="HOST", default=None,
  462. help="Overrides the Host header sent with all RPCs.")
  463. group.add_option("--no_cookies", action="store_false",
  464. dest="save_cookies", default=True,
  465. help="Do not save authentication cookies to local disk.")
  466. group.add_option("--account_type", action="store", dest="account_type",
  467. metavar="TYPE", default=AUTH_ACCOUNT_TYPE,
  468. choices=["GOOGLE", "HOSTED"],
  469. help=("Override the default account type "
  470. "(defaults to '%default', "
  471. "valid choices are 'GOOGLE' and 'HOSTED')."))
  472. # Issue
  473. group = parser.add_option_group("Issue options")
  474. group.add_option("-t", "--title", action="store", dest="title",
  475. help="New issue subject or new patch set title")
  476. group.add_option("-m", "--message", action="store", dest="message",
  477. default=None,
  478. help="New issue description or new patch set message")
  479. group.add_option("-F", "--file", action="store", dest="file",
  480. default=None, help="Read the message above from file.")
  481. group.add_option("-r", "--reviewers", action="store", dest="reviewers",
  482. metavar="REVIEWERS", default=None,
  483. help="Add reviewers (comma separated email addresses).")
  484. group.add_option("--cc", action="store", dest="cc",
  485. metavar="CC", default=None,
  486. help="Add CC (comma separated email addresses).")
  487. group.add_option("--private", action="store_true", dest="private",
  488. default=False,
  489. help="Make the issue restricted to reviewers and those CCed")
  490. # Upload options
  491. group = parser.add_option_group("Patch options")
  492. group.add_option("-i", "--issue", type="int", action="store",
  493. metavar="ISSUE", default=None,
  494. help="Issue number to which to add. Defaults to new issue.")
  495. group.add_option("--base_url", action="store", dest="base_url", default=None,
  496. help="Base URL path for files (listed as \"Base URL\" when "
  497. "viewing issue). If omitted, will be guessed automatically "
  498. "for SVN repos and left blank for others.")
  499. group.add_option("--download_base", action="store_true",
  500. dest="download_base", default=False,
  501. help="Base files will be downloaded by the server "
  502. "(side-by-side diffs may not work on files with CRs).")
  503. group.add_option("--rev", action="store", dest="revision",
  504. metavar="REV", default=None,
  505. help="Base revision/branch/tree to diff against. Use "
  506. "rev1:rev2 range to review already committed changeset.")
  507. group.add_option("--send_mail", action="store_true",
  508. dest="send_mail", default=False,
  509. help="Send notification email to reviewers.")
  510. group.add_option("-p", "--send_patch", action="store_true",
  511. dest="send_patch", default=False,
  512. help="Same as --send_mail, but include diff as an "
  513. "attachment, and prepend email subject with 'PATCH:'.")
  514. group.add_option("--vcs", action="store", dest="vcs",
  515. metavar="VCS", default=None,
  516. help=("Version control system (optional, usually upload.py "
  517. "already guesses the right VCS)."))
  518. group.add_option("--emulate_svn_auto_props", action="store_true",
  519. dest="emulate_svn_auto_props", default=False,
  520. help=("Emulate Subversion's auto properties feature."))
  521. # Perforce-specific
  522. group = parser.add_option_group("Perforce-specific options "
  523. "(overrides P4 environment variables)")
  524. group.add_option("--p4_port", action="store", dest="p4_port",
  525. metavar="P4_PORT", default=None,
  526. help=("Perforce server and port (optional)"))
  527. group.add_option("--p4_changelist", action="store", dest="p4_changelist",
  528. metavar="P4_CHANGELIST", default=None,
  529. help=("Perforce changelist id"))
  530. group.add_option("--p4_client", action="store", dest="p4_client",
  531. metavar="P4_CLIENT", default=None,
  532. help=("Perforce client/workspace"))
  533. group.add_option("--p4_user", action="store", dest="p4_user",
  534. metavar="P4_USER", default=None,
  535. help=("Perforce user"))
  536. def GetRpcServer(server, email=None, host_override=None, save_cookies=True,
  537. account_type=AUTH_ACCOUNT_TYPE):
  538. """Returns an instance of an AbstractRpcServer.
  539. Args:
  540. server: String containing the review server URL.
  541. email: String containing user's email address.
  542. host_override: If not None, string containing an alternate hostname to use
  543. in the host header.
  544. save_cookies: Whether authentication cookies should be saved to disk.
  545. account_type: Account type for authentication, either 'GOOGLE'
  546. or 'HOSTED'. Defaults to AUTH_ACCOUNT_TYPE.
  547. Returns:
  548. A new AbstractRpcServer, on which RPC calls can be made.
  549. """
  550. rpc_server_class = HttpRpcServer
  551. # If this is the dev_appserver, use fake authentication.
  552. host = (host_override or server).lower()
  553. if re.match(r'(http://)?localhost([:/]|$)', host):
  554. if email is None:
  555. email = "test@example.com"
  556. logging.info("Using debug user %s. Override with --email" % email)
  557. server = rpc_server_class(
  558. server,
  559. lambda: (email, "password"),
  560. host_override=host_override,
  561. extra_headers={"Cookie":
  562. 'dev_appserver_login="%s:False"' % email},
  563. save_cookies=save_cookies,
  564. account_type=account_type)
  565. # Don't try to talk to ClientLogin.
  566. server.authenticated = True
  567. return server
  568. def GetUserCredentials():
  569. """Prompts the user for a username and password."""
  570. # Create a local alias to the email variable to avoid Python's crazy
  571. # scoping rules.
  572. global keyring
  573. local_email = email
  574. if local_email is None:
  575. local_email = GetEmail("Email (login for uploading to %s)" % server)
  576. password = None
  577. if keyring:
  578. try:
  579. password = keyring.get_password(host, local_email)
  580. except:
  581. # Sadly, we have to trap all errors here as
  582. # gnomekeyring.IOError inherits from object. :/
  583. print "Failed to get password from keyring"
  584. keyring = None
  585. if password is not None:
  586. print "Using password from system keyring."
  587. else:
  588. password = getpass.getpass("Password for %s: " % local_email)
  589. if keyring:
  590. answer = raw_input("Store password in system keyring?(y/N) ").strip()
  591. if answer == "y":
  592. keyring.set_password(host, local_email, password)
  593. return (local_email, password)
  594. return rpc_server_class(server,
  595. GetUserCredentials,
  596. host_override=host_override,
  597. save_cookies=save_cookies)
  598. def EncodeMultipartFormData(fields, files):
  599. """Encode form fields for multipart/form-data.
  600. Args:
  601. fields: A sequence of (name, value) elements for regular form fields.
  602. files: A sequence of (name, filename, value) elements for data to be
  603. uploaded as files.
  604. Returns:
  605. (content_type, body) ready for httplib.HTTP instance.
  606. Source:
  607. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
  608. """
  609. BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-'
  610. CRLF = '\r\n'
  611. lines = []
  612. for (key, value) in fields:
  613. lines.append('--' + BOUNDARY)
  614. lines.append('Content-Disposition: form-data; name="%s"' % key)
  615. lines.append('')
  616. if isinstance(value, unicode):
  617. value = value.encode('utf-8')
  618. lines.append(value)
  619. for (key, filename, value) in files:
  620. lines.append('--' + BOUNDARY)
  621. lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' %
  622. (key, filename))
  623. lines.append('Content-Type: %s' % GetContentType(filename))
  624. lines.append('')
  625. if isinstance(value, unicode):
  626. value = value.encode('utf-8')
  627. lines.append(value)
  628. lines.append('--' + BOUNDARY + '--')
  629. lines.append('')
  630. body = CRLF.join(lines)
  631. content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
  632. return content_type, body
  633. def GetContentType(filename):
  634. """Helper to guess the content-type from the filename."""
  635. return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
  636. # Use a shell for subcommands on Windows to get a PATH search.
  637. use_shell = sys.platform.startswith("win")
  638. def RunShellWithReturnCodeAndStderr(command, print_output=False,
  639. universal_newlines=True,
  640. env=os.environ):
  641. """Executes a command and returns the output from stdout, stderr and the return code.
  642. Args:
  643. command: Command to execute.
  644. print_output: If True, the output is printed to stdout.
  645. If False, both stdout and stderr are ignored.
  646. universal_newlines: Use universal_newlines flag (default: True).
  647. Returns:
  648. Tuple (stdout, stderr, return code)
  649. """
  650. logging.info("Running %s", command)
  651. env = env.copy()
  652. env['LC_MESSAGES'] = 'C'
  653. p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  654. shell=use_shell, universal_newlines=universal_newlines,
  655. env=env)
  656. if print_output:
  657. output_array = []
  658. while True:
  659. line = p.stdout.readline()
  660. if not line:
  661. break
  662. print line.strip("\n")
  663. output_array.append(line)
  664. output = "".join(output_array)
  665. else:
  666. output = p.stdout.read()
  667. p.wait()
  668. errout = p.stderr.read()
  669. if print_output and errout:
  670. print >>sys.stderr, errout
  671. p.stdout.close()
  672. p.stderr.close()
  673. return output, errout, p.returncode
  674. def RunShellWithReturnCode(command, print_output=False,
  675. universal_newlines=True,
  676. env=os.environ):
  677. """Executes a command and returns the output from stdout and the return code."""
  678. out, err, retcode = RunShellWithReturnCodeAndStderr(command, print_output,
  679. universal_newlines, env)
  680. return out, retcode
  681. def RunShell(command, silent_ok=False, universal_newlines=True,
  682. print_output=False, env=os.environ):
  683. data, retcode = RunShellWithReturnCode(command, print_output,
  684. universal_newlines, env)
  685. if retcode:
  686. ErrorExit("Got error status from %s:\n%s" % (command, data))
  687. if not silent_ok and not data:
  688. ErrorExit("No output from %s" % command)
  689. return data
  690. class VersionControlSystem(object):
  691. """Abstract base class providing an interface to the VCS."""
  692. def __init__(self, options):
  693. """Constructor.
  694. Args:
  695. options: Command line options.
  696. """
  697. self.options = options
  698. def GetGUID(self):
  699. """Return string to distinguish the repository from others, for example to
  700. query all opened review issues for it"""
  701. raise NotImplementedError(
  702. "abstract method -- subclass %s must override" % self.__class__)
  703. def PostProcessDiff(self, diff):
  704. """Return the diff with any special post processing this VCS needs, e.g.
  705. to include an svn-style "Index:"."""
  706. return diff
  707. def GenerateDiff(self, args):
  708. """Return the current diff as a string.
  709. Args:
  710. args: Extra arguments to pass to the diff command.
  711. """
  712. raise NotImplementedError(
  713. "abstract method -- subclass %s must override" % self.__class__)
  714. def GetUnknownFiles(self):
  715. """Return a list of files unknown to the VCS."""
  716. raise NotImplementedError(
  717. "abstract method -- subclass %s must override" % self.__class__)
  718. def CheckForUnknownFiles(self):
  719. """Show an "are you sure?" prompt if there are unknown files."""
  720. unknown_files = self.GetUnknownFiles()
  721. if unknown_files:
  722. print "The following files are not added to version control:"
  723. for line in unknown_files:
  724. print line
  725. prompt = "Are you sure to continue?(y/N) "
  726. answer = raw_input(prompt).strip()
  727. if answer != "y":
  728. ErrorExit("User aborted")
  729. def GetBaseFile(self, filename):
  730. """Get the content of the upstream version of a file.
  731. Returns:
  732. A tuple (base_content, new_content, is_binary, status)
  733. base_content: The contents of the base file.
  734. new_content: For text files, this is empty. For binary files, this is
  735. the contents of the new file, since the diff output won't contain
  736. information to reconstruct the current file.
  737. is_binary: True iff the file is binary.
  738. status: The status of the file.
  739. """
  740. raise NotImplementedError(
  741. "abstract method -- subclass %s must override" % self.__class__)
  742. def GetBaseFiles(self, diff):
  743. """Helper that calls GetBase file for each file in the patch.
  744. Returns:
  745. A dictionary that maps from filename to GetBaseFile's tuple. Filenames
  746. are retrieved based on lines that start with "Index:" or
  747. "Property changes on:".
  748. """
  749. files = {}
  750. for line in diff.splitlines(True):
  751. if line.startswith('Index:') or line.startswith('Property changes on:'):
  752. unused, filename = line.split(':', 1)
  753. # On Windows if a file has property changes its filename uses '\'
  754. # instead of '/'.
  755. filename = filename.strip().replace('\\', '/')
  756. files[filename] = self.GetBaseFile(filename)
  757. return files
  758. def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options,
  759. files):
  760. """Uploads the base files (and if necessary, the current ones as well)."""
  761. def UploadFile(filename, file_id, content, is_binary, status, is_base):
  762. """Uploads a file to the server."""
  763. file_too_large = False
  764. if is_base:
  765. type = "base"
  766. else:
  767. type = "current"
  768. if len(content) > MAX_UPLOAD_SIZE:
  769. print ("Not uploading the %s file for %s because it's too large." %
  770. (type, filename))
  771. file_too_large = True
  772. content = ""
  773. checksum = md5(content).hexdigest()
  774. if options.verbose > 0 and not file_too_large:
  775. print "Uploading %s file for %s" % (type, filename)
  776. url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id)
  777. form_fields = [("filename", filename),
  778. ("status", status),
  779. ("checksum", checksum),
  780. ("is_binary", str(is_binary)),
  781. ("is_current", str(not is_base)),
  782. ]
  783. if file_too_large:
  784. form_fields.append(("file_too_large", "1"))
  785. if options.email:
  786. form_fields.append(("user", options.email))
  787. ctype, body = EncodeMultipartFormData(form_fields,
  788. [("data", filename, content)])
  789. response_body = rpc_server.Send(url, body,
  790. content_type=ctype)
  791. if not response_body.startswith("OK"):
  792. StatusUpdate(" --> %s" % response_body)
  793. sys.exit(1)
  794. patches = dict()
  795. [patches.setdefault(v, k) for k, v in patch_list]
  796. for filename in patches.keys():
  797. base_content, new_content, is_binary, status = files[filename]
  798. file_id_str = patches.get(filename)
  799. if file_id_str.find("nobase") != -1:
  800. base_content = None
  801. file_id_str = file_id_str[file_id_str.rfind("_") + 1:]
  802. file_id = int(file_id_str)
  803. if base_content != None:
  804. UploadFile(filename, file_id, base_content, is_binary, status, True)
  805. if new_content != None:
  806. UploadFile(filename, file_id, new_content, is_binary, status, False)
  807. def IsImage(self, filename):
  808. """Returns true if the filename has an image extension."""
  809. mimetype = mimetypes.guess_type(filename)[0]
  810. if not mimetype:
  811. return False
  812. return mimetype.startswith("image/")
  813. def IsBinaryData(self, data):
  814. """Returns true if data contains a null byte."""
  815. # Derived from how Mercurial's heuristic, see
  816. # http://selenic.com/hg/file/848a6658069e/mercurial/util.py#l229
  817. return bool(data and "\0" in data)
  818. class SubversionVCS(VersionControlSystem):
  819. """Implementation of the VersionControlSystem interface for Subversion."""
  820. def __init__(self, options):
  821. super(SubversionVCS, self).__init__(options)
  822. if self.options.revision:
  823. match = re.match(r"(\d+)(:(\d+))?", self.options.revision)
  824. if not match:
  825. ErrorExit("Invalid Subversion revision %s." % self.options.revision)
  826. self.rev_start = match.group(1)
  827. self.rev_end = match.group(3)
  828. else:
  829. self.rev_start = self.rev_end = None
  830. # Cache output from "svn list -r REVNO dirname".
  831. # Keys: dirname, Values: 2-tuple (ouput for start rev and end rev).
  832. self.svnls_cache = {}
  833. # Base URL is required to fetch files deleted in an older revision.
  834. # Result is cached to not guess it over and over again in GetBaseFile().
  835. required = self.options.download_base or self.options.revision is not None
  836. self.svn_base = self._GuessBase(required)
  837. def GetGUID(self):
  838. return self._GetInfo("Repository UUID")
  839. def GuessBase(self, required):
  840. """Wrapper for _GuessBase."""
  841. return self.svn_base
  842. def _GuessBase(self, required):
  843. """Returns base URL for current diff.
  844. Args:
  845. required: If true, exits if the url can't be guessed, otherwise None is
  846. returned.
  847. """
  848. url = self._GetInfo("URL")
  849. if url:
  850. scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)
  851. guess = ""
  852. # TODO(anatoli) - repository specific hacks should be handled by server
  853. if netloc == "svn.python.org" and scheme == "svn+ssh":
  854. path = "projects" + path
  855. scheme = "http"
  856. guess = "Python "
  857. elif netloc.endswith(".googlecode.com"):
  858. scheme = "http"
  859. guess = "Google Code "
  860. path = path + "/"
  861. base = urlparse.urlunparse((scheme, netloc, path, params,
  862. query, fragment))
  863. logging.info("Guessed %sbase = %s", guess, base)
  864. return base
  865. if required:
  866. ErrorExit("Can't find URL in output from svn info")
  867. return None
  868. def _GetInfo(self, key):
  869. """Parses 'svn info' for current dir. Returns value for key or None"""
  870. for line in RunShell(["svn", "info"]).splitlines():
  871. if line.startswith(key + ": "):
  872. return line.split(":", 1)[1].strip()
  873. def _EscapeFilename(self, filename):
  874. """Escapes filename for SVN commands."""
  875. if "@" in filename and not filename.endswith("@"):
  876. filename = "%s@" % filename
  877. return filename
  878. def GenerateDiff(self, args):
  879. cmd = ["svn", "diff"]
  880. if self.options.revision:
  881. cmd += ["-r", self.options.revision]
  882. cmd.extend(args)
  883. data = RunShell(cmd)
  884. count = 0
  885. for line in data.splitlines():
  886. if line.startswith("Index:") or line.startswith("Property changes on:"):
  887. count += 1
  888. logging.info(line)
  889. if not count:
  890. ErrorExit("No valid patches found in output from svn diff")
  891. return data
  892. def _CollapseKeywords(self, content, keyword_str):
  893. """Collapses SVN keywords."""
  894. # svn cat translates keywords but svn diff doesn't. As a result of this
  895. # behavior patching.PatchChunks() fails with a chunk mismatch error.
  896. # This part was originally written by the Review Board development team
  897. # who had the same problem (http://reviews.review-board.org/r/276/).
  898. # Mapping of keywords to known aliases
  899. svn_keywords = {
  900. # Standard keywords
  901. 'Date': ['Date', 'LastChangedDate'],
  902. 'Revision': ['Revision', 'LastChangedRevision', 'Rev'],
  903. 'Author': ['Author', 'LastChangedBy'],
  904. 'HeadURL': ['HeadURL', 'URL'],
  905. 'Id': ['Id'],
  906. # Aliases
  907. 'LastChangedDate': ['LastChangedDate', 'Date'],
  908. 'LastChangedRevision': ['LastChangedRevision', 'Rev', 'Revision'],
  909. 'LastChangedBy': ['LastChangedBy', 'Author'],
  910. 'URL': ['URL', 'HeadURL'],
  911. }
  912. def repl(m):
  913. if m.group(2):
  914. return "$%s::%s$" % (m.group(1), " " * len(m.group(3)))
  915. return "$%s$" % m.group(1)
  916. keywords = [keyword
  917. for name in keyword_str.split(" ")
  918. for keyword in svn_keywords.get(name, [])]
  919. return re.sub(r"\$(%s):(:?)([^\$]+)\$" % '|'.join(keywords), repl, content)
  920. def GetUnknownFiles(self):
  921. status = RunShell(["svn", "status", "--ignore-externals"], silent_ok=True)
  922. unknown_files = []
  923. for line in status.split("\n"):
  924. if line and line[0] == "?":
  925. unknown_files.append(line)
  926. return unknown_files
  927. def ReadFile(self, filename):
  928. """Returns the contents of a file."""
  929. file = open(filename, 'rb')
  930. result = ""
  931. try:
  932. result = file.read()
  933. finally:
  934. file.close()
  935. return result
  936. def GetStatus(self, filename):
  937. """Returns the status of a file."""
  938. if not self.options.revision:
  939. status = RunShell(["svn", "status", "--ignore-externals",
  940. self._EscapeFilename(filename)])
  941. if not status:
  942. ErrorExit("svn status returned no output for %s" % filename)
  943. status_lines = status.splitlines()
  944. # If file is in a cl, the output will begin with
  945. # "\n--- Changelist 'cl_name':\n". See
  946. # http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt
  947. if (len(status_lines) == 3 and
  948. not status_lines[0] and
  949. status_lines[1].startswith("--- Changelist")):
  950. status = status_lines[2]
  951. else:
  952. status = status_lines[0]
  953. # If we have a revision to diff against we need to run "svn list"
  954. # for the old and the new revision and compare the results to get
  955. # the correct status for a file.
  956. else:
  957. dirname, relfilename = os.path.split(filename)
  958. if dirname not in self.svnls_cache:
  959. cmd = ["svn", "list", "-r", self.rev_start,
  960. self._EscapeFilename(dirname) or "."]
  961. out, err, returncode = RunShellWithReturnCodeAndStderr(cmd)
  962. if returncode:
  963. # Directory might not yet exist at start revison
  964. # svn: Unable to find repository location for 'abc' in revision nnn
  965. if re.match('^svn: Unable to find repository location for .+ in revision \d+', err):
  966. old_files = ()
  967. else:
  968. ErrorExit("Failed to get status for %s:\n%s" % (filename, err))
  969. else:
  970. old_files = out.splitlines()
  971. args = ["svn", "list"]
  972. if self.rev_end:
  973. args += ["-r", self.rev_end]
  974. cmd = args + [self._EscapeFilename(dirname) or "."]
  975. out, returncode = RunShellWithReturnCode(cmd)
  976. if returncode:
  977. ErrorExit("Failed to run command %s" % cmd)
  978. self.svnls_cache[dirname] = (old_files, out.splitlines())
  979. old_files, new_files = self.svnls_cache[dirname]
  980. if relfilename in old_files and relfilename not in new_files:
  981. status = "D "
  982. elif relfilename in old_files and relfilename in new_files:
  983. status = "M "
  984. else:
  985. status = "A "
  986. return status
  987. def GetBaseFile(self, filename):
  988. status = self.GetStatus(filename)
  989. base_content = None
  990. new_content = None
  991. # If a file is copied its status will be "A +", which signifies
  992. # "addition-with-history". See "svn st" for more information. We need to
  993. # upload the original file or else diff parsing will fail if the file was
  994. # edited.
  995. if status[0] == "A" and status[3] != "+":
  996. # We'll need to upload the new content if we're adding a binary file
  997. # since diff's output won't contain it.
  998. mimetype = RunShell(["svn", "propget", "svn:mime-type",
  999. self._EscapeFilename(filename)], silent_ok=True)
  1000. base_content = ""
  1001. is_binary = bool(mimetype) and not mimetype.startswith("text/")
  1002. if is_binary and self.IsImage(filename):
  1003. new_content = self.ReadFile(filename)
  1004. elif (status[0] in ("M", "D", "R") or
  1005. (status[0] == "A" and status[3] == "+") or # Copied file.
  1006. (status[0] == " " and status[1] == "M")): # Property change.
  1007. args = []
  1008. if self.options.revision:
  1009. # filename must not be escaped. We already add an ampersand here.
  1010. url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
  1011. else:
  1012. # Don't change filename, it's needed later.
  1013. url = filename
  1014. args += ["-r", "BASE"]
  1015. cmd = ["svn"] + args + ["propget", "svn:mime-type", url]
  1016. mimetype, returncode = RunShellWithReturnCode(cmd)
  1017. if returncode:
  1018. # File does not exist in the requested revision.
  1019. # Reset mimetype, it contains an error message.
  1020. mimetype = ""
  1021. else:
  1022. mimetype = mimetype.strip()
  1023. get_base = False
  1024. # this test for binary is exactly the test prescribed by the
  1025. # official SVN docs at
  1026. # http://subversion.apache.org/faq.html#binary-files
  1027. is_binary = (bool(mimetype) and
  1028. not mimetype.startswith("text/") and
  1029. mimetype not in ("image/x-xbitmap", "image/x-xpixmap"))
  1030. if status[0] == " ":
  1031. # Empty base content just to force an upload.
  1032. base_content = ""
  1033. elif is_binary:
  1034. if self.IsImage(filename):
  1035. get_base = True
  1036. if status[0] == "M":
  1037. if not self.rev_end:
  1038. new_content = self.ReadFile(filename)
  1039. else:
  1040. url = "%s/%s@%s" % (self.svn_base, filename, self.rev_end)
  1041. new_content = RunShell(["svn", "cat", url],
  1042. universal_newlines=True, silent_ok=True)
  1043. else:
  1044. base_content = ""
  1045. else:
  1046. get_base = True
  1047. if get_base:
  1048. if is_binary:
  1049. universal_newlines = False
  1050. else:
  1051. universal_newlines = True
  1052. if self.rev_start:
  1053. # "svn cat -r REV delete_file.txt" doesn't work. cat requires
  1054. # the full URL with "@REV" appended instead of using "-r" option.
  1055. url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
  1056. base_content = RunShell(["svn", "cat", url],
  1057. universal_newlines=universal_newlines,
  1058. silent_ok=True)
  1059. else:
  1060. base_content, ret_code = RunShellWithReturnCode(
  1061. ["svn", "cat", self._EscapeFilename(filename)],
  1062. universal_newlines=universal_newlines)
  1063. if ret_code and status[0] == "R":
  1064. # It's a replaced file without local history (see issue208).
  1065. # The base file needs to be fetched from the server.
  1066. url = "%s/%s" % (self.svn_base, filename)
  1067. base_content = RunShell(["svn", "cat", url],
  1068. universal_newlines=universal_newlines,
  1069. silent_ok=True)
  1070. elif ret_code:
  1071. ErrorExit("Got error status from 'svn cat %s'" % filename)
  1072. if not is_binary:
  1073. args = []
  1074. if self.rev_start:
  1075. url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start)
  1076. else:
  1077. url = filename
  1078. args += ["-r", "BASE"]
  1079. cmd = ["svn"] + args + ["propget", "svn:keywords", url]
  1080. keywords, returncode = RunShellWithReturnCode(cmd)
  1081. if keywords and not returncode:
  1082. base_content = self._CollapseKeywords(base_content, keywords)
  1083. else:
  1084. StatusUpdate("svn status returned unexpected output: %s" % status)
  1085. sys.exit(1)
  1086. return base_content, new_content, is_binary, status[0:5]
  1087. class GitVCS(VersionControlSystem):
  1088. """Implementation of the VersionControlSystem interface for Git."""
  1089. def __init__(self, options):
  1090. super(GitVCS, self).__init__(options)
  1091. # Map of filename -> (hash before, hash after) of base file.
  1092. # Hashes for "no such file" are represented as None.
  1093. self.hashes = {}
  1094. # Map of new filename -> old filename for renames.
  1095. self.renames = {}
  1096. def GetGUID(self):
  1097. revlist = RunShell("git rev-list --parents HEAD".split()).splitlines()
  1098. # M-A: Return the 1st root hash, there could be multiple when a
  1099. # subtree is merged. In that case, more analysis would need to
  1100. # be done to figure out which HEAD is the 'most representative'.
  1101. for r in revlist:
  1102. if ' ' not in r:
  1103. return r
  1104. def PostProcessDiff(self, gitdiff):
  1105. """Converts the diff output to include an svn-style "Index:" line as well
  1106. as record the hashes of the files, so we can upload them along with our
  1107. diff."""
  1108. # Special used by git to indicate "no such content".
  1109. NULL_HASH = "0"*40
  1110. def IsFileNew(filename):
  1111. return filename in self.hashes and self.hashes[filename][0] is None
  1112. def AddSubversionPropertyChange(filename):
  1113. """Add svn's property change information into the patch if given file is
  1114. new file.
  1115. We use Subversion's auto-props setting to retrieve its property.
  1116. See http://svnbook.red-bean.com/en/1.1/ch07.html#svn-ch-7-sect-1.3.2 for
  1117. Subversion's [auto-props] setting.
  1118. """
  1119. if self.options.emulate_svn_auto_props and IsFileNew(filename):
  1120. svnprops = GetSubversionPropertyChanges(filename)
  1121. if svnprops:
  1122. svndiff.append("\n" + svnprops + "\n")
  1123. svndiff = []
  1124. filecount = 0
  1125. filename = None
  1126. for line in gitdiff.splitlines():
  1127. match = re.match(r"diff --git a/(.*) b/(.*)$", line)
  1128. if match:
  1129. # Add auto property here for previously seen file.
  1130. if filename is not None:
  1131. AddSubversionPropertyChange(filename)
  1132. filecount += 1
  1133. # Intentionally use the "after" filename so we can show renames.
  1134. filename = match.group(2)
  1135. svndiff.append("Index: %s\n" % filename)
  1136. if match.group(1) != match.group(2):
  1137. self.renames[match.group(2)] = match.group(1)
  1138. else:
  1139. # The "index" line in a git diff looks like this (long hashes elided):
  1140. # index 82c0d44..b2cee3f 100755
  1141. # We want to save the left hash, as that identifies the base file.
  1142. match = re.match(r"index (\w+)\.\.(\w+)", line)
  1143. if match:
  1144. before, after = (match.group(1), match.group(2))
  1145. if before == NULL_HASH:
  1146. before = None
  1147. if after == NULL_HASH:
  1148. after = None
  1149. self.hashes[filename] = (before, after)
  1150. svndiff.append(line + "\n")
  1151. if not filecount:
  1152. ErrorExit("No valid patches found in output from git diff")
  1153. # Add auto property for the last seen file.
  1154. assert filename is not None
  1155. AddSubversionPropertyChange(filename)
  1156. return "".join(svndiff)
  1157. def GenerateDiff(self, extra_args):
  1158. extra_args = extra_args[:]
  1159. if self.options.revision:
  1160. if ":" in self.options.revision:
  1161. extra_args = self.options.revision.split(":", 1) + extra_args
  1162. else:
  1163. extra_args = [self.options.revision] + extra_args
  1164. # --no-ext-diff is broken in some versions of Git, so try to work around
  1165. # this by overriding the environment (but there is still a problem if the
  1166. # git config key "diff.external" is used).
  1167. env = os.environ.copy()
  1168. if 'GIT_EXTERNAL_DIFF' in env: del env['GIT_EXTERNAL_DIFF']
  1169. return RunShell(
  1170. [ "git", "diff", "--no-color", "--no-ext-diff", "--full-index",
  1171. "--ignore-submodules", "-M"] + extra_args,
  1172. env=env)
  1173. def GetUnknownFiles(self):
  1174. status = RunShell(["git", "ls-files", "--exclude-standard", "--others"],
  1175. silent_ok=True)
  1176. return status.splitlines()
  1177. def GetFileContent(self, file_hash, is_binary):
  1178. """Returns the content of a file identified by its git hash."""
  1179. data, retcode = RunShellWithReturnCode(["git", "show", file_hash],
  1180. universal_newlines=not is_binary)
  1181. if retcode:
  1182. ErrorExit("Got error status from 'git show %s'" % file_hash)
  1183. return data
  1184. def GetBaseFile(self, filename):
  1185. hash_before, hash_after = self.hashes.get(filename, (None,None))
  1186. base_content = None
  1187. new_content = None
  1188. status = None
  1189. if filename in self.renames:
  1190. status = "A +" # Match svn attribute name for renames.
  1191. if filename not in self.hashes:
  1192. # If a rename doesn't change the content, we never get a hash.
  1193. base_content = RunShell(
  1194. ["git", "show", "HEAD:" + filename], silent_ok=True)
  1195. elif not hash_before:
  1196. status = "A"
  1197. base_content = ""
  1198. elif not hash_after:
  1199. status = "D"
  1200. else:
  1201. status = "M"
  1202. is_binary = self.IsBinaryData(base_content)
  1203. is_image = self.IsImage(filename)
  1204. # Grab the before/after content if we need it.
  1205. # We should include file contents if it's text or it's an image.
  1206. if not is_binary or is_image:
  1207. # Grab the base content if we don't have it already.
  1208. if base_content is None and hash_before:
  1209. base_content = self.GetFileContent(hash_before, is_binary)
  1210. # Only include the "after" file if it's an image; otherwise it
  1211. # it is reconstructed from the diff.
  1212. if is_image and hash_after:
  1213. new_content = self.GetFileContent(hash_after, is_binary)
  1214. return (base_content, new_content, is_binary, status)
  1215. class CVSVCS(VersionControlSystem):
  1216. """Implementation of the VersionControlSystem interface for CVS."""
  1217. def __init__(self, options):
  1218. super(CVSVCS, self).__init__(options)
  1219. def GetGUID(self):
  1220. """For now we don't know how to get repository ID for CVS"""
  1221. return
  1222. def GetOriginalContent_(self, filename):
  1223. RunShell(["cvs", "up", filename], silent_ok=True)
  1224. # TODO need detect file content encoding
  1225. content = open(filename).read()
  1226. return content.replace("\r\n", "\n")
  1227. def GetBaseFile(self, filename):
  1228. base_content = None
  1229. new_content = None
  1230. status = "A"
  1231. output, retcode = RunShellWithReturnCode(["cvs", "status", filename])
  1232. if retcode:
  1233. ErrorExit("Got error status from 'cvs status %s'" % filename)
  1234. if output.find("Status: Locally Modified") != -1:
  1235. status = "M"
  1236. temp_filename = "%s.tmp123" % filename
  1237. os.rename(filename, temp_filename)
  1238. base_content = self.GetOriginalContent_(filename)
  1239. os.rename(temp_filename, filename)
  1240. elif output.find("Status: Locally Added"):
  1241. status = "A"
  1242. base_content = ""
  1243. elif output.find("Status: Needs Checkout"):
  1244. status = "D"
  1245. base_content = self.GetOriginalContent_(filename)
  1246. return (base_content, new_content, self.IsBinaryData(base_content), status)
  1247. def GenerateDiff(self, extra_args):
  1248. cmd = ["cvs", "diff", "-u", "-N"]
  1249. if self.options.revision:
  1250. cmd += ["-r", self.options.revision]
  1251. cmd.extend(extra_args)
  1252. data, retcode = RunShellWithReturnCode(cmd)
  1253. count = 0
  1254. if retcode in [0, 1]:
  1255. for line in data.splitlines():
  1256. if line.startswith("Index:"):
  1257. count += 1
  1258. logging.info(line)
  1259. if not count:
  1260. ErrorExit("No valid patches found in output from cvs diff")
  1261. return data
  1262. def GetUnknownFiles(self):
  1263. data, retcode = RunShellWithReturnCode(["cvs", "diff"])
  1264. if retcode not in [0, 1]:
  1265. ErrorExit("Got error status from 'cvs diff':\n%s" % (data,))
  1266. unknown_files = []
  1267. for line in data.split("\n"):
  1268. if line and line[0] == "?":
  1269. unknown_files.append(line)
  1270. return unknown_files
  1271. class MercurialVCS(VersionControlSystem):
  1272. """Implementation of the VersionControlSystem interface for Mercurial."""
  1273. def __init__(self, options, repo_dir):
  1274. super(MercurialVCS, self).__init__(options)
  1275. # Absolute path to repository (we can be in a subdir)
  1276. self.repo_dir = os.path.normpath(repo_dir)
  1277. # Compute the subdir
  1278. cwd = os.path.normpath(os.getcwd())
  1279. assert cwd.startswith(self.repo_dir)
  1280. self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/")
  1281. if self.options.revision:
  1282. self.base_rev = self.options.revision
  1283. else:
  1284. self.base_rev = RunShell(["hg", "parent", "-q"]).split(':')[1].strip()
  1285. def GetGUID(self):
  1286. # See chapter "Uniquely identifying a repository"
  1287. # http://hgbook.red-bean.com/read/customizing-the-output-of-mercurial.html
  1288. info = RunShell("hg log -r0 --template {node}".split())
  1289. return info.strip()
  1290. def _GetRelPath(self, filename):
  1291. """Get relative path of a file according to the current directory,
  1292. given its logical path in the repo."""
  1293. absname = os.path.join(self.repo_dir, filename)
  1294. return os.path.relpath(absname)
  1295. def GenerateDiff(self, extra_args):
  1296. cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args
  1297. data = RunShell(cmd, silent_ok=True)
  1298. svndiff = []
  1299. filecount = 0
  1300. for line in data.splitlines():
  1301. m = re.match("diff --git a/(\S+) b/(\S+)", line)
  1302. if m:
  1303. # Modify line to make it look like as it comes from svn diff.
  1304. # With this modification no changes on the server side are required
  1305. # to make upload.py work with Mercurial repos.
  1306. # NOTE: for proper handling of moved/copied files, we have to use
  1307. # the second filename.
  1308. filename = m.group(2)
  1309. svndiff.append("Index: %s" % filename)
  1310. svndiff.append("=" * 67)
  1311. filecount += 1
  1312. logging.info(line)
  1313. else:
  1314. svndiff.append(line)
  1315. if not filecount:
  1316. ErrorExit("No valid patches found in output from hg diff")
  1317. return "\n".join(svndiff) + "\n"
  1318. def GetUnknownFiles(self):
  1319. """Return a list of files unknown to the VCS."""
  1320. args = []
  1321. status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."],
  1322. silent_ok=True)
  1323. unknown_files = []
  1324. for line in status.splitlines():
  1325. st, fn = line.split(" ", 1)
  1326. if st == "?":
  1327. unknown_files.append(fn)
  1328. return unknown_files
  1329. def GetBaseFile(self, filename):
  1330. # "hg status" and "hg cat" both take a path relative to the current subdir,
  1331. # but "hg diff" has given us the path relative to the repo root.
  1332. base_content = ""
  1333. new_content = None
  1334. is_binary = False
  1335. oldrelpath = relpath = self._GetRelPath(filename)
  1336. # "hg status -C" returns two lines for moved/copied files, one otherwise
  1337. out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath])
  1338. out = out.splitlines()
  1339. # HACK: strip error message about missing file/directory if it isn't in
  1340. # the working copy
  1341. if out[0].startswith('%s: ' % relpath):
  1342. out = out[1:]
  1343. status, _ = out[0].split(' ', 1)
  1344. if len(out) > 1 and status == "A":
  1345. # Moved/copied => considered as modified, use old filename to
  1346. # retrieve base contents
  1347. oldrelpath = out[1].strip()
  1348. status = "M"
  1349. if ":" in self.base_rev:
  1350. base_rev = self.base_rev.split(":", 1)[0]
  1351. else:
  1352. base_rev = self.base_rev
  1353. if status != "A":
  1354. base_content = RunShell(["hg", "cat", "-r", base_rev, oldrelpath],
  1355. silent_ok=True)
  1356. is_binary = self.IsBinaryData(base_content)
  1357. if status != "R":
  1358. new_content = open(relpath, "rb").read()
  1359. is_binary = is_binary or self.IsBinaryData(new_content)
  1360. if is_binary and base_content:
  1361. # Fetch again without converting newlines
  1362. base_content = RunShell(["hg", "cat", "-r", base_rev, oldrelpath],
  1363. silent_ok=True, universal_newlines=False)
  1364. if not is_binary or not self.IsImage(relpath):
  1365. new_content = None
  1366. return base_content, new_content, is_binary, status
  1367. class PerforceVCS(VersionControlSystem):
  1368. """Implementation of the VersionControlSystem interface for Perforce."""
  1369. def __init__(self, options):
  1370. def ConfirmLogin():
  1371. # Make sure we have a valid perforce session
  1372. while True:
  1373. data, retcode = self.RunPerforceCommandWithReturnCode(
  1374. ["login", "-s"], marshal_output=True)
  1375. if not data:
  1376. ErrorExit("Error checking perforce login")
  1377. if not retcode and (not "code" in data or data["code"] != "error"):
  1378. break
  1379. print "Enter perforce password: "
  1380. self.RunPerforceCommandWithReturnCode(["login"])
  1381. super(PerforceVCS, self).__init__(options)
  1382. self.p4_changelist = options.p4_changelist
  1383. if not self.p4_changelist:
  1384. ErrorExit("A changelist id is required")
  1385. if (options.revision):
  1386. ErrorExit("--rev is not supported for perforce")
  1387. self.p4_port = options.p4_port
  1388. self.p4_client = options.p4_client
  1389. self.p4_user = options.p4_user
  1390. ConfirmLogin()
  1391. if not options.title:
  1392. description = self.RunPerforceCommand(["describe", self.p4_changelist],
  1393. marshal_output=True)
  1394. if description and "desc" in description:
  1395. # Rietveld doesn't support multi-line descriptions
  1396. raw_title = description["desc"].strip()
  1397. lines = raw_title.splitlines()
  1398. if len(lines):
  1399. options.title = lines[0]
  1400. def GetGUID(self):
  1401. """For now we don't know how to get repository ID for Perforce"""
  1402. return
  1403. def RunPerforceCommandWithReturnCode(self, extra_args, marshal_output=False,
  1404. universal_newlines=True):
  1405. args = ["p4"]
  1406. if marshal_output:
  1407. # -G makes perforce format its output as marshalled python objects
  1408. args.extend(["-G"])
  1409. if self.p4_port:
  1410. args.extend(["-p", self.p4_port])
  1411. if self.p4_client:
  1412. args.extend(["-c", self.p4_client])
  1413. if self.p4_user:
  1414. args.extend(["-u", self.p4_user])
  1415. args.extend(extra_args)
  1416. data, retcode = RunShellWithReturnCode(
  1417. args, print_output=False, universal_newlines=universal_newlines)
  1418. if marshal_output and data:
  1419. data = marshal.loads(data)
  1420. return data, retcode
  1421. def RunPerforceCommand(self, extra_args, marshal_output=False,
  1422. universal_newlines=True):
  1423. # This might be a good place to cache call results, since things like
  1424. # describe or fstat might get called repeatedly.
  1425. data, retcode = self.RunPerforceCommandWithReturnCode(
  1426. extra_args, marshal_output, universal_newlines)
  1427. if retcode:
  1428. ErrorExit("Got error status from %s:\n%s" % (extra_args, data))
  1429. return data
  1430. def GetFileProperties(self, property_key_prefix = "", command = "describe"):
  1431. description = self.RunPerforceCommand(["describe", self.p4_changelist],
  1432. marshal_output=True)
  1433. changed_files = {}
  1434. file_index = 0
  1435. # Try depotFile0, depotFile1, ... until we don't find a match
  1436. while True:
  1437. file_key = "depotFile%d" % file_index
  1438. if file_key in description:
  1439. filename = description[file_key]
  1440. change_type = description[property_key_prefix + str(file_index)]
  1441. changed_files[filename] = change_type
  1442. file_index += 1
  1443. else:
  1444. break
  1445. return changed_files
  1446. def GetChangedFiles(self):
  1447. return self.GetFileProperties("action")
  1448. def GetUnknownFiles(self):
  1449. # Perforce doesn't detect new files, they have to be explicitly added
  1450. return []
  1451. def IsBaseBinary(self, filename):
  1452. base_filename = self.GetBaseFilename(filename)
  1453. return self.IsBinaryHelper(base_filename, "files")
  1454. def IsPendingBinary(self, filename):
  1455. return self.IsBinaryHelper(filename, "describe")
  1456. def IsBinaryHelper(self, filename, command):
  1457. file_types = self.GetFileProperties("type", command)
  1458. if not filename in file_types:
  1459. ErrorExit("Trying to check binary status of unknown file %s." % filename)
  1460. # This treats symlinks, macintosh resource files, temporary objects, and
  1461. # unicode as binary. See the Perforce docs for more details:
  1462. # http://www.perforce.com/perforce/doc.current/manuals/cmdref/o.ftypes.html
  1463. return not file_types[filename].endswith("text")
  1464. def GetFileContent(self, filename, revision, is_binary):
  1465. file_arg = filename
  1466. if revision:
  1467. file_arg += "#" + revision
  1468. # -q suppresses the initial line that displays the filename and revision
  1469. return self.RunPerforceCommand(["print", "-q", file_arg],
  1470. universal_newlines=not is_binary)
  1471. def GetBaseFilename(self, filename):
  1472. actionsWithDifferentBases = [
  1473. "move/add", # p4 move
  1474. "branch", # p4 integrate (to a new file), similar to hg "add"
  1475. "add", # p4 integrate (to a new file), after modifying the new file
  1476. ]
  1477. # We only see a different base for "add" if this is a downgraded branch
  1478. # after a file was branched (integrated), then edited.
  1479. if self.GetAction(filename) in actionsWithDifferentBases:
  1480. # -Or shows information about pending integrations/moves
  1481. fstat_result = self.RunPerforceCommand(["fstat", "-Or", filename],
  1482. marshal_output=True)
  1483. baseFileKey = "resolveFromFile0" # I think it's safe to use only file0
  1484. if baseFileKey in fstat_result:
  1485. return fstat_result[baseFileKey]
  1486. return filename
  1487. def GetBaseRevision(self, filename):
  1488. base_filename = self.GetBaseFilename(filename)
  1489. have_result = self.RunPerforceCommand(["have", base_filename],
  1490. marshal_output=True)
  1491. if "haveRev" in have_result:
  1492. return have_result["haveRev"]
  1493. def GetLocalFilename(self, filename):
  1494. where = self.RunPerforceCommand(["where", filename], marshal_output=True)
  1495. if "path" in where:
  1496. return where["path"]
  1497. def GenerateDiff(self, args):
  1498. class DiffData:
  1499. def __init__(self, perforceVCS, filename, action):
  1500. self.perforceVCS = perforceVCS
  1501. self.filename = filename
  1502. self.action = action
  1503. self.base_filename = perforceVCS.GetBaseFilename(filename)
  1504. self.file_body = None
  1505. self.base_rev = None
  1506. self.prefix = None
  1507. self.working_copy = True
  1508. self.change_summary = None
  1509. def GenerateDiffHeader(diffData):
  1510. header = []
  1511. header.append("Index: %s" % diffData.filename)
  1512. header.append("=" * 67)
  1513. if diffData.base_filename != diffData.filename:
  1514. if diffData.action.startswith("move"):
  1515. verb = "rename"
  1516. else:
  1517. verb = "copy"
  1518. header.append("%s from %s" % (verb, diffData.base_filename))
  1519. header.append("%s to %s" % (verb, diffData.filename))
  1520. suffix = "\t(revision %s)" % diffData.base_rev
  1521. header.append("--- " + diffData.base_filename + suffix)
  1522. if diffData.working_copy:
  1523. suffix = "\t(working copy)"
  1524. header.append("+++ " + diffData.filename + suffix)
  1525. if diffData.change_summary:
  1526. header.append(diffData.change_summary)
  1527. return header
  1528. def GenerateMergeDiff(diffData, args):
  1529. # -du generates a unified diff, which is nearly svn format
  1530. diffData.file_body = self.RunPerforceCommand(
  1531. ["diff", "-du", diffData.filename] + args)
  1532. diffData.base_rev = self.GetBaseRevision(diffData.filename)
  1533. diffData.prefix = ""
  1534. # We have to replace p4's file status output (the lines starting
  1535. # with +++ or ---) to match svn's diff format
  1536. lines = diffData.file_body.splitlines()
  1537. first_good_line = 0
  1538. while (first_good_line < len(lines) and
  1539. not lines[first_good_line].startswith("@@")):
  1540. first_good_line += 1
  1541. diffData.file_body = "\n".join(lines[first_good_line:])
  1542. return diffData
  1543. def GenerateAddDiff(diffData):
  1544. fstat = self.RunPerforceCommand(["fstat", diffData.filename],
  1545. marshal_output=True)
  1546. if "headRev" in fstat:
  1547. diffData.base_rev = fstat["headRev"] # Re-adding a deleted file
  1548. else:
  1549. diffData.base_rev = "0" # Brand new file
  1550. diffData.working_copy = False
  1551. rel_path = self.GetLocalFilename(diffData.filename)
  1552. diffData.file_body = open(rel_path, 'r').read()
  1553. # Replicate svn's list of changed lines
  1554. line_count = len(diffData.file_body.splitlines())
  1555. diffData.change_summary = "@@ -0,0 +1"
  1556. if line_count > 1:
  1557. diffData.change_summary += ",%d" % line_count
  1558. diffData.change_summary += " @@"
  1559. diffData.prefix = "+"
  1560. return diffData
  1561. def GenerateDeleteDiff(diffData):
  1562. diffData.base_rev = self.GetBaseRevision(diffData.filename)
  1563. is_base_binary = self.IsBaseBinary(diffData.filename)
  1564. # For deletes, base_filename == filename
  1565. diffData.file_body = self.GetFileContent(diffData.base_filename,
  1566. None,
  1567. is_base_binary)
  1568. # Replicate svn's list of changed lines
  1569. line_count = len(diffData.file_body.splitlines())
  1570. diffData.change_summary = "@@ -1"
  1571. if line_count > 1:
  1572. diffData.change_summary += ",%d" % line_count
  1573. diffData.change_summary += " +0,0 @@"
  1574. diffData.prefix = "-"
  1575. return diffData
  1576. changed_files = self.GetChangedFiles()
  1577. svndiff = []
  1578. filecount = 0
  1579. for (filename, action) in changed_files.items():
  1580. svn_status = self.PerforceActionToSvnStatus(action)
  1581. if svn_status == "SKIP":
  1582. continue
  1583. diffData = DiffData(self, filename, action)
  1584. # Is it possible to diff a branched file? Stackoverflow says no:
  1585. # http://stackoverflow.com/questions/1771314/in-perforce-command-line-how-to-diff-a-file-reopened-for-add
  1586. if svn_status == "M":
  1587. diffData = GenerateMergeDiff(diffData, args)
  1588. elif svn_status == "A":
  1589. diffData = GenerateAddDiff(diffData)
  1590. elif svn_status == "D":
  1591. diffData = GenerateDeleteDiff(diffData)
  1592. else:
  1593. ErrorExit("Unknown file action %s (svn action %s)." % \
  1594. (action, svn_status))
  1595. svndiff += GenerateDiffHeader(diffData)
  1596. for line in diffData.file_body.splitlines():
  1597. svndiff.append(diffData.prefix + line)
  1598. filecount += 1
  1599. if not filecount:
  1600. ErrorExit("No valid patches found in output from p4 diff")
  1601. return "\n".join(svndiff) + "\n"
  1602. def PerforceActionToSvnStatus(self, status):
  1603. # Mirroring the list at http://permalink.gmane.org/gmane.comp.version-control.mercurial.devel/28717
  1604. # Is there something more official?
  1605. return {
  1606. "add" : "A",
  1607. "branch" : "A",
  1608. "delete" : "D",
  1609. "edit" : "M", # Also includes changing file types.
  1610. "integrate" : "M",
  1611. "move/add" : "M",
  1612. "move/delete": "SKIP",
  1613. "purge" : "D", # How does a file's status become "purge"?
  1614. }[status]
  1615. def GetAction(self, filename):
  1616. changed_files = self.GetChangedFiles()
  1617. if not filename in changed_files:
  1618. ErrorExit("Trying to get base version of unknown file %s." % filename)
  1619. return changed_files[filename]
  1620. def GetBaseFile(self, filename):
  1621. base_filename = self.GetBaseFilename(filename)
  1622. base_content = ""
  1623. new_content = None
  1624. status = self.PerforceActionToSvnStatus(self.GetAction(filename))
  1625. if status != "A":
  1626. revision = self.GetBaseRevision(base_filename)
  1627. if not revision:
  1628. ErrorExit("Couldn't find base revision for file %s" % filename)
  1629. is_base_binary = self.IsBaseBinary(base_filename)
  1630. base_content = self.GetFileContent(base_filename,
  1631. revision,
  1632. is_base_binary)
  1633. is_binary = self.IsPendingBinary(filename)
  1634. if status != "D" and status != "SKIP":
  1635. relpath = self.GetLocalFilename(filename)
  1636. if is_binary and self.IsImage(relpath):
  1637. new_content = open(relpath, "rb").read()
  1638. return base_content, new_content, is_binary, status
  1639. # NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync.
  1640. def SplitPatch(data):
  1641. """Splits a patch into separate pieces for each file.
  1642. Args:
  1643. data: A string containing the output of svn diff.
  1644. Returns:
  1645. A list of 2-tuple (filename, text) where text is the svn diff output
  1646. pertaining to filename.
  1647. """
  1648. patches = []
  1649. filename = None
  1650. diff = []
  1651. for line in data.splitlines(True):
  1652. new_filename = None
  1653. if line.startswith('Index:'):
  1654. unused, new_filename = line.split(':', 1)
  1655. new_filename = new_filename.strip()
  1656. elif line.startswith('Property changes on:'):
  1657. unused, temp_filename = line.split(':', 1)
  1658. # When a file is modified, paths use '/' between directories, however
  1659. # when a property is modified '\' is used on Windows. Make them the same
  1660. # otherwise the file shows up twice.
  1661. temp_filename = temp_filename.strip().replace('\\', '/')
  1662. if temp_filename != filename:
  1663. # File has property changes but no modifications, create a new diff.
  1664. new_filename = temp_filename
  1665. if new_filename:
  1666. if filename and diff:
  1667. patches.append((filename, ''.join(diff)))
  1668. filename = new_filename
  1669. diff = [line]
  1670. continue
  1671. if diff is not None:
  1672. diff.append(line)
  1673. if filename and diff:
  1674. patches.append((filename, ''.join(diff)))
  1675. return patches
  1676. def UploadSeparatePatches(issue, rpc_server, patchset, data, options):
  1677. """Uploads a separate patch for each file in the diff output.
  1678. Returns a list of [patch_key, filename] for each file.
  1679. """
  1680. patches = SplitPatch(data)
  1681. rv = []
  1682. for patch in patches:
  1683. if len(patch[1]) > MAX_UPLOAD_SIZE:
  1684. print ("Not uploading the patch for " + patch[0] +
  1685. " because the file is too large.")
  1686. continue
  1687. form_fields = [("filename", patch[0])]
  1688. if not options.download_base:
  1689. form_fields.append(("content_upload", "1"))
  1690. files = [("data", "data.diff", patch[1])]
  1691. ctype, body = EncodeMultipartFormData(form_fields, files)
  1692. url = "/%d/upload_patch/%d" % (int(issue), int(patchset))
  1693. print "Uploading patch for " + patch[0]
  1694. response_body = rpc_server.Send(url, body, content_type=ctype)
  1695. lines = response_body.splitlines()
  1696. if not lines or lines[0] != "OK":
  1697. StatusUpdate(" --> %s" % response_body)
  1698. sys.exit(1)
  1699. rv.append([lines[1], patch[0]])
  1700. return rv
  1701. def GuessVCSName(options):
  1702. """Helper to guess the version control system.
  1703. This examines the current directory, guesses which VersionControlSystem
  1704. we're using, and returns an string indicating which VCS is detected.
  1705. Returns:
  1706. A pair (vcs, output). vcs is a string indicating which VCS was detected
  1707. and is one of VCS_GIT, VCS_MERCURIAL, VCS_SUBVERSION, VCS_PERFORCE,
  1708. VCS_CVS, or VCS_UNKNOWN.
  1709. Since local perforce repositories can't be easily detected, this method
  1710. will only guess VCS_PERFORCE if any perforce options have been specified.
  1711. output is a string containing any interesting output from the vcs
  1712. detection routine, or None if there is nothing interesting.
  1713. """
  1714. for attribute, value in options.__dict__.iteritems():
  1715. if attribute.startswith("p4") and value != None:
  1716. return (VCS_PERFORCE, None)
  1717. def RunDetectCommand(vcs_type, command):
  1718. """Helper to detect VCS by executing command.
  1719. Returns:
  1720. A pair (vcs, output) or None. Throws exception on error.
  1721. """
  1722. try:
  1723. out, returncode = RunShellWithReturnCode(command)
  1724. if returncode == 0:
  1725. return (vcs_type, out.strip())
  1726. except OSError, (errcode, message):
  1727. if errcode != errno.ENOENT: # command not found code
  1728. raise
  1729. # Mercurial has a command to get the base directory of a repository
  1730. # Try running it, but don't die if we don't have hg installed.
  1731. # NOTE: we try Mercurial first as it can sit on top of an SVN working copy.
  1732. res = RunDetectCommand(VCS_MERCURIAL, ["hg", "root"])
  1733. if res != None:
  1734. return res
  1735. # Subversion from 1.7 has a single centralized .svn folder
  1736. # ( see http://subversion.apache.org/docs/release-notes/1.7.html#wc-ng )
  1737. # That's why we use 'svn info' instead of checking for .svn dir
  1738. res = RunDetectCommand(VCS_SUBVERSION, ["svn", "info"])
  1739. if res != None:
  1740. return res
  1741. # Git has a command to test if you're in a git tree.
  1742. # Try running it, but don't die if we don't have git installed.
  1743. res = RunDetectCommand(VCS_GIT, ["git", "rev-parse",
  1744. "--is-inside-work-tree"])
  1745. if res != None:
  1746. return res
  1747. # detect CVS repos use `cvs status && $? == 0` rules
  1748. res = RunDetectCommand(VCS_CVS, ["cvs", "status"])
  1749. if res != None:
  1750. return res
  1751. return (VCS_UNKNOWN, None)
  1752. def GuessVCS(options):
  1753. """Helper to guess the version control system.
  1754. This verifies any user-specified VersionControlSystem (by command line
  1755. or environment variable). If the user didn't specify one, this examines
  1756. the current directory, guesses which VersionControlSystem we're using,
  1757. and returns an instance of the appropriate class. Exit with an error
  1758. if we can't figure it out.
  1759. Returns:
  1760. A VersionControlSystem instance. Exits if the VCS can't be guessed.
  1761. """
  1762. vcs = options.vcs
  1763. if not vcs:
  1764. vcs = os.environ.get("CODEREVIEW_VCS")
  1765. if vcs:
  1766. v = VCS_ABBREVIATIONS.get(vcs.lower())
  1767. if v is None:
  1768. ErrorExit("Unknown version control system %r specified." % vcs)
  1769. (vcs, extra_output) = (v, None)
  1770. else:
  1771. (vcs, extra_output) = GuessVCSName(options)
  1772. if vcs == VCS_MERCURIAL:
  1773. if extra_output is None:
  1774. extra_output = RunShell(["hg", "root"]).strip()
  1775. return MercurialVCS(options, extra_output)
  1776. elif vcs == VCS_SUBVERSION:
  1777. return SubversionVCS(options)
  1778. elif vcs == VCS_PERFORCE:
  1779. return PerforceVCS(options)
  1780. elif vcs == VCS_GIT:
  1781. return GitVCS(options)
  1782. elif vcs == VCS_CVS:
  1783. return CVSVCS(options)
  1784. ErrorExit(("Could not guess version control system. "
  1785. "Are you in a working copy directory?"))
  1786. def CheckReviewer(reviewer):
  1787. """Validate a reviewer -- either a nickname or an email addres.
  1788. Args:
  1789. reviewer: A nickname or an email address.
  1790. Calls ErrorExit() if it is an invalid email address.
  1791. """
  1792. if "@" not in reviewer:
  1793. return # Assume nickname
  1794. parts = reviewer.split("@")
  1795. if len(parts) > 2:
  1796. ErrorExit("Invalid email address: %r" % reviewer)
  1797. assert len(parts) == 2
  1798. if "." not in parts[1]:
  1799. ErrorExit("Invalid email address: %r" % reviewer)
  1800. def LoadSubversionAutoProperties():
  1801. """Returns the content of [auto-props] section of Subversion's config file as
  1802. a dictionary.
  1803. Returns:
  1804. A dictionary whose key-value pair corresponds the [auto-props] section's
  1805. key-value pair.
  1806. In following cases, returns empty dictionary:
  1807. - config file doesn't exist, or
  1808. - 'enable-auto-props' is not set to 'true-like-value' in [miscellany].
  1809. """
  1810. if os.name == 'nt':
  1811. subversion_config = os.environ.get("APPDATA") + "\\Subversion\\config"
  1812. else:
  1813. subversion_config = os.path.expanduser("~/.subversion/config")
  1814. if not os.path.exists(subversion_config):
  1815. return {}
  1816. config = ConfigParser.ConfigParser()
  1817. config.read(subversion_config)
  1818. if (config.has_section("miscellany") and
  1819. config.has_option("miscellany", "enable-auto-props") and
  1820. config.getboolean("miscellany", "enable-auto-props") and
  1821. config.has_section("auto-props")):
  1822. props = {}
  1823. for file_pattern in config.options("auto-props"):
  1824. props[file_pattern] = ParseSubversionPropertyValues(
  1825. config.get("auto-props", file_pattern))
  1826. return props
  1827. else:
  1828. return {}
  1829. def ParseSubversionPropertyValues(props):
  1830. """Parse the given property value which comes from [auto-props] section and
  1831. returns a list whose element is a (svn_prop_key, svn_prop_value) pair.
  1832. See the following doctest for example.
  1833. >>> ParseSubversionPropertyValues('svn:eol-style=LF')
  1834. [('svn:eol-style', 'LF')]
  1835. >>> ParseSubversionPropertyValues('svn:mime-type=image/jpeg')
  1836. [('svn:mime-type', 'image/jpeg')]
  1837. >>> ParseSubversionPropertyValues('svn:eol-style=LF;svn:executable')
  1838. [('svn:eol-style', 'LF'), ('svn:executable', '*')]
  1839. """
  1840. key_value_pairs = []
  1841. for prop in props.split(";"):
  1842. key_value = prop.split("=")
  1843. assert len(key_value) <= 2
  1844. if len(key_value) == 1:
  1845. # If value is not given, use '*' as a Subversion's convention.
  1846. key_value_pairs.append((key_value[0], "*"))
  1847. else:
  1848. key_value_pairs.append((key_value[0], key_value[1]))
  1849. return key_value_pairs
  1850. def GetSubversionPropertyChanges(filename):
  1851. """Return a Subversion's 'Property changes on ...' string, which is used in
  1852. the patch file.
  1853. Args:
  1854. filename: filename whose property might be set by [auto-props] config.
  1855. Returns:
  1856. A string like 'Property changes on |filename| ...' if given |filename|
  1857. matches any entries in [auto-props] section. None, otherwise.
  1858. """
  1859. global svn_auto_props_map
  1860. if svn_auto_props_map is None:
  1861. svn_auto_props_map = LoadSubversionAutoProperties()
  1862. all_props = []
  1863. for file_pattern, props in svn_auto_props_map.items():
  1864. if fnmatch.fnmatch(filename, file_pattern):
  1865. all_props.extend(props)
  1866. if all_props:
  1867. return FormatSubversionPropertyChanges(filename, all_props)
  1868. return None
  1869. def FormatSubversionPropertyChanges(filename, props):
  1870. """Returns Subversion's 'Property changes on ...' strings using given filename
  1871. and properties.
  1872. Args:
  1873. filename: filename
  1874. props: A list whose element is a (svn_prop_key, svn_prop_value) pair.
  1875. Returns:
  1876. A string which can be used in the patch file for Subversion.
  1877. See the following doctest for example.
  1878. >>> print FormatSubversionPropertyChanges('foo.cc', [('svn:eol-style', 'LF')])
  1879. Property changes on: foo.cc
  1880. ___________________________________________________________________
  1881. Added: svn:eol-style
  1882. + LF
  1883. <BLANKLINE>
  1884. """
  1885. prop_changes_lines = [
  1886. "Property changes on: %s" % filename,
  1887. "___________________________________________________________________"]
  1888. for key, value in props:
  1889. prop_changes_lines.append("Added: " + key)
  1890. prop_changes_lines.append(" + " + value)
  1891. return "\n".join(prop_changes_lines) + "\n"
  1892. def RealMain(argv, data=None):
  1893. """The real main function.
  1894. Args:
  1895. argv: Command line arguments.
  1896. data: Diff contents. If None (default) the diff is generated by
  1897. the VersionControlSystem implementation returned by GuessVCS().
  1898. Returns:
  1899. A 2-tuple (issue id, patchset id).
  1900. The patchset id is None if the base files are not uploaded by this
  1901. script (applies only to SVN checkouts).
  1902. """
  1903. options, args = parser.parse_args(argv[1:])
  1904. if options.help:
  1905. if options.verbose < 2:
  1906. # hide Perforce options
  1907. parser.epilog = "Use '--help -v' to show additional Perforce options."
  1908. parser.option_groups.remove(parser.get_option_group('--p4_port'))
  1909. parser.print_help()
  1910. sys.exit(0)
  1911. global verbosity
  1912. verbosity = options.verbose
  1913. if verbosity >= 3:
  1914. logging.getLogger().setLevel(logging.DEBUG)
  1915. elif verbosity >= 2:
  1916. logging.getLogger().setLevel(logging.INFO)
  1917. vcs = GuessVCS(options)
  1918. base = options.base_url
  1919. if isinstance(vcs, SubversionVCS):
  1920. # Guessing the base field is only supported for Subversion.
  1921. # Note: Fetching base files may become deprecated in future releases.
  1922. guessed_base = vcs.GuessBase(options.download_base)
  1923. if base:
  1924. if guessed_base and base != guessed_base:
  1925. print "Using base URL \"%s\" from --base_url instead of \"%s\"" % \
  1926. (base, guessed_base)
  1927. else:
  1928. base = guessed_base
  1929. if not base and options.download_base:
  1930. options.download_base = True
  1931. logging.info("Enabled upload of base file")
  1932. if not options.assume_yes:
  1933. vcs.CheckForUnknownFiles()
  1934. if data is None:
  1935. data = vcs.GenerateDiff(args)
  1936. data = vcs.PostProcessDiff(data)
  1937. if options.print_diffs:
  1938. print "Rietveld diff start:*****"
  1939. print data
  1940. print "Rietveld diff end:*****"
  1941. files = vcs.GetBaseFiles(data)
  1942. if verbosity >= 1:
  1943. print "Upload server:", options.server, "(change with -s/--server)"
  1944. rpc_server = GetRpcServer(options.server,
  1945. options.email,
  1946. options.host,
  1947. options.save_cookies,
  1948. options.account_type)
  1949. form_fields = []
  1950. repo_guid = vcs.GetGUID()
  1951. if repo_guid:
  1952. form_fields.append(("repo_guid", repo_guid))
  1953. if base:
  1954. b = urlparse.urlparse(base)
  1955. username, netloc = urllib.splituser(b.netloc)
  1956. if username:
  1957. logging.info("Removed username from base URL")
  1958. base = urlparse.urlunparse((b.scheme, netloc, b.path, b.params,
  1959. b.query, b.fragment))
  1960. form_fields.append(("base", base))
  1961. if options.issue:
  1962. form_fields.append(("issue", str(options.issue)))
  1963. if options.email:
  1964. form_fields.append(("user", options.email))
  1965. if options.reviewers:
  1966. for reviewer in options.reviewers.split(','):
  1967. CheckReviewer(reviewer)
  1968. form_fields.append(("reviewers", options.reviewers))
  1969. if options.cc:
  1970. for cc in options.cc.split(','):
  1971. CheckReviewer(cc)
  1972. form_fields.append(("cc", options.cc))
  1973. # Process --message, --title and --file.
  1974. message = options.message or ""
  1975. title = options.title or ""
  1976. if options.file:
  1977. if options.message:
  1978. ErrorExit("Can't specify both message and message file options")
  1979. file = open(options.file, 'r')
  1980. message = file.read()
  1981. file.close()
  1982. if options.issue:
  1983. prompt = "Title describing this patch set: "
  1984. else:
  1985. prompt = "New issue subject: "
  1986. title = (
  1987. title or message.split('\n', 1)[0].strip() or raw_input(prompt).strip())
  1988. if not title and not options.issue:
  1989. ErrorExit("A non-empty title is required for a new issue")
  1990. # For existing issues, it's fine to give a patchset an empty name. Rietveld
  1991. # doesn't accept that so use a whitespace.
  1992. title = title or " "
  1993. if len(title) > 100:
  1994. title = title[:99] + '…'
  1995. if title and not options.issue:
  1996. message = message or title
  1997. form_fields.append(("subject", title))
  1998. # If it's a new issue send message as description. Otherwise a new
  1999. # message is created below on upload_complete.
  2000. if message and not options.issue:
  2001. form_fields.append(("description", message))
  2002. # Send a hash of all the base file so the server can determine if a copy
  2003. # already exists in an earlier patchset.
  2004. base_hashes = ""
  2005. for file, info in files.iteritems():
  2006. if not info[0] is None:
  2007. checksum = md5(info[0]).hexdigest()
  2008. if base_hashes:
  2009. base_hashes += "|"
  2010. base_hashes += checksum + ":" + file
  2011. form_fields.append(("base_hashes", base_hashes))
  2012. if options.private:
  2013. if options.issue:
  2014. print "Warning: Private flag ignored when updating an existing issue."
  2015. else:
  2016. form_fields.append(("private", "1"))
  2017. if options.send_patch:
  2018. options.send_mail = True
  2019. if not options.download_base:
  2020. form_fields.append(("content_upload", "1"))
  2021. if len(data) > MAX_UPLOAD_SIZE:
  2022. print "Patch is large, so uploading file patches separately."
  2023. uploaded_diff_file = []
  2024. form_fields.append(("separate_patches", "1"))
  2025. else:
  2026. uploaded_diff_file = [("data", "data.diff", data)]
  2027. ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file)
  2028. response_body = rpc_server.Send("/upload", body, content_type=ctype)
  2029. patchset = None
  2030. if not options.download_base or not uploaded_diff_file:
  2031. lines = response_body.splitlines()
  2032. if len(lines) >= 2:
  2033. msg = lines[0]
  2034. patchset = lines[1].strip()
  2035. patches = [x.split(" ", 1) for x in lines[2:]]
  2036. else:
  2037. msg = response_body
  2038. else:
  2039. msg = response_body
  2040. StatusUpdate(msg)
  2041. if not response_body.startswith("Issue created.") and \
  2042. not response_body.startswith("Issue updated."):
  2043. sys.exit(0)
  2044. issue = msg[msg.rfind("/")+1:]
  2045. if not uploaded_diff_file:
  2046. result = UploadSeparatePatches(issue, rpc_server, patchset, data, options)
  2047. if not options.download_base:
  2048. patches = result
  2049. if not options.download_base:
  2050. vcs.UploadBaseFiles(issue, rpc_server, patches, patchset, options, files)
  2051. payload = {} # payload for final request
  2052. if options.send_mail:
  2053. payload["send_mail"] = "yes"
  2054. if options.send_patch:
  2055. payload["attach_patch"] = "yes"
  2056. if options.issue and message:
  2057. payload["message"] = message
  2058. payload = urllib.urlencode(payload)
  2059. rpc_server.Send("/" + issue + "/upload_complete/" + (patchset or ""),
  2060. payload=payload)
  2061. return issue, patchset
  2062. def main():
  2063. try:
  2064. logging.basicConfig(format=("%(asctime).19s %(levelname)s %(filename)s:"
  2065. "%(lineno)s %(message)s "))
  2066. os.environ['LC_ALL'] = 'C'
  2067. RealMain(sys.argv)
  2068. except KeyboardInterrupt:
  2069. print
  2070. StatusUpdate("Interrupted.")
  2071. sys.exit(1)
  2072. if __name__ == "__main__":
  2073. main()