Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a folder to an android project sourceset from a gradle plugin

I'm writing a plugin for gradle, to generate some classes for Android projects.

I generate those classes in the projects src/gen/java folder, as I don't want them to be mixed with real source code.

From the project's build.gradle config, I can add this to make the build tools see the generated classes :

android {
    sourceSets {
        main {
            java {
                srcDir 'src/gen/java'
            }
        }
    }
} 

The problem is that I want my plugin to set this automatically. From my plugin I tried the followings :

public class MyPlugin implements Plugin {

@Override
public void apply(Project project) {
    // ... 
    // TEST 1 : doesnt work
    project.android.sourceSets.main.java.srcDirs += "src/gen/java"

    // TEST 2 : doesnt work
    project.android.sourceSets {
        main {
            java {
                srcDir 'src/gen/java'
            }
        }
    }
}

}

Each time the plugin works, but the folder is still not seen by the compiler and it can't find the generated classes when compiling. Does any one know of another way to do this from the plugin ?

like image 948
XGouchet Avatar asked Oct 24 '25 14:10

XGouchet


1 Answers

If you move the files to the build/generated/sources dir of the app module the plugin is currently generating code for you then you don't have to add it to the source set.

you could also look at SQLDelight which is also a gradle plugin which does code generation or AutoValue

Edit:

You also need to call the registerJavaGeneratingTask on the BuildVariant that will generate the sources

like image 66
Aegis Avatar answered Oct 27 '25 22:10

Aegis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!