uber-go / mock

GoMock is a mocking framework for the Go programming language.
Apache License 2.0
1.81k stars 103 forks source link

Export the mockgen API as a library for use by other projects in generating mock codes. #124

Open sysulq opened 7 months ago

sysulq commented 7 months ago

I have a project here, github.com/sysulq/struct2interface, which converts structs into interfaces. I'm looking to take it a step further—being able to automatically generate mock structures based on interfaces. Currently, I can only generate them directly using mockgen binary. It would be perfect if it could support a library format.

Thanks in advance~

r-hang commented 2 weeks ago

Hey @sysulq,

From my experience, it's unusual to use a code generator as a library. In your program, could you shell out to mockgen to produce your mocks?

sysulq commented 2 weeks ago

@r-hang Thanks for your reply. :-)

What I did is just call mockgen through shell cmd, but I think it's more natural to call as a library in my situation, without the need to install mockgen.

I created a tool to auto create interface base on struct, and I want to go further, continue to create the mocks based on the interfaces auto created.

And here is the code in below link:

sysulq commented 2 weeks ago

A typical example is the air project, which provide a runner pkg to be imported by thirdparty project directly as a library.

r-hang commented 1 week ago

Hey @sysulq

I spent some time thinking about this PR.

From what i've seen, code generators don't generally take library form because the authors don't intend code generators to be used with other code. The only exception I can think of are code generation plugins used within tightly coupled ecosystems (e.g. protoc, thriftrw). Here, there is a strong contract within the ecosystem.

I'm hesitant to expose the code generator CLI as a library because the API for a code generator is bigger than that of a library. For example, we can't know whether or not a change to generated code won't conflict with or break other generator outputs. From my perspective, a code generator as an importable API creates an API surface that is hard to maintain.

sysulq commented 1 week ago

@r-hang Thank you for taking the time to respond.

In fact we are only exposing a single API, api.Generate, for code generation. This is a very concise, streamlined, and extensible approach, and it actually has very low maintenance costs for the code.

Moreover, for uber-go/mock, it is equivalent to expanding the scope of usage scenarios, which I believe can significantly increase Mock's long-term utilization rate. I sincerely suggest that you support this feature.

Additionally, Mockery's code generation API can be accessed via this link.

sysulq commented 2 days ago

Another typical example can be found in gorm/gen, which also can be imported as a library directly :-)