func ParseMatcher()

in pkg/labels/parse.go [117:178]


func ParseMatcher(s string) (_ *Matcher, err error) {
	ms := re.FindStringSubmatch(s)
	if len(ms) == 0 {
		return nil, fmt.Errorf("bad matcher format: %s", s)
	}

	var (
		rawValue            = ms[3]
		value               strings.Builder
		escaped             bool
		expectTrailingQuote bool
	)

	if strings.HasPrefix(rawValue, "\"") {
		rawValue = strings.TrimPrefix(rawValue, "\"")
		expectTrailingQuote = true
	}

	if !utf8.ValidString(rawValue) {
		return nil, fmt.Errorf("matcher value not valid UTF-8: %s", ms[3])
	}

	// Unescape the rawValue:
	for i, r := range rawValue {
		if escaped {
			escaped = false
			switch r {
			case 'n':
				value.WriteByte('\n')
			case '"', '\\':
				value.WriteRune(r)
			default:
				// This was a spurious escape, so treat the '\' as literal.
				value.WriteByte('\\')
				value.WriteRune(r)
			}
			continue
		}
		switch r {
		case '\\':
			if i < len(rawValue)-1 {
				escaped = true
				continue
			}
			// '\' encountered as last byte. Treat it as literal.
			value.WriteByte('\\')
		case '"':
			if !expectTrailingQuote || i < len(rawValue)-1 {
				return nil, fmt.Errorf("matcher value contains unescaped double quote: %s", ms[3])
			}
			expectTrailingQuote = false
		default:
			value.WriteRune(r)
		}
	}

	if expectTrailingQuote {
		return nil, fmt.Errorf("matcher value contains unescaped double quote: %s", ms[3])
	}

	return NewMatcher(typeMap[ms[2]], ms[1], value.String())
}