浏览文件
versionutil.go
63 行 · 2.0 KB历史下载| 1 | // SPDX-FileCopyrightText: Copyright The Lima Authors |
| 2 | // SPDX-License-Identifier: Apache-2.0 |
| 3 | |
| 4 | package versionutil |
| 5 | |
| 6 | import ( |
| 7 | "strings" |
| 8 | |
| 9 | "github.com/coreos/go-semver/semver" |
| 10 | ) |
| 11 | |
| 12 | // Parse parses a Lima version string by removing the leading "v" character and |
| 13 | // stripping everything from the first "-" forward (which are `git describe` artifacts and |
| 14 | // not semver pre-release markers) or cutting ".m" suffix from exact version. |
| 15 | // So "v0.19.1-16-gf3dc6ed.m" will be parsed as "0.19.1". |
| 16 | func Parse(version string) (*semver.Version, error) { |
| 17 | version = strings.TrimPrefix(version, "v") |
| 18 | version, _, _ = strings.Cut(version, "-") |
| 19 | version = strings.TrimSuffix(version, ".m") |
| 20 | return semver.NewVersion(version) |
| 21 | } |
| 22 | |
| 23 | func compare(limaVersion, oldVersion string) int { |
| 24 | if limaVersion == "" { |
| 25 | if oldVersion == "" { |
| 26 | return 0 |
| 27 | } |
| 28 | return -1 |
| 29 | } |
| 30 | version, err := Parse(limaVersion) |
| 31 | if err != nil { |
| 32 | return 1 |
| 33 | } |
| 34 | // Handle Unparsable oldVersion gracefully - treat as 0.0.0 so Unparsable limaVersion is always greater |
| 35 | oldVer, err := semver.NewVersion(oldVersion) |
| 36 | if err != nil { |
| 37 | return 1 |
| 38 | } |
| 39 | cmp := version.Compare(*oldVer) |
| 40 | if cmp == 0 && strings.Contains(limaVersion, "-") { |
| 41 | cmp = 1 |
| 42 | } |
| 43 | return cmp |
| 44 | } |
| 45 | |
| 46 | // GreaterThan returns true if the Lima version used to create an instance is greater |
| 47 | // than a specific older version. Always returns false if the Lima version is the empty string. |
| 48 | // Unparsable lima versions (like SHA1 commit ids) are treated as the latest version and return true. |
| 49 | // limaVersion is a `github describe` string, not a semantic version. So "0.19.1-16-gf3dc6ed.m" |
| 50 | // will be considered greater than "0.19.1". |
| 51 | func GreaterThan(limaVersion, oldVersion string) bool { |
| 52 | return compare(limaVersion, oldVersion) > 0 |
| 53 | } |
| 54 | |
| 55 | // GreaterEqual return true if limaVersion >= oldVersion. |
| 56 | func GreaterEqual(limaVersion, oldVersion string) bool { |
| 57 | return compare(limaVersion, oldVersion) >= 0 |
| 58 | } |
| 59 | |
| 60 | // LessThan returns true if limaVersion < oldVersion. |
| 61 | func LessThan(limaVersion, oldVersion string) bool { |
| 62 | return !GreaterEqual(limaVersion, oldVersion) |
| 63 | } |

