10

我的目标是在任务运行时将消息打印到控制台idea,但不幸的是,无论何时运行任何内容都会打印该消息。为什么在idea任务未运行时执行打印行?如何仅在idea执行任务时显示消息?

构建.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 '*********************************************************'
}

命令的输出gradle hello

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

BUILD SUCCESSFUL

Total time: 2.846 secs

工作解决方案

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

2 回答 2

7

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.

于 2013-06-11T20:45:07.317 回答
3

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."
    }
} 
于 2014-08-06T11:52:28.760 回答