2016-07-28 23 views
0

我一直在努力通過user guide。這看起來像是我想要做的非常簡單的事情,但我無法弄清楚如何使它工作。gradle:如何編寫一個常規任務

我想編寫一個外部groovy文件來定義一個任務,然後在build.gradle中調用該任務。這是我的build.gradle文件:

// Apply the groovy plugin to add support for Groovy 
apply plugin: 'groovy' 

// In this section you declare where to find the dependencies of your project 
repositories { 
    // Use 'jcenter' for resolving your dependencies. 
    // You can declare any Maven/Ivy/file repository here. 
    jcenter() 
} 

// In this section you declare the dependencies for your production and test code 
dependencies { 
    // We use the latest groovy 2.x version for building this library 
    compile 'org.codehaus.groovy:groovy-all:2.4.7' 
    compile gradleApi() 
    compile localGroovy()  
    // We use the awesome Spock testing and specification framework 
    testCompile 'org.spockframework:spock-core:1.0-groovy-2.4' 
    testCompile 'junit:junit:4.12' 
} 

task myTask (type: my.package.MyTask) 

然後,src/main/groovy/my/package下我有MyTask.groovy

package my.package 

import org.gradle.api.DefaultTask 
import org.gradle.api.tasks.TaskAction 

class MyTask extends DefaultTask { 
    String greeting = 'hello from MyTask' 

    @TaskAction 
    def greet(){ 
     println greeting 
    } 
} 

我甚至無法列出任務:

$ gradle tasks 

FAILURE: Build failed with an exception. 

* Where: 
Build file '/projects/gradle/build.gradle' line: 21 

* What went wrong: 
A problem occurred evaluating root project 'gradle'. 
> Could not get unknown property 'my' for root project 'gradle' of type org.gradle.api.Project. 

* Try: 
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. 

BUILD FAILED 

Total time: 3.193 secs 

在這一點上,我絕對不知道發生了什麼事情或如何做我想做的事情。這看起來是最簡單的例子,但是遵循用戶指南已經讓我無處可尋。無論我做什麼,我都無法擺脫這種例外。

如何編寫一個groovy文件並使用它在構建文件中定義一個新任務?

回答

1

你必須放置在你的常規文件:

rootProjectDir/buildSrc/src/main/groovy 

參考: https://docs.gradle.org/current/userguide/custom_tasks.html#N14573

編輯

我從來沒有試圖改變buildSrc的位置,但它似乎是一個懸而未決問題:
https://issues.gradle.org/browse/GRADLE-2816

(糾正它,如果我錯了)

+0

好吧我現在到了一個新的錯誤,所以謝謝。但是旁註:有沒有辦法改變它?我試圖學習這一點,以便我可以貢獻一個更大的項目,但較大的項目沒有buildSrc文件夾 – ewok

+1

@ewok檢查更新 – CMPS

1

現在,你已經得到了你的src搬到buildSrc你還需要解決一個小錯字在MyTask.groovy:

而不是

import org.gradle.api.tasks.DefaultTask 

使用

import org.gradle.api.tasks.TaskAction 

這應該解決您的@TaskAction註釋。

+0

謝謝。注意到並修復了它。 – ewok