Created
August 29, 2016 04:09
-
-
Save ericksli/1c71ae055ea90fdfdae41ceaebe072cb to your computer and use it in GitHub Desktop.
Android app show Git commit hash as version name
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.regex.Pattern | |
apply plugin: 'com.android.application' | |
/** | |
* Extract Git commit hash of HEAD with number of changed files | |
*/ | |
def getGitHashVersionName = { | |
try { | |
def hashOutput = new ByteArrayOutputStream() | |
def changeOutput = new ByteArrayOutputStream() | |
def gitVersionName | |
exec { | |
commandLine 'git', 'rev-list', '--max-count=1', 'HEAD' | |
standardOutput = hashOutput | |
} | |
exec { | |
commandLine 'git', 'diff-index', '--shortstat', 'HEAD' | |
standardOutput = changeOutput | |
} | |
gitVersionName = hashOutput.toString().trim().substring(0, 7); | |
if (!changeOutput.toString().trim().empty) { | |
def pattern = Pattern.compile("\\d+"); | |
def matcher = pattern.matcher(changeOutput.toString().trim()) | |
if (matcher.find()) { | |
gitVersionName += "-" + matcher.group() | |
} | |
} | |
return gitVersionName | |
} catch (ignored) { | |
return "UNKNOWN"; | |
} | |
} | |
android { | |
// Skip the other items... | |
buildTypes { | |
debug { | |
debuggable true | |
minifyEnabled false | |
signingConfig signingConfigs.debug | |
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' | |
applicationIdSuffix debug_application_id_suffex | |
buildConfigField "String", "GIT_VERSION_NAME", "\"${getGitHashVersionName()}\"" | |
} | |
release { | |
minifyEnabled true | |
signingConfig signingConfigs.release | |
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' | |
buildConfigField "String", "GIT_VERSION_NAME", "\"${getGitHashVersionName()}\"" | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment