github.com/d4l3k/go@v0.0.0-20151015000803-65fc379daeda/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 uses cgo.
   267  	"runtime/race": {"C"},
   268  
   269  	// Plan 9 alone needs io/ioutil and os.
   270  	"os/user": {"L4", "CGO", "io/ioutil", "os", "syscall"},
   271  
   272  	// Basic networking.
   273  	// Because net must be used by any package that wants to
   274  	// do networking portably, it must have a small dependency set: just L0+basic os.
   275  	"net": {"L0", "CGO", "math/rand", "os", "sort", "syscall", "time", "internal/syscall/windows", "internal/singleflight"},
   276  
   277  	// NET enables use of basic network-related packages.
   278  	"NET": {
   279  		"net",
   280  		"mime",
   281  		"net/textproto",
   282  		"net/url",
   283  	},
   284  
   285  	// Uses of networking.
   286  	"log/syslog":    {"L4", "OS", "net"},
   287  	"net/mail":      {"L4", "NET", "OS", "mime"},
   288  	"net/textproto": {"L4", "OS", "net"},
   289  
   290  	// Core crypto.
   291  	"crypto/aes":    {"L3"},
   292  	"crypto/des":    {"L3"},
   293  	"crypto/hmac":   {"L3"},
   294  	"crypto/md5":    {"L3"},
   295  	"crypto/rc4":    {"L3"},
   296  	"crypto/sha1":   {"L3"},
   297  	"crypto/sha256": {"L3"},
   298  	"crypto/sha512": {"L3"},
   299  
   300  	"CRYPTO": {
   301  		"crypto/aes",
   302  		"crypto/des",
   303  		"crypto/hmac",
   304  		"crypto/md5",
   305  		"crypto/rc4",
   306  		"crypto/sha1",
   307  		"crypto/sha256",
   308  		"crypto/sha512",
   309  	},
   310  
   311  	// Random byte, number generation.
   312  	// This would be part of core crypto except that it imports
   313  	// math/big, which imports fmt.
   314  	"crypto/rand": {"L4", "CRYPTO", "OS", "math/big", "syscall", "internal/syscall/unix"},
   315  
   316  	// Mathematical crypto: dependencies on fmt (L4) and math/big.
   317  	// We could avoid some of the fmt, but math/big imports fmt anyway.
   318  	"crypto/dsa":      {"L4", "CRYPTO", "math/big"},
   319  	"crypto/ecdsa":    {"L4", "CRYPTO", "crypto/elliptic", "math/big", "encoding/asn1"},
   320  	"crypto/elliptic": {"L4", "CRYPTO", "math/big"},
   321  	"crypto/rsa":      {"L4", "CRYPTO", "crypto/rand", "math/big"},
   322  
   323  	"CRYPTO-MATH": {
   324  		"CRYPTO",
   325  		"crypto/dsa",
   326  		"crypto/ecdsa",
   327  		"crypto/elliptic",
   328  		"crypto/rand",
   329  		"crypto/rsa",
   330  		"encoding/asn1",
   331  		"math/big",
   332  	},
   333  
   334  	// SSL/TLS.
   335  	"crypto/tls": {
   336  		"L4", "CRYPTO-MATH", "CGO", "OS",
   337  		"container/list", "crypto/x509", "encoding/pem", "net", "syscall",
   338  	},
   339  	"crypto/x509": {
   340  		"L4", "CRYPTO-MATH", "OS", "CGO",
   341  		"crypto/x509/pkix", "encoding/pem", "encoding/hex", "net", "syscall",
   342  	},
   343  	"crypto/x509/pkix": {"L4", "CRYPTO-MATH"},
   344  
   345  	// Simple net+crypto-aware packages.
   346  	"mime/multipart": {"L4", "OS", "mime", "crypto/rand", "net/textproto", "mime/quotedprintable"},
   347  	"net/smtp":       {"L4", "CRYPTO", "NET", "crypto/tls"},
   348  
   349  	// HTTP, kingpin of dependencies.
   350  	"net/http": {
   351  		"L4", "NET", "OS",
   352  		"compress/gzip", "crypto/tls", "mime/multipart", "runtime/debug",
   353  		"net/http/internal",
   354  		"golang.org/x/net/http2/hpack",
   355  	},
   356  	"net/http/internal": {"L4"},
   357  
   358  	// HTTP-using packages.
   359  	"expvar":             {"L4", "OS", "encoding/json", "net/http"},
   360  	"net/http/cgi":       {"L4", "NET", "OS", "crypto/tls", "net/http", "regexp"},
   361  	"net/http/cookiejar": {"L4", "NET", "net/http"},
   362  	"net/http/fcgi":      {"L4", "NET", "OS", "net/http", "net/http/cgi"},
   363  	"net/http/httptest":  {"L4", "NET", "OS", "crypto/tls", "flag", "net/http"},
   364  	"net/http/httputil":  {"L4", "NET", "OS", "net/http", "net/http/internal"},
   365  	"net/http/pprof":     {"L4", "OS", "html/template", "net/http", "runtime/pprof", "runtime/trace"},
   366  	"net/rpc":            {"L4", "NET", "encoding/gob", "html/template", "net/http"},
   367  	"net/rpc/jsonrpc":    {"L4", "NET", "encoding/json", "net/rpc"},
   368  }
   369  
   370  // isMacro reports whether p is a package dependency macro
   371  // (uppercase name).
   372  func isMacro(p string) bool {
   373  	return 'A' <= p[0] && p[0] <= 'Z'
   374  }
   375  
   376  func allowed(pkg string) map[string]bool {
   377  	m := map[string]bool{}
   378  	var allow func(string)
   379  	allow = func(p string) {
   380  		if m[p] {
   381  			return
   382  		}
   383  		m[p] = true // set even for macros, to avoid loop on cycle
   384  
   385  		// Upper-case names are macro-expanded.
   386  		if isMacro(p) {
   387  			for _, pp := range pkgDeps[p] {
   388  				allow(pp)
   389  			}
   390  		}
   391  	}
   392  	for _, pp := range pkgDeps[pkg] {
   393  		allow(pp)
   394  	}
   395  	return m
   396  }
   397  
   398  var bools = []bool{false, true}
   399  var geese = []string{"android", "darwin", "dragonfly", "freebsd", "linux", "nacl", "netbsd", "openbsd", "plan9", "solaris", "windows"}
   400  var goarches = []string{"386", "amd64", "arm"}
   401  
   402  type osPkg struct {
   403  	goos, pkg string
   404  }
   405  
   406  // allowedErrors are the operating systems and packages known to contain errors
   407  // (currently just "no Go source files")
   408  var allowedErrors = map[osPkg]bool{
   409  	osPkg{"windows", "log/syslog"}: true,
   410  	osPkg{"plan9", "log/syslog"}:   true,
   411  }
   412  
   413  // listStdPkgs returns the same list of packages as "go list std".
   414  func listStdPkgs(goroot string) ([]string, error) {
   415  	// Based on cmd/go's matchPackages function.
   416  	var pkgs []string
   417  
   418  	src := filepath.Join(goroot, "src") + string(filepath.Separator)
   419  	walkFn := func(path string, fi os.FileInfo, err error) error {
   420  		if err != nil || !fi.IsDir() || path == src {
   421  			return nil
   422  		}
   423  
   424  		base := filepath.Base(path)
   425  		if strings.HasPrefix(base, ".") || strings.HasPrefix(base, "_") || base == "testdata" {
   426  			return filepath.SkipDir
   427  		}
   428  
   429  		name := filepath.ToSlash(path[len(src):])
   430  		if name == "builtin" || name == "cmd" || strings.Contains(name, ".") {
   431  			return filepath.SkipDir
   432  		}
   433  
   434  		pkgs = append(pkgs, name)
   435  		return nil
   436  	}
   437  	if err := filepath.Walk(src, walkFn); err != nil {
   438  		return nil, err
   439  	}
   440  	return pkgs, nil
   441  }
   442  
   443  func TestDependencies(t *testing.T) {
   444  	iOS := runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64")
   445  	if runtime.GOOS == "nacl" || iOS {
   446  		// Tests run in a limited file system and we do not
   447  		// provide access to every source file.
   448  		t.Skipf("skipping on %s/%s, missing full GOROOT", runtime.GOOS, runtime.GOARCH)
   449  	}
   450  
   451  	ctxt := Default
   452  	all, err := listStdPkgs(ctxt.GOROOT)
   453  	if err != nil {
   454  		t.Fatal(err)
   455  	}
   456  	sort.Strings(all)
   457  
   458  	test := func(mustImport bool) {
   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  	test(true)
   478  }
   479  
   480  var buildIgnore = []byte("\n// +build ignore")
   481  
   482  func findImports(pkg string) ([]string, error) {
   483  	dir := filepath.Join(Default.GOROOT, "src", pkg)
   484  	files, err := ioutil.ReadDir(dir)
   485  	if err != nil {
   486  		return nil, err
   487  	}
   488  	var imports []string
   489  	var haveImport = map[string]bool{}
   490  	for _, file := range files {
   491  		name := file.Name()
   492  		if !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") {
   493  			continue
   494  		}
   495  		f, err := os.Open(filepath.Join(dir, name))
   496  		if err != nil {
   497  			return nil, err
   498  		}
   499  		var imp []string
   500  		data, err := readImports(f, false, &imp)
   501  		f.Close()
   502  		if err != nil {
   503  			return nil, fmt.Errorf("reading %v: %v", name, err)
   504  		}
   505  		if bytes.Contains(data, buildIgnore) {
   506  			continue
   507  		}
   508  		for _, quoted := range imp {
   509  			path, err := strconv.Unquote(quoted)
   510  			if err != nil {
   511  				continue
   512  			}
   513  			if !haveImport[path] {
   514  				haveImport[path] = true
   515  				imports = append(imports, path)
   516  			}
   517  		}
   518  	}
   519  	sort.Strings(imports)
   520  	return imports, nil
   521  }