parseConfig.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. try:
  66. pars[c]=re.sub(r,replacements[r],pars[c])
  67. except TypeError:
  68. #direct values (int, etc.) don't work with regexp, but they don't need replacements anyhow
  69. pass
  70. return pars
  71. #list
  72. if isinstance(pars,list):
  73. return [convertValuesR(x,replacements) for x in pars]
  74. #value/leaf
  75. for r in replacements:
  76. pars=re.sub(r,replacements[r],pars)
  77. return pars