##// END OF EJS Templates
revlog: more efficient implementation for issnapshot...
Boris Feld -
r41116:84491ae0 default
parent child Browse files
Show More
@@ -1,2599 +1,2603 b''
1 1 # revlog.py - storage back-end for mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
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 """Storage back-end for Mercurial.
9 9
10 10 This provides efficient delta storage with O(1) retrieve and append
11 11 and O(changes) merge between branches.
12 12 """
13 13
14 14 from __future__ import absolute_import
15 15
16 16 import collections
17 17 import contextlib
18 18 import errno
19 19 import os
20 20 import struct
21 21 import zlib
22 22
23 23 # import stuff from node for others to import from revlog
24 24 from .node import (
25 25 bin,
26 26 hex,
27 27 nullhex,
28 28 nullid,
29 29 nullrev,
30 30 short,
31 31 wdirfilenodeids,
32 32 wdirhex,
33 33 wdirid,
34 34 wdirrev,
35 35 )
36 36 from .i18n import _
37 37 from .revlogutils.constants import (
38 38 FLAG_GENERALDELTA,
39 39 FLAG_INLINE_DATA,
40 40 REVIDX_DEFAULT_FLAGS,
41 41 REVIDX_ELLIPSIS,
42 42 REVIDX_EXTSTORED,
43 43 REVIDX_FLAGS_ORDER,
44 44 REVIDX_ISCENSORED,
45 45 REVIDX_KNOWN_FLAGS,
46 46 REVIDX_RAWTEXT_CHANGING_FLAGS,
47 47 REVLOGV0,
48 48 REVLOGV1,
49 49 REVLOGV1_FLAGS,
50 50 REVLOGV2,
51 51 REVLOGV2_FLAGS,
52 52 REVLOG_DEFAULT_FLAGS,
53 53 REVLOG_DEFAULT_FORMAT,
54 54 REVLOG_DEFAULT_VERSION,
55 55 )
56 56 from .thirdparty import (
57 57 attr,
58 58 )
59 59 from . import (
60 60 ancestor,
61 61 dagop,
62 62 error,
63 63 mdiff,
64 64 policy,
65 65 pycompat,
66 66 repository,
67 67 templatefilters,
68 68 util,
69 69 )
70 70 from .revlogutils import (
71 71 deltas as deltautil,
72 72 )
73 73 from .utils import (
74 74 interfaceutil,
75 75 storageutil,
76 76 stringutil,
77 77 )
78 78
79 79 # blanked usage of all the name to prevent pyflakes constraints
80 80 # We need these name available in the module for extensions.
81 81 REVLOGV0
82 82 REVLOGV1
83 83 REVLOGV2
84 84 FLAG_INLINE_DATA
85 85 FLAG_GENERALDELTA
86 86 REVLOG_DEFAULT_FLAGS
87 87 REVLOG_DEFAULT_FORMAT
88 88 REVLOG_DEFAULT_VERSION
89 89 REVLOGV1_FLAGS
90 90 REVLOGV2_FLAGS
91 91 REVIDX_ISCENSORED
92 92 REVIDX_ELLIPSIS
93 93 REVIDX_EXTSTORED
94 94 REVIDX_DEFAULT_FLAGS
95 95 REVIDX_FLAGS_ORDER
96 96 REVIDX_KNOWN_FLAGS
97 97 REVIDX_RAWTEXT_CHANGING_FLAGS
98 98
99 99 parsers = policy.importmod(r'parsers')
100 100
101 101 # Aliased for performance.
102 102 _zlibdecompress = zlib.decompress
103 103
104 104 # max size of revlog with inline data
105 105 _maxinline = 131072
106 106 _chunksize = 1048576
107 107
108 108 # Store flag processors (cf. 'addflagprocessor()' to register)
109 109 _flagprocessors = {
110 110 REVIDX_ISCENSORED: None,
111 111 }
112 112
113 113 # Flag processors for REVIDX_ELLIPSIS.
114 114 def ellipsisreadprocessor(rl, text):
115 115 return text, False
116 116
117 117 def ellipsiswriteprocessor(rl, text):
118 118 return text, False
119 119
120 120 def ellipsisrawprocessor(rl, text):
121 121 return False
122 122
123 123 ellipsisprocessor = (
124 124 ellipsisreadprocessor,
125 125 ellipsiswriteprocessor,
126 126 ellipsisrawprocessor,
127 127 )
128 128
129 129 def addflagprocessor(flag, processor):
130 130 """Register a flag processor on a revision data flag.
131 131
132 132 Invariant:
133 133 - Flags need to be defined in REVIDX_KNOWN_FLAGS and REVIDX_FLAGS_ORDER,
134 134 and REVIDX_RAWTEXT_CHANGING_FLAGS if they can alter rawtext.
135 135 - Only one flag processor can be registered on a specific flag.
136 136 - flagprocessors must be 3-tuples of functions (read, write, raw) with the
137 137 following signatures:
138 138 - (read) f(self, rawtext) -> text, bool
139 139 - (write) f(self, text) -> rawtext, bool
140 140 - (raw) f(self, rawtext) -> bool
141 141 "text" is presented to the user. "rawtext" is stored in revlog data, not
142 142 directly visible to the user.
143 143 The boolean returned by these transforms is used to determine whether
144 144 the returned text can be used for hash integrity checking. For example,
145 145 if "write" returns False, then "text" is used to generate hash. If
146 146 "write" returns True, that basically means "rawtext" returned by "write"
147 147 should be used to generate hash. Usually, "write" and "read" return
148 148 different booleans. And "raw" returns a same boolean as "write".
149 149
150 150 Note: The 'raw' transform is used for changegroup generation and in some
151 151 debug commands. In this case the transform only indicates whether the
152 152 contents can be used for hash integrity checks.
153 153 """
154 154 _insertflagprocessor(flag, processor, _flagprocessors)
155 155
156 156 def _insertflagprocessor(flag, processor, flagprocessors):
157 157 if not flag & REVIDX_KNOWN_FLAGS:
158 158 msg = _("cannot register processor on unknown flag '%#x'.") % (flag)
159 159 raise error.ProgrammingError(msg)
160 160 if flag not in REVIDX_FLAGS_ORDER:
161 161 msg = _("flag '%#x' undefined in REVIDX_FLAGS_ORDER.") % (flag)
162 162 raise error.ProgrammingError(msg)
163 163 if flag in flagprocessors:
164 164 msg = _("cannot register multiple processors on flag '%#x'.") % (flag)
165 165 raise error.Abort(msg)
166 166 flagprocessors[flag] = processor
167 167
168 168 def getoffset(q):
169 169 return int(q >> 16)
170 170
171 171 def gettype(q):
172 172 return int(q & 0xFFFF)
173 173
174 174 def offset_type(offset, type):
175 175 if (type & ~REVIDX_KNOWN_FLAGS) != 0:
176 176 raise ValueError('unknown revlog index flags')
177 177 return int(int(offset) << 16 | type)
178 178
179 179 @attr.s(slots=True, frozen=True)
180 180 class _revisioninfo(object):
181 181 """Information about a revision that allows building its fulltext
182 182 node: expected hash of the revision
183 183 p1, p2: parent revs of the revision
184 184 btext: built text cache consisting of a one-element list
185 185 cachedelta: (baserev, uncompressed_delta) or None
186 186 flags: flags associated to the revision storage
187 187
188 188 One of btext[0] or cachedelta must be set.
189 189 """
190 190 node = attr.ib()
191 191 p1 = attr.ib()
192 192 p2 = attr.ib()
193 193 btext = attr.ib()
194 194 textlen = attr.ib()
195 195 cachedelta = attr.ib()
196 196 flags = attr.ib()
197 197
198 198 @interfaceutil.implementer(repository.irevisiondelta)
199 199 @attr.s(slots=True)
200 200 class revlogrevisiondelta(object):
201 201 node = attr.ib()
202 202 p1node = attr.ib()
203 203 p2node = attr.ib()
204 204 basenode = attr.ib()
205 205 flags = attr.ib()
206 206 baserevisionsize = attr.ib()
207 207 revision = attr.ib()
208 208 delta = attr.ib()
209 209 linknode = attr.ib(default=None)
210 210
211 211 @interfaceutil.implementer(repository.iverifyproblem)
212 212 @attr.s(frozen=True)
213 213 class revlogproblem(object):
214 214 warning = attr.ib(default=None)
215 215 error = attr.ib(default=None)
216 216 node = attr.ib(default=None)
217 217
218 218 # index v0:
219 219 # 4 bytes: offset
220 220 # 4 bytes: compressed length
221 221 # 4 bytes: base rev
222 222 # 4 bytes: link rev
223 223 # 20 bytes: parent 1 nodeid
224 224 # 20 bytes: parent 2 nodeid
225 225 # 20 bytes: nodeid
226 226 indexformatv0 = struct.Struct(">4l20s20s20s")
227 227 indexformatv0_pack = indexformatv0.pack
228 228 indexformatv0_unpack = indexformatv0.unpack
229 229
230 230 class revlogoldindex(list):
231 231 def __getitem__(self, i):
232 232 if i == -1:
233 233 return (0, 0, 0, -1, -1, -1, -1, nullid)
234 234 return list.__getitem__(self, i)
235 235
236 236 class revlogoldio(object):
237 237 def __init__(self):
238 238 self.size = indexformatv0.size
239 239
240 240 def parseindex(self, data, inline):
241 241 s = self.size
242 242 index = []
243 243 nodemap = {nullid: nullrev}
244 244 n = off = 0
245 245 l = len(data)
246 246 while off + s <= l:
247 247 cur = data[off:off + s]
248 248 off += s
249 249 e = indexformatv0_unpack(cur)
250 250 # transform to revlogv1 format
251 251 e2 = (offset_type(e[0], 0), e[1], -1, e[2], e[3],
252 252 nodemap.get(e[4], nullrev), nodemap.get(e[5], nullrev), e[6])
253 253 index.append(e2)
254 254 nodemap[e[6]] = n
255 255 n += 1
256 256
257 257 return revlogoldindex(index), nodemap, None
258 258
259 259 def packentry(self, entry, node, version, rev):
260 260 if gettype(entry[0]):
261 261 raise error.RevlogError(_('index entry flags need revlog '
262 262 'version 1'))
263 263 e2 = (getoffset(entry[0]), entry[1], entry[3], entry[4],
264 264 node(entry[5]), node(entry[6]), entry[7])
265 265 return indexformatv0_pack(*e2)
266 266
267 267 # index ng:
268 268 # 6 bytes: offset
269 269 # 2 bytes: flags
270 270 # 4 bytes: compressed length
271 271 # 4 bytes: uncompressed length
272 272 # 4 bytes: base rev
273 273 # 4 bytes: link rev
274 274 # 4 bytes: parent 1 rev
275 275 # 4 bytes: parent 2 rev
276 276 # 32 bytes: nodeid
277 277 indexformatng = struct.Struct(">Qiiiiii20s12x")
278 278 indexformatng_pack = indexformatng.pack
279 279 versionformat = struct.Struct(">I")
280 280 versionformat_pack = versionformat.pack
281 281 versionformat_unpack = versionformat.unpack
282 282
283 283 # corresponds to uncompressed length of indexformatng (2 gigs, 4-byte
284 284 # signed integer)
285 285 _maxentrysize = 0x7fffffff
286 286
287 287 class revlogio(object):
288 288 def __init__(self):
289 289 self.size = indexformatng.size
290 290
291 291 def parseindex(self, data, inline):
292 292 # call the C implementation to parse the index data
293 293 index, cache = parsers.parse_index2(data, inline)
294 294 return index, getattr(index, 'nodemap', None), cache
295 295
296 296 def packentry(self, entry, node, version, rev):
297 297 p = indexformatng_pack(*entry)
298 298 if rev == 0:
299 299 p = versionformat_pack(version) + p[4:]
300 300 return p
301 301
302 302 class revlog(object):
303 303 """
304 304 the underlying revision storage object
305 305
306 306 A revlog consists of two parts, an index and the revision data.
307 307
308 308 The index is a file with a fixed record size containing
309 309 information on each revision, including its nodeid (hash), the
310 310 nodeids of its parents, the position and offset of its data within
311 311 the data file, and the revision it's based on. Finally, each entry
312 312 contains a linkrev entry that can serve as a pointer to external
313 313 data.
314 314
315 315 The revision data itself is a linear collection of data chunks.
316 316 Each chunk represents a revision and is usually represented as a
317 317 delta against the previous chunk. To bound lookup time, runs of
318 318 deltas are limited to about 2 times the length of the original
319 319 version data. This makes retrieval of a version proportional to
320 320 its size, or O(1) relative to the number of revisions.
321 321
322 322 Both pieces of the revlog are written to in an append-only
323 323 fashion, which means we never need to rewrite a file to insert or
324 324 remove data, and can use some simple techniques to avoid the need
325 325 for locking while reading.
326 326
327 327 If checkambig, indexfile is opened with checkambig=True at
328 328 writing, to avoid file stat ambiguity.
329 329
330 330 If mmaplargeindex is True, and an mmapindexthreshold is set, the
331 331 index will be mmapped rather than read if it is larger than the
332 332 configured threshold.
333 333
334 334 If censorable is True, the revlog can have censored revisions.
335 335 """
336 336 def __init__(self, opener, indexfile, datafile=None, checkambig=False,
337 337 mmaplargeindex=False, censorable=False):
338 338 """
339 339 create a revlog object
340 340
341 341 opener is a function that abstracts the file opening operation
342 342 and can be used to implement COW semantics or the like.
343 343 """
344 344 self.indexfile = indexfile
345 345 self.datafile = datafile or (indexfile[:-2] + ".d")
346 346 self.opener = opener
347 347 # When True, indexfile is opened with checkambig=True at writing, to
348 348 # avoid file stat ambiguity.
349 349 self._checkambig = checkambig
350 350 self._censorable = censorable
351 351 # 3-tuple of (node, rev, text) for a raw revision.
352 352 self._revisioncache = None
353 353 # Maps rev to chain base rev.
354 354 self._chainbasecache = util.lrucachedict(100)
355 355 # 2-tuple of (offset, data) of raw data from the revlog at an offset.
356 356 self._chunkcache = (0, '')
357 357 # How much data to read and cache into the raw revlog data cache.
358 358 self._chunkcachesize = 65536
359 359 self._maxchainlen = None
360 360 self._deltabothparents = True
361 361 self.index = []
362 362 # Mapping of partial identifiers to full nodes.
363 363 self._pcache = {}
364 364 # Mapping of revision integer to full node.
365 365 self._nodecache = {nullid: nullrev}
366 366 self._nodepos = None
367 367 self._compengine = 'zlib'
368 368 self._maxdeltachainspan = -1
369 369 self._withsparseread = False
370 370 self._sparserevlog = False
371 371 self._srdensitythreshold = 0.50
372 372 self._srmingapsize = 262144
373 373
374 374 # Make copy of flag processors so each revlog instance can support
375 375 # custom flags.
376 376 self._flagprocessors = dict(_flagprocessors)
377 377
378 378 # 2-tuple of file handles being used for active writing.
379 379 self._writinghandles = None
380 380
381 381 mmapindexthreshold = None
382 382 v = REVLOG_DEFAULT_VERSION
383 383 opts = getattr(opener, 'options', None)
384 384 if opts is not None:
385 385 if 'revlogv2' in opts:
386 386 # version 2 revlogs always use generaldelta.
387 387 v = REVLOGV2 | FLAG_GENERALDELTA | FLAG_INLINE_DATA
388 388 elif 'revlogv1' in opts:
389 389 if 'generaldelta' in opts:
390 390 v |= FLAG_GENERALDELTA
391 391 else:
392 392 v = 0
393 393 if 'chunkcachesize' in opts:
394 394 self._chunkcachesize = opts['chunkcachesize']
395 395 if 'maxchainlen' in opts:
396 396 self._maxchainlen = opts['maxchainlen']
397 397 if 'deltabothparents' in opts:
398 398 self._deltabothparents = opts['deltabothparents']
399 399 self._lazydeltabase = bool(opts.get('lazydeltabase', False))
400 400 if 'compengine' in opts:
401 401 self._compengine = opts['compengine']
402 402 if 'maxdeltachainspan' in opts:
403 403 self._maxdeltachainspan = opts['maxdeltachainspan']
404 404 if mmaplargeindex and 'mmapindexthreshold' in opts:
405 405 mmapindexthreshold = opts['mmapindexthreshold']
406 406 self._sparserevlog = bool(opts.get('sparse-revlog', False))
407 407 withsparseread = bool(opts.get('with-sparse-read', False))
408 408 # sparse-revlog forces sparse-read
409 409 self._withsparseread = self._sparserevlog or withsparseread
410 410 if 'sparse-read-density-threshold' in opts:
411 411 self._srdensitythreshold = opts['sparse-read-density-threshold']
412 412 if 'sparse-read-min-gap-size' in opts:
413 413 self._srmingapsize = opts['sparse-read-min-gap-size']
414 414 if opts.get('enableellipsis'):
415 415 self._flagprocessors[REVIDX_ELLIPSIS] = ellipsisprocessor
416 416
417 417 # revlog v0 doesn't have flag processors
418 418 for flag, processor in opts.get(b'flagprocessors', {}).iteritems():
419 419 _insertflagprocessor(flag, processor, self._flagprocessors)
420 420
421 421 if self._chunkcachesize <= 0:
422 422 raise error.RevlogError(_('revlog chunk cache size %r is not '
423 423 'greater than 0') % self._chunkcachesize)
424 424 elif self._chunkcachesize & (self._chunkcachesize - 1):
425 425 raise error.RevlogError(_('revlog chunk cache size %r is not a '
426 426 'power of 2') % self._chunkcachesize)
427 427
428 428 self._loadindex(v, mmapindexthreshold)
429 429
430 430 def _loadindex(self, v, mmapindexthreshold):
431 431 indexdata = ''
432 432 self._initempty = True
433 433 try:
434 434 with self._indexfp() as f:
435 435 if (mmapindexthreshold is not None and
436 436 self.opener.fstat(f).st_size >= mmapindexthreshold):
437 437 indexdata = util.buffer(util.mmapread(f))
438 438 else:
439 439 indexdata = f.read()
440 440 if len(indexdata) > 0:
441 441 v = versionformat_unpack(indexdata[:4])[0]
442 442 self._initempty = False
443 443 except IOError as inst:
444 444 if inst.errno != errno.ENOENT:
445 445 raise
446 446
447 447 self.version = v
448 448 self._inline = v & FLAG_INLINE_DATA
449 449 self._generaldelta = v & FLAG_GENERALDELTA
450 450 flags = v & ~0xFFFF
451 451 fmt = v & 0xFFFF
452 452 if fmt == REVLOGV0:
453 453 if flags:
454 454 raise error.RevlogError(_('unknown flags (%#04x) in version %d '
455 455 'revlog %s') %
456 456 (flags >> 16, fmt, self.indexfile))
457 457 elif fmt == REVLOGV1:
458 458 if flags & ~REVLOGV1_FLAGS:
459 459 raise error.RevlogError(_('unknown flags (%#04x) in version %d '
460 460 'revlog %s') %
461 461 (flags >> 16, fmt, self.indexfile))
462 462 elif fmt == REVLOGV2:
463 463 if flags & ~REVLOGV2_FLAGS:
464 464 raise error.RevlogError(_('unknown flags (%#04x) in version %d '
465 465 'revlog %s') %
466 466 (flags >> 16, fmt, self.indexfile))
467 467 else:
468 468 raise error.RevlogError(_('unknown version (%d) in revlog %s') %
469 469 (fmt, self.indexfile))
470 470
471 471 self._storedeltachains = True
472 472
473 473 self._io = revlogio()
474 474 if self.version == REVLOGV0:
475 475 self._io = revlogoldio()
476 476 try:
477 477 d = self._io.parseindex(indexdata, self._inline)
478 478 except (ValueError, IndexError):
479 479 raise error.RevlogError(_("index %s is corrupted") %
480 480 self.indexfile)
481 481 self.index, nodemap, self._chunkcache = d
482 482 if nodemap is not None:
483 483 self.nodemap = self._nodecache = nodemap
484 484 if not self._chunkcache:
485 485 self._chunkclear()
486 486 # revnum -> (chain-length, sum-delta-length)
487 487 self._chaininfocache = {}
488 488 # revlog header -> revlog compressor
489 489 self._decompressors = {}
490 490
491 491 @util.propertycache
492 492 def _compressor(self):
493 493 return util.compengines[self._compengine].revlogcompressor()
494 494
495 495 def _indexfp(self, mode='r'):
496 496 """file object for the revlog's index file"""
497 497 args = {r'mode': mode}
498 498 if mode != 'r':
499 499 args[r'checkambig'] = self._checkambig
500 500 if mode == 'w':
501 501 args[r'atomictemp'] = True
502 502 return self.opener(self.indexfile, **args)
503 503
504 504 def _datafp(self, mode='r'):
505 505 """file object for the revlog's data file"""
506 506 return self.opener(self.datafile, mode=mode)
507 507
508 508 @contextlib.contextmanager
509 509 def _datareadfp(self, existingfp=None):
510 510 """file object suitable to read data"""
511 511 # Use explicit file handle, if given.
512 512 if existingfp is not None:
513 513 yield existingfp
514 514
515 515 # Use a file handle being actively used for writes, if available.
516 516 # There is some danger to doing this because reads will seek the
517 517 # file. However, _writeentry() performs a SEEK_END before all writes,
518 518 # so we should be safe.
519 519 elif self._writinghandles:
520 520 if self._inline:
521 521 yield self._writinghandles[0]
522 522 else:
523 523 yield self._writinghandles[1]
524 524
525 525 # Otherwise open a new file handle.
526 526 else:
527 527 if self._inline:
528 528 func = self._indexfp
529 529 else:
530 530 func = self._datafp
531 531 with func() as fp:
532 532 yield fp
533 533
534 534 def tip(self):
535 535 return self.node(len(self.index) - 1)
536 536 def __contains__(self, rev):
537 537 return 0 <= rev < len(self)
538 538 def __len__(self):
539 539 return len(self.index)
540 540 def __iter__(self):
541 541 return iter(pycompat.xrange(len(self)))
542 542 def revs(self, start=0, stop=None):
543 543 """iterate over all rev in this revlog (from start to stop)"""
544 544 return storageutil.iterrevs(len(self), start=start, stop=stop)
545 545
546 546 @util.propertycache
547 547 def nodemap(self):
548 548 if self.index:
549 549 # populate mapping down to the initial node
550 550 node0 = self.index[0][7] # get around changelog filtering
551 551 self.rev(node0)
552 552 return self._nodecache
553 553
554 554 def hasnode(self, node):
555 555 try:
556 556 self.rev(node)
557 557 return True
558 558 except KeyError:
559 559 return False
560 560
561 561 def candelta(self, baserev, rev):
562 562 """whether two revisions (baserev, rev) can be delta-ed or not"""
563 563 # Disable delta if either rev requires a content-changing flag
564 564 # processor (ex. LFS). This is because such flag processor can alter
565 565 # the rawtext content that the delta will be based on, and two clients
566 566 # could have a same revlog node with different flags (i.e. different
567 567 # rawtext contents) and the delta could be incompatible.
568 568 if ((self.flags(baserev) & REVIDX_RAWTEXT_CHANGING_FLAGS)
569 569 or (self.flags(rev) & REVIDX_RAWTEXT_CHANGING_FLAGS)):
570 570 return False
571 571 return True
572 572
573 573 def clearcaches(self):
574 574 self._revisioncache = None
575 575 self._chainbasecache.clear()
576 576 self._chunkcache = (0, '')
577 577 self._pcache = {}
578 578
579 579 try:
580 580 self._nodecache.clearcaches()
581 581 except AttributeError:
582 582 self._nodecache = {nullid: nullrev}
583 583 self._nodepos = None
584 584
585 585 def rev(self, node):
586 586 try:
587 587 return self._nodecache[node]
588 588 except TypeError:
589 589 raise
590 590 except error.RevlogError:
591 591 # parsers.c radix tree lookup failed
592 592 if node == wdirid or node in wdirfilenodeids:
593 593 raise error.WdirUnsupported
594 594 raise error.LookupError(node, self.indexfile, _('no node'))
595 595 except KeyError:
596 596 # pure python cache lookup failed
597 597 n = self._nodecache
598 598 i = self.index
599 599 p = self._nodepos
600 600 if p is None:
601 601 p = len(i) - 1
602 602 else:
603 603 assert p < len(i)
604 604 for r in pycompat.xrange(p, -1, -1):
605 605 v = i[r][7]
606 606 n[v] = r
607 607 if v == node:
608 608 self._nodepos = r - 1
609 609 return r
610 610 if node == wdirid or node in wdirfilenodeids:
611 611 raise error.WdirUnsupported
612 612 raise error.LookupError(node, self.indexfile, _('no node'))
613 613
614 614 # Accessors for index entries.
615 615
616 616 # First tuple entry is 8 bytes. First 6 bytes are offset. Last 2 bytes
617 617 # are flags.
618 618 def start(self, rev):
619 619 return int(self.index[rev][0] >> 16)
620 620
621 621 def flags(self, rev):
622 622 return self.index[rev][0] & 0xFFFF
623 623
624 624 def length(self, rev):
625 625 return self.index[rev][1]
626 626
627 627 def rawsize(self, rev):
628 628 """return the length of the uncompressed text for a given revision"""
629 629 l = self.index[rev][2]
630 630 if l >= 0:
631 631 return l
632 632
633 633 t = self.revision(rev, raw=True)
634 634 return len(t)
635 635
636 636 def size(self, rev):
637 637 """length of non-raw text (processed by a "read" flag processor)"""
638 638 # fast path: if no "read" flag processor could change the content,
639 639 # size is rawsize. note: ELLIPSIS is known to not change the content.
640 640 flags = self.flags(rev)
641 641 if flags & (REVIDX_KNOWN_FLAGS ^ REVIDX_ELLIPSIS) == 0:
642 642 return self.rawsize(rev)
643 643
644 644 return len(self.revision(rev, raw=False))
645 645
646 646 def chainbase(self, rev):
647 647 base = self._chainbasecache.get(rev)
648 648 if base is not None:
649 649 return base
650 650
651 651 index = self.index
652 652 iterrev = rev
653 653 base = index[iterrev][3]
654 654 while base != iterrev:
655 655 iterrev = base
656 656 base = index[iterrev][3]
657 657
658 658 self._chainbasecache[rev] = base
659 659 return base
660 660
661 661 def linkrev(self, rev):
662 662 return self.index[rev][4]
663 663
664 664 def parentrevs(self, rev):
665 665 try:
666 666 entry = self.index[rev]
667 667 except IndexError:
668 668 if rev == wdirrev:
669 669 raise error.WdirUnsupported
670 670 raise
671 671
672 672 return entry[5], entry[6]
673 673
674 674 # fast parentrevs(rev) where rev isn't filtered
675 675 _uncheckedparentrevs = parentrevs
676 676
677 677 def node(self, rev):
678 678 try:
679 679 return self.index[rev][7]
680 680 except IndexError:
681 681 if rev == wdirrev:
682 682 raise error.WdirUnsupported
683 683 raise
684 684
685 685 # Derived from index values.
686 686
687 687 def end(self, rev):
688 688 return self.start(rev) + self.length(rev)
689 689
690 690 def parents(self, node):
691 691 i = self.index
692 692 d = i[self.rev(node)]
693 693 return i[d[5]][7], i[d[6]][7] # map revisions to nodes inline
694 694
695 695 def chainlen(self, rev):
696 696 return self._chaininfo(rev)[0]
697 697
698 698 def _chaininfo(self, rev):
699 699 chaininfocache = self._chaininfocache
700 700 if rev in chaininfocache:
701 701 return chaininfocache[rev]
702 702 index = self.index
703 703 generaldelta = self._generaldelta
704 704 iterrev = rev
705 705 e = index[iterrev]
706 706 clen = 0
707 707 compresseddeltalen = 0
708 708 while iterrev != e[3]:
709 709 clen += 1
710 710 compresseddeltalen += e[1]
711 711 if generaldelta:
712 712 iterrev = e[3]
713 713 else:
714 714 iterrev -= 1
715 715 if iterrev in chaininfocache:
716 716 t = chaininfocache[iterrev]
717 717 clen += t[0]
718 718 compresseddeltalen += t[1]
719 719 break
720 720 e = index[iterrev]
721 721 else:
722 722 # Add text length of base since decompressing that also takes
723 723 # work. For cache hits the length is already included.
724 724 compresseddeltalen += e[1]
725 725 r = (clen, compresseddeltalen)
726 726 chaininfocache[rev] = r
727 727 return r
728 728
729 729 def _deltachain(self, rev, stoprev=None):
730 730 """Obtain the delta chain for a revision.
731 731
732 732 ``stoprev`` specifies a revision to stop at. If not specified, we
733 733 stop at the base of the chain.
734 734
735 735 Returns a 2-tuple of (chain, stopped) where ``chain`` is a list of
736 736 revs in ascending order and ``stopped`` is a bool indicating whether
737 737 ``stoprev`` was hit.
738 738 """
739 739 # Try C implementation.
740 740 try:
741 741 return self.index.deltachain(rev, stoprev, self._generaldelta)
742 742 except AttributeError:
743 743 pass
744 744
745 745 chain = []
746 746
747 747 # Alias to prevent attribute lookup in tight loop.
748 748 index = self.index
749 749 generaldelta = self._generaldelta
750 750
751 751 iterrev = rev
752 752 e = index[iterrev]
753 753 while iterrev != e[3] and iterrev != stoprev:
754 754 chain.append(iterrev)
755 755 if generaldelta:
756 756 iterrev = e[3]
757 757 else:
758 758 iterrev -= 1
759 759 e = index[iterrev]
760 760
761 761 if iterrev == stoprev:
762 762 stopped = True
763 763 else:
764 764 chain.append(iterrev)
765 765 stopped = False
766 766
767 767 chain.reverse()
768 768 return chain, stopped
769 769
770 770 def ancestors(self, revs, stoprev=0, inclusive=False):
771 771 """Generate the ancestors of 'revs' in reverse revision order.
772 772 Does not generate revs lower than stoprev.
773 773
774 774 See the documentation for ancestor.lazyancestors for more details."""
775 775
776 776 # first, make sure start revisions aren't filtered
777 777 revs = list(revs)
778 778 checkrev = self.node
779 779 for r in revs:
780 780 checkrev(r)
781 781 # and we're sure ancestors aren't filtered as well
782 782 if util.safehasattr(parsers, 'rustlazyancestors'):
783 783 return ancestor.rustlazyancestors(
784 784 self.index, revs,
785 785 stoprev=stoprev, inclusive=inclusive)
786 786 return ancestor.lazyancestors(self._uncheckedparentrevs, revs,
787 787 stoprev=stoprev, inclusive=inclusive)
788 788
789 789 def descendants(self, revs):
790 790 return dagop.descendantrevs(revs, self.revs, self.parentrevs)
791 791
792 792 def findcommonmissing(self, common=None, heads=None):
793 793 """Return a tuple of the ancestors of common and the ancestors of heads
794 794 that are not ancestors of common. In revset terminology, we return the
795 795 tuple:
796 796
797 797 ::common, (::heads) - (::common)
798 798
799 799 The list is sorted by revision number, meaning it is
800 800 topologically sorted.
801 801
802 802 'heads' and 'common' are both lists of node IDs. If heads is
803 803 not supplied, uses all of the revlog's heads. If common is not
804 804 supplied, uses nullid."""
805 805 if common is None:
806 806 common = [nullid]
807 807 if heads is None:
808 808 heads = self.heads()
809 809
810 810 common = [self.rev(n) for n in common]
811 811 heads = [self.rev(n) for n in heads]
812 812
813 813 # we want the ancestors, but inclusive
814 814 class lazyset(object):
815 815 def __init__(self, lazyvalues):
816 816 self.addedvalues = set()
817 817 self.lazyvalues = lazyvalues
818 818
819 819 def __contains__(self, value):
820 820 return value in self.addedvalues or value in self.lazyvalues
821 821
822 822 def __iter__(self):
823 823 added = self.addedvalues
824 824 for r in added:
825 825 yield r
826 826 for r in self.lazyvalues:
827 827 if not r in added:
828 828 yield r
829 829
830 830 def add(self, value):
831 831 self.addedvalues.add(value)
832 832
833 833 def update(self, values):
834 834 self.addedvalues.update(values)
835 835
836 836 has = lazyset(self.ancestors(common))
837 837 has.add(nullrev)
838 838 has.update(common)
839 839
840 840 # take all ancestors from heads that aren't in has
841 841 missing = set()
842 842 visit = collections.deque(r for r in heads if r not in has)
843 843 while visit:
844 844 r = visit.popleft()
845 845 if r in missing:
846 846 continue
847 847 else:
848 848 missing.add(r)
849 849 for p in self.parentrevs(r):
850 850 if p not in has:
851 851 visit.append(p)
852 852 missing = list(missing)
853 853 missing.sort()
854 854 return has, [self.node(miss) for miss in missing]
855 855
856 856 def incrementalmissingrevs(self, common=None):
857 857 """Return an object that can be used to incrementally compute the
858 858 revision numbers of the ancestors of arbitrary sets that are not
859 859 ancestors of common. This is an ancestor.incrementalmissingancestors
860 860 object.
861 861
862 862 'common' is a list of revision numbers. If common is not supplied, uses
863 863 nullrev.
864 864 """
865 865 if common is None:
866 866 common = [nullrev]
867 867
868 868 return ancestor.incrementalmissingancestors(self.parentrevs, common)
869 869
870 870 def findmissingrevs(self, common=None, heads=None):
871 871 """Return the revision numbers of the ancestors of heads that
872 872 are not ancestors of common.
873 873
874 874 More specifically, return a list of revision numbers corresponding to
875 875 nodes N such that every N satisfies the following constraints:
876 876
877 877 1. N is an ancestor of some node in 'heads'
878 878 2. N is not an ancestor of any node in 'common'
879 879
880 880 The list is sorted by revision number, meaning it is
881 881 topologically sorted.
882 882
883 883 'heads' and 'common' are both lists of revision numbers. If heads is
884 884 not supplied, uses all of the revlog's heads. If common is not
885 885 supplied, uses nullid."""
886 886 if common is None:
887 887 common = [nullrev]
888 888 if heads is None:
889 889 heads = self.headrevs()
890 890
891 891 inc = self.incrementalmissingrevs(common=common)
892 892 return inc.missingancestors(heads)
893 893
894 894 def findmissing(self, common=None, heads=None):
895 895 """Return the ancestors of heads that are not ancestors of common.
896 896
897 897 More specifically, return a list of nodes N such that every N
898 898 satisfies the following constraints:
899 899
900 900 1. N is an ancestor of some node in 'heads'
901 901 2. N is not an ancestor of any node in 'common'
902 902
903 903 The list is sorted by revision number, meaning it is
904 904 topologically sorted.
905 905
906 906 'heads' and 'common' are both lists of node IDs. If heads is
907 907 not supplied, uses all of the revlog's heads. If common is not
908 908 supplied, uses nullid."""
909 909 if common is None:
910 910 common = [nullid]
911 911 if heads is None:
912 912 heads = self.heads()
913 913
914 914 common = [self.rev(n) for n in common]
915 915 heads = [self.rev(n) for n in heads]
916 916
917 917 inc = self.incrementalmissingrevs(common=common)
918 918 return [self.node(r) for r in inc.missingancestors(heads)]
919 919
920 920 def nodesbetween(self, roots=None, heads=None):
921 921 """Return a topological path from 'roots' to 'heads'.
922 922
923 923 Return a tuple (nodes, outroots, outheads) where 'nodes' is a
924 924 topologically sorted list of all nodes N that satisfy both of
925 925 these constraints:
926 926
927 927 1. N is a descendant of some node in 'roots'
928 928 2. N is an ancestor of some node in 'heads'
929 929
930 930 Every node is considered to be both a descendant and an ancestor
931 931 of itself, so every reachable node in 'roots' and 'heads' will be
932 932 included in 'nodes'.
933 933
934 934 'outroots' is the list of reachable nodes in 'roots', i.e., the
935 935 subset of 'roots' that is returned in 'nodes'. Likewise,
936 936 'outheads' is the subset of 'heads' that is also in 'nodes'.
937 937
938 938 'roots' and 'heads' are both lists of node IDs. If 'roots' is
939 939 unspecified, uses nullid as the only root. If 'heads' is
940 940 unspecified, uses list of all of the revlog's heads."""
941 941 nonodes = ([], [], [])
942 942 if roots is not None:
943 943 roots = list(roots)
944 944 if not roots:
945 945 return nonodes
946 946 lowestrev = min([self.rev(n) for n in roots])
947 947 else:
948 948 roots = [nullid] # Everybody's a descendant of nullid
949 949 lowestrev = nullrev
950 950 if (lowestrev == nullrev) and (heads is None):
951 951 # We want _all_ the nodes!
952 952 return ([self.node(r) for r in self], [nullid], list(self.heads()))
953 953 if heads is None:
954 954 # All nodes are ancestors, so the latest ancestor is the last
955 955 # node.
956 956 highestrev = len(self) - 1
957 957 # Set ancestors to None to signal that every node is an ancestor.
958 958 ancestors = None
959 959 # Set heads to an empty dictionary for later discovery of heads
960 960 heads = {}
961 961 else:
962 962 heads = list(heads)
963 963 if not heads:
964 964 return nonodes
965 965 ancestors = set()
966 966 # Turn heads into a dictionary so we can remove 'fake' heads.
967 967 # Also, later we will be using it to filter out the heads we can't
968 968 # find from roots.
969 969 heads = dict.fromkeys(heads, False)
970 970 # Start at the top and keep marking parents until we're done.
971 971 nodestotag = set(heads)
972 972 # Remember where the top was so we can use it as a limit later.
973 973 highestrev = max([self.rev(n) for n in nodestotag])
974 974 while nodestotag:
975 975 # grab a node to tag
976 976 n = nodestotag.pop()
977 977 # Never tag nullid
978 978 if n == nullid:
979 979 continue
980 980 # A node's revision number represents its place in a
981 981 # topologically sorted list of nodes.
982 982 r = self.rev(n)
983 983 if r >= lowestrev:
984 984 if n not in ancestors:
985 985 # If we are possibly a descendant of one of the roots
986 986 # and we haven't already been marked as an ancestor
987 987 ancestors.add(n) # Mark as ancestor
988 988 # Add non-nullid parents to list of nodes to tag.
989 989 nodestotag.update([p for p in self.parents(n) if
990 990 p != nullid])
991 991 elif n in heads: # We've seen it before, is it a fake head?
992 992 # So it is, real heads should not be the ancestors of
993 993 # any other heads.
994 994 heads.pop(n)
995 995 if not ancestors:
996 996 return nonodes
997 997 # Now that we have our set of ancestors, we want to remove any
998 998 # roots that are not ancestors.
999 999
1000 1000 # If one of the roots was nullid, everything is included anyway.
1001 1001 if lowestrev > nullrev:
1002 1002 # But, since we weren't, let's recompute the lowest rev to not
1003 1003 # include roots that aren't ancestors.
1004 1004
1005 1005 # Filter out roots that aren't ancestors of heads
1006 1006 roots = [root for root in roots if root in ancestors]
1007 1007 # Recompute the lowest revision
1008 1008 if roots:
1009 1009 lowestrev = min([self.rev(root) for root in roots])
1010 1010 else:
1011 1011 # No more roots? Return empty list
1012 1012 return nonodes
1013 1013 else:
1014 1014 # We are descending from nullid, and don't need to care about
1015 1015 # any other roots.
1016 1016 lowestrev = nullrev
1017 1017 roots = [nullid]
1018 1018 # Transform our roots list into a set.
1019 1019 descendants = set(roots)
1020 1020 # Also, keep the original roots so we can filter out roots that aren't
1021 1021 # 'real' roots (i.e. are descended from other roots).
1022 1022 roots = descendants.copy()
1023 1023 # Our topologically sorted list of output nodes.
1024 1024 orderedout = []
1025 1025 # Don't start at nullid since we don't want nullid in our output list,
1026 1026 # and if nullid shows up in descendants, empty parents will look like
1027 1027 # they're descendants.
1028 1028 for r in self.revs(start=max(lowestrev, 0), stop=highestrev + 1):
1029 1029 n = self.node(r)
1030 1030 isdescendant = False
1031 1031 if lowestrev == nullrev: # Everybody is a descendant of nullid
1032 1032 isdescendant = True
1033 1033 elif n in descendants:
1034 1034 # n is already a descendant
1035 1035 isdescendant = True
1036 1036 # This check only needs to be done here because all the roots
1037 1037 # will start being marked is descendants before the loop.
1038 1038 if n in roots:
1039 1039 # If n was a root, check if it's a 'real' root.
1040 1040 p = tuple(self.parents(n))
1041 1041 # If any of its parents are descendants, it's not a root.
1042 1042 if (p[0] in descendants) or (p[1] in descendants):
1043 1043 roots.remove(n)
1044 1044 else:
1045 1045 p = tuple(self.parents(n))
1046 1046 # A node is a descendant if either of its parents are
1047 1047 # descendants. (We seeded the dependents list with the roots
1048 1048 # up there, remember?)
1049 1049 if (p[0] in descendants) or (p[1] in descendants):
1050 1050 descendants.add(n)
1051 1051 isdescendant = True
1052 1052 if isdescendant and ((ancestors is None) or (n in ancestors)):
1053 1053 # Only include nodes that are both descendants and ancestors.
1054 1054 orderedout.append(n)
1055 1055 if (ancestors is not None) and (n in heads):
1056 1056 # We're trying to figure out which heads are reachable
1057 1057 # from roots.
1058 1058 # Mark this head as having been reached
1059 1059 heads[n] = True
1060 1060 elif ancestors is None:
1061 1061 # Otherwise, we're trying to discover the heads.
1062 1062 # Assume this is a head because if it isn't, the next step
1063 1063 # will eventually remove it.
1064 1064 heads[n] = True
1065 1065 # But, obviously its parents aren't.
1066 1066 for p in self.parents(n):
1067 1067 heads.pop(p, None)
1068 1068 heads = [head for head, flag in heads.iteritems() if flag]
1069 1069 roots = list(roots)
1070 1070 assert orderedout
1071 1071 assert roots
1072 1072 assert heads
1073 1073 return (orderedout, roots, heads)
1074 1074
1075 1075 def headrevs(self):
1076 1076 try:
1077 1077 return self.index.headrevs()
1078 1078 except AttributeError:
1079 1079 return self._headrevs()
1080 1080
1081 1081 def computephases(self, roots):
1082 1082 return self.index.computephasesmapsets(roots)
1083 1083
1084 1084 def _headrevs(self):
1085 1085 count = len(self)
1086 1086 if not count:
1087 1087 return [nullrev]
1088 1088 # we won't iter over filtered rev so nobody is a head at start
1089 1089 ishead = [0] * (count + 1)
1090 1090 index = self.index
1091 1091 for r in self:
1092 1092 ishead[r] = 1 # I may be an head
1093 1093 e = index[r]
1094 1094 ishead[e[5]] = ishead[e[6]] = 0 # my parent are not
1095 1095 return [r for r, val in enumerate(ishead) if val]
1096 1096
1097 1097 def heads(self, start=None, stop=None):
1098 1098 """return the list of all nodes that have no children
1099 1099
1100 1100 if start is specified, only heads that are descendants of
1101 1101 start will be returned
1102 1102 if stop is specified, it will consider all the revs from stop
1103 1103 as if they had no children
1104 1104 """
1105 1105 if start is None and stop is None:
1106 1106 if not len(self):
1107 1107 return [nullid]
1108 1108 return [self.node(r) for r in self.headrevs()]
1109 1109
1110 1110 if start is None:
1111 1111 start = nullrev
1112 1112 else:
1113 1113 start = self.rev(start)
1114 1114
1115 1115 stoprevs = set(self.rev(n) for n in stop or [])
1116 1116
1117 1117 revs = dagop.headrevssubset(self.revs, self.parentrevs, startrev=start,
1118 1118 stoprevs=stoprevs)
1119 1119
1120 1120 return [self.node(rev) for rev in revs]
1121 1121
1122 1122 def children(self, node):
1123 1123 """find the children of a given node"""
1124 1124 c = []
1125 1125 p = self.rev(node)
1126 1126 for r in self.revs(start=p + 1):
1127 1127 prevs = [pr for pr in self.parentrevs(r) if pr != nullrev]
1128 1128 if prevs:
1129 1129 for pr in prevs:
1130 1130 if pr == p:
1131 1131 c.append(self.node(r))
1132 1132 elif p == nullrev:
1133 1133 c.append(self.node(r))
1134 1134 return c
1135 1135
1136 1136 def commonancestorsheads(self, a, b):
1137 1137 """calculate all the heads of the common ancestors of nodes a and b"""
1138 1138 a, b = self.rev(a), self.rev(b)
1139 1139 ancs = self._commonancestorsheads(a, b)
1140 1140 return pycompat.maplist(self.node, ancs)
1141 1141
1142 1142 def _commonancestorsheads(self, *revs):
1143 1143 """calculate all the heads of the common ancestors of revs"""
1144 1144 try:
1145 1145 ancs = self.index.commonancestorsheads(*revs)
1146 1146 except (AttributeError, OverflowError): # C implementation failed
1147 1147 ancs = ancestor.commonancestorsheads(self.parentrevs, *revs)
1148 1148 return ancs
1149 1149
1150 1150 def isancestor(self, a, b):
1151 1151 """return True if node a is an ancestor of node b
1152 1152
1153 1153 A revision is considered an ancestor of itself."""
1154 1154 a, b = self.rev(a), self.rev(b)
1155 1155 return self.isancestorrev(a, b)
1156 1156
1157 1157 def isancestorrev(self, a, b):
1158 1158 """return True if revision a is an ancestor of revision b
1159 1159
1160 1160 A revision is considered an ancestor of itself.
1161 1161
1162 1162 The implementation of this is trivial but the use of
1163 1163 commonancestorsheads is not."""
1164 1164 if a == nullrev:
1165 1165 return True
1166 1166 elif a == b:
1167 1167 return True
1168 1168 elif a > b:
1169 1169 return False
1170 1170 return a in self._commonancestorsheads(a, b)
1171 1171
1172 1172 def ancestor(self, a, b):
1173 1173 """calculate the "best" common ancestor of nodes a and b"""
1174 1174
1175 1175 a, b = self.rev(a), self.rev(b)
1176 1176 try:
1177 1177 ancs = self.index.ancestors(a, b)
1178 1178 except (AttributeError, OverflowError):
1179 1179 ancs = ancestor.ancestors(self.parentrevs, a, b)
1180 1180 if ancs:
1181 1181 # choose a consistent winner when there's a tie
1182 1182 return min(map(self.node, ancs))
1183 1183 return nullid
1184 1184
1185 1185 def _match(self, id):
1186 1186 if isinstance(id, int):
1187 1187 # rev
1188 1188 return self.node(id)
1189 1189 if len(id) == 20:
1190 1190 # possibly a binary node
1191 1191 # odds of a binary node being all hex in ASCII are 1 in 10**25
1192 1192 try:
1193 1193 node = id
1194 1194 self.rev(node) # quick search the index
1195 1195 return node
1196 1196 except error.LookupError:
1197 1197 pass # may be partial hex id
1198 1198 try:
1199 1199 # str(rev)
1200 1200 rev = int(id)
1201 1201 if "%d" % rev != id:
1202 1202 raise ValueError
1203 1203 if rev < 0:
1204 1204 rev = len(self) + rev
1205 1205 if rev < 0 or rev >= len(self):
1206 1206 raise ValueError
1207 1207 return self.node(rev)
1208 1208 except (ValueError, OverflowError):
1209 1209 pass
1210 1210 if len(id) == 40:
1211 1211 try:
1212 1212 # a full hex nodeid?
1213 1213 node = bin(id)
1214 1214 self.rev(node)
1215 1215 return node
1216 1216 except (TypeError, error.LookupError):
1217 1217 pass
1218 1218
1219 1219 def _partialmatch(self, id):
1220 1220 # we don't care wdirfilenodeids as they should be always full hash
1221 1221 maybewdir = wdirhex.startswith(id)
1222 1222 try:
1223 1223 partial = self.index.partialmatch(id)
1224 1224 if partial and self.hasnode(partial):
1225 1225 if maybewdir:
1226 1226 # single 'ff...' match in radix tree, ambiguous with wdir
1227 1227 raise error.RevlogError
1228 1228 return partial
1229 1229 if maybewdir:
1230 1230 # no 'ff...' match in radix tree, wdir identified
1231 1231 raise error.WdirUnsupported
1232 1232 return None
1233 1233 except error.RevlogError:
1234 1234 # parsers.c radix tree lookup gave multiple matches
1235 1235 # fast path: for unfiltered changelog, radix tree is accurate
1236 1236 if not getattr(self, 'filteredrevs', None):
1237 1237 raise error.AmbiguousPrefixLookupError(
1238 1238 id, self.indexfile, _('ambiguous identifier'))
1239 1239 # fall through to slow path that filters hidden revisions
1240 1240 except (AttributeError, ValueError):
1241 1241 # we are pure python, or key was too short to search radix tree
1242 1242 pass
1243 1243
1244 1244 if id in self._pcache:
1245 1245 return self._pcache[id]
1246 1246
1247 1247 if len(id) <= 40:
1248 1248 try:
1249 1249 # hex(node)[:...]
1250 1250 l = len(id) // 2 # grab an even number of digits
1251 1251 prefix = bin(id[:l * 2])
1252 1252 nl = [e[7] for e in self.index if e[7].startswith(prefix)]
1253 1253 nl = [n for n in nl if hex(n).startswith(id) and
1254 1254 self.hasnode(n)]
1255 1255 if nullhex.startswith(id):
1256 1256 nl.append(nullid)
1257 1257 if len(nl) > 0:
1258 1258 if len(nl) == 1 and not maybewdir:
1259 1259 self._pcache[id] = nl[0]
1260 1260 return nl[0]
1261 1261 raise error.AmbiguousPrefixLookupError(
1262 1262 id, self.indexfile, _('ambiguous identifier'))
1263 1263 if maybewdir:
1264 1264 raise error.WdirUnsupported
1265 1265 return None
1266 1266 except TypeError:
1267 1267 pass
1268 1268
1269 1269 def lookup(self, id):
1270 1270 """locate a node based on:
1271 1271 - revision number or str(revision number)
1272 1272 - nodeid or subset of hex nodeid
1273 1273 """
1274 1274 n = self._match(id)
1275 1275 if n is not None:
1276 1276 return n
1277 1277 n = self._partialmatch(id)
1278 1278 if n:
1279 1279 return n
1280 1280
1281 1281 raise error.LookupError(id, self.indexfile, _('no match found'))
1282 1282
1283 1283 def shortest(self, node, minlength=1):
1284 1284 """Find the shortest unambiguous prefix that matches node."""
1285 1285 def isvalid(prefix):
1286 1286 try:
1287 1287 node = self._partialmatch(prefix)
1288 1288 except error.AmbiguousPrefixLookupError:
1289 1289 return False
1290 1290 except error.WdirUnsupported:
1291 1291 # single 'ff...' match
1292 1292 return True
1293 1293 if node is None:
1294 1294 raise error.LookupError(node, self.indexfile, _('no node'))
1295 1295 return True
1296 1296
1297 1297 def maybewdir(prefix):
1298 1298 return all(c == 'f' for c in prefix)
1299 1299
1300 1300 hexnode = hex(node)
1301 1301
1302 1302 def disambiguate(hexnode, minlength):
1303 1303 """Disambiguate against wdirid."""
1304 1304 for length in range(minlength, 41):
1305 1305 prefix = hexnode[:length]
1306 1306 if not maybewdir(prefix):
1307 1307 return prefix
1308 1308
1309 1309 if not getattr(self, 'filteredrevs', None):
1310 1310 try:
1311 1311 length = max(self.index.shortest(node), minlength)
1312 1312 return disambiguate(hexnode, length)
1313 1313 except error.RevlogError:
1314 1314 if node != wdirid:
1315 1315 raise error.LookupError(node, self.indexfile, _('no node'))
1316 1316 except AttributeError:
1317 1317 # Fall through to pure code
1318 1318 pass
1319 1319
1320 1320 if node == wdirid:
1321 1321 for length in range(minlength, 41):
1322 1322 prefix = hexnode[:length]
1323 1323 if isvalid(prefix):
1324 1324 return prefix
1325 1325
1326 1326 for length in range(minlength, 41):
1327 1327 prefix = hexnode[:length]
1328 1328 if isvalid(prefix):
1329 1329 return disambiguate(hexnode, length)
1330 1330
1331 1331 def cmp(self, node, text):
1332 1332 """compare text with a given file revision
1333 1333
1334 1334 returns True if text is different than what is stored.
1335 1335 """
1336 1336 p1, p2 = self.parents(node)
1337 1337 return storageutil.hashrevisionsha1(text, p1, p2) != node
1338 1338
1339 1339 def _cachesegment(self, offset, data):
1340 1340 """Add a segment to the revlog cache.
1341 1341
1342 1342 Accepts an absolute offset and the data that is at that location.
1343 1343 """
1344 1344 o, d = self._chunkcache
1345 1345 # try to add to existing cache
1346 1346 if o + len(d) == offset and len(d) + len(data) < _chunksize:
1347 1347 self._chunkcache = o, d + data
1348 1348 else:
1349 1349 self._chunkcache = offset, data
1350 1350
1351 1351 def _readsegment(self, offset, length, df=None):
1352 1352 """Load a segment of raw data from the revlog.
1353 1353
1354 1354 Accepts an absolute offset, length to read, and an optional existing
1355 1355 file handle to read from.
1356 1356
1357 1357 If an existing file handle is passed, it will be seeked and the
1358 1358 original seek position will NOT be restored.
1359 1359
1360 1360 Returns a str or buffer of raw byte data.
1361 1361
1362 1362 Raises if the requested number of bytes could not be read.
1363 1363 """
1364 1364 # Cache data both forward and backward around the requested
1365 1365 # data, in a fixed size window. This helps speed up operations
1366 1366 # involving reading the revlog backwards.
1367 1367 cachesize = self._chunkcachesize
1368 1368 realoffset = offset & ~(cachesize - 1)
1369 1369 reallength = (((offset + length + cachesize) & ~(cachesize - 1))
1370 1370 - realoffset)
1371 1371 with self._datareadfp(df) as df:
1372 1372 df.seek(realoffset)
1373 1373 d = df.read(reallength)
1374 1374
1375 1375 self._cachesegment(realoffset, d)
1376 1376 if offset != realoffset or reallength != length:
1377 1377 startoffset = offset - realoffset
1378 1378 if len(d) - startoffset < length:
1379 1379 raise error.RevlogError(
1380 1380 _('partial read of revlog %s; expected %d bytes from '
1381 1381 'offset %d, got %d') %
1382 1382 (self.indexfile if self._inline else self.datafile,
1383 1383 length, realoffset, len(d) - startoffset))
1384 1384
1385 1385 return util.buffer(d, startoffset, length)
1386 1386
1387 1387 if len(d) < length:
1388 1388 raise error.RevlogError(
1389 1389 _('partial read of revlog %s; expected %d bytes from offset '
1390 1390 '%d, got %d') %
1391 1391 (self.indexfile if self._inline else self.datafile,
1392 1392 length, offset, len(d)))
1393 1393
1394 1394 return d
1395 1395
1396 1396 def _getsegment(self, offset, length, df=None):
1397 1397 """Obtain a segment of raw data from the revlog.
1398 1398
1399 1399 Accepts an absolute offset, length of bytes to obtain, and an
1400 1400 optional file handle to the already-opened revlog. If the file
1401 1401 handle is used, it's original seek position will not be preserved.
1402 1402
1403 1403 Requests for data may be returned from a cache.
1404 1404
1405 1405 Returns a str or a buffer instance of raw byte data.
1406 1406 """
1407 1407 o, d = self._chunkcache
1408 1408 l = len(d)
1409 1409
1410 1410 # is it in the cache?
1411 1411 cachestart = offset - o
1412 1412 cacheend = cachestart + length
1413 1413 if cachestart >= 0 and cacheend <= l:
1414 1414 if cachestart == 0 and cacheend == l:
1415 1415 return d # avoid a copy
1416 1416 return util.buffer(d, cachestart, cacheend - cachestart)
1417 1417
1418 1418 return self._readsegment(offset, length, df=df)
1419 1419
1420 1420 def _getsegmentforrevs(self, startrev, endrev, df=None):
1421 1421 """Obtain a segment of raw data corresponding to a range of revisions.
1422 1422
1423 1423 Accepts the start and end revisions and an optional already-open
1424 1424 file handle to be used for reading. If the file handle is read, its
1425 1425 seek position will not be preserved.
1426 1426
1427 1427 Requests for data may be satisfied by a cache.
1428 1428
1429 1429 Returns a 2-tuple of (offset, data) for the requested range of
1430 1430 revisions. Offset is the integer offset from the beginning of the
1431 1431 revlog and data is a str or buffer of the raw byte data.
1432 1432
1433 1433 Callers will need to call ``self.start(rev)`` and ``self.length(rev)``
1434 1434 to determine where each revision's data begins and ends.
1435 1435 """
1436 1436 # Inlined self.start(startrev) & self.end(endrev) for perf reasons
1437 1437 # (functions are expensive).
1438 1438 index = self.index
1439 1439 istart = index[startrev]
1440 1440 start = int(istart[0] >> 16)
1441 1441 if startrev == endrev:
1442 1442 end = start + istart[1]
1443 1443 else:
1444 1444 iend = index[endrev]
1445 1445 end = int(iend[0] >> 16) + iend[1]
1446 1446
1447 1447 if self._inline:
1448 1448 start += (startrev + 1) * self._io.size
1449 1449 end += (endrev + 1) * self._io.size
1450 1450 length = end - start
1451 1451
1452 1452 return start, self._getsegment(start, length, df=df)
1453 1453
1454 1454 def _chunk(self, rev, df=None):
1455 1455 """Obtain a single decompressed chunk for a revision.
1456 1456
1457 1457 Accepts an integer revision and an optional already-open file handle
1458 1458 to be used for reading. If used, the seek position of the file will not
1459 1459 be preserved.
1460 1460
1461 1461 Returns a str holding uncompressed data for the requested revision.
1462 1462 """
1463 1463 return self.decompress(self._getsegmentforrevs(rev, rev, df=df)[1])
1464 1464
1465 1465 def _chunks(self, revs, df=None, targetsize=None):
1466 1466 """Obtain decompressed chunks for the specified revisions.
1467 1467
1468 1468 Accepts an iterable of numeric revisions that are assumed to be in
1469 1469 ascending order. Also accepts an optional already-open file handle
1470 1470 to be used for reading. If used, the seek position of the file will
1471 1471 not be preserved.
1472 1472
1473 1473 This function is similar to calling ``self._chunk()`` multiple times,
1474 1474 but is faster.
1475 1475
1476 1476 Returns a list with decompressed data for each requested revision.
1477 1477 """
1478 1478 if not revs:
1479 1479 return []
1480 1480 start = self.start
1481 1481 length = self.length
1482 1482 inline = self._inline
1483 1483 iosize = self._io.size
1484 1484 buffer = util.buffer
1485 1485
1486 1486 l = []
1487 1487 ladd = l.append
1488 1488
1489 1489 if not self._withsparseread:
1490 1490 slicedchunks = (revs,)
1491 1491 else:
1492 1492 slicedchunks = deltautil.slicechunk(self, revs,
1493 1493 targetsize=targetsize)
1494 1494
1495 1495 for revschunk in slicedchunks:
1496 1496 firstrev = revschunk[0]
1497 1497 # Skip trailing revisions with empty diff
1498 1498 for lastrev in revschunk[::-1]:
1499 1499 if length(lastrev) != 0:
1500 1500 break
1501 1501
1502 1502 try:
1503 1503 offset, data = self._getsegmentforrevs(firstrev, lastrev, df=df)
1504 1504 except OverflowError:
1505 1505 # issue4215 - we can't cache a run of chunks greater than
1506 1506 # 2G on Windows
1507 1507 return [self._chunk(rev, df=df) for rev in revschunk]
1508 1508
1509 1509 decomp = self.decompress
1510 1510 for rev in revschunk:
1511 1511 chunkstart = start(rev)
1512 1512 if inline:
1513 1513 chunkstart += (rev + 1) * iosize
1514 1514 chunklength = length(rev)
1515 1515 ladd(decomp(buffer(data, chunkstart - offset, chunklength)))
1516 1516
1517 1517 return l
1518 1518
1519 1519 def _chunkclear(self):
1520 1520 """Clear the raw chunk cache."""
1521 1521 self._chunkcache = (0, '')
1522 1522
1523 1523 def deltaparent(self, rev):
1524 1524 """return deltaparent of the given revision"""
1525 1525 base = self.index[rev][3]
1526 1526 if base == rev:
1527 1527 return nullrev
1528 1528 elif self._generaldelta:
1529 1529 return base
1530 1530 else:
1531 1531 return rev - 1
1532 1532
1533 1533 def issnapshot(self, rev):
1534 1534 """tells whether rev is a snapshot
1535 1535 """
1536 1536 if rev == nullrev:
1537 1537 return True
1538 deltap = self.deltaparent(rev)
1539 if deltap == nullrev:
1538 entry = self.index[rev]
1539 base = entry[3]
1540 if base == rev:
1540 1541 return True
1541 1542 elif not self._sparserevlog:
1542 1543 return False
1543 p1, p2 = self.parentrevs(rev)
1544 if deltap in (p1, p2):
1544 if base == nullrev:
1545 return True
1546 p1 = entry[5]
1547 p2 = entry[6]
1548 if base == p1 or base == p2:
1545 1549 return False
1546 return self.issnapshot(deltap)
1550 return self.issnapshot(base)
1547 1551
1548 1552 def snapshotdepth(self, rev):
1549 1553 """number of snapshot in the chain before this one"""
1550 1554 if not self.issnapshot(rev):
1551 1555 raise error.ProgrammingError('revision %d not a snapshot')
1552 1556 return len(self._deltachain(rev)[0]) - 1
1553 1557
1554 1558 def revdiff(self, rev1, rev2):
1555 1559 """return or calculate a delta between two revisions
1556 1560
1557 1561 The delta calculated is in binary form and is intended to be written to
1558 1562 revlog data directly. So this function needs raw revision data.
1559 1563 """
1560 1564 if rev1 != nullrev and self.deltaparent(rev2) == rev1:
1561 1565 return bytes(self._chunk(rev2))
1562 1566
1563 1567 return mdiff.textdiff(self.revision(rev1, raw=True),
1564 1568 self.revision(rev2, raw=True))
1565 1569
1566 1570 def revision(self, nodeorrev, _df=None, raw=False):
1567 1571 """return an uncompressed revision of a given node or revision
1568 1572 number.
1569 1573
1570 1574 _df - an existing file handle to read from. (internal-only)
1571 1575 raw - an optional argument specifying if the revision data is to be
1572 1576 treated as raw data when applying flag transforms. 'raw' should be set
1573 1577 to True when generating changegroups or in debug commands.
1574 1578 """
1575 1579 if isinstance(nodeorrev, int):
1576 1580 rev = nodeorrev
1577 1581 node = self.node(rev)
1578 1582 else:
1579 1583 node = nodeorrev
1580 1584 rev = None
1581 1585
1582 1586 cachedrev = None
1583 1587 flags = None
1584 1588 rawtext = None
1585 1589 if node == nullid:
1586 1590 return ""
1587 1591 if self._revisioncache:
1588 1592 if self._revisioncache[0] == node:
1589 1593 # _cache only stores rawtext
1590 1594 if raw:
1591 1595 return self._revisioncache[2]
1592 1596 # duplicated, but good for perf
1593 1597 if rev is None:
1594 1598 rev = self.rev(node)
1595 1599 if flags is None:
1596 1600 flags = self.flags(rev)
1597 1601 # no extra flags set, no flag processor runs, text = rawtext
1598 1602 if flags == REVIDX_DEFAULT_FLAGS:
1599 1603 return self._revisioncache[2]
1600 1604 # rawtext is reusable. need to run flag processor
1601 1605 rawtext = self._revisioncache[2]
1602 1606
1603 1607 cachedrev = self._revisioncache[1]
1604 1608
1605 1609 # look up what we need to read
1606 1610 if rawtext is None:
1607 1611 if rev is None:
1608 1612 rev = self.rev(node)
1609 1613
1610 1614 chain, stopped = self._deltachain(rev, stoprev=cachedrev)
1611 1615 if stopped:
1612 1616 rawtext = self._revisioncache[2]
1613 1617
1614 1618 # drop cache to save memory
1615 1619 self._revisioncache = None
1616 1620
1617 1621 targetsize = None
1618 1622 rawsize = self.index[rev][2]
1619 1623 if 0 <= rawsize:
1620 1624 targetsize = 4 * rawsize
1621 1625
1622 1626 bins = self._chunks(chain, df=_df, targetsize=targetsize)
1623 1627 if rawtext is None:
1624 1628 rawtext = bytes(bins[0])
1625 1629 bins = bins[1:]
1626 1630
1627 1631 rawtext = mdiff.patches(rawtext, bins)
1628 1632 self._revisioncache = (node, rev, rawtext)
1629 1633
1630 1634 if flags is None:
1631 1635 if rev is None:
1632 1636 rev = self.rev(node)
1633 1637 flags = self.flags(rev)
1634 1638
1635 1639 text, validatehash = self._processflags(rawtext, flags, 'read', raw=raw)
1636 1640 if validatehash:
1637 1641 self.checkhash(text, node, rev=rev)
1638 1642
1639 1643 return text
1640 1644
1641 1645 def hash(self, text, p1, p2):
1642 1646 """Compute a node hash.
1643 1647
1644 1648 Available as a function so that subclasses can replace the hash
1645 1649 as needed.
1646 1650 """
1647 1651 return storageutil.hashrevisionsha1(text, p1, p2)
1648 1652
1649 1653 def _processflags(self, text, flags, operation, raw=False):
1650 1654 """Inspect revision data flags and applies transforms defined by
1651 1655 registered flag processors.
1652 1656
1653 1657 ``text`` - the revision data to process
1654 1658 ``flags`` - the revision flags
1655 1659 ``operation`` - the operation being performed (read or write)
1656 1660 ``raw`` - an optional argument describing if the raw transform should be
1657 1661 applied.
1658 1662
1659 1663 This method processes the flags in the order (or reverse order if
1660 1664 ``operation`` is 'write') defined by REVIDX_FLAGS_ORDER, applying the
1661 1665 flag processors registered for present flags. The order of flags defined
1662 1666 in REVIDX_FLAGS_ORDER needs to be stable to allow non-commutativity.
1663 1667
1664 1668 Returns a 2-tuple of ``(text, validatehash)`` where ``text`` is the
1665 1669 processed text and ``validatehash`` is a bool indicating whether the
1666 1670 returned text should be checked for hash integrity.
1667 1671
1668 1672 Note: If the ``raw`` argument is set, it has precedence over the
1669 1673 operation and will only update the value of ``validatehash``.
1670 1674 """
1671 1675 # fast path: no flag processors will run
1672 1676 if flags == 0:
1673 1677 return text, True
1674 1678 if not operation in ('read', 'write'):
1675 1679 raise error.ProgrammingError(_("invalid '%s' operation") %
1676 1680 operation)
1677 1681 # Check all flags are known.
1678 1682 if flags & ~REVIDX_KNOWN_FLAGS:
1679 1683 raise error.RevlogError(_("incompatible revision flag '%#x'") %
1680 1684 (flags & ~REVIDX_KNOWN_FLAGS))
1681 1685 validatehash = True
1682 1686 # Depending on the operation (read or write), the order might be
1683 1687 # reversed due to non-commutative transforms.
1684 1688 orderedflags = REVIDX_FLAGS_ORDER
1685 1689 if operation == 'write':
1686 1690 orderedflags = reversed(orderedflags)
1687 1691
1688 1692 for flag in orderedflags:
1689 1693 # If a flagprocessor has been registered for a known flag, apply the
1690 1694 # related operation transform and update result tuple.
1691 1695 if flag & flags:
1692 1696 vhash = True
1693 1697
1694 1698 if flag not in self._flagprocessors:
1695 1699 message = _("missing processor for flag '%#x'") % (flag)
1696 1700 raise error.RevlogError(message)
1697 1701
1698 1702 processor = self._flagprocessors[flag]
1699 1703 if processor is not None:
1700 1704 readtransform, writetransform, rawtransform = processor
1701 1705
1702 1706 if raw:
1703 1707 vhash = rawtransform(self, text)
1704 1708 elif operation == 'read':
1705 1709 text, vhash = readtransform(self, text)
1706 1710 else: # write operation
1707 1711 text, vhash = writetransform(self, text)
1708 1712 validatehash = validatehash and vhash
1709 1713
1710 1714 return text, validatehash
1711 1715
1712 1716 def checkhash(self, text, node, p1=None, p2=None, rev=None):
1713 1717 """Check node hash integrity.
1714 1718
1715 1719 Available as a function so that subclasses can extend hash mismatch
1716 1720 behaviors as needed.
1717 1721 """
1718 1722 try:
1719 1723 if p1 is None and p2 is None:
1720 1724 p1, p2 = self.parents(node)
1721 1725 if node != self.hash(text, p1, p2):
1722 1726 # Clear the revision cache on hash failure. The revision cache
1723 1727 # only stores the raw revision and clearing the cache does have
1724 1728 # the side-effect that we won't have a cache hit when the raw
1725 1729 # revision data is accessed. But this case should be rare and
1726 1730 # it is extra work to teach the cache about the hash
1727 1731 # verification state.
1728 1732 if self._revisioncache and self._revisioncache[0] == node:
1729 1733 self._revisioncache = None
1730 1734
1731 1735 revornode = rev
1732 1736 if revornode is None:
1733 1737 revornode = templatefilters.short(hex(node))
1734 1738 raise error.RevlogError(_("integrity check failed on %s:%s")
1735 1739 % (self.indexfile, pycompat.bytestr(revornode)))
1736 1740 except error.RevlogError:
1737 1741 if self._censorable and storageutil.iscensoredtext(text):
1738 1742 raise error.CensoredNodeError(self.indexfile, node, text)
1739 1743 raise
1740 1744
1741 1745 def _enforceinlinesize(self, tr, fp=None):
1742 1746 """Check if the revlog is too big for inline and convert if so.
1743 1747
1744 1748 This should be called after revisions are added to the revlog. If the
1745 1749 revlog has grown too large to be an inline revlog, it will convert it
1746 1750 to use multiple index and data files.
1747 1751 """
1748 1752 tiprev = len(self) - 1
1749 1753 if (not self._inline or
1750 1754 (self.start(tiprev) + self.length(tiprev)) < _maxinline):
1751 1755 return
1752 1756
1753 1757 trinfo = tr.find(self.indexfile)
1754 1758 if trinfo is None:
1755 1759 raise error.RevlogError(_("%s not found in the transaction")
1756 1760 % self.indexfile)
1757 1761
1758 1762 trindex = trinfo[2]
1759 1763 if trindex is not None:
1760 1764 dataoff = self.start(trindex)
1761 1765 else:
1762 1766 # revlog was stripped at start of transaction, use all leftover data
1763 1767 trindex = len(self) - 1
1764 1768 dataoff = self.end(tiprev)
1765 1769
1766 1770 tr.add(self.datafile, dataoff)
1767 1771
1768 1772 if fp:
1769 1773 fp.flush()
1770 1774 fp.close()
1771 1775 # We can't use the cached file handle after close(). So prevent
1772 1776 # its usage.
1773 1777 self._writinghandles = None
1774 1778
1775 1779 with self._indexfp('r') as ifh, self._datafp('w') as dfh:
1776 1780 for r in self:
1777 1781 dfh.write(self._getsegmentforrevs(r, r, df=ifh)[1])
1778 1782
1779 1783 with self._indexfp('w') as fp:
1780 1784 self.version &= ~FLAG_INLINE_DATA
1781 1785 self._inline = False
1782 1786 io = self._io
1783 1787 for i in self:
1784 1788 e = io.packentry(self.index[i], self.node, self.version, i)
1785 1789 fp.write(e)
1786 1790
1787 1791 # the temp file replace the real index when we exit the context
1788 1792 # manager
1789 1793
1790 1794 tr.replace(self.indexfile, trindex * self._io.size)
1791 1795 self._chunkclear()
1792 1796
1793 1797 def _nodeduplicatecallback(self, transaction, node):
1794 1798 """called when trying to add a node already stored.
1795 1799 """
1796 1800
1797 1801 def addrevision(self, text, transaction, link, p1, p2, cachedelta=None,
1798 1802 node=None, flags=REVIDX_DEFAULT_FLAGS, deltacomputer=None):
1799 1803 """add a revision to the log
1800 1804
1801 1805 text - the revision data to add
1802 1806 transaction - the transaction object used for rollback
1803 1807 link - the linkrev data to add
1804 1808 p1, p2 - the parent nodeids of the revision
1805 1809 cachedelta - an optional precomputed delta
1806 1810 node - nodeid of revision; typically node is not specified, and it is
1807 1811 computed by default as hash(text, p1, p2), however subclasses might
1808 1812 use different hashing method (and override checkhash() in such case)
1809 1813 flags - the known flags to set on the revision
1810 1814 deltacomputer - an optional deltacomputer instance shared between
1811 1815 multiple calls
1812 1816 """
1813 1817 if link == nullrev:
1814 1818 raise error.RevlogError(_("attempted to add linkrev -1 to %s")
1815 1819 % self.indexfile)
1816 1820
1817 1821 if flags:
1818 1822 node = node or self.hash(text, p1, p2)
1819 1823
1820 1824 rawtext, validatehash = self._processflags(text, flags, 'write')
1821 1825
1822 1826 # If the flag processor modifies the revision data, ignore any provided
1823 1827 # cachedelta.
1824 1828 if rawtext != text:
1825 1829 cachedelta = None
1826 1830
1827 1831 if len(rawtext) > _maxentrysize:
1828 1832 raise error.RevlogError(
1829 1833 _("%s: size of %d bytes exceeds maximum revlog storage of 2GiB")
1830 1834 % (self.indexfile, len(rawtext)))
1831 1835
1832 1836 node = node or self.hash(rawtext, p1, p2)
1833 1837 if node in self.nodemap:
1834 1838 return node
1835 1839
1836 1840 if validatehash:
1837 1841 self.checkhash(rawtext, node, p1=p1, p2=p2)
1838 1842
1839 1843 return self.addrawrevision(rawtext, transaction, link, p1, p2, node,
1840 1844 flags, cachedelta=cachedelta,
1841 1845 deltacomputer=deltacomputer)
1842 1846
1843 1847 def addrawrevision(self, rawtext, transaction, link, p1, p2, node, flags,
1844 1848 cachedelta=None, deltacomputer=None):
1845 1849 """add a raw revision with known flags, node and parents
1846 1850 useful when reusing a revision not stored in this revlog (ex: received
1847 1851 over wire, or read from an external bundle).
1848 1852 """
1849 1853 dfh = None
1850 1854 if not self._inline:
1851 1855 dfh = self._datafp("a+")
1852 1856 ifh = self._indexfp("a+")
1853 1857 try:
1854 1858 return self._addrevision(node, rawtext, transaction, link, p1, p2,
1855 1859 flags, cachedelta, ifh, dfh,
1856 1860 deltacomputer=deltacomputer)
1857 1861 finally:
1858 1862 if dfh:
1859 1863 dfh.close()
1860 1864 ifh.close()
1861 1865
1862 1866 def compress(self, data):
1863 1867 """Generate a possibly-compressed representation of data."""
1864 1868 if not data:
1865 1869 return '', data
1866 1870
1867 1871 compressed = self._compressor.compress(data)
1868 1872
1869 1873 if compressed:
1870 1874 # The revlog compressor added the header in the returned data.
1871 1875 return '', compressed
1872 1876
1873 1877 if data[0:1] == '\0':
1874 1878 return '', data
1875 1879 return 'u', data
1876 1880
1877 1881 def decompress(self, data):
1878 1882 """Decompress a revlog chunk.
1879 1883
1880 1884 The chunk is expected to begin with a header identifying the
1881 1885 format type so it can be routed to an appropriate decompressor.
1882 1886 """
1883 1887 if not data:
1884 1888 return data
1885 1889
1886 1890 # Revlogs are read much more frequently than they are written and many
1887 1891 # chunks only take microseconds to decompress, so performance is
1888 1892 # important here.
1889 1893 #
1890 1894 # We can make a few assumptions about revlogs:
1891 1895 #
1892 1896 # 1) the majority of chunks will be compressed (as opposed to inline
1893 1897 # raw data).
1894 1898 # 2) decompressing *any* data will likely by at least 10x slower than
1895 1899 # returning raw inline data.
1896 1900 # 3) we want to prioritize common and officially supported compression
1897 1901 # engines
1898 1902 #
1899 1903 # It follows that we want to optimize for "decompress compressed data
1900 1904 # when encoded with common and officially supported compression engines"
1901 1905 # case over "raw data" and "data encoded by less common or non-official
1902 1906 # compression engines." That is why we have the inline lookup first
1903 1907 # followed by the compengines lookup.
1904 1908 #
1905 1909 # According to `hg perfrevlogchunks`, this is ~0.5% faster for zlib
1906 1910 # compressed chunks. And this matters for changelog and manifest reads.
1907 1911 t = data[0:1]
1908 1912
1909 1913 if t == 'x':
1910 1914 try:
1911 1915 return _zlibdecompress(data)
1912 1916 except zlib.error as e:
1913 1917 raise error.RevlogError(_('revlog decompress error: %s') %
1914 1918 stringutil.forcebytestr(e))
1915 1919 # '\0' is more common than 'u' so it goes first.
1916 1920 elif t == '\0':
1917 1921 return data
1918 1922 elif t == 'u':
1919 1923 return util.buffer(data, 1)
1920 1924
1921 1925 try:
1922 1926 compressor = self._decompressors[t]
1923 1927 except KeyError:
1924 1928 try:
1925 1929 engine = util.compengines.forrevlogheader(t)
1926 1930 compressor = engine.revlogcompressor()
1927 1931 self._decompressors[t] = compressor
1928 1932 except KeyError:
1929 1933 raise error.RevlogError(_('unknown compression type %r') % t)
1930 1934
1931 1935 return compressor.decompress(data)
1932 1936
1933 1937 def _addrevision(self, node, rawtext, transaction, link, p1, p2, flags,
1934 1938 cachedelta, ifh, dfh, alwayscache=False,
1935 1939 deltacomputer=None):
1936 1940 """internal function to add revisions to the log
1937 1941
1938 1942 see addrevision for argument descriptions.
1939 1943
1940 1944 note: "addrevision" takes non-raw text, "_addrevision" takes raw text.
1941 1945
1942 1946 if "deltacomputer" is not provided or None, a defaultdeltacomputer will
1943 1947 be used.
1944 1948
1945 1949 invariants:
1946 1950 - rawtext is optional (can be None); if not set, cachedelta must be set.
1947 1951 if both are set, they must correspond to each other.
1948 1952 """
1949 1953 if node == nullid:
1950 1954 raise error.RevlogError(_("%s: attempt to add null revision") %
1951 1955 self.indexfile)
1952 1956 if node == wdirid or node in wdirfilenodeids:
1953 1957 raise error.RevlogError(_("%s: attempt to add wdir revision") %
1954 1958 self.indexfile)
1955 1959
1956 1960 if self._inline:
1957 1961 fh = ifh
1958 1962 else:
1959 1963 fh = dfh
1960 1964
1961 1965 btext = [rawtext]
1962 1966
1963 1967 curr = len(self)
1964 1968 prev = curr - 1
1965 1969 offset = self.end(prev)
1966 1970 p1r, p2r = self.rev(p1), self.rev(p2)
1967 1971
1968 1972 # full versions are inserted when the needed deltas
1969 1973 # become comparable to the uncompressed text
1970 1974 if rawtext is None:
1971 1975 # need rawtext size, before changed by flag processors, which is
1972 1976 # the non-raw size. use revlog explicitly to avoid filelog's extra
1973 1977 # logic that might remove metadata size.
1974 1978 textlen = mdiff.patchedsize(revlog.size(self, cachedelta[0]),
1975 1979 cachedelta[1])
1976 1980 else:
1977 1981 textlen = len(rawtext)
1978 1982
1979 1983 if deltacomputer is None:
1980 1984 deltacomputer = deltautil.deltacomputer(self)
1981 1985
1982 1986 revinfo = _revisioninfo(node, p1, p2, btext, textlen, cachedelta, flags)
1983 1987
1984 1988 deltainfo = deltacomputer.finddeltainfo(revinfo, fh)
1985 1989
1986 1990 e = (offset_type(offset, flags), deltainfo.deltalen, textlen,
1987 1991 deltainfo.base, link, p1r, p2r, node)
1988 1992 self.index.append(e)
1989 1993 self.nodemap[node] = curr
1990 1994
1991 1995 # Reset the pure node cache start lookup offset to account for new
1992 1996 # revision.
1993 1997 if self._nodepos is not None:
1994 1998 self._nodepos = curr
1995 1999
1996 2000 entry = self._io.packentry(e, self.node, self.version, curr)
1997 2001 self._writeentry(transaction, ifh, dfh, entry, deltainfo.data,
1998 2002 link, offset)
1999 2003
2000 2004 rawtext = btext[0]
2001 2005
2002 2006 if alwayscache and rawtext is None:
2003 2007 rawtext = deltacomputer.buildtext(revinfo, fh)
2004 2008
2005 2009 if type(rawtext) == bytes: # only accept immutable objects
2006 2010 self._revisioncache = (node, curr, rawtext)
2007 2011 self._chainbasecache[curr] = deltainfo.chainbase
2008 2012 return node
2009 2013
2010 2014 def _writeentry(self, transaction, ifh, dfh, entry, data, link, offset):
2011 2015 # Files opened in a+ mode have inconsistent behavior on various
2012 2016 # platforms. Windows requires that a file positioning call be made
2013 2017 # when the file handle transitions between reads and writes. See
2014 2018 # 3686fa2b8eee and the mixedfilemodewrapper in windows.py. On other
2015 2019 # platforms, Python or the platform itself can be buggy. Some versions
2016 2020 # of Solaris have been observed to not append at the end of the file
2017 2021 # if the file was seeked to before the end. See issue4943 for more.
2018 2022 #
2019 2023 # We work around this issue by inserting a seek() before writing.
2020 2024 # Note: This is likely not necessary on Python 3. However, because
2021 2025 # the file handle is reused for reads and may be seeked there, we need
2022 2026 # to be careful before changing this.
2023 2027 ifh.seek(0, os.SEEK_END)
2024 2028 if dfh:
2025 2029 dfh.seek(0, os.SEEK_END)
2026 2030
2027 2031 curr = len(self) - 1
2028 2032 if not self._inline:
2029 2033 transaction.add(self.datafile, offset)
2030 2034 transaction.add(self.indexfile, curr * len(entry))
2031 2035 if data[0]:
2032 2036 dfh.write(data[0])
2033 2037 dfh.write(data[1])
2034 2038 ifh.write(entry)
2035 2039 else:
2036 2040 offset += curr * self._io.size
2037 2041 transaction.add(self.indexfile, offset, curr)
2038 2042 ifh.write(entry)
2039 2043 ifh.write(data[0])
2040 2044 ifh.write(data[1])
2041 2045 self._enforceinlinesize(transaction, ifh)
2042 2046
2043 2047 def addgroup(self, deltas, linkmapper, transaction, addrevisioncb=None):
2044 2048 """
2045 2049 add a delta group
2046 2050
2047 2051 given a set of deltas, add them to the revision log. the
2048 2052 first delta is against its parent, which should be in our
2049 2053 log, the rest are against the previous delta.
2050 2054
2051 2055 If ``addrevisioncb`` is defined, it will be called with arguments of
2052 2056 this revlog and the node that was added.
2053 2057 """
2054 2058
2055 2059 if self._writinghandles:
2056 2060 raise error.ProgrammingError('cannot nest addgroup() calls')
2057 2061
2058 2062 nodes = []
2059 2063
2060 2064 r = len(self)
2061 2065 end = 0
2062 2066 if r:
2063 2067 end = self.end(r - 1)
2064 2068 ifh = self._indexfp("a+")
2065 2069 isize = r * self._io.size
2066 2070 if self._inline:
2067 2071 transaction.add(self.indexfile, end + isize, r)
2068 2072 dfh = None
2069 2073 else:
2070 2074 transaction.add(self.indexfile, isize, r)
2071 2075 transaction.add(self.datafile, end)
2072 2076 dfh = self._datafp("a+")
2073 2077 def flush():
2074 2078 if dfh:
2075 2079 dfh.flush()
2076 2080 ifh.flush()
2077 2081
2078 2082 self._writinghandles = (ifh, dfh)
2079 2083
2080 2084 try:
2081 2085 deltacomputer = deltautil.deltacomputer(self)
2082 2086 # loop through our set of deltas
2083 2087 for data in deltas:
2084 2088 node, p1, p2, linknode, deltabase, delta, flags = data
2085 2089 link = linkmapper(linknode)
2086 2090 flags = flags or REVIDX_DEFAULT_FLAGS
2087 2091
2088 2092 nodes.append(node)
2089 2093
2090 2094 if node in self.nodemap:
2091 2095 self._nodeduplicatecallback(transaction, node)
2092 2096 # this can happen if two branches make the same change
2093 2097 continue
2094 2098
2095 2099 for p in (p1, p2):
2096 2100 if p not in self.nodemap:
2097 2101 raise error.LookupError(p, self.indexfile,
2098 2102 _('unknown parent'))
2099 2103
2100 2104 if deltabase not in self.nodemap:
2101 2105 raise error.LookupError(deltabase, self.indexfile,
2102 2106 _('unknown delta base'))
2103 2107
2104 2108 baserev = self.rev(deltabase)
2105 2109
2106 2110 if baserev != nullrev and self.iscensored(baserev):
2107 2111 # if base is censored, delta must be full replacement in a
2108 2112 # single patch operation
2109 2113 hlen = struct.calcsize(">lll")
2110 2114 oldlen = self.rawsize(baserev)
2111 2115 newlen = len(delta) - hlen
2112 2116 if delta[:hlen] != mdiff.replacediffheader(oldlen, newlen):
2113 2117 raise error.CensoredBaseError(self.indexfile,
2114 2118 self.node(baserev))
2115 2119
2116 2120 if not flags and self._peek_iscensored(baserev, delta, flush):
2117 2121 flags |= REVIDX_ISCENSORED
2118 2122
2119 2123 # We assume consumers of addrevisioncb will want to retrieve
2120 2124 # the added revision, which will require a call to
2121 2125 # revision(). revision() will fast path if there is a cache
2122 2126 # hit. So, we tell _addrevision() to always cache in this case.
2123 2127 # We're only using addgroup() in the context of changegroup
2124 2128 # generation so the revision data can always be handled as raw
2125 2129 # by the flagprocessor.
2126 2130 self._addrevision(node, None, transaction, link,
2127 2131 p1, p2, flags, (baserev, delta),
2128 2132 ifh, dfh,
2129 2133 alwayscache=bool(addrevisioncb),
2130 2134 deltacomputer=deltacomputer)
2131 2135
2132 2136 if addrevisioncb:
2133 2137 addrevisioncb(self, node)
2134 2138
2135 2139 if not dfh and not self._inline:
2136 2140 # addrevision switched from inline to conventional
2137 2141 # reopen the index
2138 2142 ifh.close()
2139 2143 dfh = self._datafp("a+")
2140 2144 ifh = self._indexfp("a+")
2141 2145 self._writinghandles = (ifh, dfh)
2142 2146 finally:
2143 2147 self._writinghandles = None
2144 2148
2145 2149 if dfh:
2146 2150 dfh.close()
2147 2151 ifh.close()
2148 2152
2149 2153 return nodes
2150 2154
2151 2155 def iscensored(self, rev):
2152 2156 """Check if a file revision is censored."""
2153 2157 if not self._censorable:
2154 2158 return False
2155 2159
2156 2160 return self.flags(rev) & REVIDX_ISCENSORED
2157 2161
2158 2162 def _peek_iscensored(self, baserev, delta, flush):
2159 2163 """Quickly check if a delta produces a censored revision."""
2160 2164 if not self._censorable:
2161 2165 return False
2162 2166
2163 2167 return storageutil.deltaiscensored(delta, baserev, self.rawsize)
2164 2168
2165 2169 def getstrippoint(self, minlink):
2166 2170 """find the minimum rev that must be stripped to strip the linkrev
2167 2171
2168 2172 Returns a tuple containing the minimum rev and a set of all revs that
2169 2173 have linkrevs that will be broken by this strip.
2170 2174 """
2171 2175 return storageutil.resolvestripinfo(minlink, len(self) - 1,
2172 2176 self.headrevs(),
2173 2177 self.linkrev, self.parentrevs)
2174 2178
2175 2179 def strip(self, minlink, transaction):
2176 2180 """truncate the revlog on the first revision with a linkrev >= minlink
2177 2181
2178 2182 This function is called when we're stripping revision minlink and
2179 2183 its descendants from the repository.
2180 2184
2181 2185 We have to remove all revisions with linkrev >= minlink, because
2182 2186 the equivalent changelog revisions will be renumbered after the
2183 2187 strip.
2184 2188
2185 2189 So we truncate the revlog on the first of these revisions, and
2186 2190 trust that the caller has saved the revisions that shouldn't be
2187 2191 removed and that it'll re-add them after this truncation.
2188 2192 """
2189 2193 if len(self) == 0:
2190 2194 return
2191 2195
2192 2196 rev, _ = self.getstrippoint(minlink)
2193 2197 if rev == len(self):
2194 2198 return
2195 2199
2196 2200 # first truncate the files on disk
2197 2201 end = self.start(rev)
2198 2202 if not self._inline:
2199 2203 transaction.add(self.datafile, end)
2200 2204 end = rev * self._io.size
2201 2205 else:
2202 2206 end += rev * self._io.size
2203 2207
2204 2208 transaction.add(self.indexfile, end)
2205 2209
2206 2210 # then reset internal state in memory to forget those revisions
2207 2211 self._revisioncache = None
2208 2212 self._chaininfocache = {}
2209 2213 self._chunkclear()
2210 2214 for x in pycompat.xrange(rev, len(self)):
2211 2215 del self.nodemap[self.node(x)]
2212 2216
2213 2217 del self.index[rev:-1]
2214 2218 self._nodepos = None
2215 2219
2216 2220 def checksize(self):
2217 2221 expected = 0
2218 2222 if len(self):
2219 2223 expected = max(0, self.end(len(self) - 1))
2220 2224
2221 2225 try:
2222 2226 with self._datafp() as f:
2223 2227 f.seek(0, 2)
2224 2228 actual = f.tell()
2225 2229 dd = actual - expected
2226 2230 except IOError as inst:
2227 2231 if inst.errno != errno.ENOENT:
2228 2232 raise
2229 2233 dd = 0
2230 2234
2231 2235 try:
2232 2236 f = self.opener(self.indexfile)
2233 2237 f.seek(0, 2)
2234 2238 actual = f.tell()
2235 2239 f.close()
2236 2240 s = self._io.size
2237 2241 i = max(0, actual // s)
2238 2242 di = actual - (i * s)
2239 2243 if self._inline:
2240 2244 databytes = 0
2241 2245 for r in self:
2242 2246 databytes += max(0, self.length(r))
2243 2247 dd = 0
2244 2248 di = actual - len(self) * s - databytes
2245 2249 except IOError as inst:
2246 2250 if inst.errno != errno.ENOENT:
2247 2251 raise
2248 2252 di = 0
2249 2253
2250 2254 return (dd, di)
2251 2255
2252 2256 def files(self):
2253 2257 res = [self.indexfile]
2254 2258 if not self._inline:
2255 2259 res.append(self.datafile)
2256 2260 return res
2257 2261
2258 2262 def emitrevisions(self, nodes, nodesorder=None, revisiondata=False,
2259 2263 assumehaveparentrevisions=False,
2260 2264 deltamode=repository.CG_DELTAMODE_STD):
2261 2265 if nodesorder not in ('nodes', 'storage', 'linear', None):
2262 2266 raise error.ProgrammingError('unhandled value for nodesorder: %s' %
2263 2267 nodesorder)
2264 2268
2265 2269 if nodesorder is None and not self._generaldelta:
2266 2270 nodesorder = 'storage'
2267 2271
2268 2272 if (not self._storedeltachains and
2269 2273 deltamode != repository.CG_DELTAMODE_PREV):
2270 2274 deltamode = repository.CG_DELTAMODE_FULL
2271 2275
2272 2276 return storageutil.emitrevisions(
2273 2277 self, nodes, nodesorder, revlogrevisiondelta,
2274 2278 deltaparentfn=self.deltaparent,
2275 2279 candeltafn=self.candelta,
2276 2280 rawsizefn=self.rawsize,
2277 2281 revdifffn=self.revdiff,
2278 2282 flagsfn=self.flags,
2279 2283 deltamode=deltamode,
2280 2284 revisiondata=revisiondata,
2281 2285 assumehaveparentrevisions=assumehaveparentrevisions)
2282 2286
2283 2287 DELTAREUSEALWAYS = 'always'
2284 2288 DELTAREUSESAMEREVS = 'samerevs'
2285 2289 DELTAREUSENEVER = 'never'
2286 2290
2287 2291 DELTAREUSEFULLADD = 'fulladd'
2288 2292
2289 2293 DELTAREUSEALL = {'always', 'samerevs', 'never', 'fulladd'}
2290 2294
2291 2295 def clone(self, tr, destrevlog, addrevisioncb=None,
2292 2296 deltareuse=DELTAREUSESAMEREVS, forcedeltabothparents=None):
2293 2297 """Copy this revlog to another, possibly with format changes.
2294 2298
2295 2299 The destination revlog will contain the same revisions and nodes.
2296 2300 However, it may not be bit-for-bit identical due to e.g. delta encoding
2297 2301 differences.
2298 2302
2299 2303 The ``deltareuse`` argument control how deltas from the existing revlog
2300 2304 are preserved in the destination revlog. The argument can have the
2301 2305 following values:
2302 2306
2303 2307 DELTAREUSEALWAYS
2304 2308 Deltas will always be reused (if possible), even if the destination
2305 2309 revlog would not select the same revisions for the delta. This is the
2306 2310 fastest mode of operation.
2307 2311 DELTAREUSESAMEREVS
2308 2312 Deltas will be reused if the destination revlog would pick the same
2309 2313 revisions for the delta. This mode strikes a balance between speed
2310 2314 and optimization.
2311 2315 DELTAREUSENEVER
2312 2316 Deltas will never be reused. This is the slowest mode of execution.
2313 2317 This mode can be used to recompute deltas (e.g. if the diff/delta
2314 2318 algorithm changes).
2315 2319
2316 2320 Delta computation can be slow, so the choice of delta reuse policy can
2317 2321 significantly affect run time.
2318 2322
2319 2323 The default policy (``DELTAREUSESAMEREVS``) strikes a balance between
2320 2324 two extremes. Deltas will be reused if they are appropriate. But if the
2321 2325 delta could choose a better revision, it will do so. This means if you
2322 2326 are converting a non-generaldelta revlog to a generaldelta revlog,
2323 2327 deltas will be recomputed if the delta's parent isn't a parent of the
2324 2328 revision.
2325 2329
2326 2330 In addition to the delta policy, the ``forcedeltabothparents``
2327 2331 argument controls whether to force compute deltas against both parents
2328 2332 for merges. By default, the current default is used.
2329 2333 """
2330 2334 if deltareuse not in self.DELTAREUSEALL:
2331 2335 raise ValueError(_('value for deltareuse invalid: %s') % deltareuse)
2332 2336
2333 2337 if len(destrevlog):
2334 2338 raise ValueError(_('destination revlog is not empty'))
2335 2339
2336 2340 if getattr(self, 'filteredrevs', None):
2337 2341 raise ValueError(_('source revlog has filtered revisions'))
2338 2342 if getattr(destrevlog, 'filteredrevs', None):
2339 2343 raise ValueError(_('destination revlog has filtered revisions'))
2340 2344
2341 2345 # lazydeltabase controls whether to reuse a cached delta, if possible.
2342 2346 oldlazydeltabase = destrevlog._lazydeltabase
2343 2347 oldamd = destrevlog._deltabothparents
2344 2348
2345 2349 try:
2346 2350 if deltareuse == self.DELTAREUSEALWAYS:
2347 2351 destrevlog._lazydeltabase = True
2348 2352 elif deltareuse == self.DELTAREUSESAMEREVS:
2349 2353 destrevlog._lazydeltabase = False
2350 2354
2351 2355 destrevlog._deltabothparents = forcedeltabothparents or oldamd
2352 2356
2353 2357 populatecachedelta = deltareuse in (self.DELTAREUSEALWAYS,
2354 2358 self.DELTAREUSESAMEREVS)
2355 2359
2356 2360 deltacomputer = deltautil.deltacomputer(destrevlog)
2357 2361 index = self.index
2358 2362 for rev in self:
2359 2363 entry = index[rev]
2360 2364
2361 2365 # Some classes override linkrev to take filtered revs into
2362 2366 # account. Use raw entry from index.
2363 2367 flags = entry[0] & 0xffff
2364 2368 linkrev = entry[4]
2365 2369 p1 = index[entry[5]][7]
2366 2370 p2 = index[entry[6]][7]
2367 2371 node = entry[7]
2368 2372
2369 2373 # (Possibly) reuse the delta from the revlog if allowed and
2370 2374 # the revlog chunk is a delta.
2371 2375 cachedelta = None
2372 2376 rawtext = None
2373 2377 if populatecachedelta:
2374 2378 dp = self.deltaparent(rev)
2375 2379 if dp != nullrev:
2376 2380 cachedelta = (dp, bytes(self._chunk(rev)))
2377 2381
2378 2382 if not cachedelta:
2379 2383 rawtext = self.revision(rev, raw=True)
2380 2384
2381 2385
2382 2386 if deltareuse == self.DELTAREUSEFULLADD:
2383 2387 destrevlog.addrevision(rawtext, tr, linkrev, p1, p2,
2384 2388 cachedelta=cachedelta,
2385 2389 node=node, flags=flags,
2386 2390 deltacomputer=deltacomputer)
2387 2391 else:
2388 2392 ifh = destrevlog.opener(destrevlog.indexfile, 'a+',
2389 2393 checkambig=False)
2390 2394 dfh = None
2391 2395 if not destrevlog._inline:
2392 2396 dfh = destrevlog.opener(destrevlog.datafile, 'a+')
2393 2397 try:
2394 2398 destrevlog._addrevision(node, rawtext, tr, linkrev, p1,
2395 2399 p2, flags, cachedelta, ifh, dfh,
2396 2400 deltacomputer=deltacomputer)
2397 2401 finally:
2398 2402 if dfh:
2399 2403 dfh.close()
2400 2404 ifh.close()
2401 2405
2402 2406 if addrevisioncb:
2403 2407 addrevisioncb(self, rev, node)
2404 2408 finally:
2405 2409 destrevlog._lazydeltabase = oldlazydeltabase
2406 2410 destrevlog._deltabothparents = oldamd
2407 2411
2408 2412 def censorrevision(self, tr, censornode, tombstone=b''):
2409 2413 if (self.version & 0xFFFF) == REVLOGV0:
2410 2414 raise error.RevlogError(_('cannot censor with version %d revlogs') %
2411 2415 self.version)
2412 2416
2413 2417 censorrev = self.rev(censornode)
2414 2418 tombstone = storageutil.packmeta({b'censored': tombstone}, b'')
2415 2419
2416 2420 if len(tombstone) > self.rawsize(censorrev):
2417 2421 raise error.Abort(_('censor tombstone must be no longer than '
2418 2422 'censored data'))
2419 2423
2420 2424 # Rewriting the revlog in place is hard. Our strategy for censoring is
2421 2425 # to create a new revlog, copy all revisions to it, then replace the
2422 2426 # revlogs on transaction close.
2423 2427
2424 2428 newindexfile = self.indexfile + b'.tmpcensored'
2425 2429 newdatafile = self.datafile + b'.tmpcensored'
2426 2430
2427 2431 # This is a bit dangerous. We could easily have a mismatch of state.
2428 2432 newrl = revlog(self.opener, newindexfile, newdatafile,
2429 2433 censorable=True)
2430 2434 newrl.version = self.version
2431 2435 newrl._generaldelta = self._generaldelta
2432 2436 newrl._io = self._io
2433 2437
2434 2438 for rev in self.revs():
2435 2439 node = self.node(rev)
2436 2440 p1, p2 = self.parents(node)
2437 2441
2438 2442 if rev == censorrev:
2439 2443 newrl.addrawrevision(tombstone, tr, self.linkrev(censorrev),
2440 2444 p1, p2, censornode, REVIDX_ISCENSORED)
2441 2445
2442 2446 if newrl.deltaparent(rev) != nullrev:
2443 2447 raise error.Abort(_('censored revision stored as delta; '
2444 2448 'cannot censor'),
2445 2449 hint=_('censoring of revlogs is not '
2446 2450 'fully implemented; please report '
2447 2451 'this bug'))
2448 2452 continue
2449 2453
2450 2454 if self.iscensored(rev):
2451 2455 if self.deltaparent(rev) != nullrev:
2452 2456 raise error.Abort(_('cannot censor due to censored '
2453 2457 'revision having delta stored'))
2454 2458 rawtext = self._chunk(rev)
2455 2459 else:
2456 2460 rawtext = self.revision(rev, raw=True)
2457 2461
2458 2462 newrl.addrawrevision(rawtext, tr, self.linkrev(rev), p1, p2, node,
2459 2463 self.flags(rev))
2460 2464
2461 2465 tr.addbackup(self.indexfile, location='store')
2462 2466 if not self._inline:
2463 2467 tr.addbackup(self.datafile, location='store')
2464 2468
2465 2469 self.opener.rename(newrl.indexfile, self.indexfile)
2466 2470 if not self._inline:
2467 2471 self.opener.rename(newrl.datafile, self.datafile)
2468 2472
2469 2473 self.clearcaches()
2470 2474 self._loadindex(self.version, None)
2471 2475
2472 2476 def verifyintegrity(self, state):
2473 2477 """Verifies the integrity of the revlog.
2474 2478
2475 2479 Yields ``revlogproblem`` instances describing problems that are
2476 2480 found.
2477 2481 """
2478 2482 dd, di = self.checksize()
2479 2483 if dd:
2480 2484 yield revlogproblem(error=_('data length off by %d bytes') % dd)
2481 2485 if di:
2482 2486 yield revlogproblem(error=_('index contains %d extra bytes') % di)
2483 2487
2484 2488 version = self.version & 0xFFFF
2485 2489
2486 2490 # The verifier tells us what version revlog we should be.
2487 2491 if version != state['expectedversion']:
2488 2492 yield revlogproblem(
2489 2493 warning=_("warning: '%s' uses revlog format %d; expected %d") %
2490 2494 (self.indexfile, version, state['expectedversion']))
2491 2495
2492 2496 state['skipread'] = set()
2493 2497
2494 2498 for rev in self:
2495 2499 node = self.node(rev)
2496 2500
2497 2501 # Verify contents. 4 cases to care about:
2498 2502 #
2499 2503 # common: the most common case
2500 2504 # rename: with a rename
2501 2505 # meta: file content starts with b'\1\n', the metadata
2502 2506 # header defined in filelog.py, but without a rename
2503 2507 # ext: content stored externally
2504 2508 #
2505 2509 # More formally, their differences are shown below:
2506 2510 #
2507 2511 # | common | rename | meta | ext
2508 2512 # -------------------------------------------------------
2509 2513 # flags() | 0 | 0 | 0 | not 0
2510 2514 # renamed() | False | True | False | ?
2511 2515 # rawtext[0:2]=='\1\n'| False | True | True | ?
2512 2516 #
2513 2517 # "rawtext" means the raw text stored in revlog data, which
2514 2518 # could be retrieved by "revision(rev, raw=True)". "text"
2515 2519 # mentioned below is "revision(rev, raw=False)".
2516 2520 #
2517 2521 # There are 3 different lengths stored physically:
2518 2522 # 1. L1: rawsize, stored in revlog index
2519 2523 # 2. L2: len(rawtext), stored in revlog data
2520 2524 # 3. L3: len(text), stored in revlog data if flags==0, or
2521 2525 # possibly somewhere else if flags!=0
2522 2526 #
2523 2527 # L1 should be equal to L2. L3 could be different from them.
2524 2528 # "text" may or may not affect commit hash depending on flag
2525 2529 # processors (see revlog.addflagprocessor).
2526 2530 #
2527 2531 # | common | rename | meta | ext
2528 2532 # -------------------------------------------------
2529 2533 # rawsize() | L1 | L1 | L1 | L1
2530 2534 # size() | L1 | L2-LM | L1(*) | L1 (?)
2531 2535 # len(rawtext) | L2 | L2 | L2 | L2
2532 2536 # len(text) | L2 | L2 | L2 | L3
2533 2537 # len(read()) | L2 | L2-LM | L2-LM | L3 (?)
2534 2538 #
2535 2539 # LM: length of metadata, depending on rawtext
2536 2540 # (*): not ideal, see comment in filelog.size
2537 2541 # (?): could be "- len(meta)" if the resolved content has
2538 2542 # rename metadata
2539 2543 #
2540 2544 # Checks needed to be done:
2541 2545 # 1. length check: L1 == L2, in all cases.
2542 2546 # 2. hash check: depending on flag processor, we may need to
2543 2547 # use either "text" (external), or "rawtext" (in revlog).
2544 2548
2545 2549 try:
2546 2550 skipflags = state.get('skipflags', 0)
2547 2551 if skipflags:
2548 2552 skipflags &= self.flags(rev)
2549 2553
2550 2554 if skipflags:
2551 2555 state['skipread'].add(node)
2552 2556 else:
2553 2557 # Side-effect: read content and verify hash.
2554 2558 self.revision(node)
2555 2559
2556 2560 l1 = self.rawsize(rev)
2557 2561 l2 = len(self.revision(node, raw=True))
2558 2562
2559 2563 if l1 != l2:
2560 2564 yield revlogproblem(
2561 2565 error=_('unpacked size is %d, %d expected') % (l2, l1),
2562 2566 node=node)
2563 2567
2564 2568 except error.CensoredNodeError:
2565 2569 if state['erroroncensored']:
2566 2570 yield revlogproblem(error=_('censored file data'),
2567 2571 node=node)
2568 2572 state['skipread'].add(node)
2569 2573 except Exception as e:
2570 2574 yield revlogproblem(
2571 2575 error=_('unpacking %s: %s') % (short(node),
2572 2576 stringutil.forcebytestr(e)),
2573 2577 node=node)
2574 2578 state['skipread'].add(node)
2575 2579
2576 2580 def storageinfo(self, exclusivefiles=False, sharedfiles=False,
2577 2581 revisionscount=False, trackedsize=False,
2578 2582 storedsize=False):
2579 2583 d = {}
2580 2584
2581 2585 if exclusivefiles:
2582 2586 d['exclusivefiles'] = [(self.opener, self.indexfile)]
2583 2587 if not self._inline:
2584 2588 d['exclusivefiles'].append((self.opener, self.datafile))
2585 2589
2586 2590 if sharedfiles:
2587 2591 d['sharedfiles'] = []
2588 2592
2589 2593 if revisionscount:
2590 2594 d['revisionscount'] = len(self)
2591 2595
2592 2596 if trackedsize:
2593 2597 d['trackedsize'] = sum(map(self.rawsize, iter(self)))
2594 2598
2595 2599 if storedsize:
2596 2600 d['storedsize'] = sum(self.opener.stat(path).st_size
2597 2601 for path in self.files())
2598 2602
2599 2603 return d
General Comments 0
You need to be logged in to leave comments. Login now