##// END OF EJS Templates
i18n: add hint to digest mismatch message
i18n: add hint to digest mismatch message

File last commit:

r23067:420a0516 stable
r23076:c312ef38 stable
Show More
bundle2.py
1116 lines | 39.1 KiB | text/x-python | PythonLexer
Pierre-Yves David
bundle2: very first version of a bundle2 bundler...
r20801 # bundle2.py - generic container format to transmit arbitrary data.
#
# Copyright 2013 Facebook, Inc.
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2 or any later version.
"""Handling 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.
Pierre-Yves David
bundle2: support bundling of empty part (with a type)...
r20856 the Binary format
Pierre-Yves David
bundle2: very first version of a bundle2 bundler...
r20801 ============================
Mads Kiilerich
spelling: fixes from spell checker
r21024 All numbers are unsigned and big-endian.
Pierre-Yves David
bundle2: very first version of a bundle2 bundler...
r20801
stream level parameters
------------------------
Binary format is as follow
Pierre-Yves David
bundle2: change header size and make them signed (new format)...
r23009 :params size: int32
Pierre-Yves David
bundle2: very first version of a bundle2 bundler...
r20801
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.
Mads Kiilerich
spelling: fixes from spell checker
r21024 The blob contains a space separated list of parameters. Parameters with value
Pierre-Yves David
bundle2: urlquote stream parameter name and value...
r20811 are stored in the form `<name>=<value>`. Both name and value are urlquoted.
Pierre-Yves David
bundle2: support bundling simple parameter...
r20804
Pierre-Yves David
bundle2: refuse empty parameter name...
r20813 Empty name are obviously forbidden.
Pierre-Yves David
bundle2: implement the mandatory/advisory logic for parameter...
r20844 Name MUST start with a letter. If this first letter is lower case, the
Mads Kiilerich
spelling: fixes from spell checker
r21024 parameter is advisory and can be safely ignored. However when the first
Pierre-Yves David
bundle2: implement the mandatory/advisory logic for parameter...
r20844 letter is capital, the parameter is mandatory and the bundling process MUST
stop if he is not able to proceed it.
Pierre-Yves David
bundle2: force the first char of parameter to be an letter....
r20814
Pierre-Yves David
bundle2: clarify stream parameter design in the documentation...
r20808 Stream parameters use a simple textual format for two main reasons:
Pierre-Yves David
bundle2: support bundling simple parameter...
r20804
Mads Kiilerich
spelling: fixes from spell checker
r21024 - Stream level parameters should remain simple and we want to discourage any
Pierre-Yves David
bundle2: clarify stream parameter design in the documentation...
r20808 crazy usage.
Mads Kiilerich
spelling: fixes from spell checker
r21024 - Textual data allow easy human inspection of a bundle2 header in case of
Pierre-Yves David
bundle2: clarify stream parameter design in the documentation...
r20808 troubles.
Any Applicative level options MUST go into a bundle2 part instead.
Pierre-Yves David
bundle2: very first version of a bundle2 bundler...
r20801
Payload part
------------------------
Binary format is as follow
Pierre-Yves David
bundle2: change header size and make them signed (new format)...
r23009 :header size: int32
Pierre-Yves David
bundle2: very first version of a bundle2 bundler...
r20801
The total number of Bytes used by the part headers. When the header is empty
(size = 0) this is interpreted as the end of stream marker.
Pierre-Yves David
bundle2: support bundling of empty part (with a type)...
r20856 :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)
Pierre-Yves David
bundle2: part params
r20877
Mads Kiilerich
spelling: fixes from spell checker
r21024 :parttype: alphanumerical part name
Pierre-Yves David
bundle2: part params
r20877
Pierre-Yves David
bundle2: add an integer id to part...
r20995 :partid: A 32bits integer (unique in the bundle) that can be used to refer
to this part.
Pierre-Yves David
bundle2: part params
r20877 :parameters:
Mads Kiilerich
spelling: fixes from spell checker
r21024 Part's parameter may have arbitrary content, the binary structure is::
Pierre-Yves David
bundle2: part params
r20877
<mandatory-count><advisory-count><param-sizes><param-data>
: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 (<size-of-key>, <size-of-value) for one parameter.
:param-data:
A blob of bytes from which each parameter key and value can be
retrieved using the list of size couples stored in the previous
field.
Mandatory parameters comes first, then the advisory ones.
Pierre-Yves David
bundle2: support bundling of empty part (with a type)...
r20856
Pierre-Yves David
bundle2: forbid duplicate parameter keys...
r21607 Each parameter's key MUST be unique within the part.
Pierre-Yves David
bundle2: support bundling of empty part (with a type)...
r20856 :payload:
Pierre-Yves David
bundle2: support for bundling and unbundling payload...
r20876 payload is a series of `<chunksize><chunkdata>`.
Pierre-Yves David
bundle2: change header size and make them signed (new format)...
r23009 `chunksize` is an int32, `chunkdata` are plain bytes (as much as
Pierre-Yves David
bundle2: support for bundling and unbundling payload...
r20876 `chunksize` says)` The payload part is concluded by a zero size chunk.
The current implementation always produces either zero or one chunk.
Mads Kiilerich
spelling: fixes from spell checker
r21024 This is an implementation limitation that will ultimately be lifted.
Pierre-Yves David
bundle2: add some distinction between mandatory and advisory part...
r20891
Pierre-Yves David
bundle2: change header size and make them signed (new format)...
r23009 `chunksize` can be negative to trigger special case processing. No such
processing is in place yet.
Pierre-Yves David
bundle2: add some distinction between mandatory and advisory part...
r20891 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.
Pierre-Yves David
bundle2: read the whole bundle from stream on abort...
r20892 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.
Pierre-Yves David
bundle2: very first version of a bundle2 bundler...
r20801 """
Pierre-Yves David
bundle2: transmit exception during part generation...
r23067 import sys
Pierre-Yves David
bundle2: a very first version of bundle2 unbundler...
r20802 import util
Pierre-Yves David
bundle2: support bundling simple parameter...
r20804 import struct
Pierre-Yves David
bundle2: urlquote stream parameter name and value...
r20811 import urllib
Pierre-Yves David
bundle2: force the first char of parameter to be an letter....
r20814 import string
Pierre-Yves David
bundle2: add a `obsmarkersversion` function to extract supported version...
r22344 import obsolete
Pierre-Yves David
bundle: introduce a listkey handler...
r21655 import pushkey
Mike Hommey
bundle2: client side support for a part to import external bundles...
r23029 import url
Pierre-Yves David
bundle2: support bundling simple parameter...
r20804
Pierre-Yves David
bundle2: fix raising errors during heads checking...
r21184 import changegroup, error
Pierre-Yves David
bundle2: make sure the unbundler refuse non bundle2 stream...
r20803 from i18n import _
Pierre-Yves David
bundle2: a very first version of bundle2 unbundler...
r20802
Pierre-Yves David
bundle2: support bundling simple parameter...
r20804 _pack = struct.pack
_unpack = struct.unpack
Pierre-Yves David
bundle2: change header size and make them signed (new format)...
r23009 _magicstring = 'HG2Y'
Pierre-Yves David
bundle2: very first version of a bundle2 bundler...
r20801
Pierre-Yves David
bundle2: change header size and make them signed (new format)...
r23009 _fstreamparamsize = '>i'
_fpartheadersize = '>i'
Pierre-Yves David
bundle2: support bundling of empty part (with a type)...
r20856 _fparttypesize = '>B'
Pierre-Yves David
bundle2: add an integer id to part...
r20995 _fpartid = '>I'
Pierre-Yves David
bundle2: change header size and make them signed (new format)...
r23009 _fpayloadsize = '>i'
Pierre-Yves David
bundle2: part params
r20877 _fpartparamcount = '>BB'
Pierre-Yves David
bundle2: support chunk iterator as part data...
r21001 preferedchunksize = 4096
Pierre-Yves David
bundle2: part params
r20877 def _makefpartparamsizes(nbparams):
"""return a struct format to read part parameter sizes
The number parameters is variable so we need to build that format
dynamically.
"""
return '>'+('BB'*nbparams)
Pierre-Yves David
bundle2: support bundling simple parameter...
r20804
Pierre-Yves David
bundle2: introduce a `parthandler` decorator...
r20890 parthandlermapping = {}
Pierre-Yves David
bundle2: first version of a bundle processing...
r20889
Pierre-Yves David
bundle2: make it possible to declare params handled by a part handler...
r21623 def parthandler(parttype, params=()):
Pierre-Yves David
bundle2: introduce a `parthandler` decorator...
r20890 """decorator that register a function as a bundle2 part handler
eg::
Pierre-Yves David
bundle2: declare supported parameters for all handlers...
r21624 @parthandler('myparttype', ('mandatory', 'param', 'handled'))
Pierre-Yves David
bundle2: introduce a `parthandler` decorator...
r20890 def myparttypehandler(...):
'''process a part of type "my part".'''
...
"""
def _decorator(func):
Pierre-Yves David
bundle2: add some distinction between mandatory and advisory part...
r20891 lparttype = parttype.lower() # enforce lower case matching.
assert lparttype not in parthandlermapping
parthandlermapping[lparttype] = func
Pierre-Yves David
bundle2: make it possible to declare params handled by a part handler...
r21623 func.params = frozenset(params)
Pierre-Yves David
bundle2: introduce a `parthandler` decorator...
r20890 return func
return _decorator
Pierre-Yves David
bundle2: first version of a bundle processing...
r20889
Pierre-Yves David
bundle2: record processing results in the bundleoperation object...
r20949 class unbundlerecords(object):
"""keep record of what happens during and unbundle
New records are added using `records.add('cat', obj)`. Where 'cat' is a
Mads Kiilerich
spelling: fixes from spell checker
r21024 category of record and obj is an arbitrary object.
Pierre-Yves David
bundle2: record processing results in the bundleoperation object...
r20949
`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.
"""
def __init__(self):
self._categories = {}
self._sequences = []
Pierre-Yves David
bundle2: add reply awareness to unbundlerecords...
r20996 self._replies = {}
Pierre-Yves David
bundle2: record processing results in the bundleoperation object...
r20949
Pierre-Yves David
bundle2: add reply awareness to unbundlerecords...
r20996 def add(self, category, entry, inreplyto=None):
Pierre-Yves David
bundle2: record processing results in the bundleoperation object...
r20949 """add a new record of a given category.
The entry can then be retrieved in the list returned by
self['category']."""
self._categories.setdefault(category, []).append(entry)
self._sequences.append((category, entry))
Pierre-Yves David
bundle2: add reply awareness to unbundlerecords...
r20996 if inreplyto is not None:
self.getreplies(inreplyto).add(category, entry)
def getreplies(self, partid):
"""get the subrecords that replies to a specific part"""
return self._replies.setdefault(partid, unbundlerecords())
Pierre-Yves David
bundle2: record processing results in the bundleoperation object...
r20949
def __getitem__(self, cat):
return tuple(self._categories.get(cat, ()))
def __iter__(self):
return iter(self._sequences)
def __len__(self):
return len(self._sequences)
def __nonzero__(self):
return bool(self._sequences)
Pierre-Yves David
bundle2: introduce a bundleoperation object...
r20948 class bundleoperation(object):
"""an 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.
"""
Pierre-Yves David
bundle2: make it possible have a global transaction for the unbundling...
r20952 def __init__(self, repo, transactiongetter):
Pierre-Yves David
bundle2: introduce a bundleoperation object...
r20948 self.repo = repo
self.ui = repo.ui
Pierre-Yves David
bundle2: record processing results in the bundleoperation object...
r20949 self.records = unbundlerecords()
Pierre-Yves David
bundle2: make it possible have a global transaction for the unbundling...
r20952 self.gettransaction = transactiongetter
Pierre-Yves David
bundle2: produce a bundle2 reply...
r20997 self.reply = None
Pierre-Yves David
bundle2: introduce a bundleoperation object...
r20948
Pierre-Yves David
bundle2: make it possible have a global transaction for the unbundling...
r20952 class TransactionUnavailable(RuntimeError):
pass
def _notransaction():
"""default method to get a transaction while processing a bundle
Raise an exception to highlight the fact that no transaction was expected
to be created"""
raise TransactionUnavailable()
def processbundle(repo, unbundler, transactiongetter=_notransaction):
Pierre-Yves David
bundle2: first version of a bundle processing...
r20889 """This function process a bundle, apply effect to/from a repo
Pierre-Yves David
bundle2: feed a unbundle20 to the `processbundle` function...
r20947 It iterates over each part then searches for and uses the proper handling
code to process the part. Parts are processed in order.
Pierre-Yves David
bundle2: first version of a bundle processing...
r20889
This is very early version of this function that will be strongly reworked
before final usage.
Pierre-Yves David
bundle2: add some distinction between mandatory and advisory part...
r20891 Unknown Mandatory part will abort the process.
Pierre-Yves David
bundle2: first version of a bundle processing...
r20889 """
Pierre-Yves David
bundle2: make it possible have a global transaction for the unbundling...
r20952 op = bundleoperation(repo, transactiongetter)
Pierre-Yves David
bundle2: first version of a bundle processing...
r20889 # todo:
# - replace this is a init function soon.
# - exception catching
unbundler.params
Pierre-Yves David
bundle2: use an official iterparts method to unbundle parts...
r21129 iterparts = unbundler.iterparts()
Pierre-Yves David
bundle2: lazy unbundle of part payload...
r21019 part = None
Pierre-Yves David
bundle2: read the whole bundle from stream on abort...
r20892 try:
for part in iterparts:
Pierre-Yves David
bundle2: extract processing of part into its own function...
r23008 _processpart(op, part)
Pierre-Yves David
bundle2: decorate exception raised during bundle processing...
r21176 except Exception, exc:
Pierre-Yves David
bundle2: read the whole bundle from stream on abort...
r20892 for part in iterparts:
Pierre-Yves David
bundle2: lazy unbundle of part payload...
r21019 # consume the bundle content
part.read()
Pierre-Yves David
bundle2: decorate exception raised during bundle processing...
r21176 # Small hack to let caller code distinguish exceptions from bundle2
# processing fron the ones from bundle1 processing. This is mostly
# needed to handle different return codes to unbundle according to the
# type of bundle. We should probably clean up or drop this return code
# craziness in a future version.
exc.duringunbundle2 = True
Pierre-Yves David
bundle2: read the whole bundle from stream on abort...
r20892 raise
Pierre-Yves David
bundle2: record processing results in the bundleoperation object...
r20949 return op
Pierre-Yves David
bundle2: first version of a bundle processing...
r20889
Pierre-Yves David
bundle2: extract processing of part into its own function...
r23008 def _processpart(op, part):
"""process 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)."""
try:
parttype = part.type
# part key are matched lower case
key = parttype.lower()
try:
handler = parthandlermapping.get(key)
if handler is None:
Pierre-Yves David
bundle2: add an UnsupportedPartError...
r23010 raise error.UnsupportedPartError(parttype=key)
Pierre-Yves David
bundle2: extract processing of part into its own function...
r23008 op.ui.debug('found a handler for part %r\n' % parttype)
unknownparams = part.mandatorykeys - handler.params
if unknownparams:
unknownparams = list(unknownparams)
unknownparams.sort()
Pierre-Yves David
bundle2: add an UnsupportedPartError...
r23010 raise error.UnsupportedPartError(parttype=key,
Pierre-Yves David
bundle2: extract processing of part into its own function...
r23008 params=unknownparams)
Pierre-Yves David
bundle2: add an UnsupportedPartError...
r23010 except error.UnsupportedPartError, exc:
Pierre-Yves David
bundle2: extract processing of part into its own function...
r23008 if key != parttype: # mandatory parts
raise
op.ui.debug('ignoring unsupported advisory part %s\n' % exc)
return # skip to part processing
# handler is called outside the above try block so that we don't
# risk catching KeyErrors from anything other than the
# parthandlermapping lookup (any KeyError raised by handler()
# itself represents a defect of a different variety).
output = None
if op.reply is not None:
op.ui.pushbuffer(error=True)
output = ''
try:
handler(op, part)
finally:
if output is not None:
output = op.ui.popbuffer()
if output:
outpart = op.reply.newpart('b2x:output', data=output)
outpart.addparam('in-reply-to', str(part.id), mandatory=False)
finally:
# consume the part content to not corrupt the stream.
part.read()
Pierre-Yves David
bundle2: extract capabilities decoding...
r21138 def decodecaps(blob):
"""decode a bundle2 caps bytes blob into a dictionnary
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."""
caps = {}
for line in blob.splitlines():
if not line:
continue
if '=' not in line:
key, vals = line, ()
else:
key, vals = line.split('=', 1)
vals = vals.split(',')
key = urllib.unquote(key)
vals = [urllib.unquote(v) for v in vals]
caps[key] = vals
return caps
Pierre-Yves David
bundle2: capabilities encoding
r21139 def encodecaps(caps):
"""encode a bundle2 caps dictionary into a bytes blob"""
chunks = []
for ca in sorted(caps):
vals = caps[ca]
ca = urllib.quote(ca)
vals = [urllib.quote(v) for v in vals]
if vals:
ca = "%s=%s" % (ca, ','.join(vals))
chunks.append(ca)
return '\n'.join(chunks)
Pierre-Yves David
bundle2: very first version of a bundle2 bundler...
r20801 class bundle20(object):
"""represent an outgoing bundle2 container
Pierre-Yves David
bundle2: have ``newpart`` automatically add the part to the bundle...
r21599 Use the `addparam` method to add stream level parameter. and `newpart` to
Pierre-Yves David
bundle2: support bundling of empty part (with a type)...
r20856 populate it. Then call `getchunks` to retrieve all the binary chunks of
Mads Kiilerich
spelling: fixes from spell checker
r21024 data that compose the bundle2 container."""
Pierre-Yves David
bundle2: very first version of a bundle2 bundler...
r20801
Pierre-Yves David
bundle2: adds a capabilities attribute on bundler20...
r21134 def __init__(self, ui, capabilities=()):
Pierre-Yves David
bundle2: print debug information during bundling...
r20842 self.ui = ui
Pierre-Yves David
bundle2: very first version of a bundle2 bundler...
r20801 self._params = []
self._parts = []
Pierre-Yves David
bundle2: support for capabilities with values...
r21136 self.capabilities = dict(capabilities)
Pierre-Yves David
bundle2: very first version of a bundle2 bundler...
r20801
Pierre-Yves David
bundle2: add a ``bundle20.nbparts`` property...
r21900 @property
def nbparts(self):
"""total number of parts added to the bundler"""
return len(self._parts)
Pierre-Yves David
bundle2: small doc update on the bundler...
r21597 # methods used to defines the bundle2 content
Pierre-Yves David
bundle2: support bundling simple parameter...
r20804 def addparam(self, name, value=None):
"""add a stream level parameter"""
Pierre-Yves David
bundle2: refuse empty parameter name...
r20813 if not name:
raise ValueError('empty parameter name')
Pierre-Yves David
bundle2: force the first char of parameter to be an letter....
r20814 if name[0] not in string.letters:
raise ValueError('non letter first character: %r' % name)
Pierre-Yves David
bundle2: support bundling simple parameter...
r20804 self._params.append((name, value))
Pierre-Yves David
bundle2: support bundling of empty part (with a type)...
r20856 def addpart(self, part):
"""add a new part to the bundle2 container
Mads Kiilerich
spelling: fixes from spell checker
r21024 Parts contains the actual applicative payload."""
Pierre-Yves David
bundle2: add an integer id to part...
r20995 assert part.id is None
part.id = len(self._parts) # very cheap counter
Pierre-Yves David
bundle2: support bundling of empty part (with a type)...
r20856 self._parts.append(part)
Pierre-Yves David
bundle2: add a ``newpart`` method to ``bundle20``...
r21598 def newpart(self, typeid, *args, **kwargs):
Pierre-Yves David
bundle2: warn about error during initialization in ``newpart`` docstring...
r21602 """create 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."""
Pierre-Yves David
bundle2: add a ``newpart`` method to ``bundle20``...
r21598 part = bundlepart(typeid, *args, **kwargs)
Pierre-Yves David
bundle2: have ``newpart`` automatically add the part to the bundle...
r21599 self.addpart(part)
Pierre-Yves David
bundle2: add a ``newpart`` method to ``bundle20``...
r21598 return part
Pierre-Yves David
bundle2: small doc update on the bundler...
r21597 # methods used to generate the bundle2 stream
Pierre-Yves David
bundle2: very first version of a bundle2 bundler...
r20801 def getchunks(self):
Pierre-Yves David
bundle2: print debug information during bundling...
r20842 self.ui.debug('start emission of %s stream\n' % _magicstring)
Pierre-Yves David
bundle2: very first version of a bundle2 bundler...
r20801 yield _magicstring
Pierre-Yves David
bundle2: support bundling simple parameter...
r20804 param = self._paramchunk()
Pierre-Yves David
bundle2: print debug information during bundling...
r20842 self.ui.debug('bundle parameter: %s\n' % param)
Pierre-Yves David
bundle2: support bundling simple parameter...
r20804 yield _pack(_fstreamparamsize, len(param))
if param:
yield param
Pierre-Yves David
bundle2: support bundling of empty part (with a type)...
r20856 self.ui.debug('start of parts\n')
for part in self._parts:
self.ui.debug('bundle part: "%s"\n' % part.type)
for chunk in part.getchunks():
yield chunk
Pierre-Yves David
bundle2: print debug information during bundling...
r20842 self.ui.debug('end of bundle\n')
Pierre-Yves David
bundle2: remove an explicit packing...
r22661 yield _pack(_fpartheadersize, 0)
Pierre-Yves David
bundle2: a very first version of bundle2 unbundler...
r20802
Pierre-Yves David
bundle2: support bundling simple parameter...
r20804 def _paramchunk(self):
"""return a encoded version of all stream parameters"""
blocks = []
Pierre-Yves David
bundle2: support for bundling parameter value...
r20809 for par, value in self._params:
Pierre-Yves David
bundle2: urlquote stream parameter name and value...
r20811 par = urllib.quote(par)
Pierre-Yves David
bundle2: support for bundling parameter value...
r20809 if value is not None:
Pierre-Yves David
bundle2: urlquote stream parameter name and value...
r20811 value = urllib.quote(value)
Pierre-Yves David
bundle2: support for bundling parameter value...
r20809 par = '%s=%s' % (par, value)
blocks.append(par)
Pierre-Yves David
bundle2: support bundling simple parameter...
r20804 return ' '.join(blocks)
Pierre-Yves David
bundle2: extract stream/unpack logic in an unpackermixin...
r21013 class unpackermixin(object):
"""A mixin to extract bytes and struct data from a stream"""
Pierre-Yves David
bundle2: a very first version of bundle2 unbundler...
r20802
Pierre-Yves David
bundle2: extract stream/unpack logic in an unpackermixin...
r21013 def __init__(self, fp):
Pierre-Yves David
bundle2: a very first version of bundle2 unbundler...
r20802 self._fp = fp
def _unpack(self, format):
"""unpack this struct format from the stream"""
data = self._readexact(struct.calcsize(format))
return _unpack(format, data)
def _readexact(self, size):
"""read exactly <size> bytes from the stream"""
return changegroup.readexactly(self._fp, size)
Pierre-Yves David
bundle2: extract stream/unpack logic in an unpackermixin...
r21013
class unbundle20(unpackermixin):
"""interpret a bundle2 stream
Pierre-Yves David
bundle2: use an official iterparts method to unbundle parts...
r21129 This class is fed with a binary stream and yields parts through its
`iterparts` methods."""
Pierre-Yves David
bundle2: extract stream/unpack logic in an unpackermixin...
r21013
Pierre-Yves David
bundle2: make header reading optional...
r21066 def __init__(self, ui, fp, header=None):
"""If header is specified, we do not read it out of the stream."""
Pierre-Yves David
bundle2: extract stream/unpack logic in an unpackermixin...
r21013 self.ui = ui
super(unbundle20, self).__init__(fp)
Pierre-Yves David
bundle2: make header reading optional...
r21066 if header is None:
header = self._readexact(4)
magic, version = header[0:2], header[2:4]
if magic != 'HG':
raise util.Abort(_('not a Mercurial bundle'))
Pierre-Yves David
bundle2: change header size and make them signed (new format)...
r23009 if version != '2Y':
Pierre-Yves David
bundle2: make header reading optional...
r21066 raise util.Abort(_('unknown bundle version %s') % version)
Pierre-Yves David
bundle2: extract stream/unpack logic in an unpackermixin...
r21013 self.ui.debug('start processing of %s stream\n' % header)
Pierre-Yves David
bundle2: a very first version of bundle2 unbundler...
r20802 @util.propertycache
def params(self):
Mads Kiilerich
spelling: fixes from spell checker
r21024 """dictionary of stream level parameters"""
Pierre-Yves David
bundle2: print debug information during unbundling...
r20843 self.ui.debug('reading bundle2 stream parameters\n')
Pierre-Yves David
bundle2: support for unbundling simple parameter...
r20805 params = {}
paramssize = self._unpack(_fstreamparamsize)[0]
Pierre-Yves David
bundle2: detect and disallow a negative chunk size...
r23011 if paramssize < 0:
raise error.BundleValueError('negative bundle param size: %i'
% paramssize)
Pierre-Yves David
bundle2: support for unbundling simple parameter...
r20805 if paramssize:
for p in self._readexact(paramssize).split(' '):
Pierre-Yves David
bundle2: support for unbundling parameter value...
r20810 p = p.split('=', 1)
Pierre-Yves David
bundle2: urlunquote stream parameter name and value during unbundling...
r20812 p = [urllib.unquote(i) for i in p]
Pierre-Yves David
bundle2: support for unbundling parameter value...
r20810 if len(p) < 2:
p.append(None)
Pierre-Yves David
bundle2: implement the mandatory/advisory logic for parameter...
r20844 self._processparam(*p)
Pierre-Yves David
bundle2: support for unbundling parameter value...
r20810 params[p[0]] = p[1]
Pierre-Yves David
bundle2: support for unbundling simple parameter...
r20805 return params
Pierre-Yves David
bundle2: a very first version of bundle2 unbundler...
r20802
Pierre-Yves David
bundle2: implement the mandatory/advisory logic for parameter...
r20844 def _processparam(self, name, value):
"""process 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.
"""
if not name:
raise ValueError('empty parameter name')
if name[0] not in string.letters:
raise ValueError('non letter first character: %r' % name)
# Some logic will be later added here to try to process the option for
# a dict of known parameter.
if name[0].islower():
self.ui.debug("ignoring unknown parameter %r\n" % name)
else:
Pierre-Yves David
bundle2: add an UnsupportedPartError...
r23010 raise error.UnsupportedPartError(params=(name,))
Pierre-Yves David
bundle2: implement the mandatory/advisory logic for parameter...
r20844
Pierre-Yves David
bundle2: use an official iterparts method to unbundle parts...
r21129 def iterparts(self):
Pierre-Yves David
bundle2: a very first version of bundle2 unbundler...
r20802 """yield all parts contained in the stream"""
# make sure param have been loaded
self.params
Pierre-Yves David
bundle2: print debug information during unbundling...
r20843 self.ui.debug('start extraction of bundle2 parts\n')
Pierre-Yves David
bundle2: add an unbundle part responsible from unbundling part...
r21014 headerblock = self._readpartheader()
while headerblock is not None:
part = unbundlepart(self.ui, headerblock, self._fp)
Pierre-Yves David
bundle2: a very first version of bundle2 unbundler...
r20802 yield part
Pierre-Yves David
bundle2: add an unbundle part responsible from unbundling part...
r21014 headerblock = self._readpartheader()
Pierre-Yves David
bundle2: print debug information during unbundling...
r20843 self.ui.debug('end of bundle2 stream\n')
Pierre-Yves David
bundle2: a very first version of bundle2 unbundler...
r20802
Pierre-Yves David
bundle2: add an unbundle part responsible from unbundling part...
r21014 def _readpartheader(self):
"""reads a part header size and return the bytes blob
Pierre-Yves David
bundle2: support unbundling empty part...
r20864
Pierre-Yves David
bundle2: add an unbundle part responsible from unbundling part...
r21014 returns None if empty"""
Pierre-Yves David
bundle2: support unbundling empty part...
r20864 headersize = self._unpack(_fpartheadersize)[0]
Pierre-Yves David
bundle2: detect and disallow a negative chunk size...
r23011 if headersize < 0:
raise error.BundleValueError('negative part header size: %i'
% headersize)
Pierre-Yves David
bundle2: support unbundling empty part...
r20864 self.ui.debug('part header size: %i\n' % headersize)
Pierre-Yves David
bundle2: add an unbundle part responsible from unbundling part...
r21014 if headersize:
return self._readexact(headersize)
return None
Pierre-Yves David
bundle2: support unbundling empty part...
r20864
Pierre-Yves David
bundle2: a very first version of bundle2 unbundler...
r20802
Pierre-Yves David
bundle2: rename part to bundlepart...
r21005 class bundlepart(object):
Pierre-Yves David
bundle2: support bundling of empty part (with a type)...
r20856 """A bundle2 part contains application level payload
The part `type` is used to route the part to the application level
handler.
Pierre-Yves David
bundle2: the ability to set ``data`` attribute of the part is now official...
r21604
The part payload is contained in ``part.data``. It could be raw bytes or a
Pierre-Yves David
bundle2: introduce a ``addparam`` method on part...
r21605 generator of byte chunks.
You can add parameters to the part using the ``addparam`` method.
Parameters can be either mandatory (default) or advisory. Remote side
should be able to safely ignore the advisory ones.
Both data and parameters cannot be modified after the generation has begun.
Pierre-Yves David
bundle2: support bundling of empty part (with a type)...
r20856 """
Pierre-Yves David
bundle2: part params
r20877 def __init__(self, parttype, mandatoryparams=(), advisoryparams=(),
data=''):
Pierre-Yves David
bundle2: add an integer id to part...
r20995 self.id = None
Pierre-Yves David
bundle2: support bundling of empty part (with a type)...
r20856 self.type = parttype
Pierre-Yves David
bundle2: the ability to set ``data`` attribute of the part is now official...
r21604 self._data = data
Pierre-Yves David
bundle2: introduce a ``addparam`` method on part...
r21605 self._mandatoryparams = list(mandatoryparams)
self._advisoryparams = list(advisoryparams)
Pierre-Yves David
bundle2: forbid duplicate parameter keys...
r21607 # checking for duplicated entries
self._seenparams = set()
for pname, __ in self._mandatoryparams + self._advisoryparams:
if pname in self._seenparams:
raise RuntimeError('duplicated params: %s' % pname)
self._seenparams.add(pname)
Pierre-Yves David
bundle2: track life cycle of parts...
r21601 # status of the part's generation:
# - None: not started,
# - False: currently generated,
# - True: generation done.
self._generated = None
Pierre-Yves David
bundle2: support bundling of empty part (with a type)...
r20856
Pierre-Yves David
bundle2: the ability to set ``data`` attribute of the part is now official...
r21604 # methods used to defines the part content
def __setdata(self, data):
if self._generated is not None:
Pierre-Yves David
bundle2: move exception classes into the error module...
r21618 raise error.ReadOnlyPartError('part is being generated')
Pierre-Yves David
bundle2: the ability to set ``data`` attribute of the part is now official...
r21604 self._data = data
def __getdata(self):
return self._data
data = property(__getdata, __setdata)
Pierre-Yves David
bundle2: introduce a ``addparam`` method on part...
r21605 @property
def mandatoryparams(self):
# make it an immutable tuple to force people through ``addparam``
return tuple(self._mandatoryparams)
@property
def advisoryparams(self):
# make it an immutable tuple to force people through ``addparam``
return tuple(self._advisoryparams)
def addparam(self, name, value='', mandatory=True):
if self._generated is not None:
Pierre-Yves David
bundle2: move exception classes into the error module...
r21618 raise error.ReadOnlyPartError('part is being generated')
Pierre-Yves David
bundle2: forbid duplicate parameter keys...
r21607 if name in self._seenparams:
raise ValueError('duplicated params: %s' % name)
self._seenparams.add(name)
Pierre-Yves David
bundle2: introduce a ``addparam`` method on part...
r21605 params = self._advisoryparams
if mandatory:
params = self._mandatoryparams
params.append((name, value))
Pierre-Yves David
bundle2: track life cycle of parts...
r21601 # methods used to generates the bundle2 stream
Pierre-Yves David
bundle2: support bundling of empty part (with a type)...
r20856 def getchunks(self):
Pierre-Yves David
bundle2: track life cycle of parts...
r21601 if self._generated is not None:
raise RuntimeError('part can only be consumed once')
self._generated = False
Pierre-Yves David
bundle2: part params
r20877 #### header
## parttype
Pierre-Yves David
bundle2: support bundling of empty part (with a type)...
r20856 header = [_pack(_fparttypesize, len(self.type)),
Pierre-Yves David
bundle2: add an integer id to part...
r20995 self.type, _pack(_fpartid, self.id),
Pierre-Yves David
bundle2: support bundling of empty part (with a type)...
r20856 ]
Pierre-Yves David
bundle2: part params
r20877 ## parameters
# count
manpar = self.mandatoryparams
advpar = self.advisoryparams
header.append(_pack(_fpartparamcount, len(manpar), len(advpar)))
# size
parsizes = []
for key, value in manpar:
parsizes.append(len(key))
parsizes.append(len(value))
for key, value in advpar:
parsizes.append(len(key))
parsizes.append(len(value))
paramsizes = _pack(_makefpartparamsizes(len(parsizes) / 2), *parsizes)
header.append(paramsizes)
# key, value
for key, value in manpar:
header.append(key)
header.append(value)
for key, value in advpar:
header.append(key)
header.append(value)
## finalize header
Pierre-Yves David
bundle2: support bundling of empty part (with a type)...
r20856 headerchunk = ''.join(header)
yield _pack(_fpartheadersize, len(headerchunk))
yield headerchunk
Pierre-Yves David
bundle2: part params
r20877 ## payload
Pierre-Yves David
bundle2: transmit exception during part generation...
r23067 try:
for chunk in self._payloadchunks():
yield _pack(_fpayloadsize, len(chunk))
yield chunk
except Exception, exc:
# backup exception data for later
exc_info = sys.exc_info()
msg = 'unexpected error: %s' % exc
interpart = bundlepart('b2x:error:abort', [('message', msg)])
interpart.id = 0
yield _pack(_fpayloadsize, -1)
for chunk in interpart.getchunks():
yield chunk
# abort current part payload
yield _pack(_fpayloadsize, 0)
raise exc_info[0], exc_info[1], exc_info[2]
Pierre-Yves David
bundle2: extract a _payloadchunks method for part...
r21000 # end of payload
yield _pack(_fpayloadsize, 0)
Pierre-Yves David
bundle2: track life cycle of parts...
r21601 self._generated = True
Pierre-Yves David
bundle2: extract a _payloadchunks method for part...
r21000
def _payloadchunks(self):
"""yield chunks of a the part payload
Exists to handle the different methods to provide data to a part."""
Pierre-Yves David
bundle2: support for bundling and unbundling payload...
r20876 # we only support fixed size data now.
# This will be improved in the future.
Pierre-Yves David
bundle2: support chunk iterator as part data...
r21001 if util.safehasattr(self.data, 'next'):
buff = util.chunkbuffer(self.data)
chunk = buff.read(preferedchunksize)
while chunk:
yield chunk
chunk = buff.read(preferedchunksize)
elif len(self.data):
Pierre-Yves David
bundle2: support for bundling and unbundling payload...
r20876 yield self.data
Pierre-Yves David
bundle2: a very first version of bundle2 unbundler...
r20802
Pierre-Yves David
bundle2: add a interrupt mechanism...
r23066
flaginterrupt = -1
class interrupthandler(unpackermixin):
"""read one part and process it with restricted capability
This allows to transmit exception raised on the producer size during part
iteration while the consumer is reading a part.
Part processed in this manner only have access to a ui object,"""
def __init__(self, ui, fp):
super(interrupthandler, self).__init__(fp)
self.ui = ui
def _readpartheader(self):
"""reads a part header size and return the bytes blob
returns None if empty"""
headersize = self._unpack(_fpartheadersize)[0]
if headersize < 0:
raise error.BundleValueError('negative part header size: %i'
% headersize)
self.ui.debug('part header size: %i\n' % headersize)
if headersize:
return self._readexact(headersize)
return None
def __call__(self):
self.ui.debug('bundle2 stream interruption, looking for a part.\n')
headerblock = self._readpartheader()
if headerblock is None:
self.ui.debug('no part found during iterruption.\n')
return
part = unbundlepart(self.ui, headerblock, self._fp)
op = interruptoperation(self.ui)
_processpart(op, part)
class interruptoperation(object):
"""A limited operation to be use by part handler during interruption
It only have access to an ui object.
"""
def __init__(self, ui):
self.ui = ui
self.reply = None
@property
def repo(self):
raise RuntimeError('no repo access from stream interruption')
def gettransaction(self):
raise TransactionUnavailable('no repo access from stream interruption')
Pierre-Yves David
bundle2: add an unbundle part responsible from unbundling part...
r21014 class unbundlepart(unpackermixin):
"""a bundle part read from a bundle"""
def __init__(self, ui, header, fp):
super(unbundlepart, self).__init__(fp)
self.ui = ui
# unbundle state attr
self._headerdata = header
Pierre-Yves David
bundle2: move the fromheader closure into the class itself...
r21015 self._headeroffset = 0
Pierre-Yves David
bundle2: lazy unbundle of part payload...
r21019 self._initialized = False
self.consumed = False
Pierre-Yves David
bundle2: add an unbundle part responsible from unbundling part...
r21014 # part data
self.id = None
self.type = None
self.mandatoryparams = None
self.advisoryparams = None
Pierre-Yves David
bundle2: introduce a ``params`` dictionary on unbundled parts...
r21610 self.params = None
Pierre-Yves David
bundle2: expose mandatory params in a mandatorykeys attribute...
r21612 self.mandatorykeys = ()
Pierre-Yves David
bundle2: lazy unbundle of part payload...
r21019 self._payloadstream = None
self._readheader()
Pierre-Yves David
bundle2: add an unbundle part responsible from unbundling part...
r21014
Pierre-Yves David
bundle2: move the fromheader closure into the class itself...
r21015 def _fromheader(self, size):
"""return the next <size> byte from the header"""
offset = self._headeroffset
data = self._headerdata[offset:(offset + size)]
Pierre-Yves David
bundle2: lazy unbundle of part payload...
r21019 self._headeroffset = offset + size
Pierre-Yves David
bundle2: move the fromheader closure into the class itself...
r21015 return data
Pierre-Yves David
bundle2: move unpackheader closure into the class...
r21016 def _unpackheader(self, format):
"""read given format from header
This automatically compute the size of the format to read."""
data = self._fromheader(struct.calcsize(format))
return _unpack(format, data)
Pierre-Yves David
bundle2: introduce an ``_initparams`` method...
r21608 def _initparams(self, mandatoryparams, advisoryparams):
"""internal function to setup all logic related parameters"""
Pierre-Yves David
bundle2: make sure unbundled part param are read-only...
r21609 # make it read only to prevent people touching it by mistake.
self.mandatoryparams = tuple(mandatoryparams)
self.advisoryparams = tuple(advisoryparams)
Pierre-Yves David
bundle2: introduce a ``params`` dictionary on unbundled parts...
r21610 # user friendly UI
self.params = dict(self.mandatoryparams)
self.params.update(dict(self.advisoryparams))
Pierre-Yves David
bundle2: expose mandatory params in a mandatorykeys attribute...
r21612 self.mandatorykeys = frozenset(p[0] for p in mandatoryparams)
Pierre-Yves David
bundle2: introduce an ``_initparams`` method...
r21608
Pierre-Yves David
bundle2: lazy unbundle of part payload...
r21019 def _readheader(self):
Pierre-Yves David
bundle2: add an unbundle part responsible from unbundling part...
r21014 """read the header and setup the object"""
Pierre-Yves David
bundle2: move unpackheader closure into the class...
r21016 typesize = self._unpackheader(_fparttypesize)[0]
Pierre-Yves David
bundle2: move the fromheader closure into the class itself...
r21015 self.type = self._fromheader(typesize)
Pierre-Yves David
bundle2: add an unbundle part responsible from unbundling part...
r21014 self.ui.debug('part type: "%s"\n' % self.type)
Pierre-Yves David
bundle2: move unpackheader closure into the class...
r21016 self.id = self._unpackheader(_fpartid)[0]
Pierre-Yves David
bundle2: add an unbundle part responsible from unbundling part...
r21014 self.ui.debug('part id: "%s"\n' % self.id)
## reading parameters
# param count
Pierre-Yves David
bundle2: move unpackheader closure into the class...
r21016 mancount, advcount = self._unpackheader(_fpartparamcount)
Pierre-Yves David
bundle2: add an unbundle part responsible from unbundling part...
r21014 self.ui.debug('part parameters: %i\n' % (mancount + advcount))
# param size
Pierre-Yves David
bundle2: move unpackheader closure into the class...
r21016 fparamsizes = _makefpartparamsizes(mancount + advcount)
paramsizes = self._unpackheader(fparamsizes)
Pierre-Yves David
bundle2: add an unbundle part responsible from unbundling part...
r21014 # make it a list of couple again
paramsizes = zip(paramsizes[::2], paramsizes[1::2])
# split mandatory from advisory
mansizes = paramsizes[:mancount]
advsizes = paramsizes[mancount:]
# retrive param value
manparams = []
for key, value in mansizes:
Pierre-Yves David
bundle2: move the fromheader closure into the class itself...
r21015 manparams.append((self._fromheader(key), self._fromheader(value)))
Pierre-Yves David
bundle2: add an unbundle part responsible from unbundling part...
r21014 advparams = []
for key, value in advsizes:
Pierre-Yves David
bundle2: move the fromheader closure into the class itself...
r21015 advparams.append((self._fromheader(key), self._fromheader(value)))
Pierre-Yves David
bundle2: introduce an ``_initparams`` method...
r21608 self._initparams(manparams, advparams)
Pierre-Yves David
bundle2: add an unbundle part responsible from unbundling part...
r21014 ## part payload
Pierre-Yves David
bundle2: lazy unbundle of part payload...
r21019 def payloadchunks():
Pierre-Yves David
bundle2: add an unbundle part responsible from unbundling part...
r21014 payloadsize = self._unpack(_fpayloadsize)[0]
self.ui.debug('payload chunk size: %i\n' % payloadsize)
Pierre-Yves David
bundle2: lazy unbundle of part payload...
r21019 while payloadsize:
Pierre-Yves David
bundle2: add a interrupt mechanism...
r23066 if payloadsize == flaginterrupt:
# interruption detection, the handler will now read a
# single part and process it.
interrupthandler(self.ui, self._fp)()
elif payloadsize < 0:
msg = 'negative payload chunk size: %i' % payloadsize
Pierre-Yves David
bundle2: detect and disallow a negative chunk size...
r23011 raise error.BundleValueError(msg)
Pierre-Yves David
bundle2: add a interrupt mechanism...
r23066 else:
yield self._readexact(payloadsize)
Pierre-Yves David
bundle2: lazy unbundle of part payload...
r21019 payloadsize = self._unpack(_fpayloadsize)[0]
self.ui.debug('payload chunk size: %i\n' % payloadsize)
self._payloadstream = util.chunkbuffer(payloadchunks())
# we read the data, tell it
self._initialized = True
def read(self, size=None):
"""read payload data"""
if not self._initialized:
self._readheader()
if size is None:
data = self._payloadstream.read()
else:
data = self._payloadstream.read(size)
if size is None or len(data) < size:
self.consumed = True
return data
Pierre-Yves David
bundle2: change header size and make them signed (new format)...
r23009 capabilities = {'HG2Y': (),
Pierre-Yves David
obsmarker: move bundle2caps from the localrepo class to the bundle2 module...
r22341 'b2x:listkeys': (),
'b2x:pushkey': (),
'b2x:changegroup': (),
Mike Hommey
bundle2: client side support for a part to import external bundles...
r23029 'digests': tuple(sorted(util.DIGESTS.keys())),
'b2x:remote-changegroup': ('http', 'https'),
Pierre-Yves David
obsmarker: move bundle2caps from the localrepo class to the bundle2 module...
r22341 }
Pierre-Yves David
bundle2: introduce a `getrepocaps` to retrieve the bundle2 caps of a repo...
r22342 def getrepocaps(repo):
"""return the bundle2 capabilities for a given repo
Pierre-Yves David
bundle2: advertise the obsmarker part in bundle2 capabilities
r22343 Exists to allow extensions (like evolution) to mutate the capabilities.
Pierre-Yves David
bundle2: introduce a `getrepocaps` to retrieve the bundle2 caps of a repo...
r22342 """
Pierre-Yves David
bundle2: advertise the obsmarker part in bundle2 capabilities
r22343 caps = capabilities.copy()
Durham Goode
obsolete: add exchange option...
r22953 if obsolete.isenabled(repo, obsolete.exchangeopt):
Pierre-Yves David
bundle2: advertise the obsmarker part in bundle2 capabilities
r22343 supportedformat = tuple('V%i' % v for v in obsolete.formats)
caps['b2x:obsmarkers'] = supportedformat
return caps
Pierre-Yves David
bundle2: introduce a `getrepocaps` to retrieve the bundle2 caps of a repo...
r22342
Pierre-Yves David
bundle2: introduce a bundle2caps function...
r21644 def bundle2caps(remote):
"""return the bundlecapabilities of a peer as dict"""
raw = remote.capable('bundle2-exp')
if not raw and raw != '':
return {}
capsblob = urllib.unquote(remote.capable('bundle2-exp'))
return decodecaps(capsblob)
Pierre-Yves David
bundle2: add an unbundle part responsible from unbundling part...
r21014
Pierre-Yves David
bundle2: add a `obsmarkersversion` function to extract supported version...
r22344 def obsmarkersversion(caps):
"""extract the list of supported obsmarkers versions from a bundle2caps dict
"""
obscaps = caps.get('b2x:obsmarkers', ())
return [int(c[1:]) for c in obscaps if c.startswith('V')]
Pierre-Yves David
bundle2: move all parts into a `bx2` namespace...
r21146 @parthandler('b2x:changegroup')
Pierre-Yves David
bundle2: use reply part to return result of addchangegroup...
r20998 def handlechangegroup(op, inpart):
Pierre-Yves David
bundle2: first crude version of bundling changeset with bundle2...
r20950 """apply a changegroup part on the repo
This is a very early implementation that will massive rework before being
inflicted to any end-user.
"""
Pierre-Yves David
bundle2: make it possible have a global transaction for the unbundling...
r20952 # Make sure we trigger a transaction creation
#
# The addchangegroup function will get a transaction object by itself, but
# we need to make sure we trigger the creation of a transaction object used
# for the whole processing scope.
op.gettransaction()
Sune Foldager
changegroup: rename bundle-related functions and classes...
r22390 cg = changegroup.cg1unpacker(inpart, 'UN')
Pierre-Yves David
bundle2: add a comment about addchangegroup source and url
r23001 # the source and url passed here are overwritten by the one contained in
# the transaction.hookargs argument. So 'bundle2' is a placeholder
Pierre-Yves David
bundle2: first crude version of bundling changeset with bundle2...
r20950 ret = changegroup.addchangegroup(op.repo, cg, 'bundle2', 'bundle2')
op.records.add('changegroup', {'return': ret})
Pierre-Yves David
bundle2: use reply part to return result of addchangegroup...
r20998 if op.reply is not None:
# This is definitly not the final form of this
# return. But one need to start somewhere.
Pierre-Yves David
bundle2: update part creators to ``addparam`` when relevant...
r21606 part = op.reply.newpart('b2x:reply:changegroup')
part.addparam('in-reply-to', str(inpart.id), mandatory=False)
part.addparam('return', '%i' % ret, mandatory=False)
Pierre-Yves David
bundle2: lazy unbundle of part payload...
r21019 assert not inpart.read()
Pierre-Yves David
bundle2: first crude version of bundling changeset with bundle2...
r20950
Mike Hommey
bundle2: client side support for a part to import external bundles...
r23029 _remotechangegroupparams = tuple(['url', 'size', 'digests'] +
['digest:%s' % k for k in util.DIGESTS.keys()])
@parthandler('b2x:remote-changegroup', _remotechangegroupparams)
def handleremotechangegroup(op, inpart):
"""apply 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:<digest-type>: 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.
"""
try:
raw_url = inpart.params['url']
except KeyError:
raise util.Abort(_('remote-changegroup: missing "%s" param') % 'url')
parsed_url = util.url(raw_url)
if parsed_url.scheme not in capabilities['b2x:remote-changegroup']:
raise util.Abort(_('remote-changegroup does not support %s urls') %
parsed_url.scheme)
try:
size = int(inpart.params['size'])
except ValueError:
raise util.Abort(_('remote-changegroup: invalid value for param "%s"')
% 'size')
except KeyError:
raise util.Abort(_('remote-changegroup: missing "%s" param') % 'size')
digests = {}
for typ in inpart.params.get('digests', '').split():
param = 'digest:%s' % typ
try:
value = inpart.params[param]
except KeyError:
raise util.Abort(_('remote-changegroup: missing "%s" param') %
param)
digests[typ] = value
real_part = util.digestchecker(url.open(op.ui, raw_url), size, digests)
# Make sure we trigger a transaction creation
#
# The addchangegroup function will get a transaction object by itself, but
# we need to make sure we trigger the creation of a transaction object used
# for the whole processing scope.
op.gettransaction()
import exchange
cg = exchange.readbundle(op.repo.ui, real_part, raw_url)
if not isinstance(cg, changegroup.cg1unpacker):
raise util.Abort(_('%s: not a bundle version 1.0') %
util.hidepassword(raw_url))
ret = changegroup.addchangegroup(op.repo, cg, 'bundle2', 'bundle2')
op.records.add('changegroup', {'return': ret})
if op.reply is not None:
# This is definitly not the final form of this
# return. But one need to start somewhere.
part = op.reply.newpart('b2x:reply:changegroup')
part.addparam('in-reply-to', str(inpart.id), mandatory=False)
part.addparam('return', '%i' % ret, mandatory=False)
try:
real_part.validate()
except util.Abort, e:
raise util.Abort(_('bundle at %s is corrupted:\n%s') %
(util.hidepassword(raw_url), str(e)))
assert not inpart.read()
Pierre-Yves David
bundle2: declare supported parameters for all handlers...
r21624 @parthandler('b2x:reply:changegroup', ('return', 'in-reply-to'))
Mike Hommey
bundle2: rename functions that have the same name
r22548 def handlereplychangegroup(op, inpart):
Pierre-Yves David
bundle2: use the new ``part.params`` dictionary...
r21611 ret = int(inpart.params['return'])
replyto = int(inpart.params['in-reply-to'])
op.records.add('changegroup', {'return': ret}, replyto)
Pierre-Yves David
bundle2: first crude version of bundling changeset with bundle2...
r20950
Pierre-Yves David
bundle2: move all parts into a `bx2` namespace...
r21146 @parthandler('b2x:check:heads')
Mike Hommey
bundle2: rename functions that have the same name
r22548 def handlecheckheads(op, inpart):
Pierre-Yves David
bundle2: add a "check:heads" handler...
r21060 """check 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."""
h = inpart.read(20)
heads = []
while len(h) == 20:
heads.append(h)
h = inpart.read(20)
assert not h
if heads != op.repo.heads():
Pierre-Yves David
bundle2: add an error message to push race error...
r21185 raise error.PushRaced('repository changed while pushing - '
'please try again')
Pierre-Yves David
bundle2: introduce `replycaps` part for on-demand reply...
r21130
Pierre-Yves David
bundle2: move all parts into a `bx2` namespace...
r21146 @parthandler('b2x:output')
Pierre-Yves David
bundle2: capture remote stdout while unbundling...
r21131 def handleoutput(op, inpart):
"""forward output captured on the server to the client"""
for line in inpart.read().splitlines():
op.ui.write(('remote: %s\n' % line))
Pierre-Yves David
bundle2: move all parts into a `bx2` namespace...
r21146 @parthandler('b2x:replycaps')
Pierre-Yves David
bundle2: introduce `replycaps` part for on-demand reply...
r21130 def handlereplycaps(op, inpart):
"""Notify that a reply bundle should be created
Pierre-Yves David
bundle2: extract capabilities decoding...
r21138 The payload contains the capabilities information for the reply"""
caps = decodecaps(inpart.read())
Pierre-Yves David
bundle2: introduce `replycaps` part for on-demand reply...
r21130 if op.reply is None:
Pierre-Yves David
bundle2: add capabilities support in `replycaps` part...
r21135 op.reply = bundle20(op.ui, caps)
Pierre-Yves David
bundle2: capture remote stdout while unbundling...
r21131
Pierre-Yves David
bundle2: declare supported parameters for all handlers...
r21624 @parthandler('b2x:error:abort', ('message', 'hint'))
Pierre-Yves David
bundle2: gracefully handle abort during unbundle...
r21177 def handlereplycaps(op, inpart):
"""Used to transmit abort error over the wire"""
Pierre-Yves David
bundle2: use the new ``part.params`` dictionary...
r21611 raise util.Abort(inpart.params['message'], hint=inpart.params.get('hint'))
Pierre-Yves David
bundle2: gracefully handle UnknownPartError during unbundle...
r21183
Pierre-Yves David
bundle2: declare supported parameters for all handlers...
r21624 @parthandler('b2x:error:unsupportedcontent', ('parttype', 'params'))
Pierre-Yves David
bundle2: gracefully handle UnknownPartError during unbundle...
r21183 def handlereplycaps(op, inpart):
Pierre-Yves David
bundle2: rename b2x:error:unknownpart to b2x:error:unsupportedcontent...
r21619 """Used to transmit unknown content error over the wire"""
Pierre-Yves David
bundle2: support transmission of params error over the wire...
r21622 kwargs = {}
Pierre-Yves David
bundle2: support None parttype in BundleValueError...
r21627 parttype = inpart.params.get('parttype')
if parttype is not None:
kwargs['parttype'] = parttype
Pierre-Yves David
bundle2: support transmission of params error over the wire...
r21622 params = inpart.params.get('params')
if params is not None:
kwargs['params'] = params.split('\0')
Pierre-Yves David
bundle2: add an UnsupportedPartError...
r23010 raise error.UnsupportedPartError(**kwargs)
Pierre-Yves David
bundle2: gracefully handle PushRaced error during unbundle...
r21186
Pierre-Yves David
bundle2: make it possible to declare params handled by a part handler...
r21623 @parthandler('b2x:error:pushraced', ('message',))
Pierre-Yves David
bundle2: gracefully handle PushRaced error during unbundle...
r21186 def handlereplycaps(op, inpart):
"""Used to transmit push race error over the wire"""
Pierre-Yves David
bundle2: use the new ``part.params`` dictionary...
r21611 raise error.ResponseError(_('push failed:'), inpart.params['message'])
Pierre-Yves David
bundle: introduce a listkey handler...
r21655
@parthandler('b2x:listkeys', ('namespace',))
def handlelistkeys(op, inpart):
"""retrieve pushkey namespace content stored in a bundle2"""
namespace = inpart.params['namespace']
r = pushkey.decodekeys(inpart.read())
op.records.add('listkeys', (namespace, r))
Pierre-Yves David
bundle2: add ``pushkey`` support...
r21660
@parthandler('b2x:pushkey', ('namespace', 'key', 'old', 'new'))
def handlepushkey(op, inpart):
"""process a pushkey request"""
dec = pushkey.decode
namespace = dec(inpart.params['namespace'])
key = dec(inpart.params['key'])
old = dec(inpart.params['old'])
new = dec(inpart.params['new'])
ret = op.repo.pushkey(namespace, key, old, new)
record = {'namespace': namespace,
'key': key,
'old': old,
'new': new}
op.records.add('pushkey', record)
if op.reply is not None:
rpart = op.reply.newpart('b2x:reply:pushkey')
rpart.addparam('in-reply-to', str(inpart.id), mandatory=False)
rpart.addparam('return', '%i' % ret, mandatory=False)
@parthandler('b2x:reply:pushkey', ('return', 'in-reply-to'))
def handlepushkeyreply(op, inpart):
"""retrieve the result of a pushkey request"""
ret = int(inpart.params['return'])
partid = int(inpart.params['in-reply-to'])
op.records.add('pushkey', {'return': ret}, partid)
Pierre-Yves David
bundle2: add an obsmarkers part handler...
r22336
@parthandler('b2x:obsmarkers')
def handleobsmarker(op, inpart):
"""add a stream of obsmarkers to the repo"""
tr = op.gettransaction()
Pierre-Yves David
obsmarker: write a message with the number of markers added through bundle2
r22337 new = op.repo.obsstore.mergemarkers(tr, inpart.read())
if new:
op.repo.ui.status(_('%i new obsolescence markers\n') % new)
Pierre-Yves David
obssmarker: add a bundle2 record with the number of markers added
r22338 op.records.add('obsmarkers', {'new': new})
Pierre-Yves David
obsmarker: produce a reply part for markers received through bundle2
r22340 if op.reply is not None:
rpart = op.reply.newpart('b2x:reply:obsmarkers')
rpart.addparam('in-reply-to', str(inpart.id), mandatory=False)
rpart.addparam('new', '%i' % new, mandatory=False)
@parthandler('b2x:reply:obsmarkers', ('new', 'in-reply-to'))
def handlepushkeyreply(op, inpart):
"""retrieve the result of a pushkey request"""
ret = int(inpart.params['new'])
partid = int(inpart.params['in-reply-to'])
op.records.add('obsmarkers', {'new': ret}, partid)