github.com/googleapis/api-linter@v1.65.2/rules/aip0122/resource_id_output_only.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 aip0122
    16  
    17  import (
    18  	"github.com/googleapis/api-linter/lint"
    19  	"github.com/googleapis/api-linter/rules/internal/utils"
    20  	"github.com/jhump/protoreflect/desc"
    21  	"github.com/stoewer/go-strcase"
    22  	"google.golang.org/genproto/googleapis/api/annotations"
    23  )
    24  
    25  var resourceIdOutputOnly = &lint.FieldRule{
    26  	Name: lint.NewRuleName(122, "resource-id-output-only"),
    27  	OnlyIf: func(f *desc.FieldDescriptor) bool {
    28  		var idName string
    29  		p := f.GetParent().(*desc.MessageDescriptor)
    30  
    31  		// Build an expected ID field name based on the Resource `singular`
    32  		// field or by parsing the `type`.
    33  		isRes := utils.IsResource(p)
    34  		if isRes {
    35  			res := utils.GetResource(p)
    36  			idName = res.GetSingular()
    37  			if idName == "" {
    38  				if _, t, ok := utils.SplitResourceTypeName(res.GetType()); ok {
    39  					idName = strcase.SnakeCase(t)
    40  				}
    41  			}
    42  			idName += "_id"
    43  		}
    44  
    45  		isId := f.GetName() == "uid" || f.GetName() == idName
    46  		return isRes && isId
    47  	},
    48  	LintField: func(f *desc.FieldDescriptor) []lint.Problem {
    49  		behaviors := utils.GetFieldBehavior(f)
    50  		if !behaviors.Contains(annotations.FieldBehavior_OUTPUT_ONLY.String()) {
    51  			return []lint.Problem{
    52  				{
    53  					Message:    "Resource ID fields must have field_behavior OUTPUT_ONLY",
    54  					Descriptor: f,
    55  				},
    56  			}
    57  		}
    58  		return nil
    59  	},
    60  }