Files
releasekit/internal/versioncontract/version.go

76 lines
2.3 KiB
Go

package versioncontract
import (
"errors"
"strconv"
"strings"
"time"
)
// ErrInvalidIdentifier identifies a production identifier outside its grammar.
var ErrInvalidIdentifier = errors.New("invalid release identifier")
// ValidStableVersion reports whether version uses the selected vMAJOR.MINOR.PATCH form.
func ValidStableVersion(version string) bool {
return ValidIdentifier(version, "semver", "v")
}
// ValidIdentifier checks a production identifier without changing its spelling.
func ValidIdentifier(identifier, format, prefix string) bool {
if (prefix != "" && prefix != "v") || !strings.HasPrefix(identifier, prefix) {
return false
}
value := strings.TrimPrefix(identifier, prefix)
switch format {
case "semver":
components := strings.Split(value, ".")
return len(components) == 3 && decimal(components[0], true) && decimal(components[1], true) && decimal(components[2], true)
case "date":
parts := strings.Split(value, ".")
if len(parts) > 2 || (len(parts) == 2 && (!decimal(parts[1], true) || parts[1] == "0")) {
return false
}
date := strings.Split(parts[0], "-")
if len(date) != 3 || len(date[0]) != 4 || len(date[1]) != 2 || len(date[2]) != 2 {
return false
}
year, month, ok := yearMonth(date[0], date[1])
if !ok || !decimal(date[2], false) {
return false
}
day, _ := strconv.Atoi(date[2])
parsed := time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC)
return parsed.Year() == year && int(parsed.Month()) == month && parsed.Day() == day
case "year-month":
parts := strings.Split(value, ".")
if len(parts) != 3 || len(parts[0]) != 4 || len(parts[1]) != 2 || !decimal(parts[2], true) {
return false
}
_, _, ok := yearMonth(parts[0], parts[1])
return ok
default:
return false
}
}
func decimal(value string, canonical bool) bool {
if value == "" || (canonical && len(value) > 1 && value[0] == '0') {
return false
}
for i := 0; i < len(value); i++ {
if value[i] < '0' || value[i] > '9' {
return false
}
}
return true
}
func yearMonth(yearText, monthText string) (int, int, bool) {
if !decimal(yearText, false) || !decimal(monthText, false) {
return 0, 0, false
}
year, _ := strconv.Atoi(yearText)
month, _ := strconv.Atoi(monthText)
return year, month, year >= 1 && year <= 9999 && month >= 1 && month <= 12
}