2019-12-26 15:57:56 +00:00
|
|
|
package version
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
type version struct {
|
|
|
|
major int
|
|
|
|
minor int
|
|
|
|
}
|
|
|
|
|
|
|
|
func Compare(a string, b string) (int, error) {
|
|
|
|
first, err := parse(a)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
second, err := parse(b)
|
|
|
|
if err != nil {
|
|
|
|
return 0, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if first.major < second.major {
|
|
|
|
return -1, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if first.major > second.major {
|
|
|
|
return 1, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if first.minor < second.minor {
|
|
|
|
return -1, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if first.minor > second.minor {
|
|
|
|
return 1, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return 0, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func parse(v string) (version, error) {
|
2020-05-18 19:37:13 +00:00
|
|
|
i := strings.Index(v, ".")
|
|
|
|
if i == -1 {
|
2019-12-26 15:57:56 +00:00
|
|
|
return version{}, errors.New("version must contain major and minor parts")
|
|
|
|
}
|
|
|
|
|
2020-05-18 19:37:13 +00:00
|
|
|
major, err := strconv.Atoi(v[:i])
|
2019-12-26 15:57:56 +00:00
|
|
|
if err != nil {
|
|
|
|
return version{}, err
|
|
|
|
}
|
|
|
|
|
2020-05-18 19:37:13 +00:00
|
|
|
minor, err := strconv.Atoi(v[i+1:])
|
2019-12-26 15:57:56 +00:00
|
|
|
if err != nil {
|
|
|
|
return version{}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return version{major, minor}, nil
|
|
|
|
}
|