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