Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Gist for versioning an android application.
/**
* Copyright 2016 Avinash Ananth Narayan R
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
buildscript {
dependencies {
//noinspection GradleDynamicVersion
classpath "org.eclipse.jgit:org.eclipse.jgit:4.1.1.+"
}
repositories {
jcenter()
}
}
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.revwalk.RevWalk
import org.eclipse.jgit.storage.file.FileRepositoryBuilder
import static org.eclipse.jgit.lib.Constants.MASTER
def noGit = false
def gitRepo
def git
try {
gitRepo = new FileRepositoryBuilder()
.readEnvironment()
.findGitDir()
.build()
git = Git.wrap(gitRepo)
} catch (ignore) {
println("WARN: No git repository.")
noGit = true;
}
ext.readVersionCode = {
def count = 0
if (noGit) {
count = 1
} else {
def walk = new RevWalk(gitRepo)
def masterRef = gitRepo.getRef(MASTER)
if (masterRef == null) {
return 1;
}
def head = walk.parseCommit(masterRef.getObjectId())
try {
while (head != null) {
count++
def parents = head.getParents()
if (parents != null && parents.length > 0) {
head = walk.parseCommit(parents[0])
} else {
head = null
}
}
walk.dispose()
} finally {
walk.close()
}
}
println("using version code: $count")
return count
}
ext.readVersionName = {
def version;
try {
if (noGit) {
return "1.0"
}
def tag = git.describe().setLong(false).call()
def clean = git.status().call().isClean()
version = tag + (clean ? '' : '-dirty')
} catch (ignore) {
version = "1.0"
}
println("using version name: $version")
return version
}
@Avinash-Bhat

This comment has been minimized.

Copy link
Owner Author

@Avinash-Bhat Avinash-Bhat commented Mar 7, 2015

to use, do the following changes in the build.gradle,

apply from: 'https://gist.githubusercontent.com/Avinash-Bhat/12fc59b3d96cb427e5e9/raw/git-version.gradle'

android {
  ...
  defaultConfig {
    ...
    versionCode readVersionCode()
    versionName readVersionName()
    ...
  }
  ...
}
@Avinash-Bhat

This comment has been minimized.

Copy link
Owner Author

@Avinash-Bhat Avinash-Bhat commented Nov 29, 2015

completely moved to a jgit implementation after the fiasco of git 1.7.1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment