Gradle Task . “(type: Copy)” and <doLast> can't both work

那年仲夏 提交于 2019-12-12 19:29:06

问题


task simpleTask{
    print("simpleTask is reach");
}

task copySomeFile(type: Copy){
    print("copySomeFile is reach");
    from baseProjectPath;
    into toProjectPath;
    appendXML();
}
def appendXML(){
    //modify a.txt
}

//i just want to run "simpleTask" only, but when "gradle simpleTask", the task"copySomeFile" will be run also ! I know beacuse gradle initialization.

but if write like this

task copySomeFile(type: Copy)<<{
}

the "copySomeFile" will not work.

it seems like "(type: Copy)" can't work with the "<<" or "doLast{}"?

i just want "--gradle simpleTask" "--gradle copySomeFile" can run alone.


回答1:


You have to read about Gradle build lifecycle.

There are 2 phases you should note - Configuration and Execution. All tasks are always been configured on every build, but only some of them are really executed as the Execution phase.

What you see is that copySomeFile task was configured during the configuration phase. It doesn't copy anything, but it has to be configured. And everything within a tasks closure is task's configuration, that is why you see results of the print("copySomeFile is reach"); in the output.

<< or doLast are used to run something at the Execution phase, but your task of type Copy will not be configured if you place all it's configuration into doLast section or add << to the task definition - that is the reason why copy doesn't work.




回答2:


Yeh, i got it. How much I appreciate both of you. SHARE THE CODE:

task simpleTask {
    print("\nsimpleTask is configured"); // executed during the configuration plase, always
    doLast {
        print("\nsimpleTask is executed"); // executed during the execution plase, only if the simpleTask is executed
    }
}

task copySomeFile(type: Copy) {
    print("\ncopySomeFile is configured"); // executed always,执行其他任务时,此代码也会执行
    from "D:/a.txt";// not executed. 执行其他任务时,此代码不会执行
    into "D:/b.txt";// not executed. 执行其他任务时,此代码不会执行
    doLast {
        appendXML(); //only this task executed, the appendXML executed. 只有此task执行时,才会执行.比如(gradle copySomeFile);
    }
}
def appendXML(){
    print("\nappendXML");
}


来源:https://stackoverflow.com/questions/44198227/gradle-task-type-copy-and-dolast-cant-both-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!