1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
10 BACKSLASH_ESCAPE_RE = re.compile(r'\\(.)')
12 class SubstitutionError(Exception):
26 elif state == DEFAULT:
42 raise SubstitutionError("Substitution error, mismatched parentheses {}".format(c))
46 path = os.path.join(os.environ['TASK_KEEPMOUNT'], v)
48 if st and stat.S_ISREG(st.st_mode):
51 raise SubstitutionError("$(file {}) is not accessible or is not a regular file".format(path))
54 d = os.path.dirname(v)
57 path = os.path.join(os.environ['TASK_KEEPMOUNT'], d)
59 if st and stat.S_ISDIR(st.st_mode):
62 raise SubstitutionError("$(dir {}) is not accessible or is not a directory".format(path))
65 return os.path.splitext(os.path.basename(v))[0]
70 raise SubstitutionError("$(glob {}) no match found".format(v))
74 default_subs = {"file ": sub_file,
76 "basename ": sub_basename,
79 def do_substitution(p, c, subs=default_subs):
83 return BACKSLASH_ESCAPE_RE.sub(r'\1', c)
85 v = do_substitution(p, c[m[0]+2 : m[1]])
89 r = subs[sub](v[len(sub):])
96 raise SubstitutionError("Unknown variable or function '%s' while performing substitution on '%s'" % (v, c))
98 raise SubstitutionError("Substitution for '%s' is null while performing substitution on '%s'" % (v, c))
99 if not isinstance(r, basestring):
100 raise SubstitutionError("Substitution for '%s' must be a string while performing substitution on '%s'" % (v, c))
102 c = c[:m[0]] + r + c[m[1]+1:]