##// END OF EJS Templates
rank: compute property incrementally...
pacien -
r49610:58066051 default
parent child Browse files
Show More
@@ -1,3298 +1,3307 b''
1 # revlog.py - storage back-end for mercurial
1 # revlog.py - storage back-end for mercurial
2 # coding: utf8
2 # coding: utf8
3 #
3 #
4 # Copyright 2005-2007 Olivia Mackall <olivia@selenic.com>
4 # Copyright 2005-2007 Olivia Mackall <olivia@selenic.com>
5 #
5 #
6 # This software may be used and distributed according to the terms of the
6 # This software may be used and distributed according to the terms of the
7 # GNU General Public License version 2 or any later version.
7 # GNU General Public License version 2 or any later version.
8
8
9 """Storage back-end for Mercurial.
9 """Storage back-end for Mercurial.
10
10
11 This provides efficient delta storage with O(1) retrieve and append
11 This provides efficient delta storage with O(1) retrieve and append
12 and O(changes) merge between branches.
12 and O(changes) merge between branches.
13 """
13 """
14
14
15 from __future__ import absolute_import
15 from __future__ import absolute_import
16
16
17 import binascii
17 import binascii
18 import collections
18 import collections
19 import contextlib
19 import contextlib
20 import errno
20 import errno
21 import io
21 import io
22 import os
22 import os
23 import struct
23 import struct
24 import zlib
24 import zlib
25
25
26 # import stuff from node for others to import from revlog
26 # import stuff from node for others to import from revlog
27 from .node import (
27 from .node import (
28 bin,
28 bin,
29 hex,
29 hex,
30 nullrev,
30 nullrev,
31 sha1nodeconstants,
31 sha1nodeconstants,
32 short,
32 short,
33 wdirrev,
33 wdirrev,
34 )
34 )
35 from .i18n import _
35 from .i18n import _
36 from .pycompat import getattr
36 from .pycompat import getattr
37 from .revlogutils.constants import (
37 from .revlogutils.constants import (
38 ALL_KINDS,
38 ALL_KINDS,
39 CHANGELOGV2,
39 CHANGELOGV2,
40 COMP_MODE_DEFAULT,
40 COMP_MODE_DEFAULT,
41 COMP_MODE_INLINE,
41 COMP_MODE_INLINE,
42 COMP_MODE_PLAIN,
42 COMP_MODE_PLAIN,
43 ENTRY_RANK,
43 ENTRY_RANK,
44 FEATURES_BY_VERSION,
44 FEATURES_BY_VERSION,
45 FLAG_GENERALDELTA,
45 FLAG_GENERALDELTA,
46 FLAG_INLINE_DATA,
46 FLAG_INLINE_DATA,
47 INDEX_HEADER,
47 INDEX_HEADER,
48 KIND_CHANGELOG,
48 KIND_CHANGELOG,
49 RANK_UNKNOWN,
49 RANK_UNKNOWN,
50 REVLOGV0,
50 REVLOGV0,
51 REVLOGV1,
51 REVLOGV1,
52 REVLOGV1_FLAGS,
52 REVLOGV1_FLAGS,
53 REVLOGV2,
53 REVLOGV2,
54 REVLOGV2_FLAGS,
54 REVLOGV2_FLAGS,
55 REVLOG_DEFAULT_FLAGS,
55 REVLOG_DEFAULT_FLAGS,
56 REVLOG_DEFAULT_FORMAT,
56 REVLOG_DEFAULT_FORMAT,
57 REVLOG_DEFAULT_VERSION,
57 REVLOG_DEFAULT_VERSION,
58 SUPPORTED_FLAGS,
58 SUPPORTED_FLAGS,
59 )
59 )
60 from .revlogutils.flagutil import (
60 from .revlogutils.flagutil import (
61 REVIDX_DEFAULT_FLAGS,
61 REVIDX_DEFAULT_FLAGS,
62 REVIDX_ELLIPSIS,
62 REVIDX_ELLIPSIS,
63 REVIDX_EXTSTORED,
63 REVIDX_EXTSTORED,
64 REVIDX_FLAGS_ORDER,
64 REVIDX_FLAGS_ORDER,
65 REVIDX_HASCOPIESINFO,
65 REVIDX_HASCOPIESINFO,
66 REVIDX_ISCENSORED,
66 REVIDX_ISCENSORED,
67 REVIDX_RAWTEXT_CHANGING_FLAGS,
67 REVIDX_RAWTEXT_CHANGING_FLAGS,
68 )
68 )
69 from .thirdparty import attr
69 from .thirdparty import attr
70 from . import (
70 from . import (
71 ancestor,
71 ancestor,
72 dagop,
72 dagop,
73 error,
73 error,
74 mdiff,
74 mdiff,
75 policy,
75 policy,
76 pycompat,
76 pycompat,
77 revlogutils,
77 revlogutils,
78 templatefilters,
78 templatefilters,
79 util,
79 util,
80 )
80 )
81 from .interfaces import (
81 from .interfaces import (
82 repository,
82 repository,
83 util as interfaceutil,
83 util as interfaceutil,
84 )
84 )
85 from .revlogutils import (
85 from .revlogutils import (
86 deltas as deltautil,
86 deltas as deltautil,
87 docket as docketutil,
87 docket as docketutil,
88 flagutil,
88 flagutil,
89 nodemap as nodemaputil,
89 nodemap as nodemaputil,
90 randomaccessfile,
90 randomaccessfile,
91 revlogv0,
91 revlogv0,
92 rewrite,
92 rewrite,
93 sidedata as sidedatautil,
93 sidedata as sidedatautil,
94 )
94 )
95 from .utils import (
95 from .utils import (
96 storageutil,
96 storageutil,
97 stringutil,
97 stringutil,
98 )
98 )
99
99
100 # blanked usage of all the name to prevent pyflakes constraints
100 # blanked usage of all the name to prevent pyflakes constraints
101 # We need these name available in the module for extensions.
101 # We need these name available in the module for extensions.
102
102
103 REVLOGV0
103 REVLOGV0
104 REVLOGV1
104 REVLOGV1
105 REVLOGV2
105 REVLOGV2
106 FLAG_INLINE_DATA
106 FLAG_INLINE_DATA
107 FLAG_GENERALDELTA
107 FLAG_GENERALDELTA
108 REVLOG_DEFAULT_FLAGS
108 REVLOG_DEFAULT_FLAGS
109 REVLOG_DEFAULT_FORMAT
109 REVLOG_DEFAULT_FORMAT
110 REVLOG_DEFAULT_VERSION
110 REVLOG_DEFAULT_VERSION
111 REVLOGV1_FLAGS
111 REVLOGV1_FLAGS
112 REVLOGV2_FLAGS
112 REVLOGV2_FLAGS
113 REVIDX_ISCENSORED
113 REVIDX_ISCENSORED
114 REVIDX_ELLIPSIS
114 REVIDX_ELLIPSIS
115 REVIDX_HASCOPIESINFO
115 REVIDX_HASCOPIESINFO
116 REVIDX_EXTSTORED
116 REVIDX_EXTSTORED
117 REVIDX_DEFAULT_FLAGS
117 REVIDX_DEFAULT_FLAGS
118 REVIDX_FLAGS_ORDER
118 REVIDX_FLAGS_ORDER
119 REVIDX_RAWTEXT_CHANGING_FLAGS
119 REVIDX_RAWTEXT_CHANGING_FLAGS
120
120
121 parsers = policy.importmod('parsers')
121 parsers = policy.importmod('parsers')
122 rustancestor = policy.importrust('ancestor')
122 rustancestor = policy.importrust('ancestor')
123 rustdagop = policy.importrust('dagop')
123 rustdagop = policy.importrust('dagop')
124 rustrevlog = policy.importrust('revlog')
124 rustrevlog = policy.importrust('revlog')
125
125
126 # Aliased for performance.
126 # Aliased for performance.
127 _zlibdecompress = zlib.decompress
127 _zlibdecompress = zlib.decompress
128
128
129 # max size of revlog with inline data
129 # max size of revlog with inline data
130 _maxinline = 131072
130 _maxinline = 131072
131
131
132 # Flag processors for REVIDX_ELLIPSIS.
132 # Flag processors for REVIDX_ELLIPSIS.
133 def ellipsisreadprocessor(rl, text):
133 def ellipsisreadprocessor(rl, text):
134 return text, False
134 return text, False
135
135
136
136
137 def ellipsiswriteprocessor(rl, text):
137 def ellipsiswriteprocessor(rl, text):
138 return text, False
138 return text, False
139
139
140
140
141 def ellipsisrawprocessor(rl, text):
141 def ellipsisrawprocessor(rl, text):
142 return False
142 return False
143
143
144
144
145 ellipsisprocessor = (
145 ellipsisprocessor = (
146 ellipsisreadprocessor,
146 ellipsisreadprocessor,
147 ellipsiswriteprocessor,
147 ellipsiswriteprocessor,
148 ellipsisrawprocessor,
148 ellipsisrawprocessor,
149 )
149 )
150
150
151
151
152 def _verify_revision(rl, skipflags, state, node):
152 def _verify_revision(rl, skipflags, state, node):
153 """Verify the integrity of the given revlog ``node`` while providing a hook
153 """Verify the integrity of the given revlog ``node`` while providing a hook
154 point for extensions to influence the operation."""
154 point for extensions to influence the operation."""
155 if skipflags:
155 if skipflags:
156 state[b'skipread'].add(node)
156 state[b'skipread'].add(node)
157 else:
157 else:
158 # Side-effect: read content and verify hash.
158 # Side-effect: read content and verify hash.
159 rl.revision(node)
159 rl.revision(node)
160
160
161
161
162 # True if a fast implementation for persistent-nodemap is available
162 # True if a fast implementation for persistent-nodemap is available
163 #
163 #
164 # We also consider we have a "fast" implementation in "pure" python because
164 # We also consider we have a "fast" implementation in "pure" python because
165 # people using pure don't really have performance consideration (and a
165 # people using pure don't really have performance consideration (and a
166 # wheelbarrow of other slowness source)
166 # wheelbarrow of other slowness source)
167 HAS_FAST_PERSISTENT_NODEMAP = rustrevlog is not None or util.safehasattr(
167 HAS_FAST_PERSISTENT_NODEMAP = rustrevlog is not None or util.safehasattr(
168 parsers, 'BaseIndexObject'
168 parsers, 'BaseIndexObject'
169 )
169 )
170
170
171
171
172 @interfaceutil.implementer(repository.irevisiondelta)
172 @interfaceutil.implementer(repository.irevisiondelta)
173 @attr.s(slots=True)
173 @attr.s(slots=True)
174 class revlogrevisiondelta(object):
174 class revlogrevisiondelta(object):
175 node = attr.ib()
175 node = attr.ib()
176 p1node = attr.ib()
176 p1node = attr.ib()
177 p2node = attr.ib()
177 p2node = attr.ib()
178 basenode = attr.ib()
178 basenode = attr.ib()
179 flags = attr.ib()
179 flags = attr.ib()
180 baserevisionsize = attr.ib()
180 baserevisionsize = attr.ib()
181 revision = attr.ib()
181 revision = attr.ib()
182 delta = attr.ib()
182 delta = attr.ib()
183 sidedata = attr.ib()
183 sidedata = attr.ib()
184 protocol_flags = attr.ib()
184 protocol_flags = attr.ib()
185 linknode = attr.ib(default=None)
185 linknode = attr.ib(default=None)
186
186
187
187
188 @interfaceutil.implementer(repository.iverifyproblem)
188 @interfaceutil.implementer(repository.iverifyproblem)
189 @attr.s(frozen=True)
189 @attr.s(frozen=True)
190 class revlogproblem(object):
190 class revlogproblem(object):
191 warning = attr.ib(default=None)
191 warning = attr.ib(default=None)
192 error = attr.ib(default=None)
192 error = attr.ib(default=None)
193 node = attr.ib(default=None)
193 node = attr.ib(default=None)
194
194
195
195
196 def parse_index_v1(data, inline):
196 def parse_index_v1(data, inline):
197 # call the C implementation to parse the index data
197 # call the C implementation to parse the index data
198 index, cache = parsers.parse_index2(data, inline)
198 index, cache = parsers.parse_index2(data, inline)
199 return index, cache
199 return index, cache
200
200
201
201
202 def parse_index_v2(data, inline):
202 def parse_index_v2(data, inline):
203 # call the C implementation to parse the index data
203 # call the C implementation to parse the index data
204 index, cache = parsers.parse_index2(data, inline, revlogv2=True)
204 index, cache = parsers.parse_index2(data, inline, revlogv2=True)
205 return index, cache
205 return index, cache
206
206
207
207
208 def parse_index_cl_v2(data, inline):
208 def parse_index_cl_v2(data, inline):
209 # call the C implementation to parse the index data
209 # call the C implementation to parse the index data
210 assert not inline
210 assert not inline
211 from .pure.parsers import parse_index_cl_v2
211 from .pure.parsers import parse_index_cl_v2
212
212
213 index, cache = parse_index_cl_v2(data)
213 index, cache = parse_index_cl_v2(data)
214 return index, cache
214 return index, cache
215
215
216
216
217 if util.safehasattr(parsers, 'parse_index_devel_nodemap'):
217 if util.safehasattr(parsers, 'parse_index_devel_nodemap'):
218
218
219 def parse_index_v1_nodemap(data, inline):
219 def parse_index_v1_nodemap(data, inline):
220 index, cache = parsers.parse_index_devel_nodemap(data, inline)
220 index, cache = parsers.parse_index_devel_nodemap(data, inline)
221 return index, cache
221 return index, cache
222
222
223
223
224 else:
224 else:
225 parse_index_v1_nodemap = None
225 parse_index_v1_nodemap = None
226
226
227
227
228 def parse_index_v1_mixed(data, inline):
228 def parse_index_v1_mixed(data, inline):
229 index, cache = parse_index_v1(data, inline)
229 index, cache = parse_index_v1(data, inline)
230 return rustrevlog.MixedIndex(index), cache
230 return rustrevlog.MixedIndex(index), cache
231
231
232
232
233 # corresponds to uncompressed length of indexformatng (2 gigs, 4-byte
233 # corresponds to uncompressed length of indexformatng (2 gigs, 4-byte
234 # signed integer)
234 # signed integer)
235 _maxentrysize = 0x7FFFFFFF
235 _maxentrysize = 0x7FFFFFFF
236
236
237 FILE_TOO_SHORT_MSG = _(
237 FILE_TOO_SHORT_MSG = _(
238 b'cannot read from revlog %s;'
238 b'cannot read from revlog %s;'
239 b' expected %d bytes from offset %d, data size is %d'
239 b' expected %d bytes from offset %d, data size is %d'
240 )
240 )
241
241
242
242
243 class revlog(object):
243 class revlog(object):
244 """
244 """
245 the underlying revision storage object
245 the underlying revision storage object
246
246
247 A revlog consists of two parts, an index and the revision data.
247 A revlog consists of two parts, an index and the revision data.
248
248
249 The index is a file with a fixed record size containing
249 The index is a file with a fixed record size containing
250 information on each revision, including its nodeid (hash), the
250 information on each revision, including its nodeid (hash), the
251 nodeids of its parents, the position and offset of its data within
251 nodeids of its parents, the position and offset of its data within
252 the data file, and the revision it's based on. Finally, each entry
252 the data file, and the revision it's based on. Finally, each entry
253 contains a linkrev entry that can serve as a pointer to external
253 contains a linkrev entry that can serve as a pointer to external
254 data.
254 data.
255
255
256 The revision data itself is a linear collection of data chunks.
256 The revision data itself is a linear collection of data chunks.
257 Each chunk represents a revision and is usually represented as a
257 Each chunk represents a revision and is usually represented as a
258 delta against the previous chunk. To bound lookup time, runs of
258 delta against the previous chunk. To bound lookup time, runs of
259 deltas are limited to about 2 times the length of the original
259 deltas are limited to about 2 times the length of the original
260 version data. This makes retrieval of a version proportional to
260 version data. This makes retrieval of a version proportional to
261 its size, or O(1) relative to the number of revisions.
261 its size, or O(1) relative to the number of revisions.
262
262
263 Both pieces of the revlog are written to in an append-only
263 Both pieces of the revlog are written to in an append-only
264 fashion, which means we never need to rewrite a file to insert or
264 fashion, which means we never need to rewrite a file to insert or
265 remove data, and can use some simple techniques to avoid the need
265 remove data, and can use some simple techniques to avoid the need
266 for locking while reading.
266 for locking while reading.
267
267
268 If checkambig, indexfile is opened with checkambig=True at
268 If checkambig, indexfile is opened with checkambig=True at
269 writing, to avoid file stat ambiguity.
269 writing, to avoid file stat ambiguity.
270
270
271 If mmaplargeindex is True, and an mmapindexthreshold is set, the
271 If mmaplargeindex is True, and an mmapindexthreshold is set, the
272 index will be mmapped rather than read if it is larger than the
272 index will be mmapped rather than read if it is larger than the
273 configured threshold.
273 configured threshold.
274
274
275 If censorable is True, the revlog can have censored revisions.
275 If censorable is True, the revlog can have censored revisions.
276
276
277 If `upperboundcomp` is not None, this is the expected maximal gain from
277 If `upperboundcomp` is not None, this is the expected maximal gain from
278 compression for the data content.
278 compression for the data content.
279
279
280 `concurrencychecker` is an optional function that receives 3 arguments: a
280 `concurrencychecker` is an optional function that receives 3 arguments: a
281 file handle, a filename, and an expected position. It should check whether
281 file handle, a filename, and an expected position. It should check whether
282 the current position in the file handle is valid, and log/warn/fail (by
282 the current position in the file handle is valid, and log/warn/fail (by
283 raising).
283 raising).
284
284
285 See mercurial/revlogutils/contants.py for details about the content of an
285 See mercurial/revlogutils/contants.py for details about the content of an
286 index entry.
286 index entry.
287 """
287 """
288
288
289 _flagserrorclass = error.RevlogError
289 _flagserrorclass = error.RevlogError
290
290
291 def __init__(
291 def __init__(
292 self,
292 self,
293 opener,
293 opener,
294 target,
294 target,
295 radix,
295 radix,
296 postfix=None, # only exist for `tmpcensored` now
296 postfix=None, # only exist for `tmpcensored` now
297 checkambig=False,
297 checkambig=False,
298 mmaplargeindex=False,
298 mmaplargeindex=False,
299 censorable=False,
299 censorable=False,
300 upperboundcomp=None,
300 upperboundcomp=None,
301 persistentnodemap=False,
301 persistentnodemap=False,
302 concurrencychecker=None,
302 concurrencychecker=None,
303 trypending=False,
303 trypending=False,
304 ):
304 ):
305 """
305 """
306 create a revlog object
306 create a revlog object
307
307
308 opener is a function that abstracts the file opening operation
308 opener is a function that abstracts the file opening operation
309 and can be used to implement COW semantics or the like.
309 and can be used to implement COW semantics or the like.
310
310
311 `target`: a (KIND, ID) tuple that identify the content stored in
311 `target`: a (KIND, ID) tuple that identify the content stored in
312 this revlog. It help the rest of the code to understand what the revlog
312 this revlog. It help the rest of the code to understand what the revlog
313 is about without having to resort to heuristic and index filename
313 is about without having to resort to heuristic and index filename
314 analysis. Note: that this must be reliably be set by normal code, but
314 analysis. Note: that this must be reliably be set by normal code, but
315 that test, debug, or performance measurement code might not set this to
315 that test, debug, or performance measurement code might not set this to
316 accurate value.
316 accurate value.
317 """
317 """
318 self.upperboundcomp = upperboundcomp
318 self.upperboundcomp = upperboundcomp
319
319
320 self.radix = radix
320 self.radix = radix
321
321
322 self._docket_file = None
322 self._docket_file = None
323 self._indexfile = None
323 self._indexfile = None
324 self._datafile = None
324 self._datafile = None
325 self._sidedatafile = None
325 self._sidedatafile = None
326 self._nodemap_file = None
326 self._nodemap_file = None
327 self.postfix = postfix
327 self.postfix = postfix
328 self._trypending = trypending
328 self._trypending = trypending
329 self.opener = opener
329 self.opener = opener
330 if persistentnodemap:
330 if persistentnodemap:
331 self._nodemap_file = nodemaputil.get_nodemap_file(self)
331 self._nodemap_file = nodemaputil.get_nodemap_file(self)
332
332
333 assert target[0] in ALL_KINDS
333 assert target[0] in ALL_KINDS
334 assert len(target) == 2
334 assert len(target) == 2
335 self.target = target
335 self.target = target
336 # When True, indexfile is opened with checkambig=True at writing, to
336 # When True, indexfile is opened with checkambig=True at writing, to
337 # avoid file stat ambiguity.
337 # avoid file stat ambiguity.
338 self._checkambig = checkambig
338 self._checkambig = checkambig
339 self._mmaplargeindex = mmaplargeindex
339 self._mmaplargeindex = mmaplargeindex
340 self._censorable = censorable
340 self._censorable = censorable
341 # 3-tuple of (node, rev, text) for a raw revision.
341 # 3-tuple of (node, rev, text) for a raw revision.
342 self._revisioncache = None
342 self._revisioncache = None
343 # Maps rev to chain base rev.
343 # Maps rev to chain base rev.
344 self._chainbasecache = util.lrucachedict(100)
344 self._chainbasecache = util.lrucachedict(100)
345 # 2-tuple of (offset, data) of raw data from the revlog at an offset.
345 # 2-tuple of (offset, data) of raw data from the revlog at an offset.
346 self._chunkcache = (0, b'')
346 self._chunkcache = (0, b'')
347 # How much data to read and cache into the raw revlog data cache.
347 # How much data to read and cache into the raw revlog data cache.
348 self._chunkcachesize = 65536
348 self._chunkcachesize = 65536
349 self._maxchainlen = None
349 self._maxchainlen = None
350 self._deltabothparents = True
350 self._deltabothparents = True
351 self.index = None
351 self.index = None
352 self._docket = None
352 self._docket = None
353 self._nodemap_docket = None
353 self._nodemap_docket = None
354 # Mapping of partial identifiers to full nodes.
354 # Mapping of partial identifiers to full nodes.
355 self._pcache = {}
355 self._pcache = {}
356 # Mapping of revision integer to full node.
356 # Mapping of revision integer to full node.
357 self._compengine = b'zlib'
357 self._compengine = b'zlib'
358 self._compengineopts = {}
358 self._compengineopts = {}
359 self._maxdeltachainspan = -1
359 self._maxdeltachainspan = -1
360 self._withsparseread = False
360 self._withsparseread = False
361 self._sparserevlog = False
361 self._sparserevlog = False
362 self.hassidedata = False
362 self.hassidedata = False
363 self._srdensitythreshold = 0.50
363 self._srdensitythreshold = 0.50
364 self._srmingapsize = 262144
364 self._srmingapsize = 262144
365
365
366 # Make copy of flag processors so each revlog instance can support
366 # Make copy of flag processors so each revlog instance can support
367 # custom flags.
367 # custom flags.
368 self._flagprocessors = dict(flagutil.flagprocessors)
368 self._flagprocessors = dict(flagutil.flagprocessors)
369
369
370 # 3-tuple of file handles being used for active writing.
370 # 3-tuple of file handles being used for active writing.
371 self._writinghandles = None
371 self._writinghandles = None
372 # prevent nesting of addgroup
372 # prevent nesting of addgroup
373 self._adding_group = None
373 self._adding_group = None
374
374
375 self._loadindex()
375 self._loadindex()
376
376
377 self._concurrencychecker = concurrencychecker
377 self._concurrencychecker = concurrencychecker
378
378
379 def _init_opts(self):
379 def _init_opts(self):
380 """process options (from above/config) to setup associated default revlog mode
380 """process options (from above/config) to setup associated default revlog mode
381
381
382 These values might be affected when actually reading on disk information.
382 These values might be affected when actually reading on disk information.
383
383
384 The relevant values are returned for use in _loadindex().
384 The relevant values are returned for use in _loadindex().
385
385
386 * newversionflags:
386 * newversionflags:
387 version header to use if we need to create a new revlog
387 version header to use if we need to create a new revlog
388
388
389 * mmapindexthreshold:
389 * mmapindexthreshold:
390 minimal index size for start to use mmap
390 minimal index size for start to use mmap
391
391
392 * force_nodemap:
392 * force_nodemap:
393 force the usage of a "development" version of the nodemap code
393 force the usage of a "development" version of the nodemap code
394 """
394 """
395 mmapindexthreshold = None
395 mmapindexthreshold = None
396 opts = self.opener.options
396 opts = self.opener.options
397
397
398 if b'changelogv2' in opts and self.revlog_kind == KIND_CHANGELOG:
398 if b'changelogv2' in opts and self.revlog_kind == KIND_CHANGELOG:
399 new_header = CHANGELOGV2
399 new_header = CHANGELOGV2
400 elif b'revlogv2' in opts:
400 elif b'revlogv2' in opts:
401 new_header = REVLOGV2
401 new_header = REVLOGV2
402 elif b'revlogv1' in opts:
402 elif b'revlogv1' in opts:
403 new_header = REVLOGV1 | FLAG_INLINE_DATA
403 new_header = REVLOGV1 | FLAG_INLINE_DATA
404 if b'generaldelta' in opts:
404 if b'generaldelta' in opts:
405 new_header |= FLAG_GENERALDELTA
405 new_header |= FLAG_GENERALDELTA
406 elif b'revlogv0' in self.opener.options:
406 elif b'revlogv0' in self.opener.options:
407 new_header = REVLOGV0
407 new_header = REVLOGV0
408 else:
408 else:
409 new_header = REVLOG_DEFAULT_VERSION
409 new_header = REVLOG_DEFAULT_VERSION
410
410
411 if b'chunkcachesize' in opts:
411 if b'chunkcachesize' in opts:
412 self._chunkcachesize = opts[b'chunkcachesize']
412 self._chunkcachesize = opts[b'chunkcachesize']
413 if b'maxchainlen' in opts:
413 if b'maxchainlen' in opts:
414 self._maxchainlen = opts[b'maxchainlen']
414 self._maxchainlen = opts[b'maxchainlen']
415 if b'deltabothparents' in opts:
415 if b'deltabothparents' in opts:
416 self._deltabothparents = opts[b'deltabothparents']
416 self._deltabothparents = opts[b'deltabothparents']
417 self._lazydelta = bool(opts.get(b'lazydelta', True))
417 self._lazydelta = bool(opts.get(b'lazydelta', True))
418 self._lazydeltabase = False
418 self._lazydeltabase = False
419 if self._lazydelta:
419 if self._lazydelta:
420 self._lazydeltabase = bool(opts.get(b'lazydeltabase', False))
420 self._lazydeltabase = bool(opts.get(b'lazydeltabase', False))
421 if b'compengine' in opts:
421 if b'compengine' in opts:
422 self._compengine = opts[b'compengine']
422 self._compengine = opts[b'compengine']
423 if b'zlib.level' in opts:
423 if b'zlib.level' in opts:
424 self._compengineopts[b'zlib.level'] = opts[b'zlib.level']
424 self._compengineopts[b'zlib.level'] = opts[b'zlib.level']
425 if b'zstd.level' in opts:
425 if b'zstd.level' in opts:
426 self._compengineopts[b'zstd.level'] = opts[b'zstd.level']
426 self._compengineopts[b'zstd.level'] = opts[b'zstd.level']
427 if b'maxdeltachainspan' in opts:
427 if b'maxdeltachainspan' in opts:
428 self._maxdeltachainspan = opts[b'maxdeltachainspan']
428 self._maxdeltachainspan = opts[b'maxdeltachainspan']
429 if self._mmaplargeindex and b'mmapindexthreshold' in opts:
429 if self._mmaplargeindex and b'mmapindexthreshold' in opts:
430 mmapindexthreshold = opts[b'mmapindexthreshold']
430 mmapindexthreshold = opts[b'mmapindexthreshold']
431 self._sparserevlog = bool(opts.get(b'sparse-revlog', False))
431 self._sparserevlog = bool(opts.get(b'sparse-revlog', False))
432 withsparseread = bool(opts.get(b'with-sparse-read', False))
432 withsparseread = bool(opts.get(b'with-sparse-read', False))
433 # sparse-revlog forces sparse-read
433 # sparse-revlog forces sparse-read
434 self._withsparseread = self._sparserevlog or withsparseread
434 self._withsparseread = self._sparserevlog or withsparseread
435 if b'sparse-read-density-threshold' in opts:
435 if b'sparse-read-density-threshold' in opts:
436 self._srdensitythreshold = opts[b'sparse-read-density-threshold']
436 self._srdensitythreshold = opts[b'sparse-read-density-threshold']
437 if b'sparse-read-min-gap-size' in opts:
437 if b'sparse-read-min-gap-size' in opts:
438 self._srmingapsize = opts[b'sparse-read-min-gap-size']
438 self._srmingapsize = opts[b'sparse-read-min-gap-size']
439 if opts.get(b'enableellipsis'):
439 if opts.get(b'enableellipsis'):
440 self._flagprocessors[REVIDX_ELLIPSIS] = ellipsisprocessor
440 self._flagprocessors[REVIDX_ELLIPSIS] = ellipsisprocessor
441
441
442 # revlog v0 doesn't have flag processors
442 # revlog v0 doesn't have flag processors
443 for flag, processor in pycompat.iteritems(
443 for flag, processor in pycompat.iteritems(
444 opts.get(b'flagprocessors', {})
444 opts.get(b'flagprocessors', {})
445 ):
445 ):
446 flagutil.insertflagprocessor(flag, processor, self._flagprocessors)
446 flagutil.insertflagprocessor(flag, processor, self._flagprocessors)
447
447
448 if self._chunkcachesize <= 0:
448 if self._chunkcachesize <= 0:
449 raise error.RevlogError(
449 raise error.RevlogError(
450 _(b'revlog chunk cache size %r is not greater than 0')
450 _(b'revlog chunk cache size %r is not greater than 0')
451 % self._chunkcachesize
451 % self._chunkcachesize
452 )
452 )
453 elif self._chunkcachesize & (self._chunkcachesize - 1):
453 elif self._chunkcachesize & (self._chunkcachesize - 1):
454 raise error.RevlogError(
454 raise error.RevlogError(
455 _(b'revlog chunk cache size %r is not a power of 2')
455 _(b'revlog chunk cache size %r is not a power of 2')
456 % self._chunkcachesize
456 % self._chunkcachesize
457 )
457 )
458 force_nodemap = opts.get(b'devel-force-nodemap', False)
458 force_nodemap = opts.get(b'devel-force-nodemap', False)
459 return new_header, mmapindexthreshold, force_nodemap
459 return new_header, mmapindexthreshold, force_nodemap
460
460
461 def _get_data(self, filepath, mmap_threshold, size=None):
461 def _get_data(self, filepath, mmap_threshold, size=None):
462 """return a file content with or without mmap
462 """return a file content with or without mmap
463
463
464 If the file is missing return the empty string"""
464 If the file is missing return the empty string"""
465 try:
465 try:
466 with self.opener(filepath) as fp:
466 with self.opener(filepath) as fp:
467 if mmap_threshold is not None:
467 if mmap_threshold is not None:
468 file_size = self.opener.fstat(fp).st_size
468 file_size = self.opener.fstat(fp).st_size
469 if file_size >= mmap_threshold:
469 if file_size >= mmap_threshold:
470 if size is not None:
470 if size is not None:
471 # avoid potentiel mmap crash
471 # avoid potentiel mmap crash
472 size = min(file_size, size)
472 size = min(file_size, size)
473 # TODO: should .close() to release resources without
473 # TODO: should .close() to release resources without
474 # relying on Python GC
474 # relying on Python GC
475 if size is None:
475 if size is None:
476 return util.buffer(util.mmapread(fp))
476 return util.buffer(util.mmapread(fp))
477 else:
477 else:
478 return util.buffer(util.mmapread(fp, size))
478 return util.buffer(util.mmapread(fp, size))
479 if size is None:
479 if size is None:
480 return fp.read()
480 return fp.read()
481 else:
481 else:
482 return fp.read(size)
482 return fp.read(size)
483 except IOError as inst:
483 except IOError as inst:
484 if inst.errno != errno.ENOENT:
484 if inst.errno != errno.ENOENT:
485 raise
485 raise
486 return b''
486 return b''
487
487
488 def _loadindex(self, docket=None):
488 def _loadindex(self, docket=None):
489
489
490 new_header, mmapindexthreshold, force_nodemap = self._init_opts()
490 new_header, mmapindexthreshold, force_nodemap = self._init_opts()
491
491
492 if self.postfix is not None:
492 if self.postfix is not None:
493 entry_point = b'%s.i.%s' % (self.radix, self.postfix)
493 entry_point = b'%s.i.%s' % (self.radix, self.postfix)
494 elif self._trypending and self.opener.exists(b'%s.i.a' % self.radix):
494 elif self._trypending and self.opener.exists(b'%s.i.a' % self.radix):
495 entry_point = b'%s.i.a' % self.radix
495 entry_point = b'%s.i.a' % self.radix
496 else:
496 else:
497 entry_point = b'%s.i' % self.radix
497 entry_point = b'%s.i' % self.radix
498
498
499 if docket is not None:
499 if docket is not None:
500 self._docket = docket
500 self._docket = docket
501 self._docket_file = entry_point
501 self._docket_file = entry_point
502 else:
502 else:
503 entry_data = b''
503 entry_data = b''
504 self._initempty = True
504 self._initempty = True
505 entry_data = self._get_data(entry_point, mmapindexthreshold)
505 entry_data = self._get_data(entry_point, mmapindexthreshold)
506 if len(entry_data) > 0:
506 if len(entry_data) > 0:
507 header = INDEX_HEADER.unpack(entry_data[:4])[0]
507 header = INDEX_HEADER.unpack(entry_data[:4])[0]
508 self._initempty = False
508 self._initempty = False
509 else:
509 else:
510 header = new_header
510 header = new_header
511
511
512 self._format_flags = header & ~0xFFFF
512 self._format_flags = header & ~0xFFFF
513 self._format_version = header & 0xFFFF
513 self._format_version = header & 0xFFFF
514
514
515 supported_flags = SUPPORTED_FLAGS.get(self._format_version)
515 supported_flags = SUPPORTED_FLAGS.get(self._format_version)
516 if supported_flags is None:
516 if supported_flags is None:
517 msg = _(b'unknown version (%d) in revlog %s')
517 msg = _(b'unknown version (%d) in revlog %s')
518 msg %= (self._format_version, self.display_id)
518 msg %= (self._format_version, self.display_id)
519 raise error.RevlogError(msg)
519 raise error.RevlogError(msg)
520 elif self._format_flags & ~supported_flags:
520 elif self._format_flags & ~supported_flags:
521 msg = _(b'unknown flags (%#04x) in version %d revlog %s')
521 msg = _(b'unknown flags (%#04x) in version %d revlog %s')
522 display_flag = self._format_flags >> 16
522 display_flag = self._format_flags >> 16
523 msg %= (display_flag, self._format_version, self.display_id)
523 msg %= (display_flag, self._format_version, self.display_id)
524 raise error.RevlogError(msg)
524 raise error.RevlogError(msg)
525
525
526 features = FEATURES_BY_VERSION[self._format_version]
526 features = FEATURES_BY_VERSION[self._format_version]
527 self._inline = features[b'inline'](self._format_flags)
527 self._inline = features[b'inline'](self._format_flags)
528 self._generaldelta = features[b'generaldelta'](self._format_flags)
528 self._generaldelta = features[b'generaldelta'](self._format_flags)
529 self.hassidedata = features[b'sidedata']
529 self.hassidedata = features[b'sidedata']
530
530
531 if not features[b'docket']:
531 if not features[b'docket']:
532 self._indexfile = entry_point
532 self._indexfile = entry_point
533 index_data = entry_data
533 index_data = entry_data
534 else:
534 else:
535 self._docket_file = entry_point
535 self._docket_file = entry_point
536 if self._initempty:
536 if self._initempty:
537 self._docket = docketutil.default_docket(self, header)
537 self._docket = docketutil.default_docket(self, header)
538 else:
538 else:
539 self._docket = docketutil.parse_docket(
539 self._docket = docketutil.parse_docket(
540 self, entry_data, use_pending=self._trypending
540 self, entry_data, use_pending=self._trypending
541 )
541 )
542
542
543 if self._docket is not None:
543 if self._docket is not None:
544 self._indexfile = self._docket.index_filepath()
544 self._indexfile = self._docket.index_filepath()
545 index_data = b''
545 index_data = b''
546 index_size = self._docket.index_end
546 index_size = self._docket.index_end
547 if index_size > 0:
547 if index_size > 0:
548 index_data = self._get_data(
548 index_data = self._get_data(
549 self._indexfile, mmapindexthreshold, size=index_size
549 self._indexfile, mmapindexthreshold, size=index_size
550 )
550 )
551 if len(index_data) < index_size:
551 if len(index_data) < index_size:
552 msg = _(b'too few index data for %s: got %d, expected %d')
552 msg = _(b'too few index data for %s: got %d, expected %d')
553 msg %= (self.display_id, len(index_data), index_size)
553 msg %= (self.display_id, len(index_data), index_size)
554 raise error.RevlogError(msg)
554 raise error.RevlogError(msg)
555
555
556 self._inline = False
556 self._inline = False
557 # generaldelta implied by version 2 revlogs.
557 # generaldelta implied by version 2 revlogs.
558 self._generaldelta = True
558 self._generaldelta = True
559 # the logic for persistent nodemap will be dealt with within the
559 # the logic for persistent nodemap will be dealt with within the
560 # main docket, so disable it for now.
560 # main docket, so disable it for now.
561 self._nodemap_file = None
561 self._nodemap_file = None
562
562
563 if self._docket is not None:
563 if self._docket is not None:
564 self._datafile = self._docket.data_filepath()
564 self._datafile = self._docket.data_filepath()
565 self._sidedatafile = self._docket.sidedata_filepath()
565 self._sidedatafile = self._docket.sidedata_filepath()
566 elif self.postfix is None:
566 elif self.postfix is None:
567 self._datafile = b'%s.d' % self.radix
567 self._datafile = b'%s.d' % self.radix
568 else:
568 else:
569 self._datafile = b'%s.d.%s' % (self.radix, self.postfix)
569 self._datafile = b'%s.d.%s' % (self.radix, self.postfix)
570
570
571 self.nodeconstants = sha1nodeconstants
571 self.nodeconstants = sha1nodeconstants
572 self.nullid = self.nodeconstants.nullid
572 self.nullid = self.nodeconstants.nullid
573
573
574 # sparse-revlog can't be on without general-delta (issue6056)
574 # sparse-revlog can't be on without general-delta (issue6056)
575 if not self._generaldelta:
575 if not self._generaldelta:
576 self._sparserevlog = False
576 self._sparserevlog = False
577
577
578 self._storedeltachains = True
578 self._storedeltachains = True
579
579
580 devel_nodemap = (
580 devel_nodemap = (
581 self._nodemap_file
581 self._nodemap_file
582 and force_nodemap
582 and force_nodemap
583 and parse_index_v1_nodemap is not None
583 and parse_index_v1_nodemap is not None
584 )
584 )
585
585
586 use_rust_index = False
586 use_rust_index = False
587 if rustrevlog is not None:
587 if rustrevlog is not None:
588 if self._nodemap_file is not None:
588 if self._nodemap_file is not None:
589 use_rust_index = True
589 use_rust_index = True
590 else:
590 else:
591 use_rust_index = self.opener.options.get(b'rust.index')
591 use_rust_index = self.opener.options.get(b'rust.index')
592
592
593 self._parse_index = parse_index_v1
593 self._parse_index = parse_index_v1
594 if self._format_version == REVLOGV0:
594 if self._format_version == REVLOGV0:
595 self._parse_index = revlogv0.parse_index_v0
595 self._parse_index = revlogv0.parse_index_v0
596 elif self._format_version == REVLOGV2:
596 elif self._format_version == REVLOGV2:
597 self._parse_index = parse_index_v2
597 self._parse_index = parse_index_v2
598 elif self._format_version == CHANGELOGV2:
598 elif self._format_version == CHANGELOGV2:
599 self._parse_index = parse_index_cl_v2
599 self._parse_index = parse_index_cl_v2
600 elif devel_nodemap:
600 elif devel_nodemap:
601 self._parse_index = parse_index_v1_nodemap
601 self._parse_index = parse_index_v1_nodemap
602 elif use_rust_index:
602 elif use_rust_index:
603 self._parse_index = parse_index_v1_mixed
603 self._parse_index = parse_index_v1_mixed
604 try:
604 try:
605 d = self._parse_index(index_data, self._inline)
605 d = self._parse_index(index_data, self._inline)
606 index, chunkcache = d
606 index, chunkcache = d
607 use_nodemap = (
607 use_nodemap = (
608 not self._inline
608 not self._inline
609 and self._nodemap_file is not None
609 and self._nodemap_file is not None
610 and util.safehasattr(index, 'update_nodemap_data')
610 and util.safehasattr(index, 'update_nodemap_data')
611 )
611 )
612 if use_nodemap:
612 if use_nodemap:
613 nodemap_data = nodemaputil.persisted_data(self)
613 nodemap_data = nodemaputil.persisted_data(self)
614 if nodemap_data is not None:
614 if nodemap_data is not None:
615 docket = nodemap_data[0]
615 docket = nodemap_data[0]
616 if (
616 if (
617 len(d[0]) > docket.tip_rev
617 len(d[0]) > docket.tip_rev
618 and d[0][docket.tip_rev][7] == docket.tip_node
618 and d[0][docket.tip_rev][7] == docket.tip_node
619 ):
619 ):
620 # no changelog tampering
620 # no changelog tampering
621 self._nodemap_docket = docket
621 self._nodemap_docket = docket
622 index.update_nodemap_data(*nodemap_data)
622 index.update_nodemap_data(*nodemap_data)
623 except (ValueError, IndexError):
623 except (ValueError, IndexError):
624 raise error.RevlogError(
624 raise error.RevlogError(
625 _(b"index %s is corrupted") % self.display_id
625 _(b"index %s is corrupted") % self.display_id
626 )
626 )
627 self.index = index
627 self.index = index
628 self._segmentfile = randomaccessfile.randomaccessfile(
628 self._segmentfile = randomaccessfile.randomaccessfile(
629 self.opener,
629 self.opener,
630 (self._indexfile if self._inline else self._datafile),
630 (self._indexfile if self._inline else self._datafile),
631 self._chunkcachesize,
631 self._chunkcachesize,
632 chunkcache,
632 chunkcache,
633 )
633 )
634 self._segmentfile_sidedata = randomaccessfile.randomaccessfile(
634 self._segmentfile_sidedata = randomaccessfile.randomaccessfile(
635 self.opener,
635 self.opener,
636 self._sidedatafile,
636 self._sidedatafile,
637 self._chunkcachesize,
637 self._chunkcachesize,
638 )
638 )
639 # revnum -> (chain-length, sum-delta-length)
639 # revnum -> (chain-length, sum-delta-length)
640 self._chaininfocache = util.lrucachedict(500)
640 self._chaininfocache = util.lrucachedict(500)
641 # revlog header -> revlog compressor
641 # revlog header -> revlog compressor
642 self._decompressors = {}
642 self._decompressors = {}
643
643
644 @util.propertycache
644 @util.propertycache
645 def revlog_kind(self):
645 def revlog_kind(self):
646 return self.target[0]
646 return self.target[0]
647
647
648 @util.propertycache
648 @util.propertycache
649 def display_id(self):
649 def display_id(self):
650 """The public facing "ID" of the revlog that we use in message"""
650 """The public facing "ID" of the revlog that we use in message"""
651 # Maybe we should build a user facing representation of
651 # Maybe we should build a user facing representation of
652 # revlog.target instead of using `self.radix`
652 # revlog.target instead of using `self.radix`
653 return self.radix
653 return self.radix
654
654
655 def _get_decompressor(self, t):
655 def _get_decompressor(self, t):
656 try:
656 try:
657 compressor = self._decompressors[t]
657 compressor = self._decompressors[t]
658 except KeyError:
658 except KeyError:
659 try:
659 try:
660 engine = util.compengines.forrevlogheader(t)
660 engine = util.compengines.forrevlogheader(t)
661 compressor = engine.revlogcompressor(self._compengineopts)
661 compressor = engine.revlogcompressor(self._compengineopts)
662 self._decompressors[t] = compressor
662 self._decompressors[t] = compressor
663 except KeyError:
663 except KeyError:
664 raise error.RevlogError(
664 raise error.RevlogError(
665 _(b'unknown compression type %s') % binascii.hexlify(t)
665 _(b'unknown compression type %s') % binascii.hexlify(t)
666 )
666 )
667 return compressor
667 return compressor
668
668
669 @util.propertycache
669 @util.propertycache
670 def _compressor(self):
670 def _compressor(self):
671 engine = util.compengines[self._compengine]
671 engine = util.compengines[self._compengine]
672 return engine.revlogcompressor(self._compengineopts)
672 return engine.revlogcompressor(self._compengineopts)
673
673
674 @util.propertycache
674 @util.propertycache
675 def _decompressor(self):
675 def _decompressor(self):
676 """the default decompressor"""
676 """the default decompressor"""
677 if self._docket is None:
677 if self._docket is None:
678 return None
678 return None
679 t = self._docket.default_compression_header
679 t = self._docket.default_compression_header
680 c = self._get_decompressor(t)
680 c = self._get_decompressor(t)
681 return c.decompress
681 return c.decompress
682
682
683 def _indexfp(self):
683 def _indexfp(self):
684 """file object for the revlog's index file"""
684 """file object for the revlog's index file"""
685 return self.opener(self._indexfile, mode=b"r")
685 return self.opener(self._indexfile, mode=b"r")
686
686
687 def __index_write_fp(self):
687 def __index_write_fp(self):
688 # You should not use this directly and use `_writing` instead
688 # You should not use this directly and use `_writing` instead
689 try:
689 try:
690 f = self.opener(
690 f = self.opener(
691 self._indexfile, mode=b"r+", checkambig=self._checkambig
691 self._indexfile, mode=b"r+", checkambig=self._checkambig
692 )
692 )
693 if self._docket is None:
693 if self._docket is None:
694 f.seek(0, os.SEEK_END)
694 f.seek(0, os.SEEK_END)
695 else:
695 else:
696 f.seek(self._docket.index_end, os.SEEK_SET)
696 f.seek(self._docket.index_end, os.SEEK_SET)
697 return f
697 return f
698 except IOError as inst:
698 except IOError as inst:
699 if inst.errno != errno.ENOENT:
699 if inst.errno != errno.ENOENT:
700 raise
700 raise
701 return self.opener(
701 return self.opener(
702 self._indexfile, mode=b"w+", checkambig=self._checkambig
702 self._indexfile, mode=b"w+", checkambig=self._checkambig
703 )
703 )
704
704
705 def __index_new_fp(self):
705 def __index_new_fp(self):
706 # You should not use this unless you are upgrading from inline revlog
706 # You should not use this unless you are upgrading from inline revlog
707 return self.opener(
707 return self.opener(
708 self._indexfile,
708 self._indexfile,
709 mode=b"w",
709 mode=b"w",
710 checkambig=self._checkambig,
710 checkambig=self._checkambig,
711 atomictemp=True,
711 atomictemp=True,
712 )
712 )
713
713
714 def _datafp(self, mode=b'r'):
714 def _datafp(self, mode=b'r'):
715 """file object for the revlog's data file"""
715 """file object for the revlog's data file"""
716 return self.opener(self._datafile, mode=mode)
716 return self.opener(self._datafile, mode=mode)
717
717
718 @contextlib.contextmanager
718 @contextlib.contextmanager
719 def _sidedatareadfp(self):
719 def _sidedatareadfp(self):
720 """file object suitable to read sidedata"""
720 """file object suitable to read sidedata"""
721 if self._writinghandles:
721 if self._writinghandles:
722 yield self._writinghandles[2]
722 yield self._writinghandles[2]
723 else:
723 else:
724 with self.opener(self._sidedatafile) as fp:
724 with self.opener(self._sidedatafile) as fp:
725 yield fp
725 yield fp
726
726
727 def tiprev(self):
727 def tiprev(self):
728 return len(self.index) - 1
728 return len(self.index) - 1
729
729
730 def tip(self):
730 def tip(self):
731 return self.node(self.tiprev())
731 return self.node(self.tiprev())
732
732
733 def __contains__(self, rev):
733 def __contains__(self, rev):
734 return 0 <= rev < len(self)
734 return 0 <= rev < len(self)
735
735
736 def __len__(self):
736 def __len__(self):
737 return len(self.index)
737 return len(self.index)
738
738
739 def __iter__(self):
739 def __iter__(self):
740 return iter(pycompat.xrange(len(self)))
740 return iter(pycompat.xrange(len(self)))
741
741
742 def revs(self, start=0, stop=None):
742 def revs(self, start=0, stop=None):
743 """iterate over all rev in this revlog (from start to stop)"""
743 """iterate over all rev in this revlog (from start to stop)"""
744 return storageutil.iterrevs(len(self), start=start, stop=stop)
744 return storageutil.iterrevs(len(self), start=start, stop=stop)
745
745
746 def hasnode(self, node):
746 def hasnode(self, node):
747 try:
747 try:
748 self.rev(node)
748 self.rev(node)
749 return True
749 return True
750 except KeyError:
750 except KeyError:
751 return False
751 return False
752
752
753 def candelta(self, baserev, rev):
753 def candelta(self, baserev, rev):
754 """whether two revisions (baserev, rev) can be delta-ed or not"""
754 """whether two revisions (baserev, rev) can be delta-ed or not"""
755 # Disable delta if either rev requires a content-changing flag
755 # Disable delta if either rev requires a content-changing flag
756 # processor (ex. LFS). This is because such flag processor can alter
756 # processor (ex. LFS). This is because such flag processor can alter
757 # the rawtext content that the delta will be based on, and two clients
757 # the rawtext content that the delta will be based on, and two clients
758 # could have a same revlog node with different flags (i.e. different
758 # could have a same revlog node with different flags (i.e. different
759 # rawtext contents) and the delta could be incompatible.
759 # rawtext contents) and the delta could be incompatible.
760 if (self.flags(baserev) & REVIDX_RAWTEXT_CHANGING_FLAGS) or (
760 if (self.flags(baserev) & REVIDX_RAWTEXT_CHANGING_FLAGS) or (
761 self.flags(rev) & REVIDX_RAWTEXT_CHANGING_FLAGS
761 self.flags(rev) & REVIDX_RAWTEXT_CHANGING_FLAGS
762 ):
762 ):
763 return False
763 return False
764 return True
764 return True
765
765
766 def update_caches(self, transaction):
766 def update_caches(self, transaction):
767 if self._nodemap_file is not None:
767 if self._nodemap_file is not None:
768 if transaction is None:
768 if transaction is None:
769 nodemaputil.update_persistent_nodemap(self)
769 nodemaputil.update_persistent_nodemap(self)
770 else:
770 else:
771 nodemaputil.setup_persistent_nodemap(transaction, self)
771 nodemaputil.setup_persistent_nodemap(transaction, self)
772
772
773 def clearcaches(self):
773 def clearcaches(self):
774 self._revisioncache = None
774 self._revisioncache = None
775 self._chainbasecache.clear()
775 self._chainbasecache.clear()
776 self._segmentfile.clear_cache()
776 self._segmentfile.clear_cache()
777 self._segmentfile_sidedata.clear_cache()
777 self._segmentfile_sidedata.clear_cache()
778 self._pcache = {}
778 self._pcache = {}
779 self._nodemap_docket = None
779 self._nodemap_docket = None
780 self.index.clearcaches()
780 self.index.clearcaches()
781 # The python code is the one responsible for validating the docket, we
781 # The python code is the one responsible for validating the docket, we
782 # end up having to refresh it here.
782 # end up having to refresh it here.
783 use_nodemap = (
783 use_nodemap = (
784 not self._inline
784 not self._inline
785 and self._nodemap_file is not None
785 and self._nodemap_file is not None
786 and util.safehasattr(self.index, 'update_nodemap_data')
786 and util.safehasattr(self.index, 'update_nodemap_data')
787 )
787 )
788 if use_nodemap:
788 if use_nodemap:
789 nodemap_data = nodemaputil.persisted_data(self)
789 nodemap_data = nodemaputil.persisted_data(self)
790 if nodemap_data is not None:
790 if nodemap_data is not None:
791 self._nodemap_docket = nodemap_data[0]
791 self._nodemap_docket = nodemap_data[0]
792 self.index.update_nodemap_data(*nodemap_data)
792 self.index.update_nodemap_data(*nodemap_data)
793
793
794 def rev(self, node):
794 def rev(self, node):
795 try:
795 try:
796 return self.index.rev(node)
796 return self.index.rev(node)
797 except TypeError:
797 except TypeError:
798 raise
798 raise
799 except error.RevlogError:
799 except error.RevlogError:
800 # parsers.c radix tree lookup failed
800 # parsers.c radix tree lookup failed
801 if (
801 if (
802 node == self.nodeconstants.wdirid
802 node == self.nodeconstants.wdirid
803 or node in self.nodeconstants.wdirfilenodeids
803 or node in self.nodeconstants.wdirfilenodeids
804 ):
804 ):
805 raise error.WdirUnsupported
805 raise error.WdirUnsupported
806 raise error.LookupError(node, self.display_id, _(b'no node'))
806 raise error.LookupError(node, self.display_id, _(b'no node'))
807
807
808 # Accessors for index entries.
808 # Accessors for index entries.
809
809
810 # First tuple entry is 8 bytes. First 6 bytes are offset. Last 2 bytes
810 # First tuple entry is 8 bytes. First 6 bytes are offset. Last 2 bytes
811 # are flags.
811 # are flags.
812 def start(self, rev):
812 def start(self, rev):
813 return int(self.index[rev][0] >> 16)
813 return int(self.index[rev][0] >> 16)
814
814
815 def sidedata_cut_off(self, rev):
815 def sidedata_cut_off(self, rev):
816 sd_cut_off = self.index[rev][8]
816 sd_cut_off = self.index[rev][8]
817 if sd_cut_off != 0:
817 if sd_cut_off != 0:
818 return sd_cut_off
818 return sd_cut_off
819 # This is some annoying dance, because entries without sidedata
819 # This is some annoying dance, because entries without sidedata
820 # currently use 0 as their ofsset. (instead of previous-offset +
820 # currently use 0 as their ofsset. (instead of previous-offset +
821 # previous-size)
821 # previous-size)
822 #
822 #
823 # We should reconsider this sidedata β†’ 0 sidata_offset policy.
823 # We should reconsider this sidedata β†’ 0 sidata_offset policy.
824 # In the meantime, we need this.
824 # In the meantime, we need this.
825 while 0 <= rev:
825 while 0 <= rev:
826 e = self.index[rev]
826 e = self.index[rev]
827 if e[9] != 0:
827 if e[9] != 0:
828 return e[8] + e[9]
828 return e[8] + e[9]
829 rev -= 1
829 rev -= 1
830 return 0
830 return 0
831
831
832 def flags(self, rev):
832 def flags(self, rev):
833 return self.index[rev][0] & 0xFFFF
833 return self.index[rev][0] & 0xFFFF
834
834
835 def length(self, rev):
835 def length(self, rev):
836 return self.index[rev][1]
836 return self.index[rev][1]
837
837
838 def sidedata_length(self, rev):
838 def sidedata_length(self, rev):
839 if not self.hassidedata:
839 if not self.hassidedata:
840 return 0
840 return 0
841 return self.index[rev][9]
841 return self.index[rev][9]
842
842
843 def rawsize(self, rev):
843 def rawsize(self, rev):
844 """return the length of the uncompressed text for a given revision"""
844 """return the length of the uncompressed text for a given revision"""
845 l = self.index[rev][2]
845 l = self.index[rev][2]
846 if l >= 0:
846 if l >= 0:
847 return l
847 return l
848
848
849 t = self.rawdata(rev)
849 t = self.rawdata(rev)
850 return len(t)
850 return len(t)
851
851
852 def size(self, rev):
852 def size(self, rev):
853 """length of non-raw text (processed by a "read" flag processor)"""
853 """length of non-raw text (processed by a "read" flag processor)"""
854 # fast path: if no "read" flag processor could change the content,
854 # fast path: if no "read" flag processor could change the content,
855 # size is rawsize. note: ELLIPSIS is known to not change the content.
855 # size is rawsize. note: ELLIPSIS is known to not change the content.
856 flags = self.flags(rev)
856 flags = self.flags(rev)
857 if flags & (flagutil.REVIDX_KNOWN_FLAGS ^ REVIDX_ELLIPSIS) == 0:
857 if flags & (flagutil.REVIDX_KNOWN_FLAGS ^ REVIDX_ELLIPSIS) == 0:
858 return self.rawsize(rev)
858 return self.rawsize(rev)
859
859
860 return len(self.revision(rev))
860 return len(self.revision(rev))
861
861
862 def fast_rank(self, rev):
862 def fast_rank(self, rev):
863 """Return the rank of a revision if already known, or None otherwise.
863 """Return the rank of a revision if already known, or None otherwise.
864
864
865 The rank of a revision is the size of the sub-graph it defines as a
865 The rank of a revision is the size of the sub-graph it defines as a
866 head. Equivalently, the rank of a revision `r` is the size of the set
866 head. Equivalently, the rank of a revision `r` is the size of the set
867 `ancestors(r)`, `r` included.
867 `ancestors(r)`, `r` included.
868
868
869 This method returns the rank retrieved from the revlog in constant
869 This method returns the rank retrieved from the revlog in constant
870 time. It makes no attempt at computing unknown values for versions of
870 time. It makes no attempt at computing unknown values for versions of
871 the revlog which do not persist the rank.
871 the revlog which do not persist the rank.
872 """
872 """
873 rank = self.index[rev][ENTRY_RANK]
873 rank = self.index[rev][ENTRY_RANK]
874 if rank == RANK_UNKNOWN:
874 if rank == RANK_UNKNOWN:
875 return None
875 return None
876 return rank
876 return rank
877
877
878 def chainbase(self, rev):
878 def chainbase(self, rev):
879 base = self._chainbasecache.get(rev)
879 base = self._chainbasecache.get(rev)
880 if base is not None:
880 if base is not None:
881 return base
881 return base
882
882
883 index = self.index
883 index = self.index
884 iterrev = rev
884 iterrev = rev
885 base = index[iterrev][3]
885 base = index[iterrev][3]
886 while base != iterrev:
886 while base != iterrev:
887 iterrev = base
887 iterrev = base
888 base = index[iterrev][3]
888 base = index[iterrev][3]
889
889
890 self._chainbasecache[rev] = base
890 self._chainbasecache[rev] = base
891 return base
891 return base
892
892
893 def linkrev(self, rev):
893 def linkrev(self, rev):
894 return self.index[rev][4]
894 return self.index[rev][4]
895
895
896 def parentrevs(self, rev):
896 def parentrevs(self, rev):
897 try:
897 try:
898 entry = self.index[rev]
898 entry = self.index[rev]
899 except IndexError:
899 except IndexError:
900 if rev == wdirrev:
900 if rev == wdirrev:
901 raise error.WdirUnsupported
901 raise error.WdirUnsupported
902 raise
902 raise
903
903
904 return entry[5], entry[6]
904 return entry[5], entry[6]
905
905
906 # fast parentrevs(rev) where rev isn't filtered
906 # fast parentrevs(rev) where rev isn't filtered
907 _uncheckedparentrevs = parentrevs
907 _uncheckedparentrevs = parentrevs
908
908
909 def node(self, rev):
909 def node(self, rev):
910 try:
910 try:
911 return self.index[rev][7]
911 return self.index[rev][7]
912 except IndexError:
912 except IndexError:
913 if rev == wdirrev:
913 if rev == wdirrev:
914 raise error.WdirUnsupported
914 raise error.WdirUnsupported
915 raise
915 raise
916
916
917 # Derived from index values.
917 # Derived from index values.
918
918
919 def end(self, rev):
919 def end(self, rev):
920 return self.start(rev) + self.length(rev)
920 return self.start(rev) + self.length(rev)
921
921
922 def parents(self, node):
922 def parents(self, node):
923 i = self.index
923 i = self.index
924 d = i[self.rev(node)]
924 d = i[self.rev(node)]
925 return i[d[5]][7], i[d[6]][7] # map revisions to nodes inline
925 return i[d[5]][7], i[d[6]][7] # map revisions to nodes inline
926
926
927 def chainlen(self, rev):
927 def chainlen(self, rev):
928 return self._chaininfo(rev)[0]
928 return self._chaininfo(rev)[0]
929
929
930 def _chaininfo(self, rev):
930 def _chaininfo(self, rev):
931 chaininfocache = self._chaininfocache
931 chaininfocache = self._chaininfocache
932 if rev in chaininfocache:
932 if rev in chaininfocache:
933 return chaininfocache[rev]
933 return chaininfocache[rev]
934 index = self.index
934 index = self.index
935 generaldelta = self._generaldelta
935 generaldelta = self._generaldelta
936 iterrev = rev
936 iterrev = rev
937 e = index[iterrev]
937 e = index[iterrev]
938 clen = 0
938 clen = 0
939 compresseddeltalen = 0
939 compresseddeltalen = 0
940 while iterrev != e[3]:
940 while iterrev != e[3]:
941 clen += 1
941 clen += 1
942 compresseddeltalen += e[1]
942 compresseddeltalen += e[1]
943 if generaldelta:
943 if generaldelta:
944 iterrev = e[3]
944 iterrev = e[3]
945 else:
945 else:
946 iterrev -= 1
946 iterrev -= 1
947 if iterrev in chaininfocache:
947 if iterrev in chaininfocache:
948 t = chaininfocache[iterrev]
948 t = chaininfocache[iterrev]
949 clen += t[0]
949 clen += t[0]
950 compresseddeltalen += t[1]
950 compresseddeltalen += t[1]
951 break
951 break
952 e = index[iterrev]
952 e = index[iterrev]
953 else:
953 else:
954 # Add text length of base since decompressing that also takes
954 # Add text length of base since decompressing that also takes
955 # work. For cache hits the length is already included.
955 # work. For cache hits the length is already included.
956 compresseddeltalen += e[1]
956 compresseddeltalen += e[1]
957 r = (clen, compresseddeltalen)
957 r = (clen, compresseddeltalen)
958 chaininfocache[rev] = r
958 chaininfocache[rev] = r
959 return r
959 return r
960
960
961 def _deltachain(self, rev, stoprev=None):
961 def _deltachain(self, rev, stoprev=None):
962 """Obtain the delta chain for a revision.
962 """Obtain the delta chain for a revision.
963
963
964 ``stoprev`` specifies a revision to stop at. If not specified, we
964 ``stoprev`` specifies a revision to stop at. If not specified, we
965 stop at the base of the chain.
965 stop at the base of the chain.
966
966
967 Returns a 2-tuple of (chain, stopped) where ``chain`` is a list of
967 Returns a 2-tuple of (chain, stopped) where ``chain`` is a list of
968 revs in ascending order and ``stopped`` is a bool indicating whether
968 revs in ascending order and ``stopped`` is a bool indicating whether
969 ``stoprev`` was hit.
969 ``stoprev`` was hit.
970 """
970 """
971 # Try C implementation.
971 # Try C implementation.
972 try:
972 try:
973 return self.index.deltachain(rev, stoprev, self._generaldelta)
973 return self.index.deltachain(rev, stoprev, self._generaldelta)
974 except AttributeError:
974 except AttributeError:
975 pass
975 pass
976
976
977 chain = []
977 chain = []
978
978
979 # Alias to prevent attribute lookup in tight loop.
979 # Alias to prevent attribute lookup in tight loop.
980 index = self.index
980 index = self.index
981 generaldelta = self._generaldelta
981 generaldelta = self._generaldelta
982
982
983 iterrev = rev
983 iterrev = rev
984 e = index[iterrev]
984 e = index[iterrev]
985 while iterrev != e[3] and iterrev != stoprev:
985 while iterrev != e[3] and iterrev != stoprev:
986 chain.append(iterrev)
986 chain.append(iterrev)
987 if generaldelta:
987 if generaldelta:
988 iterrev = e[3]
988 iterrev = e[3]
989 else:
989 else:
990 iterrev -= 1
990 iterrev -= 1
991 e = index[iterrev]
991 e = index[iterrev]
992
992
993 if iterrev == stoprev:
993 if iterrev == stoprev:
994 stopped = True
994 stopped = True
995 else:
995 else:
996 chain.append(iterrev)
996 chain.append(iterrev)
997 stopped = False
997 stopped = False
998
998
999 chain.reverse()
999 chain.reverse()
1000 return chain, stopped
1000 return chain, stopped
1001
1001
1002 def ancestors(self, revs, stoprev=0, inclusive=False):
1002 def ancestors(self, revs, stoprev=0, inclusive=False):
1003 """Generate the ancestors of 'revs' in reverse revision order.
1003 """Generate the ancestors of 'revs' in reverse revision order.
1004 Does not generate revs lower than stoprev.
1004 Does not generate revs lower than stoprev.
1005
1005
1006 See the documentation for ancestor.lazyancestors for more details."""
1006 See the documentation for ancestor.lazyancestors for more details."""
1007
1007
1008 # first, make sure start revisions aren't filtered
1008 # first, make sure start revisions aren't filtered
1009 revs = list(revs)
1009 revs = list(revs)
1010 checkrev = self.node
1010 checkrev = self.node
1011 for r in revs:
1011 for r in revs:
1012 checkrev(r)
1012 checkrev(r)
1013 # and we're sure ancestors aren't filtered as well
1013 # and we're sure ancestors aren't filtered as well
1014
1014
1015 if rustancestor is not None and self.index.rust_ext_compat:
1015 if rustancestor is not None and self.index.rust_ext_compat:
1016 lazyancestors = rustancestor.LazyAncestors
1016 lazyancestors = rustancestor.LazyAncestors
1017 arg = self.index
1017 arg = self.index
1018 else:
1018 else:
1019 lazyancestors = ancestor.lazyancestors
1019 lazyancestors = ancestor.lazyancestors
1020 arg = self._uncheckedparentrevs
1020 arg = self._uncheckedparentrevs
1021 return lazyancestors(arg, revs, stoprev=stoprev, inclusive=inclusive)
1021 return lazyancestors(arg, revs, stoprev=stoprev, inclusive=inclusive)
1022
1022
1023 def descendants(self, revs):
1023 def descendants(self, revs):
1024 return dagop.descendantrevs(revs, self.revs, self.parentrevs)
1024 return dagop.descendantrevs(revs, self.revs, self.parentrevs)
1025
1025
1026 def findcommonmissing(self, common=None, heads=None):
1026 def findcommonmissing(self, common=None, heads=None):
1027 """Return a tuple of the ancestors of common and the ancestors of heads
1027 """Return a tuple of the ancestors of common and the ancestors of heads
1028 that are not ancestors of common. In revset terminology, we return the
1028 that are not ancestors of common. In revset terminology, we return the
1029 tuple:
1029 tuple:
1030
1030
1031 ::common, (::heads) - (::common)
1031 ::common, (::heads) - (::common)
1032
1032
1033 The list is sorted by revision number, meaning it is
1033 The list is sorted by revision number, meaning it is
1034 topologically sorted.
1034 topologically sorted.
1035
1035
1036 'heads' and 'common' are both lists of node IDs. If heads is
1036 'heads' and 'common' are both lists of node IDs. If heads is
1037 not supplied, uses all of the revlog's heads. If common is not
1037 not supplied, uses all of the revlog's heads. If common is not
1038 supplied, uses nullid."""
1038 supplied, uses nullid."""
1039 if common is None:
1039 if common is None:
1040 common = [self.nullid]
1040 common = [self.nullid]
1041 if heads is None:
1041 if heads is None:
1042 heads = self.heads()
1042 heads = self.heads()
1043
1043
1044 common = [self.rev(n) for n in common]
1044 common = [self.rev(n) for n in common]
1045 heads = [self.rev(n) for n in heads]
1045 heads = [self.rev(n) for n in heads]
1046
1046
1047 # we want the ancestors, but inclusive
1047 # we want the ancestors, but inclusive
1048 class lazyset(object):
1048 class lazyset(object):
1049 def __init__(self, lazyvalues):
1049 def __init__(self, lazyvalues):
1050 self.addedvalues = set()
1050 self.addedvalues = set()
1051 self.lazyvalues = lazyvalues
1051 self.lazyvalues = lazyvalues
1052
1052
1053 def __contains__(self, value):
1053 def __contains__(self, value):
1054 return value in self.addedvalues or value in self.lazyvalues
1054 return value in self.addedvalues or value in self.lazyvalues
1055
1055
1056 def __iter__(self):
1056 def __iter__(self):
1057 added = self.addedvalues
1057 added = self.addedvalues
1058 for r in added:
1058 for r in added:
1059 yield r
1059 yield r
1060 for r in self.lazyvalues:
1060 for r in self.lazyvalues:
1061 if not r in added:
1061 if not r in added:
1062 yield r
1062 yield r
1063
1063
1064 def add(self, value):
1064 def add(self, value):
1065 self.addedvalues.add(value)
1065 self.addedvalues.add(value)
1066
1066
1067 def update(self, values):
1067 def update(self, values):
1068 self.addedvalues.update(values)
1068 self.addedvalues.update(values)
1069
1069
1070 has = lazyset(self.ancestors(common))
1070 has = lazyset(self.ancestors(common))
1071 has.add(nullrev)
1071 has.add(nullrev)
1072 has.update(common)
1072 has.update(common)
1073
1073
1074 # take all ancestors from heads that aren't in has
1074 # take all ancestors from heads that aren't in has
1075 missing = set()
1075 missing = set()
1076 visit = collections.deque(r for r in heads if r not in has)
1076 visit = collections.deque(r for r in heads if r not in has)
1077 while visit:
1077 while visit:
1078 r = visit.popleft()
1078 r = visit.popleft()
1079 if r in missing:
1079 if r in missing:
1080 continue
1080 continue
1081 else:
1081 else:
1082 missing.add(r)
1082 missing.add(r)
1083 for p in self.parentrevs(r):
1083 for p in self.parentrevs(r):
1084 if p not in has:
1084 if p not in has:
1085 visit.append(p)
1085 visit.append(p)
1086 missing = list(missing)
1086 missing = list(missing)
1087 missing.sort()
1087 missing.sort()
1088 return has, [self.node(miss) for miss in missing]
1088 return has, [self.node(miss) for miss in missing]
1089
1089
1090 def incrementalmissingrevs(self, common=None):
1090 def incrementalmissingrevs(self, common=None):
1091 """Return an object that can be used to incrementally compute the
1091 """Return an object that can be used to incrementally compute the
1092 revision numbers of the ancestors of arbitrary sets that are not
1092 revision numbers of the ancestors of arbitrary sets that are not
1093 ancestors of common. This is an ancestor.incrementalmissingancestors
1093 ancestors of common. This is an ancestor.incrementalmissingancestors
1094 object.
1094 object.
1095
1095
1096 'common' is a list of revision numbers. If common is not supplied, uses
1096 'common' is a list of revision numbers. If common is not supplied, uses
1097 nullrev.
1097 nullrev.
1098 """
1098 """
1099 if common is None:
1099 if common is None:
1100 common = [nullrev]
1100 common = [nullrev]
1101
1101
1102 if rustancestor is not None and self.index.rust_ext_compat:
1102 if rustancestor is not None and self.index.rust_ext_compat:
1103 return rustancestor.MissingAncestors(self.index, common)
1103 return rustancestor.MissingAncestors(self.index, common)
1104 return ancestor.incrementalmissingancestors(self.parentrevs, common)
1104 return ancestor.incrementalmissingancestors(self.parentrevs, common)
1105
1105
1106 def findmissingrevs(self, common=None, heads=None):
1106 def findmissingrevs(self, common=None, heads=None):
1107 """Return the revision numbers of the ancestors of heads that
1107 """Return the revision numbers of the ancestors of heads that
1108 are not ancestors of common.
1108 are not ancestors of common.
1109
1109
1110 More specifically, return a list of revision numbers corresponding to
1110 More specifically, return a list of revision numbers corresponding to
1111 nodes N such that every N satisfies the following constraints:
1111 nodes N such that every N satisfies the following constraints:
1112
1112
1113 1. N is an ancestor of some node in 'heads'
1113 1. N is an ancestor of some node in 'heads'
1114 2. N is not an ancestor of any node in 'common'
1114 2. N is not an ancestor of any node in 'common'
1115
1115
1116 The list is sorted by revision number, meaning it is
1116 The list is sorted by revision number, meaning it is
1117 topologically sorted.
1117 topologically sorted.
1118
1118
1119 'heads' and 'common' are both lists of revision numbers. If heads is
1119 'heads' and 'common' are both lists of revision numbers. If heads is
1120 not supplied, uses all of the revlog's heads. If common is not
1120 not supplied, uses all of the revlog's heads. If common is not
1121 supplied, uses nullid."""
1121 supplied, uses nullid."""
1122 if common is None:
1122 if common is None:
1123 common = [nullrev]
1123 common = [nullrev]
1124 if heads is None:
1124 if heads is None:
1125 heads = self.headrevs()
1125 heads = self.headrevs()
1126
1126
1127 inc = self.incrementalmissingrevs(common=common)
1127 inc = self.incrementalmissingrevs(common=common)
1128 return inc.missingancestors(heads)
1128 return inc.missingancestors(heads)
1129
1129
1130 def findmissing(self, common=None, heads=None):
1130 def findmissing(self, common=None, heads=None):
1131 """Return the ancestors of heads that are not ancestors of common.
1131 """Return the ancestors of heads that are not ancestors of common.
1132
1132
1133 More specifically, return a list of nodes N such that every N
1133 More specifically, return a list of nodes N such that every N
1134 satisfies the following constraints:
1134 satisfies the following constraints:
1135
1135
1136 1. N is an ancestor of some node in 'heads'
1136 1. N is an ancestor of some node in 'heads'
1137 2. N is not an ancestor of any node in 'common'
1137 2. N is not an ancestor of any node in 'common'
1138
1138
1139 The list is sorted by revision number, meaning it is
1139 The list is sorted by revision number, meaning it is
1140 topologically sorted.
1140 topologically sorted.
1141
1141
1142 'heads' and 'common' are both lists of node IDs. If heads is
1142 'heads' and 'common' are both lists of node IDs. If heads is
1143 not supplied, uses all of the revlog's heads. If common is not
1143 not supplied, uses all of the revlog's heads. If common is not
1144 supplied, uses nullid."""
1144 supplied, uses nullid."""
1145 if common is None:
1145 if common is None:
1146 common = [self.nullid]
1146 common = [self.nullid]
1147 if heads is None:
1147 if heads is None:
1148 heads = self.heads()
1148 heads = self.heads()
1149
1149
1150 common = [self.rev(n) for n in common]
1150 common = [self.rev(n) for n in common]
1151 heads = [self.rev(n) for n in heads]
1151 heads = [self.rev(n) for n in heads]
1152
1152
1153 inc = self.incrementalmissingrevs(common=common)
1153 inc = self.incrementalmissingrevs(common=common)
1154 return [self.node(r) for r in inc.missingancestors(heads)]
1154 return [self.node(r) for r in inc.missingancestors(heads)]
1155
1155
1156 def nodesbetween(self, roots=None, heads=None):
1156 def nodesbetween(self, roots=None, heads=None):
1157 """Return a topological path from 'roots' to 'heads'.
1157 """Return a topological path from 'roots' to 'heads'.
1158
1158
1159 Return a tuple (nodes, outroots, outheads) where 'nodes' is a
1159 Return a tuple (nodes, outroots, outheads) where 'nodes' is a
1160 topologically sorted list of all nodes N that satisfy both of
1160 topologically sorted list of all nodes N that satisfy both of
1161 these constraints:
1161 these constraints:
1162
1162
1163 1. N is a descendant of some node in 'roots'
1163 1. N is a descendant of some node in 'roots'
1164 2. N is an ancestor of some node in 'heads'
1164 2. N is an ancestor of some node in 'heads'
1165
1165
1166 Every node is considered to be both a descendant and an ancestor
1166 Every node is considered to be both a descendant and an ancestor
1167 of itself, so every reachable node in 'roots' and 'heads' will be
1167 of itself, so every reachable node in 'roots' and 'heads' will be
1168 included in 'nodes'.
1168 included in 'nodes'.
1169
1169
1170 'outroots' is the list of reachable nodes in 'roots', i.e., the
1170 'outroots' is the list of reachable nodes in 'roots', i.e., the
1171 subset of 'roots' that is returned in 'nodes'. Likewise,
1171 subset of 'roots' that is returned in 'nodes'. Likewise,
1172 'outheads' is the subset of 'heads' that is also in 'nodes'.
1172 'outheads' is the subset of 'heads' that is also in 'nodes'.
1173
1173
1174 'roots' and 'heads' are both lists of node IDs. If 'roots' is
1174 'roots' and 'heads' are both lists of node IDs. If 'roots' is
1175 unspecified, uses nullid as the only root. If 'heads' is
1175 unspecified, uses nullid as the only root. If 'heads' is
1176 unspecified, uses list of all of the revlog's heads."""
1176 unspecified, uses list of all of the revlog's heads."""
1177 nonodes = ([], [], [])
1177 nonodes = ([], [], [])
1178 if roots is not None:
1178 if roots is not None:
1179 roots = list(roots)
1179 roots = list(roots)
1180 if not roots:
1180 if not roots:
1181 return nonodes
1181 return nonodes
1182 lowestrev = min([self.rev(n) for n in roots])
1182 lowestrev = min([self.rev(n) for n in roots])
1183 else:
1183 else:
1184 roots = [self.nullid] # Everybody's a descendant of nullid
1184 roots = [self.nullid] # Everybody's a descendant of nullid
1185 lowestrev = nullrev
1185 lowestrev = nullrev
1186 if (lowestrev == nullrev) and (heads is None):
1186 if (lowestrev == nullrev) and (heads is None):
1187 # We want _all_ the nodes!
1187 # We want _all_ the nodes!
1188 return (
1188 return (
1189 [self.node(r) for r in self],
1189 [self.node(r) for r in self],
1190 [self.nullid],
1190 [self.nullid],
1191 list(self.heads()),
1191 list(self.heads()),
1192 )
1192 )
1193 if heads is None:
1193 if heads is None:
1194 # All nodes are ancestors, so the latest ancestor is the last
1194 # All nodes are ancestors, so the latest ancestor is the last
1195 # node.
1195 # node.
1196 highestrev = len(self) - 1
1196 highestrev = len(self) - 1
1197 # Set ancestors to None to signal that every node is an ancestor.
1197 # Set ancestors to None to signal that every node is an ancestor.
1198 ancestors = None
1198 ancestors = None
1199 # Set heads to an empty dictionary for later discovery of heads
1199 # Set heads to an empty dictionary for later discovery of heads
1200 heads = {}
1200 heads = {}
1201 else:
1201 else:
1202 heads = list(heads)
1202 heads = list(heads)
1203 if not heads:
1203 if not heads:
1204 return nonodes
1204 return nonodes
1205 ancestors = set()
1205 ancestors = set()
1206 # Turn heads into a dictionary so we can remove 'fake' heads.
1206 # Turn heads into a dictionary so we can remove 'fake' heads.
1207 # Also, later we will be using it to filter out the heads we can't
1207 # Also, later we will be using it to filter out the heads we can't
1208 # find from roots.
1208 # find from roots.
1209 heads = dict.fromkeys(heads, False)
1209 heads = dict.fromkeys(heads, False)
1210 # Start at the top and keep marking parents until we're done.
1210 # Start at the top and keep marking parents until we're done.
1211 nodestotag = set(heads)
1211 nodestotag = set(heads)
1212 # Remember where the top was so we can use it as a limit later.
1212 # Remember where the top was so we can use it as a limit later.
1213 highestrev = max([self.rev(n) for n in nodestotag])
1213 highestrev = max([self.rev(n) for n in nodestotag])
1214 while nodestotag:
1214 while nodestotag:
1215 # grab a node to tag
1215 # grab a node to tag
1216 n = nodestotag.pop()
1216 n = nodestotag.pop()
1217 # Never tag nullid
1217 # Never tag nullid
1218 if n == self.nullid:
1218 if n == self.nullid:
1219 continue
1219 continue
1220 # A node's revision number represents its place in a
1220 # A node's revision number represents its place in a
1221 # topologically sorted list of nodes.
1221 # topologically sorted list of nodes.
1222 r = self.rev(n)
1222 r = self.rev(n)
1223 if r >= lowestrev:
1223 if r >= lowestrev:
1224 if n not in ancestors:
1224 if n not in ancestors:
1225 # If we are possibly a descendant of one of the roots
1225 # If we are possibly a descendant of one of the roots
1226 # and we haven't already been marked as an ancestor
1226 # and we haven't already been marked as an ancestor
1227 ancestors.add(n) # Mark as ancestor
1227 ancestors.add(n) # Mark as ancestor
1228 # Add non-nullid parents to list of nodes to tag.
1228 # Add non-nullid parents to list of nodes to tag.
1229 nodestotag.update(
1229 nodestotag.update(
1230 [p for p in self.parents(n) if p != self.nullid]
1230 [p for p in self.parents(n) if p != self.nullid]
1231 )
1231 )
1232 elif n in heads: # We've seen it before, is it a fake head?
1232 elif n in heads: # We've seen it before, is it a fake head?
1233 # So it is, real heads should not be the ancestors of
1233 # So it is, real heads should not be the ancestors of
1234 # any other heads.
1234 # any other heads.
1235 heads.pop(n)
1235 heads.pop(n)
1236 if not ancestors:
1236 if not ancestors:
1237 return nonodes
1237 return nonodes
1238 # Now that we have our set of ancestors, we want to remove any
1238 # Now that we have our set of ancestors, we want to remove any
1239 # roots that are not ancestors.
1239 # roots that are not ancestors.
1240
1240
1241 # If one of the roots was nullid, everything is included anyway.
1241 # If one of the roots was nullid, everything is included anyway.
1242 if lowestrev > nullrev:
1242 if lowestrev > nullrev:
1243 # But, since we weren't, let's recompute the lowest rev to not
1243 # But, since we weren't, let's recompute the lowest rev to not
1244 # include roots that aren't ancestors.
1244 # include roots that aren't ancestors.
1245
1245
1246 # Filter out roots that aren't ancestors of heads
1246 # Filter out roots that aren't ancestors of heads
1247 roots = [root for root in roots if root in ancestors]
1247 roots = [root for root in roots if root in ancestors]
1248 # Recompute the lowest revision
1248 # Recompute the lowest revision
1249 if roots:
1249 if roots:
1250 lowestrev = min([self.rev(root) for root in roots])
1250 lowestrev = min([self.rev(root) for root in roots])
1251 else:
1251 else:
1252 # No more roots? Return empty list
1252 # No more roots? Return empty list
1253 return nonodes
1253 return nonodes
1254 else:
1254 else:
1255 # We are descending from nullid, and don't need to care about
1255 # We are descending from nullid, and don't need to care about
1256 # any other roots.
1256 # any other roots.
1257 lowestrev = nullrev
1257 lowestrev = nullrev
1258 roots = [self.nullid]
1258 roots = [self.nullid]
1259 # Transform our roots list into a set.
1259 # Transform our roots list into a set.
1260 descendants = set(roots)
1260 descendants = set(roots)
1261 # Also, keep the original roots so we can filter out roots that aren't
1261 # Also, keep the original roots so we can filter out roots that aren't
1262 # 'real' roots (i.e. are descended from other roots).
1262 # 'real' roots (i.e. are descended from other roots).
1263 roots = descendants.copy()
1263 roots = descendants.copy()
1264 # Our topologically sorted list of output nodes.
1264 # Our topologically sorted list of output nodes.
1265 orderedout = []
1265 orderedout = []
1266 # Don't start at nullid since we don't want nullid in our output list,
1266 # Don't start at nullid since we don't want nullid in our output list,
1267 # and if nullid shows up in descendants, empty parents will look like
1267 # and if nullid shows up in descendants, empty parents will look like
1268 # they're descendants.
1268 # they're descendants.
1269 for r in self.revs(start=max(lowestrev, 0), stop=highestrev + 1):
1269 for r in self.revs(start=max(lowestrev, 0), stop=highestrev + 1):
1270 n = self.node(r)
1270 n = self.node(r)
1271 isdescendant = False
1271 isdescendant = False
1272 if lowestrev == nullrev: # Everybody is a descendant of nullid
1272 if lowestrev == nullrev: # Everybody is a descendant of nullid
1273 isdescendant = True
1273 isdescendant = True
1274 elif n in descendants:
1274 elif n in descendants:
1275 # n is already a descendant
1275 # n is already a descendant
1276 isdescendant = True
1276 isdescendant = True
1277 # This check only needs to be done here because all the roots
1277 # This check only needs to be done here because all the roots
1278 # will start being marked is descendants before the loop.
1278 # will start being marked is descendants before the loop.
1279 if n in roots:
1279 if n in roots:
1280 # If n was a root, check if it's a 'real' root.
1280 # If n was a root, check if it's a 'real' root.
1281 p = tuple(self.parents(n))
1281 p = tuple(self.parents(n))
1282 # If any of its parents are descendants, it's not a root.
1282 # If any of its parents are descendants, it's not a root.
1283 if (p[0] in descendants) or (p[1] in descendants):
1283 if (p[0] in descendants) or (p[1] in descendants):
1284 roots.remove(n)
1284 roots.remove(n)
1285 else:
1285 else:
1286 p = tuple(self.parents(n))
1286 p = tuple(self.parents(n))
1287 # A node is a descendant if either of its parents are
1287 # A node is a descendant if either of its parents are
1288 # descendants. (We seeded the dependents list with the roots
1288 # descendants. (We seeded the dependents list with the roots
1289 # up there, remember?)
1289 # up there, remember?)
1290 if (p[0] in descendants) or (p[1] in descendants):
1290 if (p[0] in descendants) or (p[1] in descendants):
1291 descendants.add(n)
1291 descendants.add(n)
1292 isdescendant = True
1292 isdescendant = True
1293 if isdescendant and ((ancestors is None) or (n in ancestors)):
1293 if isdescendant and ((ancestors is None) or (n in ancestors)):
1294 # Only include nodes that are both descendants and ancestors.
1294 # Only include nodes that are both descendants and ancestors.
1295 orderedout.append(n)
1295 orderedout.append(n)
1296 if (ancestors is not None) and (n in heads):
1296 if (ancestors is not None) and (n in heads):
1297 # We're trying to figure out which heads are reachable
1297 # We're trying to figure out which heads are reachable
1298 # from roots.
1298 # from roots.
1299 # Mark this head as having been reached
1299 # Mark this head as having been reached
1300 heads[n] = True
1300 heads[n] = True
1301 elif ancestors is None:
1301 elif ancestors is None:
1302 # Otherwise, we're trying to discover the heads.
1302 # Otherwise, we're trying to discover the heads.
1303 # Assume this is a head because if it isn't, the next step
1303 # Assume this is a head because if it isn't, the next step
1304 # will eventually remove it.
1304 # will eventually remove it.
1305 heads[n] = True
1305 heads[n] = True
1306 # But, obviously its parents aren't.
1306 # But, obviously its parents aren't.
1307 for p in self.parents(n):
1307 for p in self.parents(n):
1308 heads.pop(p, None)
1308 heads.pop(p, None)
1309 heads = [head for head, flag in pycompat.iteritems(heads) if flag]
1309 heads = [head for head, flag in pycompat.iteritems(heads) if flag]
1310 roots = list(roots)
1310 roots = list(roots)
1311 assert orderedout
1311 assert orderedout
1312 assert roots
1312 assert roots
1313 assert heads
1313 assert heads
1314 return (orderedout, roots, heads)
1314 return (orderedout, roots, heads)
1315
1315
1316 def headrevs(self, revs=None):
1316 def headrevs(self, revs=None):
1317 if revs is None:
1317 if revs is None:
1318 try:
1318 try:
1319 return self.index.headrevs()
1319 return self.index.headrevs()
1320 except AttributeError:
1320 except AttributeError:
1321 return self._headrevs()
1321 return self._headrevs()
1322 if rustdagop is not None and self.index.rust_ext_compat:
1322 if rustdagop is not None and self.index.rust_ext_compat:
1323 return rustdagop.headrevs(self.index, revs)
1323 return rustdagop.headrevs(self.index, revs)
1324 return dagop.headrevs(revs, self._uncheckedparentrevs)
1324 return dagop.headrevs(revs, self._uncheckedparentrevs)
1325
1325
1326 def computephases(self, roots):
1326 def computephases(self, roots):
1327 return self.index.computephasesmapsets(roots)
1327 return self.index.computephasesmapsets(roots)
1328
1328
1329 def _headrevs(self):
1329 def _headrevs(self):
1330 count = len(self)
1330 count = len(self)
1331 if not count:
1331 if not count:
1332 return [nullrev]
1332 return [nullrev]
1333 # we won't iter over filtered rev so nobody is a head at start
1333 # we won't iter over filtered rev so nobody is a head at start
1334 ishead = [0] * (count + 1)
1334 ishead = [0] * (count + 1)
1335 index = self.index
1335 index = self.index
1336 for r in self:
1336 for r in self:
1337 ishead[r] = 1 # I may be an head
1337 ishead[r] = 1 # I may be an head
1338 e = index[r]
1338 e = index[r]
1339 ishead[e[5]] = ishead[e[6]] = 0 # my parent are not
1339 ishead[e[5]] = ishead[e[6]] = 0 # my parent are not
1340 return [r for r, val in enumerate(ishead) if val]
1340 return [r for r, val in enumerate(ishead) if val]
1341
1341
1342 def heads(self, start=None, stop=None):
1342 def heads(self, start=None, stop=None):
1343 """return the list of all nodes that have no children
1343 """return the list of all nodes that have no children
1344
1344
1345 if start is specified, only heads that are descendants of
1345 if start is specified, only heads that are descendants of
1346 start will be returned
1346 start will be returned
1347 if stop is specified, it will consider all the revs from stop
1347 if stop is specified, it will consider all the revs from stop
1348 as if they had no children
1348 as if they had no children
1349 """
1349 """
1350 if start is None and stop is None:
1350 if start is None and stop is None:
1351 if not len(self):
1351 if not len(self):
1352 return [self.nullid]
1352 return [self.nullid]
1353 return [self.node(r) for r in self.headrevs()]
1353 return [self.node(r) for r in self.headrevs()]
1354
1354
1355 if start is None:
1355 if start is None:
1356 start = nullrev
1356 start = nullrev
1357 else:
1357 else:
1358 start = self.rev(start)
1358 start = self.rev(start)
1359
1359
1360 stoprevs = {self.rev(n) for n in stop or []}
1360 stoprevs = {self.rev(n) for n in stop or []}
1361
1361
1362 revs = dagop.headrevssubset(
1362 revs = dagop.headrevssubset(
1363 self.revs, self.parentrevs, startrev=start, stoprevs=stoprevs
1363 self.revs, self.parentrevs, startrev=start, stoprevs=stoprevs
1364 )
1364 )
1365
1365
1366 return [self.node(rev) for rev in revs]
1366 return [self.node(rev) for rev in revs]
1367
1367
1368 def children(self, node):
1368 def children(self, node):
1369 """find the children of a given node"""
1369 """find the children of a given node"""
1370 c = []
1370 c = []
1371 p = self.rev(node)
1371 p = self.rev(node)
1372 for r in self.revs(start=p + 1):
1372 for r in self.revs(start=p + 1):
1373 prevs = [pr for pr in self.parentrevs(r) if pr != nullrev]
1373 prevs = [pr for pr in self.parentrevs(r) if pr != nullrev]
1374 if prevs:
1374 if prevs:
1375 for pr in prevs:
1375 for pr in prevs:
1376 if pr == p:
1376 if pr == p:
1377 c.append(self.node(r))
1377 c.append(self.node(r))
1378 elif p == nullrev:
1378 elif p == nullrev:
1379 c.append(self.node(r))
1379 c.append(self.node(r))
1380 return c
1380 return c
1381
1381
1382 def commonancestorsheads(self, a, b):
1382 def commonancestorsheads(self, a, b):
1383 """calculate all the heads of the common ancestors of nodes a and b"""
1383 """calculate all the heads of the common ancestors of nodes a and b"""
1384 a, b = self.rev(a), self.rev(b)
1384 a, b = self.rev(a), self.rev(b)
1385 ancs = self._commonancestorsheads(a, b)
1385 ancs = self._commonancestorsheads(a, b)
1386 return pycompat.maplist(self.node, ancs)
1386 return pycompat.maplist(self.node, ancs)
1387
1387
1388 def _commonancestorsheads(self, *revs):
1388 def _commonancestorsheads(self, *revs):
1389 """calculate all the heads of the common ancestors of revs"""
1389 """calculate all the heads of the common ancestors of revs"""
1390 try:
1390 try:
1391 ancs = self.index.commonancestorsheads(*revs)
1391 ancs = self.index.commonancestorsheads(*revs)
1392 except (AttributeError, OverflowError): # C implementation failed
1392 except (AttributeError, OverflowError): # C implementation failed
1393 ancs = ancestor.commonancestorsheads(self.parentrevs, *revs)
1393 ancs = ancestor.commonancestorsheads(self.parentrevs, *revs)
1394 return ancs
1394 return ancs
1395
1395
1396 def isancestor(self, a, b):
1396 def isancestor(self, a, b):
1397 """return True if node a is an ancestor of node b
1397 """return True if node a is an ancestor of node b
1398
1398
1399 A revision is considered an ancestor of itself."""
1399 A revision is considered an ancestor of itself."""
1400 a, b = self.rev(a), self.rev(b)
1400 a, b = self.rev(a), self.rev(b)
1401 return self.isancestorrev(a, b)
1401 return self.isancestorrev(a, b)
1402
1402
1403 def isancestorrev(self, a, b):
1403 def isancestorrev(self, a, b):
1404 """return True if revision a is an ancestor of revision b
1404 """return True if revision a is an ancestor of revision b
1405
1405
1406 A revision is considered an ancestor of itself.
1406 A revision is considered an ancestor of itself.
1407
1407
1408 The implementation of this is trivial but the use of
1408 The implementation of this is trivial but the use of
1409 reachableroots is not."""
1409 reachableroots is not."""
1410 if a == nullrev:
1410 if a == nullrev:
1411 return True
1411 return True
1412 elif a == b:
1412 elif a == b:
1413 return True
1413 return True
1414 elif a > b:
1414 elif a > b:
1415 return False
1415 return False
1416 return bool(self.reachableroots(a, [b], [a], includepath=False))
1416 return bool(self.reachableroots(a, [b], [a], includepath=False))
1417
1417
1418 def reachableroots(self, minroot, heads, roots, includepath=False):
1418 def reachableroots(self, minroot, heads, roots, includepath=False):
1419 """return (heads(::(<roots> and <roots>::<heads>)))
1419 """return (heads(::(<roots> and <roots>::<heads>)))
1420
1420
1421 If includepath is True, return (<roots>::<heads>)."""
1421 If includepath is True, return (<roots>::<heads>)."""
1422 try:
1422 try:
1423 return self.index.reachableroots2(
1423 return self.index.reachableroots2(
1424 minroot, heads, roots, includepath
1424 minroot, heads, roots, includepath
1425 )
1425 )
1426 except AttributeError:
1426 except AttributeError:
1427 return dagop._reachablerootspure(
1427 return dagop._reachablerootspure(
1428 self.parentrevs, minroot, roots, heads, includepath
1428 self.parentrevs, minroot, roots, heads, includepath
1429 )
1429 )
1430
1430
1431 def ancestor(self, a, b):
1431 def ancestor(self, a, b):
1432 """calculate the "best" common ancestor of nodes a and b"""
1432 """calculate the "best" common ancestor of nodes a and b"""
1433
1433
1434 a, b = self.rev(a), self.rev(b)
1434 a, b = self.rev(a), self.rev(b)
1435 try:
1435 try:
1436 ancs = self.index.ancestors(a, b)
1436 ancs = self.index.ancestors(a, b)
1437 except (AttributeError, OverflowError):
1437 except (AttributeError, OverflowError):
1438 ancs = ancestor.ancestors(self.parentrevs, a, b)
1438 ancs = ancestor.ancestors(self.parentrevs, a, b)
1439 if ancs:
1439 if ancs:
1440 # choose a consistent winner when there's a tie
1440 # choose a consistent winner when there's a tie
1441 return min(map(self.node, ancs))
1441 return min(map(self.node, ancs))
1442 return self.nullid
1442 return self.nullid
1443
1443
1444 def _match(self, id):
1444 def _match(self, id):
1445 if isinstance(id, int):
1445 if isinstance(id, int):
1446 # rev
1446 # rev
1447 return self.node(id)
1447 return self.node(id)
1448 if len(id) == self.nodeconstants.nodelen:
1448 if len(id) == self.nodeconstants.nodelen:
1449 # possibly a binary node
1449 # possibly a binary node
1450 # odds of a binary node being all hex in ASCII are 1 in 10**25
1450 # odds of a binary node being all hex in ASCII are 1 in 10**25
1451 try:
1451 try:
1452 node = id
1452 node = id
1453 self.rev(node) # quick search the index
1453 self.rev(node) # quick search the index
1454 return node
1454 return node
1455 except error.LookupError:
1455 except error.LookupError:
1456 pass # may be partial hex id
1456 pass # may be partial hex id
1457 try:
1457 try:
1458 # str(rev)
1458 # str(rev)
1459 rev = int(id)
1459 rev = int(id)
1460 if b"%d" % rev != id:
1460 if b"%d" % rev != id:
1461 raise ValueError
1461 raise ValueError
1462 if rev < 0:
1462 if rev < 0:
1463 rev = len(self) + rev
1463 rev = len(self) + rev
1464 if rev < 0 or rev >= len(self):
1464 if rev < 0 or rev >= len(self):
1465 raise ValueError
1465 raise ValueError
1466 return self.node(rev)
1466 return self.node(rev)
1467 except (ValueError, OverflowError):
1467 except (ValueError, OverflowError):
1468 pass
1468 pass
1469 if len(id) == 2 * self.nodeconstants.nodelen:
1469 if len(id) == 2 * self.nodeconstants.nodelen:
1470 try:
1470 try:
1471 # a full hex nodeid?
1471 # a full hex nodeid?
1472 node = bin(id)
1472 node = bin(id)
1473 self.rev(node)
1473 self.rev(node)
1474 return node
1474 return node
1475 except (TypeError, error.LookupError):
1475 except (TypeError, error.LookupError):
1476 pass
1476 pass
1477
1477
1478 def _partialmatch(self, id):
1478 def _partialmatch(self, id):
1479 # we don't care wdirfilenodeids as they should be always full hash
1479 # we don't care wdirfilenodeids as they should be always full hash
1480 maybewdir = self.nodeconstants.wdirhex.startswith(id)
1480 maybewdir = self.nodeconstants.wdirhex.startswith(id)
1481 ambiguous = False
1481 ambiguous = False
1482 try:
1482 try:
1483 partial = self.index.partialmatch(id)
1483 partial = self.index.partialmatch(id)
1484 if partial and self.hasnode(partial):
1484 if partial and self.hasnode(partial):
1485 if maybewdir:
1485 if maybewdir:
1486 # single 'ff...' match in radix tree, ambiguous with wdir
1486 # single 'ff...' match in radix tree, ambiguous with wdir
1487 ambiguous = True
1487 ambiguous = True
1488 else:
1488 else:
1489 return partial
1489 return partial
1490 elif maybewdir:
1490 elif maybewdir:
1491 # no 'ff...' match in radix tree, wdir identified
1491 # no 'ff...' match in radix tree, wdir identified
1492 raise error.WdirUnsupported
1492 raise error.WdirUnsupported
1493 else:
1493 else:
1494 return None
1494 return None
1495 except error.RevlogError:
1495 except error.RevlogError:
1496 # parsers.c radix tree lookup gave multiple matches
1496 # parsers.c radix tree lookup gave multiple matches
1497 # fast path: for unfiltered changelog, radix tree is accurate
1497 # fast path: for unfiltered changelog, radix tree is accurate
1498 if not getattr(self, 'filteredrevs', None):
1498 if not getattr(self, 'filteredrevs', None):
1499 ambiguous = True
1499 ambiguous = True
1500 # fall through to slow path that filters hidden revisions
1500 # fall through to slow path that filters hidden revisions
1501 except (AttributeError, ValueError):
1501 except (AttributeError, ValueError):
1502 # we are pure python, or key was too short to search radix tree
1502 # we are pure python, or key was too short to search radix tree
1503 pass
1503 pass
1504 if ambiguous:
1504 if ambiguous:
1505 raise error.AmbiguousPrefixLookupError(
1505 raise error.AmbiguousPrefixLookupError(
1506 id, self.display_id, _(b'ambiguous identifier')
1506 id, self.display_id, _(b'ambiguous identifier')
1507 )
1507 )
1508
1508
1509 if id in self._pcache:
1509 if id in self._pcache:
1510 return self._pcache[id]
1510 return self._pcache[id]
1511
1511
1512 if len(id) <= 40:
1512 if len(id) <= 40:
1513 try:
1513 try:
1514 # hex(node)[:...]
1514 # hex(node)[:...]
1515 l = len(id) // 2 # grab an even number of digits
1515 l = len(id) // 2 # grab an even number of digits
1516 prefix = bin(id[: l * 2])
1516 prefix = bin(id[: l * 2])
1517 nl = [e[7] for e in self.index if e[7].startswith(prefix)]
1517 nl = [e[7] for e in self.index if e[7].startswith(prefix)]
1518 nl = [
1518 nl = [
1519 n for n in nl if hex(n).startswith(id) and self.hasnode(n)
1519 n for n in nl if hex(n).startswith(id) and self.hasnode(n)
1520 ]
1520 ]
1521 if self.nodeconstants.nullhex.startswith(id):
1521 if self.nodeconstants.nullhex.startswith(id):
1522 nl.append(self.nullid)
1522 nl.append(self.nullid)
1523 if len(nl) > 0:
1523 if len(nl) > 0:
1524 if len(nl) == 1 and not maybewdir:
1524 if len(nl) == 1 and not maybewdir:
1525 self._pcache[id] = nl[0]
1525 self._pcache[id] = nl[0]
1526 return nl[0]
1526 return nl[0]
1527 raise error.AmbiguousPrefixLookupError(
1527 raise error.AmbiguousPrefixLookupError(
1528 id, self.display_id, _(b'ambiguous identifier')
1528 id, self.display_id, _(b'ambiguous identifier')
1529 )
1529 )
1530 if maybewdir:
1530 if maybewdir:
1531 raise error.WdirUnsupported
1531 raise error.WdirUnsupported
1532 return None
1532 return None
1533 except TypeError:
1533 except TypeError:
1534 pass
1534 pass
1535
1535
1536 def lookup(self, id):
1536 def lookup(self, id):
1537 """locate a node based on:
1537 """locate a node based on:
1538 - revision number or str(revision number)
1538 - revision number or str(revision number)
1539 - nodeid or subset of hex nodeid
1539 - nodeid or subset of hex nodeid
1540 """
1540 """
1541 n = self._match(id)
1541 n = self._match(id)
1542 if n is not None:
1542 if n is not None:
1543 return n
1543 return n
1544 n = self._partialmatch(id)
1544 n = self._partialmatch(id)
1545 if n:
1545 if n:
1546 return n
1546 return n
1547
1547
1548 raise error.LookupError(id, self.display_id, _(b'no match found'))
1548 raise error.LookupError(id, self.display_id, _(b'no match found'))
1549
1549
1550 def shortest(self, node, minlength=1):
1550 def shortest(self, node, minlength=1):
1551 """Find the shortest unambiguous prefix that matches node."""
1551 """Find the shortest unambiguous prefix that matches node."""
1552
1552
1553 def isvalid(prefix):
1553 def isvalid(prefix):
1554 try:
1554 try:
1555 matchednode = self._partialmatch(prefix)
1555 matchednode = self._partialmatch(prefix)
1556 except error.AmbiguousPrefixLookupError:
1556 except error.AmbiguousPrefixLookupError:
1557 return False
1557 return False
1558 except error.WdirUnsupported:
1558 except error.WdirUnsupported:
1559 # single 'ff...' match
1559 # single 'ff...' match
1560 return True
1560 return True
1561 if matchednode is None:
1561 if matchednode is None:
1562 raise error.LookupError(node, self.display_id, _(b'no node'))
1562 raise error.LookupError(node, self.display_id, _(b'no node'))
1563 return True
1563 return True
1564
1564
1565 def maybewdir(prefix):
1565 def maybewdir(prefix):
1566 return all(c == b'f' for c in pycompat.iterbytestr(prefix))
1566 return all(c == b'f' for c in pycompat.iterbytestr(prefix))
1567
1567
1568 hexnode = hex(node)
1568 hexnode = hex(node)
1569
1569
1570 def disambiguate(hexnode, minlength):
1570 def disambiguate(hexnode, minlength):
1571 """Disambiguate against wdirid."""
1571 """Disambiguate against wdirid."""
1572 for length in range(minlength, len(hexnode) + 1):
1572 for length in range(minlength, len(hexnode) + 1):
1573 prefix = hexnode[:length]
1573 prefix = hexnode[:length]
1574 if not maybewdir(prefix):
1574 if not maybewdir(prefix):
1575 return prefix
1575 return prefix
1576
1576
1577 if not getattr(self, 'filteredrevs', None):
1577 if not getattr(self, 'filteredrevs', None):
1578 try:
1578 try:
1579 length = max(self.index.shortest(node), minlength)
1579 length = max(self.index.shortest(node), minlength)
1580 return disambiguate(hexnode, length)
1580 return disambiguate(hexnode, length)
1581 except error.RevlogError:
1581 except error.RevlogError:
1582 if node != self.nodeconstants.wdirid:
1582 if node != self.nodeconstants.wdirid:
1583 raise error.LookupError(
1583 raise error.LookupError(
1584 node, self.display_id, _(b'no node')
1584 node, self.display_id, _(b'no node')
1585 )
1585 )
1586 except AttributeError:
1586 except AttributeError:
1587 # Fall through to pure code
1587 # Fall through to pure code
1588 pass
1588 pass
1589
1589
1590 if node == self.nodeconstants.wdirid:
1590 if node == self.nodeconstants.wdirid:
1591 for length in range(minlength, len(hexnode) + 1):
1591 for length in range(minlength, len(hexnode) + 1):
1592 prefix = hexnode[:length]
1592 prefix = hexnode[:length]
1593 if isvalid(prefix):
1593 if isvalid(prefix):
1594 return prefix
1594 return prefix
1595
1595
1596 for length in range(minlength, len(hexnode) + 1):
1596 for length in range(minlength, len(hexnode) + 1):
1597 prefix = hexnode[:length]
1597 prefix = hexnode[:length]
1598 if isvalid(prefix):
1598 if isvalid(prefix):
1599 return disambiguate(hexnode, length)
1599 return disambiguate(hexnode, length)
1600
1600
1601 def cmp(self, node, text):
1601 def cmp(self, node, text):
1602 """compare text with a given file revision
1602 """compare text with a given file revision
1603
1603
1604 returns True if text is different than what is stored.
1604 returns True if text is different than what is stored.
1605 """
1605 """
1606 p1, p2 = self.parents(node)
1606 p1, p2 = self.parents(node)
1607 return storageutil.hashrevisionsha1(text, p1, p2) != node
1607 return storageutil.hashrevisionsha1(text, p1, p2) != node
1608
1608
1609 def _getsegmentforrevs(self, startrev, endrev, df=None):
1609 def _getsegmentforrevs(self, startrev, endrev, df=None):
1610 """Obtain a segment of raw data corresponding to a range of revisions.
1610 """Obtain a segment of raw data corresponding to a range of revisions.
1611
1611
1612 Accepts the start and end revisions and an optional already-open
1612 Accepts the start and end revisions and an optional already-open
1613 file handle to be used for reading. If the file handle is read, its
1613 file handle to be used for reading. If the file handle is read, its
1614 seek position will not be preserved.
1614 seek position will not be preserved.
1615
1615
1616 Requests for data may be satisfied by a cache.
1616 Requests for data may be satisfied by a cache.
1617
1617
1618 Returns a 2-tuple of (offset, data) for the requested range of
1618 Returns a 2-tuple of (offset, data) for the requested range of
1619 revisions. Offset is the integer offset from the beginning of the
1619 revisions. Offset is the integer offset from the beginning of the
1620 revlog and data is a str or buffer of the raw byte data.
1620 revlog and data is a str or buffer of the raw byte data.
1621
1621
1622 Callers will need to call ``self.start(rev)`` and ``self.length(rev)``
1622 Callers will need to call ``self.start(rev)`` and ``self.length(rev)``
1623 to determine where each revision's data begins and ends.
1623 to determine where each revision's data begins and ends.
1624 """
1624 """
1625 # Inlined self.start(startrev) & self.end(endrev) for perf reasons
1625 # Inlined self.start(startrev) & self.end(endrev) for perf reasons
1626 # (functions are expensive).
1626 # (functions are expensive).
1627 index = self.index
1627 index = self.index
1628 istart = index[startrev]
1628 istart = index[startrev]
1629 start = int(istart[0] >> 16)
1629 start = int(istart[0] >> 16)
1630 if startrev == endrev:
1630 if startrev == endrev:
1631 end = start + istart[1]
1631 end = start + istart[1]
1632 else:
1632 else:
1633 iend = index[endrev]
1633 iend = index[endrev]
1634 end = int(iend[0] >> 16) + iend[1]
1634 end = int(iend[0] >> 16) + iend[1]
1635
1635
1636 if self._inline:
1636 if self._inline:
1637 start += (startrev + 1) * self.index.entry_size
1637 start += (startrev + 1) * self.index.entry_size
1638 end += (endrev + 1) * self.index.entry_size
1638 end += (endrev + 1) * self.index.entry_size
1639 length = end - start
1639 length = end - start
1640
1640
1641 return start, self._segmentfile.read_chunk(start, length, df)
1641 return start, self._segmentfile.read_chunk(start, length, df)
1642
1642
1643 def _chunk(self, rev, df=None):
1643 def _chunk(self, rev, df=None):
1644 """Obtain a single decompressed chunk for a revision.
1644 """Obtain a single decompressed chunk for a revision.
1645
1645
1646 Accepts an integer revision and an optional already-open file handle
1646 Accepts an integer revision and an optional already-open file handle
1647 to be used for reading. If used, the seek position of the file will not
1647 to be used for reading. If used, the seek position of the file will not
1648 be preserved.
1648 be preserved.
1649
1649
1650 Returns a str holding uncompressed data for the requested revision.
1650 Returns a str holding uncompressed data for the requested revision.
1651 """
1651 """
1652 compression_mode = self.index[rev][10]
1652 compression_mode = self.index[rev][10]
1653 data = self._getsegmentforrevs(rev, rev, df=df)[1]
1653 data = self._getsegmentforrevs(rev, rev, df=df)[1]
1654 if compression_mode == COMP_MODE_PLAIN:
1654 if compression_mode == COMP_MODE_PLAIN:
1655 return data
1655 return data
1656 elif compression_mode == COMP_MODE_DEFAULT:
1656 elif compression_mode == COMP_MODE_DEFAULT:
1657 return self._decompressor(data)
1657 return self._decompressor(data)
1658 elif compression_mode == COMP_MODE_INLINE:
1658 elif compression_mode == COMP_MODE_INLINE:
1659 return self.decompress(data)
1659 return self.decompress(data)
1660 else:
1660 else:
1661 msg = b'unknown compression mode %d'
1661 msg = b'unknown compression mode %d'
1662 msg %= compression_mode
1662 msg %= compression_mode
1663 raise error.RevlogError(msg)
1663 raise error.RevlogError(msg)
1664
1664
1665 def _chunks(self, revs, df=None, targetsize=None):
1665 def _chunks(self, revs, df=None, targetsize=None):
1666 """Obtain decompressed chunks for the specified revisions.
1666 """Obtain decompressed chunks for the specified revisions.
1667
1667
1668 Accepts an iterable of numeric revisions that are assumed to be in
1668 Accepts an iterable of numeric revisions that are assumed to be in
1669 ascending order. Also accepts an optional already-open file handle
1669 ascending order. Also accepts an optional already-open file handle
1670 to be used for reading. If used, the seek position of the file will
1670 to be used for reading. If used, the seek position of the file will
1671 not be preserved.
1671 not be preserved.
1672
1672
1673 This function is similar to calling ``self._chunk()`` multiple times,
1673 This function is similar to calling ``self._chunk()`` multiple times,
1674 but is faster.
1674 but is faster.
1675
1675
1676 Returns a list with decompressed data for each requested revision.
1676 Returns a list with decompressed data for each requested revision.
1677 """
1677 """
1678 if not revs:
1678 if not revs:
1679 return []
1679 return []
1680 start = self.start
1680 start = self.start
1681 length = self.length
1681 length = self.length
1682 inline = self._inline
1682 inline = self._inline
1683 iosize = self.index.entry_size
1683 iosize = self.index.entry_size
1684 buffer = util.buffer
1684 buffer = util.buffer
1685
1685
1686 l = []
1686 l = []
1687 ladd = l.append
1687 ladd = l.append
1688
1688
1689 if not self._withsparseread:
1689 if not self._withsparseread:
1690 slicedchunks = (revs,)
1690 slicedchunks = (revs,)
1691 else:
1691 else:
1692 slicedchunks = deltautil.slicechunk(
1692 slicedchunks = deltautil.slicechunk(
1693 self, revs, targetsize=targetsize
1693 self, revs, targetsize=targetsize
1694 )
1694 )
1695
1695
1696 for revschunk in slicedchunks:
1696 for revschunk in slicedchunks:
1697 firstrev = revschunk[0]
1697 firstrev = revschunk[0]
1698 # Skip trailing revisions with empty diff
1698 # Skip trailing revisions with empty diff
1699 for lastrev in revschunk[::-1]:
1699 for lastrev in revschunk[::-1]:
1700 if length(lastrev) != 0:
1700 if length(lastrev) != 0:
1701 break
1701 break
1702
1702
1703 try:
1703 try:
1704 offset, data = self._getsegmentforrevs(firstrev, lastrev, df=df)
1704 offset, data = self._getsegmentforrevs(firstrev, lastrev, df=df)
1705 except OverflowError:
1705 except OverflowError:
1706 # issue4215 - we can't cache a run of chunks greater than
1706 # issue4215 - we can't cache a run of chunks greater than
1707 # 2G on Windows
1707 # 2G on Windows
1708 return [self._chunk(rev, df=df) for rev in revschunk]
1708 return [self._chunk(rev, df=df) for rev in revschunk]
1709
1709
1710 decomp = self.decompress
1710 decomp = self.decompress
1711 # self._decompressor might be None, but will not be used in that case
1711 # self._decompressor might be None, but will not be used in that case
1712 def_decomp = self._decompressor
1712 def_decomp = self._decompressor
1713 for rev in revschunk:
1713 for rev in revschunk:
1714 chunkstart = start(rev)
1714 chunkstart = start(rev)
1715 if inline:
1715 if inline:
1716 chunkstart += (rev + 1) * iosize
1716 chunkstart += (rev + 1) * iosize
1717 chunklength = length(rev)
1717 chunklength = length(rev)
1718 comp_mode = self.index[rev][10]
1718 comp_mode = self.index[rev][10]
1719 c = buffer(data, chunkstart - offset, chunklength)
1719 c = buffer(data, chunkstart - offset, chunklength)
1720 if comp_mode == COMP_MODE_PLAIN:
1720 if comp_mode == COMP_MODE_PLAIN:
1721 ladd(c)
1721 ladd(c)
1722 elif comp_mode == COMP_MODE_INLINE:
1722 elif comp_mode == COMP_MODE_INLINE:
1723 ladd(decomp(c))
1723 ladd(decomp(c))
1724 elif comp_mode == COMP_MODE_DEFAULT:
1724 elif comp_mode == COMP_MODE_DEFAULT:
1725 ladd(def_decomp(c))
1725 ladd(def_decomp(c))
1726 else:
1726 else:
1727 msg = b'unknown compression mode %d'
1727 msg = b'unknown compression mode %d'
1728 msg %= comp_mode
1728 msg %= comp_mode
1729 raise error.RevlogError(msg)
1729 raise error.RevlogError(msg)
1730
1730
1731 return l
1731 return l
1732
1732
1733 def deltaparent(self, rev):
1733 def deltaparent(self, rev):
1734 """return deltaparent of the given revision"""
1734 """return deltaparent of the given revision"""
1735 base = self.index[rev][3]
1735 base = self.index[rev][3]
1736 if base == rev:
1736 if base == rev:
1737 return nullrev
1737 return nullrev
1738 elif self._generaldelta:
1738 elif self._generaldelta:
1739 return base
1739 return base
1740 else:
1740 else:
1741 return rev - 1
1741 return rev - 1
1742
1742
1743 def issnapshot(self, rev):
1743 def issnapshot(self, rev):
1744 """tells whether rev is a snapshot"""
1744 """tells whether rev is a snapshot"""
1745 if not self._sparserevlog:
1745 if not self._sparserevlog:
1746 return self.deltaparent(rev) == nullrev
1746 return self.deltaparent(rev) == nullrev
1747 elif util.safehasattr(self.index, b'issnapshot'):
1747 elif util.safehasattr(self.index, b'issnapshot'):
1748 # directly assign the method to cache the testing and access
1748 # directly assign the method to cache the testing and access
1749 self.issnapshot = self.index.issnapshot
1749 self.issnapshot = self.index.issnapshot
1750 return self.issnapshot(rev)
1750 return self.issnapshot(rev)
1751 if rev == nullrev:
1751 if rev == nullrev:
1752 return True
1752 return True
1753 entry = self.index[rev]
1753 entry = self.index[rev]
1754 base = entry[3]
1754 base = entry[3]
1755 if base == rev:
1755 if base == rev:
1756 return True
1756 return True
1757 if base == nullrev:
1757 if base == nullrev:
1758 return True
1758 return True
1759 p1 = entry[5]
1759 p1 = entry[5]
1760 p2 = entry[6]
1760 p2 = entry[6]
1761 if base == p1 or base == p2:
1761 if base == p1 or base == p2:
1762 return False
1762 return False
1763 return self.issnapshot(base)
1763 return self.issnapshot(base)
1764
1764
1765 def snapshotdepth(self, rev):
1765 def snapshotdepth(self, rev):
1766 """number of snapshot in the chain before this one"""
1766 """number of snapshot in the chain before this one"""
1767 if not self.issnapshot(rev):
1767 if not self.issnapshot(rev):
1768 raise error.ProgrammingError(b'revision %d not a snapshot')
1768 raise error.ProgrammingError(b'revision %d not a snapshot')
1769 return len(self._deltachain(rev)[0]) - 1
1769 return len(self._deltachain(rev)[0]) - 1
1770
1770
1771 def revdiff(self, rev1, rev2):
1771 def revdiff(self, rev1, rev2):
1772 """return or calculate a delta between two revisions
1772 """return or calculate a delta between two revisions
1773
1773
1774 The delta calculated is in binary form and is intended to be written to
1774 The delta calculated is in binary form and is intended to be written to
1775 revlog data directly. So this function needs raw revision data.
1775 revlog data directly. So this function needs raw revision data.
1776 """
1776 """
1777 if rev1 != nullrev and self.deltaparent(rev2) == rev1:
1777 if rev1 != nullrev and self.deltaparent(rev2) == rev1:
1778 return bytes(self._chunk(rev2))
1778 return bytes(self._chunk(rev2))
1779
1779
1780 return mdiff.textdiff(self.rawdata(rev1), self.rawdata(rev2))
1780 return mdiff.textdiff(self.rawdata(rev1), self.rawdata(rev2))
1781
1781
1782 def revision(self, nodeorrev, _df=None):
1782 def revision(self, nodeorrev, _df=None):
1783 """return an uncompressed revision of a given node or revision
1783 """return an uncompressed revision of a given node or revision
1784 number.
1784 number.
1785
1785
1786 _df - an existing file handle to read from. (internal-only)
1786 _df - an existing file handle to read from. (internal-only)
1787 """
1787 """
1788 return self._revisiondata(nodeorrev, _df)
1788 return self._revisiondata(nodeorrev, _df)
1789
1789
1790 def sidedata(self, nodeorrev, _df=None):
1790 def sidedata(self, nodeorrev, _df=None):
1791 """a map of extra data related to the changeset but not part of the hash
1791 """a map of extra data related to the changeset but not part of the hash
1792
1792
1793 This function currently return a dictionary. However, more advanced
1793 This function currently return a dictionary. However, more advanced
1794 mapping object will likely be used in the future for a more
1794 mapping object will likely be used in the future for a more
1795 efficient/lazy code.
1795 efficient/lazy code.
1796 """
1796 """
1797 # deal with <nodeorrev> argument type
1797 # deal with <nodeorrev> argument type
1798 if isinstance(nodeorrev, int):
1798 if isinstance(nodeorrev, int):
1799 rev = nodeorrev
1799 rev = nodeorrev
1800 else:
1800 else:
1801 rev = self.rev(nodeorrev)
1801 rev = self.rev(nodeorrev)
1802 return self._sidedata(rev)
1802 return self._sidedata(rev)
1803
1803
1804 def _revisiondata(self, nodeorrev, _df=None, raw=False):
1804 def _revisiondata(self, nodeorrev, _df=None, raw=False):
1805 # deal with <nodeorrev> argument type
1805 # deal with <nodeorrev> argument type
1806 if isinstance(nodeorrev, int):
1806 if isinstance(nodeorrev, int):
1807 rev = nodeorrev
1807 rev = nodeorrev
1808 node = self.node(rev)
1808 node = self.node(rev)
1809 else:
1809 else:
1810 node = nodeorrev
1810 node = nodeorrev
1811 rev = None
1811 rev = None
1812
1812
1813 # fast path the special `nullid` rev
1813 # fast path the special `nullid` rev
1814 if node == self.nullid:
1814 if node == self.nullid:
1815 return b""
1815 return b""
1816
1816
1817 # ``rawtext`` is the text as stored inside the revlog. Might be the
1817 # ``rawtext`` is the text as stored inside the revlog. Might be the
1818 # revision or might need to be processed to retrieve the revision.
1818 # revision or might need to be processed to retrieve the revision.
1819 rev, rawtext, validated = self._rawtext(node, rev, _df=_df)
1819 rev, rawtext, validated = self._rawtext(node, rev, _df=_df)
1820
1820
1821 if raw and validated:
1821 if raw and validated:
1822 # if we don't want to process the raw text and that raw
1822 # if we don't want to process the raw text and that raw
1823 # text is cached, we can exit early.
1823 # text is cached, we can exit early.
1824 return rawtext
1824 return rawtext
1825 if rev is None:
1825 if rev is None:
1826 rev = self.rev(node)
1826 rev = self.rev(node)
1827 # the revlog's flag for this revision
1827 # the revlog's flag for this revision
1828 # (usually alter its state or content)
1828 # (usually alter its state or content)
1829 flags = self.flags(rev)
1829 flags = self.flags(rev)
1830
1830
1831 if validated and flags == REVIDX_DEFAULT_FLAGS:
1831 if validated and flags == REVIDX_DEFAULT_FLAGS:
1832 # no extra flags set, no flag processor runs, text = rawtext
1832 # no extra flags set, no flag processor runs, text = rawtext
1833 return rawtext
1833 return rawtext
1834
1834
1835 if raw:
1835 if raw:
1836 validatehash = flagutil.processflagsraw(self, rawtext, flags)
1836 validatehash = flagutil.processflagsraw(self, rawtext, flags)
1837 text = rawtext
1837 text = rawtext
1838 else:
1838 else:
1839 r = flagutil.processflagsread(self, rawtext, flags)
1839 r = flagutil.processflagsread(self, rawtext, flags)
1840 text, validatehash = r
1840 text, validatehash = r
1841 if validatehash:
1841 if validatehash:
1842 self.checkhash(text, node, rev=rev)
1842 self.checkhash(text, node, rev=rev)
1843 if not validated:
1843 if not validated:
1844 self._revisioncache = (node, rev, rawtext)
1844 self._revisioncache = (node, rev, rawtext)
1845
1845
1846 return text
1846 return text
1847
1847
1848 def _rawtext(self, node, rev, _df=None):
1848 def _rawtext(self, node, rev, _df=None):
1849 """return the possibly unvalidated rawtext for a revision
1849 """return the possibly unvalidated rawtext for a revision
1850
1850
1851 returns (rev, rawtext, validated)
1851 returns (rev, rawtext, validated)
1852 """
1852 """
1853
1853
1854 # revision in the cache (could be useful to apply delta)
1854 # revision in the cache (could be useful to apply delta)
1855 cachedrev = None
1855 cachedrev = None
1856 # An intermediate text to apply deltas to
1856 # An intermediate text to apply deltas to
1857 basetext = None
1857 basetext = None
1858
1858
1859 # Check if we have the entry in cache
1859 # Check if we have the entry in cache
1860 # The cache entry looks like (node, rev, rawtext)
1860 # The cache entry looks like (node, rev, rawtext)
1861 if self._revisioncache:
1861 if self._revisioncache:
1862 if self._revisioncache[0] == node:
1862 if self._revisioncache[0] == node:
1863 return (rev, self._revisioncache[2], True)
1863 return (rev, self._revisioncache[2], True)
1864 cachedrev = self._revisioncache[1]
1864 cachedrev = self._revisioncache[1]
1865
1865
1866 if rev is None:
1866 if rev is None:
1867 rev = self.rev(node)
1867 rev = self.rev(node)
1868
1868
1869 chain, stopped = self._deltachain(rev, stoprev=cachedrev)
1869 chain, stopped = self._deltachain(rev, stoprev=cachedrev)
1870 if stopped:
1870 if stopped:
1871 basetext = self._revisioncache[2]
1871 basetext = self._revisioncache[2]
1872
1872
1873 # drop cache to save memory, the caller is expected to
1873 # drop cache to save memory, the caller is expected to
1874 # update self._revisioncache after validating the text
1874 # update self._revisioncache after validating the text
1875 self._revisioncache = None
1875 self._revisioncache = None
1876
1876
1877 targetsize = None
1877 targetsize = None
1878 rawsize = self.index[rev][2]
1878 rawsize = self.index[rev][2]
1879 if 0 <= rawsize:
1879 if 0 <= rawsize:
1880 targetsize = 4 * rawsize
1880 targetsize = 4 * rawsize
1881
1881
1882 bins = self._chunks(chain, df=_df, targetsize=targetsize)
1882 bins = self._chunks(chain, df=_df, targetsize=targetsize)
1883 if basetext is None:
1883 if basetext is None:
1884 basetext = bytes(bins[0])
1884 basetext = bytes(bins[0])
1885 bins = bins[1:]
1885 bins = bins[1:]
1886
1886
1887 rawtext = mdiff.patches(basetext, bins)
1887 rawtext = mdiff.patches(basetext, bins)
1888 del basetext # let us have a chance to free memory early
1888 del basetext # let us have a chance to free memory early
1889 return (rev, rawtext, False)
1889 return (rev, rawtext, False)
1890
1890
1891 def _sidedata(self, rev):
1891 def _sidedata(self, rev):
1892 """Return the sidedata for a given revision number."""
1892 """Return the sidedata for a given revision number."""
1893 index_entry = self.index[rev]
1893 index_entry = self.index[rev]
1894 sidedata_offset = index_entry[8]
1894 sidedata_offset = index_entry[8]
1895 sidedata_size = index_entry[9]
1895 sidedata_size = index_entry[9]
1896
1896
1897 if self._inline:
1897 if self._inline:
1898 sidedata_offset += self.index.entry_size * (1 + rev)
1898 sidedata_offset += self.index.entry_size * (1 + rev)
1899 if sidedata_size == 0:
1899 if sidedata_size == 0:
1900 return {}
1900 return {}
1901
1901
1902 if self._docket.sidedata_end < sidedata_offset + sidedata_size:
1902 if self._docket.sidedata_end < sidedata_offset + sidedata_size:
1903 filename = self._sidedatafile
1903 filename = self._sidedatafile
1904 end = self._docket.sidedata_end
1904 end = self._docket.sidedata_end
1905 offset = sidedata_offset
1905 offset = sidedata_offset
1906 length = sidedata_size
1906 length = sidedata_size
1907 m = FILE_TOO_SHORT_MSG % (filename, length, offset, end)
1907 m = FILE_TOO_SHORT_MSG % (filename, length, offset, end)
1908 raise error.RevlogError(m)
1908 raise error.RevlogError(m)
1909
1909
1910 comp_segment = self._segmentfile_sidedata.read_chunk(
1910 comp_segment = self._segmentfile_sidedata.read_chunk(
1911 sidedata_offset, sidedata_size
1911 sidedata_offset, sidedata_size
1912 )
1912 )
1913
1913
1914 comp = self.index[rev][11]
1914 comp = self.index[rev][11]
1915 if comp == COMP_MODE_PLAIN:
1915 if comp == COMP_MODE_PLAIN:
1916 segment = comp_segment
1916 segment = comp_segment
1917 elif comp == COMP_MODE_DEFAULT:
1917 elif comp == COMP_MODE_DEFAULT:
1918 segment = self._decompressor(comp_segment)
1918 segment = self._decompressor(comp_segment)
1919 elif comp == COMP_MODE_INLINE:
1919 elif comp == COMP_MODE_INLINE:
1920 segment = self.decompress(comp_segment)
1920 segment = self.decompress(comp_segment)
1921 else:
1921 else:
1922 msg = b'unknown compression mode %d'
1922 msg = b'unknown compression mode %d'
1923 msg %= comp
1923 msg %= comp
1924 raise error.RevlogError(msg)
1924 raise error.RevlogError(msg)
1925
1925
1926 sidedata = sidedatautil.deserialize_sidedata(segment)
1926 sidedata = sidedatautil.deserialize_sidedata(segment)
1927 return sidedata
1927 return sidedata
1928
1928
1929 def rawdata(self, nodeorrev, _df=None):
1929 def rawdata(self, nodeorrev, _df=None):
1930 """return an uncompressed raw data of a given node or revision number.
1930 """return an uncompressed raw data of a given node or revision number.
1931
1931
1932 _df - an existing file handle to read from. (internal-only)
1932 _df - an existing file handle to read from. (internal-only)
1933 """
1933 """
1934 return self._revisiondata(nodeorrev, _df, raw=True)
1934 return self._revisiondata(nodeorrev, _df, raw=True)
1935
1935
1936 def hash(self, text, p1, p2):
1936 def hash(self, text, p1, p2):
1937 """Compute a node hash.
1937 """Compute a node hash.
1938
1938
1939 Available as a function so that subclasses can replace the hash
1939 Available as a function so that subclasses can replace the hash
1940 as needed.
1940 as needed.
1941 """
1941 """
1942 return storageutil.hashrevisionsha1(text, p1, p2)
1942 return storageutil.hashrevisionsha1(text, p1, p2)
1943
1943
1944 def checkhash(self, text, node, p1=None, p2=None, rev=None):
1944 def checkhash(self, text, node, p1=None, p2=None, rev=None):
1945 """Check node hash integrity.
1945 """Check node hash integrity.
1946
1946
1947 Available as a function so that subclasses can extend hash mismatch
1947 Available as a function so that subclasses can extend hash mismatch
1948 behaviors as needed.
1948 behaviors as needed.
1949 """
1949 """
1950 try:
1950 try:
1951 if p1 is None and p2 is None:
1951 if p1 is None and p2 is None:
1952 p1, p2 = self.parents(node)
1952 p1, p2 = self.parents(node)
1953 if node != self.hash(text, p1, p2):
1953 if node != self.hash(text, p1, p2):
1954 # Clear the revision cache on hash failure. The revision cache
1954 # Clear the revision cache on hash failure. The revision cache
1955 # only stores the raw revision and clearing the cache does have
1955 # only stores the raw revision and clearing the cache does have
1956 # the side-effect that we won't have a cache hit when the raw
1956 # the side-effect that we won't have a cache hit when the raw
1957 # revision data is accessed. But this case should be rare and
1957 # revision data is accessed. But this case should be rare and
1958 # it is extra work to teach the cache about the hash
1958 # it is extra work to teach the cache about the hash
1959 # verification state.
1959 # verification state.
1960 if self._revisioncache and self._revisioncache[0] == node:
1960 if self._revisioncache and self._revisioncache[0] == node:
1961 self._revisioncache = None
1961 self._revisioncache = None
1962
1962
1963 revornode = rev
1963 revornode = rev
1964 if revornode is None:
1964 if revornode is None:
1965 revornode = templatefilters.short(hex(node))
1965 revornode = templatefilters.short(hex(node))
1966 raise error.RevlogError(
1966 raise error.RevlogError(
1967 _(b"integrity check failed on %s:%s")
1967 _(b"integrity check failed on %s:%s")
1968 % (self.display_id, pycompat.bytestr(revornode))
1968 % (self.display_id, pycompat.bytestr(revornode))
1969 )
1969 )
1970 except error.RevlogError:
1970 except error.RevlogError:
1971 if self._censorable and storageutil.iscensoredtext(text):
1971 if self._censorable and storageutil.iscensoredtext(text):
1972 raise error.CensoredNodeError(self.display_id, node, text)
1972 raise error.CensoredNodeError(self.display_id, node, text)
1973 raise
1973 raise
1974
1974
1975 def _enforceinlinesize(self, tr):
1975 def _enforceinlinesize(self, tr):
1976 """Check if the revlog is too big for inline and convert if so.
1976 """Check if the revlog is too big for inline and convert if so.
1977
1977
1978 This should be called after revisions are added to the revlog. If the
1978 This should be called after revisions are added to the revlog. If the
1979 revlog has grown too large to be an inline revlog, it will convert it
1979 revlog has grown too large to be an inline revlog, it will convert it
1980 to use multiple index and data files.
1980 to use multiple index and data files.
1981 """
1981 """
1982 tiprev = len(self) - 1
1982 tiprev = len(self) - 1
1983 total_size = self.start(tiprev) + self.length(tiprev)
1983 total_size = self.start(tiprev) + self.length(tiprev)
1984 if not self._inline or total_size < _maxinline:
1984 if not self._inline or total_size < _maxinline:
1985 return
1985 return
1986
1986
1987 troffset = tr.findoffset(self._indexfile)
1987 troffset = tr.findoffset(self._indexfile)
1988 if troffset is None:
1988 if troffset is None:
1989 raise error.RevlogError(
1989 raise error.RevlogError(
1990 _(b"%s not found in the transaction") % self._indexfile
1990 _(b"%s not found in the transaction") % self._indexfile
1991 )
1991 )
1992 trindex = None
1992 trindex = None
1993 tr.add(self._datafile, 0)
1993 tr.add(self._datafile, 0)
1994
1994
1995 existing_handles = False
1995 existing_handles = False
1996 if self._writinghandles is not None:
1996 if self._writinghandles is not None:
1997 existing_handles = True
1997 existing_handles = True
1998 fp = self._writinghandles[0]
1998 fp = self._writinghandles[0]
1999 fp.flush()
1999 fp.flush()
2000 fp.close()
2000 fp.close()
2001 # We can't use the cached file handle after close(). So prevent
2001 # We can't use the cached file handle after close(). So prevent
2002 # its usage.
2002 # its usage.
2003 self._writinghandles = None
2003 self._writinghandles = None
2004 self._segmentfile.writing_handle = None
2004 self._segmentfile.writing_handle = None
2005 # No need to deal with sidedata writing handle as it is only
2005 # No need to deal with sidedata writing handle as it is only
2006 # relevant with revlog-v2 which is never inline, not reaching
2006 # relevant with revlog-v2 which is never inline, not reaching
2007 # this code
2007 # this code
2008
2008
2009 new_dfh = self._datafp(b'w+')
2009 new_dfh = self._datafp(b'w+')
2010 new_dfh.truncate(0) # drop any potentially existing data
2010 new_dfh.truncate(0) # drop any potentially existing data
2011 try:
2011 try:
2012 with self._indexfp() as read_ifh:
2012 with self._indexfp() as read_ifh:
2013 for r in self:
2013 for r in self:
2014 new_dfh.write(self._getsegmentforrevs(r, r, df=read_ifh)[1])
2014 new_dfh.write(self._getsegmentforrevs(r, r, df=read_ifh)[1])
2015 if (
2015 if (
2016 trindex is None
2016 trindex is None
2017 and troffset
2017 and troffset
2018 <= self.start(r) + r * self.index.entry_size
2018 <= self.start(r) + r * self.index.entry_size
2019 ):
2019 ):
2020 trindex = r
2020 trindex = r
2021 new_dfh.flush()
2021 new_dfh.flush()
2022
2022
2023 if trindex is None:
2023 if trindex is None:
2024 trindex = 0
2024 trindex = 0
2025
2025
2026 with self.__index_new_fp() as fp:
2026 with self.__index_new_fp() as fp:
2027 self._format_flags &= ~FLAG_INLINE_DATA
2027 self._format_flags &= ~FLAG_INLINE_DATA
2028 self._inline = False
2028 self._inline = False
2029 for i in self:
2029 for i in self:
2030 e = self.index.entry_binary(i)
2030 e = self.index.entry_binary(i)
2031 if i == 0 and self._docket is None:
2031 if i == 0 and self._docket is None:
2032 header = self._format_flags | self._format_version
2032 header = self._format_flags | self._format_version
2033 header = self.index.pack_header(header)
2033 header = self.index.pack_header(header)
2034 e = header + e
2034 e = header + e
2035 fp.write(e)
2035 fp.write(e)
2036 if self._docket is not None:
2036 if self._docket is not None:
2037 self._docket.index_end = fp.tell()
2037 self._docket.index_end = fp.tell()
2038
2038
2039 # There is a small transactional race here. If the rename of
2039 # There is a small transactional race here. If the rename of
2040 # the index fails, we should remove the datafile. It is more
2040 # the index fails, we should remove the datafile. It is more
2041 # important to ensure that the data file is not truncated
2041 # important to ensure that the data file is not truncated
2042 # when the index is replaced as otherwise data is lost.
2042 # when the index is replaced as otherwise data is lost.
2043 tr.replace(self._datafile, self.start(trindex))
2043 tr.replace(self._datafile, self.start(trindex))
2044
2044
2045 # the temp file replace the real index when we exit the context
2045 # the temp file replace the real index when we exit the context
2046 # manager
2046 # manager
2047
2047
2048 tr.replace(self._indexfile, trindex * self.index.entry_size)
2048 tr.replace(self._indexfile, trindex * self.index.entry_size)
2049 nodemaputil.setup_persistent_nodemap(tr, self)
2049 nodemaputil.setup_persistent_nodemap(tr, self)
2050 self._segmentfile = randomaccessfile.randomaccessfile(
2050 self._segmentfile = randomaccessfile.randomaccessfile(
2051 self.opener,
2051 self.opener,
2052 self._datafile,
2052 self._datafile,
2053 self._chunkcachesize,
2053 self._chunkcachesize,
2054 )
2054 )
2055
2055
2056 if existing_handles:
2056 if existing_handles:
2057 # switched from inline to conventional reopen the index
2057 # switched from inline to conventional reopen the index
2058 ifh = self.__index_write_fp()
2058 ifh = self.__index_write_fp()
2059 self._writinghandles = (ifh, new_dfh, None)
2059 self._writinghandles = (ifh, new_dfh, None)
2060 self._segmentfile.writing_handle = new_dfh
2060 self._segmentfile.writing_handle = new_dfh
2061 new_dfh = None
2061 new_dfh = None
2062 # No need to deal with sidedata writing handle as it is only
2062 # No need to deal with sidedata writing handle as it is only
2063 # relevant with revlog-v2 which is never inline, not reaching
2063 # relevant with revlog-v2 which is never inline, not reaching
2064 # this code
2064 # this code
2065 finally:
2065 finally:
2066 if new_dfh is not None:
2066 if new_dfh is not None:
2067 new_dfh.close()
2067 new_dfh.close()
2068
2068
2069 def _nodeduplicatecallback(self, transaction, node):
2069 def _nodeduplicatecallback(self, transaction, node):
2070 """called when trying to add a node already stored."""
2070 """called when trying to add a node already stored."""
2071
2071
2072 @contextlib.contextmanager
2072 @contextlib.contextmanager
2073 def reading(self):
2073 def reading(self):
2074 """Context manager that keeps data and sidedata files open for reading"""
2074 """Context manager that keeps data and sidedata files open for reading"""
2075 with self._segmentfile.reading():
2075 with self._segmentfile.reading():
2076 with self._segmentfile_sidedata.reading():
2076 with self._segmentfile_sidedata.reading():
2077 yield
2077 yield
2078
2078
2079 @contextlib.contextmanager
2079 @contextlib.contextmanager
2080 def _writing(self, transaction):
2080 def _writing(self, transaction):
2081 if self._trypending:
2081 if self._trypending:
2082 msg = b'try to write in a `trypending` revlog: %s'
2082 msg = b'try to write in a `trypending` revlog: %s'
2083 msg %= self.display_id
2083 msg %= self.display_id
2084 raise error.ProgrammingError(msg)
2084 raise error.ProgrammingError(msg)
2085 if self._writinghandles is not None:
2085 if self._writinghandles is not None:
2086 yield
2086 yield
2087 else:
2087 else:
2088 ifh = dfh = sdfh = None
2088 ifh = dfh = sdfh = None
2089 try:
2089 try:
2090 r = len(self)
2090 r = len(self)
2091 # opening the data file.
2091 # opening the data file.
2092 dsize = 0
2092 dsize = 0
2093 if r:
2093 if r:
2094 dsize = self.end(r - 1)
2094 dsize = self.end(r - 1)
2095 dfh = None
2095 dfh = None
2096 if not self._inline:
2096 if not self._inline:
2097 try:
2097 try:
2098 dfh = self._datafp(b"r+")
2098 dfh = self._datafp(b"r+")
2099 if self._docket is None:
2099 if self._docket is None:
2100 dfh.seek(0, os.SEEK_END)
2100 dfh.seek(0, os.SEEK_END)
2101 else:
2101 else:
2102 dfh.seek(self._docket.data_end, os.SEEK_SET)
2102 dfh.seek(self._docket.data_end, os.SEEK_SET)
2103 except IOError as inst:
2103 except IOError as inst:
2104 if inst.errno != errno.ENOENT:
2104 if inst.errno != errno.ENOENT:
2105 raise
2105 raise
2106 dfh = self._datafp(b"w+")
2106 dfh = self._datafp(b"w+")
2107 transaction.add(self._datafile, dsize)
2107 transaction.add(self._datafile, dsize)
2108 if self._sidedatafile is not None:
2108 if self._sidedatafile is not None:
2109 # revlog-v2 does not inline, help Pytype
2109 # revlog-v2 does not inline, help Pytype
2110 assert dfh is not None
2110 assert dfh is not None
2111 try:
2111 try:
2112 sdfh = self.opener(self._sidedatafile, mode=b"r+")
2112 sdfh = self.opener(self._sidedatafile, mode=b"r+")
2113 dfh.seek(self._docket.sidedata_end, os.SEEK_SET)
2113 dfh.seek(self._docket.sidedata_end, os.SEEK_SET)
2114 except IOError as inst:
2114 except IOError as inst:
2115 if inst.errno != errno.ENOENT:
2115 if inst.errno != errno.ENOENT:
2116 raise
2116 raise
2117 sdfh = self.opener(self._sidedatafile, mode=b"w+")
2117 sdfh = self.opener(self._sidedatafile, mode=b"w+")
2118 transaction.add(
2118 transaction.add(
2119 self._sidedatafile, self._docket.sidedata_end
2119 self._sidedatafile, self._docket.sidedata_end
2120 )
2120 )
2121
2121
2122 # opening the index file.
2122 # opening the index file.
2123 isize = r * self.index.entry_size
2123 isize = r * self.index.entry_size
2124 ifh = self.__index_write_fp()
2124 ifh = self.__index_write_fp()
2125 if self._inline:
2125 if self._inline:
2126 transaction.add(self._indexfile, dsize + isize)
2126 transaction.add(self._indexfile, dsize + isize)
2127 else:
2127 else:
2128 transaction.add(self._indexfile, isize)
2128 transaction.add(self._indexfile, isize)
2129 # exposing all file handle for writing.
2129 # exposing all file handle for writing.
2130 self._writinghandles = (ifh, dfh, sdfh)
2130 self._writinghandles = (ifh, dfh, sdfh)
2131 self._segmentfile.writing_handle = ifh if self._inline else dfh
2131 self._segmentfile.writing_handle = ifh if self._inline else dfh
2132 self._segmentfile_sidedata.writing_handle = sdfh
2132 self._segmentfile_sidedata.writing_handle = sdfh
2133 yield
2133 yield
2134 if self._docket is not None:
2134 if self._docket is not None:
2135 self._write_docket(transaction)
2135 self._write_docket(transaction)
2136 finally:
2136 finally:
2137 self._writinghandles = None
2137 self._writinghandles = None
2138 self._segmentfile.writing_handle = None
2138 self._segmentfile.writing_handle = None
2139 self._segmentfile_sidedata.writing_handle = None
2139 self._segmentfile_sidedata.writing_handle = None
2140 if dfh is not None:
2140 if dfh is not None:
2141 dfh.close()
2141 dfh.close()
2142 if sdfh is not None:
2142 if sdfh is not None:
2143 sdfh.close()
2143 sdfh.close()
2144 # closing the index file last to avoid exposing referent to
2144 # closing the index file last to avoid exposing referent to
2145 # potential unflushed data content.
2145 # potential unflushed data content.
2146 if ifh is not None:
2146 if ifh is not None:
2147 ifh.close()
2147 ifh.close()
2148
2148
2149 def _write_docket(self, transaction):
2149 def _write_docket(self, transaction):
2150 """write the current docket on disk
2150 """write the current docket on disk
2151
2151
2152 Exist as a method to help changelog to implement transaction logic
2152 Exist as a method to help changelog to implement transaction logic
2153
2153
2154 We could also imagine using the same transaction logic for all revlog
2154 We could also imagine using the same transaction logic for all revlog
2155 since docket are cheap."""
2155 since docket are cheap."""
2156 self._docket.write(transaction)
2156 self._docket.write(transaction)
2157
2157
2158 def addrevision(
2158 def addrevision(
2159 self,
2159 self,
2160 text,
2160 text,
2161 transaction,
2161 transaction,
2162 link,
2162 link,
2163 p1,
2163 p1,
2164 p2,
2164 p2,
2165 cachedelta=None,
2165 cachedelta=None,
2166 node=None,
2166 node=None,
2167 flags=REVIDX_DEFAULT_FLAGS,
2167 flags=REVIDX_DEFAULT_FLAGS,
2168 deltacomputer=None,
2168 deltacomputer=None,
2169 sidedata=None,
2169 sidedata=None,
2170 ):
2170 ):
2171 """add a revision to the log
2171 """add a revision to the log
2172
2172
2173 text - the revision data to add
2173 text - the revision data to add
2174 transaction - the transaction object used for rollback
2174 transaction - the transaction object used for rollback
2175 link - the linkrev data to add
2175 link - the linkrev data to add
2176 p1, p2 - the parent nodeids of the revision
2176 p1, p2 - the parent nodeids of the revision
2177 cachedelta - an optional precomputed delta
2177 cachedelta - an optional precomputed delta
2178 node - nodeid of revision; typically node is not specified, and it is
2178 node - nodeid of revision; typically node is not specified, and it is
2179 computed by default as hash(text, p1, p2), however subclasses might
2179 computed by default as hash(text, p1, p2), however subclasses might
2180 use different hashing method (and override checkhash() in such case)
2180 use different hashing method (and override checkhash() in such case)
2181 flags - the known flags to set on the revision
2181 flags - the known flags to set on the revision
2182 deltacomputer - an optional deltacomputer instance shared between
2182 deltacomputer - an optional deltacomputer instance shared between
2183 multiple calls
2183 multiple calls
2184 """
2184 """
2185 if link == nullrev:
2185 if link == nullrev:
2186 raise error.RevlogError(
2186 raise error.RevlogError(
2187 _(b"attempted to add linkrev -1 to %s") % self.display_id
2187 _(b"attempted to add linkrev -1 to %s") % self.display_id
2188 )
2188 )
2189
2189
2190 if sidedata is None:
2190 if sidedata is None:
2191 sidedata = {}
2191 sidedata = {}
2192 elif sidedata and not self.hassidedata:
2192 elif sidedata and not self.hassidedata:
2193 raise error.ProgrammingError(
2193 raise error.ProgrammingError(
2194 _(b"trying to add sidedata to a revlog who don't support them")
2194 _(b"trying to add sidedata to a revlog who don't support them")
2195 )
2195 )
2196
2196
2197 if flags:
2197 if flags:
2198 node = node or self.hash(text, p1, p2)
2198 node = node or self.hash(text, p1, p2)
2199
2199
2200 rawtext, validatehash = flagutil.processflagswrite(self, text, flags)
2200 rawtext, validatehash = flagutil.processflagswrite(self, text, flags)
2201
2201
2202 # If the flag processor modifies the revision data, ignore any provided
2202 # If the flag processor modifies the revision data, ignore any provided
2203 # cachedelta.
2203 # cachedelta.
2204 if rawtext != text:
2204 if rawtext != text:
2205 cachedelta = None
2205 cachedelta = None
2206
2206
2207 if len(rawtext) > _maxentrysize:
2207 if len(rawtext) > _maxentrysize:
2208 raise error.RevlogError(
2208 raise error.RevlogError(
2209 _(
2209 _(
2210 b"%s: size of %d bytes exceeds maximum revlog storage of 2GiB"
2210 b"%s: size of %d bytes exceeds maximum revlog storage of 2GiB"
2211 )
2211 )
2212 % (self.display_id, len(rawtext))
2212 % (self.display_id, len(rawtext))
2213 )
2213 )
2214
2214
2215 node = node or self.hash(rawtext, p1, p2)
2215 node = node or self.hash(rawtext, p1, p2)
2216 rev = self.index.get_rev(node)
2216 rev = self.index.get_rev(node)
2217 if rev is not None:
2217 if rev is not None:
2218 return rev
2218 return rev
2219
2219
2220 if validatehash:
2220 if validatehash:
2221 self.checkhash(rawtext, node, p1=p1, p2=p2)
2221 self.checkhash(rawtext, node, p1=p1, p2=p2)
2222
2222
2223 return self.addrawrevision(
2223 return self.addrawrevision(
2224 rawtext,
2224 rawtext,
2225 transaction,
2225 transaction,
2226 link,
2226 link,
2227 p1,
2227 p1,
2228 p2,
2228 p2,
2229 node,
2229 node,
2230 flags,
2230 flags,
2231 cachedelta=cachedelta,
2231 cachedelta=cachedelta,
2232 deltacomputer=deltacomputer,
2232 deltacomputer=deltacomputer,
2233 sidedata=sidedata,
2233 sidedata=sidedata,
2234 )
2234 )
2235
2235
2236 def addrawrevision(
2236 def addrawrevision(
2237 self,
2237 self,
2238 rawtext,
2238 rawtext,
2239 transaction,
2239 transaction,
2240 link,
2240 link,
2241 p1,
2241 p1,
2242 p2,
2242 p2,
2243 node,
2243 node,
2244 flags,
2244 flags,
2245 cachedelta=None,
2245 cachedelta=None,
2246 deltacomputer=None,
2246 deltacomputer=None,
2247 sidedata=None,
2247 sidedata=None,
2248 ):
2248 ):
2249 """add a raw revision with known flags, node and parents
2249 """add a raw revision with known flags, node and parents
2250 useful when reusing a revision not stored in this revlog (ex: received
2250 useful when reusing a revision not stored in this revlog (ex: received
2251 over wire, or read from an external bundle).
2251 over wire, or read from an external bundle).
2252 """
2252 """
2253 with self._writing(transaction):
2253 with self._writing(transaction):
2254 return self._addrevision(
2254 return self._addrevision(
2255 node,
2255 node,
2256 rawtext,
2256 rawtext,
2257 transaction,
2257 transaction,
2258 link,
2258 link,
2259 p1,
2259 p1,
2260 p2,
2260 p2,
2261 flags,
2261 flags,
2262 cachedelta,
2262 cachedelta,
2263 deltacomputer=deltacomputer,
2263 deltacomputer=deltacomputer,
2264 sidedata=sidedata,
2264 sidedata=sidedata,
2265 )
2265 )
2266
2266
2267 def compress(self, data):
2267 def compress(self, data):
2268 """Generate a possibly-compressed representation of data."""
2268 """Generate a possibly-compressed representation of data."""
2269 if not data:
2269 if not data:
2270 return b'', data
2270 return b'', data
2271
2271
2272 compressed = self._compressor.compress(data)
2272 compressed = self._compressor.compress(data)
2273
2273
2274 if compressed:
2274 if compressed:
2275 # The revlog compressor added the header in the returned data.
2275 # The revlog compressor added the header in the returned data.
2276 return b'', compressed
2276 return b'', compressed
2277
2277
2278 if data[0:1] == b'\0':
2278 if data[0:1] == b'\0':
2279 return b'', data
2279 return b'', data
2280 return b'u', data
2280 return b'u', data
2281
2281
2282 def decompress(self, data):
2282 def decompress(self, data):
2283 """Decompress a revlog chunk.
2283 """Decompress a revlog chunk.
2284
2284
2285 The chunk is expected to begin with a header identifying the
2285 The chunk is expected to begin with a header identifying the
2286 format type so it can be routed to an appropriate decompressor.
2286 format type so it can be routed to an appropriate decompressor.
2287 """
2287 """
2288 if not data:
2288 if not data:
2289 return data
2289 return data
2290
2290
2291 # Revlogs are read much more frequently than they are written and many
2291 # Revlogs are read much more frequently than they are written and many
2292 # chunks only take microseconds to decompress, so performance is
2292 # chunks only take microseconds to decompress, so performance is
2293 # important here.
2293 # important here.
2294 #
2294 #
2295 # We can make a few assumptions about revlogs:
2295 # We can make a few assumptions about revlogs:
2296 #
2296 #
2297 # 1) the majority of chunks will be compressed (as opposed to inline
2297 # 1) the majority of chunks will be compressed (as opposed to inline
2298 # raw data).
2298 # raw data).
2299 # 2) decompressing *any* data will likely by at least 10x slower than
2299 # 2) decompressing *any* data will likely by at least 10x slower than
2300 # returning raw inline data.
2300 # returning raw inline data.
2301 # 3) we want to prioritize common and officially supported compression
2301 # 3) we want to prioritize common and officially supported compression
2302 # engines
2302 # engines
2303 #
2303 #
2304 # It follows that we want to optimize for "decompress compressed data
2304 # It follows that we want to optimize for "decompress compressed data
2305 # when encoded with common and officially supported compression engines"
2305 # when encoded with common and officially supported compression engines"
2306 # case over "raw data" and "data encoded by less common or non-official
2306 # case over "raw data" and "data encoded by less common or non-official
2307 # compression engines." That is why we have the inline lookup first
2307 # compression engines." That is why we have the inline lookup first
2308 # followed by the compengines lookup.
2308 # followed by the compengines lookup.
2309 #
2309 #
2310 # According to `hg perfrevlogchunks`, this is ~0.5% faster for zlib
2310 # According to `hg perfrevlogchunks`, this is ~0.5% faster for zlib
2311 # compressed chunks. And this matters for changelog and manifest reads.
2311 # compressed chunks. And this matters for changelog and manifest reads.
2312 t = data[0:1]
2312 t = data[0:1]
2313
2313
2314 if t == b'x':
2314 if t == b'x':
2315 try:
2315 try:
2316 return _zlibdecompress(data)
2316 return _zlibdecompress(data)
2317 except zlib.error as e:
2317 except zlib.error as e:
2318 raise error.RevlogError(
2318 raise error.RevlogError(
2319 _(b'revlog decompress error: %s')
2319 _(b'revlog decompress error: %s')
2320 % stringutil.forcebytestr(e)
2320 % stringutil.forcebytestr(e)
2321 )
2321 )
2322 # '\0' is more common than 'u' so it goes first.
2322 # '\0' is more common than 'u' so it goes first.
2323 elif t == b'\0':
2323 elif t == b'\0':
2324 return data
2324 return data
2325 elif t == b'u':
2325 elif t == b'u':
2326 return util.buffer(data, 1)
2326 return util.buffer(data, 1)
2327
2327
2328 compressor = self._get_decompressor(t)
2328 compressor = self._get_decompressor(t)
2329
2329
2330 return compressor.decompress(data)
2330 return compressor.decompress(data)
2331
2331
2332 def _addrevision(
2332 def _addrevision(
2333 self,
2333 self,
2334 node,
2334 node,
2335 rawtext,
2335 rawtext,
2336 transaction,
2336 transaction,
2337 link,
2337 link,
2338 p1,
2338 p1,
2339 p2,
2339 p2,
2340 flags,
2340 flags,
2341 cachedelta,
2341 cachedelta,
2342 alwayscache=False,
2342 alwayscache=False,
2343 deltacomputer=None,
2343 deltacomputer=None,
2344 sidedata=None,
2344 sidedata=None,
2345 ):
2345 ):
2346 """internal function to add revisions to the log
2346 """internal function to add revisions to the log
2347
2347
2348 see addrevision for argument descriptions.
2348 see addrevision for argument descriptions.
2349
2349
2350 note: "addrevision" takes non-raw text, "_addrevision" takes raw text.
2350 note: "addrevision" takes non-raw text, "_addrevision" takes raw text.
2351
2351
2352 if "deltacomputer" is not provided or None, a defaultdeltacomputer will
2352 if "deltacomputer" is not provided or None, a defaultdeltacomputer will
2353 be used.
2353 be used.
2354
2354
2355 invariants:
2355 invariants:
2356 - rawtext is optional (can be None); if not set, cachedelta must be set.
2356 - rawtext is optional (can be None); if not set, cachedelta must be set.
2357 if both are set, they must correspond to each other.
2357 if both are set, they must correspond to each other.
2358 """
2358 """
2359 if node == self.nullid:
2359 if node == self.nullid:
2360 raise error.RevlogError(
2360 raise error.RevlogError(
2361 _(b"%s: attempt to add null revision") % self.display_id
2361 _(b"%s: attempt to add null revision") % self.display_id
2362 )
2362 )
2363 if (
2363 if (
2364 node == self.nodeconstants.wdirid
2364 node == self.nodeconstants.wdirid
2365 or node in self.nodeconstants.wdirfilenodeids
2365 or node in self.nodeconstants.wdirfilenodeids
2366 ):
2366 ):
2367 raise error.RevlogError(
2367 raise error.RevlogError(
2368 _(b"%s: attempt to add wdir revision") % self.display_id
2368 _(b"%s: attempt to add wdir revision") % self.display_id
2369 )
2369 )
2370 if self._writinghandles is None:
2370 if self._writinghandles is None:
2371 msg = b'adding revision outside `revlog._writing` context'
2371 msg = b'adding revision outside `revlog._writing` context'
2372 raise error.ProgrammingError(msg)
2372 raise error.ProgrammingError(msg)
2373
2373
2374 if self._inline:
2374 if self._inline:
2375 fh = self._writinghandles[0]
2375 fh = self._writinghandles[0]
2376 else:
2376 else:
2377 fh = self._writinghandles[1]
2377 fh = self._writinghandles[1]
2378
2378
2379 btext = [rawtext]
2379 btext = [rawtext]
2380
2380
2381 curr = len(self)
2381 curr = len(self)
2382 prev = curr - 1
2382 prev = curr - 1
2383
2383
2384 offset = self._get_data_offset(prev)
2384 offset = self._get_data_offset(prev)
2385
2385
2386 if self._concurrencychecker:
2386 if self._concurrencychecker:
2387 ifh, dfh, sdfh = self._writinghandles
2387 ifh, dfh, sdfh = self._writinghandles
2388 # XXX no checking for the sidedata file
2388 # XXX no checking for the sidedata file
2389 if self._inline:
2389 if self._inline:
2390 # offset is "as if" it were in the .d file, so we need to add on
2390 # offset is "as if" it were in the .d file, so we need to add on
2391 # the size of the entry metadata.
2391 # the size of the entry metadata.
2392 self._concurrencychecker(
2392 self._concurrencychecker(
2393 ifh, self._indexfile, offset + curr * self.index.entry_size
2393 ifh, self._indexfile, offset + curr * self.index.entry_size
2394 )
2394 )
2395 else:
2395 else:
2396 # Entries in the .i are a consistent size.
2396 # Entries in the .i are a consistent size.
2397 self._concurrencychecker(
2397 self._concurrencychecker(
2398 ifh, self._indexfile, curr * self.index.entry_size
2398 ifh, self._indexfile, curr * self.index.entry_size
2399 )
2399 )
2400 self._concurrencychecker(dfh, self._datafile, offset)
2400 self._concurrencychecker(dfh, self._datafile, offset)
2401
2401
2402 p1r, p2r = self.rev(p1), self.rev(p2)
2402 p1r, p2r = self.rev(p1), self.rev(p2)
2403
2403
2404 # full versions are inserted when the needed deltas
2404 # full versions are inserted when the needed deltas
2405 # become comparable to the uncompressed text
2405 # become comparable to the uncompressed text
2406 if rawtext is None:
2406 if rawtext is None:
2407 # need rawtext size, before changed by flag processors, which is
2407 # need rawtext size, before changed by flag processors, which is
2408 # the non-raw size. use revlog explicitly to avoid filelog's extra
2408 # the non-raw size. use revlog explicitly to avoid filelog's extra
2409 # logic that might remove metadata size.
2409 # logic that might remove metadata size.
2410 textlen = mdiff.patchedsize(
2410 textlen = mdiff.patchedsize(
2411 revlog.size(self, cachedelta[0]), cachedelta[1]
2411 revlog.size(self, cachedelta[0]), cachedelta[1]
2412 )
2412 )
2413 else:
2413 else:
2414 textlen = len(rawtext)
2414 textlen = len(rawtext)
2415
2415
2416 if deltacomputer is None:
2416 if deltacomputer is None:
2417 deltacomputer = deltautil.deltacomputer(self)
2417 deltacomputer = deltautil.deltacomputer(self)
2418
2418
2419 revinfo = revlogutils.revisioninfo(
2419 revinfo = revlogutils.revisioninfo(
2420 node,
2420 node,
2421 p1,
2421 p1,
2422 p2,
2422 p2,
2423 btext,
2423 btext,
2424 textlen,
2424 textlen,
2425 cachedelta,
2425 cachedelta,
2426 flags,
2426 flags,
2427 )
2427 )
2428
2428
2429 deltainfo = deltacomputer.finddeltainfo(revinfo, fh)
2429 deltainfo = deltacomputer.finddeltainfo(revinfo, fh)
2430
2430
2431 compression_mode = COMP_MODE_INLINE
2431 compression_mode = COMP_MODE_INLINE
2432 if self._docket is not None:
2432 if self._docket is not None:
2433 default_comp = self._docket.default_compression_header
2433 default_comp = self._docket.default_compression_header
2434 r = deltautil.delta_compression(default_comp, deltainfo)
2434 r = deltautil.delta_compression(default_comp, deltainfo)
2435 compression_mode, deltainfo = r
2435 compression_mode, deltainfo = r
2436
2436
2437 sidedata_compression_mode = COMP_MODE_INLINE
2437 sidedata_compression_mode = COMP_MODE_INLINE
2438 if sidedata and self.hassidedata:
2438 if sidedata and self.hassidedata:
2439 sidedata_compression_mode = COMP_MODE_PLAIN
2439 sidedata_compression_mode = COMP_MODE_PLAIN
2440 serialized_sidedata = sidedatautil.serialize_sidedata(sidedata)
2440 serialized_sidedata = sidedatautil.serialize_sidedata(sidedata)
2441 sidedata_offset = self._docket.sidedata_end
2441 sidedata_offset = self._docket.sidedata_end
2442 h, comp_sidedata = self.compress(serialized_sidedata)
2442 h, comp_sidedata = self.compress(serialized_sidedata)
2443 if (
2443 if (
2444 h != b'u'
2444 h != b'u'
2445 and comp_sidedata[0:1] != b'\0'
2445 and comp_sidedata[0:1] != b'\0'
2446 and len(comp_sidedata) < len(serialized_sidedata)
2446 and len(comp_sidedata) < len(serialized_sidedata)
2447 ):
2447 ):
2448 assert not h
2448 assert not h
2449 if (
2449 if (
2450 comp_sidedata[0:1]
2450 comp_sidedata[0:1]
2451 == self._docket.default_compression_header
2451 == self._docket.default_compression_header
2452 ):
2452 ):
2453 sidedata_compression_mode = COMP_MODE_DEFAULT
2453 sidedata_compression_mode = COMP_MODE_DEFAULT
2454 serialized_sidedata = comp_sidedata
2454 serialized_sidedata = comp_sidedata
2455 else:
2455 else:
2456 sidedata_compression_mode = COMP_MODE_INLINE
2456 sidedata_compression_mode = COMP_MODE_INLINE
2457 serialized_sidedata = comp_sidedata
2457 serialized_sidedata = comp_sidedata
2458 else:
2458 else:
2459 serialized_sidedata = b""
2459 serialized_sidedata = b""
2460 # Don't store the offset if the sidedata is empty, that way
2460 # Don't store the offset if the sidedata is empty, that way
2461 # we can easily detect empty sidedata and they will be no different
2461 # we can easily detect empty sidedata and they will be no different
2462 # than ones we manually add.
2462 # than ones we manually add.
2463 sidedata_offset = 0
2463 sidedata_offset = 0
2464
2464
2465 rank = RANK_UNKNOWN
2465 rank = RANK_UNKNOWN
2466 if self._format_version == CHANGELOGV2:
2466 if self._format_version == CHANGELOGV2:
2467 rank = len(list(self.ancestors([p1r, p2r], inclusive=True))) + 1
2467 if (p1r, p2r) == (nullrev, nullrev):
2468 rank = 1
2469 elif p1r != nullrev and p2r == nullrev:
2470 rank = 1 + self.fast_rank(p1r)
2471 elif p1r == nullrev and p2r != nullrev:
2472 rank = 1 + self.fast_rank(p2r)
2473 else: # merge node
2474 pmin, pmax = sorted((p1r, p2r))
2475 rank = 1 + self.fast_rank(pmax)
2476 rank += sum(1 for _ in self.findmissingrevs([pmax], [pmin]))
2468
2477
2469 e = revlogutils.entry(
2478 e = revlogutils.entry(
2470 flags=flags,
2479 flags=flags,
2471 data_offset=offset,
2480 data_offset=offset,
2472 data_compressed_length=deltainfo.deltalen,
2481 data_compressed_length=deltainfo.deltalen,
2473 data_uncompressed_length=textlen,
2482 data_uncompressed_length=textlen,
2474 data_compression_mode=compression_mode,
2483 data_compression_mode=compression_mode,
2475 data_delta_base=deltainfo.base,
2484 data_delta_base=deltainfo.base,
2476 link_rev=link,
2485 link_rev=link,
2477 parent_rev_1=p1r,
2486 parent_rev_1=p1r,
2478 parent_rev_2=p2r,
2487 parent_rev_2=p2r,
2479 node_id=node,
2488 node_id=node,
2480 sidedata_offset=sidedata_offset,
2489 sidedata_offset=sidedata_offset,
2481 sidedata_compressed_length=len(serialized_sidedata),
2490 sidedata_compressed_length=len(serialized_sidedata),
2482 sidedata_compression_mode=sidedata_compression_mode,
2491 sidedata_compression_mode=sidedata_compression_mode,
2483 rank=rank,
2492 rank=rank,
2484 )
2493 )
2485
2494
2486 self.index.append(e)
2495 self.index.append(e)
2487 entry = self.index.entry_binary(curr)
2496 entry = self.index.entry_binary(curr)
2488 if curr == 0 and self._docket is None:
2497 if curr == 0 and self._docket is None:
2489 header = self._format_flags | self._format_version
2498 header = self._format_flags | self._format_version
2490 header = self.index.pack_header(header)
2499 header = self.index.pack_header(header)
2491 entry = header + entry
2500 entry = header + entry
2492 self._writeentry(
2501 self._writeentry(
2493 transaction,
2502 transaction,
2494 entry,
2503 entry,
2495 deltainfo.data,
2504 deltainfo.data,
2496 link,
2505 link,
2497 offset,
2506 offset,
2498 serialized_sidedata,
2507 serialized_sidedata,
2499 sidedata_offset,
2508 sidedata_offset,
2500 )
2509 )
2501
2510
2502 rawtext = btext[0]
2511 rawtext = btext[0]
2503
2512
2504 if alwayscache and rawtext is None:
2513 if alwayscache and rawtext is None:
2505 rawtext = deltacomputer.buildtext(revinfo, fh)
2514 rawtext = deltacomputer.buildtext(revinfo, fh)
2506
2515
2507 if type(rawtext) == bytes: # only accept immutable objects
2516 if type(rawtext) == bytes: # only accept immutable objects
2508 self._revisioncache = (node, curr, rawtext)
2517 self._revisioncache = (node, curr, rawtext)
2509 self._chainbasecache[curr] = deltainfo.chainbase
2518 self._chainbasecache[curr] = deltainfo.chainbase
2510 return curr
2519 return curr
2511
2520
2512 def _get_data_offset(self, prev):
2521 def _get_data_offset(self, prev):
2513 """Returns the current offset in the (in-transaction) data file.
2522 """Returns the current offset in the (in-transaction) data file.
2514 Versions < 2 of the revlog can get this 0(1), revlog v2 needs a docket
2523 Versions < 2 of the revlog can get this 0(1), revlog v2 needs a docket
2515 file to store that information: since sidedata can be rewritten to the
2524 file to store that information: since sidedata can be rewritten to the
2516 end of the data file within a transaction, you can have cases where, for
2525 end of the data file within a transaction, you can have cases where, for
2517 example, rev `n` does not have sidedata while rev `n - 1` does, leading
2526 example, rev `n` does not have sidedata while rev `n - 1` does, leading
2518 to `n - 1`'s sidedata being written after `n`'s data.
2527 to `n - 1`'s sidedata being written after `n`'s data.
2519
2528
2520 TODO cache this in a docket file before getting out of experimental."""
2529 TODO cache this in a docket file before getting out of experimental."""
2521 if self._docket is None:
2530 if self._docket is None:
2522 return self.end(prev)
2531 return self.end(prev)
2523 else:
2532 else:
2524 return self._docket.data_end
2533 return self._docket.data_end
2525
2534
2526 def _writeentry(
2535 def _writeentry(
2527 self, transaction, entry, data, link, offset, sidedata, sidedata_offset
2536 self, transaction, entry, data, link, offset, sidedata, sidedata_offset
2528 ):
2537 ):
2529 # Files opened in a+ mode have inconsistent behavior on various
2538 # Files opened in a+ mode have inconsistent behavior on various
2530 # platforms. Windows requires that a file positioning call be made
2539 # platforms. Windows requires that a file positioning call be made
2531 # when the file handle transitions between reads and writes. See
2540 # when the file handle transitions between reads and writes. See
2532 # 3686fa2b8eee and the mixedfilemodewrapper in windows.py. On other
2541 # 3686fa2b8eee and the mixedfilemodewrapper in windows.py. On other
2533 # platforms, Python or the platform itself can be buggy. Some versions
2542 # platforms, Python or the platform itself can be buggy. Some versions
2534 # of Solaris have been observed to not append at the end of the file
2543 # of Solaris have been observed to not append at the end of the file
2535 # if the file was seeked to before the end. See issue4943 for more.
2544 # if the file was seeked to before the end. See issue4943 for more.
2536 #
2545 #
2537 # We work around this issue by inserting a seek() before writing.
2546 # We work around this issue by inserting a seek() before writing.
2538 # Note: This is likely not necessary on Python 3. However, because
2547 # Note: This is likely not necessary on Python 3. However, because
2539 # the file handle is reused for reads and may be seeked there, we need
2548 # the file handle is reused for reads and may be seeked there, we need
2540 # to be careful before changing this.
2549 # to be careful before changing this.
2541 if self._writinghandles is None:
2550 if self._writinghandles is None:
2542 msg = b'adding revision outside `revlog._writing` context'
2551 msg = b'adding revision outside `revlog._writing` context'
2543 raise error.ProgrammingError(msg)
2552 raise error.ProgrammingError(msg)
2544 ifh, dfh, sdfh = self._writinghandles
2553 ifh, dfh, sdfh = self._writinghandles
2545 if self._docket is None:
2554 if self._docket is None:
2546 ifh.seek(0, os.SEEK_END)
2555 ifh.seek(0, os.SEEK_END)
2547 else:
2556 else:
2548 ifh.seek(self._docket.index_end, os.SEEK_SET)
2557 ifh.seek(self._docket.index_end, os.SEEK_SET)
2549 if dfh:
2558 if dfh:
2550 if self._docket is None:
2559 if self._docket is None:
2551 dfh.seek(0, os.SEEK_END)
2560 dfh.seek(0, os.SEEK_END)
2552 else:
2561 else:
2553 dfh.seek(self._docket.data_end, os.SEEK_SET)
2562 dfh.seek(self._docket.data_end, os.SEEK_SET)
2554 if sdfh:
2563 if sdfh:
2555 sdfh.seek(self._docket.sidedata_end, os.SEEK_SET)
2564 sdfh.seek(self._docket.sidedata_end, os.SEEK_SET)
2556
2565
2557 curr = len(self) - 1
2566 curr = len(self) - 1
2558 if not self._inline:
2567 if not self._inline:
2559 transaction.add(self._datafile, offset)
2568 transaction.add(self._datafile, offset)
2560 if self._sidedatafile:
2569 if self._sidedatafile:
2561 transaction.add(self._sidedatafile, sidedata_offset)
2570 transaction.add(self._sidedatafile, sidedata_offset)
2562 transaction.add(self._indexfile, curr * len(entry))
2571 transaction.add(self._indexfile, curr * len(entry))
2563 if data[0]:
2572 if data[0]:
2564 dfh.write(data[0])
2573 dfh.write(data[0])
2565 dfh.write(data[1])
2574 dfh.write(data[1])
2566 if sidedata:
2575 if sidedata:
2567 sdfh.write(sidedata)
2576 sdfh.write(sidedata)
2568 ifh.write(entry)
2577 ifh.write(entry)
2569 else:
2578 else:
2570 offset += curr * self.index.entry_size
2579 offset += curr * self.index.entry_size
2571 transaction.add(self._indexfile, offset)
2580 transaction.add(self._indexfile, offset)
2572 ifh.write(entry)
2581 ifh.write(entry)
2573 ifh.write(data[0])
2582 ifh.write(data[0])
2574 ifh.write(data[1])
2583 ifh.write(data[1])
2575 assert not sidedata
2584 assert not sidedata
2576 self._enforceinlinesize(transaction)
2585 self._enforceinlinesize(transaction)
2577 if self._docket is not None:
2586 if self._docket is not None:
2578 # revlog-v2 always has 3 writing handles, help Pytype
2587 # revlog-v2 always has 3 writing handles, help Pytype
2579 wh1 = self._writinghandles[0]
2588 wh1 = self._writinghandles[0]
2580 wh2 = self._writinghandles[1]
2589 wh2 = self._writinghandles[1]
2581 wh3 = self._writinghandles[2]
2590 wh3 = self._writinghandles[2]
2582 assert wh1 is not None
2591 assert wh1 is not None
2583 assert wh2 is not None
2592 assert wh2 is not None
2584 assert wh3 is not None
2593 assert wh3 is not None
2585 self._docket.index_end = wh1.tell()
2594 self._docket.index_end = wh1.tell()
2586 self._docket.data_end = wh2.tell()
2595 self._docket.data_end = wh2.tell()
2587 self._docket.sidedata_end = wh3.tell()
2596 self._docket.sidedata_end = wh3.tell()
2588
2597
2589 nodemaputil.setup_persistent_nodemap(transaction, self)
2598 nodemaputil.setup_persistent_nodemap(transaction, self)
2590
2599
2591 def addgroup(
2600 def addgroup(
2592 self,
2601 self,
2593 deltas,
2602 deltas,
2594 linkmapper,
2603 linkmapper,
2595 transaction,
2604 transaction,
2596 alwayscache=False,
2605 alwayscache=False,
2597 addrevisioncb=None,
2606 addrevisioncb=None,
2598 duplicaterevisioncb=None,
2607 duplicaterevisioncb=None,
2599 ):
2608 ):
2600 """
2609 """
2601 add a delta group
2610 add a delta group
2602
2611
2603 given a set of deltas, add them to the revision log. the
2612 given a set of deltas, add them to the revision log. the
2604 first delta is against its parent, which should be in our
2613 first delta is against its parent, which should be in our
2605 log, the rest are against the previous delta.
2614 log, the rest are against the previous delta.
2606
2615
2607 If ``addrevisioncb`` is defined, it will be called with arguments of
2616 If ``addrevisioncb`` is defined, it will be called with arguments of
2608 this revlog and the node that was added.
2617 this revlog and the node that was added.
2609 """
2618 """
2610
2619
2611 if self._adding_group:
2620 if self._adding_group:
2612 raise error.ProgrammingError(b'cannot nest addgroup() calls')
2621 raise error.ProgrammingError(b'cannot nest addgroup() calls')
2613
2622
2614 self._adding_group = True
2623 self._adding_group = True
2615 empty = True
2624 empty = True
2616 try:
2625 try:
2617 with self._writing(transaction):
2626 with self._writing(transaction):
2618 deltacomputer = deltautil.deltacomputer(self)
2627 deltacomputer = deltautil.deltacomputer(self)
2619 # loop through our set of deltas
2628 # loop through our set of deltas
2620 for data in deltas:
2629 for data in deltas:
2621 (
2630 (
2622 node,
2631 node,
2623 p1,
2632 p1,
2624 p2,
2633 p2,
2625 linknode,
2634 linknode,
2626 deltabase,
2635 deltabase,
2627 delta,
2636 delta,
2628 flags,
2637 flags,
2629 sidedata,
2638 sidedata,
2630 ) = data
2639 ) = data
2631 link = linkmapper(linknode)
2640 link = linkmapper(linknode)
2632 flags = flags or REVIDX_DEFAULT_FLAGS
2641 flags = flags or REVIDX_DEFAULT_FLAGS
2633
2642
2634 rev = self.index.get_rev(node)
2643 rev = self.index.get_rev(node)
2635 if rev is not None:
2644 if rev is not None:
2636 # this can happen if two branches make the same change
2645 # this can happen if two branches make the same change
2637 self._nodeduplicatecallback(transaction, rev)
2646 self._nodeduplicatecallback(transaction, rev)
2638 if duplicaterevisioncb:
2647 if duplicaterevisioncb:
2639 duplicaterevisioncb(self, rev)
2648 duplicaterevisioncb(self, rev)
2640 empty = False
2649 empty = False
2641 continue
2650 continue
2642
2651
2643 for p in (p1, p2):
2652 for p in (p1, p2):
2644 if not self.index.has_node(p):
2653 if not self.index.has_node(p):
2645 raise error.LookupError(
2654 raise error.LookupError(
2646 p, self.radix, _(b'unknown parent')
2655 p, self.radix, _(b'unknown parent')
2647 )
2656 )
2648
2657
2649 if not self.index.has_node(deltabase):
2658 if not self.index.has_node(deltabase):
2650 raise error.LookupError(
2659 raise error.LookupError(
2651 deltabase, self.display_id, _(b'unknown delta base')
2660 deltabase, self.display_id, _(b'unknown delta base')
2652 )
2661 )
2653
2662
2654 baserev = self.rev(deltabase)
2663 baserev = self.rev(deltabase)
2655
2664
2656 if baserev != nullrev and self.iscensored(baserev):
2665 if baserev != nullrev and self.iscensored(baserev):
2657 # if base is censored, delta must be full replacement in a
2666 # if base is censored, delta must be full replacement in a
2658 # single patch operation
2667 # single patch operation
2659 hlen = struct.calcsize(b">lll")
2668 hlen = struct.calcsize(b">lll")
2660 oldlen = self.rawsize(baserev)
2669 oldlen = self.rawsize(baserev)
2661 newlen = len(delta) - hlen
2670 newlen = len(delta) - hlen
2662 if delta[:hlen] != mdiff.replacediffheader(
2671 if delta[:hlen] != mdiff.replacediffheader(
2663 oldlen, newlen
2672 oldlen, newlen
2664 ):
2673 ):
2665 raise error.CensoredBaseError(
2674 raise error.CensoredBaseError(
2666 self.display_id, self.node(baserev)
2675 self.display_id, self.node(baserev)
2667 )
2676 )
2668
2677
2669 if not flags and self._peek_iscensored(baserev, delta):
2678 if not flags and self._peek_iscensored(baserev, delta):
2670 flags |= REVIDX_ISCENSORED
2679 flags |= REVIDX_ISCENSORED
2671
2680
2672 # We assume consumers of addrevisioncb will want to retrieve
2681 # We assume consumers of addrevisioncb will want to retrieve
2673 # the added revision, which will require a call to
2682 # the added revision, which will require a call to
2674 # revision(). revision() will fast path if there is a cache
2683 # revision(). revision() will fast path if there is a cache
2675 # hit. So, we tell _addrevision() to always cache in this case.
2684 # hit. So, we tell _addrevision() to always cache in this case.
2676 # We're only using addgroup() in the context of changegroup
2685 # We're only using addgroup() in the context of changegroup
2677 # generation so the revision data can always be handled as raw
2686 # generation so the revision data can always be handled as raw
2678 # by the flagprocessor.
2687 # by the flagprocessor.
2679 rev = self._addrevision(
2688 rev = self._addrevision(
2680 node,
2689 node,
2681 None,
2690 None,
2682 transaction,
2691 transaction,
2683 link,
2692 link,
2684 p1,
2693 p1,
2685 p2,
2694 p2,
2686 flags,
2695 flags,
2687 (baserev, delta),
2696 (baserev, delta),
2688 alwayscache=alwayscache,
2697 alwayscache=alwayscache,
2689 deltacomputer=deltacomputer,
2698 deltacomputer=deltacomputer,
2690 sidedata=sidedata,
2699 sidedata=sidedata,
2691 )
2700 )
2692
2701
2693 if addrevisioncb:
2702 if addrevisioncb:
2694 addrevisioncb(self, rev)
2703 addrevisioncb(self, rev)
2695 empty = False
2704 empty = False
2696 finally:
2705 finally:
2697 self._adding_group = False
2706 self._adding_group = False
2698 return not empty
2707 return not empty
2699
2708
2700 def iscensored(self, rev):
2709 def iscensored(self, rev):
2701 """Check if a file revision is censored."""
2710 """Check if a file revision is censored."""
2702 if not self._censorable:
2711 if not self._censorable:
2703 return False
2712 return False
2704
2713
2705 return self.flags(rev) & REVIDX_ISCENSORED
2714 return self.flags(rev) & REVIDX_ISCENSORED
2706
2715
2707 def _peek_iscensored(self, baserev, delta):
2716 def _peek_iscensored(self, baserev, delta):
2708 """Quickly check if a delta produces a censored revision."""
2717 """Quickly check if a delta produces a censored revision."""
2709 if not self._censorable:
2718 if not self._censorable:
2710 return False
2719 return False
2711
2720
2712 return storageutil.deltaiscensored(delta, baserev, self.rawsize)
2721 return storageutil.deltaiscensored(delta, baserev, self.rawsize)
2713
2722
2714 def getstrippoint(self, minlink):
2723 def getstrippoint(self, minlink):
2715 """find the minimum rev that must be stripped to strip the linkrev
2724 """find the minimum rev that must be stripped to strip the linkrev
2716
2725
2717 Returns a tuple containing the minimum rev and a set of all revs that
2726 Returns a tuple containing the minimum rev and a set of all revs that
2718 have linkrevs that will be broken by this strip.
2727 have linkrevs that will be broken by this strip.
2719 """
2728 """
2720 return storageutil.resolvestripinfo(
2729 return storageutil.resolvestripinfo(
2721 minlink,
2730 minlink,
2722 len(self) - 1,
2731 len(self) - 1,
2723 self.headrevs(),
2732 self.headrevs(),
2724 self.linkrev,
2733 self.linkrev,
2725 self.parentrevs,
2734 self.parentrevs,
2726 )
2735 )
2727
2736
2728 def strip(self, minlink, transaction):
2737 def strip(self, minlink, transaction):
2729 """truncate the revlog on the first revision with a linkrev >= minlink
2738 """truncate the revlog on the first revision with a linkrev >= minlink
2730
2739
2731 This function is called when we're stripping revision minlink and
2740 This function is called when we're stripping revision minlink and
2732 its descendants from the repository.
2741 its descendants from the repository.
2733
2742
2734 We have to remove all revisions with linkrev >= minlink, because
2743 We have to remove all revisions with linkrev >= minlink, because
2735 the equivalent changelog revisions will be renumbered after the
2744 the equivalent changelog revisions will be renumbered after the
2736 strip.
2745 strip.
2737
2746
2738 So we truncate the revlog on the first of these revisions, and
2747 So we truncate the revlog on the first of these revisions, and
2739 trust that the caller has saved the revisions that shouldn't be
2748 trust that the caller has saved the revisions that shouldn't be
2740 removed and that it'll re-add them after this truncation.
2749 removed and that it'll re-add them after this truncation.
2741 """
2750 """
2742 if len(self) == 0:
2751 if len(self) == 0:
2743 return
2752 return
2744
2753
2745 rev, _ = self.getstrippoint(minlink)
2754 rev, _ = self.getstrippoint(minlink)
2746 if rev == len(self):
2755 if rev == len(self):
2747 return
2756 return
2748
2757
2749 # first truncate the files on disk
2758 # first truncate the files on disk
2750 data_end = self.start(rev)
2759 data_end = self.start(rev)
2751 if not self._inline:
2760 if not self._inline:
2752 transaction.add(self._datafile, data_end)
2761 transaction.add(self._datafile, data_end)
2753 end = rev * self.index.entry_size
2762 end = rev * self.index.entry_size
2754 else:
2763 else:
2755 end = data_end + (rev * self.index.entry_size)
2764 end = data_end + (rev * self.index.entry_size)
2756
2765
2757 if self._sidedatafile:
2766 if self._sidedatafile:
2758 sidedata_end = self.sidedata_cut_off(rev)
2767 sidedata_end = self.sidedata_cut_off(rev)
2759 transaction.add(self._sidedatafile, sidedata_end)
2768 transaction.add(self._sidedatafile, sidedata_end)
2760
2769
2761 transaction.add(self._indexfile, end)
2770 transaction.add(self._indexfile, end)
2762 if self._docket is not None:
2771 if self._docket is not None:
2763 # XXX we could, leverage the docket while stripping. However it is
2772 # XXX we could, leverage the docket while stripping. However it is
2764 # not powerfull enough at the time of this comment
2773 # not powerfull enough at the time of this comment
2765 self._docket.index_end = end
2774 self._docket.index_end = end
2766 self._docket.data_end = data_end
2775 self._docket.data_end = data_end
2767 self._docket.sidedata_end = sidedata_end
2776 self._docket.sidedata_end = sidedata_end
2768 self._docket.write(transaction, stripping=True)
2777 self._docket.write(transaction, stripping=True)
2769
2778
2770 # then reset internal state in memory to forget those revisions
2779 # then reset internal state in memory to forget those revisions
2771 self._revisioncache = None
2780 self._revisioncache = None
2772 self._chaininfocache = util.lrucachedict(500)
2781 self._chaininfocache = util.lrucachedict(500)
2773 self._segmentfile.clear_cache()
2782 self._segmentfile.clear_cache()
2774 self._segmentfile_sidedata.clear_cache()
2783 self._segmentfile_sidedata.clear_cache()
2775
2784
2776 del self.index[rev:-1]
2785 del self.index[rev:-1]
2777
2786
2778 def checksize(self):
2787 def checksize(self):
2779 """Check size of index and data files
2788 """Check size of index and data files
2780
2789
2781 return a (dd, di) tuple.
2790 return a (dd, di) tuple.
2782 - dd: extra bytes for the "data" file
2791 - dd: extra bytes for the "data" file
2783 - di: extra bytes for the "index" file
2792 - di: extra bytes for the "index" file
2784
2793
2785 A healthy revlog will return (0, 0).
2794 A healthy revlog will return (0, 0).
2786 """
2795 """
2787 expected = 0
2796 expected = 0
2788 if len(self):
2797 if len(self):
2789 expected = max(0, self.end(len(self) - 1))
2798 expected = max(0, self.end(len(self) - 1))
2790
2799
2791 try:
2800 try:
2792 with self._datafp() as f:
2801 with self._datafp() as f:
2793 f.seek(0, io.SEEK_END)
2802 f.seek(0, io.SEEK_END)
2794 actual = f.tell()
2803 actual = f.tell()
2795 dd = actual - expected
2804 dd = actual - expected
2796 except IOError as inst:
2805 except IOError as inst:
2797 if inst.errno != errno.ENOENT:
2806 if inst.errno != errno.ENOENT:
2798 raise
2807 raise
2799 dd = 0
2808 dd = 0
2800
2809
2801 try:
2810 try:
2802 f = self.opener(self._indexfile)
2811 f = self.opener(self._indexfile)
2803 f.seek(0, io.SEEK_END)
2812 f.seek(0, io.SEEK_END)
2804 actual = f.tell()
2813 actual = f.tell()
2805 f.close()
2814 f.close()
2806 s = self.index.entry_size
2815 s = self.index.entry_size
2807 i = max(0, actual // s)
2816 i = max(0, actual // s)
2808 di = actual - (i * s)
2817 di = actual - (i * s)
2809 if self._inline:
2818 if self._inline:
2810 databytes = 0
2819 databytes = 0
2811 for r in self:
2820 for r in self:
2812 databytes += max(0, self.length(r))
2821 databytes += max(0, self.length(r))
2813 dd = 0
2822 dd = 0
2814 di = actual - len(self) * s - databytes
2823 di = actual - len(self) * s - databytes
2815 except IOError as inst:
2824 except IOError as inst:
2816 if inst.errno != errno.ENOENT:
2825 if inst.errno != errno.ENOENT:
2817 raise
2826 raise
2818 di = 0
2827 di = 0
2819
2828
2820 return (dd, di)
2829 return (dd, di)
2821
2830
2822 def files(self):
2831 def files(self):
2823 res = [self._indexfile]
2832 res = [self._indexfile]
2824 if self._docket_file is None:
2833 if self._docket_file is None:
2825 if not self._inline:
2834 if not self._inline:
2826 res.append(self._datafile)
2835 res.append(self._datafile)
2827 else:
2836 else:
2828 res.append(self._docket_file)
2837 res.append(self._docket_file)
2829 res.extend(self._docket.old_index_filepaths(include_empty=False))
2838 res.extend(self._docket.old_index_filepaths(include_empty=False))
2830 if self._docket.data_end:
2839 if self._docket.data_end:
2831 res.append(self._datafile)
2840 res.append(self._datafile)
2832 res.extend(self._docket.old_data_filepaths(include_empty=False))
2841 res.extend(self._docket.old_data_filepaths(include_empty=False))
2833 if self._docket.sidedata_end:
2842 if self._docket.sidedata_end:
2834 res.append(self._sidedatafile)
2843 res.append(self._sidedatafile)
2835 res.extend(self._docket.old_sidedata_filepaths(include_empty=False))
2844 res.extend(self._docket.old_sidedata_filepaths(include_empty=False))
2836 return res
2845 return res
2837
2846
2838 def emitrevisions(
2847 def emitrevisions(
2839 self,
2848 self,
2840 nodes,
2849 nodes,
2841 nodesorder=None,
2850 nodesorder=None,
2842 revisiondata=False,
2851 revisiondata=False,
2843 assumehaveparentrevisions=False,
2852 assumehaveparentrevisions=False,
2844 deltamode=repository.CG_DELTAMODE_STD,
2853 deltamode=repository.CG_DELTAMODE_STD,
2845 sidedata_helpers=None,
2854 sidedata_helpers=None,
2846 ):
2855 ):
2847 if nodesorder not in (b'nodes', b'storage', b'linear', None):
2856 if nodesorder not in (b'nodes', b'storage', b'linear', None):
2848 raise error.ProgrammingError(
2857 raise error.ProgrammingError(
2849 b'unhandled value for nodesorder: %s' % nodesorder
2858 b'unhandled value for nodesorder: %s' % nodesorder
2850 )
2859 )
2851
2860
2852 if nodesorder is None and not self._generaldelta:
2861 if nodesorder is None and not self._generaldelta:
2853 nodesorder = b'storage'
2862 nodesorder = b'storage'
2854
2863
2855 if (
2864 if (
2856 not self._storedeltachains
2865 not self._storedeltachains
2857 and deltamode != repository.CG_DELTAMODE_PREV
2866 and deltamode != repository.CG_DELTAMODE_PREV
2858 ):
2867 ):
2859 deltamode = repository.CG_DELTAMODE_FULL
2868 deltamode = repository.CG_DELTAMODE_FULL
2860
2869
2861 return storageutil.emitrevisions(
2870 return storageutil.emitrevisions(
2862 self,
2871 self,
2863 nodes,
2872 nodes,
2864 nodesorder,
2873 nodesorder,
2865 revlogrevisiondelta,
2874 revlogrevisiondelta,
2866 deltaparentfn=self.deltaparent,
2875 deltaparentfn=self.deltaparent,
2867 candeltafn=self.candelta,
2876 candeltafn=self.candelta,
2868 rawsizefn=self.rawsize,
2877 rawsizefn=self.rawsize,
2869 revdifffn=self.revdiff,
2878 revdifffn=self.revdiff,
2870 flagsfn=self.flags,
2879 flagsfn=self.flags,
2871 deltamode=deltamode,
2880 deltamode=deltamode,
2872 revisiondata=revisiondata,
2881 revisiondata=revisiondata,
2873 assumehaveparentrevisions=assumehaveparentrevisions,
2882 assumehaveparentrevisions=assumehaveparentrevisions,
2874 sidedata_helpers=sidedata_helpers,
2883 sidedata_helpers=sidedata_helpers,
2875 )
2884 )
2876
2885
2877 DELTAREUSEALWAYS = b'always'
2886 DELTAREUSEALWAYS = b'always'
2878 DELTAREUSESAMEREVS = b'samerevs'
2887 DELTAREUSESAMEREVS = b'samerevs'
2879 DELTAREUSENEVER = b'never'
2888 DELTAREUSENEVER = b'never'
2880
2889
2881 DELTAREUSEFULLADD = b'fulladd'
2890 DELTAREUSEFULLADD = b'fulladd'
2882
2891
2883 DELTAREUSEALL = {b'always', b'samerevs', b'never', b'fulladd'}
2892 DELTAREUSEALL = {b'always', b'samerevs', b'never', b'fulladd'}
2884
2893
2885 def clone(
2894 def clone(
2886 self,
2895 self,
2887 tr,
2896 tr,
2888 destrevlog,
2897 destrevlog,
2889 addrevisioncb=None,
2898 addrevisioncb=None,
2890 deltareuse=DELTAREUSESAMEREVS,
2899 deltareuse=DELTAREUSESAMEREVS,
2891 forcedeltabothparents=None,
2900 forcedeltabothparents=None,
2892 sidedata_helpers=None,
2901 sidedata_helpers=None,
2893 ):
2902 ):
2894 """Copy this revlog to another, possibly with format changes.
2903 """Copy this revlog to another, possibly with format changes.
2895
2904
2896 The destination revlog will contain the same revisions and nodes.
2905 The destination revlog will contain the same revisions and nodes.
2897 However, it may not be bit-for-bit identical due to e.g. delta encoding
2906 However, it may not be bit-for-bit identical due to e.g. delta encoding
2898 differences.
2907 differences.
2899
2908
2900 The ``deltareuse`` argument control how deltas from the existing revlog
2909 The ``deltareuse`` argument control how deltas from the existing revlog
2901 are preserved in the destination revlog. The argument can have the
2910 are preserved in the destination revlog. The argument can have the
2902 following values:
2911 following values:
2903
2912
2904 DELTAREUSEALWAYS
2913 DELTAREUSEALWAYS
2905 Deltas will always be reused (if possible), even if the destination
2914 Deltas will always be reused (if possible), even if the destination
2906 revlog would not select the same revisions for the delta. This is the
2915 revlog would not select the same revisions for the delta. This is the
2907 fastest mode of operation.
2916 fastest mode of operation.
2908 DELTAREUSESAMEREVS
2917 DELTAREUSESAMEREVS
2909 Deltas will be reused if the destination revlog would pick the same
2918 Deltas will be reused if the destination revlog would pick the same
2910 revisions for the delta. This mode strikes a balance between speed
2919 revisions for the delta. This mode strikes a balance between speed
2911 and optimization.
2920 and optimization.
2912 DELTAREUSENEVER
2921 DELTAREUSENEVER
2913 Deltas will never be reused. This is the slowest mode of execution.
2922 Deltas will never be reused. This is the slowest mode of execution.
2914 This mode can be used to recompute deltas (e.g. if the diff/delta
2923 This mode can be used to recompute deltas (e.g. if the diff/delta
2915 algorithm changes).
2924 algorithm changes).
2916 DELTAREUSEFULLADD
2925 DELTAREUSEFULLADD
2917 Revision will be re-added as if their were new content. This is
2926 Revision will be re-added as if their were new content. This is
2918 slower than DELTAREUSEALWAYS but allow more mechanism to kicks in.
2927 slower than DELTAREUSEALWAYS but allow more mechanism to kicks in.
2919 eg: large file detection and handling.
2928 eg: large file detection and handling.
2920
2929
2921 Delta computation can be slow, so the choice of delta reuse policy can
2930 Delta computation can be slow, so the choice of delta reuse policy can
2922 significantly affect run time.
2931 significantly affect run time.
2923
2932
2924 The default policy (``DELTAREUSESAMEREVS``) strikes a balance between
2933 The default policy (``DELTAREUSESAMEREVS``) strikes a balance between
2925 two extremes. Deltas will be reused if they are appropriate. But if the
2934 two extremes. Deltas will be reused if they are appropriate. But if the
2926 delta could choose a better revision, it will do so. This means if you
2935 delta could choose a better revision, it will do so. This means if you
2927 are converting a non-generaldelta revlog to a generaldelta revlog,
2936 are converting a non-generaldelta revlog to a generaldelta revlog,
2928 deltas will be recomputed if the delta's parent isn't a parent of the
2937 deltas will be recomputed if the delta's parent isn't a parent of the
2929 revision.
2938 revision.
2930
2939
2931 In addition to the delta policy, the ``forcedeltabothparents``
2940 In addition to the delta policy, the ``forcedeltabothparents``
2932 argument controls whether to force compute deltas against both parents
2941 argument controls whether to force compute deltas against both parents
2933 for merges. By default, the current default is used.
2942 for merges. By default, the current default is used.
2934
2943
2935 See `revlogutil.sidedata.get_sidedata_helpers` for the doc on
2944 See `revlogutil.sidedata.get_sidedata_helpers` for the doc on
2936 `sidedata_helpers`.
2945 `sidedata_helpers`.
2937 """
2946 """
2938 if deltareuse not in self.DELTAREUSEALL:
2947 if deltareuse not in self.DELTAREUSEALL:
2939 raise ValueError(
2948 raise ValueError(
2940 _(b'value for deltareuse invalid: %s') % deltareuse
2949 _(b'value for deltareuse invalid: %s') % deltareuse
2941 )
2950 )
2942
2951
2943 if len(destrevlog):
2952 if len(destrevlog):
2944 raise ValueError(_(b'destination revlog is not empty'))
2953 raise ValueError(_(b'destination revlog is not empty'))
2945
2954
2946 if getattr(self, 'filteredrevs', None):
2955 if getattr(self, 'filteredrevs', None):
2947 raise ValueError(_(b'source revlog has filtered revisions'))
2956 raise ValueError(_(b'source revlog has filtered revisions'))
2948 if getattr(destrevlog, 'filteredrevs', None):
2957 if getattr(destrevlog, 'filteredrevs', None):
2949 raise ValueError(_(b'destination revlog has filtered revisions'))
2958 raise ValueError(_(b'destination revlog has filtered revisions'))
2950
2959
2951 # lazydelta and lazydeltabase controls whether to reuse a cached delta,
2960 # lazydelta and lazydeltabase controls whether to reuse a cached delta,
2952 # if possible.
2961 # if possible.
2953 oldlazydelta = destrevlog._lazydelta
2962 oldlazydelta = destrevlog._lazydelta
2954 oldlazydeltabase = destrevlog._lazydeltabase
2963 oldlazydeltabase = destrevlog._lazydeltabase
2955 oldamd = destrevlog._deltabothparents
2964 oldamd = destrevlog._deltabothparents
2956
2965
2957 try:
2966 try:
2958 if deltareuse == self.DELTAREUSEALWAYS:
2967 if deltareuse == self.DELTAREUSEALWAYS:
2959 destrevlog._lazydeltabase = True
2968 destrevlog._lazydeltabase = True
2960 destrevlog._lazydelta = True
2969 destrevlog._lazydelta = True
2961 elif deltareuse == self.DELTAREUSESAMEREVS:
2970 elif deltareuse == self.DELTAREUSESAMEREVS:
2962 destrevlog._lazydeltabase = False
2971 destrevlog._lazydeltabase = False
2963 destrevlog._lazydelta = True
2972 destrevlog._lazydelta = True
2964 elif deltareuse == self.DELTAREUSENEVER:
2973 elif deltareuse == self.DELTAREUSENEVER:
2965 destrevlog._lazydeltabase = False
2974 destrevlog._lazydeltabase = False
2966 destrevlog._lazydelta = False
2975 destrevlog._lazydelta = False
2967
2976
2968 destrevlog._deltabothparents = forcedeltabothparents or oldamd
2977 destrevlog._deltabothparents = forcedeltabothparents or oldamd
2969
2978
2970 self._clone(
2979 self._clone(
2971 tr,
2980 tr,
2972 destrevlog,
2981 destrevlog,
2973 addrevisioncb,
2982 addrevisioncb,
2974 deltareuse,
2983 deltareuse,
2975 forcedeltabothparents,
2984 forcedeltabothparents,
2976 sidedata_helpers,
2985 sidedata_helpers,
2977 )
2986 )
2978
2987
2979 finally:
2988 finally:
2980 destrevlog._lazydelta = oldlazydelta
2989 destrevlog._lazydelta = oldlazydelta
2981 destrevlog._lazydeltabase = oldlazydeltabase
2990 destrevlog._lazydeltabase = oldlazydeltabase
2982 destrevlog._deltabothparents = oldamd
2991 destrevlog._deltabothparents = oldamd
2983
2992
2984 def _clone(
2993 def _clone(
2985 self,
2994 self,
2986 tr,
2995 tr,
2987 destrevlog,
2996 destrevlog,
2988 addrevisioncb,
2997 addrevisioncb,
2989 deltareuse,
2998 deltareuse,
2990 forcedeltabothparents,
2999 forcedeltabothparents,
2991 sidedata_helpers,
3000 sidedata_helpers,
2992 ):
3001 ):
2993 """perform the core duty of `revlog.clone` after parameter processing"""
3002 """perform the core duty of `revlog.clone` after parameter processing"""
2994 deltacomputer = deltautil.deltacomputer(destrevlog)
3003 deltacomputer = deltautil.deltacomputer(destrevlog)
2995 index = self.index
3004 index = self.index
2996 for rev in self:
3005 for rev in self:
2997 entry = index[rev]
3006 entry = index[rev]
2998
3007
2999 # Some classes override linkrev to take filtered revs into
3008 # Some classes override linkrev to take filtered revs into
3000 # account. Use raw entry from index.
3009 # account. Use raw entry from index.
3001 flags = entry[0] & 0xFFFF
3010 flags = entry[0] & 0xFFFF
3002 linkrev = entry[4]
3011 linkrev = entry[4]
3003 p1 = index[entry[5]][7]
3012 p1 = index[entry[5]][7]
3004 p2 = index[entry[6]][7]
3013 p2 = index[entry[6]][7]
3005 node = entry[7]
3014 node = entry[7]
3006
3015
3007 # (Possibly) reuse the delta from the revlog if allowed and
3016 # (Possibly) reuse the delta from the revlog if allowed and
3008 # the revlog chunk is a delta.
3017 # the revlog chunk is a delta.
3009 cachedelta = None
3018 cachedelta = None
3010 rawtext = None
3019 rawtext = None
3011 if deltareuse == self.DELTAREUSEFULLADD:
3020 if deltareuse == self.DELTAREUSEFULLADD:
3012 text = self._revisiondata(rev)
3021 text = self._revisiondata(rev)
3013 sidedata = self.sidedata(rev)
3022 sidedata = self.sidedata(rev)
3014
3023
3015 if sidedata_helpers is not None:
3024 if sidedata_helpers is not None:
3016 (sidedata, new_flags) = sidedatautil.run_sidedata_helpers(
3025 (sidedata, new_flags) = sidedatautil.run_sidedata_helpers(
3017 self, sidedata_helpers, sidedata, rev
3026 self, sidedata_helpers, sidedata, rev
3018 )
3027 )
3019 flags = flags | new_flags[0] & ~new_flags[1]
3028 flags = flags | new_flags[0] & ~new_flags[1]
3020
3029
3021 destrevlog.addrevision(
3030 destrevlog.addrevision(
3022 text,
3031 text,
3023 tr,
3032 tr,
3024 linkrev,
3033 linkrev,
3025 p1,
3034 p1,
3026 p2,
3035 p2,
3027 cachedelta=cachedelta,
3036 cachedelta=cachedelta,
3028 node=node,
3037 node=node,
3029 flags=flags,
3038 flags=flags,
3030 deltacomputer=deltacomputer,
3039 deltacomputer=deltacomputer,
3031 sidedata=sidedata,
3040 sidedata=sidedata,
3032 )
3041 )
3033 else:
3042 else:
3034 if destrevlog._lazydelta:
3043 if destrevlog._lazydelta:
3035 dp = self.deltaparent(rev)
3044 dp = self.deltaparent(rev)
3036 if dp != nullrev:
3045 if dp != nullrev:
3037 cachedelta = (dp, bytes(self._chunk(rev)))
3046 cachedelta = (dp, bytes(self._chunk(rev)))
3038
3047
3039 sidedata = None
3048 sidedata = None
3040 if not cachedelta:
3049 if not cachedelta:
3041 rawtext = self._revisiondata(rev)
3050 rawtext = self._revisiondata(rev)
3042 sidedata = self.sidedata(rev)
3051 sidedata = self.sidedata(rev)
3043 if sidedata is None:
3052 if sidedata is None:
3044 sidedata = self.sidedata(rev)
3053 sidedata = self.sidedata(rev)
3045
3054
3046 if sidedata_helpers is not None:
3055 if sidedata_helpers is not None:
3047 (sidedata, new_flags) = sidedatautil.run_sidedata_helpers(
3056 (sidedata, new_flags) = sidedatautil.run_sidedata_helpers(
3048 self, sidedata_helpers, sidedata, rev
3057 self, sidedata_helpers, sidedata, rev
3049 )
3058 )
3050 flags = flags | new_flags[0] & ~new_flags[1]
3059 flags = flags | new_flags[0] & ~new_flags[1]
3051
3060
3052 with destrevlog._writing(tr):
3061 with destrevlog._writing(tr):
3053 destrevlog._addrevision(
3062 destrevlog._addrevision(
3054 node,
3063 node,
3055 rawtext,
3064 rawtext,
3056 tr,
3065 tr,
3057 linkrev,
3066 linkrev,
3058 p1,
3067 p1,
3059 p2,
3068 p2,
3060 flags,
3069 flags,
3061 cachedelta,
3070 cachedelta,
3062 deltacomputer=deltacomputer,
3071 deltacomputer=deltacomputer,
3063 sidedata=sidedata,
3072 sidedata=sidedata,
3064 )
3073 )
3065
3074
3066 if addrevisioncb:
3075 if addrevisioncb:
3067 addrevisioncb(self, rev, node)
3076 addrevisioncb(self, rev, node)
3068
3077
3069 def censorrevision(self, tr, censornode, tombstone=b''):
3078 def censorrevision(self, tr, censornode, tombstone=b''):
3070 if self._format_version == REVLOGV0:
3079 if self._format_version == REVLOGV0:
3071 raise error.RevlogError(
3080 raise error.RevlogError(
3072 _(b'cannot censor with version %d revlogs')
3081 _(b'cannot censor with version %d revlogs')
3073 % self._format_version
3082 % self._format_version
3074 )
3083 )
3075 elif self._format_version == REVLOGV1:
3084 elif self._format_version == REVLOGV1:
3076 rewrite.v1_censor(self, tr, censornode, tombstone)
3085 rewrite.v1_censor(self, tr, censornode, tombstone)
3077 else:
3086 else:
3078 rewrite.v2_censor(self, tr, censornode, tombstone)
3087 rewrite.v2_censor(self, tr, censornode, tombstone)
3079
3088
3080 def verifyintegrity(self, state):
3089 def verifyintegrity(self, state):
3081 """Verifies the integrity of the revlog.
3090 """Verifies the integrity of the revlog.
3082
3091
3083 Yields ``revlogproblem`` instances describing problems that are
3092 Yields ``revlogproblem`` instances describing problems that are
3084 found.
3093 found.
3085 """
3094 """
3086 dd, di = self.checksize()
3095 dd, di = self.checksize()
3087 if dd:
3096 if dd:
3088 yield revlogproblem(error=_(b'data length off by %d bytes') % dd)
3097 yield revlogproblem(error=_(b'data length off by %d bytes') % dd)
3089 if di:
3098 if di:
3090 yield revlogproblem(error=_(b'index contains %d extra bytes') % di)
3099 yield revlogproblem(error=_(b'index contains %d extra bytes') % di)
3091
3100
3092 version = self._format_version
3101 version = self._format_version
3093
3102
3094 # The verifier tells us what version revlog we should be.
3103 # The verifier tells us what version revlog we should be.
3095 if version != state[b'expectedversion']:
3104 if version != state[b'expectedversion']:
3096 yield revlogproblem(
3105 yield revlogproblem(
3097 warning=_(b"warning: '%s' uses revlog format %d; expected %d")
3106 warning=_(b"warning: '%s' uses revlog format %d; expected %d")
3098 % (self.display_id, version, state[b'expectedversion'])
3107 % (self.display_id, version, state[b'expectedversion'])
3099 )
3108 )
3100
3109
3101 state[b'skipread'] = set()
3110 state[b'skipread'] = set()
3102 state[b'safe_renamed'] = set()
3111 state[b'safe_renamed'] = set()
3103
3112
3104 for rev in self:
3113 for rev in self:
3105 node = self.node(rev)
3114 node = self.node(rev)
3106
3115
3107 # Verify contents. 4 cases to care about:
3116 # Verify contents. 4 cases to care about:
3108 #
3117 #
3109 # common: the most common case
3118 # common: the most common case
3110 # rename: with a rename
3119 # rename: with a rename
3111 # meta: file content starts with b'\1\n', the metadata
3120 # meta: file content starts with b'\1\n', the metadata
3112 # header defined in filelog.py, but without a rename
3121 # header defined in filelog.py, but without a rename
3113 # ext: content stored externally
3122 # ext: content stored externally
3114 #
3123 #
3115 # More formally, their differences are shown below:
3124 # More formally, their differences are shown below:
3116 #
3125 #
3117 # | common | rename | meta | ext
3126 # | common | rename | meta | ext
3118 # -------------------------------------------------------
3127 # -------------------------------------------------------
3119 # flags() | 0 | 0 | 0 | not 0
3128 # flags() | 0 | 0 | 0 | not 0
3120 # renamed() | False | True | False | ?
3129 # renamed() | False | True | False | ?
3121 # rawtext[0:2]=='\1\n'| False | True | True | ?
3130 # rawtext[0:2]=='\1\n'| False | True | True | ?
3122 #
3131 #
3123 # "rawtext" means the raw text stored in revlog data, which
3132 # "rawtext" means the raw text stored in revlog data, which
3124 # could be retrieved by "rawdata(rev)". "text"
3133 # could be retrieved by "rawdata(rev)". "text"
3125 # mentioned below is "revision(rev)".
3134 # mentioned below is "revision(rev)".
3126 #
3135 #
3127 # There are 3 different lengths stored physically:
3136 # There are 3 different lengths stored physically:
3128 # 1. L1: rawsize, stored in revlog index
3137 # 1. L1: rawsize, stored in revlog index
3129 # 2. L2: len(rawtext), stored in revlog data
3138 # 2. L2: len(rawtext), stored in revlog data
3130 # 3. L3: len(text), stored in revlog data if flags==0, or
3139 # 3. L3: len(text), stored in revlog data if flags==0, or
3131 # possibly somewhere else if flags!=0
3140 # possibly somewhere else if flags!=0
3132 #
3141 #
3133 # L1 should be equal to L2. L3 could be different from them.
3142 # L1 should be equal to L2. L3 could be different from them.
3134 # "text" may or may not affect commit hash depending on flag
3143 # "text" may or may not affect commit hash depending on flag
3135 # processors (see flagutil.addflagprocessor).
3144 # processors (see flagutil.addflagprocessor).
3136 #
3145 #
3137 # | common | rename | meta | ext
3146 # | common | rename | meta | ext
3138 # -------------------------------------------------
3147 # -------------------------------------------------
3139 # rawsize() | L1 | L1 | L1 | L1
3148 # rawsize() | L1 | L1 | L1 | L1
3140 # size() | L1 | L2-LM | L1(*) | L1 (?)
3149 # size() | L1 | L2-LM | L1(*) | L1 (?)
3141 # len(rawtext) | L2 | L2 | L2 | L2
3150 # len(rawtext) | L2 | L2 | L2 | L2
3142 # len(text) | L2 | L2 | L2 | L3
3151 # len(text) | L2 | L2 | L2 | L3
3143 # len(read()) | L2 | L2-LM | L2-LM | L3 (?)
3152 # len(read()) | L2 | L2-LM | L2-LM | L3 (?)
3144 #
3153 #
3145 # LM: length of metadata, depending on rawtext
3154 # LM: length of metadata, depending on rawtext
3146 # (*): not ideal, see comment in filelog.size
3155 # (*): not ideal, see comment in filelog.size
3147 # (?): could be "- len(meta)" if the resolved content has
3156 # (?): could be "- len(meta)" if the resolved content has
3148 # rename metadata
3157 # rename metadata
3149 #
3158 #
3150 # Checks needed to be done:
3159 # Checks needed to be done:
3151 # 1. length check: L1 == L2, in all cases.
3160 # 1. length check: L1 == L2, in all cases.
3152 # 2. hash check: depending on flag processor, we may need to
3161 # 2. hash check: depending on flag processor, we may need to
3153 # use either "text" (external), or "rawtext" (in revlog).
3162 # use either "text" (external), or "rawtext" (in revlog).
3154
3163
3155 try:
3164 try:
3156 skipflags = state.get(b'skipflags', 0)
3165 skipflags = state.get(b'skipflags', 0)
3157 if skipflags:
3166 if skipflags:
3158 skipflags &= self.flags(rev)
3167 skipflags &= self.flags(rev)
3159
3168
3160 _verify_revision(self, skipflags, state, node)
3169 _verify_revision(self, skipflags, state, node)
3161
3170
3162 l1 = self.rawsize(rev)
3171 l1 = self.rawsize(rev)
3163 l2 = len(self.rawdata(node))
3172 l2 = len(self.rawdata(node))
3164
3173
3165 if l1 != l2:
3174 if l1 != l2:
3166 yield revlogproblem(
3175 yield revlogproblem(
3167 error=_(b'unpacked size is %d, %d expected') % (l2, l1),
3176 error=_(b'unpacked size is %d, %d expected') % (l2, l1),
3168 node=node,
3177 node=node,
3169 )
3178 )
3170
3179
3171 except error.CensoredNodeError:
3180 except error.CensoredNodeError:
3172 if state[b'erroroncensored']:
3181 if state[b'erroroncensored']:
3173 yield revlogproblem(
3182 yield revlogproblem(
3174 error=_(b'censored file data'), node=node
3183 error=_(b'censored file data'), node=node
3175 )
3184 )
3176 state[b'skipread'].add(node)
3185 state[b'skipread'].add(node)
3177 except Exception as e:
3186 except Exception as e:
3178 yield revlogproblem(
3187 yield revlogproblem(
3179 error=_(b'unpacking %s: %s')
3188 error=_(b'unpacking %s: %s')
3180 % (short(node), stringutil.forcebytestr(e)),
3189 % (short(node), stringutil.forcebytestr(e)),
3181 node=node,
3190 node=node,
3182 )
3191 )
3183 state[b'skipread'].add(node)
3192 state[b'skipread'].add(node)
3184
3193
3185 def storageinfo(
3194 def storageinfo(
3186 self,
3195 self,
3187 exclusivefiles=False,
3196 exclusivefiles=False,
3188 sharedfiles=False,
3197 sharedfiles=False,
3189 revisionscount=False,
3198 revisionscount=False,
3190 trackedsize=False,
3199 trackedsize=False,
3191 storedsize=False,
3200 storedsize=False,
3192 ):
3201 ):
3193 d = {}
3202 d = {}
3194
3203
3195 if exclusivefiles:
3204 if exclusivefiles:
3196 d[b'exclusivefiles'] = [(self.opener, self._indexfile)]
3205 d[b'exclusivefiles'] = [(self.opener, self._indexfile)]
3197 if not self._inline:
3206 if not self._inline:
3198 d[b'exclusivefiles'].append((self.opener, self._datafile))
3207 d[b'exclusivefiles'].append((self.opener, self._datafile))
3199
3208
3200 if sharedfiles:
3209 if sharedfiles:
3201 d[b'sharedfiles'] = []
3210 d[b'sharedfiles'] = []
3202
3211
3203 if revisionscount:
3212 if revisionscount:
3204 d[b'revisionscount'] = len(self)
3213 d[b'revisionscount'] = len(self)
3205
3214
3206 if trackedsize:
3215 if trackedsize:
3207 d[b'trackedsize'] = sum(map(self.rawsize, iter(self)))
3216 d[b'trackedsize'] = sum(map(self.rawsize, iter(self)))
3208
3217
3209 if storedsize:
3218 if storedsize:
3210 d[b'storedsize'] = sum(
3219 d[b'storedsize'] = sum(
3211 self.opener.stat(path).st_size for path in self.files()
3220 self.opener.stat(path).st_size for path in self.files()
3212 )
3221 )
3213
3222
3214 return d
3223 return d
3215
3224
3216 def rewrite_sidedata(self, transaction, helpers, startrev, endrev):
3225 def rewrite_sidedata(self, transaction, helpers, startrev, endrev):
3217 if not self.hassidedata:
3226 if not self.hassidedata:
3218 return
3227 return
3219 # revlog formats with sidedata support does not support inline
3228 # revlog formats with sidedata support does not support inline
3220 assert not self._inline
3229 assert not self._inline
3221 if not helpers[1] and not helpers[2]:
3230 if not helpers[1] and not helpers[2]:
3222 # Nothing to generate or remove
3231 # Nothing to generate or remove
3223 return
3232 return
3224
3233
3225 new_entries = []
3234 new_entries = []
3226 # append the new sidedata
3235 # append the new sidedata
3227 with self._writing(transaction):
3236 with self._writing(transaction):
3228 ifh, dfh, sdfh = self._writinghandles
3237 ifh, dfh, sdfh = self._writinghandles
3229 dfh.seek(self._docket.sidedata_end, os.SEEK_SET)
3238 dfh.seek(self._docket.sidedata_end, os.SEEK_SET)
3230
3239
3231 current_offset = sdfh.tell()
3240 current_offset = sdfh.tell()
3232 for rev in range(startrev, endrev + 1):
3241 for rev in range(startrev, endrev + 1):
3233 entry = self.index[rev]
3242 entry = self.index[rev]
3234 new_sidedata, flags = sidedatautil.run_sidedata_helpers(
3243 new_sidedata, flags = sidedatautil.run_sidedata_helpers(
3235 store=self,
3244 store=self,
3236 sidedata_helpers=helpers,
3245 sidedata_helpers=helpers,
3237 sidedata={},
3246 sidedata={},
3238 rev=rev,
3247 rev=rev,
3239 )
3248 )
3240
3249
3241 serialized_sidedata = sidedatautil.serialize_sidedata(
3250 serialized_sidedata = sidedatautil.serialize_sidedata(
3242 new_sidedata
3251 new_sidedata
3243 )
3252 )
3244
3253
3245 sidedata_compression_mode = COMP_MODE_INLINE
3254 sidedata_compression_mode = COMP_MODE_INLINE
3246 if serialized_sidedata and self.hassidedata:
3255 if serialized_sidedata and self.hassidedata:
3247 sidedata_compression_mode = COMP_MODE_PLAIN
3256 sidedata_compression_mode = COMP_MODE_PLAIN
3248 h, comp_sidedata = self.compress(serialized_sidedata)
3257 h, comp_sidedata = self.compress(serialized_sidedata)
3249 if (
3258 if (
3250 h != b'u'
3259 h != b'u'
3251 and comp_sidedata[0] != b'\0'
3260 and comp_sidedata[0] != b'\0'
3252 and len(comp_sidedata) < len(serialized_sidedata)
3261 and len(comp_sidedata) < len(serialized_sidedata)
3253 ):
3262 ):
3254 assert not h
3263 assert not h
3255 if (
3264 if (
3256 comp_sidedata[0]
3265 comp_sidedata[0]
3257 == self._docket.default_compression_header
3266 == self._docket.default_compression_header
3258 ):
3267 ):
3259 sidedata_compression_mode = COMP_MODE_DEFAULT
3268 sidedata_compression_mode = COMP_MODE_DEFAULT
3260 serialized_sidedata = comp_sidedata
3269 serialized_sidedata = comp_sidedata
3261 else:
3270 else:
3262 sidedata_compression_mode = COMP_MODE_INLINE
3271 sidedata_compression_mode = COMP_MODE_INLINE
3263 serialized_sidedata = comp_sidedata
3272 serialized_sidedata = comp_sidedata
3264 if entry[8] != 0 or entry[9] != 0:
3273 if entry[8] != 0 or entry[9] != 0:
3265 # rewriting entries that already have sidedata is not
3274 # rewriting entries that already have sidedata is not
3266 # supported yet, because it introduces garbage data in the
3275 # supported yet, because it introduces garbage data in the
3267 # revlog.
3276 # revlog.
3268 msg = b"rewriting existing sidedata is not supported yet"
3277 msg = b"rewriting existing sidedata is not supported yet"
3269 raise error.Abort(msg)
3278 raise error.Abort(msg)
3270
3279
3271 # Apply (potential) flags to add and to remove after running
3280 # Apply (potential) flags to add and to remove after running
3272 # the sidedata helpers
3281 # the sidedata helpers
3273 new_offset_flags = entry[0] | flags[0] & ~flags[1]
3282 new_offset_flags = entry[0] | flags[0] & ~flags[1]
3274 entry_update = (
3283 entry_update = (
3275 current_offset,
3284 current_offset,
3276 len(serialized_sidedata),
3285 len(serialized_sidedata),
3277 new_offset_flags,
3286 new_offset_flags,
3278 sidedata_compression_mode,
3287 sidedata_compression_mode,
3279 )
3288 )
3280
3289
3281 # the sidedata computation might have move the file cursors around
3290 # the sidedata computation might have move the file cursors around
3282 sdfh.seek(current_offset, os.SEEK_SET)
3291 sdfh.seek(current_offset, os.SEEK_SET)
3283 sdfh.write(serialized_sidedata)
3292 sdfh.write(serialized_sidedata)
3284 new_entries.append(entry_update)
3293 new_entries.append(entry_update)
3285 current_offset += len(serialized_sidedata)
3294 current_offset += len(serialized_sidedata)
3286 self._docket.sidedata_end = sdfh.tell()
3295 self._docket.sidedata_end = sdfh.tell()
3287
3296
3288 # rewrite the new index entries
3297 # rewrite the new index entries
3289 ifh.seek(startrev * self.index.entry_size)
3298 ifh.seek(startrev * self.index.entry_size)
3290 for i, e in enumerate(new_entries):
3299 for i, e in enumerate(new_entries):
3291 rev = startrev + i
3300 rev = startrev + i
3292 self.index.replace_sidedata_info(rev, *e)
3301 self.index.replace_sidedata_info(rev, *e)
3293 packed = self.index.entry_binary(rev)
3302 packed = self.index.entry_binary(rev)
3294 if rev == 0 and self._docket is None:
3303 if rev == 0 and self._docket is None:
3295 header = self._format_flags | self._format_version
3304 header = self._format_flags | self._format_version
3296 header = self.index.pack_header(header)
3305 header = self.index.pack_header(header)
3297 packed = header + packed
3306 packed = header + packed
3298 ifh.write(packed)
3307 ifh.write(packed)
General Comments 0
You need to be logged in to leave comments. Login now