[PATCH] templater: add 'env()' to fetch environment variables

Matt Harbison mharbison72 at gmail.com
Sun Jan 15 20:30:56 UTC 2017


# HG changeset patch
# User Matt Harbison <matt_harbison at yahoo.com>
# Date 1484508143 18000
#      Sun Jan 15 14:22:23 2017 -0500
# Node ID 2ba757de67ce1347d088a4d9f947efe5d407ffdd
# Parent  4c0a5a256ae806fab18d56b3c44a8d1c98a40ce0
templater: add 'env()' to fetch environment variables

Template files ignore custom items in [templates] and [templatealias]
(presumably by design).  We have a couple repositories that host multiple
products, and use tags consisting of product, OS, and version.  The {latesttag}
template supports a filtering pattern, but I didn't see any other way to get the
customized pattern per product/OS into the file, without duplicating the file
for each combination.  (Yes, there is %include, but letting the build system
supply this missing piece means the template file doesn't need maintenance as
products come and go.)

diff --git a/mercurial/templater.py b/mercurial/templater.py
--- a/mercurial/templater.py
+++ b/mercurial/templater.py
@@ -14,6 +14,7 @@
 from .i18n import _
 from . import (
     config,
+    encoding,
     error,
     minirst,
     parser,
@@ -505,6 +506,20 @@
 
     return ''.join(chunks)
 
+ at templatefunc('env([var])')
+def env(context, mapping, args):
+    """A dictionary of environment variables, or the value of the single named
+    variable."""
+    if len(args) > 1:
+        # i18n: "env" is a keyword
+        raise error.ParseError(_("env expects at most one argument"))
+
+    if len(args) == 0:
+        return encoding.environ
+
+    raw = evalstring(context, mapping, args[0])
+    return pycompat.osgetenv(raw)
+
 @templatefunc('files(pattern)')
 def files(context, mapping, args):
     """All files of the current changeset matching the pattern. See
diff --git a/tests/test-tag.t b/tests/test-tag.t
--- a/tests/test-tag.t
+++ b/tests/test-tag.t
@@ -468,6 +468,10 @@
   T: t6, C: 2, D: 2
   $ hg log -r . -T '{join(latesttag(), "*")}\n'
   t4*t6
+  $ pattern='t4' hg log -r '.' -T "{latesttag(env('pattern')) % 'T: {tag}\n'}"
+  T: t4
+  $ pattern='t4' hg log -r '.' -T "{latesttag(get(env(),'pattern')) % 'T: {tag}\n'}"
+  T: t4
   $ hg ci -A -m4
   adding f4
   $ hg log -r 'wdir()' -T "{changessincelatesttag} changes since {latesttag}\n"


More information about the Mercurial-devel mailing list