File: packages.go

package info (click to toggle)
golang-golang-x-vuln 1.0.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,400 kB
  • sloc: sh: 161; asm: 40; makefile: 7
file content (39 lines) | stat: -rw-r--r-- 930 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Copyright 2022 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package test

import (
	"os/exec"
	"strings"
	"testing"

	"golang.org/x/tools/go/packages"
)

func VerifyImports(t *testing.T, allowed ...string) {
	if _, err := exec.LookPath("go"); err != nil {
		t.Skipf("skipping: %v", err)
	}
	cfg := &packages.Config{Mode: packages.NeedImports | packages.NeedDeps}
	pkgs, err := packages.Load(cfg, ".")
	if err != nil {
		t.Fatal(err)
	}
	check := map[string]struct{}{}
	for _, imp := range allowed {
		check[imp] = struct{}{}
	}
	for _, p := range pkgs {
		for _, imp := range p.Imports {
			// this is an approximate stdlib check that is good enough for these tests
			if !strings.ContainsRune(imp.ID, '.') {
				continue
			}
			if _, ok := check[imp.ID]; !ok {
				t.Errorf("include of %s is not allowed", imp.ID)
			}
		}
	}
}