version.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package utils
  2. import (
  3. "strconv"
  4. "strings"
  5. "git.i2edu.net/i2/go-zero/core/mathx"
  6. "git.i2edu.net/i2/go-zero/core/stringx"
  7. )
  8. var replacer = stringx.NewReplacer(map[string]string{
  9. "V": "",
  10. "v": "",
  11. "-": ".",
  12. })
  13. // CompareVersions returns true if the first field and the third field are equal, otherwise false.
  14. func CompareVersions(v1, op, v2 string) bool {
  15. result := compare(v1, v2)
  16. switch op {
  17. case "=", "==":
  18. return result == 0
  19. case "<":
  20. return result == -1
  21. case ">":
  22. return result == 1
  23. case "<=":
  24. return result == -1 || result == 0
  25. case ">=":
  26. return result == 0 || result == 1
  27. }
  28. return false
  29. }
  30. // return -1 if v1<v2, 0 if they are equal, and 1 if v1>v2
  31. func compare(v1, v2 string) int {
  32. v1 = replacer.Replace(v1)
  33. v2 = replacer.Replace(v2)
  34. fields1 := strings.Split(v1, ".")
  35. fields2 := strings.Split(v2, ".")
  36. ver1 := strsToInts(fields1)
  37. ver2 := strsToInts(fields2)
  38. shorter := mathx.MinInt(len(ver1), len(ver2))
  39. for i := 0; i < shorter; i++ {
  40. if ver1[i] == ver2[i] {
  41. continue
  42. } else if ver1[i] < ver2[i] {
  43. return -1
  44. } else {
  45. return 1
  46. }
  47. }
  48. if len(ver1) < len(ver2) {
  49. return -1
  50. } else if len(ver1) == len(ver2) {
  51. return 0
  52. } else {
  53. return 1
  54. }
  55. }
  56. func strsToInts(strs []string) []int64 {
  57. if len(strs) == 0 {
  58. return nil
  59. }
  60. ret := make([]int64, 0, len(strs))
  61. for _, str := range strs {
  62. i, _ := strconv.ParseInt(str, 10, 64)
  63. ret = append(ret, i)
  64. }
  65. return ret
  66. }