Debian Codegraph @

hgext/git/gitlog.py

raw
1 from __future__ import annotations
2
3 from typing import (
4 Iterable,
5 Iterator,
6 )
7
8 from mercurial.i18n import _
9
10 from mercurial.node import (
11 bin,
12 hex,
13 nullrev,
14 sha1nodeconstants,
15 )
16 from mercurial import (
17 ancestor,
18 changelog as hgchangelog,
19 dagop,
20 encoding,
21 error,
22 manifest,
23 pycompat,
24 )
25 from mercurial.interfaces import (
26 repository,
27 )
28 from mercurial.utils import stringutil
29 from . import (
30 gitutil,
31 index,
32 manifest as gitmanifest,
33 )
34
35 pygit2 = gitutil.get_pygit2()
36
37
38 class baselog: # revlog.revlog):
39 """Common implementations between changelog and manifestlog."""
40
41 def __init__(self, gr, db):
42 self.gitrepo = gr
43 self._db = db
44
45 def __len__(self) -> int:
46 return int(self._db.execute('SELECT ncommits FROM cache').fetchone()[0])
47
48 def files(self):
49 raise NotImplementedError
50
51 def storageinfo(
52 self,
53 exclusivefiles=False,
54 sharedfiles=False,
55 revisionscount=False,
56 trackedsize=False,
57 storedsize=False,
58 ):
59 raise NotImplementedError
60
61 def verifyintegrity(self, state) -> Iterable[repository.iverifyproblem]:
62 raise NotImplementedError
63
64 def revs(self, start=0, stop=None):
65 raise NotImplementedError
66
67 def addgroup(
68 self,
69 deltas,
70 linkmapper,
71 transaction,
72 addrevisioncb=None,
73 duplicaterevisioncb=None,
74 ):
75 raise NotImplementedError
76
77 def commonancestorsheads(self, node1, node2):
78 raise NotImplementedError
79
80 def descendants(self, revs):
81 raise NotImplementedError
82
83 def heads(self, start=None, stop=None):
84 raise NotImplementedError
85
86 def children(self, node):
87 raise NotImplementedError
88
89 def emitrevisions(
90 self,
91 nodes,
92 nodesorder=None,
93 revisiondata=False,
94 assumehaveparentrevisions=False,
95 ):
96 raise NotImplementedError
97
98 def getstrippoint(self, minlink):
99 raise NotImplementedError
100
101 def iscensored(self, rev):
102 raise NotImplementedError
103
104 def parentrevs(self, rev):
105 raise NotImplementedError
106
107 def rawdata(self, node):
108 raise NotImplementedError
109
110 def revision(self, node):
111 raise NotImplementedError
112
113 def size(self, rev):
114 raise NotImplementedError
115
116 def strip(self, minlink, transaction):
117 raise NotImplementedError
118
119 def addrevision(
120 self,
121 revisiondata,
122 transaction,
123 linkrev,
124 p1,
125 p2,
126 node=None,
127 flags=0,
128 cachedelta=None,
129 ):
130 raise NotImplementedError
131
132 def censorrevision(self, tr, node, tombstone=b''):
133 raise NotImplementedError
134
135 def rev(self, n):
136 if n == sha1nodeconstants.nullid:
137 return -1
138 t = self._db.execute(
139 'SELECT rev FROM changelog WHERE node = ?', (gitutil.togitnode(n),)
140 ).fetchone()
141 if t is None:
142 raise error.LookupError(n, b'00changelog.i', _(b'no node'))
143 return t[0]
144
145 def node(self, r):
146 if r == nullrev:
147 return sha1nodeconstants.nullid
148 t = self._db.execute(
149 'SELECT node FROM changelog WHERE rev = ?', (r,)
150 ).fetchone()
151 if t is None:
152 raise error.LookupError(b'%d' % r, b'00changelog.i', _(b'no rev'))
153 return bin(t[0])
154
155 def synthetic(self, n):
156 """Map any node to a non-synthetic node.
157
158 Indexing may have created synthetic nodes to handle octopus merges.
159 Certain operations on these made up nodes need to actually happen on
160 the real octopus merge commit. Given any node, this function
161 returns the real commit hash. One can think of this as hg-to-git
162 commit hash translation that always works."""
163 t = self._db.execute(
164 'SELECT synthetic FROM changelog WHERE node = ?',
165 (gitutil.togitnode(n),),
166 ).fetchone()
167 if t is None or t[0] is None:
168 return n
169 return bin(t[0])
170
171 def hasnode(self, n):
172 t = self._db.execute(
173 'SELECT node FROM changelog WHERE node = ?',
174 (gitutil.togitnode(n),),
175 ).fetchone()
176 return t is not None
177
178
179 class baselogindex:
180 def __init__(self, log):
181 self._log = log
182
183 def has_node(self, n):
184 return self._log.rev(n) != -1
185
186 def __len__(self):
187 return len(self._log)
188
189 def __getitem__(self, idx):
190 p1rev, p2rev = self._log.parentrevs(idx)
191 # TODO: it's messy that the index leaks so far out of the
192 # storage layer that we have to implement things like reading
193 # this raw tuple, which exposes revlog internals.
194 return (
195 # Pretend offset is just the index, since we don't really care.
196 idx,
197 # Same with lengths
198 idx, # length
199 idx, # rawsize
200 -1, # delta base
201 idx, # linkrev TODO is this right?
202 p1rev,
203 p2rev,
204 self._log.node(idx),
205 )
206
207 def rev(self, node):
208 return self._log.rev(node)
209
210 def get_rev(self, node):
211 return self._log.get_rev(node)
212
213
214 # TODO: an interface for the changelog type?
215 class changelog(baselog):
216 # TODO: this appears to be an enumerated type, and should probably
217 # be part of the public changelog interface
218 _copiesstorage = b'extra'
219
220 def __contains__(self, rev):
221 try:
222 self.node(rev)
223 return True
224 except error.LookupError:
225 return False
226
227 def __iter__(self):
228 return iter(range(len(self)))
229
230 @property
231 def filteredrevs(self):
232 # TODO: we should probably add a refs/hg/ namespace for hidden
233 # heads etc, but that's an idea for later.
234 return set()
235
236 @property
237 def index(self):
238 return baselogindex(self)
239
240 @property
241 def nodemap(self):
242 r = {
243 bin(v[0]): v[1]
244 for v in self._db.execute('SELECT node, rev FROM changelog')
245 }
246 r[sha1nodeconstants.nullid] = nullrev
247 return r
248
249 def tip(self):
250 t = self._db.execute(
251 'SELECT node FROM changelog ORDER BY rev DESC LIMIT 1'
252 ).fetchone()
253 if t:
254 return bin(t[0])
255 return sha1nodeconstants.nullid
256
257 def revs(self, start=0, stop=None):
258 if stop is None:
259 stop = self.tiprev()
260 t = self._db.execute(
261 'SELECT rev FROM changelog '
262 'WHERE rev >= ? AND rev <= ? '
263 'ORDER BY REV ASC',
264 (start, stop),
265 )
266 return (int(r[0]) for r in t)
267
268 def tiprev(self):
269 t = self._db.execute(
270 'SELECT rev FROM changelog ' 'ORDER BY REV DESC ' 'LIMIT 1'
271 ).fetchone()
272
273 if t is not None:
274 return t[0]
275 return -1
276
277 def _partialmatch(self, id):
278 if sha1nodeconstants.wdirhex.startswith(id):
279 raise error.WdirUnsupported
280 candidates = [
281 bin(x[0])
282 for x in self._db.execute(
283 'SELECT node FROM changelog WHERE node LIKE ?',
284 (pycompat.sysstr(id + b'%'),),
285 )
286 ]
287 if sha1nodeconstants.nullhex.startswith(id):
288 candidates.append(sha1nodeconstants.nullid)
289 if len(candidates) > 1:
290 raise error.AmbiguousPrefixLookupError(
291 id, b'00changelog.i', _(b'ambiguous identifier')
292 )
293 if candidates:
294 return candidates[0]
295 return None
296
297 def flags(self, rev):
298 return 0
299
300 def shortest(self, node, minlength=1):
301 nodehex = hex(node)
302 for attempt in range(minlength, len(nodehex) + 1):
303 candidate = nodehex[:attempt]
304 matches = int(
305 self._db.execute(
306 'SELECT COUNT(*) FROM changelog WHERE node GLOB ?',
307 (pycompat.sysstr(candidate + b'*'),),
308 ).fetchone()[0]
309 )
310 if matches == 1:
311 return candidate
312 return nodehex
313
314 def headrevs(self, revs=None):
315 realheads = [
316 int(x[0])
317 for x in self._db.execute(
318 'SELECT rev FROM changelog '
319 'INNER JOIN heads ON changelog.node = heads.node'
320 )
321 ]
322 if revs:
323 return sorted([r for r in revs if r in realheads])
324 return sorted(realheads)
325
326 def changelogrevision(self, nodeorrev):
327 # Ensure we have a node id
328 if isinstance(nodeorrev, int):
329 n = self.node(nodeorrev)
330 else:
331 n = nodeorrev
332 extra = {b'branch': b'default'}
333 # handle looking up nullid
334 if n == sha1nodeconstants.nullid:
335 return hgchangelog._changelogrevision(
336 extra=extra, manifest=sha1nodeconstants.nullid
337 )
338 n = self.synthetic(n)
339 hn = gitutil.togitnode(n)
340 # We've got a real commit!
341 index._index_repo_commit(self.gitrepo, self._db, hn, commit=True)
342 files = [
343 r[0]
344 for r in self._db.execute(
345 'SELECT filename FROM changedfiles '
346 'WHERE node = ? and filenode != ?',
347 (hn, gitutil.nullgit),
348 )
349 ]
350 filesremoved = [
351 r[0]
352 for r in self._db.execute(
353 'SELECT filename FROM changedfiles '
354 'WHERE node = ? and filenode = ?',
355 (hn, gitutil.nullgit),
356 )
357 ]
358 c = self.gitrepo[hn]
359 return hgchangelog._changelogrevision(
360 manifest=n, # pretend manifest the same as the commit node
361 user=b'%s <%s>'
362 % (c.author.name.encode('utf8'), c.author.email.encode('utf8')),
363 date=(c.author.time, -c.author.offset * 60),
364 files=files,
365 # TODO filesadded in the index
366 filesremoved=filesremoved,
367 description=c.message.encode('utf8'),
368 # TODO do we want to handle extra? how?
369 extra=extra,
370 )
371
372 def ancestors(self, revs, stoprev=0, inclusive=False):
373 revs = list(revs)
374 tip = self.rev(self.tip())
375 for r in revs:
376 if r > tip:
377 raise IndexError(b'Invalid rev %r' % r)
378 return ancestor.lazyancestors(
379 self.parentrevs, revs, stoprev=stoprev, inclusive=inclusive
380 )
381
382 # Cleanup opportunity: this is *identical* to the revlog.py version
383 def descendants(self, revs):
384 return dagop.descendantrevs(revs, self.revs, self.parentrevs)
385
386 def incrementalmissingrevs(self, common=None):
387 """Return an object that can be used to incrementally compute the
388 revision numbers of the ancestors of arbitrary sets that are not
389 ancestors of common. This is an ancestor.incrementalmissingancestors
390 object.
391
392 'common' is a list of revision numbers. If common is not supplied, uses
393 nullrev.
394 """
395 if common is None:
396 common = [nullrev]
397
398 return ancestor.incrementalmissingancestors(self.parentrevs, common)
399
400 def findmissingrevs(self, common=None, heads=None):
401 """Return the revision numbers of the ancestors of heads that
402 are not ancestors of common.
403
404 More specifically, return a list of revision numbers corresponding to
405 nodes N such that every N satisfies the following constraints:
406
407 1. N is an ancestor of some node in 'heads'
408 2. N is not an ancestor of any node in 'common'
409
410 The list is sorted by revision number, meaning it is
411 topologically sorted.
412
413 'heads' and 'common' are both lists of revision numbers. If heads is
414 not supplied, uses all of the revlog's heads. If common is not
415 supplied, uses nullid."""
416 if common is None:
417 common = [nullrev]
418 if heads is None:
419 heads = self.headrevs()
420
421 inc = self.incrementalmissingrevs(common=common)
422 return inc.missingancestors(heads)
423
424 def findmissing(self, common=None, heads=None):
425 """Return the ancestors of heads that are not ancestors of common.
426
427 More specifically, return a list of nodes N such that every N
428 satisfies the following constraints:
429
430 1. N is an ancestor of some node in 'heads'
431 2. N is not an ancestor of any node in 'common'
432
433 The list is sorted by revision number, meaning it is
434 topologically sorted.
435
436 'heads' and 'common' are both lists of node IDs. If heads is
437 not supplied, uses all of the revlog's heads. If common is not
438 supplied, uses nullid."""
439 if common is None:
440 common = [sha1nodeconstants.nullid]
441 if heads is None:
442 heads = [self.node(r) for r in self.headrevs()]
443
444 common = [self.rev(n) for n in common]
445 heads = [self.rev(n) for n in heads]
446
447 inc = self.incrementalmissingrevs(common=common)
448 return [self.node(r) for r in inc.missingancestors(heads)]
449
450 def children(self, node):
451 """find the children of a given node"""
452 c = []
453 p = self.rev(node)
454 for r in self.revs(start=p + 1):
455 prevs = [pr for pr in self.parentrevs(r) if pr != nullrev]
456 if prevs:
457 for pr in prevs:
458 if pr == p:
459 c.append(self.node(r))
460 elif p == nullrev:
461 c.append(self.node(r))
462 return c
463
464 def reachableroots(self, minroot, heads, roots, includepath=False):
465 return dagop._reachablerootspure(
466 self.parentrevs, minroot, roots, heads, includepath
467 )
468
469 # Cleanup opportunity: this is *identical* to the revlog.py version
470 def isancestor(self, a, b):
471 a, b = self.rev(a), self.rev(b)
472 return self.isancestorrev(a, b)
473
474 # Cleanup opportunity: this is *identical* to the revlog.py version
475 def isancestorrev(self, a, b):
476 if a == nullrev:
477 return True
478 elif a == b:
479 return True
480 elif a > b:
481 return False
482 return bool(self.reachableroots(a, [b], [a], includepath=False))
483
484 def parentrevs(self, rev):
485 assert rev >= 0, rev
486 t = self._db.execute(
487 'SELECT p1, p2 FROM changelog WHERE rev = ?', (rev,)
488 ).fetchone()
489 if t is None:
490 raise error.LookupError(b'%d' % rev, b'00changelog.i', _(b'no rev'))
491 return self.rev(bin(t[0])), self.rev(bin(t[1]))
492
493 # Private method is used at least by the tags code.
494 _uncheckedparentrevs = parentrevs
495
496 def commonancestorsheads(self, a, b):
497 # TODO the revlog verson of this has a C path, so we probably
498 # need to optimize this...
499 a, b = self.rev(a), self.rev(b)
500 return [
501 self.node(n)
502 for n in ancestor.commonancestorsheads(self.parentrevs, a, b)
503 ]
504
505 def branchinfo(self, rev):
506 """Git doesn't do named branches, so just put everything on default."""
507 return b'default', False
508
509 def delayupdate(self, tr):
510 # TODO: I think we can elide this because we're just dropping
511 # an object in the git repo?
512 pass
513
514 def add(
515 self,
516 manifest,
517 files,
518 desc,
519 transaction,
520 p1,
521 p2,
522 user,
523 date=None,
524 extra=None,
525 p1copies=None,
526 p2copies=None,
527 filesadded=None,
528 filesremoved=None,
529 ):
530 parents = []
531 hp1, hp2 = gitutil.togitnode(p1), gitutil.togitnode(p2)
532 if p1 != sha1nodeconstants.nullid:
533 parents.append(hp1)
534 if p2 and p2 != sha1nodeconstants.nullid:
535 parents.append(hp2)
536 assert date is not None
537 timestamp, tz = date
538 sig = pygit2.Signature(
539 encoding.unifromlocal(stringutil.person(user)),
540 encoding.unifromlocal(stringutil.email(user)),
541 int(timestamp),
542 -int(tz // 60),
543 )
544 oid = self.gitrepo.create_commit(
545 None, sig, sig, desc, gitutil.togitnode(manifest), parents
546 )
547 # Set up an internal reference to force the commit into the
548 # changelog. Hypothetically, we could even use this refs/hg/
549 # namespace to allow for anonymous heads on git repos, which
550 # would be neat.
551 self.gitrepo.references.create(
552 'refs/hg/internal/latest-commit', oid, force=True
553 )
554 # Reindex now to pick up changes. We omit the progress
555 # and log callbacks because this will be very quick.
556 index._index_repo(self.gitrepo, self._db)
557 return oid.raw
558
559
560 class manifestlog(baselog):
561 nodeconstants = sha1nodeconstants
562
563 def __getitem__(self, node):
564 return self.get(b'', node)
565
566 def get(self, relpath, node):
567 if node == sha1nodeconstants.nullid:
568 # TODO: this should almost certainly be a memgittreemanifestctx
569 return manifest.memtreemanifestctx(self, relpath)
570 node = self.synthetic(node)
571 commit = self.gitrepo[gitutil.togitnode(node)]
572 t = commit.tree
573 if relpath:
574 parts = relpath.split(b'/')
575 for p in parts:
576 te = t[p]
577 t = self.gitrepo[te.id]
578 return gitmanifest.gittreemanifestctx(self.gitrepo, t)
579
580
581 class filelog(baselog, repository.ifilestorage):
582 def __init__(self, gr, db, path):
583 super().__init__(gr, db)
584 assert isinstance(path, bytes)
585 self.path = path
586 self.nullid = sha1nodeconstants.nullid
587
588 def read(self, node):
589 if node == sha1nodeconstants.nullid:
590 return b''
591 return self.gitrepo[gitutil.togitnode(node)].data
592
593 def lookup(self, node):
594 if len(node) not in (20, 40):
595 node = int(node)
596 if isinstance(node, int):
597 assert False, b'todo revnums for nodes'
598 if len(node) == 40:
599 node = bin(node)
600 hnode = gitutil.togitnode(node)
601 if hnode in self.gitrepo:
602 return node
603 raise error.LookupError(self.path, node, _(b'no match found'))
604
605 def cmp(self, node, text):
606 """Returns True if text is different than content at `node`."""
607 return self.read(node) != text
608
609 def add(self, text, meta, transaction, link, p1=None, p2=None):
610 assert not meta # Should we even try to handle this?
611 return self.gitrepo.create_blob(text).raw
612
613 def __iter__(self) -> Iterator[int]:
614 for clrev in self._db.execute(
615 '''
616 SELECT rev FROM changelog
617 INNER JOIN changedfiles ON changelog.node = changedfiles.node
618 WHERE changedfiles.filename = ? AND changedfiles.filenode != ?
619 ''',
620 (pycompat.fsdecode(self.path), gitutil.nullgit),
621 ):
622 yield clrev[0]
623
624 def linkrev(self, fr):
625 return fr
626
627 def rev(self, node):
628 row = self._db.execute(
629 '''
630 SELECT rev FROM changelog
631 INNER JOIN changedfiles ON changelog.node = changedfiles.node
632 WHERE changedfiles.filename = ? AND changedfiles.filenode = ?''',
633 (pycompat.fsdecode(self.path), gitutil.togitnode(node)),
634 ).fetchone()
635 if row is None:
636 raise error.LookupError(self.path, node, _(b'no node'))
637 return int(row[0])
638
639 def node(self, rev):
640 maybe = self._db.execute(
641 '''SELECT filenode FROM changedfiles
642 INNER JOIN changelog ON changelog.node = changedfiles.node
643 WHERE changelog.rev = ? AND filename = ?
644 ''',
645 (rev, pycompat.fsdecode(self.path)),
646 ).fetchone()
647 if maybe is None:
648 raise IndexError('gitlog %r out of range %d' % (self.path, rev))
649 return bin(maybe[0])
650
651 def parents(self, node):
652 gn = gitutil.togitnode(node)
653 gp = pycompat.fsdecode(self.path)
654 ps = []
655 for p in self._db.execute(
656 '''SELECT p1filenode, p2filenode FROM changedfiles
657 WHERE filenode = ? AND filename = ?
658 ''',
659 (gn, gp),
660 ).fetchone():
661 if p is None:
662 commit = self._db.execute(
663 "SELECT node FROM changedfiles "
664 "WHERE filenode = ? AND filename = ?",
665 (gn, gp),
666 ).fetchone()[0]
667 # This filelog is missing some data. Build the
668 # filelog, then recurse (which will always find data).
669 commit = commit.decode('ascii')
670 index.fill_in_filelog(self.gitrepo, self._db, commit, gp, gn)
671 return self.parents(node)
672 else:
673 ps.append(bin(p))
674 return ps
675
676 def renamed(self, node):
677 # TODO: renames/copies
678 return False