revlog.py
2475 lines
| 88.2 KiB
| text/x-python
|
PythonLexer
/ mercurial / revlog.py
Martin Geisler
|
r8226 | # revlog.py - storage back-end for mercurial | ||
# | ||||
# Copyright 2005-2007 Matt Mackall <mpm@selenic.com> | ||||
# | ||||
# This software may be used and distributed according to the terms of the | ||||
Matt Mackall
|
r10263 | # GNU General Public License version 2 or any later version. | ||
mpm@selenic.com
|
r0 | |||
Martin Geisler
|
r8227 | """Storage back-end for Mercurial. | ||
This provides efficient delta storage with O(1) retrieve and append | ||||
and O(changes) merge between branches. | ||||
""" | ||||
Gregory Szorc
|
r27361 | from __future__ import absolute_import | ||
Martin von Zweigbergk
|
r25113 | import collections | ||
Boris Feld
|
r35991 | import contextlib | ||
Gregory Szorc
|
r27361 | import errno | ||
Augie Fackler
|
r29339 | import hashlib | ||
Gregory Szorc
|
r27430 | import os | ||
Gregory Szorc
|
r37460 | import re | ||
Gregory Szorc
|
r27361 | import struct | ||
import zlib | ||||
# import stuff from node for others to import from revlog | ||||
from .node import ( | ||||
bin, | ||||
hex, | ||||
Martin von Zweigbergk
|
r39227 | nullhex, | ||
Gregory Szorc
|
r27361 | nullid, | ||
nullrev, | ||||
Yuya Nishihara
|
r37467 | wdirfilenodeids, | ||
Yuya Nishihara
|
r32684 | wdirhex, | ||
Yuya Nishihara
|
r32657 | wdirid, | ||
Pulkit Goyal
|
r32402 | wdirrev, | ||
Gregory Szorc
|
r27361 | ) | ||
from .i18n import _ | ||||
Boris Feld
|
r39365 | from .revlogutils.constants import ( | ||
FLAG_GENERALDELTA, | ||||
FLAG_INLINE_DATA, | ||||
REVIDX_DEFAULT_FLAGS, | ||||
REVIDX_ELLIPSIS, | ||||
REVIDX_EXTSTORED, | ||||
REVIDX_FLAGS_ORDER, | ||||
REVIDX_ISCENSORED, | ||||
REVIDX_KNOWN_FLAGS, | ||||
REVIDX_RAWTEXT_CHANGING_FLAGS, | ||||
REVLOGV0, | ||||
REVLOGV1, | ||||
REVLOGV1_FLAGS, | ||||
REVLOGV2, | ||||
REVLOGV2_FLAGS, | ||||
REVLOG_DEFAULT_FLAGS, | ||||
REVLOG_DEFAULT_FORMAT, | ||||
REVLOG_DEFAULT_VERSION, | ||||
) | ||||
Paul Morelle
|
r35656 | from .thirdparty import ( | ||
attr, | ||||
) | ||||
Gregory Szorc
|
r27361 | from . import ( | ||
ancestor, | ||||
error, | ||||
mdiff, | ||||
Yuya Nishihara
|
r32372 | policy, | ||
Augie Fackler
|
r31574 | pycompat, | ||
Gregory Szorc
|
r39267 | repository, | ||
Gregory Szorc
|
r27361 | templatefilters, | ||
util, | ||||
) | ||||
Boris Feld
|
r39366 | from .revlogutils import ( | ||
deltas as deltautil, | ||||
) | ||||
Yuya Nishihara
|
r37102 | from .utils import ( | ||
Gregory Szorc
|
r39267 | interfaceutil, | ||
Yuya Nishihara
|
r37102 | stringutil, | ||
) | ||||
mpm@selenic.com
|
r36 | |||
Boris Feld
|
r39365 | # blanked usage of all the name to prevent pyflakes constraints | ||
# We need these name available in the module for extensions. | ||||
REVLOGV0 | ||||
REVLOGV1 | ||||
REVLOGV2 | ||||
FLAG_INLINE_DATA | ||||
FLAG_GENERALDELTA | ||||
REVLOG_DEFAULT_FLAGS | ||||
REVLOG_DEFAULT_FORMAT | ||||
REVLOG_DEFAULT_VERSION | ||||
REVLOGV1_FLAGS | ||||
REVLOGV2_FLAGS | ||||
REVIDX_ISCENSORED | ||||
REVIDX_ELLIPSIS | ||||
REVIDX_EXTSTORED | ||||
REVIDX_DEFAULT_FLAGS | ||||
REVIDX_FLAGS_ORDER | ||||
REVIDX_KNOWN_FLAGS | ||||
REVIDX_RAWTEXT_CHANGING_FLAGS | ||||
Yuya Nishihara
|
r32372 | parsers = policy.importmod(r'parsers') | ||
Gregory Szorc
|
r30817 | # Aliased for performance. | ||
_zlibdecompress = zlib.decompress | ||||
Matt Mackall
|
r5007 | |||
Benoit Boissinot
|
r10916 | # max size of revlog with inline data | ||
_maxinline = 131072 | ||||
Matt Mackall
|
r13253 | _chunksize = 1048576 | ||
Greg Ward
|
r10913 | |||
Matt Mackall
|
r7633 | RevlogError = error.RevlogError | ||
LookupError = error.LookupError | ||||
Martin von Zweigbergk
|
r38877 | AmbiguousPrefixLookupError = error.AmbiguousPrefixLookupError | ||
Mike Edgar
|
r22934 | CensoredNodeError = error.CensoredNodeError | ||
Remi Chaintron
|
r30745 | ProgrammingError = error.ProgrammingError | ||
# Store flag processors (cf. 'addflagprocessor()' to register) | ||||
_flagprocessors = { | ||||
REVIDX_ISCENSORED: None, | ||||
} | ||||
Gregory Szorc
|
r37460 | _mdre = re.compile('\1\n') | ||
def parsemeta(text): | ||||
"""return (metadatadict, metadatasize)""" | ||||
# text can be buffer, so we can't use .startswith or .index | ||||
if text[:2] != '\1\n': | ||||
return None, None | ||||
s = _mdre.search(text, 2).start() | ||||
mtext = text[2:s] | ||||
meta = {} | ||||
for l in mtext.splitlines(): | ||||
k, v = l.split(": ", 1) | ||||
meta[k] = v | ||||
return meta, (s + 2) | ||||
def packmeta(meta, text): | ||||
keys = sorted(meta) | ||||
metatext = "".join("%s: %s\n" % (k, meta[k]) for k in keys) | ||||
return "\1\n%s\1\n%s" % (metatext, text) | ||||
Gregory Szorc
|
r37461 | def _censoredtext(text): | ||
m, offs = parsemeta(text) | ||||
return m and "censored" in m | ||||
Remi Chaintron
|
r30745 | def addflagprocessor(flag, processor): | ||
"""Register a flag processor on a revision data flag. | ||||
Invariant: | ||||
Jun Wu
|
r36764 | - Flags need to be defined in REVIDX_KNOWN_FLAGS and REVIDX_FLAGS_ORDER, | ||
and REVIDX_RAWTEXT_CHANGING_FLAGS if they can alter rawtext. | ||||
Remi Chaintron
|
r30745 | - Only one flag processor can be registered on a specific flag. | ||
- flagprocessors must be 3-tuples of functions (read, write, raw) with the | ||||
following signatures: | ||||
Jun Wu
|
r31749 | - (read) f(self, rawtext) -> text, bool | ||
- (write) f(self, text) -> rawtext, bool | ||||
- (raw) f(self, rawtext) -> bool | ||||
"text" is presented to the user. "rawtext" is stored in revlog data, not | ||||
directly visible to the user. | ||||
Remi Chaintron
|
r30745 | The boolean returned by these transforms is used to determine whether | ||
Jun Wu
|
r31749 | the returned text can be used for hash integrity checking. For example, | ||
if "write" returns False, then "text" is used to generate hash. If | ||||
"write" returns True, that basically means "rawtext" returned by "write" | ||||
should be used to generate hash. Usually, "write" and "read" return | ||||
different booleans. And "raw" returns a same boolean as "write". | ||||
Remi Chaintron
|
r30745 | |||
Note: The 'raw' transform is used for changegroup generation and in some | ||||
debug commands. In this case the transform only indicates whether the | ||||
contents can be used for hash integrity checks. | ||||
""" | ||||
if not flag & REVIDX_KNOWN_FLAGS: | ||||
msg = _("cannot register processor on unknown flag '%#x'.") % (flag) | ||||
raise ProgrammingError(msg) | ||||
if flag not in REVIDX_FLAGS_ORDER: | ||||
msg = _("flag '%#x' undefined in REVIDX_FLAGS_ORDER.") % (flag) | ||||
raise ProgrammingError(msg) | ||||
if flag in _flagprocessors: | ||||
msg = _("cannot register multiple processors on flag '%#x'.") % (flag) | ||||
raise error.Abort(msg) | ||||
_flagprocessors[flag] = processor | ||||
Alexander Solovyov
|
r6703 | |||
Matt Mackall
|
r4987 | def getoffset(q): | ||
return int(q >> 16) | ||||
def gettype(q): | ||||
return int(q & 0xFFFF) | ||||
def offset_type(offset, type): | ||||
Cotizo Sima
|
r30543 | if (type & ~REVIDX_KNOWN_FLAGS) != 0: | ||
raise ValueError('unknown revlog index flags') | ||||
Augie Fackler
|
r31504 | return int(int(offset) << 16 | type) | ||
Matt Mackall
|
r4987 | |||
Augie Fackler
|
r29339 | _nullhash = hashlib.sha1(nullid) | ||
Nicolas Dumazet
|
r7883 | |||
mpm@selenic.com
|
r1091 | def hash(text, p1, p2): | ||
"""generate a hash from the given text and its parent hashes | ||||
This hash combines both the current file contents and its history | ||||
in a manner that makes it easy to distinguish nodes with the same | ||||
content in the revision graph. | ||||
""" | ||||
Nicolas Dumazet
|
r7883 | # As of now, if one of the parent node is null, p2 is null | ||
if p2 == nullid: | ||||
# deep copy of a hash is faster than creating one | ||||
Augie Fackler
|
r22784 | s = _nullhash.copy() | ||
Nicolas Dumazet
|
r7883 | s.update(p1) | ||
else: | ||||
# none of the parent nodes are nullid | ||||
Alex Gaynor
|
r33391 | if p1 < p2: | ||
a = p1 | ||||
b = p2 | ||||
else: | ||||
a = p2 | ||||
b = p1 | ||||
s = hashlib.sha1(a) | ||||
s.update(b) | ||||
mpm@selenic.com
|
r1091 | s.update(text) | ||
return s.digest() | ||||
Paul Morelle
|
r35659 | @attr.s(slots=True, frozen=True) | ||
class _revisioninfo(object): | ||||
"""Information about a revision that allows building its fulltext | ||||
node: expected hash of the revision | ||||
p1, p2: parent revs of the revision | ||||
btext: built text cache consisting of a one-element list | ||||
cachedelta: (baserev, uncompressed_delta) or None | ||||
flags: flags associated to the revision storage | ||||
One of btext[0] or cachedelta must be set. | ||||
""" | ||||
node = attr.ib() | ||||
p1 = attr.ib() | ||||
p2 = attr.ib() | ||||
btext = attr.ib() | ||||
Paul Morelle
|
r35755 | textlen = attr.ib() | ||
Paul Morelle
|
r35659 | cachedelta = attr.ib() | ||
flags = attr.ib() | ||||
Gregory Szorc
|
r39267 | @interfaceutil.implementer(repository.irevisiondelta) | ||
@attr.s(slots=True, frozen=True) | ||||
class revlogrevisiondelta(object): | ||||
node = attr.ib() | ||||
p1node = attr.ib() | ||||
p2node = attr.ib() | ||||
basenode = attr.ib() | ||||
linknode = attr.ib() | ||||
flags = attr.ib() | ||||
baserevisionsize = attr.ib() | ||||
revision = attr.ib() | ||||
delta = attr.ib() | ||||
Benoit Boissinot
|
r18585 | # index v0: | ||
# 4 bytes: offset | ||||
# 4 bytes: compressed length | ||||
# 4 bytes: base rev | ||||
# 4 bytes: link rev | ||||
Yuya Nishihara
|
r25891 | # 20 bytes: parent 1 nodeid | ||
# 20 bytes: parent 2 nodeid | ||||
# 20 bytes: nodeid | ||||
Alex Gaynor
|
r33392 | indexformatv0 = struct.Struct(">4l20s20s20s") | ||
indexformatv0_pack = indexformatv0.pack | ||||
indexformatv0_unpack = indexformatv0.unpack | ||||
Matt Mackall
|
r4918 | |||
Martin von Zweigbergk
|
r38885 | class revlogoldindex(list): | ||
def __getitem__(self, i): | ||||
Martin von Zweigbergk
|
r38888 | if i == -1: | ||
Martin von Zweigbergk
|
r38885 | return (0, 0, 0, -1, -1, -1, -1, nullid) | ||
return list.__getitem__(self, i) | ||||
Matt Mackall
|
r4972 | class revlogoldio(object): | ||
def __init__(self): | ||||
Alex Gaynor
|
r33392 | self.size = indexformatv0.size | ||
Matt Mackall
|
r4972 | |||
Benoit Boissinot
|
r13264 | def parseindex(self, data, inline): | ||
Matt Mackall
|
r4977 | s = self.size | ||
Matt Mackall
|
r4972 | index = [] | ||
timeless
|
r27637 | nodemap = {nullid: nullrev} | ||
Matt Mackall
|
r4973 | n = off = 0 | ||
l = len(data) | ||||
while off + s <= l: | ||||
cur = data[off:off + s] | ||||
off += s | ||||
Alex Gaynor
|
r33392 | e = indexformatv0_unpack(cur) | ||
Matt Mackall
|
r4977 | # transform to revlogv1 format | ||
e2 = (offset_type(e[0], 0), e[1], -1, e[2], e[3], | ||||
Matt Mackall
|
r5544 | nodemap.get(e[4], nullrev), nodemap.get(e[5], nullrev), e[6]) | ||
Matt Mackall
|
r4977 | index.append(e2) | ||
nodemap[e[6]] = n | ||||
Matt Mackall
|
r4973 | n += 1 | ||
Matt Mackall
|
r4972 | |||
Martin von Zweigbergk
|
r38885 | return revlogoldindex(index), nodemap, None | ||
Matt Mackall
|
r4972 | |||
Alexis S. L. Carvalho
|
r5338 | def packentry(self, entry, node, version, rev): | ||
Benoit Boissinot
|
r10395 | if gettype(entry[0]): | ||
Gregory Szorc
|
r32392 | raise RevlogError(_('index entry flags need revlog version 1')) | ||
Matt Mackall
|
r4986 | e2 = (getoffset(entry[0]), entry[1], entry[3], entry[4], | ||
node(entry[5]), node(entry[6]), entry[7]) | ||||
Alex Gaynor
|
r33392 | return indexformatv0_pack(*e2) | ||
Matt Mackall
|
r4986 | |||
Matt Mackall
|
r4987 | # index ng: | ||
Martin Geisler
|
r11323 | # 6 bytes: offset | ||
# 2 bytes: flags | ||||
# 4 bytes: compressed length | ||||
# 4 bytes: uncompressed length | ||||
# 4 bytes: base rev | ||||
# 4 bytes: link rev | ||||
# 4 bytes: parent 1 rev | ||||
# 4 bytes: parent 2 rev | ||||
Matt Mackall
|
r4987 | # 32 bytes: nodeid | ||
Alex Gaynor
|
r33392 | indexformatng = struct.Struct(">Qiiiiii20s12x") | ||
indexformatng_pack = indexformatng.pack | ||||
versionformat = struct.Struct(">I") | ||||
versionformat_pack = versionformat.pack | ||||
versionformat_unpack = versionformat.unpack | ||||
Matt Mackall
|
r4987 | |||
Jordi Gutiérrez Hermoso
|
r25410 | # corresponds to uncompressed length of indexformatng (2 gigs, 4-byte | ||
# signed integer) | ||||
_maxentrysize = 0x7fffffff | ||||
Matt Mackall
|
r4972 | class revlogio(object): | ||
def __init__(self): | ||||
Alex Gaynor
|
r33392 | self.size = indexformatng.size | ||
Matt Mackall
|
r4972 | |||
Benoit Boissinot
|
r13264 | def parseindex(self, data, inline): | ||
Bernhard Leiner
|
r7109 | # call the C implementation to parse the index data | ||
Matt Mackall
|
r13254 | index, cache = parsers.parse_index2(data, inline) | ||
Bryan O'Sullivan
|
r16414 | return index, getattr(index, 'nodemap', None), cache | ||
Matt Mackall
|
r4972 | |||
Alexis S. L. Carvalho
|
r5338 | def packentry(self, entry, node, version, rev): | ||
Alex Gaynor
|
r33392 | p = indexformatng_pack(*entry) | ||
Alexis S. L. Carvalho
|
r5338 | if rev == 0: | ||
Alex Gaynor
|
r33392 | p = versionformat_pack(version) + p[4:] | ||
Matt Mackall
|
r4986 | return p | ||
Eric Hopper
|
r1559 | class revlog(object): | ||
mpm@selenic.com
|
r1083 | """ | ||
the underlying revision storage object | ||||
A revlog consists of two parts, an index and the revision data. | ||||
The index is a file with a fixed record size containing | ||||
Martin Geisler
|
r6912 | information on each revision, including its nodeid (hash), the | ||
mpm@selenic.com
|
r1083 | nodeids of its parents, the position and offset of its data within | ||
the data file, and the revision it's based on. Finally, each entry | ||||
contains a linkrev entry that can serve as a pointer to external | ||||
data. | ||||
The revision data itself is a linear collection of data chunks. | ||||
Each chunk represents a revision and is usually represented as a | ||||
delta against the previous chunk. To bound lookup time, runs of | ||||
deltas are limited to about 2 times the length of the original | ||||
version data. This makes retrieval of a version proportional to | ||||
its size, or O(1) relative to the number of revisions. | ||||
Both pieces of the revlog are written to in an append-only | ||||
fashion, which means we never need to rewrite a file to insert or | ||||
remove data, and can use some simple techniques to avoid the need | ||||
for locking while reading. | ||||
FUJIWARA Katsunori
|
r29997 | |||
If checkambig, indexfile is opened with checkambig=True at | ||||
writing, to avoid file stat ambiguity. | ||||
Mark Thomas
|
r34297 | |||
If mmaplargeindex is True, and an mmapindexthreshold is set, the | ||||
index will be mmapped rather than read if it is larger than the | ||||
configured threshold. | ||||
Gregory Szorc
|
r37461 | |||
If censorable is True, the revlog can have censored revisions. | ||||
mpm@selenic.com
|
r1083 | """ | ||
Mark Thomas
|
r34297 | def __init__(self, opener, indexfile, datafile=None, checkambig=False, | ||
Gregory Szorc
|
r37461 | mmaplargeindex=False, censorable=False): | ||
mpm@selenic.com
|
r1083 | """ | ||
create a revlog object | ||||
opener is a function that abstracts the file opening operation | ||||
and can be used to implement COW semantics or the like. | ||||
""" | ||||
mpm@selenic.com
|
r0 | self.indexfile = indexfile | ||
Jun Wu
|
r32307 | self.datafile = datafile or (indexfile[:-2] + ".d") | ||
mpm@selenic.com
|
r0 | self.opener = opener | ||
FUJIWARA Katsunori
|
r29997 | # When True, indexfile is opened with checkambig=True at writing, to | ||
# avoid file stat ambiguity. | ||||
self._checkambig = checkambig | ||||
Gregory Szorc
|
r37461 | self._censorable = censorable | ||
Gregory Szorc
|
r27070 | # 3-tuple of (node, rev, text) for a raw revision. | ||
Matt Mackall
|
r4984 | self._cache = None | ||
Gregory Szorc
|
r29830 | # Maps rev to chain base rev. | ||
self._chainbasecache = util.lrucachedict(100) | ||||
Gregory Szorc
|
r27070 | # 2-tuple of (offset, data) of raw data from the revlog at an offset. | ||
Matt Mackall
|
r8316 | self._chunkcache = (0, '') | ||
Gregory Szorc
|
r27070 | # How much data to read and cache into the raw revlog data cache. | ||
Brodie Rao
|
r20180 | self._chunkcachesize = 65536 | ||
Mateusz Kwapich
|
r23255 | self._maxchainlen = None | ||
Boris Feld
|
r38759 | self._deltabothparents = True | ||
Matt Mackall
|
r4985 | self.index = [] | ||
Gregory Szorc
|
r27070 | # Mapping of partial identifiers to full nodes. | ||
Matt Mackall
|
r13258 | self._pcache = {} | ||
Gregory Szorc
|
r27070 | # Mapping of revision integer to full node. | ||
Matt Mackall
|
r13275 | self._nodecache = {nullid: nullrev} | ||
self._nodepos = None | ||||
Gregory Szorc
|
r30818 | self._compengine = 'zlib' | ||
r33202 | self._maxdeltachainspan = -1 | |||
Paul Morelle
|
r34825 | self._withsparseread = False | ||
Paul Morelle
|
r38739 | self._sparserevlog = False | ||
Paul Morelle
|
r38651 | self._srdensitythreshold = 0.50 | ||
Paul Morelle
|
r34882 | self._srmingapsize = 262144 | ||
Matt Mackall
|
r4985 | |||
Mark Thomas
|
r34297 | mmapindexthreshold = None | ||
Matt Mackall
|
r4985 | v = REVLOG_DEFAULT_VERSION | ||
Augie Fackler
|
r14960 | opts = getattr(opener, 'options', None) | ||
if opts is not None: | ||||
Gregory Szorc
|
r32697 | if 'revlogv2' in opts: | ||
# version 2 revlogs always use generaldelta. | ||||
v = REVLOGV2 | FLAG_GENERALDELTA | FLAG_INLINE_DATA | ||||
elif 'revlogv1' in opts: | ||||
Augie Fackler
|
r14960 | if 'generaldelta' in opts: | ||
Gregory Szorc
|
r32316 | v |= FLAG_GENERALDELTA | ||
Sune Foldager
|
r14333 | else: | ||
v = 0 | ||||
Brodie Rao
|
r20180 | if 'chunkcachesize' in opts: | ||
self._chunkcachesize = opts['chunkcachesize'] | ||||
Mateusz Kwapich
|
r23255 | if 'maxchainlen' in opts: | ||
self._maxchainlen = opts['maxchainlen'] | ||||
Boris Feld
|
r38759 | if 'deltabothparents' in opts: | ||
self._deltabothparents = opts['deltabothparents'] | ||||
Pierre-Yves David
|
r26907 | self._lazydeltabase = bool(opts.get('lazydeltabase', False)) | ||
Gregory Szorc
|
r30818 | if 'compengine' in opts: | ||
self._compengine = opts['compengine'] | ||||
r33202 | if 'maxdeltachainspan' in opts: | |||
self._maxdeltachainspan = opts['maxdeltachainspan'] | ||||
Mark Thomas
|
r34297 | if mmaplargeindex and 'mmapindexthreshold' in opts: | ||
mmapindexthreshold = opts['mmapindexthreshold'] | ||||
Paul Morelle
|
r38739 | self._sparserevlog = bool(opts.get('sparse-revlog', False)) | ||
withsparseread = bool(opts.get('with-sparse-read', False)) | ||||
# sparse-revlog forces sparse-read | ||||
self._withsparseread = self._sparserevlog or withsparseread | ||||
Paul Morelle
|
r34825 | if 'sparse-read-density-threshold' in opts: | ||
self._srdensitythreshold = opts['sparse-read-density-threshold'] | ||||
Paul Morelle
|
r34882 | if 'sparse-read-min-gap-size' in opts: | ||
self._srmingapsize = opts['sparse-read-min-gap-size'] | ||||
Brodie Rao
|
r20180 | |||
if self._chunkcachesize <= 0: | ||||
raise RevlogError(_('revlog chunk cache size %r is not greater ' | ||||
'than 0') % self._chunkcachesize) | ||||
elif self._chunkcachesize & (self._chunkcachesize - 1): | ||||
raise RevlogError(_('revlog chunk cache size %r is not a power ' | ||||
'of 2') % self._chunkcachesize) | ||||
Pradeepkumar Gayam
|
r11928 | |||
Gregory Szorc
|
r26241 | indexdata = '' | ||
Sune Foldager
|
r14334 | self._initempty = True | ||
mpm@selenic.com
|
r0 | try: | ||
Boris Feld
|
r35987 | with self._indexfp() as f: | ||
if (mmapindexthreshold is not None and | ||||
self.opener.fstat(f).st_size >= mmapindexthreshold): | ||||
indexdata = util.buffer(util.mmapread(f)) | ||||
else: | ||||
indexdata = f.read() | ||||
Gregory Szorc
|
r26241 | if len(indexdata) > 0: | ||
Alex Gaynor
|
r33392 | v = versionformat_unpack(indexdata[:4])[0] | ||
Sune Foldager
|
r14334 | self._initempty = False | ||
Gregory Szorc
|
r25660 | except IOError as inst: | ||
Bryan O'Sullivan
|
r1322 | if inst.errno != errno.ENOENT: | ||
raise | ||||
Matt Mackall
|
r4985 | |||
self.version = v | ||||
Gregory Szorc
|
r32316 | self._inline = v & FLAG_INLINE_DATA | ||
self._generaldelta = v & FLAG_GENERALDELTA | ||||
mason@suse.com
|
r2073 | flags = v & ~0xFFFF | ||
fmt = v & 0xFFFF | ||||
Gregory Szorc
|
r32391 | if fmt == REVLOGV0: | ||
if flags: | ||||
raise RevlogError(_('unknown flags (%#04x) in version %d ' | ||||
'revlog %s') % | ||||
(flags >> 16, fmt, self.indexfile)) | ||||
elif fmt == REVLOGV1: | ||||
if flags & ~REVLOGV1_FLAGS: | ||||
raise RevlogError(_('unknown flags (%#04x) in version %d ' | ||||
'revlog %s') % | ||||
(flags >> 16, fmt, self.indexfile)) | ||||
Gregory Szorc
|
r32697 | elif fmt == REVLOGV2: | ||
if flags & ~REVLOGV2_FLAGS: | ||||
raise RevlogError(_('unknown flags (%#04x) in version %d ' | ||||
'revlog %s') % | ||||
(flags >> 16, fmt, self.indexfile)) | ||||
Gregory Szorc
|
r32391 | else: | ||
raise RevlogError(_('unknown version (%d) in revlog %s') % | ||||
(fmt, self.indexfile)) | ||||
Matt Mackall
|
r4985 | |||
Gregory Szorc
|
r39268 | self._storedeltachains = True | ||
Gregory Szorc
|
r30154 | |||
Matt Mackall
|
r4972 | self._io = revlogio() | ||
Matt Mackall
|
r4971 | if self.version == REVLOGV0: | ||
Matt Mackall
|
r4972 | self._io = revlogoldio() | ||
Benoit Boissinot
|
r13265 | try: | ||
Gregory Szorc
|
r26241 | d = self._io.parseindex(indexdata, self._inline) | ||
Benoit Boissinot
|
r13265 | except (ValueError, IndexError): | ||
raise RevlogError(_("index %s is corrupted") % (self.indexfile)) | ||||
Benoit Boissinot
|
r13268 | self.index, nodemap, self._chunkcache = d | ||
if nodemap is not None: | ||||
Matt Mackall
|
r13275 | self.nodemap = self._nodecache = nodemap | ||
Benoit Boissinot
|
r13265 | if not self._chunkcache: | ||
self._chunkclear() | ||||
Siddharth Agarwal
|
r23306 | # revnum -> (chain-length, sum-delta-length) | ||
self._chaininfocache = {} | ||||
Gregory Szorc
|
r30817 | # revlog header -> revlog compressor | ||
self._decompressors = {} | ||||
mpm@selenic.com
|
r116 | |||
Gregory Szorc
|
r30795 | @util.propertycache | ||
def _compressor(self): | ||||
Gregory Szorc
|
r30818 | return util.compengines[self._compengine].revlogcompressor() | ||
Gregory Szorc
|
r30795 | |||
Boris Feld
|
r35986 | def _indexfp(self, mode='r'): | ||
"""file object for the revlog's index file""" | ||||
args = {r'mode': mode} | ||||
if mode != 'r': | ||||
args[r'checkambig'] = self._checkambig | ||||
if mode == 'w': | ||||
args[r'atomictemp'] = True | ||||
return self.opener(self.indexfile, **args) | ||||
Boris Feld
|
r35985 | def _datafp(self, mode='r'): | ||
"""file object for the revlog's data file""" | ||||
return self.opener(self.datafile, mode=mode) | ||||
Boris Feld
|
r35991 | @contextlib.contextmanager | ||
def _datareadfp(self, existingfp=None): | ||||
"""file object suitable to read data""" | ||||
if existingfp is not None: | ||||
yield existingfp | ||||
else: | ||||
if self._inline: | ||||
func = self._indexfp | ||||
else: | ||||
func = self._datafp | ||||
with func() as fp: | ||||
yield fp | ||||
Matt Mackall
|
r4980 | def tip(self): | ||
Martin von Zweigbergk
|
r38887 | return self.node(len(self.index) - 1) | ||
Yuya Nishihara
|
r24030 | def __contains__(self, rev): | ||
return 0 <= rev < len(self) | ||||
Matt Mackall
|
r6750 | def __len__(self): | ||
Martin von Zweigbergk
|
r38887 | return len(self.index) | ||
Matt Mackall
|
r6750 | def __iter__(self): | ||
Gregory Szorc
|
r38806 | return iter(pycompat.xrange(len(self))) | ||
Pierre-Yves David
|
r17672 | def revs(self, start=0, stop=None): | ||
"""iterate over all rev in this revlog (from start to stop)""" | ||||
Pierre-Yves David
|
r17975 | step = 1 | ||
Martin von Zweigbergk
|
r38800 | length = len(self) | ||
Pierre-Yves David
|
r17975 | if stop is not None: | ||
if start > stop: | ||||
step = -1 | ||||
stop += step | ||||
Martin von Zweigbergk
|
r38800 | if stop > length: | ||
stop = length | ||||
Pierre-Yves David
|
r17672 | else: | ||
Martin von Zweigbergk
|
r38800 | stop = length | ||
Gregory Szorc
|
r38806 | return pycompat.xrange(start, stop, step) | ||
Matt Mackall
|
r13275 | |||
@util.propertycache | ||||
def nodemap(self): | ||||
Yuya Nishihara
|
r39176 | if self.index: | ||
# populate mapping down to the initial node | ||||
Yuya Nishihara
|
r39177 | node0 = self.index[0][7] # get around changelog filtering | ||
self.rev(node0) | ||||
Matt Mackall
|
r13275 | return self._nodecache | ||
Matt Mackall
|
r13259 | |||
Matt Mackall
|
r16374 | def hasnode(self, node): | ||
try: | ||||
self.rev(node) | ||||
return True | ||||
except KeyError: | ||||
return False | ||||
Jun Wu
|
r36764 | def candelta(self, baserev, rev): | ||
"""whether two revisions (baserev, rev) can be delta-ed or not""" | ||||
# Disable delta if either rev requires a content-changing flag | ||||
# processor (ex. LFS). This is because such flag processor can alter | ||||
# the rawtext content that the delta will be based on, and two clients | ||||
# could have a same revlog node with different flags (i.e. different | ||||
# rawtext contents) and the delta could be incompatible. | ||||
if ((self.flags(baserev) & REVIDX_RAWTEXT_CHANGING_FLAGS) | ||||
or (self.flags(rev) & REVIDX_RAWTEXT_CHANGING_FLAGS)): | ||||
return False | ||||
return True | ||||
Bryan O'Sullivan
|
r16414 | def clearcaches(self): | ||
Gregory Szorc
|
r27465 | self._cache = None | ||
Gregory Szorc
|
r29830 | self._chainbasecache.clear() | ||
Gregory Szorc
|
r27465 | self._chunkcache = (0, '') | ||
self._pcache = {} | ||||
Bryan O'Sullivan
|
r16414 | try: | ||
self._nodecache.clearcaches() | ||||
except AttributeError: | ||||
self._nodecache = {nullid: nullrev} | ||||
self._nodepos = None | ||||
Matt Mackall
|
r13259 | def rev(self, node): | ||
Matt Mackall
|
r13275 | try: | ||
return self._nodecache[node] | ||||
Matt Mackall
|
r22282 | except TypeError: | ||
raise | ||||
Bryan O'Sullivan
|
r16414 | except RevlogError: | ||
# parsers.c radix tree lookup failed | ||||
Yuya Nishihara
|
r37467 | if node == wdirid or node in wdirfilenodeids: | ||
Yuya Nishihara
|
r32657 | raise error.WdirUnsupported | ||
Bryan O'Sullivan
|
r16414 | raise LookupError(node, self.indexfile, _('no node')) | ||
Matt Mackall
|
r13275 | except KeyError: | ||
Bryan O'Sullivan
|
r16414 | # pure python cache lookup failed | ||
Matt Mackall
|
r13275 | n = self._nodecache | ||
i = self.index | ||||
p = self._nodepos | ||||
if p is None: | ||||
Martin von Zweigbergk
|
r38887 | p = len(i) - 1 | ||
Joerg Sonnenberger
|
r37512 | else: | ||
assert p < len(i) | ||||
Gregory Szorc
|
r38806 | for r in pycompat.xrange(p, -1, -1): | ||
Matt Mackall
|
r13275 | v = i[r][7] | ||
n[v] = r | ||||
if v == node: | ||||
self._nodepos = r - 1 | ||||
return r | ||||
Yuya Nishihara
|
r37467 | if node == wdirid or node in wdirfilenodeids: | ||
Yuya Nishihara
|
r32657 | raise error.WdirUnsupported | ||
Matt Mackall
|
r13275 | raise LookupError(node, self.indexfile, _('no node')) | ||
Gregory Szorc
|
r30287 | # Accessors for index entries. | ||
# First tuple entry is 8 bytes. First 6 bytes are offset. Last 2 bytes | ||||
# are flags. | ||||
mason@suse.com
|
r2072 | def start(self, rev): | ||
Matt Mackall
|
r5006 | return int(self.index[rev][0] >> 16) | ||
Gregory Szorc
|
r30287 | |||
def flags(self, rev): | ||||
return self.index[rev][0] & 0xFFFF | ||||
Matt Mackall
|
r4980 | def length(self, rev): | ||
return self.index[rev][1] | ||||
Gregory Szorc
|
r30287 | |||
def rawsize(self, rev): | ||||
"""return the length of the uncompressed text for a given revision""" | ||||
l = self.index[rev][2] | ||||
Yuya Nishihara
|
r38195 | if l >= 0: | ||
Gregory Szorc
|
r30287 | return l | ||
Jun Wu
|
r31801 | t = self.revision(rev, raw=True) | ||
Gregory Szorc
|
r30287 | return len(t) | ||
Jun Wu
|
r31856 | |||
def size(self, rev): | ||||
"""length of non-raw text (processed by a "read" flag processor)""" | ||||
# fast path: if no "read" flag processor could change the content, | ||||
# size is rawsize. note: ELLIPSIS is known to not change the content. | ||||
flags = self.flags(rev) | ||||
if flags & (REVIDX_KNOWN_FLAGS ^ REVIDX_ELLIPSIS) == 0: | ||||
return self.rawsize(rev) | ||||
return len(self.revision(rev, raw=False)) | ||||
Gregory Szorc
|
r30287 | |||
Sune Foldager
|
r14252 | def chainbase(self, rev): | ||
Gregory Szorc
|
r29830 | base = self._chainbasecache.get(rev) | ||
if base is not None: | ||||
return base | ||||
Sune Foldager
|
r14252 | index = self.index | ||
Paul Morelle
|
r38187 | iterrev = rev | ||
base = index[iterrev][3] | ||||
while base != iterrev: | ||||
iterrev = base | ||||
base = index[iterrev][3] | ||||
Gregory Szorc
|
r29830 | |||
self._chainbasecache[rev] = base | ||||
Sune Foldager
|
r14252 | return base | ||
Gregory Szorc
|
r30287 | |||
def linkrev(self, rev): | ||||
return self.index[rev][4] | ||||
def parentrevs(self, rev): | ||||
Pulkit Goyal
|
r32402 | try: | ||
Gregory Szorc
|
r35539 | entry = self.index[rev] | ||
Pulkit Goyal
|
r32402 | except IndexError: | ||
if rev == wdirrev: | ||||
raise error.WdirUnsupported | ||||
raise | ||||
Gregory Szorc
|
r30287 | |||
Gregory Szorc
|
r35539 | return entry[5], entry[6] | ||
Gregory Szorc
|
r30287 | def node(self, rev): | ||
Pulkit Goyal
|
r32443 | try: | ||
return self.index[rev][7] | ||||
except IndexError: | ||||
if rev == wdirrev: | ||||
raise error.WdirUnsupported | ||||
raise | ||||
Gregory Szorc
|
r30287 | |||
# Derived from index values. | ||||
def end(self, rev): | ||||
return self.start(rev) + self.length(rev) | ||||
def parents(self, node): | ||||
i = self.index | ||||
d = i[self.rev(node)] | ||||
return i[d[5]][7], i[d[6]][7] # map revisions to nodes inline | ||||
Mateusz Kwapich
|
r23254 | def chainlen(self, rev): | ||
Siddharth Agarwal
|
r23286 | return self._chaininfo(rev)[0] | ||
Siddharth Agarwal
|
r23306 | |||
Siddharth Agarwal
|
r23286 | def _chaininfo(self, rev): | ||
Siddharth Agarwal
|
r23306 | chaininfocache = self._chaininfocache | ||
if rev in chaininfocache: | ||||
return chaininfocache[rev] | ||||
Mateusz Kwapich
|
r23254 | index = self.index | ||
generaldelta = self._generaldelta | ||||
iterrev = rev | ||||
e = index[iterrev] | ||||
clen = 0 | ||||
Siddharth Agarwal
|
r23286 | compresseddeltalen = 0 | ||
Mateusz Kwapich
|
r23254 | while iterrev != e[3]: | ||
clen += 1 | ||||
Siddharth Agarwal
|
r23286 | compresseddeltalen += e[1] | ||
Mateusz Kwapich
|
r23254 | if generaldelta: | ||
iterrev = e[3] | ||||
else: | ||||
iterrev -= 1 | ||||
Siddharth Agarwal
|
r23306 | if iterrev in chaininfocache: | ||
t = chaininfocache[iterrev] | ||||
clen += t[0] | ||||
compresseddeltalen += t[1] | ||||
break | ||||
Mateusz Kwapich
|
r23254 | e = index[iterrev] | ||
Siddharth Agarwal
|
r23306 | else: | ||
# Add text length of base since decompressing that also takes | ||||
# work. For cache hits the length is already included. | ||||
compresseddeltalen += e[1] | ||||
r = (clen, compresseddeltalen) | ||||
chaininfocache[rev] = r | ||||
return r | ||||
Gregory Szorc
|
r27468 | def _deltachain(self, rev, stoprev=None): | ||
"""Obtain the delta chain for a revision. | ||||
``stoprev`` specifies a revision to stop at. If not specified, we | ||||
stop at the base of the chain. | ||||
Returns a 2-tuple of (chain, stopped) where ``chain`` is a list of | ||||
revs in ascending order and ``stopped`` is a bool indicating whether | ||||
``stoprev`` was hit. | ||||
""" | ||||
Gregory Szorc
|
r33168 | # Try C implementation. | ||
try: | ||||
return self.index.deltachain(rev, stoprev, self._generaldelta) | ||||
except AttributeError: | ||||
pass | ||||
Gregory Szorc
|
r27468 | chain = [] | ||
# Alias to prevent attribute lookup in tight loop. | ||||
index = self.index | ||||
generaldelta = self._generaldelta | ||||
iterrev = rev | ||||
e = index[iterrev] | ||||
while iterrev != e[3] and iterrev != stoprev: | ||||
chain.append(iterrev) | ||||
if generaldelta: | ||||
iterrev = e[3] | ||||
else: | ||||
iterrev -= 1 | ||||
e = index[iterrev] | ||||
if iterrev == stoprev: | ||||
stopped = True | ||||
else: | ||||
chain.append(iterrev) | ||||
stopped = False | ||||
chain.reverse() | ||||
return chain, stopped | ||||
Siddharth Agarwal
|
r18081 | def ancestors(self, revs, stoprev=0, inclusive=False): | ||
Greg Ward
|
r10047 | """Generate the ancestors of 'revs' in reverse topological order. | ||
Joshua Redstone
|
r16868 | Does not generate revs lower than stoprev. | ||
Greg Ward
|
r10047 | |||
Siddharth Agarwal
|
r18090 | See the documentation for ancestor.lazyancestors for more details.""" | ||
Siddharth Agarwal
|
r18081 | |||
Siddharth Agarwal
|
r23328 | return ancestor.lazyancestors(self.parentrevs, revs, stoprev=stoprev, | ||
Siddharth Agarwal
|
r18090 | inclusive=inclusive) | ||
Stefano Tortarolo
|
r6872 | |||
Bryan O'Sullivan
|
r16867 | def descendants(self, revs): | ||
Greg Ward
|
r10047 | """Generate the descendants of 'revs' in revision order. | ||
Yield a sequence of revision numbers starting with a child of | ||||
some rev in revs, i.e., each revision is *not* considered a | ||||
descendant of itself. Results are ordered by revision number (a | ||||
topological sort).""" | ||||
Nicolas Dumazet
|
r12950 | first = min(revs) | ||
if first == nullrev: | ||||
for i in self: | ||||
yield i | ||||
return | ||||
Martin Geisler
|
r8150 | seen = set(revs) | ||
Pierre-Yves David
|
r17672 | for i in self.revs(start=first + 1): | ||
Stefano Tortarolo
|
r6872 | for x in self.parentrevs(i): | ||
if x != nullrev and x in seen: | ||||
seen.add(i) | ||||
yield i | ||||
break | ||||
Peter Arrenbrecht
|
r13741 | def findcommonmissing(self, common=None, heads=None): | ||
"""Return a tuple of the ancestors of common and the ancestors of heads | ||||
Pierre-Yves David
|
r15835 | that are not ancestors of common. In revset terminology, we return the | ||
tuple: | ||||
Greg Ward
|
r10047 | |||
Pierre-Yves David
|
r15835 | ::common, (::heads) - (::common) | ||
Benoit Boissinot
|
r7233 | |||
Greg Ward
|
r10047 | The list is sorted by revision number, meaning it is | ||
topologically sorted. | ||||
'heads' and 'common' are both lists of node IDs. If heads is | ||||
not supplied, uses all of the revlog's heads. If common is not | ||||
supplied, uses nullid.""" | ||||
Benoit Boissinot
|
r7233 | if common is None: | ||
common = [nullid] | ||||
if heads is None: | ||||
heads = self.heads() | ||||
common = [self.rev(n) for n in common] | ||||
heads = [self.rev(n) for n in heads] | ||||
# we want the ancestors, but inclusive | ||||
Durham Goode
|
r20073 | class lazyset(object): | ||
def __init__(self, lazyvalues): | ||||
self.addedvalues = set() | ||||
self.lazyvalues = lazyvalues | ||||
def __contains__(self, value): | ||||
return value in self.addedvalues or value in self.lazyvalues | ||||
def __iter__(self): | ||||
added = self.addedvalues | ||||
for r in added: | ||||
yield r | ||||
for r in self.lazyvalues: | ||||
if not r in added: | ||||
yield r | ||||
def add(self, value): | ||||
self.addedvalues.add(value) | ||||
def update(self, values): | ||||
self.addedvalues.update(values) | ||||
has = lazyset(self.ancestors(common)) | ||||
Martin Geisler
|
r8152 | has.add(nullrev) | ||
has.update(common) | ||||
Benoit Boissinot
|
r7233 | |||
# take all ancestors from heads that aren't in has | ||||
Benoit Boissinot
|
r8453 | missing = set() | ||
Martin von Zweigbergk
|
r25113 | visit = collections.deque(r for r in heads if r not in has) | ||
Benoit Boissinot
|
r7233 | while visit: | ||
Bryan O'Sullivan
|
r16803 | r = visit.popleft() | ||
Benoit Boissinot
|
r7233 | if r in missing: | ||
continue | ||||
else: | ||||
Benoit Boissinot
|
r8453 | missing.add(r) | ||
Benoit Boissinot
|
r7233 | for p in self.parentrevs(r): | ||
if p not in has: | ||||
visit.append(p) | ||||
Benoit Boissinot
|
r8453 | missing = list(missing) | ||
Benoit Boissinot
|
r7233 | missing.sort() | ||
Augie Fackler
|
r30391 | return has, [self.node(miss) for miss in missing] | ||
Peter Arrenbrecht
|
r13741 | |||
Siddharth Agarwal
|
r23337 | def incrementalmissingrevs(self, common=None): | ||
"""Return an object that can be used to incrementally compute the | ||||
revision numbers of the ancestors of arbitrary sets that are not | ||||
ancestors of common. This is an ancestor.incrementalmissingancestors | ||||
object. | ||||
'common' is a list of revision numbers. If common is not supplied, uses | ||||
nullrev. | ||||
""" | ||||
if common is None: | ||||
common = [nullrev] | ||||
return ancestor.incrementalmissingancestors(self.parentrevs, common) | ||||
Siddharth Agarwal
|
r17972 | def findmissingrevs(self, common=None, heads=None): | ||
"""Return the revision numbers of the ancestors of heads that | ||||
are not ancestors of common. | ||||
More specifically, return a list of revision numbers corresponding to | ||||
nodes N such that every N satisfies the following constraints: | ||||
1. N is an ancestor of some node in 'heads' | ||||
2. N is not an ancestor of any node in 'common' | ||||
The list is sorted by revision number, meaning it is | ||||
topologically sorted. | ||||
'heads' and 'common' are both lists of revision numbers. If heads is | ||||
not supplied, uses all of the revlog's heads. If common is not | ||||
supplied, uses nullid.""" | ||||
if common is None: | ||||
common = [nullrev] | ||||
if heads is None: | ||||
heads = self.headrevs() | ||||
Siddharth Agarwal
|
r23338 | inc = self.incrementalmissingrevs(common=common) | ||
return inc.missingancestors(heads) | ||||
Siddharth Agarwal
|
r17972 | |||
Peter Arrenbrecht
|
r13741 | def findmissing(self, common=None, heads=None): | ||
"""Return the ancestors of heads that are not ancestors of common. | ||||
More specifically, return a list of nodes N such that every N | ||||
satisfies the following constraints: | ||||
1. N is an ancestor of some node in 'heads' | ||||
2. N is not an ancestor of any node in 'common' | ||||
The list is sorted by revision number, meaning it is | ||||
topologically sorted. | ||||
'heads' and 'common' are both lists of node IDs. If heads is | ||||
not supplied, uses all of the revlog's heads. If common is not | ||||
supplied, uses nullid.""" | ||||
Siddharth Agarwal
|
r17971 | if common is None: | ||
common = [nullid] | ||||
if heads is None: | ||||
heads = self.heads() | ||||
common = [self.rev(n) for n in common] | ||||
heads = [self.rev(n) for n in heads] | ||||
Siddharth Agarwal
|
r23338 | inc = self.incrementalmissingrevs(common=common) | ||
return [self.node(r) for r in inc.missingancestors(heads)] | ||||
Benoit Boissinot
|
r7233 | |||
Eric Hopper
|
r1457 | def nodesbetween(self, roots=None, heads=None): | ||
Greg Ward
|
r10047 | """Return a topological path from 'roots' to 'heads'. | ||
Return a tuple (nodes, outroots, outheads) where 'nodes' is a | ||||
topologically sorted list of all nodes N that satisfy both of | ||||
these constraints: | ||||
1. N is a descendant of some node in 'roots' | ||||
2. N is an ancestor of some node in 'heads' | ||||
Eric Hopper
|
r1457 | |||
Greg Ward
|
r10047 | Every node is considered to be both a descendant and an ancestor | ||
of itself, so every reachable node in 'roots' and 'heads' will be | ||||
included in 'nodes'. | ||||
Eric Hopper
|
r1457 | |||
Greg Ward
|
r10047 | 'outroots' is the list of reachable nodes in 'roots', i.e., the | ||
subset of 'roots' that is returned in 'nodes'. Likewise, | ||||
'outheads' is the subset of 'heads' that is also in 'nodes'. | ||||
'roots' and 'heads' are both lists of node IDs. If 'roots' is | ||||
unspecified, uses nullid as the only root. If 'heads' is | ||||
unspecified, uses list of all of the revlog's heads.""" | ||||
Eric Hopper
|
r1463 | nonodes = ([], [], []) | ||
Eric Hopper
|
r1457 | if roots is not None: | ||
roots = list(roots) | ||||
Eric Hopper
|
r1463 | if not roots: | ||
return nonodes | ||||
Eric Hopper
|
r1457 | lowestrev = min([self.rev(n) for n in roots]) | ||
else: | ||||
Matt Mackall
|
r14549 | roots = [nullid] # Everybody's a descendant of nullid | ||
Thomas Arendsen Hein
|
r3578 | lowestrev = nullrev | ||
if (lowestrev == nullrev) and (heads is None): | ||||
Eric Hopper
|
r1457 | # We want _all_ the nodes! | ||
Matt Mackall
|
r6750 | return ([self.node(r) for r in self], [nullid], list(self.heads())) | ||
Eric Hopper
|
r1457 | if heads is None: | ||
# All nodes are ancestors, so the latest ancestor is the last | ||||
# node. | ||||
Matt Mackall
|
r6750 | highestrev = len(self) - 1 | ||
Eric Hopper
|
r1457 | # Set ancestors to None to signal that every node is an ancestor. | ||
ancestors = None | ||||
# Set heads to an empty dictionary for later discovery of heads | ||||
heads = {} | ||||
else: | ||||
Eric Hopper
|
r1463 | heads = list(heads) | ||
if not heads: | ||||
return nonodes | ||||
Benoit Boissinot
|
r8464 | ancestors = set() | ||
Eric Hopper
|
r1457 | # Turn heads into a dictionary so we can remove 'fake' heads. | ||
# Also, later we will be using it to filter out the heads we can't | ||||
# find from roots. | ||||
Martin Geisler
|
r14219 | heads = dict.fromkeys(heads, False) | ||
Benoit Boissinot
|
r3360 | # Start at the top and keep marking parents until we're done. | ||
Martin Geisler
|
r8163 | nodestotag = set(heads) | ||
Eric Hopper
|
r1457 | # Remember where the top was so we can use it as a limit later. | ||
highestrev = max([self.rev(n) for n in nodestotag]) | ||||
while nodestotag: | ||||
# grab a node to tag | ||||
n = nodestotag.pop() | ||||
# Never tag nullid | ||||
if n == nullid: | ||||
continue | ||||
# A node's revision number represents its place in a | ||||
# topologically sorted list of nodes. | ||||
r = self.rev(n) | ||||
if r >= lowestrev: | ||||
if n not in ancestors: | ||||
Matt Mackall
|
r14549 | # If we are possibly a descendant of one of the roots | ||
Eric Hopper
|
r1457 | # and we haven't already been marked as an ancestor | ||
Benoit Boissinot
|
r8464 | ancestors.add(n) # Mark as ancestor | ||
Eric Hopper
|
r1457 | # Add non-nullid parents to list of nodes to tag. | ||
Martin Geisler
|
r8153 | nodestotag.update([p for p in self.parents(n) if | ||
Eric Hopper
|
r1457 | p != nullid]) | ||
elif n in heads: # We've seen it before, is it a fake head? | ||||
# So it is, real heads should not be the ancestors of | ||||
# any other heads. | ||||
heads.pop(n) | ||||
Eric Hopper
|
r1459 | if not ancestors: | ||
Eric Hopper
|
r1463 | return nonodes | ||
Eric Hopper
|
r1457 | # Now that we have our set of ancestors, we want to remove any | ||
# roots that are not ancestors. | ||||
# If one of the roots was nullid, everything is included anyway. | ||||
Thomas Arendsen Hein
|
r3578 | if lowestrev > nullrev: | ||
Eric Hopper
|
r1457 | # But, since we weren't, let's recompute the lowest rev to not | ||
# include roots that aren't ancestors. | ||||
# Filter out roots that aren't ancestors of heads | ||||
Augie Fackler
|
r30391 | roots = [root for root in roots if root in ancestors] | ||
Eric Hopper
|
r1457 | # Recompute the lowest revision | ||
if roots: | ||||
Augie Fackler
|
r30391 | lowestrev = min([self.rev(root) for root in roots]) | ||
Eric Hopper
|
r1457 | else: | ||
# No more roots? Return empty list | ||||
Eric Hopper
|
r1463 | return nonodes | ||
Eric Hopper
|
r1457 | else: | ||
# We are descending from nullid, and don't need to care about | ||||
# any other roots. | ||||
Thomas Arendsen Hein
|
r3578 | lowestrev = nullrev | ||
Eric Hopper
|
r1457 | roots = [nullid] | ||
Martin Geisler
|
r8152 | # Transform our roots list into a set. | ||
Matt Mackall
|
r14549 | descendants = set(roots) | ||
Eric Hopper
|
r1457 | # Also, keep the original roots so we can filter out roots that aren't | ||
# 'real' roots (i.e. are descended from other roots). | ||||
Matt Mackall
|
r14549 | roots = descendants.copy() | ||
Eric Hopper
|
r1457 | # Our topologically sorted list of output nodes. | ||
orderedout = [] | ||||
# Don't start at nullid since we don't want nullid in our output list, | ||||
timeless@mozdev.org
|
r17483 | # and if nullid shows up in descendants, empty parents will look like | ||
Matt Mackall
|
r14549 | # they're descendants. | ||
Pierre-Yves David
|
r17672 | for r in self.revs(start=max(lowestrev, 0), stop=highestrev + 1): | ||
Eric Hopper
|
r1457 | n = self.node(r) | ||
Matt Mackall
|
r14549 | isdescendant = False | ||
if lowestrev == nullrev: # Everybody is a descendant of nullid | ||||
isdescendant = True | ||||
elif n in descendants: | ||||
# n is already a descendant | ||||
isdescendant = True | ||||
Eric Hopper
|
r1457 | # This check only needs to be done here because all the roots | ||
Matt Mackall
|
r14549 | # will start being marked is descendants before the loop. | ||
Eric Hopper
|
r1457 | if n in roots: | ||
# If n was a root, check if it's a 'real' root. | ||||
p = tuple(self.parents(n)) | ||||
Matt Mackall
|
r14549 | # If any of its parents are descendants, it's not a root. | ||
if (p[0] in descendants) or (p[1] in descendants): | ||||
Martin Geisler
|
r8152 | roots.remove(n) | ||
Eric Hopper
|
r1457 | else: | ||
p = tuple(self.parents(n)) | ||||
Matt Mackall
|
r14549 | # A node is a descendant if either of its parents are | ||
# descendants. (We seeded the dependents list with the roots | ||||
Eric Hopper
|
r1457 | # up there, remember?) | ||
Matt Mackall
|
r14549 | if (p[0] in descendants) or (p[1] in descendants): | ||
descendants.add(n) | ||||
isdescendant = True | ||||
if isdescendant and ((ancestors is None) or (n in ancestors)): | ||||
# Only include nodes that are both descendants and ancestors. | ||||
Eric Hopper
|
r1457 | orderedout.append(n) | ||
if (ancestors is not None) and (n in heads): | ||||
# We're trying to figure out which heads are reachable | ||||
# from roots. | ||||
# Mark this head as having been reached | ||||
Martin Geisler
|
r14219 | heads[n] = True | ||
Eric Hopper
|
r1457 | elif ancestors is None: | ||
# Otherwise, we're trying to discover the heads. | ||||
# Assume this is a head because if it isn't, the next step | ||||
# will eventually remove it. | ||||
Martin Geisler
|
r14219 | heads[n] = True | ||
Eric Hopper
|
r1457 | # But, obviously its parents aren't. | ||
for p in self.parents(n): | ||||
heads.pop(p, None) | ||||
Augie Fackler
|
r30391 | heads = [head for head, flag in heads.iteritems() if flag] | ||
Martin Geisler
|
r8152 | roots = list(roots) | ||
Eric Hopper
|
r1457 | assert orderedout | ||
assert roots | ||||
assert heads | ||||
return (orderedout, roots, heads) | ||||
Peter Arrenbrecht
|
r14164 | def headrevs(self): | ||
Bryan O'Sullivan
|
r16786 | try: | ||
return self.index.headrevs() | ||||
except AttributeError: | ||||
Pierre-Yves David
|
r17674 | return self._headrevs() | ||
Laurent Charignon
|
r24444 | def computephases(self, roots): | ||
Laurent Charignon
|
r25361 | return self.index.computephasesmapsets(roots) | ||
Laurent Charignon
|
r24444 | |||
Pierre-Yves David
|
r17674 | def _headrevs(self): | ||
Peter Arrenbrecht
|
r14164 | count = len(self) | ||
if not count: | ||||
return [nullrev] | ||||
Pierre-Yves David
|
r17673 | # we won't iter over filtered rev so nobody is a head at start | ||
ishead = [0] * (count + 1) | ||||
Peter Arrenbrecht
|
r14164 | index = self.index | ||
Pierre-Yves David
|
r17672 | for r in self: | ||
Pierre-Yves David
|
r17673 | ishead[r] = 1 # I may be an head | ||
Peter Arrenbrecht
|
r14164 | e = index[r] | ||
Pierre-Yves David
|
r17673 | ishead[e[5]] = ishead[e[6]] = 0 # my parent are not | ||
return [r for r, val in enumerate(ishead) if val] | ||||
Peter Arrenbrecht
|
r14164 | |||
Benoit Boissinot
|
r3923 | def heads(self, start=None, stop=None): | ||
Benoit Boissinot
|
r1550 | """return the list of all nodes that have no children | ||
Thomas Arendsen Hein
|
r1551 | |||
if start is specified, only heads that are descendants of | ||||
start will be returned | ||||
Benoit Boissinot
|
r3923 | if stop is specified, it will consider all the revs from stop | ||
as if they had no children | ||||
Thomas Arendsen Hein
|
r1551 | """ | ||
Matt Mackall
|
r4991 | if start is None and stop is None: | ||
Peter Arrenbrecht
|
r14164 | if not len(self): | ||
Matt Mackall
|
r4991 | return [nullid] | ||
Peter Arrenbrecht
|
r14164 | return [self.node(r) for r in self.headrevs()] | ||
Matt Mackall
|
r4991 | |||
Thomas Arendsen Hein
|
r1551 | if start is None: | ||
start = nullid | ||||
Benoit Boissinot
|
r3923 | if stop is None: | ||
stop = [] | ||||
Martin Geisler
|
r8152 | stoprevs = set([self.rev(n) for n in stop]) | ||
Benoit Boissinot
|
r1550 | startrev = self.rev(start) | ||
Martin von Zweigbergk
|
r32291 | reachable = {startrev} | ||
heads = {startrev} | ||||
mpm@selenic.com
|
r1083 | |||
Alexis S. L. Carvalho
|
r2490 | parentrevs = self.parentrevs | ||
Pierre-Yves David
|
r17672 | for r in self.revs(start=startrev + 1): | ||
Alexis S. L. Carvalho
|
r2490 | for p in parentrevs(r): | ||
if p in reachable: | ||||
Benoit Boissinot
|
r3923 | if r not in stoprevs: | ||
Benoit Boissinot
|
r8464 | reachable.add(r) | ||
heads.add(r) | ||||
Benoit Boissinot
|
r3923 | if p in heads and p not in stoprevs: | ||
Benoit Boissinot
|
r8464 | heads.remove(p) | ||
Benoit Boissinot
|
r3923 | |||
Alexis S. L. Carvalho
|
r2490 | return [self.node(r) for r in heads] | ||
mpm@selenic.com
|
r370 | |||
def children(self, node): | ||||
mpm@selenic.com
|
r1083 | """find the children of a given node""" | ||
mpm@selenic.com
|
r370 | c = [] | ||
p = self.rev(node) | ||||
Pierre-Yves David
|
r17672 | for r in self.revs(start=p + 1): | ||
Thomas Arendsen Hein
|
r4746 | prevs = [pr for pr in self.parentrevs(r) if pr != nullrev] | ||
if prevs: | ||||
for pr in prevs: | ||||
if pr == p: | ||||
c.append(self.node(r)) | ||||
elif p == nullrev: | ||||
c.append(self.node(r)) | ||||
mpm@selenic.com
|
r370 | return c | ||
mpm@selenic.com
|
r515 | |||
Mads Kiilerich
|
r21104 | def commonancestorsheads(self, a, b): | ||
"""calculate all the heads of the common ancestors of nodes a and b""" | ||||
a, b = self.rev(a), self.rev(b) | ||||
Boris Feld
|
r38531 | ancs = self._commonancestorsheads(a, b) | ||
return pycompat.maplist(self.node, ancs) | ||||
def _commonancestorsheads(self, *revs): | ||||
"""calculate all the heads of the common ancestors of revs""" | ||||
Mads Kiilerich
|
r21104 | try: | ||
Boris Feld
|
r38531 | ancs = self.index.commonancestorsheads(*revs) | ||
Mads Kiilerich
|
r21104 | except (AttributeError, OverflowError): # C implementation failed | ||
Boris Feld
|
r38531 | ancs = ancestor.commonancestorsheads(self.parentrevs, *revs) | ||
return ancs | ||||
Mads Kiilerich
|
r21104 | |||
Mads Kiilerich
|
r22381 | def isancestor(self, a, b): | ||
Martin von Zweigbergk
|
r38686 | """return True if node a is an ancestor of node b | ||
A revision is considered an ancestor of itself.""" | ||||
Boris Feld
|
r38533 | a, b = self.rev(a), self.rev(b) | ||
Martin von Zweigbergk
|
r38688 | return self.isancestorrev(a, b) | ||
def isancestorrev(self, a, b): | ||||
"""return True if revision a is an ancestor of revision b | ||||
Martin von Zweigbergk
|
r38690 | A revision is considered an ancestor of itself. | ||
The implementation of this is trivial but the use of | ||||
commonancestorsheads is not.""" | ||||
if a == nullrev: | ||||
return True | ||||
elif a == b: | ||||
return True | ||||
elif a > b: | ||||
return False | ||||
return a in self._commonancestorsheads(a, b) | ||||
Mads Kiilerich
|
r22381 | |||
Mads Kiilerich
|
r21107 | def ancestor(self, a, b): | ||
Mads Kiilerich
|
r22389 | """calculate the "best" common ancestor of nodes a and b""" | ||
Mads Kiilerich
|
r21107 | |||
Benoit Boissinot
|
r10897 | a, b = self.rev(a), self.rev(b) | ||
Bryan O'Sullivan
|
r18988 | try: | ||
ancs = self.index.ancestors(a, b) | ||||
Mads Kiilerich
|
r21107 | except (AttributeError, OverflowError): | ||
Bryan O'Sullivan
|
r18988 | ancs = ancestor.ancestors(self.parentrevs, a, b) | ||
Bryan O'Sullivan
|
r18987 | if ancs: | ||
# choose a consistent winner when there's a tie | ||||
Mads Kiilerich
|
r21107 | return min(map(self.node, ancs)) | ||
Bryan O'Sullivan
|
r18987 | return nullid | ||
Benoit Boissinot
|
r10897 | |||
Matt Mackall
|
r3453 | def _match(self, id): | ||
Matt Mackall
|
r16762 | if isinstance(id, int): | ||
Benoit Boissinot
|
r3156 | # rev | ||
Benoit Boissinot
|
r2641 | return self.node(id) | ||
Matt Mackall
|
r3438 | if len(id) == 20: | ||
# possibly a binary node | ||||
# odds of a binary node being all hex in ASCII are 1 in 10**25 | ||||
try: | ||||
node = id | ||||
Peter Arrenbrecht
|
r7874 | self.rev(node) # quick search the index | ||
Matt Mackall
|
r3438 | return node | ||
Brendan Cully
|
r3930 | except LookupError: | ||
Matt Mackall
|
r3438 | pass # may be partial hex id | ||
mpm@selenic.com
|
r36 | try: | ||
Benoit Boissinot
|
r3156 | # str(rev) | ||
mpm@selenic.com
|
r36 | rev = int(id) | ||
Pulkit Goyal
|
r36738 | if "%d" % rev != id: | ||
Matt Mackall
|
r4980 | raise ValueError | ||
if rev < 0: | ||||
Matt Mackall
|
r6750 | rev = len(self) + rev | ||
if rev < 0 or rev >= len(self): | ||||
Matt Mackall
|
r4980 | raise ValueError | ||
mpm@selenic.com
|
r36 | return self.node(rev) | ||
mpm@selenic.com
|
r469 | except (ValueError, OverflowError): | ||
Benoit Boissinot
|
r3156 | pass | ||
Matt Mackall
|
r3453 | if len(id) == 40: | ||
try: | ||||
Matt Mackall
|
r3438 | # a full hex nodeid? | ||
node = bin(id) | ||||
Peter Arrenbrecht
|
r7874 | self.rev(node) | ||
Benoit Boissinot
|
r3157 | return node | ||
Sune Foldager
|
r7062 | except (TypeError, LookupError): | ||
Matt Mackall
|
r3453 | pass | ||
def _partialmatch(self, id): | ||||
Yuya Nishihara
|
r37467 | # we don't care wdirfilenodeids as they should be always full hash | ||
Yuya Nishihara
|
r32684 | maybewdir = wdirhex.startswith(id) | ||
Bryan O'Sullivan
|
r16665 | try: | ||
Augie Fackler
|
r30391 | partial = self.index.partialmatch(id) | ||
if partial and self.hasnode(partial): | ||||
Yuya Nishihara
|
r32684 | if maybewdir: | ||
# single 'ff...' match in radix tree, ambiguous with wdir | ||||
raise RevlogError | ||||
Augie Fackler
|
r30391 | return partial | ||
Yuya Nishihara
|
r32684 | if maybewdir: | ||
# no 'ff...' match in radix tree, wdir identified | ||||
raise error.WdirUnsupported | ||||
Matt Mackall
|
r19471 | return None | ||
Bryan O'Sullivan
|
r16665 | except RevlogError: | ||
# parsers.c radix tree lookup gave multiple matches | ||||
Jun Wu
|
r29396 | # fast path: for unfiltered changelog, radix tree is accurate | ||
if not getattr(self, 'filteredrevs', None): | ||||
Martin von Zweigbergk
|
r38877 | raise AmbiguousPrefixLookupError(id, self.indexfile, | ||
_('ambiguous identifier')) | ||||
Matt Mackall
|
r19471 | # fall through to slow path that filters hidden revisions | ||
Bryan O'Sullivan
|
r16665 | except (AttributeError, ValueError): | ||
# we are pure python, or key was too short to search radix tree | ||||
pass | ||||
Matt Mackall
|
r13258 | if id in self._pcache: | ||
return self._pcache[id] | ||||
Martin von Zweigbergk
|
r37837 | if len(id) <= 40: | ||
Matt Mackall
|
r3453 | try: | ||
Matt Mackall
|
r3438 | # hex(node)[:...] | ||
Alejandro Santos
|
r9029 | l = len(id) // 2 # grab an even number of digits | ||
Matt Mackall
|
r13259 | prefix = bin(id[:l * 2]) | ||
nl = [e[7] for e in self.index if e[7].startswith(prefix)] | ||||
Matt Mackall
|
r19471 | nl = [n for n in nl if hex(n).startswith(id) and | ||
self.hasnode(n)] | ||||
Martin von Zweigbergk
|
r39227 | if nullhex.startswith(id): | ||
nl.append(nullid) | ||||
Matt Mackall
|
r7365 | if len(nl) > 0: | ||
Yuya Nishihara
|
r32684 | if len(nl) == 1 and not maybewdir: | ||
Matt Mackall
|
r13258 | self._pcache[id] = nl[0] | ||
Matt Mackall
|
r7365 | return nl[0] | ||
Martin von Zweigbergk
|
r38877 | raise AmbiguousPrefixLookupError(id, self.indexfile, | ||
_('ambiguous identifier')) | ||||
Yuya Nishihara
|
r32684 | if maybewdir: | ||
raise error.WdirUnsupported | ||||
Matt Mackall
|
r7365 | return None | ||
Augie Fackler
|
r36256 | except TypeError: | ||
Matt Mackall
|
r3453 | pass | ||
def lookup(self, id): | ||||
"""locate a node based on: | ||||
- revision number or str(revision number) | ||||
- nodeid or subset of hex nodeid | ||||
""" | ||||
n = self._match(id) | ||||
if n is not None: | ||||
return n | ||||
n = self._partialmatch(id) | ||||
if n: | ||||
return n | ||||
mpm@selenic.com
|
r515 | |||
Matt Mackall
|
r6228 | raise LookupError(id, self.indexfile, _('no match found')) | ||
mpm@selenic.com
|
r36 | |||
Martin von Zweigbergk
|
r37785 | def shortest(self, node, minlength=1): | ||
"""Find the shortest unambiguous prefix that matches node.""" | ||||
Martin von Zweigbergk
|
r37880 | def isvalid(prefix): | ||
Martin von Zweigbergk
|
r34247 | try: | ||
Martin von Zweigbergk
|
r37882 | node = self._partialmatch(prefix) | ||
Martin von Zweigbergk
|
r34247 | except error.RevlogError: | ||
return False | ||||
except error.WdirUnsupported: | ||||
# single 'ff...' match | ||||
return True | ||||
Martin von Zweigbergk
|
r37882 | if node is None: | ||
raise LookupError(node, self.indexfile, _('no node')) | ||||
Martin von Zweigbergk
|
r37989 | return True | ||
Martin von Zweigbergk
|
r34247 | |||
Martin von Zweigbergk
|
r37987 | def maybewdir(prefix): | ||
return all(c == 'f' for c in prefix) | ||||
Martin von Zweigbergk
|
r37785 | hexnode = hex(node) | ||
Martin von Zweigbergk
|
r37987 | |||
def disambiguate(hexnode, minlength): | ||||
Martin von Zweigbergk
|
r37990 | """Disambiguate against wdirid.""" | ||
Martin von Zweigbergk
|
r37987 | for length in range(minlength, 41): | ||
prefix = hexnode[:length] | ||||
Martin von Zweigbergk
|
r37990 | if not maybewdir(prefix): | ||
Martin von Zweigbergk
|
r37987 | return prefix | ||
if not getattr(self, 'filteredrevs', None): | ||||
try: | ||||
length = max(self.index.shortest(node), minlength) | ||||
return disambiguate(hexnode, length) | ||||
except RevlogError: | ||||
Martin von Zweigbergk
|
r37988 | if node != wdirid: | ||
Martin von Zweigbergk
|
r37987 | raise LookupError(node, self.indexfile, _('no node')) | ||
except AttributeError: | ||||
# Fall through to pure code | ||||
pass | ||||
Martin von Zweigbergk
|
r37988 | if node == wdirid: | ||
for length in range(minlength, 41): | ||||
prefix = hexnode[:length] | ||||
if isvalid(prefix): | ||||
return prefix | ||||
for length in range(minlength, 41): | ||||
Martin von Zweigbergk
|
r37880 | prefix = hexnode[:length] | ||
if isvalid(prefix): | ||||
Martin von Zweigbergk
|
r37988 | return disambiguate(hexnode, length) | ||
Martin von Zweigbergk
|
r34247 | |||
Matt Mackall
|
r2890 | def cmp(self, node, text): | ||
Nicolas Dumazet
|
r11539 | """compare text with a given file revision | ||
returns True if text is different than what is stored. | ||||
""" | ||||
Matt Mackall
|
r2890 | p1, p2 = self.parents(node) | ||
return hash(text, p1, p2) != node | ||||
Gregory Szorc
|
r32222 | def _cachesegment(self, offset, data): | ||
Gregory Szorc
|
r27070 | """Add a segment to the revlog cache. | ||
Accepts an absolute offset and the data that is at that location. | ||||
""" | ||||
Matt Mackall
|
r8316 | o, d = self._chunkcache | ||
# try to add to existing cache | ||||
Matt Mackall
|
r13253 | if o + len(d) == offset and len(d) + len(data) < _chunksize: | ||
Matt Mackall
|
r8316 | self._chunkcache = o, d + data | ||
else: | ||||
self._chunkcache = offset, data | ||||
Gregory Szorc
|
r32222 | def _readsegment(self, offset, length, df=None): | ||
Gregory Szorc
|
r27070 | """Load a segment of raw data from the revlog. | ||
Gregory Szorc
|
r26377 | |||
Gregory Szorc
|
r27070 | Accepts an absolute offset, length to read, and an optional existing | ||
Gregory Szorc
|
r26377 | file handle to read from. | ||
If an existing file handle is passed, it will be seeked and the | ||||
original seek position will NOT be restored. | ||||
Gregory Szorc
|
r27070 | |||
Returns a str or buffer of raw byte data. | ||||
Gregory Szorc
|
r26377 | """ | ||
Brodie Rao
|
r20179 | # Cache data both forward and backward around the requested | ||
# data, in a fixed size window. This helps speed up operations | ||||
# involving reading the revlog backwards. | ||||
Brodie Rao
|
r20180 | cachesize = self._chunkcachesize | ||
realoffset = offset & ~(cachesize - 1) | ||||
reallength = (((offset + length + cachesize) & ~(cachesize - 1)) | ||||
- realoffset) | ||||
Boris Feld
|
r35991 | with self._datareadfp(df) as df: | ||
df.seek(realoffset) | ||||
d = df.read(reallength) | ||||
Gregory Szorc
|
r32222 | self._cachesegment(realoffset, d) | ||
Brodie Rao
|
r20179 | if offset != realoffset or reallength != length: | ||
return util.buffer(d, offset - realoffset, length) | ||||
Matt Mackall
|
r8316 | return d | ||
Gregory Szorc
|
r32222 | def _getsegment(self, offset, length, df=None): | ||
Gregory Szorc
|
r27070 | """Obtain a segment of raw data from the revlog. | ||
Accepts an absolute offset, length of bytes to obtain, and an | ||||
optional file handle to the already-opened revlog. If the file | ||||
handle is used, it's original seek position will not be preserved. | ||||
Requests for data may be returned from a cache. | ||||
Returns a str or a buffer instance of raw byte data. | ||||
""" | ||||
Matt Mackall
|
r8316 | o, d = self._chunkcache | ||
l = len(d) | ||||
# is it in the cache? | ||||
cachestart = offset - o | ||||
cacheend = cachestart + length | ||||
if cachestart >= 0 and cacheend <= l: | ||||
if cachestart == 0 and cacheend == l: | ||||
return d # avoid a copy | ||||
Bryan O'Sullivan
|
r16423 | return util.buffer(d, cachestart, cacheend - cachestart) | ||
Matt Mackall
|
r8316 | |||
Gregory Szorc
|
r32222 | return self._readsegment(offset, length, df=df) | ||
Matt Mackall
|
r8316 | |||
Gregory Szorc
|
r32224 | def _getsegmentforrevs(self, startrev, endrev, df=None): | ||
Gregory Szorc
|
r27070 | """Obtain a segment of raw data corresponding to a range of revisions. | ||
Accepts the start and end revisions and an optional already-open | ||||
file handle to be used for reading. If the file handle is read, its | ||||
seek position will not be preserved. | ||||
Requests for data may be satisfied by a cache. | ||||
Gregory Szorc
|
r27649 | Returns a 2-tuple of (offset, data) for the requested range of | ||
revisions. Offset is the integer offset from the beginning of the | ||||
revlog and data is a str or buffer of the raw byte data. | ||||
Callers will need to call ``self.start(rev)`` and ``self.length(rev)`` | ||||
to determine where each revision's data begins and ends. | ||||
Gregory Szorc
|
r27070 | """ | ||
Gregory Szorc
|
r30288 | # Inlined self.start(startrev) & self.end(endrev) for perf reasons | ||
# (functions are expensive). | ||||
index = self.index | ||||
istart = index[startrev] | ||||
start = int(istart[0] >> 16) | ||||
Gregory Szorc
|
r30289 | if startrev == endrev: | ||
end = start + istart[1] | ||||
else: | ||||
iend = index[endrev] | ||||
end = int(iend[0] >> 16) + iend[1] | ||||
Gregory Szorc
|
r30288 | |||
Matt Mackall
|
r8318 | if self._inline: | ||
start += (startrev + 1) * self._io.size | ||||
Siddharth Agarwal
|
r19714 | end += (endrev + 1) * self._io.size | ||
length = end - start | ||||
Gregory Szorc
|
r27649 | |||
Gregory Szorc
|
r32222 | return start, self._getsegment(start, length, df=df) | ||
Matt Mackall
|
r8318 | |||
Gregory Szorc
|
r26377 | def _chunk(self, rev, df=None): | ||
Gregory Szorc
|
r27070 | """Obtain a single decompressed chunk for a revision. | ||
Accepts an integer revision and an optional already-open file handle | ||||
to be used for reading. If used, the seek position of the file will not | ||||
be preserved. | ||||
Returns a str holding uncompressed data for the requested revision. | ||||
""" | ||||
Gregory Szorc
|
r32224 | return self.decompress(self._getsegmentforrevs(rev, rev, df=df)[1]) | ||
Matt Mackall
|
r8650 | |||
Boris Feld
|
r38666 | def _chunks(self, revs, df=None, targetsize=None): | ||
Gregory Szorc
|
r27070 | """Obtain decompressed chunks for the specified revisions. | ||
Siddharth Agarwal
|
r19713 | |||
Gregory Szorc
|
r27070 | Accepts an iterable of numeric revisions that are assumed to be in | ||
ascending order. Also accepts an optional already-open file handle | ||||
to be used for reading. If used, the seek position of the file will | ||||
not be preserved. | ||||
This function is similar to calling ``self._chunk()`` multiple times, | ||||
but is faster. | ||||
Returns a list with decompressed data for each requested revision. | ||||
""" | ||||
Siddharth Agarwal
|
r19716 | if not revs: | ||
return [] | ||||
Siddharth Agarwal
|
r19713 | start = self.start | ||
length = self.length | ||||
inline = self._inline | ||||
iosize = self._io.size | ||||
Siddharth Agarwal
|
r19715 | buffer = util.buffer | ||
Siddharth Agarwal
|
r19713 | |||
l = [] | ||||
ladd = l.append | ||||
Paul Morelle
|
r34825 | if not self._withsparseread: | ||
slicedchunks = (revs,) | ||||
else: | ||||
Boris Feld
|
r39366 | slicedchunks = deltautil.slicechunk(self, revs, | ||
targetsize=targetsize) | ||||
Paul Morelle
|
r34825 | |||
for revschunk in slicedchunks: | ||||
firstrev = revschunk[0] | ||||
# Skip trailing revisions with empty diff | ||||
for lastrev in revschunk[::-1]: | ||||
if length(lastrev) != 0: | ||||
break | ||||
Paul Morelle
|
r34824 | |||
Paul Morelle
|
r34825 | try: | ||
offset, data = self._getsegmentforrevs(firstrev, lastrev, df=df) | ||||
except OverflowError: | ||||
# issue4215 - we can't cache a run of chunks greater than | ||||
# 2G on Windows | ||||
return [self._chunk(rev, df=df) for rev in revschunk] | ||||
Siddharth Agarwal
|
r19715 | |||
Paul Morelle
|
r34825 | decomp = self.decompress | ||
for rev in revschunk: | ||||
chunkstart = start(rev) | ||||
if inline: | ||||
chunkstart += (rev + 1) * iosize | ||||
chunklength = length(rev) | ||||
ladd(decomp(buffer(data, chunkstart - offset, chunklength))) | ||||
Siddharth Agarwal
|
r19713 | |||
return l | ||||
Sune Foldager
|
r14075 | |||
Matt Mackall
|
r8650 | def _chunkclear(self): | ||
Gregory Szorc
|
r27070 | """Clear the raw chunk cache.""" | ||
Matt Mackall
|
r8650 | self._chunkcache = (0, '') | ||
Benoit Boissinot
|
r1598 | |||
Pradeepkumar Gayam
|
r11929 | def deltaparent(self, rev): | ||
Sune Foldager
|
r14195 | """return deltaparent of the given revision""" | ||
Sune Foldager
|
r14253 | base = self.index[rev][3] | ||
if base == rev: | ||||
Sune Foldager
|
r14208 | return nullrev | ||
Sune Foldager
|
r14253 | elif self._generaldelta: | ||
return base | ||||
Sune Foldager
|
r14208 | else: | ||
return rev - 1 | ||||
Pradeepkumar Gayam
|
r11929 | |||
Paul Morelle
|
r39185 | def issnapshot(self, rev): | ||
"""tells whether rev is a snapshot | ||||
""" | ||||
if rev == nullrev: | ||||
return True | ||||
deltap = self.deltaparent(rev) | ||||
if deltap == nullrev: | ||||
return True | ||||
Paul Morelle
|
r39186 | p1, p2 = self.parentrevs(rev) | ||
if deltap in (p1, p2): | ||||
return False | ||||
return self.issnapshot(deltap) | ||||
Paul Morelle
|
r39185 | |||
Boris Feld
|
r39188 | def snapshotdepth(self, rev): | ||
"""number of snapshot in the chain before this one""" | ||||
if not self.issnapshot(rev): | ||||
raise ProgrammingError('revision %d not a snapshot') | ||||
return len(self._deltachain(rev)[0]) - 1 | ||||
Benoit Boissinot
|
r1941 | def revdiff(self, rev1, rev2): | ||
Jun Wu
|
r31753 | """return or calculate a delta between two revisions | ||
The delta calculated is in binary form and is intended to be written to | ||||
revlog data directly. So this function needs raw revision data. | ||||
""" | ||||
Sune Foldager
|
r14208 | if rev1 != nullrev and self.deltaparent(rev2) == rev1: | ||
Augie Fackler
|
r31369 | return bytes(self._chunk(rev2)) | ||
Matt Mackall
|
r5005 | |||
Jun Wu
|
r31753 | return mdiff.textdiff(self.revision(rev1, raw=True), | ||
self.revision(rev2, raw=True)) | ||||
mpm@selenic.com
|
r119 | |||
Remi Chaintron
|
r30743 | def revision(self, nodeorrev, _df=None, raw=False): | ||
Patrick Mezard
|
r16435 | """return an uncompressed revision of a given node or revision | ||
number. | ||||
Gregory Szorc
|
r26377 | |||
Remi Chaintron
|
r30743 | _df - an existing file handle to read from. (internal-only) | ||
raw - an optional argument specifying if the revision data is to be | ||||
treated as raw data when applying flag transforms. 'raw' should be set | ||||
to True when generating changegroups or in debug commands. | ||||
Patrick Mezard
|
r16435 | """ | ||
Matt Mackall
|
r16375 | if isinstance(nodeorrev, int): | ||
rev = nodeorrev | ||||
node = self.node(rev) | ||||
else: | ||||
node = nodeorrev | ||||
rev = None | ||||
Benoit Boissinot
|
r11996 | cachedrev = None | ||
Jun Wu
|
r31802 | flags = None | ||
Jun Wu
|
r31804 | rawtext = None | ||
Matt Mackall
|
r4980 | if node == nullid: | ||
return "" | ||||
Gregory Szorc
|
r26242 | if self._cache: | ||
if self._cache[0] == node: | ||||
Jun Wu
|
r31751 | # _cache only stores rawtext | ||
if raw: | ||||
return self._cache[2] | ||||
Jun Wu
|
r31756 | # duplicated, but good for perf | ||
if rev is None: | ||||
rev = self.rev(node) | ||||
Jun Wu
|
r31802 | if flags is None: | ||
flags = self.flags(rev) | ||||
Jun Wu
|
r31756 | # no extra flags set, no flag processor runs, text = rawtext | ||
Jun Wu
|
r31802 | if flags == REVIDX_DEFAULT_FLAGS: | ||
Jun Wu
|
r31756 | return self._cache[2] | ||
Jun Wu
|
r31804 | # rawtext is reusable. need to run flag processor | ||
rawtext = self._cache[2] | ||||
Jun Wu
|
r31756 | |||
Gregory Szorc
|
r26242 | cachedrev = self._cache[1] | ||
mpm@selenic.com
|
r0 | |||
mpm@selenic.com
|
r1083 | # look up what we need to read | ||
Jun Wu
|
r31803 | if rawtext is None: | ||
if rev is None: | ||||
rev = self.rev(node) | ||||
mpm@selenic.com
|
r0 | |||
Jun Wu
|
r31803 | chain, stopped = self._deltachain(rev, stoprev=cachedrev) | ||
if stopped: | ||||
rawtext = self._cache[2] | ||||
mpm@selenic.com
|
r0 | |||
Jun Wu
|
r31803 | # drop cache to save memory | ||
self._cache = None | ||||
Matt Mackall
|
r11754 | |||
Boris Feld
|
r38666 | targetsize = None | ||
rawsize = self.index[rev][2] | ||||
if 0 <= rawsize: | ||||
targetsize = 4 * rawsize | ||||
bins = self._chunks(chain, df=_df, targetsize=targetsize) | ||||
Jun Wu
|
r31803 | if rawtext is None: | ||
rawtext = bytes(bins[0]) | ||||
bins = bins[1:] | ||||
Matt Mackall
|
r8650 | |||
Jun Wu
|
r31803 | rawtext = mdiff.patches(rawtext, bins) | ||
Jun Wu
|
r31804 | self._cache = (node, rev, rawtext) | ||
Remi Chaintron
|
r30745 | |||
Jun Wu
|
r31802 | if flags is None: | ||
Jun Wu
|
r31804 | if rev is None: | ||
rev = self.rev(node) | ||||
Jun Wu
|
r31802 | flags = self.flags(rev) | ||
text, validatehash = self._processflags(rawtext, flags, 'read', raw=raw) | ||||
Remi Chaintron
|
r30745 | if validatehash: | ||
self.checkhash(text, node, rev=rev) | ||||
Matt Mackall
|
r13239 | return text | ||
Augie Fackler
|
r22785 | def hash(self, text, p1, p2): | ||
"""Compute a node hash. | ||||
Available as a function so that subclasses can replace the hash | ||||
as needed. | ||||
""" | ||||
return hash(text, p1, p2) | ||||
Remi Chaintron
|
r30745 | def _processflags(self, text, flags, operation, raw=False): | ||
"""Inspect revision data flags and applies transforms defined by | ||||
registered flag processors. | ||||
``text`` - the revision data to process | ||||
``flags`` - the revision flags | ||||
``operation`` - the operation being performed (read or write) | ||||
``raw`` - an optional argument describing if the raw transform should be | ||||
applied. | ||||
This method processes the flags in the order (or reverse order if | ||||
``operation`` is 'write') defined by REVIDX_FLAGS_ORDER, applying the | ||||
flag processors registered for present flags. The order of flags defined | ||||
in REVIDX_FLAGS_ORDER needs to be stable to allow non-commutativity. | ||||
Returns a 2-tuple of ``(text, validatehash)`` where ``text`` is the | ||||
processed text and ``validatehash`` is a bool indicating whether the | ||||
returned text should be checked for hash integrity. | ||||
Note: If the ``raw`` argument is set, it has precedence over the | ||||
operation and will only update the value of ``validatehash``. | ||||
""" | ||||
Jun Wu
|
r32286 | # fast path: no flag processors will run | ||
if flags == 0: | ||||
return text, True | ||||
Remi Chaintron
|
r30745 | if not operation in ('read', 'write'): | ||
raise ProgrammingError(_("invalid '%s' operation ") % (operation)) | ||||
# Check all flags are known. | ||||
if flags & ~REVIDX_KNOWN_FLAGS: | ||||
raise RevlogError(_("incompatible revision flag '%#x'") % | ||||
(flags & ~REVIDX_KNOWN_FLAGS)) | ||||
validatehash = True | ||||
# Depending on the operation (read or write), the order might be | ||||
# reversed due to non-commutative transforms. | ||||
orderedflags = REVIDX_FLAGS_ORDER | ||||
if operation == 'write': | ||||
orderedflags = reversed(orderedflags) | ||||
for flag in orderedflags: | ||||
# If a flagprocessor has been registered for a known flag, apply the | ||||
# related operation transform and update result tuple. | ||||
if flag & flags: | ||||
vhash = True | ||||
if flag not in _flagprocessors: | ||||
message = _("missing processor for flag '%#x'") % (flag) | ||||
raise RevlogError(message) | ||||
processor = _flagprocessors[flag] | ||||
if processor is not None: | ||||
readtransform, writetransform, rawtransform = processor | ||||
if raw: | ||||
vhash = rawtransform(self, text) | ||||
elif operation == 'read': | ||||
text, vhash = readtransform(self, text) | ||||
else: # write operation | ||||
text, vhash = writetransform(self, text) | ||||
validatehash = validatehash and vhash | ||||
return text, validatehash | ||||
Remi Chaintron
|
r30584 | def checkhash(self, text, node, p1=None, p2=None, rev=None): | ||
"""Check node hash integrity. | ||||
Wojciech Lopata
|
r19624 | |||
Remi Chaintron
|
r30584 | Available as a function so that subclasses can extend hash mismatch | ||
behaviors as needed. | ||||
""" | ||||
Gregory Szorc
|
r37461 | try: | ||
if p1 is None and p2 is None: | ||||
p1, p2 = self.parents(node) | ||||
if node != self.hash(text, p1, p2): | ||||
revornode = rev | ||||
if revornode is None: | ||||
revornode = templatefilters.short(hex(node)) | ||||
raise RevlogError(_("integrity check failed on %s:%s") | ||||
% (self.indexfile, pycompat.bytestr(revornode))) | ||||
except RevlogError: | ||||
if self._censorable and _censoredtext(text): | ||||
raise error.CensoredNodeError(self.indexfile, node, text) | ||||
raise | ||||
mpm@selenic.com
|
r0 | |||
Boris Feld
|
r35992 | def _enforceinlinesize(self, tr, fp=None): | ||
Gregory Szorc
|
r26376 | """Check if the revlog is too big for inline and convert if so. | ||
This should be called after revisions are added to the revlog. If the | ||||
revlog has grown too large to be an inline revlog, it will convert it | ||||
to use multiple index and data files. | ||||
""" | ||||
Martin von Zweigbergk
|
r38880 | tiprev = len(self) - 1 | ||
if (not self._inline or | ||||
(self.start(tiprev) + self.length(tiprev)) < _maxinline): | ||||
mason@suse.com
|
r2073 | return | ||
Matt Mackall
|
r8315 | |||
Chris Mason
|
r2084 | trinfo = tr.find(self.indexfile) | ||
Martin Geisler
|
r8527 | if trinfo is None: | ||
Thomas Arendsen Hein
|
r3680 | raise RevlogError(_("%s not found in the transaction") | ||
% self.indexfile) | ||||
Chris Mason
|
r2084 | |||
trindex = trinfo[2] | ||||
Mike Edgar
|
r24454 | if trindex is not None: | ||
dataoff = self.start(trindex) | ||||
else: | ||||
# revlog was stripped at start of transaction, use all leftover data | ||||
trindex = len(self) - 1 | ||||
Martin von Zweigbergk
|
r38880 | dataoff = self.end(tiprev) | ||
Chris Mason
|
r2084 | |||
tr.add(self.datafile, dataoff) | ||||
Matt Mackall
|
r8315 | |||
Matt Mackall
|
r8317 | if fp: | ||
fp.flush() | ||||
fp.close() | ||||
Matt Mackall
|
r8315 | |||
Boris Feld
|
r35988 | with self._datafp('w') as df: | ||
Matt Mackall
|
r6750 | for r in self: | ||
Gregory Szorc
|
r32224 | df.write(self._getsegmentforrevs(r, r)[1]) | ||
Benoit Boissinot
|
r6261 | |||
Boris Feld
|
r35989 | with self._indexfp('w') as fp: | ||
self.version &= ~FLAG_INLINE_DATA | ||||
self._inline = False | ||||
io = self._io | ||||
for i in self: | ||||
e = io.packentry(self.index[i], self.node, self.version, i) | ||||
fp.write(e) | ||||
mason@suse.com
|
r2073 | |||
Boris Feld
|
r35989 | # the temp file replace the real index when we exit the context | ||
# manager | ||||
Chris Mason
|
r2084 | |||
Matt Mackall
|
r8650 | tr.replace(self.indexfile, trindex * self._io.size) | ||
self._chunkclear() | ||||
mason@suse.com
|
r2073 | |||
Wojciech Lopata
|
r19625 | def addrevision(self, text, transaction, link, p1, p2, cachedelta=None, | ||
Paul Morelle
|
r35756 | node=None, flags=REVIDX_DEFAULT_FLAGS, deltacomputer=None): | ||
mpm@selenic.com
|
r1083 | """add a revision to the log | ||
text - the revision data to add | ||||
transaction - the transaction object used for rollback | ||||
link - the linkrev data to add | ||||
p1, p2 - the parent nodeids of the revision | ||||
Benoit Boissinot
|
r12012 | cachedelta - an optional precomputed delta | ||
Wojciech Lopata
|
r19625 | node - nodeid of revision; typically node is not specified, and it is | ||
computed by default as hash(text, p1, p2), however subclasses might | ||||
use different hashing method (and override checkhash() in such case) | ||||
Remi Chaintron
|
r30744 | flags - the known flags to set on the revision | ||
Boris Feld
|
r39366 | deltacomputer - an optional deltacomputer instance shared between | ||
Paul Morelle
|
r35756 | multiple calls | ||
mpm@selenic.com
|
r1083 | """ | ||
Durham Goode
|
r19326 | if link == nullrev: | ||
raise RevlogError(_("attempted to add linkrev -1 to %s") | ||||
% self.indexfile) | ||||
Matt Mackall
|
r25459 | |||
Remi Chaintron
|
r30745 | if flags: | ||
node = node or self.hash(text, p1, p2) | ||||
Jun Wu
|
r31750 | rawtext, validatehash = self._processflags(text, flags, 'write') | ||
Remi Chaintron
|
r30745 | |||
# If the flag processor modifies the revision data, ignore any provided | ||||
# cachedelta. | ||||
Jun Wu
|
r31750 | if rawtext != text: | ||
Remi Chaintron
|
r30745 | cachedelta = None | ||
Jun Wu
|
r31750 | if len(rawtext) > _maxentrysize: | ||
Matt Mackall
|
r25459 | raise RevlogError( | ||
_("%s: size of %d bytes exceeds maximum revlog storage of 2GiB") | ||||
Jun Wu
|
r31750 | % (self.indexfile, len(rawtext))) | ||
Matt Mackall
|
r25459 | |||
Jun Wu
|
r31750 | node = node or self.hash(rawtext, p1, p2) | ||
Sune Foldager
|
r14196 | if node in self.nodemap: | ||
Benoit Boissinot
|
r12023 | return node | ||
Remi Chaintron
|
r30745 | if validatehash: | ||
Jun Wu
|
r31750 | self.checkhash(rawtext, node, p1=p1, p2=p2) | ||
Remi Chaintron
|
r30745 | |||
Jun Wu
|
r32240 | return self.addrawrevision(rawtext, transaction, link, p1, p2, node, | ||
Paul Morelle
|
r35756 | flags, cachedelta=cachedelta, | ||
deltacomputer=deltacomputer) | ||||
Jun Wu
|
r32240 | |||
def addrawrevision(self, rawtext, transaction, link, p1, p2, node, flags, | ||||
Paul Morelle
|
r35756 | cachedelta=None, deltacomputer=None): | ||
Jun Wu
|
r32240 | """add a raw revision with known flags, node and parents | ||
useful when reusing a revision not stored in this revlog (ex: received | ||||
over wire, or read from an external bundle). | ||||
""" | ||||
Matt Mackall
|
r4981 | dfh = None | ||
Matt Mackall
|
r4982 | if not self._inline: | ||
Boris Feld
|
r35985 | dfh = self._datafp("a+") | ||
Boris Feld
|
r35986 | ifh = self._indexfp("a+") | ||
Benoit Boissinot
|
r6261 | try: | ||
Jun Wu
|
r31750 | return self._addrevision(node, rawtext, transaction, link, p1, p2, | ||
Paul Morelle
|
r35756 | flags, cachedelta, ifh, dfh, | ||
deltacomputer=deltacomputer) | ||||
Benoit Boissinot
|
r6261 | finally: | ||
if dfh: | ||||
dfh.close() | ||||
ifh.close() | ||||
Alexis S. L. Carvalho
|
r3390 | |||
Gregory Szorc
|
r30795 | def compress(self, data): | ||
"""Generate a possibly-compressed representation of data.""" | ||||
if not data: | ||||
return '', data | ||||
compressed = self._compressor.compress(data) | ||||
if compressed: | ||||
# The revlog compressor added the header in the returned data. | ||||
return '', compressed | ||||
Yuya Nishihara
|
r31643 | if data[0:1] == '\0': | ||
Gregory Szorc
|
r30795 | return '', data | ||
return 'u', data | ||||
Bryan O'Sullivan
|
r17128 | |||
Gregory Szorc
|
r30793 | def decompress(self, data): | ||
"""Decompress a revlog chunk. | ||||
The chunk is expected to begin with a header identifying the | ||||
format type so it can be routed to an appropriate decompressor. | ||||
""" | ||||
if not data: | ||||
return data | ||||
Gregory Szorc
|
r30817 | |||
# Revlogs are read much more frequently than they are written and many | ||||
# chunks only take microseconds to decompress, so performance is | ||||
# important here. | ||||
# | ||||
# We can make a few assumptions about revlogs: | ||||
# | ||||
# 1) the majority of chunks will be compressed (as opposed to inline | ||||
# raw data). | ||||
# 2) decompressing *any* data will likely by at least 10x slower than | ||||
# returning raw inline data. | ||||
# 3) we want to prioritize common and officially supported compression | ||||
# engines | ||||
# | ||||
# It follows that we want to optimize for "decompress compressed data | ||||
# when encoded with common and officially supported compression engines" | ||||
# case over "raw data" and "data encoded by less common or non-official | ||||
# compression engines." That is why we have the inline lookup first | ||||
# followed by the compengines lookup. | ||||
# | ||||
# According to `hg perfrevlogchunks`, this is ~0.5% faster for zlib | ||||
# compressed chunks. And this matters for changelog and manifest reads. | ||||
Augie Fackler
|
r31356 | t = data[0:1] | ||
Gregory Szorc
|
r30817 | |||
Gregory Szorc
|
r30793 | if t == 'x': | ||
try: | ||||
Gregory Szorc
|
r30817 | return _zlibdecompress(data) | ||
Gregory Szorc
|
r30793 | except zlib.error as e: | ||
Pulkit Goyal
|
r36718 | raise RevlogError(_('revlog decompress error: %s') % | ||
Yuya Nishihara
|
r37102 | stringutil.forcebytestr(e)) | ||
Gregory Szorc
|
r30817 | # '\0' is more common than 'u' so it goes first. | ||
elif t == '\0': | ||||
return data | ||||
elif t == 'u': | ||||
Gregory Szorc
|
r30793 | return util.buffer(data, 1) | ||
Gregory Szorc
|
r30817 | |||
try: | ||||
compressor = self._decompressors[t] | ||||
except KeyError: | ||||
try: | ||||
engine = util.compengines.forrevlogheader(t) | ||||
compressor = engine.revlogcompressor() | ||||
self._decompressors[t] = compressor | ||||
except KeyError: | ||||
raise RevlogError(_('unknown compression type %r') % t) | ||||
return compressor.decompress(data) | ||||
Gregory Szorc
|
r30793 | |||
Jun Wu
|
r31755 | def _addrevision(self, node, rawtext, transaction, link, p1, p2, flags, | ||
Paul Morelle
|
r35756 | cachedelta, ifh, dfh, alwayscache=False, | ||
deltacomputer=None): | ||||
Sune Foldager
|
r14292 | """internal function to add revisions to the log | ||
Benoit Boissinot
|
r12623 | |||
Sune Foldager
|
r14292 | see addrevision for argument descriptions. | ||
Jun Wu
|
r31755 | |||
note: "addrevision" takes non-raw text, "_addrevision" takes raw text. | ||||
Paul Morelle
|
r35756 | if "deltacomputer" is not provided or None, a defaultdeltacomputer will | ||
be used. | ||||
Sune Foldager
|
r14292 | invariants: | ||
Jun Wu
|
r31755 | - rawtext is optional (can be None); if not set, cachedelta must be set. | ||
Mads Kiilerich
|
r17424 | if both are set, they must correspond to each other. | ||
Sune Foldager
|
r14292 | """ | ||
Martin von Zweigbergk
|
r33939 | if node == nullid: | ||
raise RevlogError(_("%s: attempt to add null revision") % | ||||
(self.indexfile)) | ||||
Yuya Nishihara
|
r37467 | if node == wdirid or node in wdirfilenodeids: | ||
Martin von Zweigbergk
|
r34029 | raise RevlogError(_("%s: attempt to add wdir revision") % | ||
(self.indexfile)) | ||||
Paul Morelle
|
r35653 | if self._inline: | ||
fh = ifh | ||||
else: | ||||
fh = dfh | ||||
Jun Wu
|
r31755 | btext = [rawtext] | ||
Benoit Boissinot
|
r12623 | |||
Matt Mackall
|
r6750 | curr = len(self) | ||
Matt Mackall
|
r4981 | prev = curr - 1 | ||
offset = self.end(prev) | ||||
Matt Mackall
|
r12889 | p1r, p2r = self.rev(p1), self.rev(p2) | ||
mpm@selenic.com
|
r0 | |||
Durham Goode
|
r26116 | # full versions are inserted when the needed deltas | ||
# become comparable to the uncompressed text | ||||
Jun Wu
|
r31755 | if rawtext is None: | ||
Jun Wu
|
r36766 | # need rawtext size, before changed by flag processors, which is | ||
# the non-raw size. use revlog explicitly to avoid filelog's extra | ||||
# logic that might remove metadata size. | ||||
textlen = mdiff.patchedsize(revlog.size(self, cachedelta[0]), | ||||
Durham Goode
|
r26116 | cachedelta[1]) | ||
else: | ||||
Jun Wu
|
r31755 | textlen = len(rawtext) | ||
Durham Goode
|
r26116 | |||
Paul Morelle
|
r35756 | if deltacomputer is None: | ||
Boris Feld
|
r39366 | deltacomputer = deltautil.deltacomputer(self) | ||
Paul Morelle
|
r35756 | |||
Paul Morelle
|
r35755 | revinfo = _revisioninfo(node, p1, p2, btext, textlen, cachedelta, flags) | ||
Jun Wu
|
r36765 | |||
Boris Feld
|
r39368 | deltainfo = deltacomputer.finddeltainfo(revinfo, fh) | ||
Paul Morelle
|
r35652 | |||
Boris Feld
|
r39369 | e = (offset_type(offset, flags), deltainfo.deltalen, textlen, | ||
deltainfo.base, link, p1r, p2r, node) | ||||
Martin von Zweigbergk
|
r38886 | self.index.append(e) | ||
Matt Mackall
|
r4981 | self.nodemap[node] = curr | ||
Matt Mackall
|
r4977 | |||
Alexis S. L. Carvalho
|
r5338 | entry = self._io.packentry(e, self.node, self.version, curr) | ||
Boris Feld
|
r39369 | self._writeentry(transaction, ifh, dfh, entry, deltainfo.data, | ||
link, offset) | ||||
rawtext = btext[0] | ||||
Durham Goode
|
r20217 | |||
Jun Wu
|
r31755 | if alwayscache and rawtext is None: | ||
Boris Feld
|
r39228 | rawtext = deltacomputer.buildtext(revinfo, fh) | ||
Gregory Szorc
|
r26243 | |||
Augie Fackler
|
r35863 | if type(rawtext) == bytes: # only accept immutable objects | ||
Jun Wu
|
r31755 | self._cache = (node, curr, rawtext) | ||
Boris Feld
|
r39369 | self._chainbasecache[curr] = deltainfo.chainbase | ||
Durham Goode
|
r20217 | return node | ||
def _writeentry(self, transaction, ifh, dfh, entry, data, link, offset): | ||||
Gregory Szorc
|
r27430 | # Files opened in a+ mode have inconsistent behavior on various | ||
# platforms. Windows requires that a file positioning call be made | ||||
# when the file handle transitions between reads and writes. See | ||||
# 3686fa2b8eee and the mixedfilemodewrapper in windows.py. On other | ||||
# platforms, Python or the platform itself can be buggy. Some versions | ||||
# of Solaris have been observed to not append at the end of the file | ||||
# if the file was seeked to before the end. See issue4943 for more. | ||||
# | ||||
# We work around this issue by inserting a seek() before writing. | ||||
# Note: This is likely not necessary on Python 3. | ||||
ifh.seek(0, os.SEEK_END) | ||||
Martin von Zweigbergk
|
r27441 | if dfh: | ||
Gregory Szorc
|
r27430 | dfh.seek(0, os.SEEK_END) | ||
Durham Goode
|
r20217 | curr = len(self) - 1 | ||
Matt Mackall
|
r4982 | if not self._inline: | ||
mason@suse.com
|
r2073 | transaction.add(self.datafile, offset) | ||
Matt Mackall
|
r4981 | transaction.add(self.indexfile, curr * len(entry)) | ||
mason@suse.com
|
r2073 | if data[0]: | ||
Alexis S. L. Carvalho
|
r3390 | dfh.write(data[0]) | ||
dfh.write(data[1]) | ||||
Matt Mackall
|
r4981 | ifh.write(entry) | ||
mason@suse.com
|
r2073 | else: | ||
Matt Mackall
|
r4996 | offset += curr * self._io.size | ||
Patrick Mezard
|
r5324 | transaction.add(self.indexfile, offset, curr) | ||
Matt Mackall
|
r4981 | ifh.write(entry) | ||
Alexis S. L. Carvalho
|
r3390 | ifh.write(data[0]) | ||
ifh.write(data[1]) | ||||
Boris Feld
|
r35992 | self._enforceinlinesize(transaction, ifh) | ||
mason@suse.com
|
r2073 | |||
Durham Goode
|
r34292 | def addgroup(self, deltas, linkmapper, transaction, addrevisioncb=None): | ||
mpm@selenic.com
|
r1083 | """ | ||
add a delta group | ||||
mpm@selenic.com
|
r46 | |||
mpm@selenic.com
|
r1083 | given a set of deltas, add them to the revision log. the | ||
first delta is against its parent, which should be in our | ||||
log, the rest are against the previous delta. | ||||
Gregory Szorc
|
r25822 | |||
If ``addrevisioncb`` is defined, it will be called with arguments of | ||||
this revlog and the node that was added. | ||||
mpm@selenic.com
|
r1083 | """ | ||
Martin von Zweigbergk
|
r32868 | nodes = [] | ||
mpm@selenic.com
|
r515 | |||
Benoit Boissinot
|
r12624 | r = len(self) | ||
end = 0 | ||||
mpm@selenic.com
|
r46 | if r: | ||
Benoit Boissinot
|
r12624 | end = self.end(r - 1) | ||
Boris Feld
|
r35986 | ifh = self._indexfp("a+") | ||
Matt Mackall
|
r4996 | isize = r * self._io.size | ||
Matt Mackall
|
r4982 | if self._inline: | ||
Matt Mackall
|
r4996 | transaction.add(self.indexfile, end + isize, r) | ||
mason@suse.com
|
r2073 | dfh = None | ||
else: | ||||
Matt Mackall
|
r4996 | transaction.add(self.indexfile, isize, r) | ||
mason@suse.com
|
r2073 | transaction.add(self.datafile, end) | ||
Boris Feld
|
r35985 | dfh = self._datafp("a+") | ||
Mike Edgar
|
r24255 | def flush(): | ||
if dfh: | ||||
dfh.flush() | ||||
ifh.flush() | ||||
Benoit Boissinot
|
r6261 | try: | ||
Boris Feld
|
r39366 | deltacomputer = deltautil.deltacomputer(self) | ||
Benoit Boissinot
|
r6261 | # loop through our set of deltas | ||
Durham Goode
|
r34147 | for data in deltas: | ||
Durham Goode
|
r34292 | node, p1, p2, linknode, deltabase, delta, flags = data | ||
link = linkmapper(linknode) | ||||
Durham Goode
|
r34147 | flags = flags or REVIDX_DEFAULT_FLAGS | ||
Matt Mackall
|
r12336 | |||
Martin von Zweigbergk
|
r32868 | nodes.append(node) | ||
Pierre-Yves David
|
r15890 | |||
Sune Foldager
|
r14196 | if node in self.nodemap: | ||
Benoit Boissinot
|
r6261 | # this can happen if two branches make the same change | ||
continue | ||||
mpm@selenic.com
|
r192 | |||
Benoit Boissinot
|
r6261 | for p in (p1, p2): | ||
Brodie Rao
|
r16686 | if p not in self.nodemap: | ||
Sune Foldager
|
r14196 | raise LookupError(p, self.indexfile, | ||
_('unknown parent')) | ||||
mpm@selenic.com
|
r46 | |||
Benoit Boissinot
|
r14141 | if deltabase not in self.nodemap: | ||
raise LookupError(deltabase, self.indexfile, | ||||
_('unknown delta base')) | ||||
mpm@selenic.com
|
r46 | |||
Benoit Boissinot
|
r14141 | baserev = self.rev(deltabase) | ||
Mike Edgar
|
r24120 | |||
if baserev != nullrev and self.iscensored(baserev): | ||||
# if base is censored, delta must be full replacement in a | ||||
# single patch operation | ||||
hlen = struct.calcsize(">lll") | ||||
oldlen = self.rawsize(baserev) | ||||
newlen = len(delta) - hlen | ||||
if delta[:hlen] != mdiff.replacediffheader(oldlen, newlen): | ||||
raise error.CensoredBaseError(self.indexfile, | ||||
self.node(baserev)) | ||||
Mike Edgar
|
r27433 | if not flags and self._peek_iscensored(baserev, delta, flush): | ||
Mike Edgar
|
r24255 | flags |= REVIDX_ISCENSORED | ||
Gregory Szorc
|
r26243 | # We assume consumers of addrevisioncb will want to retrieve | ||
# the added revision, which will require a call to | ||||
# revision(). revision() will fast path if there is a cache | ||||
# hit. So, we tell _addrevision() to always cache in this case. | ||||
Remi Chaintron
|
r30743 | # We're only using addgroup() in the context of changegroup | ||
# generation so the revision data can always be handled as raw | ||||
# by the flagprocessor. | ||||
Durham Goode
|
r34146 | self._addrevision(node, None, transaction, link, | ||
p1, p2, flags, (baserev, delta), | ||||
ifh, dfh, | ||||
Paul Morelle
|
r35756 | alwayscache=bool(addrevisioncb), | ||
deltacomputer=deltacomputer) | ||||
Gregory Szorc
|
r25822 | |||
if addrevisioncb: | ||||
Durham Goode
|
r34146 | addrevisioncb(self, node) | ||
Gregory Szorc
|
r25822 | |||
Benoit Boissinot
|
r12624 | if not dfh and not self._inline: | ||
# addrevision switched from inline to conventional | ||||
# reopen the index | ||||
Dan Villiom Podlaski Christiansen
|
r13400 | ifh.close() | ||
Boris Feld
|
r35985 | dfh = self._datafp("a+") | ||
Boris Feld
|
r35986 | ifh = self._indexfp("a+") | ||
Benoit Boissinot
|
r6261 | finally: | ||
if dfh: | ||||
dfh.close() | ||||
ifh.close() | ||||
mpm@selenic.com
|
r46 | |||
Martin von Zweigbergk
|
r32868 | return nodes | ||
Matt Mackall
|
r1493 | |||
Mike Edgar
|
r24118 | def iscensored(self, rev): | ||
"""Check if a file revision is censored.""" | ||||
Gregory Szorc
|
r37461 | if not self._censorable: | ||
return False | ||||
return self.flags(rev) & REVIDX_ISCENSORED | ||||
Mike Edgar
|
r24118 | |||
Mike Edgar
|
r24255 | def _peek_iscensored(self, baserev, delta, flush): | ||
"""Quickly check if a delta produces a censored revision.""" | ||||
Gregory Szorc
|
r37461 | if not self._censorable: | ||
return False | ||||
# Fragile heuristic: unless new file meta keys are added alphabetically | ||||
# preceding "censored", all censored revisions are prefixed by | ||||
# "\1\ncensored:". A delta producing such a censored revision must be a | ||||
# full-replacement delta, so we inspect the first and only patch in the | ||||
# delta for this prefix. | ||||
hlen = struct.calcsize(">lll") | ||||
if len(delta) <= hlen: | ||||
return False | ||||
oldlen = self.rawsize(baserev) | ||||
newlen = len(delta) - hlen | ||||
if delta[:hlen] != mdiff.replacediffheader(oldlen, newlen): | ||||
return False | ||||
add = "\1\ncensored:" | ||||
addlen = len(add) | ||||
return newlen >= addlen and delta[hlen:hlen + addlen] == add | ||||
Mike Edgar
|
r24255 | |||
Durham Goode
|
r20074 | def getstrippoint(self, minlink): | ||
"""find the minimum rev that must be stripped to strip the linkrev | ||||
Returns a tuple containing the minimum rev and a set of all revs that | ||||
have linkrevs that will be broken by this strip. | ||||
""" | ||||
brokenrevs = set() | ||||
strippoint = len(self) | ||||
heads = {} | ||||
futurelargelinkrevs = set() | ||||
for head in self.headrevs(): | ||||
headlinkrev = self.linkrev(head) | ||||
heads[head] = headlinkrev | ||||
if headlinkrev >= minlink: | ||||
futurelargelinkrevs.add(headlinkrev) | ||||
# This algorithm involves walking down the rev graph, starting at the | ||||
# heads. Since the revs are topologically sorted according to linkrev, | ||||
# once all head linkrevs are below the minlink, we know there are | ||||
# no more revs that could have a linkrev greater than minlink. | ||||
# So we can stop walking. | ||||
while futurelargelinkrevs: | ||||
strippoint -= 1 | ||||
linkrev = heads.pop(strippoint) | ||||
if linkrev < minlink: | ||||
brokenrevs.add(strippoint) | ||||
else: | ||||
futurelargelinkrevs.remove(linkrev) | ||||
for p in self.parentrevs(strippoint): | ||||
if p != nullrev: | ||||
plinkrev = self.linkrev(p) | ||||
heads[p] = plinkrev | ||||
if plinkrev >= minlink: | ||||
futurelargelinkrevs.add(plinkrev) | ||||
return strippoint, brokenrevs | ||||
Henrik Stuart
|
r8073 | def strip(self, minlink, transaction): | ||
Alexis S. L. Carvalho
|
r5910 | """truncate the revlog on the first revision with a linkrev >= minlink | ||
This function is called when we're stripping revision minlink and | ||||
its descendants from the repository. | ||||
We have to remove all revisions with linkrev >= minlink, because | ||||
the equivalent changelog revisions will be renumbered after the | ||||
strip. | ||||
So we truncate the revlog on the first of these revisions, and | ||||
trust that the caller has saved the revisions that shouldn't be | ||||
Steven Brown
|
r15827 | removed and that it'll re-add them after this truncation. | ||
Alexis S. L. Carvalho
|
r5910 | """ | ||
Matt Mackall
|
r6750 | if len(self) == 0: | ||
mason@suse.com
|
r1535 | return | ||
Durham Goode
|
r20074 | rev, _ = self.getstrippoint(minlink) | ||
if rev == len(self): | ||||
Alexis S. L. Carvalho
|
r5909 | return | ||
mason@suse.com
|
r1535 | |||
# first truncate the files on disk | ||||
end = self.start(rev) | ||||
Matt Mackall
|
r4982 | if not self._inline: | ||
Henrik Stuart
|
r8073 | transaction.add(self.datafile, end) | ||
Matt Mackall
|
r4977 | end = rev * self._io.size | ||
mason@suse.com
|
r2073 | else: | ||
Matt Mackall
|
r4977 | end += rev * self._io.size | ||
mason@suse.com
|
r2072 | |||
Henrik Stuart
|
r8073 | transaction.add(self.indexfile, end) | ||
mason@suse.com
|
r1535 | |||
# then reset internal state in memory to forget those revisions | ||||
Matt Mackall
|
r4984 | self._cache = None | ||
Siddharth Agarwal
|
r23306 | self._chaininfocache = {} | ||
Matt Mackall
|
r8650 | self._chunkclear() | ||
Gregory Szorc
|
r38806 | for x in pycompat.xrange(rev, len(self)): | ||
mason@suse.com
|
r2072 | del self.nodemap[self.node(x)] | ||
mason@suse.com
|
r1535 | |||
Matt Mackall
|
r4979 | del self.index[rev:-1] | ||
Joerg Sonnenberger
|
r37512 | self._nodepos = None | ||
mason@suse.com
|
r1535 | |||
Matt Mackall
|
r1493 | def checksize(self): | ||
expected = 0 | ||||
Matt Mackall
|
r6750 | if len(self): | ||
expected = max(0, self.end(len(self) - 1)) | ||||
Matt Mackall
|
r1667 | |||
Matt Mackall
|
r1494 | try: | ||
Boris Feld
|
r35990 | with self._datafp() as f: | ||
f.seek(0, 2) | ||||
actual = f.tell() | ||||
Matt Mackall
|
r1667 | dd = actual - expected | ||
Gregory Szorc
|
r25660 | except IOError as inst: | ||
Matt Mackall
|
r1667 | if inst.errno != errno.ENOENT: | ||
raise | ||||
dd = 0 | ||||
try: | ||||
f = self.opener(self.indexfile) | ||||
f.seek(0, 2) | ||||
actual = f.tell() | ||||
Dan Villiom Podlaski Christiansen
|
r13400 | f.close() | ||
Matt Mackall
|
r4977 | s = self._io.size | ||
Alejandro Santos
|
r9029 | i = max(0, actual // s) | ||
Matt Mackall
|
r1667 | di = actual - (i * s) | ||
Matt Mackall
|
r4982 | if self._inline: | ||
mason@suse.com
|
r2073 | databytes = 0 | ||
Matt Mackall
|
r6750 | for r in self: | ||
Matt Mackall
|
r5312 | databytes += max(0, self.length(r)) | ||
mason@suse.com
|
r2073 | dd = 0 | ||
Matt Mackall
|
r6750 | di = actual - len(self) * s - databytes | ||
Gregory Szorc
|
r25660 | except IOError as inst: | ||
Matt Mackall
|
r1667 | if inst.errno != errno.ENOENT: | ||
raise | ||||
di = 0 | ||||
return (dd, di) | ||||
Adrian Buehlmann
|
r6891 | |||
def files(self): | ||||
Matt Mackall
|
r10282 | res = [self.indexfile] | ||
Adrian Buehlmann
|
r6891 | if not self._inline: | ||
res.append(self.datafile) | ||||
return res | ||||
Gregory Szorc
|
r30778 | |||
Gregory Szorc
|
r39267 | def emitrevisiondeltas(self, requests): | ||
frev = self.rev | ||||
prevrev = None | ||||
for request in requests: | ||||
node = request.node | ||||
rev = frev(node) | ||||
if prevrev is None: | ||||
prevrev = self.index[rev][5] | ||||
# Requesting a full revision. | ||||
if request.basenode == nullid: | ||||
baserev = nullrev | ||||
# Requesting an explicit revision. | ||||
elif request.basenode is not None: | ||||
baserev = frev(request.basenode) | ||||
# Allowing us to choose. | ||||
else: | ||||
p1rev, p2rev = self.parentrevs(rev) | ||||
deltaparentrev = self.deltaparent(rev) | ||||
# Avoid sending full revisions when delta parent is null. Pick | ||||
# prev in that case. It's tempting to pick p1 in this case, as | ||||
# p1 will be smaller in the common case. However, computing a | ||||
# delta against p1 may require resolving the raw text of p1, | ||||
# which could be expensive. The revlog caches should have prev | ||||
# cached, meaning less CPU for delta generation. There is | ||||
# likely room to add a flag and/or config option to control this | ||||
# behavior. | ||||
Gregory Szorc
|
r39268 | if deltaparentrev == nullrev and self._storedeltachains: | ||
Gregory Szorc
|
r39267 | baserev = prevrev | ||
# Revlog is configured to use full snapshot for a reason. | ||||
# Stick to full snapshot. | ||||
elif deltaparentrev == nullrev: | ||||
baserev = nullrev | ||||
# Pick previous when we can't be sure the base is available | ||||
# on consumer. | ||||
elif deltaparentrev not in (p1rev, p2rev, prevrev): | ||||
baserev = prevrev | ||||
else: | ||||
baserev = deltaparentrev | ||||
if baserev != nullrev and not self.candelta(baserev, rev): | ||||
baserev = nullrev | ||||
revision = None | ||||
delta = None | ||||
baserevisionsize = None | ||||
if self.iscensored(baserev) or self.iscensored(rev): | ||||
try: | ||||
revision = self.revision(node, raw=True) | ||||
except error.CensoredNodeError as e: | ||||
revision = e.tombstone | ||||
if baserev != nullrev: | ||||
baserevisionsize = self.rawsize(baserev) | ||||
elif baserev == nullrev: | ||||
revision = self.revision(node, raw=True) | ||||
else: | ||||
delta = self.revdiff(baserev, rev) | ||||
extraflags = REVIDX_ELLIPSIS if request.ellipsis else 0 | ||||
yield revlogrevisiondelta( | ||||
node=node, | ||||
p1node=request.p1node, | ||||
p2node=request.p2node, | ||||
linknode=request.linknode, | ||||
basenode=self.node(baserev), | ||||
flags=self.flags(rev) | extraflags, | ||||
baserevisionsize=baserevisionsize, | ||||
revision=revision, | ||||
delta=delta) | ||||
prevrev = rev | ||||
Gregory Szorc
|
r30778 | DELTAREUSEALWAYS = 'always' | ||
DELTAREUSESAMEREVS = 'samerevs' | ||||
DELTAREUSENEVER = 'never' | ||||
Boris Feld
|
r35346 | DELTAREUSEFULLADD = 'fulladd' | ||
DELTAREUSEALL = {'always', 'samerevs', 'never', 'fulladd'} | ||||
Gregory Szorc
|
r30778 | |||
def clone(self, tr, destrevlog, addrevisioncb=None, | ||||
Boris Feld
|
r38759 | deltareuse=DELTAREUSESAMEREVS, deltabothparents=None): | ||
Gregory Szorc
|
r30778 | """Copy this revlog to another, possibly with format changes. | ||
The destination revlog will contain the same revisions and nodes. | ||||
However, it may not be bit-for-bit identical due to e.g. delta encoding | ||||
differences. | ||||
The ``deltareuse`` argument control how deltas from the existing revlog | ||||
are preserved in the destination revlog. The argument can have the | ||||
following values: | ||||
DELTAREUSEALWAYS | ||||
Deltas will always be reused (if possible), even if the destination | ||||
revlog would not select the same revisions for the delta. This is the | ||||
fastest mode of operation. | ||||
DELTAREUSESAMEREVS | ||||
Deltas will be reused if the destination revlog would pick the same | ||||
revisions for the delta. This mode strikes a balance between speed | ||||
and optimization. | ||||
DELTAREUSENEVER | ||||
Deltas will never be reused. This is the slowest mode of execution. | ||||
This mode can be used to recompute deltas (e.g. if the diff/delta | ||||
algorithm changes). | ||||
Delta computation can be slow, so the choice of delta reuse policy can | ||||
significantly affect run time. | ||||
The default policy (``DELTAREUSESAMEREVS``) strikes a balance between | ||||
two extremes. Deltas will be reused if they are appropriate. But if the | ||||
delta could choose a better revision, it will do so. This means if you | ||||
are converting a non-generaldelta revlog to a generaldelta revlog, | ||||
deltas will be recomputed if the delta's parent isn't a parent of the | ||||
revision. | ||||
Boris Feld
|
r38759 | In addition to the delta policy, the ``deltabothparents`` argument | ||
Gregory Szorc
|
r30778 | controls whether to compute deltas against both parents for merges. | ||
By default, the current default is used. | ||||
""" | ||||
if deltareuse not in self.DELTAREUSEALL: | ||||
raise ValueError(_('value for deltareuse invalid: %s') % deltareuse) | ||||
if len(destrevlog): | ||||
raise ValueError(_('destination revlog is not empty')) | ||||
if getattr(self, 'filteredrevs', None): | ||||
raise ValueError(_('source revlog has filtered revisions')) | ||||
if getattr(destrevlog, 'filteredrevs', None): | ||||
raise ValueError(_('destination revlog has filtered revisions')) | ||||
# lazydeltabase controls whether to reuse a cached delta, if possible. | ||||
oldlazydeltabase = destrevlog._lazydeltabase | ||||
Boris Feld
|
r38759 | oldamd = destrevlog._deltabothparents | ||
Gregory Szorc
|
r30778 | |||
try: | ||||
if deltareuse == self.DELTAREUSEALWAYS: | ||||
destrevlog._lazydeltabase = True | ||||
elif deltareuse == self.DELTAREUSESAMEREVS: | ||||
destrevlog._lazydeltabase = False | ||||
Boris Feld
|
r38759 | destrevlog._deltabothparents = deltabothparents or oldamd | ||
Gregory Szorc
|
r30778 | |||
populatecachedelta = deltareuse in (self.DELTAREUSEALWAYS, | ||||
self.DELTAREUSESAMEREVS) | ||||
Boris Feld
|
r39366 | deltacomputer = deltautil.deltacomputer(destrevlog) | ||
Gregory Szorc
|
r30778 | index = self.index | ||
for rev in self: | ||||
entry = index[rev] | ||||
# Some classes override linkrev to take filtered revs into | ||||
# account. Use raw entry from index. | ||||
flags = entry[0] & 0xffff | ||||
linkrev = entry[4] | ||||
p1 = index[entry[5]][7] | ||||
p2 = index[entry[6]][7] | ||||
node = entry[7] | ||||
# (Possibly) reuse the delta from the revlog if allowed and | ||||
# the revlog chunk is a delta. | ||||
cachedelta = None | ||||
Jun Wu
|
r31754 | rawtext = None | ||
Gregory Szorc
|
r30778 | if populatecachedelta: | ||
dp = self.deltaparent(rev) | ||||
if dp != nullrev: | ||||
Pulkit Goyal
|
r36739 | cachedelta = (dp, bytes(self._chunk(rev))) | ||
Gregory Szorc
|
r30778 | |||
if not cachedelta: | ||||
Jun Wu
|
r31754 | rawtext = self.revision(rev, raw=True) | ||
Gregory Szorc
|
r30778 | |||
Boris Feld
|
r35346 | |||
if deltareuse == self.DELTAREUSEFULLADD: | ||||
destrevlog.addrevision(rawtext, tr, linkrev, p1, p2, | ||||
cachedelta=cachedelta, | ||||
Paul Morelle
|
r35756 | node=node, flags=flags, | ||
deltacomputer=deltacomputer) | ||||
Boris Feld
|
r35346 | else: | ||
ifh = destrevlog.opener(destrevlog.indexfile, 'a+', | ||||
checkambig=False) | ||||
dfh = None | ||||
if not destrevlog._inline: | ||||
dfh = destrevlog.opener(destrevlog.datafile, 'a+') | ||||
try: | ||||
destrevlog._addrevision(node, rawtext, tr, linkrev, p1, | ||||
Paul Morelle
|
r35756 | p2, flags, cachedelta, ifh, dfh, | ||
deltacomputer=deltacomputer) | ||||
Boris Feld
|
r35346 | finally: | ||
if dfh: | ||||
dfh.close() | ||||
ifh.close() | ||||
Gregory Szorc
|
r30778 | |||
if addrevisioncb: | ||||
addrevisioncb(self, rev, node) | ||||
finally: | ||||
destrevlog._lazydeltabase = oldlazydeltabase | ||||
Boris Feld
|
r38759 | destrevlog._deltabothparents = oldamd | ||