繁体   English   中英

从bash中的build.gradle读取versionName

[英]Read versionName from build.gradle in bash

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

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

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

我按照本文https://stackoverflow.com/a/28230711/1700776所述设置了Travis-CI。

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

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

task printVersion {
    doLast {
        println project.version
    }
}

并在Bash中执行它:

$ gradle -q pV
1.8.5

感谢alnet的评论,我提出了这个解决方案(请注意Doug Stevenson的反对 ):

# 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

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

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

并这样调用它:

gradle -q printVersionName

这个怎么样?

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

-o选项使grep只打印匹配的部分,因此可以确保传递给awk的只是模式versionCode NUMBER

例如

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中的版本

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

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

如果您有多种口味并在口味中设置了版本信息,则可以使用以下方式:

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

然后您可以使用

./gradlew -q printVersion -PflavorName=MyFlavor

我喜欢这种衬板,只得到不带引号的版本名称:

grep "versionName" app/build.gradle | awk '{print $2}' | tr -d \''"\'

grep versionName:

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

因此在build.gradle versionName "8.1.9"输入8.1.9

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM