compare.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package versions
  2. import (
  3. "strconv"
  4. "strings"
  5. )
  6. // compare compares two version strings
  7. // returns -1 if v1 < v2, 1 if v1 > v2, 0 otherwise.
  8. func compare(v1, v2 string) int {
  9. var (
  10. currTab = strings.Split(v1, ".")
  11. otherTab = strings.Split(v2, ".")
  12. )
  13. max := len(currTab)
  14. if len(otherTab) > max {
  15. max = len(otherTab)
  16. }
  17. for i := 0; i < max; i++ {
  18. var currInt, otherInt int
  19. if len(currTab) > i {
  20. currInt, _ = strconv.Atoi(currTab[i])
  21. }
  22. if len(otherTab) > i {
  23. otherInt, _ = strconv.Atoi(otherTab[i])
  24. }
  25. if currInt > otherInt {
  26. return 1
  27. }
  28. if otherInt > currInt {
  29. return -1
  30. }
  31. }
  32. return 0
  33. }
  34. // LessThan checks if a version is less than another
  35. func LessThan(v, other string) bool {
  36. return compare(v, other) == -1
  37. }
  38. // LessThanOrEqualTo checks if a version is less than or equal to another
  39. func LessThanOrEqualTo(v, other string) bool {
  40. return compare(v, other) <= 0
  41. }
  42. // GreaterThan checks if a version is greater than another
  43. func GreaterThan(v, other string) bool {
  44. return compare(v, other) == 1
  45. }
  46. // GreaterThanOrEqualTo checks if a version is greater than or equal to another
  47. func GreaterThanOrEqualTo(v, other string) bool {
  48. return compare(v, other) >= 0
  49. }
  50. // Equal checks if a version is equal to another
  51. func Equal(v, other string) bool {
  52. return compare(v, other) == 0
  53. }