81 lines
1.6 KiB
Go
81 lines
1.6 KiB
Go
package models
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
type BinaryVersion struct {
|
|
Name string
|
|
Major int
|
|
Minor int
|
|
Patch int
|
|
}
|
|
|
|
func ParseBinaryVersion(path string) (*BinaryVersion, error) {
|
|
data, err := os.ReadFile(path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
content := string(data)
|
|
|
|
lastDash := strings.LastIndex(content, "-")
|
|
if lastDash == -1 {
|
|
return nil, errors.New("no dash found in version string")
|
|
}
|
|
|
|
secondLastDash := strings.LastIndex(content[:lastDash], "-")
|
|
if secondLastDash == -1 {
|
|
return nil, errors.New("only one dash found in version string")
|
|
}
|
|
|
|
versionSlice := content[secondLastDash+1 : lastDash]
|
|
re := regexp.MustCompile(`^([A-Za-z]+)([\d\.]+)$`)
|
|
matches := re.FindStringSubmatch(versionSlice)
|
|
if len(matches) < 3 {
|
|
return nil, errors.New("invalid version format")
|
|
}
|
|
binaryVersion := BinaryVersion{
|
|
Name: matches[1],
|
|
}
|
|
numbers := strings.Split(matches[2], ".")
|
|
|
|
if len(numbers) > 0 {
|
|
binaryVersion.Major, err = strconv.Atoi(numbers[0])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
if len(numbers) > 1 {
|
|
binaryVersion.Minor, err = strconv.Atoi(numbers[1])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
if len(numbers) > 2 {
|
|
binaryVersion.Patch, err = strconv.Atoi(numbers[2])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
return &binaryVersion, nil
|
|
}
|
|
|
|
func (v *BinaryVersion) String() string {
|
|
return fmt.Sprintf("%d.%d.%d", v.Major, v.Minor, v.Patch)
|
|
}
|
|
|
|
func (v BinaryVersion) ToInt() int {
|
|
return v.Major*100 + v.Minor*10 + v.Patch
|
|
}
|
|
|
|
func (v BinaryVersion) Subtract(other BinaryVersion) int {
|
|
return v.ToInt() - other.ToInt()
|
|
}
|