github.com/googleapis/api-linter@v1.65.2/rules/aip0191/ruby_package.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 aip0191
    16  
    17  import (
    18  	"fmt"
    19  	"regexp"
    20  	"strings"
    21  
    22  	"github.com/googleapis/api-linter/lint"
    23  	"github.com/googleapis/api-linter/locations"
    24  	"github.com/jhump/protoreflect/desc"
    25  	"github.com/stoewer/go-strcase"
    26  )
    27  
    28  var rubyPackage = &lint.FileRule{
    29  	Name: lint.NewRuleName(191, "ruby-package"),
    30  	OnlyIf: func(f *desc.FileDescriptor) bool {
    31  		fops := f.GetFileOptions()
    32  		return fops != nil && fops.GetRubyPackage() != ""
    33  	},
    34  	LintFile: func(f *desc.FileDescriptor) []lint.Problem {
    35  		ns := f.GetFileOptions().GetRubyPackage()
    36  		delim := "::"
    37  
    38  		// Check for invalid characters.
    39  		if !rubyValidChars.MatchString(ns) {
    40  			return []lint.Problem{{
    41  				Message:    "Invalid characters: Ruby packages only allow [A-Za-z0-9:].",
    42  				Descriptor: f,
    43  				Location:   locations.FileRubyPackage(f),
    44  			}}
    45  		}
    46  
    47  		// Check that upper camel case is used.
    48  		upperCamel := []string{}
    49  		for _, segment := range strings.Split(ns, delim) {
    50  			upperCamel = append(upperCamel, strcase.UpperCamelCase(segment))
    51  		}
    52  		if want := strings.Join(upperCamel, delim); ns != want {
    53  			return []lint.Problem{{
    54  				Message:    "Ruby packages use UpperCamelCase.",
    55  				Suggestion: fmt.Sprintf("option ruby_package = %q;", want),
    56  				Descriptor: f,
    57  				Location:   locations.FileRubyPackage(f),
    58  			}}
    59  		}
    60  
    61  		for _, s := range f.GetServices() {
    62  			n := s.GetName()
    63  			if !packagingServiceNameEquals(n, ns, delim) {
    64  				msg := fmt.Sprintf("Case of Ruby package and service name %q must match.", n)
    65  				return []lint.Problem{{
    66  					Message:    msg,
    67  					Descriptor: f,
    68  					Location:   locations.FileRubyPackage(f),
    69  				}}
    70  			}
    71  		}
    72  
    73  		return nil
    74  	},
    75  }
    76  
    77  var rubyValidChars = regexp.MustCompile("^[A-Za-z0-9:]+$")