header.go 1.6 KB

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