jmattheis / goverter

Generate type-safe Go converters by simply defining an interface
https://goverter.jmattheis.de/
MIT License
502 stars 47 forks source link

Allow for extension of unexported functions if generated code is in same package #104

Closed phm07 closed 10 months ago

phm07 commented 10 months ago

Take the following source code:

package example

type A struct{}
type B struct{}

// goverter:converter
// goverter:output:file generated.go
// goverter:output:package example
// goverter:extend aToB
type Converter interface {
    CToD(C) D
}

type C struct {
    SomeProperty A
}

type D struct {
    SomeProperty B
}

func aToB(A) B {
    return B{}
}

Currently, generation fails with following error:

...

error parsing type:
    func example.aToB(example.A) example.B

must be exported

However, in this particular case, the function aToB could stay unexported, because the package specified with goverter:output:package is the same package as that of the generator and thus aToB is accessible from within the generated file.

In our use case, we would like to avoid exporting these helpers, as this package is the main interface for users and we want to keep the exported interface as small and relevant as possible to the task at hand. If we export these, we commit to maintaining them until the next breaking change, even if we make internal changes to how conversions work.

Would it be possible to add an extra check to cover this and allow for extension of unexported functions in this case?

Edit: This would also apply to other cases where converter methods can be used, for example map [SOURCE-PATH] TARGET | METHOD

jmattheis commented 10 months ago

Yeah, seems useful to support this for both package local types, structs fields and extend methods.

phm07 commented 10 months ago

This would also be useful for methods defined on the converter interface, for example if a method is only used internally to map a sub-struct properly. At the moment all methods defined on the converter have to be exported.

jmattheis commented 10 months ago

Feature added with v1.2.0. Goverter now allows the usage of unexported fields, methods and functions if they are accessible within the output:package.