Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.