Patchwork [3,of,6] templater: add function to help substituting patterns in template string

login
register
mail settings
Submitter Yuya Nishihara
Date Feb. 15, 2018, 1:18 p.m.
Message ID <5a8caa27847f9b8f0405.1518700721@mimosa>
Download mbox | patch
Permalink /patch/27969/
State Accepted
Headers show

Comments

Yuya Nishihara - Feb. 15, 2018, 1:18 p.m.
# HG changeset patch
# User Yuya Nishihara <yuya@tcha.org>
# Date 1515291685 -32400
#      Sun Jan 07 11:21:25 2018 +0900
# Node ID 5a8caa27847f9b8f040589ed182522904f8a9574
# Parent  edc874f03cf670040c4a3cfc257fec1a171e0da6
templater: add function to help substituting patterns in template string

This will be used to rewrite a filename pattern to a template string.

Patch

diff --git a/mercurial/templater.py b/mercurial/templater.py
--- a/mercurial/templater.py
+++ b/mercurial/templater.py
@@ -172,6 +172,26 @@  def _parsetemplate(tmpl, start, stop, qu
             raise error.ProgrammingError('unexpected type: %s' % typ)
     raise error.ProgrammingError('unterminated scanning of template')
 
+def scantemplate(tmpl):
+    """Scan (type, start, end) positions of outermost elements in template
+
+    >>> list(scantemplate(b'foo{bar}"baz'))
+    [('string', 0, 3), ('template', 3, 8), ('string', 8, 12)]
+    >>> list(scantemplate(b'outer{"inner"}outer'))
+    [('string', 0, 5), ('template', 5, 14), ('string', 14, 19)]
+    >>> list(scantemplate(b'foo\\{escaped}'))
+    [('string', 0, 5), ('string', 5, 13)]
+    """
+    last = None
+    for typ, val, pos in _scantemplate(tmpl, 0, len(tmpl)):
+        if last:
+            yield last + (pos,)
+        if typ == 'end':
+            return
+        else:
+            last = (typ, pos)
+    raise error.ProgrammingError('unterminated scanning of template')
+
 def _scantemplate(tmpl, start, stop, quote=''):
     """Parse template string into chunks of strings and template expressions"""
     sepchars = '{' + quote