github.com/googleapis/api-linter@v1.65.2/rules/aip0202/string_only_format.go (about)

     1  // Copyright 2023 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 aip0202
    16  
    17  import (
    18  	"fmt"
    19  
    20  	"bitbucket.org/creachadair/stringset"
    21  	"github.com/googleapis/api-linter/lint"
    22  	"github.com/googleapis/api-linter/rules/internal/utils"
    23  	"github.com/jhump/protoreflect/desc"
    24  	apb "google.golang.org/genproto/googleapis/api/annotations"
    25  	"google.golang.org/protobuf/types/descriptorpb"
    26  )
    27  
    28  var stringOnlyFormats = stringset.New(
    29  	apb.FieldInfo_IPV4.String(),
    30  	apb.FieldInfo_IPV6.String(),
    31  	apb.FieldInfo_IPV4_OR_IPV6.String(),
    32  	apb.FieldInfo_UUID4.String(),
    33  )
    34  
    35  var stringOnlyFormat = &lint.FieldRule{
    36  	Name: lint.NewRuleName(202, "string-only-format"),
    37  	OnlyIf: func(fd *desc.FieldDescriptor) bool {
    38  		return utils.HasFormat(fd) && fd.GetType() != descriptorpb.FieldDescriptorProto_TYPE_STRING
    39  	},
    40  	LintField: func(fd *desc.FieldDescriptor) []lint.Problem {
    41  		// Field being linted is not a string, check that it isn't using a string-only format.
    42  		if format := utils.GetFormat(fd).String(); stringOnlyFormats.Contains(format) {
    43  			return []lint.Problem{{
    44  				Message:    fmt.Sprintf("Format %q must only be used on string fields", format),
    45  				Descriptor: fd,
    46  			}}
    47  		}
    48  		return nil
    49  	},
    50  }