github.com/q45/go@v0.0.0-20151101211701-a4fb8c13db3f/src/go/build/deps_test.go (about)

     1  // Copyright 2012 The Go Authors.  All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // This file exercises the import parser but also checks that
     6  // some low-level packages do not have new dependencies added.
     7  
     8  package build
     9  
    10  import (
    11  	"bytes"
    12  	"fmt"
    13  	"io/ioutil"
    14  	"os"
    15  	"path/filepath"
    16  	"runtime"
    17  	"sort"
    18  	"strconv"
    19  	"strings"
    20  	"testing"
    21  )
    22  
    23  // pkgDeps defines the expected dependencies between packages in
    24  // the Go source tree.  It is a statement of policy.
    25  // Changes should not be made to this map without prior discussion.
    26  //
    27  // The map contains two kinds of entries:
    28  // 1) Lower-case keys are standard import paths and list the
    29  // allowed imports in that package.
    30  // 2) Upper-case keys define aliases for package sets, which can then
    31  // be used as dependencies by other rules.
    32  //
    33  // DO NOT CHANGE THIS DATA TO FIX BUILDS.
    34  //
    35  var pkgDeps = map[string][]string{
    36  	// L0 is the lowest level, core, nearly unavoidable packages.
    37  	"errors":      {},
    38  	"io":          {"errors", "sync"},
    39  	"runtime":     {"unsafe"},
    40  	"sync":        {"runtime", "sync/atomic", "unsafe"},
    41  	"sync/atomic": {"unsafe"},
    42  	"unsafe":      {},
    43  
    44  	"L0": {
    45  		"errors",
    46  		"io",
    47  		"runtime",
    48  		"sync",
    49  		"sync/atomic",
    50  		"unsafe",
    51  	},
    52  
    53  	// L1 adds simple functions and strings processing,
    54  	// but not Unicode tables.
    55  	"math":          {"unsafe"},
    56  	"math/cmplx":    {"math"},
    57  	"math/rand":     {"L0", "math"},
    58  	"sort":          {},
    59  	"strconv":       {"L0", "unicode/utf8", "math"},
    60  	"unicode/utf16": {},
    61  	"unicode/utf8":  {},
    62  
    63  	"L1": {
    64  		"L0",
    65  		"math",
    66  		"math/cmplx",
    67  		"math/rand",
    68  		"sort",
    69  		"strconv",
    70  		"unicode/utf16",
    71  		"unicode/utf8",
    72  	},
    73  
    74  	// L2 adds Unicode and strings processing.
    75  	"bufio":   {"L0", "unicode/utf8", "bytes"},
    76  	"bytes":   {"L0", "unicode", "unicode/utf8"},
    77  	"path":    {"L0", "unicode/utf8", "strings"},
    78  	"strings": {"L0", "unicode", "unicode/utf8"},
    79  	"unicode": {},
    80  
    81  	"L2": {
    82  		"L1",
    83  		"bufio",
    84  		"bytes",
    85  		"path",
    86  		"strings",
    87  		"unicode",
    88  	},
    89  
    90  	// L3 adds reflection and some basic utility packages
    91  	// and interface definitions, but nothing that makes
    92  	// system calls.
    93  	"crypto":              {"L2", "hash"},          // interfaces
    94  	"crypto/cipher":       {"L2", "crypto/subtle"}, // interfaces
    95  	"crypto/subtle":       {},
    96  	"encoding/base32":     {"L2"},
    97  	"encoding/base64":     {"L2"},
    98  	"encoding/binary":     {"L2", "reflect"},
    99  	"hash":                {"L2"}, // interfaces
   100  	"hash/adler32":        {"L2", "hash"},
   101  	"hash/crc32":          {"L2", "hash"},
   102  	"hash/crc64":          {"L2", "hash"},
   103  	"hash/fnv":            {"L2", "hash"},
   104  	"image":               {"L2", "image/color"}, // interfaces
   105  	"image/color":         {"L2"},                // interfaces
   106  	"image/color/palette": {"L2", "image/color"},
   107  	"reflect":             {"L2"},
   108  
   109  	"L3": {
   110  		"L2",
   111  		"crypto",
   112  		"crypto/cipher",
   113  		"crypto/subtle",
   114  		"encoding/base32",
   115  		"encoding/base64",
   116  		"encoding/binary",
   117  		"hash",
   118  		"hash/adler32",
   119  		"hash/crc32",
   120  		"hash/crc64",
   121  		"hash/fnv",
   122  		"image",
   123  		"image/color",
   124  		"image/color/palette",
   125  		"reflect",
   126  	},
   127  
   128  	// End of linear dependency definitions.
   129  
   130  	// Operating system access.
   131  	"syscall":                           {"L0", "unicode/utf16"},
   132  	"internal/syscall/unix":             {"L0", "syscall"},
   133  	"internal/syscall/windows":          {"L0", "syscall"},
   134  	"internal/syscall/windows/registry": {"L0", "syscall", "unicode/utf16"},
   135  	"time":          {"L0", "syscall", "internal/syscall/windows/registry"},
   136  	"os":            {"L1", "os", "syscall", "time", "internal/syscall/windows"},
   137  	"path/filepath": {"L2", "os", "syscall"},
   138  	"io/ioutil":     {"L2", "os", "path/filepath", "time"},
   139  	"os/exec":       {"L2", "os", "path/filepath", "syscall"},
   140  	"os/signal":     {"L2", "os", "syscall"},
   141  
   142  	// OS enables basic operating system functionality,
   143  	// but not direct use of package syscall, nor os/signal.
   144  	"OS": {
   145  		"io/ioutil",
   146  		"os",
   147  		"os/exec",
   148  		"path/filepath",
   149  		"time",
   150  	},
   151  
   152  	// Formatted I/O: few dependencies (L1) but we must add reflect.
   153  	"fmt": {"L1", "os", "reflect"},
   154  	"log": {"L1", "os", "fmt", "time"},
   155  
   156  	// Packages used by testing must be low-level (L2+fmt).
   157  	"regexp":         {"L2", "regexp/syntax"},
   158  	"regexp/syntax":  {"L2"},
   159  	"runtime/debug":  {"L2", "fmt", "io/ioutil", "os", "time"},
   160  	"runtime/pprof":  {"L2", "fmt", "text/tabwriter"},
   161  	"runtime/trace":  {"L0"},
   162  	"text/tabwriter": {"L2"},
   163  
   164  	"testing":          {"L2", "flag", "fmt", "os", "runtime/pprof", "runtime/trace", "time"},
   165  	"testing/iotest":   {"L2", "log"},
   166  	"testing/quick":    {"L2", "flag", "fmt", "reflect"},
   167  	"internal/testenv": {"L2", "os", "testing"},
   168  
   169  	// L4 is defined as L3+fmt+log+time, because in general once
   170  	// you're using L3 packages, use of fmt, log, or time is not a big deal.
   171  	"L4": {
   172  		"L3",
   173  		"fmt",
   174  		"log",
   175  		"time",
   176  	},
   177  
   178  	// Go parser.
   179  	"go/ast":     {"L4", "OS", "go/scanner", "go/token"},
   180  	"go/doc":     {"L4", "go/ast", "go/token", "regexp", "text/template"},
   181  	"go/parser":  {"L4", "OS", "go/ast", "go/scanner", "go/token"},
   182  	"go/printer": {"L4", "OS", "go/ast", "go/scanner", "go/token", "text/tabwriter"},
   183  	"go/scanner": {"L4", "OS", "go/token"},
   184  	"go/token":   {"L4"},
   185  
   186  	"GOPARSER": {
   187  		"go/ast",
   188  		"go/doc",
   189  		"go/parser",
   190  		"go/printer",
   191  		"go/scanner",
   192  		"go/token",
   193  	},
   194  
   195  	"go/format":       {"L4", "GOPARSER", "internal/format"},
   196  	"internal/format": {"L4", "GOPARSER"},
   197  
   198  	// Go type checking.
   199  	"go/constant":               {"L4", "go/token", "math/big"},
   200  	"go/importer":               {"L4", "go/internal/gcimporter", "go/internal/gccgoimporter", "go/types"},
   201  	"go/internal/gcimporter":    {"L4", "OS", "go/build", "go/constant", "go/token", "go/types", "text/scanner"},
   202  	"go/internal/gccgoimporter": {"L4", "OS", "debug/elf", "go/constant", "go/token", "go/types", "text/scanner"},
   203  	"go/types":                  {"L4", "GOPARSER", "container/heap", "go/constant"},
   204  
   205  	// One of a kind.
   206  	"archive/tar":              {"L4", "OS", "syscall"},
   207  	"archive/zip":              {"L4", "OS", "compress/flate"},
   208  	"container/heap":           {"sort"},
   209  	"compress/bzip2":           {"L4"},
   210  	"compress/flate":           {"L4"},
   211  	"compress/gzip":            {"L4", "compress/flate"},
   212  	"compress/lzw":             {"L4"},
   213  	"compress/zlib":            {"L4", "compress/flate"},
   214  	"database/sql":             {"L4", "container/list", "database/sql/driver"},
   215  	"database/sql/driver":      {"L4", "time"},
   216  	"debug/dwarf":              {"L4"},
   217  	"debug/elf":                {"L4", "OS", "debug/dwarf"},
   218  	"debug/gosym":              {"L4"},
   219  	"debug/macho":              {"L4", "OS", "debug/dwarf"},
   220  	"debug/pe":                 {"L4", "OS", "debug/dwarf"},
   221  	"debug/plan9obj":           {"L4", "OS"},
   222  	"encoding":                 {"L4"},
   223  	"encoding/ascii85":         {"L4"},
   224  	"encoding/asn1":            {"L4", "math/big"},
   225  	"encoding/csv":             {"L4"},
   226  	"encoding/gob":             {"L4", "OS", "encoding"},
   227  	"encoding/hex":             {"L4"},
   228  	"encoding/json":            {"L4", "encoding"},
   229  	"encoding/pem":             {"L4"},
   230  	"encoding/xml":             {"L4", "encoding"},
   231  	"flag":                     {"L4", "OS"},
   232  	"go/build":                 {"L4", "OS", "GOPARSER"},
   233  	"html":                     {"L4"},
   234  	"image/draw":               {"L4", "image/internal/imageutil"},
   235  	"image/gif":                {"L4", "compress/lzw", "image/color/palette", "image/draw"},
   236  	"image/internal/imageutil": {"L4"},
   237  	"image/jpeg":               {"L4", "image/internal/imageutil"},
   238  	"image/png":                {"L4", "compress/zlib"},
   239  	"index/suffixarray":        {"L4", "regexp"},
   240  	"internal/singleflight":    {"sync"},
   241  	"internal/trace":           {"L4", "OS"},
   242  	"math/big":                 {"L4"},
   243  	"mime":                     {"L4", "OS", "syscall", "internal/syscall/windows/registry"},
   244  	"mime/quotedprintable":     {"L4"},
   245  	"net/internal/socktest":    {"L4", "OS", "syscall"},
   246  	"net/url":                  {"L4"},
   247  	"text/scanner":             {"L4", "OS"},
   248  	"text/template/parse":      {"L4"},
   249  
   250  	"html/template": {
   251  		"L4", "OS", "encoding/json", "html", "text/template",
   252  		"text/template/parse",
   253  	},
   254  	"text/template": {
   255  		"L4", "OS", "net/url", "text/template/parse",
   256  	},
   257  
   258  	// Cgo.
   259  	"runtime/cgo": {"L0", "C"},
   260  	"CGO":         {"C", "runtime/cgo"},
   261  
   262  	// Fake entry to satisfy the pseudo-import "C"
   263  	// that shows up in programs that use cgo.
   264  	"C": {},
   265  
   266  	// Race detector/MSan uses cgo.
   267  	"runtime/race": {"C"},
   268  	"runtime/msan": {"C"},
   269  
   270  	// Plan 9 alone needs io/ioutil and os.
   271  	"os/user": {"L4", "CGO", "io/ioutil", "os", "syscall"},
   272  
   273  	// Basic networking.
   274  	// Because net must be used by any package that wants to
   275  	// do networking portably, it must have a small dependency set: just L0+basic os.
   276  	"net": {"L0", "CGO", "math/rand", "os", "sort", "syscall", "time", "internal/syscall/windows", "internal/singleflight"},
   277  
   278  	// NET enables use of basic network-related packages.
   279  	"NET": {
   280  		"net",
   281  		"mime",
   282  		"net/textproto",
   283  		"net/url",
   284  	},
   285  
   286  	// Uses of networking.
   287  	"log/syslog":    {"L4", "OS", "net"},
   288  	"net/mail":      {"L4", "NET", "OS", "mime"},
   289  	"net/textproto": {"L4", "OS", "net"},
   290  
   291  	// Core crypto.
   292  	"crypto/aes":    {"L3"},
   293  	"crypto/des":    {"L3"},
   294  	"crypto/hmac":   {"L3"},
   295  	"crypto/md5":    {"L3"},
   296  	"crypto/rc4":    {"L3"},
   297  	"crypto/sha1":   {"L3"},
   298  	"crypto/sha256": {"L3"},
   299  	"crypto/sha512": {"L3"},
   300  
   301  	"CRYPTO": {
   302  		"crypto/aes",
   303  		"crypto/des",
   304  		"crypto/hmac",
   305  		"crypto/md5",
   306  		"crypto/rc4",
   307  		"crypto/sha1",
   308  		"crypto/sha256",
   309  		"crypto/sha512",
   310  	},
   311  
   312  	// Random byte, number generation.
   313  	// This would be part of core crypto except that it imports
   314  	// math/big, which imports fmt.
   315  	"crypto/rand": {"L4", "CRYPTO", "OS", "math/big", "syscall", "internal/syscall/unix"},
   316  
   317  	// Mathematical crypto: dependencies on fmt (L4) and math/big.
   318  	// We could avoid some of the fmt, but math/big imports fmt anyway.
   319  	"crypto/dsa":      {"L4", "CRYPTO", "math/big"},
   320  	"crypto/ecdsa":    {"L4", "CRYPTO", "crypto/elliptic", "math/big", "encoding/asn1"},
   321  	"crypto/elliptic": {"L4", "CRYPTO", "math/big"},
   322  	"crypto/rsa":      {"L4", "CRYPTO", "crypto/rand", "math/big"},
   323  
   324  	"CRYPTO-MATH": {
   325  		"CRYPTO",
   326  		"crypto/dsa",
   327  		"crypto/ecdsa",
   328  		"crypto/elliptic",
   329  		"crypto/rand",
   330  		"crypto/rsa",
   331  		"encoding/asn1",
   332  		"math/big",
   333  	},
   334  
   335  	// SSL/TLS.
   336  	"crypto/tls": {
   337  		"L4", "CRYPTO-MATH", "CGO", "OS",
   338  		"container/list", "crypto/x509", "encoding/pem", "net", "syscall",
   339  	},
   340  	"crypto/x509": {
   341  		"L4", "CRYPTO-MATH", "OS", "CGO",
   342  		"crypto/x509/pkix", "encoding/pem", "encoding/hex", "net", "syscall",
   343  	},
   344  	"crypto/x509/pkix": {"L4", "CRYPTO-MATH"},
   345  
   346  	// Simple net+crypto-aware packages.
   347  	"mime/multipart": {"L4", "OS", "mime", "crypto/rand", "net/textproto", "mime/quotedprintable"},
   348  	"net/smtp":       {"L4", "CRYPTO", "NET", "crypto/tls"},
   349  
   350  	// HTTP, kingpin of dependencies.
   351  	"net/http": {
   352  		"L4", "NET", "OS",
   353  		"compress/gzip", "crypto/tls", "mime/multipart", "runtime/debug",
   354  		"net/http/internal",
   355  		"golang.org/x/net/http2/hpack",
   356  	},
   357  	"net/http/internal": {"L4"},
   358  
   359  	// HTTP-using packages.
   360  	"expvar":             {"L4", "OS", "encoding/json", "net/http"},
   361  	"net/http/cgi":       {"L4", "NET", "OS", "crypto/tls", "net/http", "regexp"},
   362  	"net/http/cookiejar": {"L4", "NET", "net/http"},
   363  	"net/http/fcgi":      {"L4", "NET", "OS", "net/http", "net/http/cgi"},
   364  	"net/http/httptest":  {"L4", "NET", "OS", "crypto/tls", "flag", "net/http"},
   365  	"net/http/httputil":  {"L4", "NET", "OS", "net/http", "net/http/internal"},
   366  	"net/http/pprof":     {"L4", "OS", "html/template", "net/http", "runtime/pprof", "runtime/trace"},
   367  	"net/rpc":            {"L4", "NET", "encoding/gob", "html/template", "net/http"},
   368  	"net/rpc/jsonrpc":    {"L4", "NET", "encoding/json", "net/rpc"},
   369  }
   370  
   371  // isMacro reports whether p is a package dependency macro
   372  // (uppercase name).
   373  func isMacro(p string) bool {
   374  	return 'A' <= p[0] && p[0] <= 'Z'
   375  }
   376  
   377  func allowed(pkg string) map[string]bool {
   378  	m := map[string]bool{}
   379  	var allow func(string)
   380  	allow = func(p string) {
   381  		if m[p] {
   382  			return
   383  		}
   384  		m[p] = true // set even for macros, to avoid loop on cycle
   385  
   386  		// Upper-case names are macro-expanded.
   387  		if isMacro(p) {
   388  			for _, pp := range pkgDeps[p] {
   389  				allow(pp)
   390  			}
   391  		}
   392  	}
   393  	for _, pp := range pkgDeps[pkg] {
   394  		allow(pp)
   395  	}
   396  	return m
   397  }
   398  
   399  var bools = []bool{false, true}
   400  var geese = []string{"android", "darwin", "dragonfly", "freebsd", "linux", "nacl", "netbsd", "openbsd", "plan9", "solaris", "windows"}
   401  var goarches = []string{"386", "amd64", "arm"}
   402  
   403  type osPkg struct {
   404  	goos, pkg string
   405  }
   406  
   407  // allowedErrors are the operating systems and packages known to contain errors
   408  // (currently just "no Go source files")
   409  var allowedErrors = map[osPkg]bool{
   410  	osPkg{"windows", "log/syslog"}: true,
   411  	osPkg{"plan9", "log/syslog"}:   true,
   412  }
   413  
   414  // listStdPkgs returns the same list of packages as "go list std".
   415  func listStdPkgs(goroot string) ([]string, error) {
   416  	// Based on cmd/go's matchPackages function.
   417  	var pkgs []string
   418  
   419  	src := filepath.Join(goroot, "src") + string(filepath.Separator)
   420  	walkFn := func(path string, fi os.FileInfo, err error) error {
   421  		if err != nil || !fi.IsDir() || path == src {
   422  			return nil
   423  		}
   424  
   425  		base := filepath.Base(path)
   426  		if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
   427  			return filepath.SkipDir
   428  		}
   429  
   430  		name := filepath.ToSlash(path[len(src):])
   431  		if name == "builtin" || name == "cmd" || strings.Contains(name, ".") {
   432  			return filepath.SkipDir
   433  		}
   434  
   435  		pkgs = append(pkgs, name)
   436  		return nil
   437  	}
   438  	if err := filepath.Walk(src, walkFn); err != nil {
   439  		return nil, err
   440  	}
   441  	return pkgs, nil
   442  }
   443  
   444  func TestDependencies(t *testing.T) {
   445  	iOS := runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64")
   446  	if runtime.GOOS == "nacl" || iOS {
   447  		// Tests run in a limited file system and we do not
   448  		// provide access to every source file.
   449  		t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
   450  	}
   451  
   452  	ctxt := Default
   453  	all, err := listStdPkgs(ctxt.GOROOT)
   454  	if err != nil {
   455  		t.Fatal(err)
   456  	}
   457  	sort.Strings(all)
   458  
   459  	for _, pkg := range all {
   460  		imports, err := findImports(pkg)
   461  		if err != nil {
   462  			t.Error(err)
   463  			continue
   464  		}
   465  		ok := allowed(pkg)
   466  		var bad []string
   467  		for _, imp := range imports {
   468  			if !ok[imp] {
   469  				bad = append(bad, imp)
   470  			}
   471  		}
   472  		if bad != nil {
   473  			t.Errorf("unexpected dependency: %s imports %v", pkg, bad)
   474  		}
   475  	}
   476  }
   477  
   478  var buildIgnore = []byte("\n// +build ignore")
   479  
   480  func findImports(pkg string) ([]string, error) {
   481  	dir := filepath.Join(Default.GOROOT, "src", pkg)
   482  	files, err := ioutil.ReadDir(dir)
   483  	if err != nil {
   484  		return nil, err
   485  	}
   486  	var imports []string
   487  	var haveImport = map[string]bool{}
   488  	for _, file := range files {
   489  		name := file.Name()
   490  		if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
   491  			continue
   492  		}
   493  		f, err := os.Open(filepath.Join(dir, name))
   494  		if err != nil {
   495  			return nil, err
   496  		}
   497  		var imp []string
   498  		data, err := readImports(f, false, &imp)
   499  		f.Close()
   500  		if err != nil {
   501  			return nil, fmt.Errorf("reading %v: %v", name, err)
   502  		}
   503  		if bytes.Contains(data, buildIgnore) {
   504  			continue
   505  		}
   506  		for _, quoted := range imp {
   507  			path, err := strconv.Unquote(quoted)
   508  			if err != nil {
   509  				continue
   510  			}
   511  			if !haveImport[path] {
   512  				haveImport[path] = true
   513  				imports = append(imports, path)
   514  			}
   515  		}
   516  	}
   517  	sort.Strings(imports)
   518  	return imports, nil
   519  }