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