【问题标题】:How can I implement gradle code version auto increrement?如何实现 gradle 代码版本自动增量?
【发布时间】:2016-02-15 11:20:33
【问题描述】:

更具体地说,我有一些构建配置:

signingConfigs {
    debug {
        keyAlias ''
        keyPassword ''
        storeFile file('') 
    }
    release {
        keyAlias ''
        keyPassword ''
        storeFile file('')
        storePassword ''
    }
}
....
defaultConfig {
    applicationId ""
    minSdkVersion 21
    targetSdkVersion 23
    versionCode code
}

我希望 gradle 在每次运行“发布”时自动增加代码版本。

到目前为止我所拥有的:

def code = 1;

//Get all the gradle task names being run
List<String> runTasks = gradle.startParameter.getTaskNames();

for (String item : runTasks) {

    //Get the version.properties file. Its our custom file for storing a code version, please don't remove it
    def versionPropsFile = file('version.properties')

    def Properties versionProps = new Properties()

    //This will prevent the gradle from exploding when there's no file yet created
    if (versionPropsFile.exists())
        versionProps.load(new FileInputStream(versionPropsFile))

    //It will insert the "0" version in case the file does not exist
    code = (versionProps['VERSION_CODE'] ?: "0").toInteger()

    if (item.contains("release")) {
        // If we're building up on Jenkins, increment the version strings
        code++

        versionProps['VERSION_CODE'] = code.toString()

        //It will overwrite the file even if it doesn't exist
        versionProps.store(versionPropsFile.newWriter(), null)
    }
}

问题:

我似乎无法进入if (item.contains("release"))。它总是错误的,但我肯定看到 gradle 运行这个任务。如何修复它或至少在控制台中输出 gradle 正在运行的所有任务(它们的名称)?

【问题讨论】:

标签: android gradle android-gradle-plugin


【解决方案1】:

我对这个问题的实现:

我有一个包含版本号的版本文件。从这个文件我们得到版本。当构建包含任务“publishRelease”(它可以是任何其他任务)时,我们会在版本文件中增加版本。 我喜欢这个解决方案,因为它使 defaultConfig 代码逻辑保持干净。

version.properties

VERSION_CODE=45

在 android 配置部分

 defaultConfig {
    applicationId "..."
    minSdkVersion 16
    targetSdkVersion 23
    versionCode getVersion()
    versionName "0.2." + versionCode
}

和 getVersion()

def getVersion() {
    def versionPropertiesFile = file('version.properties')
    def appVersion = -1;

    if (versionPropertiesFile.canRead()) {
        def Properties versionProps = new Properties()

        versionProps.load(new FileInputStream(versionPropertiesFile))

        appVersion = versionProps['VERSION_CODE'].toInteger()

        def runTasks = gradle.startParameter.taskNames
        if ('publishRelease' in runTasks) {
            print("Increase version to " + appVersion + '\n')

            appVersion += 1

            versionProps['VERSION_CODE'] = appVersion.toString()
            versionProps.store(versionPropertiesFile.newWriter(), null)
        }

    } else {
        throw new GradleException("Could not read version.properties!")
    }

    return appVersion;
}

【讨论】:

    【解决方案2】:

    试试这个。我在我的所有应用程序中都使用它并且工作正常。首先,在 /app/ 文件夹中创建一个 version.properties 文件。该文件应如下所示。 这里 VERSION_CODE 表示您的应用程序中的 versionCode 字段。当 VERSION_NAME 在您的版本名称中指示次要补丁时,这应该始终递增。 (例如 x.x.12)。

    /app/version.properties

    VERSION_NAME=0      
    VERSION_CODE=0
    

    然后在您的模块级别,build.Gradle 文件在 defaultConfig 块中添加以下代码。这将在每次发布构建后将版本代码和版本名称增加 1。 (基本上,当 assambleRelease gradle 任务执行时。如果您有不同的构建类型,请根据您的要求更改任务名称。)

    /app/build.gradle

    //Version code increment
        def versionPropsFile = file('version.properties')
        if (versionPropsFile.canRead()) {
            //load the version.properties file
            def Properties versionProps = new Properties()
            versionProps.load(new FileInputStream(versionPropsFile))
    
            /**
             * get the name of currently running task
             */
            def runTasks = gradle.startParameter.taskNames
    
            /**
             * Value to increment in minor version & version code.
             */
            def incrementCount = 0
    
            //Build version code and build type logic.
            if (':storeFinder:assembleRelease' in runTasks) {
    
                //if it is Production build package increment the version code by 1.
                incrementCount = 1;
            }
    
            //generate new version code
            def code = versionProps['VERSION_CODE'].toInteger() + incrementCount
            def minorPatch = versionProps['VERSION_NAME'].toInteger() + incrementCount
    
            //write new versionCode/version name suffix back to version.properties
            versionProps['VERSION_CODE'] = code.toString()
            versionProps['VERSION_NAME'] = minorPatch.toString()
            versionProps.store(versionPropsFile.newWriter(), null)
    
            //here version code is decided by above code.
            //noinspection GroovyAssignabilityCheck
            versionCode code
            versionName "1.0." + minorPatch;  //e.g. 1.0.61
    
        } else {
            //version.properties file not found.
            throw new GradleException("Could not read version.properties! Copy that to /app folder from version control.")
        }
    

    【讨论】:

      【解决方案3】:

      我从 googler 的 Plaid 应用程序中获取以下代码 Nick Butcher 真的很干净。

      apply plugin: 'com.android.application'
      
      // query git for the SHA, Tag and commit count. Use these to automate versioning.
      def gitSha = 'git rev-parse --short HEAD'.execute([], project.rootDir).text.trim()
      def gitTag = 'git describe --tags'.execute([], project.rootDir).text.trim()
      def gitCommitCount = 100 + Integer.parseInt('git rev-list --count HEAD'.execute([], project.rootDir).text.trim())
      
      android {
          compileSdkVersion 23
          buildToolsVersion "23.0.3"
      
          defaultConfig {
              applicationId 'net.hadifar.dope'
              minSdkVersion 14
              targetSdkVersion 23
              versionName gitTag
              versionCode gitCommitCount
              buildConfigField "String", "GIT_SHA", "\"${gitSha}\""
      
          }
      
          lintOptions {
              abortOnError false
          }
      
          compileOptions {
              sourceCompatibility JavaVersion.VERSION_1_7
              targetCompatibility JavaVersion.VERSION_1_7
          }
      
          buildTypes {
              release {
                  minifyEnabled false
                  shrinkResources true
                  proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
              }
          }
          productFlavors {}
      }
      ext {
          supportLibVersion = '23.3.0'
      }
      
      dependencies {
          compile fileTree(include: ['*.jar'], dir: 'libs')
      
          compile "com.android.support:appcompat-v7:${supportLibVersion}"
      }
      

      【讨论】:

      • 此代码不会在每个发布版本中增加版本。它随着每次提交而增加。但您可以修改以适应您的需求。
      【解决方案4】:

      git 可以提供帮助,请点击此链接:Automatic versioning and increment using Git tags and Gradle

      android {
          defaultConfig {
          ...
              // Fetch the version according to git latest tag and "how far are we from last tag"
              def longVersionName = "git -C ${rootDir} describe --tags --long".execute().text.trim()
              def (fullVersionTag, versionBuild, gitSha) = longVersionName.tokenize('-')
              def(versionMajor, versionMinor, versionPatch) = fullVersionTag.tokenize('.')
      
              // Set the version name
              versionName "$versionMajor.$versionMinor.$versionPatch($versionBuild)"
      
              // Turn the version name into a version code
              versionCode versionMajor.toInteger() * 100000 +
                      versionMinor.toInteger() * 10000 +
                      versionPatch.toInteger() * 1000 +
                      versionBuild.toInteger()
      
              // Friendly print the version output to the Gradle console
              printf("\n--------" + "VERSION DATA--------" + "\n" + "- CODE: " + versionCode + "\n" + 
                     "- NAME: " + versionName + "\n----------------------------\n")
          ...
          }
      }
      

      【讨论】:

      • 这里不发布链接,而是发布实际内容。链接可能会关闭。链接仅供参考。
      猜你喜欢
      • 2014-02-19
      • 2015-02-23
      • 2011-06-23
      • 2020-08-27
      • 2014-06-24
      • 2020-03-29
      • 1970-01-01
      • 2012-09-08
      • 2023-03-11
      相关资源
      最近更新 更多