Skip to content

Commit 74cebf0

Browse files
authored
Merge pull request #252 from riscv-software-src/yaml_remove
Add $remove to YamlLoader
2 parents 2689ee0 + 07b86c7 commit 74cebf0

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

lib/test/test_yaml_loader.rb

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,50 @@
77

88
class TestYamlLoader < Minitest::Test
99

10+
11+
def test_remove
12+
yaml = <<~YAML
13+
base:
14+
key1: value1
15+
key2: value2
16+
17+
child:
18+
$mref: "#/base"
19+
$remove: key2
20+
key3: value3
21+
YAML
22+
23+
f = Tempfile.new("yml")
24+
f.write(yaml)
25+
f.flush
26+
27+
doc = YamlLoader.load(f.path)
28+
assert_equal({ "key1" => "value1", "key3" => "value3" }, doc["child"])
29+
end
30+
31+
def test_multiple_remove
32+
yaml = <<~YAML
33+
base:
34+
key1: value1
35+
key2: value2
36+
key3: value3
37+
38+
child:
39+
$mref: "#/base"
40+
$remove:
41+
- key2
42+
- key3
43+
key4: value4
44+
YAML
45+
46+
f = Tempfile.new("yml")
47+
f.write(yaml)
48+
f.flush
49+
50+
doc = YamlLoader.load(f.path)
51+
assert_equal({ "key1" => "value1", "key4" => "value4" }, doc["child"])
52+
end
53+
1054
def test_that_mref_with_nested_replace_works
1155
yaml = <<~YAML
1256
base:

lib/yaml_loader.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ def self.expand(filename, obj, yaml_opts = {})
1414

1515
return obj.map { |v| expand(filename, v, yaml_opts) } if obj.is_a?(Array)
1616

17+
new_obj =
1718
if obj.keys.include?("$ref")
1819
# according JSON Reference, all keys except $ref are ignored
1920
relative_path = obj["$ref"].split("#")[0]
@@ -103,7 +104,9 @@ def self.expand(filename, obj, yaml_opts = {})
103104
end
104105
end
105106
end
107+
106108
final_obj
109+
107110
else
108111
obj_keys = obj.keys
109112
obj_keys.each do |key|
@@ -113,6 +116,16 @@ def self.expand(filename, obj, yaml_opts = {})
113116
end
114117
obj
115118
end
119+
120+
obj_keys = new_obj.keys
121+
if obj_keys.include? "$remove"
122+
remove_keys = obj["$remove"].is_a?(Array) ? obj["$remove"] : [obj["$remove"]]
123+
remove_keys.each do |key|
124+
new_obj.delete(key)
125+
end
126+
end
127+
new_obj.delete("$remove")
128+
new_obj
116129
end
117130

118131
# load a YAML file and expand any $ref/$mref references

0 commit comments

Comments
 (0)