From dde0a3ef3b88eb79bff8a36943cf934452eb8c26 Mon Sep 17 00:00:00 2001 From: Ned Batchelder Date: Sat, 8 Sep 2018 16:17:09 -0400 Subject: Move variable substitution to be independent --- coverage/misc.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) (limited to 'coverage/misc.py') diff --git a/coverage/misc.py b/coverage/misc.py index ab950846..e2031852 100644 --- a/coverage/misc.py +++ b/coverage/misc.py @@ -8,6 +8,7 @@ import hashlib import inspect import locale import os +import re import sys import types @@ -250,6 +251,42 @@ def _needs_to_implement(that, func_name): ) +def substitute_variables(text, variables=os.environ): + """Substitute ``${VAR}`` variables in `text` with their values. + + Variables in the text can take a number of shell-inspired forms:: + + $VAR + ${VAR} + + A dollar can be inserted with ``$$``. + + `variables` is a dictionary of variable values, defaulting to the + environment variables. + + Returns the resulting text with values substituted. + + """ + def dollar_replace(m): + """Called for each $replacement.""" + # Only one of the groups will have matched, just get its text. + word = next(w for w in m.groups() if w is not None) # pragma: part covered + if word == "$": + return "$" + else: + return variables.get(word, '') + + dollar_pattern = r"""(?x) # Use extended regex syntax + \$(?: # A dollar sign, then + (?P\w+) | # a plain word, + {(?P\w+)} | # or a {-wrapped word, + (?P[$]) # or a dollar sign. + ) + """ + text = re.sub(dollar_pattern, dollar_replace, text) + return text + + class BaseCoverageException(Exception): """The base of all Coverage exceptions.""" pass -- cgit v1.2.1