github.com/googleapis/api-linter@v1.65.2/rules/aip0123/resource_variables.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 aip0123 16 17 import ( 18 "fmt" 19 "strings" 20 21 "github.com/googleapis/api-linter/lint" 22 "github.com/googleapis/api-linter/locations" 23 "github.com/googleapis/api-linter/rules/internal/utils" 24 "github.com/jhump/protoreflect/desc" 25 "google.golang.org/genproto/googleapis/api/annotations" 26 dpb "google.golang.org/protobuf/types/descriptorpb" 27 ) 28 29 var resourceVariables = &lint.MessageRule{ 30 Name: lint.NewRuleName(123, "resource-variables"), 31 OnlyIf: hasResourceAnnotation, 32 LintMessage: func(m *desc.MessageDescriptor) []lint.Problem { 33 resource := utils.GetResource(m) 34 35 return lintResourceVariables(resource, m, locations.MessageResource(m)) 36 }, 37 } 38 39 // lintResourceVariables lints the resource ID segments of the pattern(s) in the 40 // give ResourceDescriptor. This is used for both the file-level annotation 41 // google.api.resource_definition and the message-level annotation 42 // google.api.resource. 43 func lintResourceVariables(resource *annotations.ResourceDescriptor, desc desc.Descriptor, loc *dpb.SourceCodeInfo_Location) []lint.Problem { 44 for _, pattern := range resource.GetPattern() { 45 for _, variable := range getVariables(pattern) { 46 if strings.ToLower(variable) != variable { 47 return []lint.Problem{{ 48 Message: fmt.Sprintf( 49 "Variable names in patterns should use snake case, such as %q.", 50 getDesiredPattern(pattern), 51 ), 52 Descriptor: desc, 53 Location: loc, 54 }} 55 } 56 if strings.HasSuffix(variable, "_id") { 57 return []lint.Problem{{ 58 Message: fmt.Sprintf( 59 "Variable names should omit the `_id` suffix, such as %q.", 60 getDesiredPattern(pattern), 61 ), 62 Descriptor: desc, 63 Location: loc, 64 }} 65 } 66 } 67 } 68 return nil 69 }