kcl-lang.io/kpm@v0.8.7-0.20240520061008-9fc4c5efc8c7/pkg/3rdparty/gover/toolchain.go (about) 1 // Copyright 2023 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 gover 6 7 import ( 8 "context" 9 "errors" 10 "strings" 11 ) 12 13 // FromToolchain returns the Go version for the named toolchain, 14 // derived from the name itself (not by running the toolchain). 15 // A toolchain is named "goVERSION". 16 // A suffix after the VERSION introduced by a -, space, or tab is removed. 17 // Examples: 18 // 19 // FromToolchain("go1.2.3") == "1.2.3" 20 // FromToolchain("go1.2.3-bigcorp") == "1.2.3" 21 // FromToolchain("invalid") == "" 22 func FromToolchain(name string) string { 23 if strings.ContainsAny(name, "\\/") { 24 // The suffix must not include a path separator, since that would cause 25 // exec.LookPath to resolve it from a relative directory instead of from 26 // $PATH. 27 return "" 28 } 29 30 var v string 31 if strings.HasPrefix(name, "go") { 32 v = name[2:] 33 } else { 34 return "" 35 } 36 // Some builds use custom suffixes; strip them. 37 if i := strings.IndexAny(v, " \t-"); i >= 0 { 38 v = v[:i] 39 } 40 if !IsValid(v) { 41 return "" 42 } 43 return v 44 } 45 46 func maybeToolchainVersion(name string) string { 47 if IsValid(name) { 48 return name 49 } 50 return FromToolchain(name) 51 } 52 53 // ToolchainMax returns the maximum of x and y interpreted as toolchain names, 54 // compared using Compare(FromToolchain(x), FromToolchain(y)). 55 // If x and y compare equal, Max returns x. 56 func ToolchainMax(x, y string) string { 57 if Compare(FromToolchain(x), FromToolchain(y)) < 0 { 58 return y 59 } 60 return x 61 } 62 63 // Startup records the information that went into the startup-time version switch. 64 // It is initialized by switchGoToolchain. 65 var Startup struct { 66 GOTOOLCHAIN string // $GOTOOLCHAIN setting 67 AutoFile string // go.mod or go.work file consulted 68 AutoGoVersion string // go line found in file 69 AutoToolchain string // toolchain line found in file 70 } 71 72 // A TooNewError explains that a module is too new for this version of Go. 73 type TooNewError struct { 74 What string 75 GoVersion string 76 Toolchain string // for callers if they want to use it, but not printed 77 } 78 79 var ErrTooNew = errors.New("module too new") 80 81 func (e *TooNewError) Is(err error) bool { 82 return err == ErrTooNew 83 } 84 85 // A Switcher provides the ability to switch to a new toolchain in response to TooNewErrors. 86 // See [cmd/go/internal/toolchain.Switcher] for documentation. 87 type Switcher interface { 88 Error(err error) 89 Switch(ctx context.Context) 90 }