vercmp.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Package vercmp compara versiones semver x.y.z para señales de
  2. // actualización (agente desactualizado, etc.).
  3. package vercmp
  4. import (
  5. "fmt"
  6. "strings"
  7. )
  8. // Cmp compara dos versiones x.y.z (sufijos -rN/+ se ignoran): -1, 0, 1.
  9. // Cualquiera de las dos malparsea → 0 (sin señal de novedad), para no
  10. // alertar con etiquetas no semver (dev, local builds...).
  11. func Cmp(a, b string) int {
  12. pa, okA := Parse3(a)
  13. pb, okB := Parse3(b)
  14. if !okA || !okB {
  15. return 0
  16. }
  17. for i := 0; i < 3; i++ {
  18. if pa[i] != pb[i] {
  19. if pa[i] > pb[i] {
  20. return 1
  21. }
  22. return -1
  23. }
  24. }
  25. return 0
  26. }
  27. // Parse3 devuelve [major, minor, patch]; false si no parsea como x.y.z.
  28. func Parse3(v string) ([3]int, bool) {
  29. x, _, ok := parse3Build(v)
  30. return x, ok
  31. }
  32. // CmpBuild compara dos versiones x.y.z incluyendo el número de build del
  33. // sufijo (-N/+N, también -rN): 2.25.0-437 < 2.25.0-443. Una versión sin
  34. // sufijo numérico válido cuenta como build 0, de modo que 2.25.0 < 2.25.0-437.
  35. // Malparseo → 0 (misma política que Cmp). Las señales de actualización que
  36. // dependen del build (updateAvailable, cierre del ciclo de upgrade) DEBEN
  37. // usar esta variante: Cmp ignora los sufijos y considera iguales dos builds
  38. // distintos del mismo x.y.z.
  39. func CmpBuild(a, b string) int {
  40. pa, ba, okA := parse3Build(a)
  41. pb, bb, okB := parse3Build(b)
  42. if !okA || !okB {
  43. return 0
  44. }
  45. for i := 0; i < 3; i++ {
  46. if pa[i] != pb[i] {
  47. if pa[i] > pb[i] {
  48. return 1
  49. }
  50. return -1
  51. }
  52. }
  53. switch {
  54. case ba > bb:
  55. return 1
  56. case ba < bb:
  57. return -1
  58. }
  59. return 0
  60. }
  61. // parse3Build: [major, minor, patch] + build numérico del sufijo (-437, +2,
  62. // -r3). Sufijo no numérico (beta, dev) → build 0.
  63. func parse3Build(v string) ([3]int, int, bool) {
  64. v = strings.TrimPrefix(strings.TrimSpace(v), "v")
  65. build := 0
  66. if i := strings.IndexAny(v, "-+"); i >= 0 {
  67. suf := v[i+1:]
  68. v = v[:i]
  69. if len(suf) > 0 && suf[0] == 'r' {
  70. suf = suf[1:]
  71. }
  72. if n, _ := fmt.Sscanf(suf, "%d", &build); n != 1 {
  73. build = 0
  74. }
  75. }
  76. var x [3]int
  77. if n, _ := fmt.Sscanf(v, "%d.%d.%d", &x[0], &x[1], &x[2]); n != 3 {
  78. return x, 0, false
  79. }
  80. return x, build, true
  81. }