Gradle multiple jars from single source folder

I will post my working solution here as an answer (I’ve got a hint on gradle’s forum).

The scopes in gradle are very strange thing 🙂 I thought that every task definition creates an object of some ‘Task’ class, which is something like ‘JarTask’ in this particular case. Then I can access any property of the class from anywhere in my build.gradle script. However, I found the only place where I can see the patterns, which are included in jar file – inside a from block of a task. So my working solution for now is to:

1) Define a project-level collection to contain patterns to be excluded from server.jar

2) Exclude all patterns in from block of serverJar task.

Please see final version below

sourceSets {  
    main {  
        java {  
            srcDir 'src'  
        }  
    }  
} 

// holds classes included into client.jar and util.jar, so they are to be excluded from server.jar
ext.serverExcludes = []

// util.jar
task utilJar(type: Jar) {  
    from(sourceSets.main.output) {  
        include "my/util/package/**" 
        project.ext.serverExcludes.addAll(includes)
    }  
}

// client.jar
task clientJar(type: Jar) {  
    from(sourceSets.main.output) {  
        include "my/client/package/**"
        project.ext.serverExcludes.addAll(includes)
    }  
}

// server.jar
task serverJar(type: Jar) {  
    from(sourceSets.main.output) {  
        exclude project.ext.serverExcludes
    }  
}

Leave a Comment