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