github.com/googleapis/api-linter@v1.65.2/.github/quality-checker/rule_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 main
    16  
    17  import (
    18  	"fmt"
    19  	"os"
    20  	"regexp"
    21  
    22  	"github.com/stoewer/go-strcase"
    23  )
    24  
    25  func checkRuleName(aip int, name string) []error {
    26  	path := fmt.Sprintf("rules/aip%04d/%s.go", aip, strcase.SnakeCase(name))
    27  
    28  	// Read in the file.
    29  	contentsBytes, err := os.ReadFile(path)
    30  	if err != nil {
    31  		return []error{err}
    32  	}
    33  	contents := string(contentsBytes)
    34  
    35  	// Find the rule name declaration.
    36  	// If it can not be found, complain.
    37  	match := ruleNameRegexp.FindStringSubmatch(contents)
    38  	if match == nil {
    39  		return []error{fmt.Errorf("no rule name found: AIP-%d, %s", aip, name)}
    40  	}
    41  
    42  	// If the rule name declaration does not match, complain.
    43  	errs := []error{}
    44  	if fmt.Sprintf("%d", aip) != match[1] {
    45  		errs = append(errs, fmt.Errorf("mismatch between path and rule AIP: %s", path))
    46  	}
    47  	if name != match[2] {
    48  		errs = append(errs, fmt.Errorf("mismatch between rule name and filename: %s", path))
    49  	}
    50  	return errs
    51  }
    52  
    53  var ruleNameRegexp = regexp.MustCompile(`NewRuleName\(([\d]+), "([a-z0-9-]+)"\)`)