Skip to content

Commit 2f6340f

Browse files
committed
feat(require): improve comment replacement logic
Refactor the template comment replacement for require to avoid altering assert.CollectT references. Introduce RequireComment method to safely replace "assert." with "require." while preserving "assert.CollectT". Update require.go.tmpl to use the new method. Signed-off-by: a2not <[email protected]>
1 parent fdfb9cd commit 2f6340f

File tree

2 files changed

+11
-4
lines changed

2 files changed

+11
-4
lines changed

_codegen/main.go

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -106,9 +106,7 @@ func parseTemplates() (*template.Template, *template.Template, error) {
106106
}
107107
funcTemplate = string(f)
108108
}
109-
tmpl, err := template.New("function").Funcs(template.FuncMap{
110-
"replace": strings.ReplaceAll,
111-
}).Parse(funcTemplate)
109+
tmpl, err := template.New("function").Parse(funcTemplate)
112110
if err != nil {
113111
return nil, nil, err
114112
}
@@ -298,6 +296,15 @@ func (f *testFunc) CommentWithoutT(receiver string) string {
298296
return strings.Replace(f.Comment(), search, replace, -1)
299297
}
300298

299+
func (f *testFunc) RequireComment(comment string) string {
300+
// First, protect assert.CollectT by temporarily replacing it
301+
protected := strings.ReplaceAll(comment, "assert.CollectT", "__COLLECT_T_PLACEHOLDER__")
302+
// Then do the normal replacement
303+
result := strings.ReplaceAll(protected, "assert.", "require.")
304+
// Restore assert.CollectT
305+
return strings.ReplaceAll(result, "__COLLECT_T_PLACEHOLDER__", "assert.CollectT")
306+
}
307+
301308
// Standard header https://go.dev/s/generatedcode.
302309
var headerTemplate = `// Code generated with github.com/stretchr/testify/_codegen; DO NOT EDIT.
303310

require/require.go.tmpl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
{{ replace .Comment "assert." "require."}}
1+
{{ RequireComment .Comment }}
22
func {{.DocInfo.Name}}(t TestingT, {{.Params}}) {
33
if h, ok := t.(tHelper); ok { h.Helper() }
44
if assert.{{.DocInfo.Name}}(t, {{.ForwardedParams}}) { return }

0 commit comments

Comments
 (0)