mirror of
https://github.com/opentofu/opentofu.git
synced 2025-01-13 09:32:24 -06:00
Add Versions.Sort
Sort versions from newest to oldest.
This commit is contained in:
parent
032f71f1ff
commit
fdeb3d929c
@ -1,6 +1,8 @@
|
||||
package discovery
|
||||
|
||||
import (
|
||||
"sort"
|
||||
|
||||
version "github.com/hashicorp/go-version"
|
||||
)
|
||||
|
||||
@ -45,3 +47,12 @@ func (v Version) String() string {
|
||||
func (v Version) NewerThan(other Version) bool {
|
||||
return v.raw.GreaterThan(other.raw)
|
||||
}
|
||||
|
||||
type Versions []Version
|
||||
|
||||
// Sort sorts version from newest to oldest.
|
||||
func (v Versions) Sort() {
|
||||
sort.Slice(v, func(i, j int) bool {
|
||||
return v[i].NewerThan(v[j])
|
||||
})
|
||||
}
|
||||
|
39
plugin/discovery/version_test.go
Normal file
39
plugin/discovery/version_test.go
Normal file
@ -0,0 +1,39 @@
|
||||
package discovery
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSortVersions(t *testing.T) {
|
||||
versions := Versions{
|
||||
VersionStr("4").MustParse(),
|
||||
VersionStr("3.1").MustParse(),
|
||||
VersionStr("1.2").MustParse(),
|
||||
VersionStr("1.2.3").MustParse(),
|
||||
VersionStr("2.2.3").MustParse(),
|
||||
VersionStr("3.2.1").MustParse(),
|
||||
VersionStr("2.3.2").MustParse(),
|
||||
}
|
||||
|
||||
expected := []string{
|
||||
"4.0.0",
|
||||
"3.2.1",
|
||||
"3.1.0",
|
||||
"2.3.2",
|
||||
"2.2.3",
|
||||
"1.2.3",
|
||||
"1.2.0",
|
||||
}
|
||||
|
||||
versions.Sort()
|
||||
|
||||
var sorted []string
|
||||
for _, v := range versions {
|
||||
sorted = append(sorted, v.String())
|
||||
}
|
||||
|
||||
if !reflect.DeepEqual(sorted, expected) {
|
||||
t.Fatal("versions aren't sorted:", sorted)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user