Last active
August 29, 2015 14:21
-
-
Save qrtt1/54fd0387038781f25ed2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
buildscript { | |
repositories { | |
jcenter() | |
} | |
dependencies { | |
classpath("org.eclipse.jgit:org.eclipse.jgit:4.0.0.201505050340-m2") | |
} | |
} | |
apply plugin: GitRevisionPlugin | |
import org.eclipse.jgit.storage.file.* | |
import org.eclipse.jgit.api.* | |
import org.eclipse.jgit.lib.* | |
import org.eclipse.jgit.revwalk.* | |
class GitRevisionTask extends DefaultTask { | |
def revisionFile = "revision.properties" | |
def getOutputFile() { | |
def dir = project.convention.plugins['java'].sourceSets.main.output.resourcesDir | |
return new File(dir, revisionFile) | |
} | |
def getGitRepo() { | |
try { | |
return new FileRepositoryBuilder() | |
.findGitDir() | |
.build() | |
} catch(IllegalArgumentException e) { | |
logger.warn '=' * 64 | |
logger.warn '[warn] git-repo not found. skip to generate the revision file' | |
logger.warn '=' * 64 | |
} | |
return null | |
} | |
@TaskAction | |
def action() { | |
def repo = getGitRepo() | |
if (repo == null) { return } | |
def head = repo.resolve(Constants.HEAD); | |
def git = new Git(repo) | |
Iterable<RevCommit> commits = git.log().add(head).setMaxCount(1).call(); | |
def revision = commits.iterator().next().id.toString().split("[\t ]+")[1] | |
getOutputFile().withWriter { it << "revision=${revision}\n" } | |
} | |
} | |
class GitRevisionPlugin implements Plugin<Project> { | |
void apply(Project project) { | |
GitRevisionTask task = project.getTasks() | |
.create("generateGitRevisionProperties", GitRevisionTask.class); | |
task.setDescription("Generate the git revision properties file into output resource directory") | |
task.setGroup(BasePlugin.BUILD_GROUP); | |
project.getTasks().getByName(JavaPlugin.JAR_TASK_NAME).dependsOn(task); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment