gitea源码

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package label
  4. import (
  5. "fmt"
  6. "regexp"
  7. "strings"
  8. "sync"
  9. "code.gitea.io/gitea/modules/util"
  10. )
  11. // Label represents label information loaded from template
  12. type Label struct {
  13. Name string `yaml:"name"`
  14. Color string `yaml:"color"`
  15. Description string `yaml:"description,omitempty"`
  16. Exclusive bool `yaml:"exclusive,omitempty"`
  17. ExclusiveOrder int `yaml:"exclusive_order,omitempty"`
  18. }
  19. var colorPattern = sync.OnceValue(func() *regexp.Regexp {
  20. return regexp.MustCompile(`^#([\da-fA-F]{3}|[\da-fA-F]{6})$`)
  21. })
  22. // NormalizeColor normalizes a color string to a 6-character hex code
  23. func NormalizeColor(color string) (string, error) {
  24. // normalize case
  25. color = strings.TrimSpace(strings.ToLower(color))
  26. // add leading hash
  27. if len(color) == 6 || len(color) == 3 {
  28. color = "#" + color
  29. }
  30. if !colorPattern().MatchString(color) {
  31. return "", util.NewInvalidArgumentErrorf("invalid color: %s", color)
  32. }
  33. // convert 3-character shorthand into 6-character version
  34. if len(color) == 4 {
  35. r := color[1]
  36. g := color[2]
  37. b := color[3]
  38. color = fmt.Sprintf("#%c%c%c%c%c%c", r, r, g, g, b, b)
  39. }
  40. return color, nil
  41. }