github.com/googleapis/api-linter@v1.65.2/rules/aip0140/abbreviations.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 aip0140 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/jhump/protoreflect/desc" 24 "github.com/stoewer/go-strcase" 25 "golang.org/x/text/cases" 26 "golang.org/x/text/language" 27 ) 28 29 var expectedAbbreviations = map[string]string{ 30 "configuration": "config", 31 "identifier": "id", 32 "information": "info", 33 "specification": "spec", 34 "statistics": "stats", 35 } 36 37 var abbreviations = &lint.DescriptorRule{ 38 Name: lint.NewRuleName(140, "abbreviations"), 39 LintDescriptor: func(d desc.Descriptor) (problems []lint.Problem) { 40 // Determine the correct case function to use. 41 // Most things in protobuf are PascalCase; the two exceptions are 42 // fields (snake case) and enum values (UPPER_CAMEL_CASE). 43 // 44 // We do not need to worry about word separators though, since 45 // we are checking for single words only. 46 var caseFunc func(string) string = cases.Title(language.AmericanEnglish).String 47 switch d.(type) { 48 case *desc.FieldDescriptor: 49 caseFunc = strings.ToLower 50 case *desc.EnumValueDescriptor: 51 caseFunc = strings.ToUpper 52 } 53 54 // Iterate over each abbreviation and determine whether the descriptor's 55 // name includes the long name. 56 for long, short := range expectedAbbreviations { 57 for _, segment := range strings.Split(strcase.SnakeCase(d.GetName()), "_") { 58 if segment == long { 59 problems = append(problems, lint.Problem{ 60 Message: fmt.Sprintf( 61 "Use the common abbreviation %q instead of %q.", 62 caseFunc(short), 63 caseFunc(long), 64 ), 65 Suggestion: strings.ReplaceAll(d.GetName(), caseFunc(long), caseFunc(short)), 66 Descriptor: d, 67 Location: locations.DescriptorName(d), 68 }) 69 } 70 } 71 } 72 return 73 }, 74 }