Skip to content

Instantly share code, notes, and snippets.

@ericksli
Created August 29, 2016 04:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ericksli/1c71ae055ea90fdfdae41ceaebe072cb to your computer and use it in GitHub Desktop.
Save ericksli/1c71ae055ea90fdfdae41ceaebe072cb to your computer and use it in GitHub Desktop.
Android app show Git commit hash as version name
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