github.com/googleapis/api-linter@v1.65.2/lint/rule_name.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  	"fmt"
    19  	"regexp"
    20  	"strings"
    21  )
    22  
    23  // RuleName is an identifier for a rule. Allowed characters include a-z, 0-9, -.
    24  //
    25  // The namespace separator :: is allowed between RuleName segments
    26  // (for example, my-namespace::my-rule).
    27  type RuleName string
    28  
    29  const nameSeparator string = "::"
    30  
    31  var ruleNameValidator = regexp.MustCompile("^([a-z0-9][a-z0-9-]*(::[a-z0-9][a-z0-9-]*)?)+$")
    32  
    33  // NewRuleName creates a RuleName from an AIP number and a unique name within
    34  // that AIP.
    35  func NewRuleName(aip int, name string) RuleName {
    36  	return RuleName(strings.Join([]string{
    37  		getRuleGroup(aip, aipGroups),
    38  		fmt.Sprintf("%04d", aip),
    39  		name,
    40  	}, nameSeparator))
    41  }
    42  
    43  // IsValid checks if a RuleName is syntactically valid.
    44  func (r RuleName) IsValid() bool {
    45  	return r != "" && ruleNameValidator.Match([]byte(r))
    46  }
    47  
    48  // HasPrefix returns true if r contains prefix as a namespace. prefix parameters can be "::" delimited
    49  // or specified as independent parameters.
    50  // For example:
    51  //
    52  // r := NewRuleName("foo", "bar", "baz")   // string(r) == "foo::bar::baz"
    53  //
    54  // r.HasPrefix("foo::bar")          == true
    55  // r.HasPrefix("foo", "bar")        == true
    56  // r.HasPrefix("foo", "bar", "baz") == true   // matches the entire string
    57  // r.HasPrefix("foo", "ba")         == false  // prefix must end on a delimiter
    58  func (r RuleName) HasPrefix(prefix ...string) bool {
    59  	s := strings.Join(prefix, nameSeparator)
    60  	return string(r) == s || strings.HasPrefix(string(r), s+nameSeparator)
    61  }