##// END OF EJS Templates
changelog: drop the side_write argument to revlog splitting...
marmoute -
r52210:5b3b6db4 default
parent child Browse files
Show More
@@ -1,507 +1,507 b''
1 1 # changelog.py - changelog class for mercurial
2 2 #
3 3 # Copyright 2005-2007 Olivia Mackall <olivia@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
9 9 from .i18n import _
10 10 from .node import (
11 11 bin,
12 12 hex,
13 13 )
14 14 from .thirdparty import attr
15 15
16 16 from . import (
17 17 encoding,
18 18 error,
19 19 metadata,
20 20 pycompat,
21 21 revlog,
22 22 )
23 23 from .utils import (
24 24 dateutil,
25 25 stringutil,
26 26 )
27 27 from .revlogutils import (
28 28 constants as revlog_constants,
29 29 flagutil,
30 30 )
31 31
32 32 _defaultextra = {b'branch': b'default'}
33 33
34 34
35 35 def _string_escape(text):
36 36 """
37 37 >>> from .pycompat import bytechr as chr
38 38 >>> d = {b'nl': chr(10), b'bs': chr(92), b'cr': chr(13), b'nul': chr(0)}
39 39 >>> s = b"ab%(nl)scd%(bs)s%(bs)sn%(nul)s12ab%(cr)scd%(bs)s%(nl)s" % d
40 40 >>> s
41 41 'ab\\ncd\\\\\\\\n\\x0012ab\\rcd\\\\\\n'
42 42 >>> res = _string_escape(s)
43 43 >>> s == _string_unescape(res)
44 44 True
45 45 """
46 46 # subset of the string_escape codec
47 47 text = (
48 48 text.replace(b'\\', b'\\\\')
49 49 .replace(b'\n', b'\\n')
50 50 .replace(b'\r', b'\\r')
51 51 )
52 52 return text.replace(b'\0', b'\\0')
53 53
54 54
55 55 def _string_unescape(text):
56 56 if b'\\0' in text:
57 57 # fix up \0 without getting into trouble with \\0
58 58 text = text.replace(b'\\\\', b'\\\\\n')
59 59 text = text.replace(b'\\0', b'\0')
60 60 text = text.replace(b'\n', b'')
61 61 return stringutil.unescapestr(text)
62 62
63 63
64 64 def decodeextra(text):
65 65 """
66 66 >>> from .pycompat import bytechr as chr
67 67 >>> sorted(decodeextra(encodeextra({b'foo': b'bar', b'baz': chr(0) + b'2'})
68 68 ... ).items())
69 69 [('baz', '\\x002'), ('branch', 'default'), ('foo', 'bar')]
70 70 >>> sorted(decodeextra(encodeextra({b'foo': b'bar',
71 71 ... b'baz': chr(92) + chr(0) + b'2'})
72 72 ... ).items())
73 73 [('baz', '\\\\\\x002'), ('branch', 'default'), ('foo', 'bar')]
74 74 """
75 75 extra = _defaultextra.copy()
76 76 for l in text.split(b'\0'):
77 77 if l:
78 78 k, v = _string_unescape(l).split(b':', 1)
79 79 extra[k] = v
80 80 return extra
81 81
82 82
83 83 def encodeextra(d):
84 84 # keys must be sorted to produce a deterministic changelog entry
85 85 items = [_string_escape(b'%s:%s' % (k, d[k])) for k in sorted(d)]
86 86 return b"\0".join(items)
87 87
88 88
89 89 def stripdesc(desc):
90 90 """strip trailing whitespace and leading and trailing empty lines"""
91 91 return b'\n'.join([l.rstrip() for l in desc.splitlines()]).strip(b'\n')
92 92
93 93
94 94 @attr.s
95 95 class _changelogrevision:
96 96 # Extensions might modify _defaultextra, so let the constructor below pass
97 97 # it in
98 98 extra = attr.ib()
99 99 manifest = attr.ib()
100 100 user = attr.ib(default=b'')
101 101 date = attr.ib(default=(0, 0))
102 102 files = attr.ib(default=attr.Factory(list))
103 103 filesadded = attr.ib(default=None)
104 104 filesremoved = attr.ib(default=None)
105 105 p1copies = attr.ib(default=None)
106 106 p2copies = attr.ib(default=None)
107 107 description = attr.ib(default=b'')
108 108 branchinfo = attr.ib(default=(_defaultextra[b'branch'], False))
109 109
110 110
111 111 class changelogrevision:
112 112 """Holds results of a parsed changelog revision.
113 113
114 114 Changelog revisions consist of multiple pieces of data, including
115 115 the manifest node, user, and date. This object exposes a view into
116 116 the parsed object.
117 117 """
118 118
119 119 __slots__ = (
120 120 '_offsets',
121 121 '_text',
122 122 '_sidedata',
123 123 '_cpsd',
124 124 '_changes',
125 125 )
126 126
127 127 def __new__(cls, cl, text, sidedata, cpsd):
128 128 if not text:
129 129 return _changelogrevision(extra=_defaultextra, manifest=cl.nullid)
130 130
131 131 self = super(changelogrevision, cls).__new__(cls)
132 132 # We could return here and implement the following as an __init__.
133 133 # But doing it here is equivalent and saves an extra function call.
134 134
135 135 # format used:
136 136 # nodeid\n : manifest node in ascii
137 137 # user\n : user, no \n or \r allowed
138 138 # time tz extra\n : date (time is int or float, timezone is int)
139 139 # : extra is metadata, encoded and separated by '\0'
140 140 # : older versions ignore it
141 141 # files\n\n : files modified by the cset, no \n or \r allowed
142 142 # (.*) : comment (free text, ideally utf-8)
143 143 #
144 144 # changelog v0 doesn't use extra
145 145
146 146 nl1 = text.index(b'\n')
147 147 nl2 = text.index(b'\n', nl1 + 1)
148 148 nl3 = text.index(b'\n', nl2 + 1)
149 149
150 150 # The list of files may be empty. Which means nl3 is the first of the
151 151 # double newline that precedes the description.
152 152 if text[nl3 + 1 : nl3 + 2] == b'\n':
153 153 doublenl = nl3
154 154 else:
155 155 doublenl = text.index(b'\n\n', nl3 + 1)
156 156
157 157 self._offsets = (nl1, nl2, nl3, doublenl)
158 158 self._text = text
159 159 self._sidedata = sidedata
160 160 self._cpsd = cpsd
161 161 self._changes = None
162 162
163 163 return self
164 164
165 165 @property
166 166 def manifest(self):
167 167 return bin(self._text[0 : self._offsets[0]])
168 168
169 169 @property
170 170 def user(self):
171 171 off = self._offsets
172 172 return encoding.tolocal(self._text[off[0] + 1 : off[1]])
173 173
174 174 @property
175 175 def _rawdate(self):
176 176 off = self._offsets
177 177 dateextra = self._text[off[1] + 1 : off[2]]
178 178 return dateextra.split(b' ', 2)[0:2]
179 179
180 180 @property
181 181 def _rawextra(self):
182 182 off = self._offsets
183 183 dateextra = self._text[off[1] + 1 : off[2]]
184 184 fields = dateextra.split(b' ', 2)
185 185 if len(fields) != 3:
186 186 return None
187 187
188 188 return fields[2]
189 189
190 190 @property
191 191 def date(self):
192 192 raw = self._rawdate
193 193 time = float(raw[0])
194 194 # Various tools did silly things with the timezone.
195 195 try:
196 196 timezone = int(raw[1])
197 197 except ValueError:
198 198 timezone = 0
199 199
200 200 return time, timezone
201 201
202 202 @property
203 203 def extra(self):
204 204 raw = self._rawextra
205 205 if raw is None:
206 206 return _defaultextra
207 207
208 208 return decodeextra(raw)
209 209
210 210 @property
211 211 def changes(self):
212 212 if self._changes is not None:
213 213 return self._changes
214 214 if self._cpsd:
215 215 changes = metadata.decode_files_sidedata(self._sidedata)
216 216 else:
217 217 changes = metadata.ChangingFiles(
218 218 touched=self.files or (),
219 219 added=self.filesadded or (),
220 220 removed=self.filesremoved or (),
221 221 p1_copies=self.p1copies or {},
222 222 p2_copies=self.p2copies or {},
223 223 )
224 224 self._changes = changes
225 225 return changes
226 226
227 227 @property
228 228 def files(self):
229 229 if self._cpsd:
230 230 return sorted(self.changes.touched)
231 231 off = self._offsets
232 232 if off[2] == off[3]:
233 233 return []
234 234
235 235 return self._text[off[2] + 1 : off[3]].split(b'\n')
236 236
237 237 @property
238 238 def filesadded(self):
239 239 if self._cpsd:
240 240 return self.changes.added
241 241 else:
242 242 rawindices = self.extra.get(b'filesadded')
243 243 if rawindices is None:
244 244 return None
245 245 return metadata.decodefileindices(self.files, rawindices)
246 246
247 247 @property
248 248 def filesremoved(self):
249 249 if self._cpsd:
250 250 return self.changes.removed
251 251 else:
252 252 rawindices = self.extra.get(b'filesremoved')
253 253 if rawindices is None:
254 254 return None
255 255 return metadata.decodefileindices(self.files, rawindices)
256 256
257 257 @property
258 258 def p1copies(self):
259 259 if self._cpsd:
260 260 return self.changes.copied_from_p1
261 261 else:
262 262 rawcopies = self.extra.get(b'p1copies')
263 263 if rawcopies is None:
264 264 return None
265 265 return metadata.decodecopies(self.files, rawcopies)
266 266
267 267 @property
268 268 def p2copies(self):
269 269 if self._cpsd:
270 270 return self.changes.copied_from_p2
271 271 else:
272 272 rawcopies = self.extra.get(b'p2copies')
273 273 if rawcopies is None:
274 274 return None
275 275 return metadata.decodecopies(self.files, rawcopies)
276 276
277 277 @property
278 278 def description(self):
279 279 return encoding.tolocal(self._text[self._offsets[3] + 2 :])
280 280
281 281 @property
282 282 def branchinfo(self):
283 283 extra = self.extra
284 284 return encoding.tolocal(extra.get(b"branch")), b'close' in extra
285 285
286 286
287 287 class changelog(revlog.revlog):
288 288 def __init__(self, opener, trypending=False, concurrencychecker=None):
289 289 """Load a changelog revlog using an opener.
290 290
291 291 If ``trypending`` is true, we attempt to load the index from a
292 292 ``00changelog.i.a`` file instead of the default ``00changelog.i``.
293 293 The ``00changelog.i.a`` file contains index (and possibly inline
294 294 revision) data for a transaction that hasn't been finalized yet.
295 295 It exists in a separate file to facilitate readers (such as
296 296 hooks processes) accessing data before a transaction is finalized.
297 297
298 298 ``concurrencychecker`` will be passed to the revlog init function, see
299 299 the documentation there.
300 300 """
301 301 revlog.revlog.__init__(
302 302 self,
303 303 opener,
304 304 target=(revlog_constants.KIND_CHANGELOG, None),
305 305 radix=b'00changelog',
306 306 checkambig=True,
307 307 mmaplargeindex=True,
308 308 persistentnodemap=opener.options.get(b'persistent-nodemap', False),
309 309 concurrencychecker=concurrencychecker,
310 310 trypending=trypending,
311 311 may_inline=False,
312 312 )
313 313
314 314 if self._initempty and (self._format_version == revlog.REVLOGV1):
315 315 # changelogs don't benefit from generaldelta.
316 316
317 317 self._format_flags &= ~revlog.FLAG_GENERALDELTA
318 318 self.delta_config.general_delta = False
319 319
320 320 # Delta chains for changelogs tend to be very small because entries
321 321 # tend to be small and don't delta well with each. So disable delta
322 322 # chains.
323 323 self._storedeltachains = False
324 324
325 325 self._v2_delayed = False
326 326 self._filteredrevs = frozenset()
327 327 self._filteredrevs_hashcache = {}
328 328 self._copiesstorage = opener.options.get(b'copies-storage')
329 329
330 330 @property
331 331 def filteredrevs(self):
332 332 return self._filteredrevs
333 333
334 334 @filteredrevs.setter
335 335 def filteredrevs(self, val):
336 336 # Ensure all updates go through this function
337 337 assert isinstance(val, frozenset)
338 338 self._filteredrevs = val
339 339 self._filteredrevs_hashcache = {}
340 340
341 341 def _write_docket(self, tr):
342 342 if not self._v2_delayed:
343 343 super(changelog, self)._write_docket(tr)
344 344
345 345 def delayupdate(self, tr):
346 346 """delay visibility of index updates to other readers"""
347 347 assert not self._inner.is_open
348 348 assert not self._may_inline
349 349 # enforce that older changelog that are still inline are split at the
350 350 # first opportunity.
351 351 if self._inline:
352 352 self._enforceinlinesize(tr)
353 353 if self._docket is not None:
354 354 self._v2_delayed = True
355 355 else:
356 356 new_index = self._inner.delay()
357 357 if new_index is not None:
358 358 self._indexfile = new_index
359 359 tr.registertmp(new_index)
360 360 tr.addpending(b'cl-%i' % id(self), self._writepending)
361 361 tr.addfinalize(b'cl-%i' % id(self), self._finalize)
362 362
363 363 def _finalize(self, tr):
364 364 """finalize index updates"""
365 365 assert not self._inner.is_open
366 366 if self._docket is not None:
367 367 self._docket.write(tr)
368 368 self._v2_delayed = False
369 369 else:
370 370 new_index_file = self._inner.finalize_pending()
371 371 self._indexfile = new_index_file
372 372 if self._inline:
373 373 msg = 'changelog should not be inline at that point'
374 374 raise error.ProgrammingError(msg)
375 375
376 376 def _writepending(self, tr):
377 377 """create a file containing the unfinalized state for
378 378 pretxnchangegroup"""
379 379 assert not self._inner.is_open
380 380 if self._docket:
381 381 any_pending = self._docket.write(tr, pending=True)
382 382 self._v2_delayed = False
383 383 else:
384 384 new_index, any_pending = self._inner.write_pending()
385 385 if new_index is not None:
386 386 self._indexfile = new_index
387 387 tr.registertmp(new_index)
388 388 return any_pending
389 389
390 def _enforceinlinesize(self, tr, side_write=True):
390 def _enforceinlinesize(self, tr):
391 391 if not self.is_delaying:
392 revlog.revlog._enforceinlinesize(self, tr, side_write=side_write)
392 revlog.revlog._enforceinlinesize(self, tr)
393 393
394 394 def read(self, nodeorrev):
395 395 """Obtain data from a parsed changelog revision.
396 396
397 397 Returns a 6-tuple of:
398 398
399 399 - manifest node in binary
400 400 - author/user as a localstr
401 401 - date as a 2-tuple of (time, timezone)
402 402 - list of files
403 403 - commit message as a localstr
404 404 - dict of extra metadata
405 405
406 406 Unless you need to access all fields, consider calling
407 407 ``changelogrevision`` instead, as it is faster for partial object
408 408 access.
409 409 """
410 410 d = self._revisiondata(nodeorrev)
411 411 sidedata = self.sidedata(nodeorrev)
412 412 copy_sd = self._copiesstorage == b'changeset-sidedata'
413 413 c = changelogrevision(self, d, sidedata, copy_sd)
414 414 return (c.manifest, c.user, c.date, c.files, c.description, c.extra)
415 415
416 416 def changelogrevision(self, nodeorrev):
417 417 """Obtain a ``changelogrevision`` for a node or revision."""
418 418 text = self._revisiondata(nodeorrev)
419 419 sidedata = self.sidedata(nodeorrev)
420 420 return changelogrevision(
421 421 self, text, sidedata, self._copiesstorage == b'changeset-sidedata'
422 422 )
423 423
424 424 def readfiles(self, nodeorrev):
425 425 """
426 426 short version of read that only returns the files modified by the cset
427 427 """
428 428 text = self.revision(nodeorrev)
429 429 if not text:
430 430 return []
431 431 last = text.index(b"\n\n")
432 432 l = text[:last].split(b'\n')
433 433 return l[3:]
434 434
435 435 def add(
436 436 self,
437 437 manifest,
438 438 files,
439 439 desc,
440 440 transaction,
441 441 p1,
442 442 p2,
443 443 user,
444 444 date=None,
445 445 extra=None,
446 446 ):
447 447 # Convert to UTF-8 encoded bytestrings as the very first
448 448 # thing: calling any method on a localstr object will turn it
449 449 # into a str object and the cached UTF-8 string is thus lost.
450 450 user, desc = encoding.fromlocal(user), encoding.fromlocal(desc)
451 451
452 452 user = user.strip()
453 453 # An empty username or a username with a "\n" will make the
454 454 # revision text contain two "\n\n" sequences -> corrupt
455 455 # repository since read cannot unpack the revision.
456 456 if not user:
457 457 raise error.StorageError(_(b"empty username"))
458 458 if b"\n" in user:
459 459 raise error.StorageError(
460 460 _(b"username %r contains a newline") % pycompat.bytestr(user)
461 461 )
462 462
463 463 desc = stripdesc(desc)
464 464
465 465 if date:
466 466 parseddate = b"%d %d" % dateutil.parsedate(date)
467 467 else:
468 468 parseddate = b"%d %d" % dateutil.makedate()
469 469 if extra:
470 470 branch = extra.get(b"branch")
471 471 if branch in (b"default", b""):
472 472 del extra[b"branch"]
473 473 elif branch in (b".", b"null", b"tip"):
474 474 raise error.StorageError(
475 475 _(b'the name \'%s\' is reserved') % branch
476 476 )
477 477 sortedfiles = sorted(files.touched)
478 478 flags = 0
479 479 sidedata = None
480 480 if self._copiesstorage == b'changeset-sidedata':
481 481 if files.has_copies_info:
482 482 flags |= flagutil.REVIDX_HASCOPIESINFO
483 483 sidedata = metadata.encode_files_sidedata(files)
484 484
485 485 if extra:
486 486 extra = encodeextra(extra)
487 487 parseddate = b"%s %s" % (parseddate, extra)
488 488 l = [hex(manifest), user, parseddate] + sortedfiles + [b"", desc]
489 489 text = b"\n".join(l)
490 490 rev = self.addrevision(
491 491 text, transaction, len(self), p1, p2, sidedata=sidedata, flags=flags
492 492 )
493 493 return self.node(rev)
494 494
495 495 def branchinfo(self, rev):
496 496 """return the branch name and open/close state of a revision
497 497
498 498 This function exists because creating a changectx object
499 499 just to access this is costly."""
500 500 return self.changelogrevision(rev).branchinfo
501 501
502 502 def _nodeduplicatecallback(self, transaction, rev):
503 503 # keep track of revisions that got "re-added", eg: unbunde of know rev.
504 504 #
505 505 # We track them in a list to preserve their order from the source bundle
506 506 duplicates = transaction.changes.setdefault(b'revduplicates', [])
507 507 duplicates.append(rev)
@@ -1,4067 +1,4066 b''
1 1 # revlog.py - storage back-end for mercurial
2 2 # coding: utf8
3 3 #
4 4 # Copyright 2005-2007 Olivia Mackall <olivia@selenic.com>
5 5 #
6 6 # This software may be used and distributed according to the terms of the
7 7 # GNU General Public License version 2 or any later version.
8 8
9 9 """Storage back-end for Mercurial.
10 10
11 11 This provides efficient delta storage with O(1) retrieve and append
12 12 and O(changes) merge between branches.
13 13 """
14 14
15 15
16 16 import binascii
17 17 import collections
18 18 import contextlib
19 19 import functools
20 20 import io
21 21 import os
22 22 import struct
23 23 import weakref
24 24 import zlib
25 25
26 26 # import stuff from node for others to import from revlog
27 27 from .node import (
28 28 bin,
29 29 hex,
30 30 nullrev,
31 31 sha1nodeconstants,
32 32 short,
33 33 wdirrev,
34 34 )
35 35 from .i18n import _
36 36 from .revlogutils.constants import (
37 37 ALL_KINDS,
38 38 CHANGELOGV2,
39 39 COMP_MODE_DEFAULT,
40 40 COMP_MODE_INLINE,
41 41 COMP_MODE_PLAIN,
42 42 DELTA_BASE_REUSE_NO,
43 43 DELTA_BASE_REUSE_TRY,
44 44 ENTRY_RANK,
45 45 FEATURES_BY_VERSION,
46 46 FLAG_GENERALDELTA,
47 47 FLAG_INLINE_DATA,
48 48 INDEX_HEADER,
49 49 KIND_CHANGELOG,
50 50 KIND_FILELOG,
51 51 RANK_UNKNOWN,
52 52 REVLOGV0,
53 53 REVLOGV1,
54 54 REVLOGV1_FLAGS,
55 55 REVLOGV2,
56 56 REVLOGV2_FLAGS,
57 57 REVLOG_DEFAULT_FLAGS,
58 58 REVLOG_DEFAULT_FORMAT,
59 59 REVLOG_DEFAULT_VERSION,
60 60 SUPPORTED_FLAGS,
61 61 )
62 62 from .revlogutils.flagutil import (
63 63 REVIDX_DEFAULT_FLAGS,
64 64 REVIDX_ELLIPSIS,
65 65 REVIDX_EXTSTORED,
66 66 REVIDX_FLAGS_ORDER,
67 67 REVIDX_HASCOPIESINFO,
68 68 REVIDX_ISCENSORED,
69 69 REVIDX_RAWTEXT_CHANGING_FLAGS,
70 70 )
71 71 from .thirdparty import attr
72 72 from . import (
73 73 ancestor,
74 74 dagop,
75 75 error,
76 76 mdiff,
77 77 policy,
78 78 pycompat,
79 79 revlogutils,
80 80 templatefilters,
81 81 util,
82 82 )
83 83 from .interfaces import (
84 84 repository,
85 85 util as interfaceutil,
86 86 )
87 87 from .revlogutils import (
88 88 deltas as deltautil,
89 89 docket as docketutil,
90 90 flagutil,
91 91 nodemap as nodemaputil,
92 92 randomaccessfile,
93 93 revlogv0,
94 94 rewrite,
95 95 sidedata as sidedatautil,
96 96 )
97 97 from .utils import (
98 98 storageutil,
99 99 stringutil,
100 100 )
101 101
102 102 # blanked usage of all the name to prevent pyflakes constraints
103 103 # We need these name available in the module for extensions.
104 104
105 105 REVLOGV0
106 106 REVLOGV1
107 107 REVLOGV2
108 108 CHANGELOGV2
109 109 FLAG_INLINE_DATA
110 110 FLAG_GENERALDELTA
111 111 REVLOG_DEFAULT_FLAGS
112 112 REVLOG_DEFAULT_FORMAT
113 113 REVLOG_DEFAULT_VERSION
114 114 REVLOGV1_FLAGS
115 115 REVLOGV2_FLAGS
116 116 REVIDX_ISCENSORED
117 117 REVIDX_ELLIPSIS
118 118 REVIDX_HASCOPIESINFO
119 119 REVIDX_EXTSTORED
120 120 REVIDX_DEFAULT_FLAGS
121 121 REVIDX_FLAGS_ORDER
122 122 REVIDX_RAWTEXT_CHANGING_FLAGS
123 123
124 124 parsers = policy.importmod('parsers')
125 125 rustancestor = policy.importrust('ancestor')
126 126 rustdagop = policy.importrust('dagop')
127 127 rustrevlog = policy.importrust('revlog')
128 128
129 129 # Aliased for performance.
130 130 _zlibdecompress = zlib.decompress
131 131
132 132 # max size of inline data embedded into a revlog
133 133 _maxinline = 131072
134 134
135 135 # Flag processors for REVIDX_ELLIPSIS.
136 136 def ellipsisreadprocessor(rl, text):
137 137 return text, False
138 138
139 139
140 140 def ellipsiswriteprocessor(rl, text):
141 141 return text, False
142 142
143 143
144 144 def ellipsisrawprocessor(rl, text):
145 145 return False
146 146
147 147
148 148 ellipsisprocessor = (
149 149 ellipsisreadprocessor,
150 150 ellipsiswriteprocessor,
151 151 ellipsisrawprocessor,
152 152 )
153 153
154 154
155 155 def _verify_revision(rl, skipflags, state, node):
156 156 """Verify the integrity of the given revlog ``node`` while providing a hook
157 157 point for extensions to influence the operation."""
158 158 if skipflags:
159 159 state[b'skipread'].add(node)
160 160 else:
161 161 # Side-effect: read content and verify hash.
162 162 rl.revision(node)
163 163
164 164
165 165 # True if a fast implementation for persistent-nodemap is available
166 166 #
167 167 # We also consider we have a "fast" implementation in "pure" python because
168 168 # people using pure don't really have performance consideration (and a
169 169 # wheelbarrow of other slowness source)
170 170 HAS_FAST_PERSISTENT_NODEMAP = rustrevlog is not None or hasattr(
171 171 parsers, 'BaseIndexObject'
172 172 )
173 173
174 174
175 175 @interfaceutil.implementer(repository.irevisiondelta)
176 176 @attr.s(slots=True)
177 177 class revlogrevisiondelta:
178 178 node = attr.ib()
179 179 p1node = attr.ib()
180 180 p2node = attr.ib()
181 181 basenode = attr.ib()
182 182 flags = attr.ib()
183 183 baserevisionsize = attr.ib()
184 184 revision = attr.ib()
185 185 delta = attr.ib()
186 186 sidedata = attr.ib()
187 187 protocol_flags = attr.ib()
188 188 linknode = attr.ib(default=None)
189 189
190 190
191 191 @interfaceutil.implementer(repository.iverifyproblem)
192 192 @attr.s(frozen=True)
193 193 class revlogproblem:
194 194 warning = attr.ib(default=None)
195 195 error = attr.ib(default=None)
196 196 node = attr.ib(default=None)
197 197
198 198
199 199 def parse_index_v1(data, inline):
200 200 # call the C implementation to parse the index data
201 201 index, cache = parsers.parse_index2(data, inline)
202 202 return index, cache
203 203
204 204
205 205 def parse_index_v2(data, inline):
206 206 # call the C implementation to parse the index data
207 207 index, cache = parsers.parse_index2(data, inline, format=REVLOGV2)
208 208 return index, cache
209 209
210 210
211 211 def parse_index_cl_v2(data, inline):
212 212 # call the C implementation to parse the index data
213 213 index, cache = parsers.parse_index2(data, inline, format=CHANGELOGV2)
214 214 return index, cache
215 215
216 216
217 217 if hasattr(parsers, 'parse_index_devel_nodemap'):
218 218
219 219 def parse_index_v1_nodemap(data, inline):
220 220 index, cache = parsers.parse_index_devel_nodemap(data, inline)
221 221 return index, cache
222 222
223 223
224 224 else:
225 225 parse_index_v1_nodemap = None
226 226
227 227
228 228 def parse_index_v1_rust(data, inline, default_header):
229 229 cache = (0, data) if inline else None
230 230 return rustrevlog.Index(data, default_header), cache
231 231
232 232
233 233 # corresponds to uncompressed length of indexformatng (2 gigs, 4-byte
234 234 # signed integer)
235 235 _maxentrysize = 0x7FFFFFFF
236 236
237 237 FILE_TOO_SHORT_MSG = _(
238 238 b'cannot read from revlog %s;'
239 239 b' expected %d bytes from offset %d, data size is %d'
240 240 )
241 241
242 242 hexdigits = b'0123456789abcdefABCDEF'
243 243
244 244
245 245 class _Config:
246 246 def copy(self):
247 247 return self.__class__(**self.__dict__)
248 248
249 249
250 250 @attr.s()
251 251 class FeatureConfig(_Config):
252 252 """Hold configuration values about the available revlog features"""
253 253
254 254 # the default compression engine
255 255 compression_engine = attr.ib(default=b'zlib')
256 256 # compression engines options
257 257 compression_engine_options = attr.ib(default=attr.Factory(dict))
258 258
259 259 # can we use censor on this revlog
260 260 censorable = attr.ib(default=False)
261 261 # does this revlog use the "side data" feature
262 262 has_side_data = attr.ib(default=False)
263 263 # might remove rank configuration once the computation has no impact
264 264 compute_rank = attr.ib(default=False)
265 265 # parent order is supposed to be semantically irrelevant, so we
266 266 # normally resort parents to ensure that the first parent is non-null,
267 267 # if there is a non-null parent at all.
268 268 # filelog abuses the parent order as flag to mark some instances of
269 269 # meta-encoded files, so allow it to disable this behavior.
270 270 canonical_parent_order = attr.ib(default=False)
271 271 # can ellipsis commit be used
272 272 enable_ellipsis = attr.ib(default=False)
273 273
274 274 def copy(self):
275 275 new = super().copy()
276 276 new.compression_engine_options = self.compression_engine_options.copy()
277 277 return new
278 278
279 279
280 280 @attr.s()
281 281 class DataConfig(_Config):
282 282 """Hold configuration value about how the revlog data are read"""
283 283
284 284 # should we try to open the "pending" version of the revlog
285 285 try_pending = attr.ib(default=False)
286 286 # should we try to open the "splitted" version of the revlog
287 287 try_split = attr.ib(default=False)
288 288 # When True, indexfile should be opened with checkambig=True at writing,
289 289 # to avoid file stat ambiguity.
290 290 check_ambig = attr.ib(default=False)
291 291
292 292 # If true, use mmap instead of reading to deal with large index
293 293 mmap_large_index = attr.ib(default=False)
294 294 # how much data is large
295 295 mmap_index_threshold = attr.ib(default=None)
296 296 # How much data to read and cache into the raw revlog data cache.
297 297 chunk_cache_size = attr.ib(default=65536)
298 298
299 299 # The size of the uncompressed cache compared to the largest revision seen.
300 300 uncompressed_cache_factor = attr.ib(default=None)
301 301
302 302 # The number of chunk cached
303 303 uncompressed_cache_count = attr.ib(default=None)
304 304
305 305 # Allow sparse reading of the revlog data
306 306 with_sparse_read = attr.ib(default=False)
307 307 # minimal density of a sparse read chunk
308 308 sr_density_threshold = attr.ib(default=0.50)
309 309 # minimal size of data we skip when performing sparse read
310 310 sr_min_gap_size = attr.ib(default=262144)
311 311
312 312 # are delta encoded against arbitrary bases.
313 313 generaldelta = attr.ib(default=False)
314 314
315 315
316 316 @attr.s()
317 317 class DeltaConfig(_Config):
318 318 """Hold configuration value about how new delta are computed
319 319
320 320 Some attributes are duplicated from DataConfig to help havign each object
321 321 self contained.
322 322 """
323 323
324 324 # can delta be encoded against arbitrary bases.
325 325 general_delta = attr.ib(default=False)
326 326 # Allow sparse writing of the revlog data
327 327 sparse_revlog = attr.ib(default=False)
328 328 # maximum length of a delta chain
329 329 max_chain_len = attr.ib(default=None)
330 330 # Maximum distance between delta chain base start and end
331 331 max_deltachain_span = attr.ib(default=-1)
332 332 # If `upper_bound_comp` is not None, this is the expected maximal gain from
333 333 # compression for the data content.
334 334 upper_bound_comp = attr.ib(default=None)
335 335 # Should we try a delta against both parent
336 336 delta_both_parents = attr.ib(default=True)
337 337 # Test delta base candidate group by chunk of this maximal size.
338 338 candidate_group_chunk_size = attr.ib(default=0)
339 339 # Should we display debug information about delta computation
340 340 debug_delta = attr.ib(default=False)
341 341 # trust incoming delta by default
342 342 lazy_delta = attr.ib(default=True)
343 343 # trust the base of incoming delta by default
344 344 lazy_delta_base = attr.ib(default=False)
345 345
346 346
347 347 class _InnerRevlog:
348 348 """An inner layer of the revlog object
349 349
350 350 That layer exist to be able to delegate some operation to Rust, its
351 351 boundaries are arbitrary and based on what we can delegate to Rust.
352 352 """
353 353
354 354 def __init__(
355 355 self,
356 356 opener,
357 357 index,
358 358 index_file,
359 359 data_file,
360 360 sidedata_file,
361 361 inline,
362 362 data_config,
363 363 delta_config,
364 364 feature_config,
365 365 chunk_cache,
366 366 default_compression_header,
367 367 ):
368 368 self.opener = opener
369 369 self.index = index
370 370
371 371 self.index_file = index_file
372 372 self.data_file = data_file
373 373 self.sidedata_file = sidedata_file
374 374 self.inline = inline
375 375 self.data_config = data_config
376 376 self.delta_config = delta_config
377 377 self.feature_config = feature_config
378 378
379 379 # used during diverted write.
380 380 self._orig_index_file = None
381 381
382 382 self._default_compression_header = default_compression_header
383 383
384 384 # index
385 385
386 386 # 3-tuple of file handles being used for active writing.
387 387 self._writinghandles = None
388 388
389 389 self._segmentfile = randomaccessfile.randomaccessfile(
390 390 self.opener,
391 391 (self.index_file if self.inline else self.data_file),
392 392 self.data_config.chunk_cache_size,
393 393 chunk_cache,
394 394 )
395 395 self._segmentfile_sidedata = randomaccessfile.randomaccessfile(
396 396 self.opener,
397 397 self.sidedata_file,
398 398 self.data_config.chunk_cache_size,
399 399 )
400 400
401 401 # revlog header -> revlog compressor
402 402 self._decompressors = {}
403 403 # 3-tuple of (node, rev, text) for a raw revision.
404 404 self._revisioncache = None
405 405
406 406 # cache some uncompressed chunks
407 407 # rev β†’ uncompressed_chunk
408 408 #
409 409 # the max cost is dynamically updated to be proportionnal to the
410 410 # size of revision we actually encounter.
411 411 self._uncompressed_chunk_cache = None
412 412 if self.data_config.uncompressed_cache_factor is not None:
413 413 self._uncompressed_chunk_cache = util.lrucachedict(
414 414 self.data_config.uncompressed_cache_count,
415 415 maxcost=65536, # some arbitrary initial value
416 416 )
417 417
418 418 self._delay_buffer = None
419 419
420 420 def __len__(self):
421 421 return len(self.index)
422 422
423 423 def clear_cache(self):
424 424 assert not self.is_delaying
425 425 self._revisioncache = None
426 426 if self._uncompressed_chunk_cache is not None:
427 427 self._uncompressed_chunk_cache.clear()
428 428 self._segmentfile.clear_cache()
429 429 self._segmentfile_sidedata.clear_cache()
430 430
431 431 @property
432 432 def canonical_index_file(self):
433 433 if self._orig_index_file is not None:
434 434 return self._orig_index_file
435 435 return self.index_file
436 436
437 437 @property
438 438 def is_delaying(self):
439 439 """is the revlog is currently delaying the visibility of written data?
440 440
441 441 The delaying mechanism can be either in-memory or written on disk in a
442 442 side-file."""
443 443 return (self._delay_buffer is not None) or (
444 444 self._orig_index_file is not None
445 445 )
446 446
447 447 # Derived from index values.
448 448
449 449 def start(self, rev):
450 450 """the offset of the data chunk for this revision"""
451 451 return int(self.index[rev][0] >> 16)
452 452
453 453 def length(self, rev):
454 454 """the length of the data chunk for this revision"""
455 455 return self.index[rev][1]
456 456
457 457 def end(self, rev):
458 458 """the end of the data chunk for this revision"""
459 459 return self.start(rev) + self.length(rev)
460 460
461 461 def deltaparent(self, rev):
462 462 """return deltaparent of the given revision"""
463 463 base = self.index[rev][3]
464 464 if base == rev:
465 465 return nullrev
466 466 elif self.delta_config.general_delta:
467 467 return base
468 468 else:
469 469 return rev - 1
470 470
471 471 def issnapshot(self, rev):
472 472 """tells whether rev is a snapshot"""
473 473 if not self.delta_config.sparse_revlog:
474 474 return self.deltaparent(rev) == nullrev
475 475 elif hasattr(self.index, 'issnapshot'):
476 476 # directly assign the method to cache the testing and access
477 477 self.issnapshot = self.index.issnapshot
478 478 return self.issnapshot(rev)
479 479 if rev == nullrev:
480 480 return True
481 481 entry = self.index[rev]
482 482 base = entry[3]
483 483 if base == rev:
484 484 return True
485 485 if base == nullrev:
486 486 return True
487 487 p1 = entry[5]
488 488 while self.length(p1) == 0:
489 489 b = self.deltaparent(p1)
490 490 if b == p1:
491 491 break
492 492 p1 = b
493 493 p2 = entry[6]
494 494 while self.length(p2) == 0:
495 495 b = self.deltaparent(p2)
496 496 if b == p2:
497 497 break
498 498 p2 = b
499 499 if base == p1 or base == p2:
500 500 return False
501 501 return self.issnapshot(base)
502 502
503 503 def _deltachain(self, rev, stoprev=None):
504 504 """Obtain the delta chain for a revision.
505 505
506 506 ``stoprev`` specifies a revision to stop at. If not specified, we
507 507 stop at the base of the chain.
508 508
509 509 Returns a 2-tuple of (chain, stopped) where ``chain`` is a list of
510 510 revs in ascending order and ``stopped`` is a bool indicating whether
511 511 ``stoprev`` was hit.
512 512 """
513 513 generaldelta = self.delta_config.general_delta
514 514 # Try C implementation.
515 515 try:
516 516 return self.index.deltachain(rev, stoprev, generaldelta)
517 517 except AttributeError:
518 518 pass
519 519
520 520 chain = []
521 521
522 522 # Alias to prevent attribute lookup in tight loop.
523 523 index = self.index
524 524
525 525 iterrev = rev
526 526 e = index[iterrev]
527 527 while iterrev != e[3] and iterrev != stoprev:
528 528 chain.append(iterrev)
529 529 if generaldelta:
530 530 iterrev = e[3]
531 531 else:
532 532 iterrev -= 1
533 533 e = index[iterrev]
534 534
535 535 if iterrev == stoprev:
536 536 stopped = True
537 537 else:
538 538 chain.append(iterrev)
539 539 stopped = False
540 540
541 541 chain.reverse()
542 542 return chain, stopped
543 543
544 544 @util.propertycache
545 545 def _compressor(self):
546 546 engine = util.compengines[self.feature_config.compression_engine]
547 547 return engine.revlogcompressor(
548 548 self.feature_config.compression_engine_options
549 549 )
550 550
551 551 @util.propertycache
552 552 def _decompressor(self):
553 553 """the default decompressor"""
554 554 if self._default_compression_header is None:
555 555 return None
556 556 t = self._default_compression_header
557 557 c = self._get_decompressor(t)
558 558 return c.decompress
559 559
560 560 def _get_decompressor(self, t):
561 561 try:
562 562 compressor = self._decompressors[t]
563 563 except KeyError:
564 564 try:
565 565 engine = util.compengines.forrevlogheader(t)
566 566 compressor = engine.revlogcompressor(
567 567 self.feature_config.compression_engine_options
568 568 )
569 569 self._decompressors[t] = compressor
570 570 except KeyError:
571 571 raise error.RevlogError(
572 572 _(b'unknown compression type %s') % binascii.hexlify(t)
573 573 )
574 574 return compressor
575 575
576 576 def compress(self, data):
577 577 """Generate a possibly-compressed representation of data."""
578 578 if not data:
579 579 return b'', data
580 580
581 581 compressed = self._compressor.compress(data)
582 582
583 583 if compressed:
584 584 # The revlog compressor added the header in the returned data.
585 585 return b'', compressed
586 586
587 587 if data[0:1] == b'\0':
588 588 return b'', data
589 589 return b'u', data
590 590
591 591 def decompress(self, data):
592 592 """Decompress a revlog chunk.
593 593
594 594 The chunk is expected to begin with a header identifying the
595 595 format type so it can be routed to an appropriate decompressor.
596 596 """
597 597 if not data:
598 598 return data
599 599
600 600 # Revlogs are read much more frequently than they are written and many
601 601 # chunks only take microseconds to decompress, so performance is
602 602 # important here.
603 603 #
604 604 # We can make a few assumptions about revlogs:
605 605 #
606 606 # 1) the majority of chunks will be compressed (as opposed to inline
607 607 # raw data).
608 608 # 2) decompressing *any* data will likely by at least 10x slower than
609 609 # returning raw inline data.
610 610 # 3) we want to prioritize common and officially supported compression
611 611 # engines
612 612 #
613 613 # It follows that we want to optimize for "decompress compressed data
614 614 # when encoded with common and officially supported compression engines"
615 615 # case over "raw data" and "data encoded by less common or non-official
616 616 # compression engines." That is why we have the inline lookup first
617 617 # followed by the compengines lookup.
618 618 #
619 619 # According to `hg perfrevlogchunks`, this is ~0.5% faster for zlib
620 620 # compressed chunks. And this matters for changelog and manifest reads.
621 621 t = data[0:1]
622 622
623 623 if t == b'x':
624 624 try:
625 625 return _zlibdecompress(data)
626 626 except zlib.error as e:
627 627 raise error.RevlogError(
628 628 _(b'revlog decompress error: %s')
629 629 % stringutil.forcebytestr(e)
630 630 )
631 631 # '\0' is more common than 'u' so it goes first.
632 632 elif t == b'\0':
633 633 return data
634 634 elif t == b'u':
635 635 return util.buffer(data, 1)
636 636
637 637 compressor = self._get_decompressor(t)
638 638
639 639 return compressor.decompress(data)
640 640
641 641 @contextlib.contextmanager
642 642 def reading(self):
643 643 """Context manager that keeps data and sidedata files open for reading"""
644 644 if len(self.index) == 0:
645 645 yield # nothing to be read
646 646 elif self._delay_buffer is not None and self.inline:
647 647 msg = "revlog with delayed write should not be inline"
648 648 raise error.ProgrammingError(msg)
649 649 else:
650 650 with self._segmentfile.reading():
651 651 with self._segmentfile_sidedata.reading():
652 652 yield
653 653
654 654 @property
655 655 def is_writing(self):
656 656 """True is a writing context is open"""
657 657 return self._writinghandles is not None
658 658
659 659 @property
660 660 def is_open(self):
661 661 """True if any file handle is being held
662 662
663 663 Used for assert and debug in the python code"""
664 664 return self._segmentfile.is_open or self._segmentfile_sidedata.is_open
665 665
666 666 @contextlib.contextmanager
667 667 def writing(self, transaction, data_end=None, sidedata_end=None):
668 668 """Open the revlog files for writing
669 669
670 670 Add content to a revlog should be done within such context.
671 671 """
672 672 if self.is_writing:
673 673 yield
674 674 else:
675 675 ifh = dfh = sdfh = None
676 676 try:
677 677 r = len(self.index)
678 678 # opening the data file.
679 679 dsize = 0
680 680 if r:
681 681 dsize = self.end(r - 1)
682 682 dfh = None
683 683 if not self.inline:
684 684 try:
685 685 dfh = self.opener(self.data_file, mode=b"r+")
686 686 if data_end is None:
687 687 dfh.seek(0, os.SEEK_END)
688 688 else:
689 689 dfh.seek(data_end, os.SEEK_SET)
690 690 except FileNotFoundError:
691 691 dfh = self.opener(self.data_file, mode=b"w+")
692 692 transaction.add(self.data_file, dsize)
693 693 if self.sidedata_file is not None:
694 694 assert sidedata_end is not None
695 695 # revlog-v2 does not inline, help Pytype
696 696 assert dfh is not None
697 697 try:
698 698 sdfh = self.opener(self.sidedata_file, mode=b"r+")
699 699 dfh.seek(sidedata_end, os.SEEK_SET)
700 700 except FileNotFoundError:
701 701 sdfh = self.opener(self.sidedata_file, mode=b"w+")
702 702 transaction.add(self.sidedata_file, sidedata_end)
703 703
704 704 # opening the index file.
705 705 isize = r * self.index.entry_size
706 706 ifh = self.__index_write_fp()
707 707 if self.inline:
708 708 transaction.add(self.index_file, dsize + isize)
709 709 else:
710 710 transaction.add(self.index_file, isize)
711 711 # exposing all file handle for writing.
712 712 self._writinghandles = (ifh, dfh, sdfh)
713 713 self._segmentfile.writing_handle = ifh if self.inline else dfh
714 714 self._segmentfile_sidedata.writing_handle = sdfh
715 715 yield
716 716 finally:
717 717 self._writinghandles = None
718 718 self._segmentfile.writing_handle = None
719 719 self._segmentfile_sidedata.writing_handle = None
720 720 if dfh is not None:
721 721 dfh.close()
722 722 if sdfh is not None:
723 723 sdfh.close()
724 724 # closing the index file last to avoid exposing referent to
725 725 # potential unflushed data content.
726 726 if ifh is not None:
727 727 ifh.close()
728 728
729 729 def __index_write_fp(self, index_end=None):
730 730 """internal method to open the index file for writing
731 731
732 732 You should not use this directly and use `_writing` instead
733 733 """
734 734 try:
735 735 if self._delay_buffer is None:
736 736 f = self.opener(
737 737 self.index_file,
738 738 mode=b"r+",
739 739 checkambig=self.data_config.check_ambig,
740 740 )
741 741 else:
742 742 # check_ambig affect we way we open file for writing, however
743 743 # here, we do not actually open a file for writting as write
744 744 # will appened to a delay_buffer. So check_ambig is not
745 745 # meaningful and unneeded here.
746 746 f = randomaccessfile.appender(
747 747 self.opener, self.index_file, b"r+", self._delay_buffer
748 748 )
749 749 if index_end is None:
750 750 f.seek(0, os.SEEK_END)
751 751 else:
752 752 f.seek(index_end, os.SEEK_SET)
753 753 return f
754 754 except FileNotFoundError:
755 755 if self._delay_buffer is None:
756 756 return self.opener(
757 757 self.index_file,
758 758 mode=b"w+",
759 759 checkambig=self.data_config.check_ambig,
760 760 )
761 761 else:
762 762 return randomaccessfile.appender(
763 763 self.opener, self.index_file, b"w+", self._delay_buffer
764 764 )
765 765
766 766 def __index_new_fp(self):
767 767 """internal method to create a new index file for writing
768 768
769 769 You should not use this unless you are upgrading from inline revlog
770 770 """
771 771 return self.opener(
772 772 self.index_file,
773 773 mode=b"w",
774 774 checkambig=self.data_config.check_ambig,
775 775 atomictemp=True,
776 776 )
777 777
778 778 def split_inline(self, tr, header, new_index_file_path=None):
779 779 """split the data of an inline revlog into an index and a data file"""
780 780 assert self._delay_buffer is None
781 781 existing_handles = False
782 782 if self._writinghandles is not None:
783 783 existing_handles = True
784 784 fp = self._writinghandles[0]
785 785 fp.flush()
786 786 fp.close()
787 787 # We can't use the cached file handle after close(). So prevent
788 788 # its usage.
789 789 self._writinghandles = None
790 790 self._segmentfile.writing_handle = None
791 791 # No need to deal with sidedata writing handle as it is only
792 792 # relevant with revlog-v2 which is never inline, not reaching
793 793 # this code
794 794
795 795 new_dfh = self.opener(self.data_file, mode=b"w+")
796 796 new_dfh.truncate(0) # drop any potentially existing data
797 797 try:
798 798 with self.reading():
799 799 for r in range(len(self.index)):
800 800 new_dfh.write(self.get_segment_for_revs(r, r)[1])
801 801 new_dfh.flush()
802 802
803 803 if new_index_file_path is not None:
804 804 self.index_file = new_index_file_path
805 805 with self.__index_new_fp() as fp:
806 806 self.inline = False
807 807 for i in range(len(self.index)):
808 808 e = self.index.entry_binary(i)
809 809 if i == 0:
810 810 packed_header = self.index.pack_header(header)
811 811 e = packed_header + e
812 812 fp.write(e)
813 813
814 814 # If we don't use side-write, the temp file replace the real
815 815 # index when we exit the context manager
816 816
817 817 self._segmentfile = randomaccessfile.randomaccessfile(
818 818 self.opener,
819 819 self.data_file,
820 820 self.data_config.chunk_cache_size,
821 821 )
822 822
823 823 if existing_handles:
824 824 # switched from inline to conventional reopen the index
825 825 ifh = self.__index_write_fp()
826 826 self._writinghandles = (ifh, new_dfh, None)
827 827 self._segmentfile.writing_handle = new_dfh
828 828 new_dfh = None
829 829 # No need to deal with sidedata writing handle as it is only
830 830 # relevant with revlog-v2 which is never inline, not reaching
831 831 # this code
832 832 finally:
833 833 if new_dfh is not None:
834 834 new_dfh.close()
835 835 return self.index_file
836 836
837 837 def get_segment_for_revs(self, startrev, endrev):
838 838 """Obtain a segment of raw data corresponding to a range of revisions.
839 839
840 840 Accepts the start and end revisions and an optional already-open
841 841 file handle to be used for reading. If the file handle is read, its
842 842 seek position will not be preserved.
843 843
844 844 Requests for data may be satisfied by a cache.
845 845
846 846 Returns a 2-tuple of (offset, data) for the requested range of
847 847 revisions. Offset is the integer offset from the beginning of the
848 848 revlog and data is a str or buffer of the raw byte data.
849 849
850 850 Callers will need to call ``self.start(rev)`` and ``self.length(rev)``
851 851 to determine where each revision's data begins and ends.
852 852
853 853 API: we should consider making this a private part of the InnerRevlog
854 854 at some point.
855 855 """
856 856 # Inlined self.start(startrev) & self.end(endrev) for perf reasons
857 857 # (functions are expensive).
858 858 index = self.index
859 859 istart = index[startrev]
860 860 start = int(istart[0] >> 16)
861 861 if startrev == endrev:
862 862 end = start + istart[1]
863 863 else:
864 864 iend = index[endrev]
865 865 end = int(iend[0] >> 16) + iend[1]
866 866
867 867 if self.inline:
868 868 start += (startrev + 1) * self.index.entry_size
869 869 end += (endrev + 1) * self.index.entry_size
870 870 length = end - start
871 871
872 872 return start, self._segmentfile.read_chunk(start, length)
873 873
874 874 def _chunk(self, rev):
875 875 """Obtain a single decompressed chunk for a revision.
876 876
877 877 Accepts an integer revision and an optional already-open file handle
878 878 to be used for reading. If used, the seek position of the file will not
879 879 be preserved.
880 880
881 881 Returns a str holding uncompressed data for the requested revision.
882 882 """
883 883 if self._uncompressed_chunk_cache is not None:
884 884 uncomp = self._uncompressed_chunk_cache.get(rev)
885 885 if uncomp is not None:
886 886 return uncomp
887 887
888 888 compression_mode = self.index[rev][10]
889 889 data = self.get_segment_for_revs(rev, rev)[1]
890 890 if compression_mode == COMP_MODE_PLAIN:
891 891 uncomp = data
892 892 elif compression_mode == COMP_MODE_DEFAULT:
893 893 uncomp = self._decompressor(data)
894 894 elif compression_mode == COMP_MODE_INLINE:
895 895 uncomp = self.decompress(data)
896 896 else:
897 897 msg = b'unknown compression mode %d'
898 898 msg %= compression_mode
899 899 raise error.RevlogError(msg)
900 900 if self._uncompressed_chunk_cache is not None:
901 901 self._uncompressed_chunk_cache.insert(rev, uncomp, cost=len(uncomp))
902 902 return uncomp
903 903
904 904 def _chunks(self, revs, targetsize=None):
905 905 """Obtain decompressed chunks for the specified revisions.
906 906
907 907 Accepts an iterable of numeric revisions that are assumed to be in
908 908 ascending order. Also accepts an optional already-open file handle
909 909 to be used for reading. If used, the seek position of the file will
910 910 not be preserved.
911 911
912 912 This function is similar to calling ``self._chunk()`` multiple times,
913 913 but is faster.
914 914
915 915 Returns a list with decompressed data for each requested revision.
916 916 """
917 917 if not revs:
918 918 return []
919 919 start = self.start
920 920 length = self.length
921 921 inline = self.inline
922 922 iosize = self.index.entry_size
923 923 buffer = util.buffer
924 924
925 925 fetched_revs = []
926 926 fadd = fetched_revs.append
927 927
928 928 chunks = []
929 929 ladd = chunks.append
930 930
931 931 if self._uncompressed_chunk_cache is None:
932 932 fetched_revs = revs
933 933 else:
934 934 for rev in revs:
935 935 cached_value = self._uncompressed_chunk_cache.get(rev)
936 936 if cached_value is None:
937 937 fadd(rev)
938 938 else:
939 939 ladd((rev, cached_value))
940 940
941 941 if not fetched_revs:
942 942 slicedchunks = ()
943 943 elif not self.data_config.with_sparse_read:
944 944 slicedchunks = (fetched_revs,)
945 945 else:
946 946 slicedchunks = deltautil.slicechunk(
947 947 self,
948 948 fetched_revs,
949 949 targetsize=targetsize,
950 950 )
951 951
952 952 for revschunk in slicedchunks:
953 953 firstrev = revschunk[0]
954 954 # Skip trailing revisions with empty diff
955 955 for lastrev in revschunk[::-1]:
956 956 if length(lastrev) != 0:
957 957 break
958 958
959 959 try:
960 960 offset, data = self.get_segment_for_revs(firstrev, lastrev)
961 961 except OverflowError:
962 962 # issue4215 - we can't cache a run of chunks greater than
963 963 # 2G on Windows
964 964 for rev in revschunk:
965 965 ladd((rev, self._chunk(rev)))
966 966
967 967 decomp = self.decompress
968 968 # self._decompressor might be None, but will not be used in that case
969 969 def_decomp = self._decompressor
970 970 for rev in revschunk:
971 971 chunkstart = start(rev)
972 972 if inline:
973 973 chunkstart += (rev + 1) * iosize
974 974 chunklength = length(rev)
975 975 comp_mode = self.index[rev][10]
976 976 c = buffer(data, chunkstart - offset, chunklength)
977 977 if comp_mode == COMP_MODE_PLAIN:
978 978 c = c
979 979 elif comp_mode == COMP_MODE_INLINE:
980 980 c = decomp(c)
981 981 elif comp_mode == COMP_MODE_DEFAULT:
982 982 c = def_decomp(c)
983 983 else:
984 984 msg = b'unknown compression mode %d'
985 985 msg %= comp_mode
986 986 raise error.RevlogError(msg)
987 987 ladd((rev, c))
988 988 if self._uncompressed_chunk_cache is not None:
989 989 self._uncompressed_chunk_cache.insert(rev, c, len(c))
990 990
991 991 chunks.sort()
992 992 return [x[1] for x in chunks]
993 993
994 994 def raw_text(self, node, rev):
995 995 """return the possibly unvalidated rawtext for a revision
996 996
997 997 returns (rev, rawtext, validated)
998 998 """
999 999
1000 1000 # revision in the cache (could be useful to apply delta)
1001 1001 cachedrev = None
1002 1002 # An intermediate text to apply deltas to
1003 1003 basetext = None
1004 1004
1005 1005 # Check if we have the entry in cache
1006 1006 # The cache entry looks like (node, rev, rawtext)
1007 1007 if self._revisioncache:
1008 1008 cachedrev = self._revisioncache[1]
1009 1009
1010 1010 chain, stopped = self._deltachain(rev, stoprev=cachedrev)
1011 1011 if stopped:
1012 1012 basetext = self._revisioncache[2]
1013 1013
1014 1014 # drop cache to save memory, the caller is expected to
1015 1015 # update self._inner._revisioncache after validating the text
1016 1016 self._revisioncache = None
1017 1017
1018 1018 targetsize = None
1019 1019 rawsize = self.index[rev][2]
1020 1020 if 0 <= rawsize:
1021 1021 targetsize = 4 * rawsize
1022 1022
1023 1023 if self._uncompressed_chunk_cache is not None:
1024 1024 # dynamically update the uncompressed_chunk_cache size to the
1025 1025 # largest revision we saw in this revlog.
1026 1026 factor = self.data_config.uncompressed_cache_factor
1027 1027 candidate_size = rawsize * factor
1028 1028 if candidate_size > self._uncompressed_chunk_cache.maxcost:
1029 1029 self._uncompressed_chunk_cache.maxcost = candidate_size
1030 1030
1031 1031 bins = self._chunks(chain, targetsize=targetsize)
1032 1032 if basetext is None:
1033 1033 basetext = bytes(bins[0])
1034 1034 bins = bins[1:]
1035 1035
1036 1036 rawtext = mdiff.patches(basetext, bins)
1037 1037 del basetext # let us have a chance to free memory early
1038 1038 return (rev, rawtext, False)
1039 1039
1040 1040 def sidedata(self, rev, sidedata_end):
1041 1041 """Return the sidedata for a given revision number."""
1042 1042 index_entry = self.index[rev]
1043 1043 sidedata_offset = index_entry[8]
1044 1044 sidedata_size = index_entry[9]
1045 1045
1046 1046 if self.inline:
1047 1047 sidedata_offset += self.index.entry_size * (1 + rev)
1048 1048 if sidedata_size == 0:
1049 1049 return {}
1050 1050
1051 1051 if sidedata_end < sidedata_offset + sidedata_size:
1052 1052 filename = self.sidedata_file
1053 1053 end = sidedata_end
1054 1054 offset = sidedata_offset
1055 1055 length = sidedata_size
1056 1056 m = FILE_TOO_SHORT_MSG % (filename, length, offset, end)
1057 1057 raise error.RevlogError(m)
1058 1058
1059 1059 comp_segment = self._segmentfile_sidedata.read_chunk(
1060 1060 sidedata_offset, sidedata_size
1061 1061 )
1062 1062
1063 1063 comp = self.index[rev][11]
1064 1064 if comp == COMP_MODE_PLAIN:
1065 1065 segment = comp_segment
1066 1066 elif comp == COMP_MODE_DEFAULT:
1067 1067 segment = self._decompressor(comp_segment)
1068 1068 elif comp == COMP_MODE_INLINE:
1069 1069 segment = self.decompress(comp_segment)
1070 1070 else:
1071 1071 msg = b'unknown compression mode %d'
1072 1072 msg %= comp
1073 1073 raise error.RevlogError(msg)
1074 1074
1075 1075 sidedata = sidedatautil.deserialize_sidedata(segment)
1076 1076 return sidedata
1077 1077
1078 1078 def write_entry(
1079 1079 self,
1080 1080 transaction,
1081 1081 entry,
1082 1082 data,
1083 1083 link,
1084 1084 offset,
1085 1085 sidedata,
1086 1086 sidedata_offset,
1087 1087 index_end,
1088 1088 data_end,
1089 1089 sidedata_end,
1090 1090 ):
1091 1091 # Files opened in a+ mode have inconsistent behavior on various
1092 1092 # platforms. Windows requires that a file positioning call be made
1093 1093 # when the file handle transitions between reads and writes. See
1094 1094 # 3686fa2b8eee and the mixedfilemodewrapper in windows.py. On other
1095 1095 # platforms, Python or the platform itself can be buggy. Some versions
1096 1096 # of Solaris have been observed to not append at the end of the file
1097 1097 # if the file was seeked to before the end. See issue4943 for more.
1098 1098 #
1099 1099 # We work around this issue by inserting a seek() before writing.
1100 1100 # Note: This is likely not necessary on Python 3. However, because
1101 1101 # the file handle is reused for reads and may be seeked there, we need
1102 1102 # to be careful before changing this.
1103 1103 if self._writinghandles is None:
1104 1104 msg = b'adding revision outside `revlog._writing` context'
1105 1105 raise error.ProgrammingError(msg)
1106 1106 ifh, dfh, sdfh = self._writinghandles
1107 1107 if index_end is None:
1108 1108 ifh.seek(0, os.SEEK_END)
1109 1109 else:
1110 1110 ifh.seek(index_end, os.SEEK_SET)
1111 1111 if dfh:
1112 1112 if data_end is None:
1113 1113 dfh.seek(0, os.SEEK_END)
1114 1114 else:
1115 1115 dfh.seek(data_end, os.SEEK_SET)
1116 1116 if sdfh:
1117 1117 sdfh.seek(sidedata_end, os.SEEK_SET)
1118 1118
1119 1119 curr = len(self.index) - 1
1120 1120 if not self.inline:
1121 1121 transaction.add(self.data_file, offset)
1122 1122 if self.sidedata_file:
1123 1123 transaction.add(self.sidedata_file, sidedata_offset)
1124 1124 transaction.add(self.canonical_index_file, curr * len(entry))
1125 1125 if data[0]:
1126 1126 dfh.write(data[0])
1127 1127 dfh.write(data[1])
1128 1128 if sidedata:
1129 1129 sdfh.write(sidedata)
1130 1130 if self._delay_buffer is None:
1131 1131 ifh.write(entry)
1132 1132 else:
1133 1133 self._delay_buffer.append(entry)
1134 1134 elif self._delay_buffer is not None:
1135 1135 msg = b'invalid delayed write on inline revlog'
1136 1136 raise error.ProgrammingError(msg)
1137 1137 else:
1138 1138 offset += curr * self.index.entry_size
1139 1139 transaction.add(self.canonical_index_file, offset)
1140 1140 assert not sidedata
1141 1141 ifh.write(entry)
1142 1142 ifh.write(data[0])
1143 1143 ifh.write(data[1])
1144 1144 return (
1145 1145 ifh.tell(),
1146 1146 dfh.tell() if dfh else None,
1147 1147 sdfh.tell() if sdfh else None,
1148 1148 )
1149 1149
1150 1150 def _divert_index(self):
1151 1151 return self.index_file + b'.a'
1152 1152
1153 1153 def delay(self):
1154 1154 assert not self.is_open
1155 1155 if self.inline:
1156 1156 msg = "revlog with delayed write should not be inline"
1157 1157 raise error.ProgrammingError(msg)
1158 1158 if self._delay_buffer is not None or self._orig_index_file is not None:
1159 1159 # delay or divert already in place
1160 1160 return None
1161 1161 elif len(self.index) == 0:
1162 1162 self._orig_index_file = self.index_file
1163 1163 self.index_file = self._divert_index()
1164 1164 assert self._orig_index_file is not None
1165 1165 assert self.index_file is not None
1166 1166 if self.opener.exists(self.index_file):
1167 1167 self.opener.unlink(self.index_file)
1168 1168 return self.index_file
1169 1169 else:
1170 1170 self._delay_buffer = []
1171 1171 return None
1172 1172
1173 1173 def write_pending(self):
1174 1174 assert not self.is_open
1175 1175 if self.inline:
1176 1176 msg = "revlog with delayed write should not be inline"
1177 1177 raise error.ProgrammingError(msg)
1178 1178 if self._orig_index_file is not None:
1179 1179 return None, True
1180 1180 any_pending = False
1181 1181 pending_index_file = self._divert_index()
1182 1182 if self.opener.exists(pending_index_file):
1183 1183 self.opener.unlink(pending_index_file)
1184 1184 util.copyfile(
1185 1185 self.opener.join(self.index_file),
1186 1186 self.opener.join(pending_index_file),
1187 1187 )
1188 1188 if self._delay_buffer:
1189 1189 with self.opener(pending_index_file, b'r+') as ifh:
1190 1190 ifh.seek(0, os.SEEK_END)
1191 1191 ifh.write(b"".join(self._delay_buffer))
1192 1192 any_pending = True
1193 1193 self._delay_buffer = None
1194 1194 self._orig_index_file = self.index_file
1195 1195 self.index_file = pending_index_file
1196 1196 return self.index_file, any_pending
1197 1197
1198 1198 def finalize_pending(self):
1199 1199 assert not self.is_open
1200 1200 if self.inline:
1201 1201 msg = "revlog with delayed write should not be inline"
1202 1202 raise error.ProgrammingError(msg)
1203 1203
1204 1204 delay = self._delay_buffer is not None
1205 1205 divert = self._orig_index_file is not None
1206 1206
1207 1207 if delay and divert:
1208 1208 assert False, "unreachable"
1209 1209 elif delay:
1210 1210 if self._delay_buffer:
1211 1211 with self.opener(self.index_file, b'r+') as ifh:
1212 1212 ifh.seek(0, os.SEEK_END)
1213 1213 ifh.write(b"".join(self._delay_buffer))
1214 1214 self._delay_buffer = None
1215 1215 elif divert:
1216 1216 if self.opener.exists(self.index_file):
1217 1217 self.opener.rename(
1218 1218 self.index_file,
1219 1219 self._orig_index_file,
1220 1220 checkambig=True,
1221 1221 )
1222 1222 self.index_file = self._orig_index_file
1223 1223 self._orig_index_file = None
1224 1224 else:
1225 1225 msg = b"not delay or divert found on this revlog"
1226 1226 raise error.ProgrammingError(msg)
1227 1227 return self.canonical_index_file
1228 1228
1229 1229
1230 1230 class revlog:
1231 1231 """
1232 1232 the underlying revision storage object
1233 1233
1234 1234 A revlog consists of two parts, an index and the revision data.
1235 1235
1236 1236 The index is a file with a fixed record size containing
1237 1237 information on each revision, including its nodeid (hash), the
1238 1238 nodeids of its parents, the position and offset of its data within
1239 1239 the data file, and the revision it's based on. Finally, each entry
1240 1240 contains a linkrev entry that can serve as a pointer to external
1241 1241 data.
1242 1242
1243 1243 The revision data itself is a linear collection of data chunks.
1244 1244 Each chunk represents a revision and is usually represented as a
1245 1245 delta against the previous chunk. To bound lookup time, runs of
1246 1246 deltas are limited to about 2 times the length of the original
1247 1247 version data. This makes retrieval of a version proportional to
1248 1248 its size, or O(1) relative to the number of revisions.
1249 1249
1250 1250 Both pieces of the revlog are written to in an append-only
1251 1251 fashion, which means we never need to rewrite a file to insert or
1252 1252 remove data, and can use some simple techniques to avoid the need
1253 1253 for locking while reading.
1254 1254
1255 1255 If checkambig, indexfile is opened with checkambig=True at
1256 1256 writing, to avoid file stat ambiguity.
1257 1257
1258 1258 If mmaplargeindex is True, and an mmapindexthreshold is set, the
1259 1259 index will be mmapped rather than read if it is larger than the
1260 1260 configured threshold.
1261 1261
1262 1262 If censorable is True, the revlog can have censored revisions.
1263 1263
1264 1264 If `upperboundcomp` is not None, this is the expected maximal gain from
1265 1265 compression for the data content.
1266 1266
1267 1267 `concurrencychecker` is an optional function that receives 3 arguments: a
1268 1268 file handle, a filename, and an expected position. It should check whether
1269 1269 the current position in the file handle is valid, and log/warn/fail (by
1270 1270 raising).
1271 1271
1272 1272 See mercurial/revlogutils/contants.py for details about the content of an
1273 1273 index entry.
1274 1274 """
1275 1275
1276 1276 _flagserrorclass = error.RevlogError
1277 1277
1278 1278 @staticmethod
1279 1279 def is_inline_index(header_bytes):
1280 1280 """Determine if a revlog is inline from the initial bytes of the index"""
1281 1281 if len(header_bytes) == 0:
1282 1282 return True
1283 1283
1284 1284 header = INDEX_HEADER.unpack(header_bytes)[0]
1285 1285
1286 1286 _format_flags = header & ~0xFFFF
1287 1287 _format_version = header & 0xFFFF
1288 1288
1289 1289 features = FEATURES_BY_VERSION[_format_version]
1290 1290 return features[b'inline'](_format_flags)
1291 1291
1292 1292 def __init__(
1293 1293 self,
1294 1294 opener,
1295 1295 target,
1296 1296 radix,
1297 1297 postfix=None, # only exist for `tmpcensored` now
1298 1298 checkambig=False,
1299 1299 mmaplargeindex=False,
1300 1300 censorable=False,
1301 1301 upperboundcomp=None,
1302 1302 persistentnodemap=False,
1303 1303 concurrencychecker=None,
1304 1304 trypending=False,
1305 1305 try_split=False,
1306 1306 canonical_parent_order=True,
1307 1307 data_config=None,
1308 1308 delta_config=None,
1309 1309 feature_config=None,
1310 1310 may_inline=True, # may inline new revlog
1311 1311 ):
1312 1312 """
1313 1313 create a revlog object
1314 1314
1315 1315 opener is a function that abstracts the file opening operation
1316 1316 and can be used to implement COW semantics or the like.
1317 1317
1318 1318 `target`: a (KIND, ID) tuple that identify the content stored in
1319 1319 this revlog. It help the rest of the code to understand what the revlog
1320 1320 is about without having to resort to heuristic and index filename
1321 1321 analysis. Note: that this must be reliably be set by normal code, but
1322 1322 that test, debug, or performance measurement code might not set this to
1323 1323 accurate value.
1324 1324 """
1325 1325
1326 1326 self.radix = radix
1327 1327
1328 1328 self._docket_file = None
1329 1329 self._indexfile = None
1330 1330 self._datafile = None
1331 1331 self._sidedatafile = None
1332 1332 self._nodemap_file = None
1333 1333 self.postfix = postfix
1334 1334 self._trypending = trypending
1335 1335 self._try_split = try_split
1336 1336 self._may_inline = may_inline
1337 1337 self.opener = opener
1338 1338 if persistentnodemap:
1339 1339 self._nodemap_file = nodemaputil.get_nodemap_file(self)
1340 1340
1341 1341 assert target[0] in ALL_KINDS
1342 1342 assert len(target) == 2
1343 1343 self.target = target
1344 1344 if feature_config is not None:
1345 1345 self.feature_config = feature_config.copy()
1346 1346 elif b'feature-config' in self.opener.options:
1347 1347 self.feature_config = self.opener.options[b'feature-config'].copy()
1348 1348 else:
1349 1349 self.feature_config = FeatureConfig()
1350 1350 self.feature_config.censorable = censorable
1351 1351 self.feature_config.canonical_parent_order = canonical_parent_order
1352 1352 if data_config is not None:
1353 1353 self.data_config = data_config.copy()
1354 1354 elif b'data-config' in self.opener.options:
1355 1355 self.data_config = self.opener.options[b'data-config'].copy()
1356 1356 else:
1357 1357 self.data_config = DataConfig()
1358 1358 self.data_config.check_ambig = checkambig
1359 1359 self.data_config.mmap_large_index = mmaplargeindex
1360 1360 if delta_config is not None:
1361 1361 self.delta_config = delta_config.copy()
1362 1362 elif b'delta-config' in self.opener.options:
1363 1363 self.delta_config = self.opener.options[b'delta-config'].copy()
1364 1364 else:
1365 1365 self.delta_config = DeltaConfig()
1366 1366 self.delta_config.upper_bound_comp = upperboundcomp
1367 1367
1368 1368 # Maps rev to chain base rev.
1369 1369 self._chainbasecache = util.lrucachedict(100)
1370 1370
1371 1371 self.index = None
1372 1372 self._docket = None
1373 1373 self._nodemap_docket = None
1374 1374 # Mapping of partial identifiers to full nodes.
1375 1375 self._pcache = {}
1376 1376
1377 1377 # other optionnals features
1378 1378
1379 1379 # Make copy of flag processors so each revlog instance can support
1380 1380 # custom flags.
1381 1381 self._flagprocessors = dict(flagutil.flagprocessors)
1382 1382 # prevent nesting of addgroup
1383 1383 self._adding_group = None
1384 1384
1385 1385 chunk_cache = self._loadindex()
1386 1386 self._load_inner(chunk_cache)
1387 1387 self._concurrencychecker = concurrencychecker
1388 1388
1389 1389 def _init_opts(self):
1390 1390 """process options (from above/config) to setup associated default revlog mode
1391 1391
1392 1392 These values might be affected when actually reading on disk information.
1393 1393
1394 1394 The relevant values are returned for use in _loadindex().
1395 1395
1396 1396 * newversionflags:
1397 1397 version header to use if we need to create a new revlog
1398 1398
1399 1399 * mmapindexthreshold:
1400 1400 minimal index size for start to use mmap
1401 1401
1402 1402 * force_nodemap:
1403 1403 force the usage of a "development" version of the nodemap code
1404 1404 """
1405 1405 opts = self.opener.options
1406 1406
1407 1407 if b'changelogv2' in opts and self.revlog_kind == KIND_CHANGELOG:
1408 1408 new_header = CHANGELOGV2
1409 1409 compute_rank = opts.get(b'changelogv2.compute-rank', True)
1410 1410 self.feature_config.compute_rank = compute_rank
1411 1411 elif b'revlogv2' in opts:
1412 1412 new_header = REVLOGV2
1413 1413 elif b'revlogv1' in opts:
1414 1414 new_header = REVLOGV1
1415 1415 if self._may_inline:
1416 1416 new_header |= FLAG_INLINE_DATA
1417 1417 if b'generaldelta' in opts:
1418 1418 new_header |= FLAG_GENERALDELTA
1419 1419 elif b'revlogv0' in self.opener.options:
1420 1420 new_header = REVLOGV0
1421 1421 else:
1422 1422 new_header = REVLOG_DEFAULT_VERSION
1423 1423
1424 1424 mmapindexthreshold = None
1425 1425 if self.data_config.mmap_large_index:
1426 1426 mmapindexthreshold = self.data_config.mmap_index_threshold
1427 1427 if self.feature_config.enable_ellipsis:
1428 1428 self._flagprocessors[REVIDX_ELLIPSIS] = ellipsisprocessor
1429 1429
1430 1430 # revlog v0 doesn't have flag processors
1431 1431 for flag, processor in opts.get(b'flagprocessors', {}).items():
1432 1432 flagutil.insertflagprocessor(flag, processor, self._flagprocessors)
1433 1433
1434 1434 chunk_cache_size = self.data_config.chunk_cache_size
1435 1435 if chunk_cache_size <= 0:
1436 1436 raise error.RevlogError(
1437 1437 _(b'revlog chunk cache size %r is not greater than 0')
1438 1438 % chunk_cache_size
1439 1439 )
1440 1440 elif chunk_cache_size & (chunk_cache_size - 1):
1441 1441 raise error.RevlogError(
1442 1442 _(b'revlog chunk cache size %r is not a power of 2')
1443 1443 % chunk_cache_size
1444 1444 )
1445 1445 force_nodemap = opts.get(b'devel-force-nodemap', False)
1446 1446 return new_header, mmapindexthreshold, force_nodemap
1447 1447
1448 1448 def _get_data(self, filepath, mmap_threshold, size=None):
1449 1449 """return a file content with or without mmap
1450 1450
1451 1451 If the file is missing return the empty string"""
1452 1452 try:
1453 1453 with self.opener(filepath) as fp:
1454 1454 if mmap_threshold is not None:
1455 1455 file_size = self.opener.fstat(fp).st_size
1456 1456 if file_size >= mmap_threshold:
1457 1457 if size is not None:
1458 1458 # avoid potentiel mmap crash
1459 1459 size = min(file_size, size)
1460 1460 # TODO: should .close() to release resources without
1461 1461 # relying on Python GC
1462 1462 if size is None:
1463 1463 return util.buffer(util.mmapread(fp))
1464 1464 else:
1465 1465 return util.buffer(util.mmapread(fp, size))
1466 1466 if size is None:
1467 1467 return fp.read()
1468 1468 else:
1469 1469 return fp.read(size)
1470 1470 except FileNotFoundError:
1471 1471 return b''
1472 1472
1473 1473 def get_streams(self, max_linkrev, force_inline=False):
1474 1474 """return a list of streams that represent this revlog
1475 1475
1476 1476 This is used by stream-clone to do bytes to bytes copies of a repository.
1477 1477
1478 1478 This streams data for all revisions that refer to a changelog revision up
1479 1479 to `max_linkrev`.
1480 1480
1481 1481 If `force_inline` is set, it enforces that the stream will represent an inline revlog.
1482 1482
1483 1483 It returns is a list of three-tuple:
1484 1484
1485 1485 [
1486 1486 (filename, bytes_stream, stream_size),
1487 1487 …
1488 1488 ]
1489 1489 """
1490 1490 n = len(self)
1491 1491 index = self.index
1492 1492 while n > 0:
1493 1493 linkrev = index[n - 1][4]
1494 1494 if linkrev < max_linkrev:
1495 1495 break
1496 1496 # note: this loop will rarely go through multiple iterations, since
1497 1497 # it only traverses commits created during the current streaming
1498 1498 # pull operation.
1499 1499 #
1500 1500 # If this become a problem, using a binary search should cap the
1501 1501 # runtime of this.
1502 1502 n = n - 1
1503 1503 if n == 0:
1504 1504 # no data to send
1505 1505 return []
1506 1506 index_size = n * index.entry_size
1507 1507 data_size = self.end(n - 1)
1508 1508
1509 1509 # XXX we might have been split (or stripped) since the object
1510 1510 # initialization, We need to close this race too, but having a way to
1511 1511 # pre-open the file we feed to the revlog and never closing them before
1512 1512 # we are done streaming.
1513 1513
1514 1514 if self._inline:
1515 1515
1516 1516 def get_stream():
1517 1517 with self.opener(self._indexfile, mode=b"r") as fp:
1518 1518 yield None
1519 1519 size = index_size + data_size
1520 1520 if size <= 65536:
1521 1521 yield fp.read(size)
1522 1522 else:
1523 1523 yield from util.filechunkiter(fp, limit=size)
1524 1524
1525 1525 inline_stream = get_stream()
1526 1526 next(inline_stream)
1527 1527 return [
1528 1528 (self._indexfile, inline_stream, index_size + data_size),
1529 1529 ]
1530 1530 elif force_inline:
1531 1531
1532 1532 def get_stream():
1533 1533 with self.reading():
1534 1534 yield None
1535 1535
1536 1536 for rev in range(n):
1537 1537 idx = self.index.entry_binary(rev)
1538 1538 if rev == 0 and self._docket is None:
1539 1539 # re-inject the inline flag
1540 1540 header = self._format_flags
1541 1541 header |= self._format_version
1542 1542 header |= FLAG_INLINE_DATA
1543 1543 header = self.index.pack_header(header)
1544 1544 idx = header + idx
1545 1545 yield idx
1546 1546 yield self._inner.get_segment_for_revs(rev, rev)[1]
1547 1547
1548 1548 inline_stream = get_stream()
1549 1549 next(inline_stream)
1550 1550 return [
1551 1551 (self._indexfile, inline_stream, index_size + data_size),
1552 1552 ]
1553 1553 else:
1554 1554
1555 1555 def get_index_stream():
1556 1556 with self.opener(self._indexfile, mode=b"r") as fp:
1557 1557 yield None
1558 1558 if index_size <= 65536:
1559 1559 yield fp.read(index_size)
1560 1560 else:
1561 1561 yield from util.filechunkiter(fp, limit=index_size)
1562 1562
1563 1563 def get_data_stream():
1564 1564 with self._datafp() as fp:
1565 1565 yield None
1566 1566 if data_size <= 65536:
1567 1567 yield fp.read(data_size)
1568 1568 else:
1569 1569 yield from util.filechunkiter(fp, limit=data_size)
1570 1570
1571 1571 index_stream = get_index_stream()
1572 1572 next(index_stream)
1573 1573 data_stream = get_data_stream()
1574 1574 next(data_stream)
1575 1575 return [
1576 1576 (self._datafile, data_stream, data_size),
1577 1577 (self._indexfile, index_stream, index_size),
1578 1578 ]
1579 1579
1580 1580 def _loadindex(self, docket=None):
1581 1581
1582 1582 new_header, mmapindexthreshold, force_nodemap = self._init_opts()
1583 1583
1584 1584 if self.postfix is not None:
1585 1585 entry_point = b'%s.i.%s' % (self.radix, self.postfix)
1586 1586 elif self._trypending and self.opener.exists(b'%s.i.a' % self.radix):
1587 1587 entry_point = b'%s.i.a' % self.radix
1588 1588 elif self._try_split and self.opener.exists(self._split_index_file):
1589 1589 entry_point = self._split_index_file
1590 1590 else:
1591 1591 entry_point = b'%s.i' % self.radix
1592 1592
1593 1593 if docket is not None:
1594 1594 self._docket = docket
1595 1595 self._docket_file = entry_point
1596 1596 else:
1597 1597 self._initempty = True
1598 1598 entry_data = self._get_data(entry_point, mmapindexthreshold)
1599 1599 if len(entry_data) > 0:
1600 1600 header = INDEX_HEADER.unpack(entry_data[:4])[0]
1601 1601 self._initempty = False
1602 1602 else:
1603 1603 header = new_header
1604 1604
1605 1605 self._format_flags = header & ~0xFFFF
1606 1606 self._format_version = header & 0xFFFF
1607 1607
1608 1608 supported_flags = SUPPORTED_FLAGS.get(self._format_version)
1609 1609 if supported_flags is None:
1610 1610 msg = _(b'unknown version (%d) in revlog %s')
1611 1611 msg %= (self._format_version, self.display_id)
1612 1612 raise error.RevlogError(msg)
1613 1613 elif self._format_flags & ~supported_flags:
1614 1614 msg = _(b'unknown flags (%#04x) in version %d revlog %s')
1615 1615 display_flag = self._format_flags >> 16
1616 1616 msg %= (display_flag, self._format_version, self.display_id)
1617 1617 raise error.RevlogError(msg)
1618 1618
1619 1619 features = FEATURES_BY_VERSION[self._format_version]
1620 1620 self._inline = features[b'inline'](self._format_flags)
1621 1621 self.delta_config.general_delta = features[b'generaldelta'](
1622 1622 self._format_flags
1623 1623 )
1624 1624 self.feature_config.has_side_data = features[b'sidedata']
1625 1625
1626 1626 if not features[b'docket']:
1627 1627 self._indexfile = entry_point
1628 1628 index_data = entry_data
1629 1629 else:
1630 1630 self._docket_file = entry_point
1631 1631 if self._initempty:
1632 1632 self._docket = docketutil.default_docket(self, header)
1633 1633 else:
1634 1634 self._docket = docketutil.parse_docket(
1635 1635 self, entry_data, use_pending=self._trypending
1636 1636 )
1637 1637
1638 1638 if self._docket is not None:
1639 1639 self._indexfile = self._docket.index_filepath()
1640 1640 index_data = b''
1641 1641 index_size = self._docket.index_end
1642 1642 if index_size > 0:
1643 1643 index_data = self._get_data(
1644 1644 self._indexfile, mmapindexthreshold, size=index_size
1645 1645 )
1646 1646 if len(index_data) < index_size:
1647 1647 msg = _(b'too few index data for %s: got %d, expected %d')
1648 1648 msg %= (self.display_id, len(index_data), index_size)
1649 1649 raise error.RevlogError(msg)
1650 1650
1651 1651 self._inline = False
1652 1652 # generaldelta implied by version 2 revlogs.
1653 1653 self.delta_config.general_delta = True
1654 1654 # the logic for persistent nodemap will be dealt with within the
1655 1655 # main docket, so disable it for now.
1656 1656 self._nodemap_file = None
1657 1657
1658 1658 if self._docket is not None:
1659 1659 self._datafile = self._docket.data_filepath()
1660 1660 self._sidedatafile = self._docket.sidedata_filepath()
1661 1661 elif self.postfix is None:
1662 1662 self._datafile = b'%s.d' % self.radix
1663 1663 else:
1664 1664 self._datafile = b'%s.d.%s' % (self.radix, self.postfix)
1665 1665
1666 1666 self.nodeconstants = sha1nodeconstants
1667 1667 self.nullid = self.nodeconstants.nullid
1668 1668
1669 1669 # sparse-revlog can't be on without general-delta (issue6056)
1670 1670 if not self.delta_config.general_delta:
1671 1671 self.delta_config.sparse_revlog = False
1672 1672
1673 1673 self._storedeltachains = True
1674 1674
1675 1675 devel_nodemap = (
1676 1676 self._nodemap_file
1677 1677 and force_nodemap
1678 1678 and parse_index_v1_nodemap is not None
1679 1679 )
1680 1680
1681 1681 use_rust_index = False
1682 1682 if rustrevlog is not None:
1683 1683 if self._nodemap_file is not None:
1684 1684 use_rust_index = True
1685 1685 else:
1686 1686 # Using the CIndex is not longer possible, as the
1687 1687 # `AncestorsIterator` and `LazyAncestors` classes now require
1688 1688 # a Rust index for instantiation.
1689 1689 use_rust_index = True
1690 1690
1691 1691 self._parse_index = parse_index_v1
1692 1692 if self._format_version == REVLOGV0:
1693 1693 self._parse_index = revlogv0.parse_index_v0
1694 1694 elif self._format_version == REVLOGV2:
1695 1695 self._parse_index = parse_index_v2
1696 1696 elif self._format_version == CHANGELOGV2:
1697 1697 self._parse_index = parse_index_cl_v2
1698 1698 elif devel_nodemap:
1699 1699 self._parse_index = parse_index_v1_nodemap
1700 1700 elif use_rust_index:
1701 1701 self._parse_index = functools.partial(
1702 1702 parse_index_v1_rust, default_header=new_header
1703 1703 )
1704 1704 try:
1705 1705 d = self._parse_index(index_data, self._inline)
1706 1706 index, chunkcache = d
1707 1707 use_nodemap = (
1708 1708 not self._inline
1709 1709 and self._nodemap_file is not None
1710 1710 and hasattr(index, 'update_nodemap_data')
1711 1711 )
1712 1712 if use_nodemap:
1713 1713 nodemap_data = nodemaputil.persisted_data(self)
1714 1714 if nodemap_data is not None:
1715 1715 docket = nodemap_data[0]
1716 1716 if (
1717 1717 len(d[0]) > docket.tip_rev
1718 1718 and d[0][docket.tip_rev][7] == docket.tip_node
1719 1719 ):
1720 1720 # no changelog tampering
1721 1721 self._nodemap_docket = docket
1722 1722 index.update_nodemap_data(*nodemap_data)
1723 1723 except (ValueError, IndexError):
1724 1724 raise error.RevlogError(
1725 1725 _(b"index %s is corrupted") % self.display_id
1726 1726 )
1727 1727 self.index = index
1728 1728 # revnum -> (chain-length, sum-delta-length)
1729 1729 self._chaininfocache = util.lrucachedict(500)
1730 1730
1731 1731 return chunkcache
1732 1732
1733 1733 def _load_inner(self, chunk_cache):
1734 1734 if self._docket is None:
1735 1735 default_compression_header = None
1736 1736 else:
1737 1737 default_compression_header = self._docket.default_compression_header
1738 1738
1739 1739 self._inner = _InnerRevlog(
1740 1740 opener=self.opener,
1741 1741 index=self.index,
1742 1742 index_file=self._indexfile,
1743 1743 data_file=self._datafile,
1744 1744 sidedata_file=self._sidedatafile,
1745 1745 inline=self._inline,
1746 1746 data_config=self.data_config,
1747 1747 delta_config=self.delta_config,
1748 1748 feature_config=self.feature_config,
1749 1749 chunk_cache=chunk_cache,
1750 1750 default_compression_header=default_compression_header,
1751 1751 )
1752 1752
1753 1753 def get_revlog(self):
1754 1754 """simple function to mirror API of other not-really-revlog API"""
1755 1755 return self
1756 1756
1757 1757 @util.propertycache
1758 1758 def revlog_kind(self):
1759 1759 return self.target[0]
1760 1760
1761 1761 @util.propertycache
1762 1762 def display_id(self):
1763 1763 """The public facing "ID" of the revlog that we use in message"""
1764 1764 if self.revlog_kind == KIND_FILELOG:
1765 1765 # Reference the file without the "data/" prefix, so it is familiar
1766 1766 # to the user.
1767 1767 return self.target[1]
1768 1768 else:
1769 1769 return self.radix
1770 1770
1771 1771 def _datafp(self, mode=b'r'):
1772 1772 """file object for the revlog's data file"""
1773 1773 return self.opener(self._datafile, mode=mode)
1774 1774
1775 1775 def tiprev(self):
1776 1776 return len(self.index) - 1
1777 1777
1778 1778 def tip(self):
1779 1779 return self.node(self.tiprev())
1780 1780
1781 1781 def __contains__(self, rev):
1782 1782 return 0 <= rev < len(self)
1783 1783
1784 1784 def __len__(self):
1785 1785 return len(self.index)
1786 1786
1787 1787 def __iter__(self):
1788 1788 return iter(range(len(self)))
1789 1789
1790 1790 def revs(self, start=0, stop=None):
1791 1791 """iterate over all rev in this revlog (from start to stop)"""
1792 1792 return storageutil.iterrevs(len(self), start=start, stop=stop)
1793 1793
1794 1794 def hasnode(self, node):
1795 1795 try:
1796 1796 self.rev(node)
1797 1797 return True
1798 1798 except KeyError:
1799 1799 return False
1800 1800
1801 1801 def _candelta(self, baserev, rev):
1802 1802 """whether two revisions (baserev, rev) can be delta-ed or not"""
1803 1803 # Disable delta if either rev requires a content-changing flag
1804 1804 # processor (ex. LFS). This is because such flag processor can alter
1805 1805 # the rawtext content that the delta will be based on, and two clients
1806 1806 # could have a same revlog node with different flags (i.e. different
1807 1807 # rawtext contents) and the delta could be incompatible.
1808 1808 if (self.flags(baserev) & REVIDX_RAWTEXT_CHANGING_FLAGS) or (
1809 1809 self.flags(rev) & REVIDX_RAWTEXT_CHANGING_FLAGS
1810 1810 ):
1811 1811 return False
1812 1812 return True
1813 1813
1814 1814 def update_caches(self, transaction):
1815 1815 """update on disk cache
1816 1816
1817 1817 If a transaction is passed, the update may be delayed to transaction
1818 1818 commit."""
1819 1819 if self._nodemap_file is not None:
1820 1820 if transaction is None:
1821 1821 nodemaputil.update_persistent_nodemap(self)
1822 1822 else:
1823 1823 nodemaputil.setup_persistent_nodemap(transaction, self)
1824 1824
1825 1825 def clearcaches(self):
1826 1826 """Clear in-memory caches"""
1827 1827 self._chainbasecache.clear()
1828 1828 self._inner.clear_cache()
1829 1829 self._pcache = {}
1830 1830 self._nodemap_docket = None
1831 1831 self.index.clearcaches()
1832 1832 # The python code is the one responsible for validating the docket, we
1833 1833 # end up having to refresh it here.
1834 1834 use_nodemap = (
1835 1835 not self._inline
1836 1836 and self._nodemap_file is not None
1837 1837 and hasattr(self.index, 'update_nodemap_data')
1838 1838 )
1839 1839 if use_nodemap:
1840 1840 nodemap_data = nodemaputil.persisted_data(self)
1841 1841 if nodemap_data is not None:
1842 1842 self._nodemap_docket = nodemap_data[0]
1843 1843 self.index.update_nodemap_data(*nodemap_data)
1844 1844
1845 1845 def rev(self, node):
1846 1846 """return the revision number associated with a <nodeid>"""
1847 1847 try:
1848 1848 return self.index.rev(node)
1849 1849 except TypeError:
1850 1850 raise
1851 1851 except error.RevlogError:
1852 1852 # parsers.c radix tree lookup failed
1853 1853 if (
1854 1854 node == self.nodeconstants.wdirid
1855 1855 or node in self.nodeconstants.wdirfilenodeids
1856 1856 ):
1857 1857 raise error.WdirUnsupported
1858 1858 raise error.LookupError(node, self.display_id, _(b'no node'))
1859 1859
1860 1860 # Accessors for index entries.
1861 1861
1862 1862 # First tuple entry is 8 bytes. First 6 bytes are offset. Last 2 bytes
1863 1863 # are flags.
1864 1864 def start(self, rev):
1865 1865 return int(self.index[rev][0] >> 16)
1866 1866
1867 1867 def sidedata_cut_off(self, rev):
1868 1868 sd_cut_off = self.index[rev][8]
1869 1869 if sd_cut_off != 0:
1870 1870 return sd_cut_off
1871 1871 # This is some annoying dance, because entries without sidedata
1872 1872 # currently use 0 as their ofsset. (instead of previous-offset +
1873 1873 # previous-size)
1874 1874 #
1875 1875 # We should reconsider this sidedata β†’ 0 sidata_offset policy.
1876 1876 # In the meantime, we need this.
1877 1877 while 0 <= rev:
1878 1878 e = self.index[rev]
1879 1879 if e[9] != 0:
1880 1880 return e[8] + e[9]
1881 1881 rev -= 1
1882 1882 return 0
1883 1883
1884 1884 def flags(self, rev):
1885 1885 return self.index[rev][0] & 0xFFFF
1886 1886
1887 1887 def length(self, rev):
1888 1888 return self.index[rev][1]
1889 1889
1890 1890 def sidedata_length(self, rev):
1891 1891 if not self.feature_config.has_side_data:
1892 1892 return 0
1893 1893 return self.index[rev][9]
1894 1894
1895 1895 def rawsize(self, rev):
1896 1896 """return the length of the uncompressed text for a given revision"""
1897 1897 l = self.index[rev][2]
1898 1898 if l >= 0:
1899 1899 return l
1900 1900
1901 1901 t = self.rawdata(rev)
1902 1902 return len(t)
1903 1903
1904 1904 def size(self, rev):
1905 1905 """length of non-raw text (processed by a "read" flag processor)"""
1906 1906 # fast path: if no "read" flag processor could change the content,
1907 1907 # size is rawsize. note: ELLIPSIS is known to not change the content.
1908 1908 flags = self.flags(rev)
1909 1909 if flags & (flagutil.REVIDX_KNOWN_FLAGS ^ REVIDX_ELLIPSIS) == 0:
1910 1910 return self.rawsize(rev)
1911 1911
1912 1912 return len(self.revision(rev))
1913 1913
1914 1914 def fast_rank(self, rev):
1915 1915 """Return the rank of a revision if already known, or None otherwise.
1916 1916
1917 1917 The rank of a revision is the size of the sub-graph it defines as a
1918 1918 head. Equivalently, the rank of a revision `r` is the size of the set
1919 1919 `ancestors(r)`, `r` included.
1920 1920
1921 1921 This method returns the rank retrieved from the revlog in constant
1922 1922 time. It makes no attempt at computing unknown values for versions of
1923 1923 the revlog which do not persist the rank.
1924 1924 """
1925 1925 rank = self.index[rev][ENTRY_RANK]
1926 1926 if self._format_version != CHANGELOGV2 or rank == RANK_UNKNOWN:
1927 1927 return None
1928 1928 if rev == nullrev:
1929 1929 return 0 # convention
1930 1930 return rank
1931 1931
1932 1932 def chainbase(self, rev):
1933 1933 base = self._chainbasecache.get(rev)
1934 1934 if base is not None:
1935 1935 return base
1936 1936
1937 1937 index = self.index
1938 1938 iterrev = rev
1939 1939 base = index[iterrev][3]
1940 1940 while base != iterrev:
1941 1941 iterrev = base
1942 1942 base = index[iterrev][3]
1943 1943
1944 1944 self._chainbasecache[rev] = base
1945 1945 return base
1946 1946
1947 1947 def linkrev(self, rev):
1948 1948 return self.index[rev][4]
1949 1949
1950 1950 def parentrevs(self, rev):
1951 1951 try:
1952 1952 entry = self.index[rev]
1953 1953 except IndexError:
1954 1954 if rev == wdirrev:
1955 1955 raise error.WdirUnsupported
1956 1956 raise
1957 1957
1958 1958 if self.feature_config.canonical_parent_order and entry[5] == nullrev:
1959 1959 return entry[6], entry[5]
1960 1960 else:
1961 1961 return entry[5], entry[6]
1962 1962
1963 1963 # fast parentrevs(rev) where rev isn't filtered
1964 1964 _uncheckedparentrevs = parentrevs
1965 1965
1966 1966 def node(self, rev):
1967 1967 try:
1968 1968 return self.index[rev][7]
1969 1969 except IndexError:
1970 1970 if rev == wdirrev:
1971 1971 raise error.WdirUnsupported
1972 1972 raise
1973 1973
1974 1974 # Derived from index values.
1975 1975
1976 1976 def end(self, rev):
1977 1977 return self.start(rev) + self.length(rev)
1978 1978
1979 1979 def parents(self, node):
1980 1980 i = self.index
1981 1981 d = i[self.rev(node)]
1982 1982 # inline node() to avoid function call overhead
1983 1983 if self.feature_config.canonical_parent_order and d[5] == self.nullid:
1984 1984 return i[d[6]][7], i[d[5]][7]
1985 1985 else:
1986 1986 return i[d[5]][7], i[d[6]][7]
1987 1987
1988 1988 def chainlen(self, rev):
1989 1989 return self._chaininfo(rev)[0]
1990 1990
1991 1991 def _chaininfo(self, rev):
1992 1992 chaininfocache = self._chaininfocache
1993 1993 if rev in chaininfocache:
1994 1994 return chaininfocache[rev]
1995 1995 index = self.index
1996 1996 generaldelta = self.delta_config.general_delta
1997 1997 iterrev = rev
1998 1998 e = index[iterrev]
1999 1999 clen = 0
2000 2000 compresseddeltalen = 0
2001 2001 while iterrev != e[3]:
2002 2002 clen += 1
2003 2003 compresseddeltalen += e[1]
2004 2004 if generaldelta:
2005 2005 iterrev = e[3]
2006 2006 else:
2007 2007 iterrev -= 1
2008 2008 if iterrev in chaininfocache:
2009 2009 t = chaininfocache[iterrev]
2010 2010 clen += t[0]
2011 2011 compresseddeltalen += t[1]
2012 2012 break
2013 2013 e = index[iterrev]
2014 2014 else:
2015 2015 # Add text length of base since decompressing that also takes
2016 2016 # work. For cache hits the length is already included.
2017 2017 compresseddeltalen += e[1]
2018 2018 r = (clen, compresseddeltalen)
2019 2019 chaininfocache[rev] = r
2020 2020 return r
2021 2021
2022 2022 def _deltachain(self, rev, stoprev=None):
2023 2023 return self._inner._deltachain(rev, stoprev=stoprev)
2024 2024
2025 2025 def ancestors(self, revs, stoprev=0, inclusive=False):
2026 2026 """Generate the ancestors of 'revs' in reverse revision order.
2027 2027 Does not generate revs lower than stoprev.
2028 2028
2029 2029 See the documentation for ancestor.lazyancestors for more details."""
2030 2030
2031 2031 # first, make sure start revisions aren't filtered
2032 2032 revs = list(revs)
2033 2033 checkrev = self.node
2034 2034 for r in revs:
2035 2035 checkrev(r)
2036 2036 # and we're sure ancestors aren't filtered as well
2037 2037
2038 2038 if rustancestor is not None and self.index.rust_ext_compat:
2039 2039 lazyancestors = rustancestor.LazyAncestors
2040 2040 arg = self.index
2041 2041 else:
2042 2042 lazyancestors = ancestor.lazyancestors
2043 2043 arg = self._uncheckedparentrevs
2044 2044 return lazyancestors(arg, revs, stoprev=stoprev, inclusive=inclusive)
2045 2045
2046 2046 def descendants(self, revs):
2047 2047 return dagop.descendantrevs(revs, self.revs, self.parentrevs)
2048 2048
2049 2049 def findcommonmissing(self, common=None, heads=None):
2050 2050 """Return a tuple of the ancestors of common and the ancestors of heads
2051 2051 that are not ancestors of common. In revset terminology, we return the
2052 2052 tuple:
2053 2053
2054 2054 ::common, (::heads) - (::common)
2055 2055
2056 2056 The list is sorted by revision number, meaning it is
2057 2057 topologically sorted.
2058 2058
2059 2059 'heads' and 'common' are both lists of node IDs. If heads is
2060 2060 not supplied, uses all of the revlog's heads. If common is not
2061 2061 supplied, uses nullid."""
2062 2062 if common is None:
2063 2063 common = [self.nullid]
2064 2064 if heads is None:
2065 2065 heads = self.heads()
2066 2066
2067 2067 common = [self.rev(n) for n in common]
2068 2068 heads = [self.rev(n) for n in heads]
2069 2069
2070 2070 # we want the ancestors, but inclusive
2071 2071 class lazyset:
2072 2072 def __init__(self, lazyvalues):
2073 2073 self.addedvalues = set()
2074 2074 self.lazyvalues = lazyvalues
2075 2075
2076 2076 def __contains__(self, value):
2077 2077 return value in self.addedvalues or value in self.lazyvalues
2078 2078
2079 2079 def __iter__(self):
2080 2080 added = self.addedvalues
2081 2081 for r in added:
2082 2082 yield r
2083 2083 for r in self.lazyvalues:
2084 2084 if not r in added:
2085 2085 yield r
2086 2086
2087 2087 def add(self, value):
2088 2088 self.addedvalues.add(value)
2089 2089
2090 2090 def update(self, values):
2091 2091 self.addedvalues.update(values)
2092 2092
2093 2093 has = lazyset(self.ancestors(common))
2094 2094 has.add(nullrev)
2095 2095 has.update(common)
2096 2096
2097 2097 # take all ancestors from heads that aren't in has
2098 2098 missing = set()
2099 2099 visit = collections.deque(r for r in heads if r not in has)
2100 2100 while visit:
2101 2101 r = visit.popleft()
2102 2102 if r in missing:
2103 2103 continue
2104 2104 else:
2105 2105 missing.add(r)
2106 2106 for p in self.parentrevs(r):
2107 2107 if p not in has:
2108 2108 visit.append(p)
2109 2109 missing = list(missing)
2110 2110 missing.sort()
2111 2111 return has, [self.node(miss) for miss in missing]
2112 2112
2113 2113 def incrementalmissingrevs(self, common=None):
2114 2114 """Return an object that can be used to incrementally compute the
2115 2115 revision numbers of the ancestors of arbitrary sets that are not
2116 2116 ancestors of common. This is an ancestor.incrementalmissingancestors
2117 2117 object.
2118 2118
2119 2119 'common' is a list of revision numbers. If common is not supplied, uses
2120 2120 nullrev.
2121 2121 """
2122 2122 if common is None:
2123 2123 common = [nullrev]
2124 2124
2125 2125 if rustancestor is not None and self.index.rust_ext_compat:
2126 2126 return rustancestor.MissingAncestors(self.index, common)
2127 2127 return ancestor.incrementalmissingancestors(self.parentrevs, common)
2128 2128
2129 2129 def findmissingrevs(self, common=None, heads=None):
2130 2130 """Return the revision numbers of the ancestors of heads that
2131 2131 are not ancestors of common.
2132 2132
2133 2133 More specifically, return a list of revision numbers corresponding to
2134 2134 nodes N such that every N satisfies the following constraints:
2135 2135
2136 2136 1. N is an ancestor of some node in 'heads'
2137 2137 2. N is not an ancestor of any node in 'common'
2138 2138
2139 2139 The list is sorted by revision number, meaning it is
2140 2140 topologically sorted.
2141 2141
2142 2142 'heads' and 'common' are both lists of revision numbers. If heads is
2143 2143 not supplied, uses all of the revlog's heads. If common is not
2144 2144 supplied, uses nullid."""
2145 2145 if common is None:
2146 2146 common = [nullrev]
2147 2147 if heads is None:
2148 2148 heads = self.headrevs()
2149 2149
2150 2150 inc = self.incrementalmissingrevs(common=common)
2151 2151 return inc.missingancestors(heads)
2152 2152
2153 2153 def findmissing(self, common=None, heads=None):
2154 2154 """Return the ancestors of heads that are not ancestors of common.
2155 2155
2156 2156 More specifically, return a list of nodes N such that every N
2157 2157 satisfies the following constraints:
2158 2158
2159 2159 1. N is an ancestor of some node in 'heads'
2160 2160 2. N is not an ancestor of any node in 'common'
2161 2161
2162 2162 The list is sorted by revision number, meaning it is
2163 2163 topologically sorted.
2164 2164
2165 2165 'heads' and 'common' are both lists of node IDs. If heads is
2166 2166 not supplied, uses all of the revlog's heads. If common is not
2167 2167 supplied, uses nullid."""
2168 2168 if common is None:
2169 2169 common = [self.nullid]
2170 2170 if heads is None:
2171 2171 heads = self.heads()
2172 2172
2173 2173 common = [self.rev(n) for n in common]
2174 2174 heads = [self.rev(n) for n in heads]
2175 2175
2176 2176 inc = self.incrementalmissingrevs(common=common)
2177 2177 return [self.node(r) for r in inc.missingancestors(heads)]
2178 2178
2179 2179 def nodesbetween(self, roots=None, heads=None):
2180 2180 """Return a topological path from 'roots' to 'heads'.
2181 2181
2182 2182 Return a tuple (nodes, outroots, outheads) where 'nodes' is a
2183 2183 topologically sorted list of all nodes N that satisfy both of
2184 2184 these constraints:
2185 2185
2186 2186 1. N is a descendant of some node in 'roots'
2187 2187 2. N is an ancestor of some node in 'heads'
2188 2188
2189 2189 Every node is considered to be both a descendant and an ancestor
2190 2190 of itself, so every reachable node in 'roots' and 'heads' will be
2191 2191 included in 'nodes'.
2192 2192
2193 2193 'outroots' is the list of reachable nodes in 'roots', i.e., the
2194 2194 subset of 'roots' that is returned in 'nodes'. Likewise,
2195 2195 'outheads' is the subset of 'heads' that is also in 'nodes'.
2196 2196
2197 2197 'roots' and 'heads' are both lists of node IDs. If 'roots' is
2198 2198 unspecified, uses nullid as the only root. If 'heads' is
2199 2199 unspecified, uses list of all of the revlog's heads."""
2200 2200 nonodes = ([], [], [])
2201 2201 if roots is not None:
2202 2202 roots = list(roots)
2203 2203 if not roots:
2204 2204 return nonodes
2205 2205 lowestrev = min([self.rev(n) for n in roots])
2206 2206 else:
2207 2207 roots = [self.nullid] # Everybody's a descendant of nullid
2208 2208 lowestrev = nullrev
2209 2209 if (lowestrev == nullrev) and (heads is None):
2210 2210 # We want _all_ the nodes!
2211 2211 return (
2212 2212 [self.node(r) for r in self],
2213 2213 [self.nullid],
2214 2214 list(self.heads()),
2215 2215 )
2216 2216 if heads is None:
2217 2217 # All nodes are ancestors, so the latest ancestor is the last
2218 2218 # node.
2219 2219 highestrev = len(self) - 1
2220 2220 # Set ancestors to None to signal that every node is an ancestor.
2221 2221 ancestors = None
2222 2222 # Set heads to an empty dictionary for later discovery of heads
2223 2223 heads = {}
2224 2224 else:
2225 2225 heads = list(heads)
2226 2226 if not heads:
2227 2227 return nonodes
2228 2228 ancestors = set()
2229 2229 # Turn heads into a dictionary so we can remove 'fake' heads.
2230 2230 # Also, later we will be using it to filter out the heads we can't
2231 2231 # find from roots.
2232 2232 heads = dict.fromkeys(heads, False)
2233 2233 # Start at the top and keep marking parents until we're done.
2234 2234 nodestotag = set(heads)
2235 2235 # Remember where the top was so we can use it as a limit later.
2236 2236 highestrev = max([self.rev(n) for n in nodestotag])
2237 2237 while nodestotag:
2238 2238 # grab a node to tag
2239 2239 n = nodestotag.pop()
2240 2240 # Never tag nullid
2241 2241 if n == self.nullid:
2242 2242 continue
2243 2243 # A node's revision number represents its place in a
2244 2244 # topologically sorted list of nodes.
2245 2245 r = self.rev(n)
2246 2246 if r >= lowestrev:
2247 2247 if n not in ancestors:
2248 2248 # If we are possibly a descendant of one of the roots
2249 2249 # and we haven't already been marked as an ancestor
2250 2250 ancestors.add(n) # Mark as ancestor
2251 2251 # Add non-nullid parents to list of nodes to tag.
2252 2252 nodestotag.update(
2253 2253 [p for p in self.parents(n) if p != self.nullid]
2254 2254 )
2255 2255 elif n in heads: # We've seen it before, is it a fake head?
2256 2256 # So it is, real heads should not be the ancestors of
2257 2257 # any other heads.
2258 2258 heads.pop(n)
2259 2259 if not ancestors:
2260 2260 return nonodes
2261 2261 # Now that we have our set of ancestors, we want to remove any
2262 2262 # roots that are not ancestors.
2263 2263
2264 2264 # If one of the roots was nullid, everything is included anyway.
2265 2265 if lowestrev > nullrev:
2266 2266 # But, since we weren't, let's recompute the lowest rev to not
2267 2267 # include roots that aren't ancestors.
2268 2268
2269 2269 # Filter out roots that aren't ancestors of heads
2270 2270 roots = [root for root in roots if root in ancestors]
2271 2271 # Recompute the lowest revision
2272 2272 if roots:
2273 2273 lowestrev = min([self.rev(root) for root in roots])
2274 2274 else:
2275 2275 # No more roots? Return empty list
2276 2276 return nonodes
2277 2277 else:
2278 2278 # We are descending from nullid, and don't need to care about
2279 2279 # any other roots.
2280 2280 lowestrev = nullrev
2281 2281 roots = [self.nullid]
2282 2282 # Transform our roots list into a set.
2283 2283 descendants = set(roots)
2284 2284 # Also, keep the original roots so we can filter out roots that aren't
2285 2285 # 'real' roots (i.e. are descended from other roots).
2286 2286 roots = descendants.copy()
2287 2287 # Our topologically sorted list of output nodes.
2288 2288 orderedout = []
2289 2289 # Don't start at nullid since we don't want nullid in our output list,
2290 2290 # and if nullid shows up in descendants, empty parents will look like
2291 2291 # they're descendants.
2292 2292 for r in self.revs(start=max(lowestrev, 0), stop=highestrev + 1):
2293 2293 n = self.node(r)
2294 2294 isdescendant = False
2295 2295 if lowestrev == nullrev: # Everybody is a descendant of nullid
2296 2296 isdescendant = True
2297 2297 elif n in descendants:
2298 2298 # n is already a descendant
2299 2299 isdescendant = True
2300 2300 # This check only needs to be done here because all the roots
2301 2301 # will start being marked is descendants before the loop.
2302 2302 if n in roots:
2303 2303 # If n was a root, check if it's a 'real' root.
2304 2304 p = tuple(self.parents(n))
2305 2305 # If any of its parents are descendants, it's not a root.
2306 2306 if (p[0] in descendants) or (p[1] in descendants):
2307 2307 roots.remove(n)
2308 2308 else:
2309 2309 p = tuple(self.parents(n))
2310 2310 # A node is a descendant if either of its parents are
2311 2311 # descendants. (We seeded the dependents list with the roots
2312 2312 # up there, remember?)
2313 2313 if (p[0] in descendants) or (p[1] in descendants):
2314 2314 descendants.add(n)
2315 2315 isdescendant = True
2316 2316 if isdescendant and ((ancestors is None) or (n in ancestors)):
2317 2317 # Only include nodes that are both descendants and ancestors.
2318 2318 orderedout.append(n)
2319 2319 if (ancestors is not None) and (n in heads):
2320 2320 # We're trying to figure out which heads are reachable
2321 2321 # from roots.
2322 2322 # Mark this head as having been reached
2323 2323 heads[n] = True
2324 2324 elif ancestors is None:
2325 2325 # Otherwise, we're trying to discover the heads.
2326 2326 # Assume this is a head because if it isn't, the next step
2327 2327 # will eventually remove it.
2328 2328 heads[n] = True
2329 2329 # But, obviously its parents aren't.
2330 2330 for p in self.parents(n):
2331 2331 heads.pop(p, None)
2332 2332 heads = [head for head, flag in heads.items() if flag]
2333 2333 roots = list(roots)
2334 2334 assert orderedout
2335 2335 assert roots
2336 2336 assert heads
2337 2337 return (orderedout, roots, heads)
2338 2338
2339 2339 def headrevs(self, revs=None):
2340 2340 if revs is None:
2341 2341 try:
2342 2342 return self.index.headrevs()
2343 2343 except AttributeError:
2344 2344 return self._headrevs()
2345 2345 if rustdagop is not None and self.index.rust_ext_compat:
2346 2346 return rustdagop.headrevs(self.index, revs)
2347 2347 return dagop.headrevs(revs, self._uncheckedparentrevs)
2348 2348
2349 2349 def computephases(self, roots):
2350 2350 return self.index.computephasesmapsets(roots)
2351 2351
2352 2352 def _headrevs(self):
2353 2353 count = len(self)
2354 2354 if not count:
2355 2355 return [nullrev]
2356 2356 # we won't iter over filtered rev so nobody is a head at start
2357 2357 ishead = [0] * (count + 1)
2358 2358 index = self.index
2359 2359 for r in self:
2360 2360 ishead[r] = 1 # I may be an head
2361 2361 e = index[r]
2362 2362 ishead[e[5]] = ishead[e[6]] = 0 # my parent are not
2363 2363 return [r for r, val in enumerate(ishead) if val]
2364 2364
2365 2365 def _head_node_ids(self):
2366 2366 try:
2367 2367 return self.index.head_node_ids()
2368 2368 except AttributeError:
2369 2369 return [self.node(r) for r in self.headrevs()]
2370 2370
2371 2371 def heads(self, start=None, stop=None):
2372 2372 """return the list of all nodes that have no children
2373 2373
2374 2374 if start is specified, only heads that are descendants of
2375 2375 start will be returned
2376 2376 if stop is specified, it will consider all the revs from stop
2377 2377 as if they had no children
2378 2378 """
2379 2379 if start is None and stop is None:
2380 2380 if not len(self):
2381 2381 return [self.nullid]
2382 2382 return self._head_node_ids()
2383 2383 if start is None:
2384 2384 start = nullrev
2385 2385 else:
2386 2386 start = self.rev(start)
2387 2387
2388 2388 stoprevs = {self.rev(n) for n in stop or []}
2389 2389
2390 2390 revs = dagop.headrevssubset(
2391 2391 self.revs, self.parentrevs, startrev=start, stoprevs=stoprevs
2392 2392 )
2393 2393
2394 2394 return [self.node(rev) for rev in revs]
2395 2395
2396 2396 def children(self, node):
2397 2397 """find the children of a given node"""
2398 2398 c = []
2399 2399 p = self.rev(node)
2400 2400 for r in self.revs(start=p + 1):
2401 2401 prevs = [pr for pr in self.parentrevs(r) if pr != nullrev]
2402 2402 if prevs:
2403 2403 for pr in prevs:
2404 2404 if pr == p:
2405 2405 c.append(self.node(r))
2406 2406 elif p == nullrev:
2407 2407 c.append(self.node(r))
2408 2408 return c
2409 2409
2410 2410 def commonancestorsheads(self, a, b):
2411 2411 """calculate all the heads of the common ancestors of nodes a and b"""
2412 2412 a, b = self.rev(a), self.rev(b)
2413 2413 ancs = self._commonancestorsheads(a, b)
2414 2414 return pycompat.maplist(self.node, ancs)
2415 2415
2416 2416 def _commonancestorsheads(self, *revs):
2417 2417 """calculate all the heads of the common ancestors of revs"""
2418 2418 try:
2419 2419 ancs = self.index.commonancestorsheads(*revs)
2420 2420 except (AttributeError, OverflowError): # C implementation failed
2421 2421 ancs = ancestor.commonancestorsheads(self.parentrevs, *revs)
2422 2422 return ancs
2423 2423
2424 2424 def isancestor(self, a, b):
2425 2425 """return True if node a is an ancestor of node b
2426 2426
2427 2427 A revision is considered an ancestor of itself."""
2428 2428 a, b = self.rev(a), self.rev(b)
2429 2429 return self.isancestorrev(a, b)
2430 2430
2431 2431 def isancestorrev(self, a, b):
2432 2432 """return True if revision a is an ancestor of revision b
2433 2433
2434 2434 A revision is considered an ancestor of itself.
2435 2435
2436 2436 The implementation of this is trivial but the use of
2437 2437 reachableroots is not."""
2438 2438 if a == nullrev:
2439 2439 return True
2440 2440 elif a == b:
2441 2441 return True
2442 2442 elif a > b:
2443 2443 return False
2444 2444 return bool(self.reachableroots(a, [b], [a], includepath=False))
2445 2445
2446 2446 def reachableroots(self, minroot, heads, roots, includepath=False):
2447 2447 """return (heads(::(<roots> and <roots>::<heads>)))
2448 2448
2449 2449 If includepath is True, return (<roots>::<heads>)."""
2450 2450 try:
2451 2451 return self.index.reachableroots2(
2452 2452 minroot, heads, roots, includepath
2453 2453 )
2454 2454 except AttributeError:
2455 2455 return dagop._reachablerootspure(
2456 2456 self.parentrevs, minroot, roots, heads, includepath
2457 2457 )
2458 2458
2459 2459 def ancestor(self, a, b):
2460 2460 """calculate the "best" common ancestor of nodes a and b"""
2461 2461
2462 2462 a, b = self.rev(a), self.rev(b)
2463 2463 try:
2464 2464 ancs = self.index.ancestors(a, b)
2465 2465 except (AttributeError, OverflowError):
2466 2466 ancs = ancestor.ancestors(self.parentrevs, a, b)
2467 2467 if ancs:
2468 2468 # choose a consistent winner when there's a tie
2469 2469 return min(map(self.node, ancs))
2470 2470 return self.nullid
2471 2471
2472 2472 def _match(self, id):
2473 2473 if isinstance(id, int):
2474 2474 # rev
2475 2475 return self.node(id)
2476 2476 if len(id) == self.nodeconstants.nodelen:
2477 2477 # possibly a binary node
2478 2478 # odds of a binary node being all hex in ASCII are 1 in 10**25
2479 2479 try:
2480 2480 node = id
2481 2481 self.rev(node) # quick search the index
2482 2482 return node
2483 2483 except error.LookupError:
2484 2484 pass # may be partial hex id
2485 2485 try:
2486 2486 # str(rev)
2487 2487 rev = int(id)
2488 2488 if b"%d" % rev != id:
2489 2489 raise ValueError
2490 2490 if rev < 0:
2491 2491 rev = len(self) + rev
2492 2492 if rev < 0 or rev >= len(self):
2493 2493 raise ValueError
2494 2494 return self.node(rev)
2495 2495 except (ValueError, OverflowError):
2496 2496 pass
2497 2497 if len(id) == 2 * self.nodeconstants.nodelen:
2498 2498 try:
2499 2499 # a full hex nodeid?
2500 2500 node = bin(id)
2501 2501 self.rev(node)
2502 2502 return node
2503 2503 except (binascii.Error, error.LookupError):
2504 2504 pass
2505 2505
2506 2506 def _partialmatch(self, id):
2507 2507 # we don't care wdirfilenodeids as they should be always full hash
2508 2508 maybewdir = self.nodeconstants.wdirhex.startswith(id)
2509 2509 ambiguous = False
2510 2510 try:
2511 2511 partial = self.index.partialmatch(id)
2512 2512 if partial and self.hasnode(partial):
2513 2513 if maybewdir:
2514 2514 # single 'ff...' match in radix tree, ambiguous with wdir
2515 2515 ambiguous = True
2516 2516 else:
2517 2517 return partial
2518 2518 elif maybewdir:
2519 2519 # no 'ff...' match in radix tree, wdir identified
2520 2520 raise error.WdirUnsupported
2521 2521 else:
2522 2522 return None
2523 2523 except error.RevlogError:
2524 2524 # parsers.c radix tree lookup gave multiple matches
2525 2525 # fast path: for unfiltered changelog, radix tree is accurate
2526 2526 if not getattr(self, 'filteredrevs', None):
2527 2527 ambiguous = True
2528 2528 # fall through to slow path that filters hidden revisions
2529 2529 except (AttributeError, ValueError):
2530 2530 # we are pure python, or key is not hex
2531 2531 pass
2532 2532 if ambiguous:
2533 2533 raise error.AmbiguousPrefixLookupError(
2534 2534 id, self.display_id, _(b'ambiguous identifier')
2535 2535 )
2536 2536
2537 2537 if id in self._pcache:
2538 2538 return self._pcache[id]
2539 2539
2540 2540 if len(id) <= 40:
2541 2541 # hex(node)[:...]
2542 2542 l = len(id) // 2 * 2 # grab an even number of digits
2543 2543 try:
2544 2544 # we're dropping the last digit, so let's check that it's hex,
2545 2545 # to avoid the expensive computation below if it's not
2546 2546 if len(id) % 2 > 0:
2547 2547 if not (id[-1] in hexdigits):
2548 2548 return None
2549 2549 prefix = bin(id[:l])
2550 2550 except binascii.Error:
2551 2551 pass
2552 2552 else:
2553 2553 nl = [e[7] for e in self.index if e[7].startswith(prefix)]
2554 2554 nl = [
2555 2555 n for n in nl if hex(n).startswith(id) and self.hasnode(n)
2556 2556 ]
2557 2557 if self.nodeconstants.nullhex.startswith(id):
2558 2558 nl.append(self.nullid)
2559 2559 if len(nl) > 0:
2560 2560 if len(nl) == 1 and not maybewdir:
2561 2561 self._pcache[id] = nl[0]
2562 2562 return nl[0]
2563 2563 raise error.AmbiguousPrefixLookupError(
2564 2564 id, self.display_id, _(b'ambiguous identifier')
2565 2565 )
2566 2566 if maybewdir:
2567 2567 raise error.WdirUnsupported
2568 2568 return None
2569 2569
2570 2570 def lookup(self, id):
2571 2571 """locate a node based on:
2572 2572 - revision number or str(revision number)
2573 2573 - nodeid or subset of hex nodeid
2574 2574 """
2575 2575 n = self._match(id)
2576 2576 if n is not None:
2577 2577 return n
2578 2578 n = self._partialmatch(id)
2579 2579 if n:
2580 2580 return n
2581 2581
2582 2582 raise error.LookupError(id, self.display_id, _(b'no match found'))
2583 2583
2584 2584 def shortest(self, node, minlength=1):
2585 2585 """Find the shortest unambiguous prefix that matches node."""
2586 2586
2587 2587 def isvalid(prefix):
2588 2588 try:
2589 2589 matchednode = self._partialmatch(prefix)
2590 2590 except error.AmbiguousPrefixLookupError:
2591 2591 return False
2592 2592 except error.WdirUnsupported:
2593 2593 # single 'ff...' match
2594 2594 return True
2595 2595 if matchednode is None:
2596 2596 raise error.LookupError(node, self.display_id, _(b'no node'))
2597 2597 return True
2598 2598
2599 2599 def maybewdir(prefix):
2600 2600 return all(c == b'f' for c in pycompat.iterbytestr(prefix))
2601 2601
2602 2602 hexnode = hex(node)
2603 2603
2604 2604 def disambiguate(hexnode, minlength):
2605 2605 """Disambiguate against wdirid."""
2606 2606 for length in range(minlength, len(hexnode) + 1):
2607 2607 prefix = hexnode[:length]
2608 2608 if not maybewdir(prefix):
2609 2609 return prefix
2610 2610
2611 2611 if not getattr(self, 'filteredrevs', None):
2612 2612 try:
2613 2613 length = max(self.index.shortest(node), minlength)
2614 2614 return disambiguate(hexnode, length)
2615 2615 except error.RevlogError:
2616 2616 if node != self.nodeconstants.wdirid:
2617 2617 raise error.LookupError(
2618 2618 node, self.display_id, _(b'no node')
2619 2619 )
2620 2620 except AttributeError:
2621 2621 # Fall through to pure code
2622 2622 pass
2623 2623
2624 2624 if node == self.nodeconstants.wdirid:
2625 2625 for length in range(minlength, len(hexnode) + 1):
2626 2626 prefix = hexnode[:length]
2627 2627 if isvalid(prefix):
2628 2628 return prefix
2629 2629
2630 2630 for length in range(minlength, len(hexnode) + 1):
2631 2631 prefix = hexnode[:length]
2632 2632 if isvalid(prefix):
2633 2633 return disambiguate(hexnode, length)
2634 2634
2635 2635 def cmp(self, node, text):
2636 2636 """compare text with a given file revision
2637 2637
2638 2638 returns True if text is different than what is stored.
2639 2639 """
2640 2640 p1, p2 = self.parents(node)
2641 2641 return storageutil.hashrevisionsha1(text, p1, p2) != node
2642 2642
2643 2643 def deltaparent(self, rev):
2644 2644 """return deltaparent of the given revision"""
2645 2645 base = self.index[rev][3]
2646 2646 if base == rev:
2647 2647 return nullrev
2648 2648 elif self.delta_config.general_delta:
2649 2649 return base
2650 2650 else:
2651 2651 return rev - 1
2652 2652
2653 2653 def issnapshot(self, rev):
2654 2654 """tells whether rev is a snapshot"""
2655 2655 ret = self._inner.issnapshot(rev)
2656 2656 self.issnapshot = self._inner.issnapshot
2657 2657 return ret
2658 2658
2659 2659 def snapshotdepth(self, rev):
2660 2660 """number of snapshot in the chain before this one"""
2661 2661 if not self.issnapshot(rev):
2662 2662 raise error.ProgrammingError(b'revision %d not a snapshot')
2663 2663 return len(self._inner._deltachain(rev)[0]) - 1
2664 2664
2665 2665 def revdiff(self, rev1, rev2):
2666 2666 """return or calculate a delta between two revisions
2667 2667
2668 2668 The delta calculated is in binary form and is intended to be written to
2669 2669 revlog data directly. So this function needs raw revision data.
2670 2670 """
2671 2671 if rev1 != nullrev and self.deltaparent(rev2) == rev1:
2672 2672 return bytes(self._inner._chunk(rev2))
2673 2673
2674 2674 return mdiff.textdiff(self.rawdata(rev1), self.rawdata(rev2))
2675 2675
2676 2676 def revision(self, nodeorrev):
2677 2677 """return an uncompressed revision of a given node or revision
2678 2678 number.
2679 2679 """
2680 2680 return self._revisiondata(nodeorrev)
2681 2681
2682 2682 def sidedata(self, nodeorrev):
2683 2683 """a map of extra data related to the changeset but not part of the hash
2684 2684
2685 2685 This function currently return a dictionary. However, more advanced
2686 2686 mapping object will likely be used in the future for a more
2687 2687 efficient/lazy code.
2688 2688 """
2689 2689 # deal with <nodeorrev> argument type
2690 2690 if isinstance(nodeorrev, int):
2691 2691 rev = nodeorrev
2692 2692 else:
2693 2693 rev = self.rev(nodeorrev)
2694 2694 return self._sidedata(rev)
2695 2695
2696 2696 def _rawtext(self, node, rev):
2697 2697 """return the possibly unvalidated rawtext for a revision
2698 2698
2699 2699 returns (rev, rawtext, validated)
2700 2700 """
2701 2701 # Check if we have the entry in cache
2702 2702 # The cache entry looks like (node, rev, rawtext)
2703 2703 if self._inner._revisioncache:
2704 2704 if self._inner._revisioncache[0] == node:
2705 2705 return (rev, self._inner._revisioncache[2], True)
2706 2706
2707 2707 if rev is None:
2708 2708 rev = self.rev(node)
2709 2709
2710 2710 return self._inner.raw_text(node, rev)
2711 2711
2712 2712 def _revisiondata(self, nodeorrev, raw=False):
2713 2713 # deal with <nodeorrev> argument type
2714 2714 if isinstance(nodeorrev, int):
2715 2715 rev = nodeorrev
2716 2716 node = self.node(rev)
2717 2717 else:
2718 2718 node = nodeorrev
2719 2719 rev = None
2720 2720
2721 2721 # fast path the special `nullid` rev
2722 2722 if node == self.nullid:
2723 2723 return b""
2724 2724
2725 2725 # ``rawtext`` is the text as stored inside the revlog. Might be the
2726 2726 # revision or might need to be processed to retrieve the revision.
2727 2727 rev, rawtext, validated = self._rawtext(node, rev)
2728 2728
2729 2729 if raw and validated:
2730 2730 # if we don't want to process the raw text and that raw
2731 2731 # text is cached, we can exit early.
2732 2732 return rawtext
2733 2733 if rev is None:
2734 2734 rev = self.rev(node)
2735 2735 # the revlog's flag for this revision
2736 2736 # (usually alter its state or content)
2737 2737 flags = self.flags(rev)
2738 2738
2739 2739 if validated and flags == REVIDX_DEFAULT_FLAGS:
2740 2740 # no extra flags set, no flag processor runs, text = rawtext
2741 2741 return rawtext
2742 2742
2743 2743 if raw:
2744 2744 validatehash = flagutil.processflagsraw(self, rawtext, flags)
2745 2745 text = rawtext
2746 2746 else:
2747 2747 r = flagutil.processflagsread(self, rawtext, flags)
2748 2748 text, validatehash = r
2749 2749 if validatehash:
2750 2750 self.checkhash(text, node, rev=rev)
2751 2751 if not validated:
2752 2752 self._inner._revisioncache = (node, rev, rawtext)
2753 2753
2754 2754 return text
2755 2755
2756 2756 def _sidedata(self, rev):
2757 2757 """Return the sidedata for a given revision number."""
2758 2758 sidedata_end = None
2759 2759 if self._docket is not None:
2760 2760 sidedata_end = self._docket.sidedata_end
2761 2761 return self._inner.sidedata(rev, sidedata_end)
2762 2762
2763 2763 def rawdata(self, nodeorrev):
2764 2764 """return an uncompressed raw data of a given node or revision number."""
2765 2765 return self._revisiondata(nodeorrev, raw=True)
2766 2766
2767 2767 def hash(self, text, p1, p2):
2768 2768 """Compute a node hash.
2769 2769
2770 2770 Available as a function so that subclasses can replace the hash
2771 2771 as needed.
2772 2772 """
2773 2773 return storageutil.hashrevisionsha1(text, p1, p2)
2774 2774
2775 2775 def checkhash(self, text, node, p1=None, p2=None, rev=None):
2776 2776 """Check node hash integrity.
2777 2777
2778 2778 Available as a function so that subclasses can extend hash mismatch
2779 2779 behaviors as needed.
2780 2780 """
2781 2781 try:
2782 2782 if p1 is None and p2 is None:
2783 2783 p1, p2 = self.parents(node)
2784 2784 if node != self.hash(text, p1, p2):
2785 2785 # Clear the revision cache on hash failure. The revision cache
2786 2786 # only stores the raw revision and clearing the cache does have
2787 2787 # the side-effect that we won't have a cache hit when the raw
2788 2788 # revision data is accessed. But this case should be rare and
2789 2789 # it is extra work to teach the cache about the hash
2790 2790 # verification state.
2791 2791 if (
2792 2792 self._inner._revisioncache
2793 2793 and self._inner._revisioncache[0] == node
2794 2794 ):
2795 2795 self._inner._revisioncache = None
2796 2796
2797 2797 revornode = rev
2798 2798 if revornode is None:
2799 2799 revornode = templatefilters.short(hex(node))
2800 2800 raise error.RevlogError(
2801 2801 _(b"integrity check failed on %s:%s")
2802 2802 % (self.display_id, pycompat.bytestr(revornode))
2803 2803 )
2804 2804 except error.RevlogError:
2805 2805 if self.feature_config.censorable and storageutil.iscensoredtext(
2806 2806 text
2807 2807 ):
2808 2808 raise error.CensoredNodeError(self.display_id, node, text)
2809 2809 raise
2810 2810
2811 2811 @property
2812 2812 def _split_index_file(self):
2813 2813 """the path where to expect the index of an ongoing splitting operation
2814 2814
2815 2815 The file will only exist if a splitting operation is in progress, but
2816 2816 it is always expected at the same location."""
2817 2817 parts = self.radix.split(b'/')
2818 2818 if len(parts) > 1:
2819 2819 # adds a '-s' prefix to the ``data/` or `meta/` base
2820 2820 head = parts[0] + b'-s'
2821 2821 mids = parts[1:-1]
2822 2822 tail = parts[-1] + b'.i'
2823 2823 pieces = [head] + mids + [tail]
2824 2824 return b'/'.join(pieces)
2825 2825 else:
2826 2826 # the revlog is stored at the root of the store (changelog or
2827 2827 # manifest), no risk of collision.
2828 2828 return self.radix + b'.i.s'
2829 2829
2830 def _enforceinlinesize(self, tr, side_write=True):
2830 def _enforceinlinesize(self, tr):
2831 2831 """Check if the revlog is too big for inline and convert if so.
2832 2832
2833 2833 This should be called after revisions are added to the revlog. If the
2834 2834 revlog has grown too large to be an inline revlog, it will convert it
2835 2835 to use multiple index and data files.
2836 2836 """
2837 2837 tiprev = len(self) - 1
2838 2838 total_size = self.start(tiprev) + self.length(tiprev)
2839 2839 if not self._inline or (self._may_inline and total_size < _maxinline):
2840 2840 return
2841 2841
2842 2842 if self._docket is not None:
2843 2843 msg = b"inline revlog should not have a docket"
2844 2844 raise error.ProgrammingError(msg)
2845 2845
2846 2846 # In the common case, we enforce inline size because the revlog has
2847 2847 # been appened too. And in such case, it must have an initial offset
2848 2848 # recorded in the transaction.
2849 2849 troffset = tr.findoffset(self._inner.canonical_index_file)
2850 2850 pre_touched = troffset is not None
2851 2851 if not pre_touched and self.target[0] != KIND_CHANGELOG:
2852 2852 raise error.RevlogError(
2853 2853 _(b"%s not found in the transaction") % self._indexfile
2854 2854 )
2855 2855
2856 2856 tr.addbackup(self._inner.canonical_index_file, for_offset=pre_touched)
2857 2857 tr.add(self._datafile, 0)
2858 2858
2859 2859 new_index_file_path = None
2860 if side_write:
2861 old_index_file_path = self._indexfile
2862 new_index_file_path = self._split_index_file
2863 opener = self.opener
2864 weak_self = weakref.ref(self)
2865
2866 # the "split" index replace the real index when the transaction is
2867 # finalized
2868 def finalize_callback(tr):
2869 opener.rename(
2870 new_index_file_path,
2871 old_index_file_path,
2872 checkambig=True,
2873 )
2874 maybe_self = weak_self()
2875 if maybe_self is not None:
2876 maybe_self._indexfile = old_index_file_path
2877 maybe_self._inner.index_file = maybe_self._indexfile
2878
2879 def abort_callback(tr):
2880 maybe_self = weak_self()
2881 if maybe_self is not None:
2882 maybe_self._indexfile = old_index_file_path
2883 maybe_self._inner.inline = True
2884 maybe_self._inner.index_file = old_index_file_path
2885
2886 tr.registertmp(new_index_file_path)
2887 if self.target[1] is not None:
2888 callback_id = b'000-revlog-split-%d-%s' % self.target
2889 else:
2890 callback_id = b'000-revlog-split-%d' % self.target[0]
2891 tr.addfinalize(callback_id, finalize_callback)
2892 tr.addabort(callback_id, abort_callback)
2860 old_index_file_path = self._indexfile
2861 new_index_file_path = self._split_index_file
2862 opener = self.opener
2863 weak_self = weakref.ref(self)
2864
2865 # the "split" index replace the real index when the transaction is
2866 # finalized
2867 def finalize_callback(tr):
2868 opener.rename(
2869 new_index_file_path,
2870 old_index_file_path,
2871 checkambig=True,
2872 )
2873 maybe_self = weak_self()
2874 if maybe_self is not None:
2875 maybe_self._indexfile = old_index_file_path
2876 maybe_self._inner.index_file = maybe_self._indexfile
2877
2878 def abort_callback(tr):
2879 maybe_self = weak_self()
2880 if maybe_self is not None:
2881 maybe_self._indexfile = old_index_file_path
2882 maybe_self._inner.inline = True
2883 maybe_self._inner.index_file = old_index_file_path
2884
2885 tr.registertmp(new_index_file_path)
2886 if self.target[1] is not None:
2887 callback_id = b'000-revlog-split-%d-%s' % self.target
2888 else:
2889 callback_id = b'000-revlog-split-%d' % self.target[0]
2890 tr.addfinalize(callback_id, finalize_callback)
2891 tr.addabort(callback_id, abort_callback)
2893 2892
2894 2893 self._format_flags &= ~FLAG_INLINE_DATA
2895 2894 self._inner.split_inline(
2896 2895 tr,
2897 2896 self._format_flags | self._format_version,
2898 2897 new_index_file_path=new_index_file_path,
2899 2898 )
2900 2899
2901 2900 self._inline = False
2902 2901 if new_index_file_path is not None:
2903 2902 self._indexfile = new_index_file_path
2904 2903
2905 2904 nodemaputil.setup_persistent_nodemap(tr, self)
2906 2905
2907 2906 def _nodeduplicatecallback(self, transaction, node):
2908 2907 """called when trying to add a node already stored."""
2909 2908
2910 2909 @contextlib.contextmanager
2911 2910 def reading(self):
2912 2911 with self._inner.reading():
2913 2912 yield
2914 2913
2915 2914 @contextlib.contextmanager
2916 2915 def _writing(self, transaction):
2917 2916 if self._trypending:
2918 2917 msg = b'try to write in a `trypending` revlog: %s'
2919 2918 msg %= self.display_id
2920 2919 raise error.ProgrammingError(msg)
2921 2920 if self._inner.is_writing:
2922 2921 yield
2923 2922 else:
2924 2923 data_end = None
2925 2924 sidedata_end = None
2926 2925 if self._docket is not None:
2927 2926 data_end = self._docket.data_end
2928 2927 sidedata_end = self._docket.sidedata_end
2929 2928 with self._inner.writing(
2930 2929 transaction,
2931 2930 data_end=data_end,
2932 2931 sidedata_end=sidedata_end,
2933 2932 ):
2934 2933 yield
2935 2934 if self._docket is not None:
2936 2935 self._write_docket(transaction)
2937 2936
2938 2937 @property
2939 2938 def is_delaying(self):
2940 2939 return self._inner.is_delaying
2941 2940
2942 2941 def _write_docket(self, transaction):
2943 2942 """write the current docket on disk
2944 2943
2945 2944 Exist as a method to help changelog to implement transaction logic
2946 2945
2947 2946 We could also imagine using the same transaction logic for all revlog
2948 2947 since docket are cheap."""
2949 2948 self._docket.write(transaction)
2950 2949
2951 2950 def addrevision(
2952 2951 self,
2953 2952 text,
2954 2953 transaction,
2955 2954 link,
2956 2955 p1,
2957 2956 p2,
2958 2957 cachedelta=None,
2959 2958 node=None,
2960 2959 flags=REVIDX_DEFAULT_FLAGS,
2961 2960 deltacomputer=None,
2962 2961 sidedata=None,
2963 2962 ):
2964 2963 """add a revision to the log
2965 2964
2966 2965 text - the revision data to add
2967 2966 transaction - the transaction object used for rollback
2968 2967 link - the linkrev data to add
2969 2968 p1, p2 - the parent nodeids of the revision
2970 2969 cachedelta - an optional precomputed delta
2971 2970 node - nodeid of revision; typically node is not specified, and it is
2972 2971 computed by default as hash(text, p1, p2), however subclasses might
2973 2972 use different hashing method (and override checkhash() in such case)
2974 2973 flags - the known flags to set on the revision
2975 2974 deltacomputer - an optional deltacomputer instance shared between
2976 2975 multiple calls
2977 2976 """
2978 2977 if link == nullrev:
2979 2978 raise error.RevlogError(
2980 2979 _(b"attempted to add linkrev -1 to %s") % self.display_id
2981 2980 )
2982 2981
2983 2982 if sidedata is None:
2984 2983 sidedata = {}
2985 2984 elif sidedata and not self.feature_config.has_side_data:
2986 2985 raise error.ProgrammingError(
2987 2986 _(b"trying to add sidedata to a revlog who don't support them")
2988 2987 )
2989 2988
2990 2989 if flags:
2991 2990 node = node or self.hash(text, p1, p2)
2992 2991
2993 2992 rawtext, validatehash = flagutil.processflagswrite(self, text, flags)
2994 2993
2995 2994 # If the flag processor modifies the revision data, ignore any provided
2996 2995 # cachedelta.
2997 2996 if rawtext != text:
2998 2997 cachedelta = None
2999 2998
3000 2999 if len(rawtext) > _maxentrysize:
3001 3000 raise error.RevlogError(
3002 3001 _(
3003 3002 b"%s: size of %d bytes exceeds maximum revlog storage of 2GiB"
3004 3003 )
3005 3004 % (self.display_id, len(rawtext))
3006 3005 )
3007 3006
3008 3007 node = node or self.hash(rawtext, p1, p2)
3009 3008 rev = self.index.get_rev(node)
3010 3009 if rev is not None:
3011 3010 return rev
3012 3011
3013 3012 if validatehash:
3014 3013 self.checkhash(rawtext, node, p1=p1, p2=p2)
3015 3014
3016 3015 return self.addrawrevision(
3017 3016 rawtext,
3018 3017 transaction,
3019 3018 link,
3020 3019 p1,
3021 3020 p2,
3022 3021 node,
3023 3022 flags,
3024 3023 cachedelta=cachedelta,
3025 3024 deltacomputer=deltacomputer,
3026 3025 sidedata=sidedata,
3027 3026 )
3028 3027
3029 3028 def addrawrevision(
3030 3029 self,
3031 3030 rawtext,
3032 3031 transaction,
3033 3032 link,
3034 3033 p1,
3035 3034 p2,
3036 3035 node,
3037 3036 flags,
3038 3037 cachedelta=None,
3039 3038 deltacomputer=None,
3040 3039 sidedata=None,
3041 3040 ):
3042 3041 """add a raw revision with known flags, node and parents
3043 3042 useful when reusing a revision not stored in this revlog (ex: received
3044 3043 over wire, or read from an external bundle).
3045 3044 """
3046 3045 with self._writing(transaction):
3047 3046 return self._addrevision(
3048 3047 node,
3049 3048 rawtext,
3050 3049 transaction,
3051 3050 link,
3052 3051 p1,
3053 3052 p2,
3054 3053 flags,
3055 3054 cachedelta,
3056 3055 deltacomputer=deltacomputer,
3057 3056 sidedata=sidedata,
3058 3057 )
3059 3058
3060 3059 def compress(self, data):
3061 3060 return self._inner.compress(data)
3062 3061
3063 3062 def decompress(self, data):
3064 3063 return self._inner.decompress(data)
3065 3064
3066 3065 def _addrevision(
3067 3066 self,
3068 3067 node,
3069 3068 rawtext,
3070 3069 transaction,
3071 3070 link,
3072 3071 p1,
3073 3072 p2,
3074 3073 flags,
3075 3074 cachedelta,
3076 3075 alwayscache=False,
3077 3076 deltacomputer=None,
3078 3077 sidedata=None,
3079 3078 ):
3080 3079 """internal function to add revisions to the log
3081 3080
3082 3081 see addrevision for argument descriptions.
3083 3082
3084 3083 note: "addrevision" takes non-raw text, "_addrevision" takes raw text.
3085 3084
3086 3085 if "deltacomputer" is not provided or None, a defaultdeltacomputer will
3087 3086 be used.
3088 3087
3089 3088 invariants:
3090 3089 - rawtext is optional (can be None); if not set, cachedelta must be set.
3091 3090 if both are set, they must correspond to each other.
3092 3091 """
3093 3092 if node == self.nullid:
3094 3093 raise error.RevlogError(
3095 3094 _(b"%s: attempt to add null revision") % self.display_id
3096 3095 )
3097 3096 if (
3098 3097 node == self.nodeconstants.wdirid
3099 3098 or node in self.nodeconstants.wdirfilenodeids
3100 3099 ):
3101 3100 raise error.RevlogError(
3102 3101 _(b"%s: attempt to add wdir revision") % self.display_id
3103 3102 )
3104 3103 if self._inner._writinghandles is None:
3105 3104 msg = b'adding revision outside `revlog._writing` context'
3106 3105 raise error.ProgrammingError(msg)
3107 3106
3108 3107 btext = [rawtext]
3109 3108
3110 3109 curr = len(self)
3111 3110 prev = curr - 1
3112 3111
3113 3112 offset = self._get_data_offset(prev)
3114 3113
3115 3114 if self._concurrencychecker:
3116 3115 ifh, dfh, sdfh = self._inner._writinghandles
3117 3116 # XXX no checking for the sidedata file
3118 3117 if self._inline:
3119 3118 # offset is "as if" it were in the .d file, so we need to add on
3120 3119 # the size of the entry metadata.
3121 3120 self._concurrencychecker(
3122 3121 ifh, self._indexfile, offset + curr * self.index.entry_size
3123 3122 )
3124 3123 else:
3125 3124 # Entries in the .i are a consistent size.
3126 3125 self._concurrencychecker(
3127 3126 ifh, self._indexfile, curr * self.index.entry_size
3128 3127 )
3129 3128 self._concurrencychecker(dfh, self._datafile, offset)
3130 3129
3131 3130 p1r, p2r = self.rev(p1), self.rev(p2)
3132 3131
3133 3132 # full versions are inserted when the needed deltas
3134 3133 # become comparable to the uncompressed text
3135 3134 if rawtext is None:
3136 3135 # need rawtext size, before changed by flag processors, which is
3137 3136 # the non-raw size. use revlog explicitly to avoid filelog's extra
3138 3137 # logic that might remove metadata size.
3139 3138 textlen = mdiff.patchedsize(
3140 3139 revlog.size(self, cachedelta[0]), cachedelta[1]
3141 3140 )
3142 3141 else:
3143 3142 textlen = len(rawtext)
3144 3143
3145 3144 if deltacomputer is None:
3146 3145 write_debug = None
3147 3146 if self.delta_config.debug_delta:
3148 3147 write_debug = transaction._report
3149 3148 deltacomputer = deltautil.deltacomputer(
3150 3149 self, write_debug=write_debug
3151 3150 )
3152 3151
3153 3152 if cachedelta is not None and len(cachedelta) == 2:
3154 3153 # If the cached delta has no information about how it should be
3155 3154 # reused, add the default reuse instruction according to the
3156 3155 # revlog's configuration.
3157 3156 if (
3158 3157 self.delta_config.general_delta
3159 3158 and self.delta_config.lazy_delta_base
3160 3159 ):
3161 3160 delta_base_reuse = DELTA_BASE_REUSE_TRY
3162 3161 else:
3163 3162 delta_base_reuse = DELTA_BASE_REUSE_NO
3164 3163 cachedelta = (cachedelta[0], cachedelta[1], delta_base_reuse)
3165 3164
3166 3165 revinfo = revlogutils.revisioninfo(
3167 3166 node,
3168 3167 p1,
3169 3168 p2,
3170 3169 btext,
3171 3170 textlen,
3172 3171 cachedelta,
3173 3172 flags,
3174 3173 )
3175 3174
3176 3175 deltainfo = deltacomputer.finddeltainfo(revinfo)
3177 3176
3178 3177 compression_mode = COMP_MODE_INLINE
3179 3178 if self._docket is not None:
3180 3179 default_comp = self._docket.default_compression_header
3181 3180 r = deltautil.delta_compression(default_comp, deltainfo)
3182 3181 compression_mode, deltainfo = r
3183 3182
3184 3183 sidedata_compression_mode = COMP_MODE_INLINE
3185 3184 if sidedata and self.feature_config.has_side_data:
3186 3185 sidedata_compression_mode = COMP_MODE_PLAIN
3187 3186 serialized_sidedata = sidedatautil.serialize_sidedata(sidedata)
3188 3187 sidedata_offset = self._docket.sidedata_end
3189 3188 h, comp_sidedata = self._inner.compress(serialized_sidedata)
3190 3189 if (
3191 3190 h != b'u'
3192 3191 and comp_sidedata[0:1] != b'\0'
3193 3192 and len(comp_sidedata) < len(serialized_sidedata)
3194 3193 ):
3195 3194 assert not h
3196 3195 if (
3197 3196 comp_sidedata[0:1]
3198 3197 == self._docket.default_compression_header
3199 3198 ):
3200 3199 sidedata_compression_mode = COMP_MODE_DEFAULT
3201 3200 serialized_sidedata = comp_sidedata
3202 3201 else:
3203 3202 sidedata_compression_mode = COMP_MODE_INLINE
3204 3203 serialized_sidedata = comp_sidedata
3205 3204 else:
3206 3205 serialized_sidedata = b""
3207 3206 # Don't store the offset if the sidedata is empty, that way
3208 3207 # we can easily detect empty sidedata and they will be no different
3209 3208 # than ones we manually add.
3210 3209 sidedata_offset = 0
3211 3210
3212 3211 rank = RANK_UNKNOWN
3213 3212 if self.feature_config.compute_rank:
3214 3213 if (p1r, p2r) == (nullrev, nullrev):
3215 3214 rank = 1
3216 3215 elif p1r != nullrev and p2r == nullrev:
3217 3216 rank = 1 + self.fast_rank(p1r)
3218 3217 elif p1r == nullrev and p2r != nullrev:
3219 3218 rank = 1 + self.fast_rank(p2r)
3220 3219 else: # merge node
3221 3220 if rustdagop is not None and self.index.rust_ext_compat:
3222 3221 rank = rustdagop.rank(self.index, p1r, p2r)
3223 3222 else:
3224 3223 pmin, pmax = sorted((p1r, p2r))
3225 3224 rank = 1 + self.fast_rank(pmax)
3226 3225 rank += sum(1 for _ in self.findmissingrevs([pmax], [pmin]))
3227 3226
3228 3227 e = revlogutils.entry(
3229 3228 flags=flags,
3230 3229 data_offset=offset,
3231 3230 data_compressed_length=deltainfo.deltalen,
3232 3231 data_uncompressed_length=textlen,
3233 3232 data_compression_mode=compression_mode,
3234 3233 data_delta_base=deltainfo.base,
3235 3234 link_rev=link,
3236 3235 parent_rev_1=p1r,
3237 3236 parent_rev_2=p2r,
3238 3237 node_id=node,
3239 3238 sidedata_offset=sidedata_offset,
3240 3239 sidedata_compressed_length=len(serialized_sidedata),
3241 3240 sidedata_compression_mode=sidedata_compression_mode,
3242 3241 rank=rank,
3243 3242 )
3244 3243
3245 3244 self.index.append(e)
3246 3245 entry = self.index.entry_binary(curr)
3247 3246 if curr == 0 and self._docket is None:
3248 3247 header = self._format_flags | self._format_version
3249 3248 header = self.index.pack_header(header)
3250 3249 entry = header + entry
3251 3250 self._writeentry(
3252 3251 transaction,
3253 3252 entry,
3254 3253 deltainfo.data,
3255 3254 link,
3256 3255 offset,
3257 3256 serialized_sidedata,
3258 3257 sidedata_offset,
3259 3258 )
3260 3259
3261 3260 rawtext = btext[0]
3262 3261
3263 3262 if alwayscache and rawtext is None:
3264 3263 rawtext = deltacomputer.buildtext(revinfo)
3265 3264
3266 3265 if type(rawtext) == bytes: # only accept immutable objects
3267 3266 self._inner._revisioncache = (node, curr, rawtext)
3268 3267 self._chainbasecache[curr] = deltainfo.chainbase
3269 3268 return curr
3270 3269
3271 3270 def _get_data_offset(self, prev):
3272 3271 """Returns the current offset in the (in-transaction) data file.
3273 3272 Versions < 2 of the revlog can get this 0(1), revlog v2 needs a docket
3274 3273 file to store that information: since sidedata can be rewritten to the
3275 3274 end of the data file within a transaction, you can have cases where, for
3276 3275 example, rev `n` does not have sidedata while rev `n - 1` does, leading
3277 3276 to `n - 1`'s sidedata being written after `n`'s data.
3278 3277
3279 3278 TODO cache this in a docket file before getting out of experimental."""
3280 3279 if self._docket is None:
3281 3280 return self.end(prev)
3282 3281 else:
3283 3282 return self._docket.data_end
3284 3283
3285 3284 def _writeentry(
3286 3285 self,
3287 3286 transaction,
3288 3287 entry,
3289 3288 data,
3290 3289 link,
3291 3290 offset,
3292 3291 sidedata,
3293 3292 sidedata_offset,
3294 3293 ):
3295 3294 # Files opened in a+ mode have inconsistent behavior on various
3296 3295 # platforms. Windows requires that a file positioning call be made
3297 3296 # when the file handle transitions between reads and writes. See
3298 3297 # 3686fa2b8eee and the mixedfilemodewrapper in windows.py. On other
3299 3298 # platforms, Python or the platform itself can be buggy. Some versions
3300 3299 # of Solaris have been observed to not append at the end of the file
3301 3300 # if the file was seeked to before the end. See issue4943 for more.
3302 3301 #
3303 3302 # We work around this issue by inserting a seek() before writing.
3304 3303 # Note: This is likely not necessary on Python 3. However, because
3305 3304 # the file handle is reused for reads and may be seeked there, we need
3306 3305 # to be careful before changing this.
3307 3306 index_end = data_end = sidedata_end = None
3308 3307 if self._docket is not None:
3309 3308 index_end = self._docket.index_end
3310 3309 data_end = self._docket.data_end
3311 3310 sidedata_end = self._docket.sidedata_end
3312 3311
3313 3312 files_end = self._inner.write_entry(
3314 3313 transaction,
3315 3314 entry,
3316 3315 data,
3317 3316 link,
3318 3317 offset,
3319 3318 sidedata,
3320 3319 sidedata_offset,
3321 3320 index_end,
3322 3321 data_end,
3323 3322 sidedata_end,
3324 3323 )
3325 3324 self._enforceinlinesize(transaction)
3326 3325 if self._docket is not None:
3327 3326 self._docket.index_end = files_end[0]
3328 3327 self._docket.data_end = files_end[1]
3329 3328 self._docket.sidedata_end = files_end[2]
3330 3329
3331 3330 nodemaputil.setup_persistent_nodemap(transaction, self)
3332 3331
3333 3332 def addgroup(
3334 3333 self,
3335 3334 deltas,
3336 3335 linkmapper,
3337 3336 transaction,
3338 3337 alwayscache=False,
3339 3338 addrevisioncb=None,
3340 3339 duplicaterevisioncb=None,
3341 3340 debug_info=None,
3342 3341 delta_base_reuse_policy=None,
3343 3342 ):
3344 3343 """
3345 3344 add a delta group
3346 3345
3347 3346 given a set of deltas, add them to the revision log. the
3348 3347 first delta is against its parent, which should be in our
3349 3348 log, the rest are against the previous delta.
3350 3349
3351 3350 If ``addrevisioncb`` is defined, it will be called with arguments of
3352 3351 this revlog and the node that was added.
3353 3352 """
3354 3353
3355 3354 if self._adding_group:
3356 3355 raise error.ProgrammingError(b'cannot nest addgroup() calls')
3357 3356
3358 3357 # read the default delta-base reuse policy from revlog config if the
3359 3358 # group did not specify one.
3360 3359 if delta_base_reuse_policy is None:
3361 3360 if (
3362 3361 self.delta_config.general_delta
3363 3362 and self.delta_config.lazy_delta_base
3364 3363 ):
3365 3364 delta_base_reuse_policy = DELTA_BASE_REUSE_TRY
3366 3365 else:
3367 3366 delta_base_reuse_policy = DELTA_BASE_REUSE_NO
3368 3367
3369 3368 self._adding_group = True
3370 3369 empty = True
3371 3370 try:
3372 3371 with self._writing(transaction):
3373 3372 write_debug = None
3374 3373 if self.delta_config.debug_delta:
3375 3374 write_debug = transaction._report
3376 3375 deltacomputer = deltautil.deltacomputer(
3377 3376 self,
3378 3377 write_debug=write_debug,
3379 3378 debug_info=debug_info,
3380 3379 )
3381 3380 # loop through our set of deltas
3382 3381 for data in deltas:
3383 3382 (
3384 3383 node,
3385 3384 p1,
3386 3385 p2,
3387 3386 linknode,
3388 3387 deltabase,
3389 3388 delta,
3390 3389 flags,
3391 3390 sidedata,
3392 3391 ) = data
3393 3392 link = linkmapper(linknode)
3394 3393 flags = flags or REVIDX_DEFAULT_FLAGS
3395 3394
3396 3395 rev = self.index.get_rev(node)
3397 3396 if rev is not None:
3398 3397 # this can happen if two branches make the same change
3399 3398 self._nodeduplicatecallback(transaction, rev)
3400 3399 if duplicaterevisioncb:
3401 3400 duplicaterevisioncb(self, rev)
3402 3401 empty = False
3403 3402 continue
3404 3403
3405 3404 for p in (p1, p2):
3406 3405 if not self.index.has_node(p):
3407 3406 raise error.LookupError(
3408 3407 p, self.radix, _(b'unknown parent')
3409 3408 )
3410 3409
3411 3410 if not self.index.has_node(deltabase):
3412 3411 raise error.LookupError(
3413 3412 deltabase, self.display_id, _(b'unknown delta base')
3414 3413 )
3415 3414
3416 3415 baserev = self.rev(deltabase)
3417 3416
3418 3417 if baserev != nullrev and self.iscensored(baserev):
3419 3418 # if base is censored, delta must be full replacement in a
3420 3419 # single patch operation
3421 3420 hlen = struct.calcsize(b">lll")
3422 3421 oldlen = self.rawsize(baserev)
3423 3422 newlen = len(delta) - hlen
3424 3423 if delta[:hlen] != mdiff.replacediffheader(
3425 3424 oldlen, newlen
3426 3425 ):
3427 3426 raise error.CensoredBaseError(
3428 3427 self.display_id, self.node(baserev)
3429 3428 )
3430 3429
3431 3430 if not flags and self._peek_iscensored(baserev, delta):
3432 3431 flags |= REVIDX_ISCENSORED
3433 3432
3434 3433 # We assume consumers of addrevisioncb will want to retrieve
3435 3434 # the added revision, which will require a call to
3436 3435 # revision(). revision() will fast path if there is a cache
3437 3436 # hit. So, we tell _addrevision() to always cache in this case.
3438 3437 # We're only using addgroup() in the context of changegroup
3439 3438 # generation so the revision data can always be handled as raw
3440 3439 # by the flagprocessor.
3441 3440 rev = self._addrevision(
3442 3441 node,
3443 3442 None,
3444 3443 transaction,
3445 3444 link,
3446 3445 p1,
3447 3446 p2,
3448 3447 flags,
3449 3448 (baserev, delta, delta_base_reuse_policy),
3450 3449 alwayscache=alwayscache,
3451 3450 deltacomputer=deltacomputer,
3452 3451 sidedata=sidedata,
3453 3452 )
3454 3453
3455 3454 if addrevisioncb:
3456 3455 addrevisioncb(self, rev)
3457 3456 empty = False
3458 3457 finally:
3459 3458 self._adding_group = False
3460 3459 return not empty
3461 3460
3462 3461 def iscensored(self, rev):
3463 3462 """Check if a file revision is censored."""
3464 3463 if not self.feature_config.censorable:
3465 3464 return False
3466 3465
3467 3466 return self.flags(rev) & REVIDX_ISCENSORED
3468 3467
3469 3468 def _peek_iscensored(self, baserev, delta):
3470 3469 """Quickly check if a delta produces a censored revision."""
3471 3470 if not self.feature_config.censorable:
3472 3471 return False
3473 3472
3474 3473 return storageutil.deltaiscensored(delta, baserev, self.rawsize)
3475 3474
3476 3475 def getstrippoint(self, minlink):
3477 3476 """find the minimum rev that must be stripped to strip the linkrev
3478 3477
3479 3478 Returns a tuple containing the minimum rev and a set of all revs that
3480 3479 have linkrevs that will be broken by this strip.
3481 3480 """
3482 3481 return storageutil.resolvestripinfo(
3483 3482 minlink,
3484 3483 len(self) - 1,
3485 3484 self.headrevs(),
3486 3485 self.linkrev,
3487 3486 self.parentrevs,
3488 3487 )
3489 3488
3490 3489 def strip(self, minlink, transaction):
3491 3490 """truncate the revlog on the first revision with a linkrev >= minlink
3492 3491
3493 3492 This function is called when we're stripping revision minlink and
3494 3493 its descendants from the repository.
3495 3494
3496 3495 We have to remove all revisions with linkrev >= minlink, because
3497 3496 the equivalent changelog revisions will be renumbered after the
3498 3497 strip.
3499 3498
3500 3499 So we truncate the revlog on the first of these revisions, and
3501 3500 trust that the caller has saved the revisions that shouldn't be
3502 3501 removed and that it'll re-add them after this truncation.
3503 3502 """
3504 3503 if len(self) == 0:
3505 3504 return
3506 3505
3507 3506 rev, _ = self.getstrippoint(minlink)
3508 3507 if rev == len(self):
3509 3508 return
3510 3509
3511 3510 # first truncate the files on disk
3512 3511 data_end = self.start(rev)
3513 3512 if not self._inline:
3514 3513 transaction.add(self._datafile, data_end)
3515 3514 end = rev * self.index.entry_size
3516 3515 else:
3517 3516 end = data_end + (rev * self.index.entry_size)
3518 3517
3519 3518 if self._sidedatafile:
3520 3519 sidedata_end = self.sidedata_cut_off(rev)
3521 3520 transaction.add(self._sidedatafile, sidedata_end)
3522 3521
3523 3522 transaction.add(self._indexfile, end)
3524 3523 if self._docket is not None:
3525 3524 # XXX we could, leverage the docket while stripping. However it is
3526 3525 # not powerfull enough at the time of this comment
3527 3526 self._docket.index_end = end
3528 3527 self._docket.data_end = data_end
3529 3528 self._docket.sidedata_end = sidedata_end
3530 3529 self._docket.write(transaction, stripping=True)
3531 3530
3532 3531 # then reset internal state in memory to forget those revisions
3533 3532 self._chaininfocache = util.lrucachedict(500)
3534 3533 self._inner.clear_cache()
3535 3534
3536 3535 del self.index[rev:-1]
3537 3536
3538 3537 def checksize(self):
3539 3538 """Check size of index and data files
3540 3539
3541 3540 return a (dd, di) tuple.
3542 3541 - dd: extra bytes for the "data" file
3543 3542 - di: extra bytes for the "index" file
3544 3543
3545 3544 A healthy revlog will return (0, 0).
3546 3545 """
3547 3546 expected = 0
3548 3547 if len(self):
3549 3548 expected = max(0, self.end(len(self) - 1))
3550 3549
3551 3550 try:
3552 3551 with self._datafp() as f:
3553 3552 f.seek(0, io.SEEK_END)
3554 3553 actual = f.tell()
3555 3554 dd = actual - expected
3556 3555 except FileNotFoundError:
3557 3556 dd = 0
3558 3557
3559 3558 try:
3560 3559 f = self.opener(self._indexfile)
3561 3560 f.seek(0, io.SEEK_END)
3562 3561 actual = f.tell()
3563 3562 f.close()
3564 3563 s = self.index.entry_size
3565 3564 i = max(0, actual // s)
3566 3565 di = actual - (i * s)
3567 3566 if self._inline:
3568 3567 databytes = 0
3569 3568 for r in self:
3570 3569 databytes += max(0, self.length(r))
3571 3570 dd = 0
3572 3571 di = actual - len(self) * s - databytes
3573 3572 except FileNotFoundError:
3574 3573 di = 0
3575 3574
3576 3575 return (dd, di)
3577 3576
3578 3577 def files(self):
3579 3578 """return list of files that compose this revlog"""
3580 3579 res = [self._indexfile]
3581 3580 if self._docket_file is None:
3582 3581 if not self._inline:
3583 3582 res.append(self._datafile)
3584 3583 else:
3585 3584 res.append(self._docket_file)
3586 3585 res.extend(self._docket.old_index_filepaths(include_empty=False))
3587 3586 if self._docket.data_end:
3588 3587 res.append(self._datafile)
3589 3588 res.extend(self._docket.old_data_filepaths(include_empty=False))
3590 3589 if self._docket.sidedata_end:
3591 3590 res.append(self._sidedatafile)
3592 3591 res.extend(self._docket.old_sidedata_filepaths(include_empty=False))
3593 3592 return res
3594 3593
3595 3594 def emitrevisions(
3596 3595 self,
3597 3596 nodes,
3598 3597 nodesorder=None,
3599 3598 revisiondata=False,
3600 3599 assumehaveparentrevisions=False,
3601 3600 deltamode=repository.CG_DELTAMODE_STD,
3602 3601 sidedata_helpers=None,
3603 3602 debug_info=None,
3604 3603 ):
3605 3604 if nodesorder not in (b'nodes', b'storage', b'linear', None):
3606 3605 raise error.ProgrammingError(
3607 3606 b'unhandled value for nodesorder: %s' % nodesorder
3608 3607 )
3609 3608
3610 3609 if nodesorder is None and not self.delta_config.general_delta:
3611 3610 nodesorder = b'storage'
3612 3611
3613 3612 if (
3614 3613 not self._storedeltachains
3615 3614 and deltamode != repository.CG_DELTAMODE_PREV
3616 3615 ):
3617 3616 deltamode = repository.CG_DELTAMODE_FULL
3618 3617
3619 3618 return storageutil.emitrevisions(
3620 3619 self,
3621 3620 nodes,
3622 3621 nodesorder,
3623 3622 revlogrevisiondelta,
3624 3623 deltaparentfn=self.deltaparent,
3625 3624 candeltafn=self._candelta,
3626 3625 rawsizefn=self.rawsize,
3627 3626 revdifffn=self.revdiff,
3628 3627 flagsfn=self.flags,
3629 3628 deltamode=deltamode,
3630 3629 revisiondata=revisiondata,
3631 3630 assumehaveparentrevisions=assumehaveparentrevisions,
3632 3631 sidedata_helpers=sidedata_helpers,
3633 3632 debug_info=debug_info,
3634 3633 )
3635 3634
3636 3635 DELTAREUSEALWAYS = b'always'
3637 3636 DELTAREUSESAMEREVS = b'samerevs'
3638 3637 DELTAREUSENEVER = b'never'
3639 3638
3640 3639 DELTAREUSEFULLADD = b'fulladd'
3641 3640
3642 3641 DELTAREUSEALL = {b'always', b'samerevs', b'never', b'fulladd'}
3643 3642
3644 3643 def clone(
3645 3644 self,
3646 3645 tr,
3647 3646 destrevlog,
3648 3647 addrevisioncb=None,
3649 3648 deltareuse=DELTAREUSESAMEREVS,
3650 3649 forcedeltabothparents=None,
3651 3650 sidedata_helpers=None,
3652 3651 ):
3653 3652 """Copy this revlog to another, possibly with format changes.
3654 3653
3655 3654 The destination revlog will contain the same revisions and nodes.
3656 3655 However, it may not be bit-for-bit identical due to e.g. delta encoding
3657 3656 differences.
3658 3657
3659 3658 The ``deltareuse`` argument control how deltas from the existing revlog
3660 3659 are preserved in the destination revlog. The argument can have the
3661 3660 following values:
3662 3661
3663 3662 DELTAREUSEALWAYS
3664 3663 Deltas will always be reused (if possible), even if the destination
3665 3664 revlog would not select the same revisions for the delta. This is the
3666 3665 fastest mode of operation.
3667 3666 DELTAREUSESAMEREVS
3668 3667 Deltas will be reused if the destination revlog would pick the same
3669 3668 revisions for the delta. This mode strikes a balance between speed
3670 3669 and optimization.
3671 3670 DELTAREUSENEVER
3672 3671 Deltas will never be reused. This is the slowest mode of execution.
3673 3672 This mode can be used to recompute deltas (e.g. if the diff/delta
3674 3673 algorithm changes).
3675 3674 DELTAREUSEFULLADD
3676 3675 Revision will be re-added as if their were new content. This is
3677 3676 slower than DELTAREUSEALWAYS but allow more mechanism to kicks in.
3678 3677 eg: large file detection and handling.
3679 3678
3680 3679 Delta computation can be slow, so the choice of delta reuse policy can
3681 3680 significantly affect run time.
3682 3681
3683 3682 The default policy (``DELTAREUSESAMEREVS``) strikes a balance between
3684 3683 two extremes. Deltas will be reused if they are appropriate. But if the
3685 3684 delta could choose a better revision, it will do so. This means if you
3686 3685 are converting a non-generaldelta revlog to a generaldelta revlog,
3687 3686 deltas will be recomputed if the delta's parent isn't a parent of the
3688 3687 revision.
3689 3688
3690 3689 In addition to the delta policy, the ``forcedeltabothparents``
3691 3690 argument controls whether to force compute deltas against both parents
3692 3691 for merges. By default, the current default is used.
3693 3692
3694 3693 See `revlogutil.sidedata.get_sidedata_helpers` for the doc on
3695 3694 `sidedata_helpers`.
3696 3695 """
3697 3696 if deltareuse not in self.DELTAREUSEALL:
3698 3697 raise ValueError(
3699 3698 _(b'value for deltareuse invalid: %s') % deltareuse
3700 3699 )
3701 3700
3702 3701 if len(destrevlog):
3703 3702 raise ValueError(_(b'destination revlog is not empty'))
3704 3703
3705 3704 if getattr(self, 'filteredrevs', None):
3706 3705 raise ValueError(_(b'source revlog has filtered revisions'))
3707 3706 if getattr(destrevlog, 'filteredrevs', None):
3708 3707 raise ValueError(_(b'destination revlog has filtered revisions'))
3709 3708
3710 3709 # lazydelta and lazydeltabase controls whether to reuse a cached delta,
3711 3710 # if possible.
3712 3711 old_delta_config = destrevlog.delta_config
3713 3712 destrevlog.delta_config = destrevlog.delta_config.copy()
3714 3713
3715 3714 try:
3716 3715 if deltareuse == self.DELTAREUSEALWAYS:
3717 3716 destrevlog.delta_config.lazy_delta_base = True
3718 3717 destrevlog.delta_config.lazy_delta = True
3719 3718 elif deltareuse == self.DELTAREUSESAMEREVS:
3720 3719 destrevlog.delta_config.lazy_delta_base = False
3721 3720 destrevlog.delta_config.lazy_delta = True
3722 3721 elif deltareuse == self.DELTAREUSENEVER:
3723 3722 destrevlog.delta_config.lazy_delta_base = False
3724 3723 destrevlog.delta_config.lazy_delta = False
3725 3724
3726 3725 delta_both_parents = (
3727 3726 forcedeltabothparents or old_delta_config.delta_both_parents
3728 3727 )
3729 3728 destrevlog.delta_config.delta_both_parents = delta_both_parents
3730 3729
3731 3730 with self.reading(), destrevlog._writing(tr):
3732 3731 self._clone(
3733 3732 tr,
3734 3733 destrevlog,
3735 3734 addrevisioncb,
3736 3735 deltareuse,
3737 3736 forcedeltabothparents,
3738 3737 sidedata_helpers,
3739 3738 )
3740 3739
3741 3740 finally:
3742 3741 destrevlog.delta_config = old_delta_config
3743 3742
3744 3743 def _clone(
3745 3744 self,
3746 3745 tr,
3747 3746 destrevlog,
3748 3747 addrevisioncb,
3749 3748 deltareuse,
3750 3749 forcedeltabothparents,
3751 3750 sidedata_helpers,
3752 3751 ):
3753 3752 """perform the core duty of `revlog.clone` after parameter processing"""
3754 3753 write_debug = None
3755 3754 if self.delta_config.debug_delta:
3756 3755 write_debug = tr._report
3757 3756 deltacomputer = deltautil.deltacomputer(
3758 3757 destrevlog,
3759 3758 write_debug=write_debug,
3760 3759 )
3761 3760 index = self.index
3762 3761 for rev in self:
3763 3762 entry = index[rev]
3764 3763
3765 3764 # Some classes override linkrev to take filtered revs into
3766 3765 # account. Use raw entry from index.
3767 3766 flags = entry[0] & 0xFFFF
3768 3767 linkrev = entry[4]
3769 3768 p1 = index[entry[5]][7]
3770 3769 p2 = index[entry[6]][7]
3771 3770 node = entry[7]
3772 3771
3773 3772 # (Possibly) reuse the delta from the revlog if allowed and
3774 3773 # the revlog chunk is a delta.
3775 3774 cachedelta = None
3776 3775 rawtext = None
3777 3776 if deltareuse == self.DELTAREUSEFULLADD:
3778 3777 text = self._revisiondata(rev)
3779 3778 sidedata = self.sidedata(rev)
3780 3779
3781 3780 if sidedata_helpers is not None:
3782 3781 (sidedata, new_flags) = sidedatautil.run_sidedata_helpers(
3783 3782 self, sidedata_helpers, sidedata, rev
3784 3783 )
3785 3784 flags = flags | new_flags[0] & ~new_flags[1]
3786 3785
3787 3786 destrevlog.addrevision(
3788 3787 text,
3789 3788 tr,
3790 3789 linkrev,
3791 3790 p1,
3792 3791 p2,
3793 3792 cachedelta=cachedelta,
3794 3793 node=node,
3795 3794 flags=flags,
3796 3795 deltacomputer=deltacomputer,
3797 3796 sidedata=sidedata,
3798 3797 )
3799 3798 else:
3800 3799 if destrevlog.delta_config.lazy_delta:
3801 3800 dp = self.deltaparent(rev)
3802 3801 if dp != nullrev:
3803 3802 cachedelta = (dp, bytes(self._inner._chunk(rev)))
3804 3803
3805 3804 sidedata = None
3806 3805 if not cachedelta:
3807 3806 try:
3808 3807 rawtext = self._revisiondata(rev)
3809 3808 except error.CensoredNodeError as censored:
3810 3809 assert flags & REVIDX_ISCENSORED
3811 3810 rawtext = censored.tombstone
3812 3811 sidedata = self.sidedata(rev)
3813 3812 if sidedata is None:
3814 3813 sidedata = self.sidedata(rev)
3815 3814
3816 3815 if sidedata_helpers is not None:
3817 3816 (sidedata, new_flags) = sidedatautil.run_sidedata_helpers(
3818 3817 self, sidedata_helpers, sidedata, rev
3819 3818 )
3820 3819 flags = flags | new_flags[0] & ~new_flags[1]
3821 3820
3822 3821 destrevlog._addrevision(
3823 3822 node,
3824 3823 rawtext,
3825 3824 tr,
3826 3825 linkrev,
3827 3826 p1,
3828 3827 p2,
3829 3828 flags,
3830 3829 cachedelta,
3831 3830 deltacomputer=deltacomputer,
3832 3831 sidedata=sidedata,
3833 3832 )
3834 3833
3835 3834 if addrevisioncb:
3836 3835 addrevisioncb(self, rev, node)
3837 3836
3838 3837 def censorrevision(self, tr, censor_nodes, tombstone=b''):
3839 3838 if self._format_version == REVLOGV0:
3840 3839 raise error.RevlogError(
3841 3840 _(b'cannot censor with version %d revlogs')
3842 3841 % self._format_version
3843 3842 )
3844 3843 elif self._format_version == REVLOGV1:
3845 3844 rewrite.v1_censor(self, tr, censor_nodes, tombstone)
3846 3845 else:
3847 3846 rewrite.v2_censor(self, tr, censor_nodes, tombstone)
3848 3847
3849 3848 def verifyintegrity(self, state):
3850 3849 """Verifies the integrity of the revlog.
3851 3850
3852 3851 Yields ``revlogproblem`` instances describing problems that are
3853 3852 found.
3854 3853 """
3855 3854 dd, di = self.checksize()
3856 3855 if dd:
3857 3856 yield revlogproblem(error=_(b'data length off by %d bytes') % dd)
3858 3857 if di:
3859 3858 yield revlogproblem(error=_(b'index contains %d extra bytes') % di)
3860 3859
3861 3860 version = self._format_version
3862 3861
3863 3862 # The verifier tells us what version revlog we should be.
3864 3863 if version != state[b'expectedversion']:
3865 3864 yield revlogproblem(
3866 3865 warning=_(b"warning: '%s' uses revlog format %d; expected %d")
3867 3866 % (self.display_id, version, state[b'expectedversion'])
3868 3867 )
3869 3868
3870 3869 state[b'skipread'] = set()
3871 3870 state[b'safe_renamed'] = set()
3872 3871
3873 3872 for rev in self:
3874 3873 node = self.node(rev)
3875 3874
3876 3875 # Verify contents. 4 cases to care about:
3877 3876 #
3878 3877 # common: the most common case
3879 3878 # rename: with a rename
3880 3879 # meta: file content starts with b'\1\n', the metadata
3881 3880 # header defined in filelog.py, but without a rename
3882 3881 # ext: content stored externally
3883 3882 #
3884 3883 # More formally, their differences are shown below:
3885 3884 #
3886 3885 # | common | rename | meta | ext
3887 3886 # -------------------------------------------------------
3888 3887 # flags() | 0 | 0 | 0 | not 0
3889 3888 # renamed() | False | True | False | ?
3890 3889 # rawtext[0:2]=='\1\n'| False | True | True | ?
3891 3890 #
3892 3891 # "rawtext" means the raw text stored in revlog data, which
3893 3892 # could be retrieved by "rawdata(rev)". "text"
3894 3893 # mentioned below is "revision(rev)".
3895 3894 #
3896 3895 # There are 3 different lengths stored physically:
3897 3896 # 1. L1: rawsize, stored in revlog index
3898 3897 # 2. L2: len(rawtext), stored in revlog data
3899 3898 # 3. L3: len(text), stored in revlog data if flags==0, or
3900 3899 # possibly somewhere else if flags!=0
3901 3900 #
3902 3901 # L1 should be equal to L2. L3 could be different from them.
3903 3902 # "text" may or may not affect commit hash depending on flag
3904 3903 # processors (see flagutil.addflagprocessor).
3905 3904 #
3906 3905 # | common | rename | meta | ext
3907 3906 # -------------------------------------------------
3908 3907 # rawsize() | L1 | L1 | L1 | L1
3909 3908 # size() | L1 | L2-LM | L1(*) | L1 (?)
3910 3909 # len(rawtext) | L2 | L2 | L2 | L2
3911 3910 # len(text) | L2 | L2 | L2 | L3
3912 3911 # len(read()) | L2 | L2-LM | L2-LM | L3 (?)
3913 3912 #
3914 3913 # LM: length of metadata, depending on rawtext
3915 3914 # (*): not ideal, see comment in filelog.size
3916 3915 # (?): could be "- len(meta)" if the resolved content has
3917 3916 # rename metadata
3918 3917 #
3919 3918 # Checks needed to be done:
3920 3919 # 1. length check: L1 == L2, in all cases.
3921 3920 # 2. hash check: depending on flag processor, we may need to
3922 3921 # use either "text" (external), or "rawtext" (in revlog).
3923 3922
3924 3923 try:
3925 3924 skipflags = state.get(b'skipflags', 0)
3926 3925 if skipflags:
3927 3926 skipflags &= self.flags(rev)
3928 3927
3929 3928 _verify_revision(self, skipflags, state, node)
3930 3929
3931 3930 l1 = self.rawsize(rev)
3932 3931 l2 = len(self.rawdata(node))
3933 3932
3934 3933 if l1 != l2:
3935 3934 yield revlogproblem(
3936 3935 error=_(b'unpacked size is %d, %d expected') % (l2, l1),
3937 3936 node=node,
3938 3937 )
3939 3938
3940 3939 except error.CensoredNodeError:
3941 3940 if state[b'erroroncensored']:
3942 3941 yield revlogproblem(
3943 3942 error=_(b'censored file data'), node=node
3944 3943 )
3945 3944 state[b'skipread'].add(node)
3946 3945 except Exception as e:
3947 3946 yield revlogproblem(
3948 3947 error=_(b'unpacking %s: %s')
3949 3948 % (short(node), stringutil.forcebytestr(e)),
3950 3949 node=node,
3951 3950 )
3952 3951 state[b'skipread'].add(node)
3953 3952
3954 3953 def storageinfo(
3955 3954 self,
3956 3955 exclusivefiles=False,
3957 3956 sharedfiles=False,
3958 3957 revisionscount=False,
3959 3958 trackedsize=False,
3960 3959 storedsize=False,
3961 3960 ):
3962 3961 d = {}
3963 3962
3964 3963 if exclusivefiles:
3965 3964 d[b'exclusivefiles'] = [(self.opener, self._indexfile)]
3966 3965 if not self._inline:
3967 3966 d[b'exclusivefiles'].append((self.opener, self._datafile))
3968 3967
3969 3968 if sharedfiles:
3970 3969 d[b'sharedfiles'] = []
3971 3970
3972 3971 if revisionscount:
3973 3972 d[b'revisionscount'] = len(self)
3974 3973
3975 3974 if trackedsize:
3976 3975 d[b'trackedsize'] = sum(map(self.rawsize, iter(self)))
3977 3976
3978 3977 if storedsize:
3979 3978 d[b'storedsize'] = sum(
3980 3979 self.opener.stat(path).st_size for path in self.files()
3981 3980 )
3982 3981
3983 3982 return d
3984 3983
3985 3984 def rewrite_sidedata(self, transaction, helpers, startrev, endrev):
3986 3985 if not self.feature_config.has_side_data:
3987 3986 return
3988 3987 # revlog formats with sidedata support does not support inline
3989 3988 assert not self._inline
3990 3989 if not helpers[1] and not helpers[2]:
3991 3990 # Nothing to generate or remove
3992 3991 return
3993 3992
3994 3993 new_entries = []
3995 3994 # append the new sidedata
3996 3995 with self._writing(transaction):
3997 3996 ifh, dfh, sdfh = self._inner._writinghandles
3998 3997 dfh.seek(self._docket.sidedata_end, os.SEEK_SET)
3999 3998
4000 3999 current_offset = sdfh.tell()
4001 4000 for rev in range(startrev, endrev + 1):
4002 4001 entry = self.index[rev]
4003 4002 new_sidedata, flags = sidedatautil.run_sidedata_helpers(
4004 4003 store=self,
4005 4004 sidedata_helpers=helpers,
4006 4005 sidedata={},
4007 4006 rev=rev,
4008 4007 )
4009 4008
4010 4009 serialized_sidedata = sidedatautil.serialize_sidedata(
4011 4010 new_sidedata
4012 4011 )
4013 4012
4014 4013 sidedata_compression_mode = COMP_MODE_INLINE
4015 4014 if serialized_sidedata and self.feature_config.has_side_data:
4016 4015 sidedata_compression_mode = COMP_MODE_PLAIN
4017 4016 h, comp_sidedata = self._inner.compress(serialized_sidedata)
4018 4017 if (
4019 4018 h != b'u'
4020 4019 and comp_sidedata[0] != b'\0'
4021 4020 and len(comp_sidedata) < len(serialized_sidedata)
4022 4021 ):
4023 4022 assert not h
4024 4023 if (
4025 4024 comp_sidedata[0]
4026 4025 == self._docket.default_compression_header
4027 4026 ):
4028 4027 sidedata_compression_mode = COMP_MODE_DEFAULT
4029 4028 serialized_sidedata = comp_sidedata
4030 4029 else:
4031 4030 sidedata_compression_mode = COMP_MODE_INLINE
4032 4031 serialized_sidedata = comp_sidedata
4033 4032 if entry[8] != 0 or entry[9] != 0:
4034 4033 # rewriting entries that already have sidedata is not
4035 4034 # supported yet, because it introduces garbage data in the
4036 4035 # revlog.
4037 4036 msg = b"rewriting existing sidedata is not supported yet"
4038 4037 raise error.Abort(msg)
4039 4038
4040 4039 # Apply (potential) flags to add and to remove after running
4041 4040 # the sidedata helpers
4042 4041 new_offset_flags = entry[0] | flags[0] & ~flags[1]
4043 4042 entry_update = (
4044 4043 current_offset,
4045 4044 len(serialized_sidedata),
4046 4045 new_offset_flags,
4047 4046 sidedata_compression_mode,
4048 4047 )
4049 4048
4050 4049 # the sidedata computation might have move the file cursors around
4051 4050 sdfh.seek(current_offset, os.SEEK_SET)
4052 4051 sdfh.write(serialized_sidedata)
4053 4052 new_entries.append(entry_update)
4054 4053 current_offset += len(serialized_sidedata)
4055 4054 self._docket.sidedata_end = sdfh.tell()
4056 4055
4057 4056 # rewrite the new index entries
4058 4057 ifh.seek(startrev * self.index.entry_size)
4059 4058 for i, e in enumerate(new_entries):
4060 4059 rev = startrev + i
4061 4060 self.index.replace_sidedata_info(rev, *e)
4062 4061 packed = self.index.entry_binary(rev)
4063 4062 if rev == 0 and self._docket is None:
4064 4063 header = self._format_flags | self._format_version
4065 4064 header = self.index.pack_header(header)
4066 4065 packed = header + packed
4067 4066 ifh.write(packed)
General Comments 0
You need to be logged in to leave comments. Login now