revlog.py
2671 lines
| 96.5 KiB
| text/x-python
|
PythonLexer
/ mercurial / revlog.py
|
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 | ||||
|
r10263 | # GNU General Public License version 2 or any later version. | ||
|
r0 | |||
|
r8227 | """Storage back-end for Mercurial. | ||
This provides efficient delta storage with O(1) retrieve and append | ||||
and O(changes) merge between branches. | ||||
""" | ||||
|
r27361 | from __future__ import absolute_import | ||
|
r25113 | import collections | ||
|
r35991 | import contextlib | ||
|
r27361 | import errno | ||
|
r42767 | import io | ||
|
r27430 | import os | ||
|
r27361 | import struct | ||
import zlib | ||||
# import stuff from node for others to import from revlog | ||||
from .node import ( | ||||
bin, | ||||
hex, | ||||
|
r39227 | nullhex, | ||
|
r27361 | nullid, | ||
nullrev, | ||||
|
r39908 | short, | ||
|
r37467 | wdirfilenodeids, | ||
|
r32684 | wdirhex, | ||
|
r32657 | wdirid, | ||
|
r32402 | wdirrev, | ||
|
r27361 | ) | ||
from .i18n import _ | ||||
|
r39365 | from .revlogutils.constants import ( | ||
FLAG_GENERALDELTA, | ||||
FLAG_INLINE_DATA, | ||||
REVLOGV0, | ||||
REVLOGV1, | ||||
REVLOGV1_FLAGS, | ||||
REVLOGV2, | ||||
REVLOGV2_FLAGS, | ||||
REVLOG_DEFAULT_FLAGS, | ||||
REVLOG_DEFAULT_FORMAT, | ||||
REVLOG_DEFAULT_VERSION, | ||||
) | ||||
r42954 | from .revlogutils.flagutil import ( | |||
REVIDX_DEFAULT_FLAGS, | ||||
REVIDX_ELLIPSIS, | ||||
REVIDX_EXTSTORED, | ||||
REVIDX_FLAGS_ORDER, | ||||
REVIDX_ISCENSORED, | ||||
REVIDX_RAWTEXT_CHANGING_FLAGS, | ||||
) | ||||
|
r35656 | from .thirdparty import ( | ||
attr, | ||||
) | ||||
|
r27361 | from . import ( | ||
ancestor, | ||||
|
r39898 | dagop, | ||
|
r27361 | error, | ||
mdiff, | ||||
|
r32372 | policy, | ||
|
r31574 | pycompat, | ||
|
r27361 | templatefilters, | ||
util, | ||||
) | ||||
|
r43078 | from .interfaces import ( | ||
repository, | ||||
|
r43079 | util as interfaceutil, | ||
|
r43078 | ) | ||
|
r39366 | from .revlogutils import ( | ||
deltas as deltautil, | ||||
r42955 | flagutil, | |||
|
r39366 | ) | ||
|
r37102 | from .utils import ( | ||
|
r39913 | storageutil, | ||
|
r37102 | stringutil, | ||
) | ||||
|
r36 | |||
|
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_RAWTEXT_CHANGING_FLAGS | ||||
|
r32372 | parsers = policy.importmod(r'parsers') | ||
|
r42652 | rustancestor = policy.importrust(r'ancestor') | ||
rustdagop = policy.importrust(r'dagop') | ||||
|
r32372 | |||
|
r30817 | # Aliased for performance. | ||
_zlibdecompress = zlib.decompress | ||||
|
r5007 | |||
|
r10916 | # max size of revlog with inline data | ||
_maxinline = 131072 | ||||
|
r13253 | _chunksize = 1048576 | ||
|
r10913 | |||
|
r39803 | # Flag processors for REVIDX_ELLIPSIS. | ||
def ellipsisreadprocessor(rl, text): | ||||
r43255 | return text, False, {} | |||
|
r39803 | |||
r43258 | def ellipsiswriteprocessor(rl, text, sidedata): | |||
|
r39803 | return text, False | ||
def ellipsisrawprocessor(rl, text): | ||||
return False | ||||
ellipsisprocessor = ( | ||||
ellipsisreadprocessor, | ||||
ellipsiswriteprocessor, | ||||
ellipsisrawprocessor, | ||||
) | ||||
|
r4987 | def getoffset(q): | ||
return int(q >> 16) | ||||
def gettype(q): | ||||
return int(q & 0xFFFF) | ||||
def offset_type(offset, type): | ||||
r42956 | if (type & ~flagutil.REVIDX_KNOWN_FLAGS) != 0: | |||
|
r30543 | raise ValueError('unknown revlog index flags') | ||
|
r31504 | return int(int(offset) << 16 | type) | ||
|
r4987 | |||
|
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() | ||||
|
r35755 | textlen = attr.ib() | ||
|
r35659 | cachedelta = attr.ib() | ||
flags = attr.ib() | ||||
|
r39267 | @interfaceutil.implementer(repository.irevisiondelta) | ||
|
r39898 | @attr.s(slots=True) | ||
|
r39267 | class revlogrevisiondelta(object): | ||
node = attr.ib() | ||||
p1node = attr.ib() | ||||
p2node = attr.ib() | ||||
basenode = attr.ib() | ||||
flags = attr.ib() | ||||
baserevisionsize = attr.ib() | ||||
revision = attr.ib() | ||||
delta = attr.ib() | ||||
|
r39898 | linknode = attr.ib(default=None) | ||
|
r39267 | |||
|
r39878 | @interfaceutil.implementer(repository.iverifyproblem) | ||
@attr.s(frozen=True) | ||||
class revlogproblem(object): | ||||
warning = attr.ib(default=None) | ||||
error = attr.ib(default=None) | ||||
|
r39908 | node = attr.ib(default=None) | ||
|
r39878 | |||
|
r18585 | # index v0: | ||
# 4 bytes: offset | ||||
# 4 bytes: compressed length | ||||
# 4 bytes: base rev | ||||
# 4 bytes: link rev | ||||
|
r25891 | # 20 bytes: parent 1 nodeid | ||
# 20 bytes: parent 2 nodeid | ||||
# 20 bytes: nodeid | ||||
|
r33392 | indexformatv0 = struct.Struct(">4l20s20s20s") | ||
indexformatv0_pack = indexformatv0.pack | ||||
indexformatv0_unpack = indexformatv0.unpack | ||||
|
r4918 | |||
|
r38885 | class revlogoldindex(list): | ||
def __getitem__(self, i): | ||||
|
r38888 | if i == -1: | ||
|
r38885 | return (0, 0, 0, -1, -1, -1, -1, nullid) | ||
return list.__getitem__(self, i) | ||||
|
r4972 | class revlogoldio(object): | ||
def __init__(self): | ||||
|
r33392 | self.size = indexformatv0.size | ||
|
r4972 | |||
|
r13264 | def parseindex(self, data, inline): | ||
|
r4977 | s = self.size | ||
|
r4972 | index = [] | ||
|
r27637 | nodemap = {nullid: nullrev} | ||
|
r4973 | n = off = 0 | ||
l = len(data) | ||||
while off + s <= l: | ||||
cur = data[off:off + s] | ||||
off += s | ||||
|
r33392 | e = indexformatv0_unpack(cur) | ||
|
r4977 | # transform to revlogv1 format | ||
e2 = (offset_type(e[0], 0), e[1], -1, e[2], e[3], | ||||
|
r5544 | nodemap.get(e[4], nullrev), nodemap.get(e[5], nullrev), e[6]) | ||
|
r4977 | index.append(e2) | ||
nodemap[e[6]] = n | ||||
|
r4973 | n += 1 | ||
|
r4972 | |||
|
r38885 | return revlogoldindex(index), nodemap, None | ||
|
r4972 | |||
|
r5338 | def packentry(self, entry, node, version, rev): | ||
|
r10395 | if gettype(entry[0]): | ||
|
r39809 | raise error.RevlogError(_('index entry flags need revlog ' | ||
'version 1')) | ||||
|
r4986 | e2 = (getoffset(entry[0]), entry[1], entry[3], entry[4], | ||
node(entry[5]), node(entry[6]), entry[7]) | ||||
|
r33392 | return indexformatv0_pack(*e2) | ||
|
r4986 | |||
|
r4987 | # index ng: | ||
|
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 | ||||
|
r4987 | # 32 bytes: nodeid | ||
|
r33392 | indexformatng = struct.Struct(">Qiiiiii20s12x") | ||
indexformatng_pack = indexformatng.pack | ||||
versionformat = struct.Struct(">I") | ||||
versionformat_pack = versionformat.pack | ||||
versionformat_unpack = versionformat.unpack | ||||
|
r4987 | |||
|
r25410 | # corresponds to uncompressed length of indexformatng (2 gigs, 4-byte | ||
# signed integer) | ||||
_maxentrysize = 0x7fffffff | ||||
|
r4972 | class revlogio(object): | ||
def __init__(self): | ||||
|
r33392 | self.size = indexformatng.size | ||
|
r4972 | |||
|
r13264 | def parseindex(self, data, inline): | ||
|
r7109 | # call the C implementation to parse the index data | ||
|
r13254 | index, cache = parsers.parse_index2(data, inline) | ||
|
r16414 | return index, getattr(index, 'nodemap', None), cache | ||
|
r4972 | |||
|
r5338 | def packentry(self, entry, node, version, rev): | ||
|
r33392 | p = indexformatng_pack(*entry) | ||
|
r5338 | if rev == 0: | ||
|
r33392 | p = versionformat_pack(version) + p[4:] | ||
|
r4986 | return p | ||
r43265 | class revlog(object): | |||
|
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 | ||||
|
r6912 | information on each revision, including its nodeid (hash), the | ||
|
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. | ||||
|
r29997 | |||
If checkambig, indexfile is opened with checkambig=True at | ||||
writing, to avoid file stat ambiguity. | ||||
|
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. | ||||
|
r37461 | |||
If censorable is True, the revlog can have censored revisions. | ||||
r42662 | ||||
If `upperboundcomp` is not None, this is the expected maximal gain from | ||||
compression for the data content. | ||||
|
r1083 | """ | ||
r43264 | ||||
_flagserrorclass = error.RevlogError | ||||
|
r34297 | def __init__(self, opener, indexfile, datafile=None, checkambig=False, | ||
r42662 | mmaplargeindex=False, censorable=False, | |||
upperboundcomp=None): | ||||
|
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. | ||||
r42662 | ||||
|
r1083 | """ | ||
r42662 | self.upperboundcomp = upperboundcomp | |||
|
r0 | self.indexfile = indexfile | ||
|
r32307 | self.datafile = datafile or (indexfile[:-2] + ".d") | ||
|
r0 | self.opener = opener | ||
|
r29997 | # When True, indexfile is opened with checkambig=True at writing, to | ||
# avoid file stat ambiguity. | ||||
self._checkambig = checkambig | ||||
|
r41239 | self._mmaplargeindex = mmaplargeindex | ||
|
r37461 | self._censorable = censorable | ||
|
r27070 | # 3-tuple of (node, rev, text) for a raw revision. | ||
|
r40088 | self._revisioncache = None | ||
|
r29830 | # Maps rev to chain base rev. | ||
self._chainbasecache = util.lrucachedict(100) | ||||
|
r27070 | # 2-tuple of (offset, data) of raw data from the revlog at an offset. | ||
|
r8316 | self._chunkcache = (0, '') | ||
|
r27070 | # How much data to read and cache into the raw revlog data cache. | ||
|
r20180 | self._chunkcachesize = 65536 | ||
|
r23255 | self._maxchainlen = None | ||
|
r38759 | self._deltabothparents = True | ||
|
r4985 | self.index = [] | ||
|
r27070 | # Mapping of partial identifiers to full nodes. | ||
|
r13258 | self._pcache = {} | ||
|
r27070 | # Mapping of revision integer to full node. | ||
|
r13275 | self._nodecache = {nullid: nullrev} | ||
self._nodepos = None | ||||
|
r30818 | self._compengine = 'zlib' | ||
r42210 | self._compengineopts = {} | |||
r33202 | self._maxdeltachainspan = -1 | |||
|
r34825 | self._withsparseread = False | ||
|
r38739 | self._sparserevlog = False | ||
|
r38651 | self._srdensitythreshold = 0.50 | ||
|
r34882 | self._srmingapsize = 262144 | ||
|
r4985 | |||
|
r39804 | # Make copy of flag processors so each revlog instance can support | ||
# custom flags. | ||||
r42955 | self._flagprocessors = dict(flagutil.flagprocessors) | |||
|
r39804 | |||
|
r40661 | # 2-tuple of file handles being used for active writing. | ||
self._writinghandles = None | ||||
|
r41240 | self._loadindex() | ||
def _loadindex(self): | ||||
|
r34297 | mmapindexthreshold = None | ||
r43295 | opts = self.opener.options | |||
|
r41236 | |||
if 'revlogv2' in opts: | ||||
|
r41241 | newversionflags = REVLOGV2 | FLAG_INLINE_DATA | ||
|
r41236 | elif 'revlogv1' in opts: | ||
|
r41241 | newversionflags = REVLOGV1 | FLAG_INLINE_DATA | ||
|
r41236 | if 'generaldelta' in opts: | ||
|
r41241 | newversionflags |= FLAG_GENERALDELTA | ||
r43295 | elif 'revlogv0' in self.opener.options: | |||
|
r41355 | newversionflags = REVLOGV0 | ||
|
r41236 | else: | ||
|
r41241 | newversionflags = REVLOG_DEFAULT_VERSION | ||
|
r41236 | |||
if 'chunkcachesize' in opts: | ||||
self._chunkcachesize = opts['chunkcachesize'] | ||||
if 'maxchainlen' in opts: | ||||
self._maxchainlen = opts['maxchainlen'] | ||||
if 'deltabothparents' in opts: | ||||
self._deltabothparents = opts['deltabothparents'] | ||||
r41985 | self._lazydelta = bool(opts.get('lazydelta', True)) | |||
self._lazydeltabase = False | ||||
if self._lazydelta: | ||||
self._lazydeltabase = bool(opts.get('lazydeltabase', False)) | ||||
|
r41236 | if 'compengine' in opts: | ||
self._compengine = opts['compengine'] | ||||
r42210 | if 'zlib.level' in opts: | |||
self._compengineopts['zlib.level'] = opts['zlib.level'] | ||||
r42211 | if 'zstd.level' in opts: | |||
self._compengineopts['zstd.level'] = opts['zstd.level'] | ||||
|
r41236 | if 'maxdeltachainspan' in opts: | ||
self._maxdeltachainspan = opts['maxdeltachainspan'] | ||||
|
r41239 | if self._mmaplargeindex and 'mmapindexthreshold' in opts: | ||
|
r41236 | mmapindexthreshold = opts['mmapindexthreshold'] | ||
r43298 | self.hassidedata = bool(opts.get('side-data', False)) | |||
|
r41236 | 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 | ||||
if 'sparse-read-density-threshold' in opts: | ||||
self._srdensitythreshold = opts['sparse-read-density-threshold'] | ||||
if 'sparse-read-min-gap-size' in opts: | ||||
self._srmingapsize = opts['sparse-read-min-gap-size'] | ||||
if opts.get('enableellipsis'): | ||||
self._flagprocessors[REVIDX_ELLIPSIS] = ellipsisprocessor | ||||
# revlog v0 doesn't have flag processors | ||||
for flag, processor in opts.get(b'flagprocessors', {}).iteritems(): | ||||
r42957 | flagutil.insertflagprocessor(flag, processor, self._flagprocessors) | |||
|
r40303 | |||
|
r20180 | if self._chunkcachesize <= 0: | ||
|
r39809 | raise error.RevlogError(_('revlog chunk cache size %r is not ' | ||
'greater than 0') % self._chunkcachesize) | ||||
|
r20180 | elif self._chunkcachesize & (self._chunkcachesize - 1): | ||
|
r39809 | raise error.RevlogError(_('revlog chunk cache size %r is not a ' | ||
'power of 2') % self._chunkcachesize) | ||||
|
r11928 | |||
|
r26241 | indexdata = '' | ||
|
r14334 | self._initempty = True | ||
|
r0 | try: | ||
|
r35987 | with self._indexfp() as f: | ||
if (mmapindexthreshold is not None and | ||||
|
r40091 | self.opener.fstat(f).st_size >= mmapindexthreshold): | ||
|
r41322 | # TODO: should .close() to release resources without | ||
# relying on Python GC | ||||
|
r35987 | indexdata = util.buffer(util.mmapread(f)) | ||
else: | ||||
indexdata = f.read() | ||||
|
r26241 | if len(indexdata) > 0: | ||
|
r41237 | versionflags = versionformat_unpack(indexdata[:4])[0] | ||
|
r14334 | self._initempty = False | ||
|
r41241 | else: | ||
versionflags = newversionflags | ||||
|
r25660 | except IOError as inst: | ||
|
r1322 | if inst.errno != errno.ENOENT: | ||
raise | ||||
|
r4985 | |||
|
r41241 | versionflags = newversionflags | ||
|
r41237 | self.version = versionflags | ||
|
r41238 | |||
|
r41237 | flags = versionflags & ~0xFFFF | ||
fmt = versionflags & 0xFFFF | ||||
|
r41238 | |||
|
r32391 | if fmt == REVLOGV0: | ||
if flags: | ||||
|
r39809 | raise error.RevlogError(_('unknown flags (%#04x) in version %d ' | ||
'revlog %s') % | ||||
(flags >> 16, fmt, self.indexfile)) | ||||
|
r41238 | |||
self._inline = False | ||||
self._generaldelta = False | ||||
|
r32391 | elif fmt == REVLOGV1: | ||
if flags & ~REVLOGV1_FLAGS: | ||||
|
r39809 | raise error.RevlogError(_('unknown flags (%#04x) in version %d ' | ||
'revlog %s') % | ||||
(flags >> 16, fmt, self.indexfile)) | ||||
|
r41238 | |||
self._inline = versionflags & FLAG_INLINE_DATA | ||||
self._generaldelta = versionflags & FLAG_GENERALDELTA | ||||
|
r32697 | elif fmt == REVLOGV2: | ||
if flags & ~REVLOGV2_FLAGS: | ||||
|
r39809 | raise error.RevlogError(_('unknown flags (%#04x) in version %d ' | ||
'revlog %s') % | ||||
(flags >> 16, fmt, self.indexfile)) | ||||
|
r41238 | |||
self._inline = versionflags & FLAG_INLINE_DATA | ||||
# generaldelta implied by version 2 revlogs. | ||||
self._generaldelta = True | ||||
|
r32391 | else: | ||
|
r39809 | raise error.RevlogError(_('unknown version (%d) in revlog %s') % | ||
(fmt, self.indexfile)) | ||||
|
r41525 | # sparse-revlog can't be on without general-delta (issue6056) | ||
if not self._generaldelta: | ||||
self._sparserevlog = False | ||||
|
r4985 | |||
|
r39268 | self._storedeltachains = True | ||
|
r30154 | |||
|
r4972 | self._io = revlogio() | ||
|
r4971 | if self.version == REVLOGV0: | ||
|
r4972 | self._io = revlogoldio() | ||
|
r13265 | try: | ||
|
r26241 | d = self._io.parseindex(indexdata, self._inline) | ||
|
r13265 | except (ValueError, IndexError): | ||
|
r39809 | raise error.RevlogError(_("index %s is corrupted") % | ||
self.indexfile) | ||||
|
r13268 | self.index, nodemap, self._chunkcache = d | ||
if nodemap is not None: | ||||
|
r13275 | self.nodemap = self._nodecache = nodemap | ||
|
r13265 | if not self._chunkcache: | ||
self._chunkclear() | ||||
|
r23306 | # revnum -> (chain-length, sum-delta-length) | ||
self._chaininfocache = {} | ||||
|
r30817 | # revlog header -> revlog compressor | ||
self._decompressors = {} | ||||
|
r116 | |||
|
r30795 | @util.propertycache | ||
def _compressor(self): | ||||
r42210 | engine = util.compengines[self._compengine] | |||
return engine.revlogcompressor(self._compengineopts) | ||||
|
r30795 | |||
|
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) | ||||
|
r35985 | def _datafp(self, mode='r'): | ||
"""file object for the revlog's data file""" | ||||
return self.opener(self.datafile, mode=mode) | ||||
|
r35991 | @contextlib.contextmanager | ||
def _datareadfp(self, existingfp=None): | ||||
"""file object suitable to read data""" | ||||
|
r40661 | # Use explicit file handle, if given. | ||
|
r35991 | if existingfp is not None: | ||
yield existingfp | ||||
|
r40661 | |||
# Use a file handle being actively used for writes, if available. | ||||
# There is some danger to doing this because reads will seek the | ||||
# file. However, _writeentry() performs a SEEK_END before all writes, | ||||
# so we should be safe. | ||||
elif self._writinghandles: | ||||
if self._inline: | ||||
yield self._writinghandles[0] | ||||
else: | ||||
yield self._writinghandles[1] | ||||
# Otherwise open a new file handle. | ||||
|
r35991 | else: | ||
if self._inline: | ||||
func = self._indexfp | ||||
else: | ||||
func = self._datafp | ||||
with func() as fp: | ||||
yield fp | ||||
|
r4980 | def tip(self): | ||
|
r38887 | return self.node(len(self.index) - 1) | ||
|
r24030 | def __contains__(self, rev): | ||
return 0 <= rev < len(self) | ||||
|
r6750 | def __len__(self): | ||
|
r38887 | return len(self.index) | ||
|
r6750 | def __iter__(self): | ||
|
r38806 | return iter(pycompat.xrange(len(self))) | ||
|
r17672 | def revs(self, start=0, stop=None): | ||
"""iterate over all rev in this revlog (from start to stop)""" | ||||
|
r39917 | return storageutil.iterrevs(len(self), start=start, stop=stop) | ||
|
r13275 | |||
@util.propertycache | ||||
def nodemap(self): | ||||
|
r39176 | if self.index: | ||
# populate mapping down to the initial node | ||||
|
r39177 | node0 = self.index[0][7] # get around changelog filtering | ||
self.rev(node0) | ||||
|
r13275 | return self._nodecache | ||
|
r13259 | |||
|
r16374 | def hasnode(self, node): | ||
try: | ||||
self.rev(node) | ||||
return True | ||||
except KeyError: | ||||
return False | ||||
|
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 | ||||
|
r16414 | def clearcaches(self): | ||
|
r40088 | self._revisioncache = None | ||
|
r29830 | self._chainbasecache.clear() | ||
|
r27465 | self._chunkcache = (0, '') | ||
self._pcache = {} | ||||
|
r16414 | try: | ||
|
r41480 | # If we are using the native C version, you are in a fun case | ||
# where self.index, self.nodemap and self._nodecaches is the same | ||||
# object. | ||||
|
r16414 | self._nodecache.clearcaches() | ||
except AttributeError: | ||||
self._nodecache = {nullid: nullrev} | ||||
self._nodepos = None | ||||
|
r13259 | def rev(self, node): | ||
|
r13275 | try: | ||
return self._nodecache[node] | ||||
|
r22282 | except TypeError: | ||
raise | ||||
|
r39809 | except error.RevlogError: | ||
|
r16414 | # parsers.c radix tree lookup failed | ||
|
r37467 | if node == wdirid or node in wdirfilenodeids: | ||
|
r32657 | raise error.WdirUnsupported | ||
|
r39811 | raise error.LookupError(node, self.indexfile, _('no node')) | ||
|
r13275 | except KeyError: | ||
|
r16414 | # pure python cache lookup failed | ||
|
r13275 | n = self._nodecache | ||
i = self.index | ||||
p = self._nodepos | ||||
if p is None: | ||||
|
r38887 | p = len(i) - 1 | ||
|
r37512 | else: | ||
assert p < len(i) | ||||
|
r38806 | for r in pycompat.xrange(p, -1, -1): | ||
|
r13275 | v = i[r][7] | ||
n[v] = r | ||||
if v == node: | ||||
self._nodepos = r - 1 | ||||
return r | ||||
|
r37467 | if node == wdirid or node in wdirfilenodeids: | ||
|
r32657 | raise error.WdirUnsupported | ||
|
r39811 | raise error.LookupError(node, self.indexfile, _('no node')) | ||
|
r13275 | |||
|
r30287 | # Accessors for index entries. | ||
# First tuple entry is 8 bytes. First 6 bytes are offset. Last 2 bytes | ||||
# are flags. | ||||
|
r2072 | def start(self, rev): | ||
|
r5006 | return int(self.index[rev][0] >> 16) | ||
|
r30287 | |||
def flags(self, rev): | ||||
return self.index[rev][0] & 0xFFFF | ||||
|
r4980 | def length(self, rev): | ||
return self.index[rev][1] | ||||
|
r30287 | |||
def rawsize(self, rev): | ||||
"""return the length of the uncompressed text for a given revision""" | ||||
l = self.index[rev][2] | ||||
|
r38195 | if l >= 0: | ||
|
r30287 | return l | ||
r43036 | t = self.rawdata(rev) | |||
|
r30287 | return len(t) | ||
|
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) | ||||
r42956 | if flags & (flagutil.REVIDX_KNOWN_FLAGS ^ REVIDX_ELLIPSIS) == 0: | |||
|
r31856 | return self.rawsize(rev) | ||
return len(self.revision(rev, raw=False)) | ||||
|
r30287 | |||
|
r14252 | def chainbase(self, rev): | ||
|
r29830 | base = self._chainbasecache.get(rev) | ||
if base is not None: | ||||
return base | ||||
|
r14252 | index = self.index | ||
|
r38187 | iterrev = rev | ||
base = index[iterrev][3] | ||||
while base != iterrev: | ||||
iterrev = base | ||||
base = index[iterrev][3] | ||||
|
r29830 | |||
self._chainbasecache[rev] = base | ||||
|
r14252 | return base | ||
|
r30287 | |||
def linkrev(self, rev): | ||||
return self.index[rev][4] | ||||
def parentrevs(self, rev): | ||||
|
r32402 | try: | ||
|
r35539 | entry = self.index[rev] | ||
|
r32402 | except IndexError: | ||
if rev == wdirrev: | ||||
raise error.WdirUnsupported | ||||
raise | ||||
|
r30287 | |||
|
r35539 | return entry[5], entry[6] | ||
|
r40188 | # fast parentrevs(rev) where rev isn't filtered | ||
_uncheckedparentrevs = parentrevs | ||||
|
r30287 | def node(self, rev): | ||
|
r32443 | try: | ||
return self.index[rev][7] | ||||
except IndexError: | ||||
if rev == wdirrev: | ||||
raise error.WdirUnsupported | ||||
raise | ||||
|
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 | ||||
|
r23254 | def chainlen(self, rev): | ||
|
r23286 | return self._chaininfo(rev)[0] | ||
|
r23306 | |||
|
r23286 | def _chaininfo(self, rev): | ||
|
r23306 | chaininfocache = self._chaininfocache | ||
if rev in chaininfocache: | ||||
return chaininfocache[rev] | ||||
|
r23254 | index = self.index | ||
generaldelta = self._generaldelta | ||||
iterrev = rev | ||||
e = index[iterrev] | ||||
clen = 0 | ||||
|
r23286 | compresseddeltalen = 0 | ||
|
r23254 | while iterrev != e[3]: | ||
clen += 1 | ||||
|
r23286 | compresseddeltalen += e[1] | ||
|
r23254 | if generaldelta: | ||
iterrev = e[3] | ||||
else: | ||||
iterrev -= 1 | ||||
|
r23306 | if iterrev in chaininfocache: | ||
t = chaininfocache[iterrev] | ||||
clen += t[0] | ||||
compresseddeltalen += t[1] | ||||
break | ||||
|
r23254 | e = index[iterrev] | ||
|
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 | ||||
|
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. | ||||
""" | ||||
|
r33168 | # Try C implementation. | ||
try: | ||||
return self.index.deltachain(rev, stoprev, self._generaldelta) | ||||
except AttributeError: | ||||
pass | ||||
|
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 | ||||
|
r18081 | def ancestors(self, revs, stoprev=0, inclusive=False): | ||
|
r40769 | """Generate the ancestors of 'revs' in reverse revision order. | ||
|
r16868 | Does not generate revs lower than stoprev. | ||
|
r10047 | |||
|
r18090 | See the documentation for ancestor.lazyancestors for more details.""" | ||
|
r18081 | |||
|
r40188 | # first, make sure start revisions aren't filtered | ||
revs = list(revs) | ||||
checkrev = self.node | ||||
for r in revs: | ||||
checkrev(r) | ||||
# and we're sure ancestors aren't filtered as well | ||||
|
r41150 | |||
|
r42652 | if rustancestor is not None: | ||
lazyancestors = rustancestor.LazyAncestors | ||||
|
r41150 | arg = self.index | ||
elif util.safehasattr(parsers, 'rustlazyancestors'): | ||||
lazyancestors = ancestor.rustlazyancestors | ||||
arg = self.index | ||||
else: | ||||
lazyancestors = ancestor.lazyancestors | ||||
arg = self._uncheckedparentrevs | ||||
return lazyancestors(arg, revs, stoprev=stoprev, inclusive=inclusive) | ||||
|
r6872 | |||
|
r16867 | def descendants(self, revs): | ||
|
r40035 | return dagop.descendantrevs(revs, self.revs, self.parentrevs) | ||
|
r6872 | |||
|
r13741 | def findcommonmissing(self, common=None, heads=None): | ||
"""Return a tuple of the ancestors of common and the ancestors of heads | ||||
|
r15835 | that are not ancestors of common. In revset terminology, we return the | ||
tuple: | ||||
|
r10047 | |||
|
r15835 | ::common, (::heads) - (::common) | ||
|
r7233 | |||
|
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.""" | ||||
|
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 | ||||
|
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)) | ||||
|
r8152 | has.add(nullrev) | ||
has.update(common) | ||||
|
r7233 | |||
# take all ancestors from heads that aren't in has | ||||
|
r8453 | missing = set() | ||
|
r25113 | visit = collections.deque(r for r in heads if r not in has) | ||
|
r7233 | while visit: | ||
|
r16803 | r = visit.popleft() | ||
|
r7233 | if r in missing: | ||
continue | ||||
else: | ||||
|
r8453 | missing.add(r) | ||
|
r7233 | for p in self.parentrevs(r): | ||
if p not in has: | ||||
visit.append(p) | ||||
|
r8453 | missing = list(missing) | ||
|
r7233 | missing.sort() | ||
|
r30391 | return has, [self.node(miss) for miss in missing] | ||
|
r13741 | |||
|
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] | ||||
|
r42652 | if rustancestor is not None: | ||
return rustancestor.MissingAncestors(self.index, common) | ||||
|
r23337 | return ancestor.incrementalmissingancestors(self.parentrevs, common) | ||
|
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() | ||||
|
r23338 | inc = self.incrementalmissingrevs(common=common) | ||
return inc.missingancestors(heads) | ||||
|
r17972 | |||
|
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.""" | ||||
|
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] | ||||
|
r23338 | inc = self.incrementalmissingrevs(common=common) | ||
return [self.node(r) for r in inc.missingancestors(heads)] | ||||
|
r7233 | |||
|
r1457 | def nodesbetween(self, roots=None, heads=None): | ||
|
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' | ||||
|
r1457 | |||
|
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'. | ||||
|
r1457 | |||
|
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.""" | ||||
|
r1463 | nonodes = ([], [], []) | ||
|
r1457 | if roots is not None: | ||
roots = list(roots) | ||||
|
r1463 | if not roots: | ||
return nonodes | ||||
|
r1457 | lowestrev = min([self.rev(n) for n in roots]) | ||
else: | ||||
|
r14549 | roots = [nullid] # Everybody's a descendant of nullid | ||
|
r3578 | lowestrev = nullrev | ||
if (lowestrev == nullrev) and (heads is None): | ||||
|
r1457 | # We want _all_ the nodes! | ||
|
r6750 | return ([self.node(r) for r in self], [nullid], list(self.heads())) | ||
|
r1457 | if heads is None: | ||
# All nodes are ancestors, so the latest ancestor is the last | ||||
# node. | ||||
|
r6750 | highestrev = len(self) - 1 | ||
|
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: | ||||
|
r1463 | heads = list(heads) | ||
if not heads: | ||||
return nonodes | ||||
|
r8464 | ancestors = set() | ||
|
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. | ||||
|
r14219 | heads = dict.fromkeys(heads, False) | ||
|
r3360 | # Start at the top and keep marking parents until we're done. | ||
|
r8163 | nodestotag = set(heads) | ||
|
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: | ||||
|
r14549 | # If we are possibly a descendant of one of the roots | ||
|
r1457 | # and we haven't already been marked as an ancestor | ||
|
r8464 | ancestors.add(n) # Mark as ancestor | ||
|
r1457 | # Add non-nullid parents to list of nodes to tag. | ||
|
r8153 | nodestotag.update([p for p in self.parents(n) if | ||
|
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) | ||||
|
r1459 | if not ancestors: | ||
|
r1463 | return nonodes | ||
|
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. | ||||
|
r3578 | if lowestrev > nullrev: | ||
|
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 | ||||
|
r30391 | roots = [root for root in roots if root in ancestors] | ||
|
r1457 | # Recompute the lowest revision | ||
if roots: | ||||
|
r30391 | lowestrev = min([self.rev(root) for root in roots]) | ||
|
r1457 | else: | ||
# No more roots? Return empty list | ||||
|
r1463 | return nonodes | ||
|
r1457 | else: | ||
# We are descending from nullid, and don't need to care about | ||||
# any other roots. | ||||
|
r3578 | lowestrev = nullrev | ||
|
r1457 | roots = [nullid] | ||
|
r8152 | # Transform our roots list into a set. | ||
|
r14549 | descendants = set(roots) | ||
|
r1457 | # Also, keep the original roots so we can filter out roots that aren't | ||
# 'real' roots (i.e. are descended from other roots). | ||||
|
r14549 | roots = descendants.copy() | ||
|
r1457 | # Our topologically sorted list of output nodes. | ||
orderedout = [] | ||||
# Don't start at nullid since we don't want nullid in our output list, | ||||
|
r17483 | # and if nullid shows up in descendants, empty parents will look like | ||
|
r14549 | # they're descendants. | ||
|
r17672 | for r in self.revs(start=max(lowestrev, 0), stop=highestrev + 1): | ||
|
r1457 | n = self.node(r) | ||
|
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 | ||||
|
r1457 | # This check only needs to be done here because all the roots | ||
|
r14549 | # will start being marked is descendants before the loop. | ||
|
r1457 | if n in roots: | ||
# If n was a root, check if it's a 'real' root. | ||||
p = tuple(self.parents(n)) | ||||
|
r14549 | # If any of its parents are descendants, it's not a root. | ||
if (p[0] in descendants) or (p[1] in descendants): | ||||
|
r8152 | roots.remove(n) | ||
|
r1457 | else: | ||
p = tuple(self.parents(n)) | ||||
|
r14549 | # A node is a descendant if either of its parents are | ||
# descendants. (We seeded the dependents list with the roots | ||||
|
r1457 | # up there, remember?) | ||
|
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. | ||||
|
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 | ||||
|
r14219 | heads[n] = True | ||
|
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. | ||||
|
r14219 | heads[n] = True | ||
|
r1457 | # But, obviously its parents aren't. | ||
for p in self.parents(n): | ||||
heads.pop(p, None) | ||||
|
r30391 | heads = [head for head, flag in heads.iteritems() if flag] | ||
|
r8152 | roots = list(roots) | ||
|
r1457 | assert orderedout | ||
assert roots | ||||
assert heads | ||||
return (orderedout, roots, heads) | ||||
|
r41311 | def headrevs(self, revs=None): | ||
if revs is None: | ||||
try: | ||||
return self.index.headrevs() | ||||
except AttributeError: | ||||
return self._headrevs() | ||||
|
r42652 | if rustdagop is not None: | ||
return rustdagop.headrevs(self.index, revs) | ||||
|
r41929 | return dagop.headrevs(revs, self._uncheckedparentrevs) | ||
|
r17674 | |||
|
r24444 | def computephases(self, roots): | ||
|
r25361 | return self.index.computephasesmapsets(roots) | ||
|
r24444 | |||
|
r17674 | def _headrevs(self): | ||
|
r14164 | count = len(self) | ||
if not count: | ||||
return [nullrev] | ||||
|
r17673 | # we won't iter over filtered rev so nobody is a head at start | ||
ishead = [0] * (count + 1) | ||||
|
r14164 | index = self.index | ||
|
r17672 | for r in self: | ||
|
r17673 | ishead[r] = 1 # I may be an head | ||
|
r14164 | e = index[r] | ||
|
r17673 | ishead[e[5]] = ishead[e[6]] = 0 # my parent are not | ||
return [r for r, val in enumerate(ishead) if val] | ||||
|
r14164 | |||
|
r3923 | def heads(self, start=None, stop=None): | ||
|
r1550 | """return the list of all nodes that have no children | ||
|
r1551 | |||
if start is specified, only heads that are descendants of | ||||
start will be returned | ||||
|
r3923 | if stop is specified, it will consider all the revs from stop | ||
as if they had no children | ||||
|
r1551 | """ | ||
|
r4991 | if start is None and stop is None: | ||
|
r14164 | if not len(self): | ||
|
r4991 | return [nullid] | ||
|
r14164 | return [self.node(r) for r in self.headrevs()] | ||
|
r4991 | |||
|
r1551 | if start is None: | ||
|
r40036 | start = nullrev | ||
else: | ||||
start = self.rev(start) | ||||
stoprevs = set(self.rev(n) for n in stop or []) | ||||
revs = dagop.headrevssubset(self.revs, self.parentrevs, startrev=start, | ||||
stoprevs=stoprevs) | ||||
return [self.node(rev) for rev in revs] | ||||
|
r370 | |||
def children(self, node): | ||||
|
r1083 | """find the children of a given node""" | ||
|
r370 | c = [] | ||
p = self.rev(node) | ||||
|
r17672 | for r in self.revs(start=p + 1): | ||
|
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)) | ||||
|
r370 | return c | ||
|
r515 | |||
|
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) | ||||
|
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""" | ||||
|
r21104 | try: | ||
|
r38531 | ancs = self.index.commonancestorsheads(*revs) | ||
|
r21104 | except (AttributeError, OverflowError): # C implementation failed | ||
|
r38531 | ancs = ancestor.commonancestorsheads(self.parentrevs, *revs) | ||
return ancs | ||||
|
r21104 | |||
|
r22381 | def isancestor(self, a, b): | ||
|
r38686 | """return True if node a is an ancestor of node b | ||
A revision is considered an ancestor of itself.""" | ||||
|
r38533 | a, b = self.rev(a), self.rev(b) | ||
|
r38688 | return self.isancestorrev(a, b) | ||
def isancestorrev(self, a, b): | ||||
"""return True if revision a is an ancestor of revision b | ||||
|
r38690 | A revision is considered an ancestor of itself. | ||
The implementation of this is trivial but the use of | ||||
|
r42639 | reachableroots is not.""" | ||
|
r38690 | if a == nullrev: | ||
return True | ||||
elif a == b: | ||||
return True | ||||
elif a > b: | ||||
return False | ||||
|
r42639 | return bool(self.reachableroots(a, [b], [a], includepath=False)) | ||
def reachableroots(self, minroot, heads, roots, includepath=False): | ||||
"""return (heads(::<roots> and <roots>::<heads>)) | ||||
If includepath is True, return (<roots>::<heads>).""" | ||||
try: | ||||
return self.index.reachableroots2(minroot, heads, roots, | ||||
includepath) | ||||
except AttributeError: | ||||
return dagop._reachablerootspure(self.parentrevs, | ||||
minroot, roots, heads, includepath) | ||||
|
r22381 | |||
|
r21107 | def ancestor(self, a, b): | ||
|
r22389 | """calculate the "best" common ancestor of nodes a and b""" | ||
|
r21107 | |||
|
r10897 | a, b = self.rev(a), self.rev(b) | ||
|
r18988 | try: | ||
ancs = self.index.ancestors(a, b) | ||||
|
r21107 | except (AttributeError, OverflowError): | ||
|
r18988 | ancs = ancestor.ancestors(self.parentrevs, a, b) | ||
|
r18987 | if ancs: | ||
# choose a consistent winner when there's a tie | ||||
|
r21107 | return min(map(self.node, ancs)) | ||
|
r18987 | return nullid | ||
|
r10897 | |||
|
r3453 | def _match(self, id): | ||
|
r16762 | if isinstance(id, int): | ||
|
r3156 | # rev | ||
|
r2641 | return self.node(id) | ||
|
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 | ||||
|
r7874 | self.rev(node) # quick search the index | ||
|
r3438 | return node | ||
|
r39811 | except error.LookupError: | ||
|
r3438 | pass # may be partial hex id | ||
|
r36 | try: | ||
|
r3156 | # str(rev) | ||
|
r36 | rev = int(id) | ||
|
r36738 | if "%d" % rev != id: | ||
|
r4980 | raise ValueError | ||
if rev < 0: | ||||
|
r6750 | rev = len(self) + rev | ||
if rev < 0 or rev >= len(self): | ||||
|
r4980 | raise ValueError | ||
|
r36 | return self.node(rev) | ||
|
r469 | except (ValueError, OverflowError): | ||
|
r3156 | pass | ||
|
r3453 | if len(id) == 40: | ||
try: | ||||
|
r3438 | # a full hex nodeid? | ||
node = bin(id) | ||||
|
r7874 | self.rev(node) | ||
|
r3157 | return node | ||
|
r39811 | except (TypeError, error.LookupError): | ||
|
r3453 | pass | ||
def _partialmatch(self, id): | ||||
|
r37467 | # we don't care wdirfilenodeids as they should be always full hash | ||
|
r32684 | maybewdir = wdirhex.startswith(id) | ||
|
r16665 | try: | ||
|
r30391 | partial = self.index.partialmatch(id) | ||
if partial and self.hasnode(partial): | ||||
|
r32684 | if maybewdir: | ||
# single 'ff...' match in radix tree, ambiguous with wdir | ||||
|
r39809 | raise error.RevlogError | ||
|
r30391 | return partial | ||
|
r32684 | if maybewdir: | ||
# no 'ff...' match in radix tree, wdir identified | ||||
raise error.WdirUnsupported | ||||
|
r19471 | return None | ||
|
r39809 | except error.RevlogError: | ||
|
r16665 | # parsers.c radix tree lookup gave multiple matches | ||
|
r29396 | # fast path: for unfiltered changelog, radix tree is accurate | ||
if not getattr(self, 'filteredrevs', None): | ||||
|
r39810 | raise error.AmbiguousPrefixLookupError( | ||
id, self.indexfile, _('ambiguous identifier')) | ||||
|
r19471 | # fall through to slow path that filters hidden revisions | ||
|
r16665 | except (AttributeError, ValueError): | ||
# we are pure python, or key was too short to search radix tree | ||||
pass | ||||
|
r13258 | if id in self._pcache: | ||
return self._pcache[id] | ||||
|
r37837 | if len(id) <= 40: | ||
|
r3453 | try: | ||
|
r3438 | # hex(node)[:...] | ||
|
r9029 | l = len(id) // 2 # grab an even number of digits | ||
|
r13259 | prefix = bin(id[:l * 2]) | ||
nl = [e[7] for e in self.index if e[7].startswith(prefix)] | ||||
|
r19471 | nl = [n for n in nl if hex(n).startswith(id) and | ||
self.hasnode(n)] | ||||
|
r39227 | if nullhex.startswith(id): | ||
nl.append(nullid) | ||||
|
r7365 | if len(nl) > 0: | ||
|
r32684 | if len(nl) == 1 and not maybewdir: | ||
|
r13258 | self._pcache[id] = nl[0] | ||
|
r7365 | return nl[0] | ||
|
r39810 | raise error.AmbiguousPrefixLookupError( | ||
id, self.indexfile, _('ambiguous identifier')) | ||||
|
r32684 | if maybewdir: | ||
raise error.WdirUnsupported | ||||
|
r7365 | return None | ||
|
r36256 | except TypeError: | ||
|
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 | ||||
|
r515 | |||
|
r39811 | raise error.LookupError(id, self.indexfile, _('no match found')) | ||
|
r36 | |||
|
r37785 | def shortest(self, node, minlength=1): | ||
"""Find the shortest unambiguous prefix that matches node.""" | ||||
|
r37880 | def isvalid(prefix): | ||
|
r34247 | try: | ||
|
r42852 | matchednode = self._partialmatch(prefix) | ||
|
r39856 | except error.AmbiguousPrefixLookupError: | ||
|
r34247 | return False | ||
except error.WdirUnsupported: | ||||
# single 'ff...' match | ||||
return True | ||||
|
r42852 | if matchednode is None: | ||
|
r39811 | raise error.LookupError(node, self.indexfile, _('no node')) | ||
|
r37989 | return True | ||
|
r34247 | |||
|
r37987 | def maybewdir(prefix): | ||
|
r41838 | return all(c == 'f' for c in pycompat.iterbytestr(prefix)) | ||
|
r37987 | |||
|
r37785 | hexnode = hex(node) | ||
|
r37987 | |||
def disambiguate(hexnode, minlength): | ||||
|
r37990 | """Disambiguate against wdirid.""" | ||
|
r37987 | for length in range(minlength, 41): | ||
prefix = hexnode[:length] | ||||
|
r37990 | if not maybewdir(prefix): | ||
|
r37987 | return prefix | ||
if not getattr(self, 'filteredrevs', None): | ||||
try: | ||||
length = max(self.index.shortest(node), minlength) | ||||
return disambiguate(hexnode, length) | ||||
|
r39809 | except error.RevlogError: | ||
|
r37988 | if node != wdirid: | ||
|
r39811 | raise error.LookupError(node, self.indexfile, _('no node')) | ||
|
r37987 | except AttributeError: | ||
# Fall through to pure code | ||||
pass | ||||
|
r37988 | if node == wdirid: | ||
for length in range(minlength, 41): | ||||
prefix = hexnode[:length] | ||||
if isvalid(prefix): | ||||
return prefix | ||||
for length in range(minlength, 41): | ||||
|
r37880 | prefix = hexnode[:length] | ||
if isvalid(prefix): | ||||
|
r37988 | return disambiguate(hexnode, length) | ||
|
r34247 | |||
|
r2890 | def cmp(self, node, text): | ||
|
r11539 | """compare text with a given file revision | ||
returns True if text is different than what is stored. | ||||
""" | ||||
|
r2890 | p1, p2 = self.parents(node) | ||
|
r39913 | return storageutil.hashrevisionsha1(text, p1, p2) != node | ||
|
r2890 | |||
|
r32222 | def _cachesegment(self, offset, data): | ||
|
r27070 | """Add a segment to the revlog cache. | ||
Accepts an absolute offset and the data that is at that location. | ||||
""" | ||||
|
r8316 | o, d = self._chunkcache | ||
# try to add to existing cache | ||||
|
r13253 | if o + len(d) == offset and len(d) + len(data) < _chunksize: | ||
|
r8316 | self._chunkcache = o, d + data | ||
else: | ||||
self._chunkcache = offset, data | ||||
|
r32222 | def _readsegment(self, offset, length, df=None): | ||
|
r27070 | """Load a segment of raw data from the revlog. | ||
|
r26377 | |||
|
r27070 | Accepts an absolute offset, length to read, and an optional existing | ||
|
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. | ||||
|
r27070 | |||
Returns a str or buffer of raw byte data. | ||||
|
r40660 | |||
Raises if the requested number of bytes could not be read. | ||||
|
r26377 | """ | ||
|
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. | ||||
|
r20180 | cachesize = self._chunkcachesize | ||
realoffset = offset & ~(cachesize - 1) | ||||
reallength = (((offset + length + cachesize) & ~(cachesize - 1)) | ||||
- realoffset) | ||||
|
r35991 | with self._datareadfp(df) as df: | ||
df.seek(realoffset) | ||||
d = df.read(reallength) | ||||
|
r40660 | |||
|
r32222 | self._cachesegment(realoffset, d) | ||
|
r20179 | if offset != realoffset or reallength != length: | ||
|
r40660 | startoffset = offset - realoffset | ||
if len(d) - startoffset < length: | ||||
raise error.RevlogError( | ||||
_('partial read of revlog %s; expected %d bytes from ' | ||||
'offset %d, got %d') % | ||||
(self.indexfile if self._inline else self.datafile, | ||||
length, realoffset, len(d) - startoffset)) | ||||
return util.buffer(d, startoffset, length) | ||||
if len(d) < length: | ||||
raise error.RevlogError( | ||||
_('partial read of revlog %s; expected %d bytes from offset ' | ||||
'%d, got %d') % | ||||
(self.indexfile if self._inline else self.datafile, | ||||
length, offset, len(d))) | ||||
|
r8316 | return d | ||
|
r32222 | def _getsegment(self, offset, length, df=None): | ||
|
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. | ||||
""" | ||||
|
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 | ||||
|
r16423 | return util.buffer(d, cachestart, cacheend - cachestart) | ||
|
r8316 | |||
|
r32222 | return self._readsegment(offset, length, df=df) | ||
|
r8316 | |||
|
r32224 | def _getsegmentforrevs(self, startrev, endrev, df=None): | ||
|
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. | ||||
|
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. | ||||
|
r27070 | """ | ||
|
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) | ||||
|
r30289 | if startrev == endrev: | ||
end = start + istart[1] | ||||
else: | ||||
iend = index[endrev] | ||||
end = int(iend[0] >> 16) + iend[1] | ||||
|
r30288 | |||
|
r8318 | if self._inline: | ||
start += (startrev + 1) * self._io.size | ||||
|
r19714 | end += (endrev + 1) * self._io.size | ||
length = end - start | ||||
|
r27649 | |||
|
r32222 | return start, self._getsegment(start, length, df=df) | ||
|
r8318 | |||
|
r26377 | def _chunk(self, rev, df=None): | ||
|
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. | ||||
""" | ||||
|
r32224 | return self.decompress(self._getsegmentforrevs(rev, rev, df=df)[1]) | ||
|
r8650 | |||
|
r38666 | def _chunks(self, revs, df=None, targetsize=None): | ||
|
r27070 | """Obtain decompressed chunks for the specified revisions. | ||
|
r19713 | |||
|
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. | ||||
""" | ||||
|
r19716 | if not revs: | ||
return [] | ||||
|
r19713 | start = self.start | ||
length = self.length | ||||
inline = self._inline | ||||
iosize = self._io.size | ||||
|
r19715 | buffer = util.buffer | ||
|
r19713 | |||
l = [] | ||||
ladd = l.append | ||||
|
r34825 | if not self._withsparseread: | ||
slicedchunks = (revs,) | ||||
else: | ||||
|
r39366 | slicedchunks = deltautil.slicechunk(self, revs, | ||
targetsize=targetsize) | ||||
|
r34825 | |||
for revschunk in slicedchunks: | ||||
firstrev = revschunk[0] | ||||
# Skip trailing revisions with empty diff | ||||
for lastrev in revschunk[::-1]: | ||||
if length(lastrev) != 0: | ||||
break | ||||
|
r34824 | |||
|
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] | ||||
|
r19715 | |||
|
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))) | ||||
|
r19713 | |||
return l | ||||
|
r14075 | |||
|
r8650 | def _chunkclear(self): | ||
|
r27070 | """Clear the raw chunk cache.""" | ||
|
r8650 | self._chunkcache = (0, '') | ||
|
r1598 | |||
|
r11929 | def deltaparent(self, rev): | ||
|
r14195 | """return deltaparent of the given revision""" | ||
|
r14253 | base = self.index[rev][3] | ||
if base == rev: | ||||
|
r14208 | return nullrev | ||
|
r14253 | elif self._generaldelta: | ||
return base | ||||
|
r14208 | else: | ||
return rev - 1 | ||||
|
r11929 | |||
|
r39185 | def issnapshot(self, rev): | ||
"""tells whether rev is a snapshot | ||||
""" | ||||
|
r41118 | if not self._sparserevlog: | ||
return self.deltaparent(rev) == nullrev | ||||
elif util.safehasattr(self.index, 'issnapshot'): | ||||
# directly assign the method to cache the testing and access | ||||
self.issnapshot = self.index.issnapshot | ||||
return self.issnapshot(rev) | ||||
|
r39185 | if rev == nullrev: | ||
return True | ||||
|
r41116 | entry = self.index[rev] | ||
base = entry[3] | ||||
if base == rev: | ||||
|
r39185 | return True | ||
|
r41116 | if base == nullrev: | ||
return True | ||||
p1 = entry[5] | ||||
p2 = entry[6] | ||||
if base == p1 or base == p2: | ||||
|
r39186 | return False | ||
|
r41116 | return self.issnapshot(base) | ||
|
r39185 | |||
|
r39188 | def snapshotdepth(self, rev): | ||
"""number of snapshot in the chain before this one""" | ||||
if not self.issnapshot(rev): | ||||
|
r39810 | raise error.ProgrammingError('revision %d not a snapshot') | ||
|
r39188 | return len(self._deltachain(rev)[0]) - 1 | ||
|
r1941 | def revdiff(self, rev1, rev2): | ||
|
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. | ||||
""" | ||||
|
r14208 | if rev1 != nullrev and self.deltaparent(rev2) == rev1: | ||
|
r31369 | return bytes(self._chunk(rev2)) | ||
|
r5005 | |||
r43036 | return mdiff.textdiff(self.rawdata(rev1), | |||
self.rawdata(rev2)) | ||||
|
r119 | |||
r43263 | def _processflags(self, text, flags, operation, raw=False): | |||
"""deprecated entry point to access flag processors""" | ||||
msg = ('_processflag(...) use the specialized variant') | ||||
util.nouideprecwarn(msg, '5.2', stacklevel=2) | ||||
if raw: | ||||
return text, flagutil.processflagsraw(self, text, flags) | ||||
elif operation == 'read': | ||||
return flagutil.processflagsread(self, text, flags) | ||||
else: # write operation | ||||
return flagutil.processflagswrite(self, text, flags) | ||||
|
r30743 | def revision(self, nodeorrev, _df=None, raw=False): | ||
|
r16435 | """return an uncompressed revision of a given node or revision | ||
number. | ||||
|
r26377 | |||
|
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. | ||||
|
r16435 | """ | ||
r43111 | if raw: | |||
msg = ('revlog.revision(..., raw=True) is deprecated, ' | ||||
'use revlog.rawdata(...)') | ||||
util.nouideprecwarn(msg, '5.2', stacklevel=2) | ||||
r43251 | return self._revisiondata(nodeorrev, _df, raw=raw)[0] | |||
r42944 | ||||
r43250 | def sidedata(self, nodeorrev, _df=None): | |||
"""a map of extra data related to the changeset but not part of the hash | ||||
This function currently return a dictionary. However, more advanced | ||||
mapping object will likely be used in the future for a more | ||||
efficient/lazy code. | ||||
""" | ||||
r43252 | return self._revisiondata(nodeorrev, _df)[1] | |||
r43250 | ||||
r42944 | def _revisiondata(self, nodeorrev, _df=None, raw=False): | |||
r43058 | # deal with <nodeorrev> argument type | |||
|
r16375 | if isinstance(nodeorrev, int): | ||
rev = nodeorrev | ||||
node = self.node(rev) | ||||
else: | ||||
node = nodeorrev | ||||
rev = None | ||||
r43058 | # fast path the special `nullid` rev | |||
r43057 | if node == nullid: | |||
r43251 | return "", {} | |||
r43057 | ||||
r43058 | # The text as stored inside the revlog. Might be the revision or might | |||
# need to be processed to retrieve the revision. | ||||
|
r31804 | rawtext = None | ||
r43060 | ||||
rev, rawtext, validated = self._rawtext(node, rev, _df=_df) | ||||
if raw and validated: | ||||
# if we don't want to process the raw text and that raw | ||||
# text is cached, we can exit early. | ||||
r43251 | return rawtext, {} | |||
r43060 | if rev is None: | |||
rev = self.rev(node) | ||||
# the revlog's flag for this revision | ||||
# (usually alter its state or content) | ||||
flags = self.flags(rev) | ||||
if validated and flags == REVIDX_DEFAULT_FLAGS: | ||||
# no extra flags set, no flag processor runs, text = rawtext | ||||
r43251 | return rawtext, {} | |||
sidedata = {} | ||||
r43148 | if raw: | |||
r43262 | validatehash = flagutil.processflagsraw(self, rawtext, flags) | |||
r43148 | text = rawtext | |||
else: | ||||
r43302 | try: | |||
r = flagutil.processflagsread(self, rawtext, flags) | ||||
except error.SidedataHashError as exc: | ||||
msg = _("integrity check failed on %s:%s sidedata key %d") | ||||
msg %= (self.indexfile, pycompat.bytestr(rev), | ||||
exc.sidedatakey) | ||||
raise error.RevlogError(msg) | ||||
r43253 | text, validatehash, sidedata = r | |||
r43060 | if validatehash: | |||
self.checkhash(text, node, rev=rev) | ||||
if not validated: | ||||
self._revisioncache = (node, rev, rawtext) | ||||
r43251 | return text, sidedata | |||
r43060 | ||||
def _rawtext(self, node, rev, _df=None): | ||||
"""return the possibly unvalidated rawtext for a revision | ||||
returns (rev, rawtext, validated) | ||||
""" | ||||
# revision in the cache (could be useful to apply delta) | ||||
cachedrev = None | ||||
r43058 | # An intermediate text to apply deltas to | |||
r43056 | basetext = None | |||
r43058 | ||||
# Check if we have the entry in cache | ||||
# The cache entry looks like (node, rev, rawtext) | ||||
|
r40088 | if self._revisioncache: | ||
if self._revisioncache[0] == node: | ||||
r43060 | return (rev, self._revisioncache[2], True) | |||
|
r40088 | cachedrev = self._revisioncache[1] | ||
|
r0 | |||
r43060 | if rev is None: | |||
rev = self.rev(node) | ||||
chain, stopped = self._deltachain(rev, stoprev=cachedrev) | ||||
if stopped: | ||||
basetext = self._revisioncache[2] | ||||
# drop cache to save memory, the caller is expected to | ||||
# update self._revisioncache after validating the text | ||||
self._revisioncache = None | ||||
targetsize = None | ||||
rawsize = self.index[rev][2] | ||||
if 0 <= rawsize: | ||||
targetsize = 4 * rawsize | ||||
bins = self._chunks(chain, df=_df, targetsize=targetsize) | ||||
if basetext is None: | ||||
basetext = bytes(bins[0]) | ||||
bins = bins[1:] | ||||
rawtext = mdiff.patches(basetext, bins) | ||||
del basetext # let us have a chance to free memory early | ||||
return (rev, rawtext, False) | ||||
|
r13239 | |||
r43054 | def rawdata(self, nodeorrev, _df=None): | |||
r42945 | """return an uncompressed raw data of a given node or revision number. | |||
_df - an existing file handle to read from. (internal-only) | ||||
""" | ||||
r43251 | return self._revisiondata(nodeorrev, _df, raw=True)[0] | |||
r42945 | ||||
|
r22785 | def hash(self, text, p1, p2): | ||
"""Compute a node hash. | ||||
Available as a function so that subclasses can replace the hash | ||||
as needed. | ||||
""" | ||||
|
r39913 | return storageutil.hashrevisionsha1(text, p1, p2) | ||
|
r22785 | |||
|
r30584 | def checkhash(self, text, node, p1=None, p2=None, rev=None): | ||
"""Check node hash integrity. | ||||
|
r19624 | |||
|
r30584 | Available as a function so that subclasses can extend hash mismatch | ||
behaviors as needed. | ||||
""" | ||||
|
r37461 | try: | ||
if p1 is None and p2 is None: | ||||
p1, p2 = self.parents(node) | ||||
if node != self.hash(text, p1, p2): | ||||
|
r40090 | # Clear the revision cache on hash failure. The revision cache | ||
# only stores the raw revision and clearing the cache does have | ||||
# the side-effect that we won't have a cache hit when the raw | ||||
# revision data is accessed. But this case should be rare and | ||||
# it is extra work to teach the cache about the hash | ||||
# verification state. | ||||
if self._revisioncache and self._revisioncache[0] == node: | ||||
self._revisioncache = None | ||||
|
r37461 | revornode = rev | ||
if revornode is None: | ||||
revornode = templatefilters.short(hex(node)) | ||||
|
r39809 | raise error.RevlogError(_("integrity check failed on %s:%s") | ||
|
r37461 | % (self.indexfile, pycompat.bytestr(revornode))) | ||
|
r39809 | except error.RevlogError: | ||
|
r39915 | if self._censorable and storageutil.iscensoredtext(text): | ||
|
r37461 | raise error.CensoredNodeError(self.indexfile, node, text) | ||
raise | ||||
|
r0 | |||
|
r35992 | def _enforceinlinesize(self, tr, fp=None): | ||
|
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. | ||||
""" | ||||
|
r38880 | tiprev = len(self) - 1 | ||
if (not self._inline or | ||||
(self.start(tiprev) + self.length(tiprev)) < _maxinline): | ||||
|
r2073 | return | ||
|
r8315 | |||
|
r2084 | trinfo = tr.find(self.indexfile) | ||
|
r8527 | if trinfo is None: | ||
|
r39809 | raise error.RevlogError(_("%s not found in the transaction") | ||
% self.indexfile) | ||||
|
r2084 | |||
trindex = trinfo[2] | ||||
|
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 | ||||
|
r38880 | dataoff = self.end(tiprev) | ||
|
r2084 | |||
tr.add(self.datafile, dataoff) | ||||
|
r8315 | |||
|
r8317 | if fp: | ||
fp.flush() | ||||
fp.close() | ||||
|
r40661 | # We can't use the cached file handle after close(). So prevent | ||
# its usage. | ||||
self._writinghandles = None | ||||
|
r8315 | |||
|
r40659 | with self._indexfp('r') as ifh, self._datafp('w') as dfh: | ||
|
r6750 | for r in self: | ||
|
r40659 | dfh.write(self._getsegmentforrevs(r, r, df=ifh)[1]) | ||
|
r6261 | |||
|
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) | ||||
|
r2073 | |||
|
r35989 | # the temp file replace the real index when we exit the context | ||
# manager | ||||
|
r2084 | |||
|
r8650 | tr.replace(self.indexfile, trindex * self._io.size) | ||
self._chunkclear() | ||||
|
r2073 | |||
|
r39922 | def _nodeduplicatecallback(self, transaction, node): | ||
"""called when trying to add a node already stored. | ||||
""" | ||||
|
r19625 | def addrevision(self, text, transaction, link, p1, p2, cachedelta=None, | ||
r43256 | node=None, flags=REVIDX_DEFAULT_FLAGS, deltacomputer=None, | |||
sidedata=None): | ||||
|
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 | ||||
|
r12012 | cachedelta - an optional precomputed delta | ||
|
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) | ||||
|
r30744 | flags - the known flags to set on the revision | ||
|
r39366 | deltacomputer - an optional deltacomputer instance shared between | ||
|
r35756 | multiple calls | ||
|
r1083 | """ | ||
|
r19326 | if link == nullrev: | ||
|
r39809 | raise error.RevlogError(_("attempted to add linkrev -1 to %s") | ||
% self.indexfile) | ||||
|
r25459 | |||
r43256 | if sidedata is None: | |||
sidedata = {} | ||||
r43298 | elif not self.hassidedata: | |||
raise error.ProgrammingError( | ||||
_("trying to add sidedata to a revlog who don't support them") | ||||
) | ||||
r43256 | ||||
|
r30745 | if flags: | ||
node = node or self.hash(text, p1, p2) | ||||
r43260 | rawtext, validatehash = flagutil.processflagswrite(self, text, flags, | |||
sidedata=sidedata) | ||||
|
r30745 | |||
# If the flag processor modifies the revision data, ignore any provided | ||||
# cachedelta. | ||||
|
r31750 | if rawtext != text: | ||
|
r30745 | cachedelta = None | ||
|
r31750 | if len(rawtext) > _maxentrysize: | ||
|
r39809 | raise error.RevlogError( | ||
|
r25459 | _("%s: size of %d bytes exceeds maximum revlog storage of 2GiB") | ||
|
r31750 | % (self.indexfile, len(rawtext))) | ||
|
r25459 | |||
|
r31750 | node = node or self.hash(rawtext, p1, p2) | ||
|
r14196 | if node in self.nodemap: | ||
|
r12023 | return node | ||
|
r30745 | if validatehash: | ||
|
r31750 | self.checkhash(rawtext, node, p1=p1, p2=p2) | ||
|
r30745 | |||
|
r32240 | return self.addrawrevision(rawtext, transaction, link, p1, p2, node, | ||
|
r35756 | flags, cachedelta=cachedelta, | ||
deltacomputer=deltacomputer) | ||||
|
r32240 | |||
def addrawrevision(self, rawtext, transaction, link, p1, p2, node, flags, | ||||
|
r35756 | cachedelta=None, deltacomputer=None): | ||
|
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). | ||||
""" | ||||
|
r4981 | dfh = None | ||
|
r4982 | if not self._inline: | ||
|
r35985 | dfh = self._datafp("a+") | ||
|
r35986 | ifh = self._indexfp("a+") | ||
|
r6261 | try: | ||
|
r31750 | return self._addrevision(node, rawtext, transaction, link, p1, p2, | ||
|
r35756 | flags, cachedelta, ifh, dfh, | ||
deltacomputer=deltacomputer) | ||||
|
r6261 | finally: | ||
if dfh: | ||||
dfh.close() | ||||
ifh.close() | ||||
|
r3390 | |||
|
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 | ||||
|
r31643 | if data[0:1] == '\0': | ||
|
r30795 | return '', data | ||
return 'u', data | ||||
|
r17128 | |||
|
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 | ||||
|
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. | ||||
|
r31356 | t = data[0:1] | ||
|
r30817 | |||
|
r30793 | if t == 'x': | ||
try: | ||||
|
r30817 | return _zlibdecompress(data) | ||
|
r30793 | except zlib.error as e: | ||
|
r39809 | raise error.RevlogError(_('revlog decompress error: %s') % | ||
stringutil.forcebytestr(e)) | ||||
|
r30817 | # '\0' is more common than 'u' so it goes first. | ||
elif t == '\0': | ||||
return data | ||||
elif t == 'u': | ||||
|
r30793 | return util.buffer(data, 1) | ||
|
r30817 | |||
try: | ||||
compressor = self._decompressors[t] | ||||
except KeyError: | ||||
try: | ||||
engine = util.compengines.forrevlogheader(t) | ||||
r42210 | compressor = engine.revlogcompressor(self._compengineopts) | |||
|
r30817 | self._decompressors[t] = compressor | ||
except KeyError: | ||||
|
r39809 | raise error.RevlogError(_('unknown compression type %r') % t) | ||
|
r30817 | |||
return compressor.decompress(data) | ||||
|
r30793 | |||
|
r31755 | def _addrevision(self, node, rawtext, transaction, link, p1, p2, flags, | ||
|
r35756 | cachedelta, ifh, dfh, alwayscache=False, | ||
deltacomputer=None): | ||||
|
r14292 | """internal function to add revisions to the log | ||
|
r12623 | |||
|
r14292 | see addrevision for argument descriptions. | ||
|
r31755 | |||
note: "addrevision" takes non-raw text, "_addrevision" takes raw text. | ||||
|
r35756 | if "deltacomputer" is not provided or None, a defaultdeltacomputer will | ||
be used. | ||||
|
r14292 | invariants: | ||
|
r31755 | - rawtext is optional (can be None); if not set, cachedelta must be set. | ||
|
r17424 | if both are set, they must correspond to each other. | ||
|
r14292 | """ | ||
|
r33939 | if node == nullid: | ||
|
r39809 | raise error.RevlogError(_("%s: attempt to add null revision") % | ||
self.indexfile) | ||||
|
r37467 | if node == wdirid or node in wdirfilenodeids: | ||
|
r39809 | raise error.RevlogError(_("%s: attempt to add wdir revision") % | ||
self.indexfile) | ||||
|
r34029 | |||
|
r35653 | if self._inline: | ||
fh = ifh | ||||
else: | ||||
fh = dfh | ||||
|
r31755 | btext = [rawtext] | ||
|
r12623 | |||
|
r6750 | curr = len(self) | ||
|
r4981 | prev = curr - 1 | ||
offset = self.end(prev) | ||||
|
r12889 | p1r, p2r = self.rev(p1), self.rev(p2) | ||
|
r0 | |||
|
r26116 | # full versions are inserted when the needed deltas | ||
# become comparable to the uncompressed text | ||||
|
r31755 | if rawtext is None: | ||
|
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]), | ||||
|
r26116 | cachedelta[1]) | ||
else: | ||||
|
r31755 | textlen = len(rawtext) | ||
|
r26116 | |||
|
r35756 | if deltacomputer is None: | ||
|
r39366 | deltacomputer = deltautil.deltacomputer(self) | ||
|
r35756 | |||
|
r35755 | revinfo = _revisioninfo(node, p1, p2, btext, textlen, cachedelta, flags) | ||
|
r36765 | |||
|
r39368 | deltainfo = deltacomputer.finddeltainfo(revinfo, fh) | ||
|
r35652 | |||
|
r39369 | e = (offset_type(offset, flags), deltainfo.deltalen, textlen, | ||
deltainfo.base, link, p1r, p2r, node) | ||||
|
r38886 | self.index.append(e) | ||
|
r4981 | self.nodemap[node] = curr | ||
|
r4977 | |||
|
r40216 | # Reset the pure node cache start lookup offset to account for new | ||
# revision. | ||||
if self._nodepos is not None: | ||||
self._nodepos = curr | ||||
|
r5338 | entry = self._io.packentry(e, self.node, self.version, curr) | ||
|
r39369 | self._writeentry(transaction, ifh, dfh, entry, deltainfo.data, | ||
link, offset) | ||||
rawtext = btext[0] | ||||
|
r20217 | |||
|
r31755 | if alwayscache and rawtext is None: | ||
|
r39228 | rawtext = deltacomputer.buildtext(revinfo, fh) | ||
|
r26243 | |||
|
r35863 | if type(rawtext) == bytes: # only accept immutable objects | ||
|
r40088 | self._revisioncache = (node, curr, rawtext) | ||
|
r39369 | self._chainbasecache[curr] = deltainfo.chainbase | ||
|
r20217 | return node | ||
def _writeentry(self, transaction, ifh, dfh, entry, data, link, offset): | ||||
|
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. | ||||
|
r40661 | # Note: This is likely not necessary on Python 3. However, because | ||
# the file handle is reused for reads and may be seeked there, we need | ||||
# to be careful before changing this. | ||||
|
r27430 | ifh.seek(0, os.SEEK_END) | ||
|
r27441 | if dfh: | ||
|
r27430 | dfh.seek(0, os.SEEK_END) | ||
|
r20217 | curr = len(self) - 1 | ||
|
r4982 | if not self._inline: | ||
|
r2073 | transaction.add(self.datafile, offset) | ||
|
r4981 | transaction.add(self.indexfile, curr * len(entry)) | ||
|
r2073 | if data[0]: | ||
|
r3390 | dfh.write(data[0]) | ||
dfh.write(data[1]) | ||||
|
r4981 | ifh.write(entry) | ||
|
r2073 | else: | ||
|
r4996 | offset += curr * self._io.size | ||
|
r5324 | transaction.add(self.indexfile, offset, curr) | ||
|
r4981 | ifh.write(entry) | ||
|
r3390 | ifh.write(data[0]) | ||
ifh.write(data[1]) | ||||
|
r35992 | self._enforceinlinesize(transaction, ifh) | ||
|
r2073 | |||
|
r34292 | def addgroup(self, deltas, linkmapper, transaction, addrevisioncb=None): | ||
|
r1083 | """ | ||
add a delta group | ||||
|
r46 | |||
|
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. | ||||
|
r25822 | |||
If ``addrevisioncb`` is defined, it will be called with arguments of | ||||
this revlog and the node that was added. | ||||
|
r1083 | """ | ||
|
r40661 | if self._writinghandles: | ||
raise error.ProgrammingError('cannot nest addgroup() calls') | ||||
|
r32868 | nodes = [] | ||
|
r515 | |||
|
r12624 | r = len(self) | ||
end = 0 | ||||
|
r46 | if r: | ||
|
r12624 | end = self.end(r - 1) | ||
|
r35986 | ifh = self._indexfp("a+") | ||
|
r4996 | isize = r * self._io.size | ||
|
r4982 | if self._inline: | ||
|
r4996 | transaction.add(self.indexfile, end + isize, r) | ||
|
r2073 | dfh = None | ||
else: | ||||
|
r4996 | transaction.add(self.indexfile, isize, r) | ||
|
r2073 | transaction.add(self.datafile, end) | ||
|
r35985 | dfh = self._datafp("a+") | ||
|
r24255 | def flush(): | ||
if dfh: | ||||
dfh.flush() | ||||
ifh.flush() | ||||
|
r40661 | |||
self._writinghandles = (ifh, dfh) | ||||
|
r6261 | try: | ||
|
r39366 | deltacomputer = deltautil.deltacomputer(self) | ||
|
r6261 | # loop through our set of deltas | ||
|
r34147 | for data in deltas: | ||
|
r34292 | node, p1, p2, linknode, deltabase, delta, flags = data | ||
link = linkmapper(linknode) | ||||
|
r34147 | flags = flags or REVIDX_DEFAULT_FLAGS | ||
|
r12336 | |||
|
r32868 | nodes.append(node) | ||
|
r15890 | |||
|
r14196 | if node in self.nodemap: | ||
|
r39922 | self._nodeduplicatecallback(transaction, node) | ||
|
r6261 | # this can happen if two branches make the same change | ||
continue | ||||
|
r192 | |||
|
r6261 | for p in (p1, p2): | ||
|
r16686 | if p not in self.nodemap: | ||
|
r39811 | raise error.LookupError(p, self.indexfile, | ||
_('unknown parent')) | ||||
|
r46 | |||
|
r14141 | if deltabase not in self.nodemap: | ||
|
r39811 | raise error.LookupError(deltabase, self.indexfile, | ||
_('unknown delta base')) | ||||
|
r46 | |||
|
r14141 | baserev = self.rev(deltabase) | ||
|
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)) | ||||
|
r27433 | if not flags and self._peek_iscensored(baserev, delta, flush): | ||
|
r24255 | flags |= REVIDX_ISCENSORED | ||
|
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. | ||||
|
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. | ||||
|
r34146 | self._addrevision(node, None, transaction, link, | ||
p1, p2, flags, (baserev, delta), | ||||
ifh, dfh, | ||||
|
r35756 | alwayscache=bool(addrevisioncb), | ||
deltacomputer=deltacomputer) | ||||
|
r25822 | |||
if addrevisioncb: | ||||
|
r34146 | addrevisioncb(self, node) | ||
|
r25822 | |||
|
r12624 | if not dfh and not self._inline: | ||
# addrevision switched from inline to conventional | ||||
# reopen the index | ||||
|
r13400 | ifh.close() | ||
|
r35985 | dfh = self._datafp("a+") | ||
|
r35986 | ifh = self._indexfp("a+") | ||
|
r40661 | self._writinghandles = (ifh, dfh) | ||
|
r6261 | finally: | ||
|
r40661 | self._writinghandles = None | ||
|
r6261 | if dfh: | ||
dfh.close() | ||||
ifh.close() | ||||
|
r46 | |||
|
r32868 | return nodes | ||
|
r1493 | |||
|
r24118 | def iscensored(self, rev): | ||
"""Check if a file revision is censored.""" | ||||
|
r37461 | if not self._censorable: | ||
return False | ||||
return self.flags(rev) & REVIDX_ISCENSORED | ||||
|
r24118 | |||
|
r24255 | def _peek_iscensored(self, baserev, delta, flush): | ||
"""Quickly check if a delta produces a censored revision.""" | ||||
|
r37461 | if not self._censorable: | ||
return False | ||||
|
r40361 | return storageutil.deltaiscensored(delta, baserev, self.rawsize) | ||
|
r24255 | |||
|
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. | ||||
""" | ||||
|
r40040 | return storageutil.resolvestripinfo(minlink, len(self) - 1, | ||
self.headrevs(), | ||||
self.linkrev, self.parentrevs) | ||||
|
r20074 | |||
|
r8073 | def strip(self, minlink, transaction): | ||
|
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 | ||||
|
r15827 | removed and that it'll re-add them after this truncation. | ||
|
r5910 | """ | ||
|
r6750 | if len(self) == 0: | ||
|
r1535 | return | ||
|
r20074 | rev, _ = self.getstrippoint(minlink) | ||
if rev == len(self): | ||||
|
r5909 | return | ||
|
r1535 | |||
# first truncate the files on disk | ||||
end = self.start(rev) | ||||
|
r4982 | if not self._inline: | ||
|
r8073 | transaction.add(self.datafile, end) | ||
|
r4977 | end = rev * self._io.size | ||
|
r2073 | else: | ||
|
r4977 | end += rev * self._io.size | ||
|
r2072 | |||
|
r8073 | transaction.add(self.indexfile, end) | ||
|
r1535 | |||
# then reset internal state in memory to forget those revisions | ||||
|
r40088 | self._revisioncache = None | ||
|
r23306 | self._chaininfocache = {} | ||
|
r8650 | self._chunkclear() | ||
|
r38806 | for x in pycompat.xrange(rev, len(self)): | ||
|
r2072 | del self.nodemap[self.node(x)] | ||
|
r1535 | |||
|
r4979 | del self.index[rev:-1] | ||
|
r37512 | self._nodepos = None | ||
|
r1535 | |||
|
r1493 | def checksize(self): | ||
r42038 | """Check size of index and data files | |||
return a (dd, di) tuple. | ||||
- dd: extra bytes for the "data" file | ||||
- di: extra bytes for the "index" file | ||||
A healthy revlog will return (0, 0). | ||||
""" | ||||
|
r1493 | expected = 0 | ||
|
r6750 | if len(self): | ||
expected = max(0, self.end(len(self) - 1)) | ||||
|
r1667 | |||
|
r1494 | try: | ||
|
r35990 | with self._datafp() as f: | ||
|
r42767 | f.seek(0, io.SEEK_END) | ||
|
r35990 | actual = f.tell() | ||
|
r1667 | dd = actual - expected | ||
|
r25660 | except IOError as inst: | ||
|
r1667 | if inst.errno != errno.ENOENT: | ||
raise | ||||
dd = 0 | ||||
try: | ||||
f = self.opener(self.indexfile) | ||||
|
r42767 | f.seek(0, io.SEEK_END) | ||
|
r1667 | actual = f.tell() | ||
|
r13400 | f.close() | ||
|
r4977 | s = self._io.size | ||
|
r9029 | i = max(0, actual // s) | ||
|
r1667 | di = actual - (i * s) | ||
|
r4982 | if self._inline: | ||
|
r2073 | databytes = 0 | ||
|
r6750 | for r in self: | ||
|
r5312 | databytes += max(0, self.length(r)) | ||
|
r2073 | dd = 0 | ||
|
r6750 | di = actual - len(self) * s - databytes | ||
|
r25660 | except IOError as inst: | ||
|
r1667 | if inst.errno != errno.ENOENT: | ||
raise | ||||
di = 0 | ||||
return (dd, di) | ||||
|
r6891 | |||
def files(self): | ||||
|
r10282 | res = [self.indexfile] | ||
|
r6891 | if not self._inline: | ||
res.append(self.datafile) | ||||
return res | ||||
|
r30778 | |||
|
r39898 | def emitrevisions(self, nodes, nodesorder=None, revisiondata=False, | ||
|
r40457 | assumehaveparentrevisions=False, | ||
deltamode=repository.CG_DELTAMODE_STD): | ||||
|
r40483 | if nodesorder not in ('nodes', 'storage', 'linear', None): | ||
|
r39898 | raise error.ProgrammingError('unhandled value for nodesorder: %s' % | ||
nodesorder) | ||||
if nodesorder is None and not self._generaldelta: | ||||
nodesorder = 'storage' | ||||
|
r40457 | if (not self._storedeltachains and | ||
deltamode != repository.CG_DELTAMODE_PREV): | ||||
|
r40456 | deltamode = repository.CG_DELTAMODE_FULL | ||
|
r40044 | return storageutil.emitrevisions( | ||
|
r40046 | self, nodes, nodesorder, revlogrevisiondelta, | ||
|
r40044 | deltaparentfn=self.deltaparent, | ||
candeltafn=self.candelta, | ||||
rawsizefn=self.rawsize, | ||||
revdifffn=self.revdiff, | ||||
flagsfn=self.flags, | ||||
|
r40456 | deltamode=deltamode, | ||
|
r40044 | revisiondata=revisiondata, | ||
|
r40456 | assumehaveparentrevisions=assumehaveparentrevisions) | ||
|
r39898 | |||
|
r30778 | DELTAREUSEALWAYS = 'always' | ||
DELTAREUSESAMEREVS = 'samerevs' | ||||
DELTAREUSENEVER = 'never' | ||||
|
r35346 | DELTAREUSEFULLADD = 'fulladd' | ||
DELTAREUSEALL = {'always', 'samerevs', 'never', 'fulladd'} | ||||
|
r30778 | |||
def clone(self, tr, destrevlog, addrevisioncb=None, | ||||
r43266 | deltareuse=DELTAREUSESAMEREVS, forcedeltabothparents=None): | |||
|
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). | ||||
r43267 | DELTAREUSEFULLADD | |||
Revision will be re-added as if their were new content. This is | ||||
slower than DELTAREUSEALWAYS but allow more mechanism to kicks in. | ||||
eg: large file detection and handling. | ||||
|
r30778 | |||
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. | ||||
|
r40872 | In addition to the delta policy, the ``forcedeltabothparents`` | ||
argument controls whether to force compute deltas against both parents | ||||
for merges. By default, the current default is used. | ||||
|
r30778 | """ | ||
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')) | ||||
r42023 | # lazydelta and lazydeltabase controls whether to reuse a cached delta, | |||
# if possible. | ||||
oldlazydelta = destrevlog._lazydelta | ||||
|
r30778 | oldlazydeltabase = destrevlog._lazydeltabase | ||
|
r38759 | oldamd = destrevlog._deltabothparents | ||
|
r30778 | |||
try: | ||||
if deltareuse == self.DELTAREUSEALWAYS: | ||||
destrevlog._lazydeltabase = True | ||||
r42023 | destrevlog._lazydelta = True | |||
|
r30778 | elif deltareuse == self.DELTAREUSESAMEREVS: | ||
destrevlog._lazydeltabase = False | ||||
r42023 | destrevlog._lazydelta = True | |||
elif deltareuse == self.DELTAREUSENEVER: | ||||
destrevlog._lazydeltabase = False | ||||
destrevlog._lazydelta = False | ||||
|
r30778 | |||
|
r40872 | destrevlog._deltabothparents = forcedeltabothparents or oldamd | ||
|
r30778 | |||
r43266 | self._clone(tr, destrevlog, addrevisioncb, deltareuse, | |||
forcedeltabothparents) | ||||
|
r30778 | finally: | ||
r42023 | destrevlog._lazydelta = oldlazydelta | |||
|
r30778 | destrevlog._lazydeltabase = oldlazydeltabase | ||
|
r38759 | destrevlog._deltabothparents = oldamd | ||
|
r39814 | |||
r43266 | def _clone(self, tr, destrevlog, addrevisioncb, deltareuse, | |||
forcedeltabothparents): | ||||
"""perform the core duty of `revlog.clone` after parameter processing""" | ||||
deltacomputer = deltautil.deltacomputer(destrevlog) | ||||
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 | ||||
rawtext = None | ||||
if deltareuse == self.DELTAREUSEFULLADD: | ||||
r43268 | text = self.revision(rev) | |||
destrevlog.addrevision(text, tr, linkrev, p1, p2, | ||||
r43266 | cachedelta=cachedelta, | |||
node=node, flags=flags, | ||||
deltacomputer=deltacomputer) | ||||
else: | ||||
r43268 | if destrevlog._lazydelta: | |||
dp = self.deltaparent(rev) | ||||
if dp != nullrev: | ||||
cachedelta = (dp, bytes(self._chunk(rev))) | ||||
if not cachedelta: | ||||
rawtext = self.rawdata(rev) | ||||
r43266 | 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, | ||||
p2, flags, cachedelta, ifh, dfh, | ||||
deltacomputer=deltacomputer) | ||||
finally: | ||||
if dfh: | ||||
dfh.close() | ||||
ifh.close() | ||||
if addrevisioncb: | ||||
addrevisioncb(self, rev, node) | ||||
|
r40092 | def censorrevision(self, tr, censornode, tombstone=b''): | ||
|
r39814 | if (self.version & 0xFFFF) == REVLOGV0: | ||
raise error.RevlogError(_('cannot censor with version %d revlogs') % | ||||
self.version) | ||||
|
r40092 | censorrev = self.rev(censornode) | ||
|
r39914 | tombstone = storageutil.packmeta({b'censored': tombstone}, b'') | ||
|
r39814 | |||
|
r40092 | if len(tombstone) > self.rawsize(censorrev): | ||
|
r39814 | raise error.Abort(_('censor tombstone must be no longer than ' | ||
'censored data')) | ||||
|
r40092 | # Rewriting the revlog in place is hard. Our strategy for censoring is | ||
# to create a new revlog, copy all revisions to it, then replace the | ||||
# revlogs on transaction close. | ||||
|
r39814 | |||
|
r40092 | newindexfile = self.indexfile + b'.tmpcensored' | ||
newdatafile = self.datafile + b'.tmpcensored' | ||||
|
r39814 | |||
|
r40092 | # This is a bit dangerous. We could easily have a mismatch of state. | ||
newrl = revlog(self.opener, newindexfile, newdatafile, | ||||
censorable=True) | ||||
newrl.version = self.version | ||||
newrl._generaldelta = self._generaldelta | ||||
newrl._io = self._io | ||||
|
r39814 | |||
|
r40092 | for rev in self.revs(): | ||
node = self.node(rev) | ||||
p1, p2 = self.parents(node) | ||||
|
r39814 | |||
|
r40092 | if rev == censorrev: | ||
newrl.addrawrevision(tombstone, tr, self.linkrev(censorrev), | ||||
p1, p2, censornode, REVIDX_ISCENSORED) | ||||
|
r39814 | |||
|
r40092 | if newrl.deltaparent(rev) != nullrev: | ||
raise error.Abort(_('censored revision stored as delta; ' | ||||
'cannot censor'), | ||||
hint=_('censoring of revlogs is not ' | ||||
'fully implemented; please report ' | ||||
'this bug')) | ||||
continue | ||||
|
r39814 | |||
|
r40092 | if self.iscensored(rev): | ||
if self.deltaparent(rev) != nullrev: | ||||
raise error.Abort(_('cannot censor due to censored ' | ||||
'revision having delta stored')) | ||||
rawtext = self._chunk(rev) | ||||
|
r39814 | else: | ||
r43036 | rawtext = self.rawdata(rev) | |||
|
r40092 | |||
newrl.addrawrevision(rawtext, tr, self.linkrev(rev), p1, p2, node, | ||||
self.flags(rev)) | ||||
|
r39814 | |||
|
r40092 | tr.addbackup(self.indexfile, location='store') | ||
if not self._inline: | ||||
tr.addbackup(self.datafile, location='store') | ||||
self.opener.rename(newrl.indexfile, self.indexfile) | ||||
if not self._inline: | ||||
self.opener.rename(newrl.datafile, self.datafile) | ||||
self.clearcaches() | ||||
|
r41240 | self._loadindex() | ||
|
r39878 | |||
def verifyintegrity(self, state): | ||||
"""Verifies the integrity of the revlog. | ||||
Yields ``revlogproblem`` instances describing problems that are | ||||
found. | ||||
""" | ||||
dd, di = self.checksize() | ||||
if dd: | ||||
yield revlogproblem(error=_('data length off by %d bytes') % dd) | ||||
if di: | ||||
yield revlogproblem(error=_('index contains %d extra bytes') % di) | ||||
|
r39881 | version = self.version & 0xFFFF | ||
# The verifier tells us what version revlog we should be. | ||||
if version != state['expectedversion']: | ||||
yield revlogproblem( | ||||
warning=_("warning: '%s' uses revlog format %d; expected %d") % | ||||
(self.indexfile, version, state['expectedversion'])) | ||||
|
r39905 | |||
|
r39908 | state['skipread'] = set() | ||
for rev in self: | ||||
node = self.node(rev) | ||||
# Verify contents. 4 cases to care about: | ||||
# | ||||
# common: the most common case | ||||
# rename: with a rename | ||||
# meta: file content starts with b'\1\n', the metadata | ||||
# header defined in filelog.py, but without a rename | ||||
# ext: content stored externally | ||||
# | ||||
# More formally, their differences are shown below: | ||||
# | ||||
# | common | rename | meta | ext | ||||
# ------------------------------------------------------- | ||||
# flags() | 0 | 0 | 0 | not 0 | ||||
# renamed() | False | True | False | ? | ||||
# rawtext[0:2]=='\1\n'| False | True | True | ? | ||||
# | ||||
# "rawtext" means the raw text stored in revlog data, which | ||||
r43036 | # could be retrieved by "rawdata(rev)". "text" | |||
# mentioned below is "revision(rev)". | ||||
|
r39908 | # | ||
# There are 3 different lengths stored physically: | ||||
# 1. L1: rawsize, stored in revlog index | ||||
# 2. L2: len(rawtext), stored in revlog data | ||||
# 3. L3: len(text), stored in revlog data if flags==0, or | ||||
# possibly somewhere else if flags!=0 | ||||
# | ||||
# L1 should be equal to L2. L3 could be different from them. | ||||
# "text" may or may not affect commit hash depending on flag | ||||
r42958 | # processors (see flagutil.addflagprocessor). | |||
|
r39908 | # | ||
# | common | rename | meta | ext | ||||
# ------------------------------------------------- | ||||
# rawsize() | L1 | L1 | L1 | L1 | ||||
# size() | L1 | L2-LM | L1(*) | L1 (?) | ||||
# len(rawtext) | L2 | L2 | L2 | L2 | ||||
# len(text) | L2 | L2 | L2 | L3 | ||||
# len(read()) | L2 | L2-LM | L2-LM | L3 (?) | ||||
# | ||||
# LM: length of metadata, depending on rawtext | ||||
# (*): not ideal, see comment in filelog.size | ||||
# (?): could be "- len(meta)" if the resolved content has | ||||
# rename metadata | ||||
# | ||||
# Checks needed to be done: | ||||
# 1. length check: L1 == L2, in all cases. | ||||
# 2. hash check: depending on flag processor, we may need to | ||||
# use either "text" (external), or "rawtext" (in revlog). | ||||
try: | ||||
skipflags = state.get('skipflags', 0) | ||||
if skipflags: | ||||
skipflags &= self.flags(rev) | ||||
if skipflags: | ||||
state['skipread'].add(node) | ||||
else: | ||||
# Side-effect: read content and verify hash. | ||||
self.revision(node) | ||||
l1 = self.rawsize(rev) | ||||
r43036 | l2 = len(self.rawdata(node)) | |||
|
r39908 | |||
if l1 != l2: | ||||
yield revlogproblem( | ||||
error=_('unpacked size is %d, %d expected') % (l2, l1), | ||||
node=node) | ||||
except error.CensoredNodeError: | ||||
if state['erroroncensored']: | ||||
yield revlogproblem(error=_('censored file data'), | ||||
node=node) | ||||
state['skipread'].add(node) | ||||
except Exception as e: | ||||
yield revlogproblem( | ||||
|
r39944 | error=_('unpacking %s: %s') % (short(node), | ||
stringutil.forcebytestr(e)), | ||||
|
r39908 | node=node) | ||
state['skipread'].add(node) | ||||
|
r39905 | def storageinfo(self, exclusivefiles=False, sharedfiles=False, | ||
revisionscount=False, trackedsize=False, | ||||
storedsize=False): | ||||
d = {} | ||||
if exclusivefiles: | ||||
d['exclusivefiles'] = [(self.opener, self.indexfile)] | ||||
if not self._inline: | ||||
d['exclusivefiles'].append((self.opener, self.datafile)) | ||||
if sharedfiles: | ||||
d['sharedfiles'] = [] | ||||
if revisionscount: | ||||
d['revisionscount'] = len(self) | ||||
if trackedsize: | ||||
d['trackedsize'] = sum(map(self.rawsize, iter(self))) | ||||
if storedsize: | ||||
d['storedsize'] = sum(self.opener.stat(path).st_size | ||||
for path in self.files()) | ||||
return d | ||||