Mercurial > public > mercurial-scm > hg-stable
comparison 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 |
comparison
equal
deleted
inserted
replaced
11985:81edef14922e | 11988:8380ed691df8 |
---|---|
1406 try: | 1406 try: |
1407 return int(os.environ['COLUMNS']) | 1407 return int(os.environ['COLUMNS']) |
1408 except ValueError: | 1408 except ValueError: |
1409 pass | 1409 pass |
1410 return termwidth_() | 1410 return termwidth_() |
1411 | |
1412 def interpolate(prefix, mapping, s, fn=None): | |
1413 """Return the result of interpolating items in the mapping into string s. | |
1414 | |
1415 prefix is a single character string, or a two character string with | |
1416 a backslash as the first character if the prefix needs to be escaped in | |
1417 a regular expression. | |
1418 | |
1419 fn is an optional function that will be applied to the replacement text | |
1420 just before replacement. | |
1421 """ | |
1422 fn = fn or (lambda s: s) | |
1423 r = re.compile(r'%s(%s)' % (prefix, '|'.join(mapping.keys()))) | |
1424 return r.sub(lambda x: fn(mapping[x.group()[1:]]), s) | |
1425 |