Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gradle println prints when it is not called

Tags:

gradle

My goal is to have a message printed to the console whenever the idea task is run, but unfortunately the message is printed whenever anything is run. Why are the print lines executing when the idea task is not being run? How can I display a message only when the idea task is executed?

build.gradle

apply plugin: 'idea'

task hello << {
    println 'Hello world!'
}

tasks.idea() {
    println '*********************************************************'
    println '* You should open build.gradle as a native project from *'
    println '* within IntelliJ.                                      *'
    println '*********************************************************'
}

Output of the command gradle hello

*********************************************************
* You should open build.gradle as a native project from *
* within IntelliJ.                                      *
*********************************************************
:hello
Hello world!

BUILD SUCCESSFUL

Total time: 2.846 secs

Working Solution

tasks.getByPath('idea') << {
    println '*********************************************************'
    println '* You should open build.gradle as a native project from *'
    println '* within IntelliJ.                                      *'
    println '*********************************************************'
}
like image 838
Mike Rylander Avatar asked Jun 11 '13 18:06

Mike Rylander


2 Answers

You will need to put your printlns into an action and add it to the idea task. The following example shows the use of the doFirst action:

ideaProject.doFirst {
    println '*********************************************************'
    println '* You should open build.gradle as a native project from *'
    println '* within IntelliJ.                                      *'
    println '*********************************************************'
}

There's a specific reason your code is executed before the idea task is run: It's evaluated as configuration code executed during the configuration phase of Gradle's build lifecycle. Only actions are executed during the execution phase. Your hello task does that.

EDIT: idea is org.gradle.plugins.ide.idea.model.IdeaModel in this context and not the task.

like image 96
Benjamin Muschko Avatar answered Oct 05 '22 08:10

Benjamin Muschko


If You want to force gradle to print some messages but only in execution phase, move println commands to doFirst or doLast. Example for war task:

war {
    doFirst {
        println "Packing module/project to " + archiveName + " ..."
    }
    manifest {
        // attributes ... 
    }
    // other commands ...
    doLast {
        println "Packing done. See target directory."
    }
} 
like image 38
lu_ko Avatar answered Oct 05 '22 08:10

lu_ko