简体   繁体   中英

Gradle task with compile dependencies

I want to generate a text file based on annotations in my java classes per Gradle task.

I found some references like https://mrhaki.blogspot.com/2014/09/gradle-goodness-running-groovy-scripts.html :

task runScript(type: JavaExec) {
    main = 'com.mrhaki.CurrentDate'
    classpath = sourceSets.main.compileClasspath
}

but here I have to use an external file, which I don't want.

I tried defining the class in the build.gradle file:

class MyScript {
  def call() {
    println ":: Vertx version : $io.vertx.core.impl.launcher.commands.VersionCommand.version"
  }
}

task runScript(type: JavaExec) {
  main = 'MyScript'
  classpath = sourceSets.main.runtimeClasspath
}

but it can not be resolved:

> Task :runScript FAILED
Error: Could not find or load main class MyScript

I could use some workaround to pass the script as a string in args, like

task runGroovyScript(type: JavaExec) {
    classpath = configurations.groovyScript
    main = 'groovy.ui.GroovyMain'
    args '-e', "println 'Hello Gradle!'"
}

but that would be uber-ugly.

How can I run an inline groovy code in a Gradle task?

You can implement any Groovy code you want inside a doFirst or doLast closure of a task:

task doSomething {
    doFirst {
        // any Groovy code you want
        println ":: Vertx version : $io.vertx.core.impl.launcher.commands.VersionCommand.version"
    }
}

Alternatively, you may create a custom task type that implements the desired behavior:

class MyTask extends DefaultTask {
    @TaskAction
    def doSomething() {
        println ":: Vertx version : $io.vertx.core.impl.launcher.commands.VersionCommand.version"
    }
}

task doSomething(type: MyTask)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM