Debian Codegraph @

hgext/git/index.py

raw
1 from __future__ import annotations
2
3 import collections
4 import os
5 import sqlite3
6
7 from mercurial.i18n import _
8 from mercurial.node import sha1nodeconstants
9
10 from mercurial import (
11 encoding,
12 error,
13 pycompat,
14 )
15
16 from . import gitutil
17
18
19 pygit2 = gitutil.get_pygit2()
20
21 _CURRENT_SCHEMA_VERSION = 5
22 _SCHEMA = (
23 """
24 CREATE TABLE refs (
25 -- node and name are unique together. There may be more than one name for
26 -- a given node, and there may be no name at all for a given node (in the
27 -- case of an anonymous hg head).
28 node TEXT NOT NULL,
29 name TEXT
30 );
31
32 -- The "possible heads" of the repository, which we use to figure out
33 -- if we need to re-walk the changelog.
34 CREATE TABLE possible_heads (
35 node TEXT NOT NULL
36 );
37
38 CREATE UNIQUE INDEX possible_heads_idx ON possible_heads(node);
39
40 -- The topological heads of the changelog, which hg depends on.
41 CREATE TABLE heads (
42 node TEXT NOT NULL
43 );
44
45 -- A total ordering of the changelog
46 CREATE TABLE changelog (
47 rev INTEGER NOT NULL PRIMARY KEY,
48 node TEXT NOT NULL,
49 p1 TEXT,
50 p2 TEXT,
51 synthetic TEXT,
52 changedfiles BOOLEAN
53 );
54
55 CREATE UNIQUE INDEX changelog_node_idx ON changelog(node);
56 CREATE UNIQUE INDEX changelog_node_rev_idx ON changelog(rev, node);
57
58 -- Changed files for each commit, which lets us dynamically build
59 -- filelogs.
60 CREATE TABLE changedfiles (
61 node TEXT NOT NULL,
62 filename TEXT NOT NULL,
63 -- 40 zeroes for deletions
64 filenode TEXT NOT NULL,
65 -- to handle filelog parentage:
66 p1node TEXT,
67 p1filenode TEXT,
68 p2node TEXT,
69 p2filenode TEXT
70 );
71
72 CREATE INDEX changedfiles_nodes_idx
73 ON changedfiles(node);
74
75 -- Cached values to improve performance
76 CREATE TABLE cache (
77 ncommits INTEGER
78 );
79 INSERT INTO cache (ncommits) VALUES (NULL);
80
81 PRAGMA user_version=%d
82 """
83 % _CURRENT_SCHEMA_VERSION
84 )
85
86
87 def _createdb(path):
88 # print('open db', path)
89 # import traceback
90 # traceback.print_stack()
91 db = sqlite3.connect(encoding.strfromlocal(path))
92 db.text_factory = bytes
93
94 res = db.execute('PRAGMA user_version').fetchone()[0]
95
96 # New database.
97 if res == 0:
98 for statement in _SCHEMA.split(';'):
99 db.execute(statement.strip())
100
101 db.commit()
102
103 elif res == _CURRENT_SCHEMA_VERSION:
104 pass
105
106 else:
107 raise error.Abort(_(b'sqlite database has unrecognized version'))
108
109 db.execute('PRAGMA journal_mode=WAL')
110
111 return db
112
113
114 _OUR_ORDER = ()
115 if pygit2:
116 _OUR_ORDER = (
117 pygit2.GIT_SORT_TOPOLOGICAL
118 | pygit2.GIT_SORT_TIME
119 | pygit2.GIT_SORT_REVERSE
120 )
121
122 _DIFF_FLAGS = 1 << 21 # GIT_DIFF_FORCE_BINARY, which isn't exposed by pygit2
123
124
125 def _find_nearest_ancestor_introducing_node(
126 db, gitrepo, file_path, walk_start, filenode
127 ):
128 """Find the nearest ancestor that introduces a file node.
129
130 Args:
131 db: a handle to our sqlite database.
132 gitrepo: A pygit2.Repository instance.
133 file_path: the path of a file in the repo
134 walk_start: a pygit2.Oid that is a commit where we should start walking
135 for our nearest ancestor.
136
137 Returns:
138 A hexlified SHA that is the commit ID of the next-nearest parent.
139 """
140 assert isinstance(file_path, str), 'file_path must be str, got %r' % type(
141 file_path
142 )
143 assert isinstance(filenode, str), 'filenode must be str, got %r' % type(
144 filenode
145 )
146 parent_options = {
147 row[0].decode('ascii')
148 for row in db.execute(
149 'SELECT node FROM changedfiles '
150 'WHERE filename = ? AND filenode = ?',
151 (file_path, filenode),
152 )
153 }
154 inner_walker = gitrepo.walk(walk_start, _OUR_ORDER)
155 for w in inner_walker:
156 if w.id.hex in parent_options:
157 return w.id.hex
158 raise error.ProgrammingError(
159 'Unable to find introducing commit for %s node %s from %s',
160 (file_path, filenode, walk_start),
161 )
162
163
164 def fill_in_filelog(gitrepo, db, startcommit, path, startfilenode):
165 """Given a starting commit and path, fill in a filelog's parent pointers.
166
167 Args:
168 gitrepo: a pygit2.Repository
169 db: a handle to our sqlite database
170 startcommit: a hexlified node id for the commit to start at
171 path: the path of the file whose parent pointers we should fill in.
172 filenode: the hexlified node id of the file at startcommit
173
174 TODO: make filenode optional
175 """
176 assert isinstance(
177 startcommit, str
178 ), 'startcommit must be str, got %r' % type(startcommit)
179 assert isinstance(
180 startfilenode, str
181 ), 'startfilenode must be str, got %r' % type(startfilenode)
182 visit = collections.deque([(startcommit, startfilenode)])
183 while visit:
184 cnode, filenode = visit.popleft()
185 commit = gitrepo[cnode]
186 parents = []
187 for parent in commit.parents:
188 t = parent.tree
189 for comp in path.split('/'):
190 try:
191 t = gitrepo[t[comp].id]
192 except KeyError:
193 break
194 else:
195 introducer = _find_nearest_ancestor_introducing_node(
196 db, gitrepo, path, parent.id, t.id.hex
197 )
198 parents.append((introducer, t.id.hex))
199 p1node = p1fnode = p2node = p2fnode = gitutil.nullgit
200 for par, parfnode in parents:
201 found = int(
202 db.execute(
203 'SELECT COUNT(*) FROM changedfiles WHERE '
204 'node = ? AND filename = ? AND filenode = ? AND '
205 'p1node NOT NULL',
206 (par, path, parfnode),
207 ).fetchone()[0]
208 )
209 if found == 0:
210 assert par is not None
211 visit.append((par, parfnode))
212 if parents:
213 p1node, p1fnode = parents[0]
214 if len(parents) == 2:
215 p2node, p2fnode = parents[1]
216 if len(parents) > 2:
217 raise error.ProgrammingError(
218 b"git support can't handle octopus merges"
219 )
220 db.execute(
221 'UPDATE changedfiles SET '
222 'p1node = ?, p1filenode = ?, p2node = ?, p2filenode = ? '
223 'WHERE node = ? AND filename = ? AND filenode = ?',
224 (p1node, p1fnode, p2node, p2fnode, commit.id.hex, path, filenode),
225 )
226 db.commit()
227
228
229 def _index_repo_commit(gitrepo, db, node, commit=False):
230 already_done = db.execute(
231 "SELECT changedfiles FROM changelog WHERE node=?", (node,)
232 ).fetchone()[0]
233 if already_done:
234 return # This commit has already been indexed
235
236 commit = gitrepo[node]
237 files = {}
238 # I *think* we only need to check p1 for changed files
239 # (and therefore linkrevs), because any node that would
240 # actually have this commit as a linkrev would be
241 # completely new in this rev.
242 p1 = commit.parents[0].id.hex if commit.parents else None
243 if p1 is not None:
244 patchgen = gitrepo.diff(p1, commit.id.hex, flags=_DIFF_FLAGS)
245 else:
246 patchgen = commit.tree.diff_to_tree(swap=True, flags=_DIFF_FLAGS)
247 new_files = (p.delta.new_file for p in patchgen)
248 files = {
249 nf.path: nf.id.hex
250 for nf in new_files
251 if nf.id.raw != sha1nodeconstants.nullid
252 }
253 for p, n in files.items():
254 # We intentionally set NULLs for any file parentage
255 # information so it'll get demand-computed later. We
256 # used to do it right here, and it was _very_ slow.
257 db.execute(
258 'INSERT INTO changedfiles ('
259 'node, filename, filenode, p1node, p1filenode, p2node, '
260 'p2filenode) VALUES(?, ?, ?, ?, ?, ?, ?)',
261 (commit.id.hex, p, n, None, None, None, None),
262 )
263 # Mark the commit as loaded
264 db.execute(
265 "UPDATE changelog SET changedfiles=TRUE WHERE node=?", (commit.id.hex,)
266 )
267 if commit:
268 db.commit()
269
270
271 def _index_repo(
272 gitrepo,
273 db,
274 logfn=lambda x: None,
275 progress_factory=lambda *args, **kwargs: None,
276 ):
277 # Identify all references so we can tell the walker to visit all of them.
278 all_refs = gitrepo.listall_references()
279 possible_heads = set()
280 prog = progress_factory(b'indexing refs')
281 for pos, ref in enumerate(all_refs):
282 if prog is not None:
283 prog.update(pos)
284 if not (
285 ref.startswith('refs/heads/') # local branch
286 or ref.startswith('refs/tags/') # tag
287 or ref.startswith('refs/remotes/') # remote branch
288 or ref.startswith('refs/hg/') # from this extension
289 ):
290 continue
291 try:
292 start = gitrepo.lookup_reference(ref).peel(pygit2.GIT_OBJ_COMMIT)
293 except ValueError:
294 # No commit to be found, so we don't care for hg's purposes.
295 continue
296 possible_heads.add(start.id)
297 # Optimization: if the list of refs hasn't changed, don't
298 # reindex the changelog. This doesn't matter on small
299 # repositories, but on even moderately deep histories (e.g., cpython)
300 # this is a very important performance win.
301 #
302 # TODO: we should figure out how to incrementally index history
303 # (preferably by detecting rewinds!) so that we don't have to do a
304 # full changelog walk every time a new commit is created.
305 cache_heads = {
306 pycompat.sysstr(x[0])
307 for x in db.execute('SELECT node FROM possible_heads')
308 }
309 walker = None
310 cur_cache_heads = {h.hex for h in possible_heads}
311 if cur_cache_heads == cache_heads:
312 return
313 logfn(b'heads mismatch, rebuilding dagcache\n')
314 for start in possible_heads:
315 if walker is None:
316 walker = gitrepo.walk(start, _OUR_ORDER)
317 else:
318 walker.push(start)
319
320 # Empty out the existing changelog. Even for large-ish histories
321 # we can do the top-level "walk all the commits" dance very
322 # quickly as long as we don't need to figure out the changed files
323 # list.
324 db.execute('DELETE FROM changelog')
325 if prog is not None:
326 prog.complete()
327 prog = progress_factory(b'indexing commits')
328 # This walker is sure to visit all the revisions in history, but
329 # only once.
330 pos = -1
331 for commit in walker:
332 if prog is not None:
333 prog.update(pos)
334 p1 = p2 = gitutil.nullgit
335 if len(commit.parents) <= 2:
336 if commit.parents:
337 p1 = commit.parents[0].id.hex
338 if len(commit.parents) == 2:
339 p2 = commit.parents[1].id.hex
340 pos += 1
341 db.execute(
342 'INSERT INTO changelog (rev, node, p1, p2, synthetic, changedfiles) VALUES(?, ?, ?, ?, NULL, FALSE)',
343 (pos, commit.id.hex, p1, p2),
344 )
345 else:
346 parents = list(commit.parents)
347
348 p1 = parents.pop(0).id.hex
349 while parents:
350 pos += 1
351
352 if len(parents) == 1:
353 this = commit.id.hex
354 synth = None
355 else:
356 this = "%040x" % pos
357 synth = commit.id.hex
358
359 p2 = parents.pop(0).id.hex
360
361 db.execute(
362 'INSERT INTO changelog (rev, node, p1, p2, synthetic, changedfiles) VALUES(?, ?, ?, ?, ?, FALSE)',
363 (pos, this, p1, p2, synth),
364 )
365
366 p1 = this
367 # Determine heads from the list of possible heads.
368 db.execute('DELETE FROM heads')
369 db.execute('DELETE FROM possible_heads')
370 db.executemany(
371 'INSERT INTO possible_heads (node) VALUES(?)',
372 [(hid.hex,) for hid in possible_heads],
373 )
374 db.execute(
375 '''
376 INSERT INTO heads (node)
377 SELECT node FROM possible_heads WHERE
378 node NOT IN (
379 SELECT DISTINCT possible_heads.node FROM changelog, possible_heads WHERE
380 changelog.p1 = possible_heads.node OR
381 changelog.p2 = possible_heads.node
382 )
383 '''
384 )
385 # Mark all commits with already-loaded changefiles info
386 db.execute(
387 '''
388 UPDATE changelog SET changedfiles=TRUE WHERE node IN (
389 SELECT DISTINCT node FROM changedfiles
390 )
391 '''
392 )
393
394 if prog is not None:
395 prog.complete()
396
397 # Index the changed files for head commits
398 prog = progress_factory(b'indexing head files')
399 heads = [
400 row[0].decode('ascii') for row in db.execute("SELECT * FROM heads")
401 ]
402 for pos, h in enumerate(heads):
403 if prog is not None:
404 prog.update(pos)
405 _index_repo_commit(gitrepo, db, h)
406
407 db.execute(
408 '''
409 UPDATE cache SET
410 ncommits = (SELECT COUNT(1) FROM changelog)
411 '''
412 )
413
414 db.commit()
415 if prog is not None:
416 prog.complete()
417
418
419 def get_index(
420 gitrepo, logfn=lambda x: None, progress_factory=lambda *args, **kwargs: None
421 ):
422 cachepath = os.path.join(
423 pycompat.fsencode(gitrepo.path), b'..', b'.hg', b'cache'
424 )
425 if not os.path.exists(cachepath):
426 os.makedirs(cachepath)
427 dbpath = os.path.join(cachepath, b'git-commits.sqlite')
428 db = _createdb(dbpath)
429 # TODO check against gitrepo heads before doing a full index
430 # TODO thread a ui.progress call into this layer
431 _index_repo(gitrepo, db, logfn, progress_factory)
432 return db