Debian Codegraph @

hgext/remotefilelog/historypack.py

raw
1 from __future__ import annotations
2
3 import struct
4
5 from mercurial.node import (
6 hex,
7 sha1nodeconstants,
8 )
9 from mercurial import (
10 util,
11 )
12 from mercurial.utils import hashutil
13 from . import (
14 basepack,
15 constants,
16 shallowutil,
17 )
18
19 # (filename hash, offset, size)
20 INDEXFORMAT2 = b'!20sQQII'
21 INDEXENTRYLENGTH2 = struct.calcsize(INDEXFORMAT2)
22 NODELENGTH = 20
23
24 NODEINDEXFORMAT = b'!20sQ'
25 NODEINDEXENTRYLENGTH = struct.calcsize(NODEINDEXFORMAT)
26
27 # (node, p1, p2, linknode)
28 PACKFORMAT = b"!20s20s20s20sH"
29 PACKENTRYLENGTH = 82
30
31 ENTRYCOUNTSIZE = 4
32
33 INDEXSUFFIX = b'.histidx'
34 PACKSUFFIX = b'.histpack'
35
36 ANC_NODE = 0
37 ANC_P1NODE = 1
38 ANC_P2NODE = 2
39 ANC_LINKNODE = 3
40 ANC_COPYFROM = 4
41
42
43 class historypackstore(basepack.basepackstore):
44 INDEXSUFFIX = INDEXSUFFIX
45 PACKSUFFIX = PACKSUFFIX
46
47 def getpack(self, path):
48 return historypack(path)
49
50 def getancestors(self, name, node, known=None):
51 for pack in self.packs:
52 try:
53 return pack.getancestors(name, node, known=known)
54 except KeyError:
55 pass
56
57 for pack in self.refresh():
58 try:
59 return pack.getancestors(name, node, known=known)
60 except KeyError:
61 pass
62
63 raise KeyError((name, node))
64
65 def getnodeinfo(self, name, node):
66 for pack in self.packs:
67 try:
68 return pack.getnodeinfo(name, node)
69 except KeyError:
70 pass
71
72 for pack in self.refresh():
73 try:
74 return pack.getnodeinfo(name, node)
75 except KeyError:
76 pass
77
78 raise KeyError((name, node))
79
80 def add(self, filename, node, p1, p2, linknode, copyfrom):
81 raise RuntimeError(
82 b"cannot add to historypackstore (%s:%s)" % (filename, hex(node))
83 )
84
85
86 class historypack(basepack.basepack):
87 INDEXSUFFIX = INDEXSUFFIX
88 PACKSUFFIX = PACKSUFFIX
89
90 SUPPORTED_VERSIONS = [2]
91
92 def __init__(self, path):
93 super().__init__(path)
94 self.INDEXFORMAT = INDEXFORMAT2
95 self.INDEXENTRYLENGTH = INDEXENTRYLENGTH2
96
97 def getmissing(self, keys):
98 missing = []
99 for name, node in keys:
100 try:
101 self._findnode(name, node)
102 except KeyError:
103 missing.append((name, node))
104
105 return missing
106
107 def getancestors(self, name, node, known=None):
108 """Returns as many ancestors as we're aware of.
109
110 return value: {
111 node: (p1, p2, linknode, copyfrom),
112 ...
113 }
114 """
115 if known and node in known:
116 return []
117
118 ancestors = self._getancestors(name, node, known=known)
119 results = {}
120 for ancnode, p1, p2, linknode, copyfrom in ancestors:
121 results[ancnode] = (p1, p2, linknode, copyfrom)
122
123 if not results:
124 raise KeyError((name, node))
125 return results
126
127 def getnodeinfo(self, name, node):
128 # Drop the node from the tuple before returning, since the result should
129 # just be (p1, p2, linknode, copyfrom)
130 return self._findnode(name, node)[1:]
131
132 def _getancestors(self, name, node, known=None):
133 if known is None:
134 known = set()
135 section = self._findsection(name)
136 filename, offset, size, nodeindexoffset, nodeindexsize = section
137 pending = {node}
138 o = 0
139 while o < size:
140 if not pending:
141 break
142 entry, copyfrom = self._readentry(offset + o)
143 o += PACKENTRYLENGTH
144 if copyfrom:
145 o += len(copyfrom)
146
147 ancnode = entry[ANC_NODE]
148 if ancnode in pending:
149 pending.remove(ancnode)
150 p1node = entry[ANC_P1NODE]
151 p2node = entry[ANC_P2NODE]
152 if p1node != sha1nodeconstants.nullid and p1node not in known:
153 pending.add(p1node)
154 if p2node != sha1nodeconstants.nullid and p2node not in known:
155 pending.add(p2node)
156
157 yield (ancnode, p1node, p2node, entry[ANC_LINKNODE], copyfrom)
158
159 def _readentry(self, offset):
160 data = self._data
161 entry = struct.unpack(
162 PACKFORMAT, data[offset : offset + PACKENTRYLENGTH]
163 )
164 copyfrom = None
165 copyfromlen = entry[ANC_COPYFROM]
166 if copyfromlen != 0:
167 offset += PACKENTRYLENGTH
168 copyfrom = data[offset : offset + copyfromlen]
169 return entry, copyfrom
170
171 def add(self, filename, node, p1, p2, linknode, copyfrom):
172 raise RuntimeError(
173 b"cannot add to historypack (%s:%s)" % (filename, hex(node))
174 )
175
176 def _findnode(self, name, node):
177 if self.VERSION == 0:
178 ancestors = self._getancestors(name, node)
179 for ancnode, p1node, p2node, linknode, copyfrom in ancestors:
180 if ancnode == node:
181 return (ancnode, p1node, p2node, linknode, copyfrom)
182 else:
183 section = self._findsection(name)
184 nodeindexoffset, nodeindexsize = section[3:]
185 entry = self._bisect(
186 node,
187 nodeindexoffset,
188 nodeindexoffset + nodeindexsize,
189 NODEINDEXENTRYLENGTH,
190 )
191 if entry is not None:
192 node, offset = struct.unpack(NODEINDEXFORMAT, entry)
193 entry, copyfrom = self._readentry(offset)
194 # Drop the copyfromlen from the end of entry, and replace it
195 # with the copyfrom string.
196 return entry[:4] + (copyfrom,)
197
198 raise KeyError(b"unable to find history for %s:%s" % (name, hex(node)))
199
200 def _findsection(self, name):
201 params = self.params
202 namehash = hashutil.sha1(name).digest()
203 fanoutkey = struct.unpack(
204 params.fanoutstruct, namehash[: params.fanoutprefix]
205 )[0]
206 fanout = self._fanouttable
207
208 start = fanout[fanoutkey] + params.indexstart
209 indexend = self._indexend
210
211 for i in range(fanoutkey + 1, params.fanoutcount):
212 end = fanout[i] + params.indexstart
213 if end != start:
214 break
215 else:
216 end = indexend
217
218 entry = self._bisect(namehash, start, end, self.INDEXENTRYLENGTH)
219 if not entry:
220 raise KeyError(name)
221
222 rawentry = struct.unpack(self.INDEXFORMAT, entry)
223 x, offset, size, nodeindexoffset, nodeindexsize = rawentry
224 rawnamelen = self._index[
225 nodeindexoffset : nodeindexoffset + constants.FILENAMESIZE
226 ]
227 actualnamelen = struct.unpack(b'!H', rawnamelen)[0]
228 nodeindexoffset += constants.FILENAMESIZE
229 actualname = self._index[
230 nodeindexoffset : nodeindexoffset + actualnamelen
231 ]
232 if actualname != name:
233 raise KeyError(
234 b"found file name %s when looking for %s" % (actualname, name)
235 )
236 nodeindexoffset += actualnamelen
237
238 filenamelength = struct.unpack(
239 b'!H', self._data[offset : offset + constants.FILENAMESIZE]
240 )[0]
241 offset += constants.FILENAMESIZE
242
243 actualname = self._data[offset : offset + filenamelength]
244 offset += filenamelength
245
246 if name != actualname:
247 raise KeyError(
248 b"found file name %s when looking for %s" % (actualname, name)
249 )
250
251 # Skip entry list size
252 offset += ENTRYCOUNTSIZE
253
254 nodelistoffset = offset
255 nodelistsize = (
256 size - constants.FILENAMESIZE - filenamelength - ENTRYCOUNTSIZE
257 )
258 return (
259 name,
260 nodelistoffset,
261 nodelistsize,
262 nodeindexoffset,
263 nodeindexsize,
264 )
265
266 def _bisect(self, node, start, end, entrylen):
267 # Bisect between start and end to find node
268 origstart = start
269 startnode = self._index[start : start + NODELENGTH]
270 endnode = self._index[end : end + NODELENGTH]
271
272 if startnode == node:
273 return self._index[start : start + entrylen]
274 elif endnode == node:
275 return self._index[end : end + entrylen]
276 else:
277 while start < end - entrylen:
278 mid = start + (end - start) // 2
279 mid = mid - ((mid - origstart) % entrylen)
280 midnode = self._index[mid : mid + NODELENGTH]
281 if midnode == node:
282 return self._index[mid : mid + entrylen]
283 if node > midnode:
284 start = mid
285 elif node < midnode:
286 end = mid
287 return None
288
289 def markledger(self, ledger, options=None):
290 for filename, node in self:
291 ledger.markhistoryentry(self, filename, node)
292
293 def cleanup(self, ledger):
294 entries = ledger.sources.get(self, [])
295 allkeys = set(self)
296 repackedkeys = {
297 (e.filename, e.node) for e in entries if e.historyrepacked
298 }
299
300 if len(allkeys - repackedkeys) == 0:
301 if self.path not in ledger.created:
302 util.unlinkpath(self.indexpath, ignoremissing=True)
303 util.unlinkpath(self.packpath, ignoremissing=True)
304
305 def __iter__(self):
306 for f, n, x, x, x, x in self.iterentries():
307 yield f, n
308
309 def iterentries(self):
310 # Start at 1 to skip the header
311 offset = 1
312 while offset < self.datasize:
313 data = self._data
314 # <2 byte len> + <filename>
315 filenamelen = struct.unpack(
316 b'!H', data[offset : offset + constants.FILENAMESIZE]
317 )[0]
318 offset += constants.FILENAMESIZE
319 filename = data[offset : offset + filenamelen]
320 offset += filenamelen
321
322 revcount = struct.unpack(
323 b'!I', data[offset : offset + ENTRYCOUNTSIZE]
324 )[0]
325 offset += ENTRYCOUNTSIZE
326
327 for i in range(revcount):
328 entry = struct.unpack(
329 PACKFORMAT, data[offset : offset + PACKENTRYLENGTH]
330 )
331 offset += PACKENTRYLENGTH
332
333 copyfrom = data[offset : offset + entry[ANC_COPYFROM]]
334 offset += entry[ANC_COPYFROM]
335
336 yield (
337 filename,
338 entry[ANC_NODE],
339 entry[ANC_P1NODE],
340 entry[ANC_P2NODE],
341 entry[ANC_LINKNODE],
342 copyfrom,
343 )
344
345 self._pagedin += PACKENTRYLENGTH
346
347 # If we've read a lot of data from the mmap, free some memory.
348 self.freememory()
349
350
351 class mutablehistorypack(basepack.mutablebasepack):
352 """A class for constructing and serializing a histpack file and index.
353
354 A history pack is a pair of files that contain the revision history for
355 various file revisions in Mercurial. It contains only revision history (like
356 parent pointers and linknodes), not any revision content information.
357
358 It consists of two files, with the following format:
359
360 .histpack
361 The pack itself is a series of file revisions with some basic header
362 information on each.
363
364 datapack = <version: 1 byte>
365 [<filesection>,...]
366 filesection = <filename len: 2 byte unsigned int>
367 <filename>
368 <revision count: 4 byte unsigned int>
369 [<revision>,...]
370 revision = <node: 20 byte>
371 <p1node: 20 byte>
372 <p2node: 20 byte>
373 <linknode: 20 byte>
374 <copyfromlen: 2 byte>
375 <copyfrom>
376
377 The revisions within each filesection are stored in topological order
378 (newest first). If a given entry has a parent from another file (a copy)
379 then p1node is the node from the other file, and copyfrom is the
380 filepath of the other file.
381
382 .histidx
383 The index file provides a mapping from filename to the file section in
384 the histpack. In V1 it also contains sub-indexes for specific nodes
385 within each file. It consists of three parts, the fanout, the file index
386 and the node indexes.
387
388 The file index is a list of index entries, sorted by filename hash (one
389 per file section in the pack). Each entry has:
390
391 - node (The 20 byte hash of the filename)
392 - pack entry offset (The location of this file section in the histpack)
393 - pack content size (The on-disk length of this file section's pack
394 data)
395 - node index offset (The location of the file's node index in the index
396 file) [1]
397 - node index size (the on-disk length of this file's node index) [1]
398
399 The fanout is a quick lookup table to reduce the number of steps for
400 bisecting the index. It is a series of 4 byte pointers to positions
401 within the index. It has 2^16 entries, which corresponds to hash
402 prefixes [00, 01, 02,..., FD, FE, FF]. Example: the pointer in slot 4F
403 points to the index position of the first revision whose node starts
404 with 4F. This saves log(2^16) bisect steps.
405
406 dataidx = <fanouttable>
407 <file count: 8 byte unsigned> [1]
408 <fileindex>
409 <node count: 8 byte unsigned> [1]
410 [<nodeindex>,...] [1]
411 fanouttable = [<index offset: 4 byte unsigned int>,...] (2^16 entries)
412
413 fileindex = [<file index entry>,...]
414 fileindexentry = <node: 20 byte>
415 <pack file section offset: 8 byte unsigned int>
416 <pack file section size: 8 byte unsigned int>
417 <node index offset: 4 byte unsigned int> [1]
418 <node index size: 4 byte unsigned int> [1]
419 nodeindex = <filename>[<node index entry>,...] [1]
420 filename = <filename len : 2 byte unsigned int><filename value> [1]
421 nodeindexentry = <node: 20 byte> [1]
422 <pack file node offset: 8 byte unsigned int> [1]
423
424 [1]: new in version 1.
425 """
426
427 INDEXSUFFIX = INDEXSUFFIX
428 PACKSUFFIX = PACKSUFFIX
429
430 SUPPORTED_VERSIONS = [2]
431
432 def __init__(self, ui, packpath, version=2):
433 super().__init__(ui, packpath, version=version)
434 self.files = {}
435 self.entrylocations = {}
436 self.fileentries = {}
437
438 self.INDEXFORMAT = INDEXFORMAT2
439 self.INDEXENTRYLENGTH = INDEXENTRYLENGTH2
440
441 self.NODEINDEXFORMAT = NODEINDEXFORMAT
442 self.NODEINDEXENTRYLENGTH = NODEINDEXENTRYLENGTH
443
444 def add(self, filename, node, p1, p2, linknode, copyfrom):
445 copyfrom = copyfrom or b''
446 copyfromlen = struct.pack(b'!H', len(copyfrom))
447 self.fileentries.setdefault(filename, []).append(
448 (node, p1, p2, linknode, copyfromlen, copyfrom)
449 )
450
451 def _write(self):
452 for filename in sorted(self.fileentries):
453 entries = self.fileentries[filename]
454 sectionstart = self.packfp.tell()
455
456 # Write the file section content
457 entrymap = {e[0]: e for e in entries}
458
459 def parentfunc(node):
460 x, p1, p2, x, x, x = entrymap[node]
461 parents = []
462 if p1 != sha1nodeconstants.nullid:
463 parents.append(p1)
464 if p2 != sha1nodeconstants.nullid:
465 parents.append(p2)
466 return parents
467
468 sortednodes = list(
469 reversed(
470 shallowutil.sortnodes((e[0] for e in entries), parentfunc)
471 )
472 )
473
474 # Write the file section header
475 self.writeraw(
476 b"%s%s%s"
477 % (
478 struct.pack(b'!H', len(filename)),
479 filename,
480 struct.pack(b'!I', len(sortednodes)),
481 )
482 )
483
484 sectionlen = constants.FILENAMESIZE + len(filename) + 4
485
486 rawstrings = []
487
488 # Record the node locations for the index
489 locations = self.entrylocations.setdefault(filename, {})
490 offset = sectionstart + sectionlen
491 for node in sortednodes:
492 locations[node] = offset
493 raw = b'%s%s%s%s%s%s' % entrymap[node]
494 rawstrings.append(raw)
495 offset += len(raw)
496
497 rawdata = b''.join(rawstrings)
498 sectionlen += len(rawdata)
499
500 self.writeraw(rawdata)
501
502 # Record metadata for the index
503 self.files[filename] = (sectionstart, sectionlen)
504 node = hashutil.sha1(filename).digest()
505 self.entries[node] = node
506
507 def close(self, ledger=None):
508 if self._closed:
509 return
510
511 self._write()
512
513 return super().close(ledger=ledger)
514
515 def createindex(self, nodelocations, indexoffset):
516 fileindexformat = self.INDEXFORMAT
517 fileindexlength = self.INDEXENTRYLENGTH
518 nodeindexformat = self.NODEINDEXFORMAT
519 nodeindexlength = self.NODEINDEXENTRYLENGTH
520
521 files = (
522 (hashutil.sha1(filename).digest(), filename, offset, size)
523 for filename, (offset, size) in self.files.items()
524 )
525 files = sorted(files)
526
527 # node index is after file index size, file index, and node index size
528 indexlensize = struct.calcsize(b'!Q')
529 nodeindexoffset = (
530 indexoffset
531 + indexlensize
532 + (len(files) * fileindexlength)
533 + indexlensize
534 )
535
536 fileindexentries = []
537 nodeindexentries = []
538 nodecount = 0
539 for namehash, filename, offset, size in files:
540 # File section index
541 nodelocations = self.entrylocations[filename]
542
543 nodeindexsize = len(nodelocations) * nodeindexlength
544
545 rawentry = struct.pack(
546 fileindexformat,
547 namehash,
548 offset,
549 size,
550 nodeindexoffset,
551 nodeindexsize,
552 )
553 # Node index
554 nodeindexentries.append(
555 struct.pack(constants.FILENAMESTRUCT, len(filename)) + filename
556 )
557 nodeindexoffset += constants.FILENAMESIZE + len(filename)
558
559 for node, location in sorted(nodelocations.items()):
560 nodeindexentries.append(
561 struct.pack(nodeindexformat, node, location)
562 )
563 nodecount += 1
564
565 nodeindexoffset += len(nodelocations) * nodeindexlength
566
567 fileindexentries.append(rawentry)
568
569 nodecountraw = struct.pack(b'!Q', nodecount)
570 return (
571 b''.join(fileindexentries)
572 + nodecountraw
573 + b''.join(nodeindexentries)
574 )