changeset 45308:dc10bcd5c08d

templater: start passing resource to read from into _readmapfile() This patch makes it so we pass in a file-like resource to read from instead of having `_readmapfile()` open the file. This is one more step towards making `_readmapfile()` able to read resources opened by from `importlib.resources`. We still need to pass in the mapfile path because it's used for loading dependent mapfiles from `%include` and `__base__`, and it's also used for giving the user better error messages. Besides that, one can safely call `_readmapfile()` with any file-like resource after this patch. Differential Revision: https://phab.mercurial-scm.org/D8891
author Martin von Zweigbergk <martinvonz@google.com>
date Thu, 30 Jul 2020 13:44:06 -0700
parents ba50c8a95e2b
children 65a812ed9e9f
files mercurial/templater.py
diffstat 1 files changed, 15 insertions(+), 10 deletions(-) [+]
line wrap: on
line diff
--- a/mercurial/templater.py	Tue Aug 04 09:13:10 2020 -0700
+++ b/mercurial/templater.py	Thu Jul 30 13:44:06 2020 -0700
@@ -814,14 +814,17 @@
     return b", ".join(sorted(stylelist))
 
 
-def _readmapfile(mapfile):
+def _open_mapfile(mapfile):
+    if os.path.exists(mapfile):
+        return util.posixfile(mapfile, b'rb')
+    raise error.Abort(
+        _(b"style '%s' not found") % mapfile,
+        hint=_(b"available styles: %s") % stylelist(),
+    )
+
+
+def _readmapfile(fp, mapfile):
     """Load template elements from the given map file"""
-    if not os.path.exists(mapfile):
-        raise error.Abort(
-            _(b"style '%s' not found") % mapfile,
-            hint=_(b"available styles: %s") % stylelist(),
-        )
-
     base = os.path.dirname(mapfile)
     conf = config.config()
 
@@ -838,7 +841,7 @@
                 )
                 break
 
-    data = util.posixfile(mapfile, b'rb').read()
+    data = fp.read()
     conf.parse(mapfile, data, remap={b'': b'templates'}, include=include)
 
     cache = {}
@@ -862,7 +865,8 @@
                     if os.path.isfile(p3):
                         path = p3
 
-        cache, tmap, aliases = _readmapfile(path)
+        fp = _open_mapfile(path)
+        cache, tmap, aliases = _readmapfile(fp, path)
 
     for key, val in conf[b'templates'].items():
         if not val:
@@ -999,7 +1003,8 @@
     ):
         """Create templater from the specified map file"""
         t = cls(filters, defaults, resources, cache, [], minchunk, maxchunk)
-        cache, tmap, aliases = _readmapfile(mapfile)
+        fp = _open_mapfile(mapfile)
+        cache, tmap, aliases = _readmapfile(fp, mapfile)
         t._loader.cache.update(cache)
         t._loader._map = tmap
         t._loader._aliasmap = _aliasrules.buildmap(aliases)