Remove use of tuple unpacking and dict.has_key() so as to silence
[python.git] / Tools / modulator / varsubst.py
blob3b33950650be7440380e1469450173c69c8fbc62
2 # Variable substitution. Variables are $delimited$
4 import re
6 error = 'varsubst.error'
8 class Varsubst:
9 def __init__(self, dict):
10 self.dict = dict
11 self.prog = re.compile('\$([a-zA-Z0-9_]*)\$')
12 self.do_useindent = 0
14 def useindent(self, onoff):
15 self.do_useindent = onoff
17 def subst(self, s):
18 rv = ''
19 while 1:
20 m = self.prog.search(s)
21 if not m:
22 return rv + s
23 rv = rv + s[:m.start()]
24 s = s[m.end():]
25 if m.end() - m.start() == 2:
26 # Escaped dollar
27 rv = rv + '$'
28 s = s[2:]
29 continue
30 name = m.group(1)
31 if not self.dict.has_key(name):
32 raise error, 'No such variable: '+name
33 value = self.dict[name]
34 if self.do_useindent and '\n' in value:
35 value = self._modindent(value, rv)
36 rv = rv + value
38 def _modindent(self, value, old):
39 lastnl = old.rfind('\n', 0) + 1
40 lastnl = len(old) - lastnl
41 sub = '\n' + (' '*lastnl)
42 return re.sub('\n', sub, value)
44 def _test():
45 import sys
46 import os
48 sys.stderr.write('-- Copying stdin to stdout with environment map --\n')
49 c = Varsubst(os.environ)
50 c.useindent(1)
51 d = sys.stdin.read()
52 sys.stdout.write(c.subst(d))
53 sys.exit(1)
55 if __name__ == '__main__':
56 _test()