github.com/googleapis/api-linter@v1.65.2/rules/aip0158/aip0158.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 aip0158 contains rules defined in https://aip.dev/158.
    16  package aip0158
    17  
    18  import (
    19  	"regexp"
    20  	"strings"
    21  
    22  	"github.com/googleapis/api-linter/lint"
    23  	"github.com/jhump/protoreflect/desc"
    24  )
    25  
    26  // AddRules adds all of the AIP-158 rules to the provided registry.
    27  func AddRules(r lint.RuleRegistry) error {
    28  	return r.Register(
    29  		158,
    30  		requestPaginationPageSize,
    31  		requestPaginationPageToken,
    32  		requestSkipField,
    33  		responsePaginationNextPageToken,
    34  		responseRepeatedFirstField,
    35  		responsePluralFirstField,
    36  		responseUnary,
    37  	)
    38  }
    39  
    40  var (
    41  	paginatedReq = regexp.MustCompile("^(List|Search)[A-Za-z0-9]*Request$")
    42  	paginatedRes = regexp.MustCompile("^(List|Search)[A-Za-z0-9]*Response$")
    43  )
    44  
    45  // Return true if this is an AIP-158 List request message, false otherwise.
    46  func isPaginatedRequestMessage(m *desc.MessageDescriptor) bool {
    47  	if paginatedReq.MatchString(m.GetName()) {
    48  		return true
    49  	}
    50  	// Ignore messages that happen to have these fields but are not requests.
    51  	if !strings.HasSuffix(m.GetName(), "Request") {
    52  		return false
    53  	}
    54  	return m.FindFieldByName("page_size") != nil || m.FindFieldByName("page_token") != nil
    55  }
    56  
    57  // Return true if this is an AIP-158 List response message, false otherwise.
    58  func isPaginatedResponseMessage(m *desc.MessageDescriptor) bool {
    59  	return paginatedRes.MatchString(m.GetName()) || m.FindFieldByName("next_page_token") != nil
    60  }
    61  
    62  func isPaginatedMethod(m *desc.MethodDescriptor) bool {
    63  	return isPaginatedRequestMessage(m.GetInputType()) && isPaginatedResponseMessage(m.GetOutputType())
    64  }