Skip to content

Commit 831255e

Browse files
authored
Merge pull request github#11832 from github/mbg/fix/go-version-warnings
Go: Handle output from `go version` more gracefully
2 parents f3914ff + 1ef1d63 commit 831255e

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

go/extractor/cli/go-autobuilder/go-autobuilder.go

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package main
22

33
import (
4+
"bufio"
45
"fmt"
56
"io/ioutil"
67
"log"
@@ -56,11 +57,23 @@ func getEnvGoVersion() string {
5657
if err != nil {
5758
log.Fatalf("Unable to run the go command, is it installed?\nError: %s", err.Error())
5859
}
59-
goVersion = strings.Fields(string(gover))[2]
60+
goVersion = parseGoVersion(string(gover))
6061
}
6162
return goVersion
6263
}
6364

65+
// The 'go version' command may output warnings on separate lines before
66+
// the actual version string is printed. This function parses the output
67+
// to retrieve just the version string.
68+
func parseGoVersion(data string) string {
69+
var lastLine string
70+
sc := bufio.NewScanner(strings.NewReader(data))
71+
for sc.Scan() {
72+
lastLine = sc.Text()
73+
}
74+
return strings.Fields(lastLine)[2]
75+
}
76+
6477
// Returns the current Go version in semver format, e.g. v1.14.4
6578
func getEnvGoSemVer() string {
6679
goVersion := getEnvGoVersion()

go/extractor/cli/go-autobuilder/go-autobuilder_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,16 @@ func TestGetImportPathFromRepoURL(t *testing.T) {
2020
}
2121
}
2222
}
23+
24+
func TestParseGoVersion(t *testing.T) {
25+
tests := map[string]string{
26+
"go version go1.18.9 linux/amd64": "go1.18.9",
27+
"warning: GOPATH set to GOROOT (/usr/local/go) has no effect\ngo version go1.18.9 linux/amd64": "go1.18.9",
28+
}
29+
for input, expected := range tests {
30+
actual := parseGoVersion(input)
31+
if actual != expected {
32+
t.Errorf("Expected parseGoVersion(\"%s\") to be \"%s\", but got \"%s\".", input, expected, actual)
33+
}
34+
}
35+
}

0 commit comments

Comments
 (0)