version.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package version
  2. import (
  3. "fmt"
  4. )
  5. // Version is a structured representation of a version number.
  6. type Version struct {
  7. Major int // Major version number.
  8. Minor int // Minor version number.
  9. Patch int // Patch version number.
  10. Extension string // Version extension, such as pre-release number or build metdata.
  11. Text string // Original version string, if this version was created via the Parse function.
  12. }
  13. // Compare this version (a) with another version (b).
  14. // This function returns -1 if a is less than b, 1 if a is greater than b, or 0 if a is equal to b.
  15. //
  16. // Extensions such as pre-release version or build metadata are ignored when comparing versions.
  17. func (a *Version) Compare(b *Version) int {
  18. if a == nil || b == nil {
  19. return 0
  20. }
  21. if a.Major == b.Major {
  22. if a.Minor == b.Minor {
  23. if a.Patch == b.Patch {
  24. return 0
  25. } else if a.Patch > b.Patch {
  26. return 1
  27. }
  28. } else if a.Minor > b.Minor {
  29. return 1
  30. }
  31. } else if a.Major > b.Major {
  32. return 1
  33. }
  34. return -1
  35. }
  36. // Less performs a simple comparison of this version (a) with another version (b).
  37. // This function returns true if a is less than b, or false otherwise.
  38. //
  39. // Extensions such as pre-release version or build metadata are ignored when comparing versions.
  40. func (a *Version) Less(b *Version) bool {
  41. return a.Compare(b) < 0
  42. }
  43. // SemanticString returns a version string conforming to the standard described in Semantic Versioning 2.0.0.
  44. //
  45. // See https://semver.org/#is-v123-a-semantic-version
  46. func (v *Version) SemanticString() string {
  47. if v == nil {
  48. return ""
  49. }
  50. return fmt.Sprintf("%d.%d.%d%s", v.Major, v.Minor, v.Patch, v.Extension)
  51. }
  52. func (v *Version) String() string {
  53. if v == nil {
  54. return ""
  55. }
  56. if v.Text != "" {
  57. return v.Text
  58. }
  59. return v.SemanticString()
  60. }