Skip to content

Commit

Permalink
🐛 fix: testutil - lite tpl render var parse error on contains empty f…
Browse files Browse the repository at this point in the history
…ormat
  • Loading branch information
inhere committed Sep 23, 2023
1 parent 8119792 commit 3e41471
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
6 changes: 5 additions & 1 deletion strutil/textutil/litetpl.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,13 @@ func (t *LiteTemplate) initReplacer(vr *VarReplacer) {
basefn.PanicIf(vr.Right == "", "var format right chars is required")

vr.lLen, vr.rLen = len(vr.Left), len(vr.Right)
rightLast := string(vr.Right[vr.rLen-1]) // 排除匹配,防止匹配到类似 "{} adb ddf {var}"

// eg: \{(?s:([^\}]+?))\}
// (?s:...) - 让 "." 匹配换行
// (?s:(.+?)) - 第二个 "?" 非贪婪匹配
vr.varReg = regexp.MustCompile(regexp.QuoteMeta(vr.Left) + `(?s:(.+?))` + regexp.QuoteMeta(vr.Right))
pattern := regexp.QuoteMeta(vr.Left) + `(?s:([^` + regexp.QuoteMeta(rightLast) + `]+?))` + regexp.QuoteMeta(vr.Right)
vr.varReg = regexp.MustCompile(pattern)
}

// AddFuncs add custom template functions
Expand Down
16 changes: 16 additions & 0 deletions strutil/textutil/litetpl_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,22 @@ func TestRenderString(t *testing.T) {
})
}

func TestCustomVarFmt(t *testing.T) {
lt := textutil.NewLiteTemplate(func(opt *textutil.LiteTemplateOpt) {
opt.SetVarFmt("{,}")
})

tpl := "hi, My name is { name | upFirst }, age is { age }"
str := lt.RenderString(tpl, data)
assert.Eq(t, "hi, My name is Inhere, age is 2000", str)

t.Run("with invalid var format", func(t *testing.T) {
tpl := "hi, My name is { name | upFirst }, empty {}, age is { age }"
str := lt.RenderString(tpl, data)
assert.Eq(t, "hi, My name is Inhere, empty {}, age is 2000", str)
})
}

func TestRenderFile(t *testing.T) {
s, err := textutil.RenderFile("testdata/test-lite.tpl", data)
assert.NoError(t, err)
Expand Down

0 comments on commit 3e41471

Please sign in to comment.