github.com/googleapis/api-linter@v1.65.2/rules/internal/utils/type_name.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 utils
    16  
    17  import (
    18  	"fmt"
    19  	"strings"
    20  
    21  	"github.com/jhump/protoreflect/desc"
    22  )
    23  
    24  // GetTypeName returns the name of the type of the field, as a string,
    25  // regardless of primitive, message, etc.
    26  func GetTypeName(f *desc.FieldDescriptor) string {
    27  	if k, v := f.GetMapKeyType(), f.GetMapValueType(); k != nil && v != nil {
    28  		return fmt.Sprintf("map<%s, %s>", GetTypeName(k), GetTypeName(v))
    29  	}
    30  	if m := f.GetMessageType(); m != nil {
    31  		return m.GetFullyQualifiedName()
    32  	}
    33  	if e := f.GetEnumType(); e != nil {
    34  		return e.GetFullyQualifiedName()
    35  	}
    36  	return strings.ToLower(f.GetType().String()[len("TYPE_"):])
    37  }
    38  
    39  // IsOperation returns if the message is a longrunning Operation or not.
    40  func IsOperation(m *desc.MessageDescriptor) bool {
    41  	return m.GetFullyQualifiedName() == "google.longrunning.Operation"
    42  }
    43  
    44  // GetResourceMessageName returns the resource message type name from method
    45  func GetResourceMessageName(m *desc.MethodDescriptor, expectedVerb string) string {
    46  	if !strings.HasPrefix(m.GetName(), expectedVerb) {
    47  		return ""
    48  	}
    49  
    50  	// Usually the response message will be the resource message, and its name will
    51  	// be part of method name (make a double check here to avoid the issue when
    52  	// method or output naming doesn't follow the right principles)
    53  	// Ignore this rule if the return type is an LRO
    54  	if strings.Contains(m.GetName()[len(expectedVerb):], m.GetOutputType().GetName()) && !IsOperation(m.GetOutputType()) {
    55  		return m.GetOutputType().GetName()
    56  	}
    57  	return m.GetName()[len(expectedVerb):]
    58  }