diff --git a/lib/kubetruth/template.rb b/lib/kubetruth/template.rb index 01bcdec..45729ad 100644 --- a/lib/kubetruth/template.rb +++ b/lib/kubetruth/template.rb @@ -148,7 +148,6 @@ def deflate(hash, delimiter='.') return result end - def inflate(map, delimiter='\.') result = {} map.each do |k, v| @@ -166,12 +165,22 @@ def inflate(map, delimiter='\.') result end - def typify(data) + def typify(data, parser="json") case data when Hash Hash[data.collect {|k,v| [k, typify(v)] }] when Array data.collect {|v| typify(v) } + when /^\s*\[.*\]\s*$/, /^\s*\{.*\}\s*$/ + parsed = case parser + when /json/i + JSON.load(data) + when /ya?ml/i + YAML.load(data) + else + raise "Invalid typify parser" + end + typify(parsed) when /^[0-9]+$/ data.to_i when /^[0-9\.]+$/ @@ -183,6 +192,21 @@ def typify(data) end end + def mconcat(lhs_map, rhs_map) + lhs_map.merge(rhs_map) + end + + REGEXP_FLAGS = { + 'i' => Regexp::IGNORECASE, + 'm' => Regexp::MULTILINE, + 'e' => Regexp::EXTENDED + } + + def re_replace(string, pattern, replacement, flags="") + allflags = flags.chars.inject(0) {|sum, n| sum | REGEXP_FLAGS[n] } + string.gsub(Regexp.new(pattern, allflags), replacement) + end + end Liquid::Template.register_filter(CustomLiquidFilters) diff --git a/spec/kubetruth/template_spec.rb b/spec/kubetruth/template_spec.rb index 5cec891..1598b57 100644 --- a/spec/kubetruth/template_spec.rb +++ b/spec/kubetruth/template_spec.rb @@ -355,8 +355,53 @@ module Kubetruth expect(typify(data)).to eq(result) end + it "converts embedded json" do + expect(typify('[1, 2, 3]')).to eq([1, 2, 3]) + expect(typify('{"foo": "bar"}')).to eq({"foo" => "bar"}) + end + + it "converts embedded yaml" do + expect(typify('[1, 2, 3]', "yaml")).to eq([1, 2, 3]) + expect(typify('{foo: bar}', "yaml")).to eq({"foo" => "bar"}) + end + + it "recurses conversion of embedded" do + expect(typify('[1, 2, "3"]')).to eq([1, 2, 3]) + expect(typify('{"foo": "true"}')).to eq({"foo" => true}) + end + + it "fails for invalid parser on embedded yaml" do + expect { typify("[1, 2, 3]", "yoyo") }.to raise_error(RuntimeError, /Invalid typify parser/) + end + end + describe "#mconcat" do + + it "merges two maps" do + m1 = {"x" => "y", "a" => "z"} + m2 = {"a" => "b", "y" => "z"} + expect(mconcat(m1, m2)).to eq(m1.merge(m2)) + expect(described_class.new("{{ m1 | mconcat: m2 | to_json }}").render(m1: m1, m2: m2)).to eq(m1.merge(m2).to_json) + end + + end + + describe "#re_replace" do + + it "performs gsub" do + expect(re_replace("foobar", "o+", "X")).to eq("fXbar") + expect(described_class.new('{{ "foobar" | re_replace: "o+", "X" }}').render()).to eq("fXbar") + end + + it "handles flags" do + expect(re_replace("fOObar", "o+", "X")).to eq("fOObar") + expect(re_replace("fOObar", "o+", "X", "i")).to eq("fXbar") + expect(re_replace("FOO\nOO", "f.*", "X", "i")).to eq("X\nOO") + expect(re_replace("FOO\nOO", "f.*", "X", "mi")).to eq("X") + end + + end end describe Kubetruth::Template::TemplateHashDrop do