1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- import json
- import re
- import sys
- import os
- #first pass
- def convert(fo,setup=None):
- #take RHS values that will be used later on and replace common patterns with replacePattern
- #patterns are defined in replacePattern
-
- if not isinstance(fo,dict):
- return fo
- if 'setVariables' in fo:
- for v in fo['setVariables']:
- fo[v]=replacePattern(fo[v],setup)
- #descend
- for c in fo:
- if c=='setVariables':
- continue
- if isinstance(fo[c],dict):
- fo[c]=convert(fo[c])
- continue
- if isinstance(fo[c],list):
- fo[c]=[convert(x) for x in fo[c]]
- continue
- return fo
- def replacePattern(v,setup=None):
- print('Replacing v={}'.format(v))
- #local HOME variable of the user executing the code
- if v.find('__home__')>-1:
- x=re.sub(r'__home__',os.path.expanduser('~'),v)
- print('Matching home {}->{}'.format(v,x))
- return x
- if v.find('__[env]home__')>-1:
- x=re.sub(r'__\[env\]home__',os.path.expanduser('~'),v)
- print('Matching home {}->{}'.format(v,x))
- return x
-
-
- #backward compatibility where no setup is used
- if not setup:
- return v
- #__[setup:X]Y__ will be replaced by setup[X][Y], where X is commonly a path
- pattern=r'__\[setup:([^\]]*)\](.*)(?=__)__'
- m=re.findall(pattern,v)
- print(m)
- if len(m)==1:
- g=m[0]
- return re.sub(pattern,setup[g[0]][g[1]],v)
- return v
- def convertValues(pars):
- replacements={v:pars[v] for v in pars['setVariables']}
- return convertValuesR(pars,replacements)
- def convertValuesR(pars,replacements):
- #dict
- if isinstance(pars,dict):
- for c in pars:
- if c=='setVariables':
- continue
- if c in replacements:
- continue
- if isinstance(pars[c],dict):
- pars[c]=convertValuesR(pars[c],replacements)
- continue
- if isinstance(pars[c],list):
- pars[c]=[convertValuesR(x,replacements) for x in pars[c]]
- continue
- for r in replacements:
- try:
- pars[c]=re.sub(r,replacements[r],pars[c])
- except TypeError:
- #direct values (int, etc.) don't work with regexp, but they don't need replacements anyhow
- pass
- return pars
- #list
- if isinstance(pars,list):
- return [convertValuesR(x,replacements) for x in pars]
- #value/leaf
- for r in replacements:
- pars=re.sub(r,replacements[r],pars)
- return pars
|