vburenin / ifacemaker

Generate interfaces from structure methods.
Apache License 2.0
320 stars 43 forks source link

Source package not imported if interfaces placed in different package #48

Closed kasvtv closed 2 years ago

kasvtv commented 2 years ago

If one generates an interface into a different package than the source package, e.g.:

ifacemaker -f ../bindings.go -s MyStruct -o i_mystruct.go -p interfaces -i IMyStruct

Then the generated code may be invalid if any of the method signatures contain custom types defined in the source package, e.g.: the generated code in the interfaces package references a custom type defined in the source package as MyType instead of importing from the source package and refering to it as bindings.MyType

Skarlso commented 2 years ago

Going to take a stab at this. :)

Skarlso commented 2 years ago

For the record, we will solve this by importing the source package as a . import.

Skarlso commented 2 years ago

Ok, so this isn't trivial because of trying to determine fully qualified package name including the module name so the import statement can be correct.

Because it's not trivial to get the mod file for a file, I've wrote a small utility to locate the mod file for a given file. If it doesn't exist we will add the source package, if it does exist we add the package including the parsed module path.

In any case we only do this if the target package doesn't equal the source package.

Skarlso commented 2 years ago

Also, only do that if there are declarations without package names in front of them, meaning they are local package resources.

vburenin commented 2 years ago

guys, don't overdo things on your end. auto generation of interfaces is very dangerous, especially if it becomes the part of the shared libraries, it may lead to the broken interfaces for library users.

Skarlso commented 2 years ago

Hm, an alternative, and a super easy solution would be another flag which says something like -> dotpackage, or something. Which, when defined, will be added as a . import to the file?

That wouldn't break anything yet still could be used to produce files with local resources. That would work for a single folder of course, but still better than nothing? WDYT?

Skarlso commented 2 years ago

The single folder thing isn't really a problem either... Since you usually target a single folder or a single file anyways. Not recursively many folders. So it would work but requires a bit of user action. :)

Skarlso commented 2 years ago

@vburenin Are you okay with that approach? :)

Skarlso commented 2 years ago

I added an option that can be passed in for each package to add as an extra . import. This allows for a small change set. I also added a few formattings and module update.