Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Add] EDN Named Type Overwrite #10

Merged
merged 1 commit into from
May 11, 2024
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
10 changes: 9 additions & 1 deletion pkg/parsers/edntostruct/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ package edntostruct
import "go/types"

type options struct {
tagTypes map[string]TypeFn
tagTypes map[string]TypeFn
namedTypes map[string]NamedTypeFn
}

func defaultOptions() *options {
Expand All @@ -16,6 +17,7 @@ func defaultOptions() *options {
"float64": genericTypeFn(types.Typ[types.Float64]),
"int64": genericTypeFn(types.Typ[types.Int64]),
},
namedTypes: map[string]NamedTypeFn{},
}
}

Expand All @@ -26,3 +28,9 @@ func WithTagTypeFn(tag string, fn TypeFn) Option {
opt.tagTypes[tag] = fn
}
}

func WithNamedTypeFn(name string, fn NamedTypeFn) Option {
return func(opt *options) {
opt.namedTypes[name] = fn
}
}
3 changes: 3 additions & 0 deletions pkg/parsers/edntostruct/packages.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ func addImportFixName(
destPackage *types.Package,
importPackage *types.Package,
) {
if destPackage == nil || importPackage == nil {
return
}
if destPackage.Path() == importPackage.Path() {
return
}
Expand Down
31 changes: 18 additions & 13 deletions pkg/parsers/edntostruct/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,19 +94,26 @@ func (p *Parser) parseEDNTypeToGolangStruct(

structs := make([]*types.Named, 0, len(byNamespace))
for namespace, fields := range byNamespace {
object := createStructOrderedFields(
destPackage,
prefix,
namespace,
fields,
)
name := fmt.Sprintf("%s%s", prefix, strcase.ToCamel(namespace))
var object *types.Named
if fn, ok := p.options.namedTypes[name]; ok {
var importPackage *types.Package
importPackage, object = fn()
addImportFixName(destPackage, importPackage)
} else {
object = createStructOrderedFields(
destPackage,
name,
fields,
)
existingObject := destPackage.Scope().Insert(object.Obj())
if existingObject != nil {
return nil, errors.New("unsuported mixed types")
}
}
structs = append(structs,
object,
)
existingObject := destPackage.Scope().Insert(object.Obj())
if existingObject != nil {
return nil, errors.New("unsuported mixed types")
}
}

var result types.Type
Expand Down Expand Up @@ -238,9 +245,7 @@ func (p *Parser) parseEDNTypeToGolangField(
}
var importPackage *types.Package
importPackage, fieldType = typeFn()
if importPackage != nil {
addImportFixName(destPackage, importPackage)
}
addImportFixName(destPackage, importPackage)
}
nameCamel := strcase.ToCamel(name)
if nameCamel == "Id" {
Expand Down
36 changes: 36 additions & 0 deletions pkg/parsers/edntostruct/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,42 @@ import (
type OverwriteSome struct {
Field decimal.Decimal "json:\"field\" edn:\"some/field\""
}
`,
},
},
{
name: "should be able to overwrite named types",
args: &args{
packagePath: "example.com/some/package/path",
prefix: "OverwriteNamed",
options: []Option{
WithNamedTypeFn("OverwriteNamedSomeOther", func() (*types.Package, *types.Named) {
decimalPackage := types.NewPackage("github.com/some_org/repo/package", "potato")
return decimalPackage, types.NewNamed(
types.NewTypeName(
token.NoPos,
decimalPackage,
"MagicValue",
nil,
),
nil,
nil,
)
}),
},
ednContent: []byte(`{:some/field {:other/value 22}}`),
},
want: &want{
result: `// Code generated by endtostruct DO NOT EDIT
package path

import (
potato "github.com/some_org/repo/package"
)

type OverwriteNamedSome struct {
Field potato.MagicValue "json:\"field\" edn:\"some/field\""
}
`,
},
},
Expand Down
12 changes: 10 additions & 2 deletions pkg/parsers/edntostruct/printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import (
"fmt"
"go/types"
"regexp"
"slices"
"strings"

"mvdan.cc/gofumpt/format"
)
Expand All @@ -26,13 +28,19 @@ func printPackage(
buffer := bytes.NewBufferString("// Code generated by endtostruct DO NOT EDIT\n")
buffer.WriteString(fmt.Sprintf("package %s", destPackage.Name()))
buffer.WriteString("\n\nimport (\n")
for _, importParckage := range destPackage.Imports() {
imports := destPackage.Imports()
slices.SortStableFunc(imports, func(a, b *types.Package) int {
return strings.Compare(a.Path(), b.Path())
})
for _, importParckage := range imports {
buffer.WriteString(fmt.Sprintf(`%s "%s"`, importParckage.Name(), importParckage.Path()))
buffer.WriteString("\n")
}
buffer.WriteString(")")
scope := destPackage.Scope()
for _, name := range scope.Names() {
names := scope.Names()
slices.Sort(names)
for _, name := range names {
buffer.WriteString("\n\n")
object := scope.Lookup(name)
unformatted := types.ObjectString(object, qualifier)
Expand Down
6 changes: 1 addition & 5 deletions pkg/parsers/edntostruct/structs.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
package edntostruct

import (
"fmt"
"go/token"
"go/types"
"slices"
"strings"

"github.com/iancoleman/strcase"
)

type fieldTagPair struct {
Expand All @@ -17,7 +14,6 @@ type fieldTagPair struct {

func createStructOrderedFields(
destPackage *types.Package,
prefix string,
name string,
fieldTagPairs []fieldTagPair,
) *types.Named {
Expand All @@ -34,7 +30,7 @@ func createStructOrderedFields(
typeName := types.NewTypeName(
token.NoPos,
destPackage,
fmt.Sprintf("%s%s", prefix, strcase.ToCamel(name)),
name,
structType,
)
object := types.NewNamed(
Expand Down
1 change: 1 addition & 0 deletions pkg/parsers/edntostruct/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
)

type TypeFn func() (*types.Package, types.Type)
type NamedTypeFn func() (*types.Package, *types.Named)

type TypeExtraStringer interface {
ExtraString() string
Expand Down
Loading