github.com/googleapis/api-linter@v1.65.2/rules/aip0123/resource_pattern.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 resourcePattern = &lint.MessageRule{ 30 Name: lint.NewRuleName(123, "resource-pattern"), 31 OnlyIf: hasResourceAnnotation, 32 LintMessage: func(m *desc.MessageDescriptor) []lint.Problem { 33 resource := utils.GetResource(m) 34 return lintResourcePattern(resource, m, locations.MessageResource(m)) 35 }, 36 } 37 38 func lintResourcePattern(resource *annotations.ResourceDescriptor, desc desc.Descriptor, loc *dpb.SourceCodeInfo_Location) []lint.Problem { 39 // Are any patterns declared at all? If not, complain. 40 if len(resource.GetPattern()) == 0 { 41 return []lint.Problem{{ 42 Message: "Resources should declare resource name pattern(s).", 43 Descriptor: desc, 44 Location: loc, 45 }} 46 } 47 48 // Ensure that the constant segments of the pattern uses camel case, 49 // not snake case, and there are no spaces. 50 for _, pattern := range resource.GetPattern() { 51 plainPattern := getPlainPattern(pattern) 52 53 if strings.Contains(plainPattern, "_") { 54 return []lint.Problem{{ 55 Message: fmt.Sprintf( 56 "Resource patterns should use camel case (apart from the variable names), such as %q.", 57 getDesiredPattern(pattern), 58 ), 59 Descriptor: desc, 60 Location: loc, 61 }} 62 } 63 if strings.Contains(plainPattern, " ") { 64 return []lint.Problem{{ 65 Message: "Resource patterns should not have spaces", 66 Descriptor: desc, 67 Location: loc, 68 }} 69 } 70 } 71 return nil 72 }