Debian Codegraph @

hgext/fastannotate/context.py

raw
1 # Copyright 2016-present Facebook. All Rights Reserved.
2 #
3 # context: context needed to annotate a file
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 collections
11 import contextlib
12 import os
13 import typing
14
15 from mercurial.i18n import _
16 from mercurial.node import (
17 bin,
18 hex,
19 short,
20 )
21 from mercurial import (
22 error,
23 linelog as linelogmod,
24 lock as lockmod,
25 mdiff,
26 pycompat,
27 scmutil,
28 util,
29 )
30 from mercurial.utils import (
31 hashutil,
32 stringutil,
33 )
34
35 from . import (
36 error as faerror,
37 revmap as revmapmod,
38 )
39
40 if typing.TYPE_CHECKING:
41 from mercurial.interfaces.types import (
42 FileStorageT,
43 LocalRepoFileStorageT,
44 )
45
46
47 # given path, get filelog, cached
48 @util.lrucachefunc
49 def _getflog(repo: LocalRepoFileStorageT, path: bytes) -> FileStorageT:
50 return repo.file(path)
51
52
53 # extracted from mercurial.context.basefilectx.annotate
54 def _parents(f, follow=True):
55 # Cut _descendantrev here to mitigate the penalty of lazy linkrev
56 # adjustment. Otherwise, p._adjustlinkrev() would walk changelog
57 # from the topmost introrev (= srcrev) down to p.linkrev() if it
58 # isn't an ancestor of the srcrev.
59 f._changeid
60 pl = f.parents()
61
62 # Don't return renamed parents if we aren't following.
63 if not follow:
64 pl = [p for p in pl if p.path() == f.path()]
65
66 # renamed filectx won't have a filelog yet, so set it
67 # from the cache to save time
68 for p in pl:
69 if not '_filelog' in p.__dict__:
70 p._filelog = _getflog(f._repo, p.path())
71
72 return pl
73
74
75 # extracted from mercurial.context.basefilectx.annotate. slightly modified
76 # so it takes a fctx instead of a pair of text and fctx.
77 def _decorate(fctx):
78 text = fctx.data()
79 linecount = text.count(b'\n')
80 if text and not text.endswith(b'\n'):
81 linecount += 1
82 return ([(fctx, i) for i in range(linecount)], text)
83
84
85 # extracted from mercurial.context.basefilectx.annotate. slightly modified
86 # so it takes an extra "blocks" parameter calculated elsewhere, instead of
87 # calculating diff here.
88 def _pair(parent, child, blocks):
89 for (a1, a2, b1, b2), t in blocks:
90 # Changed blocks ('!') or blocks made only of blank lines ('~')
91 # belong to the child.
92 if t == b'=':
93 child[0][b1:b2] = parent[0][a1:a2]
94 return child
95
96
97 # like scmutil.revsingle, but with lru cache, so their states (like manifests)
98 # could be reused
99 _revsingle = util.lrucachefunc(scmutil.revsingle)
100
101
102 def resolvefctx(repo, rev, path, resolverev=False, adjustctx=None):
103 """(repo, str, str) -> fctx
104
105 get the filectx object from repo, rev, path, in an efficient way.
106
107 if resolverev is True, "rev" is a revision specified by the revset
108 language, otherwise "rev" is a nodeid, or a revision number that can
109 be consumed by repo.__getitem__.
110
111 if adjustctx is not None, the returned fctx will point to a changeset
112 that introduces the change (last modified the file). if adjustctx
113 is 'linkrev', trust the linkrev and do not adjust it. this is noticeably
114 faster for big repos but is incorrect for some cases.
115 """
116 if resolverev and not isinstance(rev, int) and rev is not None:
117 ctx = _revsingle(repo, rev)
118 else:
119 ctx = repo[rev]
120
121 # If we don't need to adjust the linkrev, create the filectx using the
122 # changectx instead of using ctx[path]. This means it already has the
123 # changectx information, so blame -u will be able to look directly at the
124 # commitctx object instead of having to resolve it by going through the
125 # manifest. In a lazy-manifest world this can prevent us from downloading a
126 # lot of data.
127 if adjustctx is None:
128 # ctx.rev() is None means it's the working copy, which is a special
129 # case.
130 if ctx.rev() is None:
131 fctx = ctx[path]
132 else:
133 fctx = repo.filectx(path, changeid=ctx.rev())
134 else:
135 fctx = ctx[path]
136 if adjustctx == b'linkrev':
137 introrev = fctx.linkrev()
138 else:
139 introrev = fctx.introrev()
140 if introrev != ctx.rev():
141 fctx._changeid = introrev
142 fctx._changectx = repo[introrev]
143 return fctx
144
145
146 # like mercurial.store.encodedir, but use linelog suffixes: .m, .l, .lock
147 def encodedir(path):
148 return (
149 path.replace(b'.hg/', b'.hg.hg/')
150 .replace(b'.l/', b'.l.hg/')
151 .replace(b'.m/', b'.m.hg/')
152 .replace(b'.lock/', b'.lock.hg/')
153 )
154
155
156 def hashdiffopts(diffopts):
157 diffoptstr = stringutil.pprint(
158 sorted(
159 (k, getattr(diffopts, pycompat.sysstr(k)))
160 for k in mdiff.diffopts.defaults
161 )
162 )
163 return hex(hashutil.sha1(diffoptstr).digest())[:6]
164
165
166 _defaultdiffopthash = hashdiffopts(mdiff.defaultopts)
167
168
169 class annotateopts:
170 """like mercurial.mdiff.diffopts, but is for annotate
171
172 followrename: follow renames, like "hg annotate -f"
173 followmerge: follow p2 of a merge changeset, otherwise p2 is ignored
174 """
175
176 defaults = {
177 'diffopts': None,
178 'followrename': True,
179 'followmerge': True,
180 }
181
182 diffopts: mdiff.diffopts
183 followrename: bool
184 followmerge: bool
185
186 def __init__(self, **opts):
187 for k, v in self.defaults.items():
188 setattr(self, k, opts.get(k, v))
189
190 @util.propertycache
191 def shortstr(self) -> bytes:
192 """represent opts in a short string, suitable for a directory name"""
193 result = b''
194 if not self.followrename:
195 result += b'r0'
196 if not self.followmerge:
197 result += b'm0'
198 if self.diffopts is not None:
199 assert isinstance(self.diffopts, mdiff.diffopts)
200 diffopthash = hashdiffopts(self.diffopts)
201 if diffopthash != _defaultdiffopthash:
202 result += b'i' + diffopthash
203 return result or b'default'
204
205
206 defaultopts = annotateopts()
207
208
209 class _annotatecontext:
210 """do not use this class directly as it does not use lock to protect
211 writes. use "with annotatecontext(...)" instead.
212 """
213
214 def __init__(self, repo, path, linelogpath, revmappath, opts):
215 self.repo = repo
216 self.ui = repo.ui
217 self.path = path
218 self.opts = opts
219 self.linelogpath = linelogpath
220 self.revmappath = revmappath
221 self._linelog = None
222 self._revmap = None
223 self._node2path = {} # {str: str}
224
225 @property
226 def linelog(self):
227 if self._linelog is None:
228 if os.path.exists(self.linelogpath):
229 with open(self.linelogpath, 'rb') as f:
230 try:
231 self._linelog = linelogmod.linelog.fromdata(f.read())
232 except linelogmod.LineLogError:
233 self._linelog = linelogmod.linelog()
234 else:
235 self._linelog = linelogmod.linelog()
236 return self._linelog
237
238 @property
239 def revmap(self):
240 if self._revmap is None:
241 self._revmap = revmapmod.revmap(self.revmappath)
242 return self._revmap
243
244 def close(self):
245 if self._revmap is not None:
246 self._revmap.flush()
247 self._revmap = None
248 if self._linelog is not None:
249 with open(self.linelogpath, 'wb') as f:
250 f.write(self._linelog.encode())
251 self._linelog = None
252
253 __del__ = close
254
255 def rebuild(self):
256 """delete linelog and revmap, useful for rebuilding"""
257 self.close()
258 self._node2path.clear()
259 _unlinkpaths([self.revmappath, self.linelogpath])
260
261 @property
262 def lastnode(self):
263 """return last node in revmap, or None if revmap is empty"""
264 if self._revmap is None:
265 # fast path, read revmap without loading its full content
266 return revmapmod.getlastnode(self.revmappath)
267 else:
268 return self._revmap.rev2hsh(self._revmap.maxrev)
269
270 def isuptodate(self, master, strict=True):
271 """return True if the revmap / linelog is up-to-date, or the file
272 does not exist in the master revision. False otherwise.
273
274 it tries to be fast and could return false negatives, because of the
275 use of linkrev instead of introrev.
276
277 useful for both server and client to decide whether to update
278 fastannotate cache or not.
279
280 if strict is True, even if fctx exists in the revmap, but is not the
281 last node, isuptodate will return False. it's good for performance - no
282 expensive check was done.
283
284 if strict is False, if fctx exists in the revmap, this function may
285 return True. this is useful for the client to skip downloading the
286 cache if the client's master is behind the server's.
287 """
288 lastnode = self.lastnode
289 try:
290 f = self._resolvefctx(master, resolverev=True)
291 # choose linkrev instead of introrev as the check is meant to be
292 # *fast*.
293 linknode = self.repo.changelog.node(f.linkrev())
294 if not strict and lastnode and linknode != lastnode:
295 # check if f.node() is in the revmap. note: this loads the
296 # revmap and can be slow.
297 return self.revmap.hsh2rev(linknode) is not None
298 # avoid resolving old manifest, or slow adjustlinkrev to be fast,
299 # false negatives are acceptable in this case.
300 return linknode == lastnode
301 except LookupError:
302 # master does not have the file, or the revmap is ahead
303 return True
304
305 def annotate(self, rev, master=None, showpath=False, showlines=False):
306 """incrementally update the cache so it includes revisions in the main
307 branch till 'master'. and run annotate on 'rev', which may or may not be
308 included in the main branch.
309
310 if master is None, do not update linelog.
311
312 the first value returned is the annotate result, it is [(node, linenum)]
313 by default. [(node, linenum, path)] if showpath is True.
314
315 if showlines is True, a second value will be returned, it is a list of
316 corresponding line contents.
317 """
318
319 # the fast path test requires commit hash, convert rev number to hash,
320 # so it may hit the fast path. note: in the "fctx" mode, the "annotate"
321 # command could give us a revision number even if the user passes a
322 # commit hash.
323 if isinstance(rev, int):
324 rev = hex(self.repo.changelog.node(rev))
325
326 # fast path: if rev is in the main branch already
327 directly, revfctx = self.canannotatedirectly(rev)
328 if directly:
329 if self.ui.debugflag:
330 self.ui.debug(
331 b'fastannotate: %s: using fast path '
332 b'(resolved fctx: %s)\n'
333 % (
334 self.path,
335 stringutil.pprint(hasattr(revfctx, 'node')),
336 )
337 )
338 return self.annotatedirectly(revfctx, showpath, showlines)
339
340 # resolve master
341 masterfctx = None
342 if master:
343 try:
344 masterfctx = self._resolvefctx(
345 master, resolverev=True, adjustctx=True
346 )
347 except LookupError: # master does not have the file
348 pass
349 else:
350 if masterfctx in self.revmap: # no need to update linelog
351 masterfctx = None
352
353 # ... - @ <- rev (can be an arbitrary changeset,
354 # / not necessarily a descendant
355 # master -> o of master)
356 # |
357 # a merge -> o 'o': new changesets in the main branch
358 # |\ '#': revisions in the main branch that
359 # o * exist in linelog / revmap
360 # | . '*': changesets in side branches, or
361 # last master -> # . descendants of master
362 # | .
363 # # * joint: '#', and is a parent of a '*'
364 # |/
365 # a joint -> # ^^^^ --- side branches
366 # |
367 # ^ --- main branch (in linelog)
368
369 # these DFSes are similar to the traditional annotate algorithm.
370 # we cannot really reuse the code for perf reason.
371
372 # 1st DFS calculates merges, joint points, and needed.
373 # "needed" is a simple reference counting dict to free items in
374 # "hist", reducing its memory usage otherwise could be huge.
375 initvisit = [revfctx]
376 if masterfctx:
377 if masterfctx.rev() is None:
378 raise error.Abort(
379 _(b'cannot update linelog to wdir()'),
380 hint=_(b'set fastannotate.mainbranch'),
381 )
382 initvisit.append(masterfctx)
383 visit = initvisit[:]
384 pcache = {}
385 needed = {revfctx: 1}
386 hist = {} # {fctx: ([(llrev or fctx, linenum)], text)}
387 while visit:
388 f = visit.pop()
389 if f in pcache or f in hist:
390 continue
391 if f in self.revmap: # in the old main branch, it's a joint
392 llrev = self.revmap.hsh2rev(f.node())
393 self.linelog.annotate(llrev)
394 result = self.linelog.annotateresult
395 hist[f] = (result, f.data())
396 continue
397 pl = self._parentfunc(f)
398 pcache[f] = pl
399 for p in pl:
400 needed[p] = needed.get(p, 0) + 1
401 if p not in pcache:
402 visit.append(p)
403
404 # 2nd (simple) DFS calculates new changesets in the main branch
405 # ('o' nodes in # the above graph), so we know when to update linelog.
406 newmainbranch = set()
407 f = masterfctx
408 while f and f not in self.revmap:
409 newmainbranch.add(f)
410 pl = pcache[f]
411 if pl:
412 f = pl[0]
413 else:
414 f = None
415 break
416
417 # f, if present, is the position where the last build stopped at, and
418 # should be the "master" last time. check to see if we can continue
419 # building the linelog incrementally. (we cannot if diverged)
420 if masterfctx is not None:
421 self._checklastmasterhead(f)
422
423 if self.ui.debugflag:
424 if newmainbranch:
425 self.ui.debug(
426 b'fastannotate: %s: %d new changesets in the main'
427 b' branch\n' % (self.path, len(newmainbranch))
428 )
429 elif not hist: # no joints, no updates
430 self.ui.debug(
431 b'fastannotate: %s: linelog cannot help in '
432 b'annotating this revision\n' % self.path
433 )
434
435 # prepare annotateresult so we can update linelog incrementally
436 self.linelog.annotate(self.linelog.maxrev)
437
438 # 3rd DFS does the actual annotate
439 visit = initvisit[:]
440 progress = self.ui.makeprogress(
441 b'building cache', total=len(newmainbranch)
442 )
443 while visit:
444 f = visit[-1]
445 if f in hist:
446 visit.pop()
447 continue
448
449 ready = True
450 pl = pcache[f]
451 for p in pl:
452 if p not in hist:
453 ready = False
454 visit.append(p)
455 if not ready:
456 continue
457
458 visit.pop()
459 blocks = None # mdiff blocks, used for appending linelog
460 ismainbranch = f in newmainbranch
461 # curr is the same as the traditional annotate algorithm,
462 # if we only care about linear history (do not follow merge),
463 # then curr is not actually used.
464 assert f not in hist
465 curr = _decorate(f)
466 for i, p in enumerate(pl):
467 bs = list(self._diffblocks(hist[p][1], curr[1]))
468 if i == 0 and ismainbranch:
469 blocks = bs
470 curr = _pair(hist[p], curr, bs)
471 if needed[p] == 1:
472 del hist[p]
473 del needed[p]
474 else:
475 needed[p] -= 1
476
477 hist[f] = curr
478 del pcache[f]
479
480 if ismainbranch: # need to write to linelog
481 progress.increment()
482 bannotated = None
483 if len(pl) == 2 and self.opts.followmerge: # merge
484 bannotated = curr[0]
485 if blocks is None: # no parents, add an empty one
486 blocks = list(self._diffblocks(b'', curr[1]))
487 self._appendrev(f, blocks, bannotated)
488 elif showpath: # not append linelog, but we need to record path
489 self._node2path[f.node()] = f.path()
490
491 progress.complete()
492
493 result = [
494 ((self.revmap.rev2hsh(fr) if isinstance(fr, int) else fr.node()), l)
495 for fr, l in hist[revfctx][0]
496 ] # [(node, linenumber)]
497 return self._refineannotateresult(result, revfctx, showpath, showlines)
498
499 def canannotatedirectly(self, rev):
500 """(str) -> bool, fctx or node.
501 return (True, f) if we can annotate without updating the linelog, pass
502 f to annotatedirectly.
503 return (False, f) if we need extra calculation. f is the fctx resolved
504 from rev.
505 """
506 result = True
507 f = None
508 if not isinstance(rev, int) and rev is not None:
509 hsh = {20: bytes, 40: bin}.get(len(rev), lambda x: None)(rev)
510 if hsh is not None and (hsh, self.path) in self.revmap:
511 f = hsh
512 if f is None:
513 adjustctx = b'linkrev' if self._perfhack else True
514 f = self._resolvefctx(rev, adjustctx=adjustctx, resolverev=True)
515 result = f in self.revmap
516 if not result and self._perfhack:
517 # redo the resolution without perfhack - as we are going to
518 # do write operations, we need a correct fctx.
519 f = self._resolvefctx(rev, adjustctx=True, resolverev=True)
520 return result, f
521
522 def annotatealllines(self, rev, showpath=False, showlines=False):
523 """(rev : str) -> [(node : str, linenum : int, path : str)]
524
525 the result has the same format with annotate, but include all (including
526 deleted) lines up to rev. call this after calling annotate(rev, ...) for
527 better performance and accuracy.
528 """
529 revfctx = self._resolvefctx(rev, resolverev=True, adjustctx=True)
530
531 # find a chain from rev to anything in the mainbranch
532 if revfctx not in self.revmap:
533 chain = [revfctx]
534 a = b''
535 while True:
536 f = chain[-1]
537 pl = self._parentfunc(f)
538 if not pl:
539 break
540 if pl[0] in self.revmap:
541 a = pl[0].data()
542 break
543 chain.append(pl[0])
544
545 # both self.linelog and self.revmap is backed by filesystem. now
546 # we want to modify them but do not want to write changes back to
547 # files. so we create in-memory objects and copy them. it's like
548 # a "fork".
549 linelog = linelogmod.linelog()
550 linelog.copyfrom(self.linelog)
551 linelog.annotate(linelog.maxrev)
552 revmap = revmapmod.revmap()
553 revmap.copyfrom(self.revmap)
554
555 for f in reversed(chain):
556 b = f.data()
557 blocks = list(self._diffblocks(a, b))
558 self._doappendrev(linelog, revmap, f, blocks)
559 a = b
560 else:
561 # fastpath: use existing linelog, revmap as we don't write to them
562 linelog = self.linelog
563 revmap = self.revmap
564
565 lines = linelog.getalllines()
566 hsh = revfctx.node()
567 llrev = revmap.hsh2rev(hsh)
568 result = [(revmap.rev2hsh(r), l) for r, l in lines if r <= llrev]
569 # cannot use _refineannotateresult since we need custom logic for
570 # resolving line contents
571 if showpath:
572 result = self._addpathtoresult(result, revmap)
573 if showlines:
574 linecontents = self._resolvelines(result, revmap, linelog)
575 result = (result, linecontents)
576 return result
577
578 def _resolvelines(self, annotateresult, revmap, linelog):
579 """(annotateresult) -> [line]. designed for annotatealllines.
580 this is probably the most inefficient code in the whole fastannotate
581 directory. but we have made a decision that the linelog does not
582 store line contents. so getting them requires random accesses to
583 the revlog data, since they can be many, it can be very slow.
584 """
585 # [llrev]
586 revs = [revmap.hsh2rev(l[0]) for l in annotateresult]
587 result = [None] * len(annotateresult)
588 # {(rev, linenum): [lineindex]}
589 key2idxs = collections.defaultdict(list)
590 for i in range(len(result)):
591 key2idxs[(revs[i], annotateresult[i][1])].append(i)
592 while key2idxs:
593 # find an unresolved line and its linelog rev to annotate
594 hsh = None
595 try:
596 for (rev, _linenum), idxs in key2idxs.items():
597 if revmap.rev2flag(rev) & revmapmod.sidebranchflag:
598 continue
599 hsh = annotateresult[idxs[0]][0]
600 break
601 except StopIteration: # no more unresolved lines
602 return result
603 if hsh is None:
604 # the remaining key2idxs are not in main branch, resolving them
605 # using the hard way...
606 revlines = {}
607 for (rev, linenum), idxs in key2idxs.items():
608 if rev not in revlines:
609 hsh = annotateresult[idxs[0]][0]
610 if self.ui.debugflag:
611 self.ui.debug(
612 b'fastannotate: reading %s line #%d '
613 b'to resolve lines %r\n'
614 % (short(hsh), linenum, idxs)
615 )
616 fctx = self._resolvefctx(hsh, revmap.rev2path(rev))
617 lines = mdiff.splitnewlines(fctx.data())
618 revlines[rev] = lines
619 for idx in idxs:
620 result[idx] = revlines[rev][linenum]
621 assert all(x is not None for x in result)
622 return result
623
624 # run the annotate and the lines should match to the file content
625 self.ui.debug(
626 b'fastannotate: annotate %s to resolve lines\n' % short(hsh)
627 )
628 linelog.annotate(rev)
629 fctx = self._resolvefctx(hsh, revmap.rev2path(rev))
630 annotated = linelog.annotateresult
631 lines = mdiff.splitnewlines(fctx.data())
632 if len(lines) != len(annotated):
633 raise faerror.CorruptedFileError(b'unexpected annotated lines')
634 # resolve lines from the annotate result
635 for i, line in enumerate(lines):
636 k = annotated[i]
637 if k in key2idxs:
638 for idx in key2idxs[k]:
639 result[idx] = line
640 del key2idxs[k]
641 return result
642
643 def annotatedirectly(self, f, showpath, showlines):
644 """like annotate, but when we know that f is in linelog.
645 f can be either a 20-char str (node) or a fctx. this is for perf - in
646 the best case, the user provides a node and we don't need to read the
647 filelog or construct any filecontext.
648 """
649 if isinstance(f, bytes):
650 hsh = f
651 else:
652 hsh = f.node()
653 llrev = self.revmap.hsh2rev(hsh)
654 if not llrev:
655 raise faerror.CorruptedFileError(b'%s is not in revmap' % hex(hsh))
656 if (self.revmap.rev2flag(llrev) & revmapmod.sidebranchflag) != 0:
657 raise faerror.CorruptedFileError(
658 b'%s is not in revmap mainbranch' % hex(hsh)
659 )
660 self.linelog.annotate(llrev)
661 result = [
662 (self.revmap.rev2hsh(r), l) for r, l in self.linelog.annotateresult
663 ]
664 return self._refineannotateresult(result, f, showpath, showlines)
665
666 def _refineannotateresult(self, result, f, showpath, showlines):
667 """add the missing path or line contents, they can be expensive.
668 f could be either node or fctx.
669 """
670 if showpath:
671 result = self._addpathtoresult(result)
672 if showlines:
673 if isinstance(f, bytes): # f: node or fctx
674 llrev = self.revmap.hsh2rev(f)
675 fctx = self._resolvefctx(f, self.revmap.rev2path(llrev))
676 else:
677 fctx = f
678 lines = mdiff.splitnewlines(fctx.data())
679 if len(lines) != len(result): # linelog is probably corrupted
680 raise faerror.CorruptedFileError()
681 result = (result, lines)
682 return result
683
684 def _appendrev(self, fctx, blocks, bannotated=None):
685 self._doappendrev(self.linelog, self.revmap, fctx, blocks, bannotated)
686
687 def _diffblocks(self, a, b):
688 return mdiff.allblocks(a, b, self.opts.diffopts)
689
690 @staticmethod
691 def _doappendrev(linelog, revmap, fctx, blocks, bannotated=None):
692 """append a revision to linelog and revmap"""
693
694 def getllrev(f):
695 """(fctx) -> int"""
696 # f should not be a linelog revision
697 if isinstance(f, int):
698 raise error.ProgrammingError(b'f should not be an int')
699 # f is a fctx, allocate linelog rev on demand
700 hsh = f.node()
701 rev = revmap.hsh2rev(hsh)
702 if rev is None:
703 rev = revmap.append(hsh, sidebranch=True, path=f.path())
704 return rev
705
706 # append sidebranch revisions to revmap
707 siderevs = []
708 siderevmap = {} # node: int
709 if bannotated is not None:
710 for (a1, a2, b1, b2), op in blocks:
711 if op != b'=':
712 # f could be either linelong rev, or fctx.
713 siderevs += [
714 f
715 for f, l in bannotated[b1:b2]
716 if not isinstance(f, int)
717 ]
718 siderevs = set(siderevs)
719 if fctx in siderevs: # mainnode must be appended seperately
720 siderevs.remove(fctx)
721 for f in siderevs:
722 siderevmap[f] = getllrev(f)
723
724 # the changeset in the main branch, could be a merge
725 llrev = revmap.append(fctx.node(), path=fctx.path())
726 siderevmap[fctx] = llrev
727
728 for (a1, a2, b1, b2), op in reversed(blocks):
729 if op == b'=':
730 continue
731 if bannotated is None:
732 linelog.replacelines(llrev, a1, a2, b1, b2)
733 else:
734 blines = [
735 ((r if isinstance(r, int) else siderevmap[r]), l)
736 for r, l in bannotated[b1:b2]
737 ]
738 linelog.replacelines_vec(llrev, a1, a2, blines)
739
740 def _addpathtoresult(self, annotateresult, revmap=None):
741 """(revmap, [(node, linenum)]) -> [(node, linenum, path)]"""
742 if revmap is None:
743 revmap = self.revmap
744
745 def _getpath(nodeid):
746 path = self._node2path.get(nodeid)
747 if path is None:
748 path = revmap.rev2path(revmap.hsh2rev(nodeid))
749 self._node2path[nodeid] = path
750 return path
751
752 return [(n, l, _getpath(n)) for n, l in annotateresult]
753
754 def _checklastmasterhead(self, fctx):
755 """check if fctx is the master's head last time, raise if not"""
756 if fctx is None:
757 llrev = 0
758 else:
759 llrev = self.revmap.hsh2rev(fctx.node())
760 if not llrev:
761 raise faerror.CannotReuseError()
762 if self.linelog.maxrev != llrev:
763 raise faerror.CannotReuseError()
764
765 @util.propertycache
766 def _parentfunc(self):
767 """-> (fctx) -> [fctx]"""
768 followrename = self.opts.followrename
769 followmerge = self.opts.followmerge
770
771 def parents(f):
772 pl = _parents(f, follow=followrename)
773 if not followmerge:
774 pl = pl[:1]
775 return pl
776
777 return parents
778
779 @util.propertycache
780 def _perfhack(self):
781 return self.ui.configbool(b'fastannotate', b'perfhack')
782
783 def _resolvefctx(self, rev, path=None, **kwds):
784 return resolvefctx(self.repo, rev, (path or self.path), **kwds)
785
786
787 def _unlinkpaths(paths):
788 """silent, best-effort unlink"""
789 for path in paths:
790 try:
791 util.unlink(path)
792 except OSError:
793 pass
794
795
796 class pathhelper:
797 """helper for getting paths for lockfile, linelog and revmap"""
798
799 def __init__(self, repo, path, opts=defaultopts):
800 # different options use different directories
801 self._vfspath = os.path.join(
802 b'fastannotate', opts.shortstr, encodedir(path)
803 )
804 self._repo = repo
805
806 @property
807 def dirname(self):
808 return os.path.dirname(self._repo.vfs.join(self._vfspath))
809
810 @property
811 def linelogpath(self):
812 return self._repo.vfs.join(self._vfspath + b'.l')
813
814 def lock(self):
815 return lockmod.lock(self._repo.vfs, self._vfspath + b'.lock')
816
817 @property
818 def revmappath(self):
819 return self._repo.vfs.join(self._vfspath + b'.m')
820
821
822 @contextlib.contextmanager
823 def annotatecontext(repo, path, opts=defaultopts, rebuild=False):
824 """context needed to perform (fast) annotate on a file
825
826 an annotatecontext of a single file consists of two structures: the
827 linelog and the revmap. this function takes care of locking. only 1
828 process is allowed to write that file's linelog and revmap at a time.
829
830 when something goes wrong, this function will assume the linelog and the
831 revmap are in a bad state, and remove them from disk.
832
833 use this function in the following way:
834
835 with annotatecontext(...) as actx:
836 actx. ....
837 """
838 helper = pathhelper(repo, path, opts)
839 util.makedirs(helper.dirname)
840 revmappath = helper.revmappath
841 linelogpath = helper.linelogpath
842 actx = None
843 try:
844 with helper.lock():
845 actx = _annotatecontext(repo, path, linelogpath, revmappath, opts)
846 if rebuild:
847 actx.rebuild()
848 yield actx
849 except Exception:
850 if actx is not None:
851 actx.rebuild()
852 repo.ui.debug(b'fastannotate: %s: cache broken and deleted\n' % path)
853 raise
854 finally:
855 if actx is not None:
856 actx.close()
857
858
859 def fctxannotatecontext(fctx, follow=True, diffopts=None, rebuild=False):
860 """like annotatecontext but get the context from a fctx. convenient when
861 used in fctx.annotate
862 """
863 repo = fctx._repo
864 path = fctx._path
865 if repo.ui.configbool(b'fastannotate', b'forcefollow', True):
866 follow = True
867 aopts = annotateopts(diffopts=diffopts, followrename=follow)
868 return annotatecontext(repo, path, aopts, rebuild)