github.com/jd-ly/tools@v0.5.7/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}}`}
    18  	inv.Env = append(append([]string{}, inv.Env...), "GO111MODULE=off")
    19  	// Unset any unneeded flags.
    20  	inv.ModFile = ""
    21  	inv.ModFlag = ""
    22  	stdoutBytes, err := r.Run(ctx, inv)
    23  	if err != nil {
    24  		return 0, err
    25  	}
    26  	stdout := stdoutBytes.String()
    27  	if len(stdout) < 3 {
    28  		return 0, fmt.Errorf("bad ReleaseTags output: %q", stdout)
    29  	}
    30  	// Split up "[go1.1 go1.15]"
    31  	tags := strings.Fields(stdout[1 : len(stdout)-2])
    32  	for i := len(tags) - 1; i >= 0; i-- {
    33  		var version int
    34  		if _, err := fmt.Sscanf(tags[i], "go1.%d", &version); err != nil {
    35  			continue
    36  		}
    37  		return version, nil
    38  	}
    39  	return 0, fmt.Errorf("no parseable ReleaseTags in %v", tags)
    40  }