diff --git a/main.go b/main.go index 2b59ee9..8b87e09 100644 --- a/main.go +++ b/main.go @@ -5,6 +5,7 @@ import ( "fmt" "log" "os" + "slices" "sort" "strings" "sync" @@ -251,6 +252,34 @@ func getMaxRoomVersion(serverVersionInfo fclient.Version) string { } } +func compareVersionStrings(a, b string) int { + // Try to parse a and b as versions. + // Use only the first part of the version string as sometimes there are suffixes after a space, like " ()", which then can't be parsed. + aStart := strings.Split(a, " ")[0] + bStart := strings.Split(b, " ")[0] + aVersion, aErr := version.NewVersion(aStart) + bVersion, bErr := version.NewVersion(bStart) + // An input, which can't be parsed as a version, should be interpreted as being smaller than an input, which can be parsed as a version. + switch { + case aErr != nil && bErr == nil: + return -1 + case aErr == nil && bErr != nil: + return 1 + case aErr != nil && bErr != nil: + return strings.Compare(a, b) + } + + if cmpResult := aVersion.Compare(bVersion); cmpResult != 0 { + return cmpResult + } else { + // When the versions are equal, look at the potential suffixes in the version string. + aEnd := strings.TrimPrefix(a, aStart) + bEnd := strings.TrimPrefix(b, bStart) + + return strings.Compare(aEnd, bEnd) + } +} + func main() { userLocalpart := os.Getenv("MATRIX_USER_LOCALPART") homeserver := os.Getenv("MATRIX_HOMESERVER") @@ -334,7 +363,7 @@ func main() { for key := range maxRoomVersionInfo { maxRoomVersionKeys = append(maxRoomVersionKeys, key) } - sort.Strings(maxRoomVersionKeys) + slices.SortFunc(maxRoomVersionKeys, compareVersionStrings) for _, maxRoomVersionKey := range maxRoomVersionKeys { maxRoomVersionValue := maxRoomVersionInfo[maxRoomVersionKey] @@ -354,7 +383,7 @@ func main() { for key := range serverValue { versionKeys = append(versionKeys, key) } - sort.Strings(versionKeys) + slices.SortFunc(versionKeys, compareVersionStrings) for _, versionKey := range versionKeys { versionValue := serverValue[versionKey]