2016-12-19 39 views
1

我有一個在運行時創建的gradle任務,用於調用位於單獨gradle文件中的另一個任務(「myOtherTask」)。問題是如果其他任務不存在,則會拋出異常。在嘗試調用它之前是否可以檢查外部gradle文件中是否存在任務?確定是否在外部build.gradle文件中定義了任務

例子:

task mainTaskBlah(dependsOn: ':setupThings') 
    task setupThings(){ 
    //... 
    createMyOtherTask(/*...*/) 
    //... 
} 
def createMyOtherTask(projName, appGradleDir) { 
    def taskName = projName + 'blahTest' 
    task "$taskName"(type: GradleBuild) { 
     buildFile = appGradleDir + '/build.gradle' 
     dir = appGradleDir 
     tasks = ['myOtherTask'] 
    } 
    mainTaskBlah.dependsOn "$taskName" 
} 

回答

3

您可以檢查是否存在任務。例如,如果我們想模仿這一點,我們可以做一個命令行屬性觸發任務創建

apply plugin: "groovy" 

group = 'com.jbirdvegas.q41227870' 
version = '0.1' 

repositories { 
    jcenter() 
} 

dependencies { 
    compile localGroovy() 
} 

// if user supplied our parameter (superman) then add the task 
// simulates if the project has or doesn't have the task 
if (project.hasProperty('superman')) { 
    // create task like normal 
    project.tasks.create('superman', GradleBuild) { 
     println "SUPERMAN!!!!" 
     buildFile = project.projectDir.absolutePath + '/build.gradle' 
     dir = project.projectDir.absolutePath 
     tasks = ['myOtherTask'] 
    } 
} 

// check if the task we are interested in exists on the current project 
if (project.tasks.findByName('superman')) { 
    // task superman exists here we do whatever work we need to do 
    // when the task is present 
    def supermanTask = project.tasks.findByName('superman') 
    project.tasks.findByName('classes').dependsOn supermanTask 
} else { 
    // here we do the work needed if the task is missing 
    println "Superman not yet added" 
} 

然後,我們可以看到兩個用例,而容易

$ ./gradlew -q build -Psuperman 
SUPERMAN!!!! 
$ ./gradlew -q build 
Superman not yet added 
+0

感謝您的答覆,但我不看不出這有什麼幫助。我的目標是確定是否在project.projectDir.absolutePath +'/build.gradle'構建文件中定義了'myOtherTask'。 – Ben

+0

這說明了這一點。如果'project.tasks.findByName('myOtherTask')== null'那麼這個任務沒有被定義。我只是以不同的方式命名任務。 if(project.tasks.findByName('superman')){\ * is defined * \}'。當Gradle構建系統具有此信息時,您不會真的想嘗試手動解析build.gradle文件。 – JBirdVegas

+0

爲清晰起見添加代碼註釋 – JBirdVegas

相關問題