revlog.py
3307 lines
| 117.2 KiB
| text/x-python
|
PythonLexer
/ mercurial / revlog.py
|
r8226 | # revlog.py - storage back-end for mercurial | ||
r48181 | # coding: utf8 | |||
|
r8226 | # | ||
|
r47575 | # Copyright 2005-2007 Olivia Mackall <olivia@selenic.com> | ||
|
r8226 | # | ||
# 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 | |||
|
r47611 | import binascii | ||
|
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, | ||||
nullrev, | ||||
|
r47538 | sha1nodeconstants, | ||
|
r39908 | short, | ||
|
r32402 | wdirrev, | ||
|
r27361 | ) | ||
from .i18n import _ | ||||
|
r43359 | from .pycompat import getattr | ||
|
r39365 | from .revlogutils.constants import ( | ||
r47838 | ALL_KINDS, | |||
r48040 | CHANGELOGV2, | |||
r48029 | COMP_MODE_DEFAULT, | |||
r48023 | COMP_MODE_INLINE, | |||
r48027 | COMP_MODE_PLAIN, | |||
r49606 | ENTRY_RANK, | |||
r48005 | FEATURES_BY_VERSION, | |||
|
r39365 | FLAG_GENERALDELTA, | ||
FLAG_INLINE_DATA, | ||||
r47618 | INDEX_HEADER, | |||
r48037 | KIND_CHANGELOG, | |||
r49606 | RANK_UNKNOWN, | |||
|
r39365 | REVLOGV0, | ||
REVLOGV1, | ||||
REVLOGV1_FLAGS, | ||||
REVLOGV2, | ||||
REVLOGV2_FLAGS, | ||||
REVLOG_DEFAULT_FLAGS, | ||||
REVLOG_DEFAULT_FORMAT, | ||||
REVLOG_DEFAULT_VERSION, | ||||
r48004 | SUPPORTED_FLAGS, | |||
|
r39365 | ) | ||
r42954 | from .revlogutils.flagutil import ( | |||
REVIDX_DEFAULT_FLAGS, | ||||
REVIDX_ELLIPSIS, | ||||
REVIDX_EXTSTORED, | ||||
REVIDX_FLAGS_ORDER, | ||||
r46263 | REVIDX_HASCOPIESINFO, | |||
r42954 | REVIDX_ISCENSORED, | |||
REVIDX_RAWTEXT_CHANGING_FLAGS, | ||||
) | ||||
|
r43346 | from .thirdparty import attr | ||
|
r27361 | from . import ( | ||
ancestor, | ||||
|
r39898 | dagop, | ||
|
r27361 | error, | ||
mdiff, | ||||
|
r32372 | policy, | ||
|
r31574 | pycompat, | ||
r48186 | revlogutils, | |||
|
r27361 | templatefilters, | ||
util, | ||||
) | ||||
|
r43078 | from .interfaces import ( | ||
repository, | ||||
|
r43079 | util as interfaceutil, | ||
|
r43078 | ) | ||
|
r39366 | from .revlogutils import ( | ||
deltas as deltautil, | ||||
r48008 | docket as docketutil, | |||
r42955 | flagutil, | |||
r44486 | nodemap as nodemaputil, | |||
|
r48218 | randomaccessfile, | ||
r47812 | revlogv0, | |||
r48257 | rewrite, | |||
r43305 | sidedata as sidedatautil, | |||
|
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. | ||||
|
r47847 | |||
|
r39365 | REVLOGV0 | ||
REVLOGV1 | ||||
REVLOGV2 | ||||
|
r49618 | CHANGELOGV2 | ||
|
r39365 | FLAG_INLINE_DATA | ||
FLAG_GENERALDELTA | ||||
REVLOG_DEFAULT_FLAGS | ||||
REVLOG_DEFAULT_FORMAT | ||||
REVLOG_DEFAULT_VERSION | ||||
REVLOGV1_FLAGS | ||||
REVLOGV2_FLAGS | ||||
REVIDX_ISCENSORED | ||||
REVIDX_ELLIPSIS | ||||
r46263 | REVIDX_HASCOPIESINFO | |||
|
r39365 | REVIDX_EXTSTORED | ||
REVIDX_DEFAULT_FLAGS | ||||
REVIDX_FLAGS_ORDER | ||||
REVIDX_RAWTEXT_CHANGING_FLAGS | ||||
|
r43906 | parsers = policy.importmod('parsers') | ||
rustancestor = policy.importrust('ancestor') | ||||
rustdagop = policy.importrust('dagop') | ||||
|
r44466 | rustrevlog = policy.importrust('revlog') | ||
|
r32372 | |||
|
r30817 | # Aliased for performance. | ||
_zlibdecompress = zlib.decompress | ||||
|
r5007 | |||
|
r10916 | # max size of revlog with inline data | ||
_maxinline = 131072 | ||||
|
r10913 | |||
|
r39803 | # Flag processors for REVIDX_ELLIPSIS. | ||
def ellipsisreadprocessor(rl, text): | ||||
|
r47443 | return text, False | ||
def ellipsiswriteprocessor(rl, text): | ||||
|
r39803 | return text, False | ||
|
r43346 | |||
|
r39803 | def ellipsisrawprocessor(rl, text): | ||
return False | ||||
|
r43346 | |||
|
r39803 | ellipsisprocessor = ( | ||
ellipsisreadprocessor, | ||||
ellipsiswriteprocessor, | ||||
ellipsisrawprocessor, | ||||
) | ||||
|
r43346 | |||
|
r44409 | def _verify_revision(rl, skipflags, state, node): | ||
"""Verify the integrity of the given revlog ``node`` while providing a hook | ||||
point for extensions to influence the operation.""" | ||||
if skipflags: | ||||
state[b'skipread'].add(node) | ||||
else: | ||||
# Side-effect: read content and verify hash. | ||||
rl.revision(node) | ||||
r47028 | # True if a fast implementation for persistent-nodemap is available | |||
# | ||||
# We also consider we have a "fast" implementation in "pure" python because | ||||
# people using pure don't really have performance consideration (and a | ||||
# wheelbarrow of other slowness source) | ||||
HAS_FAST_PERSISTENT_NODEMAP = rustrevlog is not None or util.safehasattr( | ||||
parsers, 'BaseIndexObject' | ||||
) | ||||
|
r39267 | @interfaceutil.implementer(repository.irevisiondelta) | ||
|
r39898 | @attr.s(slots=True) | ||
|
r49801 | class revlogrevisiondelta: | ||
|
r39267 | node = attr.ib() | ||
p1node = attr.ib() | ||||
p2node = attr.ib() | ||||
basenode = attr.ib() | ||||
flags = attr.ib() | ||||
baserevisionsize = attr.ib() | ||||
revision = attr.ib() | ||||
delta = attr.ib() | ||||
|
r47446 | sidedata = attr.ib() | ||
|
r47843 | protocol_flags = attr.ib() | ||
|
r39898 | linknode = attr.ib(default=None) | ||
|
r39267 | |||
|
r43346 | |||
|
r39878 | @interfaceutil.implementer(repository.iverifyproblem) | ||
@attr.s(frozen=True) | ||||
|
r49801 | class revlogproblem: | ||
|
r39878 | warning = attr.ib(default=None) | ||
error = attr.ib(default=None) | ||||
|
r39908 | node = attr.ib(default=None) | ||
|
r39878 | |||
|
r43346 | |||
r47810 | def parse_index_v1(data, inline): | |||
# call the C implementation to parse the index data | ||||
index, cache = parsers.parse_index2(data, inline) | ||||
return index, cache | ||||
def parse_index_v2(data, inline): | ||||
# call the C implementation to parse the index data | ||||
|
r49618 | index, cache = parsers.parse_index2(data, inline, format=REVLOGV2) | ||
r47810 | return index, cache | |||
r48044 | def parse_index_cl_v2(data, inline): | |||
# call the C implementation to parse the index data | ||||
|
r49618 | index, cache = parsers.parse_index2(data, inline, format=CHANGELOGV2) | ||
r48044 | return index, cache | |||
r47810 | if util.safehasattr(parsers, 'parse_index_devel_nodemap'): | |||
def parse_index_v1_nodemap(data, inline): | ||||
index, cache = parsers.parse_index_devel_nodemap(data, inline) | ||||
return index, cache | ||||
else: | ||||
parse_index_v1_nodemap = None | ||||
def parse_index_v1_mixed(data, inline): | ||||
index, cache = parse_index_v1(data, inline) | ||||
return rustrevlog.MixedIndex(index), cache | ||||
|
r4972 | |||
|
r43346 | |||
|
r25410 | # corresponds to uncompressed length of indexformatng (2 gigs, 4-byte | ||
# signed integer) | ||||
|
r43346 | _maxentrysize = 0x7FFFFFFF | ||
r48181 | FILE_TOO_SHORT_MSG = _( | |||
b'cannot read from revlog %s;' | ||||
b' expected %d bytes from offset %d, data size is %d' | ||||
) | ||||
|
r25410 | |||
|
r49801 | class revlog: | ||
|
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. | ||||
|
r47349 | |||
`concurrencychecker` is an optional function that receives 3 arguments: a | ||||
file handle, a filename, and an expected position. It should check whether | ||||
the current position in the file handle is valid, and log/warn/fail (by | ||||
raising). | ||||
r48020 | ||||
r48185 | See mercurial/revlogutils/contants.py for details about the content of an | |||
index entry. | ||||
|
r1083 | """ | ||
r43264 | ||||
_flagserrorclass = error.RevlogError | ||||
|
r43346 | def __init__( | ||
self, | ||||
opener, | ||||
r47838 | target, | |||
r47921 | radix, | |||
r48014 | postfix=None, # only exist for `tmpcensored` now | |||
|
r43346 | checkambig=False, | ||
mmaplargeindex=False, | ||||
censorable=False, | ||||
upperboundcomp=None, | ||||
r44789 | persistentnodemap=False, | |||
|
r47349 | concurrencychecker=None, | ||
r48014 | trypending=False, | |||
|
r43346 | ): | ||
|
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 | ||||
r47838 | `target`: a (KIND, ID) tuple that identify the content stored in | |||
this revlog. It help the rest of the code to understand what the revlog | ||||
is about without having to resort to heuristic and index filename | ||||
analysis. Note: that this must be reliably be set by normal code, but | ||||
that test, debug, or performance measurement code might not set this to | ||||
accurate value. | ||||
|
r1083 | """ | ||
r42662 | self.upperboundcomp = upperboundcomp | |||
r47921 | ||||
self.radix = radix | ||||
r48008 | self._docket_file = None | |||
r47939 | self._indexfile = None | |||
self._datafile = None | ||||
r48181 | self._sidedatafile = None | |||
r47935 | self._nodemap_file = None | |||
r47916 | self.postfix = postfix | |||
r48014 | self._trypending = trypending | |||
r47922 | self.opener = opener | |||
r44789 | if persistentnodemap: | |||
r47935 | self._nodemap_file = nodemaputil.get_nodemap_file(self) | |||
r47922 | ||||
r47838 | assert target[0] in ALL_KINDS | |||
assert len(target) == 2 | ||||
self.target = target | ||||
|
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. | ||
|
r43347 | self._chunkcache = (0, b'') | ||
|
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 | ||
r43925 | self.index = None | |||
r48008 | self._docket = None | |||
r44804 | self._nodemap_docket = None | |||
|
r27070 | # Mapping of partial identifiers to full nodes. | ||
|
r13258 | self._pcache = {} | ||
|
r27070 | # Mapping of revision integer to full node. | ||
|
r43347 | self._compengine = b'zlib' | ||
r42210 | self._compengineopts = {} | |||
r33202 | self._maxdeltachainspan = -1 | |||
|
r34825 | self._withsparseread = False | ||
|
r38739 | self._sparserevlog = False | ||
r47996 | self.hassidedata = 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 | |||
r48181 | # 3-tuple of file handles being used for active writing. | |||
|
r40661 | self._writinghandles = None | ||
r47988 | # prevent nesting of addgroup | |||
self._adding_group = None | ||||
|
r40661 | |||
|
r41240 | self._loadindex() | ||
|
r47349 | self._concurrencychecker = concurrencychecker | ||
r47915 | def _init_opts(self): | |||
"""process options (from above/config) to setup associated default revlog mode | ||||
These values might be affected when actually reading on disk information. | ||||
The relevant values are returned for use in _loadindex(). | ||||
* newversionflags: | ||||
version header to use if we need to create a new revlog | ||||
* mmapindexthreshold: | ||||
minimal index size for start to use mmap | ||||
* force_nodemap: | ||||
force the usage of a "development" version of the nodemap code | ||||
""" | ||||
|
r34297 | mmapindexthreshold = None | ||
r43295 | opts = self.opener.options | |||
|
r41236 | |||
r48037 | if b'changelogv2' in opts and self.revlog_kind == KIND_CHANGELOG: | |||
r48040 | new_header = CHANGELOGV2 | |||
r48037 | elif b'revlogv2' in opts: | |||
r48035 | new_header = REVLOGV2 | |||
|
r43347 | elif b'revlogv1' in opts: | ||
r47942 | new_header = REVLOGV1 | FLAG_INLINE_DATA | |||
|
r43347 | if b'generaldelta' in opts: | ||
r47942 | new_header |= FLAG_GENERALDELTA | |||
|
r43347 | elif b'revlogv0' in self.opener.options: | ||
r47942 | new_header = REVLOGV0 | |||
|
r41236 | else: | ||
r47942 | new_header = REVLOG_DEFAULT_VERSION | |||
|
r41236 | |||
|
r43347 | if b'chunkcachesize' in opts: | ||
self._chunkcachesize = opts[b'chunkcachesize'] | ||||
if b'maxchainlen' in opts: | ||||
self._maxchainlen = opts[b'maxchainlen'] | ||||
if b'deltabothparents' in opts: | ||||
self._deltabothparents = opts[b'deltabothparents'] | ||||
self._lazydelta = bool(opts.get(b'lazydelta', True)) | ||||
r41985 | self._lazydeltabase = False | |||
if self._lazydelta: | ||||
|
r43347 | self._lazydeltabase = bool(opts.get(b'lazydeltabase', False)) | ||
if b'compengine' in opts: | ||||
self._compengine = opts[b'compengine'] | ||||
if b'zlib.level' in opts: | ||||
self._compengineopts[b'zlib.level'] = opts[b'zlib.level'] | ||||
if b'zstd.level' in opts: | ||||
self._compengineopts[b'zstd.level'] = opts[b'zstd.level'] | ||||
if b'maxdeltachainspan' in opts: | ||||
self._maxdeltachainspan = opts[b'maxdeltachainspan'] | ||||
if self._mmaplargeindex and b'mmapindexthreshold' in opts: | ||||
mmapindexthreshold = opts[b'mmapindexthreshold'] | ||||
self._sparserevlog = bool(opts.get(b'sparse-revlog', False)) | ||||
withsparseread = bool(opts.get(b'with-sparse-read', False)) | ||||
|
r41236 | # sparse-revlog forces sparse-read | ||
self._withsparseread = self._sparserevlog or withsparseread | ||||
|
r43347 | if b'sparse-read-density-threshold' in opts: | ||
self._srdensitythreshold = opts[b'sparse-read-density-threshold'] | ||||
if b'sparse-read-min-gap-size' in opts: | ||||
self._srmingapsize = opts[b'sparse-read-min-gap-size'] | ||||
if opts.get(b'enableellipsis'): | ||||
|
r41236 | self._flagprocessors[REVIDX_ELLIPSIS] = ellipsisprocessor | ||
# revlog v0 doesn't have flag processors | ||||
|
r49783 | for flag, processor in opts.get(b'flagprocessors', {}).items(): | ||
r42957 | flagutil.insertflagprocessor(flag, processor, self._flagprocessors) | |||
|
r40303 | |||
|
r20180 | if self._chunkcachesize <= 0: | ||
|
r43346 | raise error.RevlogError( | ||
|
r43387 | _(b'revlog chunk cache size %r is not greater than 0') | ||
|
r43346 | % self._chunkcachesize | ||
) | ||||
|
r20180 | elif self._chunkcachesize & (self._chunkcachesize - 1): | ||
|
r43346 | raise error.RevlogError( | ||
|
r43387 | _(b'revlog chunk cache size %r is not a power of 2') | ||
|
r43346 | % self._chunkcachesize | ||
) | ||||
r47915 | force_nodemap = opts.get(b'devel-force-nodemap', False) | |||
r47942 | return new_header, mmapindexthreshold, force_nodemap | |||
r47915 | ||||
r48012 | def _get_data(self, filepath, mmap_threshold, size=None): | |||
r47940 | """return a file content with or without mmap | |||
If the file is missing return the empty string""" | ||||
try: | ||||
with self.opener(filepath) as fp: | ||||
if mmap_threshold is not None: | ||||
file_size = self.opener.fstat(fp).st_size | ||||
if file_size >= mmap_threshold: | ||||
r48012 | if size is not None: | |||
# avoid potentiel mmap crash | ||||
size = min(file_size, size) | ||||
r47940 | # TODO: should .close() to release resources without | |||
# relying on Python GC | ||||
r48012 | if size is None: | |||
return util.buffer(util.mmapread(fp)) | ||||
else: | ||||
return util.buffer(util.mmapread(fp, size)) | ||||
if size is None: | ||||
return fp.read() | ||||
else: | ||||
return fp.read(size) | ||||
r47940 | except IOError as inst: | |||
if inst.errno != errno.ENOENT: | ||||
raise | ||||
return b'' | ||||
r48194 | def _loadindex(self, docket=None): | |||
r47915 | ||||
r47942 | new_header, mmapindexthreshold, force_nodemap = self._init_opts() | |||
r47939 | ||||
r48014 | if self.postfix is not None: | |||
entry_point = b'%s.i.%s' % (self.radix, self.postfix) | ||||
elif self._trypending and self.opener.exists(b'%s.i.a' % self.radix): | ||||
entry_point = b'%s.i.a' % self.radix | ||||
else: | ||||
r47946 | entry_point = b'%s.i' % self.radix | |||
r47939 | ||||
r48194 | if docket is not None: | |||
self._docket = docket | ||||
self._docket_file = entry_point | ||||
r47940 | else: | |||
r48194 | entry_data = b'' | |||
self._initempty = True | ||||
entry_data = self._get_data(entry_point, mmapindexthreshold) | ||||
if len(entry_data) > 0: | ||||
header = INDEX_HEADER.unpack(entry_data[:4])[0] | ||||
self._initempty = False | ||||
r48008 | else: | |||
r48194 | header = new_header | |||
self._format_flags = header & ~0xFFFF | ||||
self._format_version = header & 0xFFFF | ||||
supported_flags = SUPPORTED_FLAGS.get(self._format_version) | ||||
if supported_flags is None: | ||||
msg = _(b'unknown version (%d) in revlog %s') | ||||
msg %= (self._format_version, self.display_id) | ||||
raise error.RevlogError(msg) | ||||
elif self._format_flags & ~supported_flags: | ||||
msg = _(b'unknown flags (%#04x) in version %d revlog %s') | ||||
display_flag = self._format_flags >> 16 | ||||
msg %= (display_flag, self._format_version, self.display_id) | ||||
raise error.RevlogError(msg) | ||||
features = FEATURES_BY_VERSION[self._format_version] | ||||
self._inline = features[b'inline'](self._format_flags) | ||||
self._generaldelta = features[b'generaldelta'](self._format_flags) | ||||
self.hassidedata = features[b'sidedata'] | ||||
if not features[b'docket']: | ||||
self._indexfile = entry_point | ||||
index_data = entry_data | ||||
else: | ||||
self._docket_file = entry_point | ||||
if self._initempty: | ||||
self._docket = docketutil.default_docket(self, header) | ||||
else: | ||||
self._docket = docketutil.parse_docket( | ||||
self, entry_data, use_pending=self._trypending | ||||
) | ||||
if self._docket is not None: | ||||
r48008 | self._indexfile = self._docket.index_filepath() | |||
r48012 | index_data = b'' | |||
index_size = self._docket.index_end | ||||
if index_size > 0: | ||||
index_data = self._get_data( | ||||
self._indexfile, mmapindexthreshold, size=index_size | ||||
) | ||||
if len(index_data) < index_size: | ||||
msg = _(b'too few index data for %s: got %d, expected %d') | ||||
msg %= (self.display_id, len(index_data), index_size) | ||||
raise error.RevlogError(msg) | ||||
r48008 | self._inline = False | |||
# generaldelta implied by version 2 revlogs. | ||||
self._generaldelta = True | ||||
# the logic for persistent nodemap will be dealt with within the | ||||
# main docket, so disable it for now. | ||||
self._nodemap_file = None | ||||
r47946 | ||||
r48115 | if self._docket is not None: | |||
self._datafile = self._docket.data_filepath() | ||||
r48181 | self._sidedatafile = self._docket.sidedata_filepath() | |||
r48115 | elif self.postfix is None: | |||
r47946 | self._datafile = b'%s.d' % self.radix | |||
else: | ||||
self._datafile = b'%s.d.%s' % (self.radix, self.postfix) | ||||
|
r47538 | self.nodeconstants = sha1nodeconstants | ||
self.nullid = self.nodeconstants.nullid | ||||
|
r41525 | # sparse-revlog can't be on without general-delta (issue6056) | ||
if not self._generaldelta: | ||||
self._sparserevlog = False | ||||
|
r4985 | |||
|
r39268 | self._storedeltachains = True | ||
|
r30154 | |||
r44794 | devel_nodemap = ( | |||
r47935 | self._nodemap_file | |||
r47915 | and force_nodemap | |||
r47810 | and parse_index_v1_nodemap is not None | |||
r44794 | ) | |||
r45000 | use_rust_index = False | |||
if rustrevlog is not None: | ||||
r47935 | if self._nodemap_file is not None: | |||
r45000 | use_rust_index = True | |||
else: | ||||
use_rust_index = self.opener.options.get(b'rust.index') | ||||
r47810 | self._parse_index = parse_index_v1 | |||
r47910 | if self._format_version == REVLOGV0: | |||
r47812 | self._parse_index = revlogv0.parse_index_v0 | |||
r47944 | elif self._format_version == REVLOGV2: | |||
r47810 | self._parse_index = parse_index_v2 | |||
r48040 | elif self._format_version == CHANGELOGV2: | |||
r48044 | self._parse_index = parse_index_cl_v2 | |||
r44794 | elif devel_nodemap: | |||
r47810 | self._parse_index = parse_index_v1_nodemap | |||
r45000 | elif use_rust_index: | |||
r47810 | self._parse_index = parse_index_v1_mixed | |||
|
r13265 | try: | ||
r47947 | d = self._parse_index(index_data, self._inline) | |||
|
r48218 | index, chunkcache = d | ||
r44801 | use_nodemap = ( | |||
not self._inline | ||||
r47935 | and self._nodemap_file is not None | |||
r44801 | and util.safehasattr(index, 'update_nodemap_data') | |||
) | ||||
if use_nodemap: | ||||
nodemap_data = nodemaputil.persisted_data(self) | ||||
if nodemap_data is not None: | ||||
r45002 | docket = nodemap_data[0] | |||
r45481 | if ( | |||
len(d[0]) > docket.tip_rev | ||||
and d[0][docket.tip_rev][7] == docket.tip_node | ||||
): | ||||
r45002 | # no changelog tampering | |||
self._nodemap_docket = docket | ||||
index.update_nodemap_data(*nodemap_data) | ||||
|
r13265 | except (ValueError, IndexError): | ||
|
r43347 | raise error.RevlogError( | ||
r47929 | _(b"index %s is corrupted") % self.display_id | |||
|
r43347 | ) | ||
|
r48218 | self.index = index | ||
self._segmentfile = randomaccessfile.randomaccessfile( | ||||
self.opener, | ||||
(self._indexfile if self._inline else self._datafile), | ||||
self._chunkcachesize, | ||||
chunkcache, | ||||
) | ||||
|
r48219 | self._segmentfile_sidedata = randomaccessfile.randomaccessfile( | ||
self.opener, | ||||
self._sidedatafile, | ||||
self._chunkcachesize, | ||||
) | ||||
|
r23306 | # revnum -> (chain-length, sum-delta-length) | ||
|
r46364 | self._chaininfocache = util.lrucachedict(500) | ||
|
r30817 | # revlog header -> revlog compressor | ||
self._decompressors = {} | ||||
|
r116 | |||
|
r30795 | @util.propertycache | ||
r47839 | def revlog_kind(self): | |||
return self.target[0] | ||||
@util.propertycache | ||||
r47924 | def display_id(self): | |||
"""The public facing "ID" of the revlog that we use in message""" | ||||
# Maybe we should build a user facing representation of | ||||
# revlog.target instead of using `self.radix` | ||||
return self.radix | ||||
r48028 | def _get_decompressor(self, t): | |||
try: | ||||
compressor = self._decompressors[t] | ||||
except KeyError: | ||||
try: | ||||
engine = util.compengines.forrevlogheader(t) | ||||
compressor = engine.revlogcompressor(self._compengineopts) | ||||
self._decompressors[t] = compressor | ||||
except KeyError: | ||||
raise error.RevlogError( | ||||
_(b'unknown compression type %s') % binascii.hexlify(t) | ||||
) | ||||
return compressor | ||||
r47924 | @util.propertycache | |||
|
r30795 | def _compressor(self): | ||
r42210 | engine = util.compengines[self._compengine] | |||
return engine.revlogcompressor(self._compengineopts) | ||||
|
r30795 | |||
r48029 | @util.propertycache | |||
def _decompressor(self): | ||||
"""the default decompressor""" | ||||
if self._docket is None: | ||||
return None | ||||
t = self._docket.default_compression_header | ||||
c = self._get_decompressor(t) | ||||
return c.decompress | ||||
r47993 | def _indexfp(self): | |||
|
r35986 | """file object for the revlog's index file""" | ||
r47993 | return self.opener(self._indexfile, mode=b"r") | |||
def __index_write_fp(self): | ||||
# You should not use this directly and use `_writing` instead | ||||
try: | ||||
f = self.opener( | ||||
self._indexfile, mode=b"r+", checkambig=self._checkambig | ||||
) | ||||
r48012 | if self._docket is None: | |||
f.seek(0, os.SEEK_END) | ||||
else: | ||||
f.seek(self._docket.index_end, os.SEEK_SET) | ||||
r47993 | return f | |||
except IOError as inst: | ||||
if inst.errno != errno.ENOENT: | ||||
raise | ||||
return self.opener( | ||||
self._indexfile, mode=b"w+", checkambig=self._checkambig | ||||
) | ||||
def __index_new_fp(self): | ||||
# You should not use this unless you are upgrading from inline revlog | ||||
return self.opener( | ||||
self._indexfile, | ||||
mode=b"w", | ||||
checkambig=self._checkambig, | ||||
atomictemp=True, | ||||
) | ||||
|
r35986 | |||
|
r43347 | def _datafp(self, mode=b'r'): | ||
|
r35985 | """file object for the revlog's data file""" | ||
r47920 | return self.opener(self._datafile, mode=mode) | |||
|
r35985 | |||
|
r35991 | @contextlib.contextmanager | ||
r48179 | def _sidedatareadfp(self): | |||
"""file object suitable to read sidedata""" | ||||
r48181 | if self._writinghandles: | |||
yield self._writinghandles[2] | ||||
else: | ||||
with self.opener(self._sidedatafile) as fp: | ||||
yield fp | ||||
r48179 | ||||
|
r43745 | def tiprev(self): | ||
return len(self.index) - 1 | ||||
|
r4980 | def tip(self): | ||
|
r43745 | return self.node(self.tiprev()) | ||
|
r43346 | |||
|
r24030 | def __contains__(self, rev): | ||
return 0 <= rev < len(self) | ||||
|
r43346 | |||
|
r6750 | def __len__(self): | ||
|
r38887 | return len(self.index) | ||
|
r43346 | |||
|
r6750 | def __iter__(self): | ||
|
r38806 | return iter(pycompat.xrange(len(self))) | ||
|
r43346 | |||
|
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 | |||
|
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. | ||||
|
r43346 | if (self.flags(baserev) & REVIDX_RAWTEXT_CHANGING_FLAGS) or ( | ||
self.flags(rev) & REVIDX_RAWTEXT_CHANGING_FLAGS | ||||
): | ||||
|
r36764 | return False | ||
return True | ||||
r44932 | def update_caches(self, transaction): | |||
r47935 | if self._nodemap_file is not None: | |||
r44932 | if transaction is None: | |||
nodemaputil.update_persistent_nodemap(self) | ||||
else: | ||||
nodemaputil.setup_persistent_nodemap(transaction, self) | ||||
|
r16414 | def clearcaches(self): | ||
|
r40088 | self._revisioncache = None | ||
|
r29830 | self._chainbasecache.clear() | ||
|
r48218 | self._segmentfile.clear_cache() | ||
|
r48219 | self._segmentfile_sidedata.clear_cache() | ||
|
r27465 | self._pcache = {} | ||
r44988 | self._nodemap_docket = None | |||
r43925 | self.index.clearcaches() | |||
r44988 | # The python code is the one responsible for validating the docket, we | |||
# end up having to refresh it here. | ||||
use_nodemap = ( | ||||
not self._inline | ||||
r47935 | and self._nodemap_file is not None | |||
r44988 | and util.safehasattr(self.index, 'update_nodemap_data') | |||
) | ||||
if use_nodemap: | ||||
nodemap_data = nodemaputil.persisted_data(self) | ||||
if nodemap_data is not None: | ||||
self._nodemap_docket = nodemap_data[0] | ||||
self.index.update_nodemap_data(*nodemap_data) | ||||
|
r16414 | |||
|
r13259 | def rev(self, node): | ||
|
r13275 | try: | ||
r43953 | return self.index.rev(node) | |||
|
r22282 | except TypeError: | ||
raise | ||||
|
r39809 | except error.RevlogError: | ||
r43925 | # parsers.c radix tree lookup failed | |||
|
r47771 | if ( | ||
node == self.nodeconstants.wdirid | ||||
or node in self.nodeconstants.wdirfilenodeids | ||||
): | ||||
r43925 | raise error.WdirUnsupported | |||
r47926 | raise error.LookupError(node, self.display_id, _(b'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 | |||
r48181 | def sidedata_cut_off(self, rev): | |||
sd_cut_off = self.index[rev][8] | ||||
if sd_cut_off != 0: | ||||
return sd_cut_off | ||||
# This is some annoying dance, because entries without sidedata | ||||
# currently use 0 as their ofsset. (instead of previous-offset + | ||||
# previous-size) | ||||
# | ||||
# We should reconsider this sidedata → 0 sidata_offset policy. | ||||
# In the meantime, we need this. | ||||
while 0 <= rev: | ||||
e = self.index[rev] | ||||
if e[9] != 0: | ||||
return e[8] + e[9] | ||||
rev -= 1 | ||||
return 0 | ||||
|
r30287 | def flags(self, rev): | ||
return self.index[rev][0] & 0xFFFF | ||||
|
r4980 | def length(self, rev): | ||
return self.index[rev][1] | ||||
|
r30287 | |||
|
r47443 | def sidedata_length(self, rev): | ||
r47907 | if not self.hassidedata: | |||
|
r47443 | return 0 | ||
return self.index[rev][9] | ||||
|
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) | ||
|
r49360 | return len(self.revision(rev)) | ||
|
r30287 | |||
r49606 | def fast_rank(self, rev): | |||
"""Return the rank of a revision if already known, or None otherwise. | ||||
The rank of a revision is the size of the sub-graph it defines as a | ||||
head. Equivalently, the rank of a revision `r` is the size of the set | ||||
`ancestors(r)`, `r` included. | ||||
This method returns the rank retrieved from the revlog in constant | ||||
time. It makes no attempt at computing unknown values for versions of | ||||
the revlog which do not persist the rank. | ||||
""" | ||||
rank = self.index[rev][ENTRY_RANK] | ||||
|
r49706 | if self._format_version != CHANGELOGV2 or rank == RANK_UNKNOWN: | ||
r49606 | return None | |||
|
r49706 | if rev == nullrev: | ||
return 0 # convention | ||||
r49606 | return rank | |||
|
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 | ||||
r48355 | ||||
return entry[5], entry[6] | ||||
|
r35539 | |||
|
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): | ||||
|
r47444 | return self.start(rev) + self.length(rev) | ||
|
r30287 | |||
def parents(self, node): | ||||
i = self.index | ||||
d = i[self.rev(node)] | ||||
r48355 | return i[d[5]][7], i[d[6]][7] # map revisions to nodes inline | |||
|
r30287 | |||
|
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 | |||
r48043 | if rustancestor is not None and self.index.rust_ext_compat: | |||
|
r42652 | lazyancestors = rustancestor.LazyAncestors | ||
|
r41150 | 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: | ||
|
r47771 | common = [self.nullid] | ||
|
r7233 | 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 | ||||
|
r49801 | class lazyset: | ||
|
r20073 | 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] | ||||
r48043 | if rustancestor is not None and self.index.rust_ext_compat: | |||
|
r42652 | 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: | ||
|
r47771 | common = [self.nullid] | ||
|
r17971 | 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: | ||||
|
r47771 | roots = [self.nullid] # Everybody's a descendant of nullid | ||
|
r3578 | lowestrev = nullrev | ||
if (lowestrev == nullrev) and (heads is None): | ||||
|
r1457 | # We want _all_ the nodes! | ||
|
r47771 | return ( | ||
[self.node(r) for r in self], | ||||
[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 | ||||
|
r47771 | if n == self.nullid: | ||
|
r1457 | 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 | ||
|
r43346 | ancestors.add(n) # Mark as ancestor | ||
|
r1457 | # Add non-nullid parents to list of nodes to tag. | ||
|
r43346 | nodestotag.update( | ||
|
r47771 | [p for p in self.parents(n) if p != self.nullid] | ||
|
r43346 | ) | ||
elif n in heads: # We've seen it before, is it a fake head? | ||||
|
r1457 | # 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 | ||
|
r47771 | roots = [self.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) | ||||
|
r49768 | heads = [head for head, flag in heads.items() 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() | ||||
r48043 | if rustdagop is not None and self.index.rust_ext_compat: | |||
|
r42652 | 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): | ||
|
r47771 | return [self.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) | ||||
|
r44937 | stoprevs = {self.rev(n) for n in stop or []} | ||
|
r40036 | |||
|
r43346 | revs = dagop.headrevssubset( | ||
self.revs, self.parentrevs, startrev=start, stoprevs=stoprevs | ||||
) | ||||
|
r40036 | |||
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) | ||
|
r43346 | 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): | ||||
|
r44218 | """return (heads(::(<roots> and <roots>::<heads>))) | ||
|
r42639 | |||
If includepath is True, return (<roots>::<heads>).""" | ||||
try: | ||||
|
r43346 | return self.index.reachableroots2( | ||
minroot, heads, roots, includepath | ||||
) | ||||
|
r42639 | except AttributeError: | ||
|
r43346 | 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)) | ||
|
r47771 | return self.nullid | ||
|
r10897 | |||
|
r3453 | def _match(self, id): | ||
|
r16762 | if isinstance(id, int): | ||
|
r3156 | # rev | ||
|
r2641 | return self.node(id) | ||
|
r47816 | if len(id) == self.nodeconstants.nodelen: | ||
|
r3438 | # possibly a binary node | ||
# odds of a binary node being all hex in ASCII are 1 in 10**25 | ||||
try: | ||||
node = id | ||||
|
r43346 | self.rev(node) # quick search the index | ||
|
r3438 | return node | ||
|
r39811 | except error.LookupError: | ||
|
r43346 | pass # may be partial hex id | ||
|
r36 | try: | ||
|
r3156 | # str(rev) | ||
|
r36 | rev = int(id) | ||
|
r43347 | if b"%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 | ||
|
r47815 | if len(id) == 2 * self.nodeconstants.nodelen: | ||
|
r3453 | 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 | ||
|
r47771 | maybewdir = self.nodeconstants.wdirhex.startswith(id) | ||
|
r48074 | ambiguous = False | ||
|
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 | ||||
|
r48074 | ambiguous = True | ||
else: | ||||
return partial | ||||
elif maybewdir: | ||||
|
r32684 | # no 'ff...' match in radix tree, wdir identified | ||
raise error.WdirUnsupported | ||||
|
r48074 | else: | ||
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): | ||||
|
r48074 | ambiguous = True | ||
|
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 | ||||
|
r48074 | if ambiguous: | ||
raise error.AmbiguousPrefixLookupError( | ||||
id, self.display_id, _(b'ambiguous identifier') | ||||
) | ||||
|
r16665 | |||
|
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 | ||
|
r43346 | prefix = bin(id[: l * 2]) | ||
|
r13259 | nl = [e[7] for e in self.index if e[7].startswith(prefix)] | ||
|
r43346 | nl = [ | ||
n for n in nl if hex(n).startswith(id) and self.hasnode(n) | ||||
] | ||||
|
r47771 | if self.nodeconstants.nullhex.startswith(id): | ||
nl.append(self.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( | ||
r47930 | id, self.display_id, _(b'ambiguous identifier') | |||
|
r43346 | ) | ||
|
r32684 | if maybewdir: | ||
raise error.WdirUnsupported | ||||
|
r7365 | return None | ||
|
r36256 | except TypeError: | ||
|
r3453 | pass | ||
def lookup(self, id): | ||||
"""locate a node based on: | ||||
|
r46554 | - revision number or str(revision number) | ||
- nodeid or subset of hex nodeid | ||||
|
r3453 | """ | ||
n = self._match(id) | ||||
if n is not None: | ||||
return n | ||||
n = self._partialmatch(id) | ||||
if n: | ||||
return n | ||||
|
r515 | |||
r47926 | raise error.LookupError(id, self.display_id, _(b'no match found')) | |||
|
r36 | |||
|
r37785 | def shortest(self, node, minlength=1): | ||
"""Find the shortest unambiguous prefix that matches node.""" | ||||
|
r43346 | |||
|
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: | ||
r47926 | raise error.LookupError(node, self.display_id, _(b'no node')) | |||
|
r37989 | return True | ||
|
r34247 | |||
|
r37987 | def maybewdir(prefix): | ||
|
r43347 | return all(c == b'f' for c in pycompat.iterbytestr(prefix)) | ||
|
r37987 | |||
|
r37785 | hexnode = hex(node) | ||
|
r37987 | |||
def disambiguate(hexnode, minlength): | ||||
|
r37990 | """Disambiguate against wdirid.""" | ||
|
r45596 | for length in range(minlength, len(hexnode) + 1): | ||
|
r37987 | 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: | ||
|
r47771 | if node != self.nodeconstants.wdirid: | ||
r47919 | raise error.LookupError( | |||
r47926 | node, self.display_id, _(b'no node') | |||
r47919 | ) | |||
|
r37987 | except AttributeError: | ||
# Fall through to pure code | ||||
pass | ||||
|
r47771 | if node == self.nodeconstants.wdirid: | ||
|
r45596 | for length in range(minlength, len(hexnode) + 1): | ||
|
r37988 | prefix = hexnode[:length] | ||
if isvalid(prefix): | ||||
return prefix | ||||
|
r45596 | for length in range(minlength, len(hexnode) + 1): | ||
|
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 | |||
|
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: | ||
r47736 | start += (startrev + 1) * self.index.entry_size | |||
end += (endrev + 1) * self.index.entry_size | ||||
|
r19714 | length = end - start | ||
|
r27649 | |||
|
r48218 | return start, self._segmentfile.read_chunk(start, length, 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. | ||||
""" | ||||
r48027 | compression_mode = self.index[rev][10] | |||
data = self._getsegmentforrevs(rev, rev, df=df)[1] | ||||
if compression_mode == COMP_MODE_PLAIN: | ||||
return data | ||||
r48029 | elif compression_mode == COMP_MODE_DEFAULT: | |||
return self._decompressor(data) | ||||
r48027 | elif compression_mode == COMP_MODE_INLINE: | |||
return self.decompress(data) | ||||
else: | ||||
|
r48207 | msg = b'unknown compression mode %d' | ||
r48027 | msg %= compression_mode | |||
raise error.RevlogError(msg) | ||||
|
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 | ||||
r47736 | iosize = self.index.entry_size | |||
|
r19715 | buffer = util.buffer | ||
|
r19713 | |||
l = [] | ||||
ladd = l.append | ||||
|
r34825 | if not self._withsparseread: | ||
slicedchunks = (revs,) | ||||
else: | ||||
|
r43346 | 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 | ||
r48029 | # self._decompressor might be None, but will not be used in that case | |||
def_decomp = self._decompressor | ||||
|
r34825 | for rev in revschunk: | ||
chunkstart = start(rev) | ||||
if inline: | ||||
chunkstart += (rev + 1) * iosize | ||||
chunklength = length(rev) | ||||
r48027 | comp_mode = self.index[rev][10] | |||
r48026 | c = buffer(data, chunkstart - offset, chunklength) | |||
r48027 | if comp_mode == COMP_MODE_PLAIN: | |||
ladd(c) | ||||
elif comp_mode == COMP_MODE_INLINE: | ||||
ladd(decomp(c)) | ||||
r48029 | elif comp_mode == COMP_MODE_DEFAULT: | |||
ladd(def_decomp(c)) | ||||
r48027 | else: | |||
|
r48207 | msg = b'unknown compression mode %d' | ||
r48027 | msg %= comp_mode | |||
raise error.RevlogError(msg) | ||||
|
r19713 | |||
return l | ||||
|
r14075 | |||
|
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): | ||
|
r46554 | """tells whether rev is a snapshot""" | ||
|
r41118 | if not self._sparserevlog: | ||
return self.deltaparent(rev) == nullrev | ||||
|
r43347 | elif util.safehasattr(self.index, b'issnapshot'): | ||
|
r41118 | # 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): | ||||
|
r43347 | raise error.ProgrammingError(b'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 | |||
|
r43346 | return mdiff.textdiff(self.rawdata(rev1), self.rawdata(rev2)) | ||
|
r119 | |||
|
r49360 | def revision(self, nodeorrev, _df=None): | ||
|
r16435 | """return an uncompressed revision of a given node or revision | ||
number. | ||||
|
r26377 | |||
|
r30743 | _df - an existing file handle to read from. (internal-only) | ||
|
r16435 | """ | ||
|
r49360 | return self._revisiondata(nodeorrev, _df) | ||
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. | ||||
""" | ||||
r48174 | # deal with <nodeorrev> argument type | |||
if isinstance(nodeorrev, int): | ||||
rev = nodeorrev | ||||
else: | ||||
rev = self.rev(nodeorrev) | ||||
return self._sidedata(rev) | ||||
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 | |||
|
r47771 | if node == self.nullid: | ||
r48177 | return b"" | |||
r43057 | ||||
|
r44431 | # ``rawtext`` is the text as stored inside the revlog. Might be the | ||
# revision or might need to be processed to retrieve the revision. | ||||
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. | ||||
r48177 | 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 | ||||
r48177 | return rawtext | |||
|
r47443 | |||
r43148 | if raw: | |||
r43262 | validatehash = flagutil.processflagsraw(self, rawtext, flags) | |||
r43148 | text = rawtext | |||
else: | ||||
|
r47443 | r = flagutil.processflagsread(self, rawtext, flags) | ||
text, validatehash = r | ||||
r43060 | if validatehash: | |||
self.checkhash(text, node, rev=rev) | ||||
if not validated: | ||||
self._revisioncache = (node, rev, rawtext) | ||||
r48177 | return text | |||
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) | ||||
|
r43346 | del basetext # let us have a chance to free memory early | ||
r43060 | return (rev, rawtext, False) | |||
|
r13239 | |||
|
r47443 | def _sidedata(self, rev): | ||
"""Return the sidedata for a given revision number.""" | ||||
index_entry = self.index[rev] | ||||
sidedata_offset = index_entry[8] | ||||
sidedata_size = index_entry[9] | ||||
if self._inline: | ||||
r47736 | sidedata_offset += self.index.entry_size * (1 + rev) | |||
|
r47443 | if sidedata_size == 0: | ||
return {} | ||||
|
r48219 | if self._docket.sidedata_end < sidedata_offset + sidedata_size: | ||
filename = self._sidedatafile | ||||
end = self._docket.sidedata_end | ||||
offset = sidedata_offset | ||||
length = sidedata_size | ||||
m = FILE_TOO_SHORT_MSG % (filename, length, offset, end) | ||||
raise error.RevlogError(m) | ||||
comp_segment = self._segmentfile_sidedata.read_chunk( | ||||
sidedata_offset, sidedata_size | ||||
) | ||||
r48179 | ||||
r48031 | comp = self.index[rev][11] | |||
if comp == COMP_MODE_PLAIN: | ||||
segment = comp_segment | ||||
elif comp == COMP_MODE_DEFAULT: | ||||
segment = self._decompressor(comp_segment) | ||||
elif comp == COMP_MODE_INLINE: | ||||
segment = self.decompress(comp_segment) | ||||
else: | ||||
|
r48207 | msg = b'unknown compression mode %d' | ||
r48031 | msg %= comp | |||
raise error.RevlogError(msg) | ||||
|
r47443 | sidedata = sidedatautil.deserialize_sidedata(segment) | ||
return sidedata | ||||
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) | ||||
""" | ||||
r48177 | return self._revisiondata(nodeorrev, _df, raw=True) | |||
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)) | ||||
|
r43346 | raise error.RevlogError( | ||
|
r43347 | _(b"integrity check failed on %s:%s") | ||
r47931 | % (self.display_id, pycompat.bytestr(revornode)) | |||
|
r43346 | ) | ||
|
r39809 | except error.RevlogError: | ||
|
r39915 | if self._censorable and storageutil.iscensoredtext(text): | ||
r47932 | raise error.CensoredNodeError(self.display_id, node, text) | |||
|
r37461 | raise | ||
|
r0 | |||
r47988 | def _enforceinlinesize(self, tr): | |||
|
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 | ||
r47938 | total_size = self.start(tiprev) + self.length(tiprev) | |||
if not self._inline or total_size < _maxinline: | ||||
|
r2073 | return | ||
|
r8315 | |||
r47919 | troffset = tr.findoffset(self._indexfile) | |||
|
r46482 | if troffset is None: | ||
|
r43346 | raise error.RevlogError( | ||
r47919 | _(b"%s not found in the transaction") % self._indexfile | |||
|
r43346 | ) | ||
|
r49423 | trindex = None | ||
r47920 | tr.add(self._datafile, 0) | |||
|
r8315 | |||
r47988 | existing_handles = False | |||
if self._writinghandles is not None: | ||||
existing_handles = True | ||||
fp = self._writinghandles[0] | ||||
|
r8317 | fp.flush() | ||
fp.close() | ||||
|
r40661 | # We can't use the cached file handle after close(). So prevent | ||
# its usage. | ||||
self._writinghandles = None | ||||
|
r48218 | self._segmentfile.writing_handle = None | ||
|
r48219 | # No need to deal with sidedata writing handle as it is only | ||
# relevant with revlog-v2 which is never inline, not reaching | ||||
# this code | ||||
|
r8315 | |||
r47988 | new_dfh = self._datafp(b'w+') | |||
new_dfh.truncate(0) # drop any potentially existing data | ||||
try: | ||||
r47993 | with self._indexfp() as read_ifh: | |||
r47987 | for r in self: | |||
r47988 | new_dfh.write(self._getsegmentforrevs(r, r, df=read_ifh)[1]) | |||
|
r49423 | if ( | ||
trindex is None | ||||
and troffset | ||||
<= self.start(r) + r * self.index.entry_size | ||||
): | ||||
r47987 | trindex = r | |||
r47988 | new_dfh.flush() | |||
|
r49423 | if trindex is None: | ||
trindex = 0 | ||||
r47993 | with self.__index_new_fp() as fp: | |||
r47987 | self._format_flags &= ~FLAG_INLINE_DATA | |||
self._inline = False | ||||
for i in self: | ||||
e = self.index.entry_binary(i) | ||||
r48009 | if i == 0 and self._docket is None: | |||
r47987 | header = self._format_flags | self._format_version | |||
header = self.index.pack_header(header) | ||||
e = header + e | ||||
fp.write(e) | ||||
r48012 | if self._docket is not None: | |||
self._docket.index_end = fp.tell() | ||||
|
r48065 | |||
# There is a small transactional race here. If the rename of | ||||
# the index fails, we should remove the datafile. It is more | ||||
# important to ensure that the data file is not truncated | ||||
# when the index is replaced as otherwise data is lost. | ||||
tr.replace(self._datafile, self.start(trindex)) | ||||
r47987 | # the temp file replace the real index when we exit the context | |||
# manager | ||||
tr.replace(self._indexfile, trindex * self.index.entry_size) | ||||
nodemaputil.setup_persistent_nodemap(tr, self) | ||||
|
r48218 | self._segmentfile = randomaccessfile.randomaccessfile( | ||
self.opener, | ||||
self._datafile, | ||||
self._chunkcachesize, | ||||
) | ||||
|
r2073 | |||
r47988 | if existing_handles: | |||
# switched from inline to conventional reopen the index | ||||
r47993 | ifh = self.__index_write_fp() | |||
r48181 | self._writinghandles = (ifh, new_dfh, None) | |||
|
r48218 | self._segmentfile.writing_handle = new_dfh | ||
r47988 | new_dfh = None | |||
|
r48219 | # No need to deal with sidedata writing handle as it is only | ||
# relevant with revlog-v2 which is never inline, not reaching | ||||
# this code | ||||
r47988 | finally: | |||
if new_dfh is not None: | ||||
new_dfh.close() | ||||
|
r39922 | def _nodeduplicatecallback(self, transaction, node): | ||
|
r46554 | """called when trying to add a node already stored.""" | ||
|
r39922 | |||
r47988 | @contextlib.contextmanager | |||
|
r48256 | def reading(self): | ||
"""Context manager that keeps data and sidedata files open for reading""" | ||||
with self._segmentfile.reading(): | ||||
with self._segmentfile_sidedata.reading(): | ||||
yield | ||||
@contextlib.contextmanager | ||||
r47988 | def _writing(self, transaction): | |||
r48014 | if self._trypending: | |||
msg = b'try to write in a `trypending` revlog: %s' | ||||
msg %= self.display_id | ||||
raise error.ProgrammingError(msg) | ||||
r47988 | if self._writinghandles is not None: | |||
yield | ||||
else: | ||||
r48181 | ifh = dfh = sdfh = None | |||
r47988 | try: | |||
r48118 | r = len(self) | |||
# opening the data file. | ||||
dsize = 0 | ||||
if r: | ||||
dsize = self.end(r - 1) | ||||
dfh = None | ||||
if not self._inline: | ||||
try: | ||||
dfh = self._datafp(b"r+") | ||||
if self._docket is None: | ||||
dfh.seek(0, os.SEEK_END) | ||||
else: | ||||
dfh.seek(self._docket.data_end, os.SEEK_SET) | ||||
except IOError as inst: | ||||
if inst.errno != errno.ENOENT: | ||||
raise | ||||
dfh = self._datafp(b"w+") | ||||
transaction.add(self._datafile, dsize) | ||||
r48181 | if self._sidedatafile is not None: | |||
|
r48595 | # revlog-v2 does not inline, help Pytype | ||
assert dfh is not None | ||||
r48181 | try: | |||
sdfh = self.opener(self._sidedatafile, mode=b"r+") | ||||
dfh.seek(self._docket.sidedata_end, os.SEEK_SET) | ||||
except IOError as inst: | ||||
if inst.errno != errno.ENOENT: | ||||
raise | ||||
sdfh = self.opener(self._sidedatafile, mode=b"w+") | ||||
transaction.add( | ||||
self._sidedatafile, self._docket.sidedata_end | ||||
) | ||||
r48118 | ||||
# opening the index file. | ||||
r47988 | isize = r * self.index.entry_size | |||
r47993 | ifh = self.__index_write_fp() | |||
r47988 | if self._inline: | |||
transaction.add(self._indexfile, dsize + isize) | ||||
else: | ||||
transaction.add(self._indexfile, isize) | ||||
r48118 | # exposing all file handle for writing. | |||
r48181 | self._writinghandles = (ifh, dfh, sdfh) | |||
|
r48218 | self._segmentfile.writing_handle = ifh if self._inline else dfh | ||
|
r48219 | self._segmentfile_sidedata.writing_handle = sdfh | ||
r48118 | yield | |||
if self._docket is not None: | ||||
self._write_docket(transaction) | ||||
finally: | ||||
self._writinghandles = None | ||||
|
r48218 | self._segmentfile.writing_handle = None | ||
|
r48219 | self._segmentfile_sidedata.writing_handle = None | ||
r48119 | if dfh is not None: | |||
dfh.close() | ||||
r48181 | if sdfh is not None: | |||
|
r48206 | sdfh.close() | ||
r48119 | # closing the index file last to avoid exposing referent to | |||
# potential unflushed data content. | ||||
r48118 | if ifh is not None: | |||
r47988 | ifh.close() | |||
r48013 | def _write_docket(self, transaction): | |||
"""write the current docket on disk | ||||
Exist as a method to help changelog to implement transaction logic | ||||
We could also imagine using the same transaction logic for all revlog | ||||
since docket are cheap.""" | ||||
self._docket.write(transaction) | ||||
|
r43346 | def addrevision( | ||
self, | ||||
text, | ||||
transaction, | ||||
link, | ||||
p1, | ||||
p2, | ||||
cachedelta=None, | ||||
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: | ||
|
r43346 | raise error.RevlogError( | ||
r47934 | _(b"attempted to add linkrev -1 to %s") % self.display_id | |||
|
r43346 | ) | ||
|
r25459 | |||
r43256 | if sidedata is None: | |||
sidedata = {} | ||||
|
r47847 | elif sidedata and not self.hassidedata: | ||
r43298 | raise error.ProgrammingError( | |||
|
r43347 | _(b"trying to add sidedata to a revlog who don't support them") | ||
|
r43346 | ) | ||
r43256 | ||||
|
r30745 | if flags: | ||
node = node or self.hash(text, p1, p2) | ||||
|
r47443 | rawtext, validatehash = flagutil.processflagswrite(self, text, flags) | ||
|
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( | ||
|
r43347 | _( | ||
b"%s: size of %d bytes exceeds maximum revlog storage of 2GiB" | ||||
) | ||||
r47933 | % (self.display_id, len(rawtext)) | |||
|
r43346 | ) | ||
|
r25459 | |||
|
r31750 | node = node or self.hash(rawtext, p1, p2) | ||
|
r47258 | rev = self.index.get_rev(node) | ||
if rev is not None: | ||||
return rev | ||||
|
r12023 | |||
|
r30745 | if validatehash: | ||
|
r31750 | self.checkhash(rawtext, node, p1=p1, p2=p2) | ||
|
r30745 | |||
|
r47258 | return self.addrawrevision( | ||
|
r43346 | rawtext, | ||
transaction, | ||||
link, | ||||
p1, | ||||
p2, | ||||
node, | ||||
flags, | ||||
cachedelta=cachedelta, | ||||
deltacomputer=deltacomputer, | ||||
|
r47443 | sidedata=sidedata, | ||
|
r43346 | ) | ||
def addrawrevision( | ||||
self, | ||||
rawtext, | ||||
transaction, | ||||
link, | ||||
p1, | ||||
p2, | ||||
node, | ||||
flags, | ||||
cachedelta=None, | ||||
deltacomputer=None, | ||||
|
r47443 | sidedata=None, | ||
|
r43346 | ): | ||
|
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). | ||||
""" | ||||
r47988 | with self._writing(transaction): | |||
|
r47257 | return self._addrevision( | ||
|
r43346 | node, | ||
rawtext, | ||||
transaction, | ||||
link, | ||||
p1, | ||||
p2, | ||||
flags, | ||||
cachedelta, | ||||
deltacomputer=deltacomputer, | ||||
|
r47443 | sidedata=sidedata, | ||
|
r43346 | ) | ||
|
r3390 | |||
|
r30795 | def compress(self, data): | ||
"""Generate a possibly-compressed representation of data.""" | ||||
if not data: | ||||
|
r43347 | return b'', data | ||
|
r30795 | |||
compressed = self._compressor.compress(data) | ||||
if compressed: | ||||
# The revlog compressor added the header in the returned data. | ||||
|
r43347 | return b'', compressed | ||
if data[0:1] == b'\0': | ||||
return b'', data | ||||
return b'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 | |||
|
r43347 | if t == b'x': | ||
|
r30793 | try: | ||
|
r30817 | return _zlibdecompress(data) | ||
|
r30793 | except zlib.error as e: | ||
|
r43346 | raise error.RevlogError( | ||
|
r43347 | _(b'revlog decompress error: %s') | ||
|
r43346 | % stringutil.forcebytestr(e) | ||
) | ||||
|
r30817 | # '\0' is more common than 'u' so it goes first. | ||
|
r43347 | elif t == b'\0': | ||
|
r30817 | return data | ||
|
r43347 | elif t == b'u': | ||
|
r30793 | return util.buffer(data, 1) | ||
|
r30817 | |||
r48028 | compressor = self._get_decompressor(t) | |||
|
r30817 | |||
return compressor.decompress(data) | ||||
|
r30793 | |||
|
r43346 | def _addrevision( | ||
self, | ||||
node, | ||||
rawtext, | ||||
transaction, | ||||
link, | ||||
p1, | ||||
p2, | ||||
flags, | ||||
cachedelta, | ||||
alwayscache=False, | ||||
deltacomputer=None, | ||||
|
r47443 | sidedata=None, | ||
|
r43346 | ): | ||
|
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 | """ | ||
|
r47771 | if node == self.nullid: | ||
|
r43346 | raise error.RevlogError( | ||
r47934 | _(b"%s: attempt to add null revision") % self.display_id | |||
|
r43346 | ) | ||
|
r47771 | if ( | ||
node == self.nodeconstants.wdirid | ||||
or node in self.nodeconstants.wdirfilenodeids | ||||
): | ||||
|
r43346 | raise error.RevlogError( | ||
r47934 | _(b"%s: attempt to add wdir revision") % self.display_id | |||
|
r43346 | ) | ||
r47988 | if self._writinghandles is None: | |||
msg = b'adding revision outside `revlog._writing` context' | ||||
raise error.ProgrammingError(msg) | ||||
|
r34029 | |||
|
r35653 | if self._inline: | ||
r47988 | fh = self._writinghandles[0] | |||
|
r35653 | else: | ||
r47988 | fh = self._writinghandles[1] | |||
|
r35653 | |||
|
r31755 | btext = [rawtext] | ||
|
r12623 | |||
|
r6750 | curr = len(self) | ||
|
r4981 | prev = curr - 1 | ||
|
r47444 | |||
offset = self._get_data_offset(prev) | ||||
|
r47349 | |||
if self._concurrencychecker: | ||||
r48181 | ifh, dfh, sdfh = self._writinghandles | |||
# XXX no checking for the sidedata file | ||||
|
r47349 | if self._inline: | ||
# offset is "as if" it were in the .d file, so we need to add on | ||||
# the size of the entry metadata. | ||||
self._concurrencychecker( | ||||
r47919 | ifh, self._indexfile, offset + curr * self.index.entry_size | |||
|
r47349 | ) | ||
else: | ||||
# Entries in the .i are a consistent size. | ||||
self._concurrencychecker( | ||||
r47919 | ifh, self._indexfile, curr * self.index.entry_size | |||
|
r47349 | ) | ||
r47920 | self._concurrencychecker(dfh, self._datafile, offset) | |||
|
r47349 | |||
|
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. | ||||
|
r43346 | textlen = mdiff.patchedsize( | ||
revlog.size(self, cachedelta[0]), cachedelta[1] | ||||
) | ||||
|
r26116 | else: | ||
|
r31755 | textlen = len(rawtext) | ||
|
r26116 | |||
|
r35756 | if deltacomputer is None: | ||
|
r39366 | deltacomputer = deltautil.deltacomputer(self) | ||
|
r35756 | |||
r48191 | revinfo = revlogutils.revisioninfo( | |||
node, | ||||
p1, | ||||
p2, | ||||
btext, | ||||
textlen, | ||||
cachedelta, | ||||
flags, | ||||
) | ||||
|
r36765 | |||
|
r39368 | deltainfo = deltacomputer.finddeltainfo(revinfo, fh) | ||
|
r35652 | |||
r48027 | compression_mode = COMP_MODE_INLINE | |||
if self._docket is not None: | ||||
r48245 | default_comp = self._docket.default_compression_header | |||
r = deltautil.delta_compression(default_comp, deltainfo) | ||||
compression_mode, deltainfo = r | ||||
r48027 | ||||
r48030 | sidedata_compression_mode = COMP_MODE_INLINE | |||
r47907 | if sidedata and self.hassidedata: | |||
r48030 | sidedata_compression_mode = COMP_MODE_PLAIN | |||
|
r47443 | serialized_sidedata = sidedatautil.serialize_sidedata(sidedata) | ||
r48181 | sidedata_offset = self._docket.sidedata_end | |||
r48032 | h, comp_sidedata = self.compress(serialized_sidedata) | |||
if ( | ||||
h != b'u' | ||||
and comp_sidedata[0:1] != b'\0' | ||||
and len(comp_sidedata) < len(serialized_sidedata) | ||||
): | ||||
assert not h | ||||
if ( | ||||
comp_sidedata[0:1] | ||||
== self._docket.default_compression_header | ||||
): | ||||
sidedata_compression_mode = COMP_MODE_DEFAULT | ||||
serialized_sidedata = comp_sidedata | ||||
else: | ||||
sidedata_compression_mode = COMP_MODE_INLINE | ||||
serialized_sidedata = comp_sidedata | ||||
|
r47443 | else: | ||
serialized_sidedata = b"" | ||||
# Don't store the offset if the sidedata is empty, that way | ||||
# we can easily detect empty sidedata and they will be no different | ||||
# than ones we manually add. | ||||
sidedata_offset = 0 | ||||
r49606 | rank = RANK_UNKNOWN | |||
if self._format_version == CHANGELOGV2: | ||||
|
r49610 | if (p1r, p2r) == (nullrev, nullrev): | ||
rank = 1 | ||||
elif p1r != nullrev and p2r == nullrev: | ||||
rank = 1 + self.fast_rank(p1r) | ||||
elif p1r == nullrev and p2r != nullrev: | ||||
rank = 1 + self.fast_rank(p2r) | ||||
else: # merge node | ||||
|
r49710 | if rustdagop is not None and self.index.rust_ext_compat: | ||
rank = rustdagop.rank(self.index, p1r, p2r) | ||||
else: | ||||
pmin, pmax = sorted((p1r, p2r)) | ||||
rank = 1 + self.fast_rank(pmax) | ||||
rank += sum(1 for _ in self.findmissingrevs([pmax], [pmin])) | ||||
r49606 | ||||
r48188 | e = revlogutils.entry( | |||
flags=flags, | ||||
data_offset=offset, | ||||
data_compressed_length=deltainfo.deltalen, | ||||
data_uncompressed_length=textlen, | ||||
data_compression_mode=compression_mode, | ||||
data_delta_base=deltainfo.base, | ||||
link_rev=link, | ||||
parent_rev_1=p1r, | ||||
parent_rev_2=p2r, | ||||
node_id=node, | ||||
sidedata_offset=sidedata_offset, | ||||
sidedata_compressed_length=len(serialized_sidedata), | ||||
sidedata_compression_mode=sidedata_compression_mode, | ||||
r49606 | rank=rank, | |||
|
r43346 | ) | ||
|
r47438 | |||
|
r38886 | self.index.append(e) | ||
r47811 | entry = self.index.entry_binary(curr) | |||
r48009 | if curr == 0 and self._docket is None: | |||
r47910 | header = self._format_flags | self._format_version | |||
header = self.index.pack_header(header) | ||||
r47811 | entry = header + entry | |||
|
r43346 | self._writeentry( | ||
|
r47443 | transaction, | ||
entry, | ||||
deltainfo.data, | ||||
link, | ||||
offset, | ||||
serialized_sidedata, | ||||
r48181 | sidedata_offset, | |||
|
r43346 | ) | ||
|
r39369 | |||
rawtext = btext[0] | ||||
|
r20217 | |||
|
r31755 | if alwayscache and rawtext is None: | ||
|
r39228 | rawtext = deltacomputer.buildtext(revinfo, fh) | ||
|
r26243 | |||
|
r43346 | if type(rawtext) == bytes: # only accept immutable objects | ||
|
r40088 | self._revisioncache = (node, curr, rawtext) | ||
|
r39369 | self._chainbasecache[curr] = deltainfo.chainbase | ||
|
r47256 | return curr | ||
|
r20217 | |||
|
r47444 | def _get_data_offset(self, prev): | ||
"""Returns the current offset in the (in-transaction) data file. | ||||
Versions < 2 of the revlog can get this 0(1), revlog v2 needs a docket | ||||
file to store that information: since sidedata can be rewritten to the | ||||
end of the data file within a transaction, you can have cases where, for | ||||
example, rev `n` does not have sidedata while rev `n - 1` does, leading | ||||
to `n - 1`'s sidedata being written after `n`'s data. | ||||
TODO cache this in a docket file before getting out of experimental.""" | ||||
r48016 | if self._docket is None: | |||
|
r47444 | return self.end(prev) | ||
r48016 | else: | |||
return self._docket.data_end | ||||
|
r47444 | |||
r48181 | def _writeentry( | |||
self, transaction, entry, data, link, offset, sidedata, sidedata_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. | ||||
r47988 | if self._writinghandles is None: | |||
msg = b'adding revision outside `revlog._writing` context' | ||||
raise error.ProgrammingError(msg) | ||||
r48181 | ifh, dfh, sdfh = self._writinghandles | |||
r48012 | if self._docket is None: | |||
ifh.seek(0, os.SEEK_END) | ||||
else: | ||||
ifh.seek(self._docket.index_end, os.SEEK_SET) | ||||
|
r27441 | if dfh: | ||
r48016 | if self._docket is None: | |||
dfh.seek(0, os.SEEK_END) | ||||
else: | ||||
dfh.seek(self._docket.data_end, os.SEEK_SET) | ||||
r48181 | if sdfh: | |||
sdfh.seek(self._docket.sidedata_end, os.SEEK_SET) | ||||
|
r27430 | |||
|
r20217 | curr = len(self) - 1 | ||
|
r4982 | if not self._inline: | ||
r47920 | transaction.add(self._datafile, offset) | |||
r48181 | if self._sidedatafile: | |||
transaction.add(self._sidedatafile, sidedata_offset) | ||||
r47919 | transaction.add(self._indexfile, curr * len(entry)) | |||
|
r2073 | if data[0]: | ||
|
r3390 | dfh.write(data[0]) | ||
dfh.write(data[1]) | ||||
|
r47443 | if sidedata: | ||
r48181 | sdfh.write(sidedata) | |||
|
r4981 | ifh.write(entry) | ||
|
r2073 | else: | ||
r47736 | offset += curr * self.index.entry_size | |||
r47919 | transaction.add(self._indexfile, offset) | |||
|
r4981 | ifh.write(entry) | ||
|
r3390 | ifh.write(data[0]) | ||
ifh.write(data[1]) | ||||
r48181 | assert not sidedata | |||
r47988 | self._enforceinlinesize(transaction) | |||
r48012 | if self._docket is not None: | |||
|
r48595 | # revlog-v2 always has 3 writing handles, help Pytype | ||
|
r49104 | wh1 = self._writinghandles[0] | ||
wh2 = self._writinghandles[1] | ||||
wh3 = self._writinghandles[2] | ||||
assert wh1 is not None | ||||
assert wh2 is not None | ||||
assert wh3 is not None | ||||
self._docket.index_end = wh1.tell() | ||||
self._docket.data_end = wh2.tell() | ||||
self._docket.sidedata_end = wh3.tell() | ||||
r48012 | ||||
r44789 | nodemaputil.setup_persistent_nodemap(transaction, self) | |||
|
r2073 | |||
|
r46373 | def addgroup( | ||
self, | ||||
deltas, | ||||
linkmapper, | ||||
transaction, | ||||
|
r47085 | alwayscache=False, | ||
|
r46373 | addrevisioncb=None, | ||
duplicaterevisioncb=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 | """ | ||
r47988 | if self._adding_group: | |||
|
r43347 | raise error.ProgrammingError(b'cannot nest addgroup() calls') | ||
|
r40661 | |||
r47988 | self._adding_group = True | |||
|
r46373 | empty = True | ||
|
r6261 | try: | ||
r47988 | with self._writing(transaction): | |||
r47986 | deltacomputer = deltautil.deltacomputer(self) | |||
# loop through our set of deltas | ||||
for data in deltas: | ||||
( | ||||
node, | ||||
p1, | ||||
p2, | ||||
linknode, | ||||
deltabase, | ||||
delta, | ||||
flags, | ||||
sidedata, | ||||
) = data | ||||
link = linkmapper(linknode) | ||||
flags = flags or REVIDX_DEFAULT_FLAGS | ||||
rev = self.index.get_rev(node) | ||||
if rev is not None: | ||||
# this can happen if two branches make the same change | ||||
self._nodeduplicatecallback(transaction, rev) | ||||
if duplicaterevisioncb: | ||||
duplicaterevisioncb(self, rev) | ||||
empty = False | ||||
continue | ||||
for p in (p1, p2): | ||||
if not self.index.has_node(p): | ||||
raise error.LookupError( | ||||
p, self.radix, _(b'unknown parent') | ||||
) | ||||
if not self.index.has_node(deltabase): | ||||
|
r43346 | raise error.LookupError( | ||
r47986 | deltabase, self.display_id, _(b'unknown delta base') | |||
|
r43346 | ) | ||
|
r24120 | |||
r47986 | baserev = self.rev(deltabase) | |||
if baserev != nullrev and self.iscensored(baserev): | ||||
# if base is censored, delta must be full replacement in a | ||||
# single patch operation | ||||
hlen = struct.calcsize(b">lll") | ||||
oldlen = self.rawsize(baserev) | ||||
newlen = len(delta) - hlen | ||||
if delta[:hlen] != mdiff.replacediffheader( | ||||
oldlen, newlen | ||||
): | ||||
raise error.CensoredBaseError( | ||||
self.display_id, self.node(baserev) | ||||
) | ||||
if not flags and self._peek_iscensored(baserev, delta): | ||||
flags |= REVIDX_ISCENSORED | ||||
# 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. | ||||
# We're only using addgroup() in the context of changegroup | ||||
# generation so the revision data can always be handled as raw | ||||
# by the flagprocessor. | ||||
rev = self._addrevision( | ||||
node, | ||||
None, | ||||
transaction, | ||||
link, | ||||
p1, | ||||
p2, | ||||
flags, | ||||
(baserev, delta), | ||||
alwayscache=alwayscache, | ||||
deltacomputer=deltacomputer, | ||||
sidedata=sidedata, | ||||
) | ||||
if addrevisioncb: | ||||
addrevisioncb(self, rev) | ||||
empty = False | ||||
|
r6261 | finally: | ||
r47988 | self._adding_group = False | |||
|
r46373 | return not empty | ||
|
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 | |||
r47937 | def _peek_iscensored(self, baserev, delta): | |||
|
r24255 | """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. | ||||
""" | ||||
|
r43346 | 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 | ||||
r48016 | data_end = self.start(rev) | |||
|
r4982 | if not self._inline: | ||
r48016 | transaction.add(self._datafile, data_end) | |||
r47736 | end = rev * self.index.entry_size | |||
|
r2073 | else: | ||
r48016 | end = data_end + (rev * self.index.entry_size) | |||
|
r2072 | |||
r48181 | if self._sidedatafile: | |||
sidedata_end = self.sidedata_cut_off(rev) | ||||
transaction.add(self._sidedatafile, sidedata_end) | ||||
r47919 | transaction.add(self._indexfile, end) | |||
r48012 | if self._docket is not None: | |||
# XXX we could, leverage the docket while stripping. However it is | ||||
# not powerfull enough at the time of this comment | ||||
self._docket.index_end = end | ||||
r48016 | self._docket.data_end = data_end | |||
r48181 | self._docket.sidedata_end = sidedata_end | |||
r48012 | self._docket.write(transaction, stripping=True) | |||
|
r1535 | |||
# then reset internal state in memory to forget those revisions | ||||
|
r40088 | self._revisioncache = None | ||
|
r46364 | self._chaininfocache = util.lrucachedict(500) | ||
|
r48218 | self._segmentfile.clear_cache() | ||
|
r48219 | self._segmentfile_sidedata.clear_cache() | ||
|
r1535 | |||
|
r4979 | del self.index[rev:-1] | ||
|
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: | ||||
r47919 | f = self.opener(self._indexfile) | |||
|
r42767 | f.seek(0, io.SEEK_END) | ||
|
r1667 | actual = f.tell() | ||
|
r13400 | f.close() | ||
r47736 | s = self.index.entry_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): | ||||
r47919 | res = [self._indexfile] | |||
r48243 | if self._docket_file is None: | |||
if not self._inline: | ||||
res.append(self._datafile) | ||||
else: | ||||
res.append(self._docket_file) | ||||
r48248 | res.extend(self._docket.old_index_filepaths(include_empty=False)) | |||
r48243 | if self._docket.data_end: | |||
res.append(self._datafile) | ||||
r48248 | res.extend(self._docket.old_data_filepaths(include_empty=False)) | |||
r48243 | if self._docket.sidedata_end: | |||
res.append(self._sidedatafile) | ||||
r48248 | res.extend(self._docket.old_sidedata_filepaths(include_empty=False)) | |||
|
r6891 | return res | ||
|
r30778 | |||
|
r43346 | def emitrevisions( | ||
self, | ||||
nodes, | ||||
nodesorder=None, | ||||
revisiondata=False, | ||||
assumehaveparentrevisions=False, | ||||
deltamode=repository.CG_DELTAMODE_STD, | ||||
|
r47449 | sidedata_helpers=None, | ||
|
r43346 | ): | ||
|
r43347 | if nodesorder not in (b'nodes', b'storage', b'linear', None): | ||
|
r43346 | raise error.ProgrammingError( | ||
|
r43347 | b'unhandled value for nodesorder: %s' % nodesorder | ||
|
r43346 | ) | ||
|
r39898 | |||
if nodesorder is None and not self._generaldelta: | ||||
|
r43347 | nodesorder = b'storage' | ||
|
r39898 | |||
|
r43346 | if ( | ||
not self._storedeltachains | ||||
and deltamode != repository.CG_DELTAMODE_PREV | ||||
): | ||||
|
r40456 | deltamode = repository.CG_DELTAMODE_FULL | ||
|
r40044 | return storageutil.emitrevisions( | ||
|
r43346 | 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, | ||
|
r43346 | assumehaveparentrevisions=assumehaveparentrevisions, | ||
|
r47449 | sidedata_helpers=sidedata_helpers, | ||
|
r43346 | ) | ||
|
r39898 | |||
|
r43347 | DELTAREUSEALWAYS = b'always' | ||
DELTAREUSESAMEREVS = b'samerevs' | ||||
DELTAREUSENEVER = b'never' | ||||
DELTAREUSEFULLADD = b'fulladd' | ||||
DELTAREUSEALL = {b'always', b'samerevs', b'never', b'fulladd'} | ||||
|
r30778 | |||
|
r43346 | def clone( | ||
self, | ||||
tr, | ||||
destrevlog, | ||||
addrevisioncb=None, | ||||
deltareuse=DELTAREUSESAMEREVS, | ||||
forcedeltabothparents=None, | ||||
|
r47847 | sidedata_helpers=None, | ||
|
r43346 | ): | ||
|
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. | ||||
r43403 | ||||
|
r47849 | See `revlogutil.sidedata.get_sidedata_helpers` for the doc on | ||
`sidedata_helpers`. | ||||
|
r30778 | """ | ||
if deltareuse not in self.DELTAREUSEALL: | ||||
|
r43347 | raise ValueError( | ||
_(b'value for deltareuse invalid: %s') % deltareuse | ||||
) | ||||
|
r30778 | |||
if len(destrevlog): | ||||
|
r43347 | raise ValueError(_(b'destination revlog is not empty')) | ||
|
r30778 | |||
if getattr(self, 'filteredrevs', None): | ||||
|
r43347 | raise ValueError(_(b'source revlog has filtered revisions')) | ||
|
r30778 | if getattr(destrevlog, 'filteredrevs', None): | ||
|
r43347 | raise ValueError(_(b'destination revlog has filtered revisions')) | ||
|
r30778 | |||
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 | |||
|
r43346 | self._clone( | ||
r43403 | tr, | |||
destrevlog, | ||||
addrevisioncb, | ||||
deltareuse, | ||||
forcedeltabothparents, | ||||
|
r47847 | sidedata_helpers, | ||
|
r43346 | ) | ||
r43266 | ||||
|
r30778 | finally: | ||
r42023 | destrevlog._lazydelta = oldlazydelta | |||
|
r30778 | destrevlog._lazydeltabase = oldlazydeltabase | ||
|
r38759 | destrevlog._deltabothparents = oldamd | ||
|
r39814 | |||
|
r43346 | def _clone( | ||
r43403 | self, | |||
tr, | ||||
destrevlog, | ||||
addrevisioncb, | ||||
deltareuse, | ||||
forcedeltabothparents, | ||||
|
r47847 | sidedata_helpers, | ||
|
r43346 | ): | ||
r43266 | """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. | ||||
|
r43346 | flags = entry[0] & 0xFFFF | ||
r43266 | 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 | ||||
|
r47847 | if deltareuse == self.DELTAREUSEFULLADD: | ||
r48177 | text = self._revisiondata(rev) | |||
r48176 | sidedata = self.sidedata(rev) | |||
|
r47847 | |||
if sidedata_helpers is not None: | ||||
|
r47848 | (sidedata, new_flags) = sidedatautil.run_sidedata_helpers( | ||
|
r47847 | self, sidedata_helpers, sidedata, rev | ||
) | ||||
flags = flags | new_flags[0] & ~new_flags[1] | ||||
r46327 | ||||
|
r43346 | destrevlog.addrevision( | ||
text, | ||||
tr, | ||||
linkrev, | ||||
p1, | ||||
p2, | ||||
cachedelta=cachedelta, | ||||
node=node, | ||||
flags=flags, | ||||
deltacomputer=deltacomputer, | ||||
r43403 | sidedata=sidedata, | |||
|
r43346 | ) | ||
r43266 | else: | |||
r43268 | if destrevlog._lazydelta: | |||
dp = self.deltaparent(rev) | ||||
if dp != nullrev: | ||||
cachedelta = (dp, bytes(self._chunk(rev))) | ||||
|
r47847 | sidedata = None | ||
r43268 | if not cachedelta: | |||
r48177 | rawtext = self._revisiondata(rev) | |||
r48176 | sidedata = self.sidedata(rev) | |||
|
r47847 | if sidedata is None: | ||
sidedata = self.sidedata(rev) | ||||
if sidedata_helpers is not None: | ||||
|
r47848 | (sidedata, new_flags) = sidedatautil.run_sidedata_helpers( | ||
|
r47847 | self, sidedata_helpers, sidedata, rev | ||
) | ||||
flags = flags | new_flags[0] & ~new_flags[1] | ||||
r43268 | ||||
r47988 | with destrevlog._writing(tr): | |||
|
r43346 | destrevlog._addrevision( | ||
node, | ||||
rawtext, | ||||
tr, | ||||
linkrev, | ||||
p1, | ||||
p2, | ||||
flags, | ||||
cachedelta, | ||||
deltacomputer=deltacomputer, | ||||
|
r47847 | sidedata=sidedata, | ||
|
r43346 | ) | ||
r43266 | ||||
if addrevisioncb: | ||||
addrevisioncb(self, rev, node) | ||||
|
r40092 | def censorrevision(self, tr, censornode, tombstone=b''): | ||
r47910 | if self._format_version == REVLOGV0: | |||
|
r43346 | raise error.RevlogError( | ||
r47910 | _(b'cannot censor with version %d revlogs') | |||
% self._format_version | ||||
|
r43346 | ) | ||
r48183 | elif self._format_version == REVLOGV1: | |||
r48257 | rewrite.v1_censor(self, tr, censornode, tombstone) | |||
r48183 | else: | |||
r48257 | rewrite.v2_censor(self, tr, censornode, tombstone) | |||
|
r39814 | |||
|
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: | ||||
|
r43347 | yield revlogproblem(error=_(b'data length off by %d bytes') % dd) | ||
|
r39878 | if di: | ||
|
r43347 | yield revlogproblem(error=_(b'index contains %d extra bytes') % di) | ||
|
r39878 | |||
r47910 | version = self._format_version | |||
|
r39881 | |||
# The verifier tells us what version revlog we should be. | ||||
|
r43347 | if version != state[b'expectedversion']: | ||
|
r39881 | yield revlogproblem( | ||
|
r43347 | warning=_(b"warning: '%s' uses revlog format %d; expected %d") | ||
r47928 | % (self.display_id, version, state[b'expectedversion']) | |||
|
r43346 | ) | ||
|
r39905 | |||
|
r43347 | state[b'skipread'] = set() | ||
|
r44530 | state[b'safe_renamed'] = set() | ||
|
r39908 | |||
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: | ||||
|
r43347 | skipflags = state.get(b'skipflags', 0) | ||
|
r39908 | if skipflags: | ||
skipflags &= self.flags(rev) | ||||
|
r44409 | _verify_revision(self, skipflags, state, node) | ||
|
r39908 | |||
l1 = self.rawsize(rev) | ||||
r43036 | l2 = len(self.rawdata(node)) | |||
|
r39908 | |||
if l1 != l2: | ||||
yield revlogproblem( | ||||
|
r43347 | error=_(b'unpacked size is %d, %d expected') % (l2, l1), | ||
|
r43346 | node=node, | ||
) | ||||
|
r39908 | |||
except error.CensoredNodeError: | ||||
|
r43347 | if state[b'erroroncensored']: | ||
|
r43346 | yield revlogproblem( | ||
|
r43347 | error=_(b'censored file data'), node=node | ||
|
r43346 | ) | ||
|
r43347 | state[b'skipread'].add(node) | ||
|
r39908 | except Exception as e: | ||
yield revlogproblem( | ||||
|
r43347 | error=_(b'unpacking %s: %s') | ||
|
r43346 | % (short(node), stringutil.forcebytestr(e)), | ||
node=node, | ||||
) | ||||
|
r43347 | state[b'skipread'].add(node) | ||
|
r39908 | |||
|
r43346 | def storageinfo( | ||
self, | ||||
exclusivefiles=False, | ||||
sharedfiles=False, | ||||
revisionscount=False, | ||||
trackedsize=False, | ||||
storedsize=False, | ||||
): | ||||
|
r39905 | d = {} | ||
if exclusivefiles: | ||||
r47919 | d[b'exclusivefiles'] = [(self.opener, self._indexfile)] | |||
|
r39905 | if not self._inline: | ||
r47920 | d[b'exclusivefiles'].append((self.opener, self._datafile)) | |||
|
r39905 | |||
if sharedfiles: | ||||
|
r43347 | d[b'sharedfiles'] = [] | ||
|
r39905 | |||
if revisionscount: | ||||
|
r43347 | d[b'revisionscount'] = len(self) | ||
|
r39905 | |||
if trackedsize: | ||||
|
r43347 | d[b'trackedsize'] = sum(map(self.rawsize, iter(self))) | ||
|
r39905 | |||
if storedsize: | ||||
|
r43347 | d[b'storedsize'] = sum( | ||
|
r43346 | self.opener.stat(path).st_size for path in self.files() | ||
) | ||||
|
r39905 | |||
return d | ||||
|
r47452 | |||
r47990 | def rewrite_sidedata(self, transaction, helpers, startrev, endrev): | |||
r47907 | if not self.hassidedata: | |||
|
r47452 | return | ||
r48008 | # revlog formats with sidedata support does not support inline | |||
|
r47452 | assert not self._inline | ||
if not helpers[1] and not helpers[2]: | ||||
# Nothing to generate or remove | ||||
return | ||||
new_entries = [] | ||||
# append the new sidedata | ||||
r47992 | with self._writing(transaction): | |||
r48181 | ifh, dfh, sdfh = self._writinghandles | |||
dfh.seek(self._docket.sidedata_end, os.SEEK_SET) | ||||
current_offset = sdfh.tell() | ||||
|
r47452 | for rev in range(startrev, endrev + 1): | ||
entry = self.index[rev] | ||||
|
r47848 | new_sidedata, flags = sidedatautil.run_sidedata_helpers( | ||
|
r47452 | store=self, | ||
sidedata_helpers=helpers, | ||||
sidedata={}, | ||||
rev=rev, | ||||
) | ||||
serialized_sidedata = sidedatautil.serialize_sidedata( | ||||
new_sidedata | ||||
) | ||||
r48033 | ||||
sidedata_compression_mode = COMP_MODE_INLINE | ||||
if serialized_sidedata and self.hassidedata: | ||||
sidedata_compression_mode = COMP_MODE_PLAIN | ||||
h, comp_sidedata = self.compress(serialized_sidedata) | ||||
if ( | ||||
h != b'u' | ||||
and comp_sidedata[0] != b'\0' | ||||
and len(comp_sidedata) < len(serialized_sidedata) | ||||
): | ||||
assert not h | ||||
if ( | ||||
comp_sidedata[0] | ||||
== self._docket.default_compression_header | ||||
): | ||||
sidedata_compression_mode = COMP_MODE_DEFAULT | ||||
serialized_sidedata = comp_sidedata | ||||
else: | ||||
sidedata_compression_mode = COMP_MODE_INLINE | ||||
serialized_sidedata = comp_sidedata | ||||
|
r47452 | if entry[8] != 0 or entry[9] != 0: | ||
# rewriting entries that already have sidedata is not | ||||
# supported yet, because it introduces garbage data in the | ||||
# revlog. | ||||
r48002 | msg = b"rewriting existing sidedata is not supported yet" | |||
|
r47452 | raise error.Abort(msg) | ||
|
r47844 | |||
# Apply (potential) flags to add and to remove after running | ||||
# the sidedata helpers | ||||
new_offset_flags = entry[0] | flags[0] & ~flags[1] | ||||
r48019 | entry_update = ( | |||
current_offset, | ||||
len(serialized_sidedata), | ||||
new_offset_flags, | ||||
r48033 | sidedata_compression_mode, | |||
r48019 | ) | |||
|
r47452 | |||
r47991 | # the sidedata computation might have move the file cursors around | |||
r48181 | sdfh.seek(current_offset, os.SEEK_SET) | |||
sdfh.write(serialized_sidedata) | ||||
r48019 | new_entries.append(entry_update) | |||
|
r47452 | current_offset += len(serialized_sidedata) | ||
r48181 | self._docket.sidedata_end = sdfh.tell() | |||
|
r47452 | |||
r47992 | # rewrite the new index entries | |||
ifh.seek(startrev * self.index.entry_size) | ||||
|
r47844 | for i, e in enumerate(new_entries): | ||
|
r47452 | rev = startrev + i | ||
r48019 | self.index.replace_sidedata_info(rev, *e) | |||
r47811 | packed = self.index.entry_binary(rev) | |||
r48009 | if rev == 0 and self._docket is None: | |||
r47910 | header = self._format_flags | self._format_version | |||
header = self.index.pack_header(header) | ||||
r47811 | packed = header + packed | |||
r47989 | ifh.write(packed) | |||