Skip to content
This repository has been archived by the owner on Jan 31, 2024. It is now read-only.

Commit

Permalink
Merge pull request #1 from sebgl/fix-packages-sort
Browse files Browse the repository at this point in the history
Fix packages sort
  • Loading branch information
charith-elastic authored Nov 28, 2019
2 parents 90c9146 + 16e1a60 commit fe5dff2
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 8 deletions.
22 changes: 14 additions & 8 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ type apiPackage struct {

func (v *apiPackage) identifier() string { return fmt.Sprintf("%s/%s", v.apiGroup, v.apiVersion) }

func init() {
func initFlags() {
klog.InitFlags(nil)
flag.Set("alsologtostderr", "true") // for klog
flag.Parse()
Expand Down Expand Up @@ -114,6 +114,8 @@ func resolveTemplateDir(dir string) error {
func main() {
defer klog.Flush()

initFlags()

f, err := os.Open(*flConfig)
if err != nil {
klog.Fatalf("failed to open config file: %+v", err)
Expand Down Expand Up @@ -271,17 +273,21 @@ func combineAPIPackages(pkgs []*types.Package) ([]*apiPackage, error) {
for _, v := range pkgMap {
out = append(out, v)
}
sortPackages(out)

sort.SliceStable(out, func(i, j int) bool {
a := out[i]
b := out[j]
if a.apiGroup < b.apiGroup {
return true
return out, nil
}

// sortPackages sorts the given packages in a consistent alphabetical order.
func sortPackages(packages []*apiPackage) {
sort.SliceStable(packages, func(i, j int) bool {
a := packages[i]
b := packages[j]
if a.apiGroup != b.apiGroup {
return a.apiGroup < b.apiGroup
}
return a.apiVersion < b.apiVersion
})

return out, nil
}

// isVendorPackage determines if package is coming from vendor/ dir.
Expand Down
78 changes: 78 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package main

import (
"reflect"
"testing"
)

func Test_sortPackages(t *testing.T) {
tests := []struct {
name string
packages []*apiPackage
expected []*apiPackage
}{
{
name: "sort by group then version",
packages: []*apiPackage{
{
apiGroup: "a",
apiVersion: "v1",
},
{
apiGroup: "c",
apiVersion: "v1beta1",
},
{
apiGroup: "b",
apiVersion: "v1beta1",
},
{
apiGroup: "c",
apiVersion: "v1",
},
{
apiGroup: "b",
apiVersion: "v1",
},
{
apiGroup: "a",
apiVersion: "v1beta1",
},
},
expected: []*apiPackage{
{
apiGroup: "a",
apiVersion: "v1",
},
{
apiGroup: "a",
apiVersion: "v1beta1",
},
{
apiGroup: "b",
apiVersion: "v1",
},
{
apiGroup: "b",
apiVersion: "v1beta1",
},
{
apiGroup: "c",
apiVersion: "v1",
},
{
apiGroup: "c",
apiVersion: "v1beta1",
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
sortPackages(tt.packages)
if !reflect.DeepEqual(tt.expected, tt.packages) {
t.Error("Unexpected packages ordering")
}
})
}
}

0 comments on commit fe5dff2

Please sign in to comment.