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

Fix packages sort #1

Merged
merged 2 commits into from
Nov 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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")
}
})
}
}