mod.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package mod
  2. import (
  3. "runtime/debug"
  4. "sync"
  5. "golang.org/x/mod/module"
  6. "golang.org/x/mod/semver"
  7. )
  8. var (
  9. buildInfoOnce sync.Once
  10. buildInfo *debug.BuildInfo
  11. )
  12. func Version(name string) (modVersion string) {
  13. return moduleVersion(name, readBuildInfo())
  14. }
  15. func moduleVersion(name string, bi *debug.BuildInfo) (modVersion string) {
  16. if bi == nil {
  17. return
  18. }
  19. // iterate over all dependencies and find buildkit
  20. for _, dep := range bi.Deps {
  21. if dep.Path != name {
  22. continue
  23. }
  24. // get the version of buildkit dependency
  25. modVersion = dep.Version
  26. if dep.Replace != nil {
  27. // if the version is replaced, get the replaced version
  28. modVersion = dep.Replace.Version
  29. }
  30. if !module.IsPseudoVersion(modVersion) {
  31. return
  32. }
  33. // if the version is a pseudo version, get the base version
  34. // e.g. v0.10.7-0.20230306143919-70f2ad56d3e5 => v0.10.6
  35. if base, err := module.PseudoVersionBase(modVersion); err == nil && base != "" {
  36. // set canonical version of the base version (removes +incompatible suffix)
  37. // e.g. v2.1.2+incompatible => v2.1.2
  38. base = semver.Canonical(base)
  39. // if the version is a pseudo version, get the revision
  40. // e.g. v0.10.7-0.20230306143919-70f2ad56d3e5 => 70f2ad56d3e5
  41. if rev, err := module.PseudoVersionRev(modVersion); err == nil && rev != "" {
  42. // append the revision to the version
  43. // e.g. v0.10.7-0.20230306143919-70f2ad56d3e5 => v0.10.6+70f2ad56d3e5
  44. modVersion = base + "+" + rev
  45. } else {
  46. // if the revision is not available, use the base version
  47. modVersion = base
  48. }
  49. }
  50. break
  51. }
  52. return
  53. }
  54. func readBuildInfo() *debug.BuildInfo {
  55. buildInfoOnce.Do(func() {
  56. buildInfo, _ = debug.ReadBuildInfo()
  57. })
  58. return buildInfo
  59. }