I think we need to think a better and standard way of generating code in code generator provider.
In our built-in code generator
Polyrific.Catapult.Plugins.AspNetCoreMvc, we generate code using this step:
- use dotnet cli to create project and solution
- use StringBuilder and TextWriter to modify generated codes, or add a new file based on model
It’s pretty similar with how we do things in the task provider creation tutorial, where we utilize the angular cli to generate the workspace and component, then use some template file to add custom file based on model.
There’re several issues I found with this approach:
- It’s difficult to do code update when the catapult data model changes, especially when there’s a model rename. In the built-in plugin, we have this comment tag for each generated file where we put the model id there, so when the model is renamed, we have a logic to delete those files.
- When user update the code manually, it might easily get overwritten by the code generator.
Some idea I found:
For dotnet generated project:
I found this article on how Roslyn can be used to generate code in cross platform environment: https://msdn.microsoft.com/en-us/magazine/mt808499.aspx?f=255&MSPPError=-2147217396. It can semantically map the code, so it might help us on finding specific class/method, and update them accordingly. However, I found that it is a bit too low level. We might need to find a library that provide a more high level API.
I also find this library that utilize Roslyn: https://jasperfx.github.io/lamar/documentation/compilation/sourcewriter. However, I found that the feature is still limited.
- We might be able to peek into angular cli code, on how they are able to generate component, then update the module file to register the component.
For other technology/platform, it’s obviously need specific tool or mechanism in their own scope, that we can cover in another topic.
If anyone have any experience in code generation, or any idea to make the code generation scheme better, let’s discuss this here.
Basically, the goal of the discussion is to have a code generation scheme that’s:
- Able to update the code seamlessly without breaking the current code
- Able to handle edge cases of user adding custom code to the generated code