parseConfig.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import json
  2. import re
  3. import sys
  4. import os
  5. #first pass
  6. def convert(fo,setup=None):
  7. #take RHS values that will be used later on and replace common patterns with replacePattern
  8. #patterns are defined in replacePattern
  9. if not isinstance(fo,dict):
  10. return fo
  11. if 'setVariables' in fo:
  12. for v in fo['setVariables']:
  13. fo[v]=replacePattern(fo[v],setup)
  14. #descend
  15. for c in fo:
  16. if c=='setVariables':
  17. continue
  18. if isinstance(fo[c],dict):
  19. fo[c]=convert(fo[c])
  20. continue
  21. if isinstance(fo[c],list):
  22. fo[c]=[convert(x) for x in fo[c]]
  23. continue
  24. return fo
  25. def replacePattern(v,setup=None):
  26. print('Replacing v={}'.format(v))
  27. #local HOME variable of the user executing the code
  28. if v.find('__[env]home__')>-1:
  29. x=re.sub(r'__\[env\]home__',os.path.expanduser('~'),v)
  30. print('Matching home {}->{}'.format(v,x))
  31. return x
  32. #backward compatibility where no setup is used
  33. if not setup:
  34. return v
  35. #__[setup:X]Y__ will be replaced by setup[X][Y], where X is commonly a path
  36. pattern=r'__\[setup:([^\]]*)\](.*)(?=__)__'
  37. m=re.findall(pattern,v)
  38. print(m)
  39. if len(m)==1:
  40. g=m[0]
  41. return re.sub(pattern,setup[g[0]][g[1]],v)
  42. return v
  43. def convertValues(pars):
  44. replacements={v:pars[v] for v in pars['setVariables']}
  45. return convertValuesR(pars,replacements)
  46. def convertValuesR(pars,replacements):
  47. #dict
  48. if isinstance(pars,dict):
  49. for c in pars:
  50. if c=='setVariables':
  51. continue
  52. if c in replacements:
  53. continue
  54. if isinstance(pars[c],dict):
  55. pars[c]=convertValuesR(pars[c],replacements)
  56. continue
  57. if isinstance(pars[c],list):
  58. pars[c]=[convertValuesR(x,replacements) for x in pars[c]]
  59. continue
  60. for r in replacements:
  61. pars[c]=re.sub(r,replacements[r],pars[c])
  62. return pars
  63. #list
  64. if isinstance(pars,list):
  65. return [convertValuesR(x,replacements) for x in pars]
  66. #value/leaf
  67. for r in replacements:
  68. pars=re.sub(r,replacements[r],pars)
  69. return pars