info.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2023 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package externalaccount
  15. import (
  16. "runtime"
  17. "strings"
  18. "unicode"
  19. )
  20. var (
  21. // version is a package internal global variable for testing purposes.
  22. version = runtime.Version
  23. )
  24. // versionUnknown is only used when the runtime version cannot be determined.
  25. const versionUnknown = "UNKNOWN"
  26. // goVersion returns a Go runtime version derived from the runtime environment
  27. // that is modified to be suitable for reporting in a header, meaning it has no
  28. // whitespace. If it is unable to determine the Go runtime version, it returns
  29. // versionUnknown.
  30. func goVersion() string {
  31. const develPrefix = "devel +"
  32. s := version()
  33. if strings.HasPrefix(s, develPrefix) {
  34. s = s[len(develPrefix):]
  35. if p := strings.IndexFunc(s, unicode.IsSpace); p >= 0 {
  36. s = s[:p]
  37. }
  38. return s
  39. } else if p := strings.IndexFunc(s, unicode.IsSpace); p >= 0 {
  40. s = s[:p]
  41. }
  42. notSemverRune := func(r rune) bool {
  43. return !strings.ContainsRune("0123456789.", r)
  44. }
  45. if strings.HasPrefix(s, "go1") {
  46. s = s[2:]
  47. var prerelease string
  48. if p := strings.IndexFunc(s, notSemverRune); p >= 0 {
  49. s, prerelease = s[:p], s[p:]
  50. }
  51. if strings.HasSuffix(s, ".") {
  52. s += "0"
  53. } else if strings.Count(s, ".") < 2 {
  54. s += ".0"
  55. }
  56. if prerelease != "" {
  57. // Some release candidates already have a dash in them.
  58. if !strings.HasPrefix(prerelease, "-") {
  59. prerelease = "-" + prerelease
  60. }
  61. s += prerelease
  62. }
  63. return s
  64. }
  65. return versionUnknown
  66. }