ref(git): replace git's native -sort with a thrid-party function

Signed-off-by: storyicon <storyicon@foxmail.com>
This commit is contained in:
storyicon 2021-08-01 17:11:54 +08:00
parent 3953017597
commit 7b2c0762d4
7 changed files with 95 additions and 62 deletions

View file

@ -20,11 +20,41 @@ import (
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
"syscall"
"github.com/coreos/go-semver/semver"
)
// DeduplicateSlice is used to deduplicate slice items stably
// SortSemanticVersion is used to sort semantic version
func SortSemanticVersion(items []string) ([]string, []string) {
versionMap := make(map[*semver.Version]string, len(items))
versions := make(semver.Versions, 0, len(items))
var malformed []string
for _, item := range items {
s := item
if strings.HasPrefix(s, "v") {
s = item[1:]
}
version, err := semver.NewVersion(s)
if err != nil {
malformed = append(malformed, item)
continue
}
versionMap[version] = item
versions = append(versions, version)
}
sort.Sort(versions)
var data []string
for _, version := range versions {
data = append(data, versionMap[version])
}
sort.Strings(malformed)
return malformed, data
}
// DeduplicateSliceStably is used to deduplicate slice items stably
func DeduplicateSliceStably(items []string) []string {
data := make([]string, 0, len(items))
deduplicate := map[string]struct{}{}

View file

@ -84,4 +84,39 @@ func TestDeduplicateSliceStably(t *testing.T) {
}
})
}
}
}
func TestSortSemanticVersion(t *testing.T) {
type args struct {
items []string
}
tests := []struct {
name string
args args
want []string
want1 []string
}{
{
args: args{
items: []string{
"v3.0.0-beta-3.1",
"v3.0.0-alpha-2",
"3.15.0-rc1", "conformance-build-tag", "v2.4.1",
},
},
want: []string{"conformance-build-tag"},
want1: []string{"v2.4.1", "v3.0.0-alpha-2", "v3.0.0-beta-3.1", "3.15.0-rc1"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, got1 := SortSemanticVersion(tt.args.items)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("SortSemanticVersion() got = %v, want %v", got, tt.want)
}
if !reflect.DeepEqual(got1, tt.want1) {
t.Errorf("SortSemanticVersion() got1 = %v, want %v", got1, tt.want1)
}
})
}
}