Pārlūkot izejas kodu

Adding __[setup:X]Y__ pattern

Andrej 1 gadu atpakaļ
vecāks
revīzija
fc6820e1eb
3 mainītis faili ar 53 papildinājumiem un 23 dzēšanām
  1. 50 20
      parseConfig.py
  2. 1 1
      pythonScripts/convertValues.py
  3. 2 2
      template/testCfg.json

+ 50 - 20
parseConfig.py

@@ -4,27 +4,57 @@ import sys
 import os
 
 #first pass
-def convert(fo):
+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
-
-    #convert core variables
-    if 'setVariables' in fo:
-        for v in fo['setVariables']:
-            if fo[v].find('__home__')>-1:
-                fo[v]=re.sub('__home__',os.path.expanduser('~'),fo[v])
-    #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
+   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('__[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']}

+ 1 - 1
pythonScripts/convertValues.py

@@ -15,7 +15,7 @@ def main(parameterFile):
     with open(parameterFile,'r') as f:
         pars=json.load(f)
 
-    pars=parseConfig.convert(pars)
+    pars=parseConfig.convert(pars,setup)
     print(pars)
     pars=parseConfig.convertValues(pars)
     print(pars)

+ 2 - 2
template/testCfg.json

@@ -1,6 +1,6 @@
 {"setVariables":["__temp__","__true__"],
-"__temp__":"__home__/temp",
-"__true__":"T",
+"__temp__":"__[env]home__/temp",
+"__true__":"__[setup:paths]matlab__/parseConfig",
 "A":{
 	"cfg":"__temp__/testCfg.json",
 	"t":"__true__"