diff --git a/main.go b/main.go index 37a1a5c..7ab05aa 100644 --- a/main.go +++ b/main.go @@ -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() @@ -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) @@ -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. diff --git a/main_test.go b/main_test.go new file mode 100644 index 00000000..9c226f6 --- /dev/null +++ b/main_test.go @@ -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") + } + }) + } +} \ No newline at end of file