PageRenderTime 81ms CodeModel.GetById 40ms app.highlight 6ms RepoModel.GetById 34ms app.codeStats 0ms

/Tools/modulator/varsubst.py

http://unladen-swallow.googlecode.com/
Python | 56 lines | 49 code | 4 blank | 3 comment | 0 complexity | ee89d8aab33ed27dad49f05e55b72935 MD5 | raw file
 1#
 2# Variable substitution. Variables are $delimited$
 3#
 4import re
 5
 6error = 'varsubst.error'
 7
 8class Varsubst:
 9    def __init__(self, dict):
10        self.dict = dict
11        self.prog = re.compile('\$([a-zA-Z0-9_]*)\$')
12        self.do_useindent = 0
13
14    def useindent(self, onoff):
15        self.do_useindent = onoff
16
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
37
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)
43
44def _test():
45    import sys
46    import os
47
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)
54
55if __name__ == '__main__':
56    _test()