gitea源码

processor.go 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package svg
  4. import (
  5. "bytes"
  6. "fmt"
  7. "regexp"
  8. "sync"
  9. )
  10. type globalVarsStruct struct {
  11. reXMLDoc,
  12. reComment,
  13. reAttrXMLNs,
  14. reAttrSize,
  15. reAttrClassPrefix *regexp.Regexp
  16. }
  17. var globalVars = sync.OnceValue(func() *globalVarsStruct {
  18. return &globalVarsStruct{
  19. reXMLDoc: regexp.MustCompile(`(?s)<\?xml.*?>`),
  20. reComment: regexp.MustCompile(`(?s)<!--.*?-->`),
  21. reAttrXMLNs: regexp.MustCompile(`(?s)\s+xmlns\s*=\s*"[^"]*"`),
  22. reAttrSize: regexp.MustCompile(`(?s)\s+(width|height)\s*=\s*"[^"]+"`),
  23. reAttrClassPrefix: regexp.MustCompile(`(?s)\s+class\s*=\s*"`),
  24. }
  25. })
  26. // Normalize normalizes the SVG content: set default width/height, remove unnecessary tags/attributes
  27. // It's designed to work with valid SVG content. For invalid SVG content, the returned content is not guaranteed.
  28. func Normalize(data []byte, size int) []byte {
  29. vars := globalVars()
  30. data = vars.reXMLDoc.ReplaceAll(data, nil)
  31. data = vars.reComment.ReplaceAll(data, nil)
  32. data = bytes.TrimSpace(data)
  33. svgTag, svgRemaining, ok := bytes.Cut(data, []byte(">"))
  34. if !ok || !bytes.HasPrefix(svgTag, []byte(`<svg`)) {
  35. return data
  36. }
  37. normalized := bytes.Clone(svgTag)
  38. normalized = vars.reAttrXMLNs.ReplaceAll(normalized, nil)
  39. normalized = vars.reAttrSize.ReplaceAll(normalized, nil)
  40. normalized = vars.reAttrClassPrefix.ReplaceAll(normalized, []byte(` class="`))
  41. normalized = bytes.TrimSpace(normalized)
  42. normalized = fmt.Appendf(normalized, ` width="%d" height="%d"`, size, size)
  43. if !bytes.Contains(normalized, []byte(` class="`)) {
  44. normalized = append(normalized, ` class="svg"`...)
  45. }
  46. normalized = append(normalized, '>')
  47. normalized = append(normalized, svgRemaining...)
  48. return normalized
  49. }