From 2a069341db229e6a79a98a3a07685fe3468c2e9c Mon Sep 17 00:00:00 2001 From: June Date: Fri, 15 Aug 2025 23:39:16 +0200 Subject: [PATCH] sort version strings properly by adding and using new compare function With this new compare function the version strings seen in the output get sorted properly. So something like "1.89.0" gets sorted before "1.135.0", not after. It also makes the room versions count up properly with the "unknown" version getting placed at the beginning. --- main.go | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) 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]