summaryrefslogtreecommitdiff
path: root/funcs
diff options
context:
space:
mode:
authorDave Henderson <dhenderson@gmail.com>2018-11-17 13:01:20 -0500
committerDave Henderson <dhenderson@gmail.com>2018-11-17 13:01:20 -0500
commita95a25dac45df2fd04fba321eb66dbb868c1283a (patch)
treee6e8b0d9d451b2ce5e64dfec6e08f749722940d1 /funcs
parent0cf7734ef776cc7701dfbb08b080cecf5066f0eb (diff)
Adding quote and squote functions
Signed-off-by: Dave Henderson <dhenderson@gmail.com>
Diffstat (limited to 'funcs')
-rw-r--r--funcs/strings.go15
-rw-r--r--funcs/strings_test.go38
2 files changed, 53 insertions, 0 deletions
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))
+ }
+}