Include conditional dependencies and packages in gradle

I got a task in my project to add some dependencies on need basis.

We are creating a jar for different tools, lots of code we have common but some of code and dependencies required for jar is not needed for other.

Before directly jumping into actual code base I wanted get my hand dirty in some dummy project, So I have spent some time to understands gradle tasks and dependency management and created the dummy project.

I am rewriting here for my own benefit and yours as well.

We can add dependencies by providing build time argument

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    if(project.property("build").equals("build1")){
        println "Including dependencies of build1"
        compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.0'
    }
    if (project.property("build").equals("build2")){
        println "Including dependencies of  build2"
        compile group: 'com.google.code.gson', name: 'gson', version: '2.7'
    }
}


To add the conditional dependency we need to run our build command
gradle build -Pbuild="build1"
Or
gradle build -Pbuild="build2"


We can create the separate task for separate Jars.

Task build the Jar for Build1:-
task build1Jar(type: Jar){
    from sourceSets.main.output

    exclude '**/package2/**'

    manifest {
        attributes(
                "Manifest-Version": "1.0",
                "Main-Class" : "com.ravat.package1.Runner",
                "Class-Path":  configurations.runtimeClasspath.collect { it.getName() }.join(' ')
        )
    }
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
    baseName = 'build1'
}

Task build the Jar for Build2:-
task build2Jar(type: Jar){
    from sourceSets.main.output

    exclude '**/package1/**'

    manifest {
        attributes(
                "Manifest-Version": "1.0",
                "Main-Class" : "com.ravat.package2.Runner",
                "Class-Path":  configurations.runtimeClasspath.collect { it.getName() }.join(' ')
        )
    }
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
    baseName = 'build2'
}

To create a jar with required dependencies and package we need to run the following gradle command
gradle clean install build1Jar
or
gradle clean install build2Jar 

No comments:

Post a Comment

Functional programming with Java - Part 1

 Recently I was reviewing one PR raised by team memeber and going through one utitlity method and found out there are too many muatable vari...