Gradle插件项目版本号

The*_*dor 8 plugins gradle

我有一个使用project.version变量的gradle插件.

但是,当我更改build.gradle文件中的版本时,插件中的版本不会更新.

为了显示:

插入

// my-plugin
void apply(Project project) {
  project.tasks.create(name: 'printVersionFromPlugin') {
    println project.version
  }
}
Run Code Online (Sandbox Code Playgroud)

的build.gradle

version '1.0.1' // used to be 1.0.0

task printVersion {
  println project.version
}

apply plugin: 'my-plugin'
Run Code Online (Sandbox Code Playgroud)

结果

> gradle printVersion
1.0.1
> gradle printVersionFromPlugin
1.0.0
Run Code Online (Sandbox Code Playgroud)

uri*_*ris 18

您可以使用gradle属性来提取项目版本,而无需向build.gradle文件添加专用任务.

例如:

gradle properties -q | grep "version:" | awk '{print $2}'
Run Code Online (Sandbox Code Playgroud)

  • 我更喜欢这个解决方案,因为它不需要更改构建文件,我不一定拥有它. (3认同)
  • 更好的`./gradlew属性--no-daemon --console = plain -q | grep“ ^ version:” | 如果有多个版本,请使用awk'{printf $ 2}'`。另外,您不需要为此运行的守护程序。 (2认同)
  • 对于这个问题,这是错误的解决方案:在 Gradle 中,版本是一个对象,而不是字符串。包含版本的结果字符串只是分配给“project.version”的 Version 对象上“toString()”的结果。使用 grep/awk 等来解析 build.gradle 文件永远是错误的解决方案。这就像使用 grep 解析 XML。请参阅 https://mrhaki.blogspot.com/2012/09/gradle-goodness-using-objects-for.html (2认同)

Pet*_*ser 12

构建脚本和插件都犯了同样的错误.他们将版本打印为配置任务的一部分,而不是为任务提供行为(任务操作).如果在构建脚本中设置版本之前应用了插件(通常是这种情况),它将打印version属性的先前值(可能已设置一个gradle.properties).

正确的任务声明:

task printVersion {
    // any code that goes here is part of configuring the task
    // this code will always get run, even if the task is not executed
    doLast { // add a task action
        // any code that goes here is part of executing the task
        // this code will only get run if and when the task gets executed
        println project.version
    }
}
Run Code Online (Sandbox Code Playgroud)

插件的任务也一样.

  • 要仅打印版本而不打印其他 gradle 内容,请使用:`./gradlew -q printVersion`。首选表示法是“tasks.register('printVersion') {”,而不是“task printVersion {”。 (2认同)