diff mercurial/cmdutil.py @ 34857:84c6b9384d6a

log: add -L/--line-range option to follow file history by line range We add an experimental -L/--line-range option to 'hg log' taking file patterns along with a line range using the (new) FILE,FROMLINE-TOLINE syntax where FILE may be a pattern (matching exactly one file). The resulting history is similar to what the "followlines" revset except that, if --patch is specified, only diff hunks within specified line range are shown. Basically, this brings the CLI on par with what currently only exists in hgweb through line selection in "file" and "annotate" views resulting in a file log with filtered patch to only display followed line range. The option may be specified multiple times and can be combined with --rev and regular file patterns to further restrict revisions. Usage of this option requires --follow; revisions are shown in descending order and renames are followed. Only the --graph option is currently not supported. The UI is the result of a consensus from review feedback at: https://www.mercurial-scm.org/pipermail/mercurial-devel/2017-October/106749.html The implementation spreads between commands.log() and cmdutil module. In commands.log(), the main loop may now use a "hunksfilter" factory (similar to "filematcher") that, for a given "rev", produces a filtering function for diff hunks for a given file context object. The logic to build revisions from -L/--line-range options lives in cmdutil.getloglinerangerevs() which produces "revs", "filematcher" and "hunksfilter" information. Revisions obtained by following files' line range are filtered if they do not match the revset specified by --rev option. If regular FILE arguments are passed along with -L options, both filematchers are combined into a new matcher. .. feature:: Add an experimental -L/--line-range FILE,FROMLINE-TOLINE option to 'hg log' command to follow the history of files by line range. In combination with -p/--patch option, only diff hunks within specified line range will be displayed. Feedback, especially on UX aspects, is welcome.
author Denis Laxalde <denis.laxalde@logilab.fr>
date Tue, 17 Oct 2017 21:15:31 +0200
parents 890afefa7296
children 068e0e531584
line wrap: on
line diff
--- a/mercurial/cmdutil.py	Fri Oct 06 14:45:17 2017 +0200
+++ b/mercurial/cmdutil.py	Tue Oct 17 21:15:31 2017 +0200
@@ -26,12 +26,14 @@
     changelog,
     copies,
     crecord as crecordmod,
+    dagop,
     dirstateguard,
     encoding,
     error,
     formatter,
     graphmod,
     match as matchmod,
+    mdiff,
     obsolete,
     patch,
     pathutil,
@@ -2585,6 +2587,87 @@
 
     return revs, expr, filematcher
 
+def _parselinerangelogopt(repo, opts):
+    """Parse --line-range log option and return a list of tuples (filename,
+    (fromline, toline)).
+    """
+    linerangebyfname = []
+    for pat in opts.get('line_range', []):
+        try:
+            pat, linerange = pat.rsplit(',', 1)
+        except ValueError:
+            raise error.Abort(_('malformatted line-range pattern %s') % pat)
+        try:
+            fromline, toline = map(int, linerange.split('-'))
+        except ValueError:
+            raise error.Abort(_("invalid line range for %s") % pat)
+        msg = _("line range pattern '%s' must match exactly one file") % pat
+        fname = scmutil.parsefollowlinespattern(repo, None, pat, msg)
+        linerangebyfname.append(
+            (fname, util.processlinerange(fromline, toline)))
+    return linerangebyfname
+
+def getloglinerangerevs(repo, userrevs, opts):
+    """Return (revs, filematcher, hunksfilter).
+
+    "revs" are revisions obtained by processing "line-range" log options and
+    walking block ancestors of each specified file/line-range.
+
+    "filematcher(rev) -> match" is a factory function returning a match object
+    for a given revision for file patterns specified in --line-range option.
+    If neither --stat nor --patch options are passed, "filematcher" is None.
+
+    "hunksfilter(rev) -> filterfn(fctx, hunks)" is a factory function
+    returning a hunks filtering function.
+    If neither --stat nor --patch options are passed, "filterhunks" is None.
+    """
+    wctx = repo[None]
+
+    # Two-levels map of "rev -> file ctx -> [line range]".
+    linerangesbyrev = {}
+    for fname, (fromline, toline) in _parselinerangelogopt(repo, opts):
+        fctx = wctx.filectx(fname)
+        for fctx, linerange in dagop.blockancestors(fctx, fromline, toline):
+            rev = fctx.introrev()
+            if rev not in userrevs:
+                continue
+            linerangesbyrev.setdefault(
+                rev, {}).setdefault(
+                    fctx.path(), []).append(linerange)
+
+    filematcher = None
+    hunksfilter = None
+    if opts.get('patch') or opts.get('stat'):
+
+        def nofilterhunksfn(fctx, hunks):
+            return hunks
+
+        def hunksfilter(rev):
+            fctxlineranges = linerangesbyrev.get(rev)
+            if fctxlineranges is None:
+                return nofilterhunksfn
+
+            def filterfn(fctx, hunks):
+                lineranges = fctxlineranges.get(fctx.path())
+                if lineranges is not None:
+                    for hr, lines in hunks:
+                        if any(mdiff.hunkinrange(hr[2:], lr)
+                               for lr in lineranges):
+                            yield hr, lines
+                else:
+                    for hunk in hunks:
+                        yield hunk
+
+            return filterfn
+
+        def filematcher(rev):
+            files = list(linerangesbyrev.get(rev, []))
+            return scmutil.matchfiles(repo, files)
+
+    revs = sorted(linerangesbyrev, reverse=True)
+
+    return revs, filematcher, hunksfilter
+
 def _graphnodeformatter(ui, displayer):
     spec = ui.config('ui', 'graphnodetemplate')
     if not spec: