parseConfig.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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('__home__')>-1:
  29. x=re.sub(r'__home__',os.path.expanduser('~'),v)
  30. print('Matching home {}->{}'.format(v,x))
  31. return x
  32. if v.find('__[env]home__')>-1:
  33. x=re.sub(r'__\[env\]home__',os.path.expanduser('~'),v)
  34. print('Matching home {}->{}'.format(v,x))
  35. return x
  36. #backward compatibility where no setup is used
  37. if not setup:
  38. return v
  39. #__[setup:X]Y__ will be replaced by setup[X][Y], where X is commonly a path
  40. pattern=r'__\[setup:([^\]]*)\](.*)(?=__)__'
  41. m=re.findall(pattern,v)
  42. print(m)
  43. if len(m)==1:
  44. g=m[0]
  45. return re.sub(pattern,setup[g[0]][g[1]],v)
  46. return v
  47. def convertValues(pars):
  48. replacements={v:pars[v] for v in pars['setVariables']}
  49. return convertValuesR(pars,replacements)
  50. def convertValuesR(pars,replacements):
  51. #dict
  52. if isinstance(pars,dict):
  53. for c in pars:
  54. if c=='setVariables':
  55. continue
  56. if c in replacements:
  57. continue
  58. if isinstance(pars[c],dict):
  59. pars[c]=convertValuesR(pars[c],replacements)
  60. continue
  61. if isinstance(pars[c],list):
  62. pars[c]=[convertValuesR(x,replacements) for x in pars[c]]
  63. continue
  64. for r in replacements:
  65. pars[c]=re.sub(r,replacements[r],pars[c])
  66. return pars
  67. #list
  68. if isinstance(pars,list):
  69. return [convertValuesR(x,replacements) for x in pars]
  70. #value/leaf
  71. for r in replacements:
  72. pars=re.sub(r,replacements[r],pars)
  73. return pars