github.com/googleapis/api-linter@v1.65.2/lint/rule_registry.go (about)

     1  // Copyright 2019 Google LLC
     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  // 		https://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  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package lint
    16  
    17  import (
    18  	"errors"
    19  	"fmt"
    20  )
    21  
    22  // RuleRegistry is a registry for registering and looking up rules.
    23  type RuleRegistry map[RuleName]ProtoRule
    24  
    25  var (
    26  	errInvalidRuleName    = errors.New("not a valid rule name")
    27  	errInvalidRuleGroup   = errors.New("invalid rule group")
    28  	errDuplicatedRuleName = errors.New("duplicate rule name")
    29  )
    30  
    31  // Register registers the list of rules of the same AIP.
    32  // Return an error if any of the rules is found duplicate in the registry.
    33  func (r RuleRegistry) Register(aip int, rules ...ProtoRule) error {
    34  	rulePrefix := getRuleGroup(aip, aipGroups) + nameSeparator + fmt.Sprintf("%04d", aip)
    35  	for _, rl := range rules {
    36  		if !rl.GetName().IsValid() {
    37  			return errInvalidRuleName
    38  		}
    39  
    40  		if !rl.GetName().HasPrefix(rulePrefix) {
    41  			return errInvalidRuleGroup
    42  		}
    43  
    44  		if _, found := r[rl.GetName()]; found {
    45  			return errDuplicatedRuleName
    46  		}
    47  
    48  		r[rl.GetName()] = rl
    49  	}
    50  	return nil
    51  }
    52  
    53  // NewRuleRegistry creates a new rule registry.
    54  func NewRuleRegistry() RuleRegistry {
    55  	return make(RuleRegistry)
    56  }