Merge branch 'master' into 3644-arv-mount-projects
[arvados.git] / crunch_scripts / crunchutil / subst.py
index b3526883fcf193ff719c249a37343afe45e340e7..ff3486354f325bd478c637c29227ea012c6c0766 100644 (file)
@@ -1,6 +1,9 @@
 import os
 import glob
 
+class SubstitutionError(Exception):
+    pass
+
 def search(c):
     DEFAULT = 0
     DOLLAR = 1
@@ -28,7 +31,7 @@ def search(c):
             state = DEFAULT
         i += 1
     if depth != 0:
-        raise Exception("Substitution error, mismatched parentheses {}".format(c))
+        raise SubstitutionError("Substitution error, mismatched parentheses {}".format(c))
     return None
 
 def sub_file(v):
@@ -46,7 +49,7 @@ def sub_basename(v):
 def sub_glob(v):
     l = glob.glob(v)
     if len(l) == 0:
-        raise Exception("$(glob): No match on '%s'" % v)
+        raise SubstitutionError("$(glob): No match on '%s'" % v)
     else:
         return l[0]
 
@@ -57,19 +60,25 @@ default_subs = {"file ": sub_file,
 
 def do_substitution(p, c, subs=default_subs):
     while True:
-        #print("c is", c)
         m = search(c)
-        if m is not None:
-            v = do_substitution(p, c[m[0]+2 : m[1]])
-            var = True
-            for sub in subs:
-                if v.startswith(sub):
-                    r = subs[sub](v[len(sub):])
-                    var = False
-                    break
-            if var:
+        if m is None:
+            return c
+
+        v = do_substitution(p, c[m[0]+2 : m[1]])
+        var = True
+        for sub in subs:
+            if v.startswith(sub):
+                r = subs[sub](v[len(sub):])
+                var = False
+                break
+        if var:
+            if v in p:
                 r = p[v]
+            else:
+                raise SubstitutionError("Unknown variable or function '%s' while performing substitution on '%s'" % (v, c))
+            if r is None:
+                raise SubstitutionError("Substitution for '%s' is null while performing substitution on '%s'" % (v, c))
+            if not isinstance(r, basestring):
+                raise SubstitutionError("Substitution for '%s' must be a string while performing substitution on '%s'" % (v, c))
 
-            c = c[:m[0]] + r + c[m[1]+1:]
-        else:
-            return c
+        c = c[:m[0]] + r + c[m[1]+1:]