Autoincrement VersionCode with gradle extra properties

前端 未结 16 2250
逝去的感伤
逝去的感伤 2020-11-27 08:47

I\'m building an Android app with gradle. Until now I used the Manifest file to increase the versionCode, but I would like to read the versionCode from an external file and

16条回答
  •  没有蜡笔的小新
    2020-11-27 09:38

    Another way of getting a versionCode automatically is setting versionCode to the number of commits in the checked out git branch. It accomplishes following objectives:

    1. versionCode is generated automatically and consistently on any machine (including a Continuous Integration and/or Continuous Deployment server).
    2. App with this versionCode is submittable to GooglePlay.
    3. Doesn't rely on any files outside of repo.
    4. Doesn't push anything to the repo
    5. Can be manually overridden, if needed

    Using gradle-git library to accomplish the above objectives. Add code below to your build.gradle file the /app directory:

    import org.ajoberstar.grgit.Grgit
    
    repositories {
        mavenCentral()
    }
    
    buildscript {
        repositories {
            mavenCentral()
        }
    
        dependencies {
            classpath 'org.ajoberstar:grgit:1.5.0'
        }
    }
    
    android {
    /*
        if you need a build with a custom version, just add it here, but don't commit to repo,
        unless you'd like to disable versionCode to be the number of commits in the current branch.
    
        ex. project.ext.set("versionCodeManualOverride", 123)
    */
        project.ext.set("versionCodeManualOverride", null)
    
        defaultConfig {
            versionCode getCustomVersionCode()
        }
    }
    
    def getCustomVersionCode() {
    
        if (project.versionCodeManualOverride != null) {
            return project.versionCodeManualOverride
        }
    
        // current dir is /app, so it's likely that all your git repo files are in the dir
        // above.
        ext.repo = Grgit.open(project.file('..'))
    
        // should result in the same value as running
        // git rev-list  | wc -l
        def numOfCommits = ext.repo.log().size()
        return numOfCommits
    }
    

    NOTE: For this method to work, it's best to only deploy to Google Play Store from the same branch (ex. master).

提交回复
热议问题