github.com/googleapis/api-linter@v1.65.2/.github/quality-checker/rule_registered.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  	"strings"
    22  
    23  	"github.com/stoewer/go-strcase"
    24  )
    25  
    26  func checkRuleRegistered(aip int, name string) []error {
    27  	path := fmt.Sprintf("rules/aip%04d/%s.go", aip, strcase.SnakeCase(name))
    28  
    29  	// Read in the file.
    30  	contents, err := os.ReadFile(path)
    31  	if err != nil {
    32  		return []error{err}
    33  	}
    34  
    35  	// Look for a rule in the file. Complain if we can not find one.
    36  	ruleMatch := ruleRegexp.FindStringSubmatch(string(contents))
    37  	if len(ruleMatch) == 0 {
    38  		return []error{fmt.Errorf("no rule found: %s", path)}
    39  	}
    40  
    41  	// Some errors are now non-fatal; start a running tab.
    42  	errata := []error{}
    43  
    44  	// Ensure this rule is registered within its AIP module file.
    45  	ruleVar := ruleMatch[1]
    46  	contents, err = os.ReadFile(fmt.Sprintf("rules/aip%04d/aip%04d.go", aip, aip))
    47  	if err != nil {
    48  		return []error{err}
    49  	}
    50  	if !strings.Contains(string(contents), ruleVar) {
    51  		errata = append(errata, fmt.Errorf("rule %q for AIP-%d not registered in the AIP's AllRules", name, aip))
    52  	}
    53  
    54  	// Ensure that the AIP itself is registered in `rules/rules.go`.
    55  	contents, err = os.ReadFile("rules/rules.go")
    56  	if err != nil {
    57  		errata = append(errata, err)
    58  		return errata
    59  	}
    60  	if !strings.Contains(string(contents), fmt.Sprintf("aip%04d.AddRules", aip)) {
    61  		errata = append(errata, fmt.Errorf("rules.go does not call AllRules for for AIP-%d", aip))
    62  	}
    63  
    64  	// Done; return any errata we found.
    65  	return errata
    66  }
    67  
    68  var ruleRegexp = regexp.MustCompile(`var ([\w\d]+) = &lint\.[\w]+Rule\s*{`)