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

How to exclude a gradle task or method during build

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

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

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

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

如何从 'build' 中排除它并仅在发布时调用它?

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

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. 您需要在任务定义中添加 <<doLast 块。否则它会在配置阶段 运行,几乎每次你 运行 任何其他 任务。看这里:Why is my Gradle task always running?

  2. 没有 gradle 方法直接从另一个任务 invoke/call 一个任务,就像您在 uploadArchives 中尝试做的那样,而是使用 dependsOnfinalizedBy 设置任务相关性。如果 uploadArchives 依赖于 restoreCurrentVersion ,每次调用 uploadArchives 时都会首先调用 restoreCurrentVersion。