Skip to content

Commit 651a59e

Browse files
authored
adding the resolve method to resolve substitution keys in 1 config tree with another config tree (#266)
1 parent 32f5f57 commit 651a59e

File tree

2 files changed

+55
-1
lines changed

2 files changed

+55
-1
lines changed

pyhocon/config_tree.py

+26
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,32 @@ def merge_configs(a, b, copy_trees=False):
6767

6868
return a
6969

70+
71+
def resolve(self, other):
72+
"""Merge config b into a
73+
:param self: target config
74+
:type self: ConfigTree
75+
:param other: providing config
76+
:type other: ConfigTree
77+
:return: resolved config
78+
"""
79+
copyA = copy.deepcopy(self)
80+
def loop(tree):
81+
for key, value in tree.items():
82+
if isinstance(value, ConfigTree):
83+
loop(tree[key])
84+
else:
85+
if isinstance(value, ConfigValues):
86+
for token in value.tokens:
87+
if isinstance(token, ConfigSubstitution):
88+
v = other.get(token.variable, NoneValue)
89+
if v is not None:
90+
tree[key] = copy.deepcopy(v)
91+
if isinstance(tree[key], ConfigTree):
92+
tree[key].parent = tree
93+
return tree
94+
return loop(copyA)
95+
7096
def _put(self, key_path, value, append=False):
7197
key_elt = key_path[0]
7298
if len(key_path) == 1:

tests/test_config_tree.py

+29-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from pyhocon.config_tree import ConfigTree, NoneValue
44
from pyhocon.exceptions import (
55
ConfigMissingException, ConfigWrongTypeException, ConfigException)
6-
from pyhocon.config_parser import ConfigFactory
6+
from pyhocon.config_parser import ConfigFactory, NO_SUBSTITUTION
77
from pyhocon.tool import HOCONConverter
88

99

@@ -322,3 +322,31 @@ def test_config_tree_special_characters(self):
322322
assert escaped_key in hocon_tree
323323
parsed_tree = ConfigFactory.parse_string(hocon_tree)
324324
assert parsed_tree.get(key) == "value"
325+
326+
def test_config_tree_resolve(self):
327+
config = ConfigFactory.parse_string(
328+
"""
329+
a = ${sub}
330+
nested {
331+
value = ${nested.sub}
332+
}
333+
""",
334+
resolve = False
335+
)
336+
337+
substitudeConfig = ConfigFactory.parse_string(
338+
"""
339+
sub = 100
340+
nested {
341+
sub = {
342+
a: "string"
343+
b: 10
344+
}
345+
}
346+
"""
347+
)
348+
result = config.resolve(substitudeConfig)
349+
assert result.get_int('a') == 100
350+
assert result.get_string('nested.value.a') == "string"
351+
assert result.get_int('nested.value.b') == 10
352+
assert config != result

0 commit comments

Comments
 (0)