Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodydavis/349c6a4475bf8a78f08ca7d38f0fc62e to your computer and use it in GitHub Desktop.
Save rodydavis/349c6a4475bf8a78f08ca7d38f0fc62e to your computer and use it in GitHub Desktop.
[Android Gradle] Auto-Increment version code/name in AndroidManifest/Gradle before Jenkins Build
import java.util.regex.Pattern
def versionMajor = 1
def versionMinor = 0
def versionPatch = 0
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.jakewharton.sdkmanager:gradle-plugin:0.12.0'
}
}
apply plugin: 'android-sdk-manager'
apply plugin: "com.android.application"
android {
compileSdkVersion project.ANDROID_BUILD_SDK_VERSION
buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION
defaultConfig {
applicationId project.APPLICATION_ID
minSdkVersion project.ANDROID_BUILD_MIN_SDK_VERSION
targetSdkVersion project.ANDROID_BUILD_TARGET_SDK_VERSION
def vCode
def vName
def vItem
def buildNum = System.getenv("BUILD_NUMBER") ?: 0
if (buildNum != 0) {
vItem = buildNum.toInteger()
} else {
vItem = versionPatch
}
versionCode versionMajor * 10000 + versionMinor * 1000 + vItem * 100
versionName "${versionMajor}.${versionMinor}.${vItem}"
}
buildTypes {
debug {
applicationIdSuffix ".debug"
minifyEnabled false
debuggable true
testCoverageEnabled true
applicationVariants.all { variant ->
variant.outputs.each { output ->
def buildNum = System.getenv("BUILD_NUMBER") ?: 0
if (buildNum != 0) {
def manifestFile = file("src/main/AndroidManifest.xml")
def pattern = Pattern.compile("versionCode=\"(\\d+)\"")
def pattern2 = Pattern.compile("versionName=\"(.*?)\"")
def manifestText = manifestFile.getText()
def matcher = pattern.matcher(manifestText)
matcher.find()
def manifestContent = matcher.replaceAll("versionCode=\"" + buildNum + "\"")
def matcher2 = pattern2.matcher(manifestContent)
matcher2.find()
def manifestContent2 = matcher2.replaceAll("versionName=\"" + "${versionMajor}.${versionMinor}." + buildNum + "\"")
manifestFile.write(manifestContent2)
def file = output.outputFile
def newfilename = file.name.replace(".apk", "-" + buildNum + ".apk")
output.outputFile = new File(file.parent, newfilename)
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment