从bash中的build.gradle中读取versionName

问题描述 投票:8回答:8

有没有办法从Android项目的versionName文件中读取值build.gradle才能在bash中使用它?

更准确地说:如何从文件中读取该值并在Travis-CI脚本中使用它?我会像使用它一样

# ANDROID_VERSION=???
export GIT_TAG=build-$ANDROID_VERSION

我建立了一个Travis-CI,如本文https://stackoverflow.com/a/28230711/1700776所述。

我的build.gradle:http://pastebin.com/uiJ0LCSk

android bash gradle travis-ci
8个回答
8
投票

扩展Khozzy的答案,从build.gradle中检索Android包的versionName,添加以下自定义任务:

task printVersionName {
    doLast {
        println android.defaultConfig.versionName
    }
}

并调用它:

gradle -q printVersionName

9
投票

您可以定义自定义任务,即

task printVersion {
    doLast {
        println project.version
    }
}

并在Bash中执行它:

$ gradle -q pV
1.8.5

8
投票

感谢alnet's评论,我提出了这个解决方案(注意Doug Stevenson's objection):

# variables
export GRADLE_PATH=./app/build.gradle   # path to the gradle file
export GRADLE_FIELD="versionName"   # field name
# logic
export VERSION_TMP=$(grep $GRADLE_FIELD $GRADLE_PATH | awk '{print $2}')    # get value versionName"0.1.0"
export VERSION=$(echo $VERSION_TMP | sed -e 's/^"//'  -e 's/"$//')  # remove quotes 0.1.0
export GIT_TAG=$TRAVIS_BRANCH-$VERSION.$TRAVIS_BUILD_NUMBER
# result
echo gradle version: $VERSION
echo release tag: $GIT_TAG

6
投票

这个怎么样?

grep -o "versionCode\s\+\d\+" app/build.gradle | awk '{ print $2 }'

-o选项使grep只打印匹配的部分,所以你保证你传递给awk的只是模式versionCode NUMBER


1
投票

例如

android{
  android.applicationVariants.all { variant ->
    variant.outputs.each { output ->
        def outputFile = output.outputFile
        def fileName
        if (outputFile != null && outputFile.name.endsWith('.apk')) {
            if (!outputFile.name.contains('unaligned')) {
                fileName = "yourAppRootName_${variant.productFlavors[0].name}_${getVersionName()}_${variant.buildType.name}.apk"
                output.outputFile = new File(outputFile.parent + "/aligned", fileName)
            }
        }
    }
}
}

使用${getVersionName()}在build.gradle中获取版本


1
投票

如果您正在寻找Kotlin DSL的迁移版本,请参阅以下内容:

tasks.create("printVersionName") {
    doLast { println(version) }
}

1
投票

如果你有多种口味并在风味中设置版本信息,你可以使用这样的东西:

task printVersion{
doLast {
    android.productFlavors.all {
        flavor ->
            if (flavorName.matches(flavor.name)) {
                print flavor.versionName + "-" + flavor.versionCode
            }
    }
}
}

然后你可以使用它来调用它

./gradlew -q printVersion -PflavorName=MyFlavor

1
投票

我喜欢这个衬里只获得没有引号的版本名称:

grep "versionName" app/build.gradle | awk '{print $2}' | tr -d \''"\'
© www.soinside.com 2019 - 2024. All rights reserved.