-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathinstall_go_version.go
75 lines (62 loc) · 1.96 KB
/
install_go_version.go
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package build
import (
"context"
"fmt"
"os"
"os/exec"
"strings"
"github.com/hashicorp/go-version"
)
var v1_21 = version.Must(version.NewVersion("1.21"))
// installGoVersion installs given version of Go using Go
// according to https://golang.org/doc/manage-install
func (gb *GoBuild) installGoVersion(ctx context.Context, v *version.Version) (Go, error) {
goVersion := v.String()
// trim 0 patch versions as that's how Go does it
// for versions prior to 1.21
// See https://github.com/golang/go/issues/62136
if v.LessThan(v1_21) {
versionString := v.Core().String()
goVersion = strings.TrimSuffix(versionString, ".0")
}
pkgURL := fmt.Sprintf("golang.org/dl/go%s", goVersion)
gb.log().Printf("go getting %q", pkgURL)
cmd := exec.CommandContext(ctx, "go", "get", pkgURL)
out, err := cmd.CombinedOutput()
if err != nil {
return Go{}, fmt.Errorf("unable to get Go %s: %w\n%s", v, err, out)
}
gb.log().Printf("go installing %q", pkgURL)
cmd = exec.CommandContext(ctx, "go", "install", pkgURL)
out, err = cmd.CombinedOutput()
if err != nil {
return Go{}, fmt.Errorf("unable to install Go %s: %w\n%s", v, err, out)
}
cmdName := fmt.Sprintf("go%s", goVersion)
gb.log().Printf("downloading go %q", v)
cmd = exec.CommandContext(ctx, cmdName, "download")
out, err = cmd.CombinedOutput()
if err != nil {
return Go{}, fmt.Errorf("unable to download Go %s: %w\n%s", v, err, out)
}
gb.log().Printf("download of go %q finished", v)
cleanupFunc := func(ctx context.Context) {
cmd = exec.CommandContext(ctx, cmdName, "env", "GOROOT")
out, err = cmd.CombinedOutput()
if err != nil {
return
}
rootPath := strings.TrimSpace(string(out))
// run some extra checks before deleting, just to be sure
if rootPath != "" && strings.HasSuffix(rootPath, v.String()) {
os.RemoveAll(rootPath)
}
}
return Go{
Cmd: cmdName,
CleanupFunc: cleanupFunc,
Version: v,
}, nil
}