Mercurial > public > mercurial-scm > hg
diff mercurial/util.py @ 11988:8380ed691df8
util: add an interpolate() function to for replacing multiple values
util.interpolate can be used to replace multiple items in a string all at once
(and optionally apply a function to the replacement), without worrying about
recursing:
>>> import util
>>> s = '$foo, $spam'
>>> util.interpolate(r'\$', { 'foo': 'bar', 'spam': 'eggs' }, s)
'bar, eggs'
>>> util.interpolate(r'\$', { 'foo': 'spam', 'spam': 'foo' }, s)
'spam, foo'
>>> util.interpolate(r'\$', { 'foo': 'spam', 'spam': 'foo' }, s, lambda s: s.upper())
'SPAM, FOO'
The patch also changes filemerge.py to use this new function.
author | Steve Losh <steve@stevelosh.com> |
---|---|
date | Wed, 18 Aug 2010 18:18:26 -0400 |
parents | 851161f07068 |
children | ad787252fed6 |
line wrap: on
line diff
--- a/mercurial/util.py Thu Aug 19 11:14:09 2010 -0500 +++ b/mercurial/util.py Wed Aug 18 18:18:26 2010 -0400 @@ -1408,3 +1408,18 @@ except ValueError: pass return termwidth_() + +def interpolate(prefix, mapping, s, fn=None): + """Return the result of interpolating items in the mapping into string s. + + prefix is a single character string, or a two character string with + a backslash as the first character if the prefix needs to be escaped in + a regular expression. + + fn is an optional function that will be applied to the replacement text + just before replacement. + """ + fn = fn or (lambda s: s) + r = re.compile(r'%s(%s)' % (prefix, '|'.join(mapping.keys()))) + return r.sub(lambda x: fn(mapping[x.group()[1:]]), s) +