IntelliJ IDEA關聯gradle原始碼
- 建立一個gradle專案,包含gradle和groovy依賴

-
新建一個buildSrc的module——預設的自定義task和plugin在這個目錄進行編譯
-
在buildSrc的build.gradle中新增對gradle和groovy的api的依賴(否則依賴gradle的api時,編譯會失敗)
dependencies { compile gradleApi() compile localGroovy() } 複製程式碼
-
配置gradle:
-
配置環境變數,預設在C:/使用者/使用者名稱/.gradle/wrapper/dists/,有多個版本,選擇gradle-xxxx-all/xxx/gradle-xxx/bin新增到系統環境變數的path變數中
(all是帶原始碼)
執行
gradle wrapper --gradle-version 5.6.2 --distribution-type all
-
或者配置gradle wrapper,gradle/wrapper/gradle-wrapper.properties 中的distributionUrl配置成帶-all的版本
執行
gradlew.bat wrapper
-
-
以上完成後,執行gradle build,可以關聯gradle原始碼,如:
- 在build.gradle中點dependencies等可以跳轉到對應的原始碼
- 在buildSrc下新建groovy檔案,在其中依賴gradle的api,如繼承DefaultTask,可以檢視它的原始碼
-
編譯過程中gradle build如果報錯:
* What went wrong: Execution failed for task ':buildSrc:compileGroovy'. > java.lang.ExceptionInInitializerError (no error message) 複製程式碼
可以執行gradle build --stacktrace檢視錯誤堆疊,如果是如下錯誤:
Caused by: groovy.lang.GroovyRuntimeException: Conflicting module versions. Module [groovy-all is loaded in version 2.5.4 and you are trying to load version 2.3.7 ... 24 more 複製程式碼
說明gradle依賴的版本和build.gradle中依賴的版本不一致
可以檢視gradle依賴的groovy的版本

然後將build.gradle中的groovy的版本改成跟它一樣即可。
dependencies {
compile 'org.codehaus.groovy:groovy-all:2.5.4'
compile gradleApi()
compile localGroovy()
testCompile group: 'junit', name: 'junit', version: '4.12'
}
複製程式碼
-
如果沒有其他問題,應該就可以依賴gradle的api,並且可檢視原始碼
package com.hero.test import org.gradle.api.DefaultTask import org.gradle.api.tasks.Input import org.gradle.api.tasks.InputFile import org.gradle.api.tasks.OutputFile import org.gradle.api.tasks.TaskAction import org.gradle.api.tasks.Optional class LogTask extends DefaultTask { @InputFile File inputFile @InputFile File xslStyleFile @Input @Optional Map<String, String> params = [:] @OutputFile File outputFile LogTask() { onlyIf { inputFile.exists() } } @TaskAction void start() { ant.xslt(in: inputFile, style: xslStyleFile, out: outputFile) { params.each { key, value -> ant.param(name: key, expression: value) } } } } 複製程式碼
