Gradle task should not execute automatically

主宰稳场 提交于 2019-12-17 06:13:38

问题


I'm defining a task in gradle:

task releaseCandidate(type: Exec) {
    commandLine 'git', 'checkout', 'develop'

    // Increment version code in Manifest
    String manifest = new File('AndroidManifest.xml').getText('UTF-8')
    Pattern pattern = Pattern.compile('android:versionCode="([0-9]+)"')
    Matcher matcher = pattern.matcher(manifest)
    matcher.find()
    int newVersionCode = Integer.parseInt(matcher.group(1)) + 1
    manifest = manifest.replaceAll(
        "android:versionCode=\"([0-9]+)\"", "android:versionCode=\"$newVersionCode\""
    )
    new File('AndroidManifest.xml').write(manifest, 'UTF-8')

    commandLine 'git', 'diff'
}

Which I want to execute only when I explicitly call it as gradle releaseCandidate. However, when I run any other task, such as gradle assembleDebug, it also runs task releaseCandidate. I don't want that behaviour to happen. There is no task depending on releaseCandidate or vice-versa.

My project is an Android app, so I am using android gradle plugin.


回答1:


A common pitfall. Add an action to the task otherwise code will run at configuration phase. Sample task with action:

task sample << {
}

As I see You'd rather need to write a custom task than using Exec type. I suppose it's not valid to define commandLine twice.

EDIT

You can read this post to get the general idea how it all works.




回答2:


You are mixing Task configuration and groovy code. Everything that is part of the main body of a task definition will be executed in the configuration phase. The task task1 << { code } is a shorthand for


task task1 {
  doLast {
    code
  }
}

commandLine is part of the Exec Task but your other code is not and should be wrapped into a doLast this will execute the commandline first and then execute your additional code. If you need another exec commandLine then you'll need another task.


task releaseCandidate(type: Exec) {
    commandLine 'git', 'checkout', 'develop'

    doLast {
    // Increment version code in Manifest
    String manifest = new File('AndroidManifest.xml').getText('UTF-8')
    Pattern pattern = Pattern.compile('android:versionCode="([0-9]+)"')
    Matcher matcher = pattern.matcher(manifest)
    matcher.find()
    int newVersionCode = Integer.parseInt(matcher.group(1)) + 1
    manifest = manifest.replaceAll(
        "android:versionCode=\"([0-9]+)\"", "android:versionCode=\"$newVersionCode\""
    )
    new File('AndroidManifest.xml').write(manifest, 'UTF-8')
    }
}



回答3:


Just to complete @Opal answer for cases when Exec is really used (for example CommandLine reference) :

task task1 << {
   exec {
        List<String> arguments = new ArrayList<String>()
        //..
        commandLine arguments
   }
}


来源:https://stackoverflow.com/questions/23546286/gradle-task-should-not-execute-automatically

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