codereview.py 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291
  1. # coding=utf-8
  2. # (The line above is necessary so that I can use 世界 in the
  3. # *comment* below without Python getting all bent out of shape.)
  4. # Copyright 2007-2009 Google Inc.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. # See the License for the specific language governing permissions and
  16. # limitations under the License.
  17. '''Mercurial interface to codereview.appspot.com.
  18. To configure, set the following options in
  19. your repository's .hg/hgrc file.
  20. [extensions]
  21. codereview = path/to/codereview.py
  22. [codereview]
  23. server = codereview.appspot.com
  24. The server should be running Rietveld; see http://code.google.com/p/rietveld/.
  25. In addition to the new commands, this extension introduces
  26. the file pattern syntax @nnnnnn, where nnnnnn is a change list
  27. number, to mean the files included in that change list, which
  28. must be associated with the current client.
  29. For example, if change 123456 contains the files x.go and y.go,
  30. "hg diff @123456" is equivalent to"hg diff x.go y.go".
  31. '''
  32. from mercurial import cmdutil, commands, hg, util, error, match
  33. from mercurial.node import nullrev, hex, nullid, short
  34. import os, re, time
  35. import stat
  36. import subprocess
  37. import threading
  38. from HTMLParser import HTMLParser
  39. # The standard 'json' package is new in Python 2.6.
  40. # Before that it was an external package named simplejson.
  41. try:
  42. # Standard location in 2.6 and beyond.
  43. import json
  44. except Exception, e:
  45. try:
  46. # Conventional name for earlier package.
  47. import simplejson as json
  48. except:
  49. try:
  50. # Was also bundled with django, which is commonly installed.
  51. from django.utils import simplejson as json
  52. except:
  53. # We give up.
  54. raise e
  55. try:
  56. hgversion = util.version()
  57. except:
  58. from mercurial.version import version as v
  59. hgversion = v.get_version()
  60. try:
  61. from mercurial.discovery import findcommonincoming
  62. except:
  63. def findcommonincoming(repo, remote):
  64. return repo.findcommonincoming(remote)
  65. # in Mercurial 1.9 the cmdutil.match and cmdutil.revpair moved to scmutil
  66. if hgversion >= '1.9':
  67. from mercurial import scmutil
  68. else:
  69. scmutil = cmdutil
  70. oldMessage = """
  71. The code review extension requires Mercurial 1.3 or newer.
  72. To install a new Mercurial,
  73. sudo easy_install mercurial
  74. works on most systems.
  75. """
  76. linuxMessage = """
  77. You may need to clear your current Mercurial installation by running:
  78. sudo apt-get remove mercurial mercurial-common
  79. sudo rm -rf /etc/mercurial
  80. """
  81. if hgversion < '1.3':
  82. msg = oldMessage
  83. if os.access("/etc/mercurial", 0):
  84. msg += linuxMessage
  85. raise util.Abort(msg)
  86. def promptyesno(ui, msg):
  87. # Arguments to ui.prompt changed between 1.3 and 1.3.1.
  88. # Even so, some 1.3.1 distributions seem to have the old prompt!?!?
  89. # What a terrible way to maintain software.
  90. try:
  91. return ui.promptchoice(msg, ["&yes", "&no"], 0) == 0
  92. except AttributeError:
  93. return ui.prompt(msg, ["&yes", "&no"], "y") != "n"
  94. # To experiment with Mercurial in the python interpreter:
  95. # >>> repo = hg.repository(ui.ui(), path = ".")
  96. #######################################################################
  97. # Normally I would split this into multiple files, but it simplifies
  98. # import path headaches to keep it all in one file. Sorry.
  99. import sys
  100. if __name__ == "__main__":
  101. print >>sys.stderr, "This is a Mercurial extension and should not be invoked directly."
  102. sys.exit(2)
  103. server = "codereview.appspot.com"
  104. server_url_base = None
  105. defaultcc = None
  106. contributors = {}
  107. missing_codereview = None
  108. real_rollback = None
  109. releaseBranch = None
  110. #######################################################################
  111. # RE: UNICODE STRING HANDLING
  112. #
  113. # Python distinguishes between the str (string of bytes)
  114. # and unicode (string of code points) types. Most operations
  115. # work on either one just fine, but some (like regexp matching)
  116. # require unicode, and others (like write) require str.
  117. #
  118. # As befits the language, Python hides the distinction between
  119. # unicode and str by converting between them silently, but
  120. # *only* if all the bytes/code points involved are 7-bit ASCII.
  121. # This means that if you're not careful, your program works
  122. # fine on "hello, world" and fails on "hello, 世界". And of course,
  123. # the obvious way to be careful - use static types - is unavailable.
  124. # So the only way is trial and error to find where to put explicit
  125. # conversions.
  126. #
  127. # Because more functions do implicit conversion to str (string of bytes)
  128. # than do implicit conversion to unicode (string of code points),
  129. # the convention in this module is to represent all text as str,
  130. # converting to unicode only when calling a unicode-only function
  131. # and then converting back to str as soon as possible.
  132. def typecheck(s, t):
  133. if type(s) != t:
  134. raise util.Abort("type check failed: %s has type %s != %s" % (repr(s), type(s), t))
  135. # If we have to pass unicode instead of str, ustr does that conversion clearly.
  136. def ustr(s):
  137. typecheck(s, str)
  138. return s.decode("utf-8")
  139. # Even with those, Mercurial still sometimes turns unicode into str
  140. # and then tries to use it as ascii. Change Mercurial's default.
  141. def set_mercurial_encoding_to_utf8():
  142. from mercurial import encoding
  143. encoding.encoding = 'utf-8'
  144. set_mercurial_encoding_to_utf8()
  145. # Even with those we still run into problems.
  146. # I tried to do things by the book but could not convince
  147. # Mercurial to let me check in a change with UTF-8 in the
  148. # CL description or author field, no matter how many conversions
  149. # between str and unicode I inserted and despite changing the
  150. # default encoding. I'm tired of this game, so set the default
  151. # encoding for all of Python to 'utf-8', not 'ascii'.
  152. def default_to_utf8():
  153. import sys
  154. reload(sys) # site.py deleted setdefaultencoding; get it back
  155. sys.setdefaultencoding('utf-8')
  156. default_to_utf8()
  157. #######################################################################
  158. # Change list parsing.
  159. #
  160. # Change lists are stored in .hg/codereview/cl.nnnnnn
  161. # where nnnnnn is the number assigned by the code review server.
  162. # Most data about a change list is stored on the code review server
  163. # too: the description, reviewer, and cc list are all stored there.
  164. # The only thing in the cl.nnnnnn file is the list of relevant files.
  165. # Also, the existence of the cl.nnnnnn file marks this repository
  166. # as the one where the change list lives.
  167. emptydiff = """Index: ~rietveld~placeholder~
  168. ===================================================================
  169. diff --git a/~rietveld~placeholder~ b/~rietveld~placeholder~
  170. new file mode 100644
  171. """
  172. class CL(object):
  173. def __init__(self, name):
  174. typecheck(name, str)
  175. self.name = name
  176. self.desc = ''
  177. self.files = []
  178. self.reviewer = []
  179. self.cc = []
  180. self.url = ''
  181. self.local = False
  182. self.web = False
  183. self.copied_from = None # None means current user
  184. self.mailed = False
  185. self.private = False
  186. def DiskText(self):
  187. cl = self
  188. s = ""
  189. if cl.copied_from:
  190. s += "Author: " + cl.copied_from + "\n\n"
  191. if cl.private:
  192. s += "Private: " + str(self.private) + "\n"
  193. s += "Mailed: " + str(self.mailed) + "\n"
  194. s += "Description:\n"
  195. s += Indent(cl.desc, "\t")
  196. s += "Files:\n"
  197. for f in cl.files:
  198. s += "\t" + f + "\n"
  199. typecheck(s, str)
  200. return s
  201. def EditorText(self):
  202. cl = self
  203. s = _change_prolog
  204. s += "\n"
  205. if cl.copied_from:
  206. s += "Author: " + cl.copied_from + "\n"
  207. if cl.url != '':
  208. s += 'URL: ' + cl.url + ' # cannot edit\n\n'
  209. if cl.private:
  210. s += "Private: True\n"
  211. s += "Reviewer: " + JoinComma(cl.reviewer) + "\n"
  212. s += "CC: " + JoinComma(cl.cc) + "\n"
  213. s += "\n"
  214. s += "Description:\n"
  215. if cl.desc == '':
  216. s += "\t<enter description here>\n"
  217. else:
  218. s += Indent(cl.desc, "\t")
  219. s += "\n"
  220. if cl.local or cl.name == "new":
  221. s += "Files:\n"
  222. for f in cl.files:
  223. s += "\t" + f + "\n"
  224. s += "\n"
  225. typecheck(s, str)
  226. return s
  227. def PendingText(self):
  228. cl = self
  229. s = cl.name + ":" + "\n"
  230. s += Indent(cl.desc, "\t")
  231. s += "\n"
  232. if cl.copied_from:
  233. s += "\tAuthor: " + cl.copied_from + "\n"
  234. s += "\tReviewer: " + JoinComma(cl.reviewer) + "\n"
  235. s += "\tCC: " + JoinComma(cl.cc) + "\n"
  236. s += "\tFiles:\n"
  237. for f in cl.files:
  238. s += "\t\t" + f + "\n"
  239. typecheck(s, str)
  240. return s
  241. def Flush(self, ui, repo):
  242. if self.name == "new":
  243. self.Upload(ui, repo, gofmt_just_warn=True, creating=True)
  244. dir = CodeReviewDir(ui, repo)
  245. path = dir + '/cl.' + self.name
  246. f = open(path+'!', "w")
  247. f.write(self.DiskText())
  248. f.close()
  249. if sys.platform == "win32" and os.path.isfile(path):
  250. os.remove(path)
  251. os.rename(path+'!', path)
  252. if self.web and not self.copied_from:
  253. EditDesc(self.name, desc=self.desc,
  254. reviewers=JoinComma(self.reviewer), cc=JoinComma(self.cc),
  255. private=self.private)
  256. def Delete(self, ui, repo):
  257. dir = CodeReviewDir(ui, repo)
  258. os.unlink(dir + "/cl." + self.name)
  259. def Subject(self):
  260. s = line1(self.desc)
  261. if len(s) > 60:
  262. s = s[0:55] + "..."
  263. if self.name != "new":
  264. s = "code review %s: %s" % (self.name, s)
  265. typecheck(s, str)
  266. return s
  267. def Upload(self, ui, repo, send_mail=False, gofmt=True, gofmt_just_warn=False, creating=False, quiet=False):
  268. if not self.files and not creating:
  269. ui.warn("no files in change list\n")
  270. if ui.configbool("codereview", "force_gofmt", True) and gofmt:
  271. CheckFormat(ui, repo, self.files, just_warn=gofmt_just_warn)
  272. set_status("uploading CL metadata + diffs")
  273. os.chdir(repo.root)
  274. form_fields = [
  275. ("content_upload", "1"),
  276. ("reviewers", JoinComma(self.reviewer)),
  277. ("cc", JoinComma(self.cc)),
  278. ("description", self.desc),
  279. ("base_hashes", ""),
  280. ]
  281. if self.name != "new":
  282. form_fields.append(("issue", self.name))
  283. vcs = None
  284. # We do not include files when creating the issue,
  285. # because we want the patch sets to record the repository
  286. # and base revision they are diffs against. We use the patch
  287. # set message for that purpose, but there is no message with
  288. # the first patch set. Instead the message gets used as the
  289. # new CL's overall subject. So omit the diffs when creating
  290. # and then we'll run an immediate upload.
  291. # This has the effect that every CL begins with an empty "Patch set 1".
  292. if self.files and not creating:
  293. vcs = MercurialVCS(upload_options, ui, repo)
  294. data = vcs.GenerateDiff(self.files)
  295. files = vcs.GetBaseFiles(data)
  296. if len(data) > MAX_UPLOAD_SIZE:
  297. uploaded_diff_file = []
  298. form_fields.append(("separate_patches", "1"))
  299. else:
  300. uploaded_diff_file = [("data", "data.diff", data)]
  301. else:
  302. uploaded_diff_file = [("data", "data.diff", emptydiff)]
  303. if vcs and self.name != "new":
  304. form_fields.append(("subject", "diff -r " + vcs.base_rev + " " + getremote(ui, repo, {}).path))
  305. else:
  306. # First upload sets the subject for the CL itself.
  307. form_fields.append(("subject", self.Subject()))
  308. ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file)
  309. response_body = MySend("/upload", body, content_type=ctype)
  310. patchset = None
  311. msg = response_body
  312. lines = msg.splitlines()
  313. if len(lines) >= 2:
  314. msg = lines[0]
  315. patchset = lines[1].strip()
  316. patches = [x.split(" ", 1) for x in lines[2:]]
  317. if response_body.startswith("Issue updated.") and quiet:
  318. pass
  319. else:
  320. ui.status(msg + "\n")
  321. set_status("uploaded CL metadata + diffs")
  322. if not response_body.startswith("Issue created.") and not response_body.startswith("Issue updated."):
  323. raise util.Abort("failed to update issue: " + response_body)
  324. issue = msg[msg.rfind("/")+1:]
  325. self.name = issue
  326. if not self.url:
  327. self.url = server_url_base + self.name
  328. if not uploaded_diff_file:
  329. set_status("uploading patches")
  330. patches = UploadSeparatePatches(issue, rpc, patchset, data, upload_options)
  331. if vcs:
  332. set_status("uploading base files")
  333. vcs.UploadBaseFiles(issue, rpc, patches, patchset, upload_options, files)
  334. if send_mail:
  335. set_status("sending mail")
  336. MySend("/" + issue + "/mail", payload="")
  337. self.web = True
  338. set_status("flushing changes to disk")
  339. self.Flush(ui, repo)
  340. return
  341. def Mail(self, ui, repo):
  342. pmsg = "Hello " + JoinComma(self.reviewer)
  343. if self.cc:
  344. pmsg += " (cc: %s)" % (', '.join(self.cc),)
  345. pmsg += ",\n"
  346. pmsg += "\n"
  347. repourl = getremote(ui, repo, {}).path
  348. if not self.mailed:
  349. pmsg += "I'd like you to review this change to\n" + repourl + "\n"
  350. else:
  351. pmsg += "Please take another look.\n"
  352. typecheck(pmsg, str)
  353. PostMessage(ui, self.name, pmsg, subject=self.Subject())
  354. self.mailed = True
  355. self.Flush(ui, repo)
  356. def GoodCLName(name):
  357. typecheck(name, str)
  358. return re.match("^[0-9]+$", name)
  359. def ParseCL(text, name):
  360. typecheck(text, str)
  361. typecheck(name, str)
  362. sname = None
  363. lineno = 0
  364. sections = {
  365. 'Author': '',
  366. 'Description': '',
  367. 'Files': '',
  368. 'URL': '',
  369. 'Reviewer': '',
  370. 'CC': '',
  371. 'Mailed': '',
  372. 'Private': '',
  373. }
  374. for line in text.split('\n'):
  375. lineno += 1
  376. line = line.rstrip()
  377. if line != '' and line[0] == '#':
  378. continue
  379. if line == '' or line[0] == ' ' or line[0] == '\t':
  380. if sname == None and line != '':
  381. return None, lineno, 'text outside section'
  382. if sname != None:
  383. sections[sname] += line + '\n'
  384. continue
  385. p = line.find(':')
  386. if p >= 0:
  387. s, val = line[:p].strip(), line[p+1:].strip()
  388. if s in sections:
  389. sname = s
  390. if val != '':
  391. sections[sname] += val + '\n'
  392. continue
  393. return None, lineno, 'malformed section header'
  394. for k in sections:
  395. sections[k] = StripCommon(sections[k]).rstrip()
  396. cl = CL(name)
  397. if sections['Author']:
  398. cl.copied_from = sections['Author']
  399. cl.desc = sections['Description']
  400. for line in sections['Files'].split('\n'):
  401. i = line.find('#')
  402. if i >= 0:
  403. line = line[0:i].rstrip()
  404. line = line.strip()
  405. if line == '':
  406. continue
  407. cl.files.append(line)
  408. cl.reviewer = SplitCommaSpace(sections['Reviewer'])
  409. cl.cc = SplitCommaSpace(sections['CC'])
  410. cl.url = sections['URL']
  411. if sections['Mailed'] != 'False':
  412. # Odd default, but avoids spurious mailings when
  413. # reading old CLs that do not have a Mailed: line.
  414. # CLs created with this update will always have
  415. # Mailed: False on disk.
  416. cl.mailed = True
  417. if sections['Private'] in ('True', 'true', 'Yes', 'yes'):
  418. cl.private = True
  419. if cl.desc == '<enter description here>':
  420. cl.desc = ''
  421. return cl, 0, ''
  422. def SplitCommaSpace(s):
  423. typecheck(s, str)
  424. s = s.strip()
  425. if s == "":
  426. return []
  427. return re.split(", *", s)
  428. def CutDomain(s):
  429. typecheck(s, str)
  430. i = s.find('@')
  431. if i >= 0:
  432. s = s[0:i]
  433. return s
  434. def JoinComma(l):
  435. for s in l:
  436. typecheck(s, str)
  437. return ", ".join(l)
  438. def ExceptionDetail():
  439. s = str(sys.exc_info()[0])
  440. if s.startswith("<type '") and s.endswith("'>"):
  441. s = s[7:-2]
  442. elif s.startswith("<class '") and s.endswith("'>"):
  443. s = s[8:-2]
  444. arg = str(sys.exc_info()[1])
  445. if len(arg) > 0:
  446. s += ": " + arg
  447. return s
  448. def IsLocalCL(ui, repo, name):
  449. return GoodCLName(name) and os.access(CodeReviewDir(ui, repo) + "/cl." + name, 0)
  450. # Load CL from disk and/or the web.
  451. def LoadCL(ui, repo, name, web=True):
  452. typecheck(name, str)
  453. set_status("loading CL " + name)
  454. if not GoodCLName(name):
  455. return None, "invalid CL name"
  456. dir = CodeReviewDir(ui, repo)
  457. path = dir + "cl." + name
  458. if os.access(path, 0):
  459. ff = open(path)
  460. text = ff.read()
  461. ff.close()
  462. cl, lineno, err = ParseCL(text, name)
  463. if err != "":
  464. return None, "malformed CL data: "+err
  465. cl.local = True
  466. else:
  467. cl = CL(name)
  468. if web:
  469. set_status("getting issue metadata from web")
  470. d = JSONGet(ui, "/api/" + name + "?messages=true")
  471. set_status(None)
  472. if d is None:
  473. return None, "cannot load CL %s from server" % (name,)
  474. if 'owner_email' not in d or 'issue' not in d or str(d['issue']) != name:
  475. return None, "malformed response loading CL data from code review server"
  476. cl.dict = d
  477. cl.reviewer = d.get('reviewers', [])
  478. cl.cc = d.get('cc', [])
  479. if cl.local and cl.copied_from and cl.desc:
  480. # local copy of CL written by someone else
  481. # and we saved a description. use that one,
  482. # so that committers can edit the description
  483. # before doing hg submit.
  484. pass
  485. else:
  486. cl.desc = d.get('description', "")
  487. cl.url = server_url_base + name
  488. cl.web = True
  489. cl.private = d.get('private', False) != False
  490. set_status("loaded CL " + name)
  491. return cl, ''
  492. global_status = None
  493. def set_status(s):
  494. # print >>sys.stderr, "\t", time.asctime(), s
  495. global global_status
  496. global_status = s
  497. class StatusThread(threading.Thread):
  498. def __init__(self):
  499. threading.Thread.__init__(self)
  500. def run(self):
  501. # pause a reasonable amount of time before
  502. # starting to display status messages, so that
  503. # most hg commands won't ever see them.
  504. time.sleep(30)
  505. # now show status every 15 seconds
  506. while True:
  507. time.sleep(15 - time.time() % 15)
  508. s = global_status
  509. if s is None:
  510. continue
  511. if s == "":
  512. s = "(unknown status)"
  513. print >>sys.stderr, time.asctime(), s
  514. def start_status_thread():
  515. t = StatusThread()
  516. t.setDaemon(True) # allowed to exit if t is still running
  517. t.start()
  518. class LoadCLThread(threading.Thread):
  519. def __init__(self, ui, repo, dir, f, web):
  520. threading.Thread.__init__(self)
  521. self.ui = ui
  522. self.repo = repo
  523. self.dir = dir
  524. self.f = f
  525. self.web = web
  526. self.cl = None
  527. def run(self):
  528. cl, err = LoadCL(self.ui, self.repo, self.f[3:], web=self.web)
  529. if err != '':
  530. self.ui.warn("loading "+self.dir+self.f+": " + err + "\n")
  531. return
  532. self.cl = cl
  533. # Load all the CLs from this repository.
  534. def LoadAllCL(ui, repo, web=True):
  535. dir = CodeReviewDir(ui, repo)
  536. m = {}
  537. files = [f for f in os.listdir(dir) if f.startswith('cl.')]
  538. if not files:
  539. return m
  540. active = []
  541. first = True
  542. for f in files:
  543. t = LoadCLThread(ui, repo, dir, f, web)
  544. t.start()
  545. if web and first:
  546. # first request: wait in case it needs to authenticate
  547. # otherwise we get lots of user/password prompts
  548. # running in parallel.
  549. t.join()
  550. if t.cl:
  551. m[t.cl.name] = t.cl
  552. first = False
  553. else:
  554. active.append(t)
  555. for t in active:
  556. t.join()
  557. if t.cl:
  558. m[t.cl.name] = t.cl
  559. return m
  560. # Find repository root. On error, ui.warn and return None
  561. def RepoDir(ui, repo):
  562. url = repo.url();
  563. if not url.startswith('file:'):
  564. ui.warn("repository %s is not in local file system\n" % (url,))
  565. return None
  566. url = url[5:]
  567. if url.endswith('/'):
  568. url = url[:-1]
  569. typecheck(url, str)
  570. return url
  571. # Find (or make) code review directory. On error, ui.warn and return None
  572. def CodeReviewDir(ui, repo):
  573. dir = RepoDir(ui, repo)
  574. if dir == None:
  575. return None
  576. dir += '/.hg/codereview/'
  577. if not os.path.isdir(dir):
  578. try:
  579. os.mkdir(dir, 0700)
  580. except:
  581. ui.warn('cannot mkdir %s: %s\n' % (dir, ExceptionDetail()))
  582. return None
  583. typecheck(dir, str)
  584. return dir
  585. # Turn leading tabs into spaces, so that the common white space
  586. # prefix doesn't get confused when people's editors write out
  587. # some lines with spaces, some with tabs. Only a heuristic
  588. # (some editors don't use 8 spaces either) but a useful one.
  589. def TabsToSpaces(line):
  590. i = 0
  591. while i < len(line) and line[i] == '\t':
  592. i += 1
  593. return ' '*(8*i) + line[i:]
  594. # Strip maximal common leading white space prefix from text
  595. def StripCommon(text):
  596. typecheck(text, str)
  597. ws = None
  598. for line in text.split('\n'):
  599. line = line.rstrip()
  600. if line == '':
  601. continue
  602. line = TabsToSpaces(line)
  603. white = line[:len(line)-len(line.lstrip())]
  604. if ws == None:
  605. ws = white
  606. else:
  607. common = ''
  608. for i in range(min(len(white), len(ws))+1):
  609. if white[0:i] == ws[0:i]:
  610. common = white[0:i]
  611. ws = common
  612. if ws == '':
  613. break
  614. if ws == None:
  615. return text
  616. t = ''
  617. for line in text.split('\n'):
  618. line = line.rstrip()
  619. line = TabsToSpaces(line)
  620. if line.startswith(ws):
  621. line = line[len(ws):]
  622. if line == '' and t == '':
  623. continue
  624. t += line + '\n'
  625. while len(t) >= 2 and t[-2:] == '\n\n':
  626. t = t[:-1]
  627. typecheck(t, str)
  628. return t
  629. # Indent text with indent.
  630. def Indent(text, indent):
  631. typecheck(text, str)
  632. typecheck(indent, str)
  633. t = ''
  634. for line in text.split('\n'):
  635. t += indent + line + '\n'
  636. typecheck(t, str)
  637. return t
  638. # Return the first line of l
  639. def line1(text):
  640. typecheck(text, str)
  641. return text.split('\n')[0]
  642. _change_prolog = """# Change list.
  643. # Lines beginning with # are ignored.
  644. # Multi-line values should be indented.
  645. """
  646. #######################################################################
  647. # Mercurial helper functions
  648. # Get effective change nodes taking into account applied MQ patches
  649. def effective_revpair(repo):
  650. try:
  651. return scmutil.revpair(repo, ['qparent'])
  652. except:
  653. return scmutil.revpair(repo, None)
  654. # Return list of changed files in repository that match pats.
  655. # Warn about patterns that did not match.
  656. def matchpats(ui, repo, pats, opts):
  657. matcher = scmutil.match(repo, pats, opts)
  658. node1, node2 = effective_revpair(repo)
  659. modified, added, removed, deleted, unknown, ignored, clean = repo.status(node1, node2, matcher, ignored=True, clean=True, unknown=True)
  660. return (modified, added, removed, deleted, unknown, ignored, clean)
  661. # Return list of changed files in repository that match pats.
  662. # The patterns came from the command line, so we warn
  663. # if they have no effect or cannot be understood.
  664. def ChangedFiles(ui, repo, pats, opts, taken=None):
  665. taken = taken or {}
  666. # Run each pattern separately so that we can warn about
  667. # patterns that didn't do anything useful.
  668. for p in pats:
  669. modified, added, removed, deleted, unknown, ignored, clean = matchpats(ui, repo, [p], opts)
  670. redo = False
  671. for f in unknown:
  672. promptadd(ui, repo, f)
  673. redo = True
  674. for f in deleted:
  675. promptremove(ui, repo, f)
  676. redo = True
  677. if redo:
  678. modified, added, removed, deleted, unknown, ignored, clean = matchpats(ui, repo, [p], opts)
  679. for f in modified + added + removed:
  680. if f in taken:
  681. ui.warn("warning: %s already in CL %s\n" % (f, taken[f].name))
  682. if not modified and not added and not removed:
  683. ui.warn("warning: %s did not match any modified files\n" % (p,))
  684. # Again, all at once (eliminates duplicates)
  685. modified, added, removed = matchpats(ui, repo, pats, opts)[:3]
  686. l = modified + added + removed
  687. l.sort()
  688. if taken:
  689. l = Sub(l, taken.keys())
  690. return l
  691. # Return list of changed files in repository that match pats and still exist.
  692. def ChangedExistingFiles(ui, repo, pats, opts):
  693. modified, added = matchpats(ui, repo, pats, opts)[:2]
  694. l = modified + added
  695. l.sort()
  696. return l
  697. # Return list of files claimed by existing CLs
  698. def Taken(ui, repo):
  699. all = LoadAllCL(ui, repo, web=False)
  700. taken = {}
  701. for _, cl in all.items():
  702. for f in cl.files:
  703. taken[f] = cl
  704. return taken
  705. # Return list of changed files that are not claimed by other CLs
  706. def DefaultFiles(ui, repo, pats, opts):
  707. return ChangedFiles(ui, repo, pats, opts, taken=Taken(ui, repo))
  708. def Sub(l1, l2):
  709. return [l for l in l1 if l not in l2]
  710. def Add(l1, l2):
  711. l = l1 + Sub(l2, l1)
  712. l.sort()
  713. return l
  714. def Intersect(l1, l2):
  715. return [l for l in l1 if l in l2]
  716. def getremote(ui, repo, opts):
  717. # save $http_proxy; creating the HTTP repo object will
  718. # delete it in an attempt to "help"
  719. proxy = os.environ.get('http_proxy')
  720. source = hg.parseurl(ui.expandpath("default"), None)[0]
  721. try:
  722. remoteui = hg.remoteui # hg 1.6
  723. except:
  724. remoteui = cmdutil.remoteui
  725. other = hg.repository(remoteui(repo, opts), source)
  726. if proxy is not None:
  727. os.environ['http_proxy'] = proxy
  728. return other
  729. def Incoming(ui, repo, opts):
  730. _, incoming, _ = findcommonincoming(repo, getremote(ui, repo, opts))
  731. return incoming
  732. desc_re = '^(.+: |(tag )?(release|weekly)\.|fix build|undo CL)'
  733. desc_msg = '''Your CL description appears not to use the standard form.
  734. The first line of your change description is conventionally a
  735. one-line summary of the change, prefixed by the primary affected package,
  736. and is used as the subject for code review mail; the rest of the description
  737. elaborates.
  738. Examples:
  739. encoding/rot13: new package
  740. math: add IsInf, IsNaN
  741. net: fix cname in LookupHost
  742. unicode: update to Unicode 5.0.2
  743. '''
  744. def promptremove(ui, repo, f):
  745. if promptyesno(ui, "hg remove %s (y/n)?" % (f,)):
  746. if commands.remove(ui, repo, 'path:'+f) != 0:
  747. ui.warn("error removing %s" % (f,))
  748. def promptadd(ui, repo, f):
  749. if promptyesno(ui, "hg add %s (y/n)?" % (f,)):
  750. if commands.add(ui, repo, 'path:'+f) != 0:
  751. ui.warn("error adding %s" % (f,))
  752. def EditCL(ui, repo, cl):
  753. set_status(None) # do not show status
  754. s = cl.EditorText()
  755. while True:
  756. s = ui.edit(s, ui.username())
  757. clx, line, err = ParseCL(s, cl.name)
  758. if err != '':
  759. if not promptyesno(ui, "error parsing change list: line %d: %s\nre-edit (y/n)?" % (line, err)):
  760. return "change list not modified"
  761. continue
  762. # Check description.
  763. if clx.desc == '':
  764. if promptyesno(ui, "change list should have a description\nre-edit (y/n)?"):
  765. continue
  766. elif re.search('<enter reason for undo>', clx.desc):
  767. if promptyesno(ui, "change list description omits reason for undo\nre-edit (y/n)?"):
  768. continue
  769. elif not re.match(desc_re, clx.desc.split('\n')[0]):
  770. if promptyesno(ui, desc_msg + "re-edit (y/n)?"):
  771. continue
  772. # Check file list for files that need to be hg added or hg removed
  773. # or simply aren't understood.
  774. pats = ['path:'+f for f in clx.files]
  775. modified, added, removed, deleted, unknown, ignored, clean = matchpats(ui, repo, pats, {})
  776. files = []
  777. for f in clx.files:
  778. if f in modified or f in added or f in removed:
  779. files.append(f)
  780. continue
  781. if f in deleted:
  782. promptremove(ui, repo, f)
  783. files.append(f)
  784. continue
  785. if f in unknown:
  786. promptadd(ui, repo, f)
  787. files.append(f)
  788. continue
  789. if f in ignored:
  790. ui.warn("error: %s is excluded by .hgignore; omitting\n" % (f,))
  791. continue
  792. if f in clean:
  793. ui.warn("warning: %s is listed in the CL but unchanged\n" % (f,))
  794. files.append(f)
  795. continue
  796. p = repo.root + '/' + f
  797. if os.path.isfile(p):
  798. ui.warn("warning: %s is a file but not known to hg\n" % (f,))
  799. files.append(f)
  800. continue
  801. if os.path.isdir(p):
  802. ui.warn("error: %s is a directory, not a file; omitting\n" % (f,))
  803. continue
  804. ui.warn("error: %s does not exist; omitting\n" % (f,))
  805. clx.files = files
  806. cl.desc = clx.desc
  807. cl.reviewer = clx.reviewer
  808. cl.cc = clx.cc
  809. cl.files = clx.files
  810. cl.private = clx.private
  811. break
  812. return ""
  813. # For use by submit, etc. (NOT by change)
  814. # Get change list number or list of files from command line.
  815. # If files are given, make a new change list.
  816. def CommandLineCL(ui, repo, pats, opts, defaultcc=None):
  817. if len(pats) > 0 and GoodCLName(pats[0]):
  818. if len(pats) != 1:
  819. return None, "cannot specify change number and file names"
  820. if opts.get('message'):
  821. return None, "cannot use -m with existing CL"
  822. cl, err = LoadCL(ui, repo, pats[0], web=True)
  823. if err != "":
  824. return None, err
  825. else:
  826. cl = CL("new")
  827. cl.local = True
  828. cl.files = ChangedFiles(ui, repo, pats, opts, taken=Taken(ui, repo))
  829. if not cl.files:
  830. return None, "no files changed"
  831. if opts.get('reviewer'):
  832. cl.reviewer = Add(cl.reviewer, SplitCommaSpace(opts.get('reviewer')))
  833. if opts.get('cc'):
  834. cl.cc = Add(cl.cc, SplitCommaSpace(opts.get('cc')))
  835. if defaultcc:
  836. cl.cc = Add(cl.cc, defaultcc)
  837. if cl.name == "new":
  838. if opts.get('message'):
  839. cl.desc = opts.get('message')
  840. else:
  841. err = EditCL(ui, repo, cl)
  842. if err != '':
  843. return None, err
  844. return cl, ""
  845. # reposetup replaces cmdutil.match with this wrapper,
  846. # which expands the syntax @clnumber to mean the files
  847. # in that CL.
  848. original_match = None
  849. def ReplacementForCmdutilMatch(repo, pats=None, opts=None, globbed=False, default='relpath'):
  850. taken = []
  851. files = []
  852. pats = pats or []
  853. opts = opts or {}
  854. for p in pats:
  855. if p.startswith('@'):
  856. taken.append(p)
  857. clname = p[1:]
  858. if not GoodCLName(clname):
  859. raise util.Abort("invalid CL name " + clname)
  860. cl, err = LoadCL(repo.ui, repo, clname, web=False)
  861. if err != '':
  862. raise util.Abort("loading CL " + clname + ": " + err)
  863. if not cl.files:
  864. raise util.Abort("no files in CL " + clname)
  865. files = Add(files, cl.files)
  866. pats = Sub(pats, taken) + ['path:'+f for f in files]
  867. # work-around for http://selenic.com/hg/rev/785bbc8634f8
  868. if hgversion >= '1.9' and not hasattr(repo, 'match'):
  869. repo = repo[None]
  870. return original_match(repo, pats=pats, opts=opts, globbed=globbed, default=default)
  871. def RelativePath(path, cwd):
  872. n = len(cwd)
  873. if path.startswith(cwd) and path[n] == '/':
  874. return path[n+1:]
  875. return path
  876. def CheckFormat(ui, repo, files, just_warn=False):
  877. set_status("running gofmt")
  878. CheckGofmt(ui, repo, files, just_warn)
  879. CheckTabfmt(ui, repo, files, just_warn)
  880. # Check that gofmt run on the list of files does not change them
  881. def CheckGofmt(ui, repo, files, just_warn):
  882. files = [f for f in files if (f.startswith('src/') or f.startswith('test/bench/')) and f.endswith('.go')]
  883. if not files:
  884. return
  885. cwd = os.getcwd()
  886. files = [RelativePath(repo.root + '/' + f, cwd) for f in files]
  887. files = [f for f in files if os.access(f, 0)]
  888. if not files:
  889. return
  890. try:
  891. cmd = subprocess.Popen(["gofmt", "-l"] + files, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=sys.platform != "win32")
  892. cmd.stdin.close()
  893. except:
  894. raise util.Abort("gofmt: " + ExceptionDetail())
  895. data = cmd.stdout.read()
  896. errors = cmd.stderr.read()
  897. cmd.wait()
  898. set_status("done with gofmt")
  899. if len(errors) > 0:
  900. ui.warn("gofmt errors:\n" + errors.rstrip() + "\n")
  901. return
  902. if len(data) > 0:
  903. msg = "gofmt needs to format these files (run hg gofmt):\n" + Indent(data, "\t").rstrip()
  904. if just_warn:
  905. ui.warn("warning: " + msg + "\n")
  906. else:
  907. raise util.Abort(msg)
  908. return
  909. # Check that *.[chys] files indent using tabs.
  910. def CheckTabfmt(ui, repo, files, just_warn):
  911. files = [f for f in files if f.startswith('src/') and re.search(r"\.[chys]$", f)]
  912. if not files:
  913. return
  914. cwd = os.getcwd()
  915. files = [RelativePath(repo.root + '/' + f, cwd) for f in files]
  916. files = [f for f in files if os.access(f, 0)]
  917. badfiles = []
  918. for f in files:
  919. try:
  920. for line in open(f, 'r'):
  921. # Four leading spaces is enough to complain about,
  922. # except that some Plan 9 code uses four spaces as the label indent,
  923. # so allow that.
  924. if line.startswith(' ') and not re.match(' [A-Za-z0-9_]+:', line):
  925. badfiles.append(f)
  926. break
  927. except:
  928. # ignore cannot open file, etc.
  929. pass
  930. if len(badfiles) > 0:
  931. msg = "these files use spaces for indentation (use tabs instead):\n\t" + "\n\t".join(badfiles)
  932. if just_warn:
  933. ui.warn("warning: " + msg + "\n")
  934. else:
  935. raise util.Abort(msg)
  936. return
  937. #######################################################################
  938. # Mercurial commands
  939. # every command must take a ui and and repo as arguments.
  940. # opts is a dict where you can find other command line flags
  941. #
  942. # Other parameters are taken in order from items on the command line that
  943. # don't start with a dash. If no default value is given in the parameter list,
  944. # they are required.
  945. #
  946. def change(ui, repo, *pats, **opts):
  947. """create, edit or delete a change list
  948. Create, edit or delete a change list.
  949. A change list is a group of files to be reviewed and submitted together,
  950. plus a textual description of the change.
  951. Change lists are referred to by simple alphanumeric names.
  952. Changes must be reviewed before they can be submitted.
  953. In the absence of options, the change command opens the
  954. change list for editing in the default editor.
  955. Deleting a change with the -d or -D flag does not affect
  956. the contents of the files listed in that change. To revert
  957. the files listed in a change, use
  958. hg revert @123456
  959. before running hg change -d 123456.
  960. """
  961. if missing_codereview:
  962. return missing_codereview
  963. dirty = {}
  964. if len(pats) > 0 and GoodCLName(pats[0]):
  965. name = pats[0]
  966. if len(pats) != 1:
  967. return "cannot specify CL name and file patterns"
  968. pats = pats[1:]
  969. cl, err = LoadCL(ui, repo, name, web=True)
  970. if err != '':
  971. return err
  972. if not cl.local and (opts["stdin"] or not opts["stdout"]):
  973. return "cannot change non-local CL " + name
  974. else:
  975. if repo[None].branch() != "default":
  976. return "cannot run hg change outside default branch"
  977. name = "new"
  978. cl = CL("new")
  979. dirty[cl] = True
  980. files = ChangedFiles(ui, repo, pats, opts, taken=Taken(ui, repo))
  981. if opts["delete"] or opts["deletelocal"]:
  982. if opts["delete"] and opts["deletelocal"]:
  983. return "cannot use -d and -D together"
  984. flag = "-d"
  985. if opts["deletelocal"]:
  986. flag = "-D"
  987. if name == "new":
  988. return "cannot use "+flag+" with file patterns"
  989. if opts["stdin"] or opts["stdout"]:
  990. return "cannot use "+flag+" with -i or -o"
  991. if not cl.local:
  992. return "cannot change non-local CL " + name
  993. if opts["delete"]:
  994. if cl.copied_from:
  995. return "original author must delete CL; hg change -D will remove locally"
  996. PostMessage(ui, cl.name, "*** Abandoned ***", send_mail=cl.mailed)
  997. EditDesc(cl.name, closed=True, private=cl.private)
  998. cl.Delete(ui, repo)
  999. return
  1000. if opts["stdin"]:
  1001. s = sys.stdin.read()
  1002. clx, line, err = ParseCL(s, name)
  1003. if err != '':
  1004. return "error parsing change list: line %d: %s" % (line, err)
  1005. if clx.desc is not None:
  1006. cl.desc = clx.desc;
  1007. dirty[cl] = True
  1008. if clx.reviewer is not None:
  1009. cl.reviewer = clx.reviewer
  1010. dirty[cl] = True
  1011. if clx.cc is not None:
  1012. cl.cc = clx.cc
  1013. dirty[cl] = True
  1014. if clx.files is not None:
  1015. cl.files = clx.files
  1016. dirty[cl] = True
  1017. if clx.private != cl.private:
  1018. cl.private = clx.private
  1019. dirty[cl] = True
  1020. if not opts["stdin"] and not opts["stdout"]:
  1021. if name == "new":
  1022. cl.files = files
  1023. err = EditCL(ui, repo, cl)
  1024. if err != "":
  1025. return err
  1026. dirty[cl] = True
  1027. for d, _ in dirty.items():
  1028. name = d.name
  1029. d.Flush(ui, repo)
  1030. if name == "new":
  1031. d.Upload(ui, repo, quiet=True)
  1032. if opts["stdout"]:
  1033. ui.write(cl.EditorText())
  1034. elif opts["pending"]:
  1035. ui.write(cl.PendingText())
  1036. elif name == "new":
  1037. if ui.quiet:
  1038. ui.write(cl.name)
  1039. else:
  1040. ui.write("CL created: " + cl.url + "\n")
  1041. return
  1042. def code_login(ui, repo, **opts):
  1043. """log in to code review server
  1044. Logs in to the code review server, saving a cookie in
  1045. a file in your home directory.
  1046. """
  1047. if missing_codereview:
  1048. return missing_codereview
  1049. MySend(None)
  1050. def clpatch(ui, repo, clname, **opts):
  1051. """import a patch from the code review server
  1052. Imports a patch from the code review server into the local client.
  1053. If the local client has already modified any of the files that the
  1054. patch modifies, this command will refuse to apply the patch.
  1055. Submitting an imported patch will keep the original author's
  1056. name as the Author: line but add your own name to a Committer: line.
  1057. """
  1058. if repo[None].branch() != "default":
  1059. return "cannot run hg clpatch outside default branch"
  1060. return clpatch_or_undo(ui, repo, clname, opts, mode="clpatch")
  1061. def undo(ui, repo, clname, **opts):
  1062. """undo the effect of a CL
  1063. Creates a new CL that undoes an earlier CL.
  1064. After creating the CL, opens the CL text for editing so that
  1065. you can add the reason for the undo to the description.
  1066. """
  1067. if repo[None].branch() != "default":
  1068. return "cannot run hg undo outside default branch"
  1069. return clpatch_or_undo(ui, repo, clname, opts, mode="undo")
  1070. def release_apply(ui, repo, clname, **opts):
  1071. """apply a CL to the release branch
  1072. Creates a new CL copying a previously committed change
  1073. from the main branch to the release branch.
  1074. The current client must either be clean or already be in
  1075. the release branch.
  1076. The release branch must be created by starting with a
  1077. clean client, disabling the code review plugin, and running:
  1078. hg update weekly.YYYY-MM-DD
  1079. hg branch release-branch.rNN
  1080. hg commit -m 'create release-branch.rNN'
  1081. hg push --new-branch
  1082. Then re-enable the code review plugin.
  1083. People can test the release branch by running
  1084. hg update release-branch.rNN
  1085. in a clean client. To return to the normal tree,
  1086. hg update default
  1087. Move changes since the weekly into the release branch
  1088. using hg release-apply followed by the usual code review
  1089. process and hg submit.
  1090. When it comes time to tag the release, record the
  1091. final long-form tag of the release-branch.rNN
  1092. in the *default* branch's .hgtags file. That is, run
  1093. hg update default
  1094. and then edit .hgtags as you would for a weekly.
  1095. """
  1096. c = repo[None]
  1097. if not releaseBranch:
  1098. return "no active release branches"
  1099. if c.branch() != releaseBranch:
  1100. if c.modified() or c.added() or c.removed():
  1101. raise util.Abort("uncommitted local changes - cannot switch branches")
  1102. err = hg.clean(repo, releaseBranch)
  1103. if err:
  1104. return err
  1105. try:
  1106. err = clpatch_or_undo(ui, repo, clname, opts, mode="backport")
  1107. if err:
  1108. raise util.Abort(err)
  1109. except Exception, e:
  1110. hg.clean(repo, "default")
  1111. raise e
  1112. return None
  1113. def rev2clname(rev):
  1114. # Extract CL name from revision description.
  1115. # The last line in the description that is a codereview URL is the real one.
  1116. # Earlier lines might be part of the user-written description.
  1117. all = re.findall('(?m)^http://codereview.appspot.com/([0-9]+)$', rev.description())
  1118. if len(all) > 0:
  1119. return all[-1]
  1120. return ""
  1121. undoHeader = """undo CL %s / %s
  1122. <enter reason for undo>
  1123. ««« original CL description
  1124. """
  1125. undoFooter = """
  1126. »»»
  1127. """
  1128. backportHeader = """[%s] %s
  1129. ««« CL %s / %s
  1130. """
  1131. backportFooter = """
  1132. »»»
  1133. """
  1134. # Implementation of clpatch/undo.
  1135. def clpatch_or_undo(ui, repo, clname, opts, mode):
  1136. if missing_codereview:
  1137. return missing_codereview
  1138. if mode == "undo" or mode == "backport":
  1139. if hgversion < '1.4':
  1140. # Don't have cmdutil.match (see implementation of sync command).
  1141. return "hg is too old to run hg %s - update to 1.4 or newer" % mode
  1142. # Find revision in Mercurial repository.
  1143. # Assume CL number is 7+ decimal digits.
  1144. # Otherwise is either change log sequence number (fewer decimal digits),
  1145. # hexadecimal hash, or tag name.
  1146. # Mercurial will fall over long before the change log
  1147. # sequence numbers get to be 7 digits long.
  1148. if re.match('^[0-9]{7,}$', clname):
  1149. found = False
  1150. matchfn = scmutil.match(repo, [], {'rev': None})
  1151. def prep(ctx, fns):
  1152. pass
  1153. for ctx in cmdutil.walkchangerevs(repo, matchfn, {'rev': None}, prep):
  1154. rev = repo[ctx.rev()]
  1155. # Last line with a code review URL is the actual review URL.
  1156. # Earlier ones might be part of the CL description.
  1157. n = rev2clname(rev)
  1158. if n == clname:
  1159. found = True
  1160. break
  1161. if not found:
  1162. return "cannot find CL %s in local repository" % clname
  1163. else:
  1164. rev = repo[clname]
  1165. if not rev:
  1166. return "unknown revision %s" % clname
  1167. clname = rev2clname(rev)
  1168. if clname == "":
  1169. return "cannot find CL name in revision description"
  1170. # Create fresh CL and start with patch that would reverse the change.
  1171. vers = short(rev.node())
  1172. cl = CL("new")
  1173. desc = str(rev.description())
  1174. if mode == "undo":
  1175. cl.desc = (undoHeader % (clname, vers)) + desc + undoFooter
  1176. else:
  1177. cl.desc = (backportHeader % (releaseBranch, line1(desc), clname, vers)) + desc + undoFooter
  1178. v1 = vers
  1179. v0 = short(rev.parents()[0].node())
  1180. if mode == "undo":
  1181. arg = v1 + ":" + v0
  1182. else:
  1183. vers = v0
  1184. arg = v0 + ":" + v1
  1185. patch = RunShell(["hg", "diff", "--git", "-r", arg])
  1186. else: # clpatch
  1187. cl, vers, patch, err = DownloadCL(ui, repo, clname)
  1188. if err != "":
  1189. return err
  1190. if patch == emptydiff:
  1191. return "codereview issue %s has no diff" % clname
  1192. # find current hg version (hg identify)
  1193. ctx = repo[None]
  1194. parents = ctx.parents()
  1195. id = '+'.join([short(p.node()) for p in parents])
  1196. # if version does not match the patch version,
  1197. # try to update the patch line numbers.
  1198. if vers != "" and id != vers:
  1199. # "vers in repo" gives the wrong answer
  1200. # on some versions of Mercurial. Instead, do the actual
  1201. # lookup and catch the exception.
  1202. try:
  1203. repo[vers].description()
  1204. except:
  1205. return "local repository is out of date; sync to get %s" % (vers)
  1206. patch1, err = portPatch(repo, patch, vers, id)
  1207. if err != "":
  1208. if not opts["ignore_hgpatch_failure"]:
  1209. return "codereview issue %s is out of date: %s (%s->%s)" % (clname, err, vers, id)
  1210. else:
  1211. patch = patch1
  1212. argv = ["hgpatch"]
  1213. if opts["no_incoming"] or mode == "backport":
  1214. argv += ["--checksync=false"]
  1215. try:
  1216. cmd = subprocess.Popen(argv, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None, close_fds=sys.platform != "win32")
  1217. except:
  1218. return "hgpatch: " + ExceptionDetail()
  1219. out, err = cmd.communicate(patch)
  1220. if cmd.returncode != 0 and not opts["ignore_hgpatch_failure"]:
  1221. return "hgpatch failed"
  1222. cl.local = True
  1223. cl.files = out.strip().split()
  1224. if not cl.files and not opts["ignore_hgpatch_failure"]:
  1225. return "codereview issue %s has no changed files" % clname
  1226. files = ChangedFiles(ui, repo, [], opts)
  1227. extra = Sub(cl.files, files)
  1228. if extra:
  1229. ui.warn("warning: these files were listed in the patch but not changed:\n\t" + "\n\t".join(extra) + "\n")
  1230. cl.Flush(ui, repo)
  1231. if mode == "undo":
  1232. err = EditCL(ui, repo, cl)
  1233. if err != "":
  1234. return "CL created, but error editing: " + err
  1235. cl.Flush(ui, repo)
  1236. else:
  1237. ui.write(cl.PendingText() + "\n")
  1238. # portPatch rewrites patch from being a patch against
  1239. # oldver to being a patch against newver.
  1240. def portPatch(repo, patch, oldver, newver):
  1241. lines = patch.splitlines(True) # True = keep \n
  1242. delta = None
  1243. for i in range(len(lines)):
  1244. line = lines[i]
  1245. if line.startswith('--- a/'):
  1246. file = line[6:-1]
  1247. delta = fileDeltas(repo, file, oldver, newver)
  1248. if not delta or not line.startswith('@@ '):
  1249. continue
  1250. # @@ -x,y +z,w @@ means the patch chunk replaces
  1251. # the original file's line numbers x up to x+y with the
  1252. # line numbers z up to z+w in the new file.
  1253. # Find the delta from x in the original to the same
  1254. # line in the current version and add that delta to both
  1255. # x and z.
  1256. m = re.match('@@ -([0-9]+),([0-9]+) \+([0-9]+),([0-9]+) @@', line)
  1257. if not m:
  1258. return None, "error parsing patch line numbers"
  1259. n1, len1, n2, len2 = int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))
  1260. d, err = lineDelta(delta, n1, len1)
  1261. if err != "":
  1262. return "", err
  1263. n1 += d
  1264. n2 += d
  1265. lines[i] = "@@ -%d,%d +%d,%d @@\n" % (n1, len1, n2, len2)
  1266. newpatch = ''.join(lines)
  1267. return newpatch, ""
  1268. # fileDelta returns the line number deltas for the given file's
  1269. # changes from oldver to newver.
  1270. # The deltas are a list of (n, len, newdelta) triples that say
  1271. # lines [n, n+len) were modified, and after that range the
  1272. # line numbers are +newdelta from what they were before.
  1273. def fileDeltas(repo, file, oldver, newver):
  1274. cmd = ["hg", "diff", "--git", "-r", oldver + ":" + newver, "path:" + file]
  1275. data = RunShell(cmd, silent_ok=True)
  1276. deltas = []
  1277. for line in data.splitlines():
  1278. m = re.match('@@ -([0-9]+),([0-9]+) \+([0-9]+),([0-9]+) @@', line)
  1279. if not m:
  1280. continue
  1281. n1, len1, n2, len2 = int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))
  1282. deltas.append((n1, len1, n2+len2-(n1+len1)))
  1283. return deltas
  1284. # lineDelta finds the appropriate line number delta to apply to the lines [n, n+len).
  1285. # It returns an error if those lines were rewritten by the patch.
  1286. def lineDelta(deltas, n, len):
  1287. d = 0
  1288. for (old, oldlen, newdelta) in deltas:
  1289. if old >= n+len:
  1290. break
  1291. if old+len > n:
  1292. return 0, "patch and recent changes conflict"
  1293. d = newdelta
  1294. return d, ""
  1295. def download(ui, repo, clname, **opts):
  1296. """download a change from the code review server
  1297. Download prints a description of the given change list
  1298. followed by its diff, downloaded from the code review server.
  1299. """
  1300. if missing_codereview:
  1301. return missing_codereview
  1302. cl, vers, patch, err = DownloadCL(ui, repo, clname)
  1303. if err != "":
  1304. return err
  1305. ui.write(cl.EditorText() + "\n")
  1306. ui.write(patch + "\n")
  1307. return
  1308. def file(ui, repo, clname, pat, *pats, **opts):
  1309. """assign files to or remove files from a change list
  1310. Assign files to or (with -d) remove files from a change list.
  1311. The -d option only removes files from the change list.
  1312. It does not edit them or remove them from the repository.
  1313. """
  1314. if missing_codereview:
  1315. return missing_codereview
  1316. pats = tuple([pat] + list(pats))
  1317. if not GoodCLName(clname):
  1318. return "invalid CL name " + clname
  1319. dirty = {}
  1320. cl, err = LoadCL(ui, repo, clname, web=False)
  1321. if err != '':
  1322. return err
  1323. if not cl.local:
  1324. return "cannot change non-local CL " + clname
  1325. files = ChangedFiles(ui, repo, pats, opts)
  1326. if opts["delete"]:
  1327. oldfiles = Intersect(files, cl.files)
  1328. if oldfiles:
  1329. if not ui.quiet:
  1330. ui.status("# Removing files from CL. To undo:\n")
  1331. ui.status("# cd %s\n" % (repo.root))
  1332. for f in oldfiles:
  1333. ui.status("# hg file %s %s\n" % (cl.name, f))
  1334. cl.files = Sub(cl.files, oldfiles)
  1335. cl.Flush(ui, repo)
  1336. else:
  1337. ui.status("no such files in CL")
  1338. return
  1339. if not files:
  1340. return "no such modified files"
  1341. files = Sub(files, cl.files)
  1342. taken = Taken(ui, repo)
  1343. warned = False
  1344. for f in files:
  1345. if f in taken:
  1346. if not warned and not ui.quiet:
  1347. ui.status("# Taking files from other CLs. To undo:\n")
  1348. ui.status("# cd %s\n" % (repo.root))
  1349. warned = True
  1350. ocl = taken[f]
  1351. if not ui.quiet:
  1352. ui.status("# hg file %s %s\n" % (ocl.name, f))
  1353. if ocl not in dirty:
  1354. ocl.files = Sub(ocl.files, files)
  1355. dirty[ocl] = True
  1356. cl.files = Add(cl.files, files)
  1357. dirty[cl] = True
  1358. for d, _ in dirty.items():
  1359. d.Flush(ui, repo)
  1360. return
  1361. def gofmt(ui, repo, *pats, **opts):
  1362. """apply gofmt to modified files
  1363. Applies gofmt to the modified files in the repository that match
  1364. the given patterns.
  1365. """
  1366. if missing_codereview:
  1367. return missing_codereview
  1368. files = ChangedExistingFiles(ui, repo, pats, opts)
  1369. files = [f for f in files if f.endswith(".go")]
  1370. if not files:
  1371. return "no modified go files"
  1372. cwd = os.getcwd()
  1373. files = [RelativePath(repo.root + '/' + f, cwd) for f in files]
  1374. try:
  1375. cmd = ["gofmt", "-l"]
  1376. if not opts["list"]:
  1377. cmd += ["-w"]
  1378. if os.spawnvp(os.P_WAIT, "gofmt", cmd + files) != 0:
  1379. raise util.Abort("gofmt did not exit cleanly")
  1380. except error.Abort, e:
  1381. raise
  1382. except:
  1383. raise util.Abort("gofmt: " + ExceptionDetail())
  1384. return
  1385. def mail(ui, repo, *pats, **opts):
  1386. """mail a change for review
  1387. Uploads a patch to the code review server and then sends mail
  1388. to the reviewer and CC list asking for a review.
  1389. """
  1390. if missing_codereview:
  1391. return missing_codereview
  1392. cl, err = CommandLineCL(ui, repo, pats, opts, defaultcc=defaultcc)
  1393. if err != "":
  1394. return err
  1395. cl.Upload(ui, repo, gofmt_just_warn=True)
  1396. if not cl.reviewer:
  1397. # If no reviewer is listed, assign the review to defaultcc.
  1398. # This makes sure that it appears in the
  1399. # codereview.appspot.com/user/defaultcc
  1400. # page, so that it doesn't get dropped on the floor.
  1401. if not defaultcc:
  1402. return "no reviewers listed in CL"
  1403. cl.cc = Sub(cl.cc, defaultcc)
  1404. cl.reviewer = defaultcc
  1405. cl.Flush(ui, repo)
  1406. if cl.files == []:
  1407. return "no changed files, not sending mail"
  1408. cl.Mail(ui, repo)
  1409. def pending(ui, repo, *pats, **opts):
  1410. """show pending changes
  1411. Lists pending changes followed by a list of unassigned but modified files.
  1412. """
  1413. if missing_codereview:
  1414. return missing_codereview
  1415. m = LoadAllCL(ui, repo, web=True)
  1416. names = m.keys()
  1417. names.sort()
  1418. for name in names:
  1419. cl = m[name]
  1420. ui.write(cl.PendingText() + "\n")
  1421. files = DefaultFiles(ui, repo, [], opts)
  1422. if len(files) > 0:
  1423. s = "Changed files not in any CL:\n"
  1424. for f in files:
  1425. s += "\t" + f + "\n"
  1426. ui.write(s)
  1427. def reposetup(ui, repo):
  1428. global original_match
  1429. if original_match is None:
  1430. start_status_thread()
  1431. original_match = scmutil.match
  1432. scmutil.match = ReplacementForCmdutilMatch
  1433. RietveldSetup(ui, repo)
  1434. def CheckContributor(ui, repo, user=None):
  1435. set_status("checking CONTRIBUTORS file")
  1436. user, userline = FindContributor(ui, repo, user, warn=False)
  1437. if not userline:
  1438. raise util.Abort("cannot find %s in CONTRIBUTORS" % (user,))
  1439. return userline
  1440. def FindContributor(ui, repo, user=None, warn=True):
  1441. if not user:
  1442. user = ui.config("ui", "username")
  1443. if not user:
  1444. raise util.Abort("[ui] username is not configured in .hgrc")
  1445. user = user.lower()
  1446. m = re.match(r".*<(.*)>", user)
  1447. if m:
  1448. user = m.group(1)
  1449. if user not in contributors:
  1450. if warn:
  1451. ui.warn("warning: cannot find %s in CONTRIBUTORS\n" % (user,))
  1452. return user, None
  1453. user, email = contributors[user]
  1454. return email, "%s <%s>" % (user, email)
  1455. def submit(ui, repo, *pats, **opts):
  1456. """submit change to remote repository
  1457. Submits change to remote repository.
  1458. Bails out if the local repository is not in sync with the remote one.
  1459. """
  1460. if missing_codereview:
  1461. return missing_codereview
  1462. # We already called this on startup but sometimes Mercurial forgets.
  1463. set_mercurial_encoding_to_utf8()
  1464. repo.ui.quiet = True
  1465. if not opts["no_incoming"] and Incoming(ui, repo, opts):
  1466. return "local repository out of date; must sync before submit"
  1467. cl, err = CommandLineCL(ui, repo, pats, opts, defaultcc=defaultcc)
  1468. if err != "":
  1469. return err
  1470. user = None
  1471. if cl.copied_from:
  1472. user = cl.copied_from
  1473. userline = CheckContributor(ui, repo, user)
  1474. typecheck(userline, str)
  1475. about = ""
  1476. if cl.reviewer:
  1477. about += "R=" + JoinComma([CutDomain(s) for s in cl.reviewer]) + "\n"
  1478. if opts.get('tbr'):
  1479. tbr = SplitCommaSpace(opts.get('tbr'))
  1480. cl.reviewer = Add(cl.reviewer, tbr)
  1481. about += "TBR=" + JoinComma([CutDomain(s) for s in tbr]) + "\n"
  1482. if cl.cc:
  1483. about += "CC=" + JoinComma([CutDomain(s) for s in cl.cc]) + "\n"
  1484. if not cl.reviewer:
  1485. return "no reviewers listed in CL"
  1486. if not cl.local:
  1487. return "cannot submit non-local CL"
  1488. # upload, to sync current patch and also get change number if CL is new.
  1489. if not cl.copied_from:
  1490. cl.Upload(ui, repo, gofmt_just_warn=True)
  1491. # check gofmt for real; allowed upload to warn in order to save CL.
  1492. cl.Flush(ui, repo)
  1493. CheckFormat(ui, repo, cl.files)
  1494. about += "%s%s\n" % (server_url_base, cl.name)
  1495. if cl.copied_from:
  1496. about += "\nCommitter: " + CheckContributor(ui, repo, None) + "\n"
  1497. typecheck(about, str)
  1498. if not cl.mailed and not cl.copied_from: # in case this is TBR
  1499. cl.Mail(ui, repo)
  1500. # submit changes locally
  1501. date = opts.get('date')
  1502. if date:
  1503. opts['date'] = util.parsedate(date)
  1504. typecheck(opts['date'], str)
  1505. opts['message'] = cl.desc.rstrip() + "\n\n" + about
  1506. typecheck(opts['message'], str)
  1507. if opts['dryrun']:
  1508. print "NOT SUBMITTING:"
  1509. print "User: ", userline
  1510. print "Message:"
  1511. print Indent(opts['message'], "\t")
  1512. print "Files:"
  1513. print Indent('\n'.join(cl.files), "\t")
  1514. return "dry run; not submitted"
  1515. m = match.exact(repo.root, repo.getcwd(), cl.files)
  1516. node = repo.commit(ustr(opts['message']), ustr(userline), opts.get('date'), m)
  1517. if not node:
  1518. return "nothing changed"
  1519. # push to remote; if it fails for any reason, roll back
  1520. try:
  1521. log = repo.changelog
  1522. rev = log.rev(node)
  1523. parents = log.parentrevs(rev)
  1524. if (rev-1 not in parents and
  1525. (parents == (nullrev, nullrev) or
  1526. len(log.heads(log.node(parents[0]))) > 1 and
  1527. (parents[1] == nullrev or len(log.heads(log.node(parents[1]))) > 1))):
  1528. # created new head
  1529. raise util.Abort("local repository out of date; must sync before submit")
  1530. # push changes to remote.
  1531. # if it works, we're committed.
  1532. # if not, roll back
  1533. other = getremote(ui, repo, opts)
  1534. r = repo.push(other, False, None)
  1535. if r == 0:
  1536. raise util.Abort("local repository out of date; must sync before submit")
  1537. except:
  1538. real_rollback()
  1539. raise
  1540. # we're committed. upload final patch, close review, add commit message
  1541. changeURL = short(node)
  1542. url = other.url()
  1543. m = re.match("^https?://([^@/]+@)?([^.]+)\.googlecode\.com/hg/?", url)
  1544. if m:
  1545. changeURL = "http://code.google.com/p/%s/source/detail?r=%s" % (m.group(2), changeURL)
  1546. else:
  1547. print >>sys.stderr, "URL: ", url
  1548. pmsg = "*** Submitted as " + changeURL + " ***\n\n" + opts['message']
  1549. # When posting, move reviewers to CC line,
  1550. # so that the issue stops showing up in their "My Issues" page.
  1551. PostMessage(ui, cl.name, pmsg, reviewers="", cc=JoinComma(cl.reviewer+cl.cc))
  1552. if not cl.copied_from:
  1553. EditDesc(cl.name, closed=True, private=cl.private)
  1554. cl.Delete(ui, repo)
  1555. c = repo[None]
  1556. if c.branch() == releaseBranch and not c.modified() and not c.added() and not c.removed():
  1557. ui.write("switching from %s to default branch.\n" % releaseBranch)
  1558. err = hg.clean(repo, "default")
  1559. if err:
  1560. return err
  1561. return None
  1562. def sync(ui, repo, **opts):
  1563. """synchronize with remote repository
  1564. Incorporates recent changes from the remote repository
  1565. into the local repository.
  1566. """
  1567. if missing_codereview:
  1568. return missing_codereview
  1569. if not opts["local"]:
  1570. ui.status = sync_note
  1571. ui.note = sync_note
  1572. other = getremote(ui, repo, opts)
  1573. modheads = repo.pull(other)
  1574. err = commands.postincoming(ui, repo, modheads, True, "tip")
  1575. if err:
  1576. return err
  1577. commands.update(ui, repo, rev="default")
  1578. sync_changes(ui, repo)
  1579. def sync_note(msg):
  1580. # we run sync (pull -u) in verbose mode to get the
  1581. # list of files being updated, but that drags along
  1582. # a bunch of messages we don't care about.
  1583. # omit them.
  1584. if msg == 'resolving manifests\n':
  1585. return
  1586. if msg == 'searching for changes\n':
  1587. return
  1588. if msg == "couldn't find merge tool hgmerge\n":
  1589. return
  1590. sys.stdout.write(msg)
  1591. def sync_changes(ui, repo):
  1592. # Look through recent change log descriptions to find
  1593. # potential references to http://.*/our-CL-number.
  1594. # Double-check them by looking at the Rietveld log.
  1595. def Rev(rev):
  1596. desc = repo[rev].description().strip()
  1597. for clname in re.findall('(?m)^http://(?:[^\n]+)/([0-9]+)$', desc):
  1598. if IsLocalCL(ui, repo, clname) and IsRietveldSubmitted(ui, clname, repo[rev].hex()):
  1599. ui.warn("CL %s submitted as %s; closing\n" % (clname, repo[rev]))
  1600. cl, err = LoadCL(ui, repo, clname, web=False)
  1601. if err != "":
  1602. ui.warn("loading CL %s: %s\n" % (clname, err))
  1603. continue
  1604. if not cl.copied_from:
  1605. EditDesc(cl.name, closed=True, private=cl.private)
  1606. cl.Delete(ui, repo)
  1607. if hgversion < '1.4':
  1608. get = util.cachefunc(lambda r: repo[r].changeset())
  1609. changeiter, matchfn = cmdutil.walkchangerevs(ui, repo, [], get, {'rev': None})
  1610. n = 0
  1611. for st, rev, fns in changeiter:
  1612. if st != 'iter':
  1613. continue
  1614. n += 1
  1615. if n > 100:
  1616. break
  1617. Rev(rev)
  1618. else:
  1619. matchfn = scmutil.match(repo, [], {'rev': None})
  1620. def prep(ctx, fns):
  1621. pass
  1622. for ctx in cmdutil.walkchangerevs(repo, matchfn, {'rev': None}, prep):
  1623. Rev(ctx.rev())
  1624. # Remove files that are not modified from the CLs in which they appear.
  1625. all = LoadAllCL(ui, repo, web=False)
  1626. changed = ChangedFiles(ui, repo, [], {})
  1627. for _, cl in all.items():
  1628. extra = Sub(cl.files, changed)
  1629. if extra:
  1630. ui.warn("Removing unmodified files from CL %s:\n" % (cl.name,))
  1631. for f in extra:
  1632. ui.warn("\t%s\n" % (f,))
  1633. cl.files = Sub(cl.files, extra)
  1634. cl.Flush(ui, repo)
  1635. if not cl.files:
  1636. if not cl.copied_from:
  1637. ui.warn("CL %s has no files; delete (abandon) with hg change -d %s\n" % (cl.name, cl.name))
  1638. else:
  1639. ui.warn("CL %s has no files; delete locally with hg change -D %s\n" % (cl.name, cl.name))
  1640. return
  1641. def upload(ui, repo, name, **opts):
  1642. """upload diffs to the code review server
  1643. Uploads the current modifications for a given change to the server.
  1644. """
  1645. if missing_codereview:
  1646. return missing_codereview
  1647. repo.ui.quiet = True
  1648. cl, err = LoadCL(ui, repo, name, web=True)
  1649. if err != "":
  1650. return err
  1651. if not cl.local:
  1652. return "cannot upload non-local change"
  1653. cl.Upload(ui, repo)
  1654. print "%s%s\n" % (server_url_base, cl.name)
  1655. return
  1656. review_opts = [
  1657. ('r', 'reviewer', '', 'add reviewer'),
  1658. ('', 'cc', '', 'add cc'),
  1659. ('', 'tbr', '', 'add future reviewer'),
  1660. ('m', 'message', '', 'change description (for new change)'),
  1661. ]
  1662. cmdtable = {
  1663. # The ^ means to show this command in the help text that
  1664. # is printed when running hg with no arguments.
  1665. "^change": (
  1666. change,
  1667. [
  1668. ('d', 'delete', None, 'delete existing change list'),
  1669. ('D', 'deletelocal', None, 'delete locally, but do not change CL on server'),
  1670. ('i', 'stdin', None, 'read change list from standard input'),
  1671. ('o', 'stdout', None, 'print change list to standard output'),
  1672. ('p', 'pending', None, 'print pending summary to standard output'),
  1673. ],
  1674. "[-d | -D] [-i] [-o] change# or FILE ..."
  1675. ),
  1676. "^clpatch": (
  1677. clpatch,
  1678. [
  1679. ('', 'ignore_hgpatch_failure', None, 'create CL metadata even if hgpatch fails'),
  1680. ('', 'no_incoming', None, 'disable check for incoming changes'),
  1681. ],
  1682. "change#"
  1683. ),
  1684. # Would prefer to call this codereview-login, but then
  1685. # hg help codereview prints the help for this command
  1686. # instead of the help for the extension.
  1687. "code-login": (
  1688. code_login,
  1689. [],
  1690. "",
  1691. ),
  1692. "^download": (
  1693. download,
  1694. [],
  1695. "change#"
  1696. ),
  1697. "^file": (
  1698. file,
  1699. [
  1700. ('d', 'delete', None, 'delete files from change list (but not repository)'),
  1701. ],
  1702. "[-d] change# FILE ..."
  1703. ),
  1704. "^gofmt": (
  1705. gofmt,
  1706. [
  1707. ('l', 'list', None, 'list files that would change, but do not edit them'),
  1708. ],
  1709. "FILE ..."
  1710. ),
  1711. "^pending|p": (
  1712. pending,
  1713. [],
  1714. "[FILE ...]"
  1715. ),
  1716. "^mail": (
  1717. mail,
  1718. review_opts + [
  1719. ] + commands.walkopts,
  1720. "[-r reviewer] [--cc cc] [change# | file ...]"
  1721. ),
  1722. "^release-apply": (
  1723. release_apply,
  1724. [
  1725. ('', 'ignore_hgpatch_failure', None, 'create CL metadata even if hgpatch fails'),
  1726. ('', 'no_incoming', None, 'disable check for incoming changes'),
  1727. ],
  1728. "change#"
  1729. ),
  1730. # TODO: release-start, release-tag, weekly-tag
  1731. "^submit": (
  1732. submit,
  1733. review_opts + [
  1734. ('', 'no_incoming', None, 'disable initial incoming check (for testing)'),
  1735. ('n', 'dryrun', None, 'make change only locally (for testing)'),
  1736. ] + commands.walkopts + commands.commitopts + commands.commitopts2,
  1737. "[-r reviewer] [--cc cc] [change# | file ...]"
  1738. ),
  1739. "^sync": (
  1740. sync,
  1741. [
  1742. ('', 'local', None, 'do not pull changes from remote repository')
  1743. ],
  1744. "[--local]",
  1745. ),
  1746. "^undo": (
  1747. undo,
  1748. [
  1749. ('', 'ignore_hgpatch_failure', None, 'create CL metadata even if hgpatch fails'),
  1750. ('', 'no_incoming', None, 'disable check for incoming changes'),
  1751. ],
  1752. "change#"
  1753. ),
  1754. "^upload": (
  1755. upload,
  1756. [],
  1757. "change#"
  1758. ),
  1759. }
  1760. #######################################################################
  1761. # Wrappers around upload.py for interacting with Rietveld
  1762. # HTML form parser
  1763. class FormParser(HTMLParser):
  1764. def __init__(self):
  1765. self.map = {}
  1766. self.curtag = None
  1767. self.curdata = None
  1768. HTMLParser.__init__(self)
  1769. def handle_starttag(self, tag, attrs):
  1770. if tag == "input":
  1771. key = None
  1772. value = ''
  1773. for a in attrs:
  1774. if a[0] == 'name':
  1775. key = a[1]
  1776. if a[0] == 'value':
  1777. value = a[1]
  1778. if key is not None:
  1779. self.map[key] = value
  1780. if tag == "textarea":
  1781. key = None
  1782. for a in attrs:
  1783. if a[0] == 'name':
  1784. key = a[1]
  1785. if key is not None:
  1786. self.curtag = key
  1787. self.curdata = ''
  1788. def handle_endtag(self, tag):
  1789. if tag == "textarea" and self.curtag is not None:
  1790. self.map[self.curtag] = self.curdata
  1791. self.curtag = None
  1792. self.curdata = None
  1793. def handle_charref(self, name):
  1794. self.handle_data(unichr(int(name)))
  1795. def handle_entityref(self, name):
  1796. import htmlentitydefs
  1797. if name in htmlentitydefs.entitydefs:
  1798. self.handle_data(htmlentitydefs.entitydefs[name])
  1799. else:
  1800. self.handle_data("&" + name + ";")
  1801. def handle_data(self, data):
  1802. if self.curdata is not None:
  1803. self.curdata += data
  1804. def JSONGet(ui, path):
  1805. try:
  1806. data = MySend(path, force_auth=False)
  1807. typecheck(data, str)
  1808. d = fix_json(json.loads(data))
  1809. except:
  1810. ui.warn("JSONGet %s: %s\n" % (path, ExceptionDetail()))
  1811. return None
  1812. return d
  1813. # Clean up json parser output to match our expectations:
  1814. # * all strings are UTF-8-encoded str, not unicode.
  1815. # * missing fields are missing, not None,
  1816. # so that d.get("foo", defaultvalue) works.
  1817. def fix_json(x):
  1818. if type(x) in [str, int, float, bool, type(None)]:
  1819. pass
  1820. elif type(x) is unicode:
  1821. x = x.encode("utf-8")
  1822. elif type(x) is list:
  1823. for i in range(len(x)):
  1824. x[i] = fix_json(x[i])
  1825. elif type(x) is dict:
  1826. todel = []
  1827. for k in x:
  1828. if x[k] is None:
  1829. todel.append(k)
  1830. else:
  1831. x[k] = fix_json(x[k])
  1832. for k in todel:
  1833. del x[k]
  1834. else:
  1835. raise util.Abort("unknown type " + str(type(x)) + " in fix_json")
  1836. if type(x) is str:
  1837. x = x.replace('\r\n', '\n')
  1838. return x
  1839. def IsRietveldSubmitted(ui, clname, hex):
  1840. dict = JSONGet(ui, "/api/" + clname + "?messages=true")
  1841. if dict is None:
  1842. return False
  1843. for msg in dict.get("messages", []):
  1844. text = msg.get("text", "")
  1845. m = re.match('\*\*\* Submitted as [^*]*?([0-9a-f]+) \*\*\*', text)
  1846. if m is not None and len(m.group(1)) >= 8 and hex.startswith(m.group(1)):
  1847. return True
  1848. return False
  1849. def IsRietveldMailed(cl):
  1850. for msg in cl.dict.get("messages", []):
  1851. if msg.get("text", "").find("I'd like you to review this change") >= 0:
  1852. return True
  1853. return False
  1854. def DownloadCL(ui, repo, clname):
  1855. set_status("downloading CL " + clname)
  1856. cl, err = LoadCL(ui, repo, clname, web=True)
  1857. if err != "":
  1858. return None, None, None, "error loading CL %s: %s" % (clname, err)
  1859. # Find most recent diff
  1860. diffs = cl.dict.get("patchsets", [])
  1861. if not diffs:
  1862. return None, None, None, "CL has no patch sets"
  1863. patchid = diffs[-1]
  1864. patchset = JSONGet(ui, "/api/" + clname + "/" + str(patchid))
  1865. if patchset is None:
  1866. return None, None, None, "error loading CL patchset %s/%d" % (clname, patchid)
  1867. if patchset.get("patchset", 0) != patchid:
  1868. return None, None, None, "malformed patchset information"
  1869. vers = ""
  1870. msg = patchset.get("message", "").split()
  1871. if len(msg) >= 3 and msg[0] == "diff" and msg[1] == "-r":
  1872. vers = msg[2]
  1873. diff = "/download/issue" + clname + "_" + str(patchid) + ".diff"
  1874. diffdata = MySend(diff, force_auth=False)
  1875. # Print warning if email is not in CONTRIBUTORS file.
  1876. email = cl.dict.get("owner_email", "")
  1877. if not email:
  1878. return None, None, None, "cannot find owner for %s" % (clname)
  1879. him = FindContributor(ui, repo, email)
  1880. me = FindContributor(ui, repo, None)
  1881. if him == me:
  1882. cl.mailed = IsRietveldMailed(cl)
  1883. else:
  1884. cl.copied_from = email
  1885. return cl, vers, diffdata, ""
  1886. def MySend(request_path, payload=None,
  1887. content_type="application/octet-stream",
  1888. timeout=None, force_auth=True,
  1889. **kwargs):
  1890. """Run MySend1 maybe twice, because Rietveld is unreliable."""
  1891. try:
  1892. return MySend1(request_path, payload, content_type, timeout, force_auth, **kwargs)
  1893. except Exception, e:
  1894. if type(e) != urllib2.HTTPError or e.code != 500: # only retry on HTTP 500 error
  1895. raise
  1896. print >>sys.stderr, "Loading "+request_path+": "+ExceptionDetail()+"; trying again in 2 seconds."
  1897. time.sleep(2)
  1898. return MySend1(request_path, payload, content_type, timeout, force_auth, **kwargs)
  1899. # Like upload.py Send but only authenticates when the
  1900. # redirect is to www.google.com/accounts. This keeps
  1901. # unnecessary redirects from happening during testing.
  1902. def MySend1(request_path, payload=None,
  1903. content_type="application/octet-stream",
  1904. timeout=None, force_auth=True,
  1905. **kwargs):
  1906. """Sends an RPC and returns the response.
  1907. Args:
  1908. request_path: The path to send the request to, eg /api/appversion/create.
  1909. payload: The body of the request, or None to send an empty request.
  1910. content_type: The Content-Type header to use.
  1911. timeout: timeout in seconds; default None i.e. no timeout.
  1912. (Note: for large requests on OS X, the timeout doesn't work right.)
  1913. kwargs: Any keyword arguments are converted into query string parameters.
  1914. Returns:
  1915. The response body, as a string.
  1916. """
  1917. # TODO: Don't require authentication. Let the server say
  1918. # whether it is necessary.
  1919. global rpc
  1920. if rpc == None:
  1921. rpc = GetRpcServer(upload_options)
  1922. self = rpc
  1923. if not self.authenticated and force_auth:
  1924. self._Authenticate()
  1925. if request_path is None:
  1926. return
  1927. old_timeout = socket.getdefaulttimeout()
  1928. socket.setdefaulttimeout(timeout)
  1929. try:
  1930. tries = 0
  1931. while True:
  1932. tries += 1
  1933. args = dict(kwargs)
  1934. url = "http://%s%s" % (self.host, request_path)
  1935. if args:
  1936. url += "?" + urllib.urlencode(args)
  1937. req = self._CreateRequest(url=url, data=payload)
  1938. req.add_header("Content-Type", content_type)
  1939. try:
  1940. f = self.opener.open(req)
  1941. response = f.read()
  1942. f.close()
  1943. # Translate \r\n into \n, because Rietveld doesn't.
  1944. response = response.replace('\r\n', '\n')
  1945. # who knows what urllib will give us
  1946. if type(response) == unicode:
  1947. response = response.encode("utf-8")
  1948. typecheck(response, str)
  1949. return response
  1950. except urllib2.HTTPError, e:
  1951. if tries > 3:
  1952. raise
  1953. elif e.code == 401:
  1954. self._Authenticate()
  1955. elif e.code == 302:
  1956. loc = e.info()["location"]
  1957. if not loc.startswith('https://www.google.com/a') or loc.find('/ServiceLogin') < 0:
  1958. return ''
  1959. self._Authenticate()
  1960. else:
  1961. raise
  1962. finally:
  1963. socket.setdefaulttimeout(old_timeout)
  1964. def GetForm(url):
  1965. f = FormParser()
  1966. f.feed(ustr(MySend(url))) # f.feed wants unicode
  1967. f.close()
  1968. # convert back to utf-8 to restore sanity
  1969. m = {}
  1970. for k,v in f.map.items():
  1971. m[k.encode("utf-8")] = v.replace("\r\n", "\n").encode("utf-8")
  1972. return m
  1973. def EditDesc(issue, subject=None, desc=None, reviewers=None, cc=None, closed=False, private=False):
  1974. set_status("uploading change to description")
  1975. form_fields = GetForm("/" + issue + "/edit")
  1976. if subject is not None:
  1977. form_fields['subject'] = subject
  1978. if desc is not None:
  1979. form_fields['description'] = desc
  1980. if reviewers is not None:
  1981. form_fields['reviewers'] = reviewers
  1982. if cc is not None:
  1983. form_fields['cc'] = cc
  1984. if closed:
  1985. form_fields['closed'] = "checked"
  1986. if private:
  1987. form_fields['private'] = "checked"
  1988. ctype, body = EncodeMultipartFormData(form_fields.items(), [])
  1989. response = MySend("/" + issue + "/edit", body, content_type=ctype)
  1990. if response != "":
  1991. print >>sys.stderr, "Error editing description:\n" + "Sent form: \n", form_fields, "\n", response
  1992. sys.exit(2)
  1993. def PostMessage(ui, issue, message, reviewers=None, cc=None, send_mail=True, subject=None):
  1994. set_status("uploading message")
  1995. form_fields = GetForm("/" + issue + "/publish")
  1996. if reviewers is not None:
  1997. form_fields['reviewers'] = reviewers
  1998. if cc is not None:
  1999. form_fields['cc'] = cc
  2000. if send_mail:
  2001. form_fields['send_mail'] = "checked"
  2002. else:
  2003. del form_fields['send_mail']
  2004. if subject is not None:
  2005. form_fields['subject'] = subject
  2006. form_fields['message'] = message
  2007. form_fields['message_only'] = '1' # Don't include draft comments
  2008. if reviewers is not None or cc is not None:
  2009. form_fields['message_only'] = '' # Must set '' in order to override cc/reviewer
  2010. ctype = "applications/x-www-form-urlencoded"
  2011. body = urllib.urlencode(form_fields)
  2012. response = MySend("/" + issue + "/publish", body, content_type=ctype)
  2013. if response != "":
  2014. print response
  2015. sys.exit(2)
  2016. class opt(object):
  2017. pass
  2018. def nocommit(*pats, **opts):
  2019. """(disabled when using this extension)"""
  2020. raise util.Abort("codereview extension enabled; use mail, upload, or submit instead of commit")
  2021. def nobackout(*pats, **opts):
  2022. """(disabled when using this extension)"""
  2023. raise util.Abort("codereview extension enabled; use undo instead of backout")
  2024. def norollback(*pats, **opts):
  2025. """(disabled when using this extension)"""
  2026. raise util.Abort("codereview extension enabled; use undo instead of rollback")
  2027. def RietveldSetup(ui, repo):
  2028. global defaultcc, upload_options, rpc, server, server_url_base, force_google_account, verbosity, contributors
  2029. global missing_codereview
  2030. repo_config_path = ''
  2031. # Read repository-specific options from lib/codereview/codereview.cfg
  2032. try:
  2033. repo_config_path = repo.root + '/lib/codereview/codereview.cfg'
  2034. f = open(repo_config_path)
  2035. for line in f:
  2036. if line.startswith('defaultcc: '):
  2037. defaultcc = SplitCommaSpace(line[10:])
  2038. except:
  2039. # If there are no options, chances are good this is not
  2040. # a code review repository; stop now before we foul
  2041. # things up even worse. Might also be that repo doesn't
  2042. # even have a root. See issue 959.
  2043. if repo_config_path == '':
  2044. missing_codereview = 'codereview disabled: repository has no root'
  2045. else:
  2046. missing_codereview = 'codereview disabled: cannot open ' + repo_config_path
  2047. return
  2048. # Should only modify repository with hg submit.
  2049. # Disable the built-in Mercurial commands that might
  2050. # trip things up.
  2051. cmdutil.commit = nocommit
  2052. global real_rollback
  2053. real_rollback = repo.rollback
  2054. repo.rollback = norollback
  2055. # would install nobackout if we could; oh well
  2056. try:
  2057. f = open(repo.root + '/CONTRIBUTORS', 'r')
  2058. except:
  2059. raise util.Abort("cannot open %s: %s" % (repo.root+'/CONTRIBUTORS', ExceptionDetail()))
  2060. for line in f:
  2061. # CONTRIBUTORS is a list of lines like:
  2062. # Person <email>
  2063. # Person <email> <alt-email>
  2064. # The first email address is the one used in commit logs.
  2065. if line.startswith('#'):
  2066. continue
  2067. m = re.match(r"([^<>]+\S)\s+(<[^<>\s]+>)((\s+<[^<>\s]+>)*)\s*$", line)
  2068. if m:
  2069. name = m.group(1)
  2070. email = m.group(2)[1:-1]
  2071. contributors[email.lower()] = (name, email)
  2072. for extra in m.group(3).split():
  2073. contributors[extra[1:-1].lower()] = (name, email)
  2074. if not ui.verbose:
  2075. verbosity = 0
  2076. # Config options.
  2077. x = ui.config("codereview", "server")
  2078. if x is not None:
  2079. server = x
  2080. # TODO(rsc): Take from ui.username?
  2081. email = None
  2082. x = ui.config("codereview", "email")
  2083. if x is not None:
  2084. email = x
  2085. server_url_base = "http://" + server + "/"
  2086. testing = ui.config("codereview", "testing")
  2087. force_google_account = ui.configbool("codereview", "force_google_account", False)
  2088. upload_options = opt()
  2089. upload_options.email = email
  2090. upload_options.host = None
  2091. upload_options.verbose = 0
  2092. upload_options.description = None
  2093. upload_options.description_file = None
  2094. upload_options.reviewers = None
  2095. upload_options.cc = None
  2096. upload_options.message = None
  2097. upload_options.issue = None
  2098. upload_options.download_base = False
  2099. upload_options.revision = None
  2100. upload_options.send_mail = False
  2101. upload_options.vcs = None
  2102. upload_options.server = server
  2103. upload_options.save_cookies = True
  2104. if testing:
  2105. upload_options.save_cookies = False
  2106. upload_options.email = "test@example.com"
  2107. rpc = None
  2108. global releaseBranch
  2109. tags = repo.branchtags().keys()
  2110. if 'release-branch.r100' in tags:
  2111. # NOTE(rsc): This tags.sort is going to get the wrong
  2112. # answer when comparing release-branch.r99 with
  2113. # release-branch.r100. If we do ten releases a year
  2114. # that gives us 4 years before we have to worry about this.
  2115. raise util.Abort('tags.sort needs to be fixed for release-branch.r100')
  2116. tags.sort()
  2117. for t in tags:
  2118. if t.startswith('release-branch.'):
  2119. releaseBranch = t
  2120. #######################################################################
  2121. # http://codereview.appspot.com/static/upload.py, heavily edited.
  2122. #!/usr/bin/env python
  2123. #
  2124. # Copyright 2007 Google Inc.
  2125. #
  2126. # Licensed under the Apache License, Version 2.0 (the "License");
  2127. # you may not use this file except in compliance with the License.
  2128. # You may obtain a copy of the License at
  2129. #
  2130. # http://www.apache.org/licenses/LICENSE-2.0
  2131. #
  2132. # Unless required by applicable law or agreed to in writing, software
  2133. # distributed under the License is distributed on an "AS IS" BASIS,
  2134. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  2135. # See the License for the specific language governing permissions and
  2136. # limitations under the License.
  2137. """Tool for uploading diffs from a version control system to the codereview app.
  2138. Usage summary: upload.py [options] [-- diff_options]
  2139. Diff options are passed to the diff command of the underlying system.
  2140. Supported version control systems:
  2141. Git
  2142. Mercurial
  2143. Subversion
  2144. It is important for Git/Mercurial users to specify a tree/node/branch to diff
  2145. against by using the '--rev' option.
  2146. """
  2147. # This code is derived from appcfg.py in the App Engine SDK (open source),
  2148. # and from ASPN recipe #146306.
  2149. import cookielib
  2150. import getpass
  2151. import logging
  2152. import mimetypes
  2153. import optparse
  2154. import os
  2155. import re
  2156. import socket
  2157. import subprocess
  2158. import sys
  2159. import urllib
  2160. import urllib2
  2161. import urlparse
  2162. # The md5 module was deprecated in Python 2.5.
  2163. try:
  2164. from hashlib import md5
  2165. except ImportError:
  2166. from md5 import md5
  2167. try:
  2168. import readline
  2169. except ImportError:
  2170. pass
  2171. # The logging verbosity:
  2172. # 0: Errors only.
  2173. # 1: Status messages.
  2174. # 2: Info logs.
  2175. # 3: Debug logs.
  2176. verbosity = 1
  2177. # Max size of patch or base file.
  2178. MAX_UPLOAD_SIZE = 900 * 1024
  2179. # whitelist for non-binary filetypes which do not start with "text/"
  2180. # .mm (Objective-C) shows up as application/x-freemind on my Linux box.
  2181. TEXT_MIMETYPES = [
  2182. 'application/javascript',
  2183. 'application/x-javascript',
  2184. 'application/x-freemind'
  2185. ]
  2186. def GetEmail(prompt):
  2187. """Prompts the user for their email address and returns it.
  2188. The last used email address is saved to a file and offered up as a suggestion
  2189. to the user. If the user presses enter without typing in anything the last
  2190. used email address is used. If the user enters a new address, it is saved
  2191. for next time we prompt.
  2192. """
  2193. last_email_file_name = os.path.expanduser("~/.last_codereview_email_address")
  2194. last_email = ""
  2195. if os.path.exists(last_email_file_name):
  2196. try:
  2197. last_email_file = open(last_email_file_name, "r")
  2198. last_email = last_email_file.readline().strip("\n")
  2199. last_email_file.close()
  2200. prompt += " [%s]" % last_email
  2201. except IOError, e:
  2202. pass
  2203. email = raw_input(prompt + ": ").strip()
  2204. if email:
  2205. try:
  2206. last_email_file = open(last_email_file_name, "w")
  2207. last_email_file.write(email)
  2208. last_email_file.close()
  2209. except IOError, e:
  2210. pass
  2211. else:
  2212. email = last_email
  2213. return email
  2214. def StatusUpdate(msg):
  2215. """Print a status message to stdout.
  2216. If 'verbosity' is greater than 0, print the message.
  2217. Args:
  2218. msg: The string to print.
  2219. """
  2220. if verbosity > 0:
  2221. print msg
  2222. def ErrorExit(msg):
  2223. """Print an error message to stderr and exit."""
  2224. print >>sys.stderr, msg
  2225. sys.exit(1)
  2226. class ClientLoginError(urllib2.HTTPError):
  2227. """Raised to indicate there was an error authenticating with ClientLogin."""
  2228. def __init__(self, url, code, msg, headers, args):
  2229. urllib2.HTTPError.__init__(self, url, code, msg, headers, None)
  2230. self.args = args
  2231. self.reason = args["Error"]
  2232. class AbstractRpcServer(object):
  2233. """Provides a common interface for a simple RPC server."""
  2234. def __init__(self, host, auth_function, host_override=None, extra_headers={}, save_cookies=False):
  2235. """Creates a new HttpRpcServer.
  2236. Args:
  2237. host: The host to send requests to.
  2238. auth_function: A function that takes no arguments and returns an
  2239. (email, password) tuple when called. Will be called if authentication
  2240. is required.
  2241. host_override: The host header to send to the server (defaults to host).
  2242. extra_headers: A dict of extra headers to append to every request.
  2243. save_cookies: If True, save the authentication cookies to local disk.
  2244. If False, use an in-memory cookiejar instead. Subclasses must
  2245. implement this functionality. Defaults to False.
  2246. """
  2247. self.host = host
  2248. self.host_override = host_override
  2249. self.auth_function = auth_function
  2250. self.authenticated = False
  2251. self.extra_headers = extra_headers
  2252. self.save_cookies = save_cookies
  2253. self.opener = self._GetOpener()
  2254. if self.host_override:
  2255. logging.info("Server: %s; Host: %s", self.host, self.host_override)
  2256. else:
  2257. logging.info("Server: %s", self.host)
  2258. def _GetOpener(self):
  2259. """Returns an OpenerDirector for making HTTP requests.
  2260. Returns:
  2261. A urllib2.OpenerDirector object.
  2262. """
  2263. raise NotImplementedError()
  2264. def _CreateRequest(self, url, data=None):
  2265. """Creates a new urllib request."""
  2266. logging.debug("Creating request for: '%s' with payload:\n%s", url, data)
  2267. req = urllib2.Request(url, data=data)
  2268. if self.host_override:
  2269. req.add_header("Host", self.host_override)
  2270. for key, value in self.extra_headers.iteritems():
  2271. req.add_header(key, value)
  2272. return req
  2273. def _GetAuthToken(self, email, password):
  2274. """Uses ClientLogin to authenticate the user, returning an auth token.
  2275. Args:
  2276. email: The user's email address
  2277. password: The user's password
  2278. Raises:
  2279. ClientLoginError: If there was an error authenticating with ClientLogin.
  2280. HTTPError: If there was some other form of HTTP error.
  2281. Returns:
  2282. The authentication token returned by ClientLogin.
  2283. """
  2284. account_type = "GOOGLE"
  2285. if self.host.endswith(".google.com") and not force_google_account:
  2286. # Needed for use inside Google.
  2287. account_type = "HOSTED"
  2288. req = self._CreateRequest(
  2289. url="https://www.google.com/accounts/ClientLogin",
  2290. data=urllib.urlencode({
  2291. "Email": email,
  2292. "Passwd": password,
  2293. "service": "ah",
  2294. "source": "rietveld-codereview-upload",
  2295. "accountType": account_type,
  2296. }),
  2297. )
  2298. try:
  2299. response = self.opener.open(req)
  2300. response_body = response.read()
  2301. response_dict = dict(x.split("=") for x in response_body.split("\n") if x)
  2302. return response_dict["Auth"]
  2303. except urllib2.HTTPError, e:
  2304. if e.code == 403:
  2305. body = e.read()
  2306. response_dict = dict(x.split("=", 1) for x in body.split("\n") if x)
  2307. raise ClientLoginError(req.get_full_url(), e.code, e.msg, e.headers, response_dict)
  2308. else:
  2309. raise
  2310. def _GetAuthCookie(self, auth_token):
  2311. """Fetches authentication cookies for an authentication token.
  2312. Args:
  2313. auth_token: The authentication token returned by ClientLogin.
  2314. Raises:
  2315. HTTPError: If there was an error fetching the authentication cookies.
  2316. """
  2317. # This is a dummy value to allow us to identify when we're successful.
  2318. continue_location = "http://localhost/"
  2319. args = {"continue": continue_location, "auth": auth_token}
  2320. req = self._CreateRequest("http://%s/_ah/login?%s" % (self.host, urllib.urlencode(args)))
  2321. try:
  2322. response = self.opener.open(req)
  2323. except urllib2.HTTPError, e:
  2324. response = e
  2325. if (response.code != 302 or
  2326. response.info()["location"] != continue_location):
  2327. raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg, response.headers, response.fp)
  2328. self.authenticated = True
  2329. def _Authenticate(self):
  2330. """Authenticates the user.
  2331. The authentication process works as follows:
  2332. 1) We get a username and password from the user
  2333. 2) We use ClientLogin to obtain an AUTH token for the user
  2334. (see http://code.google.com/apis/accounts/AuthForInstalledApps.html).
  2335. 3) We pass the auth token to /_ah/login on the server to obtain an
  2336. authentication cookie. If login was successful, it tries to redirect
  2337. us to the URL we provided.
  2338. If we attempt to access the upload API without first obtaining an
  2339. authentication cookie, it returns a 401 response (or a 302) and
  2340. directs us to authenticate ourselves with ClientLogin.
  2341. """
  2342. for i in range(3):
  2343. credentials = self.auth_function()
  2344. try:
  2345. auth_token = self._GetAuthToken(credentials[0], credentials[1])
  2346. except ClientLoginError, e:
  2347. if e.reason == "BadAuthentication":
  2348. print >>sys.stderr, "Invalid username or password."
  2349. continue
  2350. if e.reason == "CaptchaRequired":
  2351. print >>sys.stderr, (
  2352. "Please go to\n"
  2353. "https://www.google.com/accounts/DisplayUnlockCaptcha\n"
  2354. "and verify you are a human. Then try again.")
  2355. break
  2356. if e.reason == "NotVerified":
  2357. print >>sys.stderr, "Account not verified."
  2358. break
  2359. if e.reason == "TermsNotAgreed":
  2360. print >>sys.stderr, "User has not agreed to TOS."
  2361. break
  2362. if e.reason == "AccountDeleted":
  2363. print >>sys.stderr, "The user account has been deleted."
  2364. break
  2365. if e.reason == "AccountDisabled":
  2366. print >>sys.stderr, "The user account has been disabled."
  2367. break
  2368. if e.reason == "ServiceDisabled":
  2369. print >>sys.stderr, "The user's access to the service has been disabled."
  2370. break
  2371. if e.reason == "ServiceUnavailable":
  2372. print >>sys.stderr, "The service is not available; try again later."
  2373. break
  2374. raise
  2375. self._GetAuthCookie(auth_token)
  2376. return
  2377. def Send(self, request_path, payload=None,
  2378. content_type="application/octet-stream",
  2379. timeout=None,
  2380. **kwargs):
  2381. """Sends an RPC and returns the response.
  2382. Args:
  2383. request_path: The path to send the request to, eg /api/appversion/create.
  2384. payload: The body of the request, or None to send an empty request.
  2385. content_type: The Content-Type header to use.
  2386. timeout: timeout in seconds; default None i.e. no timeout.
  2387. (Note: for large requests on OS X, the timeout doesn't work right.)
  2388. kwargs: Any keyword arguments are converted into query string parameters.
  2389. Returns:
  2390. The response body, as a string.
  2391. """
  2392. # TODO: Don't require authentication. Let the server say
  2393. # whether it is necessary.
  2394. if not self.authenticated:
  2395. self._Authenticate()
  2396. old_timeout = socket.getdefaulttimeout()
  2397. socket.setdefaulttimeout(timeout)
  2398. try:
  2399. tries = 0
  2400. while True:
  2401. tries += 1
  2402. args = dict(kwargs)
  2403. url = "http://%s%s" % (self.host, request_path)
  2404. if args:
  2405. url += "?" + urllib.urlencode(args)
  2406. req = self._CreateRequest(url=url, data=payload)
  2407. req.add_header("Content-Type", content_type)
  2408. try:
  2409. f = self.opener.open(req)
  2410. response = f.read()
  2411. f.close()
  2412. return response
  2413. except urllib2.HTTPError, e:
  2414. if tries > 3:
  2415. raise
  2416. elif e.code == 401 or e.code == 302:
  2417. self._Authenticate()
  2418. else:
  2419. raise
  2420. finally:
  2421. socket.setdefaulttimeout(old_timeout)
  2422. class HttpRpcServer(AbstractRpcServer):
  2423. """Provides a simplified RPC-style interface for HTTP requests."""
  2424. def _Authenticate(self):
  2425. """Save the cookie jar after authentication."""
  2426. super(HttpRpcServer, self)._Authenticate()
  2427. if self.save_cookies:
  2428. StatusUpdate("Saving authentication cookies to %s" % self.cookie_file)
  2429. self.cookie_jar.save()
  2430. def _GetOpener(self):
  2431. """Returns an OpenerDirector that supports cookies and ignores redirects.
  2432. Returns:
  2433. A urllib2.OpenerDirector object.
  2434. """
  2435. opener = urllib2.OpenerDirector()
  2436. opener.add_handler(urllib2.ProxyHandler())
  2437. opener.add_handler(urllib2.UnknownHandler())
  2438. opener.add_handler(urllib2.HTTPHandler())
  2439. opener.add_handler(urllib2.HTTPDefaultErrorHandler())
  2440. opener.add_handler(urllib2.HTTPSHandler())
  2441. opener.add_handler(urllib2.HTTPErrorProcessor())
  2442. if self.save_cookies:
  2443. self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies_" + server)
  2444. self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file)
  2445. if os.path.exists(self.cookie_file):
  2446. try:
  2447. self.cookie_jar.load()
  2448. self.authenticated = True
  2449. StatusUpdate("Loaded authentication cookies from %s" % self.cookie_file)
  2450. except (cookielib.LoadError, IOError):
  2451. # Failed to load cookies - just ignore them.
  2452. pass
  2453. else:
  2454. # Create an empty cookie file with mode 600
  2455. fd = os.open(self.cookie_file, os.O_CREAT, 0600)
  2456. os.close(fd)
  2457. # Always chmod the cookie file
  2458. os.chmod(self.cookie_file, 0600)
  2459. else:
  2460. # Don't save cookies across runs of update.py.
  2461. self.cookie_jar = cookielib.CookieJar()
  2462. opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar))
  2463. return opener
  2464. def GetRpcServer(options):
  2465. """Returns an instance of an AbstractRpcServer.
  2466. Returns:
  2467. A new AbstractRpcServer, on which RPC calls can be made.
  2468. """
  2469. rpc_server_class = HttpRpcServer
  2470. def GetUserCredentials():
  2471. """Prompts the user for a username and password."""
  2472. # Disable status prints so they don't obscure the password prompt.
  2473. global global_status
  2474. st = global_status
  2475. global_status = None
  2476. email = options.email
  2477. if email is None:
  2478. email = GetEmail("Email (login for uploading to %s)" % options.server)
  2479. password = getpass.getpass("Password for %s: " % email)
  2480. # Put status back.
  2481. global_status = st
  2482. return (email, password)
  2483. # If this is the dev_appserver, use fake authentication.
  2484. host = (options.host or options.server).lower()
  2485. if host == "localhost" or host.startswith("localhost:"):
  2486. email = options.email
  2487. if email is None:
  2488. email = "test@example.com"
  2489. logging.info("Using debug user %s. Override with --email" % email)
  2490. server = rpc_server_class(
  2491. options.server,
  2492. lambda: (email, "password"),
  2493. host_override=options.host,
  2494. extra_headers={"Cookie": 'dev_appserver_login="%s:False"' % email},
  2495. save_cookies=options.save_cookies)
  2496. # Don't try to talk to ClientLogin.
  2497. server.authenticated = True
  2498. return server
  2499. return rpc_server_class(options.server, GetUserCredentials,
  2500. host_override=options.host, save_cookies=options.save_cookies)
  2501. def EncodeMultipartFormData(fields, files):
  2502. """Encode form fields for multipart/form-data.
  2503. Args:
  2504. fields: A sequence of (name, value) elements for regular form fields.
  2505. files: A sequence of (name, filename, value) elements for data to be
  2506. uploaded as files.
  2507. Returns:
  2508. (content_type, body) ready for httplib.HTTP instance.
  2509. Source:
  2510. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306
  2511. """
  2512. BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-'
  2513. CRLF = '\r\n'
  2514. lines = []
  2515. for (key, value) in fields:
  2516. typecheck(key, str)
  2517. typecheck(value, str)
  2518. lines.append('--' + BOUNDARY)
  2519. lines.append('Content-Disposition: form-data; name="%s"' % key)
  2520. lines.append('')
  2521. lines.append(value)
  2522. for (key, filename, value) in files:
  2523. typecheck(key, str)
  2524. typecheck(filename, str)
  2525. typecheck(value, str)
  2526. lines.append('--' + BOUNDARY)
  2527. lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
  2528. lines.append('Content-Type: %s' % GetContentType(filename))
  2529. lines.append('')
  2530. lines.append(value)
  2531. lines.append('--' + BOUNDARY + '--')
  2532. lines.append('')
  2533. body = CRLF.join(lines)
  2534. content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
  2535. return content_type, body
  2536. def GetContentType(filename):
  2537. """Helper to guess the content-type from the filename."""
  2538. return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
  2539. # Use a shell for subcommands on Windows to get a PATH search.
  2540. use_shell = sys.platform.startswith("win")
  2541. def RunShellWithReturnCode(command, print_output=False,
  2542. universal_newlines=True, env=os.environ):
  2543. """Executes a command and returns the output from stdout and the return code.
  2544. Args:
  2545. command: Command to execute.
  2546. print_output: If True, the output is printed to stdout.
  2547. If False, both stdout and stderr are ignored.
  2548. universal_newlines: Use universal_newlines flag (default: True).
  2549. Returns:
  2550. Tuple (output, return code)
  2551. """
  2552. logging.info("Running %s", command)
  2553. p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  2554. shell=use_shell, universal_newlines=universal_newlines, env=env)
  2555. if print_output:
  2556. output_array = []
  2557. while True:
  2558. line = p.stdout.readline()
  2559. if not line:
  2560. break
  2561. print line.strip("\n")
  2562. output_array.append(line)
  2563. output = "".join(output_array)
  2564. else:
  2565. output = p.stdout.read()
  2566. p.wait()
  2567. errout = p.stderr.read()
  2568. if print_output and errout:
  2569. print >>sys.stderr, errout
  2570. p.stdout.close()
  2571. p.stderr.close()
  2572. return output, p.returncode
  2573. def RunShell(command, silent_ok=False, universal_newlines=True,
  2574. print_output=False, env=os.environ):
  2575. data, retcode = RunShellWithReturnCode(command, print_output, universal_newlines, env)
  2576. if retcode:
  2577. ErrorExit("Got error status from %s:\n%s" % (command, data))
  2578. if not silent_ok and not data:
  2579. ErrorExit("No output from %s" % command)
  2580. return data
  2581. class VersionControlSystem(object):
  2582. """Abstract base class providing an interface to the VCS."""
  2583. def __init__(self, options):
  2584. """Constructor.
  2585. Args:
  2586. options: Command line options.
  2587. """
  2588. self.options = options
  2589. def GenerateDiff(self, args):
  2590. """Return the current diff as a string.
  2591. Args:
  2592. args: Extra arguments to pass to the diff command.
  2593. """
  2594. raise NotImplementedError(
  2595. "abstract method -- subclass %s must override" % self.__class__)
  2596. def GetUnknownFiles(self):
  2597. """Return a list of files unknown to the VCS."""
  2598. raise NotImplementedError(
  2599. "abstract method -- subclass %s must override" % self.__class__)
  2600. def CheckForUnknownFiles(self):
  2601. """Show an "are you sure?" prompt if there are unknown files."""
  2602. unknown_files = self.GetUnknownFiles()
  2603. if unknown_files:
  2604. print "The following files are not added to version control:"
  2605. for line in unknown_files:
  2606. print line
  2607. prompt = "Are you sure to continue?(y/N) "
  2608. answer = raw_input(prompt).strip()
  2609. if answer != "y":
  2610. ErrorExit("User aborted")
  2611. def GetBaseFile(self, filename):
  2612. """Get the content of the upstream version of a file.
  2613. Returns:
  2614. A tuple (base_content, new_content, is_binary, status)
  2615. base_content: The contents of the base file.
  2616. new_content: For text files, this is empty. For binary files, this is
  2617. the contents of the new file, since the diff output won't contain
  2618. information to reconstruct the current file.
  2619. is_binary: True iff the file is binary.
  2620. status: The status of the file.
  2621. """
  2622. raise NotImplementedError(
  2623. "abstract method -- subclass %s must override" % self.__class__)
  2624. def GetBaseFiles(self, diff):
  2625. """Helper that calls GetBase file for each file in the patch.
  2626. Returns:
  2627. A dictionary that maps from filename to GetBaseFile's tuple. Filenames
  2628. are retrieved based on lines that start with "Index:" or
  2629. "Property changes on:".
  2630. """
  2631. files = {}
  2632. for line in diff.splitlines(True):
  2633. if line.startswith('Index:') or line.startswith('Property changes on:'):
  2634. unused, filename = line.split(':', 1)
  2635. # On Windows if a file has property changes its filename uses '\'
  2636. # instead of '/'.
  2637. filename = filename.strip().replace('\\', '/')
  2638. files[filename] = self.GetBaseFile(filename)
  2639. return files
  2640. def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options,
  2641. files):
  2642. """Uploads the base files (and if necessary, the current ones as well)."""
  2643. def UploadFile(filename, file_id, content, is_binary, status, is_base):
  2644. """Uploads a file to the server."""
  2645. set_status("uploading " + filename)
  2646. file_too_large = False
  2647. if is_base:
  2648. type = "base"
  2649. else:
  2650. type = "current"
  2651. if len(content) > MAX_UPLOAD_SIZE:
  2652. print ("Not uploading the %s file for %s because it's too large." %
  2653. (type, filename))
  2654. file_too_large = True
  2655. content = ""
  2656. checksum = md5(content).hexdigest()
  2657. if options.verbose > 0 and not file_too_large:
  2658. print "Uploading %s file for %s" % (type, filename)
  2659. url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id)
  2660. form_fields = [
  2661. ("filename", filename),
  2662. ("status", status),
  2663. ("checksum", checksum),
  2664. ("is_binary", str(is_binary)),
  2665. ("is_current", str(not is_base)),
  2666. ]
  2667. if file_too_large:
  2668. form_fields.append(("file_too_large", "1"))
  2669. if options.email:
  2670. form_fields.append(("user", options.email))
  2671. ctype, body = EncodeMultipartFormData(form_fields, [("data", filename, content)])
  2672. response_body = rpc_server.Send(url, body, content_type=ctype)
  2673. if not response_body.startswith("OK"):
  2674. StatusUpdate(" --> %s" % response_body)
  2675. sys.exit(1)
  2676. # Don't want to spawn too many threads, nor do we want to
  2677. # hit Rietveld too hard, or it will start serving 500 errors.
  2678. # When 8 works, it's no better than 4, and sometimes 8 is
  2679. # too many for Rietveld to handle.
  2680. MAX_PARALLEL_UPLOADS = 4
  2681. sema = threading.BoundedSemaphore(MAX_PARALLEL_UPLOADS)
  2682. upload_threads = []
  2683. finished_upload_threads = []
  2684. class UploadFileThread(threading.Thread):
  2685. def __init__(self, args):
  2686. threading.Thread.__init__(self)
  2687. self.args = args
  2688. def run(self):
  2689. UploadFile(*self.args)
  2690. finished_upload_threads.append(self)
  2691. sema.release()
  2692. def StartUploadFile(*args):
  2693. sema.acquire()
  2694. while len(finished_upload_threads) > 0:
  2695. t = finished_upload_threads.pop()
  2696. upload_threads.remove(t)
  2697. t.join()
  2698. t = UploadFileThread(args)
  2699. upload_threads.append(t)
  2700. t.start()
  2701. def WaitForUploads():
  2702. for t in upload_threads:
  2703. t.join()
  2704. patches = dict()
  2705. [patches.setdefault(v, k) for k, v in patch_list]
  2706. for filename in patches.keys():
  2707. base_content, new_content, is_binary, status = files[filename]
  2708. file_id_str = patches.get(filename)
  2709. if file_id_str.find("nobase") != -1:
  2710. base_content = None
  2711. file_id_str = file_id_str[file_id_str.rfind("_") + 1:]
  2712. file_id = int(file_id_str)
  2713. if base_content != None:
  2714. StartUploadFile(filename, file_id, base_content, is_binary, status, True)
  2715. if new_content != None:
  2716. StartUploadFile(filename, file_id, new_content, is_binary, status, False)
  2717. WaitForUploads()
  2718. def IsImage(self, filename):
  2719. """Returns true if the filename has an image extension."""
  2720. mimetype = mimetypes.guess_type(filename)[0]
  2721. if not mimetype:
  2722. return False
  2723. return mimetype.startswith("image/")
  2724. def IsBinary(self, filename):
  2725. """Returns true if the guessed mimetyped isnt't in text group."""
  2726. mimetype = mimetypes.guess_type(filename)[0]
  2727. if not mimetype:
  2728. return False # e.g. README, "real" binaries usually have an extension
  2729. # special case for text files which don't start with text/
  2730. if mimetype in TEXT_MIMETYPES:
  2731. return False
  2732. return not mimetype.startswith("text/")
  2733. class FakeMercurialUI(object):
  2734. def __init__(self):
  2735. self.quiet = True
  2736. self.output = ''
  2737. def write(self, *args, **opts):
  2738. self.output += ' '.join(args)
  2739. use_hg_shell = False # set to True to shell out to hg always; slower
  2740. class MercurialVCS(VersionControlSystem):
  2741. """Implementation of the VersionControlSystem interface for Mercurial."""
  2742. def __init__(self, options, ui, repo):
  2743. super(MercurialVCS, self).__init__(options)
  2744. self.ui = ui
  2745. self.repo = repo
  2746. # Absolute path to repository (we can be in a subdir)
  2747. self.repo_dir = os.path.normpath(repo.root)
  2748. # Compute the subdir
  2749. cwd = os.path.normpath(os.getcwd())
  2750. assert cwd.startswith(self.repo_dir)
  2751. self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/")
  2752. if self.options.revision:
  2753. self.base_rev = self.options.revision
  2754. else:
  2755. mqparent, err = RunShellWithReturnCode(['hg', 'log', '--rev', 'qparent', '--template={node}'])
  2756. if not err and mqparent != "":
  2757. self.base_rev = mqparent
  2758. else:
  2759. self.base_rev = RunShell(["hg", "parents", "-q"]).split(':')[1].strip()
  2760. def _GetRelPath(self, filename):
  2761. """Get relative path of a file according to the current directory,
  2762. given its logical path in the repo."""
  2763. assert filename.startswith(self.subdir), (filename, self.subdir)
  2764. return filename[len(self.subdir):].lstrip(r"\/")
  2765. def GenerateDiff(self, extra_args):
  2766. # If no file specified, restrict to the current subdir
  2767. extra_args = extra_args or ["."]
  2768. cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args
  2769. data = RunShell(cmd, silent_ok=True)
  2770. svndiff = []
  2771. filecount = 0
  2772. for line in data.splitlines():
  2773. m = re.match("diff --git a/(\S+) b/(\S+)", line)
  2774. if m:
  2775. # Modify line to make it look like as it comes from svn diff.
  2776. # With this modification no changes on the server side are required
  2777. # to make upload.py work with Mercurial repos.
  2778. # NOTE: for proper handling of moved/copied files, we have to use
  2779. # the second filename.
  2780. filename = m.group(2)
  2781. svndiff.append("Index: %s" % filename)
  2782. svndiff.append("=" * 67)
  2783. filecount += 1
  2784. logging.info(line)
  2785. else:
  2786. svndiff.append(line)
  2787. if not filecount:
  2788. ErrorExit("No valid patches found in output from hg diff")
  2789. return "\n".join(svndiff) + "\n"
  2790. def GetUnknownFiles(self):
  2791. """Return a list of files unknown to the VCS."""
  2792. args = []
  2793. status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."],
  2794. silent_ok=True)
  2795. unknown_files = []
  2796. for line in status.splitlines():
  2797. st, fn = line.split(" ", 1)
  2798. if st == "?":
  2799. unknown_files.append(fn)
  2800. return unknown_files
  2801. def GetBaseFile(self, filename):
  2802. set_status("inspecting " + filename)
  2803. # "hg status" and "hg cat" both take a path relative to the current subdir
  2804. # rather than to the repo root, but "hg diff" has given us the full path
  2805. # to the repo root.
  2806. base_content = ""
  2807. new_content = None
  2808. is_binary = False
  2809. oldrelpath = relpath = self._GetRelPath(filename)
  2810. # "hg status -C" returns two lines for moved/copied files, one otherwise
  2811. if use_hg_shell:
  2812. out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath])
  2813. else:
  2814. fui = FakeMercurialUI()
  2815. ret = commands.status(fui, self.repo, *[relpath], **{'rev': [self.base_rev], 'copies': True})
  2816. if ret:
  2817. raise util.Abort(ret)
  2818. out = fui.output
  2819. out = out.splitlines()
  2820. # HACK: strip error message about missing file/directory if it isn't in
  2821. # the working copy
  2822. if out[0].startswith('%s: ' % relpath):
  2823. out = out[1:]
  2824. status, what = out[0].split(' ', 1)
  2825. if len(out) > 1 and status == "A" and what == relpath:
  2826. oldrelpath = out[1].strip()
  2827. status = "M"
  2828. if ":" in self.base_rev:
  2829. base_rev = self.base_rev.split(":", 1)[0]
  2830. else:
  2831. base_rev = self.base_rev
  2832. if status != "A":
  2833. if use_hg_shell:
  2834. base_content = RunShell(["hg", "cat", "-r", base_rev, oldrelpath], silent_ok=True)
  2835. else:
  2836. base_content = str(self.repo[base_rev][oldrelpath].data())
  2837. is_binary = "\0" in base_content # Mercurial's heuristic
  2838. if status != "R":
  2839. new_content = open(relpath, "rb").read()
  2840. is_binary = is_binary or "\0" in new_content
  2841. if is_binary and base_content and use_hg_shell:
  2842. # Fetch again without converting newlines
  2843. base_content = RunShell(["hg", "cat", "-r", base_rev, oldrelpath],
  2844. silent_ok=True, universal_newlines=False)
  2845. if not is_binary or not self.IsImage(relpath):
  2846. new_content = None
  2847. return base_content, new_content, is_binary, status
  2848. # NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync.
  2849. def SplitPatch(data):
  2850. """Splits a patch into separate pieces for each file.
  2851. Args:
  2852. data: A string containing the output of svn diff.
  2853. Returns:
  2854. A list of 2-tuple (filename, text) where text is the svn diff output
  2855. pertaining to filename.
  2856. """
  2857. patches = []
  2858. filename = None
  2859. diff = []
  2860. for line in data.splitlines(True):
  2861. new_filename = None
  2862. if line.startswith('Index:'):
  2863. unused, new_filename = line.split(':', 1)
  2864. new_filename = new_filename.strip()
  2865. elif line.startswith('Property changes on:'):
  2866. unused, temp_filename = line.split(':', 1)
  2867. # When a file is modified, paths use '/' between directories, however
  2868. # when a property is modified '\' is used on Windows. Make them the same
  2869. # otherwise the file shows up twice.
  2870. temp_filename = temp_filename.strip().replace('\\', '/')
  2871. if temp_filename != filename:
  2872. # File has property changes but no modifications, create a new diff.
  2873. new_filename = temp_filename
  2874. if new_filename:
  2875. if filename and diff:
  2876. patches.append((filename, ''.join(diff)))
  2877. filename = new_filename
  2878. diff = [line]
  2879. continue
  2880. if diff is not None:
  2881. diff.append(line)
  2882. if filename and diff:
  2883. patches.append((filename, ''.join(diff)))
  2884. return patches
  2885. def UploadSeparatePatches(issue, rpc_server, patchset, data, options):
  2886. """Uploads a separate patch for each file in the diff output.
  2887. Returns a list of [patch_key, filename] for each file.
  2888. """
  2889. patches = SplitPatch(data)
  2890. rv = []
  2891. for patch in patches:
  2892. set_status("uploading patch for " + patch[0])
  2893. if len(patch[1]) > MAX_UPLOAD_SIZE:
  2894. print ("Not uploading the patch for " + patch[0] +
  2895. " because the file is too large.")
  2896. continue
  2897. form_fields = [("filename", patch[0])]
  2898. if not options.download_base:
  2899. form_fields.append(("content_upload", "1"))
  2900. files = [("data", "data.diff", patch[1])]
  2901. ctype, body = EncodeMultipartFormData(form_fields, files)
  2902. url = "/%d/upload_patch/%d" % (int(issue), int(patchset))
  2903. print "Uploading patch for " + patch[0]
  2904. response_body = rpc_server.Send(url, body, content_type=ctype)
  2905. lines = response_body.splitlines()
  2906. if not lines or lines[0] != "OK":
  2907. StatusUpdate(" --> %s" % response_body)
  2908. sys.exit(1)
  2909. rv.append([lines[1], patch[0]])
  2910. return rv