github.com/googleapis/api-linter@v1.65.2/rules/aip4232/required_fields.go (about) 1 // Copyright 2021 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 aip4232 16 17 import ( 18 "fmt" 19 "strings" 20 21 "bitbucket.org/creachadair/stringset" 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 // All fields annotated as REQUIRED must be in every method_signature. 29 var requiredFields = &lint.MethodRule{ 30 Name: lint.NewRuleName(4232, "required-fields"), 31 OnlyIf: hasMethodSignatures, 32 LintMethod: func(m *desc.MethodDescriptor) []lint.Problem { 33 var problems []lint.Problem 34 sigs := utils.GetMethodSignatures(m) 35 in := m.GetInputType() 36 37 requiredFields := []string{} 38 for _, f := range in.GetFields() { 39 if utils.GetFieldBehavior(f).Contains("REQUIRED") { 40 requiredFields = append(requiredFields, f.GetName()) 41 } 42 } 43 for i, sig := range sigs { 44 sigset := stringset.New(sig...).Map(func(s string) string { 45 if !strings.Contains(s, ".") { 46 return s 47 } 48 // If signature contains nested fields, get the root field 49 // to use in top-level required field check. 50 return strings.Split(s, ".")[0] 51 }) 52 if !sigset.Contains(requiredFields...) { 53 problems = append(problems, lint.Problem{ 54 Message: fmt.Sprintf("Method signature %q missing at least one of the required fields: %q", strings.Join(sig, ","), strings.Join(requiredFields, ",")), 55 Descriptor: m, 56 Location: locations.MethodSignature(m, i), 57 }) 58 } 59 } 60 61 return problems 62 }, 63 }