version.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package service
  2. import (
  3. "errors"
  4. "strconv"
  5. "strings"
  6. )
  7. // versionAtMost will return true if the provided version is less than or equal to max
  8. func versionAtMost(version, max []int) (bool, error) {
  9. if comp, err := versionCompare(version, max); err != nil {
  10. return false, err
  11. } else if comp == 1 {
  12. return false, nil
  13. }
  14. return true, nil
  15. }
  16. // versionCompare take to versions split into integer arrays and attempts to compare them
  17. // An error will be returned if there is an array length mismatch.
  18. // Return values are as follows
  19. // -1 - v1 is less than v2
  20. // 0 - v1 is equal to v2
  21. // 1 - v1 is greater than v2
  22. func versionCompare(v1, v2 []int) (int, error) {
  23. if len(v1) != len(v2) {
  24. return 0, errors.New("version length mismatch")
  25. }
  26. for idx, v2S := range v2 {
  27. v1S := v1[idx]
  28. if v1S > v2S {
  29. return 1, nil
  30. }
  31. if v1S < v2S {
  32. return -1, nil
  33. }
  34. }
  35. return 0, nil
  36. }
  37. // parseVersion will parse any integer type version seperated by periods.
  38. // This does not fully support semver style versions.
  39. func parseVersion(v string) []int {
  40. version := make([]int, 3)
  41. for idx, vStr := range strings.Split(v, ".") {
  42. vS, err := strconv.Atoi(vStr)
  43. if err != nil {
  44. return nil
  45. }
  46. version[idx] = vS
  47. }
  48. return version
  49. }