version.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. // Match tests the version against a constraint.
  37. // Gt and Lt take precedence over Gte and Lte.
  38. func (v *Version) Match(c *Constraint) bool {
  39. if v == nil {
  40. return false
  41. }
  42. if c == nil {
  43. return true
  44. }
  45. if c.Gt != nil {
  46. if v.Compare(c.Gt) <= 0 {
  47. return false
  48. }
  49. } else if c.Gte != nil {
  50. if v.Compare(c.Gte) < 0 {
  51. return false
  52. }
  53. }
  54. if c.Lt != nil {
  55. if v.Compare(c.Lt) >= 0 {
  56. return false
  57. }
  58. } else if c.Lte != nil {
  59. if v.Compare(c.Lte) > 0 {
  60. return false
  61. }
  62. }
  63. return true
  64. }
  65. // Less performs a simple comparison of this version (a) with another version (b).
  66. // This function returns true if a is less than b, or false otherwise.
  67. //
  68. // Extensions such as pre-release version or build metadata are ignored when comparing versions.
  69. func (a *Version) Less(b *Version) bool {
  70. return a.Compare(b) < 0
  71. }
  72. // SemanticString returns a version string conforming to the standard described in Semantic Versioning 2.0.0.
  73. //
  74. // See https://semver.org/#is-v123-a-semantic-version
  75. func (v *Version) SemanticString() string {
  76. if v == nil {
  77. return ""
  78. }
  79. return fmt.Sprintf("%d.%d.%d%s", v.Major, v.Minor, v.Patch, v.Extension)
  80. }
  81. func (v *Version) String() string {
  82. if v == nil {
  83. return ""
  84. }
  85. if v.Text != "" {
  86. return v.Text
  87. }
  88. return v.SemanticString()
  89. }