How to get Android Studio main SourceSet with Gradle API?
Asked Answered
I

3

6

I'm working on developing a gradle plugin for Android Studio.Here is my problem How can I get Android Studio main SourceSet with Gradle API?

I want to do some copy stuff with java source directory. Before asking this question, I found something useful but not work.

SourceSet main = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME)

I get this error message
Caused by: org.gradle.api.UnknownDomainObjectException: SourceSet with name 'main' not found.

Imperative answered 11/5, 2016 at 10:29 Comment(1)
What exactly were you trying to do here?Concourse
I
3

First,the code doesn't work because it's only for the java project with java gradle plugin. So I googled and found something work around. Here is my code.

project.afterEvaluate {
    ...
    def sets;
    if (Utils.is140orAbove()) {
        sets = project.android.sourceSets;
    } else {
        sets = project.android.sourceSetsContainer;
    }
    sets.all { AndroidSourceSet sourceSet ->
        if(sourceSet.name.startsWith("main"))
            for(File file:sourceSet.java.getSrcDirs())
                if(file.exists()) {
                    mainSource = file;
                    break;
                }
    }
    ...
}

My code is not beautiful.Waiting for better answer.

Imperative answered 12/5, 2016 at 8:3 Comment(0)
D
1
android.sourceSets.main.java.getSrcDirs()[0].path

This works for me in Android Studio 3.1 and later

Dwelt answered 26/2, 2019 at 10:0 Comment(0)
I
0
project.android.sourceSets.main

works. Note that it has type AndroidSourceSet, not SourceSet. It has basically the same API, though, with Android-relevant additions.

Incarnation answered 22/6, 2017 at 14:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.