github.com/googleapis/api-linter@v1.65.2/rules/aip0215/versioned_packages.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 aip0215
    16  
    17  import (
    18  	"regexp"
    19  	"strings"
    20  
    21  	"github.com/googleapis/api-linter/lint"
    22  	"github.com/googleapis/api-linter/locations"
    23  	"github.com/googleapis/api-linter/rules/internal/utils"
    24  	"github.com/jhump/protoreflect/desc"
    25  )
    26  
    27  var versionedPackages = &lint.FileRule{
    28  	Name: lint.NewRuleName(215, "versioned-packages"),
    29  	OnlyIf: func(f *desc.FileDescriptor) bool {
    30  		// Common protos are exempt.
    31  		if utils.IsCommonProto(f) {
    32  			return false
    33  		}
    34  
    35  		// Ignore this if there is no package.
    36  		segments := strings.Split(f.GetPackage(), ".")
    37  		if len(segments) == 1 && segments[0] == "" {
    38  			return false
    39  		}
    40  
    41  		// Exempt anything containing .type, or .v1master, .v2master, .master, etc.
    42  		for _, segment := range segments {
    43  			if segment == "type" || strings.HasSuffix(segment, "master") || strings.HasSuffix(segment, "main") {
    44  				return false
    45  			}
    46  		}
    47  
    48  		// Everything else should follow the rule.
    49  		return true
    50  	},
    51  	LintFile: func(f *desc.FileDescriptor) []lint.Problem {
    52  		if !version.MatchString(f.GetPackage()) {
    53  			return []lint.Problem{{
    54  				Message:    "API components should be in versioned packages.",
    55  				Descriptor: f,
    56  				Location:   locations.FilePackage(f),
    57  			}}
    58  		}
    59  		return nil
    60  	},
    61  }
    62  
    63  var version = regexp.MustCompile(`\.v[\d]+(p[\d]+)?(alpha|beta|eap|test)?[\d]*`)