aboutsummaryrefslogtreecommitdiff
path: root/src/cmd/go/internal/work/testgo.go
blob: 8b77871b23f26922b4612c9017522710f1511af5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// 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.

// This file contains extra hooks for testing the go command.

//go:build testgo
// +build testgo

package work

import (
	"cmd/go/internal/cfg"
	"cmd/go/internal/search"
	"fmt"
	"os"
	"path/filepath"
	"runtime"
)

func init() {
	if v := os.Getenv("TESTGO_VERSION"); v != "" {
		runtimeVersion = v
	}

	if testGOROOT := os.Getenv("TESTGO_GOROOT"); testGOROOT != "" {
		// Disallow installs to the GOROOT from which testgo was built.
		// Installs to other GOROOTs — such as one set explicitly within a test — are ok.
		allowInstall = func(a *Action) error {
			if cfg.BuildN {
				return nil
			}

			rel := search.InDir(a.Target, testGOROOT)
			if rel == "" {
				return nil
			}

			callerPos := ""
			if _, file, line, ok := runtime.Caller(1); ok {
				if shortFile := search.InDir(file, filepath.Join(testGOROOT, "src")); shortFile != "" {
					file = shortFile
				}
				callerPos = fmt.Sprintf("%s:%d: ", file, line)
			}
			return fmt.Errorf("%stestgo must not write to GOROOT (installing to %s)", callerPos, filepath.Join("GOROOT", rel))
		}
	}
}