Skip to content

Commit

Permalink
feat: Add non-must template funcs with may prefix
Browse files Browse the repository at this point in the history
  • Loading branch information
gabe565 committed Jul 26, 2024
1 parent fbfa81d commit eb5ebfb
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 5 deletions.
22 changes: 17 additions & 5 deletions internal/template/func_map.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,27 @@ import (
"text/template"

"github.com/Masterminds/sprig/v3"
"github.com/clevyr/yampl/internal/util"
)

func FuncMap() template.FuncMap {
fmap := sprig.TxtFuncMap()
for k, v := range fmap {
if strings.HasPrefix(k, "must") {
k := strings.TrimPrefix(k, "must")
k = strings.ToLower(k[0:1]) + k[1:]
fmap[k] = v
// Prefix functions with "may" that have a "must" counterpart
for key, fn := range fmap {
if !strings.HasPrefix(key, "must") {
mustKey := "must" + util.UpperFirst(key)
if _, ok := fmap[mustKey]; ok {
key = "may" + util.UpperFirst(key)
fmap[key] = fn
}
}
}
// Remove prefix from "must" functions
for key, fn := range fmap {
if strings.HasPrefix(key, "must") {
k := strings.TrimPrefix(key, "must")
k = util.LowerFirst(k)
fmap[k] = fn
}
}
fmap["repo"] = DockerRepo
Expand Down
25 changes: 25 additions & 0 deletions internal/util/strings.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package util

import "strings"

func UpperFirst(s string) string {
switch len(s) {
case 0:
return s
case 1:
return strings.ToUpper(s)
default:
return strings.ToUpper(s[0:1]) + s[1:]
}
}

func LowerFirst(s string) string {
switch len(s) {
case 0:
return s
case 1:
return strings.ToLower(s)
default:
return strings.ToLower(s[0:1]) + s[1:]
}
}
47 changes: 47 additions & 0 deletions internal/util/strings_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package util

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestLowerFirst(t *testing.T) {
type args struct {
s string
}
tests := []struct {
name string
args args
want string
}{
{"empty", args{""}, ""},
{"len 1", args{"A"}, "a"},
{"multiple", args{"TestArg"}, "testArg"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equalf(t, tt.want, LowerFirst(tt.args.s), "LowerFirst(%v)", tt.args.s)
})
}
}

func TestUpperFirst(t *testing.T) {
type args struct {
s string
}
tests := []struct {
name string
args args
want string
}{
{"empty", args{""}, ""},
{"len 1", args{"a"}, "A"},
{"multiple", args{"testArg"}, "TestArg"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assert.Equalf(t, tt.want, UpperFirst(tt.args.s), "UpperFirst(%v)", tt.args.s)
})
}
}

0 comments on commit eb5ebfb

Please sign in to comment.