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