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