Repository navigation
Expand file tree
/
Copy pathStringInterPolationExample.py
More file actions
82 lines (77 loc) · 2.61 KB
/
Copy pathStringInterPolationExample.py
File metadata and controls
82 lines (77 loc) · 2.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# I just wrote two functions to do this
# Once I read the config file, I provide the config object as the input to the second function pasted here.
This would look like this:
self.config = self.get_config("config_file.cfg")
self.config = self.search_and_realize_references(config=self.config)
"""
# ---------------------------- Config File reference automation ------------------------------- #
"""
Class StringInterpolation(object):
def init(self, config_file):
self.config = self.get_config(config_file)
self.config = self.search_and_realize_references(config=self.config)
def find_reference_vals(self, st):
"""
st is a string that may contain multiple references
:param st: <string>
:return: list
"""
strng_replacement = 0
refs_in_str = re.findall(r'\${.+?}', st)
if refs_in_str == []:
return [st]
new_refs_in_str = []
for ref in refs_in_str:
ref1 = ref[2:-1]
ref_keys = ref1.split('.')
max_depth = len(ref_keys)
pre_text = self.config
if max_depth == 1:
new_refs_in_str.append(self.config[ref1])
for i in ref_keys:
if type(pre_text) == dict or 'configobj' in str(type(pre_text)):
if i in pre_text.keys():
pre_text = pre_text[i]
elif type(pre_text) == list:
try:
if int(i) in range(len(pre_text)):
pre_text = pre_text[int(i)]
except Exception as e:
self.logger.error("the list key should have integers as extension")
self.logger.error(e)
sys.exit(1)
else:
self.logger.error("Malformed references spotted in the config file")
self.logger.error(ref)
sys.exit(1)
if ref != st and ref in st:
if type(pre_text)== str:
st = st.replace(ref, pre_text, 1)
strng_replacement += 1
else:
error_warn = "Type of the Value {} for the reference_key {} can not be " \
"concatenated with string: {}".format(pre_text, ref, st)
self.logger.error(error_warn)
sys.exit(1)
else:
new_refs_in_str.append(pre_text)
if strng_replacement !=0:
new_refs_in_str.append(st)
return new_refs_in_str
def search_and_realize_references(self, config):
"""
takes in a config file
finds if there are any references ... which has format: ${references}
:param config:
:return:
"""
if isinstance(config, dict):
for k, v in config.iteritems():
config[k] = self.search_and_realize_references(v)
elif isinstance(config, list):
for elem in config:
self.search_and_realize_references(elem)
else:
config = self.find_reference_vals(st=config)[0]
# self.logger.info("All references mapped to the actual values in the Config File")
return config