github.com/googleapis/api-linter@v1.65.2/rules/aip0123/resource_name_components_alternate.go (about)

     1  // Copyright 2023 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 aip0123
    16  
    17  import (
    18  	"fmt"
    19  	"regexp"
    20  	"strings"
    21  
    22  	"github.com/googleapis/api-linter/lint"
    23  	"github.com/googleapis/api-linter/locations"
    24  	"github.com/googleapis/api-linter/rules/internal/utils"
    25  	"github.com/jhump/protoreflect/desc"
    26  )
    27  
    28  var identifierRegexp = regexp.MustCompile("^{[a-z][_a-z0-9]*[a-z0-9]}$")
    29  
    30  var resourceNameComponentsAlternate = &lint.MessageRule{
    31  	Name:   lint.NewRuleName(123, "resource-name-components-alternate"),
    32  	OnlyIf: utils.IsResource,
    33  	LintMessage: func(m *desc.MessageDescriptor) []lint.Problem {
    34  		var problems []lint.Problem
    35  		resource := utils.GetResource(m)
    36  		for _, p := range resource.GetPattern() {
    37  			components := strings.Split(p, "/")
    38  			for i, c := range components {
    39  				identifierExpected := i%2 == 1
    40  				if identifierExpected != isIdentifier(c) {
    41  					problems = append(problems, lint.Problem{
    42  						Message:    fmt.Sprintf("Resource pattern %q must alternate between collection and identifier. %q is not an identifier", p, c),
    43  						Descriptor: m,
    44  						Location:   locations.MessageResource(m),
    45  					})
    46  					break
    47  				}
    48  			}
    49  		}
    50  		return problems
    51  	},
    52  }
    53  
    54  func isIdentifier(s string) bool {
    55  	return identifierRegexp.MatchString(s)
    56  }