From 464b8484eedf6b3ac74b9aec88041c469d6affbb Mon Sep 17 00:00:00 2001 From: Matt Conway Date: Thu, 20 Jan 2022 13:20:47 -0500 Subject: [PATCH] add a re_contains filter for rgex string comparison --- README.md | 1 + lib/kubetruth/template.rb | 5 +++++ spec/kubetruth/template_spec.rb | 18 ++++++++++++++++++ 3 files changed, 24 insertions(+) diff --git a/README.md b/README.md index 65b3618..8df575d 100644 --- a/README.md +++ b/README.md @@ -192,6 +192,7 @@ ones: | `typify` | Converts string values into primitive types (int, float, bool) where applicable for a nested data structure | | `merge` | Combines two hashes into one, a.l.a ruby merge | | `re_replace` | Regexp search and replace, a.l.a ruby gsub, e.g. `"foo" | re_replace: "o+", "X"` | +| `re_contains` | Returns a boolean for the regexp compare against the string target, e.g. `"foo" | re_contains: "o+"` => `true` | The default `resource_templates` make use of the `context` attribute to allow simpler modification of some common fields. These include: diff --git a/lib/kubetruth/template.rb b/lib/kubetruth/template.rb index 08bf777..250b0a0 100644 --- a/lib/kubetruth/template.rb +++ b/lib/kubetruth/template.rb @@ -207,6 +207,11 @@ def re_replace(string, pattern, replacement, flags="") string.gsub(Regexp.new(pattern, allflags), replacement) end + def re_contains(string, pattern, flags="") + allflags = flags.chars.inject(0) {|sum, n| sum | REGEXP_FLAGS[n] } + return (string =~ Regexp.new(pattern, allflags)) != nil + end + end Liquid::Template.register_filter(CustomLiquidFilters) diff --git a/spec/kubetruth/template_spec.rb b/spec/kubetruth/template_spec.rb index c7dd9ab..793c9b8 100644 --- a/spec/kubetruth/template_spec.rb +++ b/spec/kubetruth/template_spec.rb @@ -402,6 +402,24 @@ module Kubetruth end end + + describe "#re_contains" do + + it "performs match" do + expect(re_contains("foobar", "o+")).to eq(true) + expect(re_contains("foobar", "x+")).to eq(false) + expect(described_class.new('{{ "foobar" | re_contains: "o+" }}').render()).to eq("true") + end + + it "handles flags" do + expect(re_contains("fOObar", "o+")).to eq(false) + expect(re_contains("fOObar", "o+", "i")).to eq(true) + expect(re_contains("FOO\nOO", "f.{5}", "i")).to eq(false) + expect(re_contains("FOO\nOO", "f.{5}", "mi")).to eq(true) + end + + end + end describe Kubetruth::Template::TemplateHashDrop do