# HG changeset patch # User Steve Losh # Date 2010-08-18 22:18:26 # Node ID 8380ed691df862dd5b1e4fce600b20f959254c1e # Parent 81edef14922e704d9efb75aa20850f000baf2ed6 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. diff --git a/mercurial/filemerge.py b/mercurial/filemerge.py --- a/mercurial/filemerge.py +++ b/mercurial/filemerge.py @@ -222,8 +222,8 @@ def filemerge(repo, mynode, orig, fcd, f if "$output" in args: out, a = a, back # read input from backup, write to original replace = dict(local=a, base=b, other=c, output=out) - args = re.sub("\$(local|base|other|output)", - lambda x: '"%s"' % util.localpath(replace[x.group()[1:]]), args) + args = util.interpolate(r'\$', replace, args, + lambda s: '"%s"' % util.localpath(s)) r = util.system(toolpath + ' ' + args, cwd=repo.root, environ=env) if not r and (_toolbool(ui, tool, "checkconflicts") or diff --git a/mercurial/util.py b/mercurial/util.py --- a/mercurial/util.py +++ b/mercurial/util.py @@ -1408,3 +1408,18 @@ def termwidth(): 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) +