Search code examples
javagradlesource-sets

Gradle: includeFlat and sourceSets dependecy for per-platform builds


I'm new to Java world and Gradle. I've made a JSerial lib which will support multiple platforms (Android, Linux and Windows).

To be able to choose the platform I'm targetting, I've defined some sourceSets in my JSerial gradle file:

sourceSets {
    windows {
        compileClasspath += sourceSets.main.output
        runtimeClasspath += sourceSets.main.output
    }
    linux {
        compileClasspath += sourceSets.main.output
        runtimeClasspath += sourceSets.main.output
    }
}

dependencies {
    linuxCompile 'net.java.dev.jna:jna:4.1.0'
    linuxCompile 'net.java.dev.jna:jna-platform:4.1.0'
    windowsCompile 'net.java.dev.jna:jna:4.1.0'
    windowsCompile 'net.java.dev.jna:jna-platform:4.1.0'
}

The default main sourceSets builds the common interface, etc. Then the windows sourceSet will build windows implementation (and same for Linux and Android).

I create a project which uses this library and depends on it using gradle's includeFlat. Here is the dependency part of my gradle file:

dependencies {
    compile project(':JSerial')
    testCompile group: 'junit', name: 'junit', version: '4.11'
}

This works. But I would like to depends on the "windows" sourceSet, because this project is a windows application. I tried the following:

dependencies {
    compile project(':JSerial').sourceSets.windows.output
    testCompile group: 'junit', name: 'junit', version: '4.11'
}

But it doesn't work, I have the following error:

Could not find property 'windows' on SourceSet container.

What's wrong ?

PS: If there is a better way to do what I'm trying without using sourceSets, please tell me !


Solution

  • I finally found a solution which I think is elegant. Instead of using sourceSets I used multi-project. Here is my project:

    Serial/
      build.gradle
      src/main/java/com.package/
        SerialPort.java
      windows/
        build.gradle
        src/main/java/com.package/
          SerialPortWindows.java
    
    Application/
      build.gradle
      settings.gradle
    

    In my Application's settings.gradle:

    includeFlat 'Serial'
    includeFlat 'Serial/windows'
    

    In my Application's build.gradle:

    dependencies {
         project(':Serial/windows')
    }
    

    In my Serial/windows's build.gradle (which requires SerialPort interface to compile):

    dependencies {
         project(':Serial')
    }
    

    Then when I build my application, it requires Serial/windows which requires Serial. I think I will be able to defines multiple build.gradle files for my application (for example one for Linux and one for Windows), whith different dependencies.