Commit a918864c authored by Russ Cox's avatar Russ Cox

cmd/go: split out cmd/go/internal/cfg

This is one CL in a long sequence of changes to break up the
go command from one package into a plausible group of packages.

This sequence is concerned only with moving code, not changing
or cleaning up code. There will still be more cleanup after this sequence.

The entire sequence will be submitted together: it is not a goal
for the tree to build at every step.

For #18653.

Change-Id: Icb3f168ade91e7da5fcab89ac75b768daefff359
Reviewed-on: https://go-review.googlesource.com/36191Reviewed-by: 's avatarDavid Crawshaw <crawshaw@golang.org>
parent 762eb408
......@@ -6,6 +6,7 @@ package main
import (
"bytes"
"cmd/go/internal/cfg"
"fmt"
"io"
"io/ioutil"
......@@ -28,7 +29,7 @@ The report includes useful system information.
}
func init() {
cmdBug.Flag.BoolVar(&buildV, "v", false, "")
cmdBug.Flag.BoolVar(&cfg.BuildV, "v", false, "")
}
func runBug(cmd *Command, args []string) {
......@@ -38,13 +39,13 @@ func runBug(cmd *Command, args []string) {
fmt.Fprint(&buf, "#### System details\n\n")
fmt.Fprintln(&buf, "```")
fmt.Fprintf(&buf, "go version %s %s/%s\n", runtime.Version(), runtime.GOOS, runtime.GOARCH)
env := newEnv
env := cfg.NewEnv
env = append(env, extraEnvVars()...)
for _, e := range env {
// Hide the TERM environment variable from "go bug".
// See issue #18128
if e.name != "TERM" {
fmt.Fprintf(&buf, "%s=\"%s\"\n", e.name, e.value)
if e.Name != "TERM" {
fmt.Fprintf(&buf, "%s=\"%s\"\n", e.Name, e.Value)
}
}
printGoDetails(&buf)
......@@ -97,7 +98,7 @@ func printOSDetails(w io.Writer) {
if err == nil {
fmt.Fprintf(w, "/etc/release: %s\n", out)
} else {
if buildV {
if cfg.BuildV {
fmt.Printf("failed to read /etc/release: %v\n", err)
}
}
......@@ -114,7 +115,7 @@ func printCDetails(w io.Writer) {
// Print up to the first newline.
fmt.Fprintf(w, "gdb --version: %s\n", firstLine(out))
} else {
if buildV {
if cfg.BuildV {
fmt.Printf("failed to run gdb --version: %v\n", err)
}
}
......@@ -123,7 +124,7 @@ func printCDetails(w io.Writer) {
func inspectGoVersion(w io.Writer) {
data, err := httpGET("https://golang.org/VERSION?m=text")
if err != nil {
if buildV {
if cfg.BuildV {
fmt.Printf("failed to read from golang.org/VERSION: %v\n", err)
}
return
......@@ -150,7 +151,7 @@ func printCmdOut(w io.Writer, prefix, path string, args ...string) {
cmd := exec.Command(path, args...)
out, err := cmd.Output()
if err != nil {
if buildV {
if cfg.BuildV {
fmt.Printf("%s %s: %v\n", path, strings.Join(args, " "), err)
}
return
......
This diff is collapsed.
......@@ -5,6 +5,7 @@
package main
import (
"cmd/go/internal/cfg"
"fmt"
"io/ioutil"
"os"
......@@ -172,7 +173,7 @@ func clean(p *Package) {
}
}
if buildN || buildX {
if cfg.BuildN || cfg.BuildX {
b.showcmd(p.Dir, "rm -f %s", strings.Join(allRemove, " "))
}
......@@ -185,9 +186,9 @@ func clean(p *Package) {
if dir.IsDir() {
// TODO: Remove once Makefiles are forgotten.
if cleanDir[name] {
if buildN || buildX {
if cfg.BuildN || cfg.BuildX {
b.showcmd(p.Dir, "rm -r %s", name)
if buildN {
if cfg.BuildN {
continue
}
}
......@@ -198,7 +199,7 @@ func clean(p *Package) {
continue
}
if buildN {
if cfg.BuildN {
continue
}
......@@ -208,10 +209,10 @@ func clean(p *Package) {
}
if cleanI && p.target != "" {
if buildN || buildX {
if cfg.BuildN || cfg.BuildX {
b.showcmd("", "rm -f %s", p.target)
}
if !buildN {
if !cfg.BuildN {
removeFile(p.target)
}
}
......
......@@ -6,6 +6,8 @@
package main
import "cmd/go/internal/cfg"
var cmdDoc = &Command{
Run: runDoc,
UsageLine: "doc [-u] [-c] [package|[package.]symbol[.method]]",
......@@ -114,5 +116,5 @@ Flags:
}
func runDoc(cmd *Command, args []string) {
run(buildToolExec, tool("doc"), args)
run(cfg.BuildToolexec, tool("doc"), args)
}
......@@ -5,6 +5,7 @@
package main
import (
"cmd/go/internal/cfg"
"fmt"
"os"
"runtime"
......@@ -25,22 +26,18 @@ each named variable on its own line.
`,
}
type envVar struct {
name, value string
}
func mkEnv() []envVar {
func mkEnv() []cfg.EnvVar {
var b builder
b.init()
env := []envVar{
{"GOARCH", goarch},
env := []cfg.EnvVar{
{"GOARCH", cfg.Goarch},
{"GOBIN", gobin},
{"GOEXE", exeSuffix},
{"GOEXE", cfg.ExeSuffix},
{"GOHOSTARCH", runtime.GOARCH},
{"GOHOSTOS", runtime.GOOS},
{"GOOS", goos},
{"GOPATH", buildContext.GOPATH},
{"GOOS", cfg.Goos},
{"GOPATH", cfg.BuildContext.GOPATH},
{"GORACE", os.Getenv("GORACE")},
{"GOROOT", goroot},
{"GOTOOLDIR", toolDir},
......@@ -50,48 +47,48 @@ func mkEnv() []envVar {
}
if gccgoBin != "" {
env = append(env, envVar{"GCCGO", gccgoBin})
env = append(env, cfg.EnvVar{"GCCGO", gccgoBin})
} else {
env = append(env, envVar{"GCCGO", gccgoName})
env = append(env, cfg.EnvVar{"GCCGO", gccgoName})
}
switch goarch {
switch cfg.Goarch {
case "arm":
env = append(env, envVar{"GOARM", os.Getenv("GOARM")})
env = append(env, cfg.EnvVar{"GOARM", os.Getenv("GOARM")})
case "386":
env = append(env, envVar{"GO386", os.Getenv("GO386")})
env = append(env, cfg.EnvVar{"GO386", os.Getenv("GO386")})
}
cmd := b.gccCmd(".")
env = append(env, envVar{"CC", cmd[0]})
env = append(env, envVar{"GOGCCFLAGS", strings.Join(cmd[3:], " ")})
env = append(env, cfg.EnvVar{"CC", cmd[0]})
env = append(env, cfg.EnvVar{"GOGCCFLAGS", strings.Join(cmd[3:], " ")})
cmd = b.gxxCmd(".")
env = append(env, envVar{"CXX", cmd[0]})
env = append(env, cfg.EnvVar{"CXX", cmd[0]})
if buildContext.CgoEnabled {
env = append(env, envVar{"CGO_ENABLED", "1"})
if cfg.BuildContext.CgoEnabled {
env = append(env, cfg.EnvVar{"CGO_ENABLED", "1"})
} else {
env = append(env, envVar{"CGO_ENABLED", "0"})
env = append(env, cfg.EnvVar{"CGO_ENABLED", "0"})
}
return env
}
func findEnv(env []envVar, name string) string {
func findEnv(env []cfg.EnvVar, name string) string {
for _, e := range env {
if e.name == name {
return e.value
if e.Name == name {
return e.Value
}
}
return ""
}
// extraEnvVars returns environment variables that should not leak into child processes.
func extraEnvVars() []envVar {
func extraEnvVars() []cfg.EnvVar {
var b builder
b.init()
cppflags, cflags, cxxflags, fflags, ldflags := b.cflags(&Package{})
return []envVar{
return []cfg.EnvVar{
{"PKG_CONFIG", b.pkgconfigCmd()},
{"CGO_CFLAGS", strings.Join(cflags, " ")},
{"CGO_CPPFLAGS", strings.Join(cppflags, " ")},
......@@ -102,7 +99,7 @@ func extraEnvVars() []envVar {
}
func runEnv(cmd *Command, args []string) {
env := newEnv
env := cfg.NewEnv
env = append(env, extraEnvVars()...)
if len(args) > 0 {
for _, name := range args {
......@@ -112,16 +109,16 @@ func runEnv(cmd *Command, args []string) {
}
for _, e := range env {
if e.name != "TERM" {
if e.Name != "TERM" {
switch runtime.GOOS {
default:
fmt.Printf("%s=\"%s\"\n", e.name, e.value)
fmt.Printf("%s=\"%s\"\n", e.Name, e.Value)
case "plan9":
if strings.IndexByte(e.value, '\x00') < 0 {
fmt.Printf("%s='%s'\n", e.name, strings.Replace(e.value, "'", "''", -1))
if strings.IndexByte(e.Value, '\x00') < 0 {
fmt.Printf("%s='%s'\n", e.Name, strings.Replace(e.Value, "'", "''", -1))
} else {
v := strings.Split(e.value, "\x00")
fmt.Printf("%s=(", e.name)
v := strings.Split(e.Value, "\x00")
fmt.Printf("%s=(", e.Name)
for x, s := range v {
if x > 0 {
fmt.Printf(" ")
......@@ -131,7 +128,7 @@ func runEnv(cmd *Command, args []string) {
fmt.Printf(")\n")
}
case "windows":
fmt.Printf("set %s=%s\n", e.name, e.value)
fmt.Printf("set %s=%s\n", e.Name, e.Value)
}
}
}
......
......@@ -4,7 +4,10 @@
package main
import "cmd/go/internal/str"
import (
"cmd/go/internal/cfg"
"cmd/go/internal/str"
)
var cmdFix = &Command{
Run: runFix,
......@@ -27,6 +30,6 @@ func runFix(cmd *Command, args []string) {
// Use pkg.gofiles instead of pkg.Dir so that
// the command only applies to this package,
// not to packages in subdirectories.
run(str.StringList(buildToolExec, tool("fix"), relPaths(pkg.allgofiles)))
run(str.StringList(cfg.BuildToolexec, tool("fix"), relPaths(pkg.allgofiles)))
}
}
......@@ -7,6 +7,7 @@ package main
import (
"bufio"
"bytes"
"cmd/go/internal/cfg"
"fmt"
"io"
"log"
......@@ -200,7 +201,7 @@ func (g *Generator) run() (ok bool) {
}()
g.dir, g.file = filepath.Split(g.path)
g.dir = filepath.Clean(g.dir) // No final separator please.
if buildV {
if cfg.BuildV {
fmt.Fprintf(os.Stderr, "%s\n", shortPath(g.path))
}
......@@ -255,10 +256,10 @@ func (g *Generator) run() (ok bool) {
continue
}
// Run the command line.
if buildN || buildX {
if cfg.BuildN || cfg.BuildX {
fmt.Fprintf(os.Stderr, "%s\n", strings.Join(words, " "))
}
if buildN {
if cfg.BuildN {
continue
}
g.exec(words)
......@@ -277,8 +278,8 @@ func isGoGenerate(buf []byte) bool {
// single go:generate command.
func (g *Generator) setEnv() {
g.env = []string{
"GOARCH=" + buildContext.GOARCH,
"GOOS=" + buildContext.GOOS,
"GOARCH=" + cfg.BuildContext.GOARCH,
"GOOS=" + cfg.BuildContext.GOOS,
"GOFILE=" + g.file,
"GOLINE=" + strconv.Itoa(g.lineNum),
"GOPACKAGE=" + g.pkg,
......@@ -393,7 +394,7 @@ func (g *Generator) exec(words []string) {
cmd.Stderr = os.Stderr
// Run the command in the package directory.
cmd.Dir = g.dir
cmd.Env = mergeEnvLists(g.env, origEnv)
cmd.Env = mergeEnvLists(g.env, cfg.OrigEnv)
err := cmd.Run()
if err != nil {
g.errorf("running %q: %s", words[0], err)
......
......@@ -5,6 +5,7 @@
package main
import (
"cmd/go/internal/cfg"
"cmd/go/internal/str"
"fmt"
"go/build"
......@@ -303,7 +304,7 @@ func download(arg string, parent *Package, stk *importStack, mode int) {
// due to wildcard expansion.
for _, p := range pkgs {
if *getFix {
run(buildToolExec, str.StringList(tool("fix"), relPaths(p.allgofiles)))
run(cfg.BuildToolexec, str.StringList(tool("fix"), relPaths(p.allgofiles)))
// The imports might have changed, so reload again.
p = reloadPackage(arg, stk)
......@@ -424,7 +425,7 @@ func downloadPackage(p *Package) error {
if p.build.SrcRoot == "" {
// Package not found. Put in first directory of $GOPATH.
list := filepath.SplitList(buildContext.GOPATH)
list := filepath.SplitList(cfg.BuildContext.GOPATH)
if len(list) == 0 {
return fmt.Errorf("cannot download, $GOPATH not set. For more details see: 'go help gopath'")
}
......@@ -446,7 +447,7 @@ func downloadPackage(p *Package) error {
}
downloadRootCache[root] = true
if buildV {
if cfg.BuildV {
fmt.Fprintf(os.Stderr, "%s (download)\n", rootPath)
}
......@@ -473,7 +474,7 @@ func downloadPackage(p *Package) error {
if err = os.MkdirAll(parent, 0777); err != nil {
return err
}
if buildV && !gopathExisted && p.build.Root == buildContext.GOPATH {
if cfg.BuildV && !gopathExisted && p.build.Root == cfg.BuildContext.GOPATH {
fmt.Fprintf(os.Stderr, "created GOPATH=%s; see 'go help gopath'\n", p.build.Root)
}
......@@ -487,7 +488,7 @@ func downloadPackage(p *Package) error {
}
}
if buildN {
if cfg.BuildN {
// Do not show tag sync in -n; it's noise more than anything,
// and since we're not running commands, no tag will be found.
// But avoid printing nothing.
......
......@@ -12,6 +12,7 @@
package main
import (
"cmd/go/internal/cfg"
"cmd/internal/browser"
"crypto/tls"
"fmt"
......@@ -79,7 +80,7 @@ func httpsOrHTTP(importPath string, security securityMode) (urlStr string, body
}
u.RawQuery = "go-get=1"
urlStr = u.String()
if buildV {
if cfg.BuildV {
log.Printf("Fetching %s", urlStr)
}
if security == insecure && scheme == "https" { // fail earlier
......@@ -96,7 +97,7 @@ func httpsOrHTTP(importPath string, security securityMode) (urlStr string, body
}
urlStr, res, err := fetch("https")
if err != nil {
if buildV {
if cfg.BuildV {
log.Printf("https fetch failed: %v", err)
}
if security == insecure {
......@@ -110,7 +111,7 @@ func httpsOrHTTP(importPath string, security securityMode) (urlStr string, body
}
// Note: accepting a non-200 OK here, so people can serve a
// meta import in their http 404 page.
if buildV {
if cfg.BuildV {
log.Printf("Parsing meta tags from %s (status code %d)", urlStr, res.StatusCode)
}
return urlStr, res.Body, nil
......
// Copyright 2017 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 cfg holds configuration shared by multiple parts
// of the go command.
package cfg
import (
"go/build"
"runtime"
)
// These are general "build flags" used by build and other commands.
var (
BuildA bool // -a flag
BuildBuildmode string // -buildmode flag
BuildContext = build.Default
BuildI bool // -i flag
BuildLdflags []string // -ldflags flag
BuildLinkshared bool // -linkshared flag
BuildMSan bool // -msan flag
BuildN bool // -n flag
BuildO string // -o flag
BuildP = runtime.NumCPU() // -p flag
BuildPkgdir string // -pkgdir flag
BuildRace bool // -race flag
BuildToolexec []string // -toolexec flag
BuildToolchainName string
BuildToolchainCompiler string
BuildToolchainLinker string
BuildV bool // -v flag
BuildWork bool // -work flag
BuildX bool // -x flag
)
// The test coverage mode affects package loading. Sigh.
var TestCoverMode string // -covermode flag
// An EnvVar is an environment variable Name=Value.
type EnvVar struct {
Name string
Value string
}
// OrigEnv is the original environment of the program at startup.
var OrigEnv []string
// NewEnv is the new environment for running commands.
var NewEnv []EnvVar
// Global build parameters (used during package load)
var (
Goarch string
Goos string
ExeSuffix string
Gopath []string
)
......@@ -6,6 +6,7 @@ package main
import (
"bufio"
"cmd/go/internal/cfg"
"encoding/json"
"io"
"os"
......@@ -165,7 +166,7 @@ func runList(cmd *Command, args []string) {
var cachedCtxt *Context
context := func() *Context {
if cachedCtxt == nil {
cachedCtxt = newContext(&buildContext)
cachedCtxt = newContext(&cfg.BuildContext)
}
return cachedCtxt
}
......
......@@ -7,6 +7,7 @@ package main
import (
"bufio"
"bytes"
"cmd/go/internal/cfg"
"cmd/go/internal/str"
"flag"
"fmt"
......@@ -119,9 +120,6 @@ func setExitStatus(n int) {
exitMu.Unlock()
}
var origEnv []string
var newEnv []envVar
func main() {
_ = go11tag
flag.Usage = usage
......@@ -141,7 +139,7 @@ func main() {
// Diagnose common mistake: GOPATH==GOROOT.
// This setting is equivalent to not setting GOPATH at all,
// which is not what most people want when they do it.
if gopath := buildContext.GOPATH; gopath == runtime.GOROOT() {
if gopath := cfg.BuildContext.GOPATH; gopath == runtime.GOROOT() {
fmt.Fprintf(os.Stderr, "warning: GOPATH set to GOROOT (%s) has no effect\n", gopath)
} else {
for _, p := range filepath.SplitList(gopath) {
......@@ -169,11 +167,11 @@ func main() {
// the same default computation of these as we do,
// but in practice there might be skew
// This makes sure we all agree.
origEnv = os.Environ()
newEnv = mkEnv()
for _, env := range newEnv {
if os.Getenv(env.name) != env.value {
os.Setenv(env.name, env.value)
cfg.OrigEnv = os.Environ()
cfg.NewEnv = mkEnv()
for _, env := range cfg.NewEnv {
if os.Getenv(env.Name) != env.Value {
os.Setenv(env.Name, env.Value)
}
}
......@@ -455,9 +453,9 @@ func exitIfErrors() {
func run(cmdargs ...interface{}) {
cmdline := str.StringList(cmdargs...)
if buildN || buildX {
if cfg.BuildN || cfg.BuildX {
fmt.Printf("%s\n", strings.Join(cmdline, " "))
if buildN {
if cfg.BuildN {
return
}
}
......@@ -602,12 +600,12 @@ func matchPackages(pattern string) []string {
have := map[string]bool{
"builtin": true, // ignore pseudo-package that exists only for documentation
}
if !buildContext.CgoEnabled {
if !cfg.BuildContext.CgoEnabled {
have["runtime/cgo"] = true // ignore during walk
}
var pkgs []string
for _, src := range buildContext.SrcDirs() {
for _, src := range cfg.BuildContext.SrcDirs() {
if (pattern == "std" || pattern == "cmd") && src != gorootSrc {
continue
}
......@@ -643,7 +641,7 @@ func matchPackages(pattern string) []string {
if !match(name) {
return nil
}
_, err = buildContext.ImportDir(path, 0)
_, err = cfg.BuildContext.ImportDir(path, 0)
if err != nil {
if _, noGo := err.(*build.NoGoError); noGo {
return nil
......@@ -720,7 +718,7 @@ func matchPackagesInFS(pattern string) []string {
// as not matching the pattern. Go 1.5 and earlier skipped, but that
// behavior means people miss serious mistakes.
// See golang.org/issue/11407.
if p, err := buildContext.ImportDir(path, 0); err != nil && (p == nil || len(p.InvalidGoFiles) == 0) {
if p, err := cfg.BuildContext.ImportDir(path, 0); err != nil && (p == nil || len(p.InvalidGoFiles) == 0) {
if _, noGo := err.(*build.NoGoError); !noGo {
log.Print(err)
}
......
......@@ -6,6 +6,7 @@ package main
import (
"bytes"
"cmd/go/internal/cfg"
"cmd/go/internal/str"
"crypto/sha1"
"errors"
......@@ -143,11 +144,11 @@ type CoverVar struct {
func (p *Package) copyBuild(pp *build.Package) {
p.build = pp
if pp.PkgTargetRoot != "" && buildPkgdir != "" {
if pp.PkgTargetRoot != "" && cfg.BuildPkgdir != "" {
old := pp.PkgTargetRoot
pp.PkgRoot = buildPkgdir
pp.PkgTargetRoot = buildPkgdir
pp.PkgObj = filepath.Join(buildPkgdir, strings.TrimPrefix(pp.PkgObj, old))
pp.PkgRoot = cfg.BuildPkgdir
pp.PkgTargetRoot = cfg.BuildPkgdir
pp.PkgObj = filepath.Join(cfg.BuildPkgdir, strings.TrimPrefix(pp.PkgObj, old))
}
p.Dir = pp.Dir
......@@ -364,7 +365,7 @@ func loadImport(path, srcDir string, parent *Package, stk *importStack, importPo
// Not vendoring, or we already found the vendored path.
buildMode |= build.IgnoreVendor
}
bp, err := buildContext.Import(path, srcDir, buildMode)
bp, err := cfg.BuildContext.Import(path, srcDir, buildMode)
bp.ImportPath = importPath
if gobin != "" {
bp.BinDir = gobin
......@@ -587,7 +588,7 @@ func disallowInternal(srcDir string, p *Package, stk *importStack) *Package {
}
// We can't check standard packages with gccgo.
if buildContext.Compiler == "gccgo" && p.Standard {
if cfg.BuildContext.Compiler == "gccgo" && p.Standard {
return p
}
......@@ -846,7 +847,7 @@ func (p *Package) load(stk *importStack, bp *build.Package, err error) *Package
useBindir := p.Name == "main"
if !p.Standard {
switch buildBuildmode {
switch cfg.BuildBuildmode {
case "c-archive", "c-shared", "plugin":
useBindir = false
}
......@@ -861,8 +862,8 @@ func (p *Package) load(stk *importStack, bp *build.Package, err error) *Package
return p
}
_, elem := filepath.Split(p.Dir)
full := buildContext.GOOS + "_" + buildContext.GOARCH + "/" + elem
if buildContext.GOOS != toolGOOS || buildContext.GOARCH != toolGOARCH {
full := cfg.BuildContext.GOOS + "_" + cfg.BuildContext.GOARCH + "/" + elem
if cfg.BuildContext.GOOS != toolGOOS || cfg.BuildContext.GOARCH != toolGOARCH {
// Install cross-compiled binaries to subdirectories of bin.
elem = full
}
......@@ -880,7 +881,7 @@ func (p *Package) load(stk *importStack, bp *build.Package, err error) *Package
// Override all the usual logic and force it into the tool directory.
p.target = filepath.Join(gorootPkg, "tool", full)
}
if p.target != "" && buildContext.GOOS == "windows" {
if p.target != "" && cfg.BuildContext.GOOS == "windows" {
p.target += ".exe"
}
} else if p.local {
......@@ -889,12 +890,12 @@ func (p *Package) load(stk *importStack, bp *build.Package, err error) *Package
p.target = ""
} else {
p.target = p.build.PkgObj
if buildLinkshared {
if cfg.BuildLinkshared {
shlibnamefile := p.target[:len(p.target)-2] + ".shlibname"
shlib, err := ioutil.ReadFile(shlibnamefile)
if err == nil {
libname := strings.TrimSpace(string(shlib))
if buildContext.Compiler == "gccgo" {
if cfg.BuildContext.Compiler == "gccgo" {
p.Shlib = filepath.Join(p.build.PkgTargetRoot, "shlibs", libname)
} else {
p.Shlib = filepath.Join(p.build.PkgTargetRoot, libname)
......@@ -918,23 +919,23 @@ func (p *Package) load(stk *importStack, bp *build.Package, err error) *Package
importPaths = append(importPaths, "syscall")
}
if buildContext.CgoEnabled && p.Name == "main" && !p.Goroot {
if cfg.BuildContext.CgoEnabled && p.Name == "main" && !p.Goroot {
// Currently build modes c-shared, pie (on systems that do not
// support PIE with internal linking mode), plugin, and
// -linkshared force external linking mode, as of course does
// -ldflags=-linkmode=external. External linking mode forces
// an import of runtime/cgo.
pieCgo := buildBuildmode == "pie" && (buildContext.GOOS != "linux" || buildContext.GOARCH != "amd64")
pieCgo := cfg.BuildBuildmode == "pie" && (cfg.BuildContext.GOOS != "linux" || cfg.BuildContext.GOARCH != "amd64")
linkmodeExternal := false
for i, a := range buildLdflags {
for i, a := range cfg.BuildLdflags {
if a == "-linkmode=external" {
linkmodeExternal = true
}
if a == "-linkmode" && i+1 < len(buildLdflags) && buildLdflags[i+1] == "external" {
if a == "-linkmode" && i+1 < len(cfg.BuildLdflags) && cfg.BuildLdflags[i+1] == "external" {
linkmodeExternal = true
}
}
if buildBuildmode == "c-shared" || buildBuildmode == "plugin" || pieCgo || buildLinkshared || linkmodeExternal {
if cfg.BuildBuildmode == "c-shared" || cfg.BuildBuildmode == "plugin" || pieCgo || cfg.BuildLinkshared || linkmodeExternal {
importPaths = append(importPaths, "runtime/cgo")
}
}
......@@ -945,19 +946,19 @@ func (p *Package) load(stk *importStack, bp *build.Package, err error) *Package
importPaths = append(importPaths, "runtime")
// When race detection enabled everything depends on runtime/race.
// Exclude certain packages to avoid circular dependencies.
if buildRace && (!p.Standard || !raceExclude[p.ImportPath]) {
if cfg.BuildRace && (!p.Standard || !raceExclude[p.ImportPath]) {
importPaths = append(importPaths, "runtime/race")
}
// MSan uses runtime/msan.
if buildMSan && (!p.Standard || !raceExclude[p.ImportPath]) {
if cfg.BuildMSan && (!p.Standard || !raceExclude[p.ImportPath]) {
importPaths = append(importPaths, "runtime/msan")
}
// On ARM with GOARM=5, everything depends on math for the link.
if p.Name == "main" && goarch == "arm" {
if p.Name == "main" && cfg.Goarch == "arm" {
importPaths = append(importPaths, "math")
}
// In coverage atomic mode everything depends on sync/atomic.
if testCoverMode == "atomic" && (!p.Standard || (p.ImportPath != "runtime/cgo" && p.ImportPath != "runtime/race" && p.ImportPath != "sync/atomic")) {
if cfg.TestCoverMode == "atomic" && (!p.Standard || (p.ImportPath != "runtime/cgo" && p.ImportPath != "runtime/race" && p.ImportPath != "sync/atomic")) {
importPaths = append(importPaths, "sync/atomic")
}
}
......@@ -1082,14 +1083,14 @@ func (p *Package) load(stk *importStack, bp *build.Package, err error) *Package
}
// unsafe is a fake package.
if p.Standard && (p.ImportPath == "unsafe" || buildContext.Compiler == "gccgo") {
if p.Standard && (p.ImportPath == "unsafe" || cfg.BuildContext.Compiler == "gccgo") {
p.target = ""
}
p.Target = p.target
// If cgo is not enabled, ignore cgo supporting sources
// just as we ignore go files containing import "C".
if !buildContext.CgoEnabled {
if !cfg.BuildContext.CgoEnabled {
p.CFiles = nil
p.CXXFiles = nil
p.MFiles = nil
......@@ -1102,7 +1103,7 @@ func (p *Package) load(stk *importStack, bp *build.Package, err error) *Package
}
// The gc toolchain only permits C source files with cgo.
if len(p.CFiles) > 0 && !p.usesCgo() && !p.usesSwig() && buildContext.Compiler == "gc" {
if len(p.CFiles) > 0 && !p.usesCgo() && !p.usesSwig() && cfg.BuildContext.Compiler == "gc" {
p.Error = &PackageError{
ImportStack: stk.copy(),
Err: fmt.Sprintf("C source files not allowed when not using cgo or SWIG: %s", strings.Join(p.CFiles, " ")),
......@@ -1445,7 +1446,7 @@ var isGoRelease = strings.HasPrefix(runtime.Version(), "go1")
// isStale reports whether package p needs to be rebuilt,
// along with the reason why.
func isStale(p *Package) (bool, string) {
if p.Standard && (p.ImportPath == "unsafe" || buildContext.Compiler == "gccgo") {
if p.Standard && (p.ImportPath == "unsafe" || cfg.BuildContext.Compiler == "gccgo") {
// fake, builtin package
return false, "builtin package"
}
......@@ -1473,7 +1474,7 @@ func isStale(p *Package) (bool, string) {
}
// If the -a flag is given, rebuild everything.
if buildA {
if cfg.BuildA {
return true, "build -a flag in use"
}
......@@ -1560,10 +1561,10 @@ func isStale(p *Package) (bool, string) {
// Excluding $GOROOT used to also fix issue 4106, but that's now
// taken care of above (at least when the installed Go is a released version).
if p.Root != goroot {
if olderThan(buildToolchainCompiler) {
if olderThan(cfg.BuildToolchainCompiler) {
return true, "newer compiler"
}
if p.build.IsCommand() && olderThan(buildToolchainLinker) {
if p.build.IsCommand() && olderThan(cfg.BuildToolchainLinker) {
return true, "newer linker"
}
}
......@@ -1643,7 +1644,7 @@ func computeBuildID(p *Package) {
// Include the content of runtime/internal/sys/zversion.go in the hash
// for package runtime. This will give package runtime a
// different build ID in each Go release.
if p.Standard && p.ImportPath == "runtime/internal/sys" && buildContext.Compiler != "gccgo" {
if p.Standard && p.ImportPath == "runtime/internal/sys" && cfg.BuildContext.Compiler != "gccgo" {
data, err := ioutil.ReadFile(filepath.Join(p.Dir, "zversion.go"))
if err != nil {
fatalf("go: %s", err)
......@@ -1694,7 +1695,7 @@ func loadPackage(arg string, stk *importStack) *Package {
stk.push(arg)
defer stk.pop()
bp, err := buildContext.ImportDir(filepath.Join(gorootSrc, arg), 0)
bp, err := cfg.BuildContext.ImportDir(filepath.Join(gorootSrc, arg), 0)
bp.ImportPath = arg
bp.Goroot = true
bp.BinDir = gorootBin
......@@ -1722,7 +1723,7 @@ func loadPackage(arg string, stk *importStack) *Package {
// referring to io/ioutil rather than a hypothetical import of
// "./ioutil".
if build.IsLocalImport(arg) {
bp, _ := buildContext.ImportDir(filepath.Join(cwd, arg), build.FindOnly)
bp, _ := cfg.BuildContext.ImportDir(filepath.Join(cwd, arg), build.FindOnly)
if bp.ImportPath != "" && bp.ImportPath != "." {
arg = bp.ImportPath
}
......@@ -1867,7 +1868,7 @@ var (
// It only supports the gc toolchain.
// Other toolchain maintainers should adjust this function.
func readBuildID(name, target string) (id string, err error) {
if buildToolchainName != "gc" {
if cfg.BuildToolchainName != "gc" {
return "", errBuildIDToolchain
}
......
......@@ -5,6 +5,7 @@
package main
import (
"cmd/go/internal/cfg"
"cmd/go/internal/str"
"io/ioutil"
"os"
......@@ -160,9 +161,9 @@ func TestSharedLibName(t *testing.T) {
if err != nil {
t.Fatal(err)
}
oldGopath := buildContext.GOPATH
oldGopath := cfg.BuildContext.GOPATH
defer func() {
buildContext.GOPATH = oldGopath
cfg.BuildContext.GOPATH = oldGopath
os.Chdir(cwd)
err := os.RemoveAll(tmpGopath)
if err != nil {
......@@ -174,7 +175,7 @@ func TestSharedLibName(t *testing.T) {
if err != nil {
t.Fatal(err)
}
buildContext.GOPATH = tmpGopath
cfg.BuildContext.GOPATH = tmpGopath
os.Chdir(root)
}
computed, err := libname(data.args, data.pkgs)
......
......@@ -5,6 +5,7 @@
package main
import (
"cmd/go/internal/cfg"
"cmd/go/internal/str"
"fmt"
"os"
......@@ -20,10 +21,10 @@ func findExecCmd() []string {
return execCmd
}
execCmd = []string{} // avoid work the second time
if goos == runtime.GOOS && goarch == runtime.GOARCH {
if cfg.Goos == runtime.GOOS && cfg.Goarch == runtime.GOARCH {
return execCmd
}
path, err := exec.LookPath(fmt.Sprintf("go_%s_%s_exec", goos, goarch))
path, err := exec.LookPath(fmt.Sprintf("go_%s_%s_exec", cfg.Goos, cfg.Goarch))
if err == nil {
execCmd = []string{path}
}
......@@ -117,7 +118,7 @@ func runRun(cmd *Command, args []string) {
// this case could only happen if the provided source uses cgo
// while cgo is disabled.
hint := ""
if !buildContext.CgoEnabled {
if !cfg.BuildContext.CgoEnabled {
hint = " (cgo is disabled)"
}
fatalf("go run: no suitable source files%s", hint)
......@@ -132,9 +133,9 @@ func runRun(cmd *Command, args []string) {
// been compiled. We ignore exit status.
func (b *builder) runProgram(a *action) error {
cmdline := str.StringList(findExecCmd(), a.deps[0].target, a.args)
if buildN || buildX {
if cfg.BuildN || cfg.BuildX {
b.showcmd("", "%s", strings.Join(cmdline, " "))
if buildN {
if cfg.BuildN {
return nil
}
}
......@@ -149,7 +150,7 @@ func runStdin(cmdline []string) {
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Env = origEnv
cmd.Env = cfg.OrigEnv
startSigHandlers()
if err := cmd.Run(); err != nil {
errorf("%v", err)
......
......@@ -6,6 +6,7 @@ package main
import (
"bytes"
"cmd/go/internal/cfg"
"cmd/go/internal/str"
"errors"
"fmt"
......@@ -375,9 +376,9 @@ See the documentation of the testing package for more information.
}
var (
testC bool // -c flag
testCover bool // -cover flag
testCoverMode string // -covermode flag
testC bool // -c flag
testCover bool // -cover flag
// Note: testCoverMode is cfg.TestCoverMode (-covermode)
testCoverPaths []string // -coverpkg flag
testCoverPkgs []*Package // -coverpkg flag
testO string // -o flag
......@@ -444,18 +445,18 @@ func runTest(cmd *Command, args []string) {
// In these cases, streaming the output produces the same result
// as not streaming, just more immediately.
testStreamOutput = len(pkgArgs) == 0 || testBench ||
(testShowPass && (len(pkgs) == 1 || buildP == 1))
(testShowPass && (len(pkgs) == 1 || cfg.BuildP == 1))
// For 'go test -i -o x.test', we want to build x.test. Imply -c to make the logic easier.
if buildI && testO != "" {
if cfg.BuildI && testO != "" {
testC = true
}
var b builder
b.init()
if buildI {
buildV = testV
if cfg.BuildI {
cfg.BuildV = testV
deps := make(map[string]bool)
for dep := range testMainDeps {
......@@ -479,7 +480,7 @@ func runTest(cmd *Command, args []string) {
if deps["C"] {
delete(deps, "C")
deps["runtime/cgo"] = true
if goos == runtime.GOOS && goarch == runtime.GOARCH && !buildRace && !buildMSan {
if cfg.Goos == runtime.GOOS && cfg.Goarch == runtime.GOARCH && !cfg.BuildRace && !cfg.BuildMSan {
deps["cmd/cgo"] = true
}
}
......@@ -535,7 +536,7 @@ func runTest(cmd *Command, args []string) {
p.Stale = true // rebuild
p.StaleReason = "rebuild for coverage"
p.fake = true // do not warn about rebuild
p.coverMode = testCoverMode
p.coverMode = cfg.TestCoverMode
var coverFiles []string
coverFiles = append(coverFiles, p.GoFiles...)
coverFiles = append(coverFiles, p.CgoFiles...)
......@@ -625,10 +626,10 @@ func runTest(cmd *Command, args []string) {
args = " " + args
}
extraOpts := ""
if buildRace {
if cfg.BuildRace {
extraOpts = "-race "
}
if buildMSan {
if cfg.BuildMSan {
extraOpts = "-msan "
}
fmt.Fprintf(os.Stderr, "installing these packages with 'go test %s-i%s' will speed future tests.\n\n", extraOpts, args)
......@@ -775,7 +776,7 @@ func builderTest(b *builder, p *Package) (buildAction, runAction, printAction *a
ptest.build.ImportPos = m
if localCover {
ptest.coverMode = testCoverMode
ptest.coverMode = cfg.TestCoverMode
var coverFiles []string
coverFiles = append(coverFiles, ptest.GoFiles...)
coverFiles = append(coverFiles, ptest.CgoFiles...)
......@@ -884,10 +885,10 @@ func builderTest(b *builder, p *Package) (buildAction, runAction, printAction *a
recompileForTest(pmain, p, ptest, testDir)
}
if buildContext.GOOS == "darwin" {
if buildContext.GOARCH == "arm" || buildContext.GOARCH == "arm64" {
if cfg.BuildContext.GOOS == "darwin" {
if cfg.BuildContext.GOARCH == "arm" || cfg.BuildContext.GOARCH == "arm64" {
t.IsIOS = true
t.NeedOS = true
t.NeedCgo = true
}
}
if t.TestMain == nil {
......@@ -900,7 +901,7 @@ func builderTest(b *builder, p *Package) (buildAction, runAction, printAction *a
}
}
if !buildN {
if !cfg.BuildN {
// writeTestmain writes _testmain.go. This must happen after recompileForTest,
// because recompileForTest modifies XXX.
if err := writeTestmain(filepath.Join(testDir, "_testmain.go"), t); err != nil {
......@@ -928,8 +929,8 @@ func builderTest(b *builder, p *Package) (buildAction, runAction, printAction *a
a := b.action(modeBuild, modeBuild, pmain)
a.objdir = testDir + string(filepath.Separator)
a.objpkg = filepath.Join(testDir, "main.a")
a.target = filepath.Join(testDir, testBinary) + exeSuffix
if goos == "windows" {
a.target = filepath.Join(testDir, testBinary) + cfg.ExeSuffix
if cfg.Goos == "windows" {
// There are many reserved words on Windows that,
// if used in the name of an executable, cause Windows
// to try to ask for extra permissions.
......@@ -954,7 +955,7 @@ func builderTest(b *builder, p *Package) (buildAction, runAction, printAction *a
// we could just do this always on Windows.
for _, bad := range windowsBadWords {
if strings.Contains(testBinary, bad) {
a.target = filepath.Join(testDir, "test.test") + exeSuffix
a.target = filepath.Join(testDir, "test.test") + cfg.ExeSuffix
break
}
}
......@@ -963,7 +964,7 @@ func builderTest(b *builder, p *Package) (buildAction, runAction, printAction *a
if testC || testNeedBinary {
// -c or profiling flag: create action to copy binary to ./test.out.
target := filepath.Join(cwd, testBinary+exeSuffix)
target := filepath.Join(cwd, testBinary+cfg.ExeSuffix)
if testO != "" {
target = testO
if !filepath.IsAbs(target) {
......@@ -1098,9 +1099,9 @@ func builderRunTest(b *builder, a *action) error {
args := str.StringList(findExecCmd(), a.deps[0].target, testArgs)
a.testOutput = new(bytes.Buffer)
if buildN || buildX {
if cfg.BuildN || cfg.BuildX {
b.showcmd("", "%s", strings.Join(args, " "))
if buildN {
if cfg.BuildN {
return nil
}
}
......@@ -1115,7 +1116,7 @@ func builderRunTest(b *builder, a *action) error {
cmd := exec.Command(args[0], args[1:]...)
cmd.Dir = a.p.Dir
cmd.Env = envForDir(cmd.Dir, origEnv)
cmd.Env = envForDir(cmd.Dir, cfg.OrigEnv)
var buf bytes.Buffer
if testStreamOutput {
cmd.Stdout = os.Stdout
......@@ -1227,7 +1228,7 @@ func coveragePercentage(out []byte) string {
// builderCleanTest is the action for cleaning up after a test.
func builderCleanTest(b *builder, a *action) error {
if buildWork {
if cfg.BuildWork {
return nil
}
run := a.deps[0]
......@@ -1345,7 +1346,7 @@ type testFuncs struct {
}
func (t *testFuncs) CoverMode() string {
return testCoverMode
return cfg.TestCoverMode
}
func (t *testFuncs) CoverEnabled() bool {
......
......@@ -5,6 +5,7 @@
package main
import (
"cmd/go/internal/cfg"
"flag"
"fmt"
"os"
......@@ -31,7 +32,7 @@ type testFlagSpec struct {
var testFlagDefn = []*testFlagSpec{
// local.
{name: "c", boolVar: &testC},
{name: "i", boolVar: &buildI},
{name: "i", boolVar: &cfg.BuildI},
{name: "o"},
{name: "cover", boolVar: &testCover},
{name: "covermode"},
......@@ -169,7 +170,7 @@ func testFlags(args []string) (packageNames, passToTest []string) {
case "covermode":
switch value {
case "set", "count", "atomic":
testCoverMode = value
cfg.TestCoverMode = value
default:
fatalf("invalid flag argument for -covermode: %q", value)
}
......@@ -186,11 +187,11 @@ func testFlags(args []string) (packageNames, passToTest []string) {
}
}
if testCoverMode == "" {
testCoverMode = "set"
if buildRace {
if cfg.TestCoverMode == "" {
cfg.TestCoverMode = "set"
if cfg.BuildRace {
// Default coverage mode is atomic when -race is set.
testCoverMode = "atomic"
cfg.TestCoverMode = "atomic"
}
}
......
......@@ -5,6 +5,7 @@
package main
import (
"cmd/go/internal/cfg"
"fmt"
"go/build"
"os"
......@@ -50,7 +51,7 @@ func tool(toolName string) string {
if toolIsWindows {
toolPath += toolWindowsExtension
}
if len(buildToolExec) > 0 {
if len(cfg.BuildToolexec) > 0 {
return toolPath
}
// Give a nice message if there is no tool with that name.
......@@ -115,7 +116,7 @@ func runTool(cmd *Command, args []string) {
// or we're printing command lines too (-x mode).
// Assume if command exited cleanly (even with non-zero status)
// it printed any messages it wanted to print.
if e, ok := err.(*exec.ExitError); !ok || !e.Exited() || buildX {
if e, ok := err.(*exec.ExitError); !ok || !e.Exited() || cfg.BuildX {
fmt.Fprintf(os.Stderr, "go tool %s: %s\n", toolName, err)
}
setExitStatus(1)
......
......@@ -6,6 +6,7 @@ package main
import (
"bytes"
"cmd/go/internal/cfg"
"encoding/json"
"errors"
"fmt"
......@@ -373,7 +374,7 @@ func (v *vcsCmd) run1(dir string, cmdline string, keyval []string, verbose bool)
cmd := exec.Command(v.cmd, args...)
cmd.Dir = dir
cmd.Env = envForDir(cmd.Dir, os.Environ())
if buildX {
if cfg.BuildX {
fmt.Printf("cd %s\n", dir)
fmt.Printf("%s %s\n", v.cmd, strings.Join(args, " "))
}
......@@ -383,7 +384,7 @@ func (v *vcsCmd) run1(dir string, cmdline string, keyval []string, verbose bool)
err = cmd.Run()
out := buf.Bytes()
if err != nil {
if verbose || buildV {
if verbose || cfg.BuildV {
fmt.Fprintf(os.Stderr, "# cd %s; %s %s\n", dir, v.cmd, strings.Join(args, " "))
os.Stderr.Write(out)
}
......@@ -687,7 +688,7 @@ func repoRootForImportDynamic(importPath string, security securityMode) (*repoRo
}
return nil, fmt.Errorf("parse %s: no go-import meta tags (%s)", urlStr, err)
}
if buildV {
if cfg.BuildV {
log.Printf("get %q: found meta tag %#v at %s", importPath, mmi, urlStr)
}
// If the import was "uni.edu/bob/project", which said the
......@@ -697,7 +698,7 @@ func repoRootForImportDynamic(importPath string, security securityMode) (*repoRo
// non-evil student). Instead, first verify the root and see
// if it matches Bob's claim.
if mmi.Prefix != importPath {
if buildV {
if cfg.BuildV {
log.Printf("get %q: verifying non-authoritative meta tag", importPath)
}
urlStr0 := urlStr
......
......@@ -7,6 +7,7 @@ package main
import (
"path/filepath"
"cmd/go/internal/cfg"
"cmd/go/internal/str"
)
......@@ -52,5 +53,5 @@ func runVetFiles(p *Package, files []string) {
for i := range files {
files[i] = filepath.Join(p.Dir, files[i])
}
run(buildToolExec, tool("vet"), relPaths(files))
run(cfg.BuildToolexec, tool("vet"), relPaths(files))
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment