a +bZ @sdZddlmZmZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddl mZmZddlmZmZmZmZmZmZmZmZmZmZmZmZmZmZddlm Z m!Z!dd l"m#Z#ej$Z$ej%Z%e j&Z'e j(Z)d Z*d Z+d Z,d Z-d Z.d Z/dZ0e1dZ2ddZ3ddZ4ddZ5ddZ6iZ7dddZ8Gddde9Z:Gddde9Z;Gdd d e<Z=d!d"Z>dd#d$Z?Gd%d&d&e9Z@dd(d)ZAd*d+ZBd,d-ZCd.d/ZDd0d1ZEd2d3ZFd4d5ZGd6dd7d8d9d:ZHgd;ZIGdd?d?e9ZKdd@dAZLGdBdCdCeKZMdDeMiZNiZOdEdFZPePdGdHdIZQGdJdKdKe9ZRdLZSGdMdNdNeKZTGdOdPdPe9ZUdQdRZVGdSdTdTeKZWGdUdVdVeWZXdddWddeYeZej[\dXddYdZd[ Z]dd]d^Z^d_d`Z_dadbZ`ddcddZadedfZbdgdhZcdidjZddkdlZedmdnZfdodpZgdqdrZhdsdtZidudvZjddxdyZkddzd{Zld|d}Zme8d~dddZneYgdddej[\DZoe8deoddZpe8ddddZqe8dddZre8dddZse8dddZte8dddZue8dddZve8dddZwGdddejxZye8ddddZze8ddddZ{e8ddddZ|e8ddddZ}e8ddddZ~e8ddddZe8dddZe8dddZe8ddddZe8dddÄZe8ddŃddDŽZe8dȃddʄZe dˡZe8d̃dd΄Ze8dσddфZe8ddӃddՄZddׄZdS)aHandling of the new bundle2 format The goal of bundle2 is to act as an atomically packet to transmit a set of payloads in an application agnostic way. It consist in a sequence of "parts" that will be handed to and processed by the application layer. General format architecture =========================== The format is architectured as follow - magic string - stream level parameters - payload parts (any number) - end of stream marker. the Binary format ============================ All numbers are unsigned and big-endian. stream level parameters ------------------------ Binary format is as follow :params size: int32 The total number of Bytes used by the parameters :params value: arbitrary number of Bytes A blob of `params size` containing the serialized version of all stream level parameters. The blob contains a space separated list of parameters. Parameters with value are stored in the form `=`. Both name and value are urlquoted. Empty name are obviously forbidden. Name MUST start with a letter. If this first letter is lower case, the parameter is advisory and can be safely ignored. However when the first letter is capital, the parameter is mandatory and the bundling process MUST stop if he is not able to proceed it. Stream parameters use a simple textual format for two main reasons: - Stream level parameters should remain simple and we want to discourage any crazy usage. - Textual data allow easy human inspection of a bundle2 header in case of troubles. Any Applicative level options MUST go into a bundle2 part instead. Payload part ------------------------ Binary format is as follow :header size: int32 The total number of Bytes used by the part header. When the header is empty (size = 0) this is interpreted as the end of stream marker. :header: The header defines how to interpret the part. It contains two piece of data: the part type, and the part parameters. The part type is used to route an application level handler, that can interpret payload. Part parameters are passed to the application level handler. They are meant to convey information that will help the application level object to interpret the part payload. The binary format of the header is has follow :typesize: (one byte) :parttype: alphanumerical part name (restricted to [a-zA-Z0-9_:-]*) :partid: A 32bits integer (unique in the bundle) that can be used to refer to this part. :parameters: Part's parameter may have arbitrary content, the binary structure is:: :mandatory-count: 1 byte, number of mandatory parameters :advisory-count: 1 byte, number of advisory parameters :param-sizes: N couple of bytes, where N is the total number of parameters. Each couple contains (, `. `chunksize` is an int32, `chunkdata` are plain bytes (as much as `chunksize` says)` The payload part is concluded by a zero size chunk. The current implementation always produces either zero or one chunk. This is an implementation limitation that will ultimately be lifted. `chunksize` can be negative to trigger special case processing. No such processing is in place yet. Bundle processing ============================ Each part is processed in order using a "part handler". Handler are registered for a certain part type. The matching of a part to its handler is case insensitive. The case of the part type is used to know if a part is mandatory or advisory. If the Part type contains any uppercase char it is considered mandatory. When no handler is known for a Mandatory part, the process is aborted and an exception is raised. If the part is advisory and no handler is known, the part is ignored. When the process is aborted, the full bundle is still read from the stream to keep the channel usable. But none of the part read from an abort are processed. In the future, dropping the stream may become an option for channel we do not care to preserve. )absolute_importdivisionN)_)hexshort) bookmarks changegroupencodingerrorobsoletephasespushkeypycompat requirementsscmutil streamclonetagsurlutil) stringutilurlutil) repositorys>is>Bs>Is>BBs[^a-zA-Z0-9_:-]cCs|ddr|d|dS)z(debug regarding output stream (bundling)devel bundle2.debugsbundle2-output: %s N configbooldebuguimessager"7/usr/lib64/python3.9/site-packages/mercurial/bundle2.pyoutdebugs r$cCs|ddr|d|dS)z"debug on input stream (unbundling)rrsbundle2-input: %s Nrrr"r"r#indebugs r%cCst|rt|dS)z9raise ValueError if a parttype contains invalid characterN)_parttypeforbiddensearch ValueErrorparttyper"r"r#validateparttypes r+cCs dd|S)zreturn a struct format to read part parameter sizes The number parameters is variable so we need to build that format dynamically. >sBBr")Znbparamsr"r"r#_makefpartparamsizessr-r"cstfdd}|S)zdecorator that register a function as a bundle2 part handler eg:: @parthandler('myparttype', ('mandatory', 'param', 'handled')) def myparttypehandler(...): '''process a part of type "my part".''' ... cs*}|tvsJ|t|<t|_|SN)lowerparthandlermapping frozensetparams)funcZ lparttyper2r*r"r# _decorators   zparthandler.._decorator)r+)r*r2r5r"r4r# parthandlers r6c@sNeZdZdZddZdddZddZd d Zd d Zd dZ ddZ e Z dS)unbundlerecordsakeep record of what happens during and unbundle New records are added using `records.add('cat', obj)`. Where 'cat' is a category of record and obj is an arbitrary object. `records['cat']` will return all entries of this category 'cat'. Iterating on the object itself will yield `('category', obj)` tuples for all entries. All iterations happens in chronological order. cCsi|_g|_i|_dSr.) _categories _sequences_repliesselfr"r"r#__init__ szunbundlerecords.__init__NcCsB|j|g||j||f|dur>||||dS)zadd a new record of a given category. The entry can then be retrieved in the list returned by self['category'].N)r8 setdefaultappendr9 getrepliesadd)r<categoryentryZ inreplytor"r"r#rAszunbundlerecords.addcCs|j|tS)z3get the records that are replies to a specific part)r:r>r7)r<partidr"r"r#r@szunbundlerecords.getrepliescCst|j|dS)Nr")tupler8get)r<catr"r"r# __getitem__ szunbundlerecords.__getitem__cCs t|jSr.)iterr9r;r"r"r#__iter__#szunbundlerecords.__iter__cCs t|jSr.)lenr9r;r"r"r#__len__&szunbundlerecords.__len__cCs t|jSr.)boolr9r;r"r"r# __nonzero__)szunbundlerecords.__nonzero__)N) __name__ __module__ __qualname____doc__r=rAr@rHrJrLrN__bool__r"r"r"r#r7s  r7c@s*eZdZdZd ddZddZdd Zd S) bundleoperationaPan object that represents a single bundling process Its purpose is to carry unbundle-related objects and states. A new object should be created at the beginning of each bundle processing. The object is to be returned by the processing function. The object has very little content now it will ultimately contain: * an access to the repo the bundle is applied to, * a ui object, * a way to retrieve a transaction to add changes to the repo, * a way to record the result of processing each part, * a way to construct a bundle response when applicable. TcCs>||_|j|_t|_d|_||_i|_||_i|_||_ dSr.) repor r7recordsreply captureoutputhookargs_gettransactionmodessource)r<rVtransactiongetterrYr]r"r"r#r=?szbundleoperation.__init__cCs.|}|jr$|j|j|j|_d|_|Sr.)r[rZupdate)r<Z transactionr"r"r#gettransactionKs zbundleoperation.gettransactioncCs$|jdurtd|j|dS)Ns@attempted to add hookargs to operation after transaction started)rZr ProgrammingErrorr_)r<rZr"r"r# addhookargsZs  zbundleoperation.addhookargsN)TrU)rOrPrQrRr=r`rbr"r"r"r#rT/s rTc@s eZdZdS)TransactionUnavailableN)rOrPrQr"r"r"r#rccsrccCs tdS)zdefault method to get a transaction while processing a bundle Raise an exception to highlight the fact that no transaction was expected to be createdNrcr"r"r"r#_notransactiongsrec st|trddjd<|dur0djvr0|jd<|durLdjvrL|jd<t||fdd|dSt|fdd|d}t||||fi||SdS) N1bundle2ssourceurlcsSr.r"r"trr"r#wrUzapplybundle..r]csSr.r"r"rir"r#rkzrU) isinstance unbundle20rZ processbundlerT_processchangegroup)rV unbundlerrjr]rkwargsopr"rir# applybundleos    rtc@s$eZdZddZddZddZdS) partiteratorcCs(||_||_||_d|_d|_d|_dS)Nr)rVrsrqiteratorcountcurrent)r<rVrsrqr"r"r#r=s zpartiterator.__init__csfdd}|_jS)Nc3sBtjd}|D](\}}|_|_|V|d_qdS)Nr) enumeraterq iterpartsrwrxconsume)itrrwpr;r"r#r3s z$partiterator.__enter__..func)rv)r<r3r"r;r# __enter__s zpartiterator.__enter__cCs|js dSt|trd}z(|jr*|j|jD] }|q0WntyVd}Yn0d|_g}d}|jjdur|jj}|jjj }||_ ||_ |r||j j d|jdS)NFTs%bundle2-input-bundle: %i parts total )rvrm Exceptionrxr{Zduringunbundle2rsrX salvageoutput capabilitiesZ _replycapsZ_bundle2salvagedoutputrVr rrw)r<typeexctbZ seekerrorpartsalvagedZ replycapsr"r"r#__exit__s0        zpartiterator.__exit__N)rOrPrQr=r~rr"r"r"r#rus rurUcCs|dur"|durt}t|||d}|j|jjrdg}|jrP|dt|j|jdusd|jturp|dn |d|d|jd |t ||||S) a,This function process a bundle, apply effect to/from a repo It iterates over each part then searches for and uses the proper handling code to process the part. Parts are processed in order. Unknown Mandatory part will abort the process. It is temporarily possible to provide a prebuilt bundleoperation to the function. This is used to ensure output is properly propagated in case of an error during the unbundling. This output capturing part will likely be reworked and this ability will probably go away in the process. Nrlsbundle2-input-bundle:s %i paramss no-transactions with-transaction rU) rerTr2r debugflagr?rKr[rjoin processparts)rVrqr^rsr]msgr"r"r#ros     rocCsDt|||$}|D]}t||qWdn1s60YdSr.)ru _processpart)rVrsrqpartsrr"r"r#rsrcKs0|j|j|||fi|}|jdd|i|S)N changegroupreturn)ZapplyrVrWrA)rscgrjr]rrrretr"r"r#rpsrpc Csd}zz~t|j}|dur0d}tj|jdt|jd|j|j|j}|rt |}| dd |}tj|j|dd}Wntjyp}z|j rt|jd |WYd}~W|jj rdd |jg}|j s|d t|j}t|j|}|s|rD|d |r&|d ||r:|d||d|d||jd |dSd}~00W|jj rd |jg}|j s|d t|j}t|j|}|s|r|d |r|d ||r|d||d|d||jd |n|jj rd |jg}|j sF|d t|j}t|j|}|sj|r|d |r|d ||r|d||d|d||jd |0|S)Nsunknownsunsupported-typer)sfound a handler for part %ssunsupported-params (%s)s, )r*r2s supporteds%ignoring unsupported advisory part %ssbundle2-input-part: "%s" (advisory) (params: %i mandatory %i advisory)s %s rU)r0rFrr BundleUnknownFeatureErrorr%r mandatorykeysr2listsortr mandatoryrr?rKr) rsrstatushandlerZ unknownparamsrrnbmpnbapr"r"r# _gethandlers                        rc Cst||}|durdSd}|jr>|jdur>|jjdddd}zN|||W|dur^|j}|r|jjd|dd}|jdt |j dd nB|dur|j}|r|jjd|dd}|jdt |j dd 0dS) zprocess a single part from a bundle The part is guaranteed to have been fully consumed when the function exits (even if an exception is raised).NT)r ZsubprocrUoutputFdatar in-reply-tor) rrYrXr Z pushbufferZ popbuffernewpartaddparamrbytestrid)rsrroutputZoutpartr"r"r#r&s.    rcCsji}|D]X}|sq d|vr*|d}}n|dd\}}|d}t|}dd|D}|||<q |S)zdecode a bundle2 caps bytes blob into a dictionary The blob is a list of capabilities (one per line) Capabilities may have values using a line of the form:: capability=value1,value2,value3 The values are always a list.=r"r,cSsg|]}t|qSr"urlrequnquote.0vr"r"r# VrUzdecodecaps..) splitlinessplitrr)Zblobcapslinekeyvalsr"r"r# decodecapsCs      rcCs\g}t|D]D}||}t|}dd|D}|rFd|d|f}||q d|S)z2encode a bundle2 caps dictionary into a bytes blobcSsg|]}t|qSr")rquoterr"r"r#rarUzencodecaps..%s=%srr)sortedrrrr?)rchunkscarr"r"r# encodecaps[s   r)rUUN)HG10UNr)HG10sBZ)HG10GZsGZ)rUHG20rHG10BZr)rrrc@sneZdZdZdZdddZdddZed d Zdd d Z d dZ ddZ ddZ ddZ ddZddZdS)bundle20zrepresent an outgoing bundle2 container Use the `addparam` method to add stream level parameter. and `newpart` to populate it. Then call `getchunks` to retrieve all the binary chunks of data that compose the bundle2 container.rr"cCs:||_g|_g|_t||_tjd|_d|_ d|_ dS)NrT) r _params_partsdictrr compengines forbundletype _compengine _compoptsprefercompressed)r<r rr"r"r#r=s zbundle20.__init__NcCsH|dvr dStdd|jDr$J|d|tj||_||_dS)z$setup core part compression to )NrNcss|]\}}|dkVqdS) compressionN)r/)rnrr"r"r# rUz*bundle20.setcompression..s Compression)anyrrrrrrr)r<Zalgcompoptsr"r"r#setcompressions  zbundle20.setcompressioncCs t|jS)z*total number of parts added to the bundler)rKrr;r"r"r#nbpartsszbundle20.nbpartscCsH|std|ddttjvr4td||j||fdS)zadd a stream level parametersempty parameter namerrsnon letter first character: %sN)r rarrstring ascii_lettersrr?)r<namevaluer"r"r#rs zbundle20.addparamcCs*|jdusJt|j|_|j|dS)z_add a new part to the bundle2 container Parts contains the actual applicative payload.N)rrKrr?)r<rr"r"r#addparts zbundle20.addpartcOs$t|g|Ri|}|||S)aqcreate a new part and add it to the containers As the part is directly added to the containers. For now, this means that any failure to properly initialize the part after calling ``newpart`` should result in a failure of the whole bundling process. You can still fall back to manually create and add if you need better control.) bundlepartr)r<Ztypeidargsrrrr"r"r#rs  zbundle20.newpartccs|jjrTd|jg}|jr.|dt|j|dt|j|jd|t |jd|j|jV| }t |jd|t t t|V|r|V|j ||jD] }|VqdS)Nsbundle2-output-bundle: "%s",s (%i params)s %i parts total rUsstart emission of %s streamsbundle parameter: %s)r r _magicstringrr?rKrrrr$ _paramchunk_pack_fstreamparamsizercompressstream _getcorechunkr)r<rparamchunkr"r"r# getchunkss"  zbundle20.getchunkscCsPg}|jD]:\}}t|}|dur:t|}d||f}||q d|S)z1return a encoded version of all stream parametersNr )rrrr?r)r<ZblocksZparrr"r"r#rs    zbundle20._paramchunkccs`t|jd|jD]0}t|jd|j|j|jdD] }|Vq6qt|jdttdVdS)zUyield chunk for the core part of the bundle (all but headers and parameters)sstart of partssbundle part: "%s"r s end of bundlerN)r$r rrrr_fpartheadersize)r<rrr"r"r#rs    zbundle20._getcorechunkcCs.g}|jD]}|jdr ||q |S)zreturn a list with a copy of all output parts in the bundle This is meant to be used during error handling to make sure we preserve server outputr)rr startswithr?copy)r<rrr"r"r#rs   zbundle20.salvageoutput)r")N)N)rOrPrQrRrr=rpropertyrrrrrrrrr"r"r"r#rvs     rc@s(eZdZdZddZddZddZdS) unpackermixinz6A mixin to extract bytes and struct data from a streamcCs ||_dSr.)_fp)r<fpr"r"r#r=szunpackermixin.__init__cCs|t|}t||S)aunpack this struct format from the stream This method is meant for internal usage by the bundle2 protocol only. They directly manipulate the low level stream including bundle2 level instruction. Do not use it to implement higher-level logic or methods.) _readexactstructcalcsize_unpackr<formatrr"r"r#rszunpackermixin._unpackcCst|j|S)aread exactly bytes from the stream This method is meant for internal usage by the bundle2 protocol only. They directly manipulate the low level stream including bundle2 level instruction. Do not use it to implement higher-level logic or methods.)r readexactlyr)r<sizer"r"r#rszunpackermixin._readexactN)rOrPrQrRr=rrr"r"r"r#rs rcCs|durt|d}|dd|dd}}|dkrV|d||fttdt|}|durzttd||||}t|d ||S) z7return a valid unbundler object for a given magicstringNrsHGs6error: invalid magic: %r (version %r), should be 'HG' snot a Mercurial bundlesunknown bundle version %ssstart processing of %s stream) r rrr Abortr formatmaprFr%)r rZ magicstringmagicversionZunbundlerclassrqr"r"r# getunbundlers    rcsleZdZdZdZfddZejddZddZ d d Z d d Z dddZ ddZ ddZddZZS)rnz|interpret a bundle2 stream This class is fed with a binary stream and yields parts through its `iterparts` methods.rcs.||_tjd|_d|_tt||dS)z.rNr)rsortdictrrKr? _processparam)r<Z paramsblockr2r}r"r"r#r?s    zunbundle20._processallparamscCs|s td|ddttjvr0td|zt|}WnBty|ddrpt |j d|nt j |fdYn0||||dS)aprocess a parameter, applying its effect if needed Parameter starting with a lower case letter are advisory and will be ignored when unknown. Those starting with an upper case letter are mandatory and will this function will raise a KeyError when unknown. Note: no option are currently supported. Any input will be either ignored or failing. zempty parameter namerrznon letter first character: %ssignoring unknown parameter %s)r2N) r(rrrrb2streamparamsmapr/KeyErrorislowerr%r r r)r<rrrr"r"r#r Ks   zunbundle20._processparamc csJ|jVdt|vsJ|td}|dkr.decoratorr")rr&r"r%r#b2streamparamhandlers r'rcCs>|tjjvrtj|f|fdtj||_|dur:d|_dS)z)rrPrOrrr)r<rr"r"r#__repr__szbundlepart.__repr__cCs.t|jdrJ||j|j|j|j|jS)zreturn a copy of the part The new part have the very same content but no partid assigned yet. Parts with generated data cannot be copied.next) rr#rrrr-r.r,rr;r"r"r#rszbundlepart.copycCs|jSr.)r,r;r"r"r#rszbundlepart.datacCs|jdurtd||_dS)Npart is being generated)r1r ReadOnlyPartErrorr,)r<rr"r"r#r#s  cCs t|jSr.)rEr-r;r"r"r#r2)szbundlepart.mandatoryparamscCs t|jSr.)rEr.r;r"r"r#r3.szbundlepart.advisoryparamscCsX|jdurtd||jvr*td||j||j}|rF|j}|||fdS)zadd a parameter to the part If 'mandatory' is set to True, the remote handler must claim support for this parameter or the unbundling will be aborted. The 'name' and 'value' cannot exceed 255 bytes each. Nr7r+) r1r r8r0r(rAr.r-r?)r<rrrr2r"r"r#r3s     zbundlepart.addparamc cs|jdurtdd|_|jrd|jg}|js<|dt|j}t|j }|sX|r|d|rt|d||r|d||d|j s|d n byte from the header)r[rZ)r<roffsetrr"r"r# _fromheaderas zunbundlepart._fromheadercCs|t|}t||S)zaread given format from header This automatically compute the size of the format to read.)rbrrrrr"r"r# _unpackheaderhszunbundlepart._unpackheadercCsHt||_t||_t|j|_|j|jtdd|D|_dS)z7internal function to setup all logic related parameterscss|]}|dVqdS)rNr")rr}r"r"r#rwrUz+unbundlepart._initparams..N) rEr2r3rr r2r_r1r)r<r2r3r"r"r# _initparamsos   zunbundlepart._initparamsc Csd|td}|||_t|jd|j|td|_t|jdt |j|j|j k|_ |j |_|t \}}t|jd||t ||}||}tt|ddd|ddd}|d|}||d}g}|D]"\} } ||| || fqg} |D]$\} } | || || fq||| t||_d|_dS) z$read the header and setup the objectrspart type: "%s"s part id: "%s"spart parameters: %iNrrT)rcr?rbrr%r r@rrrr/rrAr-rzipr?rdrrJrC_payloadstreamr\) r<ZtypesizeZmancountZadvcountZ fparamsizesrIZmansizesZadvsizesZ manparamsrrZ advparamsr"r"r#r^ys.    "     zunbundlepart._readheadercCst|j|jS)z+Generator of decoded chunks in the payload.)rWr rr;r"r"r#rCszunbundlepart._payloadchunkscCs:|jr dS|d}|r6|jt|7_|d}qdS)zRead the part payload until completion. By consuming the part data, the underlying stream read offset will be advanced to the next part (or end of stream). Nr)r]rKr_rK)r<rr"r"r#r{s  zunbundlepart.consumeNcCs||js||dur"|j}n |j|}|jt|7_|dusTt||krx|jsr|jrr|jd|jd|_|S)zread payload dataNs*bundle2-input-part: total payload size %i T) r\r^rfrKr_rKr]r r)r<rrr"r"r#rKs   zunbundlepart.read)N) rOrPrQrRr=rbrcrdr^rCr{rKr$r"r"rr#rHs  #rcsZeZdZdZfddZdddZddZd d Zej fd d Z dd dZ ddZ Z S)raA bundle2 part in a bundle that is seekable. Regular ``unbundlepart`` instances can only be read once. This class extends ``unbundlepart`` to enable bi-directional seeking within the part. Bundle2 part data consists of framed chunks. Offsets when seeking refer to the decoded data, not the offsets in the underlying bundle2 stream. To facilitate quickly seeking within the decoded data, instances of this class maintain a mapping between offsets in the underlying stream and the decoded payload. This mapping will consume memory in proportion to the number of chunks within the payload (which almost certainly increases in proportion with the size of the part). csg|_tt||||dSr.) _chunkindexrrr=r`rr"r#r=szseekableunbundlepart.__init__rccst|jdkr4|dksJd|jd|fn.|t|jksNJd|||j|d|j|d}t|j|jD]@}|d7}|t|7}|t|jkr|j||f|Vq~dS)z/seek to specified chunk and start yielding datarsMust start with chunk 0sUnknown chunk %drN)rKrgr?_tellfp_seekfprWr r)r<Zchunknumposrr"r"r#rCs z#seekableunbundlepart._payloadchunkscCsbt|jD]J\}\}}||kr*|dfS||kr |d||j|ddfSq tddS)z>for a given payload position, return a chunk number and offsetrrs Unknown chunkN)ryrgr()r<rjrZpposZfposr"r"r# _findchunks  $zseekableunbundlepart._findchunkcCs|jSr.)r_r;r"r"r#tellszseekableunbundlepart.tellcCs(|tjkr|}nb|tjkr&|j|}nL|tjkrd|jsP|d}|rP|d}q@|jdd|}ntd|f||jddkr|js|d}|r|d}qd|kr|jddksntd|j|kr$| |\}}t | ||_ ||}t||krttd||_dS)Nrr=rsUnknown whence value: %risOffset out of ranges Seek failed )osSEEK_SETSEEK_CURr_SEEK_ENDr]rKrgr(rkrrJrCrfrKr rr)r<rawhenceZnewposrZinternaloffsetZadjustr"r"r#rXs0           zseekableunbundlepart.seekcCs$|jr|j||SttddS)amove the underlying file pointer This method is meant for internal usage by the bundle2 protocol only. They directly manipulate the low level stream including bundle2 level instruction. Do not use it to implement higher-level logic or methods.sFile pointer is not seekableN)rYrrXNotImplementedErrorr)r<rarqr"r"r#riszseekableunbundlepart._seekfpc CsR|jrNz |jWStyL}z"|jtjkr6d|_nWYd}~n d}~00dS)a,return the file offset, or None if file is not seekable This method is meant for internal usage by the bundle2 protocol only. They directly manipulate the low level stream including bundle2 level instruction. Do not use it to implement higher-level logic or methods.FN)rYrrlIOErrorerrnoZESPIPE)r<er"r"r#rh&s  zseekableunbundlepart._tellfp)r)r)rOrPrQrRr=rCrkrlrmrnrXrirhr$r"r"rr#rs    r)sabortsunsupportedcontents pushracedpushkey)shttpshttps)sheads)sv2) r bookmarksserrorlistkeysrvdigestsremote-changegroup hgtagsfnodesphasesstreamFcCs|dvrtdt}ttt||d<t |tj rZtddtj D}||d<|rfd|d<|j d d }|d krd |d <d|j ddvr|d|d kr|j jd ddd}|j d d}|r|s|d|S)a_return the bundle2 capabilities for a given repo Exists to allow extensions (like evolution) to mutate the capabilities. The returned value is used for servers advertising their capabilities as well as clients advertising their capabilities to servers as part of bundle2 requests. The ``role`` argument specifies which is which. )sclientservers&role argument must be client or serverrcss|]}d|VqdS)sV%iNr"rr"r"r#rZrUzgetrepocaps.. obsmarkersr"spushbackr~sconcurrent-push-modes check-related)srelateds checkheadsr|rslegacy.exchanges uncompressedT)Z untrustedsbundle2.streamr})r rarrrErr Zsupportedincomingversionsr isenabledZ exchangeoptformatsr configZ configlistpopr)rVZ allowpushbackZrolerZsupportedformatZcpmodeZstreamsupportedZfeaturesupportedr"r"r# getrepocapsIs0     rcCs2|d}|s|dkriSt|d}t|S)z0return the bundle capabilities of a peer as dictrgrU)capablerrr)remoterawZcapsblobr"r"r# bundle2capsvs   rcCs|dd}dd|DS)zIextract the list of supported obsmarkers versions from a bundle2caps dictrr"cSs&g|]}|drt|ddqS)VrN)rintrcr"r"r#rrUz%obsmarkersversion..rF)rZobscapsr"r"r#obsmarkersversions rc  Cs|dr0t||d|} t|| ||||| dS|dsHtd|i} d|vr\d| d<t|| } | || t||| |||| } tj || ||d S) Nr01)vfs compressionrrsunknown bundle type: %s obsolescence)sV1rr) rr makechangegroup writebundler rarr_addpartsfromoptsr writechunks)r rVr]filename bundletypeoutgoingoptsrrrrrbundle chunkiterr"r"r#writenewbundles*    rc Csx|ddr|d}|dur(t|}t||||}|jd|d}|d|jd|jvr||jdd|jdd d |d r| d |j r|jd dt j d d t j|jvr|dd|dd rt||dd|ddrt||||ddrt||||dd r@|j|j} t|| |ddd |d d rtt ||j} t | } |jd| ddS)NrTs cg.versionrversionclcount nbchanges%dFrr|s%ln and secret() targetphase exp-sidedatarfsstreamv2)streamstagsfnodescachesrevbranchcachersobsolescence-mandatory phase-heads)rFr Z safeversionrrrrrextrasrevs ancestorsofr ZsecretrREPO_FEATURE_SIDE_DATAfeaturesaddpartbundlestream2addparttagsfnodescacheaddpartrevbranchcacheobsstoreZrelevantmarkersmissingbuildobsmarkerspartZsubsetphaseheadsZ binaryencode) r rVbundlerr]rr cgversionrrZ obsmarkers headsbyphaseZ phasedatar"r"r#rsH             rcCsZt|}g}|jD]$}|j|dd}|r|||gq|rV|jdd|ddS)NF)Zcomputemissingr{rUr)rhgtagsfnodescache unfilteredrZgetfnodeextendrr)rVrrcachernodefnoder"r"r#rs rc st|}|j}tdd|jD]*}|||\}}|||q&fdd}|j d|dddS)NcSs ttfSr.)r/r"r"r"r#rkrUz'addpartrevbranchcache..c3srtD]`\}\}}t|}tt|t|t|V|Vt|D] }|VqLt|D] }|Vq`q dSr.)ritemsr Z fromlocal rbcstructpackrK)branchnodesclosedZ utf8branchrZ branchesdatar"r#generates   z'addpartrevbranchcache..generatecache:rev-branch-cacheFr) Zrevbranchcacher changelog collections defaultdictrZ branchinforevrAr) rVrrrclrrr"rr"rr#rs   rcCs"dd|D}tdt|S)NcSsg|]}|dkr|qS)ssharedr")rZreqr"r"r#rrUz+_formatrequirementsspec..r)rrrr)rr"r"r#_formatrequirementsspecsrcCst|}dtd|f}|S)Ns%s%ss requirements=)rrr)rr2r"r"r#_formatrequirementsparamssrcCs(d}|jr$dddt|jD}|S)z\Formats a repo's wanted sidedata categories into a bytestring for capabilities exchange.rUrcss|]}t|VqdSr.)rrrr"r"r#rsz0format_remote_wanted_sidedata..)Z_wanted_sidedatarr)rVwantedr"r"r#format_remote_wanted_sidedatas  rcCs|d}t|S)Nexp-wanted-sidedata)rread_wanted_sidedata)rsidedata_categoriesr"r"r#read_remote_wanted_sidedata%s rcCs|rt|dStS)Nr)r/r) formattedr"r"r#r*src Ks|ddsdSt|s0tjtdtddd|_|d}|d}|jdd }|s`|rr|srttd d}|j rt |j }|sttd n|j j |vrd }t ||||\}} } t|} t| } |jd | d} | jdd| d d| jdd|d d| jd| d ddS)NrFs<stream data requested but server does not allow this featuresrwell-behaved clients should not be requesting stream data from servers not advertising it; the client may be buggyhint includepats excludepats experimentalsserver.stream-narrow-cloness,server does not support narrow stream clonessPserver has obsolescence markers, but client cannot receive them via stream cloneTstream2r bytecountrr filecount requirements)rFrZallowservergenerationr rrrr rrrrZ_versionZ generatev2Zstreamed_requirementsrrr) rrVrrrrZ narrowstreamZincludeobsmarkersremoteversions filecount bytecountitrrr"r"r#r0sN         rTcCsL|sdSt|j}t|}|dur,tdtj|d|d}|jd||dS)zadd an obsmarker part to the bundler with No part is created if markers is empty. Raises ValueError if the bundler doesn't support any known obsmarker format. Ns0bundler does not support common obsmarker formatT)rrr)rrr Z commonversionr(Z encodemarkersr)rZmarkersrrrrr"r"r#ris  rc s|dkrjt|}|||jdd}|djdjvr`|jddjddd |} nr|d usvJjd krtt d t |\} | t j j vrtt d | t j | fdd} | } tj|| ||dS)zWrite a bundle file and return its filename. Existing files will not be overwritten. If no filename is specified, a temporary file is created. bz2 compression can be turned off. The bundle file will be deleted in case of errors. rrrrrrrFrNrs.old bundle types only supports v1 changegroupss#unknown stream compression type: %sc3s&VD] }|VqdSr.)rr)rrZ compenginerrHr"r#rszwritebundle..chunkiterr)rrrrrrrr rr bundletypesrrr)rr r) r rrrrrrrrrcompr"rr#rzs,         rcCsdd|jdD}d}d}|D]>}|dkr4d}q`|dkrJ||d7}q |dkr ||d7}q |dkrrd|}n|dkrd|}|S)z:logic to combine 0 or more addchangegroup results into onecSsg|]}|ddqS)rrr)rrr"r"r#rrUz-combinechangegroupresults..rrrr=)rW)rsresultsZ changedheadsresultrr"r"r#combinechangegroupresultss  rr)rrrr treemanifestrc Csrddlm}|}|jdd}t||d}d}d|jvrNt|jd}d|jvrt |j st |j j dkrt td |j jtj||j j|j j|j j|j j_t|j i}|jd }|durt||d <|jd } t| |d <t||||jdfd|i|} |jdur`|jjddd} | jdt |j!dd| jdd| dd|"rnJdS)z$apply a changegroup part on the repor) localreporrNrrrs[bundle contains tree manifests, but local repo is non-empty and does not use tree manifestsr targetphaserrrgZ expectedtotalreply:changegroupFrrr%i)#rr`r2rFr rrristreemanifestrVrKrr rrrrAZTREEMANIFEST_REQUIREMENTZresolvestorevfsoptionsr rZsvfsoptionsZwritereporequirementsrrpr]rXrrrrrrK) rsinpartrrjZunpackerversionrZ nbchangesetsZ extrakwargsrZremote_sidedatarrr"r"r#handlechangegroupsV         r)rhsizerycCsg|] }d|qS) digest:%sr")rrr"r"r#rrUrrzc Cs<z|jd}Wn$ty2ttddYn0t|}|jtdvr`ttd|jzt |jd}WnFt yttddYn$tyttddYn0i}|j dd D]J}d |}z|j|}Wn&tyttd|Yn0|||<qt t|j|||} |} d d lm} | |jj| |} t| tjsttd t|t|| | |jd } |jdur|jd}|jdt |j!dd|jdd| ddz | "WnFtjy(}z*ttdt||j#fWYd}~n d}~00|$r8JdS)aapply a bundle10 on the repo, given an url and validation information All the information about the remote bundle to import are given as parameters. The parameters include: - url: the url to the bundle10. - size: the bundle10 file size. It is used to validate what was retrieved by the client matches the server knowledge about the bundle. - digests: a space separated list of the digest types provided as parameters. - digest:: the hexadecimal representation of the digest with that name. Like the size, it is used to validate what was retrieved by the client matches what the server knows about the bundle. When multiple digest types are given, all of them are checked. rhs&remote-changegroup: missing "%s" paramrzs+remote-changegroup does not support %s urlsrs0remote-changegroup: invalid value for param "%s"ryrUrr)exchanges%s: not a bundle version 1.0rgNrrFrrrsbundle at %s is corrupted: %s)%r2rr rrrrschemerrr(rFrrZ digestcheckeropenr r`rrZ readbundlerVrmr Z cg1unpackerZ hidepasswordrpr]rXrrrrrZvalidater!rK)rsrZraw_urlZ parsed_urlrZdigeststyprrZ real_partrjrrrrrur"r"r#handleremotechangegroupsn            rr)rrcCs4t|jd}t|jd}|jdd|i|dS)Nrrrrr2rWrA)rsrrZreplytor"r"r#handlereplychangegroupSsrscheck:bookmarksc Cst|j|}d}d}d}|D]r\}}|jj|}||kr|durV||t|f} n0|durp||t|f} n||t|t|f} t| qdS)zcheck location of bookmarks This part is to be used to detect push race regarding bookmark, it contains binary encoded (bookmark, node) tuple. If the local state does not marks the one in the part, a PushRaced exception is raised s]remote repository changed while pushing - please try again (bookmark "%s" move from %s to %s)sbremote repository changed while pushing - please try again (bookmark "%s" is missing, expected %s)sfremote repository changed while pushing - please try again (bookmark "%s" set on %s, expected missing)N)r binarydecoderV _bookmarksrFrr PushRaced) rsrZbookdataZ msgstandardZ msgmissingZmsgexistbookrZ currentnodefinalmsgr"r"r#handlecheckbookmarksZs( rs check:headscCsr|d}g}t|dkr0|||d}q|r8J|jddrN|t|t|jkrnt ddS)zcheck that head of the repo did not change This is used to detect a push race when using unbundle. This replaces the "heads" argument of unbundle.rbundle2lazylocking:remote repository changed while pushing - please try againN) rKrKr?r rr`rrVheadsr r)rsrhrr"r"r#handlecheckheadss    rscheck:updated-headscCs|d}g}t|dkr0|||d}q|r8J|jddrN|t}|j D]}| |qb|D]}||vrvt dqvdS)aNcheck for race on the heads touched by a push This is similar to 'check:heads' but focus on the heads actually updated during the push. If other activities happen on unrelated heads, it is ignored. This allow server with high traffic to avoid push contention as long as unrelated parts of the graph are involved.rrrrN) rKrKr?r rr`r/rVZ branchmapZ iterheadsr_r r)rsrrrZ currentheadsZlsr"r"r#handlecheckupdatedheadss     rs check:phasesc Cst|}|j}|j}|j}d}t|D]T\}}|D]F} ||| | } | |kr:|t | tj | tj |f} t | q:q.dS)zjcheck that phase boundaries of the repository did not change This is used to detect a push race. sQremote repository changed while pushing - please try again (%s is %s expected %s)N)r rrVrrZ _phasecacherZ iteritemsZphaserrZ phasenamesr r) rsrZ phasetonodesZunfirZ phasecacherZ expectedphaserrZ actualphaserr"r"r#handlecheckphasess   rrcCs*|D]}|jtd|q dS)z3forward output captured on the server to the clients remote: %s N)rKrr rr)rsrrr"r"r# handleoutputsrs replycapscCs(t|}|jdur$t|j||_dS)zqNotify that a reply bundle should be created The payload contains the capabilities information for the replyN)rrKrXrr )rsrrr"r"r#handlereplycapss  r c@seZdZdZdS) AbortFromPartz=Sub-class of Abort that denotes an error from a bundle2 part.N)rOrPrQrRr"r"r"r#r sr r;)r<hintcCst|jd|jdddS)z*Used to transmit abort error over the wirer<r rN)r r2rFrsrr"r"r#handleerrorabortsr s error:pushkey) namespacekeynewoldretrcCsLi}dD] }|j|}|dur|||<qtj|jdfit|dS)z=Used to transmit failure of a mandatory pushkey over the wirerrrrrNr)r2rFr PushkeyFailedr strkwargs)rsrrrrrr"r"r#handleerrorpushkeys  rserror:unsupportedcontent)parttypeparamscCs\i}|jd}|dur ||d<|jd}|durB|d|d<tjfit|dS)z4Used to transmit unknown content error over the wirerNr)r2rFrr rrr)rsrrrr*r2r"r"r#handleerrorunsupportedcontents  rserror:pushraced)r<cCsttd|jddS)z.Used to transmit push race error over the wires push failed:r<N)r Z ResponseErrorrr2r r"r"r#handleerrorpushraced srrx)rcCs.|jd}t|}|jd||fdS)z6retrieve pushkey namespace content stored in a bundle2rrxN)r2rZ decodekeysrKrWrA)rsr namespacerr"r"r#handlelistkeys s rrvrrrrc Cstj}||jd}||jd}||jd}||jd}|jddrT||j||||}||||d}|jd||j d ur|j d } | j d t |jd d | j dd|d d |jr|si} dD]}||jvr|j|| |<qtjfdd|jit | d S)zprocess a pushkey requestrrrrrrrrvN reply:pushkeyrFrrrrrDr)rdecoder2r rr`rVrWrArXrrrrrrr rr) rsrZdecrroldnewrrecordrpartrrr"r"r# handlepushkey s4   r%rwc stj|}jjdd}jdd}|dkr>}jj}|rg|D]`\}}|j } d| d<d| d<|| d<t ||d | d <t |d ur|nd | d < | qRD] } jj dddit| q|D](\}}t|rtd|} t| q|j||rfdd} j| nB|dkrr|D]"\}}||d} jd| qLntd|d S)adtransmit bookmark information The part contains binary encoded bookmark information. The exact behavior of this part can be controlled by the 'bookmarks' mode on the bundle operation. When mode is 'apply' (the default) the bookmark information is applied as is to the unbundling repository. Make sure a 'check:bookmarks' part is issued earlier to check for push races in such update. This behavior is suitable for pushing. When mode is 'records', the information is recorded into the 'bookmarks' records of the bundle operation. This behavior is suitable for pulling. r~sbookmarks-pushkey-compatrwsapplyrfs pushkeycompatrrrUrNr prepushkeythrowTs$cannot accept divergent bookmark %s!cs&D]}jjdit|qdS)Nrv)rv)rVhookrr)Zunused_successrZZallhooksrsr"r#runhookk szhandlebookmark..runhooksrecords)sbookmarksnodesunknown bookmark mode: %s)r&)rrrVr rr\rFr`rrZrrr?r(rrZ isdivergentrr rZ applychangesZ _afterlockrWrAra) rsrZchangesZ pushkeycompatZ bookmarksmoderjZ bookstorerrrZrr*r#r"r)r#handlebookmark7 sR           r+rcCs$t|}t|j|j|dS)z%apply phases from bundle part to repoN)r rZ updatephasesrVrr`)rsrrr"r"r# handlephases{ s r,rcCs4t|jd}t|jd}|jdd|i|dS)(retrieve the result of a pushkey requestrrrvNrrsrrrDr"r"r#handlepushkeyreply sr/rcCs|}|}|jddr2|jdt||jsT|jjj rT|jj ddS|jj ||}|j |j dd|i|jdur|jd}|jd t|jd d |jdd |d d dS) z&add a stream of obsmarkers to the reporsobsmarkers-exchange-debugs&obsmarker-exchange: %i bytes received s3ignoring obsolescence markers, feature not enabled Nrrreply:obsmarkersrFrr)r`rKr rZ writenoi18nrKrrVrreadonlyrZ mergemarkersZinvalidatevolatilesetsrWrArXrrrrr)rsrrjZ markerdatar"r$r"r"r#handleobsmarker s(    r2r0)rrcCs4t|jd}t|jd}|jdd|i|dS)r-rrrNrr.r"r"r#handleobsmarkerreply sr3r{cCs|jddr|t|j}d}|d}|d}t|dksVt|dkrd|j dqz| |||d7}q*| |j d|dS) z|Applies .hgtags fnodes cache entries to the local repo. Payload is pairs of 20 byte changeset nodes and filenodes. rrrrs1ignoring incomplete received .hgtags fnodes data rs'applied %i hgtags fnodes cache entries N) r rr`rrrVrrKrKrZsetfnodewrite)rsrrrwrrr"r"r#handlehgtagsfnodes s     r5s>IIIrcCsdS)zLegacy part, ignored for compatibility with bundles from or for Mercurial before 5.7. Newer Mercurial computes the cache efficiently enough during unbundling that the additional transfer is unnecessary.Nr"r r"r"r# handlerbc sr6spushvarscCsH|jddrDi}|jD] \}}|}d|}|||<q||dS)z5unbundle a bundle2 containing shellvars on the serverspushspushvars.serversUSERVAR_N)r rr3r>rb)rsrrZrrr"r"r#bundle2getvars s r7r)rrrcCst|jd}|r|dng}t|jd}t|jd}|j}t|r^td}t ||j dt |||||dS)Nrrrrs1cannot apply stream clone to non empty repositorysapplying stream bundle )rrr2rrrVrKrr rr rrZ applybundlev2)rsrrrrrVrr"r"r#handlestreamv2bundle s  r8cCst}|j} |d|D]} || | q|rtj|||||d} | j|jht |dddd} |j d| d} | d|t |r| d d tj|jvr| d d t|}| d ||S) aKgenerates bundle2 for widening a narrow clone bundler is the bundle to which data should be added repo is the localrepository instance oldmatcher matches what the client already has newmatcher matches what the client needs (including what it already has) common is set of common heads between server and client known is a set of revs known on the client side (used in ellipses) cgversion is the changegroup version to send ellipses is boolean value telling whether to send ellipses data or not returns bundle2 of the data required for extending s::%ln) oldmatcherZmatcherZ fullnodesFs narrow_widen)rrrrrrfrr)r/rrrArr Z getbundlerrZnullidrrrrrrrrr)rrVr9Z newmatchercommonZknownrZellipsesZ commonnodesrrZpackerZcgdatarrr"r"r# widen_bundle s8      r;)r")N)NNrU)N)FN)NNN)T)NNN)rRZ __future__rrrrtrmrerrrFZi18nrrrrrrr r r r r rrrrrrrrZutilsrrZ interfacesrZurlerrrrrrUrrrr?r@rrArLcompiler&r$r%r+r-r0r6objectr7rT RuntimeErrorrcrertrurorrprrrrrZbundlepriorityrrrrnrr r'r*rrrNrOrWrrrErZDIGESTSkeysrrrrrrrrrrrrrrrrrrZ_remotechangegroupparamsrrrrrrrr rr r rrrrr%r+r,r/r2r3r5rTrr6r7r8r;r"r"r"r#sF @    04 G % * | !  l48x| -  %5 9  - 7 N  %            C