pkg.re/essentialkaos/ek.10@v12.41.0+incompatible/sortutil/sortutil.go (about) 1 // Package sortutil provides methods for sorting slices 2 package sortutil 3 4 // ////////////////////////////////////////////////////////////////////////////////// // 5 // // 6 // Copyright (c) 2022 ESSENTIAL KAOS // 7 // Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0> // 8 // // 9 // ////////////////////////////////////////////////////////////////////////////////// // 10 11 import ( 12 "sort" 13 "strconv" 14 "strings" 15 ) 16 17 // ////////////////////////////////////////////////////////////////////////////////// // 18 19 type versionSlice []string 20 type stringSlice []string 21 22 // ////////////////////////////////////////////////////////////////////////////////// // 23 24 func (s versionSlice) Len() int { return len(s) } 25 func (s versionSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } 26 func (s versionSlice) Less(i, j int) bool { 27 return VersionCompare(s[i], s[j]) 28 } 29 30 func (s stringSlice) Len() int { return len(s) } 31 func (s stringSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } 32 func (s stringSlice) Less(i, j int) bool { 33 return strings.ToLower(s[i]) < strings.ToLower(s[j]) 34 } 35 36 // ////////////////////////////////////////////////////////////////////////////////// // 37 38 // Versions sorts versions slice 39 func Versions(s []string) { 40 sort.Sort(versionSlice(s)) 41 } 42 43 // VersionCompare compares 2 versions and returns true if v1 less v2. This function 44 // can be used for version sorting with structs 45 func VersionCompare(v1, v2 string) bool { 46 is := strings.Split(v1, ".") 47 js := strings.Split(v2, ".") 48 49 il, jl := len(is), len(js) 50 51 l := il 52 53 if jl > l { 54 l = jl 55 } 56 57 for k := 0; k < l; k++ { 58 switch { 59 case il-1 < k: 60 return true 61 case jl-1 < k: 62 return false 63 } 64 65 if is[k] == js[k] { 66 continue 67 } 68 69 ii, err1 := strconv.ParseInt(is[k], 10, 64) 70 ji, err2 := strconv.ParseInt(js[k], 10, 64) 71 72 if err1 != nil || err2 != nil { 73 return is[k] < js[k] 74 } 75 76 switch { 77 case ii < ji: 78 return true 79 case ii > ji: 80 return false 81 } 82 } 83 84 return true 85 } 86 87 // Strings sorts strings slice and support case insensitive mode 88 func Strings(s []string, caseInsensitive bool) { 89 if caseInsensitive { 90 sort.Sort(stringSlice(s)) 91 } else { 92 sort.Strings(s) 93 } 94 }