Ditched '_find_SET()', since it was a no-value-added wrapper around
[python/dscho.git] / Tools / modulator / varsubst.py
blob06e9683a4785360edc4bee57255292157494a8b3
2 # Variable substitution. Variables are $delimited$
4 import string
5 import regex
6 import regsub
8 error = 'varsubst.error'
10 class Varsubst:
11 def __init__(self, dict):
12 self.dict = dict
13 self.prog = regex.compile('\$[a-zA-Z0-9_]*\$')
14 self.do_useindent = 0
16 def useindent(self, onoff):
17 self.do_useindent = onoff
19 def subst(self, str):
20 rv = ''
21 while 1:
22 pos = self.prog.search(str)
23 if pos < 0:
24 return rv + str
25 if pos:
26 rv = rv + str[:pos]
27 str = str[pos:]
28 len = self.prog.match(str)
29 if len == 2:
30 # Escaped dollar
31 rv = rv + '$'
32 str = str[2:]
33 continue
34 name = str[1:len-1]
35 str = str[len:]
36 if not self.dict.has_key(name):
37 raise error, 'No such variable: '+name
38 value = self.dict[name]
39 if self.do_useindent and '\n' in value:
40 value = self._modindent(value, rv)
41 rv = rv + value
43 def _modindent(self, value, old):
44 lastnl = string.rfind(old, '\n', 0) + 1
45 lastnl = len(old) - lastnl
46 sub = '\n' + (' '*lastnl)
47 return regsub.gsub('\n', sub, value)
49 def _test():
50 import sys
51 import os
53 sys.stderr.write('-- Copying stdin to stdout with environment map --\n')
54 c = Varsubst(os.environ)
55 c.useindent(1)
56 d = sys.stdin.read()
57 sys.stdout.write(c.subst(d))
58 sys.exit(1)
60 if __name__ == '__main__':
61 _test()