Skip to content

Commit

Permalink
add optional alphabetical sorting to all keys
Browse files Browse the repository at this point in the history
  • Loading branch information
alehechka committed Jul 4, 2022
1 parent 70c5051 commit 642d446
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
34 changes: 26 additions & 8 deletions jenshared/addStructs.go
Original file line number Diff line number Diff line change
@@ -1,35 +1,53 @@
package jenshared

import (
"sort"

"github.com/dave/jennifer/jen"
)

func addStructs(f *jen.File, itemMap TypeItemsMap) {
for name, items := range itemMap {
f.Add(createStruct(name, items))
func addStructs(f *jen.File, itemMap TypeItemsMap, config *Config) {
keys := make([]string, 0, len(itemMap))
for key := range itemMap {
keys = append(keys, key)
}

if config.Alphabetical {
sort.Strings(keys)
}

for _, key := range keys {
f.Add(createStruct(key, itemMap[key], config))
f.Line()
}
}

func addStruct(f *jen.File, name string, items TypeItems) {
f.Add(createStruct(name, items))
func addStruct(f *jen.File, name string, items TypeItems, config *Config) {
f.Add(createStruct(name, items, config))
}

func createStruct(name string, items TypeItems) *jen.Statement {
func createStruct(name string, items TypeItems, config *Config) *jen.Statement {

if len(items) == 1 && name == items[0].Name {
return jen.Type().Id(name).Id(items[0].Type)
}

structItems := createStructItems(items)
structItems := createStructItems(items, config)

return jen.Type().Id(name).Struct(structItems...)
}

func createStructItems(items TypeItems) []jen.Code {
func createStructItems(items TypeItems, config *Config) []jen.Code {
structItems := make([]jen.Code, 0)

if config.Alphabetical {
sort.Slice(items, func(i, ii int) bool {
return items[i].Title() < items[ii].Title()
})
}

for _, item := range items {
item.OmitEmpty = config.OmitEmpty
structItems = append(structItems, createStructItem(item))
}

Expand Down
1 change: 1 addition & 0 deletions jenshared/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ type Config struct {
OutputDirectory string
TimeFormat string
OmitEmpty bool
Alphabetical bool
Debugger *log.Logger
}

Expand Down

0 comments on commit 642d446

Please sign in to comment.