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

     1  package aip0132
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/googleapis/api-linter/lint"
     8  	"github.com/googleapis/api-linter/rules/internal/utils"
     9  	"github.com/jhump/protoreflect/desc"
    10  	"github.com/stoewer/go-strcase"
    11  )
    12  
    13  // The List standard method should contain a parent field.
    14  var requestParentRequired = &lint.MessageRule{
    15  	Name:   lint.NewRuleName(132, "request-parent-required"),
    16  	OnlyIf: utils.IsListRequestMessage,
    17  	LintMessage: func(m *desc.MessageDescriptor) []lint.Problem {
    18  		// Rule check: Establish that a `parent` field is present.
    19  		if m.FindFieldByName("parent") == nil {
    20  			// Sanity check: If the resource has a pattern, and that pattern
    21  			// contains only one variable, then a parent field is not expected.
    22  			//
    23  			// In order to parse out the pattern, we get the resource message
    24  			// from the response, then get the resource annotation from that,
    25  			// and then inspect the pattern there (oy!).
    26  			plural := strings.TrimPrefix(strings.TrimSuffix(m.GetName(), "Request"), "List")
    27  			if resp := utils.FindMessage(m.GetFile(), fmt.Sprintf("List%sResponse", plural)); resp != nil {
    28  				if paged := resp.FindFieldByName(strcase.SnakeCase(plural)); paged != nil {
    29  					if resource := utils.GetResource(paged.GetMessageType()); resource != nil {
    30  						for _, pattern := range resource.GetPattern() {
    31  							if strings.Count(pattern, "{") == 1 {
    32  								return nil
    33  							}
    34  						}
    35  					}
    36  				}
    37  			}
    38  
    39  			// Nope, there should be a parent field and is not. Complain.
    40  			return []lint.Problem{{
    41  				Message:    fmt.Sprintf("Message %q has no `parent` field", m.GetName()),
    42  				Descriptor: m,
    43  			}}
    44  		}
    45  
    46  		return nil
    47  	},
    48  }