From a95a25dac45df2fd04fba321eb66dbb868c1283a Mon Sep 17 00:00:00 2001 From: Dave Henderson Date: Sat, 17 Nov 2018 13:01:20 -0500 Subject: Adding quote and squote functions Signed-off-by: Dave Henderson --- funcs/strings.go | 15 +++++++++++++++ funcs/strings_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) (limited to 'funcs') diff --git a/funcs/strings.go b/funcs/strings.go index f803a48d..fbf58dcc 100644 --- a/funcs/strings.go +++ b/funcs/strings.go @@ -6,6 +6,7 @@ package funcs // in templates easier. import ( + "fmt" "sync" "github.com/Masterminds/goutils" @@ -40,6 +41,8 @@ func AddStringFuncs(f map[string]interface{}) { f["trimSpace"] = StrNS().TrimSpace f["indent"] = StrNS().Indent f["sort"] = StrNS().Sort + f["quote"] = StrNS().Quote + f["squote"] = StrNS().Squote // these are legacy aliases with non-pipelinable arg order f["contains"] = strings.Contains @@ -208,3 +211,15 @@ func (f *StringFuncs) Indent(args ...interface{}) (string, error) { func (f *StringFuncs) Slug(in interface{}) string { return slug.Make(conv.ToString(in)) } + +// Quote - +func (f *StringFuncs) Quote(in interface{}) string { + return fmt.Sprintf("%q", conv.ToString(in)) +} + +// Squote - +func (f *StringFuncs) Squote(in interface{}) string { + s := conv.ToString(in) + s = strings.Replace(s, `'`, `''`, -1) + return fmt.Sprintf("'%s'", s) +} diff --git a/funcs/strings_test.go b/funcs/strings_test.go index f4da1a73..04a97bcc 100644 --- a/funcs/strings_test.go +++ b/funcs/strings_test.go @@ -106,3 +106,41 @@ func TestSort(t *testing.T) { assert.Equal(t, out, must(sf.Sort([]interface{}{"foo", "bar", "baz"}))) } + +func TestQuote(t *testing.T) { + sf := &StringFuncs{} + testdata := []struct { + in interface{} + out string + }{ + {``, `""`}, + {`foo`, `"foo"`}, + {nil, `"nil"`}, + {123.4, `"123.4"`}, + {`hello "world"`, `"hello \"world\""`}, + {`it's its`, `"it's its"`}, + } + + for _, d := range testdata { + assert.Equal(t, d.out, sf.Quote(d.in)) + } +} + +func TestSquote(t *testing.T) { + sf := &StringFuncs{} + testdata := []struct { + in interface{} + out string + }{ + {``, `''`}, + {`foo`, `'foo'`}, + {nil, `'nil'`}, + {123.4, `'123.4'`}, + {`hello "world"`, `'hello "world"'`}, + {`it's its`, `'it''s its'`}, + } + + for _, d := range testdata { + assert.Equal(t, d.out, sf.Squote(d.in)) + } +} -- cgit v1.2.3