androidkotlingradle

How can I generate code based on content of the other module?


I have to generate kotlin code based on types from an external module.

Example project:
|-Base
| |-interface ContentProvider
|
|-First
| |-interface FirstProvider : ContentProvider
|
|-Second
| |-interface SecondProvider : ContentProvider
|
|-Main app
  |-class providers (generated)
    |- object : FirstProvider
    |- object : SecondProvider

So, I have to generate class providers which contains implementation of each descendant of ContentProvider

I have tried to use KSP to achieve that, but KSP has not an access to content of an other module.

I need some idea how it could be implemented.


Solution

  • I tested many different approaches to solve this problem and came back to using KSP. The solution was split between two KSP plugins.

    KSP scanning plugin

    Added to all modules in which scanning must be performed. In modules, this plugin collects information about the types necessary for final generation. The collected type information is used to generate types with metadata about the types required for final generation. The metadata types placed into package with a predefined name, as example: com.viacheslav.synt.

    KSP generating plugin

    The second plugin, using Resolver.getDeclarationsFromPackage, gets all metadata types from package with predefined name. The metadata types contains the types information needed at this stage. Using this metadata, I gain access to information about types with all the capabilities for their analysis. Based on this data, the plugin generates the final code, which handles all the necessary types from all modules.

    Precompiled script plugins

    I use Precompiled script plugins in projects, this made it easy to connect the KSP scanning plugin to all project modules.