github.com/googleapis/api-linter@v1.65.2/rules/aip0148/declarative_friendly_fields.go (about) 1 // Copyright 2020 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 aip0148 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/rules/internal/utils" 24 "github.com/jhump/protoreflect/desc" 25 ) 26 27 var declarativeFriendlyRequired = &lint.MessageRule{ 28 Name: lint.NewRuleName(148, "declarative-friendly-fields"), 29 OnlyIf: func(m *desc.MessageDescriptor) bool { 30 if resource := utils.DeclarativeFriendlyResource(m); resource == m { 31 return true 32 } 33 return false 34 }, 35 LintMessage: func(m *desc.MessageDescriptor) []lint.Problem { 36 singleton := utils.IsSingletonResource(m) 37 // Define the fields that are expected. 38 missingFields := stringset.New() 39 for name, typ := range reqFields { 40 if singleton && singletonExceptions.Contains(name) { 41 continue 42 } 43 f := m.FindFieldByName(name) 44 if f == nil || utils.GetTypeName(f) != typ { 45 missingFields.Add(fmt.Sprintf("%s %s", typ, name)) 46 } 47 } 48 if missingFields.Len() > 0 { 49 msg := "Declarative-friendly resources must include the following fields:\n" 50 if missingFields.Len() == 1 { 51 msg = fmt.Sprintf( 52 "Declarative-friendly resources must include the `%s` field.", 53 missingFields.Unordered()[0], 54 ) 55 } else { 56 for _, field := range missingFields.Elements() { 57 msg += fmt.Sprintf(" - `%s`\n", field) 58 } 59 } 60 return []lint.Problem{{ 61 Message: strings.TrimSuffix(msg, "\n"), 62 Descriptor: m, 63 }} 64 } 65 return nil 66 }, 67 } 68 69 var reqFields = map[string]string{ 70 "name": "string", 71 "uid": "string", 72 "display_name": "string", 73 "create_time": "google.protobuf.Timestamp", 74 "update_time": "google.protobuf.Timestamp", 75 "delete_time": "google.protobuf.Timestamp", 76 } 77 78 var singletonExceptions = stringset.New( 79 "delete_time", 80 "uid", 81 )