如何在构建期间排除gradle任务或方法

时间:2016-03-03 20:19:05

标签: gradle build.gradle gradle-release-plugin gradle-task

我定义了一个读取属性文件并更新某个字段的任务。我希望这只在我执行'release'时运行,而不是在'build'期间运行。

我正在使用此gradle-release插件进行发布:https://github.com/researchgate/gradle-release

此插件会在每个版本上将gradle.properties文件中的版本更新为下一个版本。我还需要保留当前的版本号,因此我编写了这个方法。

但是,每当我进行构建时,此任务都会执行。我试图将其更改为方法,并在'uploadArchives'中调用该方法,我认为只在'release'期间运行。然而没有结果。它会在每次构建时继续执行!

如何将其从“构建”中排除并仅在发布时调用它?

这是任务和一些代码片段:

task restoreCurrentVersion {
    try {
        String key = 'currentVersion'
        File propertiesFile = project(':commons').file("gradle.properties")
        String currentVersion = project(':commons').version
        this.ant.replaceregexp(file: propertiesFile, byline: true) {
            regexp(pattern: "^(\\s*)$key(\\s*)=(\\s*).+")
            substitution(expression: "\\1$key\\2=\\3$currentVersion")
        }
    } catch (BuildException be) {
        throw new GradleException('Unable to write version property.', be)
    }
}

uploadArchives {
    repositories.mavenDeployer {
        repository(url: 'file://Users/my.home/.m2/repository/')
    }
 //   restoreCurrentVersion()   //Uncommenting this makes the method (when converted the above task to a method) to execute always
}

createReleaseTag.dependsOn uploadArchives    
ext.'release.useAutomaticVersion' = "true"

1 个答案:

答案 0 :(得分:1)

  1. 您需要在任务定义中添加<<doLast块。否则它将在配置阶段运行,这几乎是每次运行任何其他任务时。见这里:Why is my Gradle task always running?

  2. 没有像您尝试在uploadArchives中那样直接从其他任务调用/调用任务的gradle方法,而是使用dependsOnfinalizedBy来设置任务依赖项。如果uploadArchives依赖于restoreCurrentVersion,则每次调用uploadArchives时都会首先调用restoreCurrentVersion。