github.com/whtcorpsinc/milevadb-prod@v0.0.0-20211104133533-f57f4be3b597/dbs/memristed/utils.go (about)

     1  // Copyright 2020 WHTCORPS INC, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package memristed
    15  
    16  import (
    17  	"strings"
    18  
    19  	"github.com/whtcorpsinc/errors"
    20  )
    21  
    22  func checkLabelConstraint(label string) (LabelConstraint, error) {
    23  	r := LabelConstraint{}
    24  
    25  	if len(label) < 4 {
    26  		return r, errors.Errorf("label constraint should be in format '{+|-}key=value', but got '%s'", label)
    27  	}
    28  
    29  	var op LabelConstraintOp
    30  	switch label[0] {
    31  	case '+':
    32  		op = In
    33  	case '-':
    34  		op = NotIn
    35  	default:
    36  		return r, errors.Errorf("label constraint should be in format '{+|-}key=value', but got '%s'", label)
    37  	}
    38  
    39  	ekv := strings.Split(label[1:], "=")
    40  	if len(ekv) != 2 {
    41  		return r, errors.Errorf("label constraint should be in format '{+|-}key=value', but got '%s'", label)
    42  	}
    43  
    44  	key := strings.TrimSpace(ekv[0])
    45  	if key == "" {
    46  		return r, errors.Errorf("label constraint should be in format '{+|-}key=value', but got '%s'", label)
    47  	}
    48  
    49  	val := strings.TrimSpace(ekv[1])
    50  	if val == "" {
    51  		return r, errors.Errorf("label constraint should be in format '{+|-}key=value', but got '%s'", label)
    52  	}
    53  
    54  	r.Key = key
    55  	r.Op = op
    56  	r.Values = []string{val}
    57  	return r, nil
    58  }
    59  
    60  // CheckLabelConstraints will check labels, and build LabelConstraints for rule.
    61  func CheckLabelConstraints(labels []string) ([]LabelConstraint, error) {
    62  	constraints := make([]LabelConstraint, 0, len(labels))
    63  	for _, str := range labels {
    64  		label, err := checkLabelConstraint(strings.TrimSpace(str))
    65  		if err != nil {
    66  			return constraints, err
    67  		}
    68  		constraints = append(constraints, label)
    69  	}
    70  	return constraints, nil
    71  }