##// END OF EJS Templates
revlog: remove unnecessary cache validation in _chunks...
Gregory Szorc -
r27650:e7222d32 default
parent child Browse files
Show More
@@ -1,1790 +1,1783 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 errno
18 18 import os
19 19 import struct
20 20 import zlib
21 21
22 22 # import stuff from node for others to import from revlog
23 23 from .node import (
24 24 bin,
25 25 hex,
26 26 nullid,
27 27 nullrev,
28 28 )
29 29 from .i18n import _
30 30 from . import (
31 31 ancestor,
32 32 error,
33 33 mdiff,
34 34 parsers,
35 35 templatefilters,
36 36 util,
37 37 )
38 38
39 39 _pack = struct.pack
40 40 _unpack = struct.unpack
41 41 _compress = zlib.compress
42 42 _decompress = zlib.decompress
43 43 _sha = util.sha1
44 44
45 45 # revlog header flags
46 46 REVLOGV0 = 0
47 47 REVLOGNG = 1
48 48 REVLOGNGINLINEDATA = (1 << 16)
49 49 REVLOGGENERALDELTA = (1 << 17)
50 50 REVLOG_DEFAULT_FLAGS = REVLOGNGINLINEDATA
51 51 REVLOG_DEFAULT_FORMAT = REVLOGNG
52 52 REVLOG_DEFAULT_VERSION = REVLOG_DEFAULT_FORMAT | REVLOG_DEFAULT_FLAGS
53 53 REVLOGNG_FLAGS = REVLOGNGINLINEDATA | REVLOGGENERALDELTA
54 54
55 55 # revlog index flags
56 56 REVIDX_ISCENSORED = (1 << 15) # revision has censor metadata, must be verified
57 57 REVIDX_DEFAULT_FLAGS = 0
58 58 REVIDX_KNOWN_FLAGS = REVIDX_ISCENSORED
59 59
60 60 # max size of revlog with inline data
61 61 _maxinline = 131072
62 62 _chunksize = 1048576
63 63
64 64 RevlogError = error.RevlogError
65 65 LookupError = error.LookupError
66 66 CensoredNodeError = error.CensoredNodeError
67 67
68 68 def getoffset(q):
69 69 return int(q >> 16)
70 70
71 71 def gettype(q):
72 72 return int(q & 0xFFFF)
73 73
74 74 def offset_type(offset, type):
75 75 return long(long(offset) << 16 | type)
76 76
77 77 _nullhash = _sha(nullid)
78 78
79 79 def hash(text, p1, p2):
80 80 """generate a hash from the given text and its parent hashes
81 81
82 82 This hash combines both the current file contents and its history
83 83 in a manner that makes it easy to distinguish nodes with the same
84 84 content in the revision graph.
85 85 """
86 86 # As of now, if one of the parent node is null, p2 is null
87 87 if p2 == nullid:
88 88 # deep copy of a hash is faster than creating one
89 89 s = _nullhash.copy()
90 90 s.update(p1)
91 91 else:
92 92 # none of the parent nodes are nullid
93 93 l = [p1, p2]
94 94 l.sort()
95 95 s = _sha(l[0])
96 96 s.update(l[1])
97 97 s.update(text)
98 98 return s.digest()
99 99
100 100 def decompress(bin):
101 101 """ decompress the given input """
102 102 if not bin:
103 103 return bin
104 104 t = bin[0]
105 105 if t == '\0':
106 106 return bin
107 107 if t == 'x':
108 108 try:
109 109 return _decompress(bin)
110 110 except zlib.error as e:
111 111 raise RevlogError(_("revlog decompress error: %s") % str(e))
112 112 if t == 'u':
113 113 return util.buffer(bin, 1)
114 114 raise RevlogError(_("unknown compression type %r") % t)
115 115
116 116 # index v0:
117 117 # 4 bytes: offset
118 118 # 4 bytes: compressed length
119 119 # 4 bytes: base rev
120 120 # 4 bytes: link rev
121 121 # 20 bytes: parent 1 nodeid
122 122 # 20 bytes: parent 2 nodeid
123 123 # 20 bytes: nodeid
124 124 indexformatv0 = ">4l20s20s20s"
125 125
126 126 class revlogoldio(object):
127 127 def __init__(self):
128 128 self.size = struct.calcsize(indexformatv0)
129 129
130 130 def parseindex(self, data, inline):
131 131 s = self.size
132 132 index = []
133 133 nodemap = {nullid: nullrev}
134 134 n = off = 0
135 135 l = len(data)
136 136 while off + s <= l:
137 137 cur = data[off:off + s]
138 138 off += s
139 139 e = _unpack(indexformatv0, cur)
140 140 # transform to revlogv1 format
141 141 e2 = (offset_type(e[0], 0), e[1], -1, e[2], e[3],
142 142 nodemap.get(e[4], nullrev), nodemap.get(e[5], nullrev), e[6])
143 143 index.append(e2)
144 144 nodemap[e[6]] = n
145 145 n += 1
146 146
147 147 # add the magic null revision at -1
148 148 index.append((0, 0, 0, -1, -1, -1, -1, nullid))
149 149
150 150 return index, nodemap, None
151 151
152 152 def packentry(self, entry, node, version, rev):
153 153 if gettype(entry[0]):
154 154 raise RevlogError(_("index entry flags need RevlogNG"))
155 155 e2 = (getoffset(entry[0]), entry[1], entry[3], entry[4],
156 156 node(entry[5]), node(entry[6]), entry[7])
157 157 return _pack(indexformatv0, *e2)
158 158
159 159 # index ng:
160 160 # 6 bytes: offset
161 161 # 2 bytes: flags
162 162 # 4 bytes: compressed length
163 163 # 4 bytes: uncompressed length
164 164 # 4 bytes: base rev
165 165 # 4 bytes: link rev
166 166 # 4 bytes: parent 1 rev
167 167 # 4 bytes: parent 2 rev
168 168 # 32 bytes: nodeid
169 169 indexformatng = ">Qiiiiii20s12x"
170 170 versionformat = ">I"
171 171
172 172 # corresponds to uncompressed length of indexformatng (2 gigs, 4-byte
173 173 # signed integer)
174 174 _maxentrysize = 0x7fffffff
175 175
176 176 class revlogio(object):
177 177 def __init__(self):
178 178 self.size = struct.calcsize(indexformatng)
179 179
180 180 def parseindex(self, data, inline):
181 181 # call the C implementation to parse the index data
182 182 index, cache = parsers.parse_index2(data, inline)
183 183 return index, getattr(index, 'nodemap', None), cache
184 184
185 185 def packentry(self, entry, node, version, rev):
186 186 p = _pack(indexformatng, *entry)
187 187 if rev == 0:
188 188 p = _pack(versionformat, version) + p[4:]
189 189 return p
190 190
191 191 class revlog(object):
192 192 """
193 193 the underlying revision storage object
194 194
195 195 A revlog consists of two parts, an index and the revision data.
196 196
197 197 The index is a file with a fixed record size containing
198 198 information on each revision, including its nodeid (hash), the
199 199 nodeids of its parents, the position and offset of its data within
200 200 the data file, and the revision it's based on. Finally, each entry
201 201 contains a linkrev entry that can serve as a pointer to external
202 202 data.
203 203
204 204 The revision data itself is a linear collection of data chunks.
205 205 Each chunk represents a revision and is usually represented as a
206 206 delta against the previous chunk. To bound lookup time, runs of
207 207 deltas are limited to about 2 times the length of the original
208 208 version data. This makes retrieval of a version proportional to
209 209 its size, or O(1) relative to the number of revisions.
210 210
211 211 Both pieces of the revlog are written to in an append-only
212 212 fashion, which means we never need to rewrite a file to insert or
213 213 remove data, and can use some simple techniques to avoid the need
214 214 for locking while reading.
215 215 """
216 216 def __init__(self, opener, indexfile):
217 217 """
218 218 create a revlog object
219 219
220 220 opener is a function that abstracts the file opening operation
221 221 and can be used to implement COW semantics or the like.
222 222 """
223 223 self.indexfile = indexfile
224 224 self.datafile = indexfile[:-2] + ".d"
225 225 self.opener = opener
226 226 # 3-tuple of (node, rev, text) for a raw revision.
227 227 self._cache = None
228 228 # 2-tuple of (rev, baserev) defining the base revision the delta chain
229 229 # begins at for a revision.
230 230 self._basecache = None
231 231 # 2-tuple of (offset, data) of raw data from the revlog at an offset.
232 232 self._chunkcache = (0, '')
233 233 # How much data to read and cache into the raw revlog data cache.
234 234 self._chunkcachesize = 65536
235 235 self._maxchainlen = None
236 236 self._aggressivemergedeltas = False
237 237 self.index = []
238 238 # Mapping of partial identifiers to full nodes.
239 239 self._pcache = {}
240 240 # Mapping of revision integer to full node.
241 241 self._nodecache = {nullid: nullrev}
242 242 self._nodepos = None
243 243
244 244 v = REVLOG_DEFAULT_VERSION
245 245 opts = getattr(opener, 'options', None)
246 246 if opts is not None:
247 247 if 'revlogv1' in opts:
248 248 if 'generaldelta' in opts:
249 249 v |= REVLOGGENERALDELTA
250 250 else:
251 251 v = 0
252 252 if 'chunkcachesize' in opts:
253 253 self._chunkcachesize = opts['chunkcachesize']
254 254 if 'maxchainlen' in opts:
255 255 self._maxchainlen = opts['maxchainlen']
256 256 if 'aggressivemergedeltas' in opts:
257 257 self._aggressivemergedeltas = opts['aggressivemergedeltas']
258 258 self._lazydeltabase = bool(opts.get('lazydeltabase', False))
259 259
260 260 if self._chunkcachesize <= 0:
261 261 raise RevlogError(_('revlog chunk cache size %r is not greater '
262 262 'than 0') % self._chunkcachesize)
263 263 elif self._chunkcachesize & (self._chunkcachesize - 1):
264 264 raise RevlogError(_('revlog chunk cache size %r is not a power '
265 265 'of 2') % self._chunkcachesize)
266 266
267 267 indexdata = ''
268 268 self._initempty = True
269 269 try:
270 270 f = self.opener(self.indexfile)
271 271 indexdata = f.read()
272 272 f.close()
273 273 if len(indexdata) > 0:
274 274 v = struct.unpack(versionformat, indexdata[:4])[0]
275 275 self._initempty = False
276 276 except IOError as inst:
277 277 if inst.errno != errno.ENOENT:
278 278 raise
279 279
280 280 self.version = v
281 281 self._inline = v & REVLOGNGINLINEDATA
282 282 self._generaldelta = v & REVLOGGENERALDELTA
283 283 flags = v & ~0xFFFF
284 284 fmt = v & 0xFFFF
285 285 if fmt == REVLOGV0 and flags:
286 286 raise RevlogError(_("index %s unknown flags %#04x for format v0")
287 287 % (self.indexfile, flags >> 16))
288 288 elif fmt == REVLOGNG and flags & ~REVLOGNG_FLAGS:
289 289 raise RevlogError(_("index %s unknown flags %#04x for revlogng")
290 290 % (self.indexfile, flags >> 16))
291 291 elif fmt > REVLOGNG:
292 292 raise RevlogError(_("index %s unknown format %d")
293 293 % (self.indexfile, fmt))
294 294
295 295 self._io = revlogio()
296 296 if self.version == REVLOGV0:
297 297 self._io = revlogoldio()
298 298 try:
299 299 d = self._io.parseindex(indexdata, self._inline)
300 300 except (ValueError, IndexError):
301 301 raise RevlogError(_("index %s is corrupted") % (self.indexfile))
302 302 self.index, nodemap, self._chunkcache = d
303 303 if nodemap is not None:
304 304 self.nodemap = self._nodecache = nodemap
305 305 if not self._chunkcache:
306 306 self._chunkclear()
307 307 # revnum -> (chain-length, sum-delta-length)
308 308 self._chaininfocache = {}
309 309
310 310 def tip(self):
311 311 return self.node(len(self.index) - 2)
312 312 def __contains__(self, rev):
313 313 return 0 <= rev < len(self)
314 314 def __len__(self):
315 315 return len(self.index) - 1
316 316 def __iter__(self):
317 317 return iter(xrange(len(self)))
318 318 def revs(self, start=0, stop=None):
319 319 """iterate over all rev in this revlog (from start to stop)"""
320 320 step = 1
321 321 if stop is not None:
322 322 if start > stop:
323 323 step = -1
324 324 stop += step
325 325 else:
326 326 stop = len(self)
327 327 return xrange(start, stop, step)
328 328
329 329 @util.propertycache
330 330 def nodemap(self):
331 331 self.rev(self.node(0))
332 332 return self._nodecache
333 333
334 334 def hasnode(self, node):
335 335 try:
336 336 self.rev(node)
337 337 return True
338 338 except KeyError:
339 339 return False
340 340
341 341 def clearcaches(self):
342 342 self._cache = None
343 343 self._basecache = None
344 344 self._chunkcache = (0, '')
345 345 self._pcache = {}
346 346
347 347 try:
348 348 self._nodecache.clearcaches()
349 349 except AttributeError:
350 350 self._nodecache = {nullid: nullrev}
351 351 self._nodepos = None
352 352
353 353 def rev(self, node):
354 354 try:
355 355 return self._nodecache[node]
356 356 except TypeError:
357 357 raise
358 358 except RevlogError:
359 359 # parsers.c radix tree lookup failed
360 360 raise LookupError(node, self.indexfile, _('no node'))
361 361 except KeyError:
362 362 # pure python cache lookup failed
363 363 n = self._nodecache
364 364 i = self.index
365 365 p = self._nodepos
366 366 if p is None:
367 367 p = len(i) - 2
368 368 for r in xrange(p, -1, -1):
369 369 v = i[r][7]
370 370 n[v] = r
371 371 if v == node:
372 372 self._nodepos = r - 1
373 373 return r
374 374 raise LookupError(node, self.indexfile, _('no node'))
375 375
376 376 def node(self, rev):
377 377 return self.index[rev][7]
378 378 def linkrev(self, rev):
379 379 return self.index[rev][4]
380 380 def parents(self, node):
381 381 i = self.index
382 382 d = i[self.rev(node)]
383 383 return i[d[5]][7], i[d[6]][7] # map revisions to nodes inline
384 384 def parentrevs(self, rev):
385 385 return self.index[rev][5:7]
386 386 def start(self, rev):
387 387 return int(self.index[rev][0] >> 16)
388 388 def end(self, rev):
389 389 return self.start(rev) + self.length(rev)
390 390 def length(self, rev):
391 391 return self.index[rev][1]
392 392 def chainbase(self, rev):
393 393 index = self.index
394 394 base = index[rev][3]
395 395 while base != rev:
396 396 rev = base
397 397 base = index[rev][3]
398 398 return base
399 399 def chainlen(self, rev):
400 400 return self._chaininfo(rev)[0]
401 401
402 402 def _chaininfo(self, rev):
403 403 chaininfocache = self._chaininfocache
404 404 if rev in chaininfocache:
405 405 return chaininfocache[rev]
406 406 index = self.index
407 407 generaldelta = self._generaldelta
408 408 iterrev = rev
409 409 e = index[iterrev]
410 410 clen = 0
411 411 compresseddeltalen = 0
412 412 while iterrev != e[3]:
413 413 clen += 1
414 414 compresseddeltalen += e[1]
415 415 if generaldelta:
416 416 iterrev = e[3]
417 417 else:
418 418 iterrev -= 1
419 419 if iterrev in chaininfocache:
420 420 t = chaininfocache[iterrev]
421 421 clen += t[0]
422 422 compresseddeltalen += t[1]
423 423 break
424 424 e = index[iterrev]
425 425 else:
426 426 # Add text length of base since decompressing that also takes
427 427 # work. For cache hits the length is already included.
428 428 compresseddeltalen += e[1]
429 429 r = (clen, compresseddeltalen)
430 430 chaininfocache[rev] = r
431 431 return r
432 432
433 433 def _deltachain(self, rev, stoprev=None):
434 434 """Obtain the delta chain for a revision.
435 435
436 436 ``stoprev`` specifies a revision to stop at. If not specified, we
437 437 stop at the base of the chain.
438 438
439 439 Returns a 2-tuple of (chain, stopped) where ``chain`` is a list of
440 440 revs in ascending order and ``stopped`` is a bool indicating whether
441 441 ``stoprev`` was hit.
442 442 """
443 443 chain = []
444 444
445 445 # Alias to prevent attribute lookup in tight loop.
446 446 index = self.index
447 447 generaldelta = self._generaldelta
448 448
449 449 iterrev = rev
450 450 e = index[iterrev]
451 451 while iterrev != e[3] and iterrev != stoprev:
452 452 chain.append(iterrev)
453 453 if generaldelta:
454 454 iterrev = e[3]
455 455 else:
456 456 iterrev -= 1
457 457 e = index[iterrev]
458 458
459 459 if iterrev == stoprev:
460 460 stopped = True
461 461 else:
462 462 chain.append(iterrev)
463 463 stopped = False
464 464
465 465 chain.reverse()
466 466 return chain, stopped
467 467
468 468 def flags(self, rev):
469 469 return self.index[rev][0] & 0xFFFF
470 470 def rawsize(self, rev):
471 471 """return the length of the uncompressed text for a given revision"""
472 472 l = self.index[rev][2]
473 473 if l >= 0:
474 474 return l
475 475
476 476 t = self.revision(self.node(rev))
477 477 return len(t)
478 478 size = rawsize
479 479
480 480 def ancestors(self, revs, stoprev=0, inclusive=False):
481 481 """Generate the ancestors of 'revs' in reverse topological order.
482 482 Does not generate revs lower than stoprev.
483 483
484 484 See the documentation for ancestor.lazyancestors for more details."""
485 485
486 486 return ancestor.lazyancestors(self.parentrevs, revs, stoprev=stoprev,
487 487 inclusive=inclusive)
488 488
489 489 def descendants(self, revs):
490 490 """Generate the descendants of 'revs' in revision order.
491 491
492 492 Yield a sequence of revision numbers starting with a child of
493 493 some rev in revs, i.e., each revision is *not* considered a
494 494 descendant of itself. Results are ordered by revision number (a
495 495 topological sort)."""
496 496 first = min(revs)
497 497 if first == nullrev:
498 498 for i in self:
499 499 yield i
500 500 return
501 501
502 502 seen = set(revs)
503 503 for i in self.revs(start=first + 1):
504 504 for x in self.parentrevs(i):
505 505 if x != nullrev and x in seen:
506 506 seen.add(i)
507 507 yield i
508 508 break
509 509
510 510 def findcommonmissing(self, common=None, heads=None):
511 511 """Return a tuple of the ancestors of common and the ancestors of heads
512 512 that are not ancestors of common. In revset terminology, we return the
513 513 tuple:
514 514
515 515 ::common, (::heads) - (::common)
516 516
517 517 The list is sorted by revision number, meaning it is
518 518 topologically sorted.
519 519
520 520 'heads' and 'common' are both lists of node IDs. If heads is
521 521 not supplied, uses all of the revlog's heads. If common is not
522 522 supplied, uses nullid."""
523 523 if common is None:
524 524 common = [nullid]
525 525 if heads is None:
526 526 heads = self.heads()
527 527
528 528 common = [self.rev(n) for n in common]
529 529 heads = [self.rev(n) for n in heads]
530 530
531 531 # we want the ancestors, but inclusive
532 532 class lazyset(object):
533 533 def __init__(self, lazyvalues):
534 534 self.addedvalues = set()
535 535 self.lazyvalues = lazyvalues
536 536
537 537 def __contains__(self, value):
538 538 return value in self.addedvalues or value in self.lazyvalues
539 539
540 540 def __iter__(self):
541 541 added = self.addedvalues
542 542 for r in added:
543 543 yield r
544 544 for r in self.lazyvalues:
545 545 if not r in added:
546 546 yield r
547 547
548 548 def add(self, value):
549 549 self.addedvalues.add(value)
550 550
551 551 def update(self, values):
552 552 self.addedvalues.update(values)
553 553
554 554 has = lazyset(self.ancestors(common))
555 555 has.add(nullrev)
556 556 has.update(common)
557 557
558 558 # take all ancestors from heads that aren't in has
559 559 missing = set()
560 560 visit = collections.deque(r for r in heads if r not in has)
561 561 while visit:
562 562 r = visit.popleft()
563 563 if r in missing:
564 564 continue
565 565 else:
566 566 missing.add(r)
567 567 for p in self.parentrevs(r):
568 568 if p not in has:
569 569 visit.append(p)
570 570 missing = list(missing)
571 571 missing.sort()
572 572 return has, [self.node(r) for r in missing]
573 573
574 574 def incrementalmissingrevs(self, common=None):
575 575 """Return an object that can be used to incrementally compute the
576 576 revision numbers of the ancestors of arbitrary sets that are not
577 577 ancestors of common. This is an ancestor.incrementalmissingancestors
578 578 object.
579 579
580 580 'common' is a list of revision numbers. If common is not supplied, uses
581 581 nullrev.
582 582 """
583 583 if common is None:
584 584 common = [nullrev]
585 585
586 586 return ancestor.incrementalmissingancestors(self.parentrevs, common)
587 587
588 588 def findmissingrevs(self, common=None, heads=None):
589 589 """Return the revision numbers of the ancestors of heads that
590 590 are not ancestors of common.
591 591
592 592 More specifically, return a list of revision numbers corresponding to
593 593 nodes N such that every N satisfies the following constraints:
594 594
595 595 1. N is an ancestor of some node in 'heads'
596 596 2. N is not an ancestor of any node in 'common'
597 597
598 598 The list is sorted by revision number, meaning it is
599 599 topologically sorted.
600 600
601 601 'heads' and 'common' are both lists of revision numbers. If heads is
602 602 not supplied, uses all of the revlog's heads. If common is not
603 603 supplied, uses nullid."""
604 604 if common is None:
605 605 common = [nullrev]
606 606 if heads is None:
607 607 heads = self.headrevs()
608 608
609 609 inc = self.incrementalmissingrevs(common=common)
610 610 return inc.missingancestors(heads)
611 611
612 612 def findmissing(self, common=None, heads=None):
613 613 """Return the ancestors of heads that are not ancestors of common.
614 614
615 615 More specifically, return a list of nodes N such that every N
616 616 satisfies the following constraints:
617 617
618 618 1. N is an ancestor of some node in 'heads'
619 619 2. N is not an ancestor of any node in 'common'
620 620
621 621 The list is sorted by revision number, meaning it is
622 622 topologically sorted.
623 623
624 624 'heads' and 'common' are both lists of node IDs. If heads is
625 625 not supplied, uses all of the revlog's heads. If common is not
626 626 supplied, uses nullid."""
627 627 if common is None:
628 628 common = [nullid]
629 629 if heads is None:
630 630 heads = self.heads()
631 631
632 632 common = [self.rev(n) for n in common]
633 633 heads = [self.rev(n) for n in heads]
634 634
635 635 inc = self.incrementalmissingrevs(common=common)
636 636 return [self.node(r) for r in inc.missingancestors(heads)]
637 637
638 638 def nodesbetween(self, roots=None, heads=None):
639 639 """Return a topological path from 'roots' to 'heads'.
640 640
641 641 Return a tuple (nodes, outroots, outheads) where 'nodes' is a
642 642 topologically sorted list of all nodes N that satisfy both of
643 643 these constraints:
644 644
645 645 1. N is a descendant of some node in 'roots'
646 646 2. N is an ancestor of some node in 'heads'
647 647
648 648 Every node is considered to be both a descendant and an ancestor
649 649 of itself, so every reachable node in 'roots' and 'heads' will be
650 650 included in 'nodes'.
651 651
652 652 'outroots' is the list of reachable nodes in 'roots', i.e., the
653 653 subset of 'roots' that is returned in 'nodes'. Likewise,
654 654 'outheads' is the subset of 'heads' that is also in 'nodes'.
655 655
656 656 'roots' and 'heads' are both lists of node IDs. If 'roots' is
657 657 unspecified, uses nullid as the only root. If 'heads' is
658 658 unspecified, uses list of all of the revlog's heads."""
659 659 nonodes = ([], [], [])
660 660 if roots is not None:
661 661 roots = list(roots)
662 662 if not roots:
663 663 return nonodes
664 664 lowestrev = min([self.rev(n) for n in roots])
665 665 else:
666 666 roots = [nullid] # Everybody's a descendant of nullid
667 667 lowestrev = nullrev
668 668 if (lowestrev == nullrev) and (heads is None):
669 669 # We want _all_ the nodes!
670 670 return ([self.node(r) for r in self], [nullid], list(self.heads()))
671 671 if heads is None:
672 672 # All nodes are ancestors, so the latest ancestor is the last
673 673 # node.
674 674 highestrev = len(self) - 1
675 675 # Set ancestors to None to signal that every node is an ancestor.
676 676 ancestors = None
677 677 # Set heads to an empty dictionary for later discovery of heads
678 678 heads = {}
679 679 else:
680 680 heads = list(heads)
681 681 if not heads:
682 682 return nonodes
683 683 ancestors = set()
684 684 # Turn heads into a dictionary so we can remove 'fake' heads.
685 685 # Also, later we will be using it to filter out the heads we can't
686 686 # find from roots.
687 687 heads = dict.fromkeys(heads, False)
688 688 # Start at the top and keep marking parents until we're done.
689 689 nodestotag = set(heads)
690 690 # Remember where the top was so we can use it as a limit later.
691 691 highestrev = max([self.rev(n) for n in nodestotag])
692 692 while nodestotag:
693 693 # grab a node to tag
694 694 n = nodestotag.pop()
695 695 # Never tag nullid
696 696 if n == nullid:
697 697 continue
698 698 # A node's revision number represents its place in a
699 699 # topologically sorted list of nodes.
700 700 r = self.rev(n)
701 701 if r >= lowestrev:
702 702 if n not in ancestors:
703 703 # If we are possibly a descendant of one of the roots
704 704 # and we haven't already been marked as an ancestor
705 705 ancestors.add(n) # Mark as ancestor
706 706 # Add non-nullid parents to list of nodes to tag.
707 707 nodestotag.update([p for p in self.parents(n) if
708 708 p != nullid])
709 709 elif n in heads: # We've seen it before, is it a fake head?
710 710 # So it is, real heads should not be the ancestors of
711 711 # any other heads.
712 712 heads.pop(n)
713 713 if not ancestors:
714 714 return nonodes
715 715 # Now that we have our set of ancestors, we want to remove any
716 716 # roots that are not ancestors.
717 717
718 718 # If one of the roots was nullid, everything is included anyway.
719 719 if lowestrev > nullrev:
720 720 # But, since we weren't, let's recompute the lowest rev to not
721 721 # include roots that aren't ancestors.
722 722
723 723 # Filter out roots that aren't ancestors of heads
724 724 roots = [n for n in roots if n in ancestors]
725 725 # Recompute the lowest revision
726 726 if roots:
727 727 lowestrev = min([self.rev(n) for n in roots])
728 728 else:
729 729 # No more roots? Return empty list
730 730 return nonodes
731 731 else:
732 732 # We are descending from nullid, and don't need to care about
733 733 # any other roots.
734 734 lowestrev = nullrev
735 735 roots = [nullid]
736 736 # Transform our roots list into a set.
737 737 descendants = set(roots)
738 738 # Also, keep the original roots so we can filter out roots that aren't
739 739 # 'real' roots (i.e. are descended from other roots).
740 740 roots = descendants.copy()
741 741 # Our topologically sorted list of output nodes.
742 742 orderedout = []
743 743 # Don't start at nullid since we don't want nullid in our output list,
744 744 # and if nullid shows up in descendants, empty parents will look like
745 745 # they're descendants.
746 746 for r in self.revs(start=max(lowestrev, 0), stop=highestrev + 1):
747 747 n = self.node(r)
748 748 isdescendant = False
749 749 if lowestrev == nullrev: # Everybody is a descendant of nullid
750 750 isdescendant = True
751 751 elif n in descendants:
752 752 # n is already a descendant
753 753 isdescendant = True
754 754 # This check only needs to be done here because all the roots
755 755 # will start being marked is descendants before the loop.
756 756 if n in roots:
757 757 # If n was a root, check if it's a 'real' root.
758 758 p = tuple(self.parents(n))
759 759 # If any of its parents are descendants, it's not a root.
760 760 if (p[0] in descendants) or (p[1] in descendants):
761 761 roots.remove(n)
762 762 else:
763 763 p = tuple(self.parents(n))
764 764 # A node is a descendant if either of its parents are
765 765 # descendants. (We seeded the dependents list with the roots
766 766 # up there, remember?)
767 767 if (p[0] in descendants) or (p[1] in descendants):
768 768 descendants.add(n)
769 769 isdescendant = True
770 770 if isdescendant and ((ancestors is None) or (n in ancestors)):
771 771 # Only include nodes that are both descendants and ancestors.
772 772 orderedout.append(n)
773 773 if (ancestors is not None) and (n in heads):
774 774 # We're trying to figure out which heads are reachable
775 775 # from roots.
776 776 # Mark this head as having been reached
777 777 heads[n] = True
778 778 elif ancestors is None:
779 779 # Otherwise, we're trying to discover the heads.
780 780 # Assume this is a head because if it isn't, the next step
781 781 # will eventually remove it.
782 782 heads[n] = True
783 783 # But, obviously its parents aren't.
784 784 for p in self.parents(n):
785 785 heads.pop(p, None)
786 786 heads = [n for n, flag in heads.iteritems() if flag]
787 787 roots = list(roots)
788 788 assert orderedout
789 789 assert roots
790 790 assert heads
791 791 return (orderedout, roots, heads)
792 792
793 793 def headrevs(self):
794 794 try:
795 795 return self.index.headrevs()
796 796 except AttributeError:
797 797 return self._headrevs()
798 798
799 799 def computephases(self, roots):
800 800 return self.index.computephasesmapsets(roots)
801 801
802 802 def _headrevs(self):
803 803 count = len(self)
804 804 if not count:
805 805 return [nullrev]
806 806 # we won't iter over filtered rev so nobody is a head at start
807 807 ishead = [0] * (count + 1)
808 808 index = self.index
809 809 for r in self:
810 810 ishead[r] = 1 # I may be an head
811 811 e = index[r]
812 812 ishead[e[5]] = ishead[e[6]] = 0 # my parent are not
813 813 return [r for r, val in enumerate(ishead) if val]
814 814
815 815 def heads(self, start=None, stop=None):
816 816 """return the list of all nodes that have no children
817 817
818 818 if start is specified, only heads that are descendants of
819 819 start will be returned
820 820 if stop is specified, it will consider all the revs from stop
821 821 as if they had no children
822 822 """
823 823 if start is None and stop is None:
824 824 if not len(self):
825 825 return [nullid]
826 826 return [self.node(r) for r in self.headrevs()]
827 827
828 828 if start is None:
829 829 start = nullid
830 830 if stop is None:
831 831 stop = []
832 832 stoprevs = set([self.rev(n) for n in stop])
833 833 startrev = self.rev(start)
834 834 reachable = set((startrev,))
835 835 heads = set((startrev,))
836 836
837 837 parentrevs = self.parentrevs
838 838 for r in self.revs(start=startrev + 1):
839 839 for p in parentrevs(r):
840 840 if p in reachable:
841 841 if r not in stoprevs:
842 842 reachable.add(r)
843 843 heads.add(r)
844 844 if p in heads and p not in stoprevs:
845 845 heads.remove(p)
846 846
847 847 return [self.node(r) for r in heads]
848 848
849 849 def children(self, node):
850 850 """find the children of a given node"""
851 851 c = []
852 852 p = self.rev(node)
853 853 for r in self.revs(start=p + 1):
854 854 prevs = [pr for pr in self.parentrevs(r) if pr != nullrev]
855 855 if prevs:
856 856 for pr in prevs:
857 857 if pr == p:
858 858 c.append(self.node(r))
859 859 elif p == nullrev:
860 860 c.append(self.node(r))
861 861 return c
862 862
863 863 def descendant(self, start, end):
864 864 if start == nullrev:
865 865 return True
866 866 for i in self.descendants([start]):
867 867 if i == end:
868 868 return True
869 869 elif i > end:
870 870 break
871 871 return False
872 872
873 873 def commonancestorsheads(self, a, b):
874 874 """calculate all the heads of the common ancestors of nodes a and b"""
875 875 a, b = self.rev(a), self.rev(b)
876 876 try:
877 877 ancs = self.index.commonancestorsheads(a, b)
878 878 except (AttributeError, OverflowError): # C implementation failed
879 879 ancs = ancestor.commonancestorsheads(self.parentrevs, a, b)
880 880 return map(self.node, ancs)
881 881
882 882 def isancestor(self, a, b):
883 883 """return True if node a is an ancestor of node b
884 884
885 885 The implementation of this is trivial but the use of
886 886 commonancestorsheads is not."""
887 887 return a in self.commonancestorsheads(a, b)
888 888
889 889 def ancestor(self, a, b):
890 890 """calculate the "best" common ancestor of nodes a and b"""
891 891
892 892 a, b = self.rev(a), self.rev(b)
893 893 try:
894 894 ancs = self.index.ancestors(a, b)
895 895 except (AttributeError, OverflowError):
896 896 ancs = ancestor.ancestors(self.parentrevs, a, b)
897 897 if ancs:
898 898 # choose a consistent winner when there's a tie
899 899 return min(map(self.node, ancs))
900 900 return nullid
901 901
902 902 def _match(self, id):
903 903 if isinstance(id, int):
904 904 # rev
905 905 return self.node(id)
906 906 if len(id) == 20:
907 907 # possibly a binary node
908 908 # odds of a binary node being all hex in ASCII are 1 in 10**25
909 909 try:
910 910 node = id
911 911 self.rev(node) # quick search the index
912 912 return node
913 913 except LookupError:
914 914 pass # may be partial hex id
915 915 try:
916 916 # str(rev)
917 917 rev = int(id)
918 918 if str(rev) != id:
919 919 raise ValueError
920 920 if rev < 0:
921 921 rev = len(self) + rev
922 922 if rev < 0 or rev >= len(self):
923 923 raise ValueError
924 924 return self.node(rev)
925 925 except (ValueError, OverflowError):
926 926 pass
927 927 if len(id) == 40:
928 928 try:
929 929 # a full hex nodeid?
930 930 node = bin(id)
931 931 self.rev(node)
932 932 return node
933 933 except (TypeError, LookupError):
934 934 pass
935 935
936 936 def _partialmatch(self, id):
937 937 try:
938 938 n = self.index.partialmatch(id)
939 939 if n and self.hasnode(n):
940 940 return n
941 941 return None
942 942 except RevlogError:
943 943 # parsers.c radix tree lookup gave multiple matches
944 944 # fall through to slow path that filters hidden revisions
945 945 pass
946 946 except (AttributeError, ValueError):
947 947 # we are pure python, or key was too short to search radix tree
948 948 pass
949 949
950 950 if id in self._pcache:
951 951 return self._pcache[id]
952 952
953 953 if len(id) < 40:
954 954 try:
955 955 # hex(node)[:...]
956 956 l = len(id) // 2 # grab an even number of digits
957 957 prefix = bin(id[:l * 2])
958 958 nl = [e[7] for e in self.index if e[7].startswith(prefix)]
959 959 nl = [n for n in nl if hex(n).startswith(id) and
960 960 self.hasnode(n)]
961 961 if len(nl) > 0:
962 962 if len(nl) == 1:
963 963 self._pcache[id] = nl[0]
964 964 return nl[0]
965 965 raise LookupError(id, self.indexfile,
966 966 _('ambiguous identifier'))
967 967 return None
968 968 except TypeError:
969 969 pass
970 970
971 971 def lookup(self, id):
972 972 """locate a node based on:
973 973 - revision number or str(revision number)
974 974 - nodeid or subset of hex nodeid
975 975 """
976 976 n = self._match(id)
977 977 if n is not None:
978 978 return n
979 979 n = self._partialmatch(id)
980 980 if n:
981 981 return n
982 982
983 983 raise LookupError(id, self.indexfile, _('no match found'))
984 984
985 985 def cmp(self, node, text):
986 986 """compare text with a given file revision
987 987
988 988 returns True if text is different than what is stored.
989 989 """
990 990 p1, p2 = self.parents(node)
991 991 return hash(text, p1, p2) != node
992 992
993 993 def _addchunk(self, offset, data):
994 994 """Add a segment to the revlog cache.
995 995
996 996 Accepts an absolute offset and the data that is at that location.
997 997 """
998 998 o, d = self._chunkcache
999 999 # try to add to existing cache
1000 1000 if o + len(d) == offset and len(d) + len(data) < _chunksize:
1001 1001 self._chunkcache = o, d + data
1002 1002 else:
1003 1003 self._chunkcache = offset, data
1004 1004
1005 1005 def _loadchunk(self, offset, length, df=None):
1006 1006 """Load a segment of raw data from the revlog.
1007 1007
1008 1008 Accepts an absolute offset, length to read, and an optional existing
1009 1009 file handle to read from.
1010 1010
1011 1011 If an existing file handle is passed, it will be seeked and the
1012 1012 original seek position will NOT be restored.
1013 1013
1014 1014 Returns a str or buffer of raw byte data.
1015 1015 """
1016 1016 if df is not None:
1017 1017 closehandle = False
1018 1018 else:
1019 1019 if self._inline:
1020 1020 df = self.opener(self.indexfile)
1021 1021 else:
1022 1022 df = self.opener(self.datafile)
1023 1023 closehandle = True
1024 1024
1025 1025 # Cache data both forward and backward around the requested
1026 1026 # data, in a fixed size window. This helps speed up operations
1027 1027 # involving reading the revlog backwards.
1028 1028 cachesize = self._chunkcachesize
1029 1029 realoffset = offset & ~(cachesize - 1)
1030 1030 reallength = (((offset + length + cachesize) & ~(cachesize - 1))
1031 1031 - realoffset)
1032 1032 df.seek(realoffset)
1033 1033 d = df.read(reallength)
1034 1034 if closehandle:
1035 1035 df.close()
1036 1036 self._addchunk(realoffset, d)
1037 1037 if offset != realoffset or reallength != length:
1038 1038 return util.buffer(d, offset - realoffset, length)
1039 1039 return d
1040 1040
1041 1041 def _getchunk(self, offset, length, df=None):
1042 1042 """Obtain a segment of raw data from the revlog.
1043 1043
1044 1044 Accepts an absolute offset, length of bytes to obtain, and an
1045 1045 optional file handle to the already-opened revlog. If the file
1046 1046 handle is used, it's original seek position will not be preserved.
1047 1047
1048 1048 Requests for data may be returned from a cache.
1049 1049
1050 1050 Returns a str or a buffer instance of raw byte data.
1051 1051 """
1052 1052 o, d = self._chunkcache
1053 1053 l = len(d)
1054 1054
1055 1055 # is it in the cache?
1056 1056 cachestart = offset - o
1057 1057 cacheend = cachestart + length
1058 1058 if cachestart >= 0 and cacheend <= l:
1059 1059 if cachestart == 0 and cacheend == l:
1060 1060 return d # avoid a copy
1061 1061 return util.buffer(d, cachestart, cacheend - cachestart)
1062 1062
1063 1063 return self._loadchunk(offset, length, df=df)
1064 1064
1065 1065 def _chunkraw(self, startrev, endrev, df=None):
1066 1066 """Obtain a segment of raw data corresponding to a range of revisions.
1067 1067
1068 1068 Accepts the start and end revisions and an optional already-open
1069 1069 file handle to be used for reading. If the file handle is read, its
1070 1070 seek position will not be preserved.
1071 1071
1072 1072 Requests for data may be satisfied by a cache.
1073 1073
1074 1074 Returns a 2-tuple of (offset, data) for the requested range of
1075 1075 revisions. Offset is the integer offset from the beginning of the
1076 1076 revlog and data is a str or buffer of the raw byte data.
1077 1077
1078 1078 Callers will need to call ``self.start(rev)`` and ``self.length(rev)``
1079 1079 to determine where each revision's data begins and ends.
1080 1080 """
1081 1081 start = self.start(startrev)
1082 1082 end = self.end(endrev)
1083 1083 if self._inline:
1084 1084 start += (startrev + 1) * self._io.size
1085 1085 end += (endrev + 1) * self._io.size
1086 1086 length = end - start
1087 1087
1088 1088 return start, self._getchunk(start, length, df=df)
1089 1089
1090 1090 def _chunk(self, rev, df=None):
1091 1091 """Obtain a single decompressed chunk for a revision.
1092 1092
1093 1093 Accepts an integer revision and an optional already-open file handle
1094 1094 to be used for reading. If used, the seek position of the file will not
1095 1095 be preserved.
1096 1096
1097 1097 Returns a str holding uncompressed data for the requested revision.
1098 1098 """
1099 1099 return decompress(self._chunkraw(rev, rev, df=df)[1])
1100 1100
1101 1101 def _chunks(self, revs, df=None):
1102 1102 """Obtain decompressed chunks for the specified revisions.
1103 1103
1104 1104 Accepts an iterable of numeric revisions that are assumed to be in
1105 1105 ascending order. Also accepts an optional already-open file handle
1106 1106 to be used for reading. If used, the seek position of the file will
1107 1107 not be preserved.
1108 1108
1109 1109 This function is similar to calling ``self._chunk()`` multiple times,
1110 1110 but is faster.
1111 1111
1112 1112 Returns a list with decompressed data for each requested revision.
1113 1113 """
1114 1114 if not revs:
1115 1115 return []
1116 1116 start = self.start
1117 1117 length = self.length
1118 1118 inline = self._inline
1119 1119 iosize = self._io.size
1120 1120 buffer = util.buffer
1121 1121
1122 1122 l = []
1123 1123 ladd = l.append
1124 1124
1125 # preload the cache
1126 1125 try:
1127 while True:
1128 # ensure that the cache doesn't change out from under us
1129 _cache = self._chunkcache
1130 self._chunkraw(revs[0], revs[-1], df=df)[1]
1131 if _cache == self._chunkcache:
1132 break
1133 offset, data = _cache
1126 offset, data = self._chunkraw(revs[0], revs[-1], df=df)
1134 1127 except OverflowError:
1135 1128 # issue4215 - we can't cache a run of chunks greater than
1136 1129 # 2G on Windows
1137 1130 return [self._chunk(rev, df=df) for rev in revs]
1138 1131
1139 1132 for rev in revs:
1140 1133 chunkstart = start(rev)
1141 1134 if inline:
1142 1135 chunkstart += (rev + 1) * iosize
1143 1136 chunklength = length(rev)
1144 1137 ladd(decompress(buffer(data, chunkstart - offset, chunklength)))
1145 1138
1146 1139 return l
1147 1140
1148 1141 def _chunkclear(self):
1149 1142 """Clear the raw chunk cache."""
1150 1143 self._chunkcache = (0, '')
1151 1144
1152 1145 def deltaparent(self, rev):
1153 1146 """return deltaparent of the given revision"""
1154 1147 base = self.index[rev][3]
1155 1148 if base == rev:
1156 1149 return nullrev
1157 1150 elif self._generaldelta:
1158 1151 return base
1159 1152 else:
1160 1153 return rev - 1
1161 1154
1162 1155 def revdiff(self, rev1, rev2):
1163 1156 """return or calculate a delta between two revisions"""
1164 1157 if rev1 != nullrev and self.deltaparent(rev2) == rev1:
1165 1158 return str(self._chunk(rev2))
1166 1159
1167 1160 return mdiff.textdiff(self.revision(rev1),
1168 1161 self.revision(rev2))
1169 1162
1170 1163 def revision(self, nodeorrev, _df=None):
1171 1164 """return an uncompressed revision of a given node or revision
1172 1165 number.
1173 1166
1174 1167 _df is an existing file handle to read from. It is meant to only be
1175 1168 used internally.
1176 1169 """
1177 1170 if isinstance(nodeorrev, int):
1178 1171 rev = nodeorrev
1179 1172 node = self.node(rev)
1180 1173 else:
1181 1174 node = nodeorrev
1182 1175 rev = None
1183 1176
1184 1177 cachedrev = None
1185 1178 if node == nullid:
1186 1179 return ""
1187 1180 if self._cache:
1188 1181 if self._cache[0] == node:
1189 1182 return self._cache[2]
1190 1183 cachedrev = self._cache[1]
1191 1184
1192 1185 # look up what we need to read
1193 1186 text = None
1194 1187 if rev is None:
1195 1188 rev = self.rev(node)
1196 1189
1197 1190 # check rev flags
1198 1191 if self.flags(rev) & ~REVIDX_KNOWN_FLAGS:
1199 1192 raise RevlogError(_('incompatible revision flag %x') %
1200 1193 (self.flags(rev) & ~REVIDX_KNOWN_FLAGS))
1201 1194
1202 1195 chain, stopped = self._deltachain(rev, stoprev=cachedrev)
1203 1196 if stopped:
1204 1197 text = self._cache[2]
1205 1198
1206 1199 # drop cache to save memory
1207 1200 self._cache = None
1208 1201
1209 1202 bins = self._chunks(chain, df=_df)
1210 1203 if text is None:
1211 1204 text = str(bins[0])
1212 1205 bins = bins[1:]
1213 1206
1214 1207 text = mdiff.patches(text, bins)
1215 1208
1216 1209 text = self._checkhash(text, node, rev)
1217 1210
1218 1211 self._cache = (node, rev, text)
1219 1212 return text
1220 1213
1221 1214 def hash(self, text, p1, p2):
1222 1215 """Compute a node hash.
1223 1216
1224 1217 Available as a function so that subclasses can replace the hash
1225 1218 as needed.
1226 1219 """
1227 1220 return hash(text, p1, p2)
1228 1221
1229 1222 def _checkhash(self, text, node, rev):
1230 1223 p1, p2 = self.parents(node)
1231 1224 self.checkhash(text, p1, p2, node, rev)
1232 1225 return text
1233 1226
1234 1227 def checkhash(self, text, p1, p2, node, rev=None):
1235 1228 if node != self.hash(text, p1, p2):
1236 1229 revornode = rev
1237 1230 if revornode is None:
1238 1231 revornode = templatefilters.short(hex(node))
1239 1232 raise RevlogError(_("integrity check failed on %s:%s")
1240 1233 % (self.indexfile, revornode))
1241 1234
1242 1235 def checkinlinesize(self, tr, fp=None):
1243 1236 """Check if the revlog is too big for inline and convert if so.
1244 1237
1245 1238 This should be called after revisions are added to the revlog. If the
1246 1239 revlog has grown too large to be an inline revlog, it will convert it
1247 1240 to use multiple index and data files.
1248 1241 """
1249 1242 if not self._inline or (self.start(-2) + self.length(-2)) < _maxinline:
1250 1243 return
1251 1244
1252 1245 trinfo = tr.find(self.indexfile)
1253 1246 if trinfo is None:
1254 1247 raise RevlogError(_("%s not found in the transaction")
1255 1248 % self.indexfile)
1256 1249
1257 1250 trindex = trinfo[2]
1258 1251 if trindex is not None:
1259 1252 dataoff = self.start(trindex)
1260 1253 else:
1261 1254 # revlog was stripped at start of transaction, use all leftover data
1262 1255 trindex = len(self) - 1
1263 1256 dataoff = self.end(-2)
1264 1257
1265 1258 tr.add(self.datafile, dataoff)
1266 1259
1267 1260 if fp:
1268 1261 fp.flush()
1269 1262 fp.close()
1270 1263
1271 1264 df = self.opener(self.datafile, 'w')
1272 1265 try:
1273 1266 for r in self:
1274 1267 df.write(self._chunkraw(r, r)[1])
1275 1268 finally:
1276 1269 df.close()
1277 1270
1278 1271 fp = self.opener(self.indexfile, 'w', atomictemp=True)
1279 1272 self.version &= ~(REVLOGNGINLINEDATA)
1280 1273 self._inline = False
1281 1274 for i in self:
1282 1275 e = self._io.packentry(self.index[i], self.node, self.version, i)
1283 1276 fp.write(e)
1284 1277
1285 1278 # if we don't call close, the temp file will never replace the
1286 1279 # real index
1287 1280 fp.close()
1288 1281
1289 1282 tr.replace(self.indexfile, trindex * self._io.size)
1290 1283 self._chunkclear()
1291 1284
1292 1285 def addrevision(self, text, transaction, link, p1, p2, cachedelta=None,
1293 1286 node=None):
1294 1287 """add a revision to the log
1295 1288
1296 1289 text - the revision data to add
1297 1290 transaction - the transaction object used for rollback
1298 1291 link - the linkrev data to add
1299 1292 p1, p2 - the parent nodeids of the revision
1300 1293 cachedelta - an optional precomputed delta
1301 1294 node - nodeid of revision; typically node is not specified, and it is
1302 1295 computed by default as hash(text, p1, p2), however subclasses might
1303 1296 use different hashing method (and override checkhash() in such case)
1304 1297 """
1305 1298 if link == nullrev:
1306 1299 raise RevlogError(_("attempted to add linkrev -1 to %s")
1307 1300 % self.indexfile)
1308 1301
1309 1302 if len(text) > _maxentrysize:
1310 1303 raise RevlogError(
1311 1304 _("%s: size of %d bytes exceeds maximum revlog storage of 2GiB")
1312 1305 % (self.indexfile, len(text)))
1313 1306
1314 1307 node = node or self.hash(text, p1, p2)
1315 1308 if node in self.nodemap:
1316 1309 return node
1317 1310
1318 1311 dfh = None
1319 1312 if not self._inline:
1320 1313 dfh = self.opener(self.datafile, "a+")
1321 1314 ifh = self.opener(self.indexfile, "a+")
1322 1315 try:
1323 1316 return self._addrevision(node, text, transaction, link, p1, p2,
1324 1317 REVIDX_DEFAULT_FLAGS, cachedelta, ifh, dfh)
1325 1318 finally:
1326 1319 if dfh:
1327 1320 dfh.close()
1328 1321 ifh.close()
1329 1322
1330 1323 def compress(self, text):
1331 1324 """ generate a possibly-compressed representation of text """
1332 1325 if not text:
1333 1326 return ("", text)
1334 1327 l = len(text)
1335 1328 bin = None
1336 1329 if l < 44:
1337 1330 pass
1338 1331 elif l > 1000000:
1339 1332 # zlib makes an internal copy, thus doubling memory usage for
1340 1333 # large files, so lets do this in pieces
1341 1334 z = zlib.compressobj()
1342 1335 p = []
1343 1336 pos = 0
1344 1337 while pos < l:
1345 1338 pos2 = pos + 2**20
1346 1339 p.append(z.compress(text[pos:pos2]))
1347 1340 pos = pos2
1348 1341 p.append(z.flush())
1349 1342 if sum(map(len, p)) < l:
1350 1343 bin = "".join(p)
1351 1344 else:
1352 1345 bin = _compress(text)
1353 1346 if bin is None or len(bin) > l:
1354 1347 if text[0] == '\0':
1355 1348 return ("", text)
1356 1349 return ('u', text)
1357 1350 return ("", bin)
1358 1351
1359 1352 def _isgooddelta(self, d, textlen):
1360 1353 """Returns True if the given delta is good. Good means that it is within
1361 1354 the disk span, disk size, and chain length bounds that we know to be
1362 1355 performant."""
1363 1356 if d is None:
1364 1357 return False
1365 1358
1366 1359 # - 'dist' is the distance from the base revision -- bounding it limits
1367 1360 # the amount of I/O we need to do.
1368 1361 # - 'compresseddeltalen' is the sum of the total size of deltas we need
1369 1362 # to apply -- bounding it limits the amount of CPU we consume.
1370 1363 dist, l, data, base, chainbase, chainlen, compresseddeltalen = d
1371 1364 if (dist > textlen * 4 or l > textlen or
1372 1365 compresseddeltalen > textlen * 2 or
1373 1366 (self._maxchainlen and chainlen > self._maxchainlen)):
1374 1367 return False
1375 1368
1376 1369 return True
1377 1370
1378 1371 def _addrevision(self, node, text, transaction, link, p1, p2, flags,
1379 1372 cachedelta, ifh, dfh, alwayscache=False):
1380 1373 """internal function to add revisions to the log
1381 1374
1382 1375 see addrevision for argument descriptions.
1383 1376 invariants:
1384 1377 - text is optional (can be None); if not set, cachedelta must be set.
1385 1378 if both are set, they must correspond to each other.
1386 1379 """
1387 1380 btext = [text]
1388 1381 def buildtext():
1389 1382 if btext[0] is not None:
1390 1383 return btext[0]
1391 1384 baserev = cachedelta[0]
1392 1385 delta = cachedelta[1]
1393 1386 # special case deltas which replace entire base; no need to decode
1394 1387 # base revision. this neatly avoids censored bases, which throw when
1395 1388 # they're decoded.
1396 1389 hlen = struct.calcsize(">lll")
1397 1390 if delta[:hlen] == mdiff.replacediffheader(self.rawsize(baserev),
1398 1391 len(delta) - hlen):
1399 1392 btext[0] = delta[hlen:]
1400 1393 else:
1401 1394 if self._inline:
1402 1395 fh = ifh
1403 1396 else:
1404 1397 fh = dfh
1405 1398 basetext = self.revision(self.node(baserev), _df=fh)
1406 1399 btext[0] = mdiff.patch(basetext, delta)
1407 1400 try:
1408 1401 self.checkhash(btext[0], p1, p2, node)
1409 1402 if flags & REVIDX_ISCENSORED:
1410 1403 raise RevlogError(_('node %s is not censored') % node)
1411 1404 except CensoredNodeError:
1412 1405 # must pass the censored index flag to add censored revisions
1413 1406 if not flags & REVIDX_ISCENSORED:
1414 1407 raise
1415 1408 return btext[0]
1416 1409
1417 1410 def builddelta(rev):
1418 1411 # can we use the cached delta?
1419 1412 if cachedelta and cachedelta[0] == rev:
1420 1413 delta = cachedelta[1]
1421 1414 else:
1422 1415 t = buildtext()
1423 1416 if self.iscensored(rev):
1424 1417 # deltas based on a censored revision must replace the
1425 1418 # full content in one patch, so delta works everywhere
1426 1419 header = mdiff.replacediffheader(self.rawsize(rev), len(t))
1427 1420 delta = header + t
1428 1421 else:
1429 1422 if self._inline:
1430 1423 fh = ifh
1431 1424 else:
1432 1425 fh = dfh
1433 1426 ptext = self.revision(self.node(rev), _df=fh)
1434 1427 delta = mdiff.textdiff(ptext, t)
1435 1428 data = self.compress(delta)
1436 1429 l = len(data[1]) + len(data[0])
1437 1430 if basecache[0] == rev:
1438 1431 chainbase = basecache[1]
1439 1432 else:
1440 1433 chainbase = self.chainbase(rev)
1441 1434 dist = l + offset - self.start(chainbase)
1442 1435 if self._generaldelta:
1443 1436 base = rev
1444 1437 else:
1445 1438 base = chainbase
1446 1439 chainlen, compresseddeltalen = self._chaininfo(rev)
1447 1440 chainlen += 1
1448 1441 compresseddeltalen += l
1449 1442 return dist, l, data, base, chainbase, chainlen, compresseddeltalen
1450 1443
1451 1444 curr = len(self)
1452 1445 prev = curr - 1
1453 1446 base = chainbase = curr
1454 1447 offset = self.end(prev)
1455 1448 delta = None
1456 1449 if self._basecache is None:
1457 1450 self._basecache = (prev, self.chainbase(prev))
1458 1451 basecache = self._basecache
1459 1452 p1r, p2r = self.rev(p1), self.rev(p2)
1460 1453
1461 1454 # full versions are inserted when the needed deltas
1462 1455 # become comparable to the uncompressed text
1463 1456 if text is None:
1464 1457 textlen = mdiff.patchedsize(self.rawsize(cachedelta[0]),
1465 1458 cachedelta[1])
1466 1459 else:
1467 1460 textlen = len(text)
1468 1461
1469 1462 # should we try to build a delta?
1470 1463 if prev != nullrev:
1471 1464 tested = set()
1472 1465 if cachedelta and self._generaldelta and self._lazydeltabase:
1473 1466 # Assume what we received from the server is a good choice
1474 1467 # build delta will reuse the cache
1475 1468 candidatedelta = builddelta(cachedelta[0])
1476 1469 tested.add(cachedelta[0])
1477 1470 if self._isgooddelta(candidatedelta, textlen):
1478 1471 delta = candidatedelta
1479 1472 if delta is None and self._generaldelta:
1480 1473 # exclude already lazy tested base if any
1481 1474 parents = [p for p in (p1r, p2r)
1482 1475 if p != nullrev and p not in tested]
1483 1476 if parents and not self._aggressivemergedeltas:
1484 1477 # Pick whichever parent is closer to us (to minimize the
1485 1478 # chance of having to build a fulltext).
1486 1479 parents = [max(parents)]
1487 1480 tested.update(parents)
1488 1481 pdeltas = []
1489 1482 for p in parents:
1490 1483 pd = builddelta(p)
1491 1484 if self._isgooddelta(pd, textlen):
1492 1485 pdeltas.append(pd)
1493 1486 if pdeltas:
1494 1487 delta = min(pdeltas, key=lambda x: x[1])
1495 1488 if delta is None and prev not in tested:
1496 1489 # other approach failed try against prev to hopefully save us a
1497 1490 # fulltext.
1498 1491 candidatedelta = builddelta(prev)
1499 1492 if self._isgooddelta(candidatedelta, textlen):
1500 1493 delta = candidatedelta
1501 1494 if delta is not None:
1502 1495 dist, l, data, base, chainbase, chainlen, compresseddeltalen = delta
1503 1496 else:
1504 1497 text = buildtext()
1505 1498 data = self.compress(text)
1506 1499 l = len(data[1]) + len(data[0])
1507 1500 base = chainbase = curr
1508 1501
1509 1502 e = (offset_type(offset, flags), l, textlen,
1510 1503 base, link, p1r, p2r, node)
1511 1504 self.index.insert(-1, e)
1512 1505 self.nodemap[node] = curr
1513 1506
1514 1507 entry = self._io.packentry(e, self.node, self.version, curr)
1515 1508 self._writeentry(transaction, ifh, dfh, entry, data, link, offset)
1516 1509
1517 1510 if alwayscache and text is None:
1518 1511 text = buildtext()
1519 1512
1520 1513 if type(text) == str: # only accept immutable objects
1521 1514 self._cache = (node, curr, text)
1522 1515 self._basecache = (curr, chainbase)
1523 1516 return node
1524 1517
1525 1518 def _writeentry(self, transaction, ifh, dfh, entry, data, link, offset):
1526 1519 # Files opened in a+ mode have inconsistent behavior on various
1527 1520 # platforms. Windows requires that a file positioning call be made
1528 1521 # when the file handle transitions between reads and writes. See
1529 1522 # 3686fa2b8eee and the mixedfilemodewrapper in windows.py. On other
1530 1523 # platforms, Python or the platform itself can be buggy. Some versions
1531 1524 # of Solaris have been observed to not append at the end of the file
1532 1525 # if the file was seeked to before the end. See issue4943 for more.
1533 1526 #
1534 1527 # We work around this issue by inserting a seek() before writing.
1535 1528 # Note: This is likely not necessary on Python 3.
1536 1529 ifh.seek(0, os.SEEK_END)
1537 1530 if dfh:
1538 1531 dfh.seek(0, os.SEEK_END)
1539 1532
1540 1533 curr = len(self) - 1
1541 1534 if not self._inline:
1542 1535 transaction.add(self.datafile, offset)
1543 1536 transaction.add(self.indexfile, curr * len(entry))
1544 1537 if data[0]:
1545 1538 dfh.write(data[0])
1546 1539 dfh.write(data[1])
1547 1540 ifh.write(entry)
1548 1541 else:
1549 1542 offset += curr * self._io.size
1550 1543 transaction.add(self.indexfile, offset, curr)
1551 1544 ifh.write(entry)
1552 1545 ifh.write(data[0])
1553 1546 ifh.write(data[1])
1554 1547 self.checkinlinesize(transaction, ifh)
1555 1548
1556 1549 def addgroup(self, cg, linkmapper, transaction, addrevisioncb=None):
1557 1550 """
1558 1551 add a delta group
1559 1552
1560 1553 given a set of deltas, add them to the revision log. the
1561 1554 first delta is against its parent, which should be in our
1562 1555 log, the rest are against the previous delta.
1563 1556
1564 1557 If ``addrevisioncb`` is defined, it will be called with arguments of
1565 1558 this revlog and the node that was added.
1566 1559 """
1567 1560
1568 1561 # track the base of the current delta log
1569 1562 content = []
1570 1563 node = None
1571 1564
1572 1565 r = len(self)
1573 1566 end = 0
1574 1567 if r:
1575 1568 end = self.end(r - 1)
1576 1569 ifh = self.opener(self.indexfile, "a+")
1577 1570 isize = r * self._io.size
1578 1571 if self._inline:
1579 1572 transaction.add(self.indexfile, end + isize, r)
1580 1573 dfh = None
1581 1574 else:
1582 1575 transaction.add(self.indexfile, isize, r)
1583 1576 transaction.add(self.datafile, end)
1584 1577 dfh = self.opener(self.datafile, "a+")
1585 1578 def flush():
1586 1579 if dfh:
1587 1580 dfh.flush()
1588 1581 ifh.flush()
1589 1582 try:
1590 1583 # loop through our set of deltas
1591 1584 chain = None
1592 1585 while True:
1593 1586 chunkdata = cg.deltachunk(chain)
1594 1587 if not chunkdata:
1595 1588 break
1596 1589 node = chunkdata['node']
1597 1590 p1 = chunkdata['p1']
1598 1591 p2 = chunkdata['p2']
1599 1592 cs = chunkdata['cs']
1600 1593 deltabase = chunkdata['deltabase']
1601 1594 delta = chunkdata['delta']
1602 1595 flags = chunkdata['flags'] or REVIDX_DEFAULT_FLAGS
1603 1596
1604 1597 content.append(node)
1605 1598
1606 1599 link = linkmapper(cs)
1607 1600 if node in self.nodemap:
1608 1601 # this can happen if two branches make the same change
1609 1602 chain = node
1610 1603 continue
1611 1604
1612 1605 for p in (p1, p2):
1613 1606 if p not in self.nodemap:
1614 1607 raise LookupError(p, self.indexfile,
1615 1608 _('unknown parent'))
1616 1609
1617 1610 if deltabase not in self.nodemap:
1618 1611 raise LookupError(deltabase, self.indexfile,
1619 1612 _('unknown delta base'))
1620 1613
1621 1614 baserev = self.rev(deltabase)
1622 1615
1623 1616 if baserev != nullrev and self.iscensored(baserev):
1624 1617 # if base is censored, delta must be full replacement in a
1625 1618 # single patch operation
1626 1619 hlen = struct.calcsize(">lll")
1627 1620 oldlen = self.rawsize(baserev)
1628 1621 newlen = len(delta) - hlen
1629 1622 if delta[:hlen] != mdiff.replacediffheader(oldlen, newlen):
1630 1623 raise error.CensoredBaseError(self.indexfile,
1631 1624 self.node(baserev))
1632 1625
1633 1626 if not flags and self._peek_iscensored(baserev, delta, flush):
1634 1627 flags |= REVIDX_ISCENSORED
1635 1628
1636 1629 # We assume consumers of addrevisioncb will want to retrieve
1637 1630 # the added revision, which will require a call to
1638 1631 # revision(). revision() will fast path if there is a cache
1639 1632 # hit. So, we tell _addrevision() to always cache in this case.
1640 1633 chain = self._addrevision(node, None, transaction, link,
1641 1634 p1, p2, flags, (baserev, delta),
1642 1635 ifh, dfh,
1643 1636 alwayscache=bool(addrevisioncb))
1644 1637
1645 1638 if addrevisioncb:
1646 1639 addrevisioncb(self, chain)
1647 1640
1648 1641 if not dfh and not self._inline:
1649 1642 # addrevision switched from inline to conventional
1650 1643 # reopen the index
1651 1644 ifh.close()
1652 1645 dfh = self.opener(self.datafile, "a+")
1653 1646 ifh = self.opener(self.indexfile, "a+")
1654 1647 finally:
1655 1648 if dfh:
1656 1649 dfh.close()
1657 1650 ifh.close()
1658 1651
1659 1652 return content
1660 1653
1661 1654 def iscensored(self, rev):
1662 1655 """Check if a file revision is censored."""
1663 1656 return False
1664 1657
1665 1658 def _peek_iscensored(self, baserev, delta, flush):
1666 1659 """Quickly check if a delta produces a censored revision."""
1667 1660 return False
1668 1661
1669 1662 def getstrippoint(self, minlink):
1670 1663 """find the minimum rev that must be stripped to strip the linkrev
1671 1664
1672 1665 Returns a tuple containing the minimum rev and a set of all revs that
1673 1666 have linkrevs that will be broken by this strip.
1674 1667 """
1675 1668 brokenrevs = set()
1676 1669 strippoint = len(self)
1677 1670
1678 1671 heads = {}
1679 1672 futurelargelinkrevs = set()
1680 1673 for head in self.headrevs():
1681 1674 headlinkrev = self.linkrev(head)
1682 1675 heads[head] = headlinkrev
1683 1676 if headlinkrev >= minlink:
1684 1677 futurelargelinkrevs.add(headlinkrev)
1685 1678
1686 1679 # This algorithm involves walking down the rev graph, starting at the
1687 1680 # heads. Since the revs are topologically sorted according to linkrev,
1688 1681 # once all head linkrevs are below the minlink, we know there are
1689 1682 # no more revs that could have a linkrev greater than minlink.
1690 1683 # So we can stop walking.
1691 1684 while futurelargelinkrevs:
1692 1685 strippoint -= 1
1693 1686 linkrev = heads.pop(strippoint)
1694 1687
1695 1688 if linkrev < minlink:
1696 1689 brokenrevs.add(strippoint)
1697 1690 else:
1698 1691 futurelargelinkrevs.remove(linkrev)
1699 1692
1700 1693 for p in self.parentrevs(strippoint):
1701 1694 if p != nullrev:
1702 1695 plinkrev = self.linkrev(p)
1703 1696 heads[p] = plinkrev
1704 1697 if plinkrev >= minlink:
1705 1698 futurelargelinkrevs.add(plinkrev)
1706 1699
1707 1700 return strippoint, brokenrevs
1708 1701
1709 1702 def strip(self, minlink, transaction):
1710 1703 """truncate the revlog on the first revision with a linkrev >= minlink
1711 1704
1712 1705 This function is called when we're stripping revision minlink and
1713 1706 its descendants from the repository.
1714 1707
1715 1708 We have to remove all revisions with linkrev >= minlink, because
1716 1709 the equivalent changelog revisions will be renumbered after the
1717 1710 strip.
1718 1711
1719 1712 So we truncate the revlog on the first of these revisions, and
1720 1713 trust that the caller has saved the revisions that shouldn't be
1721 1714 removed and that it'll re-add them after this truncation.
1722 1715 """
1723 1716 if len(self) == 0:
1724 1717 return
1725 1718
1726 1719 rev, _ = self.getstrippoint(minlink)
1727 1720 if rev == len(self):
1728 1721 return
1729 1722
1730 1723 # first truncate the files on disk
1731 1724 end = self.start(rev)
1732 1725 if not self._inline:
1733 1726 transaction.add(self.datafile, end)
1734 1727 end = rev * self._io.size
1735 1728 else:
1736 1729 end += rev * self._io.size
1737 1730
1738 1731 transaction.add(self.indexfile, end)
1739 1732
1740 1733 # then reset internal state in memory to forget those revisions
1741 1734 self._cache = None
1742 1735 self._chaininfocache = {}
1743 1736 self._chunkclear()
1744 1737 for x in xrange(rev, len(self)):
1745 1738 del self.nodemap[self.node(x)]
1746 1739
1747 1740 del self.index[rev:-1]
1748 1741
1749 1742 def checksize(self):
1750 1743 expected = 0
1751 1744 if len(self):
1752 1745 expected = max(0, self.end(len(self) - 1))
1753 1746
1754 1747 try:
1755 1748 f = self.opener(self.datafile)
1756 1749 f.seek(0, 2)
1757 1750 actual = f.tell()
1758 1751 f.close()
1759 1752 dd = actual - expected
1760 1753 except IOError as inst:
1761 1754 if inst.errno != errno.ENOENT:
1762 1755 raise
1763 1756 dd = 0
1764 1757
1765 1758 try:
1766 1759 f = self.opener(self.indexfile)
1767 1760 f.seek(0, 2)
1768 1761 actual = f.tell()
1769 1762 f.close()
1770 1763 s = self._io.size
1771 1764 i = max(0, actual // s)
1772 1765 di = actual - (i * s)
1773 1766 if self._inline:
1774 1767 databytes = 0
1775 1768 for r in self:
1776 1769 databytes += max(0, self.length(r))
1777 1770 dd = 0
1778 1771 di = actual - len(self) * s - databytes
1779 1772 except IOError as inst:
1780 1773 if inst.errno != errno.ENOENT:
1781 1774 raise
1782 1775 di = 0
1783 1776
1784 1777 return (dd, di)
1785 1778
1786 1779 def files(self):
1787 1780 res = [self.indexfile]
1788 1781 if not self._inline:
1789 1782 res.append(self.datafile)
1790 1783 return res
General Comments 0
You need to be logged in to leave comments. Login now