From c021a5b919f35ff7a112bd802b094654e6a6ec40 Mon Sep 17 00:00:00 2001 From: Earl Warren Date: Thu, 15 Feb 2024 15:56:17 +0100 Subject: [PATCH] templates: HasPrefix support for template.HTML Refactor locale&string&template related code has .Title be template.HTML and "Improve HTML title on repositories" needs to check the prefix with StringUtils.HasPrefix --- modules/templates/util_string.go | 11 +++++++++-- modules/templates/util_string_test.go | 20 ++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 modules/templates/util_string_test.go diff --git a/modules/templates/util_string.go b/modules/templates/util_string.go index 2771b1e22..3f51c122b 100644 --- a/modules/templates/util_string.go +++ b/modules/templates/util_string.go @@ -4,6 +4,7 @@ package templates import ( + "html/template" "strings" "code.gitea.io/gitea/modules/base" @@ -17,8 +18,14 @@ func NewStringUtils() *StringUtils { return &stringUtils } -func (su *StringUtils) HasPrefix(s, prefix string) bool { - return strings.HasPrefix(s, prefix) +func (su *StringUtils) HasPrefix(s any, prefix string) bool { + switch v := s.(type) { + case string: + return strings.HasPrefix(v, prefix) + case template.HTML: + return strings.HasPrefix(string(v), prefix) + } + return false } func (su *StringUtils) Contains(s, substr string) bool { diff --git a/modules/templates/util_string_test.go b/modules/templates/util_string_test.go new file mode 100644 index 000000000..5844cf201 --- /dev/null +++ b/modules/templates/util_string_test.go @@ -0,0 +1,20 @@ +// Copyright Earl Warren +// SPDX-License-Identifier: MIT + +package templates + +import ( + "html/template" + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_StringUtils_HasPrefix(t *testing.T) { + su := &StringUtils{} + assert.True(t, su.HasPrefix("ABC", "A")) + assert.False(t, su.HasPrefix("ABC", "B")) + assert.True(t, su.HasPrefix(template.HTML("ABC"), "A")) + assert.False(t, su.HasPrefix(template.HTML("ABC"), "B")) + assert.False(t, su.HasPrefix(123, "B")) +}