symbian-qemu-0.9.1-12/python-2.6.1/Tools/modulator/varsubst.py
changeset 1 2fb8b9db1c86
equal deleted inserted replaced
0:ffa851df0825 1:2fb8b9db1c86
       
     1 #
       
     2 # Variable substitution. Variables are $delimited$
       
     3 #
       
     4 import re
       
     5 
       
     6 error = 'varsubst.error'
       
     7 
       
     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
       
    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 
       
    44 def _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 
       
    55 if __name__ == '__main__':
       
    56     _test()