Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradle: How to add a custom task after compilation but before packaging files into a Jar?

My build.gradle is currently:

project(':rss-middletier') {
    apply plugin: 'java'

    dependencies {
        compile project(':rss-core')
        compile 'asm:asm-all:3.2'
        compile 'com.sun.jersey:jersey-server:1.9.1'
        compile group: 'org.javalite', name: 'activejdbc', version: '1.4.9'
    }

    jar {
        from(configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }) {
            exclude "META-INF/*.SF"
            exclude "META-INF/*.DSA"
            exclude "META-INF/*.RSA"
        }
        manifest { attributes 'Main-Class': 
'com.netflix.recipes.rss.server.MiddleTierServer' }
    }
}

But rather than packaging these compiled classes into a jar directly, I'd like to instrument them first by running the following task:

task instrument(dependsOn: 'build', type: JavaExec) {
    main = 'org.javalite.instrumentation.Main'
    classpath = buildscript.configurations.classpath
    classpath += project(':rss-middletier').sourceSets.main.runtimeClasspath
    jvmArgs '-DoutputDirectory=' + project(':rss-middletier').sourceSets
        .main.output.classesDir.getPath()
}

Only after I have instrumented these classes, I will then want to package them into a JAR file. Is there a way so that I can do this instrumentation before the packaging?

Thanks a lot!!!

like image 269
Hongyi Li Avatar asked Jul 22 '14 23:07

Hongyi Li


People also ask

Where is the jar file after Gradle build?

The result JAR will be created in build/libs/ directory by default.

How do I skip tasks in Gradle?

To skip any task from the Gradle build, we can use the -x or –exclude-task option. In this case, we'll use “-x test” to skip tests from the build. As a result, the test sources aren't compiled, and therefore, aren't executed.


1 Answers

Finally figured out the way to do it!

task instrument(type: JavaExec) {
    //your instrumentation task steps here
}
compileJava.doLast {
    tasks.instrument.execute()
}
jar {
    //whatever jar actions you need to do
}

Hope this can prevent others from being stuck on this problem for days :)

like image 181
Hongyi Li Avatar answered Sep 19 '22 05:09

Hongyi Li