code.gitea.io/gitea@v1.19.3/modules/label/label.go (about)

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