mirror of
https://github.com/goreleaser/goreleaser.git
synced 2025-03-17 20:47:50 +02:00
refactor(tmpl): avoid unnecessary byte/string conversion (#4356)
We can use `(*regexp.Regexp).MatchString` instead of `(*regexp.Regexp).Match([]byte(...))` to avoid unnecessary `[]byte` conversions and reduce allocations. A one-line change for free performance gain. Benchmark: ```go func BenchmarkMatch(b *testing.B) { for i := 0; i < b.N; i++ { if match := envOnlyRe.Match([]byte("{{ .Env.FOO }}")); !match { b.Fail() } } } func BenchmarkMatchString(b *testing.B) { for i := 0; i < b.N; i++ { if match := envOnlyRe.MatchString("{{ .Env.FOO }}"); !match { b.Fail() } } } ``` Result: ``` goos: linux goarch: amd64 pkg: github.com/goreleaser/goreleaser/internal/tmpl cpu: AMD Ryzen 7 PRO 4750U with Radeon Graphics BenchmarkMatch-16 4320873 381.2 ns/op 16 B/op 1 allocs/op BenchmarkMatchString-16 5973543 203.9 ns/op 0 B/op 0 allocs/op PASS ok github.com/goreleaser/goreleaser/internal/tmpl 3.366s ``` Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
This commit is contained in:
parent
8203f919b0
commit
37e3fdee55
@ -260,6 +260,8 @@ func (e ExpectedSingleEnvErr) Error() string {
|
||||
return "expected {{ .Env.VAR_NAME }} only (no plain-text or other interpolation)"
|
||||
}
|
||||
|
||||
var envOnlyRe = regexp.MustCompile(`^{{\s*\.Env\.[^.\s}]+\s*}}$`)
|
||||
|
||||
// ApplySingleEnvOnly enforces template to only contain a single environment variable
|
||||
// and nothing else.
|
||||
func (t *Template) ApplySingleEnvOnly(s string) (string, error) {
|
||||
@ -272,8 +274,7 @@ func (t *Template) ApplySingleEnvOnly(s string) (string, error) {
|
||||
// but regexp reduces the complexity and should be sufficient,
|
||||
// given the context is mostly discouraging users from bad practice
|
||||
// of hard-coded credentials, rather than catch all possible cases
|
||||
envOnlyRe := regexp.MustCompile(`^{{\s*\.Env\.[^.\s}]+\s*}}$`)
|
||||
if !envOnlyRe.Match([]byte(s)) {
|
||||
if !envOnlyRe.MatchString(s) {
|
||||
return "", ExpectedSingleEnvErr{}
|
||||
}
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user