github.com/powerman/golang-tools@v0.1.11-0.20220410185822-5ad214d8d803/internal/gocommand/version.go (about) 1 // Copyright 2020 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package gocommand 6 7 import ( 8 "context" 9 "fmt" 10 "strings" 11 ) 12 13 // GoVersion checks the go version by running "go list" with modules off. 14 // It returns the X in Go 1.X. 15 func GoVersion(ctx context.Context, inv Invocation, r *Runner) (int, error) { 16 inv.Verb = "list" 17 inv.Args = []string{"-e", "-f", `{{context.ReleaseTags}}`, `--`, `unsafe`} 18 inv.Env = append(append([]string{}, inv.Env...), "GO111MODULE=off") 19 // Unset any unneeded flags, and remove them from BuildFlags, if they're 20 // present. 21 inv.ModFile = "" 22 inv.ModFlag = "" 23 var buildFlags []string 24 for _, flag := range inv.BuildFlags { 25 // Flags can be prefixed by one or two dashes. 26 f := strings.TrimPrefix(strings.TrimPrefix(flag, "-"), "-") 27 if strings.HasPrefix(f, "mod=") || strings.HasPrefix(f, "modfile=") { 28 continue 29 } 30 buildFlags = append(buildFlags, flag) 31 } 32 inv.BuildFlags = buildFlags 33 stdoutBytes, err := r.Run(ctx, inv) 34 if err != nil { 35 return 0, err 36 } 37 stdout := stdoutBytes.String() 38 if len(stdout) < 3 { 39 return 0, fmt.Errorf("bad ReleaseTags output: %q", stdout) 40 } 41 // Split up "[go1.1 go1.15]" 42 tags := strings.Fields(stdout[1 : len(stdout)-2]) 43 for i := len(tags) - 1; i >= 0; i-- { 44 var version int 45 if _, err := fmt.Sscanf(tags[i], "go1.%d", &version); err != nil { 46 continue 47 } 48 return version, nil 49 } 50 return 0, fmt.Errorf("no parseable ReleaseTags in %v", tags) 51 }