Merge pull request #11832 from github/mbg/fix/go-version-warnings

Go: Handle output from `go version` more gracefully
This commit is contained in:
Chris Smowton
2023-01-06 14:05:39 +00:00
committed by GitHub
2 changed files with 27 additions and 1 deletions

View File

@@ -1,6 +1,7 @@
package main
import (
"bufio"
"fmt"
"io/ioutil"
"log"
@@ -56,11 +57,23 @@ func getEnvGoVersion() string {
if err != nil {
log.Fatalf("Unable to run the go command, is it installed?\nError: %s", err.Error())
}
goVersion = strings.Fields(string(gover))[2]
goVersion = parseGoVersion(string(gover))
}
return goVersion
}
// The 'go version' command may output warnings on separate lines before
// the actual version string is printed. This function parses the output
// to retrieve just the version string.
func parseGoVersion(data string) string {
var lastLine string
sc := bufio.NewScanner(strings.NewReader(data))
for sc.Scan() {
lastLine = sc.Text()
}
return strings.Fields(lastLine)[2]
}
// Returns the current Go version in semver format, e.g. v1.14.4
func getEnvGoSemVer() string {
goVersion := getEnvGoVersion()

View File

@@ -20,3 +20,16 @@ func TestGetImportPathFromRepoURL(t *testing.T) {
}
}
}
func TestParseGoVersion(t *testing.T) {
tests := map[string]string{
"go version go1.18.9 linux/amd64": "go1.18.9",
"warning: GOPATH set to GOROOT (/usr/local/go) has no effect\ngo version go1.18.9 linux/amd64": "go1.18.9",
}
for input, expected := range tests {
actual := parseGoVersion(input)
if actual != expected {
t.Errorf("Expected parseGoVersion(\"%s\") to be \"%s\", but got \"%s\".", input, expected, actual)
}
}
}