knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/test/imports/banned_deps_test.go (about)

     1  /*
     2  Copyright 2019 The Knative Authors
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package imports
    18  
    19  import (
    20  	"fmt"
    21  	"os"
    22  	"path/filepath"
    23  	"runtime"
    24  	"strings"
    25  	"testing"
    26  )
    27  
    28  type vbTuple struct {
    29  	banned string
    30  	vanity string
    31  }
    32  
    33  var bannedImports = []vbTuple{
    34  	{
    35  		banned: "github.com/knative",
    36  		vanity: "knative.dev",
    37  	}, {
    38  		banned: "github.com/kubernetes",
    39  		vanity: "k8s.io",
    40  	}, {
    41  		banned: "github.com/istio",
    42  		vanity: "istio.io",
    43  	},
    44  }
    45  
    46  // TestBannedImports run with:
    47  //
    48  //	go test ./vendor/knative.dev/pkg/test/imports/ -run TestBannedImports
    49  //
    50  // Or with test-infra:
    51  //
    52  //	report_go_test ${REPO_ROOT_DIR}/vendor/knative.dev/pkg/test/imports/...
    53  func TestBannedImports(t *testing.T) {
    54  	_, filename, _, _ := runtime.Caller(0)
    55  	dir := filepath.Dir(filename)
    56  
    57  	if !strings.Contains(dir, "vendor") {
    58  		t.Skipf("knative.dev/pkg not vendored, skipping...")
    59  	}
    60  
    61  	parts := strings.Split(dir, "vendor")
    62  
    63  	dir = fmt.Sprintf("%s%s%s", parts[0], string(filepath.Separator), "vendor")
    64  
    65  	err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
    66  		if !info.IsDir() {
    67  			return nil
    68  		}
    69  		for _, vb := range bannedImports {
    70  			if strings.HasSuffix(path, vb.banned) {
    71  				return fmt.Errorf("%q is a banned import prefix, use vanity import prefix %q instead", vb.banned, vb.vanity)
    72  			}
    73  		}
    74  		return nil
    75  	})
    76  	if err != nil {
    77  		t.Error(err.Error())
    78  	}
    79  }