compare.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package versions // import "github.com/docker/docker/api/types/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. if v1 == v2 {
  10. return 0
  11. }
  12. var (
  13. currTab = strings.Split(v1, ".")
  14. otherTab = strings.Split(v2, ".")
  15. )
  16. maxVer := len(currTab)
  17. if len(otherTab) > maxVer {
  18. maxVer = len(otherTab)
  19. }
  20. for i := 0; i < maxVer; i++ {
  21. var currInt, otherInt int
  22. if len(currTab) > i {
  23. currInt, _ = strconv.Atoi(currTab[i])
  24. }
  25. if len(otherTab) > i {
  26. otherInt, _ = strconv.Atoi(otherTab[i])
  27. }
  28. if currInt > otherInt {
  29. return 1
  30. }
  31. if otherInt > currInt {
  32. return -1
  33. }
  34. }
  35. return 0
  36. }
  37. // LessThan checks if a version is less than another
  38. func LessThan(v, other string) bool {
  39. return compare(v, other) == -1
  40. }
  41. // LessThanOrEqualTo checks if a version is less than or equal to another
  42. func LessThanOrEqualTo(v, other string) bool {
  43. return compare(v, other) <= 0
  44. }
  45. // GreaterThan checks if a version is greater than another
  46. func GreaterThan(v, other string) bool {
  47. return compare(v, other) == 1
  48. }
  49. // GreaterThanOrEqualTo checks if a version is greater than or equal to another
  50. func GreaterThanOrEqualTo(v, other string) bool {
  51. return compare(v, other) >= 0
  52. }
  53. // Equal checks if a version is equal to another
  54. func Equal(v, other string) bool {
  55. return compare(v, other) == 0
  56. }