初始提交: Gitea 项目代码

This commit is contained in:
root
2026-05-30 22:47:36 +08:00
commit f288f76350
6116 changed files with 776822 additions and 0 deletions
+56
View File
@@ -0,0 +1,56 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package svg
import (
"bytes"
"fmt"
"regexp"
"sync"
)
type globalVarsStruct struct {
reXMLDoc,
reComment,
reAttrXMLNs,
reAttrSize,
reAttrClassPrefix *regexp.Regexp
}
var globalVars = sync.OnceValue(func() *globalVarsStruct {
return &globalVarsStruct{
reXMLDoc: regexp.MustCompile(`(?s)<\?xml.*?>`),
reComment: regexp.MustCompile(`(?s)<!--.*?-->`),
reAttrXMLNs: regexp.MustCompile(`(?s)\s+xmlns\s*=\s*"[^"]*"`),
reAttrSize: regexp.MustCompile(`(?s)\s+(width|height)\s*=\s*"[^"]+"`),
reAttrClassPrefix: regexp.MustCompile(`(?s)\s+class\s*=\s*"`),
}
})
// Normalize normalizes the SVG content: set default width/height, remove unnecessary tags/attributes
// It's designed to work with valid SVG content. For invalid SVG content, the returned content is not guaranteed.
func Normalize(data []byte, size int) []byte {
vars := globalVars()
data = vars.reXMLDoc.ReplaceAll(data, nil)
data = vars.reComment.ReplaceAll(data, nil)
data = bytes.TrimSpace(data)
svgTag, svgRemaining, ok := bytes.Cut(data, []byte(">"))
if !ok || !bytes.HasPrefix(svgTag, []byte(`<svg`)) {
return data
}
normalized := bytes.Clone(svgTag)
normalized = vars.reAttrXMLNs.ReplaceAll(normalized, nil)
normalized = vars.reAttrSize.ReplaceAll(normalized, nil)
normalized = vars.reAttrClassPrefix.ReplaceAll(normalized, []byte(` class="`))
normalized = bytes.TrimSpace(normalized)
normalized = fmt.Appendf(normalized, ` width="%d" height="%d"`, size, size)
if !bytes.Contains(normalized, []byte(` class="`)) {
normalized = append(normalized, ` class="svg"`...)
}
normalized = append(normalized, '>')
normalized = append(normalized, svgRemaining...)
return normalized
}
+29
View File
@@ -0,0 +1,29 @@
// Copyright 2023 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package svg
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestNormalize(t *testing.T) {
res := Normalize([]byte("foo"), 1)
assert.Equal(t, "foo", string(res))
res = Normalize([]byte(`<?xml version="1.0"?>
<!--
comment
-->
<svg xmlns = "...">content</svg>`), 1)
assert.Equal(t, `<svg width="1" height="1" class="svg">content</svg>`, string(res))
res = Normalize([]byte(`<svg
width="100"
class="svg-icon"
>content</svg>`), 16)
assert.Equal(t, `<svg class="svg-icon" width="16" height="16">content</svg>`, string(res))
}
+133
View File
@@ -0,0 +1,133 @@
// Copyright 2020 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package svg
import (
"fmt"
"html/template"
"path"
"strings"
"sync"
gitea_html "gitea.dev/modules/htmlutil"
"gitea.dev/modules/log"
"gitea.dev/modules/public"
)
type svgIconItem struct {
html string
mocking bool
}
type svgCacheKey struct {
icon string
size int
class string
}
var (
svgIcons map[string]svgIconItem
svgCacheMu sync.Mutex
svgCache sync.Map
svgCacheCount int
svgCacheLimit = 10000
)
const defaultSize = 16
// Init discovers SVG icons and populates the `svgIcons` variable
func Init() error {
const svgAssetsPath = "assets/img/svg"
files, err := public.AssetFS().ListFiles(svgAssetsPath)
if err != nil {
return err
}
svgIcons = make(map[string]svgIconItem, len(files))
for _, file := range files {
if path.Ext(file) != ".svg" {
continue
}
bs, err := public.AssetFS().ReadFile(svgAssetsPath, file)
if err != nil {
log.Error("Failed to read SVG file %s: %v", file, err)
} else {
svgIcons[file[:len(file)-4]] = svgIconItem{html: string(Normalize(bs, defaultSize))}
}
}
return nil
}
func MockIcon(icon string) func() {
if svgIcons == nil {
svgIcons = make(map[string]svgIconItem)
}
orig, exist := svgIcons[icon]
svgIcons[icon] = svgIconItem{
html: fmt.Sprintf(`<svg class="svg %s" width="%d" height="%d"></svg>`, icon, defaultSize, defaultSize),
mocking: true,
}
return func() {
if exist {
svgIcons[icon] = orig
} else {
delete(svgIcons, icon)
}
}
}
// RenderHTML renders icons - arguments icon name (string), size (int), class (string)
func RenderHTML(icon string, others ...any) template.HTML {
result, _ := renderHTML(icon, others...)
return result
}
func renderHTML(icon string, others ...any) (_ template.HTML, usingCache bool) {
if icon == "" {
return "", false
}
size, class := gitea_html.ParseSizeAndClass(defaultSize, "", others...)
if svgItem, ok := svgIcons[icon]; ok {
svgStr := svgItem.html
// fast path for default size and no classes
if size == defaultSize && class == "" {
return template.HTML(svgStr), false
}
cacheKey := svgCacheKey{icon, size, class}
cachedHTML, cached := svgCache.Load(cacheKey)
if cached && !svgItem.mocking {
return cachedHTML.(template.HTML), true
}
// the code is somewhat hacky, but it just works, because the SVG contents are all normalized
if size != defaultSize {
svgStr = strings.Replace(svgStr, fmt.Sprintf(`width="%d"`, defaultSize), fmt.Sprintf(`width="%d"`, size), 1)
svgStr = strings.Replace(svgStr, fmt.Sprintf(`height="%d"`, defaultSize), fmt.Sprintf(`height="%d"`, size), 1)
}
if class != "" {
svgStr = strings.Replace(svgStr, `class="`, fmt.Sprintf(`class="%s `, class), 1)
}
result := template.HTML(svgStr)
if !svgItem.mocking {
// no need to double-check, the rendering is fast enough and the cache is just an optimization
svgCacheMu.Lock()
if svgCacheCount >= svgCacheLimit {
svgCache.Clear()
svgCacheCount = 0
}
svgCacheCount++
svgCache.Store(cacheKey, result)
svgCacheMu.Unlock()
}
return result, false
}
// during test (or something wrong happens), there is no SVG loaded, so use a dummy span to tell that the icon is missing
dummy := template.HTML(fmt.Sprintf("<span>%s(%d/%s)</span>", template.HTMLEscapeString(icon), size, template.HTMLEscapeString(class)))
return dummy, false
}
+54
View File
@@ -0,0 +1,54 @@
// Copyright 2026 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package svg
import (
"testing"
"gitea.dev/modules/test"
"github.com/stretchr/testify/assert"
)
func TestRenderHTMLCache(t *testing.T) {
const svgRealContent = "RealContent"
svgIcons = map[string]svgIconItem{
"test": {html: `<svg class="svg test" width="16" height="16">` + svgRealContent + `</svg>`},
}
// default params: no cache entry
_, usingCache := renderHTML("test")
assert.False(t, usingCache)
_, usingCache = renderHTML("test")
assert.False(t, usingCache)
// non-default params: cached
_, usingCache = renderHTML("test", 24)
assert.False(t, usingCache)
_, usingCache = renderHTML("test", 24)
assert.True(t, usingCache)
// mocked svg shouldn't be cached
revertMock := MockIcon("test")
mockedHTML, usingCache := renderHTML("test", 24)
assert.False(t, usingCache)
assert.NotContains(t, mockedHTML, svgRealContent)
revertMock()
realHTML, usingCache := renderHTML("test", 24)
assert.True(t, usingCache)
assert.Contains(t, realHTML, svgRealContent)
t.Run("CacheWithLimit", func(t *testing.T) {
assert.NotZero(t, svgCacheCount)
const testLimit = 3
defer test.MockVariableValue(&svgCacheLimit, testLimit)()
for i := range 10 {
_, usingCache = renderHTML("test", 100+i)
assert.False(t, usingCache)
_, usingCache = renderHTML("test", 100+i)
assert.True(t, usingCache)
assert.LessOrEqual(t, svgCacheCount, testLimit)
}
})
}