version.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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.Major == b.Major {
  19. if a.Minor == b.Minor {
  20. if a.Patch == b.Patch {
  21. return 0
  22. } else if a.Patch > b.Patch {
  23. return 1
  24. }
  25. } else if a.Minor > b.Minor {
  26. return 1
  27. }
  28. } else if a.Major > b.Major {
  29. return 1
  30. }
  31. return -1
  32. }
  33. // Less performs a simple comparison of this version (a) with another version (b).
  34. // This function returns true if a is less than b, or false otherwise.
  35. //
  36. // Extensions such as pre-release version or build metadata are ignored when comparing versions.
  37. func (a *Version) Less(b *Version) bool {
  38. return a.Compare(b) < 0
  39. }
  40. // SemanticString returns a version string conforming to the standard described in Semantic Versioning 2.0.0.
  41. //
  42. // See https://semver.org/#is-v123-a-semantic-version
  43. func (v *Version) SemanticString() string {
  44. return fmt.Sprintf("%d.%d.%d%s", v.Major, v.Minor, v.Patch, v.Extension)
  45. }
  46. func (v *Version) String() string {
  47. if v.Text != "" {
  48. return v.Text
  49. }
  50. return v.SemanticString()
  51. }