github.com/tomwright/dasel@v1.27.3/internal/selfupdate/version.go (about) 1 package selfupdate 2 3 import ( 4 "fmt" 5 "regexp" 6 "strconv" 7 "strings" 8 ) 9 10 // Version is a semver version. 11 type Version struct { 12 Raw string 13 Major int 14 Minor int 15 Patch int 16 } 17 18 // String returns a string representation of the Version. 19 func (v *Version) String() string { 20 if v.IsDevelopment() || v.Major == 0 && v.Minor == 0 && v.Patch == 0 { 21 return v.Raw 22 } 23 return fmt.Sprintf("v%d.%d.%d", v.Major, v.Minor, v.Patch) 24 } 25 26 // IsDevelopment returns true if it's a development version. 27 func (v *Version) IsDevelopment() bool { 28 return v.Raw == "development" || v.Raw == "dev" || strings.HasPrefix(v.Raw, "development-") 29 } 30 31 // Compare compares this version to the other version. 32 // Returns 1 if newer, -1 if older, 0 if same. 33 func (v *Version) Compare(other *Version) int { 34 if v.Major > other.Major { 35 return 1 36 } 37 if v.Major < other.Major { 38 return -1 39 } 40 if v.Minor > other.Minor { 41 return 1 42 } 43 if v.Minor < other.Minor { 44 return -1 45 } 46 if v.Patch > other.Patch { 47 return 1 48 } 49 if v.Patch < other.Patch { 50 return -1 51 } 52 53 return 0 54 } 55 56 var versionRegexp = regexp.MustCompile(`v([0-9]+)\.([0-9]+)\.([0-9]+)`) 57 58 func versionFromString(version string) *Version { 59 res := &Version{ 60 Raw: strings.TrimSpace(version), 61 } 62 match := versionRegexp.FindStringSubmatch(res.Raw) 63 mustAtoi := func(in string) int { 64 out, err := strconv.Atoi(in) 65 if err != nil { 66 panic(err) 67 } 68 return out 69 } 70 if len(match) == 4 { 71 res.Major = mustAtoi(match[1]) 72 res.Minor = mustAtoi(match[2]) 73 res.Patch = mustAtoi(match[3]) 74 } 75 return res 76 }