Skip to content

Commit 07b86c7

Browse files
authored
Merge branch 'main' into yaml_remove
Signed-off-by: Derek Hower <[email protected]>
2 parents 9db188b + 2689ee0 commit 07b86c7

File tree

2 files changed

+59
-8
lines changed

2 files changed

+59
-8
lines changed

lib/test/test_yaml_loader.rb

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
class TestYamlLoader < Minitest::Test
99

10+
1011
def test_remove
1112
yaml = <<~YAML
1213
base:
@@ -41,7 +42,7 @@ def test_multiple_remove
4142
- key3
4243
key4: value4
4344
YAML
44-
45+
4546
f = Tempfile.new("yml")
4647
f.write(yaml)
4748
f.flush
@@ -50,6 +51,37 @@ def test_multiple_remove
5051
assert_equal({ "key1" => "value1", "key4" => "value4" }, doc["child"])
5152
end
5253

54+
def test_that_mref_with_nested_replace_works
55+
yaml = <<~YAML
56+
base:
57+
key1:
58+
sub_key1: value1
59+
key2: value2
60+
61+
middle:
62+
$mref: "#/base"
63+
key3: value3
64+
key4: value4
65+
66+
bottom:
67+
$mref:
68+
- "#/base"
69+
- "#/middle"
70+
key1:
71+
sub_key6: value6
72+
key2: value2_new
73+
key4: value4_new
74+
key5: value5
75+
YAML
76+
77+
f = Tempfile.new("yml")
78+
f.write(yaml)
79+
f.flush
80+
81+
doc = YamlLoader.load(f.path)
82+
assert_equal({ "key1" => {"sub_key1" => "value1", "sub_key6" => "value6"}, "key2" => "value2_new", "key3" => "value3", "key4" => "value4_new", "key5" => "value5" }, doc["bottom"])
83+
end
84+
5385
def test_that_spurious_recursive_mref_works
5486
yaml = <<~YAML
5587
base:

lib/yaml_loader.rb

Lines changed: 26 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -75,19 +75,38 @@ def self.expand(filename, obj, yaml_opts = {})
7575

7676
target_obj = expand(filename, target_obj, yaml_opts)
7777
target_obj.each do |target_key, target_value|
78-
new_obj[target_key] = target_value
78+
if (new_obj[target_key].is_a?(Hash))
79+
raise "Should be a hash" unless target_value.is_a?(Hash)
80+
new_obj[target_key] = target_value.merge(new_obj[target_key])
81+
else
82+
new_obj[target_key] = target_value
83+
end
7984
end
8085
end
8186

8287
obj.delete("$mref")
83-
obj_keys = obj.keys
84-
obj_keys.each do |key|
85-
value = obj[key]
86-
87-
new_obj[key] = expand(filename, value, yaml_opts)
88+
# now merge target_obj and obj
89+
keys = (obj.keys + new_obj.keys).uniq
90+
final_obj = {}
91+
keys.each do |key|
92+
if !obj.key?(key)
93+
final_obj[key] = new_obj[key]
94+
elsif !new_obj.key?(key)
95+
final_obj[key] = expand(filename, obj[key], yaml_opts)
96+
else
97+
value = obj[key]
98+
99+
if new_obj[key].is_a?(Hash)
100+
raise "should be a hash" unless new_obj[key].is_a?(Hash)
101+
final_obj[key] = new_obj[key].merge(obj[key])
102+
else
103+
final_obj[key] = expand(filename, obj[key], yaml_opts)
104+
end
105+
end
88106
end
89107

90-
new_obj
108+
final_obj
109+
91110
else
92111
obj_keys = obj.keys
93112
obj_keys.each do |key|

0 commit comments

Comments
 (0)