upload.py 85 KB

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