semverutil.go 939 B

12345678910111213141516171819202122232425262728293031323334353637
  1. // Copyright 2020 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package semverutil
  5. import (
  6. "strings"
  7. "github.com/Masterminds/semver/v3"
  8. )
  9. // Compare returns true if the comparison is true for given versions. It returns false if
  10. // comparison is false, or failed to parse one or both versions as Semantic Versions.
  11. //
  12. // See https://github.com/Masterminds/semver#basic-comparisons for supported comparisons.
  13. func Compare(version1, comparison, version2 string) bool {
  14. clean := func(v string) string {
  15. if strings.Count(v, ".") > 2 {
  16. fields := strings.SplitN(v, ".", 4)
  17. v = strings.Join(fields[:3], ".")
  18. }
  19. return v
  20. }
  21. v, err := semver.NewVersion(clean(version1))
  22. if err != nil {
  23. return false
  24. }
  25. c, err := semver.NewConstraint(comparison + " " + clean(version2))
  26. if err != nil {
  27. return false
  28. }
  29. return c.Check(v)
  30. }