Debian Codegraph @

hgext/fastannotate/revmap.py

raw
1 # Copyright 2016-present Facebook. All Rights Reserved.
2 #
3 # revmap: trivial hg hash - linelog rev bidirectional map
4 #
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.
7
8 from __future__ import annotations
9
10 import bisect
11 import io
12 import os
13 import struct
14
15 from mercurial.node import hex
16 from mercurial import (
17 error as hgerror,
18 )
19 from . import error
20
21 # the revmap file format is straightforward:
22 #
23 # 8 bytes: header
24 # 1 byte : flag for linelog revision 1
25 # ? bytes: (optional) '\0'-terminated path string
26 # only exists if (flag & renameflag) != 0
27 # 20 bytes: hg hash for linelog revision 1
28 # 1 byte : flag for linelog revision 2
29 # ? bytes: (optional) '\0'-terminated path string
30 # 20 bytes: hg hash for linelog revision 2
31 # ....
32 #
33 # the implementation is kinda stupid: __init__ loads the whole revmap.
34 # no laziness. benchmark shows loading 10000 revisions is about 0.015
35 # seconds, which looks enough for our use-case. if this implementation
36 # becomes a bottleneck, we can change it to lazily read the file
37 # from the end.
38
39 # whether the changeset is in the side branch. i.e. not in the linear main
40 # branch but only got referenced by lines in merge changesets.
41 sidebranchflag = 1
42
43 # whether the changeset changes the file path (ie. is a rename)
44 renameflag = 2
45
46 # len(mercurial.node.nullid)
47 _hshlen = 20
48
49
50 class revmap:
51 """trivial hg bin hash - linelog rev bidirectional map
52
53 also stores a flag (uint8) for each revision, and track renames.
54 """
55
56 HEADER = b'REVMAP1\0'
57
58 def __init__(self, path=None):
59 """create or load the revmap, optionally associate to a file
60
61 if path is None, the revmap is entirely in-memory. the caller is
62 responsible for locking. concurrent writes to a same file is unsafe.
63 the caller needs to make sure one file is associated to at most one
64 revmap object at a time."""
65 self.path = path
66 self._rev2hsh = [None]
67 self._rev2flag = [None]
68 self._hsh2rev = {}
69 # since rename does not happen frequently, do not store path for every
70 # revision. self._renamerevs can be used for bisecting.
71 self._renamerevs = [0]
72 self._renamepaths = [b'']
73 self._lastmaxrev = -1
74 if path:
75 if os.path.exists(path):
76 self._load()
77 else:
78 # write the header so "append" can do incremental updates
79 self.flush()
80
81 def copyfrom(self, rhs):
82 """copy the map data from another revmap. do not affect self.path"""
83 self._rev2hsh = rhs._rev2hsh[:]
84 self._rev2flag = rhs._rev2flag[:]
85 self._hsh2rev = rhs._hsh2rev.copy()
86 self._renamerevs = rhs._renamerevs[:]
87 self._renamepaths = rhs._renamepaths[:]
88 self._lastmaxrev = -1
89
90 @property
91 def maxrev(self):
92 """return max linelog revision number"""
93 return len(self._rev2hsh) - 1
94
95 def append(self, hsh, sidebranch=False, path=None, flush=False):
96 """add a binary hg hash and return the mapped linelog revision.
97 if flush is True, incrementally update the file.
98 """
99 if hsh in self._hsh2rev:
100 raise error.CorruptedFileError(
101 b'%r is in revmap already' % hex(hsh)
102 )
103 if len(hsh) != _hshlen:
104 raise hgerror.ProgrammingError(
105 b'hsh must be %d-char long' % _hshlen
106 )
107 idx = len(self._rev2hsh)
108 flag = 0
109 if sidebranch:
110 flag |= sidebranchflag
111 if path is not None and path != self._renamepaths[-1]:
112 flag |= renameflag
113 self._renamerevs.append(idx)
114 self._renamepaths.append(path)
115 self._rev2hsh.append(hsh)
116 self._rev2flag.append(flag)
117 self._hsh2rev[hsh] = idx
118 if flush:
119 self.flush()
120 return idx
121
122 def rev2hsh(self, rev):
123 """convert linelog revision to hg hash. return None if not found."""
124 if rev > self.maxrev or rev < 0:
125 return None
126 return self._rev2hsh[rev]
127
128 def rev2flag(self, rev):
129 """get the flag (uint8) for a given linelog revision.
130 return None if revision does not exist.
131 """
132 if rev > self.maxrev or rev < 0:
133 return None
134 return self._rev2flag[rev]
135
136 def rev2path(self, rev):
137 """get the path for a given linelog revision.
138 return None if revision does not exist.
139 """
140 if rev > self.maxrev or rev < 0:
141 return None
142 idx = bisect.bisect_right(self._renamerevs, rev) - 1
143 return self._renamepaths[idx]
144
145 def hsh2rev(self, hsh):
146 """convert hg hash to linelog revision. return None if not found."""
147 return self._hsh2rev.get(hsh)
148
149 def clear(self, flush=False):
150 """make the map empty. if flush is True, write to disk"""
151 # rev 0 is reserved, real rev starts from 1
152 self._rev2hsh = [None]
153 self._rev2flag = [None]
154 self._hsh2rev = {}
155 self._rev2path = [b'']
156 self._lastmaxrev = -1
157 if flush:
158 self.flush()
159
160 def flush(self):
161 """write the state down to the file"""
162 if not self.path:
163 return
164 if self._lastmaxrev == -1: # write the entire file
165 with open(self.path, 'wb') as f:
166 f.write(self.HEADER)
167 for i in range(1, len(self._rev2hsh)):
168 self._writerev(i, f)
169 else: # append incrementally
170 with open(self.path, 'ab') as f:
171 for i in range(self._lastmaxrev + 1, len(self._rev2hsh)):
172 self._writerev(i, f)
173 self._lastmaxrev = self.maxrev
174
175 def _load(self):
176 """load state from file"""
177 if not self.path:
178 return
179 # use local variables in a loop. CPython uses LOAD_FAST for them,
180 # which is faster than both LOAD_CONST and LOAD_GLOBAL.
181 flaglen = 1
182 hshlen = _hshlen
183 with open(self.path, 'rb') as f:
184 if f.read(len(self.HEADER)) != self.HEADER:
185 raise error.CorruptedFileError()
186 self.clear(flush=False)
187 while True:
188 buf = f.read(flaglen)
189 if not buf:
190 break
191 flag = ord(buf)
192 rev = len(self._rev2hsh)
193 if flag & renameflag:
194 path = self._readcstr(f)
195 self._renamerevs.append(rev)
196 self._renamepaths.append(path)
197 hsh = f.read(hshlen)
198 if len(hsh) != hshlen:
199 raise error.CorruptedFileError()
200 self._hsh2rev[hsh] = rev
201 self._rev2flag.append(flag)
202 self._rev2hsh.append(hsh)
203 self._lastmaxrev = self.maxrev
204
205 def _writerev(self, rev, f):
206 """append a revision data to file"""
207 flag = self._rev2flag[rev]
208 hsh = self._rev2hsh[rev]
209 f.write(struct.pack(b'B', flag))
210 if flag & renameflag:
211 path = self.rev2path(rev)
212 if path is None:
213 raise error.CorruptedFileError(b'cannot find path for %s' % rev)
214 f.write(path + b'\0')
215 f.write(hsh)
216
217 @staticmethod
218 def _readcstr(f):
219 """read a C-language-like '\0'-terminated string"""
220 buf = b''
221 while True:
222 ch = f.read(1)
223 if not ch: # unexpected eof
224 raise error.CorruptedFileError()
225 if ch == b'\0':
226 break
227 buf += ch
228 return buf
229
230 def __contains__(self, f):
231 """(fctx or (node, path)) -> bool.
232 test if (node, path) is in the map, and is not in a side branch.
233 f can be either a tuple of (node, path), or a fctx.
234 """
235 if isinstance(f, tuple): # f: (node, path)
236 hsh, path = f
237 else: # f: fctx
238 hsh, path = f.node(), f.path()
239 rev = self.hsh2rev(hsh)
240 if rev is None:
241 return False
242 if path is not None and path != self.rev2path(rev):
243 return False
244 return (self.rev2flag(rev) & sidebranchflag) == 0
245
246
247 def getlastnode(path):
248 """return the last hash in a revmap, without loading its full content.
249 this is equivalent to `m = revmap(path); m.rev2hsh(m.maxrev)`, but faster.
250 """
251 hsh = None
252 try:
253 with open(path, 'rb') as f:
254 f.seek(-_hshlen, io.SEEK_END)
255 if f.tell() > len(revmap.HEADER):
256 hsh = f.read(_hshlen)
257 except OSError:
258 pass
259 return hsh