go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/proto/protowalk/processor_required.go (about)

     1  // Copyright 2022 The LUCI Authors.
     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  //      http://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 protowalk
    16  
    17  import (
    18  	"google.golang.org/genproto/googleapis/api/annotations"
    19  	"google.golang.org/protobuf/proto"
    20  	"google.golang.org/protobuf/reflect/protoreflect"
    21  	"google.golang.org/protobuf/types/descriptorpb"
    22  )
    23  
    24  // RequiredProcessor implements the recommended behavior of
    25  // aip.dev/203#required, namely that it produces a Report for unset
    26  // fields marked like:
    27  //
    28  //	type name = <tag> [(google.api.field_behavior) = REQUIRED];
    29  //
    30  // NOTE: In LUCI code, it's recommended to use "protoc-gen-validate" (i.e. PGV)
    31  // annotations to indicate required fields. The PGV generated code is easier to
    32  // use and (likely) more efficient than the implementation in this package.
    33  type RequiredProcessor struct{}
    34  
    35  var _ FieldProcessor = RequiredProcessor{}
    36  
    37  // Process implements FieldProcessor.
    38  func (RequiredProcessor) Process(field protoreflect.FieldDescriptor, msg protoreflect.Message) (data ResultData, applied bool) {
    39  	return ResultData{Message: "required", IsErr: true}, true
    40  }
    41  
    42  func init() {
    43  	RegisterFieldProcessor(&RequiredProcessor{}, func(field protoreflect.FieldDescriptor) ProcessAttr {
    44  		if fo := field.Options().(*descriptorpb.FieldOptions); fo != nil {
    45  			for _, fb := range proto.GetExtension(fo, annotations.E_FieldBehavior).([]annotations.FieldBehavior) {
    46  				if fb == annotations.FieldBehavior_REQUIRED {
    47  					return ProcessIfUnset
    48  				}
    49  			}
    50  		}
    51  		return ProcessNever
    52  	})
    53  }