header.go raw

   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 externalaccount
   6  
   7  import (
   8  	"runtime"
   9  	"strings"
  10  	"unicode"
  11  )
  12  
  13  var (
  14  	// version is a package internal global variable for testing purposes.
  15  	version = runtime.Version
  16  )
  17  
  18  // versionUnknown is only used when the runtime version cannot be determined.
  19  const versionUnknown = "UNKNOWN"
  20  
  21  // goVersion returns a Go runtime version derived from the runtime environment
  22  // that is modified to be suitable for reporting in a header, meaning it has no
  23  // whitespace. If it is unable to determine the Go runtime version, it returns
  24  // versionUnknown.
  25  func goVersion() string {
  26  	const develPrefix = "devel +"
  27  
  28  	s := version()
  29  	if strings.HasPrefix(s, develPrefix) {
  30  		s = s[len(develPrefix):]
  31  		if p := strings.IndexFunc(s, unicode.IsSpace); p >= 0 {
  32  			s = s[:p]
  33  		}
  34  		return s
  35  	} else if p := strings.IndexFunc(s, unicode.IsSpace); p >= 0 {
  36  		s = s[:p]
  37  	}
  38  
  39  	notSemverRune := func(r rune) bool {
  40  		return !strings.ContainsRune("0123456789.", r)
  41  	}
  42  
  43  	if strings.HasPrefix(s, "go1") {
  44  		s = s[2:]
  45  		var prerelease string
  46  		if p := strings.IndexFunc(s, notSemverRune); p >= 0 {
  47  			s, prerelease = s[:p], s[p:]
  48  		}
  49  		if strings.HasSuffix(s, ".") {
  50  			s += "0"
  51  		} else if strings.Count(s, ".") < 2 {
  52  			s += ".0"
  53  		}
  54  		if prerelease != "" {
  55  			// Some release candidates already have a dash in them.
  56  			if !strings.HasPrefix(prerelease, "-") {
  57  				prerelease = "-" + prerelease
  58  			}
  59  			s += prerelease
  60  		}
  61  		return s
  62  	}
  63  	return "UNKNOWN"
  64  }
  65